repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
EaglesoftZJ/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/api/ApiServiceMessage.java
2168
package im.actor.core.api; /* * Generated by the Actor API Scheme generator. DO NOT EDIT! */ import im.actor.runtime.bser.*; import im.actor.runtime.collections.*; import static im.actor.runtime.bser.Utils.*; import im.actor.core.network.parser.*; import androidx.annotation.Nullable; import org.jetbrains.annotations.NotNull; import com.google.j2objc.annotations.ObjectiveCName; import java.io.IOException; import java.util.List; import java.util.ArrayList; public class ApiServiceMessage extends ApiMessage { private String text; private ApiServiceEx ext; public ApiServiceMessage(@NotNull String text, @Nullable ApiServiceEx ext) { this.text = text; this.ext = ext; } public ApiServiceMessage() { } public int getHeader() { return 2; } @NotNull public String getText() { return this.text; } @Nullable public ApiServiceEx getExt() { return this.ext; } @Override public void parse(BserValues values) throws IOException { this.text = values.getString(1); if (values.optBytes(3) != null) { this.ext = ApiServiceEx.fromBytes(values.getBytes(3)); } if (values.hasRemaining()) { setUnmappedObjects(values.buildRemaining()); } } @Override public void serialize(BserWriter writer) throws IOException { if (this.text == null) { throw new IOException(); } writer.writeString(1, this.text); if (this.ext != null) { writer.writeBytes(3, this.ext.buildContainer()); } if (this.getUnmappedObjects() != null) { SparseArray<Object> unmapped = this.getUnmappedObjects(); for (int i = 0; i < unmapped.size(); i++) { int key = unmapped.keyAt(i); writer.writeUnmapped(key, unmapped.get(key)); } } } @Override public String toString() { String res = "struct ServiceMessage{"; res += "text=" + this.text; res += ", ext=" + (this.ext != null ? "set":"empty"); res += "}"; return res; } }
agpl-3.0
clreinki/GalaxyHarvester
getResourceByName.py
4352
#!/usr/bin/python """ Copyright 2010 Paul Willworth <[email protected]> This file is part of Galaxy Harvester. Galaxy Harvester 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. Galaxy Harvester 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 Galaxy Harvester. If not, see <http://www.gnu.org/licenses/>. """ import os import sys import Cookie import dbSession import dbShared import cgi import MySQLdb import ghLists from xml.dom import minidom # form = cgi.FieldStorage() spawnName = form.getfirst('name', '') galaxy = form.getfirst('galaxy', '') # escape input to prevent sql injection spawnName = dbShared.dbInsertSafe(spawnName) galaxy = dbShared.dbInsertSafe(galaxy) # Main program print 'Content-type: text/xml\n' doc = minidom.Document() eRoot = doc.createElement("result") doc.appendChild(eRoot) eName = doc.createElement("spawnName") tName = doc.createTextNode(spawnName) eName.appendChild(tName) eRoot.appendChild(eName) try: conn = dbShared.ghConn() cursor = conn.cursor() except Exception: result = "Error: could not connect to database" if (cursor): cursor.execute('SELECT spawnID, resourceType, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER FROM tResources WHERE galaxy=' + galaxy + ' AND spawnName="' + spawnName + '";') row = cursor.fetchone() if (row != None): spawnID = str(row[0]) eSpawn = doc.createElement("spawnID") tSpawn = doc.createTextNode(spawnID) eSpawn.appendChild(tSpawn) eRoot.appendChild(eSpawn) eType = doc.createElement("resourceType") tType = doc.createTextNode(str(row[1])) eType.appendChild(tType) eRoot.appendChild(eType) eCR = doc.createElement("CR") tCR = doc.createTextNode(str(row[2])) eCR.appendChild(tCR) eRoot.appendChild(eCR) eCD = doc.createElement("CD") tCD = doc.createTextNode(str(row[3])) eCD.appendChild(tCD) eRoot.appendChild(eCD) eDR = doc.createElement("DR") tDR = doc.createTextNode(str(row[4])) eDR.appendChild(tDR) eRoot.appendChild(eDR) eFL = doc.createElement("FL") tFL = doc.createTextNode(str(row[5])) eFL.appendChild(tFL) eRoot.appendChild(eFL) eHR = doc.createElement("HR") tHR = doc.createTextNode(str(row[6])) eHR.appendChild(tHR) eRoot.appendChild(eHR) eMA = doc.createElement("MA") tMA = doc.createTextNode(str(row[7])) eMA.appendChild(tMA) eRoot.appendChild(eMA) ePE = doc.createElement("PE") tPE = doc.createTextNode(str(row[8])) ePE.appendChild(tPE) eRoot.appendChild(ePE) eOQ = doc.createElement("OQ") tOQ = doc.createTextNode(str(row[9])) eOQ.appendChild(tOQ) eRoot.appendChild(eOQ) eSR = doc.createElement("SR") tSR = doc.createTextNode(str(row[10])) eSR.appendChild(tSR) eRoot.appendChild(eSR) eUT = doc.createElement("UT") tUT = doc.createTextNode(str(row[11])) eUT.appendChild(tUT) eRoot.appendChild(eUT) eER = doc.createElement("ER") tER = doc.createTextNode(str(row[12])) eER.appendChild(tER) eRoot.appendChild(eER) cursor.execute('SELECT tResourcePlanet.planetID, planetName FROM tResourcePlanet INNER JOIN tPlanet ON tResourcePlanet.planetID=tPlanet.planetID WHERE spawnID="' + spawnID + '";') row = cursor.fetchone() planets = "" planetNames = "" while (row != None): planets = planets + str(row[0]) + "," planetNames = planetNames + row[1] + ", " row = cursor.fetchone() if (len(planetNames) > 0): planetNames = planetNames[0:len(planetNames)-2] ePlanets = doc.createElement("Planets") tPlanets = doc.createTextNode(planetNames) ePlanets.appendChild(tPlanets) eRoot.appendChild(ePlanets) result = "found" else: result = "new" cursor.close() conn.close() else: result = "Error: could not connect to database" eText = doc.createElement("resultText") tText = doc.createTextNode(result) eText.appendChild(tText) eRoot.appendChild(eText) print doc.toxml() if (result.find("Error:") > -1): sys.exit(500) else: sys.exit(200)
agpl-3.0
onlyasurvey/OAS_workspace
tags/1.0.0-SNAPSHOT/OnlyASurvey/OnlyASurveyWeb/src/main/java/com/oas/model/question/BooleanQuestion.java
904
package com.oas.model.question; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.PrimaryKeyJoinColumns; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import com.oas.model.Question; import com.oas.model.Survey; /** * Boolean question type. * * @author Jason Halliday * @since September 5, 2008 */ @Entity @Table(schema = "oas", name = "boolean_question") @Inheritance(strategy = InheritanceType.JOINED) @SequenceGenerator(name = "baseObjectSequence", sequenceName = "oas.base_object_id_seq") @PrimaryKeyJoinColumns( { @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id") }) public class BooleanQuestion extends Question { public BooleanQuestion() { } public BooleanQuestion(Survey survey) { super(survey); } }
agpl-3.0
openfisca/openfisca-qt
openfisca_qt/gui/utils/sourcecode.py
1547
# -*- coding: utf-8 -*- # # Copyright © 2009-2010 Pierre Raybaut # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """ Source code text utilities """ # Order is important: EOL_CHARS = (("\r\n", 'nt'), ("\n", 'posix'), ("\r", 'mac')) def get_eol_chars(text): """Get text EOL characters""" for eol_chars, _os_name in EOL_CHARS: if text.find(eol_chars) > -1: return eol_chars def get_os_name_from_eol_chars(eol_chars): """Return OS name from EOL characters""" for chars, os_name in EOL_CHARS: if eol_chars == chars: return os_name def get_eol_chars_from_os_name(os_name): """Return EOL characters from OS name""" for eol_chars, name in EOL_CHARS: if name == os_name: return eol_chars def has_mixed_eol_chars(text): """Detect if text has mixed EOL characters""" eol_chars = get_eol_chars(text) if eol_chars is None: return False correct_text = eol_chars.join((text+eol_chars).splitlines()) return repr(correct_text) != repr(text) def fix_indentation(text): """Replace tabs by spaces""" return text.replace('\t', ' '*4) def is_builtin(text): """Test if passed string is the name of a Python builtin object""" import __builtin__ return text in [str(name) for name in dir(__builtin__) if not name.startswith('_')] def is_keyword(text): """Test if passed string is the name of a Python keyword""" import keyword return text in keyword.kwlist
agpl-3.0
plentymarkets/plugin-hack-api
Modules/Pim/SearchService/Filter/CategoryFilter.php
1627
<?php namespace Plenty\Modules\Pim\SearchService\Filter; use Illuminate\Contracts\Support\Arrayable; use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Statement\Filter\TermFilter; use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Statement\Filter\TermsFilter; use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Statement\StatementInterface; use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Type\Filter\BoolMustFilter; use Plenty\Modules\Cloud\ElasticSearch\Lib\Query\Type\TypeInterface; /** * Includes filters for categories */ abstract class CategoryFilter implements TypeInterface { const DEPTH_BRANCH = 'branch'; const DEPTH_ANY = 'any'; const KEY_BRANCH = 'branch'; const KEY_ANY = 'any'; /** * Restricts the result to have any of the categoryIds. */ abstract public function isInAtLeastOneCategory( array $categoryIds, string $depth = self::DEPTH_ANY ):self; /** * Get the path by depth. */ abstract public static function getPathByDepth( string $depth ):string; /** * Restricts the result to have all of the categoryIds. */ abstract public function isInEachCategory( array $categoryIds, string $depth = self::DEPTH_ANY ):self; /** * Restricts the result to have the categoryId. */ abstract public function isInCategory( int $categoryId, string $depth = self::DEPTH_ANY ):self; /** * Restricts the result to have a category. */ abstract public function isInACategory( ):self; abstract public function toArray( ):array; abstract public function addStatement( StatementInterface $statement ); abstract public function addQuery( $statement ); }
agpl-3.0
theatrus/eve-central.com
core/src/main/scala/com/evecentral/dataaccess/GetOrders.scala
3671
package com.evecentral.dataaccess import akka.actor.Actor import akka.dispatch.{RequiresMessageQueue, BoundedMessageQueueSemantics} import com.evecentral.Database import net.noerd.prequel.{LongFormattable, StringFormattable} import org.joda.time.{DateTime, Period} import org.slf4j.LoggerFactory case class MarketOrder(typeid: Long, orderId: Long, price: Double, bid: Boolean, station: Station, system: SolarSystem, region: Region, range: Int, volremain: Long, volenter: Long, minVolume: Long, expires: Period, reportedAt: DateTime) { val weightPrice = price * volenter } object MarketOrder { implicit def pimpMoToDouble(m: MarketOrder): Double = { m.price } } /** * Get a list of orders. * TODO: the Long parameters really should be a MarketType, Region etc */ case class GetOrdersFor(bid: Option[Boolean], types: Seq[Long], regions: Seq[Long], systems: Seq[Long], hours: Long = 24, minq: Long = 1) case class OrderList(query: GetOrdersFor, result: Seq[MarketOrder]) class GetOrdersActor extends Actor with RequiresMessageQueue[BoundedMessageQueueSemantics] { private val log = LoggerFactory.getLogger(getClass) /** * This query does a lot of internal SQL building and not a prepared statement. I'm sorry, * but at least everything is typesafe :-) */ private def orderList(filter: GetOrdersFor): Seq[MarketOrder] = { val db = Database.coreDb val regionLimit = Database.concatQuery("regionid", filter.regions) val typeLimit = Database.concatQuery("typeid", filter.types) val systems = Database.concatQuery("systemid", filter.systems) val hours = "%d hours".format(filter.hours) val bid = filter.bid match { case Some(b) => b match { case true => "bid = 1" case _ => "bid = 0" } case None => "1=1" } val orders = db.transaction { tx => tx.select("SELECT typeid,orderid,price,bid,stationid,systemid,regionid,range,volremain,volenter,minvolume,EXTRACT(EPOCH FROM duration),reportedtime" + " FROM current_market WHERE reportedtime >= NOW() - (INTERVAL ?) AND volenter >= ? AND " + bid + " AND (" + typeLimit + ") AND (" + regionLimit + ") AND ( " + systems + ")", StringFormattable(hours), LongFormattable(filter.minq)) { row => val typeid = row.nextLong.get val orderid = row.nextLong.get val price = row.nextDouble.get val bid = row.nextBoolean.get val stationid = row.nextLong.get val systemid = row.nextLong.get // Get a mock system or station if required (i.e. not in the database?) val region = StaticProvider.regionsMap(row.nextLong.get) val system = StaticProvider.systemsMap.getOrElse(systemid, SolarSystem(systemid, "Unknown", 0.0, region, 0)) val station = StaticProvider.stationsMap.getOrElse(stationid, Station(stationid, "Unknown", "Unknown", system)) val range = row.nextInt.get val volremain = row.nextLong.get val volenter = row.nextLong.get val minvol = row.nextLong.get val duration = new Period(row.nextLong.get * 1000) MarketOrder(typeid, orderid, price, bid, station, system, region, range, volremain, volenter, minvol, duration, new DateTime(row.nextDate.get) ) } } log.info("ORDERS: Fetched for " + typeLimit.toString) orders } def receive = { case x: GetOrdersFor => { sender ! OrderList(x, orderList(x)) } } }
agpl-3.0
uclouvain/osis
assessments/api/serializers/session.py
1536
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business involves the administration of students, teachers, # courses, programs and so on. # # Copyright (C) 2015-2021 Université catholique de Louvain (http://www.uclouvain.be) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################## from rest_framework import serializers class SessionSerializer(serializers.Serializer): start_date = serializers.DateField() end_date = serializers.DateField() year = serializers.IntegerField() month_session_name = serializers.CharField()
agpl-3.0
moskiteau/KalturaGeneratedAPIClientsJava
src/com/kaltura/client/types/KalturaAccessControlServeRemoteEdgeServerAction.java
2903
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2015 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import org.w3c.dom.Element; import com.kaltura.client.KalturaParams; import com.kaltura.client.KalturaApiException; import com.kaltura.client.utils.ParseUtils; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * @date Mon, 10 Aug 15 02:02:11 -0400 * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaAccessControlServeRemoteEdgeServerAction extends KalturaRuleAction { /** Comma separated list of edge servers playBack should be done from */ public String edgeServerIds; public KalturaAccessControlServeRemoteEdgeServerAction() { } public KalturaAccessControlServeRemoteEdgeServerAction(Element node) throws KalturaApiException { super(node); NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node aNode = childNodes.item(i); String nodeName = aNode.getNodeName(); String txt = aNode.getTextContent(); if (nodeName.equals("edgeServerIds")) { this.edgeServerIds = ParseUtils.parseString(txt); continue; } } } public KalturaParams toParams() { KalturaParams kparams = super.toParams(); kparams.add("objectType", "KalturaAccessControlServeRemoteEdgeServerAction"); kparams.add("edgeServerIds", this.edgeServerIds); return kparams; } }
agpl-3.0
prefeiturasp/SME-SGP
Src/MSTech.GestaoEscolar.CustomResourceProviders/DBResourceReader.cs
2116
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Resources; namespace MSTech.GestaoEscolar.CustomResourceProviders { /// <summary> /// Implementation of IResourceReader required to retrieve a dictionary /// of resource values for implicit localization. /// </summary> public class DBResourceReader : DisposableBaseType, IResourceReader, IEnumerable<KeyValuePair<string, object>> { private ListDictionary resourceDictionary; public DBResourceReader(ListDictionary resourceDictionary) { this.resourceDictionary = resourceDictionary; } protected override void Cleanup() { try { this.resourceDictionary = null; } finally { base.Cleanup(); } } #region IResourceReader Members public void Close() { this.Dispose(); } public IDictionaryEnumerator GetEnumerator() { if (Disposed) { throw new ObjectDisposedException("DBResourceReader object is already disposed."); } return this.resourceDictionary.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { if (Disposed) { throw new ObjectDisposedException("DBResourceReader object is already disposed."); } return this.resourceDictionary.GetEnumerator(); } #endregion #region IEnumerable<KeyValuePair<string,object>> Members IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() { if (Disposed) { throw new ObjectDisposedException("DBResourceReader object is already disposed."); } return this.resourceDictionary.GetEnumerator() as IEnumerator<KeyValuePair<string, object>>; } #endregion } }
agpl-3.0
Sina30/PHP-Fusion-9.00
locale/Ukrainian/bbcodes/right.php
189
<?php $locale['bb_right_description'] = "Вирівняти по правому полю"; $locale['bb_right_usage'] = "текст розташований по правому полю"; ?>
agpl-3.0
pgdurand/Bioinformatics-UI-API
src/bzh/plealog/bioinfo/ui/carto/data/BasicFeatureOrganizer.java
7853
/* Copyright (C) 2006-2016 Patrick G. Durand * * 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. * * You may obtain a copy of the License at * * https://www.gnu.org/licenses/agpl-3.0.txt * * 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. */ package bzh.plealog.bioinfo.ui.carto.data; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import bzh.plealog.bioinfo.api.data.feature.Feature; import bzh.plealog.bioinfo.api.data.feature.FeatureTable; import bzh.plealog.bioinfo.api.data.sequence.DSequence; import bzh.plealog.bioinfo.ui.carto.config.FeaturePainterSystem; import bzh.plealog.bioinfo.ui.carto.core.CartoViewerPanel; import bzh.plealog.bioinfo.ui.carto.core.FeatureGraphics; import bzh.plealog.bioinfo.ui.carto.drawer.BasicFeatureDrawingLane; import bzh.plealog.bioinfo.ui.carto.painter.FeaturePainter; /** * Utility class aims at preparing FeatureTable data for the viewer. * This class is used as a singleton, even if the code is not written * to efficiently implement such a design pattern. * * * @author Patrick G. Durand */ public class BasicFeatureOrganizer { private static FeatureOrganizerManager _featureManager; /** * Set a FeatureOrganizerManager to this BasicFeatureOrganizer. Call this method * before using organizeFeatures methods. It is advised to call this method and pass * null after calling organizeFeatures methods. * * @param fom a FeatureOrganizerManager instance or null. * */ public static void setFeatureOrganizerManager(FeatureOrganizerManager fom){ _featureManager = fom; } /** * @deprecated use FeatureOrganizerManager. */ public static void setReferenceFeatureName(String referenceFeatureName){ //_referenceFeatureName = referenceFeatureName; } private static FGraphics getFGraphics(Feature feature){ FGraphics fg, fg2; fg = FeaturePainterSystem.getGraphics(feature.getKey()); if (_featureManager!=null){ fg2 = _featureManager.getFGraphics(feature, fg); if (fg2!=null){ fg=fg2; } } return fg; } private static FeaturePainter getFeaturePainter(Feature feature){ FeaturePainter fp, fp2; fp = FeaturePainterSystem.getPainter(feature.getKey()); if (_featureManager!=null){ fp2 = _featureManager.getFeaturePainter(feature, fp); if (fp2!=null){ fp=fp2; } } return fp; } private static void organizeFeaturesUsingReferenceFeature(CartoViewerPanel viewer, FeatureTable ft, DSequence seq, String[] featureOrdering, boolean forceOneLanePerCategory, int viewerWidth){ ArrayList<FeatureGraphics> gFeatures; Enumeration<Feature> features; Feature feature; BasicFeatureDrawingLane bfdl; String featKey; features = ft.enumFeatures(); while(features.hasMoreElements()){ feature = (Feature) features.nextElement(); gFeatures = new ArrayList<FeatureGraphics>(); gFeatures.add(new FeatureGraphics(feature, getFGraphics(feature), getFeaturePainter(feature))); bfdl = new BasicFeatureDrawingLane(seq, gFeatures); featKey = feature.getKey(); bfdl.setLeftLabel(featKey); bfdl.setTopMargin(1); bfdl.setBottomMargin(1); viewer.addDrawingLane(bfdl); } } private static List<FeatureGraphics> getFeatureGraphics(FeatureTable ft){ ArrayList<FeatureGraphics> data; Enumeration<Feature> myEnum; Feature feature; data = new ArrayList<FeatureGraphics>(); myEnum = ft.enumFeatures(); while(myEnum.hasMoreElements()){ feature = (Feature) myEnum.nextElement(); data.add(new FeatureGraphics(feature, getFGraphics(feature), getFeaturePainter(feature))); } return data; } private static void handleFeatures(CartoViewerPanel viewer, FeatureForACategory fac, DSequence seq, int refLabelSize){ BasicFeatureDrawingLane bfdl; String featKey; int i, nLanes; nLanes = fac.getLanes(); for(i=0;i<nLanes;i++){ bfdl = new BasicFeatureDrawingLane(seq, getFeatureGraphics(fac.getFeaturesForLane(i))); featKey = fac.getCategoryName(); bfdl.setLeftLabel(featKey); bfdl.setTopMargin(1); bfdl.setBottomMargin(1); bfdl.setReferenceLabelSize(refLabelSize); viewer.addDrawingLane(bfdl); } } /** * @deprecated use FeatureOrganizerManager. */ public static void organizeFeatures(CartoViewerPanel viewer, FeatureTable ft, DSequence seq, String[] featureOrdering, boolean forceOneLanePerCategory, int viewerWidth){ BasicFeatureOrganizer.organizeFeatures(viewer, ft, seq, null, forceOneLanePerCategory, viewerWidth); } /** * Prepare the features for viewing purpose. * * @param viewer the panel used to display the features. * @param ft the features to display. * @param seq the DNA sequence on which the features will be mapped. * @param forceOneLanePerCategory if true then all features of a same type are put within a * single lane. * @param viewerWidth the width of the viewing area. Unit is pixels. */ public static void organizeFeatures(CartoViewerPanel viewer, FeatureTable ft, DSequence seq, boolean forceOneLanePerCategory, int viewerWidth){ FeatureOrganizer organizer; ArrayList<FeatureCategoryMatcher> matchers; List<FeatureForACategory> results; String featKey; HashSet<String> featTypes; Enumeration<Feature> enu; String[] featureOrdering=null; int labelLength = String.valueOf(seq.getRulerModel().getSeqPos(seq.size()-1)).length(); if (_featureManager!=null && _featureManager.getFeatureOrderingNames() != null){ featureOrdering=_featureManager.getFeatureOrderingNames(); } if (_featureManager!=null && _featureManager.getReferenceFeatureName()!=null){ organizeFeaturesUsingReferenceFeature(viewer, ft, seq, featureOrdering, forceOneLanePerCategory, viewerWidth); return; } matchers = new ArrayList<FeatureCategoryMatcher>(); featTypes = new HashSet<String>(); enu = ft.enumFeatures(); while(enu.hasMoreElements()){ featKey = ((Feature)enu.nextElement()).getKey(); if (featTypes.contains(featKey)==false){ featTypes.add(featKey); matchers.add(new FeatureCategoryMatcher(featKey)); } } organizer = new FeatureOrganizer(matchers, forceOneLanePerCategory); results = organizer.organize(ft, (double)viewerWidth/(double) seq.size()); if (featureOrdering!=null){ featTypes.clear(); for(String type : featureOrdering){ for(FeatureForACategory fac : results){ if (type.equalsIgnoreCase(fac.getCategoryName())){ featTypes.add(type); handleFeatures(viewer, fac, seq, labelLength); } } } for(FeatureForACategory fac : results){ if (featTypes.contains(fac.getCategoryName())){ continue; } handleFeatures(viewer, fac, seq, labelLength); } } else{ for(FeatureForACategory fac : results){ handleFeatures(viewer, fac, seq, labelLength); } } } }
agpl-3.0
jesseh/dothis
volunteering/migrations/0057_auto_20150126_2232.py
388
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('volunteering', '0056_event_is_past'), ] operations = [ migrations.RenameField( model_name='event', old_name='is_past', new_name='is_done', ), ]
agpl-3.0
scylladb/scylla
cql3/restrictions/primary_key_restrictions.hh
4532
/* */ /* * Copyright (C) 2015-present ScyllaDB * * Modified by ScyllaDB */ /* * SPDX-License-Identifier: (AGPL-3.0-or-later and Apache-2.0) */ #pragma once #include <vector> #include "cql3/query_options.hh" #include "cql3/statements/bound.hh" #include "cql3/restrictions/restrictions.hh" #include "cql3/restrictions/restriction.hh" #include "cql3/restrictions/restriction.hh" #include "types.hh" #include "query-request.hh" #include <seastar/core/shared_ptr.hh> namespace cql3 { namespace restrictions { /** * A set of restrictions on a primary key part (partition key or clustering key). * * What was in AbstractPrimaryKeyRestrictions was moved here (In pre 1.8 Java interfaces could not have default * implementations of methods). */ class partition_key_restrictions: public restriction, public restrictions, public enable_shared_from_this<partition_key_restrictions> { public: partition_key_restrictions() = default; virtual void merge_with(::shared_ptr<restriction> other) = 0; virtual ::shared_ptr<partition_key_restrictions> merge_to(schema_ptr, ::shared_ptr<restriction> restriction) { merge_with(restriction); return this->shared_from_this(); } using restrictions::has_supporting_index; bool empty() const override { return get_column_defs().empty(); } uint32_t size() const override { return uint32_t(get_column_defs().size()); } bool has_unrestricted_components(const schema& schema) const { return size() < schema.partition_key_size(); } virtual bool needs_filtering(const schema& schema) const { return !empty() && !has_token(expression) && (has_unrestricted_components(schema) || has_slice_or_needs_filtering(expression)); } // NOTICE(sarna): This function is useless for partition key restrictions, // but it should remain here until single_column_primary_key_restrictions class is detemplatized. virtual unsigned int num_prefix_columns_that_need_not_be_filtered() const { return 0; } virtual bool is_all_eq() const { return false; } size_t prefix_size(const schema&) const { return 0; } }; class clustering_key_restrictions : public restriction, public restrictions, public enable_shared_from_this<clustering_key_restrictions> { public: clustering_key_restrictions() = default; virtual void merge_with(::shared_ptr<restriction> other) = 0; virtual ::shared_ptr<clustering_key_restrictions> merge_to(schema_ptr, ::shared_ptr<restriction> restriction) { merge_with(restriction); return this->shared_from_this(); } using restrictions::has_supporting_index; bool empty() const override { return get_column_defs().empty(); } uint32_t size() const override { return uint32_t(get_column_defs().size()); } bool has_unrestricted_components(const schema& schema) const { return size() < schema.clustering_key_size(); } virtual bool needs_filtering(const schema& schema) const { return false; } // How long a prefix of the restrictions could have resulted in // need_filtering() == false. These restrictions do not need to be // applied during filtering. // For example, if we have the filter "c1 < 3 and c2 > 3", c1 does // not need filtering (just a read stopping at c1=3) but c2 does, // so num_prefix_columns_that_need_not_be_filtered() will be 1. virtual unsigned int num_prefix_columns_that_need_not_be_filtered() const { return 0; } virtual bool is_all_eq() const { return false; } size_t prefix_size(const schema& schema) const { size_t count = 0; if (schema.clustering_key_columns().empty()) { return count; } auto column_defs = get_column_defs(); column_id expected_column_id = schema.clustering_key_columns().begin()->id; for (auto&& cdef : column_defs) { if (schema.position(*cdef) != expected_column_id) { return count; } expected_column_id++; count++; } return count; } }; // FIXME(sarna): transitive hack only, do not judge. Should be dropped after all primary_key_restrictions<T> uses are removed from code. template<typename ValueType> using primary_key_restrictions = std::conditional_t<std::is_same_v<ValueType, partition_key>, partition_key_restrictions, clustering_key_restrictions>; } }
agpl-3.0
syci/partner-contact
base_vat_sanitized/models/res_partner.py
790
# Copyright 2016 Akretion (http://www.akretion.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). # @author Alexis de Lattre <[email protected]> import re from odoo import api, fields, models class ResPartner(models.Model): _inherit = "res.partner" sanitized_vat = fields.Char( compute="_compute_sanitized_vat", string="Sanitized TIN", store=True, readonly=True, help="TIN in uppercase without spaces nor special caracters.", ) @classmethod def _sanitize_vat(cls, vat): return vat and re.sub(r"\W+", "", vat).upper() or False @api.depends("vat") def _compute_sanitized_vat(self): for partner in self: partner.sanitized_vat = self._sanitize_vat(partner.vat)
agpl-3.0
PROCERGS/login-cidadao
src/PROCERGS/LoginCidadao/CoreBundle/Helper/MeuRSHelper.php
4066
<?php /* * This file is part of the login-cidadao project or it's bundles. * * (c) Guilherme Donato <guilhermednt on github> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PROCERGS\LoginCidadao\CoreBundle\Helper; use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityRepository; use LoginCidadao\CoreBundle\Entity\PersonRepository; use LoginCidadao\CoreBundle\Model\PersonInterface; use PROCERGS\LoginCidadao\CoreBundle\Entity\PersonMeuRS; use PROCERGS\LoginCidadao\CoreBundle\Entity\PersonMeuRSRepository; class MeuRSHelper { /** @var EntityManager */ protected $em; /** @var PersonMeuRSRepository */ protected $personMeuRSRepository; public function __construct( EntityManager $em, EntityRepository $personMeuRSRepository ) { $this->em = $em; $this->personMeuRSRepository = $personMeuRSRepository; } /** * @param \LoginCidadao\CoreBundle\Model\PersonInterface $person * @param boolean $create * @return PersonMeuRS */ public function getPersonMeuRS(PersonInterface $person, $create = false) { $personMeuRS = $this->personMeuRSRepository->findOneBy( array( 'person' => $person, ) ); if ($create && !($personMeuRS instanceof PersonMeuRS)) { $personMeuRS = new PersonMeuRS(); $personMeuRS->setPerson($person); $this->em->persist($personMeuRS); $this->em->flush($personMeuRS); } return $personMeuRS; } public function getVoterRegistration(PersonInterface $person) { $personMeuRS = $this->getPersonMeuRS($person); return $personMeuRS ? $personMeuRS->getVoterRegistration() : null; } public function setVoterRegistration( EntityManager $em, PersonInterface $person, $value ) { $personMeuRS = $this->getPersonMeuRS($person, true); $personMeuRS->setVoterRegistration($value); $em->persist($personMeuRS); } public function getNfgAccessToken(PersonInterface $person) { $personMeuRS = $this->getPersonMeuRS($person); return $personMeuRS ? $personMeuRS->getNfgAccessToken() : null; } public function getNfgProfile(PersonInterface $person) { $personMeuRS = $this->getPersonMeuRS($person); return $personMeuRS ? $personMeuRS->getNfgProfile() : null; } public function findPersonByVoterRegistration($voterRegistration) { $result = $this->personMeuRSRepository ->findOneBy(compact('voterRegistration')); return $result ? $result->getPerson() : null; } /** * @param $voterRegistration * @return PersonMeuRS|object|null */ public function findPersonMeuRSByVoterRegistration($voterRegistration) { return $this->personMeuRSRepository ->findOneBy(compact('voterRegistration')); } /** * @param string $cpf * @param bool $create * @return null|PersonMeuRS */ public function getPersonByCpf($cpf, $create = false) { /** @var PersonInterface|null $person */ $person = $this->getPersonRepository()->findOneBy(compact('cpf')); if (!$person) { return null; } return $this->getPersonMeuRS($person, $create); } /** * @param string $email * @param bool $create * @return null|PersonMeuRS */ public function getPersonByEmail($email, $create = false) { /** @var PersonInterface|null $person */ $person = $this->getPersonRepository()->findOneByEmail($email); if (!$person) { return null; } return $this->getPersonMeuRS($person, $create); } /** * @return PersonRepository|EntityRepository */ private function getPersonRepository() { return $this->em->getRepository('LoginCidadaoCoreBundle:Person'); } }
agpl-3.0
boob-sbcm/3838438
src/main/java/com/rapidminer/operator/learner/bayes/DistributionModel.java
3022
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.learner.bayes; import java.util.Collection; import com.rapidminer.example.Attribute; import com.rapidminer.example.ExampleSet; import com.rapidminer.example.set.ExampleSetUtilities; import com.rapidminer.operator.ProcessStoppedException; import com.rapidminer.operator.learner.UpdateablePredictionModel; import com.rapidminer.tools.math.distribution.Distribution; /** * DistributionModel is a model for learners which estimate distributions of attribute values from * example sets like NaiveBayes. * * Predictions are calculated as product of the conditional probabilities for all attributes times * the class probability. * * The basic learning concept is to simply count occurances of classes and attribute values. This * means no propabilities are calculated during the learning step. This is only done before output. * Optionally, this calculation can apply a Laplace correction which means in particular that zero * probabilities are avoided which would hide information in distributions of other attributes. * * @author Tobias Malbrecht */ public abstract class DistributionModel extends UpdateablePredictionModel { private static final long serialVersionUID = -402827845291958569L; public DistributionModel(ExampleSet exampleSet, ExampleSetUtilities.SetsCompareOption setsCompareOption, ExampleSetUtilities.TypesCompareOption typesCompareOption) { super(exampleSet, setsCompareOption, typesCompareOption); } public abstract String[] getAttributeNames(); public abstract int getNumberOfAttributes(); public abstract double getLowerBound(int attributeIndex); public abstract double getUpperBound(int attributeIndex); public abstract boolean isDiscrete(int attributeIndex); public abstract Collection<Integer> getClassIndices(); public abstract int getNumberOfClasses(); public abstract String getClassName(int index); public abstract Distribution getDistribution(int classIndex, int attributeIndex); @Override public abstract ExampleSet performPrediction(ExampleSet exampleSet, Attribute predictedLabel) throws ProcessStoppedException; }
agpl-3.0
briandk/transcriptase
src/main/menu/windows-menu.ts
1184
import { createSharedMenuItems, editMenu, fileOperationsSubmenu } from "./shared-menu" import isDev from "electron-is-dev" export function createWindowsMenu( window: Electron.BrowserWindow, ): Electron.MenuItemConstructorOptions[] { const shared = createSharedMenuItems(window) // TODO: check what macFileMenu exports. There may be some // type issues with how the mac, windows, and linux menus get constructed. // const fileMenu: Electron.MenuItemConstructorOptions = { label: "&File", submenu: fileOperationsSubmenu.concat({ label: "Quit", role: "quit", accelerator: "Alt+F4" }), } const viewMenu: Electron.MenuItemConstructorOptions = { label: "View", submenu: isDev ? [ { ...shared.reload, accelerator: "Ctrl+R" }, { ...shared.storybook, accelerator: "Alt+Shift+S" }, { ...shared.toggleDevTools, accelerator: "Ctrl+Alt+I" }, ] : [{ ...shared.fullScreen, accelerator: "Ctrl+Alt+F" }], } const helpMenu: Electron.MenuItemConstructorOptions = { label: "Help", submenu: [process.env.HOMEPAGE && shared.visit].filter(Boolean), } return [fileMenu, editMenu, viewMenu, helpMenu] }
agpl-3.0
digitalbazaar/monarch
cpp/v8/V8Engine.cpp
3434
/* * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved. */ #include "monarch/rt/DynamicObjectIterator.h" #include "monarch/v8/V8Engine.h" using namespace std; using namespace v8; using namespace monarch::rt; using namespace monarch::v8; #define EXCEPTION_PREFIX "monarch.v8" V8Engine::V8Engine() { } V8Engine::~V8Engine() { // Dispose the persistent context. mContext.Dispose(); } // FIXME: add options to control default init process bool V8Engine::initialize(V8Controller* c) { mController = c; // Handle scope for temporary handles. HandleScope handle_scope; // Create a new context and store persistent reference Handle<Context> context = Context::New(NULL, c->getGlobals()); mContext = Persistent<Context>::New(context); return true; } bool V8Engine::setDynamicObject(const char* name, DynamicObject& dyno) { bool rval = true; // lock V8 while script is running Locker locker; // Handle scope for temporary handles. HandleScope handleScope; // Enter context. Context::Scope contextScope(mContext); Handle<Object> jsDyno = V8Controller::wrapDynamicObject(&dyno); mContext->Global()->Set(String::New(name), jsDyno); return rval; } bool V8Engine::getDynamicObject(const char* name, DynamicObject& dyno) { bool rval = true; // lock V8 while script is running Locker locker; // Handle scope for temporary handles. HandleScope handleScope; // Enter context. Context::Scope contextScope(mContext); Local<Value> jsDyno = mContext->Global()->Get(String::New(name)); dyno = V8Controller::j2d(jsDyno); return rval; } bool V8Engine::runScript(const char* js, std::string& result) { bool rval = true; // lock V8 while script is running Locker locker; // Create a stack-allocated handle scope. HandleScope handle_scope; // Enter the engine context for compiling and running the script. Context::Scope context_scope(mContext); // We're just about to compile the script; set up an error handler to // catch any exceptions the script might throw. TryCatch tryCatch; // Create a string containing the JavaScript source code. Local< ::v8::String> source = ::v8::String::New(js); // Script containing the compiled source. Local< ::v8::Script> script; // Result of the script after it has been run. Local<Value> resultval; if(rval) { // Compile the source code. script = ::v8::Script::Compile(source); if(script.IsEmpty()) { String::Utf8Value error(tryCatch.Exception()); // The script failed to compile ExceptionRef e = new rt::Exception( "Script failed to compile.", EXCEPTION_PREFIX ".CompileError"); e->getDetails()["error"] = *error; rt::Exception::set(e); rval = false; } } if(rval) { // Run the script to get the result. resultval = script->Run(); if(resultval.IsEmpty()) { String::Utf8Value error(tryCatch.Exception()); // The script failed to run ExceptionRef e = new rt::Exception( "Script failed to run.", EXCEPTION_PREFIX ".RunError"); e->getDetails()["error"] = *error; rt::Exception::set(e); rval = false; } } if(rval) { ::v8::String::AsciiValue ascii(resultval); result = *ascii; } return rval; }
agpl-3.0
EASOL/easol
application/views/Cohorts/students.php
1407
<?php /* @var $cohort Edfi_Cohort */ ?> <div class="row"> <div class="col-md-12"> <h1 class="page-header">Cohort</h1> <br/><br/> </div> </div> <div class="col-md-6"> <table class="table table-bordered "> <tr> <th>Cohort ID:</th> <td><?= $cohort->CohortIdentifier ?></td> </tr> <tr> <th>Cohort Description:</th> <td><?= $cohort->CohortDescription ?></td> </tr> </table> </div> <br> <div class="row"> <div class="col-md-12"> <div class="datatablegrid"> <table id="student-table" class="table table-striped table-bordered table-widget" cellspacing="0" width="100%"> <thead> <tr> <th>Student Name</th> </tr> </thead> <tbody> <?php foreach ($student_listing as $row) : ?> <tr> <td> <a href="<?php echo site_url('student/profile/' . $row->StudentUSI) ?>"><?php echo $row->FirstName . ' ' . $row->LastSurname; ?></a> </td> </tr> <?php endforeach; ?> </tbody> </table> <div class="pull-right form-group" style="padding-top: 0.25em;"> <div id="csv-button"></div> </div> </div> </div> </div>
agpl-3.0
rosenpin/Gadgetbridge
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/devices/hplus/HPlusHealthSampleProvider.java
10573
/* Copyright (C) 2017 Andreas Shimokawa, João Paulo Barraca This file is part of Gadgetbridge. Gadgetbridge 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. Gadgetbridge 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 nodomain.freeyourgadget.gadgetbridge.devices.hplus; /* * @author João Paulo Barraca &lt;[email protected]&gt; */ import android.support.annotation.NonNull; import android.util.Log; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.GregorianCalendar; import java.util.List; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.Property; import de.greenrobot.dao.query.QueryBuilder; import nodomain.freeyourgadget.gadgetbridge.database.DBHelper; import nodomain.freeyourgadget.gadgetbridge.devices.AbstractSampleProvider; import nodomain.freeyourgadget.gadgetbridge.entities.DaoSession; import nodomain.freeyourgadget.gadgetbridge.entities.Device; import nodomain.freeyourgadget.gadgetbridge.entities.HPlusHealthActivityOverlay; import nodomain.freeyourgadget.gadgetbridge.entities.HPlusHealthActivityOverlayDao; import nodomain.freeyourgadget.gadgetbridge.entities.HPlusHealthActivitySample; import nodomain.freeyourgadget.gadgetbridge.entities.HPlusHealthActivitySampleDao; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.model.ActivityKind; import nodomain.freeyourgadget.gadgetbridge.model.ActivitySample; import nodomain.freeyourgadget.gadgetbridge.service.devices.hplus.HPlusDataRecord; public class HPlusHealthSampleProvider extends AbstractSampleProvider<HPlusHealthActivitySample> { private GBDevice mDevice; private DaoSession mSession; public HPlusHealthSampleProvider(GBDevice device, DaoSession session) { super(device, session); mSession = session; mDevice = device; } public int normalizeType(int rawType) { switch (rawType) { case HPlusDataRecord.TYPE_DAY_SLOT: case HPlusDataRecord.TYPE_DAY_SUMMARY: case HPlusDataRecord.TYPE_REALTIME: case HPlusDataRecord.TYPE_SLEEP: case HPlusDataRecord.TYPE_UNKNOWN: return ActivityKind.TYPE_UNKNOWN; default: return rawType; } } public int toRawActivityKind(int activityKind) { switch (activityKind){ case ActivityKind.TYPE_DEEP_SLEEP: return ActivityKind.TYPE_DEEP_SLEEP; case ActivityKind.TYPE_LIGHT_SLEEP: return ActivityKind.TYPE_LIGHT_SLEEP; default: return HPlusDataRecord.TYPE_DAY_SLOT; } } @NonNull @Override protected Property getTimestampSampleProperty() { return HPlusHealthActivitySampleDao.Properties.Timestamp; } @Override public HPlusHealthActivitySample createActivitySample() { return new HPlusHealthActivitySample(); } @Override protected Property getRawKindSampleProperty() { return null; // HPlusHealthActivitySampleDao.Properties.RawKind; } @Override public float normalizeIntensity(int rawIntensity) { return rawIntensity / (float) 100.0; } @NonNull @Override protected Property getDeviceIdentifierSampleProperty() { return HPlusHealthActivitySampleDao.Properties.DeviceId; } @Override public AbstractDao<HPlusHealthActivitySample, ?> getSampleDao() { return getSession().getHPlusHealthActivitySampleDao(); } public List<HPlusHealthActivitySample> getActivityamples(int timestamp_from, int timestamp_to) { return getAllActivitySamples(timestamp_from, timestamp_to); } public List<HPlusHealthActivitySample> getSleepSamples(int timestamp_from, int timestamp_to) { return getAllActivitySamples(timestamp_from, timestamp_to); } @NonNull @Override public List<HPlusHealthActivitySample> getAllActivitySamples(int timestamp_from, int timestamp_to) { List<HPlusHealthActivitySample> samples = super.getGBActivitySamples(timestamp_from, timestamp_to, ActivityKind.TYPE_ALL); Device dbDevice = DBHelper.findDevice(getDevice(), getSession()); if (dbDevice == null) { return Collections.emptyList(); } QueryBuilder<HPlusHealthActivityOverlay> qb = getSession().getHPlusHealthActivityOverlayDao().queryBuilder(); qb.where(HPlusHealthActivityOverlayDao.Properties.DeviceId.eq(dbDevice.getId()), HPlusHealthActivityOverlayDao.Properties.TimestampFrom.ge(timestamp_from - 3600 * 24), HPlusHealthActivityOverlayDao.Properties.TimestampTo.le(timestamp_to), HPlusHealthActivityOverlayDao.Properties.TimestampTo.ge(timestamp_from)); List<HPlusHealthActivityOverlay> overlayRecords = qb.build().list(); //Apply Overlays for (HPlusHealthActivityOverlay overlay : overlayRecords) { //Create fake events to improve activity counters if there are no events around the overlay //timestamp boundaries //Insert one before, one at the beginning, one at the end, and one 1s after. insertVirtualItem(samples, Math.max(overlay.getTimestampFrom() - 1, timestamp_from), overlay.getDeviceId(), overlay.getUserId()); insertVirtualItem(samples, Math.max(overlay.getTimestampFrom(), timestamp_from), overlay.getDeviceId(), overlay.getUserId()); insertVirtualItem(samples, Math.min(overlay.getTimestampTo() - 1, timestamp_to - 1), overlay.getDeviceId(), overlay.getUserId()); insertVirtualItem(samples, Math.min(overlay.getTimestampTo(), timestamp_to), overlay.getDeviceId(), overlay.getUserId()); } Collections.sort(samples, new Comparator<HPlusHealthActivitySample>() { public int compare(HPlusHealthActivitySample one, HPlusHealthActivitySample other) { return one.getTimestamp() - other.getTimestamp(); } }); //Apply Overlays for (HPlusHealthActivityOverlay overlay : overlayRecords) { long nonSleepTimeEnd = 0; for (HPlusHealthActivitySample sample : samples) { if (sample.getRawKind() == ActivityKind.TYPE_NOT_WORN) continue; if (sample.getTimestamp() >= overlay.getTimestampFrom() && sample.getTimestamp() < overlay.getTimestampTo()) { if (overlay.getRawKind() == ActivityKind.TYPE_NOT_WORN || overlay.getRawKind() == ActivityKind.TYPE_LIGHT_SLEEP || overlay.getRawKind() == ActivityKind.TYPE_DEEP_SLEEP) { if (sample.getRawKind() == HPlusDataRecord.TYPE_DAY_SLOT && sample.getSteps() > 0){ nonSleepTimeEnd = sample.getTimestamp() + 10 * 60; // 10 minutes continue; }else if(sample.getRawKind() == HPlusDataRecord.TYPE_REALTIME && sample.getTimestamp() <= nonSleepTimeEnd){ continue; } if (overlay.getRawKind() == ActivityKind.TYPE_NOT_WORN) sample.setHeartRate(0); if (sample.getRawKind() != ActivityKind.TYPE_NOT_WORN) sample.setRawKind(overlay.getRawKind()); sample.setRawIntensity(10); } } } } //Fix Step counters //Todays sample steps will come from the Day Slots messages //Historical steps will be provided by Day Summaries messages //This will allow both week and current day results to be consistent Calendar today = GregorianCalendar.getInstance(); today.set(Calendar.HOUR_OF_DAY, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); today.set(Calendar.MILLISECOND, 0); int stepsTodayMax = 0; int stepsTodayCount = 0; HPlusHealthActivitySample lastSample = null; for (HPlusHealthActivitySample sample: samples) { if (sample.getTimestamp() >= today.getTimeInMillis() / 1000) { /**Strategy is: * Calculate max steps from realtime messages * Calculate sum of steps from day 10 minute slot summaries */ if(sample.getRawKind() == HPlusDataRecord.TYPE_REALTIME) { stepsTodayMax = Math.max(stepsTodayMax, sample.getSteps()); }else if(sample.getRawKind() == HPlusDataRecord.TYPE_DAY_SLOT) { stepsTodayCount += sample.getSteps(); } sample.setSteps(ActivitySample.NOT_MEASURED); lastSample = sample; } else { if (sample.getRawKind() != HPlusDataRecord.TYPE_DAY_SUMMARY) { sample.setSteps(ActivitySample.NOT_MEASURED); } } } if(lastSample != null) lastSample.setSteps(Math.max(stepsTodayCount, stepsTodayMax)); detachFromSession(); return samples; } private List<HPlusHealthActivitySample> insertVirtualItem(List<HPlusHealthActivitySample> samples, int timestamp, long deviceId, long userId) { HPlusHealthActivitySample sample = new HPlusHealthActivitySample( timestamp, // ts deviceId, userId, // User id null, // Raw Data ActivityKind.TYPE_UNKNOWN, 1, // Intensity ActivitySample.NOT_MEASURED, // Steps ActivitySample.NOT_MEASURED, // HR ActivitySample.NOT_MEASURED, // Distance ActivitySample.NOT_MEASURED // Calories ); sample.setProvider(this); samples.add(sample); return samples; } }
agpl-3.0
RajkumarSelvaraju/FixNix_CRM
include/javascript/yui3/build/datatype/datatype-xml-format.js
546
/* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 3.3.0 build: 3167 */ YUI.add('datatype-xml-format',function(Y){var LANG=Y.Lang;Y.mix(Y.namespace("DataType.XML"),{format:function(data){try{if(!LANG.isUndefined(XMLSerializer)){return(new XMLSerializer()).serializeToString(data);}} catch(e){if(data&&data.xml){return data.xml;} else{return(LANG.isValue(data)&&data.toString)?data.toString():"";}}}});},'3.3.0',{requires:['yui-base']});
agpl-3.0
chastell/kamerling
test/kamerling/handler_test.rb
985
require_relative '../test_helper' require_relative '../../lib/kamerling/addr' require_relative '../../lib/kamerling/handler' require_relative '../../lib/kamerling/message' require_relative '../../lib/kamerling/receiver' require_relative '../../lib/kamerling/registrar' module Kamerling describe Handler do describe '#handle' do fake :receiver, as: :class fake :registrar, as: :class let(:addr) { Addr.new } let(:handler) { Handler.new(receiver: receiver, registrar: registrar) } it 'handles RGST inputs' do message = Message.new('RGST') handler.handle message, addr: addr _(registrar).must_have_received :call, [addr: addr, message: message] end it 'handles RSLT inputs' do message = Message.new('RSLT') handler.handle message, addr: addr _(receiver).must_have_received :call, [addr: addr, message: message] end end end end
agpl-3.0
odoo-brazil/l10n-brazil-wip
financial/reports/financial_cashflow.py
20320
# -*- coding: utf-8 -*- # Copyright 2017 KMEE # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models, tools from odoo.tools.safe_eval import safe_eval from ..constants import ( FINANCIAL_STATE, FINANCIAL_TYPE ) class FinancialCashflow(models.Model): _name = 'financial.cashflow' _auto = False _order = 'date_business_maturity, id' amount_cumulative_balance = fields.Monetary( string=u"Balance", ) amount_debit = fields.Monetary( string=u"Debit", ) amount_credit = fields.Monetary( string=u"Credit", ) amount_paid = fields.Monetary( string=u"Paid", ) state = fields.Selection( selection=FINANCIAL_STATE, string=u'Status', ) company_id = fields.Many2one( comodel_name='res.company', string=u'Company', ) currency_id = fields.Many2one( comodel_name='res.currency', string=u'Currency', ) partner_id = fields.Many2one( string=u'Partner', comodel_name='res.partner', ) document_number = fields.Char( string=u"Document Nº", ) document_item = fields.Char() date = fields.Date( string=u"Document date", ) amount_total = fields.Monetary( string=u"Total", ) date_maturity = fields.Date( string=u"Maturity", ) financial_type = fields.Selection( selection=FINANCIAL_TYPE, ) date_business_maturity = fields.Date( string=u'Business maturity', ) payment_method_id = fields.Many2one( comodel_name='account.payment.method', string=u'Payment Method', ) payment_term_id = fields.Many2one( string=u'Payment term', comodel_name='account.payment.term', ) analytic_account_id = fields.Many2one( comodel_name='account.analytic.account', string=u'Analytic account' ) account_type_id = fields.Many2one( comodel_name='account.account.type', string=u'Account', ) bank_id = fields.Many2one( comodel_name='res.partner.bank', string=u'Bank Account', ) def recalculate_balance(self, res): balance = 0.00 for record in res: credit = record.get('amount_credit', 0.00) debit = record.get('amount_debit', 0.00) if not debit and not credit and record.get( 'amount_cumulative_balance', 0.00): balance += record.get('amount_cumulative_balance', 0.00) balance += credit + debit record['amount_cumulative_balance'] = balance @api.model def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): res = super(FinancialCashflow, self)\ .read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy) self.recalculate_balance(res) return res @api.model def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None): res = super(FinancialCashflow, self)\ .search_read(domain, fields, offset, limit, order=False) self.recalculate_balance(res) return res @api.model_cr def init(self): tools.drop_view_if_exists(self.env.cr, self._table) self.env.cr.execute(""" DROP VIEW IF EXISTS financial_cashflow; DROP VIEW IF EXISTS financial_cashflow_base; DROP VIEW IF EXISTS financial_cashflow_debit; DROP VIEW IF EXISTS financial_cashflow_bank; DROP VIEW IF EXISTS financial_cashflow_credit; """) self.env.cr.execute(""" CREATE OR REPLACE VIEW financial_cashflow_credit AS SELECT financial_move.create_date, financial_move.id, financial_move.document_number, financial_move.financial_type, financial_move.state, financial_move.date_business_maturity, financial_move.date, financial_move.payment_method_id, financial_move.payment_term_id, financial_move.date_maturity, financial_move.partner_id, financial_move.currency_id, financial_move.account_type_id, financial_move.analytic_account_id, financial_move.bank_id, coalesce(financial_move.amount_paid, 0) AS amount_paid, coalesce(financial_move.amount_total, 0) AS amount_total, coalesce(financial_move.amount_residual, 0) AS amount_credit, 0 AS amount_debit, coalesce(financial_move.amount_total, 0) AS amount_balance FROM public.financial_move WHERE financial_move.financial_type = '2receive' and financial_move.amount_residual != 0.0 ; """) self.env.cr.execute(""" CREATE OR REPLACE VIEW financial_cashflow_credit_rr AS SELECT financial_move.create_date, financial_move.id, financial_move.document_number, financial_move.financial_type, financial_move.state, -- financial_move.date_business_maturity, financial_move.date_credit_debit as date_business_maturity, financial_move.date, financial_move.payment_method_id, financial_move.payment_term_id, financial_move.date_maturity, financial_move.partner_id, financial_move.currency_id, financial_move.account_type_id, financial_move.analytic_account_id, financial_move.bank_id, --- financial_move.journal_id, coalesce(financial_move.amount_paid, 0) AS amount_paid, coalesce(financial_move.amount_total, 0) AS amount_total, coalesce(financial_move.amount_total, 0) AS amount_credit, 0 AS amount_debit, coalesce(financial_move.amount_total, 0) AS amount_balance FROM public.financial_move WHERE financial_move.financial_type = 'receipt_item'; """) self.env.cr.execute(""" CREATE OR REPLACE VIEW financial_cashflow_bank AS SELECT res_partner_bank.date_balance as create_date, res_partner_bank.id * (-1) as id, 'Saldo inicial' as document_number, 'open' as financial_type, 'residual' as state, res_partner_bank.date_balance as date_business_maturity, res_partner_bank.date_balance as date, res_partner_bank.id as bank_id, --- NULL as journal_id, NULL as payment_method_id, NULL as payment_term_id, res_partner_bank.date_balance as date_maturity, NULL as partner_id, res_partner_bank.currency_id, ( select res_id from ir_model_data where name = 'data_account_type_liquidity' ) as account_type_id, NULL as analytic_account_id, coalesce(res_partner_bank.initial_balance, 0) as amount_paid, 0 as amount_balance, 0 as amount_total, coalesce(res_partner_bank.initial_balance, 0) as amount_credit, 0 as amount_debit FROM public.res_partner_bank INNER JOIN public.res_company ON res_partner_bank.partner_id = res_company.partner_id; """) self.env.cr.execute(""" CREATE OR REPLACE VIEW financial_cashflow_debit AS SELECT financial_move.create_date, financial_move.id, financial_move.document_number, financial_move.financial_type, financial_move.state, financial_move.date_business_maturity, financial_move.date, financial_move.payment_method_id, financial_move.payment_term_id, financial_move.date_maturity, financial_move.partner_id, financial_move.currency_id, financial_move.account_type_id, financial_move.analytic_account_id, financial_move.bank_id, --- financial_move.journal_id, coalesce(financial_move.amount_paid, 0) AS amount_paid, coalesce(financial_move.amount_total, 0) AS amount_total, 0 AS amount_credit, (-1) * coalesce(financial_move.amount_residual, 0) AS amount_debit, (-1) * coalesce(financial_move.amount_total, 0) AS amount_balance FROM public.financial_move WHERE financial_move.financial_type = '2pay' and financial_move.amount_residual != 0.0 ; """) self.env.cr.execute(""" CREATE OR REPLACE VIEW financial_cashflow_debit_pp AS SELECT financial_move.create_date, financial_move.id, financial_move.document_number, financial_move.financial_type, financial_move.state, -- financial_move.date_business_maturity, financial_move.date_credit_debit as date_business_maturity, financial_move.date, financial_move.payment_method_id, financial_move.payment_term_id, financial_move.date_maturity, financial_move.partner_id, financial_move.currency_id, financial_move.account_type_id, financial_move.analytic_account_id, financial_move.bank_id, --- financial_move.journal_id, coalesce(financial_move.amount_paid, 0) AS amount_paid, coalesce(financial_move.amount_total, 0) AS amount_total, 0 AS amount_credit, (-1) * coalesce(financial_move.amount_total, 0) AS amount_debit, (-1) * coalesce(financial_move.amount_total, 0) AS amount_balance FROM public.financial_move WHERE financial_move.financial_type = 'payment_item'; """) self.env.cr.execute(""" CREATE OR REPLACE VIEW financial_cashflow_base AS SELECT c.create_date, c.id, c.document_number, c.financial_type, c.state, c.date_business_maturity, c.date, c.payment_method_id, c.payment_term_id, c.date_maturity, c.partner_id, c.currency_id, c.account_type_id, c.analytic_account_id, --- c.journal_id, c.bank_id, c.amount_total, c.amount_paid, c.amount_credit, c.amount_debit, c.amount_balance FROM financial_cashflow_credit c UNION ALL SELECT crr.create_date, crr.id, crr.document_number, crr.financial_type, crr.state, crr.date_business_maturity, crr.date, crr.payment_method_id, crr.payment_term_id, crr.date_maturity, crr.partner_id, crr.currency_id, crr.account_type_id, crr.analytic_account_id, --- crr.journal_id, crr.bank_id, crr.amount_total, crr.amount_paid, crr.amount_credit, crr.amount_debit, crr.amount_balance FROM financial_cashflow_credit_rr crr UNION ALL SELECT d.create_date, d.id, d.document_number, d.financial_type, d.state, d.date_business_maturity, d.date, d.payment_method_id, d.payment_term_id, d.date_maturity, d.partner_id, d.currency_id, d.account_type_id, d.analytic_account_id, --- d.journal_id, d.bank_id, d.amount_total, d.amount_paid, d.amount_credit, d.amount_debit, d.amount_balance FROM financial_cashflow_debit d UNION ALL SELECT dpp.create_date, dpp.id, dpp.document_number, dpp.financial_type, dpp.state, dpp.date_business_maturity, dpp.date, dpp.payment_method_id, dpp.payment_term_id, dpp.date_maturity, dpp.partner_id, dpp.currency_id, dpp.account_type_id, dpp.analytic_account_id, --- dpp.journal_id, dpp.bank_id, dpp.amount_total, dpp.amount_paid, dpp.amount_credit, dpp.amount_debit, dpp.amount_balance FROM financial_cashflow_debit_pp dpp UNION ALL SELECT b.create_date, b.id, b.document_number, b.financial_type, b.state, b.date_business_maturity, b.date, b.payment_method_id, b.payment_term_id, b.date_maturity, b.partner_id, b.currency_id, b.account_type_id, b.analytic_account_id, --- b.journal_id, b.bank_id, b.amount_total, b.amount_paid, b.amount_credit, b.amount_debit, b.amount_balance FROM financial_cashflow_bank b """) self.env.cr.execute(""" CREATE OR REPLACE VIEW financial_cashflow AS SELECT b.create_date, b.id, b.document_number, b.financial_type, b.state, b.date_business_maturity, b.date, b.payment_method_id, b.payment_term_id, b.date_maturity, b.partner_id, b.currency_id, b.account_type_id, b.analytic_account_id, --- b.journal_id, b.bank_id, b.amount_total, b.amount_paid, b.amount_credit, b.amount_debit, b.amount_balance, SUM(b.amount_balance) OVER (order by b.date_business_maturity, b.id) AS amount_cumulative_balance -- aqui deveria haver um campo balance_date ou algo assim -- que seria a data de crédito/débito efetivo na conta -- pois boletos e cheques tem data de crédito d+1 ou d+2 -- após o depósito/pagamento. Exemplo: -- over(order by b.data_credito_debito) FROM financial_cashflow_base b; """) @api.model def _query_get(self, domain=None): context = dict(self._context or {}) domain = domain and safe_eval(str(domain)) or [] date_field = 'date' if context.get('aged_balance'): date_field = 'date_maturity' if context.get('date_to'): domain += [(date_field, '<=', context['date_to'])] if context.get('date_from'): if not context.get('strict_range'): domain += [ '|', (date_field, '>=', context['date_from']), ('account_type_id.user_type_id.include_initial_balance', '=', True)] elif context.get('initial_bal'): domain += [(date_field, '<', context['date_from'])] else: domain += [(date_field, '>=', context['date_from'])] # if context.get('journal_ids'): # domain += [('journal_id', 'in', context['journal_ids'])] state = context.get('state') if state and state.lower() != 'all': domain += [('state', '=', state)] if context.get('company_id'): domain += [('company_id', '=', context['company_id'])] if 'company_ids' in context: domain += [('company_id', 'in', context['company_ids'])] # if context.get('reconcile_date'): # domain += ['|', ('reconciled', '=', False), '|', ( # 'matched_debit_ids.create_date', '>', # context['reconcile_date']), ( # 'matched_credit_ids.create_date', '>', # context['reconcile_date'])] if context.get('account_tag_ids'): domain += [ ('account_type_id.tag_ids', 'in', context['account_tag_ids'].ids)] if context.get('analytic_tag_ids'): domain += ['|', ( 'analytic_account_id.tag_ids', 'in', context['analytic_tag_ids'].ids), ('analytic_tag_ids', 'in', context['analytic_tag_ids'].ids)] if context.get('analytic_account_ids'): domain += [ ('analytic_account_id', 'in', context['analytic_account_ids'].ids)] where_clause = "" where_clause_params = [] tables = '' if domain: query = self._where_calc(domain) tables, where_clause, where_clause_params = query.get_sql() return tables, where_clause, where_clause_params
agpl-3.0
GaiaOnlineCommunity/GaiaOnline.Unity.Library
src/GaiaOnline.Game.Client/Controller/MovementController.cs
355
using System; using System.Collections.Generic; using System.Text; using UnityEngine; namespace GaiaOnline { public abstract class MovementController : MonoBehaviour { /// <summary> /// Returns the current input direction. /// </summary> /// <returns>The direction of the input.</returns> public abstract Vector2 GetInputDirection(); } }
agpl-3.0
vimvim/AkkaTest
src/main/scala/rtmp/protocol/v2/handshake/ValidationScheme1.scala
1234
package rtmp.protocol.v2.handshake import akka.event.LoggingAdapter /** * */ class ValidationScheme1(implicit override val log:LoggingAdapter) extends ValidationScheme(1, log) { /** * Returns the DH byte offset. * * @return dh offset */ def getDHOffset(bytes: Array[Byte]): Int = { var offset: Int = (bytes(768) & 0x0ff) + (bytes(769) & 0x0ff) + (bytes(770) & 0x0ff) + (bytes(771) & 0x0ff) offset = offset % 632 offset = offset + 8 if (offset + Constants.KEY_LENGTH >= 1536) { log.error("Invalid DH offset") } offset } /** * Returns a digest byte offset. * * @param pBuffer source for digest data * @return digest offset */ def getDigestOffset(pBuffer: Array[Byte]): Int = { if (log.isDebugEnabled) { log.debug("Scheme 1 offset bytes {},{},{},{}", Array[Int](pBuffer(772) & 0x0ff, pBuffer(773) & 0x0ff, pBuffer(774) & 0x0ff, pBuffer(775) & 0x0ff)) } var offset: Int = (pBuffer(772) & 0x0ff) + (pBuffer(773) & 0x0ff) + (pBuffer(774) & 0x0ff) + (pBuffer(775) & 0x0ff) offset = offset % 728 offset = offset + 776 if (offset + Constants.DIGEST_LENGTH >= 1536) { log.error("Invalid digest offset") } offset } }
agpl-3.0
SYNHAK/spiff
client/html/app/js/ui/controllers/epicenter.js
3668
angular.module('spiff.epicenter', [ 'spiff', 'spaceapi', 'messages' ]) .controller('ChangePassCtrl', function($scope, $modalInstance, Spiff, SpiffRestangular, Messages) { $scope.d = {}; $scope.requestReset = function() { SpiffRestangular.one('member', Spiff.currentUser.id).patch({'currentPassword': $scope.d.current, 'password': $scope.d.new}); Messages.info("Password changed."); } }) .controller('ResetPassCtrl', function($scope, Spiff, $modalInstance, SpiffRestangular, Messages) { $scope.d = {}; $scope.state = 0; $scope.requestReset = function() { if ($scope.state == 0) { SpiffRestangular.all('member').requestPasswordReset({'userid': $scope.d.userid}).then(function() { $scope.state++; }); } else if ($scope.state == 1) { Spiff.login($scope.d.userid, $scope.d.code).then(function(user) { $scope.state++; }); } else if ($scope.state == 2) { SpiffRestangular.one('member', Spiff.currentUser.id).patch({'currentPassword': $scope.d.code, 'password': $scope.d.newPass}).then(function() { Messages.info("Password updated."); $modalInstance.close(); }); } }; }) .controller('LoginCtrl', function($scope, $modalInstance, Spiff, resetFunc) { $scope.d = {}; $scope.login = function() { var username = $scope.d.username; var password = $scope.d.password; Spiff.login(username, password).then(function(user) { if (user.status >= 300 || user.status < 200) { if (user.status == 401) { $scope.error = "Incorrect username or password"; } } else { $scope.error = null; $modalInstance.close() } }); $scope.showPasswordReset = function() { $modalInstance.close(); resetFunc(); }; }; }) .controller('EpicenterCtrl', function($scope, Spiff, $modal, SpaceAPI) { $scope.Spiff = Spiff; var loginIsOpen = false; $scope.showLogin = function() { console.log("Login is opened: "+loginIsOpen); if (!loginIsOpen) { loginIsOpen = true; $modal.open({ templateUrl: 'partials/login.html', controller: 'LoginCtrl', resolve: {resetFunc: function() {return $scope.showPasswordReset;}} }).result.then(function() { console.log("Finished login"); loginIsOpen = false; }); } }; $scope.showPasswordReset = function() { $modal.open({ templateUrl: 'partials/reset-password.html', controller: 'ResetPassCtrl', }).result.then(function() { }); }; $scope.changePassword = function() { $modal.open({ templateUrl: 'partials/change-password.html', controller: 'ChangePassCtrl', }).result.then(function() { }); }; $scope.enterAdmin = function() { $modal.open({ templateUrl: 'partials/open-admin.html', controller: function($scope, $modalInstance) { $scope.close = function() {$modalInstance.close();} } }); }; $scope.logout = function() { Spiff.logout(); }; $scope.$on('showLogin', function() { $scope.showLogin(); }); Spiff.$on('loginRequired', function(element, response) { $scope.showLogin(); }); Spiff.$on('error', function(element, response) { $modal.open({ templateUrl: 'error.html', controller: function($scope, $modalInstance) { $scope.status = response.status; $scope.message = response.data.error_message; $scope.traceback = response.data.traceback; $scope.close = function() { $modalInstance.close(); } } }); }); SpaceAPI.ready(function(api) { $scope.spaceAPI = api.data; }); });
agpl-3.0
jl777/OTExtension
ot/iknp-ot-ext-rec.cpp
4417
/* * iknp-ot-ext-receiver.cpp * * Created on: Mar 4, 2015 * Author: mzohner */ #include "iknp-ot-ext-rec.h" BOOL IKNPOTExtRec::receiver_routine(uint32_t id, uint64_t myNumOTs) { uint64_t myStartPos = id * myNumOTs; uint64_t wd_size_bits = m_nBlockSizeBits; myNumOTs = min(myNumOTs + myStartPos, m_nOTs) - myStartPos; uint64_t lim = myStartPos + myNumOTs; uint64_t processedOTBlocks = min((uint64_t) NUMOTBLOCKS, ceil_divide(myNumOTs, wd_size_bits)); uint64_t OTsPerIteration = processedOTBlocks * wd_size_bits; uint64_t OTwindow = NUMOTBLOCKS * wd_size_bits; uint64_t** rndmat; channel* chan = new channel(id, m_cRcvThread, m_cSndThread); //counter variables uint64_t numblocks = ceil_divide(myNumOTs, OTsPerIteration); // A temporary part of the T matrix CBitVector T(wd_size_bits * OTsPerIteration); // The send buffer #ifdef GENERATE_T_EXPLICITELY CBitVector vSnd(m_nBaseOTs * OTsPerIteration * 2); #else CBitVector vSnd(m_nBaseOTs * OTsPerIteration); #endif // A temporary buffer that stores the resulting seeds from the hash buffer //TODO: Check for some maximum size CBitVector seedbuf(OTwindow * m_cCrypt->get_aes_key_bytes() * 8); uint64_t otid = myStartPos; queue<mask_block> mask_queue; CBitVector maskbuf; maskbuf.Create(m_nBitLength * OTwindow); if(m_eSndOTFlav == Snd_GC_OT) { uint8_t* rnd_seed = chan->blocking_receive(); initRndMatrix(&rndmat, m_nBitLength, m_nBaseOTs); fillRndMatrix(rnd_seed, rndmat, m_nBitLength, m_nBaseOTs, m_cCrypt); free(rnd_seed); } #ifdef OTTiming double totalMtxTime = 0, totalTnsTime = 0, totalHshTime = 0, totalRcvTime = 0, totalSndTime = 0, totalChkTime = 0, totalMaskTime = 0; timeval tempStart, tempEnd; #endif while (otid < lim) { processedOTBlocks = min((uint64_t) NUMOTBLOCKS, ceil_divide(lim - otid, wd_size_bits)); OTsPerIteration = processedOTBlocks * wd_size_bits; //nSize = bits_in_bytes(m_nBaseOTs * OTsPerIteration); #ifdef OTTiming gettimeofday(&tempStart, NULL); #endif BuildMatrices(T, vSnd, otid, processedOTBlocks); #ifdef OTTiming gettimeofday(&tempEnd, NULL); totalMtxTime += getMillies(tempStart, tempEnd); gettimeofday(&tempStart, NULL); #endif MaskBaseOTs(T, vSnd, otid, processedOTBlocks); #ifdef OTTiming gettimeofday(&tempEnd, NULL); totalMaskTime += getMillies(tempStart, tempEnd); gettimeofday(&tempStart, NULL); #endif T.Transpose(wd_size_bits, OTsPerIteration); #ifdef OTTiming gettimeofday(&tempEnd, NULL); totalTnsTime += getMillies(tempStart, tempEnd); gettimeofday(&tempStart, NULL); #endif HashValues(T, seedbuf, maskbuf, otid, min(lim - otid, OTsPerIteration), rndmat); #ifdef OTTiming gettimeofday(&tempEnd, NULL); totalHshTime += getMillies(tempStart, tempEnd); gettimeofday(&tempStart, NULL); #endif SendMasks(vSnd, chan, otid, OTsPerIteration); #ifdef OTTiming gettimeofday(&tempEnd, NULL); totalSndTime += getMillies(tempStart, tempEnd); gettimeofday(&tempStart, NULL); #endif SetOutput(maskbuf, otid, OTsPerIteration, &mask_queue, chan);//ReceiveAndUnMask(chan); //counter += min(lim - OT_ptr, OTsPerIteration); otid += min(lim - otid, OTsPerIteration); #ifdef OTTiming gettimeofday(&tempEnd, NULL); totalRcvTime += getMillies(tempStart, tempEnd); #endif vSnd.Reset(); T.Reset(); } //sndthread->signal_end(id); if(m_eSndOTFlav != Snd_R_OT && m_eSndOTFlav != Snd_GC_OT) { //finevent->Wait(); while(chan->is_alive()) ReceiveAndUnMask(chan, &mask_queue); } chan->synchronize_end(); T.delCBitVector(); vSnd.delCBitVector(); seedbuf.delCBitVector(); maskbuf.delCBitVector(); if(m_eSndOTFlav==Snd_GC_OT) freeRndMatrix(rndmat, m_nBaseOTs); #ifdef OTTiming cout << "Receiver time benchmark for performing " << myNumOTs << " OTs on " << m_nBitLength << " bit strings" << endl; cout << "Time needed for: " << endl; cout << "\t Matrix Generation:\t" << totalMtxTime << " ms" << endl; cout << "\t Base OT Masking:\t" << totalMaskTime << " ms" << endl; cout << "\t Sending Matrix:\t" << totalSndTime << " ms" << endl; cout << "\t Transposing Matrix:\t" << totalTnsTime << " ms" << endl; cout << "\t Hashing Matrix:\t" << totalHshTime << " ms" << endl; cout << "\t Receiving Values:\t" << totalRcvTime << " ms" << endl; #endif return TRUE; } void IKNPOTExtRec::ComputeBaseOTs(field_type ftype) { m_cBaseOT = new NaorPinkas(m_cCrypt, ftype); ComputePKBaseOTs(); delete m_cBaseOT; }
agpl-3.0
PairMhai/Backend
comment/urls.py
147
from django.conf.urls import url from comment.views import * urlpatterns = [ url(r'^$', CommentListAndCreateView.as_view(), name="comment") ]
agpl-3.0
slashattack89/oc_filesmv
l10n/cs_CZ.php
595
<?php $TRANSLATIONS = array( "No filesystem found" => "Souborový systém nenalezen", "No data supplied." => "Nebyla dodána žádná data.", "Src and Dest are not allowed to be the same location!" => "Src a Dest nelze cílit do stejného umístění!", "Could not move %s - File with this name already exists" => "Nelze přesunout %s - již existuje soubor se stejným názvem", "Could not move %s" => "Nelze přesunout %s", "Move" => "Přesunout", "Copy" => "Kopie", "Destination directory" => "Cílový adresář" ); $PLURAL_FORMS = "nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;";
agpl-3.0
Tatwi/legend-of-hondo
MMOCoreORB/bin/scripts/commands/sniperShot.lua
2431
--Copyright (C) 2007 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. --true = 1, false = 0 SniperShotCommand = { name = "snipershot", minDamage = 200, speed = 1.0, healthCostMultiplier = 0.5, actionCostMultiplier = 0.5, mindCostMultiplier = 2.0, accuracyBonus = 5, poolsToDamage = RANDOM_ATTRIBUTE, animation = "fire_1_special_single", animType = GENERATE_RANGED, combatSpam = "snipershot", weaponType = RIFLEWEAPON, range = -1 } AddCommand(SniperShotCommand)
agpl-3.0
NicolasEYSSERIC/Silverpeas-Core
web-core/src/main/java/com/silverpeas/web/mappers/EntityNotFoundExceptionMapper.java
1964
/* * Copyright (C) 2000 - 2012 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 withWriter Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.web.mappers; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityNotFoundException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; /** * Implementation of ExceptionMapper to send down a "404 Not Found" in the event unparsable JSON is * received. */ @Provider public class EntityNotFoundExceptionMapper implements ExceptionMapper<EntityNotFoundException> { @Override public Response toResponse(EntityNotFoundException exception) { Logger.getLogger(EntityNotFoundExceptionMapper.class.getSimpleName()).log(Level.INFO, exception.getMessage(), exception); return Response.status(Response.Status.NOT_FOUND).entity("The asked resource isn't found").build(); } }
agpl-3.0
opencadc/core
cadc-util/src/main/java/ca/nrc/cadc/net/RangeNotSatisfiableException.java
4444
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2020. (c) 2020. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * ************************************************************************ */ package ca.nrc.cadc.net; /** * Exception to convey that the received content did not meet the * length provided by the client. * * @author adriand */ public class RangeNotSatisfiableException extends RuntimeException { public RangeNotSatisfiableException(String message) { super(message); } public RangeNotSatisfiableException(String message, Throwable cause) { super(message, cause); } }
agpl-3.0
uniteddiversity/mycollab
mycollab-config/src/main/java/com/esofthead/mycollab/configuration/Storage.java
3986
/** * This file is part of mycollab-config. * * mycollab-config 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-config 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-config. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.configuration; import com.esofthead.mycollab.core.MyCollabException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * File configuration for storage file in MyCollab. We support two kinds of file * system: * <ul> * <li>S3 mode: Files are stored in Amazon S3. This is used for MyCollab cloud * service.</li> * <li>File system: Files are stored in OS file storage. This is used for * installation mode of MyCollab</li> * </ul> * * @author MyCollab Ltd. * @since 1.0 */ public abstract class Storage { private static Logger LOG = LoggerFactory.getLogger(Storage.class); private static final String S3_CONF_CLS = "com.esofthead.mycollab.ondemand.configuration.S3Storage"; public static final String FILE_STORAGE_SYSTEM = "file"; public static final String S3_STORAGE_SYSTEM = "s3"; private static Storage instance; static { // Load storage configuration String storageSystem = ApplicationProperties.getString(ApplicationProperties.STORAGE_SYSTEM, Storage.FILE_STORAGE_SYSTEM); if (Storage.FILE_STORAGE_SYSTEM.equals(storageSystem)) { instance = new FileStorage(); } else if (Storage.S3_STORAGE_SYSTEM.equals(storageSystem)) { try { Class<Storage> s3Conf = (Class<Storage>) Class.forName(S3_CONF_CLS); instance = s3Conf.newInstance(); } catch (Exception e) { LOG.error(String.format("Can not load s3 file system with class %s", S3_CONF_CLS), e); System.exit(-1); } } else { throw new MyCollabException(String.format("Can not load storage %s", storageSystem)); } } public static Storage getInstance() { return instance; } public static String getResourcePath(String documentPath) { return SiteConfiguration.getResourceDownloadUrl() + documentPath; } public static String getLogoPath(Integer accountId, String logoName, int size) { if (logoName == null || "".equals(logoName)) { return MyCollabAssets.newAssetLink("icons/logo.png"); } return String.format("%s%d/.assets/%s_%d.png", SiteConfiguration.getResourceDownloadUrl(), accountId, logoName, size); } public static String getFavIconPath(Integer sAccountId, String favIconName) { if (favIconName == null || "".equals(favIconName)) { return MyCollabAssets.newAssetLink("favicon.ico"); } return String.format("%s%d/.assets/%s.ico", SiteConfiguration.getResourceDownloadUrl(), sAccountId, favIconName); } public static String getAvatarPath(String userAvatarId, int size) { if (StringUtils.isBlank(userAvatarId)) { return MyCollabAssets.newAssetLink(String.format("icons/default_user_avatar_%d.png", size)); } else { return String.format("%savatar/%s_%d.png", SiteConfiguration.getResourceDownloadUrl(), userAvatarId, size); } } public static boolean isFileStorage() { return (instance instanceof FileStorage); } public static boolean isS3Storage() { return !isFileStorage(); } }
agpl-3.0
BarcodeBucket/barcodebucket.com
web/legacy.php
159
<?php $app = require_once __DIR__.'/../src/app.php'; require_once __DIR__.'/../config/prod.php'; require_once __DIR__.'/../src/controllers.php'; $app->run();
agpl-3.0
ShroudComputing/shroud
lib/classes/model.js
924
'use strict'; const Document = require('camo').Document; const Attribute = require.main.require('./classes/attribute.js'); exports = module.exports = (function () { const attributes = {}; class Model extends Document { constructor() { super(); if (this.constructor === Model) { throw new Error('Can\'t instantiate Model directly'); } const self = this; const name = this.constructor.name; Object.keys(attributes[name]).forEach(function(key) { self[key] = attributes[name][key]; }); } static attribute(name, attribute) { // @todo: Optimize the mapping of attributes? if (!attributes[this.name]) { attributes[this.name] = {}; } if (attribute.prototype instanceof Attribute) { attribute = [attribute]; } attributes[this.name][name] = attribute; return this; } } return Model; }());
agpl-3.0
diqube/diqube
diqube-plan/src/main/java/org/diqube/plan/planner/WireManager.java
1086
/** * diqube: Distributed Query Base. * * Copyright (C) 2015 Bastian Gloeckle * * This file is part of diqube. * * diqube is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.diqube.plan.planner; import org.diqube.execution.consumers.GenericConsumer; /** * Wires outputs of steps to inputs of other steps. * * @author Bastian Gloeckle */ public interface WireManager<T> { public void wire(Class<? extends GenericConsumer> type, T sourceStep, T destStep); }
agpl-3.0
isard-vdi/isard
frontend/src/shared/constants.js
1313
export const apiV3Segment = '/api/v3' export const apiWebSockets = '/api/v3/socket.io' export const apiAdminSegment = '/isard-admin' export const authenticationSegment = '/authentication' export const appTitle = 'IsardVDI' export const cardIcons = { default: ['fas', 'desktop'], windows: ['fab', 'windows'], ubuntu: ['fab', 'ubuntu'], fedora: ['fab', 'fedora'], linux: ['fab', 'linux'], centos: ['fab', 'centos'] } export const desktopStates = { not_created: 'notCreated', failed: 'failed', started: 'started', stopped: 'stopped', waitingip: 'waitingip', working: 'working', 'shutting-down': 'shutting-down', downloading: 'downloading' } export const status = { notCreated: { icon: ['fas', 'play'], variant: 'success' }, started: { action: 'stop', icon: 'stop', variant: 'danger' }, waitingip: { action: 'stop', icon: 'stop', variant: 'danger' }, stopped: { action: 'start', icon: 'play', variant: 'success' }, failed: { action: 'start', icon: 'play' }, 'shutting-down': { action: '', icon: '' }, working: { action: '', icon: '' }, downloading: { action: '', icon: '' } } export const localClientInstructionsUrl = 'https://isard.gitlab.io/isardvdi-docs/user/local-client/'
agpl-3.0
al3x/ground-control
src/frontend/components/AdminCallAssignmentCreationForm.js
3485
import React from 'react'; import Relay from 'react-relay'; import {BernieColors, BernieText} from './styles/bernie-css' import {Paper} from 'material-ui'; import GCForm from './forms/GCForm'; import Form from 'react-formal'; import CreateCallAssignment from '../mutations/CreateCallAssignment'; import yup from 'yup'; import MutationHandler from './MutationHandler'; export default class AdminCallAssignmentCreationForm extends React.Component { surveyRenderers = { 'BSDSurvey' : 'Simple BSD survey renderer', 'BSDPhonebankRSVPSurvey' : 'BSD survey + events', } surveyProcessors = { 'bsd-event-rsvper' : 'Create event RSVPs' } styles = { formContainer: { width: 280, paddingLeft: 15, paddingRight: 15, paddingTop: 15, paddingBottom: 15, marginTop: 15, border: 'solid 1px ' + BernieColors.lightGray } } formSchema = yup.object({ surveyId: yup.number().required(), intervieweeGroup: yup.string().required(), name: yup.string().required(), instructions: yup.string(), renderer: yup.string().required(), processors: yup.array().of(yup.string()).required() }) render() { return ( <div> <MutationHandler ref='mutationHandler' successMessage='Call assignment created!' mutationClass={CreateCallAssignment} /> <div style={BernieText.title}> Create Assignment </div> <div> Create a new phonebanking assignment. Before you fill out this form, make sure you've set up the correct objects in BSD. </div> <Paper zDepth={0} style={this.styles.formContainer}> <GCForm schema={this.formSchema} onSubmit={(formValue) => { this.refs.mutationHandler.send({ listContainer: this.props.listContainer, ...formValue }) }} > <Form.Field name='name' label='Name' /> <br /> <Form.Field name='instructions' multiLine={true} rows={5} label="Instructions" hintText="(Optional) Enter HTML or plain text instructions for this call assignment." /><br /> <Form.Field name='surveyId' label='BSD signup form ID' /><br /> <Form.Field name='intervieweeGroup' multiLine={true} rows={5} label="Interviewee group" hintText="Enter a SQL query, BSD cons_group_id, or the word 'everyone'" /><br /> <Form.Field name='renderer' type='select' choices={this.surveyRenderers} label='How to render the survey?' style={{ width: '100%' }} /><br /> <Form.Field name='processors' choices={this.surveyProcessors} label='Post-submit survey processors' /><br /> <Form.Button type='submit' label='Create!' fullWidth={true} /> </GCForm> </Paper> </div> ) } } export default Relay.createContainer(AdminCallAssignmentCreationForm, { fragments: { listContainer: () => Relay.QL` fragment on ListContainer { ${CreateCallAssignment.getFragment('listContainer')}, } ` }, });
agpl-3.0
jmesteve/openerp
openerp/addons/account_balance_reporting/account_balance_reporting_report.py
21960
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP - Account balance reporting engine # Copyright (C) 2009 Pexego Sistemas Informáticos. All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## """ Account balance report objects Generic account balance report document (with header and detail lines). Designed following the needs of the Spanish/Spain localization. """ from openerp.osv import orm,fields from openerp.tools.translate import _ import re import time import netsvc import logging # CSS classes for the account line templates CSS_CLASSES = [('default','Default'),('l1', 'Level 1'), ('l2', 'Level 2'), ('l3', 'Level 3'), ('l4', 'Level 4'), ('l5', 'Level 5')] class account_balance_reporting(orm.Model): """ Account balance report. It stores the configuration/header fields of an account balance report, and the linked lines of detail with the values of the accounting concepts (values generated from the selected template lines of detail formulas). """ _name = "account.balance.reporting" _columns = { 'name': fields.char('Name', size=64, required=True, select=True), 'template_id': fields.many2one('account.balance.reporting.template', 'Template', ondelete='set null', required=True, select=True, states={'calc_done': [('readonly', True)], 'done': [('readonly', True)]}), 'calc_date': fields.datetime("Calculation date", readonly=True), 'state': fields.selection([('draft','Draft'), ('calc','Processing'), ('calc_done','Processed'), ('done','Done'), ('canceled','Canceled')], 'State'), 'company_id': fields.many2one('res.company', 'Company', ondelete='cascade', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'current_fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal year 1', select=True, required=True, states={'calc_done': [('readonly', True)], 'done': [('readonly', True)]}), 'current_period_ids': fields.many2many('account.period', 'account_balance_reporting_account_period_current_rel', 'account_balance_reporting_id', 'period_id', 'Fiscal year 1 periods', states={'calc_done': [('readonly', True)], 'done': [('readonly', True)]}), 'previous_fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal year 2', select=True, states={'calc_done': [('readonly', True)], 'done': [('readonly', True)]}), 'previous_period_ids': fields.many2many('account.period', 'account_balance_reporting_account_period_previous_rel', 'account_balance_reporting_id', 'period_id', 'Fiscal year 2 periods', states={'calc_done': [('readonly', True)], 'done': [('readonly', True)]}), 'line_ids': fields.one2many('account.balance.reporting.line', 'report_id', 'Lines', states = {'done': [('readonly', True)]}), } _defaults = { 'company_id': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context).company_id.id, 'state': 'draft', } def action_calculate(self, cr, uid, ids, context=None): """Called when the user presses the Calculate button. It will use the report template to generate lines of detail for the report with calculated values.""" if context is None: context = {} line_obj = self.pool.get('account.balance.reporting.line') # Set the state to 'calculating' self.write(cr, uid, ids, { 'state': 'calc', 'calc_date': time.strftime('%Y-%m-%d %H:%M:%S') }) for report in self.browse(cr, uid, ids, context=context): # Clear the report data (unlink the lines of detail) line_obj.unlink(cr, uid, [line.id for line in report.line_ids], context=context) # Fill the report with a 'copy' of the lines of its template (if it has one) if report.template_id: for template_line in report.template_id.line_ids: line_obj.create(cr, uid, { 'code': template_line.code, 'name': template_line.name, 'report_id': report.id, 'template_line_id': template_line.id, 'parent_id': None, 'current_value': None, 'previous_value': None, 'sequence': template_line.sequence, 'css_class': template_line.css_class, }, context=context) # Set the parents of the lines in the report # Note: We reload the reports objects to refresh the lines of detail. for report in self.browse(cr, uid, ids, context=context): if report.template_id: # Set line parents (now that they have been created) for line in report.line_ids: tmpl_line = line.template_line_id if tmpl_line and tmpl_line.parent_id: parent_line_ids = line_obj.search(cr, uid, [('report_id', '=', report.id), ('code', '=', tmpl_line.parent_id.code)]) line_obj.write(cr, uid, line.id, { 'parent_id': (parent_line_ids and parent_line_ids[0] or False), }, context=context) # Calculate the values of the lines # Note: We reload the reports objects to refresh the lines of detail. for report in self.browse(cr, uid, ids, context=context): if report.template_id: # Refresh the report's lines values for line in report.line_ids: line.refresh_values() # Set the report as calculated self.write(cr, uid, [report.id], { 'state': 'calc_done' }, context=context) else: # Ouch! no template: Going back to draft state. self.write(cr, uid, [report.id], {'state': 'draft'}, context=context) return True def action_confirm(self, cr, uid, ids, context=None): """Called when the user clicks the confirm button.""" self.write(cr, uid, ids, {'state': 'done'}, context=context) return True def action_cancel(self, cr, uid, ids, context=None): """Called when the user clicks the cancel button.""" self.write(cr, uid, ids, {'state': 'canceled'}, context=context) return True def action_recover(self, cr, uid, ids, context=None): """Called when the user clicks the draft button to create a new workflow instance.""" self.write(cr, uid, ids, {'state': 'draft', 'calc_date': None}, context=context) wf_service = netsvc.LocalService("workflow") for id in ids: wf_service.trg_create(uid, 'account.balance.reporting', id, cr) return True def calculate_action(self, cr, uid, ids, context=None): """Calculate the selected balance report data.""" for id in ids: # Send the calculate signal to the balance report to trigger # action_calculate. wf_service = netsvc.LocalService('workflow') wf_service.trg_validate(uid, 'account.balance.reporting', id, 'calculate', cr) return 'close' class account_balance_reporting_line(orm.Model): """ Account balance report line / Accounting concept One line of detail of the balance report representing an accounting concept with its values. The accounting concepts follow a parent-children hierarchy. Its values (current and previous) are calculated based on the 'value' formula of the linked template line. """ _name = "account.balance.reporting.line" _columns = { 'report_id': fields.many2one('account.balance.reporting', 'Report', ondelete='cascade'), 'sequence': fields.integer('Sequence', required=True), 'code': fields.char('Code', size=64, required=True, select=True), 'name': fields.char('Name', size=256, required=True, select=True), 'notes': fields.text('Notes'), 'current_value': fields.float('Fiscal year 1', digits=(16,2)), 'previous_value': fields.float('Fiscal year 2', digits=(16,2)), 'calc_date': fields.datetime("Calculation date"), 'css_class': fields.selection(CSS_CLASSES, 'CSS Class'), 'template_line_id': fields.many2one( 'account.balance.reporting.template.line', 'Line template', ondelete='set null'), 'parent_id': fields.many2one('account.balance.reporting.line', 'Parent', ondelete='cascade'), 'child_ids': fields.one2many('account.balance.reporting.line', 'parent_id', 'Children'), } _defaults = { 'report_id': lambda self, cr, uid, context: context.get('report_id', None), 'css_class': 'default', } _order = "sequence, code" _sql_constraints = [ ('report_code_uniq', 'unique(report_id, code)', _("The code must be unique for this report!")) ] def name_get(self, cr, uid, ids, context=None): """Redefine the method to show the code in the name ("[code] name").""" res = [] for item in self.browse(cr, uid, ids, context=context): res.append((item.id, "[%s] %s" % (item.code, item.name))) return res def name_search(self, cr, uid, name, args=[], operator='ilike', context=None, limit=80): """Redefine the method to allow searching by code.""" ids = [] if name: ids = self.search(cr, uid, [('code','ilike',name)]+ args, limit=limit, context=context) if not ids: ids = self.search(cr, uid, [('name',operator,name)]+ args, limit=limit, context=context) return self.name_get(cr, uid, ids, context=context) def refresh_values(self, cr, uid, ids, context=None): """ Recalculates the values of this report line using the linked line report values formulas: Depending on this formula the final value is calculated as follows: - Empy report value: sum of (this concept) children values. - Number with decimal point ("10.2"): that value (constant). - Account numbers separated by commas ("430,431,(437)"): Sum of the account balances. (The sign of the balance depends on the balance mode) - Concept codes separated by "+" ("11000+12000"): Sum of those concepts values. """ if context is None: context = {} for line in self.browse(cr, uid, ids, context=context): tmpl_line = line.template_line_id balance_mode = int(tmpl_line.template_id.balance_mode) current_value = 0.0 previous_value = 0.0 report = line.report_id # We use the same code to calculate both fiscal year values, # just iterating over them. for fyear in ('current', 'previous'): value = 0 if fyear == 'current': tmpl_value = tmpl_line.current_value elif fyear == 'previous': tmpl_value = (tmpl_line.previous_value or tmpl_line.current_value) # Remove characters after a ";" (we use ; for comments) if tmpl_value: tmpl_value = tmpl_value.split(';')[0] if (fyear == 'current' and not report.current_fiscalyear_id) \ or (fyear == 'previous' and not report.previous_fiscalyear_id): value = 0 else: if not tmpl_value: # Empy template value => sum of the children values for child in line.child_ids: if child.calc_date != child.report_id.calc_date: # Tell the child to refresh its values child.refresh_values() # Reload the child data child = self.browse(cr, uid, child.id, context=context) if fyear == 'current': value += child.current_value elif fyear == 'previous': value += child.previous_value elif re.match(r'^\-?[0-9]*\.[0-9]*$', tmpl_value): # Number with decimal points => that number value # (constant). value = float(tmpl_value) elif re.match(r'^[0-9a-zA-Z,\(\)\*_\ ]*$', tmpl_value): # Account numbers separated by commas => sum of the # account balances. We will use the context to filter # the accounts by fiscalyear and periods. ctx = context.copy() if fyear == 'current': ctx.update({ 'fiscalyear': report.current_fiscalyear_id.id, 'periods': [p.id for p in report.current_period_ids], }) elif fyear == 'previous': ctx.update({ 'fiscalyear': report.previous_fiscalyear_id.id, 'periods': [p.id for p in report.previous_period_ids], }) value = line._get_account_balance(tmpl_value, balance_mode, ctx) elif re.match(r'^[\+\-0-9a-zA-Z_\*\ ]*$', tmpl_value): # Account concept codes separated by "+" => sum of the # concepts (template lines) values. for line_code in re.findall(r'(-?\(?[0-9a-zA-Z_]*\)?)', tmpl_value): sign = 1 if line_code.startswith('-') or \ (line_code.startswith('(') and balance_mode in (2, 4)): sign = -1 line_code = line_code.strip('-()*') # findall might return empty strings if line_code: # Search for the line (perfect match) line_ids = self.search(cr, uid, [ ('report_id','=', report.id), ('code', '=', line_code), ], context=context) for child in self.browse(cr, uid, line_ids, context=context): if child.calc_date != child.report_id.calc_date: child.refresh_values() # Reload the child data child = self.browse(cr, uid, child.id, context=context) if fyear == 'current': value += child.current_value * sign elif fyear == 'previous': value += child.previous_value * sign # Negate the value if needed if tmpl_line.negate: value = -value if fyear == 'current': current_value = value elif fyear == 'previous': previous_value = value # Write the values self.write(cr, uid, line.id, { 'current_value': current_value, 'previous_value': previous_value, 'calc_date': line.report_id.calc_date, }, context=context) return True def _get_account_balance(self, cr, uid, ids, code, balance_mode=0, context=None): """ It returns the (debit, credit, balance*) tuple for a account with the given code, or the sum of those values for a set of accounts when the code is in the form "400,300,(323)" Depending on the balance_mode, the balance is calculated as follows: Mode 0: debit-credit for all accounts (default); Mode 1: debit-credit, credit-debit for accounts in brackets; Mode 2: credit-debit for all accounts; Mode 3: credit-debit, debit-credit for accounts in brackets. Also the user may specify to use only the debit or credit of the account instead of the balance writing "debit(551)" or "credit(551)". """ acc_obj = self.pool.get('account.account') logger = logging.getLogger(__name__) res = 0.0 line = self.browse(cr, uid, ids[0], context=context) company_id = line.report_id.company_id.id # We iterate over the accounts listed in "code", so code can be # a string like "430+431+432-438"; accounts split by "+" will be added, # accounts split by "-" will be substracted. for acc_code in re.findall('(-?\w*\(?[0-9a-zA-Z_]*\)?)', code): # Check if the code is valid (findall might return empty strings) acc_code = acc_code.strip() if acc_code: # Check the sign of the code (substraction) if acc_code.startswith('-'): sign = -1 acc_code = acc_code[1:].strip() # Strip the sign else: sign = 1 if re.match(r'^debit\(.*\)$', acc_code): # Use debit instead of balance mode = 'debit' acc_code = acc_code[6:-1] # Strip debit() elif re.match(r'^credit\(.*\)$', acc_code): # Use credit instead of balance mode = 'credit' acc_code = acc_code[7:-1] # Strip credit() else: mode = 'balance' # Calculate sign of the balance mode sign_mode = 1 if balance_mode in (1, 2, 3): # for accounts in brackets or mode 2, the sign is reversed if (acc_code.startswith('(') and acc_code.endswith(')')) \ or balance_mode == 2: sign_mode = -1 # Strip the brackets (if any) if acc_code.startswith('(') and acc_code.endswith(')'): acc_code = acc_code[1:-1] # Search for the account (perfect match) account_ids = acc_obj.search(cr, uid, [ ('code', '=', acc_code), ('company_id','=', company_id) ], context=context) if not account_ids: # Search for a subaccount ending with '0' account_ids = acc_obj.search(cr, uid, [ ('code', '=like', '%s%%0' % acc_code), ('company_id','=', company_id) ], context=context) if not account_ids: logger.warning("Account with code '%s' not found!" %acc_code) for account in acc_obj.browse(cr, uid, account_ids, context=context): if mode == 'debit': res += account.debit * sign elif mode == 'credit': res += account.credit * sign else: res += account.balance * sign * sign_mode return res
agpl-3.0
ojs/WorkflowBundle
VipaWorkflowBundle.php
132
<?php namespace Vipa\WorkflowBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class VipaWorkflowBundle extends Bundle { }
agpl-3.0
lmaslag/test
engine/Library/Zend/Validate/File/Sha1.php
5087
<?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 [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Validate * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Validate_File_Hash */ require_once 'Zend/Validate/File/Hash.php'; /** * Validator for the sha1 hash of given files * * @category Zend * @package Zend_Validate * @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_Validate_File_Sha1 extends Zend_Validate_File_Hash { /** * @const string Error constants */ const DOES_NOT_MATCH = 'fileSha1DoesNotMatch'; const NOT_DETECTED = 'fileSha1NotDetected'; const NOT_FOUND = 'fileSha1NotFound'; /** * @var array Error message templates */ protected $_messageTemplates = array( self::DOES_NOT_MATCH => "File '%value%' does not match the given sha1 hashes", self::NOT_DETECTED => "A sha1 hash could not be evaluated for the given file", self::NOT_FOUND => "File '%value%' is not readable or does not exist", ); /** * Hash of the file * * @var string */ protected $_hash; /** * Sets validator options * * $hash is the hash we accept for the file $file * * @param string|array $options * @return void */ public function __construct($options) { if ($options instanceof Zend_Config) { $options = $options->toArray(); } elseif (is_scalar($options)) { $options = array('hash1' => $options); } elseif (!is_array($options)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Invalid options to validator provided'); } $this->setHash($options); } /** * Returns all set sha1 hashes * * @return array */ public function getSha1() { return $this->getHash(); } /** * Sets the sha1 hash for one or multiple files * * @param string|array $options * @return Zend_Validate_File_Hash Provides a fluent interface */ public function setHash($options) { if (!is_array($options)) { $options = (array) $options; } $options['algorithm'] = 'sha1'; parent::setHash($options); return $this; } /** * Sets the sha1 hash for one or multiple files * * @param string|array $options * @return Zend_Validate_File_Hash Provides a fluent interface */ public function setSha1($options) { $this->setHash($options); return $this; } /** * Adds the sha1 hash for one or multiple files * * @param string|array $options * @return Zend_Validate_File_Hash Provides a fluent interface */ public function addHash($options) { if (!is_array($options)) { $options = (array) $options; } $options['algorithm'] = 'sha1'; parent::addHash($options); return $this; } /** * Adds the sha1 hash for one or multiple files * * @param string|array $options * @return Zend_Validate_File_Hash Provides a fluent interface */ public function addSha1($options) { $this->addHash($options); return $this; } /** * Defined by Zend_Validate_Interface * * Returns true if and only if the given file confirms the set hash * * @param string $value Filename to check for hash * @param array $file File data from Zend_File_Transfer * @return boolean */ public function isValid($value, $file = null) { // Is file readable ? require_once 'Zend/Loader.php'; if (!Zend_Loader::isReadable($value)) { return $this->_throw($file, self::NOT_FOUND); } $hashes = array_unique(array_keys($this->_hash)); $filehash = hash_file('sha1', $value); if ($filehash === false) { return $this->_throw($file, self::NOT_DETECTED); } foreach ($hashes as $hash) { if ($filehash === $hash) { return true; } } return $this->_throw($file, self::DOES_NOT_MATCH); } }
agpl-3.0
Illarion-eV/Illarion-Content
item/signpost.lua
1189
--[[ Illarion Server 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/>. ]] -- Wegweiserskript -- Nitram local lookat = require("base.lookat") local oldSlimeFeeding = require("content.oldSlimeFeeding") local M = {} -- UPDATE items SET itm_script='item.signpost' WHERE itm_id IN (1817,1809,1808,1807,308,1804,586,3084,3081,3082,3083,519,520,521,337,1914,1915,2046,2069,512,2924,2925,2926,2927); function M.LookAtItem(User, Item) if Item:getData("oldSlimeFeeding") == "true" then oldSlimeFeeding.setSignText(Item) end return lookat.GenerateLookAt(User, Item, lookat.NONE) end return M
agpl-3.0
yamcs/yamcs
yamcs-core/src/test/java/org/yamcs/parameterarchive/RealtimeArchiveFillerTest.java
13822
package org.yamcs.parameterarchive; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.rocksdb.RocksDBException; import org.yamcs.ConfigurationException; import org.yamcs.Processor; import org.yamcs.YConfiguration; import org.yamcs.YamcsServer; import org.yamcs.parameter.BasicParameterValue; import org.yamcs.parameter.ParameterRequestManager; import org.yamcs.parameter.ParameterValue; import org.yamcs.parameterarchive.RealtimeArchiveFiller.SegmentQueue; import org.yamcs.protobuf.Pvalue.AcquisitionStatus; import org.yamcs.utils.TimeEncoding; import org.yamcs.utils.ValueUtility; import org.yaml.snakeyaml.Yaml; /** * Implements unit tests for {@link RealtimeArchiveFiller}. */ public class RealtimeArchiveFillerTest { /** The size of an interval, in milliseconds. (2^23 seconds) */ private static final long INTERVAL_SIZE_MILLIS = 8388608000L; /** The amount of a backward time jump that will trigger a cache flush. */ private static final long PAST_JUMP_THRESHOLD_SECS = 86400; private static final long PAST_JUMP_THRESHOLD_MILLIS = PAST_JUMP_THRESHOLD_SECS * 1000; /** The Yamcs instant at the start of 2021. */ private static final long YEAR_2021_START_INSTANT = 1609472533000L; @Mock private ParameterArchive parameterArchive; @Mock private ParameterIdDb parameterIdDb; @Mock private ParameterGroupIdDb parameterGroupIdDb; @Mock private YamcsServer yamcsServer; @Mock private Processor processor; @Mock private ParameterRequestManager parameterRequestManager; @Before public void setup() { MockitoAnnotations.openMocks(this); when(processor.getParameterRequestManager()).thenReturn(parameterRequestManager); when(parameterArchive.getYamcsInstance()).thenReturn("realtime"); when(parameterArchive.getParameterIdDb()).thenReturn(parameterIdDb); when(parameterArchive.getParameterGroupIdDb()).thenReturn(parameterGroupIdDb); // TimeEncoding is used when logging messages by RealtimeArchiveFiller. TimeEncoding.setUp(); } /** * Tests that when there are no parameter values added to the archiver * that no segments are written. * * @throws InterruptedException if the archiver is interrupted during shutdown * @throws RocksDBException if there is an error writing to RocksDB * @throws IOException if there is an I/O error writing segments */ @Test public void testNoParametersToArchive() throws InterruptedException, RocksDBException, IOException { when(yamcsServer.getProcessor(anyString(), anyString())).thenReturn(processor); RealtimeArchiveFiller filler = getFiller(1000); filler.start(); filler.shutDown(); verify(parameterArchive, never()).writeToArchive(any(PGSegment.class)); } /** * Tests that when no processor is configured the archiver fails to start. */ @Test(expected = ConfigurationException.class) public void testNoProcessor() { RealtimeArchiveFiller filler = getFiller(1000); filler.start(); } /** * Tests that all segments are flushed when the archiver is shut down. In this * case there is a single value archived, which should be in one segment. * * @throws InterruptedException if the archiver is interrupted during shutdown * @throws RocksDBException if there is an error writing to RocksDB * @throws IOException if there is an I/O error writing segments */ @Test public void testFlushOnShutdown() throws InterruptedException, RocksDBException, IOException { when(yamcsServer.getProcessor(anyString(), anyString())).thenReturn(processor); RealtimeArchiveFiller filler = getFiller(1000); filler.start(); List<ParameterValue> values = getValues(0, 0, "/myproject/value"); filler.processParameters(values); filler.shutDown(); verify(parameterArchive, times(1)).writeToArchive(any(PGSegment.class)); } /** * Tests that a new value added older than the <code>pastJumpThreshold</code> * causes a complete cache flush before adding the value. * * @throws InterruptedException if the executor is interrupted while shutting down * @throws IOException if there is an error writing to the archive * @throws RocksDBException if there is an error writing to the database */ @Test public void testFlushBeforeVeryOldValues() throws InterruptedException, RocksDBException, IOException { when(yamcsServer.getProcessor(anyString(), anyString())).thenReturn(processor); RealtimeArchiveFiller filler = getFiller(1000); filler.start(); List<ParameterValue> values = getValues(YEAR_2021_START_INSTANT + PAST_JUMP_THRESHOLD_MILLIS + 1, YEAR_2021_START_INSTANT + PAST_JUMP_THRESHOLD_MILLIS + 1, "/myproject/value"); filler.processParameters(values); values = getValues(YEAR_2021_START_INSTANT, YEAR_2021_START_INSTANT, "/myproject/value"); filler.processParameters(values); // Shut down the executor to make sure the write of the first segment completes. filler.executor.shutdown(); filler.executor.awaitTermination(10, TimeUnit.SECONDS); verify(parameterArchive, times(1)).writeToArchive(any(PGSegment.class)); // And the archiver should now have one segment for the old data. assertEquals(1, filler.getSegments(0, 0, false).size()); } /** * Tests that values older than the sorting threshold are not added. * * @throws InterruptedException if the executor is interrupted while shutting down * @throws IOException if there is an error writing to the archive * @throws RocksDBException if there is an error writing to the database */ @Test public void testIgnoreOldValues() throws InterruptedException, RocksDBException, IOException { when(yamcsServer.getProcessor(anyString(), anyString())).thenReturn(processor); RealtimeArchiveFiller filler = getFiller(1000); filler.start(); List<ParameterValue> values = getValues(5000, 5000, "/myproject/value"); filler.processParameters(values); // Add a value that is older than the last time minues the sorting threshold. values = getValues(3000, 3000, "/myproject/value"); filler.processParameters(values); // Shut down and capture the segment that was written. filler.shutDown(); ArgumentCaptor<PGSegment> segCaptor = ArgumentCaptor.forClass(PGSegment.class); verify(parameterArchive).writeToArchive(segCaptor.capture()); PGSegment seg = segCaptor.getValue(); assertEquals(5000, seg.getSegmentStart()); assertEquals(5000, seg.getSegmentEnd()); } /** * Tests that when adding a new value, if there is a segment from a prior interval * that ends before the new time minus the sorting threshold, that the old segment * is archived. * * @throws InterruptedException if the executor is interrupted while shutting down * @throws IOException if there is an error writing to the archive * @throws RocksDBException if there is an error writing to the database */ @Test public void testPriorIntervalSegmentIsArchived() throws InterruptedException, RocksDBException, IOException { when(yamcsServer.getProcessor(anyString(), anyString())).thenReturn(processor); RealtimeArchiveFiller filler = getFiller(1000); filler.start(); List<ParameterValue> values = getValues(INTERVAL_SIZE_MILLIS+1, INTERVAL_SIZE_MILLIS+1, "/myproject/value"); filler.processParameters(values); // Add a value that is older than the last time minues the sorting threshold. values = getValues(3000, 3000, "/myproject/value"); filler.processParameters(values); // Shut down the executor to make sure the write of the first segment completes. filler.executor.shutdown(); filler.executor.awaitTermination(10, TimeUnit.SECONDS); verify(parameterArchive, times(1)).writeToArchive(any(PGSegment.class)); // And the archiver should now have one segment for the old data. assertEquals(1, filler.getSegments(0, 0, false).size()); } /** * Tests that when adding a new value, a prior segment that ends before the * current time minus the sorting threshold is archived. * * @throws InterruptedException if the executor is interrupted while shutting down * @throws IOException if there is an error writing to the archive * @throws RocksDBException if there is an error writing to the database */ @Test public void testFullIntervalOutsideSortingThresholdIsArchived() throws InterruptedException, RocksDBException, IOException { when(parameterArchive.getMaxSegmentSize()).thenReturn(2); when(yamcsServer.getProcessor(anyString(), anyString())).thenReturn(processor); RealtimeArchiveFiller filler = getFiller(1000); filler.start(); // Add two values to fill up a segment. List<ParameterValue> values = getValues(0, 0, "/myproject/value"); filler.processParameters(values); values = getValues(1, 1, "/myproject/value"); filler.processParameters(values); // Add a new value after the sorting threshold has elapsed. values = getValues(1002, 1002, "/myproject/value"); filler.processParameters(values); // Shut down the executor to make sure the write of the first segment completes. filler.executor.shutdown(); filler.executor.awaitTermination(10, TimeUnit.SECONDS); verify(parameterArchive, times(1)).writeToArchive(any(PGSegment.class)); // And the archiver should now have one segment for the old data. assertEquals(1, filler.getSegments(0, 0, false).size()); } /** * Tests that when the cache is full, a new value cannot be added, but that * all segments are flushed when the archive is shut down. * * @throws InterruptedException if the executor is interrupted while shutting down * @throws IOException if there is an error writing to the archive * @throws RocksDBException if there is an error writing to the database */ @Test public void testAddWhenCacheIsFull() throws InterruptedException, RocksDBException, IOException { when(parameterArchive.getMaxSegmentSize()).thenReturn(2); when(yamcsServer.getProcessor(anyString(), anyString())).thenReturn(processor); RealtimeArchiveFiller filler = getFiller(1000); filler.start(); for (int i=0; i < SegmentQueue.QSIZE - 1; ++i) { // Add two values to fill a segment. List<ParameterValue> values = getValues(2*i, 2*i, "/myproject/value"); filler.processParameters(values); values = getValues(2*i + 1, 2*i + 1, "/myproject/value"); filler.processParameters(values); } // The queue should now be full. Adding another value should fail. assertEquals(SegmentQueue.QSIZE - 1, filler.getSegments(0, 0, false).size()); List<ParameterValue> values = getValues(2*SegmentQueue.QSIZE, 2*SegmentQueue.QSIZE, "/myproject/value"); filler.processParameters(values); assertEquals(SegmentQueue.QSIZE - 1, filler.getSegments(0, 0, false).size()); // Shut down and make sure all segments are flushed. filler.shutDown(); verify(parameterArchive, times(SegmentQueue.QSIZE - 1)).writeToArchive(any(PGSegment.class)); } private RealtimeArchiveFiller getFiller(long sortingThreshold) { String configStr = String.format( "sortingThreshold: %d\n" + "pastJumpThreshold: %d\n", sortingThreshold, PAST_JUMP_THRESHOLD_SECS); YConfiguration config = YConfiguration.wrap(new Yaml().load(configStr)); RealtimeArchiveFiller filler = new RealtimeArchiveFiller(parameterArchive, config); filler.setYamcsServer(yamcsServer); return filler; } private List<ParameterValue> getValues(long genTime, long acqTime, String... names) { List<ParameterValue> values = new ArrayList<>(); for (String name : names) { ParameterValue value = new ParameterValue(name); value.setGenerationTime(genTime); value.setAcquisitionTime(acqTime); value.setAcquisitionStatus(AcquisitionStatus.ACQUIRED); value.setRawSignedInteger(123); value.setEngValue(value.getRawValue()); values.add(value); } return values; } List<BasicParameterValue> getParaList(long time) { ParameterValue pv = new ParameterValue("test1"); pv.setEngValue(ValueUtility.getUint64Value(time)); pv.setGenerationTime(time); return Arrays.asList(pv); } }
agpl-3.0
sintefmath/scene
src/collada/Triangles.cpp
5495
/* Copyright STIFTELSEN SINTEF 2014 * * This file is part of Scene. * * Scene is free software: you can redistribute it and/or modifyit 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. * * Scene 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 the Scene. If not, see <http://www.gnu.org/licenses/>. */ #include <unordered_map> #include <boost/lexical_cast.hpp> #include "scene/Log.hpp" #include "scene/DataBase.hpp" #include "scene/Geometry.hpp" #include "scene/SourceBuffer.hpp" #include "scene/collada/Importer.hpp" #include "scene/collada/Exporter.hpp" namespace Scene { namespace Collada { using std::unordered_map; using std::string; using std::vector; using boost::lexical_cast; /* Note: functionality replaced by parseSimplePrimitives. bool Importer::parseTriangles( Geometry* geometry, const std::unordered_map<std::string,Geometry::VertexInput>& inputs, xmlNodePtr triangles_node ) { Logger log = getLogger( "Scene.XML.Builder.parseTriangles" ); if(!assertNode( triangles_node, "triangles" ) ) { return false; } Primitives prim_set; prim_set.m_type = PRIMITIVE_TRIANGLES; prim_set.m_index_offset_vertex = 0; prim_set.m_index_elements = 1; prim_set.m_vertices = 3; // count attribute string count_str = attribute( triangles_node, "count" ); if( count_str.empty() ) { SCENELOG_ERROR( log, "Required attribute count empty." ); return false; } try { prim_set.m_count = boost::lexical_cast<size_t>( count_str ); } catch( const boost::bad_lexical_cast& e ) { SCENELOG_ERROR( log, "Failed to parse count attribute: " << e.what() ); return false; } // material attribute prim_set.m_material_symbol = attribute( triangles_node, "material" ); // Parse inputs. These define the number of elements for each index. We only // use one element, see comment in xml/Input.cpp @ parseInputShared. xmlNodePtr n = triangles_node->children; while( n != NULL && xmlStrEqual( n->name, BAD_CAST "input" ) ) { if( !parseInputShared( prim_set, inputs, n) ) { return false; } n = n->next; } // Get indices if present if( n!= NULL && xmlStrEqual( n->name, BAD_CAST "p" ) ) { vector<int> p; if(!parseBodyAsInts( p, n, prim_set.m_vertices * prim_set.m_count, prim_set.m_index_offset_vertex, prim_set.m_index_elements ) ) { SCENELOG_ERROR( log, "Failed to parse <p>." ); return false; } prim_set.m_index_source_id = geometry->id() + "_indices_" + boost::lexical_cast<string>( geometry->primitiveSets() ); SourceBuffer* ix = m_database.addSourceBuffer( prim_set.m_index_source_id ); ix->contents( p ); // and iterate one step forwards n = n->next; } else { prim_set.m_index_source_id = ""; } // and plow through the rest of the nodes for( ; n!=NULL; n=n->next ) { if( xmlStrEqual( n->name, BAD_CAST "extra" ) ) { // ignore } else { SCENELOG_WARN( log, "Unexpected node " << reinterpret_cast<const char*>( n->name) ); } } prim_set.m_index_offset_vertex = 0; prim_set.m_index_elements = 1; geometry->addPrimitiveSet( prim_set ); return true; } */ /* xmlNodePtr Exporter::createTriangles( Context& context, const Primitives& ps ) const { Logger log = getLogger( "Scene.Builder.createTriangles" ); xmlNodePtr triangle_node = xmlNewNode( NULL, BAD_CAST "triangles" ); // Add attribute 'count', required. const string count_str = lexical_cast<string>( ps.m_primitive_count ); xmlNewProp( triangle_node, BAD_CAST "count", BAD_CAST count_str.c_str() ); // Add attribute 'material', optional if( !ps.m_material_symbol.empty() ) { xmlNewProp( triangle_node, BAD_CAST "material", BAD_CAST ps.m_material_symbol.c_str() ); context.m_referenced_materials[ ps.m_material_symbol ] = true; } // Add <p> child if indexed if( !ps.m_index_buffer_id.empty() ) { const SourceBuffer* buffer = m_database.library<SourceBuffer>().get( ps.m_index_buffer_id ); if( buffer == NULL ) { SCENELOG_ERROR( log, "Failed to locate index buffer '" << ps.m_index_buffer_id << "'." ); return NULL; } xmlNodePtr p_node = xmlNewChild( triangle_node, NULL, BAD_CAST "p", NULL ); setBody( p_node, buffer->intData(), buffer->elementCount() ); } return triangle_node; } */ } // of namespace Scene } // of namespace Scene
agpl-3.0
bringsvor/l10n_no_vatreport
__init__.py
1007
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2013 ZedeS Technologies, zedestech.com # Copyright (C) 2013 Datalege AS, www.datalege.no # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import vat_report import account_tax_code
agpl-3.0
Ramkavanan/SHCRM
app/protected/modules/users/elements/assets/UsersValidation.js
2618
$(document).ready(function(){ $("label[for=User_jobTitle]").append("<span class='required'>*</span>"); $("label[for=User_officePhone]").append("<span class='required'>*</span>"); $("label[for=User_manager_id]").append("<span class='required'>*</span>"); $("label[for=User_role_id]").append("<span class='required'>*</span>"); $("label[for=User_mobilePhone]").append("<span class='required'>*</span>"); $("label[for=User_department]").append("<span class='required'>*</span>"); $("label[for=User_language_value]").append("<span class='required'>*</span>"); $("label[for=User_timeZone_value]").append("<span class='required'>*</span>"); $("label[for=User_currency_id]").append("<span class='required'>*</span>"); $("label:contains('Address')").append("<span class='required'>*</span>"); $("label[for=User_locale_value]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_jobTitle]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_officePhone]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_manager_id]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_role_id]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_mobilePhone]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_department]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_language_value]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_timeZone_value]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_currency_id]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_locale_value]").append("<span class='required'>*</span>"); $("label[for=UserPasswordForm_primaryEmail_emailAddress]").append("<span class='required'>*</span>"); /** * For mobile and phone number validations in user create page. */ var fieldIds = ["#UserPasswordForm_officePhone", "#UserPasswordForm_mobilePhone"]; PhoneNumAndMobNunberValidation(fieldIds); }); function PhoneNumAndMobNunberValidation(ids){ $.each(ids, function( index, value ) { $(value).attr("placeholder", "(___) ___-____"); $(value).attr("maxlength","10"); $(value).keypress(function(e){ this.value = this.value.replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,"($1) $2-$3"); if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { return false; } }); }); }
agpl-3.0
standardnotes/web
app/assets/javascripts/preferences/panes/account/subscription/SubscriptionWrapper.tsx
581
import { WebApplication } from '@/ui_models/application'; import { FunctionalComponent } from 'preact'; import { useState } from 'preact/hooks'; import { Subscription } from './Subscription'; import { SubscriptionState } from './subscription_state'; type Props = { application: WebApplication; }; export const SubscriptionWrapper: FunctionalComponent<Props> = ({ application, }) => { const [subscriptionState] = useState(() => new SubscriptionState()); return ( <Subscription application={application} subscriptionState={subscriptionState} /> ); };
agpl-3.0
24eme/vinsdeloire
project/plugins/acVinEtablissementPlugin/lib/model/Etablissement/Etablissement.class.php
17271
<?php class Etablissement extends BaseEtablissement { protected $_interpro = null; protected $droit = null; /** * @return _Compte */ public function getInterproObject() { if (is_null($this->_interpro)) { $this->_interpro = InterproClient::getInstance()->find($this->interpro); } return $this->_interpro; } public function constructId() { $this->set('_id', 'ETABLISSEMENT-' . $this->identifiant); if ($this->isViticulteur()) { $this->raisins_mouts = is_null($this->raisins_mouts) ? EtablissementClient::RAISINS_MOUTS_NON : $this->raisins_mouts; $this->exclusion_drm = is_null($this->exclusion_drm) ? EtablissementClient::EXCLUSION_DRM_NON : $this->exclusion_drm; $this->type_dr = is_null($this->type_dr) ? EtablissementClient::TYPE_DR_DRM : $this->type_dr; } if ($this->isViticulteur() || $this->isNegociant()) { $this->relance_ds = is_null($this->relance_ds) ? EtablissementClient::RELANCE_DS_OUI : $this->relance_ds; } $this->statut = is_null($this->statut) ? EtablissementClient::STATUT_ACTIF : $this->statut; } public function setRelanceDS($value) { if (!($this->isViticulteur() || $this->isNegociant() || $this->isNegociantPur())) { throw new sfException("Le champs 'relance_ds' n'est valable que pour les viticulteurs ou les négociants"); } $this->_set('relance_ds', $value); } public function setExclusionDRM($value) { if (!($this->isViticulteur())) { throw new sfException("Le champs 'exclusion_drm' n'est valable que pour les viticulteurs"); } $this->_set('exclusion_drm', $value); } public function setRaisinsMouts($value) { if (!($this->isViticulteur())) { throw new sfException("Le champs 'raisins_mouts' n'est valable que pour les viticulteurs"); } $this->_set('raisins_mouts', $value); } public function setTypeDR($value) { if (!($this->isViticulteur())) { throw new sfException("Le champs 'type_dr' n'est valable que pour les viticulteurs"); } $this->_set('type_dr', $value); } public function getAllDRM() { return acCouchdbManager::getClient()->startkey(array($this->identifiant, null)) ->endkey(array($this->identifiant, null)) ->getView("drm", "all"); } private function cleanPhone($phone) { $phone = preg_replace('/[^0-9\+]+/', '', $phone); $phone = preg_replace('/^00/', '+', $phone); $phone = preg_replace('/^0/', '+33', $phone); if (strlen($phone) == 9 && preg_match('/^[64]/', $phone)) $phone = '+33' . $phone; if (!preg_match('/^\+/', $phone) || (strlen($phone) != 12 && preg_match('/^\+33/', $phone))) echo("$phone n'est pas un téléphone correct pour " . $this->_id . "\n"); return $phone; } public function getMasterCompte() { if ($this->compte) return CompteClient::getInstance()->find($this->compte); return CompteClient::getInstance()->find($this->getSociete()->compte_societe); } public function getContact() { return $this->getMasterCompte(); } public function getSociete() { return SocieteClient::getInstance()->find($this->id_societe); } public function isSameCoordonneeThanSociete() { return $this->isSameContactThanSociete(); } public function isSameContactThanSociete() { return ($this->compte == $this->getSociete()->compte_societe); } public function getNumCompteEtablissement() { if (!$this->compte) return null; if ($this->compte != $this->getSociete()->compte_societe) return $this->compte; return null; } public function getNoTvaIntraCommunautaire() { $societe = $this->getSociete(); if (!$societe) { return null; } return $societe->no_tva_intracommunautaire; } public function setFax($fax) { if ($fax) $this->_set('fax', $this->cleanPhone($fax)); } public function setTelephone($phone, $idcompte = null) { if ($phone) $this->_set('telephone', $this->cleanPhone($phone)); } public function getDenomination() { return ($this->nom) ? $this->nom : $this->raison_sociale; } public function addLiaison($type, $etablissement) { if (!in_array($type, EtablissementClient::listTypeLiaisons())) throw new sfException("liaison type \"$type\" unknown"); $liaison = $this->liaisons_operateurs->add($type . '_' . $etablissement->_id); $liaison->type_liaison = $type; $liaison->id_etablissement = $etablissement->_id; $liaison->libelle_etablissement = $etablissement->nom; return $liaison; } public function isNegociant() { return ($this->famille == EtablissementFamilles::FAMILLE_NEGOCIANT); } public function isNegociantPur(){ return ($this->famille == EtablissementFamilles::FAMILLE_NEGOCIANT_PUR); } public function isViticulteur() { return ($this->famille == EtablissementFamilles::FAMILLE_PRODUCTEUR); } public function isCourtier() { return ($this->famille == EtablissementFamilles::FAMILLE_COURTIER); } public function isCooperative() { return ($this->_get('famille') == EtablissementFamilles::FAMILLE_COOPERATIVE); } public function getFamilleType() { $familleType = array(EtablissementFamilles::FAMILLE_PRODUCTEUR => 'vendeur', EtablissementFamilles::FAMILLE_NEGOCIANT => 'acheteur', EtablissementFamilles::FAMILLE_NEGOCIANT_PUR => 'acheteur', EtablissementFamilles::FAMILLE_COURTIER => 'mandataire'); return $familleType[$this->famille]; } public function getDepartement() { if ($this->siege->code_postal) { return substr($this->siege->code_postal, 0, 2); } return null; } public function getFamille(){ if($this->isCooperative()){ return EtablissementFamilles::FAMILLE_PRODUCTEUR; } return $this->_get('famille'); } public function getDroit() { if (is_null($this->droit)) { $this->droit = new EtablissementDroit($this); } return $this->droit; } public function hasDroit($droit) { return $this->getDroit()->has($droit); } public function hasDroitsAcquittes(){ return $this->getMasterCompte()->hasDroit(Roles::TELEDECLARATION_DRM_ACQUITTE); } public function getDroits() { return EtablissementFamilles::getDroitsByFamilleAndSousFamille($this->famille, $this->sous_famille); } public function isInterLoire($produit) { if (preg_match('/AOC_INTERLOIRE/', $produit)) { return ( ($this->region == EtablissementClient::REGION_CENTRE_AOP) || ($this->region == EtablissementClient::REGION_PDL_AOP) || ($this->region == EtablissementClient::REGION_TOURS) || ($this->region == EtablissementClient::REGION_NANTES) || ($this->region == EtablissementClient::REGION_ANGERS) ); } return (($this->region != EtablissementClient::REGION_HORSINTERLOIRE) && ($this->region != EtablissementClient::REGION_HORS_REGION)); } protected function synchroRecetteLocale() { if ($this->recette_locale->id_douane) { $soc = SocieteClient::getInstance()->find($this->recette_locale->id_douane); if ($soc && $this->recette_locale->nom != $soc->raison_sociale) { $this->recette_locale->nom = $soc->raison_sociale; $this->recette_locale->ville = $soc->siege->commune; } } } protected function initFamille() { if (!$this->famille) { $this->famille = EtablissementFamilles::FAMILLE_PRODUCTEUR; } if (!$this->sous_famille) { $this->sous_famille = EtablissementFamilles::SOUS_FAMILLE_CAVE_PARTICULIERE; } } protected function synchroFromSociete() { $soc = SocieteClient::getInstance()->find($this->id_societe); if (!$soc) throw new sfException("$id n'est pas une société connue"); $this->cooperative = $soc->cooperative; $this->add('raison_sociale', $soc->raison_sociale); } protected function synchroAndSaveSociete() { $soc = $this->getSociete(); $soc->addEtablissement($this); $soc->save(true); } protected function synchroAndSaveCompte() { $compte_master = $this->getMasterCompte(); if ($this->isSameContactThanSociete()) { $compte_master->addOrigine($this->_id); if (($this->statut != EtablissementClient::STATUT_SUSPENDU)) { $compte_master->statut = $this->statut; } } else { $compte_master->statut = $this->statut; } $compte_master->save(false, true); } public function switchOrigineAndSaveCompte($old_id) { $this->synchroFromCompte(); if (!$old_id) { return; } if ($this->isSameContactThanSociete()) { CompteClient::getInstance()->findAndDelete($old_id, true); $compte = $this->getContact(); $compte->addOrigine($this->_id); } else { $compte = CompteClient::getInstance()->find($old_id); $compte->removeOrigine($this->_id); $compte->statut = $this->statut; } $compte->save(false, true); } public function save($fromsociete = false, $fromclient = false, $fromcompte = false) { $this->constructId(); $this->synchroRecetteLocale(); $this->initFamille(); $this->synchroFromSociete(); //parfois l'interpro n'est pas setté $this->interpro = "INTERPRO-inter-loire"; if (!$fromclient) { if (!$this->compte) { $compte = CompteClient::getInstance()->createCompteFromEtablissement($this); $compte->constructId(); $compte->statut = $this->statut; $this->compte = $compte->_id; parent::save(); $compte->save(true, true); } } parent::save(); if (!$fromsociete) { $this->synchroAndSaveSociete(); if (!$fromcompte) { $this->synchroAndSaveCompte(); } } } public function isActif() { return ($this->statut == EtablissementClient::STATUT_ACTIF); } public function setIdSociete($id) { $soc = SocieteClient::getInstance()->find($id); if (!$soc) throw new sfException("$id n'est pas une société connue"); $this->_set("id_societe", $id); } public function __toString() { return sprintf('%s (%s)', $this->nom, $this->identifiant); } public function getBailleurs() { $bailleurs = array(); if (!(count($this->liaisons_operateurs))) return $bailleurs; $liaisons = $this->liaisons_operateurs; foreach ($liaisons as $key => $liaison) { if ($liaison->type_liaison == EtablissementClient::TYPE_LIAISON_BAILLEUR) $bailleurs[$key] = $liaison; } return $bailleurs; } public function findBailleurByNom($nom) { $bailleurs = $this->getBailleurs(); foreach ($bailleurs as $key => $liaison) { if ($liaison->libelle_etablissement == str_replace("&", "", $nom)) return EtablissementClient::getInstance()->find($liaison->id_etablissement); if ($liaison->exist('aliases')) foreach ($liaison->aliases as $alias) { if (strtoupper($alias) == strtoupper(str_replace("&", "", $nom))) return EtablissementClient::getInstance()->find($liaison->id_etablissement); } } return null; } public function addAliasForBailleur($identifiant_bailleur, $alias) { $bailleurNameNode = EtablissementClient::TYPE_LIAISON_BAILLEUR . '_' . $identifiant_bailleur; if (!$this->liaisons_operateurs->exist($bailleurNameNode)) throw new sfException("La liaison avec le bailleur $identifiant_bailleur n'existe pas"); if (!$this->liaisons_operateurs->$bailleurNameNode->exist('aliases')) $this->liaisons_operateurs->$bailleurNameNode->add('aliases'); $this->liaisons_operateurs->$bailleurNameNode->aliases->add(str_replace("&amp;","",$alias), str_replace("&amp;","",$alias)); } public function synchroFromCompte() { $compte = $this->getMasterCompte(); if (!$compte) { return null; } $this->siege->adresse = $compte->adresse; if ($compte->exist('adresse_complementaire')) $this->siege->add('adresse_complementaire', $compte->adresse_complementaire); $this->siege->code_postal = $compte->code_postal; $this->siege->commune = $compte->commune; $this->email = $compte->email; $this->fax = $compte->fax; $this->telephone = ($compte->telephone_bureau) ? $compte->telephone_bureau : $compte->telephone_mobile; return $this; } public function getSiegeAdresses() { $a = $this->siege->adresse; if ($this->siege->exist("adresse_complementaire")) { $a .= ' ; ' . $this->siege->adresse_complementaire; } return $a; } public function findEmail() { $etablissementPrincipal = $this->getSociete()->getEtablissementPrincipal(); if ($this->_get('email')) { return $this->get('email'); } if (($etablissementPrincipal->identifiant == $this->identifiant) || !$etablissementPrincipal->exist('email') || !$etablissementPrincipal->email) { return false; } return $etablissementPrincipal->get('email'); } public function getEtablissementPrincipal() { return SocieteClient::getInstance()->find($this->id_societe)->getEtablissementPrincipal(); } public function hasCompteTeledeclarationActivate() { return $this->getSociete()->getMasterCompte()->isTeledeclarationActive(); } public function getEmailTeledeclaration() { if($this->exist('teledeclaration_email') && $this->teledeclaration_email){ return $this->teledeclaration_email; } if($this->exist('email') && $this->email){ return $this->email; } return null; } public function setEmailTeledeclaration($email) { $this->add('teledeclaration_email', $email); } public function hasRegimeCrd() { return $this->exist('crd_regime') && $this->crd_regime; } public function getCrdRegimeArray(){ if(!$this->hasRegimeCrd()){ return null; } return explode(",",$this->crd_regime); } public function hasRegimeCollectifAcquitte(){ return in_array(EtablissementClient::REGIME_CRD_COLLECTIF_ACQUITTE, $this->getCrdRegimeArray()); } public function hasRegimeCollectifSuspendu(){ return in_array(EtablissementClient::REGIME_CRD_COLLECTIF_SUSPENDU, $this->getCrdRegimeArray()); } public function hasRegimePersonnalise(){ return in_array(EtablissementClient::REGIME_CRD_PERSONNALISE, $this->getCrdRegimeArray()); } public function hasLegalSignature() { return $this->getSociete()->hasLegalSignature(); } public function isRegionIGPValDeLoire() { return ($this->region != EtablissementClient::REGION_HORS_REGION); } public function getMoisToSetStock() { if ($this->exist('mois_stock_debut') && $this->mois_stock_debut) { return $this->mois_stock_debut; } return DRMPaiement::NUM_MOIS_DEBUT_CAMPAGNE; } public function getCodeInsee() { if (!$this->siege->exist('code_insee') && $this->cvi) { $this->siege->add('code_insee', substr($this->cvi, 0, 5)); } if ($this->siege->exist('code_insee')) { return $this->siege->code_insee; } return null; } public function getNatureInao() { if (preg_match('/SICA( |$)/i', $this->raison_sociale)) { return '07'; } if (preg_match('/(SCEA|GFA|GAEC)( |$)/i', $this->raison_sociale)) { return '06'; } if ($this->isCooperative()) { if (preg_match('/union/i', $this->raison_sociale)) { return '05'; } return '04'; } if ($this->famille == EtablissementClient::FAMILLE_PRODUCTEUR) { return '01'; } if ($this->famille == EtablissementClient::FAMILLE_NEGOCIANT || $this->famille == EtablissementClient::FAMILLE_NEGOCIANT_PUR) { return '08'; } return '09'; } }
agpl-3.0
nilcy/yoyo
yoyo-actor/yoyo-actor-service-api/src/main/java/yoyo/actor/service/domain/parts/HomeAddress.java
738
// ======================================================================== // Copyright (C) YOYO Project Team. All rights reserved. // GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 // http://www.gnu.org/licenses/agpl-3.0.txt // ======================================================================== package yoyo.actor.service.domain.parts; import javax.persistence.Cacheable; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; /** * 自宅住所 * @author nilcy */ @Entity @DiscriminatorValue("H") @Cacheable(true) public class HomeAddress extends Address<HomeAddress> { /** 製品番号 */ private static final long serialVersionUID = -8419047041954578883L; }
agpl-3.0
UberPOV/UberPOV
source/backend/render/tracetask.cpp
35538
//****************************************************************************** /// /// @file backend/render/tracetask.cpp /// /// @todo What's in here? /// /// @copyright /// @parblock /// /// UberPOV Raytracer version 1.37. /// Portions Copyright 2013-2015 Christoph Lipka. /// /// UberPOV 1.37 is an experimental unofficial branch of POV-Ray 3.7, and is /// subject to the same licensing terms and conditions. /// /// ---------------------------------------------------------------------------- /// /// Persistence of Vision Ray Tracer ('POV-Ray') version 3.7. /// Copyright 1991-2015 Persistence of Vision Raytracer Pty. Ltd. /// /// POV-Ray 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. /// /// POV-Ray 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/>. /// /// ---------------------------------------------------------------------------- /// /// POV-Ray is based on the popular DKB raytracer version 2.12. /// DKBTrace was originally written by David K. Buck. /// DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins. /// /// @endparblock /// //******************************************************************************* #include <vector> #include <boost/thread.hpp> // frame.h must always be the first POV file included (pulls in platform config) #include "backend/frame.h" #include "backend/render/tracetask.h" #include "backend/math/chi2.h" #include "backend/math/matrices.h" #include "backend/render/trace.h" #include "backend/scene/scene.h" #include "backend/scene/threaddata.h" #include "backend/scene/view.h" #include "backend/support/jitter.h" #include "backend/texture/normal.h" #ifdef PROFILE_INTERSECTIONS #include "base/image/image.h" #endif // this must be the last file included #include "base/povdebug.h" namespace pov { #ifdef PROFILE_INTERSECTIONS bool gDoneBSP; bool gDoneBVH; POV_ULONG gMinVal = ULLONG_MAX ; POV_ULONG gMaxVal = 0; POV_ULONG gIntersectionTime; vector<vector<POV_ULONG> > gBSPIntersectionTimes; vector<vector<POV_ULONG> > gBVHIntersectionTimes; vector <vector<POV_ULONG> > *gIntersectionTimes; #endif class SmartBlock { public: SmartBlock(int ox, int oy, int bw, int bh); bool GetFlag(int x, int y) const; void SetFlag(int x, int y, bool f); RGBTColour& operator()(int x, int y); const RGBTColour& operator()(int x, int y) const; vector<RGBTColour>& GetPixels(); private: vector<RGBTColour> framepixels; vector<RGBTColour> pixels; vector<bool> frameflags; vector<bool> flags; int offsetx; int offsety; int blockwidth; int blockheight; int GetOffset(int x, int y) const; }; SmartBlock::SmartBlock(int ox, int oy, int bw, int bh) : offsetx(ox), offsety(oy), blockwidth(bw), blockheight(bh) { framepixels.resize((blockwidth * 2) + (blockheight * 2) + 4); pixels.resize(blockwidth * blockheight); frameflags.resize((blockwidth * 2) + (blockheight * 2) + 4); flags.resize(blockwidth * blockheight); } bool SmartBlock::GetFlag(int x, int y) const { int offset = GetOffset(x, y); if(offset < 0) return frameflags[-1 - offset]; else return flags[offset]; } void SmartBlock::SetFlag(int x, int y, bool f) { int offset = GetOffset(x, y); if(offset < 0) frameflags[-1 - offset] = f; else flags[offset] = f; } RGBTColour& SmartBlock::operator()(int x, int y) { int offset = GetOffset(x, y); if(offset < 0) return framepixels[-1 - offset]; else return pixels[offset]; } const RGBTColour& SmartBlock::operator()(int x, int y) const { int offset = GetOffset(x, y); if(offset < 0) return framepixels[-1 - offset]; else return pixels[offset]; } vector<RGBTColour>& SmartBlock::GetPixels() { return pixels; } int SmartBlock::GetOffset(int x, int y) const { x -= offsetx; y -= offsety; if(x < 0) x = -1; else if(x >= blockwidth) x = blockwidth; if(y < 0) y = -1; else if(y >= blockheight) y = blockheight; if((x < 0) && (y < 0)) return -1; else if((x >= blockwidth) && (y < 0)) return -2; else if((x < 0) && (y >= blockheight)) return -3; else if((x >= blockwidth) && (y >= blockheight)) return -4; else if(x < 0) return -(4 + y); else if(y < 0) return -(4 + x + blockheight); else if(x >= blockwidth) return -(4 + y + blockheight + blockwidth); else if(y >= blockheight) return -(4 + x + blockheight + blockwidth + blockheight); else return (x + (y * blockwidth)); } TraceTask::SubdivisionBuffer::SubdivisionBuffer(size_t s) : colors(s * s), sampled(s * s), size(s) { Clear(); } void TraceTask::SubdivisionBuffer::SetSample(size_t x, size_t y, const RGBTColour& col) { colors[x + (y * size)] = col; sampled[x + (y * size)] = true; } bool TraceTask::SubdivisionBuffer::Sampled(size_t x, size_t y) { return sampled[x + (y * size)]; } RGBTColour& TraceTask::SubdivisionBuffer::operator()(size_t x, size_t y) { return colors[x + (y * size)]; } void TraceTask::SubdivisionBuffer::Clear() { for(vector<bool>::iterator i(sampled.begin()); i != sampled.end(); i++) *i = false; } TraceTask::TraceTask(ViewData *vd, unsigned int tm, DBL js, DBL aat, DBL aac, unsigned int aad, pov_base::GammaCurvePtr& aag, unsigned int ps, bool psc, bool final, bool hr, size_t seed) : RenderTask(vd, seed, "Trace"), trace(vd, GetViewDataPtr(), vd->GetSceneData()->parsedMaxTraceLevel, vd->GetSceneData()->parsedAdcBailout, vd->GetQualityFeatureFlags(), cooperate, media, radiosity), cooperate(*this), tracingMethod(tm), jitterScale(js), aaThreshold(aat), aaConfidence(aac), aaDepth(aad), aaGamma(aag), previewSize(ps), previewSkipCorner(psc), finalTrace(final), highReproducibility(hr), media(GetViewDataPtr(), &trace, &photonGatherer), radiosity(vd->GetSceneData(), GetViewDataPtr(), vd->GetSceneData()->radiositySettings, vd->GetRadiosityCache(), cooperate, final, vd->GetCamera().Location, hr), photonGatherer(&vd->GetSceneData()->mediaPhotonMap, vd->GetSceneData()->photonSettings) { #ifdef PROFILE_INTERSECTIONS Rectangle ra = vd->GetRenderArea(); if (vd->GetSceneData()->boundingMethod == 2) { gBSPIntersectionTimes.clear(); gBSPIntersectionTimes.resize(ra.bottom + 1); for (int i = 0; i < ra.bottom + 1; i++) gBSPIntersectionTimes[i].resize(ra.right + 1); gIntersectionTimes = &gBSPIntersectionTimes; gDoneBSP = true; } else { gBVHIntersectionTimes.clear(); gBVHIntersectionTimes.resize(ra.bottom + 1); for (int i = 0; i < ra.bottom + 1; i++) gBVHIntersectionTimes[i].resize(ra.right + 1); gIntersectionTimes = &gBVHIntersectionTimes; gDoneBVH = true; } #endif // TODO: this could be initialised someplace more suitable GetViewDataPtr()->qualityFlags = vd->GetQualityFeatureFlags(); } TraceTask::~TraceTask() { } void TraceTask::Run() { #ifdef RTR_HACK bool forever = GetViewData()->GetRealTimeRaytracing(); do { #endif switch(tracingMethod) { case 0: if(previewSize > 0) SimpleSamplingM0P(); else SimpleSamplingM0(); break; case 1: NonAdaptiveSupersamplingM1(); break; case 2: AdaptiveSupersamplingM2(); break; case 3: StochasticSupersamplingM3(); break; } #ifdef RTR_HACK if(forever) { const Camera *camera = GetViewData()->GetRTRData()->CompletedFrame(); Cooperate(); if(camera != NULL) trace.SetupCamera(*camera); } } while(forever); #endif GetViewData()->SetHighestTraceLevel(trace.GetHighestTraceLevel()); } void TraceTask::Stopped() { // nothing to do for now [trf] } void TraceTask::Finish() { GetViewDataPtr()->timeType = SceneThreadData::kRenderTime; GetViewDataPtr()->realTime = ConsumedRealTime(); GetViewDataPtr()->cpuTime = ConsumedCPUTime(); #ifdef PROFILE_INTERSECTIONS if (gDoneBSP && gDoneBVH) { int width = gBSPIntersectionTimes[0].size(); int height = gBSPIntersectionTimes.size(); if (width == gBVHIntersectionTimes[0].size() && height == gBVHIntersectionTimes.size()) { SNGL scale = 1.0 / (gMaxVal - gMinVal); Image::WriteOptions opts; opts.bpcc = 16; Image *img = Image::Create(width, height, Image::Gray_Int16, false); for (int y = 0 ; y < height ; y++) for (int x = 0 ; x < width ; x++) img->SetGrayValue(x, y, (gBSPIntersectionTimes[y][x] - gMinVal) * scale); OStream *imagefile(NewOStream("bspprofile.png", 0, false)); Image::Write(Image::PNG, imagefile, img, opts); delete imagefile; delete img; img = Image::Create(width, height, Image::Gray_Int16, false); imagefile = NewOStream("bvhprofile.png", 0, false); for (int y = 0 ; y < height ; y++) for (int x = 0 ; x < width ; x++) img->SetGrayValue(x, y, (gBVHIntersectionTimes[y][x] - gMinVal) * scale); Image::Write(Image::PNG, imagefile, img, opts); delete imagefile; delete img; img = Image::Create(width, height, Image::Gray_Int16, false); imagefile = NewOStream("summedprofile.png", 0, false); for (int y = 0 ; y < height ; y++) for (int x = 0 ; x < width ; x++) img->SetGrayValue(x, y, 0.5f + ((((gBSPIntersectionTimes[y][x] - gMinVal) - (gBVHIntersectionTimes[y][x] - gMinVal)) * scale) / 2)); Image::Write(Image::PNG, imagefile, img, opts); delete imagefile; delete img; img = Image::Create(width, height, Image::RGBFT_Float, false); imagefile = NewOStream("rgbprofile.png", 0, false); for (int y = 0 ; y < height ; y++) { for (int x = 0 ; x < width ; x++) { RGBTColour col; float bspval = (gBSPIntersectionTimes[y][x] - gMinVal) * scale ; float bvhval = (gBVHIntersectionTimes[y][x] - gMinVal) * scale ; float diff = bspval - bvhval ; if (diff > 0.0) col.blue() += diff ; else col.red() -= diff ; img->SetRGBTValue(x, y, col); } } Image::Write(Image::PNG, imagefile, img, opts); delete imagefile; delete img; } gDoneBSP = gDoneBVH = false; gMinVal = ULLONG_MAX; gMaxVal = 0; } #endif } void TraceTask::SimpleSamplingM0() { POVRect rect; vector<RGBTColour> pixels; unsigned int serial; while(GetViewData()->GetNextRectangle(rect, serial) == true) { radiosity.BeforeTile(highReproducibility? serial : 0); pixels.clear(); pixels.reserve(rect.GetArea()); for(DBL y = DBL(rect.top); y <= DBL(rect.bottom); y++) { for(DBL x = DBL(rect.left); x <= DBL(rect.right); x++) { #ifdef PROFILE_INTERSECTIONS POV_LONG it = ULLONG_MAX; for (int i = 0 ; i < 3 ; i++) { TransColour c; gIntersectionTime = 0; trace(x, y, GetViewData()->GetWidth(), GetViewData()->GetHeight(), c); if (gIntersectionTime < it) it = gIntersectionTime; } (*gIntersectionTimes)[(int) y] [(int) x] = it; if (it < gMinVal) gMinVal = it; if (it > gMaxVal) gMaxVal = it; #endif RGBTColour col; trace(x, y, GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); GetViewDataPtr()->Stats()[Number_Of_Pixels]++; pixels.push_back(col); Cooperate(); } } radiosity.AfterTile(); GetViewDataPtr()->AfterTile(); GetViewData()->CompletedRectangle(rect, serial, pixels, 1, finalTrace); Cooperate(); } } void TraceTask::SimpleSamplingM0P() { DBL stepsize(previewSize); POVRect rect; vector<Vector2d> pixelpositions; vector<RGBTColour> pixelcolors; unsigned int serial; while(GetViewData()->GetNextRectangle(rect, serial) == true) { radiosity.BeforeTile(highReproducibility? serial : 0); unsigned int px = (rect.GetWidth() + previewSize - 1) / previewSize; unsigned int py = (rect.GetHeight() + previewSize - 1) / previewSize; pixelpositions.clear(); pixelpositions.reserve(px * py); pixelcolors.clear(); pixelcolors.reserve(px * py); for(DBL y = DBL(rect.top); y <= DBL(rect.bottom); y += stepsize) { for(DBL x = DBL(rect.left); x <= DBL(rect.right); x += stepsize) { if((previewSkipCorner == true) && (fmod(x, stepsize * 2.0) < EPSILON) && (fmod(y, stepsize * 2.0) < EPSILON)) continue; #ifdef PROFILE_INTERSECTIONS POV_LONG it = ULLONG_MAX; for (int i = 0 ; i < 3 ; i++) { TransColour c; gIntersectionTime = 0; trace(x, y, GetViewData()->GetWidth(), GetViewData()->GetHeight(), c); if (gIntersectionTime < it) it = gIntersectionTime; } (*gIntersectionTimes)[(int) y] [(int) x] = it; if (it < gMinVal) gMinVal = it; if (it > gMaxVal) gMaxVal = it; #endif RGBTColour col; trace(x, y, GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); GetViewDataPtr()->Stats()[Number_Of_Pixels]++; pixelpositions.push_back(Vector2d(x, y)); pixelcolors.push_back(col); Cooperate(); } } radiosity.AfterTile(); GetViewDataPtr()->AfterTile(); if(pixelpositions.size() > 0) GetViewData()->CompletedRectangle(rect, serial, pixelpositions, pixelcolors, previewSize, finalTrace); Cooperate(); } } void TraceTask::NonAdaptiveSupersamplingM1() { POVRect rect; unsigned int serial; jitterScale = jitterScale / DBL(aaDepth); while(GetViewData()->GetNextRectangle(rect, serial) == true) { radiosity.BeforeTile(highReproducibility? serial : 0); SmartBlock pixels(rect.left, rect.top, rect.GetWidth(), rect.GetHeight()); // sample line above current block for(int x = rect.left; x <= rect.right; x++) { trace(DBL(x), DBL(rect.top) - 1.0, GetViewData()->GetWidth(), GetViewData()->GetHeight(), pixels(x, rect.top - 1)); GetViewDataPtr()->Stats()[Number_Of_Pixels]++; // Cannot supersample this pixel, so just claim it was already supersampled! [trf] // [CJC] see comment for leftmost pixels below; similar situation applies here pixels.SetFlag(x, rect.top - 1, true); Cooperate(); } for(int y = rect.top; y <= rect.bottom; y++) { trace(DBL(rect.left) - 1.0, y, GetViewData()->GetWidth(), GetViewData()->GetHeight(), pixels(rect.left - 1, y)); // sample pixel left of current line in block GetViewDataPtr()->Stats()[Number_Of_Pixels]++; // Cannot supersample this pixel, so just claim it was already supersampled! [trf] // [CJC] NB this could in some circumstances cause an artifact at a block boundary, // if the leftmost pixel on this blockline ends up not being supersampled because the // difference between it and the rightmost pixel on the same line in the last block // was insufficient to trigger the supersample right now, *BUT* if the rightmost pixel // *had* been supersampled, AND the difference was then enough to trigger the call // to supersample the current pixel, AND when the block on the left was/is rendered, // the abovementioned rightmost pixel *does* get supersampled due to the logic applied // when the code rendered *that* block ... [a long set of preconditions but possible]. // there's no easy solution to this because if we *do* supersample right now, the // reverse situation could apply if the rightmost pixel in the last block ends up // not being supersampled ... pixels.SetFlag(rect.left - 1, y, true); Cooperate(); for(int x = rect.left; x <= rect.right; x++) { // trace current pixel trace(DBL(x), DBL(y), GetViewData()->GetWidth(), GetViewData()->GetHeight(), pixels(x, y)); GetViewDataPtr()->Stats()[Number_Of_Pixels]++; Cooperate(); bool sampleleft = (pixels.GetFlag(x - 1, y) == false); bool sampletop = (pixels.GetFlag(x, y - 1) == false); bool samplecurrent = true; // perform antialiasing NonAdaptiveSupersamplingForOnePixel(DBL(x), DBL(y), pixels(x - 1, y), pixels(x, y - 1), pixels(x, y), sampleleft, sampletop, samplecurrent); // if these pixels have been supersampled, set their supersampling flag if(sampleleft == true) pixels.SetFlag(x - 1, y, true); if(sampletop == true) pixels.SetFlag(x, y - 1, true); if(samplecurrent == true) pixels.SetFlag(x, y, true); } } radiosity.AfterTile(); GetViewDataPtr()->AfterTile(); GetViewData()->CompletedRectangle(rect, serial, pixels.GetPixels(), 1, finalTrace); Cooperate(); } } void TraceTask::AdaptiveSupersamplingM2() { POVRect rect; unsigned int serial; size_t subsize = (1 << aaDepth); SubdivisionBuffer buffer(subsize + 1); jitterScale = jitterScale / DBL((1 << aaDepth) + 1); while(GetViewData()->GetNextRectangle(rect, serial) == true) { radiosity.BeforeTile(highReproducibility? serial : 0); SmartBlock pixels(rect.left, rect.top, rect.GetWidth(), rect.GetHeight()); for(int y = rect.top; y <= rect.bottom + 1; y++) { for(int x = rect.left; x <= rect.right + 1; x++) { // trace upper-left corners of all pixels trace(DBL(x) - 0.5, DBL(y) - 0.5, GetViewData()->GetWidth(), GetViewData()->GetHeight(), pixels(x, y)); GetViewDataPtr()->Stats()[Number_Of_Pixels]++; Cooperate(); } } // note that the bottom and/or right corner are the // upper-left corner of the bottom and/or right pixels for(int y = rect.top; y <= rect.bottom; y++) { for(int x = rect.left; x <= rect.right; x++) { buffer.Clear(); buffer.SetSample(0, 0, pixels(x, y)); buffer.SetSample(0, subsize, pixels(x, y + 1)); buffer.SetSample(subsize, 0, pixels(x + 1, y)); buffer.SetSample(subsize, subsize, pixels(x + 1, y + 1)); SubdivideOnePixel(DBL(x), DBL(y), 0.5, 0, 0, subsize, buffer, pixels(x, y), aaDepth - 1); Cooperate(); } } radiosity.AfterTile(); GetViewDataPtr()->AfterTile(); GetViewData()->CompletedRectangle(rect, serial, pixels.GetPixels(), 1, finalTrace); Cooperate(); } } void TraceTask::StochasticSupersamplingM3() { POVRect rect; vector<RGBTColour> pixels; vector<PreciseRGBTColour> pixelsSum; vector<PreciseRGBTColour> pixelsSumSqr; vector<unsigned int> pixelsSamples; unsigned int serial; bool sampleMore; // Create list of thresholds for confidence test. vector<double> confidenceFactor; unsigned int minSamples = 1; // TODO currently hard-coded unsigned int maxSamples = max(minSamples, 1u << (aaDepth*2)); confidenceFactor.reserve(maxSamples*5); double threshold = aaThreshold; double confidence = aaConfidence; if(maxSamples > 1) { for(int n = 1; n <= maxSamples*5; n++) confidenceFactor.push_back(ndtri((1+confidence)/2) / sqrt((double)n)); } else confidenceFactor.push_back(0.0); while(GetViewData()->GetNextRectangle(rect, serial) == true) { radiosity.BeforeTile(highReproducibility? serial : 0); pixels.clear(); pixelsSum.clear(); pixelsSumSqr.clear(); pixelsSamples.clear(); pixels.reserve(rect.GetArea()); pixelsSum.reserve(rect.GetArea()); pixelsSumSqr.reserve(rect.GetArea()); pixelsSamples.reserve(rect.GetArea()); do { sampleMore = false; unsigned int index = 0; for(unsigned int y = rect.top; y <= rect.bottom; y++) { for(unsigned int x = rect.left; x <= rect.right; x++) { PreciseRGBTColour neighborSum; PreciseRGBTColour neighborSumSqr; unsigned int neighborSamples(0); unsigned int samples(0); unsigned int index2; if (index < pixelsSamples.size()) { samples = pixelsSamples [index]; neighborSum = pixelsSum [index]; neighborSumSqr = pixelsSumSqr [index]; neighborSamples = pixelsSamples [index]; } // TODO - we should obtain information about the neighboring render blocks as well index2 = index - 1; if (x > rect.left) { neighborSum += pixelsSum [index2]; neighborSumSqr += pixelsSumSqr [index2]; neighborSamples += pixelsSamples [index2]; } index2 = index - rect.GetWidth(); if (y > rect.top) { neighborSum += pixelsSum [index2]; neighborSumSqr += pixelsSumSqr [index2]; neighborSamples += pixelsSamples [index2]; } index2 = index + 1; if (x < rect.right) { neighborSum += pixelsSum [index2]; neighborSumSqr += pixelsSumSqr [index2]; neighborSamples += pixelsSamples [index2]; } index2 = index + rect.GetWidth(); if (y < rect.bottom) { neighborSum += pixelsSum [index2]; neighborSumSqr += pixelsSumSqr [index2]; neighborSamples += pixelsSamples [index2]; } while(true) { if (samples >= minSamples) { if (samples >= maxSamples) break; PreciseRGBTColour variance = (neighborSumSqr - Sqr(neighborSum)/neighborSamples) / (neighborSamples-1); double cf = confidenceFactor[neighborSamples-1]; PreciseRGBTColour sqrtvar = Sqrt(variance); PreciseRGBTColour confidenceDelta = sqrtvar * cf; if ((confidenceDelta.red() <= threshold) && (confidenceDelta.green() <= threshold) && (confidenceDelta.blue() <= threshold) && (confidenceDelta.transm() <= threshold)) break; } RGBTColour colTemp; PreciseRGBTColour col, colSqr; Vector2d jitter = Uniform2dOnSquare(GetViewDataPtr()->stochasticRandomGenerator) - 0.5; trace(x + jitter.x(), y + jitter.y(), GetViewData()->GetWidth(), GetViewData()->GetHeight(), colTemp, max(samples, minSamples)); col = PreciseRGBTColour(GammaCurve::Encode(aaGamma, colTemp)); colSqr = Sqr(col); if (index >= pixelsSamples.size()) { GetViewDataPtr()->Stats()[Number_Of_Pixels]++; pixels.push_back(colTemp); pixelsSum.push_back(col); pixelsSumSqr.push_back(colSqr); pixelsSamples.push_back(1); } else { pixels [index] += colTemp; pixelsSum [index] += col; pixelsSumSqr [index] += colSqr; pixelsSamples [index] ++; } neighborSum += col; neighborSumSqr += colSqr; neighborSamples ++; samples ++; // Whenever one or more pixels are re-sampled, neighborhood variance constraints may require us to also re-sample others. sampleMore = true; Cooperate(); if (samples >= minSamples) // TODO break; } index ++; } } } while (sampleMore); // So far we've just accumulated the samples for any pixel; // now compute the actual average. unsigned int index = 0; for(unsigned int y = rect.top; y <= rect.bottom; y++) { for(unsigned int x = rect.left; x <= rect.right; x++) { pixels [index] /= pixelsSamples[index]; index ++; } } radiosity.AfterTile(); GetViewDataPtr()->AfterTile(); GetViewData()->CompletedRectangle(rect, serial, pixels, 1, finalTrace); Cooperate(); } } void TraceTask::NonAdaptiveSupersamplingForOnePixel(DBL x, DBL y, RGBTColour& leftcol, RGBTColour& topcol, RGBTColour& curcol, bool& sampleleft, bool& sampletop, bool& samplecurrent) { RGBTColour gcLeft = GammaCurve::Encode(aaGamma, leftcol); RGBTColour gcTop = GammaCurve::Encode(aaGamma, topcol); RGBTColour gcCur = GammaCurve::Encode(aaGamma, curcol); bool leftdiff = (ColourDistanceRGBT(gcLeft, gcCur) >= aaThreshold); bool topdiff = (ColourDistanceRGBT(gcTop, gcCur) >= aaThreshold); sampleleft = sampleleft && leftdiff; sampletop = sampletop && topdiff; samplecurrent = ((leftdiff == true) || (topdiff == true)); if(sampleleft == true) SupersampleOnePixel(x - 1.0, y, leftcol); if(sampletop == true) SupersampleOnePixel(x, y - 1.0, topcol); if(samplecurrent == true) SupersampleOnePixel(x, y, curcol); } void TraceTask::SupersampleOnePixel(DBL x, DBL y, RGBTColour& col) { DBL step(1.0 / DBL(aaDepth)); DBL range(0.5 - (step * 0.5)); DBL rx, ry; RGBTColour tempcol; GetViewDataPtr()->Stats()[Number_Of_Pixels_Supersampled]++; for(DBL yy = -range; yy <= (range + EPSILON); yy += step) { for(DBL xx = -range; xx <= (range + EPSILON); xx += step) { if (jitterScale > 0.0) { Jitter2d(x + xx, y + yy, rx, ry); trace(x + xx + (rx * jitterScale), y + yy + (ry * jitterScale), GetViewData()->GetWidth(), GetViewData()->GetHeight(), tempcol); } else trace(x + xx, y + yy, GetViewData()->GetWidth(), GetViewData()->GetHeight(), tempcol); col += tempcol; GetViewDataPtr()->Stats()[Number_Of_Samples]++; Cooperate(); } } col /= (aaDepth * aaDepth + 1); } void TraceTask::SubdivideOnePixel(DBL x, DBL y, DBL d, size_t bx, size_t by, size_t bstep, SubdivisionBuffer& buffer, RGBTColour& result, int level) { RGBTColour& cx0y0 = buffer(bx, by); RGBTColour& cx0y2 = buffer(bx, by + bstep); RGBTColour& cx2y0 = buffer(bx + bstep, by); RGBTColour& cx2y2 = buffer(bx + bstep, by + bstep); size_t bstephalf = bstep / 2; // o = no operation, + = input, * = output // Input: // +o+ // ooo // +o+ RGBTColour cx0y0g = GammaCurve::Encode(aaGamma, cx0y0); RGBTColour cx0y2g = GammaCurve::Encode(aaGamma, cx0y2); RGBTColour cx2y0g = GammaCurve::Encode(aaGamma, cx2y0); RGBTColour cx2y2g = GammaCurve::Encode(aaGamma, cx2y2); if((level > 0) && ((ColourDistanceRGBT(cx0y0g, cx0y2g) >= aaThreshold) || (ColourDistanceRGBT(cx0y0g, cx2y0g) >= aaThreshold) || (ColourDistanceRGBT(cx0y0g, cx2y2g) >= aaThreshold) || (ColourDistanceRGBT(cx0y2g, cx2y0g) >= aaThreshold) || (ColourDistanceRGBT(cx0y2g, cx2y2g) >= aaThreshold) || (ColourDistanceRGBT(cx2y0g, cx2y2g) >= aaThreshold))) { RGBTColour rcx0y0; RGBTColour rcx0y1; RGBTColour rcx1y0; RGBTColour rcx1y1; RGBTColour col; DBL rxcx0y1, rycx0y1; DBL rxcx1y0, rycx1y0; DBL rxcx2y1, rycx2y1; DBL rxcx1y2, rycx1y2; DBL rxcx1y1, rycx1y1; DBL d2 = d * 0.5; // Trace: // ooo // *oo // ooo if(buffer.Sampled(bx, by + bstephalf) == false) { if (jitterScale > 0.0) { Jitter2d(x - d, y, rxcx0y1, rycx0y1); trace(x - d + (rxcx0y1 * jitterScale), y + (rycx0y1 * jitterScale), GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); } else trace(x - d, y, GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); buffer.SetSample(bx, by + bstephalf, col); GetViewDataPtr()->Stats()[Number_Of_Samples]++; Cooperate(); } // Trace: // o*o // ooo // ooo if(buffer.Sampled(bx + bstephalf, by) == false) { if (jitterScale > 0.0) { Jitter2d(x, y - d, rxcx1y0, rycx1y0); trace(x + (rxcx1y0 * jitterScale), y - d + (rycx1y0 * jitterScale), GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); } else trace(x, y - d, GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); buffer.SetSample(bx + bstephalf, by, col); GetViewDataPtr()->Stats()[Number_Of_Samples]++; Cooperate(); } // Trace: // ooo // oo* // ooo if(buffer.Sampled(bx + bstep, by + bstephalf) == false) { if (jitterScale > 0.0) { Jitter2d(x + d, y, rxcx2y1, rycx2y1); trace(x + d + (rxcx2y1 * jitterScale), y + (rycx2y1 * jitterScale), GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); } else trace(x + d, y, GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); buffer.SetSample(bx + bstep, by + bstephalf, col); GetViewDataPtr()->Stats()[Number_Of_Samples]++; Cooperate(); } // Trace: // ooo // ooo // o*o if(buffer.Sampled(bx + bstephalf, by + bstep) == false) { if (jitterScale > 0.0) { Jitter2d(x, y + d, rxcx1y2, rycx1y2); trace(x + (rxcx1y2 * jitterScale), y + d + (rycx1y2 * jitterScale), GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); } else trace(x, y + d, GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); buffer.SetSample(bx + bstephalf, by + bstep, col); GetViewDataPtr()->Stats()[Number_Of_Samples]++; Cooperate(); } // Trace: // ooo // o*o // ooo if(buffer.Sampled(bx + bstephalf, by + bstephalf) == false) { if (jitterScale > 0.0) { Jitter2d(x, y, rxcx1y1, rycx1y1); trace(x + (rxcx1y1 * jitterScale), y + (rycx1y1 * jitterScale), GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); } else trace(x, y, GetViewData()->GetWidth(), GetViewData()->GetHeight(), col); buffer.SetSample(bx + bstephalf, by + bstephalf, col); GetViewDataPtr()->Stats()[Number_Of_Samples]++; Cooperate(); } // Subdivide Input: // ++o // ++o // ooo // Subdivide Output: // *o // oo SubdivideOnePixel(x - d2, y - d2, d2, bx, by, bstephalf, buffer, rcx0y0, level - 1); // Subdivide Input: // ooo // ++o // ++o // Subdivide Output: // oo // *o SubdivideOnePixel(x - d2, y + d2, d2, bx, by + bstephalf, bstephalf, buffer, rcx0y1, level - 1); // Subdivide Input: // o++ // o++ // ooo // Subdivide Output: // o* // oo SubdivideOnePixel(x + d2, y - d2, d2, bx + bstephalf, by, bstephalf, buffer, rcx1y0, level - 1); // Subdivide Input: // ooo // o++ // o++ // Subdivide Output: // oo // o* SubdivideOnePixel(x + d2, y + d2, d2, bx + bstephalf, by + bstephalf, bstephalf, buffer, rcx1y1, level - 1); result = (rcx0y0 + rcx0y1 + rcx1y0 + rcx1y1) / 4.0; } else { result = (cx0y0 + cx0y2 + cx2y0 + cx2y2) / 4.0; } } }
agpl-3.0
pgorod/SuiteCRM
modules/AOW_Actions/actions/actionCreateRecord.php
19741
<?php /** * * 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 - 2018 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 [email protected]. * * 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". */ require_once 'modules/AOW_Actions/actions/actionBase.php'; class actionCreateRecord extends actionBase { /** * @return array */ public function loadJS() { return array('modules/AOW_Actions/actions/actionCreateRecord.js'); } /** * @param $line * @param SugarBean|null $bean * @param array $params * @return string */ public function edit_display($line, SugarBean $bean = null, $params = array()) { global $app_list_strings; $modules = $app_list_strings['aow_moduleList']; $checked = 'CHECKED'; if (isset($params['relate_to_workflow']) && !$params['relate_to_workflow']) { $checked = ''; } $html = "<table border='0' cellpadding='0' cellspacing='0' width='100%' data-workflow-action='create-record'>"; $html .= '<tr>'; $html .= '<td id="name_label" class="name_label" scope="row" valign="top"><label>' . translate('LBL_RECORD_TYPE', 'AOW_Actions') . '</label>:<span class="required"> *</span>&nbsp;&nbsp;'; $html .= "<select name='aow_actions_param[".$line."][record_type]' id='aow_actions_param_record_type".$line."' onchange='show_crModuleFields($line);'>".get_select_options_with_id($modules, $params['record_type']). '</select></td>'; $html .= '<td id="relate_label" class="relate_label" scope="row" valign="top"><label>' . translate('LBL_RELATE_WORKFLOW', 'AOW_Actions') . '</label>:'; $html .= "<input type='hidden' name='aow_actions_param[".$line."][relate_to_workflow]' value='0' >"; $html .= "<input type='checkbox' id='aow_actions_param[".$line."][relate_to_workflow]' name='aow_actions_param[".$line."][relate_to_workflow]' value='1' $checked></td>"; $html .= '</tr>'; $html .= '<tr>'; $html .= '<td colspan="4" scope="row"><table id="crLine' . $line . '_table" width="100%" class="lines"></table></td>'; $html .= '</tr>'; $html .= '<tr>'; $html .= '<td colspan="4" scope="row"><input type="button" tabindex="116" style="display:none" class="button" value="'.translate( 'LBL_ADD_FIELD', 'AOW_Actions' ).'" id="addcrline'.$line.'" onclick="add_crLine('.$line.')" /></td>'; $html .= '</tr>'; $html .= '<tr>'; $html .= '<td colspan="4" scope="row"><table id="crRelLine'.$line.'_table" width="100%" class="relationship"></table></td>'; $html .= '</tr>'; $html .= '<tr>'; $html .= '<td colspan="4" scope="row"><input type="button" tabindex="116" style="display:none" class="button" value="'.translate( 'LBL_ADD_RELATIONSHIP', 'AOW_Actions' ).'" id="addcrrelline'.$line.'" onclick="add_crRelLine('.$line.')" /></td>'; $html .= '</tr>'; if (isset($params['record_type']) && $params['record_type'] != '') { require_once 'modules/AOW_WorkFlow/aow_utils.php'; $html .= "<script id ='aow_script".$line."'>"; $html .= 'cr_fields[' . $line . '] = "' . trim(preg_replace( '/\s+/', ' ', getModuleFields( $params['record_type'], 'EditView', '', array(), array('email1', 'email2') ) )) . '";'; $html .= 'cr_relationships[' . $line . '] = "' . trim(preg_replace( '/\s+/', ' ', getModuleRelationships($params['record_type']) )) . '";'; $html .= 'cr_module[' .$line. '] = "' .$params['record_type']. '";'; if (isset($params['field'])) { foreach ($params['field'] as $key => $field) { if (is_array($params['value'][$key])) { $params['value'][$key] = json_encode($params['value'][$key]); } $html .= "load_crline('".$line."','".$field."','".str_replace(array("\r\n","\r","\n"), ' ', $params['value'][$key])."','".$params['value_type'][$key]."');"; } } if (isset($params['rel'])) { foreach ($params['rel'] as $key => $field) { if (is_array($params['rel_value'][$key])) { $params['rel_value'][$key] = json_encode($params['rel_value'][$key]); } $html .= "load_crrelline('".$line."','".$field."','".$params['rel_value'][$key]."','".$params['rel_value_type'][$key]."');"; } } $html .= '</script>'; } return $html; } /** * @param SugarBean $bean * @param array $params * @param bool $in_save * @return bool */ public function run_action(SugarBean $bean, $params = array(), $in_save = false) { global $beanList; if (isset($params['record_type']) && $params['record_type'] != '') { if ($beanList[$params['record_type']]) { $record = new $beanList[$params['record_type']](); $this->set_record($record, $bean, $params); $this->set_relationships($record, $bean, $params); if (isset($params['relate_to_workflow']) && $params['relate_to_workflow']) { require_once 'modules/Relationships/Relationship.php'; $key = Relationship::retrieve_by_modules($bean->module_dir, $record->module_dir, DBManagerFactory::getInstance()); if (!empty($key)) { foreach ($bean->field_defs as $field=>$def) { if ($def['type'] == 'link' && !empty($def['relationship']) && $def['relationship'] == $key) { $bean->load_relationship($field); $bean->$field->add($record->id); break; } } } } return true; } } return false; } /** * @param SugarBean $record * @param SugarBean $bean * @param array $params * @param bool $in_save */ public function set_record(SugarBean $record, SugarBean $bean, $params = array(), $in_save = false) { global $app_list_strings, $timedate; $record_vardefs = $record->getFieldDefinitions(); if (isset($params['field'])) { foreach ($params['field'] as $key => $field) { if ($field === '') { continue; } $value = ''; switch ($params['value_type'][$key]) { case 'Field': if ($params['value'][$key] === '') { continue 2; } $fieldName = $params['value'][$key]; $data = $bean->field_defs[$fieldName]; switch ($data['type']) { case 'double': case 'decimal': case 'currency': case 'float': case 'uint': case 'ulong': case 'long': case 'short': case 'tinyint': case 'int': $value = format_number($bean->$fieldName); break; case 'relate': if (isset($data['id_name']) && $record_vardefs[$field]['type'] === 'relate') { $idName = $data['id_name']; $value = $bean->$idName; } else { $value = $bean->$fieldName; } break; default: $value = $bean->$fieldName; break; } break; case 'Date': $dformat = 'Y-m-d H:i:s'; if ($record_vardefs[$field]['type'] === 'date') { $dformat = 'Y-m-d'; } switch ($params['value'][$key][3]) { case 'business_hours': require_once 'modules/AOBH_BusinessHours/AOBH_BusinessHours.php'; $businessHours = new AOBH_BusinessHours(); $dateToUse = $params['value'][$key][0]; $sign = $params['value'][$key][1]; $amount = $params['value'][$key][2]; if ($sign !== 'plus') { $amount = 0-$amount; } if ($dateToUse === 'now') { $value = $businessHours->addBusinessHours($amount); } elseif ($dateToUse === 'field') { $dateToUse = $params['field'][$key]; $value = $businessHours->addBusinessHours($amount, $timedate->fromDb($bean->$dateToUse)); } else { $value = $businessHours->addBusinessHours($amount, $timedate->fromDb($bean->$dateToUse)); } $value = $timedate->asDb($value); break; default: if ($params['value'][$key][0] === 'now') { $date = gmdate($dformat); } elseif ($params['value'][$key][0] === 'field') { $dateToUse = $params['field'][$key]; $date = $record->$dateToUse; } elseif ($params['value'][$key][0] === 'today') { $date = $params['value'][$key][0]; } else { $dateToUse = $params['value'][$key][0]; $date = $bean->$dateToUse; } if ($params['value'][$key][1] !== 'now') { $value = date($dformat, strtotime($date . ' '.$app_list_strings['aow_date_operator'][$params['value'][$key][1]].$params['value'][$key][2].' '.$params['value'][$key][3])); } else { $value = date($dformat, strtotime($date)); } break; } break; case 'Round_Robin': case 'Least_Busy': case 'Random': switch ($params['value'][$key][0]) { case 'security_group': require_once 'modules/SecurityGroups/SecurityGroup.php'; $security_group = new SecurityGroup(); $security_group->retrieve($params['value'][$key][1]); $group_users = $security_group->get_linked_beans('users', 'User'); $users = array(); $r_users = array(); if ($params['value'][$key][2] != '') { require_once 'modules/ACLRoles/ACLRole.php'; $role = new ACLRole(); $role->retrieve($params['value'][$key][2]); $role_users = $role->get_linked_beans('users', 'User'); foreach ($role_users as $role_user) { $r_users[$role_user->id] = $role_user->name; } } foreach ($group_users as $group_user) { if ($params['value'][$key][2] != '' && !isset($r_users[$group_user->id])) { continue; } $users[$group_user->id] = $group_user->name; } break; case 'role': require_once 'modules/ACLRoles/ACLRole.php'; $role = new ACLRole(); $role->retrieve($params['value'][$key][2]); $role_users = $role->get_linked_beans('users', 'User'); $users = array(); foreach ($role_users as $role_user) { $users[$role_user->id] = $role_user->name; } break; case 'all': default: $users = get_user_array(false); break; } // format the users array $users = array_values(array_flip($users)); if (empty($users)) { $value = ''; } elseif (count($users) == 1) { $value = $users[0]; } else { switch ($params['value_type'][$key]) { case 'Round_Robin': $value = getRoundRobinUser($users, $this->id); break; case 'Least_Busy': $user_id = 'assigned_user_id'; if (isset($record_vardefs[$field]['id_name']) && $record_vardefs[$field]['id_name'] != '') { $user_id = $record_vardefs[$field]['id_name']; } $value = getLeastBusyUser($users, $user_id, $record); break; case 'Random': default: shuffle($users); $value = $users[0]; break; } } setLastUser($value, $this->id); break; case 'Value': default: $value = $params['value'][$key]; break; } if ($record_vardefs[$field]['type'] === 'relate' && isset($record_vardefs[$field]['id_name'])) { $field = $record_vardefs[$field]['id_name']; } $record->$field = $value; } } $bean_processed = isset($record->processed) ? $record->processed : false; if ($in_save) { global $current_user; $record->processed = true; $check_notify = $record->assigned_user_id != $current_user->id && $record->assigned_user_id != $record->fetched_row['assigned_user_id']; } else { $check_notify = $record->assigned_user_id != $record->fetched_row['assigned_user_id']; } $record->process_save_dates =false; $record->new_with_id = false; $record->save($check_notify); $record->processed = $bean_processed; } /** * @param SugarBean $record * @param SugarBean $bean * @param array $params */ public function set_relationships(SugarBean $record, SugarBean $bean, $params = array()) { $record_vardefs = $record->getFieldDefinitions(); require_once 'modules/Relationships/Relationship.php'; if (isset($params['rel'])) { foreach ($params['rel'] as $key => $field) { if ($field == '' || $params['rel_value'][$key] == '') { continue; } $relField = $params['rel_value'][$key]; switch ($params['rel_value_type'][$key]) { case 'Field': $data = $bean->field_defs[$relField]; if ($data['type'] == 'relate' && isset($data['id_name'])) { $relField = $data['id_name']; } $rel_id = $bean->$relField; break; default: $rel_id = $relField; break; } $def = $record_vardefs[$field]; if ($def['type'] == 'link' && !empty($def['relationship'])) { $record->load_relationship($field); $record->$field->add($rel_id); } } } } }
agpl-3.0
ByersHouse/crmwork
modules/bh_Realty/bh_Realty.php
3156
<?php /** * * 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 - 2017 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 [email protected]. * * 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". */ class bh_Realty extends Basic { public $new_schema = true; public $module_dir = 'bh_Realty'; public $object_name = 'bh_Realty'; public $table_name = 'bh_realty'; public $importable = false; public $id; public $name; public $date_entered; public $date_modified; public $modified_user_id; public $modified_by_name; public $created_by; public $created_by_name; public $description; public $deleted; public $created_by_link; public $realty_owner_pledge; public $modified_user_link; public $realty_type_ownership; public $realty_method_obtaining; public $realty_date_purchase; public $realty_property_type; public $assigned_user_id; public $assigned_user_name; public $assigned_user_link; public $SecurityGroups; public function bean_implements($interface) { switch($interface) { case 'ACL': return true; } return false; } }
agpl-3.0
VictorBersy/Foundry
db/schema.rb
1763
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20140529171932) do create_table "users", force: true do |t| t.string "email", default: "", null: false t.string "username" t.string "screen_name" t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at" t.datetime "updated_at" end add_index "users", ["email"], name: "index_users_on_email", unique: true add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true add_index "users", ["screen_name"], name: "index_users_on_screen_name", unique: true add_index "users", ["username"], name: "index_users_on_username", unique: true end
agpl-3.0
iwatendo/skybeje
src/Contents/Sender/GetProfileSender.ts
258
import Sender from "../../Base/Container/Sender"; /** * ユーザープロフィール要求 */ export default class GetProfileSender extends Sender { public static ID = "GetProfile"; constructor() { super(GetProfileSender.ID); } }
agpl-3.0
agibsonccc/startuphousebooking
src/main/java/com/startuphouse/booking/solr/SolrListener.java
1032
package com.startuphouse.booking.solr; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.solr.core.CoreContainer; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; public class SolrListener implements ServletContextListener{ @Override public void contextInitialized(ServletContextEvent servletContextEvent) { } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { ServletContext servletContext = null; WebApplicationContext springContext = null; CoreContainer multicoreContainer = null; servletContext = servletContextEvent.getServletContext(); springContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); multicoreContainer = (CoreContainer)springContext.getBean("multiCoreContainer"); if(multicoreContainer!=null){ multicoreContainer.shutdown(); } } }
agpl-3.0
epeios-q37/epeios
devel/strng/strng_test.cpp
1252
/* Copyright (C) 1999 Claude SIMON (http://q37.info/contact/). This file is part of the Epeios framework. The Epeios framework 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. The Epeios framework 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 the Epeios framework. If not, see <http://www.gnu.org/licenses/> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "strng.h" #include "err.h" #include "cio.h" using cio::CIn; using cio::COut; using cio::CErr; void Generic( int argc, char *argv[] ) { qRH qRB qRR qRT qRE } int main( int argc, char *argv[] ) { int ExitValue = EXIT_SUCCESS; qRFH qRFB COut << "Test of library " << STRNG_NAME << ' ' << __DATE__" "__TIME__"\n"; Generic( argc, argv ); qRFR ExitValue = EXIT_FAILURE; qRFT qRFE return ExitValue; }
agpl-3.0
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/source/dcma-util/src/main/java/com/ephesoft/dcma/util/EphesoftDateUtil.java
2427
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address [email protected]. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.dcma.util; import java.util.Calendar; /** * @author Ephesoft * */ public class EphesoftDateUtil { /** * @return */ public static Long getCurrentDateInMillis() { Calendar cal = Calendar.getInstance(); return cal.getTimeInMillis(); } /** * @return */ public static Long getOneYearAfterDateInMillis() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, 1); return cal.getTimeInMillis(); } }
agpl-3.0
donsunsoft/axelor-development-kit
axelor-core/src/main/java/com/axelor/script/AbstractScriptHelper.java
1855
/** * Axelor Business Solutions * * Copyright (C) 2005-2016 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.script; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.axelor.common.StringUtils; import com.google.common.base.Preconditions; public abstract class AbstractScriptHelper implements ScriptHelper { private ScriptBindings bindings; @Override public ScriptBindings getBindings() { return bindings; } @Override public void setBindings(ScriptBindings bindings) { this.bindings = bindings; } @Override public final boolean test(String expr) { if (StringUtils.isBlank(expr)) return true; Object result = eval(expr); if (result == null) return false; if (result instanceof Number && result.equals(0)) return false; if (result instanceof Boolean) return (Boolean) result; return true; } @Override public Object call(Object obj, String methodCall) { Preconditions.checkNotNull(obj); Preconditions.checkNotNull(methodCall); Pattern p = Pattern.compile("(\\w+)\\((.*?)\\)"); Matcher m = p.matcher(methodCall); if (!m.matches()) { return null; } return doCall(obj, methodCall); } protected abstract Object doCall(Object obj, String methodCall); }
agpl-3.0
vahnj/mastodon
app/javascript/flavours/glitch/reducers/user_lists.js
3469
import { FOLLOWERS_FETCH_SUCCESS, FOLLOWERS_EXPAND_SUCCESS, FOLLOWING_FETCH_SUCCESS, FOLLOWING_EXPAND_SUCCESS, FOLLOW_REQUESTS_FETCH_SUCCESS, FOLLOW_REQUESTS_EXPAND_SUCCESS, FOLLOW_REQUEST_AUTHORIZE_SUCCESS, FOLLOW_REQUEST_REJECT_SUCCESS, } from 'flavours/glitch/actions/accounts'; import { REBLOGS_FETCH_SUCCESS, FAVOURITES_FETCH_SUCCESS, } from 'flavours/glitch/actions/interactions'; import { BLOCKS_FETCH_SUCCESS, BLOCKS_EXPAND_SUCCESS, } from 'flavours/glitch/actions/blocks'; import { MUTES_FETCH_SUCCESS, MUTES_EXPAND_SUCCESS, } from 'flavours/glitch/actions/mutes'; import { Map as ImmutableMap, List as ImmutableList } from 'immutable'; const initialState = ImmutableMap({ followers: ImmutableMap(), following: ImmutableMap(), reblogged_by: ImmutableMap(), favourited_by: ImmutableMap(), follow_requests: ImmutableMap(), blocks: ImmutableMap(), mutes: ImmutableMap(), }); const normalizeList = (state, type, id, accounts, next) => { return state.setIn([type, id], ImmutableMap({ next, items: ImmutableList(accounts.map(item => item.id)), })); }; const appendToList = (state, type, id, accounts, next) => { return state.updateIn([type, id], map => { return map.set('next', next).update('items', list => list.concat(accounts.map(item => item.id))); }); }; export default function userLists(state = initialState, action) { switch(action.type) { case FOLLOWERS_FETCH_SUCCESS: return normalizeList(state, 'followers', action.id, action.accounts, action.next); case FOLLOWERS_EXPAND_SUCCESS: return appendToList(state, 'followers', action.id, action.accounts, action.next); case FOLLOWING_FETCH_SUCCESS: return normalizeList(state, 'following', action.id, action.accounts, action.next); case FOLLOWING_EXPAND_SUCCESS: return appendToList(state, 'following', action.id, action.accounts, action.next); case REBLOGS_FETCH_SUCCESS: return state.setIn(['reblogged_by', action.id], ImmutableList(action.accounts.map(item => item.id))); case FAVOURITES_FETCH_SUCCESS: return state.setIn(['favourited_by', action.id], ImmutableList(action.accounts.map(item => item.id))); case FOLLOW_REQUESTS_FETCH_SUCCESS: return state.setIn(['follow_requests', 'items'], ImmutableList(action.accounts.map(item => item.id))).setIn(['follow_requests', 'next'], action.next); case FOLLOW_REQUESTS_EXPAND_SUCCESS: return state.updateIn(['follow_requests', 'items'], list => list.concat(action.accounts.map(item => item.id))).setIn(['follow_requests', 'next'], action.next); case FOLLOW_REQUEST_AUTHORIZE_SUCCESS: case FOLLOW_REQUEST_REJECT_SUCCESS: return state.updateIn(['follow_requests', 'items'], list => list.filterNot(item => item === action.id)); case BLOCKS_FETCH_SUCCESS: return state.setIn(['blocks', 'items'], ImmutableList(action.accounts.map(item => item.id))).setIn(['blocks', 'next'], action.next); case BLOCKS_EXPAND_SUCCESS: return state.updateIn(['blocks', 'items'], list => list.concat(action.accounts.map(item => item.id))).setIn(['blocks', 'next'], action.next); case MUTES_FETCH_SUCCESS: return state.setIn(['mutes', 'items'], ImmutableList(action.accounts.map(item => item.id))).setIn(['mutes', 'next'], action.next); case MUTES_EXPAND_SUCCESS: return state.updateIn(['mutes', 'items'], list => list.concat(action.accounts.map(item => item.id))).setIn(['mutes', 'next'], action.next); default: return state; } };
agpl-3.0
piratas-ar/loomio
db/migrate/20151118022605_members_can_add_members_default_true.rb
231
class MembersCanAddMembersDefaultTrue < ActiveRecord::Migration[4.2] def change remove_column :groups, :members_invitable_by change_column :groups, :members_can_add_members, :boolean, default: true, null: false end end
agpl-3.0
afshinnj/php-mvc
assets/framework/ckeditor/plugins/preview/lang/es.js
228
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'preview', 'es', { preview: 'Vista Previa' } );
agpl-3.0
lafactura/datea-api
datea_api/apps/tag/search_indexes.py
1205
from haystack import indexes from tag.models import Tag class TagIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True, template_name="search/indexes/tag/tag_index.txt") tag = indexes.CharField(model_attr="tag", faceted=True) title = indexes.CharField(model_attr="title", null=True) obj_id = indexes.IntegerField(model_attr='pk') follow_count = indexes.IntegerField(model_attr="follow_count") dateo_count = indexes.IntegerField(model_attr="dateo_count") is_standalone = indexes.BooleanField() follow_key = indexes.CharField() rank = indexes.IntegerField(model_attr="rank") published = indexes.BooleanField() tag_auto = indexes.NgramField(model_attr='tag') def get_model(self): return Tag def prepare_tag(self, obj): return obj.tag.lower() def prepare_is_standalone(self, obj): return not obj.campaigns.count() and not obj.campaigns_secondary.count() def prepare_published(self, obj): return True def prepare_follow_key(self, obj): return 'tag.'+str(obj.pk) def index_queryset(self, using=None): return self.get_model().objects.all()
agpl-3.0
gnu-lorien/chummer-from-another
public/javascripts/allSkills.js
6605
ALL_SKILLS = [ { "name": "Archery", "linkedAttribute": "Agility" }, { "name": "Automatics", "linkedAttribute": "Agility" }, { "name": "Blades", "linkedAttribute": "Agility" }, { "name": "Clubs", "linkedAttribute": "Agility" }, { "name": "Escape Artist", "linkedAttribute": "Agility" }, { "name": "Exotic Melee Weapon (Specific)", "linkedAttribute": "Agility" }, { "name": "Exotic Ranged Weapon (Specific)", "linkedAttribute": "Agility" }, { "name": "Gunnery", "linkedAttribute": "Agility" }, { "name": "Gymnastics", "linkedAttribute": "Agility" }, { "name": "Heavy Weapons", "linkedAttribute": "Agility" }, { "name": "Locksmith", "linkedAttribute": "Agility" }, { "name": "Longarms", "linkedAttribute": "Agility" }, { "name": "Palming", "linkedAttribute": "Agility" }, { "name": "Pistols", "linkedAttribute": "Agility" }, { "name": "Sneaking", "linkedAttribute": "Agility" }, { "name": "Throwing Weapon", "linkedAttribute": "Agility" }, { "name": "Unarmed Combat", "linkedAttribute": "Agility" }, { "name": "Diving", "linkedAttribute": "Body" }, { "name": "Free-Fall", "linkedAttribute": "Body" }, { "name": "Pilot Aerospace", "linkedAttribute": "Reaction" }, { "name": "Pilot Aircraft", "linkedAttribute": "Reaction" }, { "name": "Pilot Walker", "linkedAttribute": "Reaction" }, { "name": "Pilot Exotic Vehicle (Specific)", "linkedAttribute": "Reaction" }, { "name": "Pilot Ground Craft", "linkedAttribute": "Reaction" }, { "name": "Pilot Watercraft", "linkedAttribute": "Reaction" }, { "name": "Running", "linkedAttribute": "Strength" }, { "name": "Swimming", "linkedAttribute": "Strength" }, { "name": "Con", "linkedAttribute": "Charisma" }, { "name": "Etiquette", "linkedAttribute": "Charisma" }, { "name": "Instruction", "linkedAttribute": "Charisma" }, { "name": "Intimidation", "linkedAttribute": "Charisma" }, { "name": "Leadership", "linkedAttribute": "Charisma" }, { "name": "Negotiation", "linkedAttribute": "Charisma" }, { "name": "Performance", "linkedAttribute": "Charisma" }, { "name": "Impersonation", "linkedAttribute": "Charisma" }, { "name": "Animal", "linkedAttribute": "Charisma" }, { "name": "Handling", "linkedAttribute": "Charisma" }, { "name": "Artisan", "linkedAttribute": "Intuition" }, { "name": "Assensing", "linkedAttribute": "Intuition" }, { "name": "Disguise", "linkedAttribute": "Intuition" }, { "name": "Interests Knowledge", "linkedAttribute": "Intuition" }, { "name": "Language", "linkedAttribute": "Intuition" }, { "name": "Navigation", "linkedAttribute": "Intuition" }, { "name": "Perception", "linkedAttribute": "Intuition" }, { "name": "Street Knowledge", "linkedAttribute": "Intuition" }, { "name": "Tracking", "linkedAttribute": "Intuition" }, { "name": "Academic Knowledge", "linkedAttribute": "Logic" }, { "name": "Aeronautics Mechanics", "linkedAttribute": "Logic" }, { "name": "Arcane", "linkedAttribute": "Logic" }, { "name": "Armorer", "linkedAttribute": "Logic" }, { "name": "Automotive Mechanic", "linkedAttribute": "Logic" }, { "name": "Biotechnology", "linkedAttribute": "Logic" }, { "name": "Chemistry", "linkedAttribute": "Logic" }, { "name": "Computer", "linkedAttribute": "Logic" }, { "name": "Cybertechnology", "linkedAttribute": "Logic" }, { "name": "Cybercombat", "linkedAttribute": "Logic" }, { "name": "Demolition", "linkedAttribute": "Logic" }, { "name": "Electronic Warfare", "linkedAttribute": "Logic" }, { "name": "First Aid", "linkedAttribute": "Logic" }, { "name": "Industrial Mechanics", "linkedAttribute": "Logic" }, { "name": "Hacking", "linkedAttribute": "Logic" }, { "name": "Hardware", "linkedAttribute": "Logic" }, { "name": "Medicine", "linkedAttribute": "Logic" }, { "name": "Nautical Mechanics", "linkedAttribute": "Logic" }, { "name": "Professional Knowledge", "linkedAttribute": "Logic" }, { "name": "Software", "linkedAttribute": "Logic" }, { "name": "Forgery", "linkedAttribute": "Logic" }, { "name": "Astral Combat", "linkedAttribute": "Willpower" }, { "name": "Survival", "linkedAttribute": "Willpower" }, { "name": "Alchemy", "linkedAttribute": "Magic" }, { "name": "Banishing", "linkedAttribute": "Magic" }, { "name": "Binding", "linkedAttribute": "Magic" }, { "name": "Counterspelling", "linkedAttribute": "Magic" }, { "name": "Ritual Spellcasting", "linkedAttribute": "Magic" }, { "name": "Spellcasting", "linkedAttribute": "Magic" }, { "name": "Summoning", "linkedAttribute": "Magic" }, { "name": "Enchanting", "linkedAttribute": "Magic" }, { "name": "Disenchanting", "linkedAttribute": "Magic" }, { "name": "Compiling", "linkedAttribute": "Resonance" }, { "name": "Decompiling", "linkedAttribute": "Resonance" }, { "name": "Registering", "linkedAttribute": "Resonance" } ]
agpl-3.0
danigm/sweetter
sweetter/ublogging/register.py
2271
from django.conf import settings from django.core.mail import send_mail from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from ublogging.models import Profile, User from ublogging.models import RegisterUserForm import flash def send_confirmation(user): subject = "sweetter 3.0 registry confirmation" profile = Profile.objects.get(user=user) from_email = settings.MSG_FROM vars = {'username': user.username, 'apikey': profile.apikey} message = settings.CONFIRMATION_MSG % vars to_email = user.email send_mail(subject, message, from_email, [to_email], fail_silently=False) def join(request): if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): user = form.save() user.is_active = False user.save() send_confirmation(user) flash.set_flash(request, "Thanks for register, you'll receive a confirmation email") form = RegisterUserForm() return render_to_response('join.html', { 'form': form, }, context_instance=RequestContext(request)) else: flash.set_flash(request, "Validation error", "error") return render_to_response('join.html', { 'form': form }, context_instance=RequestContext(request)) else: form = RegisterUserForm() return render_to_response('join.html', { 'form': form, }, context_instance=RequestContext(request)) def validate(request, apikey): try: profile = Profile.objects.get(apikey=apikey) profile.user.is_active = True profile.user.save() flash.set_flash(request, "User validated, now you can loggin") except: flash.set_flash(request, "Invalid apikey", "error") return HttpResponseRedirect(reverse('ublogging.views.index')) def adduser(username, password, email): u = User(username=username, email=email) u.set_password(password) u.is_active = True u.save() profile, new = Profile.objects.get_or_create(user=u) profile.save() return u
agpl-3.0
bikeindex/bikewise
app/controllers/api/v1/types.rb
1240
module API module V1 class Types < API::V1::Root include API::V1::Defaults resource :types do helpers do def find_selections if params[:include_user_created] && params[:include_user_created] != 'undefined' @selections = Selection.all else @selections = Selection.default end @selections end end desc "Return all the selections" params do optional :include_user_created, type: Boolean, default: 0, desc: 'Include user submitted types instead of default types.' end get do find_selections render @selections end desc "Return selections for a given type" params do requires :select_type, type: String, desc: 'Selection type', values: SELECTION_TYPES optional :include_user_created, type: Boolean, default: false, desc: 'Include user submitted types (instead of only default types)' end get ':select_type' do find_selections @selections = @selections.where(select_type: params[:select_type]) render @selections end end end end end
agpl-3.0
xepan/xepan
lib/TMail/Transport/PHPMailer.php
3545
<?php class TMail_Transport_PHPMailer extends TMail_Transport_SwiftMailer { /*public $PHPMailer = null; function init(){ parent::init(); require_once("PHPMailer/class.phpmailer.php"); $this->PHPMailer = $mail = new PHPMailer(true); $mail->IsSMTP(); $mail->SMTPDebug = 0; // enables SMTP debug information (for testing) $mail->SMTPAuthSecure = 'ssl'; $mail->AltBody = null; $mail->IsHTML(true); $mail->SMTPKeepAlive = true; } function send($to, $from, $subject, $body, $headers="",$ccs=array(), $bcc=array(), $skip_inlining_images=false, $read_confirmation_to=''){ $mail = $this->PHPMailer; $mail->ClearAllRecipients(); if(is_array($to)){ foreach ($to as $to_1) { $mail->AddAddress($to_1); } }else{ $mail->AddAddress($to); } if($ccs){ if(is_array($ccs)){ foreach ($ccs as $ccs_1) { $mail->AddCC($ccs_1); } }else{ $mail->AddCC($ccs); } } if($bcc){ if(is_array($bcc)){ foreach ($bcc as $bcc_1) { $mail->AddBCC($bcc_1); } }else{ $mail->AddBCC($bcc); } } if(!$skip_inlining_images){ $body = $this->convertImagesInline($body); } $mail->Subject = $subject; $mail->MsgHTML($body); $mail->SMTPAuth = $this->api->current_website['email_username']?true:false; // enable SMTP authentication $mail->Host = $this->api->current_website['email_host']; $mail->Port = $this->api->current_website['email_port']; $mail->Username = $this->api->current_website['email_username']; $mail->Password = $this->api->current_website['email_password']; if($this->add('Controller_EpanCMSApp')->emailSettings($mail) !== true){ $mail->AddReplyTo($this->api->current_website['email_reply_to'], $this->api->current_website['email_reply_to_name']); $mail->SetFrom($this->api->current_website['email_from'], $this->api->current_website['email_from_name']); } $mail->AddAddress($to); $mail->Subject = $subject; $mail->MsgHTML($body); foreach (explode("\n", $headers) as $h){ $mail->AddCustomHeader($h); } $mail->Send(); } function convertImagesInline(&$body){ // get all img tags preg_match_all('/<img.*?>/', $body, $matches); if (!isset($matches[0])) return; // foreach tag, create the cid and embed image $i = 1; foreach ($matches[0] as $img) { // make cid $id = 'img'.($i++); // replace image web path with local path preg_match('/src="(.*?)"/', $body, $m); if (!isset($m[1])) continue; $arr = parse_url($m[1]); if (!isset($arr['host']) || !isset($arr['path']))continue; // add $this->PHPMailer->AddEmbeddedImage(getcwd().'/'.$arr['path'], $id, 'attachment', 'base64', 'image/jpeg'); $body = str_replace($img, '<img alt="" src="cid:'.$id.'" style="border: none;" />', $body); } return $body; } function __destruct(){ $this->PHPMailer->SmtpClose(); }*/ }
agpl-3.0
lmaslag/test
engine/Shopware/Components/DummyPlugin/Bootstrap.php
1703
<?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. */ /** * Shopware DummyPlugin Bootstrap * * @category Shopware * @package Shopware\Components\DummyPlugin\Bootstrap * @copyright Copyright (c) shopware AG (http://www.shopware.de) */ abstract class Shopware_Components_DummyPlugin_Bootstrap extends Shopware_Components_Plugin_Bootstrap { /** * Returns the version of plugin as string. * * @return string */ public function getVersion() { return '0.0.1'; } /** * Returns capabilities */ public function getCapabilities() { return array( 'install' => true, 'update' => true, 'enable' => true, 'dummy' => true ); } }
agpl-3.0
SKIRT/SKIRT
SKIRTcore/BaryOctTreeNode.hpp
1789
/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #ifndef BARYOCTTREENODE_HPP #define BARYOCTTREENODE_HPP #include "OctTreeNode.hpp" ////////////////////////////////////////////////////////////////////// /** BaryOctTreeNode is a TreeNode subclass that represents nodes in an OctTreeDustGrid using barycentric subdivision. */ class BaryOctTreeNode : public OctTreeNode { public: /** This constructor creates a new barycentric octtree node with the specified father node, identifier, and spatial extent (defined by the coordinates of the corner points). The constructor sets the level of the new node to be one higher than the level of the father. If the pointer to the father is null, the level of the new cell is zero. */ BaryOctTreeNode(TreeNode* father, int id, const Box& extent); protected: /** This function creates a fresh new node of class BaryOctTreeNode, i.e. the same type as the receiving node. The arguments are the same as those for the constructor. Ownership for the new node is passed to the caller. */ virtual TreeNode* createnode(TreeNode* father, int id, const Box& extent); public: /** This function creates eight new nodes subdividing the node at the barycenter, and adds these new nodes as its own child nodes. It invokes createchildren_splitpoint() to accomplish its task. */ void createchildren(int id, const TreeNodeDensityCalculator* calc); }; ////////////////////////////////////////////////////////////////////// #endif // BARYOCTTREENODE_HPP
agpl-3.0
quikkian-ua-devops/will-financials
kfs-ar/src/main/java/org/kuali/kfs/module/ar/report/service/impl/ContractsGrantsReportHelperServiceImpl.java
15506
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.ar.report.service.impl; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRParameter; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import org.apache.commons.lang.time.DateUtils; import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAward; import org.kuali.kfs.kns.datadictionary.BusinessObjectEntry; import org.kuali.kfs.kns.service.DataDictionaryService; import org.kuali.kfs.krad.util.KRADConstants; import org.kuali.kfs.krad.util.ObjectUtils; import org.kuali.kfs.krad.util.UrlFactory; import org.kuali.kfs.module.ar.ArConstants; import org.kuali.kfs.module.ar.ArPropertyConstants; import org.kuali.kfs.module.ar.report.ContractsGrantsReportDataHolder; import org.kuali.kfs.module.ar.report.service.ContractsGrantsReportHelperService; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.KFSConstants.ReportGeneration; import org.kuali.kfs.sys.report.ReportInfo; import org.kuali.kfs.sys.service.ReportGenerationService; import org.kuali.rice.core.api.config.property.ConfigContext; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.core.api.search.SearchOperator; import org.kuali.rice.core.web.format.BooleanFormatter; import org.kuali.rice.core.web.format.CollectionFormatter; import org.kuali.rice.core.web.format.DateFormatter; import org.kuali.rice.core.web.format.Formatter; import org.kuali.rice.kew.api.KewApiConstants; import org.kuali.rice.kim.api.KimConstants; import org.kuali.rice.kim.api.identity.Person; import org.kuali.rice.kim.api.identity.PersonService; import org.kuali.rice.krad.bo.BusinessObject; import org.springframework.util.StringUtils; import java.io.ByteArrayOutputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; import java.util.Set; /** * A number of methods which help the C&G Billing reports build their PDFs and do look-ups */ public class ContractsGrantsReportHelperServiceImpl implements ContractsGrantsReportHelperService { private org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ContractsGrantsReportHelperServiceImpl.class); protected DataDictionaryService dataDictionaryService; protected ReportGenerationService reportGenerationService; protected ConfigurationService configurationService; protected DateTimeService dateTimeService; protected PersonService personService; /** * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsReportHelperService#generateReport(org.kuali.kfs.module.ar.report.ContractsGrantsReportDataHolder, org.kuali.kfs.sys.report.ReportInfo, java.io.ByteArrayOutputStream) */ @Override public String generateReport(ContractsGrantsReportDataHolder reportDataHolder, ReportInfo reportInfo, ByteArrayOutputStream baos) { Date runDate = new Date(); String reportFileName = reportInfo.getReportFileName(); String reportDirectory = reportInfo.getReportsDirectory(); String reportTemplateClassPath = reportInfo.getReportTemplateClassPath(); String reportTemplateName = reportInfo.getReportTemplateName(); ResourceBundle resourceBundle = reportInfo.getResourceBundle(); String subReportTemplateClassPath = reportInfo.getSubReportTemplateClassPath(); Map<String, String> subReports = reportInfo.getSubReports(); Map<String, Object> reportData = reportDataHolder.getReportData(); // check title and set if (ObjectUtils.isNull(reportData.get(KFSConstants.REPORT_TITLE))) { reportData.put(KFSConstants.REPORT_TITLE, reportInfo.getReportTitle()); } reportData.put(JRParameter.REPORT_RESOURCE_BUNDLE, resourceBundle); reportData.put(ReportGeneration.PARAMETER_NAME_SUBREPORT_DIR, subReportTemplateClassPath); reportData.put(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME, subReports); addParametersToReportData(reportData); String template = reportTemplateClassPath + reportTemplateName; String fullReportFileName = reportGenerationService.buildFullFileName(runDate, reportDirectory, reportFileName, ""); List<String> data = Arrays.asList(KFSConstants.EMPTY_STRING); JRDataSource dataSource = new JRBeanCollectionDataSource(data); reportGenerationService.generateReportToOutputStream(reportData, dataSource, template, baos); return reportFileName; } /** * In order to generate a report with the appropriate labels when KC CGB integration * is enabled we need to be able to pass some parameters to report generation template * instead of using the generic messages.properties values. The necessary values are * fetched from the data dictionary. */ public void addParametersToReportData(Map<String, Object> reportData) { BusinessObjectEntry boe = (BusinessObjectEntry) getDataDictionaryService().getDataDictionary().getBusinessObjectEntry(ContractsAndGrantsBillingAward.class.getName()); reportData.put("awardProposalId", boe.getAttributeDefinition("proposalNumber").getLabel()); reportData.put("agencySponsorCode", boe.getAttributeDefinition("agencyNumber").getLabel()); } /** * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsReportHelperService#getFieldNameForSorting(int, java.lang.String) */ @Override public String getFieldNameForSorting(int index, String businessObjectName) { BusinessObjectEntry boe = (BusinessObjectEntry) getDataDictionaryService().getDataDictionary().getBusinessObjectEntry(businessObjectName); List<String> lookupResultFields = boe.getLookupDefinition().getResultFieldNames(); return lookupResultFields.get(index); } /** * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsReportHelperService#getListOfValuesSortedProperties(java.util.List, java.lang.String) */ @Override public List<String> getListOfValuesSortedProperties(List list, String propertyName) { List<String> returnList = new ArrayList<String>(); for (Object object : list) { if (!returnList.contains(getPropertyValue(object, propertyName))) { returnList.add(getPropertyValue(object, propertyName)); } } return returnList; } /** * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsReportHelperService#getPropertyValue(java.lang.Object, java.lang.String) */ @Override public String getPropertyValue(Object object, String propertyName) { Object fieldValue = ObjectUtils.getPropertyValue(object, propertyName); return (ObjectUtils.isNull(fieldValue)) ? "" : StringUtils.trimAllWhitespace(fieldValue.toString()); } /** * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsReportHelperService#createTitleText(java.lang.Class) */ @Override public String createTitleText(Class<? extends BusinessObject> boClass) { String titleText = ""; final String titlePrefixProp = getConfigurationService().getPropertyValueAsString("title.inquiry.url.value.prependtext"); if (org.apache.commons.lang.StringUtils.isNotBlank(titlePrefixProp)) { titleText += titlePrefixProp + " "; } final String objectLabel = getDataDictionaryService().getDataDictionary().getBusinessObjectEntry(boClass.getName()).getObjectLabel(); if (org.apache.commons.lang.StringUtils.isNotBlank(objectLabel)) { titleText += objectLabel + " "; } return titleText; } /** * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsReportHelperService#formatByType(java.lang.Object, org.kuali.rice.core.web.format.Formatter) */ @Override public String formatByType(Object prop, Formatter preferredFormatter) { Formatter formatter = preferredFormatter; // for Booleans, always use BooleanFormatter if (prop instanceof Boolean) { formatter = new BooleanFormatter(); } // for Dates, always use DateFormatter if (prop instanceof Date) { formatter = new DateFormatter(); } // for collection, use the list formatter if a formatter hasn't been defined yet if (prop instanceof Collection && ObjectUtils.isNull(formatter)) { formatter = new CollectionFormatter(); } if (ObjectUtils.isNotNull(formatter)) { return (String) formatter.format(prop); } else { return prop.toString(); } } /** * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsReportHelperService#appendEndTimeToDate(java.lang.String) */ @Override public String correctEndDateForTime(String dateString) { try { final Date dateDate = DateUtils.addDays(dateTimeService.convertToDate(dateString), 1); final String newDateString = dateTimeService.toString(dateDate, KFSConstants.MONTH_DAY_YEAR_DATE_FORMAT); return newDateString; } catch (ParseException ex) { LOG.warn("invalid date format for errorDate: " + dateString); } return KFSConstants.EMPTY_STRING; } /** * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsReportHelperService#fixDateCriteria(java.lang.String, java.lang.String, boolean) */ @Override public String fixDateCriteria(String dateLowerBound, String dateUpperBound, boolean includeTime) { final String correctedUpperBound = includeTime && StringUtils.hasText(dateUpperBound) ? correctEndDateForTime(dateUpperBound) : dateUpperBound; if (StringUtils.hasText(dateLowerBound)) { if (StringUtils.hasText(dateUpperBound)) { return dateLowerBound + SearchOperator.BETWEEN.op() + correctedUpperBound; } else { return SearchOperator.GREATER_THAN_EQUAL.op() + dateLowerBound; } } else { if (StringUtils.hasText(dateUpperBound)) { return SearchOperator.LESS_THAN_EQUAL.op() + correctedUpperBound; } } return null; } /** * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsReportHelperService#lookupPrincipalIds(java.lang.String) */ @Override public Set<String> lookupPrincipalIds(String principalName) { if (!StringUtils.hasText(principalName)) { return new HashSet<String>(); } Map<String, String> fieldValues = new HashMap<String, String>(); fieldValues.put(KimConstants.UniqueKeyConstants.PRINCIPAL_NAME, principalName); final Collection<Person> peoples = getPersonService().findPeople(fieldValues); if (peoples == null || peoples.isEmpty()) { return new HashSet<String>(); } Set<String> principalIdsSet = new HashSet<String>(); for (Person person : peoples) { principalIdsSet.add(person.getPrincipalId()); } return principalIdsSet; } @Override public String getDocSearchUrl(String docId) { String baseUrl = ConfigContext.getCurrentContextConfig().getKEWBaseURL() + "/" + KewApiConstants.DOC_HANDLER_REDIRECT_PAGE; Properties parameters = new Properties(); parameters.put(KewApiConstants.COMMAND_PARAMETER, KewApiConstants.DOCSEARCH_COMMAND); parameters.put(KewApiConstants.DOCUMENT_ID_PARAMETER, docId); String docSearchUrl = UrlFactory.parameterizeUrl(baseUrl, parameters); return docSearchUrl; } @Override public String getInitiateCollectionActivityDocumentUrl(String proposalNumber, String invoiceNumber) { String initiateUrl = KRADConstants.EMPTY_STRING; Properties parameters = new Properties(); parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, KFSConstants.DOC_HANDLER_METHOD); if (StringUtils.hasText(proposalNumber)) { parameters.put(ArPropertyConstants.ContractsGrantsCollectionActivityDocumentFields.SELECTED_PROPOSAL_NUMBER, proposalNumber); } parameters.put(ArPropertyConstants.ContractsGrantsCollectionActivityDocumentFields.SELECTED_INVOICE_DOCUMENT_NUMBER, invoiceNumber); parameters.put(KFSConstants.PARAMETER_COMMAND, KFSConstants.INITIATE_METHOD); parameters.put(KFSConstants.DOCUMENT_TYPE_NAME, ArConstants.ArDocumentTypeCodes.CONTRACTS_GRANTS_COLLECTION_ACTIVTY); final String baseUrl = StringUtils.hasText(proposalNumber) ? getBaseContractsGrantsCollectionActivityDocumentUrl() : KFSConstants.EMPTY_STRING; initiateUrl = UrlFactory.parameterizeUrl(baseUrl, parameters); return initiateUrl; } /** * @return the base url for the contracts & grants collection activity document */ protected String getBaseContractsGrantsCollectionActivityDocumentUrl() { return ArConstants.MultipleValueReturnActions.CONTRACTS_GRANTS_COLLECTION_ACTIVITY_INVOICES; } public DataDictionaryService getDataDictionaryService() { return dataDictionaryService; } public void setDataDictionaryService(DataDictionaryService dataDictionaryService) { this.dataDictionaryService = dataDictionaryService; } /** * @return reportGenerationService */ public ReportGenerationService getReportGenerationService() { return reportGenerationService; } /** * @param reportGenerationService */ public void setReportGenerationService(ReportGenerationService reportGenerationService) { this.reportGenerationService = reportGenerationService; } public ConfigurationService getConfigurationService() { return configurationService; } public void setConfigurationService(ConfigurationService configurationService) { this.configurationService = configurationService; } public DateTimeService getDateTimeService() { return dateTimeService; } public void setDateTimeService(DateTimeService dateTimeService) { this.dateTimeService = dateTimeService; } public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } }
agpl-3.0
simvesel/wsh-lib
src/lib/sys_utils.js
8718
/* Copyright © 2014 — 2016 Svyatoslav Skriplyonok. All rights reserved. Licensed under the GNU AFFERO GENERAL PUBLIC LICENSE, Version 3 License: https://github.com/simvesel/wsh-lib/blob/master/LICENSE */ "use strict"; g_cApp.iMaxPropertyDeepForPrintFunction = 7; g_cApp.xasMsgGeneralTitle = g_cApp.xasAppName + ": "; String.prototype.repeat = function( miTimes ) { for( var e = ''; e.length < miTimes; ) { e += this; } return e; }; function recursive_property( obj, masPath, iDeep ) { if( iDeep === g_cApp.iMaxPropertyDeepForPrintFunction ) return masPath + "\n\tToo large object..."; var masCurr = masPath; // if( Object.prototype.toString.call( obj ) === '[object Object]' ) if( obj !== null && typeof obj !== 'undefined' ) { for( var key in obj ) { var mcVal = obj[ key ]; if( typeof mcVal === 'string' ) { masPath += '\n"' + key + '":"' + mcVal + '"'; } else if( typeof mcVal === 'function' ) { masPath += '\n"' + key + '":\tFUNCTION'; } else if( typeof mcVal !== 'object' || mcVal === null ) { masPath += '\n"' + key + '":\t' + mcVal; } else { ++iDeep; masPath += "\n" + recursive_property( mcVal, masCurr + "." + key, iDeep ); masPath += "\n" + masCurr; } } } return masPath; } function print_recursive_property( mcObj, iGlobDeep ) { iGlobDeep = iGlobDeep || 7; g_cApp.iMaxPropertyDeepForPrintFunction = iGlobDeep; return echo( recursive_property( mcObj, "_ROOT_", 0 ) ); } function fn_try_catch( fn_name ) { try { // echo( "size input args", arguments[1], arguments[4] ); var mvArgs = []; if( arguments.length > 1 ) { var i = arguments.length - 2; do { mvArgs[ i ] = arguments[ i+1 ]; } while( i-- > 0 ); // echo( "mvArgs", mvArgs ); } return fn_name.apply( g_cGlobal, mvArgs ); } catch( mcEx ) { print_recursive_property( mcEx ); } } // JScript Object for store VBScript code Proxy g_cApp.vbs = {}; g_cApp.vbs.objProxy = new ActiveXObject( "SLV.VBS.Proxy" ); /** TODO windows 7 & IE 11: AppActivate don`t set focus on IE prompt window vbscript: InputBox( Message, Title, Value ) ie html page ie hta applictaion */ /* reg replace (\w+)[, ]* \1 = (typeof \1 === 'undefined') ? null : \1; */ g_cApp.vbs.prompt = function( PromptText, DefaultValue, Title, iXPos, iYPos, Helpfile, iContext ) { Title = (typeof Title === 'undefined' || Title === null) ? "prompt..." : Title; Title = g_cApp.xasMsgGeneralTitle + Title /* DefaultValue = (typeof DefaultValue === 'undefined') ? null : DefaultValue; iXPos = (typeof iXPos === 'undefined') ? null : iXPos; iYPos = (typeof iYPos === 'undefined') ? null : iYPos; Helpfile = (typeof Helpfile === 'undefined') ? null : Helpfile; Context = (typeof Context === 'undefined') ? null : Context; */ var mRes = g_cApp.vbs.objProxy.inner_hidden_prompt( PromptText, Title, DefaultValue, iXPos, iYPos, Helpfile, iContext ); if( typeof mRes === "undefined" ) { return null; } return mRes; }; /** * The following constants are used with the MsgBox function to * identify what buttons and icons appear on a message box and which * button is the default. */ g_cApp.vbs.OKOnly = 0; // Display OK button only. g_cApp.vbs.OKCancel = 1; // Display OK and Cancel buttons. g_cApp.vbs.AbortRetryIgnore = 2; // Display Abort, Retry, and Ignore buttons. g_cApp.vbs.YesNoCancel = 3; // Display Yes, No, and Cancel buttons. g_cApp.vbs.YesNo = 4; // Display Yes and No buttons. g_cApp.vbs.RetryCancel = 5; // Display Retry and Cancel buttons. g_cApp.vbs.Critical = 16; // Display Critical Message icon. g_cApp.vbs.Question = 32; // Display Warning Query icon. g_cApp.vbs.Exclamation = 48; // Display Warning Message icon. g_cApp.vbs.Information = 64; // Display Information Message icon. g_cApp.vbs.DefaultButton1 = 0; // First button is default. g_cApp.vbs.DefaultButton2 = 256; // Second button is default. g_cApp.vbs.DefaultButton3 = 512; // Third button is default. g_cApp.vbs.DefaultButton4 = 768; // Fourth button is default. g_cApp.vbs.ApplicationModal = 0; // Application modal; the user must respond to the message box before continuing work in the current application. g_cApp.vbs.SystemModal = 4096; // System modal; all applications are suspended until the user responds to the message box. /** * The following constants are used with the MsgBox function to * identify which button a user has selected. */ g_cApp.vbs.OK = 1; // OK g_cApp.vbs.Cancel = 2; // Cancel g_cApp.vbs.Abort = 3; // Abort g_cApp.vbs.Retry = 4; // Retry g_cApp.vbs.Ignore = 5; // Ignore g_cApp.vbs.Yes = 6; // Yes g_cApp.vbs.No = 7; // No g_cApp.vbs.msgbox = function( PromptText, iButtons, Title, Helpfile, iContext ) { Title = (typeof Title === 'undefined' || Title === null) ? "question/message..." : Title; Title = g_cApp.xasMsgGeneralTitle + Title iButtons = (typeof iButtons === 'undefined' || iButtons === null) ? (g_cApp.vbs.YesNoCancel | g_cApp.vbs.DefaultButton2 | g_cApp.vbs.Question) : iButtons; var mRes = g_cApp.vbs.objProxy.inner_hidden_MsgBox( PromptText, iButtons, Title, Helpfile, iContext ); return mRes; }; //g_cApp.vbs.msgbox( "Are you terminator?" ); //var g_tst = new ActiveXObject( "InputDlg.Dialog" ); //echo( g_tst.InputBox( "==mes==", "==title==", "@" ) ); g_cApp.cacheRegExp = {}; // https://gist.github.com/dperini/729294 g_cApp.cacheRegExp.url = new RegExp ( "^(" + // protocol identifier "(?:(?:https?|ftps?)://)" + // user:pass authentication "(?:\\S+(?::\\S*)?@)?" + "(?:" + // IP address exclusion // private & local networks "(?!(?:10|127)(?:\\.\\d{1,3}){3})" + "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" + "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + // IP address dotted notation octets // excludes loopback network 0.0.0.0 // excludes reserved space >= 224.0.0.0 // excludes network & broacast addresses // (first & last IP address of each class) "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" + // host name "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" + // domain name "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" + // TLD identifier "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + // TLD may end with dot "\\.?" + ")" + // port number "(?::\\d{2,5})?" + // resource path "(?:[/?#]\\S*)?" + "|magnet:\\?xt=urn:btih:[0-9a-f]{40}.*)" + "$", "i" ); // A helper function to view a prompt window function fn_exec_ie_prompt( mcData ) { mcData.xcOut_val = null; /* return false; var oIE = g_ws.CreateObject( "InternetExplorer.Application" ); oIE.navigate( "about:blank" ); oIE.Visible = 0; oIE.Document.title = mcData.xasCaption; while( oIE.Busy ) { g_ws.sleep( 50 ); } g_ws.sleep( 50 ); //print_recursive_property( oIE ); var obj = oIE.Document.Script; //g_sh.AppActivate( "iexplore.exe" ); //g_sh.AppActivate( "Internet Explorer" ); //g_sh.AppActivate( oIE.Document.title ); //g_sh.AppActivate( "Microsoft Internet Explorer" ); //g_sh.AppActivate( "Запрос пользователю" ); mcData.xcOut_val = obj.prompt( mcData.xasCaption, mcData.xcIn_val ); // mcData.xcOut_val = null; oIE.Quit(); */ mcData.xcOut_val = g_cApp.vbs.prompt( mcData.xasCaption, mcData.xcIn_val ); if( mcData.xcOut_val === null ) { return false; } if( typeof mcData.xcOut_val !== 'string' ) { mcData.xcOut_val = "" + mcData.xcOut_val; } if( typeof mcData.xasValidRule === 'undefined' ) { mcData.xasValidRule = ""; } var masRegExp; switch( mcData.xasValidRule ) { case 'dec': case 'num': mcData.xcOut_val = parseFloat( mcData.xcOut_val ); return true; case 'nat': masRegExp = /^[1-9]\d*$/; break; case 'int': masRegExp = /^(\+|-)?\d+$/; break; case 'url': // /^(https?|ftps?):\/\/.+$/; masRegExp = g_cApp.cacheRegExp.url; break; default: { if( mcData.xasValidRule.length === 0 ) { masRegExp = /^.*$/; } else { masRegExp = new RegExp( mcData.xasValidRule ); } } } // throw new Error( 69, "Value incorrect \"" + masRegExp.toString() + "\"" ); // echo( "BEFORE: masRegExp.test( mcData.xcOut_val );" ); // print_recursive_property( masRegExp ); // var mmm = masRegExp.test( mcData.xcOut_val ); // echo( "BEFORE: return mmm;" ); // return mmm; return masRegExp.test( mcData.xcOut_val ); } function g_validation_prompt( mcData ) { try { return fn_exec_ie_prompt( mcData ); } catch( err ) { mcData.xcErr = err; return false; } }
agpl-3.0
UM-USElab/gradecraft-development
app/models/concerns/copyable.rb
680
require_relative "../copy_validator" # NOTE: If at any point we add additional associations for copying, the # validation schema needs to be updated in the CopyValidator class module Copyable extend ActiveSupport::Concern def copy(attributes={}, lookup_store=nil) lookup_store ||= ModelCopierLookups.new copy = self.dup copy.copy_attributes(attributes) # call save so we have an id on the copy to store copy.save lookup_store.store(self, copy) copy end def copy_attributes(attributes) attributes.each do |name, value| method = "#{name}=" if self.respond_to? method self.send method, value end end end end
agpl-3.0
bsolano/sivio
src/Model/Table/ExternalReferencesTable.php
1828
<?php namespace App\Model\Table; use App\Model\Entity\ExternalReference; use Cake\ORM\Query; use Cake\ORM\RulesChecker; use Cake\ORM\Table; use Cake\Validation\Validator; /** * ExternalReferences Model * * @property \Cake\ORM\Association\BelongsTo $People */ class ExternalReferencesTable extends Table { /** * Initialize method * * @param array $config The configuration for the Table. * @return void */ public function initialize(array $config) { parent::initialize($config); $this->table('external_references'); $this->displayField('id'); $this->primaryKey('id'); $this->addBehavior('Timestamp'); $this->belongsTo('People', [ 'foreignKey' => 'person_id' ]); } /** * Default validation rules. * * @param \Cake\Validation\Validator $validator Validator instance. * @return \Cake\Validation\Validator */ public function validationDefault(Validator $validator) { $validator ->integer('id') ->allowEmpty('id', 'create'); $validator ->allowEmpty('receptor'); $validator ->allowEmpty('telefono'); $validator ->allowEmpty('direccion'); $validator ->allowEmpty('observacion'); $validator ->allowEmpty('persona'); return $validator; } /** * Returns a rules checker object that will be used for validating * application integrity. * * @param \Cake\ORM\RulesChecker $rules The rules object to be modified. * @return \Cake\ORM\RulesChecker */ public function buildRules(RulesChecker $rules) { $rules->add($rules->existsIn(['person_id'], 'People')); return $rules; } }
agpl-3.0
CloCkWeRX/growstuff
spec/views/crops/hierarchy.html.haml_spec.rb
986
## DEPRECATION NOTICE: Do not add new tests to this file! ## ## View and controller tests are deprecated in the Growstuff project. ## We no longer write new view and controller tests, but instead write ## feature tests (in spec/features) using Capybara (https://github.com/jnicklas/capybara). ## These test the full stack, behaving as a browser, and require less complicated setup ## to run. Please feel free to delete old view/controller tests as they are reimplemented ## in feature tests. ## ## If you submit a pull request containing new view or controller tests, it will not be ## merged. require 'rails_helper' describe "crops/hierarchy" do before(:each) do controller.stub(:current_user) { nil } @tomato = FactoryGirl.create(:tomato) @roma = FactoryGirl.create(:crop, name: 'Roma tomato', parent: @tomato) assign(:crops, [@tomato, @roma]) render end it "shows crop hierarchy" do assert_select "ul>li>ul>li", text: @roma.name end end
agpl-3.0
sharidas/core
apps/files/l10n/lt_LT.js
7627
OC.L10N.register( "files", { "Storage is temporarily not available" : "Saugykla yra laikinai neprieinama", "Storage invalid" : "Saugykla neteisinga", "Unknown error" : "Neatpažinta klaida", "All files" : "Visi failai", "Saved" : "Išsaugoti", "File could not be found" : "Nepavyko rasti failo", "Home" : "Namų", "Close" : "Užverti", "Favorites" : "Mėgstamiausi", "Could not create folder \"{dir}\"" : "Nepavyko sukurti aplanko \"{dir}\"", "Upload cancelled." : "Įkėlimas atšauktas.", "Unable to upload {filename} as it is a directory or has 0 bytes" : "Nepavyksta įkelti {filename}, nes tai katalogas arba yra 0 baitų dydžio", "Not enough free space, you are uploading {size1} but only {size2} is left" : "Nepakanka laisvos vietos. Keliate {size1}, bet tik {size2} yra likę", "Uploading..." : "Įkeliama...", "..." : "...", "{loadedSize} of {totalSize} ({bitrate})" : "{loadedSize} iš {totalSize} ({bitrate})", "File upload is in progress. Leaving the page now will cancel the upload." : "Failo įkėlimas pradėtas. Jei paliksite šį puslapį, įkėlimas nutrūks.", "Actions" : "Veiksmai", "Download" : "Atsisiųsti", "Rename" : "Pervadinti", "Delete" : "Ištrinti", "Disconnect storage" : "Atjungti saugyklą", "Unshare" : "Nebesidalinti", "Files" : "Failai", "Details" : "Informacija", "Select" : "Pasirinkiti", "Pending" : "Laukiantis", "Unable to determine date" : "Nepavyksta nustatyti datos", "Invalid path" : "Netinkamas kelias", "This operation is forbidden" : "Ši operacija yra uždrausta", "This directory is unavailable, please check the logs or contact the administrator" : "Katalogas nepasiekiamas, prašome peržiūrėti žurnalo įrašus arba susisiekti su administratoriumi", "Could not move \"{file}\", target exists" : "Nepavyko perkelti \"{file}\", toks jau egzistuoja", "Could not move \"{file}\"" : "Nepavyko perkelti \"{file}\"", "{newName} already exists" : "{newName} jau egzistuoja", "Could not rename \"{fileName}\", it does not exist any more" : "Nepavyko pervadinti failo \"{fileName}\", nes jis jau nebeegzistuoja", "The name \"{targetName}\" is already used in the folder \"{dir}\". Please choose a different name." : "Pavadinimas \"{targetName}\" jau naudojamas aplanke \"{dir}\". Prašome pasirinkti kitokį pavadinimą.", "Could not rename \"{fileName}\"" : "Nepavyko pervadinti failo \"{fileName}\"", "Could not create file \"{file}\"" : "Nepavyko sukurti failo \"{file}\"", "Could not create file \"{file}\" because it already exists" : "Nepavyko sukurti failo \"{file}\" - failas su tokiu pavadinimu jau egzistuoja", "Could not create folder \"{dir}\" because it already exists" : "Nepavyko sukurti aplanko \"{dir}\"- aplankas su tokiu pavadinimu jau egzistuoja", "Error deleting file \"{fileName}\"." : "Klaida trinant failą \"{fileName}\".", "No entries in this folder match '{filter}'" : "Nėra įrašų šiame aplanko atitikmeniui „{filter}“", "Name" : "Pavadinimas", "Size" : "Dydis", "Modified" : "Pakeista", "_%n folder_::_%n folders_" : ["%n aplankas","%n aplankai","%n aplankų"], "_%n file_::_%n files_" : ["%n failas","%n failai","%n failų"], "{dirs} and {files}" : "{dirs} ir {files}", "You don’t have permission to upload or create files here" : "Jūs neturite leidimo čia įkelti arba kurti failus", "_Uploading %n file_::_Uploading %n files_" : ["Įkeliamas %n failas","Įkeliami %n failai","Įkeliama %n failų"], "New" : "Naujas", "\"{name}\" is an invalid file name." : "„{name}“ yra netinkamas failo pavadinime.", "File name cannot be empty." : "Failo pavadinimas negali būti tuščias.", "Storage of {owner} is full, files can not be updated or synced anymore!" : "{owner} saugykla yra pilna, failai daugiau nebegali būti atnaujinti arba sinchronizuojami!", "Your storage is full, files can not be updated or synced anymore!" : "Jūsų visa vieta serveryje užimta", "Storage of {owner} is almost full ({usedSpacePercent}%)" : "{owner} saugykla yra beveik pilna ({usedSpacePercent}%)", "Your storage is almost full ({usedSpacePercent}%)" : "Jūsų vieta serveryje beveik visa užimta ({usedSpacePercent}%)", "_matches '{filter}'_::_match '{filter}'_" : ["atitikmuo „{filter}“","atitikmenys „{filter}“","atitikmenų „{filter}“"], "Path" : "Kelias", "_%n byte_::_%n bytes_" : ["%n baitas","%n baitai","%n baitų"], "Favorited" : "Pažymėta mėgstamu", "Favorite" : "Mėgiamas", "Folder" : "Katalogas", "New folder" : "Naujas aplankas", "{newname} already exists" : "{newname} jau egzistuoja", "Upload" : "Įkelti", "An error occurred while trying to update the tags" : "Bandant atnaujinti žymes įvyko klaida", "A new file or folder has been <strong>created</strong>" : "Naujas failas ar aplankas buvo <strong>sukurtas</strong>", "A file or folder has been <strong>changed</strong>" : "Failas ar aplankas buvo <strong>pakeistas</strong>", "Limit notifications about creation and changes to your <strong>favorite files</strong> <em>(Stream only)</em>" : "Riboti pranešimus apie sukūrimą ir pokyčius jūsų <strong>mėgiamuose failuose</strong> <em>(Tik srautas)</em>", "A file or folder has been <strong>deleted</strong>" : "Failas ar aplankas buvo <strong>ištrintas</strong>", "A file or folder has been <strong>restored</strong>" : "Failas ar aplankas buvo <strong>atkurtas</strong>", "You created %1$s" : "Jūs sukūrėte %1$s", "%2$s created %1$s" : "%2$s sukūrė %1$s", "%1$s was created in a public folder" : "%1$s buvo sukurta viešajame aplanke", "You changed %1$s" : "Jūs pakeitėte %1$s", "%2$s changed %1$s" : "%2$s pakeitė %1$s", "You deleted %1$s" : "Jūs ištrynėte %1$s", "%2$s deleted %1$s" : "%2$s ištrynė %1$s", "You restored %1$s" : "Jūs atkūrėte %1$s", "%2$s restored %1$s" : "%2$s atkurta %1$s", "Changed by %2$s" : "Pakeitė %2$s", "Deleted by %2$s" : "Ištrynė %2$s", "Restored by %2$s" : "Atkūrė %2$s", "Upload (max. %s)" : "Įkelti (maks. %s)", "File handling" : "Failų tvarkymas", "Maximum upload size" : "Maksimalus įkeliamo failo dydis", "max. possible: " : "maks. galima:", "Save" : "Išsaugoti", "With PHP-FPM it might take 5 minutes for changes to be applied." : "Su PHP-FPM atnaujinimai gali užtrukti apie 5min.", "Missing permissions to edit from here." : "Draudžiama iš čia redaguoti", "Settings" : "Nustatymai", "Show hidden files" : "Rodyti paslėptus failus", "WebDAV" : "WebDAV", "No files in here" : "Čia nėra failų", "Upload some content or sync with your devices!" : "Įkelkite kokį nors turinį, arba sinchronizuokite su savo įrenginiais!", "No entries found in this folder" : "Nerasta įrašų šiame aplanke", "Select all" : "Pažymėti viską", "Upload too large" : "Įkėlimui failas per didelis", "The files you are trying to upload exceed the maximum size for file uploads on this server." : "Bandomų įkelti failų dydis viršija maksimalų, kuris leidžiamas šiame serveryje", "No favorites" : "Nėra mėgstamiausių", "Files and folders you mark as favorite will show up here" : "Failai ir aplankai, kuriuos pažymite mėgstamais, atsiras čia", "Text file" : "Teksto failas", "New text file.txt" : "Naujas tekstas file.txt" }, "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);");
agpl-3.0
fablabbcn/SCOPESdf
app/controllers/search_controller.rb
1497
class SearchController < ApplicationController skip_before_filter :verify_authenticity_token # REMOVE THIS OBVIOUSLY def index @query = params[:q] end ## Search # "GET" "http://localhost:3000/search/:entity" # filter is the attribute you want to search on.. currently set up for email and name on user # format_response is how you want to get the data back: `id` is list of ids, `exists` is boolean of presence # format_response: # exists # ids # objects (default) def main if params[:entity] == "user" returnable = userSearch(search_params[:filter]) end render json: {status: returnable} end private def search_params params.require(:search).permit(:format_response, :name, filter: [ :email, :name ]) end # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Object Searches # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def userSearch(filter) if filter == {} return false end puts filter.inspect # tested: email, name # puts filter result = User.where(filter) if filter.key?("email") result = User.email_search(filter["email"]) else filter.key?("name") result = User.name_search(filter["name"]) end if search_params[:format_response] == "id" return result.map{|u| u.id} end if search_params[:format_response] == "exists" return (result.count > 0) ? true : false end result.to_a # TODO - see if anything should be hidden? end end
agpl-3.0
anuradha-iic/sugar
custom/Extension/modules/Opportunities/Ext/Language/en_us.lang.php
224
<?php $mod_strings['LBL_AMOUNT_NRC'] = 'Opportunity NRCs'; $mod_strings['LBL_TOTAL_OPP_AMOUNT'] = 'Opportunity Total'; $mod_strings['LBL_AMOUNT'] = 'Opportunity MRCs'; $mod_strings['LBL_LIST_AMOUNT'] = 'Opportunity MRCs';
agpl-3.0
dooferlad/juju
worker/logger/logger_test.go
2485
// Copyright 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package logger_test import ( "time" "github.com/juju/loggo" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "gopkg.in/juju/names.v2" "github.com/juju/juju/agent" apilogger "github.com/juju/juju/api/logger" "github.com/juju/juju/juju/testing" "github.com/juju/juju/state" "github.com/juju/juju/worker" "github.com/juju/juju/worker/logger" ) // worstCase is used for timeouts when timing out // will fail the test. Raising this value should // not affect the overall running time of the tests // unless they fail. const worstCase = 5 * time.Second type LoggerSuite struct { testing.JujuConnSuite loggerApi *apilogger.State machine *state.Machine } var _ = gc.Suite(&LoggerSuite{}) func (s *LoggerSuite) SetUpTest(c *gc.C) { s.JujuConnSuite.SetUpTest(c) apiConn, machine := s.OpenAPIAsNewMachine(c) // Create the machiner API facade. s.loggerApi = apilogger.NewState(apiConn) c.Assert(s.loggerApi, gc.NotNil) s.machine = machine } func (s *LoggerSuite) waitLoggingInfo(c *gc.C, expected string) { timeout := time.After(worstCase) for { select { case <-timeout: c.Fatalf("timeout while waiting for logging info to change") case <-time.After(10 * time.Millisecond): loggerInfo := loggo.LoggerInfo() if loggerInfo != expected { c.Logf("logging is %q, still waiting", loggerInfo) continue } return } } } type mockConfig struct { agent.Config c *gc.C tag names.Tag } func (mock *mockConfig) Tag() names.Tag { return mock.tag } func agentConfig(c *gc.C, tag names.Tag) *mockConfig { return &mockConfig{c: c, tag: tag} } func (s *LoggerSuite) makeLogger(c *gc.C) (worker.Worker, *mockConfig) { config := agentConfig(c, s.machine.Tag()) w, err := logger.NewLogger(s.loggerApi, config) c.Assert(err, jc.ErrorIsNil) return w, config } func (s *LoggerSuite) TestRunStop(c *gc.C) { loggingWorker, _ := s.makeLogger(c) c.Assert(worker.Stop(loggingWorker), gc.IsNil) } func (s *LoggerSuite) TestInitialState(c *gc.C) { config, err := s.State.ModelConfig() c.Assert(err, jc.ErrorIsNil) expected := config.LoggingConfig() initial := "<root>=DEBUG;wibble=ERROR" c.Assert(expected, gc.Not(gc.Equals), initial) loggo.ResetLoggers() err = loggo.ConfigureLoggers(initial) c.Assert(err, jc.ErrorIsNil) loggingWorker, _ := s.makeLogger(c) defer worker.Stop(loggingWorker) s.waitLoggingInfo(c, expected) }
agpl-3.0
jameinel/juju
core/network/source_netlink_test.go
3780
// Copyright 2021 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. //go:build linux // +build linux package network import ( "net" "github.com/juju/testing" jc "github.com/juju/testing/checkers" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" gc "gopkg.in/check.v1" ) type sourceNetlinkSuite struct { testing.IsolationSuite } var _ = gc.Suite(&sourceNetlinkSuite{}) func (s *sourceNetlinkSuite) TestNetlinkAddr(c *gc.C) { raw, err := netlink.ParseAddr("192.168.20.1/24") c.Assert(err, jc.ErrorIsNil) addr := &netlinkAddr{raw} c.Check(addr.String(), gc.Equals, "192.168.20.1/24") c.Assert(addr.IP(), gc.NotNil) c.Check(addr.IP().String(), gc.Equals, "192.168.20.1") c.Assert(addr.IPNet(), gc.NotNil) c.Check(addr.IPNet().String(), gc.Equals, "192.168.20.1/24") raw, err = netlink.ParseAddr("fe80::5054:ff:fedd:eef0/64") c.Assert(err, jc.ErrorIsNil) addr = &netlinkAddr{raw} c.Check(addr.String(), gc.Equals, "fe80::5054:ff:fedd:eef0/64") c.Assert(addr.IP(), gc.NotNil) c.Check(addr.IP().String(), gc.Equals, "fe80::5054:ff:fedd:eef0") c.Assert(addr.IPNet(), gc.NotNil) c.Check(addr.IPNet().String(), gc.Equals, "fe80::5054:ff:fedd:eef0/64") c.Check(addr.IsSecondary(), jc.IsFalse) addr.addr.Flags = addr.addr.Flags | unix.IFA_F_SECONDARY c.Check(addr.IsSecondary(), jc.IsTrue) } func (s *sourceNetlinkSuite) TestNetlinkAttrs(c *gc.C) { link := &stubLink{flags: net.FlagUp} nic := &netlinkNIC{nic: link} c.Check(nic.MTU(), gc.Equals, 1500) c.Check(nic.Name(), gc.Equals, "eno3") c.Check(nic.IsUp(), jc.IsTrue) c.Check(nic.Index(), gc.Equals, 3) c.Check(nic.HardwareAddr(), gc.DeepEquals, net.HardwareAddr{}) } func (s *sourceNetlinkSuite) TestNetlinkNICType(c *gc.C) { link := &stubLink{} nic := &netlinkNIC{nic: link} // If we have get value, return it. link.linkType = "bond" c.Check(nic.Type(), gc.Equals, BondDevice) // Infer loopback from flags. link.linkType = "" link.flags = net.FlagUp | net.FlagLoopback c.Check(nic.Type(), gc.Equals, LoopbackDevice) // Default to ethernet otherwise. link.flags = net.FlagUp | net.FlagBroadcast | net.FlagMulticast c.Check(nic.Type(), gc.Equals, EthernetDevice) } func (s *sourceNetlinkSuite) TestNetlinkNICAddrs(c *gc.C) { raw1, err := netlink.ParseAddr("192.168.20.1/24") c.Assert(err, jc.ErrorIsNil) raw2, err := netlink.ParseAddr("fe80::5054:ff:fedd:eef0/64") c.Assert(err, jc.ErrorIsNil) getAddrs := func(link netlink.Link) ([]netlink.Addr, error) { // Check that we called correctly passing the inner nic. c.Assert(link.Attrs().Name, gc.Equals, "eno3") return []netlink.Addr{*raw1, *raw2}, nil } nic := netlinkNIC{ nic: &stubLink{}, getAddrs: getAddrs, } addrs, err := nic.Addresses() c.Assert(err, jc.ErrorIsNil) c.Assert(addrs, gc.HasLen, 2) c.Assert(addrs[0].String(), gc.Equals, "192.168.20.1/24") c.Assert(addrs[1].String(), gc.Equals, "fe80::5054:ff:fedd:eef0/64") } func (s *sourceNetlinkSuite) TestNetlinkSourceInterfaces(c *gc.C) { link1 := &stubLink{linkType: "bridge"} link2 := &stubLink{linkType: "bond"} source := &netlinkConfigSource{ linkList: func() ([]netlink.Link, error) { return []netlink.Link{link1, link2}, nil }, } nics, err := source.Interfaces() c.Assert(err, jc.ErrorIsNil) c.Assert(nics, gc.HasLen, 2) c.Check(nics[0].Type(), gc.Equals, BridgeDevice) c.Check(nics[1].Type(), gc.Equals, BondDevice) } // stubLink stubs netlink.Link type stubLink struct { linkType string flags net.Flags } func (l *stubLink) Attrs() *netlink.LinkAttrs { return &netlink.LinkAttrs{ Index: 3, MTU: 1500, Name: "eno3", HardwareAddr: net.HardwareAddr{}, Flags: l.flags, } } func (l *stubLink) Type() string { return l.linkType }
agpl-3.0
EaglesoftZJ/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/api/rpc/RequestRemoveContact.java
1694
package im.actor.core.api.rpc; /* * Generated by the Actor API Scheme generator. DO NOT EDIT! */ import im.actor.runtime.bser.*; import im.actor.runtime.collections.*; import static im.actor.runtime.bser.Utils.*; import im.actor.core.network.parser.*; import androidx.annotation.Nullable; import org.jetbrains.annotations.NotNull; import com.google.j2objc.annotations.ObjectiveCName; import java.io.IOException; import java.util.List; import java.util.ArrayList; import im.actor.core.api.*; public class RequestRemoveContact extends Request<ResponseSeq> { public static final int HEADER = 0x59; public static RequestRemoveContact fromBytes(byte[] data) throws IOException { return Bser.parse(new RequestRemoveContact(), data); } private int uid; private long accessHash; public RequestRemoveContact(int uid, long accessHash) { this.uid = uid; this.accessHash = accessHash; } public RequestRemoveContact() { } public int getUid() { return this.uid; } public long getAccessHash() { return this.accessHash; } @Override public void parse(BserValues values) throws IOException { this.uid = values.getInt(1); this.accessHash = values.getLong(2); } @Override public void serialize(BserWriter writer) throws IOException { writer.writeInt(1, this.uid); writer.writeLong(2, this.accessHash); } @Override public String toString() { String res = "rpc RemoveContact{"; res += "uid=" + this.uid; res += "}"; return res; } @Override public int getHeaderKey() { return HEADER; } }
agpl-3.0
JARR/JARR
src/web/js/components/RightPanel.react.js
18805
var React = require('react'); var createReactClass = require('create-react-class'); var Col = require('react-bootstrap/lib/Col'); var Glyphicon = require('react-bootstrap/lib/Glyphicon'); var Button = require('react-bootstrap/lib/Button'); var ButtonGroup = require('react-bootstrap/lib/ButtonGroup'); var Modal = require('react-bootstrap/lib/Modal'); var PropTypes = require('prop-types'); var RightPanelActions = require('../actions/RightPanelActions'); var RightPanelStore = require('../stores/RightPanelStore'); var MenuStore = require('../stores/MenuStore'); var JarrTime = require('./time.react'); var PanelMixin = { propTypes: {obj: PropTypes.object.isRequired}, getInitialState: function() { return {edit_mode: false, obj: this.props.obj, showModal: false}; }, getHeader: function() { var icon = null; if(this.props.obj.icon_url){ icon = (<img width="16px" src={this.props.obj.icon_url} />); } var btn_grp = null; if(this.isEditable() || this.isRemovable()) { var edit_button = null; if(this.isEditable()) { edit_button = (<Button onClick={this.onClickEdit}> <Glyphicon glyph="pencil" /> </Button>); } var rem_button = null; if(this.isRemovable()) { rem_button = (<Button onClick={this.onClickRemove}> <Glyphicon glyph="remove-sign" /> </Button>); } btn_grp = (<ButtonGroup bsSize="small"> {edit_button} {rem_button} </ButtonGroup>); } return (<div id="right-panel-heading" className="panel-heading"> <Modal show={this.state.showModal} onHide={this.closeModal}> <Modal.Header closeButton> <Modal.Title>Are you sure ?</Modal.Title> </Modal.Header> <Modal.Footer> <Button onClick={this.confirmDelete}> Confirm </Button> </Modal.Footer> </Modal> <h4>{icon}{this.getTitle()}</h4> {btn_grp} </div>); }, getKey: function(prefix, suffix) { return ((this.state.edit_mode?'edit':'fix') + prefix + '-' + this.props.obj.id + '-' + suffix); }, getCore: function() { var items = []; var key; if(!this.state.edit_mode) { this.fields.filter(function(field) { return field.type != 'ignore'; }).map(function(field) { key = this.getKey('dt', field.key); items.push(<dt key={key}>{field.title}</dt>); key = this.getKey('dd', field.key); if(field.type == 'string') { items.push(<dd key={key}>{this.props.obj[field.key]}</dd>); } else if(field.type == 'bool') { if(this.props.obj[field.key]) { items.push(<dd key={key}><Glyphicon glyph="check" /></dd>); } else { items.push(<dd key={key}><Glyphicon glyph="unchecked" /></dd>); } } else if (field.type == 'list') { items.push(<dd key={key}>{this.props.obj[field.key].reduce(function(previousTag, currentTag) { return currentTag.concat(", ", previousTag) }, "")}</dd>) } else if (field.type == 'link') { items.push(<dd key={key}> <a href={this.props.obj[field.key]}> {this.props.obj[field.key]} </a> </dd>); } }.bind(this)); } else { this.fields.filter(function(field) { return field.type != 'ignore'; }).map(function(field) { key = this.getKey('dd', field.key); items.push(<dt key={key}>{field.title}</dt>); key = this.getKey('dt', field.key); var input = null; if(field.type == 'string' || field.type == 'link') { input = (<input type="text" name={field.key} onChange={this.saveField} defaultValue={this.props.obj[field.key]} />); } else if (field.type == 'bool') { input = (<input type="checkbox" name={field.key} onChange={this.saveField} defaultChecked={this.props.obj[field.key]} />); } items.push(<dd key={key}>{input}</dd>); }.bind(this)); } return (<dl className="dl-horizontal">{items}</dl>); }, getSubmit: function() { return (<dd key={this.getKey('dd', 'submit')}> <button className="btn btn-default" onClick={this.saveObj}> Submit </button> </dd>); }, render: function() { return (<div className="panel panel-default"> {this.getHeader()} {this.getBody()} </div> ); }, onClickEdit: function() { this.setState({edit_mode: !this.state.edit_mode}); }, onClickRemove: function() { this.setState({showModal: true}); }, closeModal: function() { this.setState({showModal: false}); }, confirmDelete: function() { this.setState({showModal: false}, function() { RightPanelActions.delObj(this.props.obj.id, this.obj_type); }.bind(this)); }, saveField: function(evnt) { var obj = this.state.obj; for(var i in this.fields) { if(evnt.target.name == this.fields[i].key) { if(this.fields[i].type == 'bool') { obj[evnt.target.name] = evnt.target.checked; } else { obj[evnt.target.name] = evnt.target.value; } break; } } this.setState({obj: obj}); }, saveObj: function() { var to_push = {}; this.fields.map(function(field) { to_push[field.key] = this.state.obj[field.key]; }.bind(this)); this.setState({edit_mode: false}, function() { RightPanelActions.putObj(this.props.obj.id, this.obj_type, to_push); }.bind(this)); }, }; var Article = createReactClass({ mixins: [PanelMixin], isEditable: function() {return false;}, isRemovable: function() {return true;}, fields: [{'title': 'Date', 'type': 'string', 'key': 'date'}, {'title': 'Original link', 'type': 'link', 'key': 'link'}, {'title': 'Tags', 'type': 'list', 'key': 'tags'} ], obj_type: 'article', getTitle: function() {return this.props.obj.title;}, getBody: function() { return (<div className="panel-body"> {this.getCore()} <div id="article-content" dangerouslySetInnerHTML={ {__html: this.props.obj.content}} /> </div>); } }); var Feed = createReactClass({ mixins: [PanelMixin], isEditable: function() {return true;}, isRemovable: function() {return true;}, obj_type: 'feed', fields: [{'title': 'Feed title', 'type': 'string', 'key': 'title'}, {'title': 'Description', 'type': 'string', 'key': 'description'}, {'title': 'Feed link', 'type': 'link', 'key': 'link'}, {'title': 'Site link', 'type': 'link', 'key': 'site_link'}, {'title': 'Enabled', 'type': 'bool', 'key': 'enabled'}, {'title': 'Private', 'type': 'bool', 'key': 'private'}, {'title': 'Filters', 'type': 'ignore', 'key': 'filters'}, {'title': 'Category', 'type': 'ignore', 'key': 'category_id'}, ], getTitle: function() {return this.props.obj.title;}, getFilterRow: function(i, filter) { return (<dd key={'d' + i + '-' + this.props.obj.id} className="input-group filter-row"> <span className="input-group-btn"> <button className="btn btn-default" type="button" data-index={i} onClick={this.removeFilterRow}> <Glyphicon glyph='minus' /> </button> </span> <select name="action on" className="form-control" data-index={i} onChange={this.saveFilterChange} defaultValue={filter['action on']}> <option value="match">match</option> <option value="no match">no match</option> </select> <input name="pattern" type="text" className="form-control" data-index={i} onChange={this.saveFilterChange} defaultValue={filter.pattern} /> <select name="type" className="form-control" data-index={i} onChange={this.saveFilterChange} defaultValue={filter.type}> <option value='simple match'>simple match</option> <option value='regex'>regex</option> </select> <select name="action" className="form-control" data-index={i} onChange={this.saveFilterChange} defaultValue={filter.action}> <option value="mark as read">mark as read</option> <option value="mark as favorite">mark as favorite</option> </select> </dd>); }, getFilterRows: function() { var rows = []; if(this.state.edit_mode) { for(var i in this.state.obj.filters) { rows.push(this.getFilterRow(i, this.state.obj.filters[i])); } return (<dl className="dl-horizontal"> <dt>Filters</dt> <dd> <button className="btn btn-default" type="button" onClick={this.addFilterRow}> <Glyphicon glyph='plus' /> </button> </dd> {rows} </dl>); } rows = []; rows.push(<dt key={'d-title'}>Filters</dt>); for(var i in this.state.obj.filters) { rows.push(<dd key={'d' + i}> When {this.state.obj.filters[i]['action on']} on "{this.state.obj.filters[i].pattern}" ({this.state.obj.filters[i].type}) "=" {this.state.obj.filters[i].action} </dd>); } return <dl className="dl-horizontal">{rows}</dl>; }, getCategorySelect: function() { var content = null; if(this.state.edit_mode) { var categ_options = []; for(var index in MenuStore._datas.categories_order) { var cat_id = MenuStore._datas.categories_order[index]; categ_options.push( <option value={cat_id} key={MenuStore._datas.categories[cat_id].id}> {MenuStore._datas.categories[cat_id].name} </option>); } content = (<select name="category_id" className="form-control" onChange={this.saveField} defaultValue={this.props.obj.category_id}> {categ_options} </select>); } else { content = MenuStore._datas.categories[this.props.obj.category_id].name; } return (<dl className="dl-horizontal"> <dt>Category</dt><dd>{content}</dd> </dl>); }, getErrorFields: function() { if(this.props.obj.error_count < MenuStore._datas.error_threshold) { return; } if(this.props.obj.error_count < MenuStore._datas.max_error) { return (<dl className="dl-horizontal"> <dt>State</dt> <dd>The download of this feed has encountered some problems. However its error counter will be reinitialized at the next successful retrieving.</dd> <dt>Last error</dt> <dd>{this.props.obj.last_error}</dd> </dl>); } return (<dl className="dl-horizontal"> <dt>State</dt> <dd>That feed has encountered too much consecutive errors and won't be retrieved anymore.</dd> <dt>Last error</dt> <dd>{this.props.obj.last_error}</dd> <dd> <Button onClick={this.resetErrors}>Reset error count </Button> </dd> </dl>); }, resetErrors: function() { var obj = this.state.obj; obj.error_count = 0; this.setState({obj: obj}, function() { RightPanelActions.resetErrors(this.props.obj.id); }.bind(this)); }, getBody: function() { return (<div className="panel-body"> <dl className="dl-horizontal"> <dt>Created on</dt> <dd><JarrTime stamp={this.props.obj.created_rel} text={this.props.obj.created_date} /> </dd> <dt>Last fetched</dt> <dd><JarrTime stamp={this.props.obj.last_rel} text={this.props.obj.last_retrieved} /> </dd> </dl> {this.getErrorFields()} {this.getCategorySelect()} {this.getCore()} {this.getFilterRows()} {this.state.edit_mode?this.getSubmit():null} </div> ); }, addFilterRow: function() { var obj = this.state.obj; obj.filters.push({action: "mark as read", 'action on': "match", type: "simple match", pattern: ""}); this.setState({obj: obj}); }, removeFilterRow: function(evnt) { var obj = this.state.obj; delete obj.filters[evnt.target.getAttribute('data-index')]; this.setState({obj: obj}); }, saveFilterChange: function(evnt) { var index = evnt.target.getAttribute('data-index'); var obj = this.state.obj; obj.filters[index][evnt.target.name] = evnt.target.value; this.setState({obj: obj}); }, }); var Category = createReactClass({ mixins: [PanelMixin], isEditable: function() { if(this.props.obj.id != 0) {return true;} else {return false;} }, isRemovable: function() {return this.isEditable();}, obj_type: 'category', fields: [{'title': 'Category name', 'type': 'string', 'key': 'name'}], getTitle: function() {return this.props.obj.name;}, getBody: function() { return (<div className="panel-body"> {this.getCore()} {this.state.edit_mode?this.getSubmit():null} </div>); }, }); var RightPanel = createReactClass({ getInitialState: function() { return {category: null, feed: null, article: null, current: null}; }, getCategoryCrum: function() { return (<li><a onClick={this.selectCategory} href="#"> {this.state.category.name} </a></li>); }, getFeedCrum: function() { return (<li><a onClick={this.selectFeed} href="#"> {this.state.feed.title} </a></li>); }, getArticleCrum: function() { return <li>{this.state.article.title}</li>; }, render: function() { window.scrollTo(0, 0); var brd_category = null; var brd_feed = null; var brd_article = null; var breadcrum = null; if(this.state.category) { brd_category = (<li className="rp-crum"> <a onClick={this.selectCategory} href="#"> {this.state.category.name} </a> </li>); } if(this.state.feed) { brd_feed = (<li className="rp-crum"> <a onClick={this.selectFeed} href="#"> {this.state.feed.title} </a> </li>); } if(this.state.article) { brd_article = <li className="rp-crum">{this.state.article.title}</li>; } if(brd_category || brd_feed || brd_article) { breadcrum = (<ol className="breadcrumb" id="rp-breadcrum"> {brd_category} {brd_feed} {brd_article} </ol>); } if(this.state.current == 'article') { var cntnt = (<Article type='article' obj={this.state.article} key={this.state.article.id} />); } else if(this.state.current == 'feed') { var cntnt = (<Feed type='feed' obj={this.state.feed} key={this.state.feed.id} />); } else if(this.state.current == 'category') { var cntnt = (<Category type='category' obj={this.state.category} key={this.state.category.id} />); } return (<Col id="right-panel" xsHidden smOffset={4} mdOffset={7} lgOffset={6} sm={8} md={5} lg={6}> {breadcrum} {cntnt} </Col> ); }, selectCategory: function() { this.setState({current: 'category'}); }, selectFeed: function() { this.setState({current: 'feed'}); }, selectArticle: function() { this.setState({current: 'article'}); }, componentDidMount: function() { RightPanelStore.addChangeListener(this._onChange); }, componentWillUnmount: function() { RightPanelStore.removeChangeListener(this._onChange); }, _onChange: function() { this.setState(RightPanelStore.getAll()); }, }); module.exports = RightPanel;
agpl-3.0
BelledonneCommunications/flexisip
src/sofia-wrapper/su-root.cc
1693
/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010-2021 Belledonne Communications SARL, 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 "flexisip/logmanager.hh" #include "flexisip/sofia-wrapper/su-root.hh" using namespace std; namespace sofiasip { void SuRoot::addToMainLoop(function<void()> functionToAdd) { su_msg_r msg = SU_MSG_R_INIT; if (-1 == su_msg_create(msg, su_root_task(mCPtr), su_root_task(mCPtr), mainLoopFunctionCallback, sizeof(function<void()>*))) { LOGF("Couldn't create auth async message"); } auto clientCb = reinterpret_cast<function<void()>**>(su_msg_data(msg)); *clientCb = new function<void()>(functionToAdd); if (-1 == su_msg_send(msg)) { LOGF("Couldn't send auth async message to main thread."); } } void SuRoot::mainLoopFunctionCallback(su_root_magic_t* rm, su_msg_t** msg, void* u) { auto clientCb = *reinterpret_cast<function<void()>**>(su_msg_data(msg)); (*clientCb)(); delete clientCb; } } // namespace sofiasip
agpl-3.0
open-synergy/opnsynid-partner-contact
partner_financial_risk_policy/tests/test_risk_policy.py
17936
# -*- coding: utf-8 -*- # Copyright 2017 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp.tests.common import TransactionCase from openerp.exceptions import except_orm from openerp import tools class TestRiskPolicy(TransactionCase): def setUp(self, *args, **kwargs): result = super(TestRiskPolicy, self).setUp(*args, **kwargs) # Data self.obj_partner = self.env["res.partner"] self.user = self.env.ref("base.user_root") self.group1 = self.env["res.groups"].create({ "name": "Group 1", "users": [(6, 0, [self.user.id])] }) self.group2 = self.env["res.groups"].create({ "name": "Group 2", }) self.partner = self.obj_partner.create({ "name": "Test 1", "customer": True, }) self.policy1 = self.env["partner.risk_limit_policy"].create({ "name": "Policy 1", "sequence": 1, "group_ids": [(6, 0, [self.group1.id])], "total_risk_limit": 1.0, "invoice_draft_limit": 1.0, "invoice_open_limit": 1.0, "invoice_unpaid_limit": 1.0, "account_amount_limit": 1.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": True, }) self.policy1._compute_user() self.policy2 = self.env["partner.risk_limit_policy"].create({ "name": "Policy 2", "sequence": 2, }) return result def test_initial_policy(self): self.assertTrue(self.partner.unset_total_risk_limit_policy) self.assertTrue(self.partner.unset_invoice_draft_limit_policy) self.assertTrue(self.partner.unset_invoice_open_limit_policy) self.assertTrue(self.partner.unset_invoice_unpaid_limit_policy) self.assertTrue(self.partner.unset_account_amount_limit_policy) def test_partner_failed_zero_total_risk_limit(self): self.policy1.write({ "total_risk_limit": 1.0, "invoice_draft_limit": 1.0, "invoice_open_limit": 1.0, "invoice_unpaid_limit": 1.0, "account_amount_limit": 1.0, "unset_total_risk_limit": False, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": True, }) with self.assertRaises(except_orm) as cm: self.partner.write({ "credit_limit": 0.0, }) err_msg = "Error while validating constraint\n\n%s" % \ "Unauthorized to unset credit limit amount" self.assertEqual( cm.exception.value, tools.ustr(err_msg) ) def test_partner_failed_zero_invoice_draft_limit(self): self.policy1.write({ "total_risk_limit": 1.0, "invoice_draft_limit": 1.0, "invoice_open_limit": 1.0, "invoice_unpaid_limit": 1.0, "account_amount_limit": 1.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": False, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": True, }) with self.assertRaises(except_orm) as cm: self.partner.write({ "credit_limit": 0.0, "risk_invoice_draft_limit": 0.0, }) err_msg = "Error while validating constraint\n\n%s" % \ "Unauthorized to unset invoice draft amount" self.assertEqual( cm.exception.value, tools.ustr(err_msg) ) self.assertTrue(self.partner.unset_total_risk_limit_policy) self.assertFalse(self.partner.unset_invoice_draft_limit_policy) self.assertTrue(self.partner.unset_invoice_open_limit_policy) self.assertTrue(self.partner.unset_invoice_unpaid_limit_policy) self.assertTrue(self.partner.unset_account_amount_limit_policy) def test_partner_failed_zero_invoice_open_limit(self): self.policy1.write({ "total_risk_limit": 1.0, "invoice_draft_limit": 1.0, "invoice_open_limit": 1.0, "invoice_unpaid_limit": 1.0, "account_amount_limit": 1.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": False, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": True, }) with self.assertRaises(except_orm) as cm: self.partner.write({ "credit_limit": 0.0, "risk_invoice_draft_limit": 0.0, "risk_invoice_open_limit": 0.0, }) err_msg = "Error while validating constraint\n\n%s" % \ "Unauthorized to unset invoice open amount" self.assertEqual( cm.exception.value, tools.ustr(err_msg) ) self.assertTrue(self.partner.unset_total_risk_limit_policy) self.assertTrue(self.partner.unset_invoice_draft_limit_policy) self.assertFalse(self.partner.unset_invoice_open_limit_policy) self.assertTrue(self.partner.unset_invoice_unpaid_limit_policy) self.assertTrue(self.partner.unset_account_amount_limit_policy) def test_partner_failed_zero_invoice_unpaid_limit(self): self.policy1.write({ "total_risk_limit": 1.0, "invoice_draft_limit": 1.0, "invoice_open_limit": 1.0, "invoice_unpaid_limit": 1.0, "account_amount_limit": 1.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": False, "unset_account_amount_limit": True, }) with self.assertRaises(except_orm) as cm: self.partner.write({ "credit_limit": 0.0, "risk_invoice_draft_limit": 0.0, "risk_invoice_open_limit": 0.0, "risk_invoice_unpaid_limit": 0.0, }) err_msg = "Error while validating constraint\n\n%s" % \ "Unauthorized to unset invoice unpaid amount" self.assertEqual( cm.exception.value, tools.ustr(err_msg) ) self.assertTrue(self.partner.unset_total_risk_limit_policy) self.assertTrue(self.partner.unset_invoice_draft_limit_policy) self.assertTrue(self.partner.unset_invoice_open_limit_policy) self.assertFalse(self.partner.unset_invoice_unpaid_limit_policy) self.assertTrue(self.partner.unset_account_amount_limit_policy) def test_partner_failed_zero_account_amount_limit(self): self.policy1.write({ "total_risk_limit": 1.0, "invoice_draft_limit": 1.0, "invoice_open_limit": 1.0, "invoice_unpaid_limit": 1.0, "account_amount_limit": 1.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": False, }) with self.assertRaises(except_orm) as cm: self.partner.write({ "credit_limit": 0.0, "risk_invoice_draft_limit": 0.0, "risk_invoice_open_limit": 0.0, "risk_invoice_unpaid_limit": 0.0, "risk_account_amount_limit": 0.0, }) err_msg = "Error while validating constraint\n\n%s" % \ "Unauthorized to unset other account amount" self.assertEqual( cm.exception.value, tools.ustr(err_msg) ) self.assertTrue(self.partner.unset_total_risk_limit_policy) self.assertTrue(self.partner.unset_invoice_draft_limit_policy) self.assertTrue(self.partner.unset_invoice_open_limit_policy) self.assertTrue(self.partner.unset_invoice_unpaid_limit_policy) self.assertFalse(self.partner.unset_account_amount_limit_policy) def test_partner_failed_total_risk_limit(self): self.policy1.write({ "total_risk_limit": 100.00, "invoice_draft_limit": 100.0, "invoice_open_limit": 100.0, "invoice_unpaid_limit": 100.0, "account_amount_limit": 100.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": True, }) with self.assertRaises(except_orm) as cm: self.partner.write({ "credit_limit": 200.00, "risk_invoice_draft_limit": 100.00, "risk_invoice_open_limit": 100.00, "risk_invoice_unpaid_limit": 100.00, "risk_account_amount_limit": 100.0, }) err_msg = "Error while validating constraint\n\n%s" % \ "Unauthorized credit limit amount" self.assertEqual( cm.exception.value, tools.ustr(err_msg) ) self.assertEqual( self.partner.total_risk_limit_policy, 100.00 ) self.assertEqual( self.partner.invoice_draft_limit_policy, 100.00 ) self.assertEqual( self.partner.invoice_open_limit_policy, 100.00 ) self.assertEqual( self.partner.invoice_unpaid_limit_policy, 100.00 ) self.assertEqual( self.partner.account_amount_limit_policy, 100.00 ) def test_partner_failed_invoice_draft_limit(self): self.policy1.write({ "total_risk_limit": 200.00, "invoice_draft_limit": 100.0, "invoice_open_limit": 100.0, "invoice_unpaid_limit": 100.0, "account_amount_limit": 100.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": True, }) with self.assertRaises(except_orm) as cm: self.partner.write({ "credit_limit": 200.00, "risk_invoice_draft_limit": 200.00, "risk_invoice_open_limit": 100.00, "risk_invoice_unpaid_limit": 100.00, "risk_account_amount_limit": 100.0, }) err_msg = "Error while validating constraint\n\n%s" % \ "Unauthorized invoice draft amount" self.assertEqual( cm.exception.value, tools.ustr(err_msg) ) self.assertEqual( self.partner.total_risk_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_draft_limit_policy, 100.00 ) self.assertEqual( self.partner.invoice_open_limit_policy, 100.00 ) self.assertEqual( self.partner.invoice_unpaid_limit_policy, 100.00 ) self.assertEqual( self.partner.account_amount_limit_policy, 100.00 ) def test_partner_failed_invoice_open_limit(self): self.policy1.write({ "total_risk_limit": 200.00, "invoice_draft_limit": 200.0, "invoice_open_limit": 100.0, "invoice_unpaid_limit": 100.0, "account_amount_limit": 100.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": True, }) with self.assertRaises(except_orm) as cm: self.partner.write({ "credit_limit": 200.00, "risk_invoice_draft_limit": 200.00, "risk_invoice_open_limit": 200.00, "risk_invoice_unpaid_limit": 100.00, "risk_account_amount_limit": 100.0, }) err_msg = "Error while validating constraint\n\n%s" % \ "Unauthorized invoice open amount" self.assertEqual( cm.exception.value, tools.ustr(err_msg) ) self.assertEqual( self.partner.total_risk_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_draft_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_open_limit_policy, 100.00 ) self.assertEqual( self.partner.invoice_unpaid_limit_policy, 100.00 ) self.assertEqual( self.partner.account_amount_limit_policy, 100.00 ) def test_partner_failed_invoice_unpaid_limit(self): self.policy1.write({ "total_risk_limit": 200.00, "invoice_draft_limit": 200.0, "invoice_open_limit": 200.0, "invoice_unpaid_limit": 100.0, "account_amount_limit": 100.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": True, }) with self.assertRaises(except_orm) as cm: self.partner.write({ "credit_limit": 200.00, "risk_invoice_draft_limit": 200.00, "risk_invoice_open_limit": 200.00, "risk_invoice_unpaid_limit": 200.00, "risk_account_amount_limit": 100.0, }) err_msg = "Error while validating constraint\n\n%s" % \ "Unauthorized invoice unpaid amount" self.assertEqual( cm.exception.value, tools.ustr(err_msg) ) self.assertEqual( self.partner.total_risk_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_draft_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_open_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_unpaid_limit_policy, 100.00 ) self.assertEqual( self.partner.account_amount_limit_policy, 100.00 ) def test_partner_failed_account_amount_limit(self): self.policy1.write({ "total_risk_limit": 200.00, "invoice_draft_limit": 200.0, "invoice_open_limit": 200.0, "invoice_unpaid_limit": 200.0, "account_amount_limit": 100.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": True, }) with self.assertRaises(except_orm) as cm: self.partner.write({ "credit_limit": 200.00, "risk_invoice_draft_limit": 200.00, "risk_invoice_open_limit": 200.00, "risk_invoice_unpaid_limit": 200.00, "risk_account_amount_limit": 200.0, }) err_msg = "Error while validating constraint\n\n%s" % \ "Unauthorized other account amount" self.assertEqual( cm.exception.value, tools.ustr(err_msg) ) self.assertEqual( self.partner.total_risk_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_draft_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_open_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_unpaid_limit_policy, 200.00 ) self.assertEqual( self.partner.account_amount_limit_policy, 100.00 ) def test_partner_success_all_limit(self): self.policy1.write({ "total_risk_limit": 200.00, "invoice_draft_limit": 200.0, "invoice_open_limit": 200.0, "invoice_unpaid_limit": 200.0, "account_amount_limit": 200.0, "unset_total_risk_limit": True, "unset_invoice_draft_limit": True, "unset_invoice_open_limit": True, "unset_invoice_unpaid_limit": True, "unset_account_amount_limit": True, }) self.partner.write({ "credit_limit": 200.00, "risk_invoice_draft_limit": 200.00, "risk_invoice_open_limit": 200.00, "risk_invoice_unpaid_limit": 200.00, "risk_account_amount_limit": 200.0, }) self.assertEqual( self.partner.total_risk_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_draft_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_open_limit_policy, 200.00 ) self.assertEqual( self.partner.invoice_unpaid_limit_policy, 200.00 ) self.assertEqual( self.partner.account_amount_limit_policy, 200.00 )
agpl-3.0
deepstupid/sphinx5
sphinx4-core/src/main/java/edu/cmu/sphinx/fst/operations/ProjectType.java
680
/** * * Copyright 1999-2012 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.fst.operations; /** * Enum used in {@link edu.cmu.sphinx.fst.operations.Project} operation. * * It specifies whether the Project operation will take place on input or output * labels * * @author John Salatas */ public enum ProjectType { INPUT, OUTPUT }
agpl-3.0
pollopolea/core
apps/federatedfilesharing/lib/AddressHandler.php
4792
<?php /** * @author Björn Schießle <[email protected]> * @author Thomas Müller <[email protected]> * * @copyright Copyright (c) 2018, ownCloud GmbH * @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/> * */ namespace OCA\FederatedFileSharing; use OC\HintException; use OCP\IL10N; use OCP\IURLGenerator; /** * Class AddressHandler - parse, modify and construct federated sharing addresses * * @package OCA\FederatedFileSharing */ class AddressHandler { /** @var IL10N */ private $l; /** @var IURLGenerator */ private $urlGenerator; /** * AddressHandler constructor. * * @param IURLGenerator $urlGenerator * @param IL10N $il10n */ public function __construct( IURLGenerator $urlGenerator, IL10N $il10n ) { $this->l = $il10n; $this->urlGenerator = $urlGenerator; } /** * split user and remote from federated cloud id * * @param string $address federated share address * @return array [user, remoteURL] * @throws HintException */ public function splitUserRemote($address) { if (strpos($address, '@') === false) { $hint = $this->l->t('Invalid Federated Cloud ID'); throw new HintException('Invalid Federated Cloud ID', $hint); } // Find the first character that is not allowed in user names $id = str_replace('\\', '/', $address); $posSlash = strpos($id, '/'); $posColon = strpos($id, ':'); if ($posSlash === false && $posColon === false) { $invalidPos = strlen($id); } else if ($posSlash === false) { $invalidPos = $posColon; } else if ($posColon === false) { $invalidPos = $posSlash; } else { $invalidPos = min($posSlash, $posColon); } // Find the last @ before $invalidPos $pos = $lastAtPos = 0; while ($lastAtPos !== false && $lastAtPos <= $invalidPos) { $pos = $lastAtPos; $lastAtPos = strpos($id, '@', $pos + 1); } if ($pos !== false) { $user = substr($id, 0, $pos); $remote = substr($id, $pos + 1); $remote = $this->fixRemoteURL($remote); if (!empty($user) && !empty($remote)) { return [$user, $remote]; } } $hint = $this->l->t('Invalid Federated Cloud ID'); throw new HintException('Invalid Federated Cloud ID', $hint); } /** * generate remote URL part of federated ID * * @return string url of the current server */ public function generateRemoteURL() { $url = $this->urlGenerator->getAbsoluteURL('/'); return $url; } /** * check if two federated cloud IDs refer to the same user * * @param string $user1 * @param string $server1 * @param string $user2 * @param string $server2 * @return bool true if both users and servers are the same */ public function compareAddresses($user1, $server1, $user2, $server2) { $normalizedServer1 = strtolower($this->removeProtocolFromUrl($server1)); $normalizedServer2 = strtolower($this->removeProtocolFromUrl($server2)); if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) { // FIXME this should be a method in the user management instead \OCP\Util::emitHook( '\OCA\Files_Sharing\API\Server2Server', 'preLoginNameUsedAsUserName', ['uid' => &$user1] ); \OCP\Util::emitHook( '\OCA\Files_Sharing\API\Server2Server', 'preLoginNameUsedAsUserName', ['uid' => &$user2] ); if ($user1 === $user2) { return true; } } return false; } /** * remove protocol from URL * * @param string $url * @return string */ public function removeProtocolFromUrl($url) { if (strpos($url, 'https://') === 0) { return substr($url, strlen('https://')); } else if (strpos($url, 'http://') === 0) { return substr($url, strlen('http://')); } return $url; } /** * Strips away a potential file names and trailing slashes: * - http://localhost * - http://localhost/ * - http://localhost/index.php * - http://localhost/index.php/s/{shareToken} * * all return: http://localhost * * @param string $remote * @return string */ protected function fixRemoteURL($remote) { $remote = str_replace('\\', '/', $remote); if ($fileNamePosition = strpos($remote, '/index.php')) { $remote = substr($remote, 0, $fileNamePosition); } $remote = rtrim($remote, '/'); return $remote; } }
agpl-3.0
azyva/dragom-api
src/main/java/org/azyva/dragom/model/config/NodeConfigTransferObject.java
7040
/* * Copyright 2015 - 2017 AZYVA INC. INC. * * This file is part of Dragom. * * Dragom 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. * * Dragom 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 Dragom. If not, see <http://www.gnu.org/licenses/>. */ package org.azyva.dragom.model.config; import java.util.List; import org.azyva.dragom.model.plugin.NodePlugin; /** * Transfer object for a {@link MutableNodeConfig} basic configuration data. * <p> * MutableNodeConfig and its sub-interfaces return and take as argument this * interface to allow getting and setting atomically data. See * {@link MutableConfig}. * <p> * It so happens that the only configuration data that can be transfered from and * to MutableNodeConfig's (and its sub-interfaces) are the same and are * represented by this interface. If MutableNodeConfig and its sub-interfaces * eventually contain other configuration data that are not common, the * orientation will probably be to introduce new transfer objects instead * implementing an interface hierarchy to factor out commonality. * <p> * Since this interface represents a transfer object, implementations are * generally straightforward, and in most cases, * SimpleNodeConfigTransferObject will be adequate. Specifically if an * implementation of MutableNodeConfig needs to manage concurrency with optimistic * locking, {@link OptimisticLockHandle} should be used instead of including some * hidden field within the NodeConfigTransferObject implementation. * * @author David Raymond */ public interface NodeConfigTransferObject { /** * @return Name. */ String getName(); /** * Sets the name. * * @param name See description. */ void setName(String name); /** * Returns a {@link PropertyDefConfig}. * <p> * If the PropertyDefConfig exists but is defined with the value field set to * null, a PropertyDefConfig is returned (instead of returning null). * * @param name Name of the PropertyDefConfig. * @return PropertyDefConfig. null if the PropertyDefConfig does not exist. */ PropertyDefConfig getPropertyDefConfig(String name); /** * Verifies if a {@link PropertyDefConfig} exists. * <p> * If the PropertyDefConfig exists but is defined with the value field set to * null, true is returned. * <p> * Returns true if an only if {@link #getPropertyDefConfig} does not return null. * * @param name Name of the PropertyDefConfig. * @return Indicates if the PropertyDefConfig exists. */ boolean isPropertyExists(String name); /** * Returns a List of all the {@link PropertyDefConfig}'s. * <p> * If no PropertyDefConfig is defined for the NodeConfig, an empty List is * returned (as opposed to null). * <p> * The order of the PropertyDefConfig is generally expected to be as defined * in the underlying storage for the configuration, hence the List return type. * But no particular order is actually guaranteed. * * @return See description. */ public List<PropertyDefConfig> getListPropertyDefConfig(); /** * Removes a {@link PropertyDefConfig}. * * @param name Name of the PropertyDefConfig. */ public void removePropertyDefConfig(String name); /** * Sets a {@link PropertyDefConfig}. * <p> * If one already exists with the same name, it is overwritten. Otherwise it is * added. * <p> * Mostly any implementation of PropertyDefConfig can be used, although * SimplePropertyDefConfig is generally the better choice. * * @param propertyDefConfig PropertyDefConfig. * @return Indicates if a new PropertyDefConfig was added (as opposed to an * existing one having been overwritten. */ public boolean setPropertyDefConfig(PropertyDefConfig propertyDefConfig); /** * Returns a {@link PluginDefConfig}. * <p> * If the PluginDefConfig exists but is defined with the pluginClass field set to * null, a PluginDefConfig is returned (instead of returning null). * * @param classNodePlugin Class of the {@link NodePlugin} interface. * @param pluginId Plugin ID to distinguish between multiple instances of the same * plugin. Can be null to get a PluginDefConfig whose field pluginId is null. * @return PluginDefConfig. null if the PluginDefConfig does not exist. */ public PluginDefConfig getPluginDefConfig(Class<? extends NodePlugin> classNodePlugin, String pluginId); /** * Verifies if a {@link PluginDefConfig} exists. * <p> * If the PluginDefConfig exists but is defined with the pluginClass field set to * null, true is returned. * <p> * Returns true if an only if {@link #getPluginDefConfig} does not return null. * * @param classNodePlugin Class of the {@link NodePlugin} interface. * @param pluginId Plugin ID to distinguish between multiple instances of the same * plugin. Can be null to get a PluginDefConfig whose field pluginId is null. * @return Indicates if the PluginDefConfig exists. */ public boolean isPluginDefConfigExists(Class<? extends NodePlugin> classNodePlugin, String pluginId); /** * Returns a List of all the {@link PluginDefConfig}'s. * <p> * If no PluginDefConfig is defined for the NodeConfig, an empty Set is returned * (as opposed to null). * <p> * The order of the PluginDefConfig is generally expected to be as defined * in the underlying storage for the configuration, hence the List return type. * But no particular order is actually guaranteed. * * @return See description. */ public List<PluginDefConfig> getListPluginDefConfig(); /** * Removes a {@link PropertyDefConfig}. * * @param classNodePlugin Class of the {@link NodePlugin} interface. * @param pluginId Plugin ID to distinguish between multiple instances of the same * plugin. Can be null to get a PluginDefConfig whose field pluginId is null. */ public void removePlugingDefConfig(Class<? extends NodePlugin> classNodePlugin, String pluginId); /** * Sets a {@link PluginDefConfig}. * <p> * If one already exists with the same {@link PluginKey}, it is overwritten. * Otherwise it is added. * <p> * Mostly any implementation of PluginDefConfig can be used, although * SimplePluginDefConfig is generally the better choice. * * @param pluginDefConfig PluginDefConfig. * @return Indicates if a new PluginDefConfig was added (as opposed to an existing * one having been overwritten. */ public boolean setPluginDefConfig(PluginDefConfig pluginDefConfig); }
agpl-3.0
s-haase/shopware
engine/Shopware/Bundle/StoreFrontBundle/Gateway/DBAL/Hydrator/MediaHydrator.php
7252
<?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\StoreFrontBundle\Gateway\DBAL\Hydrator; use Doctrine\DBAL\Connection; use Shopware\Bundle\StoreFrontBundle\Struct; use Shopware\Bundle\MediaBundle\MediaService; use Shopware\Components\Thumbnail\Manager; use Shopware\Models; /** * @category Shopware * @package Shopware\Bundle\StoreFrontBundle\Gateway\DBAL\Hydrator * @copyright Copyright (c) shopware AG (http://www.shopware.de) */ class MediaHydrator extends Hydrator { /** * @var AttributeHydrator */ private $attributeHydrator; /** * @var Manager */ private $thumbnailManager; /** * @var MediaService */ private $mediaService; /** * @var Connection */ private $database; /** * @param AttributeHydrator $attributeHydrator * @param \Shopware\Components\Thumbnail\Manager $thumbnailManager * @param MediaService $mediaService * @param Connection $database */ public function __construct(AttributeHydrator $attributeHydrator, Manager $thumbnailManager, MediaService $mediaService, Connection $database) { $this->attributeHydrator = $attributeHydrator; $this->thumbnailManager = $thumbnailManager; $this->mediaService = $mediaService; $this->database = $database; } /** * @param array $data * @return Struct\Media */ public function hydrate(array $data) { $media = new Struct\Media(); $translation = $this->getTranslation($data, '__media'); $data = array_merge($data, $translation); if (isset($data['__media_id'])) { $media->setId((int) $data['__media_id']); } if (isset($data['__media_name'])) { $media->setName($data['__media_name']); } if (isset($data['__media_description'])) { $media->setDescription($data['__media_description']); } if (isset($data['__media_type'])) { $media->setType($data['__media_type']); } if (isset($data['__media_extension'])) { $media->setExtension($data['__media_extension']); } if (isset($data['__media_path'])) { $media->setFile($this->mediaService->getUrl($data['__media_path'])); } /** * Live Migration to add width/height to images */ if ($this->isUpdateRequired($media, $data)) { $data = $this->updateMedia($data); } if (isset($data['__media_width'])) { $media->setWidth((int) $data['__media_width']); } if (isset($data['__media_height'])) { $media->setHeight((int) $data['__media_height']); } if ($media->getType() == Struct\Media::TYPE_IMAGE && $data['__mediaSettings_create_thumbnails']) { $media->setThumbnails( $this->getMediaThumbnails($data) ); } if (!empty($data['__mediaAttribute_id'])) { $this->attributeHydrator->addAttribute($media, $data, 'mediaAttribute', 'media'); } return $media; } /** * @param Struct\Media $media * @param array $data * @return bool */ private function isUpdateRequired(Struct\Media $media, array $data) { if ($media->getType() != Struct\Media::TYPE_IMAGE) { return false; } if (!array_key_exists('__media_width', $data)) { return false; } if (!array_key_exists('__media_height', $data)) { return false; } if ($data['__media_width'] !== null && $data['__media_height'] !== null) { return false; } return $this->mediaService->has($data['__media_path']); } /** * @param array $data * @return \Shopware\Bundle\StoreFrontBundle\Struct\Media */ public function hydrateProductImage(array $data) { $media = $this->hydrate($data); $translation = $this->getTranslation($data, '__image'); $data = array_merge($data, $translation); // For legacy reasons we check if the __image_description can be used if (!empty($data['__image_description'])) { $media->setName($data['__image_description']); } if (!$media->getName() && $media->getDescription()) { $media->setName($media->getDescription()); } $media->setPreview((bool) ($data['__image_main'] == 1)); if (!empty($data['__imageAttribute_id'])) { $this->attributeHydrator->addAttribute($media, $data, 'imageAttribute', 'image', 'image'); } return $media; } /** * @param array $data Contains the array data for the media * @return array */ private function getMediaThumbnails(array $data) { $thumbnailData = $this->thumbnailManager->getMediaThumbnails( $data['__media_name'], $data['__media_type'], $data['__media_extension'], explode(';', $data['__mediaSettings_thumbnail_size']) ); $thumbnails = []; foreach ($thumbnailData as $row) { $retina = $row['retinaSource']; if (!$data['__mediaSettings_thumbnail_high_dpi']) { $retina = null; } if (!empty($retina)) { $retina = $this->mediaService->getUrl($retina); } $thumbnails[] = new Struct\Thumbnail( $this->mediaService->getUrl($row['source']), $retina, $row['maxWidth'], $row['maxHeight'] ); } return $thumbnails; } /** * @param array $data * @return array */ private function updateMedia(array $data) { list($width, $height) = getimagesizefromstring($this->mediaService->read($data['__media_path'])); $this->database->executeUpdate( 'UPDATE s_media SET width = :width, height = :height WHERE id = :id', [ ':width' => $width, ':height' => $height, ':id' => $data['__media_id'] ] ); $data['__media_width'] = $width; $data['__media_height'] = $height; return $data; } }
agpl-3.0
LibreTime/libretime
legacy/public/js/airtime/schedule/schedule.js
16712
var AIRTIME = (function(AIRTIME){ var mod; if (AIRTIME.schedule === undefined) { AIRTIME.schedule = {}; } mod = AIRTIME.schedule; return AIRTIME; }(AIRTIME || {})); var serverTimezoneOffset = 0; function closeDialogCalendar(event, ui) { $el = $(this); $el.dialog('destroy'); $el.remove(); //need to refetch the events to update scheduled status. $("#schedule_calendar").fullCalendar( 'refetchEvents' ); } function confirmCancelShow(show_instance_id){ if (confirm($.i18n._('Cancel Current Show?'))) { var url = baseUrl+"Schedule/cancel-current-show"; $.ajax({ url: url, data: {format: "json", id: show_instance_id}, success: function(data){ scheduleRefetchEvents(data); } }); } } function confirmCancelRecordedShow(show_instance_id){ if (confirm($.i18n._('Stop recording current show?'))) { var url = baseUrl+"Schedule/cancel-current-show"; $.ajax({ url: url, data: {format: "json", id: show_instance_id}, success: function(data){ scheduleRefetchEvents(data); } }); } } function findViewportDimensions() { var viewportwidth, viewportheight; // the more standards compliant browsers (mozilla/netscape/opera/IE7) use // window.innerWidth and window.innerHeight if (typeof window.innerWidth != 'undefined') { viewportwidth = window.innerWidth, viewportheight = window.innerHeight; } // IE6 in standards compliant mode (i.e. with a valid doctype as the first // line in the document) else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) { viewportwidth = document.documentElement.clientWidth; viewportheight = document.documentElement.clientHeight; } // older versions of IE else { viewportwidth = document.getElementsByTagName('body')[0].clientWidth; viewportheight = document.getElementsByTagName('body')[0].clientHeight; } return { width: viewportwidth, height: viewportheight-45 }; } function highlightMediaTypeSelector(dialog) { var selected; if (location.hash === "") { selected = dialog.find("a[href$='#tracks']"); } else { selected = dialog.find("a[href$='"+location.hash+"']") } selected.parent().addClass("selected"); $("#library_filter").text(selected.text()); // Slightly hacky way of triggering the click event when it's outside of the anchor text dialog.find(".media_type_selector").on("click", function() { // Need get(0) here so we don't create a stack overflow by recurring the click on the parent $(this).find("a").get(0).click(); }); $(window).on('hashchange', function() { var selected = dialog.find("a[href$='"+location.hash+"']"); AIRTIME.library.selectNone(); dialog.find(".media_type_selector").each(function () { $(this).removeClass("selected"); }); $("#library_filter").text(selected.text()); selected.parent().addClass("selected"); oTable.fnDraw(); }); } function buildTimerange(dialog) { var builder = dialog.find("#show_builder"), oBaseDatePickerSettings = { dateFormat: 'yy-mm-dd', //i18n_months, i18n_days_short are in common.js monthNames: i18n_months, dayNamesMin: i18n_days_short, onClick: function(sDate, oDatePicker) { $(this).datepicker("setDate", sDate); }, onClose: validateTimeRange }, oBaseTimePickerSettings = { showPeriodLabels: false, showCloseButton: true, closeButtonText: $.i18n._("Done"), showLeadingZero: false, defaultTime: '0:00', hourText: $.i18n._("Hour"), minuteText: $.i18n._("Minute"), onClose: validateTimeRange }; /* * Icon hover states for search. */ builder.on("mouseenter", ".sb-timerange .ui-button", function(ev) { $(this).addClass("ui-state-hover"); }); builder.on("mouseleave", ".sb-timerange .ui-button", function(ev) { $(this).removeClass("ui-state-hover"); }); builder.find(dateStartId) .datepicker(oBaseDatePickerSettings); builder.find(timeStartId) .timepicker(oBaseTimePickerSettings); builder.find(dateEndId) .datepicker(oBaseDatePickerSettings); builder.find(timeEndId) .timepicker(oBaseTimePickerSettings); var oRange = AIRTIME.utilities.fnGetScheduleRange(dateStartId, timeStartId, dateEndId, timeEndId); AIRTIME.showbuilder.fnServerData.start = oRange.start; AIRTIME.showbuilder.fnServerData.end = oRange.end; } function buildScheduleDialog (json, instance_id) { var dialog = $(json.dialog), viewport = findViewportDimensions(), height = Math.floor(viewport.height * 0.96), width = Math.floor(viewport.width * 0.96), fnServer = AIRTIME.showbuilder.fnServerData; dialog.dialog({ autoOpen: false, title: json.title, width: width, height: height, resizable: false, draggable: true, modal: true, close: closeDialogCalendar, buttons: [ { text: $.i18n._("Ok"), class: "btn", click: function() { $(this).dialog("close"); //getUsabilityHint(); } } ] }); //set the start end times so the builder datatables knows its time range. fnServer.start = json.start; fnServer.end = json.end; fnServer.ops = {}; fnServer.ops.showFilter = 0; fnServer.ops.showInstanceFilter = instance_id; fnServer.ops.myShows = 0; AIRTIME.library.libraryInit(); AIRTIME.showbuilder.builderDataTable(); dialog.dialog('open'); highlightMediaTypeSelector(dialog); buildTimerange(dialog); } function buildContentDialog (json){ var dialog = $(json.dialog), viewport = findViewportDimensions(), height = viewport.height * 2/3, width = viewport.width * 4/5; if (json.show_error == true){ alertShowErrorAndReload(); } dialog.find("#show_progressbar").progressbar({ value: json.percentFilled }); dialog.dialog({ autoOpen: false, title: $.i18n._("Contents of Show") +" '" + json.showTitle + "'", width: width, height: height, modal: true, close: closeDialogCalendar, buttons: [ { text: $.i18n._("Ok"), "class": "btn", click: function() { dialog.remove(); } } ] }); dialog.dialog('open'); } /** * Use user preference for time scale; defaults to month if preference was never set */ function getTimeScalePreference(data) { return data.calendarInit.timeScale; } /** * Use user preference for time interval; defaults to 30m if preference was never set */ function getTimeIntervalPreference(data) { return parseInt(data.calendarInit.timeInterval); } function createFullCalendar(data){ serverTimezoneOffset = data.calendarInit.timezoneOffset; var mainHeight = $(window).height() - 200 - 35; $('#schedule_calendar').fullCalendar({ header: { left: 'prev, next, today', center: 'title', right: 'agendaDay, agendaWeek, month' }, defaultView: getTimeScalePreference(data), slotMinutes: getTimeIntervalPreference(data), firstDay: data.calendarInit.weekStartDay, editable: false, allDaySlot: false, axisFormat: 'H:mm', timeFormat: { agenda: 'H:mm{ - H:mm}', month: 'H:mm{ - H:mm}' }, //i18n_months is in common.js monthNames: i18n_months, monthNamesShort: [ $.i18n._('Jan'), $.i18n._('Feb'), $.i18n._('Mar'), $.i18n._('Apr'), $.i18n._('May'), $.i18n._('Jun'), $.i18n._('Jul'), $.i18n._('Aug'), $.i18n._('Sep'), $.i18n._('Oct'), $.i18n._('Nov'), $.i18n._('Dec') ], buttonText: { today: $.i18n._('Today'), month: $.i18n._('Month'), week: $.i18n._('Week'), day: $.i18n._('Day') }, dayNames: [ $.i18n._('Sunday'), $.i18n._('Monday'), $.i18n._('Tuesday'), $.i18n._('Wednesday'), $.i18n._('Thursday'), $.i18n._('Friday'), $.i18n._('Saturday') ], dayNamesShort: [ $.i18n._('Sun'), $.i18n._('Mon'), $.i18n._('Tue'), $.i18n._('Wed'), $.i18n._('Thu'), $.i18n._('Fri'), $.i18n._('Sat') ], contentHeight: mainHeight, theme: true, lazyFetching: true, serverTimestamp: parseInt(data.calendarInit.timestamp, 10), serverTimezoneOffset: parseInt(data.calendarInit.timezoneOffset, 10), events: getFullCalendarEvents, //callbacks (in full-calendar-functions.js) viewDisplay: viewDisplay, dayClick: dayClick, eventRender: eventRender, eventAfterRender: eventAfterRender, eventDrop: eventDrop, eventResize: eventResize, windowResize: windowResize }); } //Alert the error and reload the page //this function is used to resolve concurrency issue function alertShowErrorAndReload(){ alert($.i18n._("The show instance doesn't exist anymore!")); window.location.reload(); } $(document).ready(function() { $.contextMenu({ selector: 'div.fc-event', trigger: "left", ignoreRightClick: true, className: 'calendar-context-menu', build: function($el, e) { var data, items, callback; data = $el.data("event"); function processMenuItems(oItems) { //define a schedule callback. if (oItems.schedule !== undefined) { callback = function() { $.post(oItems.schedule.url, {format: "json", id: data.id}, function(json){ buildScheduleDialog(json, data.id); }); }; oItems.schedule.callback = callback; } //define a clear callback. if (oItems.clear !== undefined) { callback = function() { if (confirm($.i18n._("Remove all content?"))) { $.post(oItems.clear.url, {format: "json", id: data.id}, function(json){ scheduleRefetchEvents(json); }); } }; oItems.clear.callback = callback; } //define an edit callback. if (oItems.edit !== undefined) { if(oItems.edit.items !== undefined){ var edit = oItems.edit.items; //edit a single instance callback = function() { $.get(edit.instance.url, {format: "json", showId: data.showId, instanceId: data.id, type: "instance"}, function(json){ beginEditShow(json); }); }; edit.instance.callback = callback; //edit this instance and all callback = function() { $.get(edit.all.url, {format: "json", showId: data.showId, instanceId: data.id, type: "all"}, function(json){ beginEditShow(json); }); }; edit.all.callback = callback; }else{ callback = function() { $.get(oItems.edit.url, {format: "json", showId: data.showId, instanceId: data.id, type: oItems.edit._type}, function(json){ beginEditShow(json); }); }; oItems.edit.callback = callback; } } //define a content callback. if (oItems.content !== undefined) { callback = function() { $.get(oItems.content.url, {format: "json", id: data.id}, function(json){ buildContentDialog(json); }); }; oItems.content.callback = callback; } //define a cancel recorded show callback. if (oItems.cancel_recorded !== undefined) { callback = function() { confirmCancelRecordedShow(data.id); }; oItems.cancel_recorded.callback = callback; } //define a view recorded callback. if (oItems.view_recorded !== undefined) { callback = function() { $.get(oItems.view_recorded.url, {format: "json"}, function(json){ //in library.js buildEditMetadataDialog(json); }); }; oItems.view_recorded.callback = callback; } //define a cancel callback. if (oItems.cancel !== undefined) { callback = function() { confirmCancelShow(data.id); }; oItems.cancel.callback = callback; } //define a delete callback. if (oItems.del !== undefined) { //repeating show multiple delete options if (oItems.del.items !== undefined) { var del = oItems.del.items; //delete a single instance callback = function() { $.post(del.single.url, {format: "json", id: data.id}, function(json){ scheduleRefetchEvents(json); }); }; del.single.callback = callback; //delete this instance and all following instances. callback = function() { $.post(del.following.url, {format: "json", id: data.id}, function(json){ scheduleRefetchEvents(json); }); }; del.following.callback = callback; } //single show else { callback = function() { $.post(oItems.del.url, {format: "json", id: data.id}, function(json){ scheduleRefetchEvents(json); }); }; oItems.del.callback = callback; } } items = oItems; } $.ajax({ url: baseUrl+"schedule/make-context-menu", type: "GET", data: {instanceId : data.id, showId: data.showId, format: "json"}, dataType: "json", async: false, success: function(json){ processMenuItems(json.items); } }); return { className: 'calendar-context-menu', items: items, determinePosition : function($menu, x, y) { $menu.css('display', 'block') .position({ my: "left top", at: "right top", of: this, offset: "-20 10", collision: "fit"}) .css('display', 'none'); } }; } }); });
agpl-3.0
moufmouf/packanalyst
src/Mouf/Packanalyst/Services/PackagistScoreService.php
1710
<?php namespace Mouf\Packanalyst\Services; use Mouf\Packanalyst\Dao\PackageDao; use Psr\Log\LoggerInterface; use GuzzleHttp; /** * This class is in charge of retrieving nb of downloads from Packagist and applying them in the Mongo database. * * @author David Négrier <[email protected]> */ class PackagistScoreService { private $packageDao; private $logger; // Number of seconds to wait between requests const WAIT_TIME_BETWEEN_REQUESTS = 10; public function __construct(PackageDao $packageDao, LoggerInterface $logger) { $this->packageDao = $packageDao; $this->logger = $logger; } public function updateAllScores() { $i = 1; do { $this->logger->notice('Downloading scores for page {page}', ['page' => $i]); $result = $this->request($i); foreach ($result['results'] as $packageResult) { $packages = $this->packageDao->getPackagesByName($packageResult['name']); foreach ($packages as $package) { $package['downloads'] = $packageResult['downloads']; $package['favers'] = $packageResult['favers']; $this->packageDao->save($package); } } sleep(self::WAIT_TIME_BETWEEN_REQUESTS); ++$i; } while (isset($result['next'])); } /** * Performs a request to the API, returns. * * @param number $page */ private function request($page = 1) { $client = new GuzzleHttp\Client(); $response = $client->get('https://packagist.org/search.json?q=&page='.$page); return $response->json(); } }
agpl-3.0
grafana/grafana
pkg/services/ngalert/api/lotex_am.go
5856
package api import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "strconv" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" "github.com/grafana/grafana/pkg/web" "gopkg.in/yaml.v3" ) var endpoints = map[string]map[string]string{ "cortex": { "silences": "/alertmanager/api/v2/silences", "silence": "/alertmanager/api/v2/silence/%s", "status": "/alertmanager/api/v2/status", "groups": "/alertmanager/api/v2/alerts/groups", "alerts": "/alertmanager/api/v2/alerts", "config": "/api/v1/alerts", }, "prometheus": { "silences": "/api/v2/silences", "silence": "/api/v2/silence/%s", "status": "/api/v2/status", "groups": "/api/v2/alerts/groups", "alerts": "/api/v2/alerts", }, } const ( defaultImplementation = "cortex" ) type LotexAM struct { log log.Logger *AlertingProxy } func NewLotexAM(proxy *AlertingProxy, log log.Logger) *LotexAM { return &LotexAM{ log: log, AlertingProxy: proxy, } } func (am *LotexAM) withAMReq( ctx *models.ReqContext, method string, endpoint string, pathParams []string, body io.Reader, extractor func(*response.NormalResponse) (interface{}, error), headers map[string]string, ) response.Response { recipient, err := strconv.ParseInt(web.Params(ctx.Req)[":Recipient"], 10, 64) if err != nil { return response.Error(http.StatusBadRequest, "Recipient is invalid", err) } ds, err := am.DataProxy.DataSourceCache.GetDatasource(ctx.Req.Context(), recipient, ctx.SignedInUser, ctx.SkipCache) if err != nil { if errors.Is(err, models.ErrDataSourceAccessDenied) { return ErrResp(http.StatusForbidden, err, "Access denied to datasource") } if errors.Is(err, models.ErrDataSourceNotFound) { return ErrResp(http.StatusNotFound, err, "Unable to find datasource") } return ErrResp(http.StatusInternalServerError, err, "Unable to load datasource meta data") } impl := ds.JsonData.Get("implementation").MustString(defaultImplementation) implEndpoints, ok := endpoints[impl] if !ok { return ErrResp(http.StatusBadRequest, fmt.Errorf("unsupported Alert Manager implementation \"%s\"", impl), "") } endpointPath, ok := implEndpoints[endpoint] if !ok { return ErrResp(http.StatusBadRequest, fmt.Errorf("unsupported endpoint \"%s\" for Alert Manager implementation \"%s\"", endpoint, impl), "") } iPathParams := make([]interface{}, len(pathParams)) for idx, value := range pathParams { iPathParams[idx] = value } return am.withReq( ctx, method, withPath(*ctx.Req.URL, fmt.Sprintf(endpointPath, iPathParams...)), body, extractor, headers, ) } func (am *LotexAM) RouteGetAMStatus(ctx *models.ReqContext) response.Response { return am.withAMReq( ctx, http.MethodGet, "status", nil, nil, jsonExtractor(&apimodels.GettableStatus{}), nil, ) } func (am *LotexAM) RouteCreateSilence(ctx *models.ReqContext, silenceBody apimodels.PostableSilence) response.Response { blob, err := json.Marshal(silenceBody) if err != nil { return ErrResp(500, err, "Failed marshal silence") } return am.withAMReq( ctx, http.MethodPost, "silences", nil, bytes.NewBuffer(blob), jsonExtractor(&apimodels.GettableSilence{}), map[string]string{"Content-Type": "application/json"}, ) } func (am *LotexAM) RouteDeleteAlertingConfig(ctx *models.ReqContext) response.Response { return am.withAMReq( ctx, http.MethodDelete, "config", nil, nil, messageExtractor, nil, ) } func (am *LotexAM) RouteDeleteSilence(ctx *models.ReqContext) response.Response { return am.withAMReq( ctx, http.MethodDelete, "silence", []string{web.Params(ctx.Req)[":SilenceId"]}, nil, messageExtractor, nil, ) } func (am *LotexAM) RouteGetAlertingConfig(ctx *models.ReqContext) response.Response { return am.withAMReq( ctx, http.MethodGet, "config", nil, nil, yamlExtractor(&apimodels.GettableUserConfig{}), nil, ) } func (am *LotexAM) RouteGetAMAlertGroups(ctx *models.ReqContext) response.Response { return am.withAMReq( ctx, http.MethodGet, "groups", nil, nil, jsonExtractor(&apimodels.AlertGroups{}), nil, ) } func (am *LotexAM) RouteGetAMAlerts(ctx *models.ReqContext) response.Response { return am.withAMReq( ctx, http.MethodGet, "alerts", nil, nil, jsonExtractor(&apimodels.GettableAlerts{}), nil, ) } func (am *LotexAM) RouteGetSilence(ctx *models.ReqContext) response.Response { return am.withAMReq( ctx, http.MethodGet, "silence", []string{web.Params(ctx.Req)[":SilenceId"]}, nil, jsonExtractor(&apimodels.GettableSilence{}), nil, ) } func (am *LotexAM) RouteGetSilences(ctx *models.ReqContext) response.Response { return am.withAMReq( ctx, http.MethodGet, "silences", nil, nil, jsonExtractor(&apimodels.GettableSilences{}), nil, ) } func (am *LotexAM) RoutePostAlertingConfig(ctx *models.ReqContext, config apimodels.PostableUserConfig) response.Response { yml, err := yaml.Marshal(&config) if err != nil { return ErrResp(500, err, "Failed marshal alert manager configuration ") } return am.withAMReq( ctx, http.MethodPost, "config", nil, bytes.NewBuffer(yml), messageExtractor, nil, ) } func (am *LotexAM) RoutePostAMAlerts(ctx *models.ReqContext, alerts apimodels.PostableAlerts) response.Response { yml, err := yaml.Marshal(alerts) if err != nil { return ErrResp(500, err, "Failed marshal postable alerts") } return am.withAMReq( ctx, http.MethodPost, "alerts", nil, bytes.NewBuffer(yml), messageExtractor, nil, ) } func (am *LotexAM) RoutePostTestReceivers(ctx *models.ReqContext, config apimodels.TestReceiversConfigBodyParams) response.Response { return NotImplementedResp }
agpl-3.0
daily-bruin/meow
meow/scheduler/migrations/0009_auto_20190607_1518.py
538
# Generated by Django 2.0.4 on 2019-06-07 22:18 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('scheduler', '0008_auto_20190606_1503'), ] operations = [ migrations.AlterField( model_name='posthistory', name='last_edit_user', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
agpl-3.0
gnosygnu/xowa_android
_400_xowa/src/main/java/gplx/xowa/apps/apis/xowa/gui/browsers/Xoapi_prog_log.java
682
package gplx.xowa.apps.apis.xowa.gui.browsers; import gplx.*; import gplx.xowa.*; import gplx.xowa.apps.*; import gplx.xowa.apps.apis.*; import gplx.xowa.apps.apis.xowa.*; import gplx.xowa.apps.apis.xowa.gui.*; import gplx.gfui.*; import gplx.xowa.guis.views.*; public class Xoapi_prog_log implements Gfo_invk { public void Init_by_kit(Xoae_app app) {this.app = app;} private Xoae_app app; public void Show() {app.Gui_mgr().Show_prog();} public Object Invk(GfsCtx ctx, int ikey, String k, GfoMsg m) { if (ctx.Match(k, Invk_show)) this.Show(); else return Gfo_invk_.Rv_unhandled; return this; } private static final String Invk_show = "show"; }
agpl-3.0
JaapJoris/bps
manage.py
239
#!/usr/bin/env python3 import os, sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bps.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
agpl-3.0
lnogues/superdesk-client-core
scripts/superdesk-desks/controllers/DeskListController.js
1869
DeskListController.$inject = ['$scope', 'desks', 'superdesk', 'privileges', 'tasks', 'api', 'betaService']; export function DeskListController($scope, desks, superdesk, privileges, tasks, api, beta) { var userDesks; function sorted(result) { var items = result._items || []; items.sort(compareNames); return items; function compareNames(a, b) { return a.name.localeCompare(b.name); } } desks.initialize() .then(function() { $scope.desks = desks.desks; $scope.deskStages = desks.deskStages; desks.fetchCurrentUserDesks().then(function (desk_list) { userDesks = desk_list._items; }); }); $scope.statuses = tasks.statuses; $scope.online_users = false; api('roles').query().then(function(result) { $scope.roles = sorted(result); }); $scope.privileges = privileges.privileges; beta.isBeta().then(function(isBeta) { var views = ['content', 'users', 'sluglines']; if (isBeta) { views = ['content', 'tasks', 'users', 'sluglines']; } $scope.$applyAsync(function() { $scope.views = views; $scope.view = $scope.views[0]; }); }); $scope.setView = function(view) { $scope.view = view; }; $scope.changeOnlineUsers = function(value) { $scope.online_users = value; }; $scope.isMemberOf = function(desk) { return _.find(userDesks, {_id: desk._id}); }; $scope.openDeskView = function(desk, target) { desks.setCurrentDeskId(desk._id); superdesk.intent('view', target); }; $scope.$on('desks:refresh:stages', function(e, deskId) { desks.refreshStages().then(function() { $scope.deskStages[deskId] = desks.deskStages[deskId]; }); }); }
agpl-3.0
newspeak/newspeak-server
shared/newspeak/src/newspeak/filter/upload_test.go
281
package filter_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" // . "newspeak/filter" ) var _ = Describe("Upload", func() { Context("example context", func() { It("should pass", func() { example := true Expect(example).To(Equal(true)) }) }) })
agpl-3.0
boob-sbcm/3838438
src/main/java/com/rapidminer/gui/properties/ExpressionPropertyDialog.java
52337
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.properties; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.text.BadLocationException; import org.fife.ui.rsyntaxtextarea.AbstractTokenMakerFactory; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.Style; import org.fife.ui.rsyntaxtextarea.SyntaxScheme; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenMakerFactory; import org.fife.ui.rtextarea.Gutter; import org.fife.ui.rtextarea.RTextScrollPane; import org.jdesktop.swingx.JXTaskPane; import com.rapidminer.Process; import com.rapidminer.gui.look.Colors; import com.rapidminer.gui.tools.ExtendedJScrollPane; import com.rapidminer.gui.tools.FilterListener; import com.rapidminer.gui.tools.FilterTextField; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.gui.tools.ScrollableJPopupMenu; import com.rapidminer.gui.tools.SwingTools; import com.rapidminer.gui.tools.TextFieldWithAction; import com.rapidminer.gui.tools.syntax.ExpressionTokenMaker; import com.rapidminer.operator.Operator; import com.rapidminer.operator.ports.InputPort; import com.rapidminer.operator.ports.metadata.ExampleSetMetaData; import com.rapidminer.operator.ports.metadata.ModelMetaData; import com.rapidminer.parameter.ParameterTypeExpression; import com.rapidminer.tools.FontTools; import com.rapidminer.tools.I18N; import com.rapidminer.tools.Observable; import com.rapidminer.tools.Observer; import com.rapidminer.tools.expression.ExampleResolver; import com.rapidminer.tools.expression.ExpressionException; import com.rapidminer.tools.expression.ExpressionParser; import com.rapidminer.tools.expression.ExpressionParserBuilder; import com.rapidminer.tools.expression.ExpressionRegistry; import com.rapidminer.tools.expression.FunctionDescription; import com.rapidminer.tools.expression.FunctionInput; import com.rapidminer.tools.expression.FunctionInput.Category; import com.rapidminer.tools.expression.MacroResolver; /** * * The {@link ExpressionPropertyDialog} enables to enter an expression out of functions, attribute * values, constants and macro values and validates the expression's syntax. * * @author Ingo Mierswa, Marco Boeck, Sabrina Kirstein * */ public class ExpressionPropertyDialog extends PropertyDialog { private static final long serialVersionUID = 5567661137372752202L; /** * An input panel owns an {@link Observer}, which is updated about model changes. * * @author Sabrina Kirstein */ private class PrivateInputObserver implements Observer<FunctionInputPanel> { @Override public void update(Observable<FunctionInputPanel> observable, FunctionInputPanel arg) { if (arg != null) { // add the function name to the expression if (arg.getCategory() == Category.SCOPE) { boolean predefined = false; for (String predefinedMacro : controllingProcess.getMacroHandler() .getAllGraphicallySupportedPredefinedMacros()) { // if this is a predefined macro if (predefinedMacro.equals(arg.getInputName())) { // if the old expression parser is supported if (parser.getExpressionContext().getFunction("macro") != null) { // if the predefined macro is the number applied times, evaluate it if (predefinedMacro .equals(Operator.STRING_EXPANSION_MACRO_NUMBER_APPLIED_TIMES_USER_FRIENDLY) || predefinedMacro.equals(Operator.STRING_EXPANSION_MACRO_NUMBER_APPLIED_TIMES)) { addToExpression("%{" + arg.getInputName() + "}"); // otherwise show the string } else { addToExpression("macro(\"" + arg.getInputName() + "\")"); } } else { // if the predefined macro is the number applied times, evaluate it if (predefinedMacro .equals(Operator.STRING_EXPANSION_MACRO_NUMBER_APPLIED_TIMES_USER_FRIENDLY) || predefinedMacro.equals(Operator.STRING_EXPANSION_MACRO_NUMBER_APPLIED_TIMES)) { addToExpression("eval(%{" + arg.getInputName() + "})"); // otherwise show the string } else { addToExpression("%{" + arg.getInputName() + "}"); } } predefined = true; break; } } // if the macro is a custom macro, give the user the choice between adding the // value or an evaluated expression (only if "macro" and/or "eval" functions // available in the dialog context) if (!predefined) { if (parser.getExpressionContext().getFunction("macro") != null || parser.getExpressionContext().getFunction("eval") != null) { MacroSelectionDialog macroSelectionDialog = new MacroSelectionDialog(arg, parser.getExpressionContext().getFunction("macro") != null); macroSelectionDialog.setLocation(arg.getLocationOnScreen().x, arg.getLocationOnScreen().y + 40); macroSelectionDialog.setVisible(true); addToExpression(macroSelectionDialog.getExpression()); } else { addToExpression("%{" + arg.getInputName() + "}"); } } } else if (arg.getCategory() == Category.DYNAMIC) { if (parser.getExpressionContext().getConstant(arg.getInputName()) != null) { // if the attribute has the same name as a constant, add it with the // brackets addToExpression("[" + arg.getInputName() + "]"); } else if (arg.getInputName().matches("(^[A-Za-z])([A-Z_a-z\\d]*)")) { // check whether the attribute is alphanumerical without a number at the // front addToExpression(arg.getInputName()); } else { // if the attribute is not alphanumeric, add it with the brackets, // escape [ , ] and \ String inputName = arg.getInputName().replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]"); addToExpression("[" + inputName + "]"); } } else { addToExpression(arg.getInputName()); } } else { // the filtered model changed: // update the panels in regard to the filtered model updateInputs(); } } } /** * {@link FunctionDescriptionPanel} owns an {@link Observer}, which is updated on model changes. * * @author Sabrina Kirstein */ private class PrivateModelObserver implements Observer<FunctionDescription> { @Override public void update(Observable<FunctionDescription> observable, FunctionDescription arg) { if (arg != null) { // add the function name to the expression addToExpression(arg.getDisplayName(), arg); } else { // the filtered model changed: // update the panels in regard to the filtered model updateFunctions(); } } } /** * * Mouse listener to react on hover events of the filter menu button. Highlights the button, * when hovered. * * @author Sabrina Kirstein * */ private final class HoverBorderMouseListener extends MouseAdapter { private final JButton button; public HoverBorderMouseListener(final JButton pageButton) { this.button = pageButton; } @Override public void mouseReleased(final MouseEvent e) { if (!button.isEnabled()) { button.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); } super.mouseReleased(e); } @Override public void mouseExited(final MouseEvent e) { button.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); super.mouseExited(e); } @Override public void mouseEntered(final MouseEvent e) { if (button.isEnabled()) { button.setBorder(BorderFactory.createLineBorder(SwingTools.RAPIDMINER_ORANGE, 1)); } super.mouseEntered(e); } } // EXPRESSION /** text area with the highlighted current expression */ private RSyntaxTextArea currentExpression = new RSyntaxTextArea(); /** scroll pane of the text area with the highlighted current expression */ private RTextScrollPane scrollPaneExpression = new RTextScrollPane(); // PARSER private final ExpressionParser parser; private final com.rapidminer.Process controllingProcess; // INPUTS /** search text filter of the inputs field */ private final FilterTextField inputsFilterField = new FilterTextField(12); /** QuickFilter: Nominal */ private JCheckBox chbNominal; /** QuickFilter: Numeric */ private JCheckBox chbNumeric; /** QuickFilter: Date_time */ private JCheckBox chbDateTime; /** the input categorization panes */ private Map<String, JXTaskPane> inputCategoryTaskPanes; /** model of the inputs */ private FunctionInputsModel inputsModel = new FunctionInputsModel(); /** observer to update the GUI, if the model changed or an input value was clicked */ private PrivateInputObserver inputObserver = new PrivateInputObserver(); /** listener which checks if the value of the filter string changed */ private FilterListener filterInputsListener = new FilterListener() { @Override public void valueChanged(String value) { // gives the filter string to the model inputsModel.setFilterNameString(value); } }; /** action which is executed when the filter search field is cleared */ private transient final ResourceAction clearInputsFilterAction = new ResourceAction(true, "clear_filter") { private static final long serialVersionUID = 3236281211064051583L; @Override public void actionPerformed(final ActionEvent e) { inputsFilterField.clearFilter(); inputsModel.setFilterNameString(""); inputsFilterField.requestFocusInWindow(); } }; /** panel containing this {@link FunctionInput}s part */ private JPanel inputsPanel = new JPanel(); /** layout of the inputs part */ private GridBagLayout inputsLayout; // FUNCTIONS /** search text field in the {@link FunctionDescription}s part */ private final FilterTextField functionsFilterField = new FilterTextField(12); /** the function categorization panes */ private Map<String, JXTaskPane> functionCategoryTaskPanes; /** model of the {@link FunctionDescription}s */ private FunctionDescriptionModel functionModel = new FunctionDescriptionModel(); /** observer to update the GUI, if the model changed or a function was clicked */ private PrivateModelObserver functionObserver = new PrivateModelObserver(); /** listener which checks if the value of the filter string changed */ private FilterListener filterFunctionsListener = new FilterListener() { @Override public void valueChanged(String value) { functionModel.setFilterNameString(value); } }; /** action which is executed when the filter search field is cleared */ private transient final ResourceAction clearFunctionsFilterAction = new ResourceAction(true, "clear_filter") { private static final long serialVersionUID = 3236281211064051583L; @Override public void actionPerformed(final ActionEvent e) { functionsFilterField.clearFilter(); functionModel.setFilterNameString(""); functionsFilterField.requestFocusInWindow(); } }; /** scroll pane containing the different {@link FunctionDescriptionPanel}s */ private JScrollPane functionButtonScrollPane; /** panel containing the {@link FunctionDescription}s part */ private JPanel functionsPanel = new JPanel(); /** layout of the functions part */ private GridBagLayout functionButtonsLayout = new GridBagLayout(); /** * hack to prevent filter popup (inputs part) from opening itself again when you click the * button to actually close it while it is open */ private long lastPopupCloseTime; /** syntax highlighting color */ private static final Color DARK_PURPLE = new Color(139, 0, 139); /** syntax highlighting color */ private static final Color DARK_CYAN = new Color(0, 139, 139); /** color of the validation label, when no error occured */ private static final Color DARK_GREEN = new Color(45, 136, 45); /** the background color of the lists with functions */ private static final Color LIGHTER_GRAY = Colors.WINDOW_BACKGROUND; /** Color of the expression border */ private static final Color COLOR_BORDER_EXPRESSION = Colors.TEXTFIELD_BORDER; /** Color of the category title {@link JXTaskPane}s */ private static final Color COLOR_TITLE_TASKPANE_BACKGROUND = new Color(230, 230, 230); /** icon to of the search text field, which is shown when the clear filter icon is hovered */ private static final ImageIcon CLEAR_FILTER_HOVERED_ICON = SwingTools.createIcon("16/x-mark_orange.png"); /** maximal number of {@link FunctionInput}s that is shown in open {@link JXTaskPane}(s) */ private static final int MAX_NMBR_INPUTS_SHOWN = 7; /** * maximal number of {@link FunctionDescription}s that is shown in open {@link JXTaskPane}(s) */ private static final int MAX_NMBR_FUNCTIONS_SHOWN = 15; /** size of the expression */ private static final int NUMBER_OF_EXPRESSION_ROWS = 6; /** message when the search in the model resulted in an empty set */ private static final String MESSAGE_NO_RESULTS = " No search results found."; /** Icon name of the error icon (parser) */ private static final String ERROR_ICON_NAME = "error.png"; /** The font size of the categories({@link JXTaskPane}s) titles */ private static final String FONT_SIZE_HEADER = "5"; /** maximal width of the inputs panel part */ private static final int WIDTH_ATTRIBUTE_PANEL = 350; /** width of the search field in the inputs part */ private static final int WIDTH_INPUTS_SEARCH_FIELD = 200; /** width of the search field in the functions part */ private static final int WIDTH_FUNCTION_SEARCH_FIELD = 300; /** height of the expression field */ private static final int HEIGHT_EXPRESSION_SCROLL_PANE = 120; /** height of the search fields */ private static final int HEIGHT_SEARCH_FIELD = 24; /** standard padding size */ private static final int STD_INSET_GBC = 7; /** error icon (parser) */ private static Icon ERROR_ICON = null; static { ERROR_ICON = SwingTools.createIcon("13/" + ERROR_ICON_NAME); } /** label showing a validation result of the expression */ private JLabel validationLabel = new JLabel(); private JTextArea validationTextArea = new JTextArea(); /** typical filter icon */ private static final ImageIcon ICON_FILTER = SwingTools.createIcon("16/" + "funnel.png"); /** * Creates an {@link ExpressionPropertyDialog} with the given initial value. * * @param type * @param initialValue */ public ExpressionPropertyDialog(final ParameterTypeExpression type, String initialValue) { this(type, null, initialValue); } /** * Creates an {@link ExpressionPropertyDialog} with the given initial value, controlling * process, expression parser, input model and function model * * @param type * @param process * @param inputs * @param functions * @param parser * @param initialValue */ public ExpressionPropertyDialog(ParameterTypeExpression type, Process process, List<FunctionInput> inputs, List<FunctionDescription> functions, ExpressionParser parser, String initialValue) { super(type, "expression"); this.inputsModel.addObserver(inputObserver, false); this.functionModel.addObserver(functionObserver, false); this.controllingProcess = getControllingProcessOrNull(type, process); this.inputsModel.addContent(inputs); this.functionModel.addContent(functions); this.parser = parser; ExpressionTokenMaker.removeFunctionInputs(); ExpressionTokenMaker.addFunctionInputs(inputs); ExpressionTokenMaker.addFunctions(functions); initGui(initialValue); FunctionDescriptionPanel.updateMaximalWidth(functionsPanel.getSize().width); updateFunctions(); } /** * Creates an {@link ExpressionPropertyDialog} with the given initial value and a controlling * process * * @param type * @param process * @param initialValue */ public ExpressionPropertyDialog(ParameterTypeExpression type, Process process, String initialValue) { super(type, "expression"); // add observers to receive model updates inputsModel.addObserver(inputObserver, false); functionModel.addObserver(functionObserver, false); // create ExpressionParser with Process to enable Process functions controllingProcess = getControllingProcessOrNull(type, process); // use the ExpressionParserBuilder to create the parser ExpressionParserBuilder builder = new ExpressionParserBuilder(); // use a compatibility level to only show functions that are available if (type.getInputPort() != null) { builder = builder .withCompatibility(type.getInputPort().getPorts().getOwner().getOperator().getCompatibilityLevel()); } if (controllingProcess != null) { builder = builder.withProcess(controllingProcess); // make macros available to the parser builder = builder.withScope(new MacroResolver(controllingProcess.getMacroHandler())); } // make attributes available to the parser InputPort inPort = ((ParameterTypeExpression) getParameterType()).getInputPort(); if (inPort != null) { if (inPort.getMetaData() instanceof ExampleSetMetaData) { ExampleSetMetaData emd = (ExampleSetMetaData) inPort.getMetaData(); if (emd != null) { builder = builder.withDynamics(new ExampleResolver(emd)); } } else if (inPort.getMetaData() instanceof ModelMetaData) { ModelMetaData mmd = (ModelMetaData) inPort.getMetaData(); if (mmd != null) { ExampleSetMetaData emd = mmd.getTrainingSetMetaData(); if (emd != null) { builder = builder.withDynamics(new ExampleResolver(emd)); } } } } // show all registered modules builder = builder.withModules(ExpressionRegistry.INSTANCE.getAll()); // finally create the parser parser = builder.build(); // fetch the expression context from the parser // add the current function inputs to the functions input model inputsModel.addContent(parser.getExpressionContext().getFunctionInputs()); // add the existing functions to the functions model functionModel.addContent(parser.getExpressionContext().getFunctionDescriptions()); // remove deprecated expression context from the syntax highlighting ExpressionTokenMaker.removeFunctionInputs(); // add the current expression context to the syntax highlighting ExpressionTokenMaker.addFunctionInputs(parser.getExpressionContext().getFunctionInputs()); ExpressionTokenMaker.addFunctions(parser.getExpressionContext().getFunctionDescriptions()); // initialize the UI initGui(initialValue); FunctionDescriptionPanel.updateMaximalWidth(functionsPanel.getSize().width); updateFunctions(); } private Process getControllingProcessOrNull(ParameterTypeExpression type, Process process) { if (process != null) { return process; } else if (type.getInputPort() != null) { return type.getInputPort().getPorts().getOwner().getOperator().getProcess(); } else { return null; } } /** * Initializes the UI of the dialog. * * @param initialValue * of the expression */ public void initGui(String initialValue) { // this is the only way to set colors for the JXTaskPane component /* background color */ UIManager.put("TaskPane.background", LIGHTER_GRAY); /* title hover color */ UIManager.put("TaskPane.titleOver", SwingTools.RAPIDMINER_ORANGE); UIManager.put("TaskPane.specialTitleOver", SwingTools.RAPIDMINER_ORANGE); /* border color */ UIManager.put("TaskPane.borderColor", LIGHTER_GRAY); /* foreground */ UIManager.put("TaskPane.foreground", Color.black); UIManager.put("TaskPane.titleForeground", Color.black); UIManager.put("TaskPane.specialTitleForeground", Color.black); /* title background */ UIManager.put("TaskPane.specialTitleBackground", COLOR_TITLE_TASKPANE_BACKGROUND); UIManager.put("TaskPane.titleBackgroundGradientStart", COLOR_TITLE_TASKPANE_BACKGROUND); UIManager.put("TaskPane.titleBackgroundGradientEnd", COLOR_TITLE_TASKPANE_BACKGROUND); // add OK and cancel button Collection<AbstractButton> buttons = new LinkedList<AbstractButton>(); final JButton okButton = makeOkButton("expression_property_dialog_apply"); buttons.add(okButton); buttons.add(makeCancelButton()); // Create the main panel JPanel mainPanel = new JPanel(); GridBagLayout mainLayout = new GridBagLayout(); mainPanel.setLayout(mainLayout); GridBagConstraints mainC = new GridBagConstraints(); mainC.fill = GridBagConstraints.BOTH; mainC.weightx = 1; mainC.weighty = 0; mainC.gridwidth = 2; mainC.gridx = 0; mainC.gridy = 0; mainC.insets = new Insets(0, STD_INSET_GBC, 0, STD_INSET_GBC); // EXPRESSION JPanel expressionPanel = new JPanel(); GridBagLayout expressionLayout = new GridBagLayout(); expressionPanel.setLayout(expressionLayout); GridBagConstraints expressionC = new GridBagConstraints(); expressionC.fill = GridBagConstraints.BOTH; expressionC.insets = new Insets(STD_INSET_GBC, STD_INSET_GBC, STD_INSET_GBC, STD_INSET_GBC); expressionC.gridx = 0; expressionC.gridy = 0; expressionC.gridwidth = 2; expressionC.weightx = 0; expressionC.weighty = 0; // expression title JLabel label = new JLabel("<html><b><font size=" + FONT_SIZE_HEADER + ">Expression</font></b></html>"); expressionC.gridy += 1; expressionPanel.add(label, expressionC); // current expression // validate the expression when it was changed currentExpression.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { if (e.getModifiersEx() == KeyEvent.CTRL_DOWN_MASK) { if (e.getExtendedKeyCode() == KeyEvent.VK_ENTER) { okButton.doClick(); } } } @Override public void keyReleased(KeyEvent e) { validateExpression(); } }); // Use the custom token maker to highlight RapidMiner expressions AbstractTokenMakerFactory atmf = (AbstractTokenMakerFactory) TokenMakerFactory.getDefaultInstance(); atmf.putMapping("text/expression", "com.rapidminer.gui.tools.syntax.ExpressionTokenMaker"); currentExpression.setSyntaxEditingStyle("text/expression"); // the current line should not be highlighted currentExpression.setHighlightCurrentLine(false); // enable bracket matching (just works if brackets have the token type Token.SEPARATOR) currentExpression.setBracketMatchingEnabled(true); currentExpression.setAnimateBracketMatching(true); currentExpression.setPaintMatchedBracketPair(true); // set initial size currentExpression.setRows(NUMBER_OF_EXPRESSION_ROWS); // set custom colors for syntax highlighting currentExpression.setSyntaxScheme(getExpressionColorScheme(currentExpression.getSyntaxScheme())); currentExpression.setBorder(BorderFactory.createEmptyBorder()); scrollPaneExpression = new RTextScrollPane(currentExpression, true); scrollPaneExpression.setMinimumSize(new Dimension(getMinimumSize().width, HEIGHT_EXPRESSION_SCROLL_PANE)); scrollPaneExpression.setPreferredSize(new Dimension(getPreferredSize().width, HEIGHT_EXPRESSION_SCROLL_PANE)); scrollPaneExpression.setMaximumSize(new Dimension(getMaximumSize().width, HEIGHT_EXPRESSION_SCROLL_PANE)); scrollPaneExpression.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 0, COLOR_BORDER_EXPRESSION)); scrollPaneExpression.getVerticalScrollBar() .setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Colors.TEXTFIELD_BORDER)); // use the gutter to display an error icon in the line with an error Gutter gutter = scrollPaneExpression.getGutter(); gutter.setBookmarkingEnabled(true); expressionC.gridy += 1; expressionC.weightx = 1; expressionC.insets = new Insets(0, STD_INSET_GBC, STD_INSET_GBC, STD_INSET_GBC); expressionC.fill = GridBagConstraints.BOTH; expressionC.gridwidth = 6; expressionPanel.add(scrollPaneExpression, expressionC); JPanel validationPanel = new JPanel(); validationPanel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.fill = GridBagConstraints.BOTH; // insert validation label validationLabel.setAlignmentX(SwingConstants.LEFT); validationPanel.add(validationLabel, gbc); gbc.gridy += 1; validationTextArea.setAlignmentX(SwingConstants.LEFT); validationTextArea.setEditable(false); validationTextArea.setRows(2); validationTextArea.setOpaque(false); validationTextArea.setBorder(BorderFactory.createEmptyBorder()); validationPanel.add(validationTextArea, gbc); expressionC.fill = GridBagConstraints.BOTH; expressionC.insets = new Insets(STD_INSET_GBC, STD_INSET_GBC, 0, STD_INSET_GBC); expressionC.gridx = 0; expressionC.weightx = 1; expressionC.gridy += 1; expressionC.gridwidth = 6; expressionC.anchor = GridBagConstraints.NORTHWEST; expressionPanel.add(validationPanel, expressionC); // add expression part to the main panel mainPanel.add(expressionPanel, mainC); // FUNCTIONS JPanel functionPanel = new JPanel(); GridBagLayout functionsLayout = new GridBagLayout(); functionPanel.setLayout(functionsLayout); GridBagConstraints functionsC = new GridBagConstraints(); // add functions title functionsC.insets = new Insets(0, STD_INSET_GBC, STD_INSET_GBC, STD_INSET_GBC); functionsC.gridy = 0; functionsC.gridx = 0; functionsC.anchor = GridBagConstraints.NORTHWEST; functionPanel.add(new JLabel("<html><b><font size=" + FONT_SIZE_HEADER + ">Functions</font></b></html>"), functionsC); functionsC.insets = new Insets(0, 0, STD_INSET_GBC, STD_INSET_GBC); functionsC.gridx += 1; functionsC.anchor = GridBagConstraints.SOUTHEAST; // add search field for functions functionsFilterField.addFilterListener(filterFunctionsListener); TextFieldWithAction textField = new TextFieldWithAction(functionsFilterField, clearFunctionsFilterAction, CLEAR_FILTER_HOVERED_ICON); textField.setMinimumSize(new Dimension(WIDTH_FUNCTION_SEARCH_FIELD, HEIGHT_SEARCH_FIELD)); textField.setPreferredSize(new Dimension(WIDTH_FUNCTION_SEARCH_FIELD, HEIGHT_SEARCH_FIELD)); textField.setMaximumSize(new Dimension(WIDTH_FUNCTION_SEARCH_FIELD, HEIGHT_SEARCH_FIELD)); functionPanel.add(textField, functionsC); // create the functions panel and display the existing functions updateFunctions(); JPanel outerFunctionPanel = new JPanel(); outerFunctionPanel.setLayout(new GridBagLayout()); GridBagConstraints outerFunctionC = new GridBagConstraints(); outerFunctionC.gridwidth = GridBagConstraints.REMAINDER; outerFunctionC.fill = GridBagConstraints.HORIZONTAL; outerFunctionC.weightx = 1; outerFunctionC.weighty = 1; outerFunctionC.anchor = GridBagConstraints.NORTHWEST; functionsPanel.setBackground(LIGHTER_GRAY); outerFunctionPanel.add(functionsPanel, outerFunctionC); outerFunctionC.fill = GridBagConstraints.BOTH; JPanel gapPanel2 = new JPanel(); gapPanel2.setBackground(LIGHTER_GRAY); outerFunctionPanel.add(gapPanel2, outerFunctionC); outerFunctionPanel.setBackground(LIGHTER_GRAY); // add the functions panel to the scroll bar functionButtonScrollPane = new ExtendedJScrollPane(outerFunctionPanel); functionButtonScrollPane.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Colors.TEXTFIELD_BORDER)); // the scroll bar should always be visible functionButtonScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); // add scroll pane to function panel functionsC.gridx = 0; functionsC.gridy += 1; functionsC.fill = GridBagConstraints.BOTH; functionsC.weightx = 1; functionsC.weighty = 1; functionsC.insets = new Insets(0, STD_INSET_GBC, STD_INSET_GBC, STD_INSET_GBC); functionsC.gridwidth = 2; functionsC.anchor = GridBagConstraints.NORTH; functionPanel.add(functionButtonScrollPane, functionsC); // add function panel to the main panel mainC.weighty = 1; mainC.gridwidth = 1; mainC.weightx = 0.9; mainC.gridy += 1; mainPanel.add(functionPanel, mainC); // INPUTS inputsLayout = new GridBagLayout(); inputsPanel.setLayout(inputsLayout); // add inputs panel to the outer panel JPanel outerInputPanel = new JPanel(); outerInputPanel.setLayout(new GridBagLayout()); GridBagConstraints outerInputC = new GridBagConstraints(); outerInputC.gridwidth = GridBagConstraints.REMAINDER; outerInputC.fill = GridBagConstraints.HORIZONTAL; outerInputC.weightx = 1; outerInputC.weighty = 1; outerInputC.anchor = GridBagConstraints.NORTHWEST; inputsPanel.setBackground(LIGHTER_GRAY); outerInputPanel.add(inputsPanel, outerInputC); outerInputC.weighty = 1; outerInputC.fill = GridBagConstraints.BOTH; JPanel gapPanel = new JPanel(); gapPanel.setBackground(LIGHTER_GRAY); outerInputPanel.add(gapPanel, outerInputC); // and update the view of the inputs if (inputsModel.getFilteredModel().size() > 0) { updateInputs(); // add inputs title JPanel outerInputsPanel = new JPanel(); outerInputsPanel.setLayout(new GridBagLayout()); outerInputsPanel.setMinimumSize(new Dimension(WIDTH_ATTRIBUTE_PANEL, getMinimumSize().height)); outerInputsPanel.setPreferredSize(new Dimension(WIDTH_ATTRIBUTE_PANEL, getPreferredSize().height)); outerInputsPanel.setMaximumSize(new Dimension(WIDTH_ATTRIBUTE_PANEL, getMaximumSize().height)); GridBagConstraints outerGBC = new GridBagConstraints(); outerGBC.gridx = 0; outerGBC.gridy = 0; outerGBC.insets = new Insets(0, STD_INSET_GBC, STD_INSET_GBC, STD_INSET_GBC); outerGBC.anchor = GridBagConstraints.NORTHWEST; outerInputsPanel.add(new JLabel("<html><b><font size=" + FONT_SIZE_HEADER + ">Inputs</font></b></html>"), outerGBC); outerGBC.gridx += 1; outerGBC.weightx = 1; outerInputsPanel.add(new JLabel(" "), outerGBC); // add search text field for FunctionInputs outerGBC.gridx += 1; outerGBC.weightx = 0.1; outerGBC.anchor = GridBagConstraints.SOUTHEAST; outerGBC.insets = new Insets(0, 0, STD_INSET_GBC, 0); inputsFilterField.addFilterListener(filterInputsListener); TextFieldWithAction inputTextField = new TextFieldWithAction(inputsFilterField, clearInputsFilterAction, CLEAR_FILTER_HOVERED_ICON); inputTextField.setMaximumSize(new Dimension(WIDTH_INPUTS_SEARCH_FIELD, HEIGHT_SEARCH_FIELD)); inputTextField.setPreferredSize(new Dimension(WIDTH_INPUTS_SEARCH_FIELD, HEIGHT_SEARCH_FIELD)); inputTextField.setMinimumSize(new Dimension(WIDTH_INPUTS_SEARCH_FIELD, HEIGHT_SEARCH_FIELD)); outerInputsPanel.add(inputTextField, outerGBC); // Add type filter for nominal input values chbNominal = new JCheckBox(new ResourceAction(true, "expression_property_dialog.quick_filter.nominal") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent arg0) { inputsModel.setNominalFilter(chbNominal.isSelected()); } }); chbNominal.setSelected(inputsModel.isNominalFilterToggled()); // Add type filter for numerical input values chbNumeric = new JCheckBox(new ResourceAction(true, "expression_property_dialog.quick_filter.numerical") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent arg0) { inputsModel.setNumericFilter(chbNumeric.isSelected()); } }); chbNumeric.setSelected(inputsModel.isNumericFilterToggled()); // Add type filter for date time input values chbDateTime = new JCheckBox(new ResourceAction(true, "expression_property_dialog.quick_filter.date_time") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent arg0) { inputsModel.setDateTimeFilter(chbDateTime.isSelected()); } }); chbDateTime.setSelected(inputsModel.isDateTimeFilterToggled()); // create the menu with the type filters final ScrollableJPopupMenu filterMenu = new ScrollableJPopupMenu(); // small hack to prevent the popup from opening itself when you click the button to // actually // close it filterMenu.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {} @Override public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { lastPopupCloseTime = System.currentTimeMillis(); } @Override public void popupMenuCanceled(final PopupMenuEvent e) {} }); filterMenu.add(chbNominal); filterMenu.add(chbNumeric); filterMenu.add(chbDateTime); // create button to open the type filter menu final JButton filterDropdownButton = new JButton(ICON_FILTER); filterDropdownButton.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); filterDropdownButton.setContentAreaFilled(false); filterDropdownButton.addMouseListener(new HoverBorderMouseListener(filterDropdownButton)); filterDropdownButton.setToolTipText(I18N.getMessage(I18N.getGUIBundle(), "gui.label.expression_property_dialog.quick_filter.filter_select.tip")); // show the menu when the button is clicked filterDropdownButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (!filterMenu.isVisible()) { // hack to prevent filter popup from opening itself again when you click the // button to actually close it while it is open if (System.currentTimeMillis() - lastPopupCloseTime < 250) { return; } int menuWidth = filterMenu.getSize().width; if (menuWidth == 0) { // guess the correct width for the first opening menuWidth = 108; } filterMenu.show(filterDropdownButton, -menuWidth + filterDropdownButton.getSize().width, filterDropdownButton.getHeight()); filterMenu.requestFocusInWindow(); } } }); outerGBC.gridx += 1; outerGBC.insets = new Insets(0, 0, STD_INSET_GBC, STD_INSET_GBC); outerInputsPanel.add(filterDropdownButton, outerGBC); // create scroll bar for inputs outerInputPanel.setBackground(LIGHTER_GRAY); ExtendedJScrollPane inputsScrollPane = new ExtendedJScrollPane(outerInputPanel); inputsScrollPane.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Colors.TEXTFIELD_BORDER)); inputsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); outerGBC.gridx = 0; outerGBC.insets = new Insets(0, STD_INSET_GBC, STD_INSET_GBC, STD_INSET_GBC); outerGBC.gridwidth = 4; outerGBC.gridy += 1; outerGBC.fill = GridBagConstraints.BOTH; outerGBC.anchor = GridBagConstraints.NORTH; outerGBC.weightx = 1; outerGBC.weighty = 1; outerInputsPanel.add(inputsScrollPane, outerGBC); // add inputs part to the main panel mainC.weightx = 0.1; mainC.gridx += 1; mainPanel.add(outerInputsPanel, mainC); } setIconImage(SwingTools.createIcon("16/rapidminer_studio.png").getImage()); layoutDefault(mainPanel, HUGE, buttons.toArray(new AbstractButton[buttons.size()])); // if an initial value is given, set it if (initialValue != null) { currentExpression.setText(initialValue); } // validate the expression validateExpression(); setResizable(false); } /** * @return current expression */ public String getExpression() { return currentExpression.getText(); } @Override protected Icon getInfoIcon() { return null; } @Override protected String getInfoText() { return ""; } /** * Adds the given value to the expression text * * @param value * that is added to the expression text */ private void addToExpression(String value) { if (value == null) { return; } String selectedText = currentExpression.getSelectedText(); if (selectedText != null && selectedText.length() > 0) { // replace selected text by function including the selection as argument (if the string // to be added actually IS a function...) if (value.endsWith("()")) { int selectionStart = currentExpression.getSelectionStart(); int selectionEnd = currentExpression.getSelectionEnd(); String text = currentExpression.getText(); String firstPart = text.substring(0, selectionStart); String lastPart = text.substring(selectionEnd); currentExpression.setText(firstPart + value + lastPart); int lengthForCaretPosition = value.length(); if (value.endsWith("()")) { lengthForCaretPosition--; } currentExpression.setCaretPosition(selectionStart + lengthForCaretPosition); addToExpression(selectedText); currentExpression.setCaretPosition(currentExpression.getCaretPosition() + 1); validateExpression(); requestExpressionFocus(); } else { int selectionStart = currentExpression.getSelectionStart(); int selectionEnd = currentExpression.getSelectionEnd(); String text = currentExpression.getText(); String firstPart = text.substring(0, selectionStart); String lastPart = text.substring(selectionEnd); currentExpression.setText(firstPart + value + lastPart); int lengthForCaretPosition = value.length(); if (value.endsWith("()")) { lengthForCaretPosition--; } currentExpression.setCaretPosition(selectionStart + lengthForCaretPosition); validateExpression(); requestExpressionFocus(); } } else { // just add the text at the current caret position int caretPosition = currentExpression.getCaretPosition(); String text = currentExpression.getText(); if (text != null && text.length() > 0) { String firstPart = text.substring(0, caretPosition); String lastPart = text.substring(caretPosition); currentExpression.setText(firstPart + value + lastPart); int lengthForCaretPosition = value.length(); if (value.endsWith("()")) { lengthForCaretPosition--; } currentExpression.setCaretPosition(caretPosition + lengthForCaretPosition); } else { currentExpression.setText(value); int lengthForCaretPosition = value.length(); if (value.endsWith("()")) { lengthForCaretPosition--; } currentExpression.setCaretPosition(caretPosition + lengthForCaretPosition); currentExpression.setCaretPosition(lengthForCaretPosition); } validateExpression(); requestExpressionFocus(); } } /** * Adds the given value (function name) to the expression text. If the function has no * arguments, the caret is placed after the function's right parenthesis. * * @param value * @param function */ private void addToExpression(String value, FunctionDescription function) { addToExpression(value); if (function.getNumberOfArguments() == 0) { currentExpression.setCaretPosition(currentExpression.getCaretPosition() + 1); } } /** * Requests focus on the expression text */ private void requestExpressionFocus() { currentExpression.requestFocusInWindow(); } /** * Updates the function panel */ private void updateFunctions() { // remove all content functionsPanel.removeAll(); functionsPanel.setLayout(functionButtonsLayout); functionCategoryTaskPanes = new HashMap<>(); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1; gbc.gridx = 0; gbc.gridy = 0; int totalFunctionCount = 0; // get the filtered model (the FunctionDescriptions we want to display) Map<String, List<FunctionDescription>> filteredModel = functionModel.getFilteredModel(); String filterName = functionModel.getFilterNameString(); boolean searchStringGiven = !filterName.isEmpty(); for (String functionGroup : filteredModel.keySet()) { boolean perfectMatch = false; JXTaskPane functionCategoryTaskPane = new JXTaskPane(); functionCategoryTaskPane.setName(functionGroup); List<FunctionDescription> list = functionModel.getFilteredModel(functionGroup); totalFunctionCount += list.size(); for (FunctionDescription function : list) { // create the panels for the functions, register the observer and add them to the // related category final FunctionDescriptionPanel funcDescPanel = new FunctionDescriptionPanel(function); funcDescPanel.registerObserver(functionObserver); functionCategoryTaskPane.add(funcDescPanel); if (!perfectMatch && searchStringGiven) { // check for function name equality without brackets and with brackets String functionName = function.getDisplayName().split("\\(")[0]; if (filterName.toLowerCase(Locale.ENGLISH).equals(functionName.toLowerCase(Locale.ENGLISH)) || filterName .toLowerCase(Locale.ENGLISH).equals(function.getDisplayName().toLowerCase(Locale.ENGLISH))) { perfectMatch = true; } } } functionCategoryTaskPane.setTitle(functionGroup); functionCategoryTaskPane.setAnimated(false); // if there is only one category in the filtered model, open the task pane if (filteredModel.keySet().size() == 1) { functionCategoryTaskPane.setCollapsed(false); } else { functionCategoryTaskPane.setCollapsed(true); } if (perfectMatch) { functionCategoryTaskPane.setCollapsed(false); } functionCategoryTaskPanes.put(functionGroup, functionCategoryTaskPane); gbc.ipady = 10; functionsPanel.add(functionCategoryTaskPane, gbc); gbc.gridy += 1; } // if the number of result functions is clear, open the task panes // (if you can see all categories even if they are opened) if (totalFunctionCount <= MAX_NMBR_FUNCTIONS_SHOWN) { for (JXTaskPane taskPane : functionCategoryTaskPanes.values()) { taskPane.setCollapsed(false); } } // if there are no results, show a simple message if (filteredModel.isEmpty()) { gbc.ipady = 10; functionsPanel.add(new JLabel(MESSAGE_NO_RESULTS), gbc); } functionsPanel.revalidate(); } /** * updates the inputs panel */ private void updateInputs() { // remove all content inputsPanel.removeAll(); inputsPanel.setLayout(inputsLayout); inputCategoryTaskPanes = new HashMap<>(); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1; gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; int totalEntryCount = 0; // get the filtered model (the FunctionInputs we want to display) Map<String, List<FunctionInput>> filteredModel = inputsModel.getFilteredModel(); String filterName = inputsModel.getFilterNameString(); boolean searchStringGiven = !filterName.isEmpty(); List<String> keySet = new LinkedList<>(filteredModel.keySet()); boolean anyPerfectMatch = false; for (String type : keySet) { boolean perfectMatch = false; JXTaskPane inputCategoryTaskPane = new JXTaskPane(); inputCategoryTaskPane.setName(type); List<FunctionInput> list = inputsModel.getFilteredModel(type); for (FunctionInput entry : list) { // set a value where we want to see a role, value or description in a second line String value = null; if (entry.getCategory() == Category.DYNAMIC || entry.getCategory() == Category.CONSTANT) { totalEntryCount += 1; value = entry.getAdditionalInformation(); } else if (entry.getCategory() == Category.SCOPE) { totalEntryCount += 1; // use the current scope value value = parser.getExpressionContext().getScopeString(entry.getName()); } FunctionInputPanel inputPanel = null; // create the panels for the inputs, register the observer and add them to the // related category if (value == null) { inputPanel = new FunctionInputPanel(entry); } else { inputPanel = new FunctionInputPanel(entry, value); } inputPanel.registerObserver(inputObserver); inputCategoryTaskPane.add(inputPanel); if (!perfectMatch && searchStringGiven) { // check if the input name is equal to search term if (filterName.toLowerCase(Locale.ENGLISH).equals(entry.getName().toLowerCase(Locale.ENGLISH))) { perfectMatch = true; anyPerfectMatch = true; } } } inputCategoryTaskPane.setTitle(type); inputCategoryTaskPane.setAnimated(false); // if there is only one category in the filtered model, open the task pane if (filteredModel.keySet().size() == 1) { inputCategoryTaskPane.setCollapsed(false); } else { inputCategoryTaskPane.setCollapsed(true); } if (perfectMatch) { inputCategoryTaskPane.setCollapsed(false); } inputCategoryTaskPanes.put(type, inputCategoryTaskPane); gbc.ipady = 10; inputsPanel.add(inputCategoryTaskPane, gbc); gbc.gridy += 1; } // if the number of result inputs is clear, open the task panes // (if you can see all categories even if they are opened) if (totalEntryCount <= MAX_NMBR_INPUTS_SHOWN) { for (JXTaskPane taskPane : inputCategoryTaskPanes.values()) { taskPane.setCollapsed(false); } } else { // if there was no perfect match open attributes if there are not too much entries if (!anyPerfectMatch) { // if attributes can be opened such that you can see that there are more categories, // open the attributes categories if (filteredModel.get(ExampleResolver.KEY_ATTRIBUTES) != null && filteredModel.get(ExampleResolver.KEY_SPECIAL_ATTRIBUTES) != null && filteredModel.get(ExampleResolver.KEY_ATTRIBUTES).size() + filteredModel .get(ExampleResolver.KEY_SPECIAL_ATTRIBUTES).size() <= MAX_NMBR_INPUTS_SHOWN) { inputCategoryTaskPanes.get(ExampleResolver.KEY_ATTRIBUTES).setCollapsed(false); inputCategoryTaskPanes.get(ExampleResolver.KEY_SPECIAL_ATTRIBUTES).setCollapsed(false); } else if (filteredModel.get(ExampleResolver.KEY_ATTRIBUTES) != null && filteredModel.get(ExampleResolver.KEY_ATTRIBUTES).size() <= MAX_NMBR_INPUTS_SHOWN) { inputCategoryTaskPanes.get(ExampleResolver.KEY_ATTRIBUTES).setCollapsed(false); } } } // if there are no results, show a simple message if (filteredModel.isEmpty()) { gbc.ipady = 10; inputsPanel.add(new JLabel(MESSAGE_NO_RESULTS), gbc); } inputsPanel.revalidate(); } /** * Validates the syntax of the current text in the expression field */ private void validateExpression() { // remove error buttons removeLineSignals(); String expression = currentExpression.getText(); if (expression != null) { if (expression.trim().length() > 0) { try { // make a syntax check parser.checkSyntax(expression); // show status of the expression showError(false, "<b>Info: </b>", "Expression is syntactically correct."); } catch (ExpressionException e) { // show status of the expression showError(true, "<b>Error: </b>", e.getMessage()); // if the line of the error is given, show an error icon in this line int line = e.getErrorLine(); if (line > 0) { signalLine(line); } return; } } else { // show status of the expression showError(false, "", "Please specify a valid expression."); } } else { // show status of the expression showError(false, "", "Please specify a valid expression."); } } /** * Changes the {@link SyntaxScheme} of a {@link RSyntaxTextArea} to use custom colors * * @param textAreaSyntaxScheme * the {@link SyntaxScheme} which should be changed * @return the changed {@link SyntaxScheme} with custom colors */ private SyntaxScheme getExpressionColorScheme(SyntaxScheme textAreaSyntaxScheme) { SyntaxScheme ss = textAreaSyntaxScheme; // show brackets in dark purple ss.setStyle(Token.SEPARATOR, new Style(DARK_PURPLE)); // show double quotes / strings in dark cyan ss.setStyle(Token.LITERAL_STRING_DOUBLE_QUOTE, new Style(DARK_CYAN)); // show attributes in RapidMiner orange ss.setStyle(Token.VARIABLE, new Style(SwingTools.RAPIDMINER_ORANGE)); // show unknown attributes that are placed in brackets in [] in black ss.setStyle(Token.COMMENT_KEYWORD, new Style(Color.black)); // show operators that are not defined in the functions in black (like other unknown words) ss.setStyle(Token.OPERATOR, new Style(Color.black)); return ss; } /** * Removes all line signals that show error occurrences */ private void removeLineSignals() { scrollPaneExpression.getGutter().removeAllTrackingIcons(); } /** * Shows an error icon in the given line * * @param line * that should show an error icon */ private void signalLine(int line) { // use the gutter of the expression scroll pane to display icons try { scrollPaneExpression.getGutter().addLineTrackingIcon(line - 1, ERROR_ICON); } catch (BadLocationException e) { // in this case don't show an error icon } } /** * Show a title and a message (error or information) about the status of the expression * * @param error * if the message is an error message * @param title * title of the message * @param message * message, which shows in case of error the place of the error */ private void showError(boolean error, String title, String message) { // set colors accordingly if (error) { validationLabel.setForeground(Color.RED); validationTextArea.setForeground(Color.RED); } else { validationLabel.setForeground(DARK_GREEN); validationTextArea.setForeground(DARK_GREEN); } // add the explanation line to the label to use a different font and the same indentation as // the title String[] splittedMessage = message.split("\n"); String explanation = splittedMessage.length > 0 ? splittedMessage[0] : ""; explanation = (explanation.charAt(0) + "").toUpperCase() + explanation.substring(1); validationLabel.setText("<html>" + title + explanation + "</html>"); // show the error message with the place of the error in monospaced // DO NOT CHANGE THIS, AS THE INDENTATION IS WRONG OTHERWISE validationTextArea.setFont(FontTools.getFont(Font.MONOSPACED, Font.PLAIN, 12)); // set the error message // strip the error message if necessary if (splittedMessage.length > 1) { int buffer = 50; int stepsize = 5; int stringWidth = SwingTools.getStringWidth(validationTextArea, splittedMessage[1]) + buffer; boolean cut = false; while (stringWidth > validationTextArea.getSize().width - stepsize) { cut = true; splittedMessage[1] = splittedMessage[1].substring(stepsize, splittedMessage[1].length()); if (splittedMessage.length > 2) { splittedMessage[2] = splittedMessage[2].substring(stepsize, splittedMessage[2].length()); } stringWidth = SwingTools.getStringWidth(validationTextArea, splittedMessage[1]) + buffer; } if (cut) { splittedMessage[1] = "[...]" + splittedMessage[1]; if (splittedMessage.length > 2) { splittedMessage[2] = " " + splittedMessage[2]; } } } String errorMessage = splittedMessage.length > 1 ? splittedMessage[1] : "\n"; if (splittedMessage.length > 2) { errorMessage += "\n" + splittedMessage[2]; } validationTextArea.setText(errorMessage); } }
agpl-3.0
zcorrecteurs/monolith-www
src/Zco/Bundle/CoreBundle/Parser/SmiliesFeature.php
2768
<?php /** * zCorrecteurs.fr est le logiciel qui fait fonctionner www.zcorrecteurs.fr * * Copyright (C) 2012-2019 Corrigraphie * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace Zco\Bundle\CoreBundle\Parser; /** * Composant de remplacement des smilies. * * @author mwsaz <[email protected]> * @copyright mwsaz <[email protected]> 2010-2012 */ class SmiliesFeature extends AbstractFeature { /** * Liste des smilies disponibles avec en clé le code du smilie et en * valeur le nom de l'image associée. * * @var array */ private static $smilies = array( ':)' => 'smile.png', ':D' => 'heureux.png', ';)' => 'clin.png', ':p' => 'langue.png', ':lol:' => 'rire.gif', ':euh:' => 'unsure.gif', ':(' => 'triste.png', ':o' => 'huh.png', ':colere2:' => 'mechant.png', 'o_O' => 'blink.gif', '^^' => 'hihi.png', ':-°' => 'siffle.png', ':ange:' => 'ange.png', ':colere:' => 'angry.gif', ':diable:' => 'diable.png', ':magicien:' => 'magicien.png', ':ninja:' => 'ninja.png', '>_<' => 'pinch.png', ':pirate:' => 'pirate.png', ':\'(' => 'pleure.png', ':honte:' => 'rouge.png', ':soleil:' => 'soleil.png', ':waw:' => 'waw.png', ':zorro:' => 'zorro.png' ); /** * Remplace les smilies dans le texte. * * @param string $content * @param array $options * @return string */ public function postProcessText(string $content, array $options): string { static $recherche = array(); static $smilies = array(); if (!$recherche || !$smilies) { foreach (self::$smilies as $smilie => $url) { $smilie = htmlspecialchars($smilie); $smilies[$smilie] = '<img src="/bundles/zcocore/img/zcode/smilies/' .$url.'" alt="'.$smilie.'"/>'; $recherche[] = preg_quote($smilie, '`'); } $recherche = implode('|', $recherche); $recherche = '`(\s|^|>)('.$recherche.')(\s|$|<)(?![^><]*"[^>]*>)`'; } //On essaye d'éviter les smilies qui sont dans les attributs. return preg_replace_callback($recherche, function($m) use($smilies) { return $m[1].$smilies[$m[2]].$m[3]; }, $content); } }
agpl-3.0
pkgta1/shuffle
pogom/models.py
119635
#!/usr/bin/python # -*- coding: utf-8 -*- import logging import itertools import calendar import sys import traceback import gc import time import geopy import math from peewee import (InsertQuery, Check, CompositeKey, ForeignKeyField, SmallIntegerField, IntegerField, CharField, DoubleField, BooleanField, DateTimeField, fn, DeleteQuery, FloatField, SQL, TextField, JOIN, OperationalError) from playhouse.flask_utils import FlaskDB from playhouse.pool import PooledMySQLDatabase from playhouse.shortcuts import RetryOperationalError, case from playhouse.migrate import migrate, MySQLMigrator, SqliteMigrator from playhouse.sqlite_ext import SqliteExtDatabase from datetime import datetime, timedelta from base64 import b64encode from cachetools import TTLCache from cachetools import cached from timeit import default_timer from . import config from .utils import (get_pokemon_name, get_pokemon_rarity, get_pokemon_types, get_args, cellid, in_radius, date_secs, clock_between, get_move_name, get_move_damage, get_move_energy, get_move_type, clear_dict_response, calc_pokemon_level) from .transform import transform_from_wgs_to_gcj, get_new_coords from .customLog import printPokemon from .account import (tutorial_pokestop_spin, get_player_level, check_login, setup_api, encounter_pokemon_request) log = logging.getLogger(__name__) args = get_args() flaskDb = FlaskDB() cache = TTLCache(maxsize=100, ttl=60 * 5) db_schema_version = 19 class MyRetryDB(RetryOperationalError, PooledMySQLDatabase): pass # Reduction of CharField to fit max length inside 767 bytes for utf8mb4 charset class Utf8mb4CharField(CharField): def __init__(self, max_length=191, *args, **kwargs): self.max_length = max_length super(CharField, self).__init__(*args, **kwargs) def init_database(app): if args.db_type == 'mysql': log.info('Connecting to MySQL database on %s:%i...', args.db_host, args.db_port) connections = args.db_max_connections if hasattr(args, 'accounts'): connections *= len(args.accounts) db = MyRetryDB( args.db_name, user=args.db_user, password=args.db_pass, host=args.db_host, port=args.db_port, max_connections=connections, stale_timeout=300, charset='utf8mb4') else: log.info('Connecting to local SQLite database') db = SqliteExtDatabase(args.db, pragmas=( ('journal_mode', 'WAL'), ('mmap_size', 1024 * 1024 * 32), ('cache_size', 10000), ('journal_size_limit', 1024 * 1024 * 4),)) app.config['DATABASE'] = db flaskDb.init_app(app) return db class BaseModel(flaskDb.Model): @classmethod def get_all(cls): results = [m for m in cls.select().dicts()] if args.china: for result in results: result['latitude'], result['longitude'] = \ transform_from_wgs_to_gcj( result['latitude'], result['longitude']) return results class Pokemon(BaseModel): # We are base64 encoding the ids delivered by the api # because they are too big for sqlite to handle. encounter_id = Utf8mb4CharField(primary_key=True, max_length=50) spawnpoint_id = Utf8mb4CharField(index=True) pokemon_id = SmallIntegerField(index=True) latitude = DoubleField() longitude = DoubleField() disappear_time = DateTimeField(index=True) individual_attack = SmallIntegerField(null=True) individual_defense = SmallIntegerField(null=True) individual_stamina = SmallIntegerField(null=True) move_1 = SmallIntegerField(null=True) move_2 = SmallIntegerField(null=True) cp = SmallIntegerField(null=True) cp_multiplier = FloatField(null=True) weight = FloatField(null=True) height = FloatField(null=True) gender = SmallIntegerField(null=True) form = SmallIntegerField(null=True) last_modified = DateTimeField( null=True, index=True, default=datetime.utcnow) class Meta: indexes = ((('latitude', 'longitude'), False),) @staticmethod def get_active(swLat, swLng, neLat, neLng, timestamp=0, oSwLat=None, oSwLng=None, oNeLat=None, oNeLng=None): now_date = datetime.utcnow() query = Pokemon.select() if not (swLat and swLng and neLat and neLng): query = (query .where(Pokemon.disappear_time > now_date) .dicts()) elif timestamp > 0: # If timestamp is known only load modified Pokemon. query = (query .where(((Pokemon.last_modified > datetime.utcfromtimestamp(timestamp / 1000)) & (Pokemon.disappear_time > now_date)) & ((Pokemon.latitude >= swLat) & (Pokemon.longitude >= swLng) & (Pokemon.latitude <= neLat) & (Pokemon.longitude <= neLng))) .dicts()) elif oSwLat and oSwLng and oNeLat and oNeLng: # Send Pokemon in view but exclude those within old boundaries. # Only send newly uncovered Pokemon. query = (query .where(((Pokemon.disappear_time > now_date) & (((Pokemon.latitude >= swLat) & (Pokemon.longitude >= swLng) & (Pokemon.latitude <= neLat) & (Pokemon.longitude <= neLng))) & ~((Pokemon.disappear_time > now_date) & (Pokemon.latitude >= oSwLat) & (Pokemon.longitude >= oSwLng) & (Pokemon.latitude <= oNeLat) & (Pokemon.longitude <= oNeLng)))) .dicts()) else: query = (Pokemon .select() # Add 1 hour buffer to include spawnpoints that persist # after tth, like shsh. .where((Pokemon.disappear_time > now_date) & (((Pokemon.latitude >= swLat) & (Pokemon.longitude >= swLng) & (Pokemon.latitude <= neLat) & (Pokemon.longitude <= neLng)))) .dicts()) # Performance: disable the garbage collector prior to creating a # (potentially) large dict with append(). gc.disable() pokemon = [] for p in list(query): p['pokemon_name'] = get_pokemon_name(p['pokemon_id']) p['pokemon_rarity'] = get_pokemon_rarity(p['pokemon_id']) p['pokemon_types'] = get_pokemon_types(p['pokemon_id']) if args.china: p['latitude'], p['longitude'] = \ transform_from_wgs_to_gcj(p['latitude'], p['longitude']) pokemon.append(p) # Re-enable the GC. gc.enable() return pokemon @staticmethod def get_active_by_id(ids, swLat, swLng, neLat, neLng): if not (swLat and swLng and neLat and neLng): query = (Pokemon .select() .where((Pokemon.pokemon_id << ids) & (Pokemon.disappear_time > datetime.utcnow())) .dicts()) else: query = (Pokemon .select() .where((Pokemon.pokemon_id << ids) & (Pokemon.disappear_time > datetime.utcnow()) & (Pokemon.latitude >= swLat) & (Pokemon.longitude >= swLng) & (Pokemon.latitude <= neLat) & (Pokemon.longitude <= neLng)) .dicts()) # Performance: disable the garbage collector prior to creating a # (potentially) large dict with append(). gc.disable() pokemon = [] for p in query: p['pokemon_name'] = get_pokemon_name(p['pokemon_id']) p['pokemon_rarity'] = get_pokemon_rarity(p['pokemon_id']) p['pokemon_types'] = get_pokemon_types(p['pokemon_id']) if args.china: p['latitude'], p['longitude'] = \ transform_from_wgs_to_gcj(p['latitude'], p['longitude']) pokemon.append(p) # Re-enable the GC. gc.enable() return pokemon @classmethod @cached(cache) def get_seen(cls, timediff): if timediff: timediff = datetime.utcnow() - timediff pokemon_count_query = (Pokemon .select(Pokemon.pokemon_id, fn.COUNT(Pokemon.pokemon_id).alias( 'count'), fn.MAX(Pokemon.disappear_time).alias( 'lastappeared') ) .where(Pokemon.disappear_time > timediff) .group_by(Pokemon.pokemon_id) .alias('counttable') ) query = (Pokemon .select(Pokemon.pokemon_id, Pokemon.disappear_time, Pokemon.latitude, Pokemon.longitude, pokemon_count_query.c.count) .join(pokemon_count_query, on=(Pokemon.pokemon_id == pokemon_count_query.c.pokemon_id)) .distinct() .where(Pokemon.disappear_time == pokemon_count_query.c.lastappeared) .dicts() ) # Performance: disable the garbage collector prior to creating a # (potentially) large dict with append(). gc.disable() pokemon = [] total = 0 for p in query: p['pokemon_name'] = get_pokemon_name(p['pokemon_id']) pokemon.append(p) total += p['count'] # Re-enable the GC. gc.enable() return {'pokemon': pokemon, 'total': total} @classmethod def get_appearances(cls, pokemon_id, timediff): ''' :param pokemon_id: id of Pokemon that we need appearances for :param timediff: limiting period of the selection :return: list of Pokemon appearances over a selected period ''' if timediff: timediff = datetime.utcnow() - timediff query = (Pokemon .select(Pokemon.latitude, Pokemon.longitude, Pokemon.pokemon_id, fn.Count(Pokemon.spawnpoint_id).alias('count'), Pokemon.spawnpoint_id) .where((Pokemon.pokemon_id == pokemon_id) & (Pokemon.disappear_time > timediff) ) .group_by(Pokemon.latitude, Pokemon.longitude, Pokemon.pokemon_id, Pokemon.spawnpoint_id) .dicts() ) return list(query) @classmethod def get_appearances_times_by_spawnpoint(cls, pokemon_id, spawnpoint_id, timediff): ''' :param pokemon_id: id of Pokemon that we need appearances times for. :param spawnpoint_id: spawnpoint id we need appearances times for. :param timediff: limiting period of the selection. :return: list of time appearances over a selected period. ''' if timediff: timediff = datetime.utcnow() - timediff query = (Pokemon .select(Pokemon.disappear_time) .where((Pokemon.pokemon_id == pokemon_id) & (Pokemon.spawnpoint_id == spawnpoint_id) & (Pokemon.disappear_time > timediff) ) .order_by(Pokemon.disappear_time.asc()) .tuples() ) return list(itertools.chain(*query)) @classmethod def get_spawn_time(cls, disappear_time): return (disappear_time + 2700) % 3600 @classmethod def get_spawnpoints(cls, swLat, swLng, neLat, neLng, timestamp=0, oSwLat=None, oSwLng=None, oNeLat=None, oNeLng=None): query = (Pokemon .select(Pokemon.latitude, Pokemon.longitude, Pokemon.spawnpoint_id, (date_secs(Pokemon.disappear_time)).alias('time'), fn.Count(Pokemon.spawnpoint_id).alias('count'))) if timestamp > 0: query = (query .where(((Pokemon.last_modified > datetime.utcfromtimestamp(timestamp / 1000))) & ((Pokemon.latitude >= swLat) & (Pokemon.longitude >= swLng) & (Pokemon.latitude <= neLat) & (Pokemon.longitude <= neLng))) .dicts()) elif oSwLat and oSwLng and oNeLat and oNeLng: # Send spawnpoints in view but exclude those within old boundaries. # Only send newly uncovered spawnpoints. query = (query .where((((Pokemon.latitude >= swLat) & (Pokemon.longitude >= swLng) & (Pokemon.latitude <= neLat) & (Pokemon.longitude <= neLng))) & ~((Pokemon.latitude >= oSwLat) & (Pokemon.longitude >= oSwLng) & (Pokemon.latitude <= oNeLat) & (Pokemon.longitude <= oNeLng))) .dicts()) elif swLat and swLng and neLat and neLng: query = (query .where((Pokemon.latitude <= neLat) & (Pokemon.latitude >= swLat) & (Pokemon.longitude >= swLng) & (Pokemon.longitude <= neLng) )) query = query.group_by(Pokemon.latitude, Pokemon.longitude, Pokemon.spawnpoint_id, SQL('time')) queryDict = query.dicts() spawnpoints = {} for sp in queryDict: key = sp['spawnpoint_id'] disappear_time = cls.get_spawn_time(sp.pop('time')) count = int(sp['count']) if key not in spawnpoints: spawnpoints[key] = sp else: spawnpoints[key]['special'] = True if ('time' not in spawnpoints[key] or count >= spawnpoints[key]['count']): spawnpoints[key]['time'] = disappear_time spawnpoints[key]['count'] = count # Helping out the GC. for sp in spawnpoints.values(): del sp['count'] return list(spawnpoints.values()) @classmethod def get_spawnpoints_in_hex(cls, center, steps): log.info('Finding spawnpoints {} steps away.'.format(steps)) n, e, s, w = hex_bounds(center, steps) query = (Pokemon .select(Pokemon.latitude.alias('lat'), Pokemon.longitude.alias('lng'), (date_secs(Pokemon.disappear_time)).alias('time'), Pokemon.spawnpoint_id )) query = (query.where((Pokemon.latitude <= n) & (Pokemon.latitude >= s) & (Pokemon.longitude >= w) & (Pokemon.longitude <= e) )) # Sqlite doesn't support distinct on columns. if args.db_type == 'mysql': query = query.distinct(Pokemon.spawnpoint_id) else: query = query.group_by(Pokemon.spawnpoint_id) s = list(query.dicts()) # The distance between scan circles of radius 70 in a hex is 121.2436 # steps - 1 to account for the center circle then add 70 for the edge. step_distance = ((steps - 1) * 121.2436) + 70 # Compare spawnpoint list to a circle with radius steps * 120. # Uses the direct geopy distance between the center and the spawnpoint. filtered = [] for idx, sp in enumerate(s): if geopy.distance.distance( center, (sp['lat'], sp['lng'])).meters <= step_distance: filtered.append(s[idx]) # At this point, 'time' is DISAPPEARANCE time, we're going to morph it # to APPEARANCE time accounting for hour wraparound. for location in filtered: # todo: this DOES NOT ACCOUNT for Pokemon that appear sooner and # live longer, but you'll _always_ have at least 15 minutes, so it # works well enough. location['time'] = cls.get_spawn_time(location['time']) return filtered class Pokestop(BaseModel): pokestop_id = Utf8mb4CharField(primary_key=True, max_length=50) enabled = BooleanField() latitude = DoubleField() longitude = DoubleField() last_modified = DateTimeField(index=True) lure_expiration = DateTimeField(null=True, index=True) active_fort_modifier = Utf8mb4CharField(max_length=50, null=True, index=True) last_updated = DateTimeField( null=True, index=True, default=datetime.utcnow) class Meta: indexes = ((('latitude', 'longitude'), False),) @staticmethod def get_stops(swLat, swLng, neLat, neLng, timestamp=0, oSwLat=None, oSwLng=None, oNeLat=None, oNeLng=None, lured=False): query = Pokestop.select(Pokestop.active_fort_modifier, Pokestop.enabled, Pokestop.latitude, Pokestop.longitude, Pokestop.last_modified, Pokestop.lure_expiration, Pokestop.pokestop_id) if not (swLat and swLng and neLat and neLng): query = (query .dicts()) elif timestamp > 0: query = (query .where(((Pokestop.last_updated > datetime.utcfromtimestamp(timestamp / 1000))) & (Pokestop.latitude >= swLat) & (Pokestop.longitude >= swLng) & (Pokestop.latitude <= neLat) & (Pokestop.longitude <= neLng)) .dicts()) elif oSwLat and oSwLng and oNeLat and oNeLng and lured: query = (query .where((((Pokestop.latitude >= swLat) & (Pokestop.longitude >= swLng) & (Pokestop.latitude <= neLat) & (Pokestop.longitude <= neLng)) & (Pokestop.active_fort_modifier.is_null(False))) & ~((Pokestop.latitude >= oSwLat) & (Pokestop.longitude >= oSwLng) & (Pokestop.latitude <= oNeLat) & (Pokestop.longitude <= oNeLng)) & (Pokestop.active_fort_modifier.is_null(False))) .dicts()) elif oSwLat and oSwLng and oNeLat and oNeLng: # Send stops in view but exclude those within old boundaries. Only # send newly uncovered stops. query = (query .where(((Pokestop.latitude >= swLat) & (Pokestop.longitude >= swLng) & (Pokestop.latitude <= neLat) & (Pokestop.longitude <= neLng)) & ~((Pokestop.latitude >= oSwLat) & (Pokestop.longitude >= oSwLng) & (Pokestop.latitude <= oNeLat) & (Pokestop.longitude <= oNeLng))) .dicts()) elif lured: query = (query .where(((Pokestop.last_updated > datetime.utcfromtimestamp(timestamp / 1000))) & ((Pokestop.latitude >= swLat) & (Pokestop.longitude >= swLng) & (Pokestop.latitude <= neLat) & (Pokestop.longitude <= neLng)) & (Pokestop.active_fort_modifier.is_null(False))) .dicts()) else: query = (query .where((Pokestop.latitude >= swLat) & (Pokestop.longitude >= swLng) & (Pokestop.latitude <= neLat) & (Pokestop.longitude <= neLng)) .dicts()) # Performance: disable the garbage collector prior to creating a # (potentially) large dict with append(). gc.disable() pokestops = [] for p in query: if args.china: p['latitude'], p['longitude'] = \ transform_from_wgs_to_gcj(p['latitude'], p['longitude']) pokestops.append(p) # Re-enable the GC. gc.enable() return pokestops class Gym(BaseModel): gym_id = Utf8mb4CharField(primary_key=True, max_length=50) team_id = SmallIntegerField() guard_pokemon_id = SmallIntegerField() gym_points = IntegerField() enabled = BooleanField() latitude = DoubleField() longitude = DoubleField() last_modified = DateTimeField(index=True) last_scanned = DateTimeField(default=datetime.utcnow, index=True) class Meta: indexes = ((('latitude', 'longitude'), False),) @staticmethod def get_gyms(swLat, swLng, neLat, neLng, timestamp=0, oSwLat=None, oSwLng=None, oNeLat=None, oNeLng=None): if not (swLat and swLng and neLat and neLng): results = (Gym .select() .dicts()) elif timestamp > 0: # If timestamp is known only send last scanned Gyms. results = (Gym .select() .where(((Gym.last_scanned > datetime.utcfromtimestamp(timestamp / 1000)) & (Gym.latitude >= swLat) & (Gym.longitude >= swLng) & (Gym.latitude <= neLat) & (Gym.longitude <= neLng))) .dicts()) elif oSwLat and oSwLng and oNeLat and oNeLng: # Send gyms in view but exclude those within old boundaries. Only # send newly uncovered gyms. results = (Gym .select() .where(((Gym.latitude >= swLat) & (Gym.longitude >= swLng) & (Gym.latitude <= neLat) & (Gym.longitude <= neLng)) & ~((Gym.latitude >= oSwLat) & (Gym.longitude >= oSwLng) & (Gym.latitude <= oNeLat) & (Gym.longitude <= oNeLng))) .dicts()) else: results = (Gym .select() .where((Gym.latitude >= swLat) & (Gym.longitude >= swLng) & (Gym.latitude <= neLat) & (Gym.longitude <= neLng)) .dicts()) # Performance: disable the garbage collector prior to creating a # (potentially) large dict with append(). gc.disable() gyms = {} gym_ids = [] for g in results: g['name'] = None g['pokemon'] = [] gyms[g['gym_id']] = g gym_ids.append(g['gym_id']) if len(gym_ids) > 0: pokemon = (GymMember .select( GymMember.gym_id, GymPokemon.cp.alias('pokemon_cp'), GymPokemon.pokemon_id, Trainer.name.alias('trainer_name'), Trainer.level.alias('trainer_level')) .join(Gym, on=(GymMember.gym_id == Gym.gym_id)) .join(GymPokemon, on=(GymMember.pokemon_uid == GymPokemon.pokemon_uid)) .join(Trainer, on=(GymPokemon.trainer_name == Trainer.name)) .where(GymMember.gym_id << gym_ids) .where(GymMember.last_scanned > Gym.last_modified) .order_by(GymMember.gym_id, GymPokemon.cp) .distinct() .dicts()) for p in pokemon: p['pokemon_name'] = get_pokemon_name(p['pokemon_id']) gyms[p['gym_id']]['pokemon'].append(p) details = (GymDetails .select( GymDetails.gym_id, GymDetails.name) .where(GymDetails.gym_id << gym_ids) .dicts()) for d in details: gyms[d['gym_id']]['name'] = d['name'] # Re-enable the GC. gc.enable() return gyms @staticmethod def get_gym(id): result = (Gym .select(Gym.gym_id, Gym.team_id, GymDetails.name, GymDetails.description, Gym.guard_pokemon_id, Gym.gym_points, Gym.latitude, Gym.longitude, Gym.last_modified, Gym.last_scanned) .join(GymDetails, JOIN.LEFT_OUTER, on=(Gym.gym_id == GymDetails.gym_id)) .where(Gym.gym_id == id) .dicts() .get()) result['guard_pokemon_name'] = get_pokemon_name( result['guard_pokemon_id']) if result['guard_pokemon_id'] else '' result['pokemon'] = [] pokemon = (GymMember .select(GymPokemon.cp.alias('pokemon_cp'), GymPokemon.pokemon_id, GymPokemon.pokemon_uid, GymPokemon.move_1, GymPokemon.move_2, GymPokemon.iv_attack, GymPokemon.iv_defense, GymPokemon.iv_stamina, Trainer.name.alias('trainer_name'), Trainer.level.alias('trainer_level')) .join(Gym, on=(GymMember.gym_id == Gym.gym_id)) .join(GymPokemon, on=(GymMember.pokemon_uid == GymPokemon.pokemon_uid)) .join(Trainer, on=(GymPokemon.trainer_name == Trainer.name)) .where(GymMember.gym_id == id) .where(GymMember.last_scanned > Gym.last_modified) .order_by(GymPokemon.cp.desc()) .distinct() .dicts()) for p in pokemon: p['pokemon_name'] = get_pokemon_name(p['pokemon_id']) p['move_1_name'] = get_move_name(p['move_1']) p['move_1_damage'] = get_move_damage(p['move_1']) p['move_1_energy'] = get_move_energy(p['move_1']) p['move_1_type'] = get_move_type(p['move_1']) p['move_2_name'] = get_move_name(p['move_2']) p['move_2_damage'] = get_move_damage(p['move_2']) p['move_2_energy'] = get_move_energy(p['move_2']) p['move_2_type'] = get_move_type(p['move_2']) result['pokemon'].append(p) return result class LocationAltitude(BaseModel): cellid = Utf8mb4CharField(primary_key=True, max_length=50) latitude = DoubleField() longitude = DoubleField() last_modified = DateTimeField(index=True, default=datetime.utcnow, null=True) altitude = DoubleField() class Meta: indexes = ((('latitude', 'longitude'), False),) # DB format of a new location altitude @staticmethod def new_loc(loc, altitude): return {'cellid': cellid(loc), 'latitude': loc[0], 'longitude': loc[1], 'altitude': altitude} # find a nearby altitude from the db # looking for one within 140m @classmethod def get_nearby_altitude(cls, loc): n, e, s, w = hex_bounds(loc, radius=0.14) # 140m # Get all location altitudes in that box. query = (cls .select() .where((cls.latitude <= n) & (cls.latitude >= s) & (cls.longitude >= w) & (cls.longitude <= e)) .dicts()) altitude = None if len(list(query)): altitude = query[0]['altitude'] return altitude @classmethod def save_altitude(cls, loc, altitude): InsertQuery(cls, rows=[cls.new_loc(loc, altitude)]).upsert().execute() class ScannedLocation(BaseModel): cellid = Utf8mb4CharField(primary_key=True, max_length=50) latitude = DoubleField() longitude = DoubleField() last_modified = DateTimeField( index=True, default=datetime.utcnow, null=True) # Marked true when all five bands have been completed. done = BooleanField(default=False) # Five scans/hour is required to catch all spawns. # Each scan must be at least 12 minutes from the previous check, # with a 2 minute window during which the scan can be done. # Default of -1 is for bands not yet scanned. band1 = SmallIntegerField(default=-1) band2 = SmallIntegerField(default=-1) band3 = SmallIntegerField(default=-1) band4 = SmallIntegerField(default=-1) band5 = SmallIntegerField(default=-1) # midpoint is the center of the bands relative to band 1. # If band 1 is 10.4 minutes, and band 4 is 34.0 minutes, midpoint # is -0.2 minutes in minsec. Extra 10 seconds in case of delay in # recording now time. midpoint = SmallIntegerField(default=0) # width is how wide the valid window is. Default is 0, max is 2 minutes. # If band 1 is 10.4 minutes, and band 4 is 34.0 minutes, midpoint # is 0.4 minutes in minsec. width = SmallIntegerField(default=0) class Meta: indexes = ((('latitude', 'longitude'), False),) constraints = [Check('band1 >= -1'), Check('band1 < 3600'), Check('band2 >= -1'), Check('band2 < 3600'), Check('band3 >= -1'), Check('band3 < 3600'), Check('band4 >= -1'), Check('band4 < 3600'), Check('band5 >= -1'), Check('band5 < 3600'), Check('midpoint >= -130'), Check('midpoint <= 130'), Check('width >= 0'), Check('width <= 130')] @staticmethod def get_recent(swLat, swLng, neLat, neLng, timestamp=0, oSwLat=None, oSwLng=None, oNeLat=None, oNeLng=None): activeTime = (datetime.utcnow() - timedelta(minutes=15)) if timestamp > 0: query = (ScannedLocation .select() .where(((ScannedLocation.last_modified >= datetime.utcfromtimestamp(timestamp / 1000))) & (ScannedLocation.latitude >= swLat) & (ScannedLocation.longitude >= swLng) & (ScannedLocation.latitude <= neLat) & (ScannedLocation.longitude <= neLng)) .dicts()) elif oSwLat and oSwLng and oNeLat and oNeLng: # Send scannedlocations in view but exclude those within old # boundaries. Only send newly uncovered scannedlocations. query = (ScannedLocation .select() .where((((ScannedLocation.last_modified >= activeTime)) & (ScannedLocation.latitude >= swLat) & (ScannedLocation.longitude >= swLng) & (ScannedLocation.latitude <= neLat) & (ScannedLocation.longitude <= neLng)) & ~(((ScannedLocation.last_modified >= activeTime)) & (ScannedLocation.latitude >= oSwLat) & (ScannedLocation.longitude >= oSwLng) & (ScannedLocation.latitude <= oNeLat) & (ScannedLocation.longitude <= oNeLng))) .dicts()) else: query = (ScannedLocation .select() .where((ScannedLocation.last_modified >= activeTime) & (ScannedLocation.latitude >= swLat) & (ScannedLocation.longitude >= swLng) & (ScannedLocation.latitude <= neLat) & (ScannedLocation.longitude <= neLng)) .order_by(ScannedLocation.last_modified.asc()) .dicts()) return list(query) # DB format of a new location. @staticmethod def new_loc(loc): return {'cellid': cellid(loc), 'latitude': loc[0], 'longitude': loc[1], 'done': False, 'band1': -1, 'band2': -1, 'band3': -1, 'band4': -1, 'band5': -1, 'width': 0, 'midpoint': 0, 'last_modified': None} # Used to update bands. @staticmethod def db_format(scan, band, nowms): scan.update({'band' + str(band): nowms}) scan['done'] = reduce(lambda x, y: x and ( scan['band' + str(y)] > -1), range(1, 6), True) return scan # Shorthand helper for DB dict. @staticmethod def _q_init(scan, start, end, kind, sp_id=None): return {'loc': scan['loc'], 'kind': kind, 'start': start, 'end': end, 'step': scan['step'], 'sp': sp_id} @classmethod def get_by_cellids(cls, cellids): query = (cls .select() .where(cls.cellid << cellids) .dicts()) d = {} for sl in list(query): key = "{}".format(sl['cellid']) d[key] = sl return d @classmethod def find_in_locs(cls, loc, locs): key = "{}".format(cellid(loc)) return locs[key] if key in locs else cls.new_loc(loc) # Return value of a particular scan from loc, or default dict if not found. @classmethod def get_by_loc(cls, loc): query = (cls .select() .where(cls.cellid == cellid(loc)) .dicts()) return query[0] if len(list(query)) else cls.new_loc(loc) # Check if spawnpoints in a list are in any of the existing # spannedlocation records. Otherwise, search through the spawnpoint list # and update scan_spawn_point dict for DB bulk upserting. @classmethod def link_spawn_points(cls, scans, initial, spawn_points, distance, scan_spawn_point, force=False): for cell, scan in scans.iteritems(): if initial[cell]['done'] and not force: continue # Difference in degrees at the equator for 70m is actually 0.00063 # degrees and gets smaller the further north or south you go deg_at_lat = 0.0007 / math.cos(math.radians(scan['loc'][0])) for sp in spawn_points: if (abs(sp['latitude'] - scan['loc'][0]) > 0.0008 or abs(sp['longitude'] - scan['loc'][1]) > deg_at_lat): continue if in_radius((sp['latitude'], sp['longitude']), scan['loc'], distance): scan_spawn_point[cell + sp['id']] = { 'spawnpoint': sp['id'], 'scannedlocation': cell} # Return list of dicts for upcoming valid band times. @classmethod def linked_spawn_points(cls, cell): # Unable to use a normal join, since MySQL produces foreignkey # constraint errors when trying to upsert fields that are foreignkeys # on another table query = (SpawnPoint .select() .join(ScanSpawnPoint) .join(cls) .where(cls.cellid == cell).dicts()) return list(query) # Return list of dicts for upcoming valid band times. @classmethod def get_cell_to_linked_spawn_points(cls, cellids, location_change_date): # Get all spawnpoints from the hive's cells sp_from_cells = (ScanSpawnPoint .select(ScanSpawnPoint.spawnpoint) .where(ScanSpawnPoint.scannedlocation << cellids) .alias('spcells')) # A new SL (new ones are created when the location changes) or # it can be a cell from another active hive one_sp_scan = (ScanSpawnPoint .select(ScanSpawnPoint.spawnpoint, fn.MAX(ScanSpawnPoint.scannedlocation).alias( 'cellid')) .join(sp_from_cells, on=sp_from_cells.c.spawnpoint_id == ScanSpawnPoint.spawnpoint) .join(cls, on=(cls.cellid == ScanSpawnPoint.scannedlocation)) .where(((cls.last_modified >= (location_change_date)) & (cls.last_modified > ( datetime.utcnow() - timedelta(minutes=60)))) | (cls.cellid << cellids)) .group_by(ScanSpawnPoint.spawnpoint) .alias('maxscan')) # As scan locations overlap,spawnpoints can belong to up to 3 locations # This sub-query effectively assigns each SP to exactly one location. query = (SpawnPoint .select(SpawnPoint, one_sp_scan.c.cellid) .join(one_sp_scan, on=(SpawnPoint.id == one_sp_scan.c.spawnpoint_id)) .where(one_sp_scan.c.cellid << cellids) .dicts()) l = list(query) ret = {} for item in l: if item['cellid'] not in ret: ret[item['cellid']] = [] ret[item['cellid']].append(item) return ret # Return list of dicts for upcoming valid band times. @classmethod def get_times(cls, scan, now_date, scanned_locations): s = cls.find_in_locs(scan['loc'], scanned_locations) if s['done']: return [] max = 3600 * 2 + 250 # Greater than maximum possible value. min = {'end': max} nowms = date_secs(now_date) if s['band1'] == -1: return [cls._q_init(scan, nowms, nowms + 3599, 'band')] # Find next window. basems = s['band1'] for i in range(2, 6): ms = s['band' + str(i)] # Skip bands already done. if ms > -1: continue radius = 120 - s['width'] / 2 end = (basems + s['midpoint'] + radius + (i - 1) * 720 - 10) % 3600 end = end if end >= nowms else end + 3600 if end < min['end']: min = cls._q_init(scan, end - radius * 2 + 10, end, 'band') return [min] if min['end'] < max else [] # Checks if now falls within an unfilled band for a scanned location. # Returns the updated scan location dict. @classmethod def update_band(cls, scan, now_date): scan['last_modified'] = now_date if scan['done']: return scan now_secs = date_secs(now_date) if scan['band1'] == -1: return cls.db_format(scan, 1, now_secs) # Calculate if number falls in band with remaining points. basems = scan['band1'] delta = (now_secs - basems - scan['midpoint']) % 3600 band = int(round(delta / 12 / 60.0) % 5) + 1 # Check if that band is already filled. if scan['band' + str(band)] > -1: return scan # Check if this result falls within the band's 2 minute window. offset = (delta + 1080) % 720 - 360 if abs(offset) > 120 - scan['width'] / 2: return scan # Find band midpoint/width. scan = cls.db_format(scan, band, now_secs) bts = [scan['band' + str(i)] for i in range(1, 6)] bts = filter(lambda ms: ms > -1, bts) bts_delta = map(lambda ms: (ms - basems) % 3600, bts) bts_offsets = map(lambda ms: (ms + 1080) % 720 - 360, bts_delta) min_scan = min(bts_offsets) max_scan = max(bts_offsets) scan['width'] = max_scan - min_scan scan['midpoint'] = (max_scan + min_scan) / 2 return scan @classmethod def get_bands_filled_by_cellids(cls, cellids): return int(cls .select(fn.SUM(case(cls.band1, ((-1, 0),), 1) + case(cls.band2, ((-1, 0),), 1) + case(cls.band3, ((-1, 0),), 1) + case(cls.band4, ((-1, 0),), 1) + case(cls.band5, ((-1, 0),), 1)) .alias('band_count')) .where(cls.cellid << cellids) .scalar() or 0) @classmethod def reset_bands(cls, scan_loc): scan_loc['done'] = False scan_loc['last_modified'] = datetime.utcnow() for i in range(1, 6): scan_loc['band' + str(i)] = -1 @classmethod def select_in_hex(cls, locs): # There should be a way to delegate this to SpawnPoint.select_in_hex, # but w/e. cells = [] for i, e in enumerate(locs): cells.append(cellid(e[1])) # Get all spawns for the locations. sp = list(cls .select() .where(cls.cellid << cells) .dicts()) # For each spawn work out if it is in the hex (clipping the diagonals). in_hex = [] for spawn in sp: in_hex.append(spawn) return in_hex class MainWorker(BaseModel): worker_name = Utf8mb4CharField(primary_key=True, max_length=50) message = TextField(null=True, default="") method = Utf8mb4CharField(max_length=50) last_modified = DateTimeField(index=True) accounts_working = IntegerField() accounts_captcha = IntegerField() accounts_failed = IntegerField() @staticmethod def get_account_stats(): account_stats = (MainWorker .select(fn.SUM(MainWorker.accounts_working), fn.SUM(MainWorker.accounts_captcha), fn.SUM(MainWorker.accounts_failed)) .scalar(as_tuple=True)) dict = {'working': 0, 'captcha': 0, 'failed': 0} if account_stats[0] is not None: dict = {'working': int(account_stats[0]), 'captcha': int(account_stats[1]), 'failed': int(account_stats[2])} return dict class WorkerStatus(BaseModel): username = Utf8mb4CharField(primary_key=True, max_length=50) worker_name = Utf8mb4CharField(index=True, max_length=50) success = IntegerField() fail = IntegerField() no_items = IntegerField() skip = IntegerField() captcha = IntegerField() last_modified = DateTimeField(index=True) message = Utf8mb4CharField(max_length=191) last_scan_date = DateTimeField(index=True) latitude = DoubleField(null=True) longitude = DoubleField(null=True) @staticmethod def db_format(status, name='status_worker_db'): status['worker_name'] = status.get('worker_name', name) return {'username': status['username'], 'worker_name': status['worker_name'], 'success': status['success'], 'fail': status['fail'], 'no_items': status['noitems'], 'skip': status['skip'], 'captcha': status['captcha'], 'last_modified': datetime.utcnow(), 'message': status['message'], 'last_scan_date': status.get('last_scan_date', datetime.utcnow()), 'latitude': status.get('latitude', None), 'longitude': status.get('longitude', None)} @staticmethod def get_recent(): query = (WorkerStatus .select() .where((WorkerStatus.last_modified >= (datetime.utcnow() - timedelta(minutes=5)))) .order_by(WorkerStatus.username) .dicts()) status = [] for s in query: status.append(s) return status @staticmethod def get_worker(username, loc=False): query = (WorkerStatus .select() .where((WorkerStatus.username == username)) .dicts()) # Sometimes is appears peewee is slow to load, and this produces # an exception. Retry after a second to give peewee time to load. while True: try: result = query[0] if len(query) else { 'username': username, 'success': 0, 'fail': 0, 'no_items': 0, 'skip': 0, 'last_modified': datetime.utcnow(), 'message': 'New account {} loaded'.format(username), 'last_scan_date': datetime.utcnow(), 'latitude': loc[0] if loc else None, 'longitude': loc[1] if loc else None } break except Exception as e: log.error('Exception in get_worker under account {}. ' 'Exception message: {}'.format(username, repr(e))) traceback.print_exc(file=sys.stdout) time.sleep(1) return result class SpawnPoint(BaseModel): id = Utf8mb4CharField(primary_key=True, max_length=50) latitude = DoubleField() longitude = DoubleField() last_scanned = DateTimeField(index=True) # kind gives the four quartiles of the spawn, as 's' for seen # or 'h' for hidden. For example, a 30 minute spawn is 'hhss'. kind = Utf8mb4CharField(max_length=4, default='hhhs') # links shows whether a Pokemon encounter id changes between quartiles or # stays the same. Both 1x45 and 1x60h3 have the kind of 'sssh', but the # different links shows when the encounter id changes. Same encounter id # is shared between two quartiles, links shows a '+'. A different # encounter id between two quartiles is a '-'. # # For the hidden times, an 'h' is used. Until determined, '?' is used. # Note index is shifted by a half. links[0] is the link between # kind[0] and kind[1] and so on. links[3] is the link between # kind[3] and kind[0] links = Utf8mb4CharField(max_length=4, default='????') # Count consecutive times spawn should have been seen, but wasn't. # If too high, will not be scheduled for review, and treated as inactive. missed_count = IntegerField(default=0) # Next 2 fields are to narrow down on the valid TTH window. # Seconds after the hour of the latest Pokemon seen time within the hour. latest_seen = SmallIntegerField() # Seconds after the hour of the earliest time Pokemon wasn't seen after an # appearance. earliest_unseen = SmallIntegerField() class Meta: indexes = ((('latitude', 'longitude'), False),) constraints = [Check('earliest_unseen >= 0'), Check('earliest_unseen < 3600'), Check('latest_seen >= 0'), Check('latest_seen < 3600')] # Returns the spawnpoint dict from ID, or a new dict if not found. @classmethod def get_by_id(cls, id, latitude=0, longitude=0): query = (cls .select() .where(cls.id == id) .dicts()) return query[0] if query else { 'id': id, 'latitude': latitude, 'longitude': longitude, 'last_scanned': None, # Null value used as new flag. 'kind': 'hhhs', 'links': '????', 'missed_count': 0, 'latest_seen': None, 'earliest_unseen': None } # Confirm if tth has been found. @staticmethod def tth_found(sp): # Fully indentified if no '?' in links and # latest_seen == earliest_unseen. return sp['latest_seen'] == sp['earliest_unseen'] # Return [start, end] in seconds after the hour for the spawn, despawn # time of a spawnpoint. @classmethod def start_end(cls, sp, spawn_delay=0, links=False): links_arg = links links = links if links else str(sp['links']) if links == '????': # Clean up for old data. links = str(sp['kind'].replace('s', '?')) # Make some assumptions if link not fully identified. if links.count('-') == 0: links = links[:-1] + '-' links = links.replace('?', '+') links = links[:-1] + '-' plus_or_minus = links.index( '+') if links.count('+') else links.index('-') start = sp['earliest_unseen'] - (4 - plus_or_minus) * 900 + spawn_delay no_tth_adjust = 60 if not links_arg and not cls.tth_found(sp) else 0 end = sp['latest_seen'] - (3 - links.index('-')) * 900 + no_tth_adjust return [start % 3600, end % 3600] # Return a list of dicts with the next spawn times. @classmethod def get_times(cls, cell, scan, now_date, scan_delay, cell_to_linked_spawn_points, sp_by_id): l = [] now_secs = date_secs(now_date) linked_spawn_points = (cell_to_linked_spawn_points[cell] if cell in cell_to_linked_spawn_points else []) for sp in linked_spawn_points: if sp['missed_count'] > 5: continue endpoints = SpawnPoint.start_end(sp, scan_delay) cls.add_if_not_scanned('spawn', l, sp, scan, endpoints[0], endpoints[1], now_date, now_secs, sp_by_id) # Check to see if still searching for valid TTH. if cls.tth_found(sp): continue # Add a spawnpoint check between latest_seen and earliest_unseen. start = sp['latest_seen'] end = sp['earliest_unseen'] # So if the gap between start and end < 89 seconds make the gap # 89 seconds if ((end > start and end - start < 89) or (start > end and (end + 3600) - start < 89)): end = (start + 89) % 3600 # So we move the search gap on 45 to within 45 and 89 seconds from # the last scan. TTH appears in the last 90 seconds of the Spawn. start = sp['latest_seen'] + 45 cls.add_if_not_scanned('TTH', l, sp, scan, start, end, now_date, now_secs, sp_by_id) return l @classmethod def add_if_not_scanned(cls, kind, l, sp, scan, start, end, now_date, now_secs, sp_by_id): # Make sure later than now_secs. while end < now_secs: start, end = start + 3600, end + 3600 # Ensure start before end. while start > end: start -= 3600 while start < 0: start, end = start + 3600, end + 3600 last_scanned = sp_by_id[sp['id']]['last_scanned'] if ((now_date - last_scanned).total_seconds() > now_secs - start): l.append(ScannedLocation._q_init(scan, start, end, kind, sp['id'])) @classmethod def select_in_hex_by_cellids(cls, cellids, location_change_date): # Get all spawnpoints from the hive's cells sp_from_cells = (ScanSpawnPoint .select(ScanSpawnPoint.spawnpoint) .where(ScanSpawnPoint.scannedlocation << cellids) .alias('spcells')) # Allocate a spawnpoint to one cell only, this can either be # A new SL (new ones are created when the location changes) or # it can be a cell from another active hive one_sp_scan = (ScanSpawnPoint .select(ScanSpawnPoint.spawnpoint, fn.MAX(ScanSpawnPoint.scannedlocation).alias( 'Max_ScannedLocation_id')) .join(sp_from_cells, on=sp_from_cells.c.spawnpoint_id == ScanSpawnPoint.spawnpoint) .join( ScannedLocation, on=(ScannedLocation.cellid == ScanSpawnPoint.scannedlocation)) .where(((ScannedLocation.last_modified >= (location_change_date)) & ( ScannedLocation.last_modified > ( datetime.utcnow() - timedelta(minutes=60)))) | (ScannedLocation.cellid << cellids)) .group_by(ScanSpawnPoint.spawnpoint) .alias('maxscan')) query = (cls .select(cls) .join(one_sp_scan, on=(one_sp_scan.c.spawnpoint_id == cls.id)) .where(one_sp_scan.c.Max_ScannedLocation_id << cellids) .dicts()) in_hex = [] for spawn in list(query): in_hex.append(spawn) return in_hex @classmethod def select_in_hex_by_location(cls, center, steps): R = 6378.1 # KM radius of the earth hdist = ((steps * 120.0) - 50.0) / 1000.0 n, e, s, w = hex_bounds(center, steps) # Get all spawns in that box. sp = list(cls .select() .where((cls.latitude <= n) & (cls.latitude >= s) & (cls.longitude >= w) & (cls.longitude <= e)) .dicts()) # For each spawn work out if it is in the hex (clipping the diagonals). in_hex = [] for spawn in sp: # Get the offset from the center of each spawn in km. offset = [math.radians(spawn['latitude'] - center[0]) * R, math.radians(spawn['longitude'] - center[1]) * (R * math.cos(math.radians(center[0])))] # Check against the 4 lines that make up the diagonals. if (offset[1] + (offset[0] * 0.5)) > hdist: # Too far NE continue if (offset[1] - (offset[0] * 0.5)) > hdist: # Too far SE continue if ((offset[0] * 0.5) - offset[1]) > hdist: # Too far NW continue if ((0 - offset[1]) - (offset[0] * 0.5)) > hdist: # Too far SW continue # If it gets to here it's a good spawn. in_hex.append(spawn) return in_hex class ScanSpawnPoint(BaseModel): scannedlocation = ForeignKeyField(ScannedLocation, null=True) spawnpoint = ForeignKeyField(SpawnPoint, null=True) class Meta: primary_key = CompositeKey('spawnpoint', 'scannedlocation') class SpawnpointDetectionData(BaseModel): id = Utf8mb4CharField(primary_key=True, max_length=54) # Removed ForeignKeyField since it caused MySQL issues. encounter_id = Utf8mb4CharField(max_length=54) # Removed ForeignKeyField since it caused MySQL issues. spawnpoint_id = Utf8mb4CharField(max_length=54, index=True) scan_time = DateTimeField() tth_secs = SmallIntegerField(null=True) @staticmethod def set_default_earliest_unseen(sp): sp['earliest_unseen'] = (sp['latest_seen'] + 15 * 60) % 3600 @classmethod def classify(cls, sp, scan_loc, now_secs, sighting=None): # Get past sightings. query = list(cls.select() .where(cls.spawnpoint_id == sp['id']) .order_by(cls.scan_time.asc()) .dicts()) if sighting: query.append(sighting) tth_found = False for s in query: if s['tth_secs'] is not None: tth_found = True tth_secs = (s['tth_secs'] - 1) % 3600 # To reduce CPU usage, give an intial reading of 15 minute spawns if # not done with initial scan of location. if not scan_loc['done']: # We only want to reset a SP if it is new and not due the # location changing (which creates new Scannedlocations) if not tth_found: sp['kind'] = 'hhhs' if not sp['earliest_unseen']: sp['latest_seen'] = now_secs cls.set_default_earliest_unseen(sp) elif clock_between(sp['latest_seen'], now_secs, sp['earliest_unseen']): sp['latest_seen'] = now_secs return # Make a record of links, so we can reset earliest_unseen # if it changes. old_kind = str(sp['kind']) # Make a sorted list of the seconds after the hour. seen_secs = sorted(map(lambda x: date_secs(x['scan_time']), query)) # Include and entry for the TTH if it found if tth_found: seen_secs.append(tth_secs) seen_secs.sort() # Add the first seen_secs to the end as a clock wrap around. if seen_secs: seen_secs.append(seen_secs[0] + 3600) # Make a list of gaps between sightings. gap_list = [seen_secs[i + 1] - seen_secs[i] for i in range(len(seen_secs) - 1)] max_gap = max(gap_list) # An hour minus the largest gap in minutes gives us the duration the # spawn was there. Round up to the nearest 15 minute interval for our # current best guess duration. duration = (int((60 - max_gap / 60.0) / 15) + 1) * 15 # If the second largest gap is larger than 15 minutes, then there are # two gaps greater than 15 minutes. It must be a double spawn. if len(gap_list) > 4 and sorted(gap_list)[-2] > 900: sp['kind'] = 'hshs' sp['links'] = 'h?h?' else: # Convert the duration into a 'hhhs', 'hhss', 'hsss', 'ssss' string # accordingly. 's' is for seen, 'h' is for hidden. sp['kind'] = ''.join( ['s' if i > (3 - duration / 15) else 'h' for i in range(0, 4)]) # Assume no hidden times. sp['links'] = sp['kind'].replace('s', '?') if sp['kind'] != 'ssss': if (not sp['earliest_unseen'] or sp['earliest_unseen'] != sp['latest_seen'] or not tth_found): # New latest_seen will be just before max_gap. sp['latest_seen'] = seen_secs[gap_list.index(max_gap)] # if we don't have a earliest_unseen yet or if the kind of # spawn has changed, reset to latest_seen + 14 minutes. if not sp['earliest_unseen'] or sp['kind'] != old_kind: cls.set_default_earliest_unseen(sp) return # Only ssss spawns from here below. sp['links'] = '+++-' if sp['earliest_unseen'] == sp['latest_seen']: return # Make a sight_list of dicts: # {date: first seen time, # delta: duration of sighting, # same: whether encounter ID was same or different over that time} # # For 60 minute spawns ('ssss'), the largest gap doesn't give the # earliest spawnpoint because a Pokemon is always there. Use the union # of all intervals where the same encounter ID was seen to find the # latest_seen. If a different encounter ID was seen, then the # complement of that interval was the same ID, so union that # complement as well. sight_list = [{'date': query[i]['scan_time'], 'delta': query[i + 1]['scan_time'] - query[i]['scan_time'], 'same': query[i + 1]['encounter_id'] == query[i]['encounter_id'] } for i in range(len(query) - 1) if query[i + 1]['scan_time'] - query[i]['scan_time'] < timedelta(hours=1) ] start_end_list = [] for s in sight_list: if s['same']: # Get the seconds past the hour for start and end times. start = date_secs(s['date']) end = (start + int(s['delta'].total_seconds())) % 3600 else: # Convert diff range to same range by taking the clock # complement. start = date_secs(s['date'] + s['delta']) % 3600 end = date_secs(s['date']) start_end_list.append([start, end]) # Take the union of all the ranges. while True: # union is list of unions of ranges with the same encounter id. union = [] for start, end in start_end_list: if not union: union.append([start, end]) continue # Cycle through all ranges in union, since it might overlap # with any of them. for u in union: if clock_between(u[0], start, u[1]): u[1] = end if not(clock_between( u[0], end, u[1])) else u[1] elif clock_between(u[0], end, u[1]): u[0] = start if not(clock_between( u[0], start, u[1])) else u[0] elif union.count([start, end]) == 0: union.append([start, end]) # Are no more unions possible? if union == start_end_list: break start_end_list = union # Make another pass looking for unions. # If more than one disparate union, take the largest as our starting # point. union = reduce(lambda x, y: x if (x[1] - x[0]) % 3600 > (y[1] - y[0]) % 3600 else y, union, [0, 3600]) sp['latest_seen'] = union[1] sp['earliest_unseen'] = union[0] log.info('1x60: appear %d, despawn %d, duration: %d min.', union[0], union[1], ((union[1] - union[0]) % 3600) / 60) # Expand the seen times for 30 minute spawnpoints based on scans when spawn # wasn't there. Return true if spawnpoint dict changed. @classmethod def unseen(cls, sp, now_secs): # Return if we already have a tth. if sp['latest_seen'] == sp['earliest_unseen']: return False # If now_secs is later than the latest seen return. if not clock_between(sp['latest_seen'], now_secs, sp['earliest_unseen']): return False sp['earliest_unseen'] = now_secs return True class Versions(flaskDb.Model): key = Utf8mb4CharField() val = SmallIntegerField() class Meta: primary_key = False class GymMember(BaseModel): gym_id = Utf8mb4CharField(index=True) pokemon_uid = Utf8mb4CharField(index=True) last_scanned = DateTimeField(default=datetime.utcnow, index=True) class Meta: primary_key = False class GymPokemon(BaseModel): pokemon_uid = Utf8mb4CharField(primary_key=True, max_length=50) pokemon_id = SmallIntegerField() cp = SmallIntegerField() trainer_name = Utf8mb4CharField(index=True) num_upgrades = SmallIntegerField(null=True) move_1 = SmallIntegerField(null=True) move_2 = SmallIntegerField(null=True) height = FloatField(null=True) weight = FloatField(null=True) stamina = SmallIntegerField(null=True) stamina_max = SmallIntegerField(null=True) cp_multiplier = FloatField(null=True) additional_cp_multiplier = FloatField(null=True) iv_defense = SmallIntegerField(null=True) iv_stamina = SmallIntegerField(null=True) iv_attack = SmallIntegerField(null=True) last_seen = DateTimeField(default=datetime.utcnow) class Trainer(BaseModel): name = Utf8mb4CharField(primary_key=True, max_length=50) team = SmallIntegerField() level = SmallIntegerField() last_seen = DateTimeField(default=datetime.utcnow) class GymDetails(BaseModel): gym_id = Utf8mb4CharField(primary_key=True, max_length=50) name = Utf8mb4CharField() description = TextField(null=True, default="") url = Utf8mb4CharField() last_scanned = DateTimeField(default=datetime.utcnow) class Token(flaskDb.Model): token = TextField() last_updated = DateTimeField(default=datetime.utcnow, index=True) @staticmethod def get_valid(limit=15): # Make sure we don't grab more than we can process if limit > 15: limit = 15 valid_time = datetime.utcnow() - timedelta(seconds=30) token_ids = [] tokens = [] try: with flaskDb.database.transaction(): query = (Token .select() .where(Token.last_updated > valid_time) .order_by(Token.last_updated.asc()) .limit(limit)) for t in query: token_ids.append(t.id) tokens.append(t.token) if tokens: log.debug('Retrived Token IDs: {}'.format(token_ids)) result = DeleteQuery(Token).where( Token.id << token_ids).execute() log.debug('Deleted {} tokens.'.format(result)) except OperationalError as e: log.error('Failed captcha token transactional query: {}'.format(e)) return tokens class HashKeys(BaseModel): key = Utf8mb4CharField(primary_key=True, max_length=20) maximum = SmallIntegerField(default=0) remaining = SmallIntegerField(default=0) peak = SmallIntegerField(default=0) expires = DateTimeField(null=True) last_updated = DateTimeField(default=datetime.utcnow) @staticmethod def get_by_key(key): query = (HashKeys .select() .where(HashKeys.key == key) .dicts()) return query[0] if query else { 'maximum': 0, 'remaining': 0, 'peak': 0, 'expires': None, 'last_updated': None } @staticmethod def get_obfuscated_keys(): # Obfuscate hashing keys before we sent them to the front-end. hashkeys = HashKeys.get_all() for i, s in enumerate(hashkeys): hashkeys[i]['key'] = s['key'][:-9] + '*'*9 return hashkeys @staticmethod # Retrieve the last stored 'peak' value for each hashing key. def getStoredPeak(key): result = HashKeys.select(HashKeys.peak).where(HashKeys.key == key) if result: # only one row can be returned return result[0].peak else: return 0 def hex_bounds(center, steps=None, radius=None): # Make a box that is (70m * step_limit * 2) + 70m away from the # center point. Rationale is that you need to travel. sp_dist = 0.07 * (2 * steps + 1) if steps else radius n = get_new_coords(center, sp_dist, 0)[0] e = get_new_coords(center, sp_dist, 90)[1] s = get_new_coords(center, sp_dist, 180)[0] w = get_new_coords(center, sp_dist, 270)[1] return (n, e, s, w) # todo: this probably shouldn't _really_ be in "models" anymore, but w/e. def parse_map(args, map_dict, step_location, db_update_queue, wh_update_queue, key_scheduler, api, status, now_date, account, account_sets): pokemon = {} pokestops = {} gyms = {} skipped = 0 stopsskipped = 0 forts = [] forts_count = 0 wild_pokemon = [] wild_pokemon_count = 0 nearby_pokemon = 0 spawn_points = {} scan_spawn_points = {} sightings = {} new_spawn_points = [] sp_id_list = [] captcha_url = '' # Consolidate the individual lists in each cell into two lists of Pokemon # and a list of forts. cells = map_dict['responses']['GET_MAP_OBJECTS']['map_cells'] # Get the level for the pokestop spin, and to send to webhook. level = get_player_level(map_dict) # Use separate level indicator for our L30 encounters. encounter_level = level # Helping out the GC. if 'GET_INVENTORY' in map_dict['responses']: del map_dict['responses']['GET_INVENTORY'] for i, cell in enumerate(cells): # If we have map responses then use the time from the request if i == 0: now_date = datetime.utcfromtimestamp( cell['current_timestamp_ms'] / 1000) nearby_pokemon += len(cell.get('nearby_pokemons', [])) # Parse everything for stats (counts). Future enhancement -- we don't # necessarily need to know *how many* forts/wild/nearby were found but # we'd like to know whether or not *any* were found to help determine # if a scan was actually bad. if config['parse_pokemon']: wild_pokemon += cell.get('wild_pokemons', []) if config['parse_pokestops'] or config['parse_gyms']: forts += cell.get('forts', []) # Update count regardless of Pokémon parsing or not, we need the count. # Length is O(1). wild_pokemon_count += len(cell.get('wild_pokemons', [])) forts_count += len(cell.get('forts', [])) now_secs = date_secs(now_date) if wild_pokemon: wild_pokemon_count = len(wild_pokemon) if forts: forts_count = len(forts) del map_dict['responses']['GET_MAP_OBJECTS'] # If there are no wild or nearby Pokemon . . . if not wild_pokemon and not nearby_pokemon: # . . . and there are no gyms/pokestops then it's unusable/bad. if not forts: log.warning('Bad scan. Parsing found absolutely nothing.') log.info('Common causes: captchas or IP bans.') else: # No wild or nearby Pokemon but there are forts. It's probably # a speed violation. log.warning('No nearby or wild Pokemon but there are visible gyms ' 'or pokestops. Possible speed violation.') scan_loc = ScannedLocation.get_by_loc(step_location) done_already = scan_loc['done'] ScannedLocation.update_band(scan_loc, now_date) just_completed = not done_already and scan_loc['done'] if wild_pokemon and config['parse_pokemon']: encounter_ids = [b64encode(str(p['encounter_id'])) for p in wild_pokemon] # For all the wild Pokemon we found check if an active Pokemon is in # the database. query = (Pokemon .select(Pokemon.encounter_id, Pokemon.spawnpoint_id) .where((Pokemon.disappear_time >= now_date) & (Pokemon.encounter_id << encounter_ids)) .dicts()) # Store all encounter_ids and spawnpoint_ids for the Pokemon in query. # All of that is needed to make sure it's unique. encountered_pokemon = [ (p['encounter_id'], p['spawnpoint_id']) for p in query] for p in wild_pokemon: sp = SpawnPoint.get_by_id(p['spawn_point_id'], p[ 'latitude'], p['longitude']) spawn_points[p['spawn_point_id']] = sp sp['missed_count'] = 0 sighting = { 'id': b64encode(str(p['encounter_id'])) + '_' + str(now_secs), 'encounter_id': b64encode(str(p['encounter_id'])), 'spawnpoint_id': p['spawn_point_id'], 'scan_time': now_date, 'tth_secs': None } # Keep a list of sp_ids to return. sp_id_list.append(p['spawn_point_id']) # time_till_hidden_ms was overflowing causing a negative integer. # It was also returning a value above 3.6M ms. if 0 < p['time_till_hidden_ms'] < 3600000: d_t_secs = date_secs(datetime.utcfromtimestamp( (p['last_modified_timestamp_ms'] + p['time_till_hidden_ms']) / 1000.0)) if (sp['latest_seen'] != sp['earliest_unseen'] or not sp['last_scanned']): log.info('TTH found for spawnpoint %s.', sp['id']) sighting['tth_secs'] = d_t_secs # Only update when TTH is seen for the first time. # Just before Pokemon migrations, Niantic sets all TTH # to the exact time of the migration, not the normal # despawn time. sp['latest_seen'] = d_t_secs sp['earliest_unseen'] = d_t_secs scan_spawn_points[scan_loc['cellid'] + sp['id']] = { 'spawnpoint': sp['id'], 'scannedlocation': scan_loc['cellid']} if not sp['last_scanned']: log.info('New Spawn Point found.') new_spawn_points.append(sp) # If we found a new spawnpoint after the location was already # fully scanned then either it's new, or we had a bad scan. # Either way, rescan the location. if scan_loc['done'] and not just_completed: log.warning('Location was fully scanned, and yet a brand ' 'new spawnpoint found.') log.warning('Redoing scan of this location to identify ' 'new spawnpoint.') ScannedLocation.reset_bands(scan_loc) if (not SpawnPoint.tth_found(sp) or sighting['tth_secs'] or not scan_loc['done'] or just_completed): SpawnpointDetectionData.classify(sp, scan_loc, now_secs, sighting) sightings[p['encounter_id']] = sighting sp['last_scanned'] = datetime.utcfromtimestamp( p['last_modified_timestamp_ms'] / 1000.0) if ((b64encode(str(p['encounter_id'])), p['spawn_point_id']) in encountered_pokemon): # If Pokemon has been encountered before don't process it. skipped += 1 continue start_end = SpawnPoint.start_end(sp, 1) seconds_until_despawn = (start_end[1] - now_secs) % 3600 disappear_time = now_date + \ timedelta(seconds=seconds_until_despawn) pokemon_id = p['pokemon_data']['pokemon_id'] printPokemon(pokemon_id, p['latitude'], p['longitude'], disappear_time) # Scan for IVs/CP and moves. encounter_result = None if args.encounter and (pokemon_id in args.enc_whitelist): time.sleep(args.encounter_delay) hlvl_account = None hlvl_api = None using_accountset = False scan_location = [p['latitude'], p['longitude']] # If the host has L30s in the regular account pool, we # can just use the current account. if level >= 30: hlvl_account = account hlvl_api = api else: # Get account to use for IV and CP scanning. hlvl_account = account_sets.next('30', scan_location) # If we don't have an API object yet, it means we didn't re-use # an old one, so we're using AccountSet. using_accountset = not hlvl_api # If we didn't get an account, we can't encounter. if hlvl_account: # Logging. log.debug('Encountering Pokémon ID %s with account %s' + ' at %s, %s.', pokemon_id, hlvl_account['username'], scan_location[0], scan_location[1]) # If not args.no_api_store is enabled, we need to # re-use an old API object if it's stored and we're # using an account from the AccountSet. if not args.no_api_store and using_accountset: hlvl_api = hlvl_account.get('api', None) # Make new API for this account if we're not using an # API that's already logged in. if not hlvl_api: hlvl_api = setup_api(args, status, account) # Hashing key. # TODO: all of this should be handled properly... all # these useless, inefficient threads passing around all # these single-use variables are making me ill. if args.hash_key: key = key_scheduler.next() log.debug('Using hashing key %s for this' + ' encounter.', key) hlvl_api.activate_hash_server(key) # We have an API object now. If necessary, store it. if using_accountset and not args.no_api_store: hlvl_account['api'] = hlvl_api # Set location. hlvl_api.set_position(*scan_location) # Log in. check_login(args, hlvl_account, hlvl_api, scan_location, status['proxy_url']) # Encounter Pokémon. encounter_result = encounter_pokemon_request( hlvl_api, p['encounter_id'], p['spawn_point_id'], scan_location) # Handle errors. if encounter_result: # Readability. responses = encounter_result['responses'] # Check for captcha. captcha_url = responses[ 'CHECK_CHALLENGE']['challenge_url'] # Throw warning but finish parsing. if len(captcha_url) > 1: # Flag account. hlvl_account['captcha'] = True log.error('Account %s encountered a captcha.' + ' Account will not be used.', hlvl_account['username']) else: # Update level indicator before we clear the # response. encounter_level = get_player_level( encounter_result) # User error? if encounter_level < 30: raise Exception('Expected account of level 30' + ' or higher, but account ' + hlvl_account['username'] + ' is only level ' + encounter_level + '.') # We're done with the encounter. If it's from an # AccountSet, release account back to the pool. if using_accountset: account_sets.release(hlvl_account) # Clear the response for memory management. encounter_result = clear_dict_response( encounter_result) else: # Something happened. Clean up. # We're done with the encounter. If it's from an # AccountSet, release account back to the pool. if using_accountset: account_sets.release(hlvl_account) else: log.error('No L30 accounts are available, please' + ' consider adding more. Skipping encounter.') pokemon[p['encounter_id']] = { 'encounter_id': b64encode(str(p['encounter_id'])), 'spawnpoint_id': p['spawn_point_id'], 'pokemon_id': pokemon_id, 'latitude': p['latitude'], 'longitude': p['longitude'], 'disappear_time': disappear_time, 'individual_attack': None, 'individual_defense': None, 'individual_stamina': None, 'move_1': None, 'move_2': None, 'cp': None, 'cp_multiplier': None, 'height': None, 'weight': None, 'gender': p['pokemon_data']['pokemon_display']['gender'], 'form': None } # Check for Unown's alphabetic character. if pokemon_id == 201: pokemon[p['encounter_id']]['form'] = p['pokemon_data'][ 'pokemon_display'].get('form', None) if (encounter_result is not None and 'wild_pokemon' in encounter_result['responses']['ENCOUNTER']): pokemon_info = encounter_result['responses'][ 'ENCOUNTER']['wild_pokemon']['pokemon_data'] # IVs. individual_attack = pokemon_info.get('individual_attack', 0) individual_defense = pokemon_info.get('individual_defense', 0) individual_stamina = pokemon_info.get('individual_stamina', 0) cp = pokemon_info.get('cp', None) # Logging: let the user know we succeeded. log.debug('Encounter for Pokémon ID %s' + ' at %s, %s successful: ' + ' %s/%s/%s, %s CP.', pokemon_id, p['latitude'], p['longitude'], individual_attack, individual_defense, individual_stamina, cp) pokemon[p['encounter_id']].update({ 'individual_attack': individual_attack, 'individual_defense': individual_defense, 'individual_stamina': individual_stamina, 'move_1': pokemon_info['move_1'], 'move_2': pokemon_info['move_2'], 'height': pokemon_info['height_m'], 'weight': pokemon_info['weight_kg'] }) # Only add CP if we're level 30+. if encounter_level >= 30: pokemon[p['encounter_id']]['cp'] = cp pokemon[p['encounter_id']][ 'cp_multiplier'] = pokemon_info.get( 'cp_multiplier', None) if args.webhooks: if (pokemon_id in args.webhook_whitelist or (not args.webhook_whitelist and pokemon_id not in args.webhook_blacklist)): wh_poke = pokemon[p['encounter_id']].copy() wh_poke.update({ 'disappear_time': calendar.timegm( disappear_time.timetuple()), 'last_modified_time': p['last_modified_timestamp_ms'], 'time_until_hidden_ms': p['time_till_hidden_ms'], 'verified': SpawnPoint.tth_found(sp), 'seconds_until_despawn': seconds_until_despawn, 'spawn_start': start_end[0], 'spawn_end': start_end[1], 'player_level': encounter_level }) if wh_poke['cp_multiplier'] is not None: wh_poke.update({ 'pokemon_level': calc_pokemon_level( wh_poke['cp_multiplier']) }) wh_update_queue.put(('pokemon', wh_poke)) if forts and (config['parse_pokestops'] or config['parse_gyms']): if config['parse_pokestops']: stop_ids = [f['id'] for f in forts if f.get('type') == 1] if stop_ids: query = (Pokestop .select(Pokestop.pokestop_id, Pokestop.last_modified) .where((Pokestop.pokestop_id << stop_ids)) .dicts()) encountered_pokestops = [(f['pokestop_id'], int( (f['last_modified'] - datetime(1970, 1, 1)).total_seconds())) for f in query] # Complete tutorial with a Pokestop spin if args.complete_tutorial and not (len(captcha_url) > 1): if config['parse_pokestops']: tutorial_pokestop_spin( api, level, forts, step_location, account) else: log.error( 'Pokestop can not be spun since parsing Pokestops is ' + 'not active. Check if \'-nk\' flag is accidentally set.') for f in forts: if config['parse_pokestops'] and f.get('type') == 1: # Pokestops. if 'active_fort_modifier' in f: lure_expiration = (datetime.utcfromtimestamp( f['last_modified_timestamp_ms'] / 1000.0) + timedelta(minutes=args.lure_duration)) active_fort_modifier = f['active_fort_modifier'] if args.webhooks and args.webhook_updates_only: wh_update_queue.put(('pokestop', { 'pokestop_id': b64encode(str(f['id'])), 'enabled': f['enabled'], 'latitude': f['latitude'], 'longitude': f['longitude'], 'last_modified_time': f[ 'last_modified_timestamp_ms'], 'lure_expiration': calendar.timegm( lure_expiration.timetuple()), 'active_fort_modifier': active_fort_modifier })) else: lure_expiration, active_fort_modifier = None, None # Send all pokestops to webhooks. if args.webhooks and not args.webhook_updates_only: # Explicitly set 'webhook_data', in case we want to change # the information pushed to webhooks. Similar to above and # previous commits. l_e = None if lure_expiration is not None: l_e = calendar.timegm(lure_expiration.timetuple()) wh_update_queue.put(('pokestop', { 'pokestop_id': b64encode(str(f['id'])), 'enabled': f['enabled'], 'latitude': f['latitude'], 'longitude': f['longitude'], 'last_modified_time': f['last_modified_timestamp_ms'], 'lure_expiration': l_e, 'active_fort_modifier': active_fort_modifier })) if ((f['id'], int(f['last_modified_timestamp_ms'] / 1000.0)) in encountered_pokestops): # If pokestop has been encountered before and hasn't # changed don't process it. stopsskipped += 1 continue pokestops[f['id']] = { 'pokestop_id': f['id'], 'enabled': f.get('enabled', 0), 'latitude': f['latitude'], 'longitude': f['longitude'], 'last_modified': datetime.utcfromtimestamp( f['last_modified_timestamp_ms'] / 1000.0), 'lure_expiration': lure_expiration, 'active_fort_modifier': active_fort_modifier } # Currently, there are only stops and gyms. elif config['parse_gyms'] and f.get('type') is None: # Send gyms to webhooks. if args.webhooks and not args.webhook_updates_only: # Explicitly set 'webhook_data', in case we want to change # the information pushed to webhooks. Similar to above # and previous commits. wh_update_queue.put(('gym', { 'gym_id': b64encode(str(f['id'])), 'team_id': f.get('owned_by_team', 0), 'guard_pokemon_id': f.get('guard_pokemon_id', 0), 'gym_points': f.get('gym_points', 0), 'enabled': f['enabled'], 'latitude': f['latitude'], 'longitude': f['longitude'], 'last_modified': f['last_modified_timestamp_ms'] })) gyms[f['id']] = { 'gym_id': f['id'], 'team_id': f.get('owned_by_team', 0), 'guard_pokemon_id': f.get('guard_pokemon_id', 0), 'gym_points': f.get('gym_points', 0), 'enabled': f['enabled'], 'latitude': f['latitude'], 'longitude': f['longitude'], 'last_modified': datetime.utcfromtimestamp( f['last_modified_timestamp_ms'] / 1000.0), } # Helping out the GC. del forts log.info('Parsing found Pokemon: %d, nearby: %d, pokestops: %d, gyms: %d.', len(pokemon) + skipped, nearby_pokemon, len(pokestops) + stopsskipped, len(gyms)) log.debug('Skipped Pokemon: %d, pokestops: %d.', skipped, stopsskipped) # Look for spawnpoints within scan_loc that are not here to see if we # can narrow down tth window. for sp in ScannedLocation.linked_spawn_points(scan_loc['cellid']): if sp['id'] in sp_id_list: # Don't overwrite changes from this parse with DB version. sp = spawn_points[sp['id']] else: # If the cell has completed, we need to classify all # the SPs that were not picked up in the scan if just_completed: SpawnpointDetectionData.classify(sp, scan_loc, now_secs) spawn_points[sp['id']] = sp if SpawnpointDetectionData.unseen(sp, now_secs): spawn_points[sp['id']] = sp endpoints = SpawnPoint.start_end(sp, args.spawn_delay) if clock_between(endpoints[0], now_secs, endpoints[1]): sp['missed_count'] += 1 spawn_points[sp['id']] = sp log.warning('%s kind spawnpoint %s has no Pokemon %d times' ' in a row.', sp['kind'], sp['id'], sp['missed_count']) log.info('Possible causes: Still doing initial scan, super' ' rare double spawnpoint during') log.info('hidden period, or Niantic has removed ' 'spawnpoint.') if (not SpawnPoint.tth_found(sp) and scan_loc['done'] and (now_secs - sp['latest_seen'] - args.spawn_delay) % 3600 < 60): log.warning('Spawnpoint %s was unable to locate a TTH, with ' 'only %ss after Pokemon last seen.', sp['id'], (now_secs - sp['latest_seen']) % 3600) log.info('Restarting current 15 minute search for TTH.') if sp['id'] not in sp_id_list: SpawnpointDetectionData.classify(sp, scan_loc, now_secs) sp['latest_seen'] = (sp['latest_seen'] - 60) % 3600 sp['earliest_unseen'] = ( sp['earliest_unseen'] + 14 * 60) % 3600 spawn_points[sp['id']] = sp db_update_queue.put((ScannedLocation, {0: scan_loc})) if pokemon: db_update_queue.put((Pokemon, pokemon)) if pokestops: db_update_queue.put((Pokestop, pokestops)) if gyms: db_update_queue.put((Gym, gyms)) if spawn_points: db_update_queue.put((SpawnPoint, spawn_points)) db_update_queue.put((ScanSpawnPoint, scan_spawn_points)) if sightings: db_update_queue.put((SpawnpointDetectionData, sightings)) if not nearby_pokemon and not wild_pokemon: # After parsing the forts, we'll mark this scan as bad due to # a possible speed violation. return { 'count': wild_pokemon_count + forts_count, 'gyms': gyms, 'sp_id_list': sp_id_list, 'bad_scan': True, 'scan_secs': now_secs } return { 'count': wild_pokemon_count + forts_count, 'gyms': gyms, 'sp_id_list': sp_id_list, 'bad_scan': False, 'scan_secs': now_secs } def parse_gyms(args, gym_responses, wh_update_queue, db_update_queue): gym_details = {} gym_members = {} gym_pokemon = {} trainers = {} i = 0 for g in gym_responses.values(): gym_state = g['gym_state'] gym_id = gym_state['fort_data']['id'] gym_details[gym_id] = { 'gym_id': gym_id, 'name': g['name'], 'description': g.get('description'), 'url': g['urls'][0], } if args.webhooks: webhook_data = { 'id': b64encode(str(gym_id)), 'latitude': gym_state['fort_data']['latitude'], 'longitude': gym_state['fort_data']['longitude'], 'team': gym_state['fort_data'].get('owned_by_team', 0), 'name': g['name'], 'description': g.get('description'), 'url': g['urls'][0], 'pokemon': [], } for member in gym_state.get('memberships', []): gym_members[i] = { 'gym_id': gym_id, 'pokemon_uid': member['pokemon_data']['id'], } gym_pokemon[i] = { 'pokemon_uid': member['pokemon_data']['id'], 'pokemon_id': member['pokemon_data']['pokemon_id'], 'cp': member['pokemon_data']['cp'], 'trainer_name': member['trainer_public_profile']['name'], 'num_upgrades': member['pokemon_data'].get('num_upgrades', 0), 'move_1': member['pokemon_data'].get('move_1'), 'move_2': member['pokemon_data'].get('move_2'), 'height': member['pokemon_data'].get('height_m'), 'weight': member['pokemon_data'].get('weight_kg'), 'stamina': member['pokemon_data'].get('stamina'), 'stamina_max': member['pokemon_data'].get('stamina_max'), 'cp_multiplier': member['pokemon_data'].get('cp_multiplier'), 'additional_cp_multiplier': member['pokemon_data'].get( 'additional_cp_multiplier', 0), 'iv_defense': member['pokemon_data'].get( 'individual_defense', 0), 'iv_stamina': member['pokemon_data'].get( 'individual_stamina', 0), 'iv_attack': member['pokemon_data'].get( 'individual_attack', 0), 'last_seen': datetime.utcnow(), } trainers[i] = { 'name': member['trainer_public_profile']['name'], 'team': gym_state['fort_data']['owned_by_team'], 'level': member['trainer_public_profile']['level'], 'last_seen': datetime.utcnow(), } if args.webhooks: webhook_data['pokemon'].append({ 'pokemon_uid': member['pokemon_data']['id'], 'pokemon_id': member['pokemon_data']['pokemon_id'], 'cp': member['pokemon_data']['cp'], 'num_upgrades': member['pokemon_data'].get( 'num_upgrades', 0), 'move_1': member['pokemon_data'].get('move_1'), 'move_2': member['pokemon_data'].get('move_2'), 'height': member['pokemon_data'].get('height_m'), 'weight': member['pokemon_data'].get('weight_kg'), 'stamina': member['pokemon_data'].get('stamina'), 'stamina_max': member['pokemon_data'].get('stamina_max'), 'cp_multiplier': member['pokemon_data'].get( 'cp_multiplier'), 'additional_cp_multiplier': member['pokemon_data'].get( 'additional_cp_multiplier', 0), 'iv_defense': member['pokemon_data'].get( 'individual_defense', 0), 'iv_stamina': member['pokemon_data'].get( 'individual_stamina', 0), 'iv_attack': member['pokemon_data'].get( 'individual_attack', 0), 'trainer_name': member['trainer_public_profile']['name'], 'trainer_level': member['trainer_public_profile']['level'], }) i += 1 if args.webhooks: wh_update_queue.put(('gym_details', webhook_data)) # All this database stuff is synchronous (not using the upsert queue) on # purpose. Since the search workers load the GymDetails model from the # database to determine if a gym needs to be rescanned, we need to be sure # the GymDetails get fully committed to the database before moving on. # # We _could_ synchronously upsert GymDetails, then queue the other tables # for upsert, but that would put that Gym's overall information in a weird # non-atomic state. # Upsert all the models. if gym_details: db_update_queue.put((GymDetails, gym_details)) if gym_pokemon: db_update_queue.put((GymPokemon, gym_pokemon)) if trainers: db_update_queue.put((Trainer, trainers)) # This needs to be completed in a transaction, because we don't wany any # other thread or process to mess with the GymMembers for the gyms we're # updating while we're updating the bridge table. with flaskDb.database.transaction(): # Get rid of all the gym members, we're going to insert new records. if gym_details: DeleteQuery(GymMember).where( GymMember.gym_id << gym_details.keys()).execute() # Insert new gym members. if gym_members: db_update_queue.put((GymMember, gym_members)) log.info('Upserted gyms: %d, gym members: %d.', len(gym_details), len(gym_members)) def db_updater(args, q, db): # The forever loop. while True: try: while True: try: flaskDb.connect_db() break except Exception as e: log.warning('%s... Retrying...', repr(e)) time.sleep(5) # Loop the queue. while True: last_upsert = default_timer() model, data = q.get() bulk_upsert(model, data, db) q.task_done() log.debug('Upserted to %s, %d records (upsert queue ' 'remaining: %d) in %.2f seconds.', model.__name__, len(data), q.qsize(), default_timer() - last_upsert) # Helping out the GC. del model del data if q.qsize() > 50: log.warning( "DB queue is > 50 (@%d); try increasing --db-threads.", q.qsize()) except Exception as e: log.exception('Exception in db_updater: %s', repr(e)) time.sleep(5) def clean_db_loop(args): while True: try: query = (MainWorker .delete() .where((MainWorker.last_modified < (datetime.utcnow() - timedelta(minutes=30))))) query.execute() query = (WorkerStatus .delete() .where((WorkerStatus.last_modified < (datetime.utcnow() - timedelta(minutes=30))))) query.execute() # Remove active modifier from expired lured pokestops. query = (Pokestop .update(lure_expiration=None, active_fort_modifier=None) .where(Pokestop.lure_expiration < datetime.utcnow())) query.execute() # Remove old (unusable) captcha tokens query = (Token .delete() .where((Token.last_updated < (datetime.utcnow() - timedelta(minutes=2))))) query.execute() # Remove expired HashKeys query = (HashKeys .delete() .where(HashKeys.expires < (datetime.now() - timedelta(days=1)))) query.execute() # If desired, clear old Pokemon spawns. if args.purge_data > 0: log.info("Beginning purge of old Pokemon spawns.") start = datetime.utcnow() query = (Pokemon .delete() .where((Pokemon.disappear_time < (datetime.utcnow() - timedelta(hours=args.purge_data))))) rows = query.execute() end = datetime.utcnow() diff = end - start log.info("Completed purge of old Pokemon spawns. " "%i deleted in %f seconds.", rows, diff.total_seconds()) log.info('Regular database cleaning complete.') time.sleep(60) except Exception as e: log.exception('Exception in clean_db_loop: %s', repr(e)) def bulk_upsert(cls, data, db): num_rows = len(data.values()) i = 0 if args.db_type == 'mysql': step = 250 else: # SQLite has a default max number of parameters of 999, # so we need to limit how many rows we insert for it. step = 50 with db.atomic(): while i < num_rows: log.debug('Inserting items %d to %d.', i, min(i + step, num_rows)) try: # Turn off FOREIGN_KEY_CHECKS on MySQL, because apparently it's # unable to recognize strings to update unicode keys for # foreign key fields, thus giving lots of foreign key # constraint errors. if args.db_type == 'mysql': db.execute_sql('SET FOREIGN_KEY_CHECKS=0;') # Use peewee's own implementation of the insert_many() method. InsertQuery(cls, rows=data.values()[ i:min(i + step, num_rows)]).upsert().execute() if args.db_type == 'mysql': db.execute_sql('SET FOREIGN_KEY_CHECKS=1;') except Exception as e: # If there is a DB table constraint error, dump the data and # don't retry. # # Unrecoverable error strings: unrecoverable = ['constraint', 'has no attribute', 'peewee.IntegerField object at'] has_unrecoverable = filter( lambda x: x in str(e), unrecoverable) if has_unrecoverable: log.warning('%s. Data is:', repr(e)) log.warning(data.items()) else: log.warning('%s... Retrying...', repr(e)) time.sleep(1) continue i += step def create_tables(db): db.connect() tables = [Pokemon, Pokestop, Gym, ScannedLocation, GymDetails, GymMember, GymPokemon, Trainer, MainWorker, WorkerStatus, SpawnPoint, ScanSpawnPoint, SpawnpointDetectionData, Token, LocationAltitude, HashKeys] for table in tables: if not table.table_exists(): log.info('Creating table: %s', table.__name__) db.create_tables([table], safe=True) else: log.debug('Skipping table %s, it already exists.', table.__name__) db.close() def drop_tables(db): tables = [Pokemon, Pokestop, Gym, ScannedLocation, Versions, GymDetails, GymMember, GymPokemon, Trainer, MainWorker, WorkerStatus, SpawnPoint, ScanSpawnPoint, SpawnpointDetectionData, LocationAltitude, Token, HashKeys] db.connect() db.execute_sql('SET FOREIGN_KEY_CHECKS=0;') for table in tables: if table.table_exists(): log.info('Dropping table: %s', table.__name__) db.drop_tables([table], safe=True) db.execute_sql('SET FOREIGN_KEY_CHECKS=1;') db.close() def verify_table_encoding(db): if args.db_type == 'mysql': db.connect() cmd_sql = ''' SELECT table_name FROM information_schema.tables WHERE table_collation != "utf8mb4_unicode_ci" AND table_schema = "%s"; ''' % args.db_name change_tables = db.execute_sql(cmd_sql) cmd_sql = "SHOW tables;" tables = db.execute_sql(cmd_sql) if change_tables.rowcount > 0: log.info('Changing collation and charset on %s tables.', change_tables.rowcount) if change_tables.rowcount == tables.rowcount: log.info('Changing whole database, this might a take while.') with db.atomic(): db.execute_sql('SET FOREIGN_KEY_CHECKS=0;') for table in change_tables: log.debug('Changing collation and charset on table %s.', table[0]) cmd_sql = '''ALTER TABLE %s CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;''' % str(table[0]) db.execute_sql(cmd_sql) db.execute_sql('SET FOREIGN_KEY_CHECKS=1;') db.close() def verify_database_schema(db): db.connect() if not Versions.table_exists(): db.create_tables([Versions]) if ScannedLocation.table_exists(): # Versions table doesn't exist, but there are tables. This must # mean the user is coming from a database that existed before we # started tracking the schema version. Perform a full upgrade. InsertQuery(Versions, {Versions.key: 'schema_version', Versions.val: 0}).execute() database_migrate(db, 0) else: InsertQuery(Versions, {Versions.key: 'schema_version', Versions.val: db_schema_version}).execute() else: db_ver = Versions.get(Versions.key == 'schema_version').val if db_ver < db_schema_version: database_migrate(db, db_ver) elif db_ver > db_schema_version: log.error('Your database version (%i) appears to be newer than ' 'the code supports (%i).', db_ver, db_schema_version) log.error('Please upgrade your code base or drop all tables in ' 'your database.') sys.exit(1) db.close() def database_migrate(db, old_ver): # Update database schema version. Versions.update(val=db_schema_version).where( Versions.key == 'schema_version').execute() log.info('Detected database version %i, updating to %i...', old_ver, db_schema_version) # Perform migrations here. migrator = None if args.db_type == 'mysql': migrator = MySQLMigrator(db) else: migrator = SqliteMigrator(db) if old_ver < 2: migrate(migrator.add_column('pokestop', 'encounter_id', Utf8mb4CharField(max_length=50, null=True))) if old_ver < 3: migrate( migrator.add_column('pokestop', 'active_fort_modifier', Utf8mb4CharField(max_length=50, null=True)), migrator.drop_column('pokestop', 'encounter_id'), migrator.drop_column('pokestop', 'active_pokemon_id') ) if old_ver < 4: db.drop_tables([ScannedLocation]) if old_ver < 5: # Some Pokemon were added before the 595 bug was "fixed". # Clean those up for a better UX. query = (Pokemon .delete() .where(Pokemon.disappear_time > (datetime.utcnow() - timedelta(hours=24)))) query.execute() if old_ver < 6: migrate( migrator.add_column('gym', 'last_scanned', DateTimeField(null=True)), ) if old_ver < 7: migrate( migrator.drop_column('gymdetails', 'description'), migrator.add_column('gymdetails', 'description', TextField(null=True, default="")) ) if old_ver < 8: migrate( migrator.add_column('pokemon', 'individual_attack', IntegerField(null=True, default=0)), migrator.add_column('pokemon', 'individual_defense', IntegerField(null=True, default=0)), migrator.add_column('pokemon', 'individual_stamina', IntegerField(null=True, default=0)), migrator.add_column('pokemon', 'move_1', IntegerField(null=True, default=0)), migrator.add_column('pokemon', 'move_2', IntegerField(null=True, default=0)) ) if old_ver < 9: migrate( migrator.add_column('pokemon', 'last_modified', DateTimeField(null=True, index=True)), migrator.add_column('pokestop', 'last_updated', DateTimeField(null=True, index=True)) ) if old_ver < 10: # Information in ScannedLocation and Member Status is probably # out of date. Drop and recreate with new schema. db.drop_tables([ScannedLocation]) db.drop_tables([WorkerStatus]) if old_ver < 11: db.drop_tables([ScanSpawnPoint]) if old_ver < 13: db.drop_tables([WorkerStatus]) db.drop_tables([MainWorker]) if old_ver < 14: migrate( migrator.add_column('pokemon', 'weight', DoubleField(null=True, default=0)), migrator.add_column('pokemon', 'height', DoubleField(null=True, default=0)), migrator.add_column('pokemon', 'gender', IntegerField(null=True, default=0)) ) if old_ver < 15: # we don't have to touch sqlite because it has REAL and INTEGER only if args.db_type == 'mysql': db.execute_sql('ALTER TABLE `pokemon` ' 'MODIFY COLUMN `weight` FLOAT NULL DEFAULT NULL,' 'MODIFY COLUMN `height` FLOAT NULL DEFAULT NULL,' 'MODIFY COLUMN `gender` SMALLINT NULL DEFAULT NULL' ';') if old_ver < 16: log.info('This DB schema update can take some time. ' 'Please be patient.') # change some column types from INT to SMALLINT # we don't have to touch sqlite because it has INTEGER only if args.db_type == 'mysql': db.execute_sql( 'ALTER TABLE `pokemon` ' 'MODIFY COLUMN `pokemon_id` SMALLINT NOT NULL,' 'MODIFY COLUMN `individual_attack` SMALLINT ' 'NULL DEFAULT NULL,' 'MODIFY COLUMN `individual_defense` SMALLINT ' 'NULL DEFAULT NULL,' 'MODIFY COLUMN `individual_stamina` SMALLINT ' 'NULL DEFAULT NULL,' 'MODIFY COLUMN `move_1` SMALLINT NULL DEFAULT NULL,' 'MODIFY COLUMN `move_2` SMALLINT NULL DEFAULT NULL;' ) db.execute_sql( 'ALTER TABLE `gym` ' 'MODIFY COLUMN `team_id` SMALLINT NOT NULL,' 'MODIFY COLUMN `guard_pokemon_id` SMALLINT NOT NULL;' ) db.execute_sql( 'ALTER TABLE `scannedlocation` ' 'MODIFY COLUMN `band1` SMALLINT NOT NULL,' 'MODIFY COLUMN `band2` SMALLINT NOT NULL,' 'MODIFY COLUMN `band3` SMALLINT NOT NULL,' 'MODIFY COLUMN `band4` SMALLINT NOT NULL,' 'MODIFY COLUMN `band5` SMALLINT NOT NULL,' 'MODIFY COLUMN `midpoint` SMALLINT NOT NULL,' 'MODIFY COLUMN `width` SMALLINT NOT NULL;' ) db.execute_sql( 'ALTER TABLE `spawnpoint` ' 'MODIFY COLUMN `latest_seen` SMALLINT NOT NULL,' 'MODIFY COLUMN `earliest_unseen` SMALLINT NOT NULL;' ) db.execute_sql( 'ALTER TABLE `spawnpointdetectiondata` ' 'MODIFY COLUMN `tth_secs` SMALLINT NULL DEFAULT NULL;' ) db.execute_sql( 'ALTER TABLE `versions` ' 'MODIFY COLUMN `val` SMALLINT NOT NULL;' ) db.execute_sql( 'ALTER TABLE `gympokemon` ' 'MODIFY COLUMN `pokemon_id` SMALLINT NOT NULL,' 'MODIFY COLUMN `cp` SMALLINT NOT NULL,' 'MODIFY COLUMN `num_upgrades` SMALLINT NULL DEFAULT NULL,' 'MODIFY COLUMN `move_1` SMALLINT NULL DEFAULT NULL,' 'MODIFY COLUMN `move_2` SMALLINT NULL DEFAULT NULL,' 'MODIFY COLUMN `stamina` SMALLINT NULL DEFAULT NULL,' 'MODIFY COLUMN `stamina_max` SMALLINT NULL DEFAULT NULL,' 'MODIFY COLUMN `iv_defense` SMALLINT NULL DEFAULT NULL,' 'MODIFY COLUMN `iv_stamina` SMALLINT NULL DEFAULT NULL,' 'MODIFY COLUMN `iv_attack` SMALLINT NULL DEFAULT NULL;' ) db.execute_sql( 'ALTER TABLE `trainer` ' 'MODIFY COLUMN `team` SMALLINT NOT NULL,' 'MODIFY COLUMN `level` SMALLINT NOT NULL;' ) # add some missing indexes migrate( migrator.add_index('gym', ('last_scanned',), False), migrator.add_index('gymmember', ('last_scanned',), False), migrator.add_index('gymmember', ('pokemon_uid',), False), migrator.add_index('gympokemon', ('trainer_name',), False), migrator.add_index('pokestop', ('active_fort_modifier',), False), migrator.add_index('spawnpointdetectiondata', ('spawnpoint_id',), False), migrator.add_index('token', ('last_updated',), False) ) # pokestop.last_updated was missing in a previous migration # check whether we have to add it has_last_updated_index = False for index in db.get_indexes('pokestop'): if index.columns[0] == 'last_updated': has_last_updated_index = True break if not has_last_updated_index: log.debug('pokestop.last_updated index is missing. Creating now.') migrate( migrator.add_index('pokestop', ('last_updated',), False) ) if old_ver < 17: migrate( migrator.add_column('pokemon', 'form', SmallIntegerField(null=True)) ) if old_ver < 18: migrate( migrator.add_column('pokemon', 'cp', SmallIntegerField(null=True)) ) if old_ver < 19: migrate( migrator.add_column('pokemon', 'cp_multiplier', FloatField(null=True)) ) # Always log that we're done. log.info('Schema upgrade complete.')
agpl-3.0
watzerm/SchemeRealizer
includes/view/About.php
3996
<?php /* SchemeRealizer - A free ORM and Translator for Diagrams, Databases and PHP-Classes/Interfaces. Copyright (C) 2016 Michael Watzer 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/>. */ /** * @author Christian Dittrich * @version 1.1 * @since 19.03.2017 * @category View functions for About page */ /** * @return String * @category function which holds the html code of the About section */ function getAbout(){ $about = <<<ABOUT <div id="subContentDIV"> <h2><b>About.</b></h2> ABOUT; $about .= <<<ABOUT <h3><b>Where can I view the source code?</b></h3> <h4><a href='https://github.com/watzerm/SchemeRealizer' target='_blank'>View on GitHub!</a></h4> ABOUT; $about .= <<<ABOUT <h3><b>What does SchemeRealizer provide?</b></h3> <li>Convert your documentation into code and vice versa</li> <li>An GUI-based ORM to flush your database into code and vice versa</li> <li>In general a translation from one system to another, as long as SchemeRealizer provides it</li> <li>An API for third-party projects to use the full functionality of SchemeRealizer</li> <li>A clean and technical documentation for developers</li> ABOUT; $about .= <<<ABOUT <h3><b>Which Systems are supported?</b></h3> <li>PHP-based classes</li> <li>PHP-based interfaces</li> <li>Java-based classes</li> <li>Java-based interfaces</li> <li>UML class diagrams in .txt files</li> <li>MySQL</li> <li>MariaDB</li> <li>SQLite</li> <li>MongoDB</li> ABOUT; $about .= <<<ABOUT <h3><b>Where is the documentation?</b></h3> There are several documentation files in the doc directory.<br /> <h4><b>Short explanation</b></h4> <h5><b>Architecture</b></h5> Contains the software architecture of SchemeRealizer.<br /> SchemeRealizer is based on a simple MVC architecture where JSON-Strings are passed from one page to another.<br /> <h5><b>NORM</b></h5> Which syntax does a class-diagram follow? <h5><b>api</b></h5> A genereal documentation about the API for third-party projects.<br /> Furthermore a tech. documentation where members and methods are described.<br /> <h5><b>gen</b></h5> A documentation concerning the validation process for SQL-based engines.<br /> <h5><b>php</b></h5> Documentation concerning the parsing process.<br /> With basic math and theoretical informatic knowledge you can get a sneak peek on how we parse PHP-based classes.<br /> <h5><b>java</b></h5> Documentation concerning the parsing process.<br /> <h5><b>structure</b></h5> The syntax on how JSON-Strings are build-up in SchemeRealizer.<br /> <h5><b>utils</b></h5> A Javadoc like documentation about the utils-classes, the core of SchemeRealizer.<br /> ABOUT; $about .= <<<ABOUT <h3><b>License?</b></h3> GNU Affero General Public License.<br /> ABOUT; $about .= <<<ABOUT <h3><b>Who developed SchemeRealizer?</b></h3> SchemeRealizer is developed and maintained by two developers in Austria, Vienna.<br /> <h4><b>Contact?</b></h4> <li>Michael Watzer, lead developer(<a href="mailto:[email protected]">[email protected]</a>)</li> <li>Christian Dittrich, developer (<a href="mailto:[email protected]">[email protected]</a>)</li> ABOUT; $about .= "</div>"; return $about; }
agpl-3.0
akvo/akvo-sites-zz-template
code/wp-content/plugins/wp-flexible-map/includes/class.FlxMapLocalisation.php
5117
<?php if (!defined('ABSPATH')) { exit; } /** * class for managing the plugin */ class FlxMapLocalisation { const TEXT_DOMAIN = 'wp-flexible-map'; const TRANSIENT_LANGPACKS = 'flexible_map_langpacks'; protected $script_strings; /** * initialise the class if it hasn't been */ public function __construct() { // declare l10n strings used in JavaScript so a gettext scanner can find them // and record for use in filtering localisations $this->script_strings = array( 'Click for details' => __('Click for details', 'wp-flexible-map'), 'Directions' => __('Directions', 'wp-flexible-map'), 'From' => __('From', 'wp-flexible-map'), 'Get directions' => __('Get directions', 'wp-flexible-map'), ); } /** * get localisations for map scripts, ignoring admin localisations * @param array $locales * @return array */ public function getLocalisations($locales) { $i18n = array(); $langPacks = array(); // record list of locales for language pack update fetches foreach (array_keys($locales) as $locale) { $moLocale = self::getMoLocale($locale); $mofile = self::getMofilePath($moLocale); $langPacks[] = $moLocale; // check for specific locale first, e.g. 'zh-CN', then for generic locale, e.g. 'zh' // (backwards compatibility) if (!$mofile && strlen($locale) > 2) { $locale = substr($locale, 0, 2); $moLocale = self::getMoLocale($locale); $mofile = self::getMofilePath($moLocale); } if ($mofile) { $mo = new MO(); if ($mo->import_from_file($mofile)) { $strings = self::getMoStrings($mofile); if (!empty($strings)) { // filter to only contain strings we need in JavaScript $strings = array_intersect_key($strings, $this->script_strings); $i18n[$locale] = $strings; } } } } if (!empty($langPacks)) { $this->updateGlobalMapLocales($langPacks); } return $i18n; } /** * translate locale code to .mo file code, for backwards compatibility with earlier versions of plugin * @param string $locale * @return string */ protected static function getMoLocale($locale) { // map old two-character language-only locales that now need to target language_country translations static $upgradeMap = array( 'bg' => 'bg_BG', 'cs' => 'cs_CZ', 'da' => 'da_DK', 'de' => 'de_DE', 'es' => 'es_ES', 'fa' => 'fa_IR', 'fr' => 'fr_FR', 'gl' => 'gl_ES', 'he' => 'he_IL', 'hi' => 'hi_IN', 'hu' => 'hu_HU', 'id' => 'id_ID', 'is' => 'is_IS', 'it' => 'it_IT', 'ko' => 'ko_KR', 'lt' => 'lt_LT', 'mk' => 'mk_MK', 'ms' => 'ms_MY', 'mt' => 'mt_MT', 'nb' => 'nb_NO', 'nl' => 'nl_NL', 'pl' => 'pl_PL', 'pt' => 'pt_PT', 'ro' => 'ro_RO', 'ru' => 'ru_RU', 'sk' => 'sk_SK', 'sl' => 'sl_SL', 'sr' => 'sr_RS', 'sv' => 'sv_SE', 'ta' => 'ta_IN', 'tr' => 'tr_TR', 'zh' => 'zh_CN', ); if (isset($upgradeMap[$locale])) { // upgrade old two-character language-only locales return $upgradeMap[$locale]; } // revert locale name to WordPress locale name as used in .mo files return strtr($locale, '-', '_'); } /** * get full path to .mo file * @param string $moLocale * @return string|bool returns false if it doesn't exist */ protected static function getMofilePath($moLocale) { // try translation packs downloaded from translate.wordpress.org first $path = sprintf('%s/plugins/%s-%s.mo', WP_LANG_DIR, self::TEXT_DOMAIN, $moLocale); if (is_readable($path)) { return $path; } // try local packs delivered with the plugin $path = sprintf('%slanguages/%s-%s.mo', FLXMAP_PLUGIN_ROOT, self::TEXT_DOMAIN, $moLocale); if (is_readable($path)) { return $path; } return false; } /** * get strings from .mo file * @param string $mofile * @return array */ protected static function getMoStrings($mofile) { $strings = array(); $mo = new MO(); if ($mo->import_from_file($mofile)) { // pull all translation strings into a simplified format for our script // TODO: handle plurals (not yet needed, don't have any) foreach ($mo->entries as $original => $translation) { // skip admin-side strings, identified by context if ($translation->context === 'plugin details links') { continue; } $strings[$original] = $translation->translations[0]; } } return $strings; } /** * get locales used by maps across site (or multisite network) * for global language updates from translate.wordpress.org * @return array */ public static function getGlobalMapLocales() { $langPacks = get_site_transient(self::TRANSIENT_LANGPACKS); if (!is_array($langPacks)) { $langPacks = array(); } return $langPacks; } /** * add locales to history of locales used by maps across site (or multisite network) * for global language updates from translate.wordpress.org * @param array $locales */ protected function updateGlobalMapLocales($locales) { $langPacks = self::getGlobalMapLocales(); $diff = array_diff($locales, $langPacks); if (!empty($diff)) { $langPacks = array_merge($langPacks, $diff); set_site_transient(self::TRANSIENT_LANGPACKS, $langPacks, WEEK_IN_SECONDS); } } }
agpl-3.0
cris-iisc/mpc-primitives
crislib/libscapi/lib/boost_1_64_0/libs/asio/test/windows/basic_stream_handle.cpp
681
// // basic_stream_handle.cpp // ~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Disable autolinking for unit tests. #if !defined(BOOST_ALL_NO_LIB) #define BOOST_ALL_NO_LIB 1 #endif // !defined(BOOST_ALL_NO_LIB) // Test that header file is self-contained. #include <boost/asio/windows/basic_stream_handle.hpp> #include <boost/asio.hpp> #include "../unit_test.hpp" BOOST_ASIO_TEST_SUITE ( "windows/basic_stream_handle", BOOST_ASIO_TEST_CASE(null_test) )
agpl-3.0