repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Anshumankumar/Arya
src/ml/logisticRegression.cpp
6177
#ifndef ARYA_LOGISTIC_REGRESSION_HPP #define ARYA_LOGISTIC_REGRESSION_HPP #include <ml/csvParser.hpp> #include <ml/model.hpp> #include <cmath> class LogisticRegression:public Process<Model*, Model *> { calculateCost(); } using Row = std::pair< int ,std::vector <int>>; class LogisticRegression:public Process<CsvParser<Row>*,CsvParser<Row>*> { int maxRow; double alpha; double prevCost; public: using Process::Process; double sigmoid(double t) { return 1/(1+exp(-t)); } double calculateCost(std::vector<double> &weight ,std::vector<int> &vec, int &label) { double sum=0; for (auto &value:vec) sum += weight[value]; double sig = sigmoid(sum); return -label*log(sig)-(1-label)*log(1-sig); } double calculateError(std::vector<double> &weight ,std::vector<int> &vec, int &label) { double sum=0; for (auto &value:vec) sum += weight[value]; return sigmoid(sum) -label; } double calculateProb(std::vector<double> &weight ,std::vector<int> &vec) { double sum=0; for (auto &value:vec) sum += weight[value]; return sigmoid(sum); } double printCost(std::vector<double> &weight ,Row *t) { double J =0; for (int i=0;i<maxRow;i++) { J += calculateCost(weight,t[i].second, t[i].first); } std::cerr << J/maxRow << "\n"; return J/maxRow; } void optimise(std::vector<double> &weight, Row *t, double *error,int i) { #pragma omp parallel for for (int i=0; i< maxRow; i++) error[i] = calculateError(weight,t[i].second, t[i].first); std::vector<std::vector<double>> weights(4,std::vector<double>(weight.size(),0.0)); #pragma omp parallel for for (int j=0; j<4; j++) { for (int i=j*maxRow/4; i< (j+1)*maxRow/4; i++) { for (auto &value:t[i].second) { weights[j][value] += error[i]; } } } if (i%10 == 1) alpha = alpha*2; std::vector<double>weight3 = weight; for (int i=0;i<weight.size();i++) { weight3[i] -= alpha*(weights[0][i] + weights[1][i] + weights[2][i] + weights[3][i])/maxRow; } double currentCost = printCost(weight3,t); while ((prevCost - currentCost ) < 0) { weight3 = weight; alpha = alpha/1.35; for (int i=0;i<weight.size();i++) { weight3[i] -= alpha*(weights[0][i] + weights[1][i] + weights[2][i] + weights[3][i])/maxRow; } currentCost = printCost(weight3,t); } prevCost = currentCost; weight = weight3; } std::vector<double> train(Row *t, std::vector<double> &weight) { int maxIter = PGET<int>("maxIter"); double * error = new double[maxRow]; prevCost = printCost(weight,t); for (int i=0; i<maxIter; i++) { std::cerr << "Iteration no: " << i << "\n"; optimise(weight,t,error,i); } delete [] error; return weight; } void printROC(Row *t, double *prob, double k) { int tp = 0; int fp = 0; int fn = 0; int tn = 0; for(int i=0; i < maxRow; i++) { if (prob[i] > k && t[i].first == 1 ) tp++; if (prob[i] > k && t[i].first == 0 ) fp++; if (prob[i] < k && t[i].first == 1 ) fn++; if (prob[i] < k && t[i].first == 0 ) tn++; } if (tp ==0) return; double prec = ((double)tp)/(tp+fp); double rec = ((double)tp)/(tp+fn); double fpr = ((double)fp)/(fp+tn); double F1 = 2*prec*rec/(prec+rec); std::cout << prec << "," << fpr << "," <<rec <<"," << F1 << "\n"; } double* test(Row *t, std::vector<double> &weight) { printCost(weight,t); double * prob = new double[maxRow]; for(int i=0; i < maxRow; i++) { prob[i] = calculateProb(weight,t[i].second); } for (int i=0; i< 1000;i++) printROC(t,prob,i*0.0001); return prob; } Output run(const Input &in) { Output out; int ti = PGET<int>("ti"); for (int i=0;i<ti;i++) { std::cerr << i <<"\n"; maxRow = PGET<int>("maxRow"); alpha = PGET<double>("alpha"); std::string classType = PGET<std::string>("classType"); std::string filename = PGET<std::string>("filename"); std::cerr << "FILENAME: " << filename << "\n"; out = in->run(filename); Row* t = out->getNext(maxRow); std::cerr << maxRow << "\n"; auto indexer = std::static_pointer_cast<Indexer>(PRGET("indexer")); auto weight = indexer->getWeight(); std::cerr << "Weight size " << weight.size() << "\n"; if (classType == "trainer") { weight = train(t,weight); indexer->setWeight(weight); std::string ifile = PGET<std::string>("ifile"); indexer->saveIndex(ifile); } else if (classType == "tester") { double *prob = test(t,weight); delete prob; } } return out; } }; class SP:public SerialProcess<std::string,bool> { public: using SerialProcess::SerialProcess; void preRun() { int mtoken = PGET<int>("maxToken"); setCommonProcess(ProcessPtr (new Indexer("indexer",mtoken))); } }; int main() { SP sp("sp"); sp.addSubProcess(new CsvParser<Row>("csvParser")); sp.addSubProcess(new LogisticRegression("lr")); sp.addSubProcess(new LogisticRegression("lrt")); Params p = new Params(parseParam("/home/anshuman/Personal/arya/config/ml.param")); sp.setParam(std::make_shared<Params>(p)); sp.run(""); return 0; } #endif
gpl-3.0
akardapolov/ASH-Viewer
egantt/src/main/java/com/egantt/swing/cell/editor/state/resize/AbstractResizeEditor.java
1264
package com.egantt.swing.cell.editor.state.resize; import java.awt.Point; import java.util.Iterator; import com.egantt.model.drawing.DrawingPart; import com.egantt.model.drawing.DrawingState; import com.egantt.model.drawing.axis.AxisInterval; import com.egantt.model.drawing.axis.MutableInterval; import com.egantt.swing.cell.editor.state.StateEditor; public abstract class AbstractResizeEditor implements StateEditor{ public MutableInterval getInterval(Point point, int buffer, DrawingState drawing, Object axisKey) { Object key = drawing.getValueAt(point, buffer, buffer); return (MutableInterval) getInterval(key, drawing, axisKey); } // ________________________________________________________________________ protected AxisInterval getInterval(Object key, DrawingState drawing, Object axisKey) { for (Iterator iter = drawing.parts(); iter.hasNext();) { DrawingPart part = (DrawingPart) iter.next(); if (part.isSummaryPart()) continue; AxisInterval[] interval = part.getInterval(key, new AxisInterval[] {}); int index = part.keys().indexOf(axisKey); if (index < 0) continue; if (interval != null && index < interval.length && interval[index] != null) return interval[index]; } return null; } }
gpl-3.0
Lizzaran/LeagueSharp-Standalones
SFXUtility/SFXTurnAround/Library/Extensions/NET/ListExtensions.cs
3529
#region License /* Copyright 2014 - 2015 Nikita Bernthaler ListExtensions.cs is part of SFXLibrary. SFXLibrary 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. SFXLibrary 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 SFXLibrary. If not, see <http://www.gnu.org/licenses/>. */ #endregion License #region using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; #endregion namespace SFXTurnAround.Library.Extensions.NET { public static class ListExtensions { public static IEnumerable<T> Randomize<T>(this IEnumerable<T> target) { var r = new Random(); return target.OrderBy(x => r.Next()); } public static T DeepClone<T>(this T input) where T : ISerializable { using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); try { formatter.Serialize(stream, input); stream.Position = 0; return (T) formatter.Deserialize(stream); } catch { return default(T); } } } public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return source.DistinctBy(keySelector, null); } /// <exception cref="ArgumentNullException"><paramref name="source" /> is <see langword="null" />.</exception> public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) { if (source == null) { throw new ArgumentNullException("source"); } if (keySelector == null) { throw new ArgumentNullException("keySelector"); } return DistinctByImpl(source, keySelector, comparer); } private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) { var knownKeys = new HashSet<TKey>(comparer); return source.Where(element => knownKeys.Add(keySelector(element))); } private static IEnumerable<int> ConstructSetFromBits(int i) { for (var n = 0; i != 0; i /= 2, n++) { if ((i & 1) != 0) { yield return n; } } } public static IEnumerable<List<T>> ProduceEnumeration<T>(List<T> list) { for (var i = 0; i < 1 << list.Count; i++) { yield return ConstructSetFromBits(i).Select(n => list[n]).ToList(); } } } }
gpl-3.0
parogers/junker
src/sprites/bomb.js
2581
/* JUNKER - Arcade tank shooter written in Javascript using HTML5 * Copyright (C) 2015 Peter Rogers (peter.rogers@gmail.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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/>. * * See LICENSE.txt for the full text of the license. */ /* bomb.js */ function Bomb(x, y, targetX, targetY) { /* Constructor */ Sprite.call(this); this.x = x; this.y = y; this.startx = x; this.starty = y; this.speed = 300; this.targetX = targetX; this.targetY = targetY; this.frame = 0; this.time = 0; this.frames = []; var dist = Math.sqrt(Math.pow(x - targetX, 2) + Math.pow(y - targetY, 2)); this.duration = dist / 200.0; } Bomb.prototype = new Sprite; Bomb.prototype.spawn = function(level) { this.frames = [ resources.images.bomb1, resources.images.bomb2, resources.images.bomb3, resources.images.bomb3, resources.images.bomb2, resources.images.bomb2, resources.images.bomb1, resources.images.bomb1, ]; this.set_image(this.frames[0]); this.level = level; this.level.airSprites.add(this); } Bomb.prototype.update = function(dt) { this.time += dt; if (this.time > this.duration) { /* The bomb explodes */ //resources.explodeAudio.play(); var exp = new MultiExplosion(this.x, this.y, 50, 2); exp.spawn(this.level); this.level.remove_sprite(this); return; } /* Shows the bomb getting bigger, then smaller as it approaches the * target. */ var n = Math.round((this.time / this.duration) * (this.frames.length-1)); this.set_image(this.frames[n]); /* Update the bomb position */ var tm = Math.sin(Math.PI * (this.time/this.duration)/2); //tm = Math.pow(tm, 0.7); this.x = this.startx + tm * (this.targetX - this.startx); this.y = this.starty + tm * (this.targetY - this.starty); /* Remove the shot when it's no longer on screen */ if (!this.level.check_pos_visible(this.x, this.y)) { this.level.remove_sprite(this); } }
gpl-3.0
firestarter/firestarter
redist/mirror-lib/lagoon/auxiliary/specifier_getter.hpp
1938
/** * .file lagoon/auxiliary/specifier_getter.hpp * .brief Implementation of an internal helper function for * creating instances of specifier implementations * * Copyright 2008-2011 Matus Chochlik. 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) */ #ifndef LAGOON_AUX_SPECIFIER_GETTER_1011291729_HPP #define LAGOON_AUX_SPECIFIER_GETTER_1011291729_HPP #include <lagoon/specifiers.hpp> #include <lagoon/utils.hpp> #include <mirror/specifier_tags.hpp> LAGOON_NAMESPACE_BEGIN namespace aux { // Function creating inheritance type specifiers template <typename Specifier, typename Interface> inline shared<Interface> get_inheritance_type_spec(void) { Specifier _spec; static inheritance_type_specifier spec(_spec); return shared<Interface>(&spec); } // Function creating access type specifiers template <typename Specifier, typename Interface> inline shared<Interface> get_access_type_spec(void) { Specifier _spec; static access_type_specifier spec(_spec); return shared<Interface>(&spec); } // Function creating elaborated type specifiers template <typename Specifier, typename Interface> inline shared<Interface> get_elaborated_type_spec(void) { Specifier _spec; static elaborated_type_specifier spec(_spec); return shared<Interface>(&spec); } // Function creating storage class specifiers template <typename Specifier, typename Interface> inline shared<Interface> get_storage_class_spec(void) { Specifier _spec; static storage_class_specifier spec(_spec); return shared<Interface>(&spec); } // Function creating storage class specifiers template <typename Specifier, typename Interface> inline shared<Interface> get_constness_spec(void) { Specifier _spec; static constness_specifier spec(_spec); return shared<Interface>(&spec); } } // namespace aux LAGOON_NAMESPACE_END #endif //include guard
gpl-3.0
piwik/piwik
plugins/CoreHome/DataTableRowAction/MultiRowEvolution.php
3326
<?php /** * Piwik - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * */ namespace Piwik\Plugins\CoreHome\DataTableRowAction; use Piwik\Common; use Piwik\Context; use Piwik\Piwik; /** * MULTI ROW EVOLUTION * The class handles the popover that shows the evolution of a multiple rows in a data table */ class MultiRowEvolution extends RowEvolution { /** The requested metric */ protected $metric; /** Show all metrics in the evolution graph when the popover opens */ protected $initiallyShowAllMetrics = true; /** The metrics available in the metrics select */ protected $metricsForSelect; /** * The constructor * @param int $idSite * @param \Piwik\Date $date ($this->date from controller) */ public function __construct($idSite, $date) { $this->metric = Common::getRequestVar('column', '', 'string'); parent::__construct($idSite, $date); } protected function loadEvolutionReport($column = false) { // set the "column" parameter for the API.getRowEvolution call parent::loadEvolutionReport($this->metric); } protected function extractEvolutionReport($report) { $this->metric = $report['column']; $this->dataTable = $report['reportData']; $this->availableMetrics = $report['metadata']['metrics']; $this->metricsForSelect = $report['metadata']['columns']; $this->dimension = $report['metadata']['dimension']; } /** * Render the popover * @param \Piwik\Plugins\CoreHome\Controller $controller * @param View (the popover_rowevolution template) */ public function renderPopover($controller, $view) { // add data for metric select box $view->availableMetrics = $this->metricsForSelect; $view->selectedMetric = $this->metric; $view->availableRecordsText = $this->dimension . ': ' . Piwik::translate('RowEvolution_ComparingRecords', array(count($this->availableMetrics))); return parent::renderPopover($controller, $view); } protected function getRowEvolutionGraphFromController(\Piwik\Plugins\CoreHome\Controller $controller) { // the row evolution graphs should not compare serieses return Context::executeWithQueryParameters(['compareSegments' => [], 'comparePeriods' => [], 'compareDates' => []], function () use ($controller) { return parent::getRowEvolutionGraphFromController($controller); }); } public function getRowEvolutionGraph($graphType = false, $metrics = false) { // the row evolution graphs should not compare serieses return Context::executeWithQueryParameters(['compareSegments' => [], 'comparePeriods' => [], 'compareDates' => []], function () use ($graphType, $metrics) { return parent::getRowEvolutionGraph($graphType, $metrics); }); } protected function getSparkline($metric) { // the row evolution graphs should not compare serieses return Context::executeWithQueryParameters(['compareSegments' => [], 'comparePeriods' => [], 'compareDates' => []], function () use ($metric) { return parent::getSparkline($metric); }); } }
gpl-3.0
insomynwa/wp-content
themes/gon-cakeshop/woocommerce/single-product/title.php
327
<?php /** * Single Product title * * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } ?> <?php $gon_options = gon_get_global_variables(); ?> <h1 itemprop="name" class="product_title entry-title"> <?php the_title(); ?> </h1>
gpl-3.0
devbridge/BetterCMS
Modules/BetterCms.Module.Root/Models/ContentRegion.cs
2107
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ContentRegion.cs" company="Devbridge Group LLC"> // // Copyright (C) 2015,2016 Devbridge Group LLC // // 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 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 Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> // // <summary> // Better CMS is a publishing focused and developer friendly .NET open source CMS. // // Website: https://www.bettercms.com // GitHub: https://github.com/devbridge/bettercms // Email: info@bettercms.com // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using BetterCms.Core.DataContracts; using BetterModules.Core.Models; namespace BetterCms.Module.Root.Models { [Serializable] public class ContentRegion : EquatableEntity<ContentRegion>, IContentRegion { public virtual Content Content { get; set; } public virtual Region Region { get; set; } IDynamicContentContainer IContentRegion.Content { get { return (IDynamicContentContainer)Content; } set { Content = (Content)value; } } IRegion IContentRegion.Region { get { return Region; } set { Region = (Region)value; } } } }
gpl-3.0
dsilva609/Project-Cinderella
BusinessLogic/Migrations/201609010023336_removed type from tracklist.Designer.cs
860
// <auto-generated /> namespace BusinessLogic.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class removedtypefromtracklist : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(removedtypefromtracklist)); string IMigrationMetadata.Id { get { return "201609010023336_removed type from tracklist"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
gpl-3.0
hakan648/Gap
Project/Gap.Win/Form1.cs
9180
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Gap.Win { using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms.VisualStyles; using Gap.Network; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //Test Chat //lbOnlineUsers.Items.Add("Hakan"); } protected override void OnClosing(CancelEventArgs e) { this.Logout(); } private Socket _transmitterSocket; private void btnConnect_Click(object sender, EventArgs e) { //var clientThread = new Thread(StartClient); //clientThread.Name = "Client_clientThread"; //clientThread.IsBackground = true; //clientThread.Start(); Task.Run(() => StartClient()); } private void StartClient() { var name = txtUsername.Text; this._transmitterSocket = Connect(); this.receiverSocket = InitialReceiverSocket(); int receiverPort = ((IPEndPoint)receiverSocket.LocalEndPoint).Port; //var notifyThread = new Thread(this.HandleServerNotifies); //notifyThread.Name = "Client_notifyThread"; //notifyThread.IsBackground = true; //notifyThread.Start(); Task.Run(() => HandleServerNotifies()); IntroReceiverPort(receiverPort); Login(name); UpdateOnlineUsers(); } private void btnDisconnect_Click(object sender, EventArgs e) { this.Logout(); lbLogs.Items.Clear(); lbOnlineUsers.Items.Clear(); } private void UpdateOnlineUsers() { var onlineUsers = GetOnlineUsers(); this.DisplayOnlineUsers(onlineUsers); } private void DisplayOnlineUsers(string[] onlineUsers) { if (lbOnlineUsers.InvokeRequired) { lbOnlineUsers.Invoke(new MethodInvoker(() => this.DisplayOnlineUsers(onlineUsers))); return; } lbOnlineUsers.Items.Clear(); foreach (var onlineUserName in onlineUsers) { this.lbOnlineUsers.Items.Add(onlineUserName); } //this.AddLog("New user loggedin:"); //foreach (var onlineUserName in onlineUsers) //{ // this.AddLog(onlineUserName); //} } private static Socket Connect() { TcpClient tcpClient = new TcpClient(); Configuration configuration = Configuration.Load(); tcpClient.Connect(configuration.ServerAddress, configuration.ServerPort); return tcpClient.Client; } private string[] GetOnlineUsers() { return this.SendRequest("getOnlineUsers").Parameters; } private void Login(string name) { this.SendRequest("login", name); } private void Logout() { if (this._transmitterSocket != null && this._transmitterSocket.Connected) { Task.Run(() => { this.SendRequest("logout"); this.CloseSockets(); }); } } private void CloseSockets() { //this.transmitterSocket.Shutdown(SocketShutdown.Both); //this.transmitterSocket.Disconnect(false); //this._transmitterSocket.Dispose(); } private Gap.Network.Message SendRequest(string requestName, string parameter) { var requestMessage = new Gap.Network.Message { Name = requestName, Parameters = new string[] { parameter } }; return SendRequest(requestMessage); } private Gap.Network.Message SendRequest(string requestName) { var requestMessage = new Gap.Network.Message { Name = requestName }; return SendRequest(requestMessage); } private Gap.Network.Message SendRequest(Gap.Network.Message requestMessage) { Gap.Network.Message.Send(_transmitterSocket, requestMessage); return Gap.Network.Message.Receive(_transmitterSocket); } public void SendMessage(string toUsername, string message) { var requestMessage = new Gap.Network.Message { Name = "message", Parameters = new string[] { toUsername, message } }; SendRequest(requestMessage); } //Notify private Socket receiverSocket; private Socket serverTransmitterSocket; private static Socket InitialReceiverSocket() { TcpListener clienTcpListener = new TcpListener(IPAddress.Any, 0); clienTcpListener.Start(1); return clienTcpListener.Server; } private void HandleServerNotifies() { this.serverTransmitterSocket = this.receiverSocket.Accept(); string notifyName; do { notifyName = this.ProcessNotify(); } while (notifyName != "bye"); //this.serverTransmitterSocket.Shutdown(SocketShutdown.Both); this.serverTransmitterSocket.Close(); //this.receiverSocket.Shutdown(SocketShutdown.Both); this.receiverSocket.Close(); } public string ProcessNotify() { var responseMessage = Gap.Network.Message.Receive(serverTransmitterSocket); switch (responseMessage.Name) { case "debug": AddLog(string.Format("Server has sent a debug message: {0}", responseMessage.Parameters[0])); break; case "bye": AddLog("Server wants to finish this session"); break; case "getOnlineUsers": this.DisplayOnlineUsers(responseMessage.Parameters); break; case "message": this.Invoke( new Action( () => SendMessageToForm(responseMessage.Parameters[0], responseMessage.Parameters[1]))); break; //case "logout": // this.Logout(); // break; //case "IntroReceiverPort": // int clientReceiverPort = int.Parse(notifyParameter); // ConnectToClient(clientReceiverPort); // break; } Gap.Network.Message.Send(serverTransmitterSocket, "OK"); return responseMessage.Name; } private void IntroReceiverPort(int receiverPort) { this.SendRequest("IntroReceiverPort", receiverPort.ToString()); } private void AddLog(string log) { //Console.WriteLine(log); if (lbLogs.InvokeRequired) { lbLogs.Invoke(new MethodInvoker(() => this.AddLog(log))); } else { lbLogs.Items.Add(log); } } //Chat form List<ChatForm> chatForms = new List<ChatForm>(); private void lbOnlineUsers_MouseDoubleClick(object sender, MouseEventArgs e) { if (lbOnlineUsers.SelectedItem == null) return; string username = lbOnlineUsers.SelectedItem.ToString(); ShowChatForm(username); } private void SendMessageToForm(string senderUsername, string message) { var chatForm = this.ShowChatForm(senderUsername); chatForm.AddMessage(senderUsername, message); } private ChatForm ShowChatForm(string senderUsername) { ChatForm chatForm = chatForms.FirstOrDefault(x => x.Text == senderUsername); if (chatForm != null) { chatForm.Focus(); } else { chatForm = new ChatForm(); chatForms.Add(chatForm); chatForm.Text = senderUsername; chatForm.MainForm = this; chatForm.OwnerUsername = txtUsername.Text; chatForm.StartPosition = FormStartPosition.Manual; chatForm.Location = new Point(this.Location.X, this.Location.Y + this.Size.Height / 2); chatForm.Show(); } return chatForm; } } }
gpl-3.0
isnuryusuf/ingress-indonesia-dev
apk/classes-ekstartk/com/nianticproject/ingress/common/b/f.java
755
package com.nianticproject.ingress.common.b; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureAtlas.TextureAtlasData; import com.nianticproject.ingress.common.x.p; final class f implements com.nianticproject.ingress.common.x.f { f(TextureAtlas.TextureAtlasData paramTextureAtlasData, o paramo, String paramString) { } public final com.nianticproject.ingress.common.x.f a(p paramp) { TextureAtlas localTextureAtlas = new TextureAtlas(this.a); this.b.a(localTextureAtlas); return null; } public final String n_() { return this.c; } } /* Location: classes_dex2jar.jar * Qualified Name: com.nianticproject.ingress.common.b.f * JD-Core Version: 0.6.2 */
gpl-3.0
exequielrafaela/proton
modules/aws_fab.py
2515
# aws cloudtrail lookup-events --lookup-attributes AttributeKey=Username,AttributeValue=matias.desanti # > /home/delivery/Programming/proton/conf/AWS/cloudtrail_lookup-events.json # aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AuthorizeSecurityGroupIngress # > /home/delivery/Programming/proton/conf/AWS/cloudtrail_lookup-event-by-event # $ aws cloudtrail lookup-events --start-time 2017-03-08T20:40:00.000Z --end-time 2017-03-08T21:20:00.000Z # --lookup-attributes AttributeKey=EventName,AttributeValue=AuthorizeSecurityGroupIngress # > /home/delivery/Programming/proton/conf/AWS/cloudtrail_lookup-event-by-event-with-time.json # aws ec2 describe-instances > /home/delivery/Programming/proton/conf/AWS/ec2-instance-details.json import os import pwd from fabric.api import settings, env, sudo, local # from fabric.contrib.files import exists, append from fabric.decorators import task # from fabric.tasks import Task from termcolor import colored import json @task def sec_grup_per_ec2(sgid='sg-'): """ Method to obaint all de EC2s associated to a certain AWS Security Group Remember that this task it's intended to be run with role "local" :param sgid: AWS security group ID """ # global user_exists with settings(warn_only=False): try: with open('./conf/AWS/ec2-instance-details.json') as json_data: json_raw = json.load(json_data) # print(json_raw) #for key, value in json_raw.items(): #print key, value print json_raw["Reservations"][0]["Instances"][0]["SecurityGroups"][0]["GroupId"] print json_raw["Reservations"][0]["Instances"][0]["SecurityGroups"][1]["GroupId"] print json_raw["Reservations"][1]["Instances"][0]["SecurityGroups"][0]["GroupId"] # print json_raw["Reservations"][1]["Instances"][0]["SecurityGroups"][1]["GroupId"] => Since this # has only 1 Sec group then this line will result in "IndexError: list index out of range" # sg_item = [item for item in json_raw["Reservations"] # if item["Instances"][0]["SecurityGroups"][0]["GroupId"] == sgid] # print sg_item except KeyError: print colored('################################', 'red') print colored('User ' + sgid + 'does not exists', 'red') print colored('################################', 'red')
gpl-3.0
mattnye/sparkler
searchform.php
426
<?php /** * Search form markup * * @package WordPress * @subpackage Sparkler * @since Sparkler 1.0 */ ?> <form action="<?php echo esc_url(home_url('/')); ?>" method="get" class="form-search"> <div class="rel icon icon-magnifying-glass"> <input type="text" id="s" name="s" placeholder="Search" /> <input type="submit" value="<?php esc_attr_e('Search', 'sparkler'); ?>" /> </div><!--rel--> </form>
gpl-3.0
pressbooks/pressbooks
inc/covergenerator/class-isbn.php
6141
<?php namespace Pressbooks\Covergenerator; use function Pressbooks\Utility\debug_error_log; /** * @see https://github.com/bwipp/postscriptbarcode/wiki/ISBN */ class Isbn { /** * @var string */ protected $isbnNumber; /** * @var string */ protected $isbnTextFont = 'Courier'; /** * @var int */ protected $isbnTextSize = 9; /** * @var string */ protected $textFont = 'Helvetica'; /** * @var int */ protected $textSize = 12; /** * @var int */ protected $dpi = 300; /** * Constructor */ function __construct() { } /** * Create an ISBN png and sideload it into WordPress * * @param string $isbn_number * * @throws \Exception * * @return string */ public function createBarcode( $isbn_number ) { if ( ! $this->validateIsbnNumber( $isbn_number ) ) { \Pressbooks\add_error( __( 'There was a problem creating the barcode: Invalid ISBN number.', 'pressbooks' ) ); return false; } $this->isbnNumber = $this->fixIsbnNumber( $isbn_number ); $ps = \Pressbooks\Utility\create_tmp_file(); $png = \Pressbooks\Utility\create_tmp_file(); $this->compile( $ps ); $this->gs( $ps, $png, $this->dpi ); $this->crop( $png ); $old_id = \Pressbooks\Image\attachment_id_from_url( get_option( 'pressbooks_cg_isbn' ) ); if ( $old_id ) { wp_delete_attachment( $old_id, true ); } if ( ! function_exists( 'media_handle_sideload' ) ) { require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/file.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); } $pid = media_handle_sideload( [ 'name' => "{$this->isbnNumber}.png", 'tmp_name' => $png, ], 0 ); if ( is_wp_error( $pid ) ) { throw new \Exception( $pid->get_error_message() ); } $src = wp_get_attachment_url( $pid ); if ( false === $src ) { throw new \Exception( 'No attachment url.' ); } update_option( 'pressbooks_cg_isbn', $src ); return $src; } /** * Validate an ISBN string * * @param $isbn_number * * @return bool */ public function validateIsbnNumber( $isbn_number ) { // Regex to split a string only by the last whitespace character @list( $isbn_number, $addon ) = preg_split( '/\s+(?=\S*+$)/', trim( $isbn_number ) ); // @codingStandardsIgnoreLine $is_valid_isbn = ( new \Isbn\Isbn() )->validation->isbn( $isbn_number ); $is_valid_addon = true; if ( $addon ) { if ( ! preg_match( '/^([0-9]{2}|[0-9]{5})$/', $addon ) ) { $is_valid_addon = false; } } return $is_valid_isbn && $is_valid_addon; } /** * Fix an ISBN string * * @param $isbn_number * * @return string */ public function fixIsbnNumber( $isbn_number ) { // Regex to split a string only by the last whitespace character @list( $isbn_number, $addon ) = preg_split( '/\s+(?=\S*+$)/', trim( $isbn_number ) ); // @codingStandardsIgnoreLine $isbn_number = ( new \Isbn\Isbn() )->hyphens->fixHyphens( $isbn_number ); if ( $addon ) { $isbn_number .= " $addon"; } return $isbn_number; } /** * ISBN Invocation Code. * * @see https://github.com/bwipp/postscriptbarcode/wiki/ISBN * @see https://github.com/bwipp/postscriptbarcode/wiki/Symbol-Dimensions * @see https://github.com/bwipp/postscriptbarcode/wiki/Text-Properties * * @param string $isbn * @param string $isbn_text_font * @param float $isbn_text_size * @param string $text_font * @param float $text_size * * @return string */ public function invocation( $isbn, $isbn_text_font, $isbn_text_size, $text_font, $text_size ) { $ps[] = "50 50 moveto ({$isbn}) (includetext isbntextfont={$isbn_text_font} isbntextsize={$isbn_text_size} textfont={$text_font} textsize={$text_size})"; $ps[] = '/isbn /uk.co.terryburton.bwipp findresource exec'; return implode( "\n", $ps ) . "\n"; } /** * Compile an ISBN Postscript file * * @param string $path_to_ps * * @throws \LogicException */ public function compile( $path_to_ps ) { if ( empty( $this->isbnNumber ) ) { throw new \LogicException( '$this->isbnNumber is not set' ); } $isbn = \Pressbooks\Utility\get_contents( PB_PLUGIN_DIR . 'symbionts/postscriptbarcode/isbn.ps' ); $invocation = $this->invocation( $this->isbnNumber, $this->isbnTextFont, $this->isbnTextSize, $this->textFont, $this->textSize ); // @codingStandardsIgnoreStart file_put_contents( $path_to_ps, $isbn ); file_put_contents( $path_to_ps, $invocation, FILE_APPEND | LOCK_EX ); file_put_contents( $path_to_ps, ( "\n" . 'showpage' ), FILE_APPEND | LOCK_EX ); // @codingStandardsIgnoreEnd } /** * Use Ghostscript to convert a PostScript file into a grayscale PNG file * * @param string $input_path_to_ps * @param string $output_path_to_png * @param int $dpi */ public function gs( $input_path_to_ps, $output_path_to_png, $dpi ) { $dpi = (int) $dpi; $command = PB_GS_COMMAND . " -dQUIET -dNOPAUSE -dSAFER -dBATCH -sDEVICE=pnggray -r{$dpi} -sOutputFile=" . escapeshellarg( $output_path_to_png ) . ' ' . escapeshellarg( $input_path_to_ps ); // Execute command $output = []; $return_var = 0; exec( $command, $output, $return_var ); // @codingStandardsIgnoreLine if ( ! empty( $output ) ) { // @codingStandardsIgnoreStart debug_error_log( $command ); debug_error_log( print_r( $output, true ) ); // @codingStandardsIgnoreEnd } } /** * Use ImageMagick to automatically crop & pad a PNG file with a white border * * @param string $path_to_png * @param string $border */ public function crop( $path_to_png, $border = '20x20' ) { $border = escapeshellarg( $border ); $command = PB_CONVERT_COMMAND . ' ' . escapeshellarg( $path_to_png ) . " -trim +repage -bordercolor white -border {$border} " . escapeshellarg( $path_to_png ); // Execute command $output = []; $return_var = 0; exec( $command, $output, $return_var ); // @codingStandardsIgnoreLine if ( ! empty( $output ) ) { // @codingStandardsIgnoreStart debug_error_log( $command ); debug_error_log( print_r( $output, true ) ); // @codingStandardsIgnoreEnd } } }
gpl-3.0
wandora-team/wandora
resources/server/d3/browser/static/js/main.js
12149
(function() { 'use strict'; var tm, svg, zoomWrapper, force, linkAll, linkEnter, nodeAll, nodeEnter, pseudoAll, pseudoEnter; var myAddress = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: ''); /** * Global config * @type {Object} */ var conf = { debug: false, //log stuff? serviceAddr: myAddress+'/jtm/', //wheres data? //#SVG size w: 900, h: 900, gw: 800, gh: 800, // Force layout conf linkDistance: 200, nodeSize: 20, strength: 1, charge: -200, // Label element conf rw: 200, rh: 20, labelLength: 23, // Special association and player types for type-instance associations typeInstance: "si:http://psi.topicmaps.org/iso13250/model/type-instance", type: "si:http://psi.topicmaps.org/iso13250/model/type", instance: "si:http://psi.topicmaps.org/iso13250/model/instance", // Colors for Nodes and links cols: d3.scale.category20(), assocCols: d3.scale.category20b() }; /** * Basic console.log wrapper * @param {Object} o Object to be logged. Note special handling for groups. */ var log = function(o) { if (!conf.debug || !console) return; if (o instanceof Group && console.group) { console.group(o.g); for (var i = 0; i < o.a.length; i++) { log(o.a[i]); } console.groupEnd(); } else { console.log(o); } }; /** * The Group class used for logging * @param {String} g Group description * @param {Array of objects} a An array of objects to log */ var Group = function(g, a) { this.g = g; this.a = a; }; /** * The Node class used to represent topics in the graph * @param {String} si The SI of the topic * @param {String} name The name to be displayed */ var Node = function(si, name) { this.si = si; this.name = name; }; /** * The PseudoNode class used to glue associations with more than two players * together. */ var PseudoNode = function() {}; /** * The TopicMap wrapper class used to hold the response data from the server. * @param {Object} data The response from the server. */ var TopicMap = function(data) { this.as = data.associations; this.topics = data.topics; this.version = data.version; this.initNodes(); this.initLinks(); }; /** * Basic getter * @return {Array of objects} All the topics in the TopicMap */ TopicMap.prototype.getTopics = function() { return this.topics; }; /** * Basic getter * @return {Array of objects} All the associations in the TopicMap */ TopicMap.prototype.getAssociations = function() { return this.associations; }; /** * Get the topic with the subject identifier si * @param {String} si The subject identifier * @return {Object} The topic with the identifier si */ TopicMap.prototype.getTopic = function(si) { var t, sis; for (var i = 0; i < this.topics.length; i++) { t = this.topics[i]; sis = t.subject_identifiers; if (sis.indexOf(si) != -1) return t; } }; /** * Get the Node with the subject identifier si * @param {String} si The subject identifier * @return {Node} The node with the identifier si */ TopicMap.prototype.getNode = function(si) { for (var i = this.nodes.length - 1; i >= 0; i--) { if (this.nodes[i].si == si) return this.nodes[i]; } }; /** * Create Nodes from the topics in the TopicMap */ TopicMap.prototype.initNodes = function() { this.nodes = []; for (var i = this.topics.length - 1; i >= 0; i--) { var si = this.topics[i].subject_identifiers[0], name = this.topics[i].names[0].value; this.nodes.push(new Node(si, name)); } }; /** * Create links from the associations in the TopicMap. Also create * PseudoNodes if we need them and creates indices for topic and association * types. */ TopicMap.prototype.initLinks = function() { /** * Simple helper to see if an two player association (pair) is already * added. * @param {Array of pairs} arr The array against which to check * @param {String} s1 The first element of the pair * @param {String} s2 The second element of the pair * @return {Boolean} True if the array already has the pair */ function arrayHasPair(arr, s1, s2) { for (var i = arr.length - 1; i >= 0; i--) { var ap = arr[i].sort(), p = [s1, s2].sort(); if (ap[0] == p[0] && ap[1] == p[1]) return true; } return false; } this.links = []; this.pseudoNodes = []; this.types = []; this.assocTypes = []; var pairs = []; var a, s1, s2, t1, t2; var i, j, k; /* Iterate over all the associations in the TopicMap */ for (i = this.as.length - 1; i >= 0; i--) { a = this.as[i]; /* Update the association type array */ if (this.assocTypes.indexOf(a.type)) this.assocTypes.push(a.type); /* Special case: type-instance associations are used to define types for topics so we use them to define topic types. */ if (a.type == conf.typeInstance) { var ins, type; for (j = 0; j < a.roles.length; j++) { if (a.roles[j].type == conf.type) type = a.roles[j].player; else if (a.roles[j].type == conf.instance) ins = a.roles[j].player; } if (ins.search("si:") !== 0) break; ins = ins.slice(3); if (type.search("si:") !== 0) break; type = type.slice(3); var t = this.getNode(ins); t.type = type; if (this.types.indexOf(type) == -1) this.types.push(type); /* The usual case: association has two players and is represented with a single link. */ } else if (a.roles.length > 2) { var pn = new PseudoNode(); pn.type = a.type; this.pseudoNodes.push(pn); for (k = a.roles.length - 1; k >= 0; k--) { s1 = a.roles[k].player; if (s1.search("si:") !== 0) break; s1 = s1.slice(3); var p = this.getNode(s1); this.links.push({ source: pn, target: p, type: a.type }); } /* Special case: more than two players. Here we need to add a PseudoNode to which all the players are connected to. */ } else if (a.roles.length == 2) { for (j = a.roles.length - 1; j >= 0; j--) { s1 = a.roles[0].player; if (s1.search("si:") !== 0) break; s1 = s1.slice(3); s2 = a.roles[1].player; if (s2.search("si:") !== 0) break; s2 = s2.slice(3); if (s1 != s2 && !arrayHasPair(pairs, s1, s2)) { pairs.push([s1, s2]); this.links.push({ type: a.type, source: this.getNode(s1), target: this.getNode(s2) }); } } } } }; /** * Event listener for the 'tick' event from the force layout. Updates the node * and link coordinates according to the coordinates from the layout. */ function tick() { linkAll.attr({ "x1": function(d) { return d.source.x; }, "y1": function(d) { return d.source.y; }, "x2": function(d) { return d.target.x; }, "y2": function(d) { return d.target.y; } }); nodeAll.attr("transform", function(d) { return "translate(" + d.x + ", " + d.y + ")"; }); pseudoAll.attr("transform", function(d) { return "translate(" + d.x + ", " + d.y + ")"; }); } /** * Initialize the graph element in the DOM. Also declare zoom behavior for the * zoomWrapper inside the SVG element and initialize the force layout. */ function initGraph() { svg = d3.select("#svg") .attr({ width: conf.w, height: conf.h, }).call(d3.behavior.zoom().on("zoom", zoom)); zoomWrapper = svg.append("g"); force = d3.layout.force() .size([conf.gw, conf.gh]) .linkDistance(conf.linkDistance) .charge(conf.charge) .nodes(tm.nodes.concat(tm.pseudoNodes)) .links(tm.links); } /** * Event listener for clicking on Nodes. Update the location hash with the SI * from the clicked Node. * @param {Node} d The datum Node from the clicked element */ function onNodeClick(d) { //http://github.com/mbostock/d3/pull/1341 if (!d3.event.defaultPrevented) { if (!d.si) return; var si = d.si; location.hash = si; // triggers hashchange } } /** * Event listener: add hover class to nodes on mouseover * @param {Node} d The datum Node of the mouseovered element */ function onNodeMouseover(d) { /*jshint validthis:true */ d3.select(this).classed("hover", true); } /** * Event listener: remove hover class from nodes on mouseout * @param {Node} d The datum Node of the mouseouted (?) element */ function onNodeMouseout(d) { /*jshint validthis:true */ d3.select(this).classed("hover", false); } /** * Event listener: update the zoom scale and translation of the .zoomWrapper on * 'zoom' event on #SVG */ function zoom() { var t = d3.event.translate, s = d3.event.scale; zoomWrapper.attr("transform", "translate(" + t + ")scale(" + s + ")"); } /** * Bind data to selections and add / remove nodes and links in the graph. */ function draw() { /* Bind tick and (re)start the force layout */ force.on("tick", tick).start(); /* Bind data */ linkAll = zoomWrapper.selectAll(".link") .data(tm.links); nodeAll = zoomWrapper.selectAll(".node") .data(tm.nodes); pseudoAll = zoomWrapper.selectAll(".pseudo") .data(tm.pseudoNodes); log(new Group('enter node data', [nodeAll.enter()])); /* Add new Nodes */ nodeEnter = nodeAll.enter().append("g") .classed("node", true) .attr("data-id", function(d) { return d.si; }) .on("mouseover", onNodeMouseover) .on("mouseout", onNodeMouseout) .on('touchstart', function(d) { d3.event.preventDefault(); // no scrolling }) .on('click', onNodeClick) .call(force.drag); nodeEnter.append("rect") .attr({ x: '-' + (conf.rw / 2) + 'px', y: '-' + (4 + conf.rh / 2) + 'px', width: conf.rw + 'px', height: conf.rh + 'px', fill: function(d) { var i = tm.types.indexOf(d.type); if (i > -1) return conf.cols(i); return "#999"; } }); nodeEnter.append("text") .text(function(d) { if (d.name) return (d.name.length > conf.labelLength) ? d.name.substring(0, conf.labelLength - 3) + "..." : d.name; return ""; }); log(new Group('exit node data', [nodeAll.exit()])); /* Remove old Nodes */ nodeAll.exit().remove(); /* Add new PseudoNodes */ pseudoEnter = pseudoAll.enter().insert("g", ".node") .classed("pseudo", true); pseudoEnter.append("circle") .attr({ r: 5, fill: function(d) { var i = tm.assocTypes.indexOf(d.type); return conf.assocCols(i); } }); /* Remove old PseudoNodes */ pseudoAll.exit().remove(); log(new Group('enter link data', [linkAll.enter()])); var enter = linkAll.enter(); /* Add new links */ linkEnter = linkAll.enter().insert("line", ".node") .classed("link", true) .attr('stroke', function(d) { var i = tm.assocTypes.indexOf(d.type); return conf.assocCols(i); }); log(new Group('exit link data', [linkAll.exit()])); /* Remove old links */ linkAll.exit().remove(); } /** * Loads the JTM data from u. Usually called on hashchange * @param {String} u The URL for the JTM resource provided by the JTM service module. */ function loadData(u) { d3.json(u, function(err, data) { if (typeof(data) != "undefined" && data.item_type == "topicmap") { tm = new TopicMap(data); force.nodes(tm.nodes.concat(tm.pseudoNodes)); force.links(tm.links); draw(); } }); } /* Construct the URL for the first fetch */ var u = conf.serviceAddr; if (location.hash.length > 2) u += "?topic=" + location.hash.slice(1); /* On with the circus! Fetch data from u and start initializing stuff. */ d3.json(u, function(err, data) { var desc = d3.select('.description'); d3.select('.info-toggle').on('click',function(){ var isVisible = desc.classed('visible'); desc.classed('visible',!isVisible); d3.select(this).classed('on',!isVisible); }); /* All's fine? d3.json sets data to undefined on error. */ if (typeof(data) != "undefined" && data.item_type == "topicmap") { /** * Yup! */ d3.select(".error").remove(); tm = new TopicMap(data); initGraph(); draw(); window.onhashchange = function() { var si = location.hash.slice(1), u = conf.serviceAddr + "?topic=" + encodeURIComponent(si); loadData(u); }; } else { /** * Nope! Display the error in the main content span. */ log(err); d3.select("#mainContent").insert("div", "#chart") .classed("error", true) .html(err.response); } }); })();
gpl-3.0
freayd/qevel
translations/qevel_fr.ts
4068
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS><TS version="1.1" language="fr"> <context> <name>AboutDialog</name> <message> <location filename="../dialogs/about_dialog.ui" line="14"/> <source>About Qevel</source> <translation>À propos de Qevel</translation> </message> <message> <location filename="../dialogs/about_dialog.ui" line="53"/> <source>Close</source> <translation>Fermer</translation> </message> <message> <location filename="../dialogs/about_dialog.ui" line="33"/> <source>Show license</source> <translation>Afficher la licence</translation> </message> <message> <location filename="../sources/about_dialog.cpp" line="50"/> <source>GNU General Public License</source> <translation>Licence Publique Générale GNU</translation> </message> <message> <location filename="../sources/about_dialog.cpp" line="59"/> <source>A copy of the GNU General Public License can be found at &lt;a href=&quot;%1&quot;&gt;%1&lt;/a&gt;.</source> <translation>Une copie de la Licence Publique Générale GNU peut être trouvée à &lt;a href=&quot;%1&quot;&gt;%1&lt;/a&gt;.</translation> </message> <message> <location filename="../sources/about_dialog.cpp" line="96"/> <source>&lt;h2&gt;%1 %2&lt;/h2&gt;&lt;p&gt;%1 is a free cross-platform file manager.&lt;/p&gt;&lt;br/&gt;Copyright 2009 &lt;a href=&quot;%3&quot;&gt;%4&lt;/a&gt;&lt;p align=&quot;justify&quot;&gt;%1 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.&lt;/p&gt;&lt;p align=&quot;justify&quot;&gt;%1 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.&lt;/p&gt;</source> <translation>&lt;h2&gt;%1 %2&lt;/h2&gt;&lt;p&gt;%1 est un gestionnaire de fichiers multiplateforme gratuit.&lt;/p&gt;&lt;br/&gt;Copyright 2009 &lt;a href=&quot;%3&quot;&gt;%4&lt;/a&gt;&lt;p align=&quot;justify&quot;&gt;%1 est un logiciel libre ; vous pouvez le redistribuer et/ou le modifier suivant les termes de la Licence Publique Générale GNU, telle que publiée par la Free Software Foundation : soit la version 3 de la licence, soit (à votre gré) toute version ultérieure.&lt;/p&gt;&lt;p align=&quot;justify&quot;&gt;%1 est distribué dans l&apos;espoir qu&apos;il sera utile mais sans aucune garantie ; sans même la garantie implicite de commerciabilité ni de conformité à une utilisation particulière. Consultez la Licence Publique Générale GNU pour plus de détails.&lt;/p&gt;</translation> </message> </context> <context> <name>MainWindow</name> <message> <location filename="../dialogs/main_window.ui" line="25"/> <source>&amp;File</source> <translation>&amp;Fichier</translation> </message> <message> <location filename="../dialogs/main_window.ui" line="31"/> <source>&amp;Help</source> <translation>&amp;Aide</translation> </message> <message> <location filename="../dialogs/main_window.ui" line="41"/> <source>E&amp;xit</source> <translation>&amp;Quitter</translation> </message> <message> <location filename="../dialogs/main_window.ui" line="44"/> <source>Ctrl+Q</source> <translation>Ctrl+Q</translation> </message> <message> <location filename="../dialogs/main_window.ui" line="49"/> <source>About &amp;Qt...</source> <translation>À propos de &amp;Qt...</translation> </message> <message> <location filename="../dialogs/main_window.ui" line="54"/> <source>&amp;About Qevel...</source> <translation>À &amp;propos de Qevel...</translation> </message> </context> </TS>
gpl-3.0
gama-platform/gama
ummisco.gama.network/src/ummisco/gama/network/common/MessageFactory.java
3556
package ummisco.gama.network.common; import ummisco.gama.network.common.CommandMessage.CommandType; public final class MessageFactory { private static final byte[] keyChain = { 3, 5, 8, 13 }; private static final int MAX_HEADER_SIZE = 1024; public enum MessageType{ COMMAND_MESSAGE, NETWORK_MESSAGE, PLAIN_MESSAGE } public static NetworkMessage buildNetworkMessage(final String from, final String to, final String data) { return new NetworkMessage(from, to, data); } public static NetworkMessage buildNetworkMessage(final String from, final String data) { return new NetworkMessage(from, data); } public static CommandMessage buildCommandMessage(final String from, final String to,final CommandType cmd, final String data) { return new CommandMessage(from, to, cmd, data); } public static String packMessage(final NetworkMessage msg) { final String mKey = new String(keyChain); return mKey + msg.getSender() + mKey + msg.getReceiver() + mKey + msg.getPlainContents(); } public static String packMessage(final CommandMessage msg) { final String mKey = new String(keyChain); return mKey + mKey + msg.getSender() + mKey + msg.getReceiver() + mKey+ msg.getCommand().ordinal() + mKey + msg.getPlainContents(); } public static MessageType identifyMessageType(final String data) { final String key = new String(keyChain); if (data.substring(0, keyChain.length*2).equals(key+key)) return MessageType.COMMAND_MESSAGE; if (data.substring(0, keyChain.length).equals(key)) return MessageType.NETWORK_MESSAGE; return MessageType.PLAIN_MESSAGE; } public static NetworkMessage unPackNetworkMessage(final String reciever, final String data) { final String key = new String(keyChain); MessageType ctype = identifyMessageType(data); if (ctype == MessageType.COMMAND_MESSAGE) return null; if (ctype==MessageType.PLAIN_MESSAGE) return new NetworkMessage(reciever, data); final int size = MAX_HEADER_SIZE < data.length() ? MAX_HEADER_SIZE : data.length(); final String header = data.substring(0, size); final String headSplit[] = header.split(key); final String from = headSplit[1]; final String to = headSplit[2]; final String content = data.substring(from.length() + to.length() + 3 * key.length()); return new NetworkMessage(from, to, content); } public static CommandMessage unPackCommandMessage(final String sender, final String data) { final String key = new String(keyChain); if (identifyMessageType(data) != MessageType.COMMAND_MESSAGE) return null; final int size = MAX_HEADER_SIZE < data.length() ? MAX_HEADER_SIZE : data.length(); final String header = data.substring(0, size); final String headSplit[] = header.split(key); final String from = headSplit[2]; final String to = headSplit[3]; final int command = Integer.valueOf(headSplit[4]).intValue(); final String content = data.substring(from.length() + to.length()+headSplit[4].length() + 5 * key.length()); return new CommandMessage(from, to,CommandType.values()[command], content); } public static String unpackReceiverName(final String data) { final String key = new String(keyChain); String start =""; MessageType ctype = identifyMessageType(data); if(ctype == MessageType.COMMAND_MESSAGE) start = key + key; if (ctype == MessageType.NETWORK_MESSAGE) start = key ; if (ctype==MessageType.PLAIN_MESSAGE) return NetworkMessage.UNDEFINED; String sbcontent = data.substring(start.length()); return sbcontent.split(key)[1]; } }
gpl-3.0
denz/geophys
gnss/base.py
10422
import re from functools import wraps, partial import warnings from contextlib import contextmanager from mmap import mmap from itertools import takewhile import os from pprint import pprint from .logger import logger from .utils import slugify DATATYPES = {} QUIET_ON_CLEAN_VALUES = True class BlocksRegistry(type): def register_datatype(new): if not new.valid_filetype in DATATYPES: DATATYPES[new.valid_filetype] = new return new def __new__(cls, name, bases, members): new = type(name, bases, members) new.valid_filetype = classmethod(new.valid_filetype.__func__) return cls.register_datatype(new) class TextBlockDoesNotExists(Exception): pass class Blocks(object): coding = 'ascii' @classmethod def valid_filetype(cls, src): return False @classmethod def tokenize_filename(cls, filename, notation): return re.match(notation, filename) def textblock(self, name): if not hasattr(self, 'file'): self.file = open(self.src, 'r+b') if not hasattr(self, 'mmap'): self.mmap = mmap(self.file.fileno(), 0) #potential optimization point self.mmap.seek(0) name = bytes(name, 'ascii') startpos = self.mmap.find(b'+'+name) if startpos == -1: raise TextBlockDoesNotExists() self.mmap.seek(startpos) self.mmap.readline() self.line_num = 1 line = b'' while not line.startswith(b'-'+name): if line: yield line.decode(self.coding).strip('\n') line = self.mmap.readline() self.line_num += 1 def close(self): if hasattr(self, 'file'): self.file.close() if hasattr(self, 'mmap'): self.mmap.close() def __del__(self): self.close() def clean_meta_week(self, value): return int(value) clean_meta_hour = clean_meta_day = clean_meta_week def clean_meta_center(self, value): return value.upper() def clean_meta(self, name, value): custom_cleaner = getattr(self, 'clean_meta_%s'%slugify(name), None) return custom_cleaner(value) if custom_cleaner else value.strip() def setup_meta_from_filename(self): group = self.tokenize_filename(os.path.basename(self.src), self.notation).group self.meta = dict(zip(self.tokens, [self.clean_meta(token, group(token)) for token in self.tokens])) def __init__(self, src): self.src = src if hasattr(self, 'notation') and hasattr(self, 'tokens'): self.setup_meta_from_filename() @contextmanager def datafile(*args, **kwargs): for selector, cls in DATATYPES.items(): if selector(*args, **kwargs): yield cls(*args, **kwargs) return # logger.warn('Cannot find suitable datatype for `%s`. Base class used'%\ # (str(args)+' '+str(kwargs))) yield Blocks(*args, **kwargs) class BlockMixin(object): def __get__(self, instance, owner): if not instance: return self.__class__ if not hasattr(instance, self.name): setattr(instance, self.name, self.__class__(self.name, **self.kwargs)) getattr(instance, self.name).instance = instance return getattr(instance, self.name) def get_block(self, name): try: return self.instance.textblock(name) except TextBlockDoesNotExists as e: if self.kwargs.get('mandatory', True): raise non_transparsers = ('__getattribute__','clear', '__init__') def transparse(wrapped, parser): @wraps(wrapped) def wrapper(self, *args, **kwargs): if not hasattr(self, '_parsed'): parser.__get__(self, parser.__class__)() return wrapped.__get__(self, self.__class__)(*args, **kwargs) wrapper.transparsed = wrapped return wrapper def untransparse(instance, to): for method_name in dir(instance): method = getattr(instance, method_name) if callable(method) and hasattr(method, 'transparsed'): setattr(instance, method_name, method.transparsed.__get__(instance, to)) def setup_transparsers(locals, base, parser, exclude=non_transparsers): for method_name in dir(base): if not method_name in exclude: method = getattr(base, method_name) if callable(method) and getattr(method, '__objclass__', None) is base: locals[method_name] = transparse(method, parser) class DictBlock(dict, BlockMixin): key_column_len = 18 def item(self, line): return (line[:(self.key_column_len-1)].strip(), line[(self.key_column_len-1):].strip()) def parse(self): text = self.get_block(self.name) #untransparse before any actions untransparse(self, dict) self._parsed = True for line in text: self.__setitem__(*self.item(line.strip())) def __init__(self, name, **kwargs): self.name = name self.kwargs = kwargs dict.__init__.__get__(self, dict)() setup_transparsers(locals(), dict, parse) class TextBlock(str, BlockMixin): def parse(self): text = self.get_block(self.name) self = ''.join(text) #untransparse before any actions untransparse(self, dict) self._parsed = True def __init__(self, name, **kwargs): self.name = name self.kwargs = kwargs dict.__init__.__get__(self, str)() setup_transparsers(locals(), str, parse) class ListBlock(list, BlockMixin): cleaner_prefix = 'clean_' def slugify(self, header): return slugify(header) def default_clean(self, s): return s.strip() def clean(self, header, value): custom_cleaner = '%s%s'%(self.cleaner_prefix, self.slugify(header)) return getattr(self, custom_cleaner, self.default_clean)(value) def tokenize(self, line): try: return dict((header, self.clean(header, line[start:stop])) \ for (header, (start, stop)) in self.headers.items()) except Exception as e: def info(obj): return dict((k,v) for k,v in obj.__dict__.items() \ if not (callable(v) or k.startswith('__'))) pprint ({'block':info(self), 'data':info(self.instance)}) if self.kwargs['quiet_on_clean_values']: print (e) return None else: raise def parse(self): lines = self.get_block(self.name) if not hasattr(self, 'headers'): self.headers = ParseHeaders() line = None if isinstance(self.headers, ParseHeaders) and not self.headers: line = self.headers.parse(lines) else: takewhile(lambda s:startswith('*'), lines) next(lines) #can remove transparsing decorators now untransparse(self, dict) self._parsed = True append_if_good_dataline = lambda tokens:tokens is not None \ and self.append(tokens) if line: append_if_good_dataline(self.tokenize(line)) for line in lines: append_if_good_dataline(self.tokenize(line)) def __init__(self, name, **kwargs): self.name = name kwargs['quiet_on_clean_values'] = kwargs.get('quiet_on_clean_values', QUIET_ON_CLEAN_VALUES) self.kwargs = kwargs list.__init__.__get__(self, list)() setup_transparsers(locals(), list, parse) class ParseHeaders(dict): line_width = 80 subsplitter = ' ' def __init__(self, *args, **kwargs): self.prefix = kwargs.get('prefix', '*') super(ParseHeaders, self).__init__(*args, **kwargs) def clean_key(self, key): return key.strip('_') def flatten(self, start, stop, subheaders): if not len(subheaders): return headers = iter(subheaders[-1]) for (header, (substart, substop)) in headers: if substart>=start and substop<=stop: has_subs = False for (subheader, (subsubstart, subsubstop)) in self.flatten(substart, substop, subheaders[:-1]): has_subs = True yield (''.join([header, self.subsplitter, subheader]), (subsubstart, subsubstop)) if not has_subs: yield (header, (substart, substop)) def parse_header_line(self, line): if not hasattr(self, 'subheaders'): self.subheaders = [] subheaders = [] pos = len(line) - len(line[1:].lstrip()) for header in line[pos:].split(' '): newpos = pos + len(header) if header.strip(): subheaders += (self.clean_key(header), (pos, newpos)), pos = newpos + 1 if len(self.subheaders): #see +SITE/ECCENTRICITY, last column if self.subheaders[-1][-1][1][1] > subheaders[-1][1][1]: subheaders[-1] = \ (subheaders[-1][0], (subheaders[-1][1][0], self.subheaders[-1][-1][1][1])) self.subheaders += subheaders, def parse(self, lines): line = next(lines) while line.startswith(self.prefix): self.parse_header_line(line) line = next(lines) super(ParseHeaders, self).__init__(self.flatten(0, self.line_width, self.subheaders)) return line def __get__(self, instance, owner): if not instance: return self.__class__ if not hasattr(instance, '_headers'): instance._headers = self.__class__() instance._headers.instance = instance return instance._headers
gpl-3.0
hlim/studio2
src/main/java/org/craftercms/studio/impl/v1/service/configuration/ServicesConfigImpl.java
21181
/******************************************************************************* * Crafter Studio Web-content authoring solution * Copyright (C) 2007-2016 Crafter Software Corporation. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.craftercms.studio.impl.v1.service.configuration; import javolution.util.FastList; import org.apache.commons.lang.StringUtils; import org.craftercms.commons.lang.Callback; import org.craftercms.core.service.CacheService; import org.craftercms.core.util.cache.CacheTemplate; import org.craftercms.studio.api.v1.repository.ContentRepository; import org.craftercms.studio.api.v1.service.GeneralLockService; import org.craftercms.studio.api.v1.service.configuration.ContentTypesConfig; import org.craftercms.studio.api.v1.service.content.ContentService; import org.craftercms.studio.api.v1.constant.CStudioConstants; import org.craftercms.studio.api.v1.service.AbstractRegistrableService; import org.craftercms.studio.api.v1.service.configuration.ServicesConfig; import org.craftercms.studio.api.v1.to.*; import org.craftercms.studio.impl.v1.service.StudioCacheContext; import org.craftercms.studio.impl.v1.util.ContentFormatUtils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * Implementation of ServicesConfigImpl. This class requires a configuration * file in the repository * * */ public class ServicesConfigImpl implements ServicesConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ServicesConfigImpl.class); protected static final String WEM_PROJECTS_PATH = "/wem-projects"; protected static final String WORK_AREA_PATH = "/work-area"; protected static final String LIVE_PATH = "/live"; /** path keys **/ protected static final String PATH_CONTENT = "content"; protected static final String PATH_WCM_CONTENT = "wcm-content"; protected static final String PATH_PROTOTYPE = "prototype"; protected static final String PATH_TEMPLATE = "template"; /** pattern keys **/ protected static final String PATTERN_PAGE = "page"; protected static final String PATTERN_COMPONENT = "component"; protected static final String PATTERN_ASSET = "asset"; protected static final String PATTERN_DOCUMENT = "document"; protected static final String PATTERN_RENDERING_TEMPLATE = "rendering-template"; protected static final String PATTERN_LEVEL_DESCRIPTOR = "level-descriptor"; protected static final String PATTERN_PREVIEWABLE_MIMETYPES = "previewable-mimetypes"; /** xml element names **/ protected static final String ELM_PATTERN = "pattern"; /** xml attribute names **/ protected static final String ATTR_DEPTH = "@depth"; protected static final String ATTR_DISPLAY_NAME = "@displayName"; protected static final String ATTR_NAMESPACE = "@namespace"; protected static final String ATTR_NAME = "@name"; protected static final String ATTR_SITE = "@site"; protected static final String ATTR_PATH = "@path"; protected static final String ATTR_READ_DIRECT_CHILDREN = "@read-direct-children"; protected static final String ATTR_ATTACH_ROOT_PREFIX = "@attach-root-prefix"; protected static final String LIVE_REPOSITORY_PATH_SUFFIX = "-live"; /** * the location where to find the configuration file */ protected String configPath; /** * configuration file name */ protected String configFileName; /** * content types configuration */ protected ContentTypesConfig contentTypesConfig; /** * Content service */ protected ContentService contentService; protected ContentRepository contentRepository; protected CacheTemplate cacheTemplate; protected SiteConfigTO getSiteConfig(final String site) { CacheService cacheService = cacheTemplate.getCacheService(); StudioCacheContext cacheContext = new StudioCacheContext(site, true); Object cacheKey = cacheTemplate.getKey(site, configPath.replaceFirst(CStudioConstants.PATTERN_SITE, site), configFileName); generalLockService.lock(cacheContext.getId()); try { if (!cacheService.hasScope(cacheContext)) { cacheService.addScope(cacheContext); } } finally { generalLockService.unlock(cacheContext.getId()); } SiteConfigTO config = cacheTemplate.getObject(cacheContext, new Callback<SiteConfigTO>() { @Override public SiteConfigTO execute() { return loadConfiguration(site); } }, site, configPath.replaceFirst(CStudioConstants.PATTERN_SITE, site), configFileName); return config; } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getWebProject(java.lang.String) */ public String getWemProject(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getWemProject() != null) { return config.getWemProject(); } return null; } @Override public List<DmFolderConfigTO> getFolders(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getFolders(); } return null; } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.wcm.service.api.WcmServicesConfig#getRootPrefix(java.lang.String) */ public String getRootPrefix(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getRootPrefix(); } return null; } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getContentType(java.lang.String, java.lang.String) */ public ContentTypeConfigTO getContentTypeConfig(String site, String name) { return contentTypesConfig.getContentTypeConfig(site, name); } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getAssetPatterns(java.lang.String) */ public List<String> getAssetPatterns(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getAssetPatterns(); } return null; } public List<DeleteDependencyConfigTO> getDeleteDependencyPatterns(String site,String contentType) { if(contentType==null){ return Collections.emptyList(); } ContentTypeConfigTO contentTypeConfig = contentTypesConfig.getContentTypeConfig(site, contentType); if (contentTypeConfig != null) { return contentTypeConfig.getDeleteDependencyPattern(); } return Collections.emptyList(); } public List<CopyDependencyConfigTO> getCopyDependencyPatterns(String site,String contentType) { if(contentType==null){ return Collections.emptyList(); } ContentTypeConfigTO contentTypeConfig = contentTypesConfig.getContentTypeConfig(site, contentType); if (contentTypeConfig != null) { return contentTypeConfig.getCopyDepedencyPattern(); } return Collections.emptyList(); } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getComponentPatterns(java.lang.String) */ public List<String> getComponentPatterns(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getComponentPatterns(); } return null; } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getPagePatterns(java.lang.String) */ public List<String> getPagePatterns(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getPagePatterns(); } return null; } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getRenderingTemplatePatterns(java.lang.String) */ public List<String> getRenderingTemplatePatterns(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getRenderingTemplatePatterns(); } return null; } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getLevelDescriptorPatterns(java.lang.String) */ public List<String> getLevelDescriptorPatterns(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getLevelDescriptorPatterns(); } return null; } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getDocumentPatterns(java.lang.String) */ public List<String> getDocumentPatterns(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getDocumentPatterns(); } return null; } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getLevelDescriptorName(java.lang.String) */ public String getLevelDescriptorName(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getLevelDescriptorName(); } return null; } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getDisplayInWidgetPathPatterns(java.lang.String) */ public List<String> getDisplayInWidgetPathPatterns(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getDisplayPatterns(); } return null; } /* * (non-Javadoc) * @see org.craftercms.cstudio.alfresco.service.api.ServicesConfig#getDefaultTimezone(java.lang.String) */ public String getDefaultTimezone(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null) { return config.getTimezone(); } else { return null; } } /** * load services configuration * */ @SuppressWarnings("unchecked") protected SiteConfigTO loadConfiguration(String site) { String siteConfigPath = configPath.replaceFirst(CStudioConstants.PATTERN_SITE, site); Document document = null; SiteConfigTO siteConfig = null; try { document = contentService.getContentAsDocument(site, siteConfigPath + "/" + configFileName); } catch (DocumentException e) { LOGGER.error("Error while loading configuration for " + site + " at " + siteConfigPath, e); } if (document != null) { Element root = document.getRootElement(); Node configNode = root.selectSingleNode("/site-config"); String name = configNode.valueOf("display-name"); siteConfig = new SiteConfigTO(); siteConfig.setName(name); //siteConfig.setSiteName(configNode.valueOf("name")); siteConfig.setWemProject(configNode.valueOf("wem-project")); //siteConfig.setDefaultContentType(configNode.valueOf("default-content-type")); //String assetUrl = configNode.valueOf("assets-url"); siteConfig.setTimezone(configNode.valueOf("default-timezone")); //siteConfig.setAssetUrl(assetUrl); //loadNamespaceToTypeMap(siteConfig, configNode.selectNodes("namespace-to-type-map/namespace")); //loadModelConfig(siteConfig, configNode.selectNodes("models/model")); //SearchConfigTO searchConfig = _contentTypesConfig.loadSearchConfig(configNode.selectSingleNode("search")); //siteConfig.setDefaultSearchConfig(searchConfig); loadSiteRepositoryConfiguration(siteConfig, configNode.selectSingleNode("repository")); // set the last updated date siteConfig.setLastUpdated(new Date()); } else { LOGGER.error("No site configuration found for " + site + " at " + siteConfigPath); } return siteConfig; } /** * load the web-project configuration * * @param siteConfig * @param node */ @SuppressWarnings("unchecked") protected void loadSiteRepositoryConfiguration(SiteConfigTO siteConfig, Node node) { RepositoryConfigTO repoConfigTO = new RepositoryConfigTO(); repoConfigTO.setRootPrefix(node.valueOf("@rootPrefix")); repoConfigTO.setLevelDescriptorName(node.valueOf("level-descriptor")); //repoConfigTO.setIndexRepository(ContentFormatUtils.getBooleanValue(node.valueOf("index-repository"))); /*String timeValue = node.valueOf("index-time-to-live"); if (!StringUtils.isEmpty(timeValue)) { long indexTimeToLive = ContentFormatUtils.getLongValue(timeValue); if (indexTimeToLive > 0) { repoConfigTO.setIndexTimeToLive(indexTimeToLive); } }*/ //repoConfigTO.setCheckForRenamed(org.craftercms.cstudio.alfresco.util.ContentFormatUtils.getBooleanValue(node.valueOf("check-for-renamed"))); loadFolderConfiguration(siteConfig, repoConfigTO, node.selectNodes("folders/folder")); loadPatterns(siteConfig, repoConfigTO, node.selectNodes("patterns/pattern-group")); //List<String> excludePaths = getStringList(node.selectNodes("exclude-paths/exclude-path")); //repoConfigTO.setExcludePaths(excludePaths); List<String> displayPatterns = getStringList(node.selectNodes("display-in-widget-patterns/display-in-widget-pattern")); repoConfigTO.setDisplayPatterns(displayPatterns); //loadTemplateConfig(repoConfigTO, node.selectSingleNode("common-prototype-config")); siteConfig.setRepositoryConfig(repoConfigTO); } /** * get a list of string values * * @param nodes * @return a list of string values */ protected List<String> getStringList(List<Node> nodes) { List<String> items = null; if (nodes != null && nodes.size() > 0) { items = new FastList<String>(nodes.size()); for (Node node : nodes) { items.add(node.getText()); } } else { items = new FastList<String>(0); } return items; } /** * load page/component/assets patterns configuration * * @param site * @param nodes */ @SuppressWarnings("unchecked") protected void loadPatterns(SiteConfigTO site, RepositoryConfigTO repo, List<Node> nodes) { if (nodes != null) { for (Node node : nodes) { String patternKey = node.valueOf(ATTR_NAME); if (!StringUtils.isEmpty(patternKey)) { List<Node> patternNodes = node.selectNodes(ELM_PATTERN); if (patternNodes != null) { List<String> patterns = new FastList<String>(patternNodes.size()); for (Node patternNode : patternNodes) { String pattern = patternNode.getText(); if (!StringUtils.isEmpty(pattern)) { patterns.add(pattern); } } if (patternKey.equals(PATTERN_PAGE)) { repo.setPagePatterns(patterns); } else if (patternKey.equals(PATTERN_COMPONENT)) { repo.setComponentPatterns(patterns); } else if (patternKey.equals(PATTERN_ASSET)) { repo.setAssetPatterns(patterns); } else if (patternKey.equals(PATTERN_DOCUMENT)) { repo.setDocumentPatterns(patterns); } else if (patternKey.equals(PATTERN_RENDERING_TEMPLATE)) { repo.setRenderingTemplatePatterns(patterns); } else if (patternKey.equals(PATTERN_LEVEL_DESCRIPTOR)) { repo.setLevelDescriptorPatterns(patterns); } else if (patternKey.equals(PATTERN_PREVIEWABLE_MIMETYPES)) { repo.setPreviewableMimetypesPaterns(patterns); } else { LOGGER.error("Unknown pattern key: " + patternKey + " is provided in " + site.getName()); } } } else { LOGGER.error("no pattern key provided in " + site.getName() + " configuration. Skipping the pattern."); } } } else { LOGGER.warn(site.getName() + " does not have any pattern configuration."); } } /** * load top level folder configuration * * @param site * @param folderNodes */ protected void loadFolderConfiguration(SiteConfigTO site, RepositoryConfigTO repo, List<Node> folderNodes) { if (folderNodes != null) { List<DmFolderConfigTO> folders = new FastList<DmFolderConfigTO>(folderNodes.size()); for (Node folderNode : folderNodes) { DmFolderConfigTO folderConfig = new DmFolderConfigTO(); folderConfig.setName(folderNode.valueOf(ATTR_NAME)); folderConfig.setPath(folderNode.valueOf(ATTR_PATH)); folderConfig.setReadDirectChildren(ContentFormatUtils.getBooleanValue(folderNode.valueOf(ATTR_READ_DIRECT_CHILDREN))); folderConfig.setAttachRootPrefix(ContentFormatUtils.getBooleanValue(folderNode.valueOf(ATTR_ATTACH_ROOT_PREFIX))); folders.add(folderConfig); } repo.setFolders(folders); } else { LOGGER.warn(site.getName() + " does not have any folder configuration."); } } public List<String> getPreviewableMimetypesPaterns(String site) { SiteConfigTO config = getSiteConfig(site); if (config != null && config.getRepositoryConfig() != null) { return config.getRepositoryConfig().getPreviewableMimetypesPaterns(); } return null; } @Override public void reloadConfiguration(String site) { CacheService cacheService = cacheTemplate.getCacheService(); StudioCacheContext cacheContext = new StudioCacheContext(site, true); Object cacheKey = cacheTemplate.getKey(site, configPath.replaceFirst(CStudioConstants.PATTERN_SITE, site), configFileName); generalLockService.lock(cacheContext.getId()); try { if (cacheService.hasScope(cacheContext)) { cacheService.remove(cacheContext, cacheKey); } else { cacheService.addScope(cacheContext); } } finally { generalLockService.unlock(cacheContext.getId()); } SiteConfigTO config = loadConfiguration(site); cacheService.put(cacheContext, cacheKey, config); } public void setContentService(ContentService contentService) { this.contentService = contentService; } public void setConfigPath(String configPath) { this.configPath = configPath; } public void setConfigFileName(String configFileName) { this.configFileName = configFileName; } public ContentTypesConfig getContentTypesConfig() { return contentTypesConfig; } public void setContentTypesConfig(ContentTypesConfig contentTypesConfig) { this.contentTypesConfig = contentTypesConfig; } public ContentRepository getContentRepository() { return contentRepository; } public void setContentRepository(ContentRepository contentRepository) { this.contentRepository = contentRepository; } public CacheTemplate getCacheTemplate() { return cacheTemplate; } public void setCacheTemplate(CacheTemplate cacheTemplate) { this.cacheTemplate = cacheTemplate; } public GeneralLockService getGeneralLockService() { return generalLockService; } public void setGeneralLockService(GeneralLockService generalLockService) { this.generalLockService = generalLockService; } protected GeneralLockService generalLockService; }
gpl-3.0
nguyenviet1993/lmsonline
lang/vi/completion.php
15046
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'completion', language 'vi', branch 'MOODLE_32_STABLE' * * @package completion * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['achievinggrade'] = 'Điểm đạt được'; $string['activities'] = 'Các hoạt động'; $string['activitiescompleted'] = 'Các hoạt động đã hoàn thành'; $string['activitiescompletednote'] = 'Chú ý: Hoạt động hoàn thành phải được thiết đặt cho một hoạt động để xuất hiện trong danh sách trên.'; $string['activityaggregation'] = 'Điều kiện yêu cầu'; $string['activityaggregation_all'] = 'TẤT CẢ các hoạt động được chọn hoàn thành'; $string['activityaggregation_any'] = 'BẤT KÌ các hoạt động được chọn hoàn thành'; $string['activitycompletion'] = 'Hoàn thành các hoạt động'; $string['aggregationmethod'] = 'Phương pháp tính gộp (aggregation)'; $string['all'] = 'Tất cả'; $string['any'] = 'Bất kỳ'; $string['approval'] = 'Đồng ý'; $string['badautocompletion'] = 'Khi bạn chọn hoàn thành tự động, bạn cũng phải kích hoạt ít nhất một yêu cầu (bên dưới).'; $string['completed'] = 'Đã hoàn thành'; $string['completedunlocked'] = 'Các tùy chọn hoàn thành được mở'; $string['completedunlockedtext'] = 'Khi bạn lưu các thay đổi, trạng thái hoàn thành đối với tất cả học sinh sẽ bị xóa. Nếu bạn đổi ý về điều này, không lưu mẫu đơn lại.'; $string['completedwarning'] = 'Các tùy chọn hoàn thành đã khóa'; $string['completedwarningtext'] = 'Một hay nhiều học sinh ({$a}) đã đánh dấu hoạt động này như hoàn thành rồi. Thay đổi các lựa chọn hoàn thành sẽ xóa trạng thái hoàn thành của họ và có thể gây hiểu nhầm. Vì vậy các lựa chọn đã bị khóa và không nên mở khóa trừ khi thực sự cần thiết.'; $string['completion'] = 'Kiểm tra độ hoàn thành'; $string['completionactivitydefault'] = 'Dùng hoạt động mặc định'; $string['completion-alt-auto-enabled'] = 'Hệ thống xác định phần này đã hoàn thành theo điều kiện đặt ra'; $string['completion-alt-auto-fail'] = 'Đã hoàn thành (không đạt điểm vượt qua)'; $string['completion-alt-auto-n'] = 'Chưa hoàn thành'; $string['completion-alt-auto-pass'] = 'Đã hoàn thành (đạt điểm vượt qua)'; $string['completion-alt-auto-y'] = 'Đã hoàn thành'; $string['completion-alt-manual-enabled'] = 'Học viên có thể tự đánh dấu là đã hoàn thành phần này'; $string['completion-alt-manual-n'] = 'Chưa hoàn thành; hãy chọn đánh dấu chưa hoàn thành'; $string['completion-alt-manual-y'] = 'Đã hoàn thành; hãy chọn đánh dấu hoàn thành'; $string['completion_automatic'] = 'Khi các điều kiện được thỏa mãn, đánh dấu hoạt động như là đã hoàn thành'; $string['completiondefault'] = 'Theo dõi hoàn thành mặc định'; $string['completiondisabled'] = 'Tắt, không hiện những cài đặt hoạt động'; $string['completionduration'] = 'Ghi danh'; $string['completionenabled'] = 'Được kích hoạt, kiểm soát thông qua các thiết lập hoàn thành và hoạt động'; $string['completionexpected'] = 'Ngày hoàn thành dự kiến là'; $string['completionexpected_help'] = 'Thiết lập này chỉ định ngày giờ hoạt động hoàn thành theo mong đợi. Ngày giờ không được hiển thị cho học sinh và chỉ được hiển thị trong báo cáo hoàn thành hoạt động.'; $string['completion-fail'] = 'Đã hoàn thành (không được điểm đạt)'; $string['completion_help'] = 'Nếu được kích hoạt, hoàn thành hoạt động được theo dõi, thủ công hoặc tự động, dựa trên các điều kiện nhất định. Nhiều điều kiện có thể được đặt nếu muốn. Nếu vậy, hoạt động sẽ chỉ được xem là hoàn thành khi TẤT CẢ điều kiện được thỏa. Một dấu chọn kế bên tên hoạt động trên trang khóa học chỉ ra khi nào hoạt động hoàn tất.'; $string['completionicons'] = 'Các hộp đánh dấu hoàn thành'; $string['completionicons_help'] = 'Một dấu chọn kế bên tên hoạt động có thể được sử dụng để chỉ ra khi nào hoạt động hoàn thành. Nếu khung có viền nét đứt hiển thị, dấu chọn sẽ xuất hiện tự động khi bạn hoàn thành hoạt động theo các điều kiện được đặt bởi giáo viên. Nếu khung có viền nét liền hiển thị, bạn có thể nhấn vào nó để chọn khung khi nghĩ rằng mình đã hoàn thành hoạt động. (Nhấn lại để bỏ chọn nếu đổi ý.) Chọn tùy ý và đơn giản chỉ là một cách để theo dõi quá trình của bạn trong khóa học.'; $string['completion_manual'] = 'Học viên có thể tự đánh dấu là đã hoàn thành hoạt động'; $string['completion-n'] = 'Chưa hoàn thành'; $string['completion_none'] = 'Không chỉ rõ việc hoàn thành hoạt động'; $string['completionnotenabled'] = 'Việc hoàn thành không được kích hoạt'; $string['completionnotenabledforcourse'] = 'Việc hoàn thành không được kích hoạt cho khóa học này'; $string['completionnotenabledforsite'] = 'Việc hoàn thành không được kích hoạt cho hê thống này'; $string['completionondate'] = 'Ngày giờ'; $string['completionondatevalue'] = 'Người dùng phải còn ghi danh cho đến khi'; $string['completion-pass'] = 'Đã hoàn thành (được điểm đạt)'; $string['completionsettingslocked'] = 'Cài đặt hoàn thành đã khóa'; $string['completion-title-manual-n'] = 'Đánh dấu là đã hoàn thành'; $string['completion-title-manual-y'] = 'Đánh dấu là chưa hoàn thành'; $string['completionusegrade'] = 'Yêu cầu điểm số'; $string['completionusegrade_desc'] = 'Học viên phải nhận điểm số để hoàn thành hoạt động này'; $string['completionusegrade_help'] = 'Nếu được kích hoạt, hoạt động được xem như hoàn thành khi học sinh đạt điểm. Biểu tượng đạt và trượt có thể hiển thị nếu điểm đạt cho hoạt động được đặt.'; $string['completionview'] = 'Yêu cầu phải xem'; $string['completionview_desc'] = 'Học viên phải xem hoạt động này để hoàn thành nó'; $string['completion-y'] = 'Đã hoàn thành'; $string['configcompletiondefault'] = 'Thiết lập mặc định đối với theo dõi hoàn thành khi tạo các hoạt động mới.'; $string['configenablecompletion'] = 'Khi được kích hoạt, nó giúp bật tính năng theo dõi hoàn thành (quá trình) ở cấp khóa học.'; $string['confirmselfcompletion'] = 'Tự xác nhận đã hoàn thành'; $string['courseaggregation'] = 'Điều kiện yêu cầu'; $string['courseaggregation_all'] = 'TẤT CẢ khóa học được chọn hoàn thành'; $string['courseaggregation_any'] = 'BẤT KÌ khóa học được chọn hoàn thành'; $string['coursealreadycompleted'] = 'Bạn đã hoàn thành khóa học này'; $string['coursecomplete'] = 'Khóa học hoàn thành'; $string['coursecompleted'] = 'Khóa học đã hoàn thành'; $string['coursecompletion'] = 'Hoàn thành khóa học'; $string['coursecompletioncondition'] = 'Điều kiện: {$a}'; $string['coursegrade'] = 'Điểm số khóa học'; $string['coursesavailable'] = 'Khóa học hiện có'; $string['coursesavailableexplaination'] = 'Chú ý: Các điều kiện hoàn thành khóa học phải được đặt cho một khóa học để xuất hiện trong danh sách trên.'; $string['criteria'] = 'Tiêu chuẩn'; $string['criteriagroup'] = 'Nhóm tiêu chuẩn'; $string['criteriarequiredall'] = 'Yêu cầu phải thỏa mãn tất cả các tiêu chuẩn dưới đây'; $string['criteriarequiredany'] = 'Yêu cầu nào dưới đây cũng phải thỏa mãn'; $string['csvdownload'] = 'Tải định dạng bảng (UTF-8 .csv)'; $string['datepassed'] = 'Ngày đã qua'; $string['days'] = 'Các ngày'; $string['daysoftotal'] = '{$a->days} trong {$a->total}'; $string['deletecompletiondata'] = 'Xóa dữ liệu hoàn thành'; $string['dependencies'] = 'Phần phụ thuộc'; $string['dependenciescompleted'] = 'Hoàn thành các khóa học khác'; $string['editcoursecompletionsettings'] = 'Chỉnh sửa các cài đặt hoàn thành khóa học'; $string['enablecompletion'] = 'Mở việc theo dõi sự hoàn thành'; $string['enablecompletion_help'] = 'Nếu được kích hoạt, các điều kiện hoàn thành khóa học có thể đặt trong thiết lập hoạt động và/hoặc các điều kiện hoàn thành khóa học có thể được đặt.'; $string['enrolmentduration'] = 'Số ngày còn lại'; $string['enrolmentdurationlength'] = 'Người dùng phải giữ ghi danh trong'; $string['err_noactivities'] = 'Thông tin hoàn thành không được kích hoạt cho bất kì hoạt động nào, vì vậy không thể hiển thị gì. Bạn có thể kích hoạt thông tin hoàn thành bằng cách chỉnh sửa các thiết lập cho hoạt động.'; $string['err_nocourses'] = 'Hoàn thành khóa học không được kích hoạt cho bất kì khóa học khác nào, vì vậy không thể hiển thị gì. Bạn có thể kích hoạt hoàn thành khóa học trong các thiết lập khóa học.'; $string['err_noroles'] = 'Không có quyền với khả năng moodle/course:markcomplete trong khóa học này.'; $string['err_nousers'] = 'Không có học sinh trong khóa học hay nhóm này có thông tin hoàn thành được hiển thị. (Mặc định, thông tin hoàn thành chỉ được hiển thị với học sinh, nếu không có học sinh, bạn sẽ thấy lỗi này. Quản trị viên có thể thay thế lựa chọn này thông qua màn hình quản trị.)'; $string['err_settingslocked'] = 'Một hay nhiều học sinh đã hoàn thành tiêu chuẩn vì vậy các thiết lập đã bị khóa. Mở khóa các thiết lập tiêu chuẩn hoàn thành sẽ xóa bất kì dữ liệu người dùng hiện có và có thể gây hiểu nhầm.'; $string['err_system'] = 'Lỗi nội bộ đã xảy ra trong hệ thống hoàn thành. (Quản trị hệ thống có thể kích hoạt thông tin kiểm lỗi để xem thêm chi tiết.)'; $string['eventcoursecompleted'] = 'Khóa học đã hoàn thành'; $string['eventcoursecompletionupdated'] = 'Khóa học hoàn thành được cập nhật'; $string['eventcoursemodulecompletionupdated'] = 'Hoàn thành mô-đun khóa học được cập nhật'; $string['excelcsvdownload'] = 'Tải về định dạng tương thích Excel (.csv)'; $string['fraction'] = 'Phân số'; $string['graderequired'] = 'Điểm khóa học yêu cầu'; $string['gradexrequired'] = 'Yêu cầu {$a}'; $string['inprogress'] = 'Đang tiến hành'; $string['manualcompletionby'] = 'Hoàn thành bằng tay bởi'; $string['manualcompletionbynote'] = 'Chú ý: Khả năng moodle/course:markcomplete phải được cấp cho một vài trò để xuất hiện trong danh sách.'; $string['manualselfcompletion'] = 'Tự hoàn thành'; $string['manualselfcompletionnote'] = 'Chú ý: Khối tự hoàn thành nên được thêm vào khóa học nếu tự hoàn thành thủ công được kích hoạt.'; $string['markcomplete'] = 'Đánh dấu hoàn thành'; $string['markedcompleteby'] = 'Được {$a} đánh dấu là đã hoàn thành'; $string['markingyourselfcomplete'] = 'Tự đánh dấu đã hoàn thành'; $string['moredetails'] = 'Chi tiết'; $string['nocriteriaset'] = 'Không có tiêu chuẩn hoàn thành nào được cài cho khóa học này'; $string['notcompleted'] = 'Chưa hoàn thành'; $string['notenroled'] = 'Bạn chưa ghi danh vào khóa này'; $string['nottracked'] = 'Hiện tại bạn không bị theo dõi bởi hoàn thành khóa học'; $string['notyetstarted'] = 'Chưa bắt đầu'; $string['overallaggregation'] = 'Các yêu cầu hoàn thành'; $string['overallaggregation_all'] = 'Khóa học hoàn thành khi TẤT CẢ điều kiện thỏa.'; $string['overallaggregation_any'] = 'Khóa học hoàn thành khi BẤT KÌ điều kiện nào thỏa'; $string['pending'] = 'Đang ngưng'; $string['periodpostenrolment'] = 'Giai đoạn sau ghi danh'; $string['progress'] = 'Quá trình người học'; $string['progress-title'] = '{$a->người dùng}, {$a->hoạt động}: {$a->trạng thái} {$a->ngày}'; $string['progresstotal'] = 'Quá trình: {$a->complete} / {$a->total}'; $string['remainingenroledfortime'] = 'Ghi danh được lưu lại trong một thời đoạn'; $string['remainingenroleduntildate'] = 'Ghi danh được lưu lại cho đến một ngày xác định'; $string['requiredcriteria'] = 'Điều kiện yêu cầu'; $string['roleaggregation'] = 'Điều kiện yêu cầu'; $string['roleaggregation_all'] = 'TẤT CẢ vai trò được chọn để đánh dấu khi điều kiện thỏa'; $string['roleaggregation_any'] = 'BẤT KÌ vai trò nào được chọn để đánh dấu khi điều kiện thỏa'; $string['saved'] = 'Đã lưu'; $string['seedetails'] = 'Xem chi tiết'; $string['self'] = 'Tự động'; $string['selfcompletion'] = 'Tự động hoàn thành'; $string['showinguser'] = 'Hiển thị người ùng'; $string['unenrolingfromcourse'] = 'Rút tên khỏi khóa học'; $string['unenrolment'] = 'Rút tên'; $string['unit'] = 'Đơn vị'; $string['unlockcompletion'] = 'Mở khóa các cài đặt hoàn thành'; $string['unlockcompletiondelete'] = 'Mở khóa các cài đặt hoàn thành và xóa dữ liệu hoàn thành của người dùng'; $string['usernotenroled'] = 'Người dùng không được ghi danh vào khóa học này'; $string['viewcoursereport'] = 'Xem báo cáo khóa học'; $string['viewingactivity'] = 'Xem {$a}'; $string['xdays'] = '{$a} ngày'; $string['yourprogress'] = 'Quá trình học của bạn';
gpl-3.0
ReproducibleBuilds/diffoscope
diffoscope/comparators/javascript.py
1313
# -*- coding: utf-8 -*- # # diffoscope: in-depth comparison of files, archives, and directories # # Copyright © 2016 Emanuel Bronshtein <e3amn2l@gmx.com> # # diffoscope 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. # # diffoscope 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 diffoscope. If not, see <https://www.gnu.org/licenses/>. from diffoscope.tools import tool_required from diffoscope.difference import Difference from .utils.file import File from .utils.command import Command class JavaScriptBeautify(Command): @tool_required('js-beautify') def cmdline(self): return ['js-beautify', self.path] class JavaScriptFile(File): DESCRIPTION = "JavaScript files" FILE_EXTENSION_SUFFIX = '.js' def compare_details(self, other, source=None): return [Difference.from_command(JavaScriptBeautify, self.path, other.path)]
gpl-3.0
Cubeville/HawkEye-Redux
api/src/main/java/org/cubeville/hawkeye/ItemType.java
1566
/* * HawkEye Redux * Copyright (C) 2012-2013 Cubeville <http://www.cubeville.org> and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.cubeville.hawkeye; public enum ItemType { /** * Block that can be placed in the world */ BLOCK, /** * Regular item */ ITEM; /** * Gets the type of a specified item id * * @param id Item id to check * @return Item's type */ public static ItemType getType(int id) { return isBlock(id) ? BLOCK : (isItem(id) ? ITEM : null); } /** * Checks if the specified item id is a block * * @param id Item id to check * @return True if specified id is a block id, false if not */ public static boolean isBlock(int id) { return id >= 0 && id <= 255; } /** * Checks if the specified item id is an item * * @param id Item id to check * @return True if specified id is an item id, false if not */ public static boolean isItem(int id) { return id > 255; } }
gpl-3.0
datoszs/czech-lawyers
frontend/case/DisputeForm.js
2188
import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {Panel} from 'react-bootstrap'; import {RichText, Msg} from '../containers'; import {EmailField, TextField, CaptchaForm, TextAreaField, SelectOption, SelectField} from '../containers/form'; import formstatus from '../formstatus'; import {FORM} from './constants'; import {dispute} from './actions'; import {getDetail} from './selectors'; const DisputeForm = ({advocateFinal, resultFinal}) => ( <Panel bsStyle="danger" header={<Msg msg="case.dispute" />}> <RichText msg="case.dispute.text" /> <CaptchaForm form={FORM} action={dispute}> <TextField name="full_name" label="form.name" required /> <EmailField name="from" label="form.email" required /> <SelectField name="disputed_tagging" label="case.dispute.reason" required> {resultFinal || <SelectOption label="case.dispute.reason.result" id="case_result" />} {advocateFinal || <SelectOption label="case.dispute.reason.advocate" id="advocate" />} {resultFinal || advocateFinal || <SelectOption label="case.dispute.reason.both" id="both" />} {advocateFinal && <RichText msg="case.dispute.final.advocate" />} {resultFinal && <RichText msg="case.dispute.final.result" />} </SelectField> <TextAreaField name="content" label="case.dispute.comment" required /> <formstatus.ErrorContainer formName={FORM} defaultMsg="case.dispute.error.default" errorMap={{inconsistent: 'case.dispute.error.inconsistent'}} /> <formstatus.SubmitButton bsStyle="danger" msg="case.dispute.submit" formName={FORM} /> </CaptchaForm> </Panel> ); DisputeForm.propTypes = { advocateFinal: PropTypes.bool.isRequired, resultFinal: PropTypes.bool.isRequired, }; const mapStateToProps = (state) => { const detail = getDetail(state); return { advocateFinal: detail.advocateFinal, resultFinal: detail.resultFinal, }; }; export default connect(mapStateToProps)(DisputeForm);
gpl-3.0
CCAFS/MARLO
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/ProjectOutcomePandrManager.java
2812
/***************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO 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. * MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ package org.cgiar.ccafs.marlo.data.manager; import org.cgiar.ccafs.marlo.data.model.ProjectOutcomePandr; import java.util.List; /** * @author Christian Garcia */ public interface ProjectOutcomePandrManager { /** * This method removes a specific projectOutcomePandr value from the database. * * @param projectOutcomePandrId is the projectOutcomePandr identifier. * @return true if the projectOutcomePandr was successfully deleted, false otherwise. */ public void deleteProjectOutcomePandr(long projectOutcomePandrId); /** * This method validate if the projectOutcomePandr identify with the given id exists in the system. * * @param projectOutcomePandrID is a projectOutcomePandr identifier. * @return true if the projectOutcomePandr exists, false otherwise. */ public boolean existProjectOutcomePandr(long projectOutcomePandrID); /** * This method gets a list of projectOutcomePandr that are active * * @return a list from ProjectOutcomePandr null if no exist records */ public List<ProjectOutcomePandr> findAll(); /** * This method gets a projectOutcomePandr object by a given projectOutcomePandr identifier. * * @param projectOutcomePandrID is the projectOutcomePandr identifier. * @return a ProjectOutcomePandr object. */ public ProjectOutcomePandr getProjectOutcomePandrById(long projectOutcomePandrID); /** * This method saves the information of the given projectOutcomePandr * * @param projectOutcomePandr - is the projectOutcomePandr object with the new information to be added/updated. * @return a number greater than 0 representing the new ID assigned by the database, 0 if the projectOutcomePandr was * updated * or -1 is some error occurred. */ public ProjectOutcomePandr saveProjectOutcomePandr(ProjectOutcomePandr projectOutcomePandr); }
gpl-3.0
Tmin10/EVE-Security-Service
server-api/src/main/java/ru/tmin10/EVESecurityService/serverApi/model/GetCharactersCharacterIdLoyaltyPointsInternalServerError.java
2365
/* * EVE Swagger Interface * An OpenAPI for EVE Online * * OpenAPI spec version: 0.4.9.dev1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ru.tmin10.EVESecurityService.serverApi.model; import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * Internal server error */ @ApiModel(description = "Internal server error") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-06-11T18:18:08.749+04:00") public class GetCharactersCharacterIdLoyaltyPointsInternalServerError { @SerializedName("error") private String error = null; public GetCharactersCharacterIdLoyaltyPointsInternalServerError error(String error) { this.error = error; return this; } /** * Internal server error message * @return error **/ @ApiModelProperty(example = "null", value = "Internal server error message") public String getError() { return error; } public void setError(String error) { this.error = error; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GetCharactersCharacterIdLoyaltyPointsInternalServerError getCharactersCharacterIdLoyaltyPointsInternalServerError = (GetCharactersCharacterIdLoyaltyPointsInternalServerError) o; return Objects.equals(this.error, getCharactersCharacterIdLoyaltyPointsInternalServerError.error); } @Override public int hashCode() { return Objects.hash(error); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class GetCharactersCharacterIdLoyaltyPointsInternalServerError {\n"); sb.append(" error: ").append(toIndentedString(error)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
gpl-3.0
UnknownStudio/ChinaCraft2
src/main/java/cn/mccraft/chinacraft/item/ItemCCPickaxe.java
306
package cn.mccraft.chinacraft.item; import cn.mccraft.chinacraft.init.CCCreativeTabs; import net.minecraft.item.ItemPickaxe; public class ItemCCPickaxe extends ItemPickaxe{ public ItemCCPickaxe(ToolMaterial material) { super(material); setCreativeTab(CCCreativeTabs.tabCore); } }
gpl-3.0
XGProyect/XG-Proyect-v3.x.x
src/upload/app/language/english/game/stay_lang.php
336
<?php $lang = [ 'stay_report_title' => 'Parking Fleet', 'stay_mess_owner' => 'Your fleet has reached the planet %s %s and delivered its goods:<br>%s: metal %s: crystal %s: deuterium.', 'stay_mess_user' => 'Your fleet is returning from planet %s %s.<br><br>The fleet is delivering %s metal, %s crystal and %s deuterium.', ];
gpl-3.0
linuxdeepin/dde-daemon
accounts/utils_test.go
2969
/* * Copyright (C) 2014 ~ 2018 Deepin Technology Co., Ltd. * * Author: jouyouyun <jouyouwen717@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package accounts import ( "testing" "github.com/godbus/dbus" "github.com/stretchr/testify/assert" ) var str = []string{"/bin/sh", "/bin/bash", "/bin/zsh", "/usr/bin/zsh", "/usr/bin/fish", } func Test_GetLocaleFromFile(t *testing.T) { assert.Equal(t, getLocaleFromFile("testdata/locale"), "zh_CN.UTF-8") } func Test_SystemLayout(t *testing.T) { layout, err := getSystemLayout("testdata/keyboard_us") assert.NoError(t, err) assert.Equal(t, layout, "us;") layout, _ = getSystemLayout("testdata/keyboard_us_chr") assert.Equal(t, layout, "us;chr") } func TestAvailableShells(t *testing.T) { var ret = []string{"/bin/sh", "/bin/bash", "/bin/zsh", "/usr/bin/zsh", "/usr/bin/fish", } shells := getAvailableShells("testdata/shells") assert.ElementsMatch(t, shells, ret) } func TestIsStrInArray(t *testing.T) { ret := isStrInArray("testdata/shells", str) assert.Equal(t, ret, false) ret = isStrInArray("/bin/sh", str) assert.Equal(t, ret, true) } func TestIsStrvEqual(t *testing.T) { var str1 = []string{"/bin/sh", "/bin/bash", "/bin/zsh", "/usr/bin/zsh", "/usr/bin/fish", } var str2 = []string{"/bin/sh", "/bin/bash"} ret := isStrvEqual(str, str1) assert.Equal(t, ret, true) ret = isStrvEqual(str, str2) assert.Equal(t, ret, false) } func TestGetValueFromLine(t *testing.T) { ret := getValueFromLine("testdata/shells", "/") assert.Equal(t, ret, "shells") } func Test_getDetailsKey(t *testing.T) { type args struct { details map[string]dbus.Variant key string } tests := []struct { name string args args want interface{} wantErr bool }{ { name: "getDetailsKey", args: args{ details: map[string]dbus.Variant{ "te": dbus.MakeVariant(true), }, key: "te", }, want: true, wantErr: false, }, { name: "getDetailsKey not found", args: args{ details: map[string]dbus.Variant{ "te": dbus.MakeVariant(true), }, key: "te1", }, want: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := getDetailsKey(tt.args.details, tt.args.key) if tt.wantErr { assert.Error(t, err) return } assert.Equal(t, tt.want, got) }) } }
gpl-3.0
aconley/pofd_affine
examples/multi_gauss_example.cc
11749
//Multi-dimensional Gaussian example #include<string> #include<iostream> #include<fstream> #include<cstdlib> #include<vector> #include<limits> #include<getopt.h> #include "../include/global_settings.h" #include "../include/affineExcept.h" #include "../include/affineEnsemble.h" #include "../include/paramSet.h" #include "../include/hdf5utils.h" //The covariance matrix is set up as // 1) A correlation matrix with the band structure [-0.1, 0.2, 1, 0.2, 0.1] // 2) Sigmas of [1.0, 0.9, 0.8, 0.7, 0.6] /*! \brief Multi-dimensional Gaussian, centered at 0.5 in all dimensions */ class multiGauss : public affineEnsemble { private: double* invCovMatrix; //!< Inverse covariance matrix, nparams by nparams double* work1; //!< Working vector double* work2; //!< Working vector public: multiGauss(const std::string&, unsigned int, unsigned int, unsigned int, unsigned int, double, unsigned int, bool); virtual ~multiGauss(); void initChains(); void generateInitialPosition(const paramSet&); double getLogLike(const paramSet&, bool& params_rejected); bool areParamsValid(const paramSet& p) const; void getStats(std::vector<float>&, std::vector<float>&) const; }; multiGauss::multiGauss(const std::string& filename, unsigned int NWALKERS, unsigned int NPARAMS, unsigned int NSAMPLES, unsigned int INIT_STEPS=0, double INIT_TEMP=2.0, unsigned int MIN_BURN=50, bool FIXED_BURN=false) : affineEnsemble(NWALKERS, NPARAMS, NSAMPLES, INIT_STEPS, INIT_TEMP, MIN_BURN, FIXED_BURN) { if (NPARAMS > 0) { invCovMatrix = new double[NPARAMS * NPARAMS]; work1 = new double[NPARAMS]; work2 = new double[NPARAMS]; } else { invCovMatrix = NULL; work1 = NULL; work2 = NULL; } //Read in file std::ifstream ifs(filename.c_str()); if (!ifs) throw affineExcept("multiGauss", "multiGauss", "Couldn't open input file"); for (unsigned int i = 0; i < NPARAMS*NPARAMS; ++i) ifs >> invCovMatrix[i]; ifs.close(); } multiGauss::~multiGauss() { if (invCovMatrix != NULL) delete[] invCovMatrix; if (work1 != NULL) delete[] work1; if (work2 != NULL) delete[] work2; } void multiGauss::initChains() { // This doesn't do much of anything except call generateInitialPosition // the around the mean is_init = true; if (rank != 0) return; unsigned int npar = getNParams(); paramSet p(npar); for (unsigned int i = 0; i < npar; ++i) p[i] = 0.55; //Slightly off has_initStep = true; initStep = p; generateInitialPosition(p); } // This isn't really necessary for this simple distribution, but // as an example of how to use it, reject all points outside [-10, 10] bool multiGauss::areParamsValid(const paramSet& p) const { unsigned int npar = getNParams(); for (unsigned int i = 0; i < npar; ++i) if (fabs(p[i]) > 10) return false; return true; } // Note we use areParamsValid to reject invalid starting positions void multiGauss::generateInitialPosition(const paramSet& p) { const unsigned int maxiters = 20; if (rank != 0) return; chains.clear(); chains.addChunk(1); unsigned int npar = p.getNParams(); if (npar != getNParams()) throw affineExcept("multiGauss", "generateInitialPosition", "Wrong number of params in p"); if (!areParamsValid(p)) throw affineExcept("multiGauss", "generateInitialPosition", "Initial position seed is invalid"); paramSet p2(npar); unsigned int nwalk = getNWalkers(); bool is_valid; unsigned int iter; for (unsigned int i = 0; i < nwalk; ++i) { iter = 0; is_valid = false; while (!is_valid) { if (iter > maxiters) throw affineExcept("multiGauss", "generateInitialPosition", "Unable to generate initial position"); for (unsigned int j = 0; j < npar; ++j) p2[j] = rangen.doub() - 0.5 + p[j]; is_valid = areParamsValid(p2); ++iter; } chains.addNewStep(i, p2, -std::numeric_limits<double>::infinity()); naccept[i] = 0; } chains.setSkipFirst(); } double multiGauss::getLogLike(const paramSet& p, bool& params_rejected) { unsigned int npar = getNParams(); if (npar == 0) { params_rejected = true; return 0; } else params_rejected = false; //Mean subtracted vector; mean is 0.5 in all dim for (unsigned int i = 0; i < npar; ++i) work1[i] = p[i] - 0.5; //First product double sum, *ptr; for (unsigned int i = 0; i < npar; ++i) { ptr = invCovMatrix + npar*i; sum = ptr[0]*work1[0]; for (unsigned int j = 1; j < npar; ++j) sum += ptr[j]*work1[j]; work2[i] = sum; } //Second sum = work1[0]*work2[0]; for (unsigned int i = 1; i < npar; ++i) sum += work1[i]*work2[i]; return -0.5*sum; } void multiGauss::getStats(std::vector<float>& mn, std::vector<float>& var) const { unsigned int npar = getNParams(); mn.resize(npar); var.resize(npar); float cmn, cvar, lowlim, uplim; for (unsigned int i = 0; i < npar; ++i) { chains.getParamStats(i, cmn, cvar, lowlim, uplim); mn[i] = cmn; var[i] = cvar; } } /////////////////////////////////// int main(int argc, char** argv) { const unsigned int ndim = 5; unsigned int nwalkers, nsamples, min_burn, init_steps; std::string invcovfile, outfile; bool verbose, fixed_burn; double init_temp; verbose = false; min_burn = 20; init_steps = 20; init_temp = 2.0; fixed_burn = false; int c; int option_index = 0; static struct option long_options[] = { {"help",no_argument,0,'h'}, {"fixedburn", no_argument, 0, 'f'}, {"inittemp", required_argument, 0, 'I'}, {"initsteps", required_argument, 0, 'i'}, {"minburn", required_argument, 0, 'm'}, {"verbose",no_argument,0,'v'}, {"Version",no_argument,0,'V'}, {0,0,0,0} }; char optstring[] = "hfi:I:m:vV"; int rank, nproc; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nproc); MPI_Comm_rank(MPI_COMM_WORLD, &rank); while ((c = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1) switch(c) { case 'h' : if (rank == 0) { std::cerr << "NAME" << std::endl; std::cerr << "\tmulti_gauss_example -- draws samples from a " << " 5-dimensional " << std::endl; std::cerr << "\t\tmulti-variate Gaussian" << std::endl; std::cerr << std::endl; std::cerr << "SYNOPSIS" << std::endl; std::cerr << "\tmulti_gauss_example nwalkers nsamples outfile" << std::endl; std::cerr << "DESCRIPTION:" << std::endl; std::cerr << "\tDraws samples from a multi-variate Gaussian using" << std::endl; std::cerr << "\tan affine-invariant MCMC code, using nwalkers walkers" << std::endl; std::cerr << "\tand generating (approximately) nsamples samples. The" << std::endl; std::cerr << "\tresults are written to outfile. The input covariance" << std::endl; std::cerr << "\tmatrix is fixed, and the mean is 0.5 in all " << "dimensions." << std::endl; std::cerr << std::endl; std::cerr << "OPTIONS" << std::endl; std::cerr << "\t-h, --help" << std::endl; std::cerr << "\t\tOutput this help." << std::endl; std::cerr << "\t-f, --fixedburn" << std::endl; std::cerr << "\t\tUsed a fixed burn in length before starting main" << " sample," << std::endl; std::cerr << "\t\trather than using the autocorrelation." << std::endl; std::cerr << "\t-i, --initsteps STEPS" << std::endl; std::cerr << "\t\tTake this many initial steps per walker, then " << "recenter" << std::endl; std::cerr << "\t\taround the best one before starting burn in" << " (def: 20)" << std::endl; std::cerr << "\t-I, --inittemp VALUE" << std::endl; std::cerr << "\t\tTemperature used during initial steps (def: 2.0)" << std::endl; std::cerr << "\t-m, --minburn NSTEPS" << std::endl; std::cerr << "\t\tNumber of burn-in steps to do per walker (def: 20)" << std::endl; std::cerr << "\t-v, --verbose" << std::endl; std::cerr << "\t\tOuput informational messages as it runs" << std::endl; std::cerr << "\t-V, --version" << std::endl; std::cerr << "\t\tOuput the version number of mcmc_affine in use" << std::endl; } MPI_Finalize(); return 0; break; case 'f': fixed_burn = true; break; case 'i': init_steps = atoi(optarg); break; case 'I': init_temp = atof(optarg); break; case 'm': min_burn = atoi(optarg); break; case 'v' : verbose = true; break; case 'V' : if (rank == 0) { std::cerr << "mcmc_affine version number: " << mcmc_affine::version << std::endl; } MPI_Finalize(); return 0; break; } if (optind >= argc - 2) { if (rank == 0) { std::cerr << "Required arguments missing" << std::endl; } MPI_Finalize(); return 1; } nwalkers = atoi(argv[optind]); nsamples = atoi(argv[optind+1]); outfile = std::string(argv[optind+2]); if (nwalkers == 0 || nsamples == 0) { MPI_Finalize(); return 0; } if (nproc < 2) { if (rank == 0) { std::cerr << "Must run on multiple processes" << std::endl; } MPI_Finalize(); return 1; } invcovfile = "exampledata/test_invcovmat.txt"; //Hardwired cov matrix try { multiGauss mg(invcovfile, nwalkers, ndim, nsamples, init_steps, init_temp, min_burn, fixed_burn); if (verbose) { mg.setVerbose(); if (rank == 0) std::cout << mg << std::endl; } mg.setParamName(0, "mn[0]"); mg.setParamName(1, "mn[1]"); mg.setParamName(2, "mn[2]"); mg.setParamName(3, "mn[3]"); mg.setParamName(4, "mn[4]"); mg.sample(); //Also initializes if (rank == 0) { mg.printStatistics(); std::vector<float> accept; mg.getAcceptanceFrac(accept); double mnacc = accept[0]; for (unsigned int i = 1; i < nwalkers; ++i) mnacc += accept[i]; std::cout << "Mean acceptance: " << mnacc / static_cast<double>(nwalkers) << std::endl; std::vector<float> acor; bool succ = mg.getAcor(acor); if (succ) { std::cout << "Autocorrelation length: " << acor[0]; for (unsigned int i = 1; i < acor.size(); ++i) std::cout << " " << acor[i]; std::cout << std::endl; } else std::cout << "Failed to compute autocorrelation" << std::endl; hdf5utils::outfiletype ftype; ftype = hdf5utils::getOutputFileType(outfile); switch(ftype) { case hdf5utils::TXT: mg.writeToFile(outfile); break; case hdf5utils::FITS: throw affineExcept("multi_gauss_example", "main", "No support for FITS output"); break; case hdf5utils::UNKNOWN: case hdf5utils::HDF5: mg.writeToHDF5(outfile); break; } } } catch ( const affineExcept& ex ) { std::cerr << "Error encountered" << std::endl; std::cerr << ex << std::endl; int jnk; if (rank == 0) for (int i = 1; i < nproc; ++i) MPI_Send(&jnk, 1, MPI_INT, i, mcmc_affine::STOP, MPI_COMM_WORLD); MPI_Finalize(); return 1; } MPI_Finalize(); return 0; }
gpl-3.0
Belfalaz/ctf
bruteflag/index.php
2100
<html> <head> <title>Flag 1.0</title> <meta charset="utf-8" /> <link href="css/style.css" rel="stylesheet" type="text/css"> <script type="text/javascript"> function check(){ if(document.getElementById('txt_search').value == ""){ alert('Please Enter Search String'); return false; } } </script> </head> <body> <div> <!-- Container --> <header> <!-- Header --> <h1><a href="index.php">Flag 1.0</a></h1> </header> <div class=".search"> <!-- Content --> You must <b>FIND</b> flag by yourself!<br><br> <form method="get" action="" onsubmit="javascript:return check();"> Search <input type="text" name="search" id="txt_search" placeholder="Search.."> <button type="submit">GO</button> </form> <div class="datagrid"> <table> <thead> <tr> <th>No.</th> <th>Subject</th> </tr> </thead> <?php #include("config.php"); $url = parse_url(getenv("CLEARDB_DATABASE_URL")); $dbhost = $url["host"]; $dbuser = $url["user"]; $dbpass = $url["pass"]; $dbname = substr($url["path"], 1); if(isset($_GET['search']) != "") { $search = $_GET['search']; $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($conn->connect_error) { die("<tbody><tr><td>Err</td><td>Connection Failed</td></tr></tbody>"); } $param = "%" . $_GET['search'] . "%"; $stmt = $conn->prepare("SELECT * FROM crackflag WHERE data LIKE ? or subject LIKE ?"); $stmt->bind_param("ss", $param, $param); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_assoc(); if($row) { echo "<tbody>"; echo "<tr><td>" . $row["id"] . "</td><td>" . $row["subject"] . "</td></tr>"; echo "</tbody>"; } $conn->close(); } else { echo "<tbody>"; echo "<tr><td>Err</td><td>Please Enter Search String.</td></tr>"; echo "</tbody>"; } ?> </table> </div> </div> </div> </body> </html>
gpl-3.0
mrworkman/Project-Renfrew
GrammarTests/GrammarTests.cs
1093
// Project Renfrew // Copyright(C) 2017 Stephen Workman (workman.stephen@gmail.com) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 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/>. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GrammarTests { //[TestClass] public class GrammarTests { //[TestMethod] //public void ShouldThrowExceptionIfRuleDoesNotTerminateWithAnAction() { // throw new NotImplementedException(); //} } }
gpl-3.0
danieldizzy/smartcard-reader
app/src/main/java/org/docrj/smartcard/reader/AppViewActivity.java
15096
/* * Copyright 2015 Ryan Jones * * This file is part of smartcard-reader, package org.docrj.smartcard.reader. * * smartcard-reader 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. * * smartcard-reader 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 smartcard-reader. If not, see <http://www.gnu.org/licenses/>. */ package org.docrj.smartcard.reader; import android.os.Build; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.TextView; import com.afollestad.materialdialogs.AlertDialogWrapper; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; public class AppViewActivity extends ActionBarActivity { private static final String TAG = LaunchActivity.TAG; private static final String[] DEFAULT_GROUPS = SmartcardApp.GROUPS; // actions private static final String ACTION_EDIT_APP = AppListActivity.ACTION_EDIT_APP; private static final String ACTION_COPY_APP = AppListActivity.ACTION_COPY_APP; // extras private static final String EXTRA_APP_POS = AppListActivity.EXTRA_APP_POS; private static final String EXTRA_SELECT = AppListActivity.EXTRA_SELECT; // dialogs private static final int DIALOG_CONFIRM_DELETE = 0; // requests private static final int REQUEST_EDIT_APP = 0; private static final int REQUEST_COPY_APP = 1; private SharedPreferences.Editor mEditor; private ArrayList<SmartcardApp> mApps; private int mSelectedAppPos; private int mAppPos; private boolean mReadOnly; private HashSet<String> mUserGroups; private List<String> mSortedAllGroups; private int mSelectedGrpPos; // batch select group idx private String mSelectedGrpName; private int mExpandedGrpPos; // app browse group idx private String mExpandedGrpName; private EditText mName; private EditText mAid; private RadioGroup mType; private TextView mGroups; private TextView mNote; private AlertDialog mConfirmDeleteDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_view); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); // persistent data in shared prefs SharedPreferences ss = getSharedPreferences("prefs", Context.MODE_PRIVATE); mEditor = ss.edit(); mSelectedAppPos = ss.getInt("selected_app_pos", 0); Gson gson = new Gson(); String json = ss.getString("groups", null); if (json == null) { mUserGroups = new LinkedHashSet<>(); } else { Type collectionType = new TypeToken<LinkedHashSet<String>>() { }.getType(); mUserGroups = gson.fromJson(json, collectionType); } // alphabetize, case insensitive mSortedAllGroups = new ArrayList<>(mUserGroups); mSortedAllGroups.addAll(Arrays.asList(DEFAULT_GROUPS)); Collections.sort(mSortedAllGroups, String.CASE_INSENSITIVE_ORDER); // when deleting an app results in an empty group, we remove the group; // we may need to adjust group position indices for batch select and app // browse activities, which apply to the sorted list of groups mSelectedGrpPos = ss.getInt("selected_grp_pos", 0); mSelectedGrpName = mSortedAllGroups.get(mSelectedGrpPos); mExpandedGrpPos = ss.getInt("expanded_grp_pos", -1); mExpandedGrpName = (mExpandedGrpPos == -1) ? "" : mSortedAllGroups.get(mExpandedGrpPos); Intent intent = getIntent(); mAppPos = intent.getIntExtra(EXTRA_APP_POS, 0); mName = (EditText) findViewById(R.id.app_name); mAid = (EditText) findViewById(R.id.app_aid); mType = (RadioGroup) findViewById(R.id.radio_grp_type); mNote = (TextView) findViewById(R.id.note); mGroups = (TextView) findViewById(R.id.group_list); // view only mName.setFocusable(false); mAid.setFocusable(false); for (int i = 0; i < mType.getChildCount(); i++) { mType.getChildAt(i).setClickable(false); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window w = getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS, WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); w.setStatusBarColor(getResources().getColor(R.color.primary_dark)); } } @Override public void onResume() { SharedPreferences ss = getSharedPreferences("prefs", Context.MODE_PRIVATE); String json = ss.getString("apps", null); if (json != null) { // deserialize list of SmartcardApp Gson gson = new Gson(); Type collectionType = new TypeToken<ArrayList<SmartcardApp>>() { }.getType(); mApps = gson.fromJson(json, collectionType); } SmartcardApp app = mApps.get(mAppPos); mReadOnly = app.isReadOnly(); mName.setText(app.getName()); mAid.setText(app.getAid()); mType.check((app.getType() == SmartcardApp.TYPE_OTHER) ? R.id.radio_other : R.id.radio_payment); updateGroups(mApps.get(mAppPos).getGroups()); if (!mReadOnly) { mNote.setVisibility(View.GONE); } super.onResume(); } @Override public void onStop() { super.onStop(); if (mConfirmDeleteDialog != null) { mConfirmDeleteDialog.dismiss(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_app_view, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // handle read-only apps if (mReadOnly) { MenuItem editMenuItem = menu.findItem(R.id.menu_edit_app); editMenuItem.setVisible(false); MenuItem delMenuItem = menu.findItem(R.id.menu_delete_app); delMenuItem.setVisible(false); } return true; } private void updateGroups(HashSet<String> appGroups) { String grpText = getString(R.string.none); if (appGroups.size() == 0) { if (!mReadOnly) { grpText += " - " + getString(R.string.edit_to_add_groups); } } else if (appGroups.size() == 1) { grpText = appGroups.toString().replaceAll("[\\[\\]]", "");; if (!mReadOnly) { grpText += " - " + getString(R.string.edit_to_add_groups); } } else { grpText = appGroups.toString().replaceAll("[\\[\\]]", ""); grpText = grpText.replace(", ", ",\n"); } mGroups.setText(grpText); } @SuppressWarnings("deprecation") @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent i = NavUtils.getParentActivityIntent(this); NavUtils.navigateUpTo(this, i); return true; case R.id.menu_edit_app: editApp(); return true; case R.id.menu_copy_app: copyApp(); return true; case R.id.menu_delete_app: showDialog(DIALOG_CONFIRM_DELETE); return true; case R.id.menu_select_app: selectApp(); return true; } return super.onOptionsItemSelected(item); } private void editApp() { Intent i = new Intent(this, AppEditActivity.class); i.setAction(ACTION_EDIT_APP); i.putExtra(EXTRA_APP_POS, mAppPos); startActivityForResult(i, REQUEST_EDIT_APP); } private void copyApp() { Intent i = new Intent(this, AppEditActivity.class); i.setAction(ACTION_COPY_APP); i.putExtra(EXTRA_APP_POS, mAppPos); if (getIntent().getBooleanExtra(EXTRA_SELECT, false)) { i.putExtra(EXTRA_SELECT, true); } startActivityForResult(i, REQUEST_COPY_APP); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_EDIT_APP || requestCode == REQUEST_COPY_APP) { if (resultCode == RESULT_OK) { // copy-to app view created successfully, and it // replaces this copy-from app view in the stack finish(); } } } private void deleteApp() { // adjust selected position for app select mode if (mSelectedAppPos == mAppPos) { mSelectedAppPos = 0; } else if (mSelectedAppPos > mAppPos) { mSelectedAppPos--; } // remove app from list SmartcardApp app = mApps.remove(mAppPos); HashSet<String> groups = app.getGroups(); // only bother to adjust groups if app was assigned to // more than the default other/payment group if (groups.size() > 1) { for (String group : groups) { if (Util.isGroupEmpty(group, mApps)) { removeGroup(group); } } } writePrefs(); finish(); } private void selectApp() { mSelectedAppPos = mAppPos; mEditor.putInt("selected_app_pos", mSelectedAppPos); mEditor.commit(); new Launcher(this).launch(Launcher.TEST_MODE_APP_SELECT, true, true); finish(); } @SuppressWarnings("deprecation") @Override protected Dialog onCreateDialog(int id) { //AlertDialog.Builder builder = new AlertDialog.Builder( // this, R.style.dialog); AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(this); //final LayoutInflater li = getLayoutInflater(); Dialog dialog = null; switch (id) { case DIALOG_CONFIRM_DELETE: //final View view = li.inflate(R.layout.dialog_confirm_delete, null); builder//.setView(view) .setCancelable(true) .setIcon(R.drawable.ic_action_delete_gray) .setTitle(mName.getText()) .setMessage(R.string.confirm_delete_app) .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { deleteApp(); } }) .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); mConfirmDeleteDialog = (AlertDialog) builder.create(); dialog = mConfirmDeleteDialog; break; } return dialog; } private void writePrefs() { // serialize list of apps Gson gson = new Gson(); String json = gson.toJson(mApps); mEditor.putString("apps", json); // selected app in app select mode mEditor.putInt("selected_app_pos", mSelectedAppPos); // serialize hash set of user-added groups json = gson.toJson(mUserGroups); mEditor.putString("groups", json); // selected group in batch select mode mEditor.putInt("selected_grp_pos", mSelectedGrpPos); // expanded group in app browse mEditor.putInt("expanded_grp_pos", mExpandedGrpPos); mEditor.commit(); } private void removeGroup(String name) { // remove from saved hash set mUserGroups.remove(name); // adjust selected group position indices as needed if (name.equals(mSelectedGrpName)) { // always guaranteed at least two groups: other and payment mSelectedGrpName = (mSelectedGrpPos == 0) ? mSortedAllGroups.get(1) : mSortedAllGroups.get(0); mSelectedGrpPos = 0; } else if (name.compareTo(mSelectedGrpName) < 0) { mSelectedGrpPos--; mSelectedGrpName = mSortedAllGroups.get(mSelectedGrpPos); } // adjust expanded group position index as needed if (name.equals(mExpandedGrpName)) { // no expanded group; all collapsed mExpandedGrpPos = -1; mExpandedGrpName = ""; } else if (name.compareTo(mExpandedGrpName) < 0) { mExpandedGrpPos--; mExpandedGrpName = mSortedAllGroups.get(mExpandedGrpPos); } // remove from sorted list mSortedAllGroups.remove(name); } }
gpl-3.0
marcosgreis/carcounter
src/frametask/delayer.hpp
1172
/* * Copyright (C) 2016 Marcos Goulart Reis. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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/>. */ #ifndef __TASKDELAYER_H__ #define __TASKDELAYER_H__ #include "frametask.hpp" namespace carcounter { class TaskDelayer : public FrameTask { public: TaskDelayer(const std::string &name, int delay) : FrameTask(name), _delay(delay) {}; TaskDelayer(int delay) : TaskDelayer("TaskDelayer", delay) {}; virtual void execute(); private: std::once_flag _flag; int _delay; }; } #endif // __TASKDELAYER_H__
gpl-3.0
eumesmoson/curso
node_modules/foreman/test/console-trim.test.js
1059
// Needed before requiring colors, otherwise its colorizers are no-ops. process.stdout.isTTY = true; var assert = require('chai').assert , util = require('util') , Console = require('../lib/console').Console , colors = require('../lib/colors') var red = colors.red('red') var blue = colors.blue('blue') var long = 'Roses are red, Violets are blue, this string is long, and should be trimmed, too!' var colorLong = long.replace('red', red).replace('blue', blue); assert.lengthOf(long, 81) assert.lengthOf(colorLong, 99) assert.equal(Console.trim(colorLong, 50), Console.trim(long, 50)) assert.equal(Console.trim(colorLong, long.length), colorLong, 'trim() should leave colors intact if no trimming is performed') var indented = ' indented'; assert.equal(Console.trim(indented, 100), indented, 'trim() should always preserve leading whitespace') var padded = ' padded '; var trimmed = ' padded'; assert.equal(Console.trim(padded, 100), trimmed, 'trim() should always trim trailing whitespace')
gpl-3.0
AtiwadkarAjinkya/600-Interview-Programs
EvenFibonnaciSum.java
719
package comsciers.com; import java.util.Scanner; public class EvenFibonnaciSum { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Enter Upper Limit"); int limit = sc.nextInt(); int f1,f2=0,f3=1; int sum = 0; System.out.println("Fibonacci Series\n"); for(int i=0; i<limit; i++){ f1=f2; f2=f3; f3=f1 + f2; System.out.print(f3+" "); if(f3%2==0) { sum +=f3; } } System.out.println("\nSum of Even Fibonacci Numbers is "+sum); } }
gpl-3.0
gdimitriu/chappy
chappy-interfaces/src/main/java/chappy/interfaces/markers/ISystemLogsPersistence.java
992
/** Copyright (c) 2017 Gabriel Dimitriu All rights reserved. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. This file is part of chappy project. Chappy 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. Chappy 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 Chappy. If not, see <http://www.gnu.org/licenses/>. */ package chappy.interfaces.markers; /** * Marker for system persistence. * @author Gabriel Dimitriu * */ public interface ISystemLogsPersistence { }
gpl-3.0
h-adachi/WinGame
WinGame/SceneGame.cpp
401
#include "SceneTitle.h" #include "SceneGame.h" void SceneGame::Enter(InputList& inputs) { inputs.Clear(); inputs.Append("enter", VK_RETURN); } void SceneGame::Exit() { } IScene* SceneGame::Update(InputList& inputs) { IScene* scene = this; if (inputs.Get("enter").isPress()) { scene = new SceneTitle(); } return scene; } void SceneGame::Draw(HDC hdc) { TextOut(hdc, 0, 0, L"Game", 4); }
gpl-3.0
chenc4/RedwoodHQ
project_templates/java_project_appium/src/utils/SwipeAndFindElement.java
3120
package utils; import java.util.HashMap; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.SwipeElementDirection; /** * Created by dinkark on 13-Oct-2016 */ public class SwipeAndFindElement { public static MobileElement find(HashMap<String, String> params, AppiumDriver<MobileElement> driver) { int noOfTimes = Integer.parseInt(params.get(Constants.NO_OF_TIMES)); MobileElement element = null; HashMap<String, String> searchElementParams = new HashMap<>(); searchElementParams.put(Constants.ID, params.get(Constants.SEARCHING_ELEMENT_ID)); searchElementParams.put(Constants.ID_TYPE, params.get(Constants.SEARCHING_ELEMENT_ID_TYPE)); searchElementParams.put(Constants.APP_TYPE, params.get(Constants.SEARCHING_ELEMENT_APP_TYPE)); MobileElement swipeElement = Elements.find(params, driver); for (int i = 0; i < noOfTimes; i++) { switch (params.get(Constants.DIRECTION)) { case Constants.UP: if (params.get(Constants.APP_TYPE).equals(Constants.ANDROID)) { swipeElement.swipe(SwipeElementDirection.UP, (int) (0.25 * swipeElement.getSize().getHeight()), (int) (0.25 * swipeElement.getSize().getHeight()), 500); } else { SwipeElement.swipeUpSlow(swipeElement, driver); } break; case Constants.DOWN: if (params.get(Constants.APP_TYPE).equals(Constants.ANDROID)) { swipeElement.swipe(SwipeElementDirection.DOWN, (int) (0.25 * swipeElement.getSize().getHeight()), (int) (0.25 * swipeElement.getSize().getHeight()), 500); } else { SwipeElement.swipeDownSlow(swipeElement, driver); } break; case Constants.RIGHT: if (params.get(Constants.APP_TYPE).equals(Constants.ANDROID)) { swipeElement.swipe(SwipeElementDirection.RIGHT, (int) (0.25 * swipeElement.getSize().getWidth()), (int) (0.25 * swipeElement.getSize().getWidth()), 500); } else { SwipeElement.swipeRightSlow(swipeElement, driver); } break; case Constants.LEFT: if (params.get(Constants.APP_TYPE).equals(Constants.ANDROID)) { swipeElement.swipe(SwipeElementDirection.LEFT, (int) (0.25 * swipeElement.getSize().getWidth()), (int) (0.25 * swipeElement.getSize().getWidth()), 500); } else { SwipeElement.swipeLeftSlow(swipeElement, driver); } break; default: if (params.get(Constants.APP_TYPE).equals(Constants.ANDROID)) { swipeElement.swipe(SwipeElementDirection.UP, (int) (0.25 * swipeElement.getSize().getHeight()), (int) (0.25 * swipeElement.getSize().getHeight()), 500); } else { SwipeElement.swipeUpSlow(swipeElement, driver); } break; } if (isElementPresent(searchElementParams, driver)) { if (Elements.find(searchElementParams, driver).isDisplayed()) { element = Elements.find(searchElementParams, driver); break; } } } return element; } public static boolean isElementPresent(HashMap<String, String> searchElementParams, AppiumDriver<MobileElement> driver) { boolean size = Elements.findAll(searchElementParams, driver).size() > 0; return size; } }
gpl-3.0
jackey-qiu/genx_pc_qiu
MPI_run_files/GenX_run_multiple_mpi_new_3_raxr_BETA.py
24789
#!/usr/bin/python from mpi4py import MPI import numpy as np from numpy import * from datetime import datetime genxpath = '/home/qiu05/genx_pc_qiu' import sys,os import time sys.path.insert(0,genxpath) #sys.path.append(genxpath+'/geometry_modules') import model, time, fom_funcs import diffev import filehandling as io from global_vars import * #import the global var split_jobs (either 1 for Model-dependent CTR/RAXR fit or 7 for Model-independent RAXR fit) ##new in version 2## #errro bar for each par will be calculated before program being halted ##new in version 3## #find the best control parameters (pop size:N, mutation constant:km, cross_over constant: kr, mutation propability:pf) and trial methods for fitting comm=MPI.COMM_WORLD size=comm.Get_size() rank=comm.Get_rank() #split the world comm into 7 local comms (split_job=7, that means each sub comm will deal with 3 RAXR spectra) comm_group=comm.Split(color=rank/(size/split_jobs),key=rank) size_group=comm_group.Get_size() rank_group=comm_group.Get_rank() spectras=[0,1,2]#each comm will deal with three spectras (there are 21 RAXR spectra in total) def find_boundary(n_process,n_jobs,rank): step_len=int(n_jobs/n_process) remainder=int(n_jobs%n_process) left,right=0,0 if rank<=remainder-1: left=rank*(step_len+1) right=(rank+1)*(step_len+1)-1 elif rank>remainder-1: left=remainder*(step_len+1)+(rank-remainder)*step_len right=remainder*(step_len+1)+(rank-remainder+1)*step_len-1 return left,right # Okay lets make it possible to batch script this file ... if len(sys.argv) !=3: print sys.argv print 'Wrong number of arguments to %s'%sys.argv[0] print 'Usage: %s infile.gx'%sys.argv[0] sys.exit(1) infile = sys.argv[1] #pop_num=int(sys.argv[2]) pop_num=size/split_jobs*2 #there are only 5 independent fit pars for model fit, so you dont need a large population size (30-50 should be fine) t_start_0=datetime.now() ############################################################################### # Parameter section - modify values according to your needs ############################################################################### # # To leave any of the control parameters unchanged with respect to the ones in # the loaded .gx file, you need to comment out the corresponding variables # below # List of repetition numbers. # For each number in the list, one run will be performed for each distinct com- # bination of km, kr, and fom parameters (see below). The run files will be # named according to these numbers # e.g. range(5) --> [0,1,2,3,4] (total of 5 repetitions named 0-4) # range(5,10) --> [5,6,7,8,9] (total of 5 repetitions starting with 5) # [1] --> [1] (one iteration with index 1) #iter_list = range(5) #print "the run starts @ %s"%(str(datetime.now())) iter_list = [1] ##################### # figure of merit (FOM) to use # needs to be a list of strings, valid names are: # 'R1' # 'R2' # 'log' # 'diff' # 'sqrt' # 'chi2bars' # 'chibars' # 'logbars' # 'sintth4' # e.g.: fom_list = ['log','R1'] # performs all repetitions for 'log' and 'R1' #fom_list = ['R1_weighted'] fom_list = ['diff'] # diffev control parameters # needs to be a list of parameters combinations to use. # example: # krkm_list = [[0.7,0.8], [0.9,0.95]] # will run fits with these parameter combinations: # 1. km = 0.7, kr = 0.8 # 2. km = 0.9, kr = 0.95 #krkm_list = [[0.1,0.9],[0.3,0.9],[0.5,0.9],[0.7,0.9],[0.9,0.9]] krkmPf_list =[[0.9,0.9,0.8]] # NOT YET WORKING!!! create_trial = ['best_1_bin']#'best_1_bin','rand_1_bin',#'best_either_or','rand_either_or' # Population size use_pop_mult = False # absolute (F) or relative (T) population size pop_mult = 8 # if use_pop_mult = True, populatio multiplier pop_size = pop_num # if use_pop_mult = False, population size # Generations use_max_generations = True # absolute (T) or relative (F) maximum gen. max_generations=200 # if use_max_generations = True max_generation_mult = 6 # if use_max_generations = False # Parallel processing use_parallel_processing = True # Fitting use_start_guess = False use_boundaries = True use_autosave = True autosave_interval = 50 max_log = 600000 # Sleep time between generations sleep_time = 0.000001 ############################################################################### # End of parameter section #------------------------- # DO NOT MODIFY CODE BELOW ############################################################################### mod = model.Model() config = io.Config() opt = diffev.DiffEv() def autosave(): #print 'Updating the parameters' mod.parameters.set_value_pars(opt.best_vec) io.save_gx(outfile, mod, opt, config) opt.set_autosave_func(autosave) par_list = [(trial,f,rm,i) for trial in create_trial for f in fom_list for rm in krkmPf_list \ for i in iter_list] tmp_fom=[] tmp_trial_vec=[] tmp_pop_vec=[] tmp_fom_vec=[] for pars in par_list: trial=pars[0] fom = pars[1] km = pars[2][0] # km kr = pars[2][1] # kr pf=pars[2][2] iter = pars[3] # Load the model ... if rank==0: print 'Loading model %s...'%infile io.load_gx(infile, mod, opt, config) for spectra in spectras: # Simulate, this will also compile the model script if rank==0: print 'Simulating model...' mod.simulate() # Setting up the solver eval('mod.set_fom_func(fom_funcs.%s)' % fom) # Lets set the solver parameters (same for all processors): try: opt.set_create_trial(trial) except: print 'Warning: create_trial is not defined in script.' try: opt.set_kr(kr) except: print 'Warning: kr is not defined in script.' try: opt.set_km(km) except : print 'Warning: km is not defined in script.' try: opt.pf=pf except: print 'Warning; pf is not defined in script.' try: opt.set_use_pop_mult(use_pop_mult) except: print 'Warning: use_pop_mult is not defined in script.' try: opt.set_pop_mult(pop_mult) except: print 'Warning: pop_mult is not defined in script.' try: opt.set_pop_size(pop_size) except: print 'Warning: pop_size is not defined in script.' try: opt.set_use_max_generations(use_max_generations) except: print 'Warning: use_max_generations is not defined in script.' try: opt.set_max_generations(max_generations) except: print 'Warning: max_generations is not defined in script.' try: opt.set_max_generation_mult(max_generation_mult) except: print 'Warning: max_generation_mult is not defined in script.' try: opt.set_use_parallel_processing(use_parallel_processing) except: print 'Warning: use_parallel_processing is not defined in script.' try: opt.set_use_start_guess(use_start_guess) except: print 'Warning: use_start_guess is not defined in script.' try: opt.set_use_boundaries(use_boundaries) except: print 'Warning: use_boundaries is not defined in script.' try: opt.set_use_autosave(use_autosave) except: print 'Warning: use_autosave is not defined in script.' try: opt.set_autosave_interval(autosave_interval) except: print 'Warning: autosave_interval is not defined in script.' try: opt.set_max_log(max_log) except: print 'Warning: max_log is not defined in script.' try: opt.set_sleep_time(sleep_time) except: print 'Warning: sleep_time is not defined in script.' if rank==0:#rank 0 will be in charge of all I/O print 'doing spectra '+str(spectra) #set the fit parameters and the data to be fit for ii in range(mod.parameters.get_len_rows()):#clear the fit parameters first mod.parameters.set_value(ii,2,False) for each in mod.data.items:#clear to-be-used datasets each.use=False for ii in range(mod.parameters.get_len_rows()):#set the fit parameters each=mod.parameters.get_value(ii,0) if each=='rgh_raxs.setA'+str(rank/(size/split_jobs)*len(spectras)+spectra+1): if "\"MI\"" in mod.get_script() or "\'MI\'" in mod.get_script():#if it is a model-independent fit [mod.parameters.set_value(ii+i,2,True) for i in range(5)] elif "\"MD\"" in mod.get_script() or "\'MD\'" in mod.get_script():#if it is a model-dependent fit [mod.parameters.set_value(ii+i,2,True) for i in range(3)] mod.data.items[(rank/(size/split_jobs))*len(spectras)+1+spectra].use=True#set the to-be-used dataset (first RAXR dataset is the second dataset) comm_group.Barrier()#wait for every processoer to have the same setup before moving on # Sets up the fitting ... if rank==0:print 'Setting up the optimizer...' opt.reset() # <--- Add this line opt.init_fitting(mod) #rank 0 is in charge of generating of pop vectors, and distribute to the other processors if rank_group==0: opt.pop_vec = [opt.par_min + np.random.rand(opt.n_dim)*(opt.par_max -\ opt.par_min) for i in range(opt.n_pop)] tmp_pop_vec=opt.pop_vec tmp_pop_vec=comm_group.bcast(tmp_pop_vec,root=0) opt.pop_vec=tmp_pop_vec if opt.use_start_guess: opt.pop_vec[0] = array(opt.start_guess) opt.trial_vec = [zeros(opt.n_dim) for i in range(opt.n_pop)] opt.best_vec = opt.pop_vec[0] opt.init_fom_eval() options_float = ['km', 'kr', 'pf','pop mult', 'pop size',\ 'max generations', 'max generation mult',\ 'sleep time', 'max log elements',\ 'autosave interval',\ 'parallel processes', 'parallel chunksize', 'allowed fom discrepancy'] set_float = [opt.km, opt.kr,opt.pf, opt.pop_mult,\ opt.pop_size,\ opt.max_generations,\ opt.max_generation_mult,\ opt.sleep_time,\ opt.max_log, \ opt.autosave_interval,\ opt.processes,\ opt.chunksize,\ opt.fom_allowed_dis ] options_bool = ['use pop mult', 'use max generations', 'use start guess', 'use boundaries', 'use parallel processing', 'use autosave', ] set_bool = [ opt.use_pop_mult, opt.use_max_generations, opt.use_start_guess, opt.use_boundaries, opt.use_parallel_processing, opt.use_autosave, ] # Make sure that the config is set if config: # Start witht the float values for index in range(len(options_float)): try: val = config.set('solver', options_float[index],\ set_float[index]) except io.OptionError, e: print 'Could not locate save solver.' +\ options_float[index] # Then the bool flags for index in range(len(options_bool)): try: val = config.set('solver',\ options_bool[index], set_bool[index]) except io.OptionError, e: print 'Could not write option solver.' +\ options_bool[index] try: config.set('solver', 'create trial',\ opt.get_create_trial()) except io.OptionError, e: print 'Could not write option solver.create trial' else: print 'Could not write config to file' ### end of block: save config # build outfile names outfile = infile.replace('.gx',str(rank/(size/split_jobs))+'_ran.gx') if rank_group==0: print 'Saving the initial model to %s'%outfile io.save_gx(outfile, mod, opt, config) if rank==0: print '' print 'Settings:' print '---------' print 'Number of fit parameters = %s' % len(opt.best_vec) print 'FOM function = %s' % mod.fom_func.func_name print '' print 'opt.km = %s' % opt.km print 'opt.kr = %s' % opt.kr print 'opt.create_trial = %s' % opt.create_trial.im_func print '' print 'opt.use_parallel_processing = %s' % opt.use_parallel_processing print '' print 'opt.use_max_generations = %s' % opt.use_max_generations print 'opt.max_generation_mult = %s' % opt.max_generation_mult print 'opt.max_generations = %s' % opt.max_generations print 'opt.max_gen = %s' % opt.max_gen print 'opt.max_log = %s' % opt.max_log print '' print 'opt.use_start_guess = %s' % opt.use_start_guess print 'opt.use_boundaries = %s' % opt.use_boundaries print 'opt.use_autosave = %s' % opt.use_autosave print 'opt.autosave_interval = %s' % opt.autosave_interval print '' print 'opt.pop_size = %s' % opt.pop_size print 'opt.use_pop_mult = %s' % opt.use_pop_mult print 'opt.pop_mult = %s' % opt.pop_mult print 'opt.n_pop = %s' % opt.n_pop print '' print '--------' print '' # To start the fitting print 'Fitting starting...' if rank_group==0:t1 = time.time() if rank==0:opt.text_output('Calculating start FOM ...') opt.running = True opt.error = False opt.n_fom = 0 # Old leftovers before going parallel, rank 0 calculate fom vec and distribute to the other processors left,right=find_boundary(size_group,len(opt.pop_vec),rank_group) tmp_fom_vec=[opt.calc_fom(vec) for vec in opt.pop_vec[left:right+1]] comm_group.Barrier() tmp_fom_vec=comm_group.gather(tmp_fom_vec,root=0) if rank_group==0: tmp_fom_list=[] for i in list(tmp_fom_vec): tmp_fom_list=tmp_fom_list+i tmp_fom_vec=tmp_fom_list tmp_fom_vec=comm_group.bcast(tmp_fom_vec,root=0) opt.fom_vec=tmp_fom_vec [opt.par_evals.append(vec, axis = 0)\ for vec in opt.pop_vec] [opt.fom_evals.append(vec) for vec in opt.fom_vec] best_index = argmin(opt.fom_vec) opt.best_vec = copy(opt.pop_vec[best_index]) opt.best_fom = opt.fom_vec[best_index] if len(opt.fom_log) == 0: opt.fom_log = r_[opt.fom_log,\ [[len(opt.fom_log),opt.best_fom]]] # Flag to keep track if there has been any improvemnts # in the fit - used for updates opt.new_best = True if rank==0:opt.text_output('Going into optimization ...') opt.plot_output(opt) opt.parameter_output(opt) comm_group.Barrier() t_mid=datetime.now() gen = opt.fom_log[-1,0] if rank_group==0: mean_speed=0 speed_inc=0. for gen in range(int(opt.fom_log[-1,0]) + 1, opt.max_gen\ + int(opt.fom_log[-1,0]) + 1): if opt.stop: break if rank_group==0: t_start = time.time() speed_inc=speed_inc+1. opt.init_new_generation(gen) # Create the vectors who will be compared to the # population vectors #here rank 0 create trial vector and then broacast to the other processors if rank_group==0: [opt.create_trial(index) for index in range(opt.n_pop)] tmp_trial_vec=opt.trial_vec else: tmp_trial_vec=0 tmp_trial_vec=comm_group.bcast(tmp_trial_vec,root=0) comm_group.Barrier() opt.trial_vec=tmp_trial_vec #each processor only do a segment of trial vec opt.eval_fom() tmp_fom=opt.trial_fom comm_group.Barrier() #collect foms and reshape them and set the completed tmp_fom to trial_fom tmp_fom=comm_group.gather(tmp_fom,root=0) if rank_group==0: tmp_fom_list=[] for i in list(tmp_fom): tmp_fom_list=tmp_fom_list+i tmp_fom=tmp_fom_list tmp_fom=comm_group.bcast(tmp_fom,root=0) opt.trial_fom=np.array(tmp_fom).reshape(opt.n_pop,) # Calculate the fom of the trial vectors and update the population [opt.update_pop(index) for index in range(opt.n_pop)] # Add the evaluation to the logging [opt.par_evals.append(vec, axis = 0)\ for vec in opt.trial_vec] [opt.fom_evals.append(vec) for vec in opt.trial_fom] # Add the best value to the fom log opt.fom_log = r_[opt.fom_log,\ [[len(opt.fom_log),opt.best_fom]]] if gen==1: # Let the model calculate the simulation of the best. sim_fom = opt.calc_sim(opt.best_vec) # Sanity of the model does the simualtions fom agree with # the best fom if rank_group==0: if abs(sim_fom - opt.best_fom) > opt.fom_allowed_dis: opt.text_output('Disagrement between two different fom evaluations') opt.error = ('The disagreement between two subsequent evaluations is larger than %s. Check the model for circular assignments.'%opt.fom_allowed_dis) break # Update the plot data for any gui or other output opt.plot_output(opt) opt.parameter_output(opt) # Let the optimization sleep for a while time.sleep(opt.sleep_time) # Time measurent to track the speed if rank_group==0: t = time.time() - t_start if t > 0: speed = opt.n_pop/t mean_speed=mean_speed+speed else: speed = 999999 if rank==0: opt.text_output('FOM: %.3f Generation: %d Speed: %.1f @ rank 0'%\ (opt.best_fom, gen, speed)) opt.new_best = False # Do an autosave if activated and the interval is coorect if rank_group==0 and gen%opt.autosave_interval == 0 and opt.use_autosave: opt.autosave() if gen%opt.autosave_interval==0: std_val=std(opt.fom_log[:,1][-200:]) if std_val<0.00001: if rank_group==0: opt.text_output('std='+str(std_val)) break else: if rank_group==0: opt.text_output('std='+str(std_val)+'at local comm of'+str(rank/split_jobs)) #calculate the error bar for parameters n_elements = len(opt.start_guess) #print 'Number of elemets to calc errobars for ', n_elements cum_N=0 for index in range(n_elements): # calculate the error # TODO: Check the error bar buisness again and how to treat # Chi2 #print "senor",self.fom_error_bars_level try: (error_low, error_high) = opt.calc_error_bar(index, 1.05) except: break error_str = '(%.3e, %.3e)'%(error_low, error_high) while mod.parameters.get_value(index+cum_N,2)!=True: cum_N=cum_N+1 mod.parameters.set_value(index+cum_N,5,error_str) opt.autosave() if rank_group==0: if not opt.error: opt.text_output('Stopped at Generation: %d after %d fom evaluations...'%(gen, opt.n_fom)) # Lets clean up and delete our pool of workers opt.eval_fom = None # Now the optimization has stopped opt.running = False # Run application specific clean-up actions opt.fitting_ended(opt) t_end=datetime.now() if rank_group==0: t2 = time.time() print 'Fitting finsihed for comm'+str(rank/(size/split_jobs))+'!' print 'Time to fit: ', (t2-t1)/60., ' min' print 'Updating the parameters' mod.parameters.set_value_pars(opt.best_vec) if rank_group==0: #calculate the error bar for parameters n_elements = len(opt.start_guess) #print 'Number of elemets to calc errobars for ', n_elements cum_N=0 for index in range(n_elements): # calculate the error # TODO: Check the error bar buisness again and how to treat # Chi2 #print "senor",self.fom_error_bars_level try: (error_low, error_high) = opt.calc_error_bar(index, 1.05) except: break error_str = '(%.3e, %.3e)'%(error_low, error_high) while mod.parameters.get_value(index+cum_N,2)!=True: cum_N=cum_N+1 mod.parameters.set_value(index+cum_N,5,error_str) io.save_gx(outfile, mod, opt, config) #t_mid-t_start_0 is the headover time before fitting starts, this headover time depend on # of cups used and can be up to 2hr in the case of using 100 cup chips if rank==0: print "comm0 run starts @",str(t_start_0) print "comm0 fitting starts @",str(t_mid) print "comm0 run stops @",str(t_end) print "comm0 headover time is ",str(t_mid-t_start_0) print "comm0 fitting time is ",str(t_end-t_mid) print 'comm0 Fitting sucessfully finished with mean speed of ',mean_speed/speed_inc else: pass comm.Barrier() par_data=mod.parameters.data par_data_together=comm.gather(par_data,root=0) #combine best fit pars from different outfiles to one single gx file if rank==0: mod_temp = model.Model() config_temp = io.Config() opt_temp = diffev.DiffEv() io.load_gx(infile, mod_temp, opt_temp, config_temp) mod_sub_set=par_data_together[0:-1:size/split_jobs] for each_mod in mod_sub_set: i=mod_sub_set.index(each_mod) start_temp,end_temp=None,None for ii in range(len(each_mod)):#set the fit parameters each=each_mod[ii][0] if each=='rgh_raxs.setA'+str(i*len(spectras)+1):start_temp=ii else:pass if each=='rgh_raxs.setA'+str(i*len(spectras)+spectras[-1]+1): end_temp=ii+4 for grid_index in range(start_temp,end_temp+1): for k in range(6): if k==2: mod_temp.parameters.set_value(grid_index,k,False) else: mod_temp.parameters.set_value(grid_index,k,each_mod[grid_index][k]) break io.save_gx(infile.replace(".gx","combined_ran.gx"),mod_temp,opt,config) #remove temp outfiles only the combined file will be kept if rank_group==0: os.remove(infile.replace('.gx',str(rank/(size/split_jobs))+'_ran.gx')) else: pass comm.Barrier() sys.exit()
gpl-3.0
dleuenbe/pfila2017
client/src/app/+admin/password-change-confirmation/password-change-confirmation.component.ts
356
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-password-change-confirmation', templateUrl: './password-change-confirmation.component.html', styleUrls: ['./password-change-confirmation.component.scss'] }) export class PasswordChangeConfirmationComponent implements OnInit { constructor() { } ngOnInit() { } }
gpl-3.0
MyCoRe-Org/mycore
mycore-webtools/src/main/java/org/mycore/webtools/processing/socket/impl/MCRMessageType.java
922
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe 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. * * MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.webtools.processing.socket.impl; enum MCRMessageType { error, registry, addCollection, removeCollection, updateProcessable, updateCollectionProperty }
gpl-3.0
hohohahi/Bottle_CloudServer
src/main/java/com/shishuo/cms/entity/Comment.java
2783
/* * Copyright © 2013 Changsha Shishuo Network Technology Co., Ltd. All rights reserved. * 长沙市师说网络科技有限公司 版权所有 * http://www.shishuo.com */ package com.shishuo.cms.entity; import java.util.Date; import com.shishuo.cms.constant.CommentConstant; /** * 评论实体 * * @author Administrator * */ public class Comment { /** * 评论Id */ private long commentId; /** * 所属用户Id */ private long userId; /** * 父亲Id */ private long fatherId; /** * 所属种类的Id */ private long kindId; /** * 所属种类 */ private CommentConstant.kind kind; /** * 评论名称 */ private String name; /** * 所属用户email */ private String email; /** * 评论者网址 */ private String url; /** * 评论内容 */ private String content; /** * 所属Ip */ private String ip; /** * 所属phone */ private String phone; /** * 审核状态 */ private CommentConstant.Status status; /** * 时间 */ private Date createTime; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public long getCommentId() { return commentId; } public void setCommentId(long commentId) { this.commentId = commentId; } public long getKindId() { return kindId; } public void setKindId(long kindId) { this.kindId = kindId; } public CommentConstant.kind getKind() { return kind; } public void setKind(CommentConstant.kind kind) { this.kind = kind; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public long getFatherId() { return fatherId; } public void setFatherId(long fatherId) { this.fatherId = fatherId; } public CommentConstant.Status getStatus() { return status; } public void setStatus(CommentConstant.Status status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
gpl-3.0
trackplus/Genji
src/main/java/com/aurel/track/persist/TProjectPeer.java
30756
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * 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/>. */ /* $Id:$ */ package com.aurel.track.persist; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.aurel.track.util.IntegerStringBean; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.apache.torque.TorqueException; import org.apache.torque.util.Criteria; import org.apache.torque.util.Criteria.Criterion; import com.aurel.track.beans.TProjectBean; import com.aurel.track.beans.TSystemStateBean; import com.aurel.track.dao.ProjectDAO; import com.aurel.track.fieldType.constants.BooleanFields; import com.aurel.track.fieldType.constants.SystemFields; import com.aurel.track.util.GeneralUtils; import com.workingdogs.village.DataSetException; import com.workingdogs.village.Record; import com.workingdogs.village.Value; /** * */ public class TProjectPeer extends com.aurel.track.persist.BaseTProjectPeer implements ProjectDAO { private static final long serialVersionUID = -9027581282625320080L; private static final Logger LOGGER = LogManager.getLogger(TProjectPeer.class); private static Class[] deletePeerClasses = { TWorkItemPeer.class, TReleasePeer.class, //overrided doDelete TProjectCategoryPeer.class, //overrided doDelete TClassPeer.class, //overrided doDelete TAccessControlListPeer.class, TReportLayoutPeer.class, TProjectAccountPeer.class, TProjectReportRepositoryPeer.class, TVersionControlParameterPeer.class, TFieldConfigPeer.class, //overrided doDelete TFieldPeer.class, //overrided doDelete TScreenConfigPeer.class, TScreenPeer.class, TInitStatePeer.class, TEventPeer.class, TQueryRepositoryPeer.class, //overrided doDelete TNotifySettingsPeer.class, TExportTemplatePeer.class, TScriptsPeer.class, TFilterCategoryPeer.class, TReportCategoryPeer.class, TDashboardScreenPeer.class, TWorkflowConnectPeer.class, TOrgProjectSLAPeer.class, TMailTemplateConfigPeer.class, TMailTextBlockPeer.class //lastly delete the project itself //TProjectPeer.class, }; private static String[] deleteFields = { TWorkItemPeer.PROJECTKEY, TReleasePeer.PROJKEY, TProjectCategoryPeer.PROJKEY, TClassPeer.PROJKEY, TAccessControlListPeer.PROJKEY, TReportLayoutPeer.PROJECT, TProjectAccountPeer.PROJECT, TProjectReportRepositoryPeer.PROJECT, TVersionControlParameterPeer.PROJECT, TFieldConfigPeer.PROJECT, TFieldPeer.PROJECT, TScreenConfigPeer.PROJECT, TScreenPeer.PROJECT, TInitStatePeer.PROJECT, TEventPeer.PROJECT, TQueryRepositoryPeer.PROJECT, TNotifySettingsPeer.PROJECT, TExportTemplatePeer.PROJECT, TScriptsPeer.PROJECT, TFilterCategoryPeer.PROJECT, TReportCategoryPeer.PROJECT, TDashboardScreenPeer.PROJECT, TWorkflowConnectPeer.PROJECT, TOrgProjectSLAPeer.PROJECT, TMailTemplateConfigPeer.PROJECT, TMailTextBlockPeer.PROJECT //lastly delete the project itself //TProjectPeer.PKEY }; /** * Loads a project by primary key * @param objectID * @return */ @Override public TProjectBean loadByPrimaryKey(Integer objectID) { TProject tProject = null; try { tProject = retrieveByPK(objectID); } catch(Exception e) { LOGGER.debug("Loading of a project by primary key " + objectID + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } if (tProject!=null) { return tProject.getBean(); } return null; } /** * Gets an projectBean by label * @param label * @return */ @Override public TProjectBean loadByLabel(String label) { List<TProject> torqueList = null; Criteria crit = new Criteria(); crit.add(LABEL, label); try { torqueList = doSelect(crit); } catch (Exception e) { LOGGER.error("Loading the project by label " + label + " failed with " + e.getMessage()); return null; } if (torqueList==null || torqueList.isEmpty()) { return null; } return ((TProject)torqueList.get(0)).getBean(); } /** * Gets a projectBean by prefix * @param prefix * @return */ @Override public List<TProjectBean> loadByPrefix(String prefix) { Criteria crit = new Criteria(); crit.add(PREFIX, prefix); try { return convertTorqueListToBeanList(doSelect(crit)); } catch (Exception e) { LOGGER.error("Loading the project by prefix " + prefix + " failed with " + e.getMessage()); return null; } } /** * Loads the private project for the person * @param personID * @return */ @Override public boolean hasPrivateProject(Integer personID) { List<TProject> torqueList = null; Criteria crit = new Criteria(); //the negative projectType is for private projects crit.add(PROJECTTYPE, 0, Criteria.LESS_THAN); crit.add(DEFOWNER, personID); try { torqueList = doSelect(crit); } catch (Exception e) { LOGGER.error("Loading the private project for person " + personID + " failed with " + e.getMessage()); return true; } return torqueList!=null && !torqueList.isEmpty(); } /** * Loads the private project for the person * @param personID * @return */ @Override public List<TProjectBean> getPrivateProject(Integer personID) { Criteria crit = new Criteria(); //the negative projectType is for private projects crit.add(PROJECTTYPE, 0, Criteria.LESS_THAN); crit.add(DEFOWNER, personID); try { return convertTorqueListToBeanList(doSelect(crit)); } catch (Exception e) { LOGGER.error("Loading the private project for person " + personID + " failed with " + e.getMessage()); return null; } } /** * Gets the projectBeans by uuid list * @param uuids * @return */ @Override public List<TProjectBean> loadByUUIDs(List<String> uuids) { return loadByFieldValues(uuids, TPUUID); } /** * Loads a projectBean list by a project type * @param projectTypeID * @return */ @Override public List<TProjectBean> loadByProjectType(Integer projectTypeID) { Criteria crit = new Criteria(); crit.add(PROJECTTYPE, projectTypeID); crit.add(PKEY, 0, Criteria.GREATER_THAN); try { return convertTorqueListToBeanList(doSelect(crit)); } catch (Exception e) { LOGGER.error("Loading of projects by project type " + projectTypeID + " failed with " + e.getMessage()); return null; } } /** * Count the number of projects * @param all: if true count all projects (mainProjects parameter has no importance) * @param mainProjects: if all is false whether to count the main- or the sub-projects * @return */ @Override public int count(boolean all, boolean mainProjects) { String COUNT = "count(" + PKEY + ")"; Criteria crit = new Criteria(); if (!all) { if (mainProjects) { crit.add(PARENT, (Object)null, Criteria.ISNULL); } else { crit.add(PARENT, (Object)null, Criteria.ISNOTNULL); } } crit.addSelectColumn(COUNT); try { return ((Record) doSelectVillageRecords(crit).get(0)).getValue(1).asInt(); } catch (Exception e) { LOGGER.error("Counting the projects all " + all + " mainProjects " + mainProjects + " failed with " + e.getMessage()); return 0; } } /** * Gets the projectBeans by label list * @param labels * @return */ @Override public List<TProjectBean> loadByLabels(List<String> labels) { return loadByFieldValues(labels, LABEL); } /** * Load the projects by a String field * @param fieldValues * @param fieldName * @return */ private List<TProjectBean> loadByFieldValues(List<String> fieldValues, String fieldName) { if (fieldValues==null || fieldValues.isEmpty()) { return new LinkedList<TProjectBean>(); } List<TProject> projectBeanList = new LinkedList<TProject>(); List<List<String>> chunksList = GeneralUtils.getListOfStringChunks(fieldValues); if (chunksList==null) { return new LinkedList<TProjectBean>(); } Iterator<List<String>> iterator = chunksList.iterator(); int i = 0; while (iterator.hasNext()) { i++; List<String> chunk = iterator.next(); Criteria criteria = new Criteria(); criteria.addIn(fieldName, chunk); try { projectBeanList.addAll(doSelect(criteria)); } catch(Exception e) { LOGGER.error("Loading the projectBeans by " + fieldName + " and the chunk number " + i + " of length " + chunk.size() + " failed with " + e.getMessage(), e); } } return convertTorqueListToBeanList(projectBeanList); } /** * Loads a ProjectBean list by projectIDs * @param projectIDs * @return */ @Override public List<TProjectBean> loadByProjectIDs(List<Integer> projectIDs) { if (projectIDs==null || projectIDs.isEmpty()) { LOGGER.info("No projectIDs specified " + projectIDs); return new LinkedList<TProjectBean>(); } Criteria crit = new Criteria(); crit.addIn(PKEY, projectIDs); crit.addAscendingOrderByColumn(LABEL); try { return convertTorqueListToBeanList(doSelect(crit)); } catch (Exception e) { LOGGER.error("Loading of projects by IDs failed with " + e.getMessage()); return null; } } /** * Loads all projects * @return */ @Override public List<TProjectBean> loadAll() { List<TProject> torqueList = null; Criteria crit = new Criteria(); crit.addAscendingOrderByColumn(LABEL); crit.add(PKEY, 0, Criteria.GREATER_THAN); try { torqueList = doSelect(crit); } catch (Exception e) { LOGGER.error("Loading of all projects failed with " + e.getMessage()); return null; } return convertTorqueListToBeanList(torqueList); } /** * Loads all main projects (those without parent project) * @return */ @Override public List<TProjectBean> loadAllMainProjects() { Criteria crit = new Criteria(); crit.addAscendingOrderByColumn(LABEL); crit.add(PKEY, 0, Criteria.GREATER_THAN); crit.add(PARENT, (Object)null, Criteria.ISNULL); crit.addAscendingOrderByColumn(LABEL); try { return convertTorqueListToBeanList(doSelect(crit)); } catch (Exception e) { LOGGER.error("Loading of all main projects failed with " + e.getMessage()); return null; } } /** * Loads the main (no child) projects with specific states * @param states * @return */ @Override public List<TProjectBean> loadMainProjectsByStates(int[] states) { Criteria crit = new Criteria(); crit.add(PKEY, 0, Criteria.GREATER_THAN); crit.add(PARENT, (Object)null, Criteria.ISNULL); if (states!=null && states.length>0) { crit.addIn(STATUS, states); } crit.addAscendingOrderByColumn(LABEL); try { return convertTorqueListToBeanList(doSelect(crit)); } catch (Exception e) { if (states != null) { LOGGER.error("Loading the main projects with states " + states.length + " failed with " + e.getMessage()); } return null; } } /** * Loads all subprojects for a project * @param projectID * @return */ @Override public List<TProjectBean> loadSubrojects(Integer projectID) { Criteria crit = new Criteria(); crit.addAscendingOrderByColumn(LABEL); crit.add(PARENT, projectID); try { return convertTorqueListToBeanList(doSelect(crit)); } catch (Exception e) { LOGGER.error("Loading of all subprojects of the project " + projectID + " failed with " + e.getMessage()); return null; } } /** * Loads the subprojects with specific states for parent projects * @param projectID * @param states * @return */ @Override public List<TProjectBean> loadSubprojectsByParentsAndStates(List<Integer> projectIDs, int[] states) { List<TProjectBean> projectBeans = new LinkedList<TProjectBean>(); if (projectIDs==null || projectIDs.isEmpty()) { return projectBeans; } List<int[]> projectIDChunksList = GeneralUtils.getListOfChunks(projectIDs); if (projectIDChunksList==null) { return projectBeans; } Iterator<int[]> iterator = projectIDChunksList.iterator(); while (iterator.hasNext()) { Criteria criteria = new Criteria(); int[] projectIDChunk = iterator.next(); if (states!=null && states.length>0) { criteria.addIn(STATUS, states); } criteria.addIn(PARENT, projectIDChunk); criteria.addAscendingOrderByColumn(LABEL); try { projectBeans.addAll(convertTorqueListToBeanList(doSelect(criteria))); } catch(Exception e) { LOGGER.error("Loading the projectBeans by parent IDs " + projectIDs.size() + " and states " + states + " failed with " + e.getMessage()); } } return projectBeans; } /** * Loads the subprojects with specific states for a parent project * @param projectID * @param states * @return */ @Override public List<TProjectBean> loadSubprojectsByParentAndStates(Integer projectID, int[] states) { Criteria crit = new Criteria(); crit.add(PARENT, projectID); if (states!=null && states.length>0) { crit.addIn(STATUS, states); } crit.addAscendingOrderByColumn(LABEL); try { return convertTorqueListToBeanList(doSelect(crit)); } catch (Exception e) { LOGGER.error("Loading of all subprojects of the project " + projectID + " failed with " + e.getMessage()); return null; } } /** * Load all ProjectBeans except those closed * Should be called only be system admin * @return */ @Override public List<TProjectBean> loadProjectsByStateIDs(int[] stateIDs) { Criteria crit = new Criteria(); //states only when specified if (stateIDs != null && stateIDs.length>0) { crit.addIn(STATUS, stateIDs); } crit.add(PKEY, 0, Criteria.GREATER_THAN); crit.addAscendingOrderByColumn(LABEL); try { return convertTorqueListToBeanList(doSelect(crit)); } catch(Exception e) { LOGGER.error("Loading the active and inactive projects failed with " + e.getMessage()); return null; } } /** * Whether this project name already exists on the same level * @param name * @param parentProject * @param exceptProjectID * @param nonPrivate verify only the non private projects * @return */ @Override public boolean projectNameExists(String name, Integer parentProjectID, Integer exceptProjectID, boolean nonPrivate) { List<TProject> torqueList = null; Criteria crit = new Criteria(); crit.add(LABEL, name); if (parentProjectID==null) { crit.add(PARENT, (Object)null, Criteria.EQUAL); } else { crit.add(PARENT, parentProjectID, Criteria.EQUAL); } if (exceptProjectID!=null) { crit.add(PKEY, exceptProjectID, Criteria.NOT_EQUAL); } if (nonPrivate) { crit.addJoin(PROJECTTYPE, TProjectTypePeer.OBJECTID); crit.add(TProjectTypePeer.DEFAULTFORPRIVATE, (Object)BooleanFields.TRUE_VALUE, Criteria.NOT_EQUAL); } try { torqueList = doSelect(crit); } catch (Exception e) { LOGGER.error("Loading the projects by name " + name + " and parentProject " + parentProjectID + " failed with " + e.getMessage()); } return torqueList!=null && !torqueList.isEmpty(); } /** * Whether this project name already exists * @param prefix * @param parentProject * @param exceptProjectID * @param nonPrivate verify only the non private projects * @return */ @Override public boolean projectPrefixExists(String prefix, Integer parentProjectID, Integer exceptProjectID, boolean nonPrivate) { List<TProject> torqueList = null; Criteria crit = new Criteria(); crit.add(PREFIX, prefix); if (exceptProjectID!=null) { crit.add(PKEY, exceptProjectID, Criteria.NOT_EQUAL); } if (nonPrivate) { crit.addJoin(PROJECTTYPE, TProjectTypePeer.OBJECTID); crit.add(TProjectTypePeer.DEFAULTFORPRIVATE, (Object)BooleanFields.TRUE_VALUE, Criteria.NOT_EQUAL); } try { torqueList = doSelect(crit); } catch (Exception e) { LOGGER.error("Loading the projects by prefix " + prefix + " failed with " + e.getMessage()); } return torqueList!=null && !torqueList.isEmpty(); } /** * Loads a ProjectBean list by workItemKeys * @param workItemKeys * @return */ @Override public List<TProjectBean> loadByWorkItemKeys(int[] workItemIDs) { List<TProject> projects = new ArrayList<TProject>(); if (workItemIDs==null || workItemIDs.length==0) { return convertTorqueListToBeanList(projects); } List<int[]> workItemIDChunksList = GeneralUtils.getListOfChunks(workItemIDs); if (workItemIDChunksList==null) { return convertTorqueListToBeanList(projects); } Iterator<int[]> iterator = workItemIDChunksList.iterator(); while (iterator.hasNext()) { int[] workItemIDChunk = iterator.next(); Criteria criteria = new Criteria(); criteria.addJoin(BaseTWorkItemPeer.PROJECTKEY, PKEY); criteria.addIn(BaseTWorkItemPeer.WORKITEMKEY, workItemIDChunk); criteria.setDistinct(); try { projects.addAll(doSelect(criteria)); } catch(Exception e) { LOGGER.error("Loading the projectBeans by workItemKeys failed with " + e.getMessage()); } } //remove duplicate projects Set<Integer> projectIDs = new HashSet<Integer>(); for (Iterator<TProject> itrProject = projects.iterator(); itrProject.hasNext();) { TProject tProject = itrProject.next(); Integer projectID = tProject.getObjectID(); if (projectIDs.contains(projectID)) { itrProject.remove(); } else { projectIDs.add(projectID); } } return convertTorqueListToBeanList(projects); } /** * Loads a ProjectBean by workItemID * @param workItemIDs * @return */ @Override public TProjectBean loadByWorkItemKey(Integer workItemID) { List projects = null; Criteria criteria = new Criteria(); criteria.addJoin(BaseTWorkItemPeer.PROJECTKEY, PKEY); criteria.add(BaseTWorkItemPeer.WORKITEMKEY, workItemID); try { projects = doSelect(criteria); } catch(Exception e) { LOGGER.error("Loading the projectBean by workItemID failed with " + e.getMessage()); } if (projects==null || projects.isEmpty()) { return null; } return ((TProject)projects.get(0)).getBean(); } /** * Load by users and right and state independently of the project level (main or subproject) * @param personIDs * @param right * @param states * @return */ @Override public List<TProjectBean> loadByUserAndRightAndState(List<Integer> personIDs, int[] right, int[] states) { if (personIDs==null || personIDs.isEmpty()) { return new LinkedList<TProjectBean>(); } Criteria crit = new Criteria(); crit.addJoin(TAccessControlListPeer.PROJKEY, PKEY); TAccessControlListPeer.addExtendedAccessKeyCriteria(crit, right); crit.addIn(TAccessControlListPeer.PERSONKEY, personIDs); //states only when specified if (states!=null && states.length>0) { crit.addIn(STATUS, states); } crit.add(PKEY, 0, Criteria.GREATER_THAN); crit.setDistinct(); crit.addAscendingOrderByColumn(LABEL); try { return convertTorqueListToBeanList(doSelect(crit)); } catch(Exception e) { LOGGER.error("Loading the projects by " + personIDs.size() + " user and right " + right + " and states failed with " + e.getMessage()); return null; } } /** * Load subprojects by persons, parent project, explicit right and states * @param personIDs * @param parentProjectID * @param right * @param states * @return */ @Override public List<TProjectBean> loadSubprojectsByUserAndRightAndState( List<Integer> personIDs, Integer parentProjectID, int[] right, int[] states) { Criteria crit = new Criteria(); crit.addJoin(TAccessControlListPeer.PROJKEY, PKEY); TAccessControlListPeer.addExtendedAccessKeyCriteria(crit, right); crit.addIn(TAccessControlListPeer.PERSONKEY, personIDs); //states only when specified if (states!=null && states.length>0) { crit.addIn(STATUS, states); } crit.add(PKEY, 0, Criteria.GREATER_THAN); crit.add(PARENT, parentProjectID); crit.setDistinct(); crit.addAscendingOrderByColumn(LABEL); try { return convertTorqueListToBeanList(doSelect(crit)); } catch(Exception e) { LOGGER.error("Loading the subprojects by parent project " + parentProjectID + ", " + personIDs.size() + " users, right " + right[0] + " and states failed with " + e.getMessage(), e); return null; } } /** * Load the distinct projects containing issues having the field set * @param fieldID * @return */ @Override public List<TProjectBean> getProjectsWithField(Integer fieldID) { Criteria crit = new Criteria(); crit.add(TAttributeValuePeer.FIELDKEY, fieldID); crit.addJoin(TAttributeValuePeer.WORKITEM, TWorkItemPeer.WORKITEMKEY); crit.addJoin(TWorkItemPeer.PROJECTKEY, TProjectPeer.PKEY); crit.setDistinct(); try { return convertTorqueListToBeanList(doSelect(crit)); } catch (TorqueException e) { LOGGER.error("Getting projects with field " + fieldID + " failed with: " + e); return null; } } /** * Loads a list of projectBeans which has notificationSettings * (set either explicitely by a person or inherited the default) * @param personID * @return */ @Override public List<TProjectBean> loadByOwnOrDefaultNotifySettings(Integer personID) { Criteria criteria = new Criteria(); criteria.addJoin(PKEY, BaseTNotifySettingsPeer.PROJECT); Criterion personCrit = criteria.getNewCriterion(BaseTNotifySettingsPeer.PERSON, personID, Criteria.EQUAL); Criterion defaultCrit = criteria.getNewCriterion(BaseTNotifySettingsPeer.PERSON, (Object)null, Criteria.ISNULL); criteria.add(personCrit.or(defaultCrit)); //if a project has default and own notifiy settings then take only one time criteria.setDistinct(); try { return convertTorqueListToBeanList(doSelect(criteria)); } catch (TorqueException e) { LOGGER.error("Loading of projects with notify assignments either as default or by person " + personID + " failed with " + e.getMessage()); return null; } } /** * Loads a list of projectBeans which has default notificationSettings set * @return */ @Override public List<TProjectBean> loadByDefaultNotifySettings() { Criteria criteria = new Criteria(); criteria.addJoin(PKEY, BaseTNotifySettingsPeer.PROJECT); criteria.add(BaseTNotifySettingsPeer.PERSON, (Object)null, Criteria.ISNULL); criteria.setDistinct(); try { return convertTorqueListToBeanList(doSelect(criteria)); } catch (TorqueException e) { LOGGER.error("Loading of the projects having default notify assignments failed with " + e.getMessage()); return null; } } /** * Saves a projectBean in the TProject table * @param projectBean * @return */ @Override public Integer save(TProjectBean projectBean) { try { TProject tProject = BaseTProject.createTProject(projectBean); tProject.save(); return tProject.getObjectID(); } catch (Exception e) { LOGGER.error("Simple saving of a project failed with " + e.getMessage()); return null; } } /** * Deletes the project dependencies * @param projectID * @return */ @Override public void deleteDependencies(Integer projectID) { ReflectionHelper.delete(deletePeerClasses, deleteFields, projectID); } /** * @param projectID primary key of a project * @throws Exception */ @Override public void delete(Integer projectID) { LOGGER.fatal("Project with ID " + projectID + " is deleted..."); Criteria criteria = new Criteria(); criteria.add(PKEY, projectID); try { doDelete(criteria); } catch (TorqueException e) { LOGGER.error("Deleting the project " + projectID + " failed with " + e.getMessage()); } } /** * Helper for deep and shallow copy * @param workItemBean * @param deep * @return */ @Override public TProjectBean copy(TProjectBean projectOriginal, boolean deep) { TProjectBean tProjectCopy = null; if (projectOriginal!=null) { try { tProjectCopy = (BaseTProject.createTProject(projectOriginal).copy(deep)).getBean(); } catch (TorqueException e) { String copyMode; if (deep) { copyMode = "Deep"; } else { copyMode = "Shallow"; } LOGGER.error(copyMode + " copy failed with " + e.getMessage()); } } return tProjectCopy; } /** * Filter the projects from the projectIDs having specific projectStates * @param projectIDs * @param projectStates * @return */ @Override public Set<Integer> filterProjectsIDsByStates(Set<Integer> projectIDs, int[] projectStates) { Set<Integer> filteredProjectIDs = new HashSet<Integer>(); if (projectIDs==null || projectIDs.isEmpty()) { return filteredProjectIDs; } List<int[]> projectIDChunksList = GeneralUtils.getListOfChunks(GeneralUtils.createIntegerListFromCollection(projectIDs)); if (projectIDChunksList==null) { return filteredProjectIDs; } Iterator<int[]> iterator = projectIDChunksList.iterator(); while (iterator.hasNext()) { Criteria criteria = new Criteria(); int[] projectIDChunk = iterator.next(); if (projectStates!=null && projectStates.length>0) { criteria.addIn(STATUS, projectStates); } criteria.addIn(PKEY, projectIDChunk); try { filteredProjectIDs.addAll(getProjectIDs(criteria)); } catch(Exception e) { LOGGER.error("Loading the projectBeans by projectIDs " + projectIDs.size() + " and states " + projectStates + " failed with " + e.getMessage()); } } return filteredProjectIDs; } /** * Gets the projectIDs from resultset * @param criteria * @param raciRoles * @return */ private static Set<Integer> getProjectIDs(Criteria criteria) { Set<Integer> projectIDs = new HashSet<Integer>(); try { criteria.addSelectColumn(PKEY); criteria.setDistinct(); List<Record> projectIDRecords = doSelectVillageRecords(criteria); if (projectIDRecords!=null) { for (Record record : projectIDRecords) { try { Value value = record.getValue(1); if (value!=null) { Integer projectID = value.asIntegerObj(); if (projectID!=null) { projectIDs.add(projectID); } } } catch (DataSetException e) { LOGGER.error("Getting the projectID failed with " + e.getMessage()); } } } } catch (TorqueException e) { LOGGER.error("Loading of projectIDs failed with " + e.getMessage()); } return projectIDs; } /********************************************************* * Manager-, Responsible-, My- and Custom Reports methods * *********************************************************/ /** * Gets the projectBeans for a prepared criteria * @param preparedCriteria * @return * @throws TorqueException */ private static List<TProjectBean> getReportProjects(Criteria preparedCriteria) throws TorqueException { return convertTorqueListToBeanList(doSelect(preparedCriteria)); } /** * Get the IDs of the closed projects form projectIDs * @param projectIDs * @return */ @Override public Set<Integer> getClosedProjectIDs(List<Integer> projectIDs) { Set<Integer> closedProjectIDs = new HashSet<Integer>(); if (projectIDs==null || projectIDs.isEmpty()) { return closedProjectIDs; } List projects = new ArrayList(); Criteria crit = new Criteria(); crit.addJoin(BaseTProjectPeer.STATUS, BaseTSystemStatePeer.OBJECTID); crit.addIn(BaseTProjectPeer.PKEY, projectIDs); crit.add(BaseTSystemStatePeer.STATEFLAG, TSystemStateBean.STATEFLAGS.CLOSED); try { projects = doSelect(crit); } catch (TorqueException e) { LOGGER.error("Filtering the closed projects failed with " + e.getMessage()); } Iterator iterator = projects.iterator(); while (iterator.hasNext()) { TProject tProject = (TProject)iterator.next(); closedProjectIDs.add(tProject.getObjectID()); } return closedProjectIDs; } private static List<TProjectBean> convertTorqueListToBeanList(List<TProject> torqueList) { List<TProjectBean> beanList = new ArrayList<TProjectBean>(); if (torqueList!=null){ Iterator<TProject> itrTorqueList = torqueList.iterator(); while (itrTorqueList.hasNext()){ beanList.add(itrTorqueList.next().getBean()); } } return beanList; } /** * Get the projectBeans from the history of the workItemIDs, a project might appear more times in this list! * @param workItemIDs * @return */ @Override public List<TProjectBean> loadHistoryProjects(int[] workItemIDs) { List<TProjectBean> projectBeanList = new ArrayList<TProjectBean>(); List<int[]> workItemIDChunksList = GeneralUtils.getListOfChunks(workItemIDs); if (workItemIDChunksList!=null && !workItemIDChunksList.isEmpty()) { Iterator<int[]> iterator = workItemIDChunksList.iterator(); while (iterator.hasNext()) { int[] workItemIDChunk = iterator.next(); Criteria criteria = HistoryDropdownContainerLoader.prepareHistorySystemOptionCriteria( workItemIDChunk, true, PKEY, SystemFields.PROJECT); try { projectBeanList.addAll(convertTorqueListToBeanList(doSelect(criteria))); } catch(Exception e) { LOGGER.error("Loading the new history projectBeans for workItems and personID failed with " + e.getMessage()); } criteria = HistoryDropdownContainerLoader.prepareHistorySystemOptionCriteria( workItemIDChunk, false, PKEY, SystemFields.PROJECT); try { projectBeanList.addAll(convertTorqueListToBeanList(doSelect(criteria))); } catch(Exception e) { LOGGER.error("Loading the old history projectBeans for workItems failed with " + e.getMessage()); } } } return projectBeanList; } public List<IntegerStringBean> getPath(Integer objectID) { List<IntegerStringBean> result=new ArrayList<IntegerStringBean>(); Integer projectID=objectID; while(projectID!=null){ TProject project = getInternalProject(projectID); if(project!=null){ result.add(0,new IntegerStringBean(project.getLabel(), project.getObjectID())); projectID = project.getParent(); }else{ return null; } } return result; } private TProject getInternalProject(Integer objectID) { TProject project = null; try { project = retrieveByPK(objectID); } catch (Exception e) { LOGGER.info("Loading the project by primary key " + objectID + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return project; } }
gpl-3.0
McMoonLakeDev/Script
src/com/minecraft/moonlake/script/execute/Executor.java
862
/* * Copyright (C) 2017 The MoonLake Authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.minecraft.moonlake.script.execute; public interface Executor<T> extends Comparable<T> { Object execute(Object... argument) throws Exception; }
gpl-3.0
brangerbriz/webroutes
nw-app/telegeography-data/internetexchanges/buildings/20170.js
574
{"exchanges":[{"info":[{"onclick":null,"link":"mailto:","value":"Antonio Harris, Executive Director"},{"onclick":null,"link":null,"value":"54 11 4326 0777"},{"onclick":null,"link":"mailto:info@cabase.org.ar","value":"info@cabase.org.ar"},{"onclick":"window.open(this.href,'ix-new-window');return false;","link":"http://www.cabase.org.ar","value":"Website"},{"onclick":null,"link":null,"value":"Online since: April 1998"}],"slug":"cabase-ixp-mar-del-plata-argentina","name":"CABASE IXP"}],"address":["\u003Caddress not available\u003E","Mar del Plata, Argentina"],"id":20170}
gpl-3.0
vincentcasseau/hyStrath
src/thermophysicalModels/strath/strathSpecie/transport/speciesTransport/powerLawEucken/powerLawEuckenTransport.H
6672
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2016-2021 hyStrath \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of hyStrath, a derivative work of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::powerLawEuckenTransport Description Transport package using the power law and Eucken's formulas. Templated into a given thermodynamics package (needed for thermal conductivity). SourceFiles powerLawEuckenTransportI.H powerLawEuckenTransport.C \*---------------------------------------------------------------------------*/ #ifndef powerLawEuckenTransport_H #define powerLawEuckenTransport_H // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // Forward declaration of friend functions and operators template<class Thermo> class powerLawEuckenTransport; template<class Thermo> inline powerLawEuckenTransport<Thermo> operator+ ( const powerLawEuckenTransport<Thermo>&, const powerLawEuckenTransport<Thermo>& ); template<class Thermo> inline powerLawEuckenTransport<Thermo> operator- ( const powerLawEuckenTransport<Thermo>&, const powerLawEuckenTransport<Thermo>& ); template<class Thermo> inline powerLawEuckenTransport<Thermo> operator* ( const scalar, const powerLawEuckenTransport<Thermo>& ); template<class Thermo> inline powerLawEuckenTransport<Thermo> operator== ( const powerLawEuckenTransport<Thermo>&, const powerLawEuckenTransport<Thermo>& ); template<class Thermo> Ostream& operator<< ( Ostream&, const powerLawEuckenTransport<Thermo>& ); /*---------------------------------------------------------------------------*\ Class powerLawEuckenTransport Declaration \*---------------------------------------------------------------------------*/ template<class Thermo> class powerLawEuckenTransport : public Thermo { // Private data // Power law's coefficients scalar Tref_, dref_, omega_, muref_; //- Factor in vibrational thermal conductivity kappave // Hard-sphere: (7-2*omega_m)/5 with omega_m = 0.5 // Default value: 1.2 scalar eta_s_; public: // Constructors //- Construct from components inline powerLawEuckenTransport ( const Thermo& t, const scalar Tref, const scalar dref, const scalar omega, const scalar muref, const scalar eta_s ); //- Construct as named copy inline powerLawEuckenTransport ( const word&, const powerLawEuckenTransport& ); //- Construct from Istream powerLawEuckenTransport(Istream&); //- Construct from dictionary powerLawEuckenTransport(const dictionary& dict); //- Construct and return a clone inline autoPtr<powerLawEuckenTransport> clone() const; // Selector from Istream inline static autoPtr<powerLawEuckenTransport> New(Istream& is); // Selector from dictionary inline static autoPtr<powerLawEuckenTransport> New ( const dictionary& dict ); // Member functions //- Return the instantiated type name static word typeName() { return "powerLawEucken<" + Thermo::typeName() + '>'; } //- Dynamic viscosity [kg/ms] inline scalar mu(const scalar p, const scalar Tt) const; //- Thermal conductivity, translational mode [W/mK] inline scalar kappatrans(const scalar p, const scalar Tt) const; //- Thermal conductivity, rotational mode [W/mK] inline scalar kappar(const scalar p, const scalar Tr) const; //- Thermal conductivity, trans-rotational mode [W/mK] inline scalar kappatr(const scalar p, const scalar Tt) const; //- Thermal conductivity, vibro-electronic energy mode [W/mK] inline scalar kappave ( const scalar p, const scalar Tt, const scalar Tve ) const; //- Write to Ostream void write(Ostream& os) const; // Member operators inline powerLawEuckenTransport& operator= ( const powerLawEuckenTransport& ); inline void operator+=(const powerLawEuckenTransport&); inline void operator-=(const powerLawEuckenTransport&); inline void operator*=(const scalar); // Friend operators friend powerLawEuckenTransport operator+ <Thermo> ( const powerLawEuckenTransport&, const powerLawEuckenTransport& ); friend powerLawEuckenTransport operator- <Thermo> ( const powerLawEuckenTransport&, const powerLawEuckenTransport& ); friend powerLawEuckenTransport operator* <Thermo> ( const scalar, const powerLawEuckenTransport& ); friend powerLawEuckenTransport operator== <Thermo> ( const powerLawEuckenTransport&, const powerLawEuckenTransport& ); // Ostream Operator friend Ostream& operator<< <Thermo> ( Ostream&, const powerLawEuckenTransport& ); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #include "powerLawEuckenTransportI.H" #ifdef NoRepository # include "powerLawEuckenTransport.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
gpl-3.0
avdata99/SIAT
siat-1.0-SOURCE/src/iface/src/ar/gov/rosario/siat/def/iface/model/ParametroAdapter.java
1020
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda. //This file is part of SIAT. SIAT is licensed under the terms //of the GNU General Public License, version 3. //See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt> package ar.gov.rosario.siat.def.iface.model; import ar.gov.rosario.siat.base.iface.model.SiatAdapterModel; import ar.gov.rosario.siat.def.iface.util.DefSecurityConstants; /** * Adapter del Parametro * * @author tecso */ public class ParametroAdapter extends SiatAdapterModel{ private static final long serialVersionUID = 1L; public static final String NAME = "parametroAdapterVO"; private ParametroVO parametro = new ParametroVO(); // Constructores public ParametroAdapter(){ super(DefSecurityConstants.ABM_PARAMETRO); } // Getters y Setters public ParametroVO getParametro() { return parametro; } public void setParametro(ParametroVO parametroVO) { this.parametro = parametroVO; } // View getters }
gpl-3.0
dvoraka/av-service
avprogram/src/main/java/dvoraka/avservice/avprogram/package-info.java
88
/** * Anti-virus infrastructure and wrappers. */ package dvoraka.avservice.avprogram;
gpl-3.0
Invertika/data
scripts/maps/ow-n0012-p0018-o0000.lua
1400
---------------------------------------------------------------------------------- -- Map File -- -- -- -- In dieser Datei stehen die entsprechenden externen NPC's, Trigger und -- -- anderer Dinge. -- -- -- ---------------------------------------------------------------------------------- -- Copyright 2010 The Invertika Development Team -- -- -- -- This file is part of Invertika. -- -- -- -- Invertika is free software; you can redistribute it and/or modify it -- -- under the terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2 of the License, or any later version. -- ---------------------------------------------------------------------------------- require "scripts/lua/npclib" require "scripts/libs/warp" atinit(function() create_inter_map_warp_trigger(672, 620, 670, 722) --- Intermap warp end)
gpl-3.0
Sarius997/Multiplayer-PD
src/com/sarius/multiplayer_pd/levels/RegularLevel.java
18242
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2015 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.sarius.multiplayer_pd.levels; import com.sarius.multiplayer_pd.Bones; import com.sarius.multiplayer_pd.Challenges; import com.sarius.multiplayer_pd.Dungeon; import com.sarius.multiplayer_pd.actors.Actor; import com.sarius.multiplayer_pd.actors.buffs.Buff; import com.sarius.multiplayer_pd.actors.mobs.Bestiary; import com.sarius.multiplayer_pd.actors.mobs.Mob; import com.sarius.multiplayer_pd.items.Generator; import com.sarius.multiplayer_pd.items.Heap; import com.sarius.multiplayer_pd.items.Item; import com.sarius.multiplayer_pd.items.rings.RingOfWealth; import com.sarius.multiplayer_pd.items.scrolls.Scroll; import com.sarius.multiplayer_pd.levels.Room.Type; import com.sarius.multiplayer_pd.levels.painters.Painter; import com.sarius.multiplayer_pd.levels.painters.ShopPainter; import com.sarius.multiplayer_pd.levels.traps.AlarmTrap; import com.sarius.multiplayer_pd.levels.traps.FireTrap; import com.sarius.multiplayer_pd.levels.traps.GrippingTrap; import com.sarius.multiplayer_pd.levels.traps.LightningTrap; import com.sarius.multiplayer_pd.levels.traps.ParalyticTrap; import com.sarius.multiplayer_pd.levels.traps.PoisonTrap; import com.sarius.multiplayer_pd.levels.traps.ToxicTrap; import com.watabou.utils.Bundle; import com.watabou.utils.Graph; import com.watabou.utils.Random; import com.watabou.utils.Rect; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; public abstract class RegularLevel extends Level { protected HashSet<Room> rooms; protected Room roomEntrance; protected Room roomExit; protected ArrayList<Room.Type> specials; public int secretDoors; @Override protected boolean build() { if (!initRooms()) { return false; } int distance; int retry = 0; int minDistance = (int)Math.sqrt( rooms.size() ); do { do { roomEntrance = Random.element( rooms ); } while (roomEntrance.width() < 4 || roomEntrance.height() < 4); do { roomExit = Random.element( rooms ); } while (roomExit == roomEntrance || roomExit.width() < 4 || roomExit.height() < 4); Graph.buildDistanceMap( rooms, roomExit ); distance = roomEntrance.distance(); if (retry++ > 10) { return false; } } while (distance < minDistance); roomEntrance.type = Type.ENTRANCE; roomExit.type = Type.EXIT; HashSet<Room> connected = new HashSet<Room>(); connected.add( roomEntrance ); Graph.buildDistanceMap( rooms, roomExit ); List<Room> path = Graph.buildPath( rooms, roomEntrance, roomExit ); Room room = roomEntrance; for (Room next : path) { room.connect( next ); room = next; connected.add( room ); } Graph.setPrice( path, roomEntrance.distance ); Graph.buildDistanceMap( rooms, roomExit ); path = Graph.buildPath( rooms, roomEntrance, roomExit ); room = roomEntrance; for (Room next : path) { room.connect( next ); room = next; connected.add( room ); } int nConnected = (int)(rooms.size() * Random.Float( 0.5f, 0.7f )); while (connected.size() < nConnected) { Room cr = Random.element( connected ); Room or = Random.element( cr.neigbours ); if (!connected.contains( or )) { cr.connect( or ); connected.add( or ); } } if (Dungeon.shopOnLevel()) { Room shop = null; for (Room r : roomEntrance.connected.keySet()) { if (r.connected.size() == 1 && ((r.width()-1)*(r.height()-1) >= ShopPainter.spaceNeeded())) { shop = r; break; } } if (shop == null) { return false; } else { shop.type = Room.Type.SHOP; } } specials = new ArrayList<Room.Type>( Room.SPECIALS ); if (Dungeon.bossLevel( Dungeon.depth + 1 )) { specials.remove( Room.Type.WEAK_FLOOR ); } if (Dungeon.isChallenged( Challenges.NO_ARMOR )){ //no sense in giving an armor reward room on a run with no armor. specials.remove( Room.Type.CRYPT ); } if (Dungeon.isChallenged( Challenges.NO_HERBALISM )){ //sorry warden, no lucky sungrass or blandfruit seeds for you! specials.remove( Room.Type.GARDEN ); } if (!assignRoomType()) return false; paint(); paintWater(); paintGrass(); placeTraps(); return true; } protected void placeSign(){ while (true) { int pos = roomEntrance.random(); if (pos != entrance && traps.get(pos) == null) { map[pos] = Terrain.SIGN; break; } } } protected boolean initRooms() { rooms = new HashSet<Room>(); split( new Rect( 0, 0, WIDTH - 1, HEIGHT - 1 ) ); if (rooms.size() < 8) { return false; } Room[] ra = rooms.toArray( new Room[0] ); for (int i=0; i < ra.length-1; i++) { for (int j=i+1; j < ra.length; j++) { ra[i].addNeigbour( ra[j] ); } } return true; } protected boolean assignRoomType() { int specialRooms = 0; for (Room r : rooms) { if (r.type == Type.NULL && r.connected.size() == 1) { if (specials.size() > 0 && r.width() > 3 && r.height() > 3 && Random.Int( specialRooms * specialRooms + 2 ) == 0) { if (pitRoomNeeded) { r.type = Type.PIT; pitRoomNeeded = false; specials.remove( Type.ARMORY ); specials.remove( Type.CRYPT ); specials.remove( Type.LABORATORY ); specials.remove( Type.LIBRARY ); specials.remove( Type.STATUE ); specials.remove( Type.TREASURY ); specials.remove( Type.VAULT ); specials.remove( Type.WEAK_FLOOR ); } else if (Dungeon.depth % 5 == 2 && specials.contains( Type.LABORATORY )) { r.type = Type.LABORATORY; } else if (Dungeon.depth >= Dungeon.transmutation && specials.contains( Type.MAGIC_WELL )) { r.type = Type.MAGIC_WELL; } else { int n = specials.size(); r.type = specials.get( Math.min( Random.Int( n ), Random.Int( n ) ) ); if (r.type == Type.WEAK_FLOOR) { weakFloorCreated = true; } } Room.useType( r.type ); specials.remove( r.type ); specialRooms++; } else if (Random.Int( 2 ) == 0){ HashSet<Room> neigbours = new HashSet<Room>(); for (Room n : r.neigbours) { if (!r.connected.containsKey( n ) && !Room.SPECIALS.contains( n.type ) && n.type != Type.PIT) { neigbours.add( n ); } } if (neigbours.size() > 1) { r.connect( Random.element( neigbours ) ); } } } } int count = 0; for (Room r : rooms) { if (r.type == Type.NULL) { int connections = r.connected.size(); if (connections == 0) { } else if (Random.Int( connections * connections ) == 0) { r.type = Type.STANDARD; count++; } else { r.type = Type.TUNNEL; } } } while (count < 6) { Room r = randomRoom( Type.TUNNEL, 1 ); if (r != null) { r.type = Type.STANDARD; count++; } } return true; } protected void paintWater() { boolean[] lake = water(); for (int i=0; i < LENGTH; i++) { if (map[i] == Terrain.EMPTY && lake[i]) { map[i] = Terrain.WATER; } } } protected void paintGrass() { boolean[] grass = grass(); if (feeling == Feeling.GRASS) { for (Room room : rooms) { if (room.type != Type.NULL && room.type != Type.PASSAGE && room.type != Type.TUNNEL) { grass[(room.left + 1) + (room.top + 1) * WIDTH] = true; grass[(room.right - 1) + (room.top + 1) * WIDTH] = true; grass[(room.left + 1) + (room.bottom - 1) * WIDTH] = true; grass[(room.right - 1) + (room.bottom - 1) * WIDTH] = true; } } } for (int i=WIDTH+1; i < LENGTH-WIDTH-1; i++) { if (map[i] == Terrain.EMPTY && grass[i]) { int count = 1; for (int n : NEIGHBOURS8) { if (grass[i + n]) { count++; } } map[i] = (Random.Float() < count / 12f) ? Terrain.HIGH_GRASS : Terrain.GRASS; } } } protected abstract boolean[] water(); protected abstract boolean[] grass(); protected void placeTraps() { int nTraps = nTraps(); float[] trapChances = trapChances(); for (int i=0; i < nTraps; i++) { int trapPos = Random.Int( LENGTH ); if (map[trapPos] == Terrain.EMPTY) { map[trapPos] = Terrain.SECRET_TRAP; switch (Random.chances( trapChances )) { case 0: setTrap( new ToxicTrap().hide(), trapPos); break; case 1: setTrap( new FireTrap().hide(), trapPos); break; case 2: setTrap( new ParalyticTrap().hide(), trapPos); break; case 3: setTrap( new PoisonTrap().hide(), trapPos); break; case 4: setTrap( new AlarmTrap().hide(), trapPos); break; case 5: setTrap( new LightningTrap().hide(), trapPos); break; case 6: setTrap( new GrippingTrap().hide(), trapPos); break; case 7: setTrap( new LightningTrap().hide(), trapPos); break; } } } } protected int nTraps() { return Dungeon.depth <= 1 ? 0 : Random.Int( 1, rooms.size() + Dungeon.depth ); } protected float[] trapChances() { float[] chances = { 1, 1, 1, 1, 1, 1, 1, 1 }; return chances; } protected int minRoomSize = 7; protected int maxRoomSize = 9; protected void split( Rect rect ) { int w = rect.width(); int h = rect.height(); if (w > maxRoomSize && h < minRoomSize) { int vw = Random.Int( rect.left + 3, rect.right - 3 ); split( new Rect( rect.left, rect.top, vw, rect.bottom ) ); split( new Rect( vw, rect.top, rect.right, rect.bottom ) ); } else if (h > maxRoomSize && w < minRoomSize) { int vh = Random.Int( rect.top + 3, rect.bottom - 3 ); split( new Rect( rect.left, rect.top, rect.right, vh ) ); split( new Rect( rect.left, vh, rect.right, rect.bottom ) ); } else if ((Math.random() <= (minRoomSize * minRoomSize / rect.square()) && w <= maxRoomSize && h <= maxRoomSize) || w < minRoomSize || h < minRoomSize) { rooms.add( (Room)new Room().set( rect ) ); } else { if (Random.Float() < (float)(w - 2) / (w + h - 4)) { int vw = Random.Int( rect.left + 3, rect.right - 3 ); split( new Rect( rect.left, rect.top, vw, rect.bottom ) ); split( new Rect( vw, rect.top, rect.right, rect.bottom ) ); } else { int vh = Random.Int( rect.top + 3, rect.bottom - 3 ); split( new Rect( rect.left, rect.top, rect.right, vh ) ); split( new Rect( rect.left, vh, rect.right, rect.bottom ) ); } } } protected void paint() { for (Room r : rooms) { if (r.type != Type.NULL) { placeDoors( r ); r.type.paint( this, r ); } else { if (feeling == Feeling.CHASM && Random.Int( 2 ) == 0) { Painter.fill( this, r, Terrain.WALL ); } } } for (Room r : rooms) { paintDoors( r ); } } private void placeDoors( Room r ) { for (Room n : r.connected.keySet()) { Room.Door door = r.connected.get( n ); if (door == null) { Rect i = r.intersect( n ); if (i.width() == 0) { door = new Room.Door( i.left, Random.Int( i.top + 1, i.bottom ) ); } else { door = new Room.Door( Random.Int( i.left + 1, i.right ), i.top); } r.connected.put( n, door ); n.connected.put( r, door ); } } } protected void paintDoors( Room r ) { for (Room n : r.connected.keySet()) { if (joinRooms( r, n )) { continue; } Room.Door d = r.connected.get( n ); int door = d.x + d.y * WIDTH; switch (d.type) { case EMPTY: map[door] = Terrain.EMPTY; break; case TUNNEL: map[door] = tunnelTile(); break; case REGULAR: if (Dungeon.depth <= 1) { map[door] = Terrain.DOOR; } else { boolean secret = (Dungeon.depth < 6 ? Random.Int( 12 - Dungeon.depth ) : Random.Int( 6 )) == 0; map[door] = secret ? Terrain.SECRET_DOOR : Terrain.DOOR; if (secret) { secretDoors++; } } break; case UNLOCKED: map[door] = Terrain.DOOR; break; case HIDDEN: map[door] = Terrain.SECRET_DOOR; break; case BARRICADE: map[door] = Random.Int( 3 ) == 0 ? Terrain.BOOKSHELF : Terrain.BARRICADE; break; case LOCKED: map[door] = Terrain.LOCKED_DOOR; break; } } } protected boolean joinRooms( Room r, Room n ) { if (r.type != Room.Type.STANDARD || n.type != Room.Type.STANDARD) { return false; } Rect w = r.intersect( n ); if (w.left == w.right) { if (w.bottom - w.top < 3) { return false; } if (w.height() == Math.max( r.height(), n.height() )) { return false; } if (r.width() + n.width() > maxRoomSize) { return false; } w.top += 1; w.bottom -= 0; w.right++; Painter.fill( this, w.left, w.top, 1, w.height(), Terrain.EMPTY ); } else { if (w.right - w.left < 3) { return false; } if (w.width() == Math.max( r.width(), n.width() )) { return false; } if (r.height() + n.height() > maxRoomSize) { return false; } w.left += 1; w.right -= 0; w.bottom++; Painter.fill( this, w.left, w.top, w.width(), 1, Terrain.EMPTY ); } return true; } @Override public int nMobs() { switch(Dungeon.depth) { case 1: //mobs are not randomly spawned on floor 1. return 0; default: return 2 + Dungeon.depth % 5 + Random.Int(5); } } @Override protected void createMobs() { //on floor 1, 10 rats are created so the player can get level 2. int mobsToSpawn = Dungeon.depth == 1 ? 10 : nMobs(); HashSet<Room> stdRooms = new HashSet<>(); for (Room room : rooms) { if (room.type == Type.STANDARD) stdRooms.add(room); } Iterator<Room> stdRoomIter = stdRooms.iterator(); while (mobsToSpawn > 0) { if (!stdRoomIter.hasNext()) stdRoomIter = stdRooms.iterator(); Room roomToSpawn = stdRoomIter.next(); Mob mob = Bestiary.mob( Dungeon.depth ); mob.pos = roomToSpawn.random(); if (findMob(mob.pos) == null && Level.passable[mob.pos]) { mobsToSpawn--; mobs.add(mob); //TODO: perhaps externalize this logic into a method. Do I want to make mobs more likely to clump deeper down? if (mobsToSpawn > 0 && Random.Int(4) == 0){ mob = Bestiary.mob( Dungeon.depth ); mob.pos = roomToSpawn.random(); if (findMob(mob.pos) == null && Level.passable[mob.pos]) { mobsToSpawn--; mobs.add(mob); } } } } } @Override public int randomRespawnCell() { int count = 0; int cell = -1; while (true) { if (++count > 30) { return -1; } Room room = randomRoom( Room.Type.STANDARD, 10 ); if (room == null) { continue; } cell = room.random(); if (!Dungeon.visible[cell] && Actor.findChar( cell ) == null && Level.passable[cell]) { return cell; } } } @Override public int randomDestination() { int cell = -1; while (true) { Room room = Random.element( rooms ); if (room == null) { continue; } cell = room.random(); if (Level.passable[cell]) { return cell; } } } @Override protected void createItems() { int nItems = 3; int bonus = 0; for (Buff buff : Dungeon.hero.buffs(RingOfWealth.Wealth.class)) { bonus += ((RingOfWealth.Wealth) buff).level; } //just incase someone gets a ridiculous ring, cap this at 80% bonus = Math.min(bonus, 10); while (Random.Float() < (0.3f + bonus*0.05f)) { nItems++; } for (int i=0; i < nItems; i++) { Heap.Type type = null; switch (Random.Int( 20 )) { case 0: type = Heap.Type.SKELETON; break; case 1: case 2: case 3: case 4: type = Heap.Type.CHEST; break; case 5: type = Dungeon.depth > 1 ? Heap.Type.MIMIC : Heap.Type.CHEST; break; default: type = Heap.Type.HEAP; } drop( Generator.random(), randomDropCell() ).type = type; } for (Item item : itemsToSpawn) { int cell = randomDropCell(); if (item instanceof Scroll) { while ((map[cell] == Terrain.TRAP || map[cell] == Terrain.SECRET_TRAP) && traps.get( cell ) instanceof FireTrap) { cell = randomDropCell(); } } drop( item, cell ).type = Heap.Type.HEAP; } Item item = Bones.get(); if (item != null) { drop( item, randomDropCell() ).type = Heap.Type.REMAINS; } } protected Room randomRoom( Room.Type type, int tries ) { for (int i=0; i < tries; i++) { Room room = Random.element( rooms ); if (room.type == type) { return room; } } return null; } public Room room( int pos ) { for (Room room : rooms) { if (room.type != Type.NULL && room.inside( pos )) { return room; } } return null; } protected int randomDropCell() { while (true) { Room room = randomRoom( Room.Type.STANDARD, 1 ); if (room != null) { int pos = room.random(); if (passable[pos]) { return pos; } } } } @Override public int pitCell() { for (Room room : rooms) { if (room.type == Type.PIT) { return room.random(); } } return super.pitCell(); } @Override public void storeInBundle( Bundle bundle ) { super.storeInBundle( bundle ); bundle.put( "rooms", rooms ); } @SuppressWarnings("unchecked") @Override public void restoreFromBundle( Bundle bundle ) { super.restoreFromBundle( bundle ); rooms = new HashSet<Room>( (Collection<Room>) ((Collection<?>) bundle.getCollection( "rooms" )) ); for (Room r : rooms) { if (r.type == Type.WEAK_FLOOR) { weakFloorCreated = true; break; } } } }
gpl-3.0
wimoverwater/Sick-Beard
sickbeard/browser.py
2469
import os import glob import string import cherrypy from sickbeard import encodingKludge as ek # use the built-in if it's available (python 2.6), if not use the included library try: import json except ImportError: from lib import simplejson as json # this is for the drive letter code, it only works on windows if os.name == 'nt': from ctypes import windll # adapted from http://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-drive-letters-in-python/827490 def getWinDrives(): assert os.name == 'nt' drives = [] bitmask = windll.kernel32.GetLogicalDrives() for letter in string.uppercase: if bitmask & 1: drives.append(letter) bitmask >>= 1 return drives # Returns a list of dictionaries with the folders contained at the given path # Give the empty string as the path to list the contents of the root path # (under Unix this means "/", on Windows this will be a list of drive letters) def foldersAtPath(path, includeParent = False): assert os.path.isabs(path) or path == "" if path == "": if os.name == 'nt': entries = [] for letter in getWinDrives(): letterPath = letter + ':\\' entries.append({'name': letterPath, 'path': letterPath}) return entries else: path = '/' # fix up the path and find the parent path = os.path.abspath(os.path.normpath(path)) parentPath = os.path.dirname(path) # if we're at the root then the next step is the meta-node showing our drive letters if path == parentPath and os.name == 'nt': parentPath = "" fileList = [{ 'name': filename, 'path': ek.ek(os.path.join, path, filename) } for filename in ek.ek(os.listdir, path)] fileList = filter(lambda entry: ek.ek(os.path.isdir, entry['path']), fileList) fileList = sorted(fileList, lambda x, y: cmp(os.path.basename(x['name']).lower(), os.path.basename(y['path']).lower())) entries = [] if includeParent and parentPath != path: entries.append({ 'name': "..", 'path': parentPath }) entries.extend(fileList) return entries class WebFileBrowser: @cherrypy.expose def index(self, path=''): cherrypy.response.headers['Content-Type'] = "application/json" return json.dumps(foldersAtPath(path, True)) @cherrypy.expose def complete(self, q, limit=10, timestamp=None): cherrypy.response.headers['Content-Type'] = "text/plain" paths = [entry['path'] for entry in foldersAtPath(os.path.dirname(q))] return "\n".join(paths[0:int(limit)])
gpl-3.0
lyy289065406/expcodes
java/01-framework/dubbo-admin/incubator-dubbo-ops/dubbo-admin-frontend/node/node_modules/npm/node_modules/request/node_modules/har-validator/node_modules/ajv/node_modules/json-stable-stringify/node_modules/jsonify/lib/stringify.js
5543
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); case 'object': if (!value) return 'null'; gap += indent; partial = []; // Array.isArray if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and // wrap them in brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be // stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } module.exports = function (value, replacer, space) { var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } // If the space parameter is a string, it will be used as the indent string. else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); };
gpl-3.0
powercoders/PCBot
src/org/rsbot/script/methods/Trade.java
7033
package org.rsbot.script.methods; import org.rsbot.script.wrappers.RSComponent; import org.rsbot.script.wrappers.RSInterface; import org.rsbot.script.wrappers.RSItem; import org.rsbot.script.wrappers.RSPlayer; import java.util.ArrayList; import java.util.List; /** * Trade handling. * * @author Timer * @author kyleshay */ public class Trade extends MethodProvider { public static final int INTERFACE_TRADE_MAIN = 335; public static final int INTERFACE_TRADE_SECOND = 334; public static final int INTERFACE_TRADE_MAIN_NAME = 15; public static final int INTERFACE_TRADE_SECOND_NAME = 54; public static final int INTERFACE_TRADE_MAIN_OUR = 30; public static final int INTERFACE_TRADE_MAIN_THEIR = 33; public static final int INTERFACE_TRADE_MAIN_ACCEPT = 17; public static final int INTERFACE_TRADE_MAIN_DECLINE = 19; public static final int INTERFACE_TRADE_SECOND_ACCEPT = 36; public static final int INTERFACE_TRADE_SECOND_DECLINE = 37; private final static int INTERFACE_TRADE_MAIN_INV_SLOTS = 21; public static final int TRADE_TYPE_MAIN = 0; public static final int TRADE_TYPE_SECONDARY = 1; public static final int TRADE_TYPE_NONE = 2; Trade(final MethodContext ctx) { super(ctx); } /** * Are we in the first stage of a trade? * * @return <tt>true</tt> if in first stage. */ public boolean inTradeMain() { final RSInterface tradeInterface = methods.interfaces.get(INTERFACE_TRADE_MAIN); return tradeInterface != null && tradeInterface.isValid(); } /** * Are we in the second stage of a trade? * * @return <tt>true</tt> if in second stage. */ public boolean inTradeSecond() { final RSInterface tradeInterface = methods.interfaces.get(INTERFACE_TRADE_SECOND); return tradeInterface != null && tradeInterface.isValid(); } /** * Checks if you're in a trade. * * @return <tt>true</tt> if you're trading; otherwise <tt>false</tt>. */ public boolean inTrade() { return inTradeMain() || inTradeSecond(); } /** * Trades a player. * * @param playerName The player's name. * @param tradeWait Timeout to wait for the trade. * @return <tt>true</tt> if traded. */ public boolean tradePlayer(final String playerName, final int tradeWait) { if (!inTrade()) { final RSPlayer targetPlayer = methods.players.getNearest(playerName); return targetPlayer != null && targetPlayer.interact("Trade with", targetPlayer.getName()) && waitForTrade(TRADE_TYPE_MAIN, tradeWait); } else { return isTradingWith(playerName); } } /** * Trades a player. * * @param playerName The player's name. * @return <tt>true</tt> if traded. */ public boolean tradePlayer(final String playerName) { return tradePlayer(playerName, 15000); } /** * Trades a player. * * @param targetPlayer The player you wish to trade. * @param tradeWait The time out for the trade. * @return <tt>true</tt> if traded. */ public boolean tradePlayer(final RSPlayer targetPlayer, final int tradeWait) { if (!inTrade()) { return targetPlayer != null && targetPlayer.interact("Trade with", targetPlayer.getName()) && waitForTrade(TRADE_TYPE_MAIN, tradeWait); } else { return isTradingWith(targetPlayer.getName()); } } /** * Trades a player. * * @param targetPlayer The desired player. * @return <tt>true</tt> if traded. */ public boolean tradePlayer(final RSPlayer targetPlayer) { return tradePlayer(targetPlayer, 15000); } /** * Accepts a trade * * @return <tt>true</tt> on accept. */ public boolean acceptTrade() { if (inTradeMain()) { return methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_ACCEPT).interact("Accept"); } else { return inTradeSecond() && methods.interfaces.get(INTERFACE_TRADE_SECOND).getComponent(INTERFACE_TRADE_SECOND_ACCEPT).interact("Accept"); } } /** * Declines a trade * * @return <tt>true</tt> on decline */ public boolean declineTrade() { if (inTradeMain()) { return methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_DECLINE).interact("Decline"); } else { return inTradeSecond() && methods.interfaces.get(INTERFACE_TRADE_SECOND).getComponent(INTERFACE_TRADE_SECOND_DECLINE).interact("Decline"); } } /** * Waits for trade type to be true. * * @param tradeType The trade type. * @param timeOut Time out of waiting. * @return <tt>true</tt> if true, otherwise false. */ public boolean waitForTrade(final int tradeType, final long timeOut) { final long timeCounter = System.currentTimeMillis() + timeOut; while (timeCounter - System.currentTimeMillis() > 0) { switch (tradeType) { case TRADE_TYPE_MAIN: if (inTradeMain()) { return true; } break; case TRADE_TYPE_SECONDARY: if (inTradeSecond()) { return true; } break; case TRADE_TYPE_NONE: if (!inTrade()) { return true; } break; } sleep(5); } return false; } /** * Gets who you're trading with. * * @return The person's name you're trading with. */ public String getTradingWith() { if (inTradeMain()) { final String name = methods.interfaces.getComponent(INTERFACE_TRADE_MAIN, INTERFACE_TRADE_MAIN_NAME).getText(); return name.substring(name.indexOf(": ") + 2); } else if (inTradeSecond()) { return methods.interfaces.getComponent(INTERFACE_TRADE_SECOND, INTERFACE_TRADE_SECOND_NAME).getText(); } return null; } /** * Checks if you're trading with someone. * * @param name The person's name. * @return <tt>true</tt> if true; otherwise <tt>false</tt>. */ public boolean isTradingWith(final String name) { return getTradingWith().equals(name); } /** * Returns the total number of items offered by another player * * @return The number of items offered. */ public int getNumberOfItemsOffered() { int number = 0; for (int i = 0; i < 28; i++) { if (methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_THEIR).getComponent(i).getComponentStackSize() != 0) { ++number; } } return number; } /** * Returns the items offered by another player * * @return The items offered. */ public RSItem[] getItemsOffered() { List<RSItem> items = new ArrayList<RSItem>(); for (int i = 0; i < 28; i++) { RSComponent component = methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_THEIR).getComponent(i); if (component != null && component.getComponentStackSize() != 0) { items.add(new RSItem(methods, component)); } } return items.toArray(new RSItem[items.size()]); } /** * Returns the total number of free slots the other player has * * @return The number of free slots. */ public int getFreeSlots() { if (inTradeMain()) { String text = methods.interfaces.get(INTERFACE_TRADE_MAIN).getComponent(INTERFACE_TRADE_MAIN_INV_SLOTS).getText().substring(4, 6); text = text.trim(); try { return Integer.parseInt(text); } catch (final Exception ignored) { } } return 0; } }
gpl-3.0
mpoquet/execo
doc/code_samples/g5k_tcp_congestion.py
5388
from execo import * from execo_g5k import * from execo_engine import * import yaml, re, itertools class g5k_tcp_congestion(Engine): def run(self): result_file = self.result_dir + "/results" params = { "num_flows": igeom(1, 20, 5), "tcp_congestion_control": ["cubic", "reno"], "repeat": list(range(0, 3)), } combs = sweep(params) sweeper = ParamSweeper(self.result_dir + "/sweeper", combs) logger.info("experiment plan: " + str(combs)) logger.info("compute resources to reserve") planning = get_planning() slots = compute_slots(planning, "01:00:00") wanted = {'grid5000': 0} start_date, end_date, resources = find_first_slot(slots, wanted) actual_resources = dict( list({ list(clusters)[0]:1 for site,clusters in itertools.groupby(sorted([ cluster for cluster, n_nodes in resources.items() if cluster in get_g5k_clusters() and n_nodes > 0 and 1e9 == [adapter for adapter in get_host_attributes(cluster + "-1")["network_adapters"] if adapter.get("network_address") == cluster + "-1." + get_cluster_site(cluster) + ".grid5000.fr"][0]["rate"]], lambda c1, c2: cmp(get_cluster_site(c1), get_cluster_site(c2))), get_cluster_site) }.items())[0:2]) if len(actual_resources) >= 2: logger.info("try to reserve " + str(actual_resources)) job_specs = get_jobs_specs(actual_resources) for job_spec in job_specs: job_spec[0].job_type = "deploy" logger.info("submit job: " + str(job_specs)) jobid, sshkey = oargridsub(job_specs, start_date, walltime = end_date - start_date) if jobid: try: logger.info("wait job start") wait_oargrid_job_start(jobid) logger.info("get job nodes") nodes = get_oargrid_job_nodes(jobid) if len(nodes) != 2: raise Exception("not enough nodes") logger.info("deploy %i nodes" % (len(nodes),)) deployed, undeployed = deploy(Deployment(nodes, env_name = "jessie-x64-min")) logger.info("%i deployed, %i undeployed" % (len(deployed), len(undeployed))) if len(deployed) != 2: raise Exception("not enough deployed nodes") logger.info("prepare nodes") Remote("apt-get -y install iperf", nodes, connection_params = {"user": "root"}).run() logger.info("start experiment campaign") while len(sweeper.get_remaining()) > 0: comb = sweeper.get_next() destination = SshProcess("iperf -s", nodes[0], connection_params = {"user": "root"}) sources = SshProcess("iperf -c %s -P %i -Z %s" % (nodes[0].address, comb["num_flows"], comb["tcp_congestion_control"]), nodes[1], connection_params = {"user": "root"}) with destination.start(): sleep(2) sources.run() if comb["num_flows"] > 1: pattern = "^\[SUM\].*\s(\d+(\.\d+)?) (\w?)bits/sec" else: pattern = "^\[\s*\d+\].*\s(\d+(\.\d+)?) (\w?)bits/sec" bw_mo = re.search(pattern, sources.stdout, re.MULTILINE) if bw_mo: bw = float(bw_mo.group(1)) * {"": 1, "K": 1e3, "M": 1e6, "G": 1e9}[bw_mo.group(3)] results = { "params": comb, "bw": bw } with open(result_file, "a") as f: yaml.dump([results], f, width = 72) logger.info("comb : %s bw = %f bits/s" % (comb, bw)) sweeper.done(comb) else: logger.info("comb failed: %s" % (comb,)) logger.info("sources stdout:\n" + sources.stdout) logger.info("sources stderr:\n" + sources.stderr) logger.info("destination stdout:\n" + destination.stdout) logger.info("destination stderr:\n" + destination.stderr) sweeper.skip(comb) finally: logger.info("deleting job") oargriddel([jobid]) else: logger.info("not enough resources available: " + str(actual_resources)) if __name__ == "__main__": engine = g5k_tcp_congestion() engine.start()
gpl-3.0
qilicun/python
python2/PyMOTW-1.132/PyMOTW/subprocess/subprocess_signal_parent_shell.py
691
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2009 Doug Hellmann All rights reserved. # """ """ #end_pymotw_header import os import signal import subprocess import tempfile import time import sys script = '''#!/bin/sh echo "Shell script in process $$" set -x python signal_child.py ''' script_file = tempfile.NamedTemporaryFile('wt') script_file.write(script) script_file.flush() proc = subprocess.Popen(['sh', script_file.name], close_fds=True) print 'PARENT : Pausing before sending signal to child %s...' % proc.pid sys.stdout.flush() time.sleep(1) print 'PARENT : Signaling child %s' % proc.pid sys.stdout.flush() os.kill(proc.pid, signal.SIGUSR1) time.sleep(3)
gpl-3.0
Tuxos/Symcon-LaMetric
LaMetric/setbluetooth.php
365
<? SetValue($_IPS['VARIABLE'], $_IPS['VALUE']); $parentid = IPS_GetParent($_IPS['VARIABLE']); $bluetoothnameid = IPS_GetObjectIDByName('Bluetooth Name', $parentid); $btid = IPS_GetObjectIDByName('Bluetooth', $parentid); $mode = GetValueBoolean($btid); $bluetoothname = GetValueString($bluetoothnameid); LM_bluetooth($parentid, $bluetoothname, $mode); ?>
gpl-3.0
Altaxo/Altaxo
Altaxo/CoreTest/Science/Thermodynamics/Fluids/Fluids/Test_Methyl_Z_Z_Z__9_12_15_octadecatrienoate.cs
35732
#region Copyright ///////////////////////////////////////////////////////////////////////////// // Altaxo: a data processing and data plotting program // Copyright (C) 2002-2018 Dr. Dirk Lellinger // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // ///////////////////////////////////////////////////////////////////////////// #endregion Copyright using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Altaxo.Science.Thermodynamics.Fluids { /// <summary> /// Tests and test data for <see cref="Methyl_Z_Z_Z__9_12_15_octadecatrienoate"/>. /// </summary> /// <remarks> /// <para>Reference:</para> /// <para>The test data was created automatically using calls into the TREND.DLL of the following software:</para> /// <para>TREND 3.0.: Span, R.; Eckermann, T.; Herrig, S.; Hielscher, S.; Jäger, A.; Thol, M. (2016): TREND.Thermodynamic Reference and Engineering Data 3.0.Lehrstuhl für Thermodynamik, Ruhr-Universität Bochum.</para> /// </remarks> public class Test_Methyl_Z_Z_Z__9_12_15_octadecatrienoate : FluidTestBase { public Test_Methyl_Z_Z_Z__9_12_15_octadecatrienoate() { _fluid = Methyl_Z_Z_Z__9_12_15_octadecatrienoate.Instance; _testDataMolecularWeight = 0.29245618; _testDataTriplePointTemperature = 218.65; _testDataTriplePointPressure = 8.28E-12; _testDataTriplePointLiquidMoleDensity = double.NaN; _testDataTriplePointVaporMoleDensity = double.NaN; _testDataCriticalPointTemperature = 772; _testDataCriticalPointPressure = 1368997.20361407; _testDataCriticalPointMoleDensity = 847.3; _testDataNormalBoilingPointTemperature = 629.129108153121; _testDataNormalSublimationPointTemperature = null; _testDataIsMeltingCurveImplemented = false; _testDataIsSublimationCurveImplemented = false; // TestData contains: // 0. Temperature (Kelvin) // 1. Mole density (mol/m³) // 2. Pressure (Pa) // 3. Internal energy (J/mol) // 4. Enthalpy (J/mol) // 5. Entropy (J/mol K) // 6. Isochoric heat capacity (J/(mol K)) // 7. Isobaric heat capacity (J/(mol K)) // 8. Speed of sound (m/s) _testDataEquationOfState = new (double temperature, double moleDensity, double pressure, double internalEnergy, double enthalpy, double entropy, double isochoricHeatCapacity, double isobaricHeatCapacity, double speedOfSound)[] { ( 303, 3049.6092451394, 1000.00000088135, -230888.067472743, -230887.73956188, -507.673056105678, 521.633695025975, 619.80686989155, 1392.55344712477 ), ( 342, 2954.14763645882, 1000.00000004701, -206544.850667017, -206544.5121599, -432.110492564209, 540.446954843177, 630.010246882184, 1260.4968617032 ), ( 381, 2862.03538181384, 999.999999177481, -181656.825317368, -181656.475915678, -363.213781211889, 562.975057276659, 647.237415209079, 1141.11851561199 ), ( 420, 2771.0496851496, 999.999999060367, -155999.25461428, -155998.893740203, -299.116591860704, 587.885348667327, 669.19493980797, 1029.77979574988 ), ( 459, 2679.16834951966, 999.999981673083, -129415.386914051, -129415.013663903, -238.606885498609, 614.337164978625, 694.573402028344, 923.481348497293 ), ( 498, 0.241978111652348, 1000.00000000145, -24948.5068001469, -20815.9016104752, -11.743166969531, 602.287041755331, 610.694859452971, 119.583472053997 ), ( 537, 0.224294522222973, 1000.00000000061, -786.410603187477, 3672.01303591727, 35.5826801240527, 636.526752953938, 644.909381627406, 124.190133024843 ), ( 576, 0.209037021531256, 1000.00000000027, 24687.6706262696, 29471.5122284652, 81.94842738911, 669.564731927822, 677.930653040345, 128.621615322223 ), ( 615, 0.195733391071248, 1000.00000000013, 51424.2800354229, 56533.2703539737, 127.397103501133, 701.265140231256, 709.619671162937, 132.898895041249 ), ( 654, 0.184028097528086, 1000.00000000007, 79369.1595505743, 84803.1123731722, 171.956127103691, 731.522392071944, 739.868925656007, 137.038555346447 ), ( 693, 0.173647810148598, 1000.00000000003, 108464.63854003, 114223.42121137, 215.643018852856, 760.269076904994, 768.609825814499, 141.054064128513 ), ( 732, 0.164378647090256, 1000.00000000001, 138651.144738942, 144734.659950324, 258.46971125462, 787.475482017841, 795.811925123988, 144.956603363851 ), ( 771, 0.156050685122544, 1000.00000000001, 169868.595843499, 176276.770208224, 300.445574542678, 813.144742568356, 821.477894246816, 148.755625160611 ), ( 810, 0.148527128895026, 1000.00000000001, 202057.559628688, 208790.336377553, 341.579398861383, 837.306304015017, 845.636878512082, 152.459236861314 ), ( 849, 0.141696562771076, 1000, 235160.151526896, 242217.485737717, 381.880591086593, 860.009265172103, 868.337778456477, 156.074476127174 ), ( 888, 0.135467297084765, 999.999999999998, 269120.683135965, 276502.538546974, 421.359814283533, 881.316396246933, 889.643230246294, 159.607513085281 ), ( 927, 0.129763170782085, 1000, 303886.095671846, 311592.442503331, 460.029251585013, 901.299147033318, 909.624590934093, 163.063802689964 ), ( 966, 0.124520387462263, 1000, 339406.218721484, 347437.03215196, 497.902630362391, 920.033691363297, 928.357968705194, 166.448202145675 ), ( 303, 3049.6281006455, 9999.99999800088, -230888.804192614, -230885.525104257, -507.675487561196, 521.636887456412, 619.806817791646, 1392.5828458912 ), ( 342, 2954.17021413993, 10000.0000003651, -206545.695154686, -206542.310109386, -432.112961868004, 540.450076040413, 630.009644619419, 1260.53143400805 ), ( 381, 2862.06255105297, 10000.0000005612, -181657.804240098, -181654.310256363, -363.216350610766, 562.97820170427, 647.236121189387, 1141.15934705564 ), ( 420, 2771.08271682207, 9999.99999883773, -156000.404405342, -155996.79570758, -299.1193295148, 587.888593419797, 669.192714378058, 1029.8284052456 ), ( 459, 2679.20914452494, 9999.99998193349, -129416.75935517, -129413.026910466, -238.609875634506, 614.340575717798, 694.569831171033, 923.539810038334 ), ( 498, 2584.32200802196, 9999.99993117877, -101790.025972107, -101786.156485293, -180.857002371842, 641.685852233135, 722.590073034655, 820.192338625205 ), ( 537, 2483.859709625, 9999.99985092069, -73025.6584792664, -73021.6324870527, -125.261398567881, 669.386785984328, 752.884649251017, 718.16741847575 ), ( 576, 2.11158211975695, 10000.0000028476, 24553.2564374399, 29289.0419459848, 62.5698989475105, 670.009407807567, 678.856539081833, 127.36810348763 ), ( 615, 1.97275084112371, 10000.0000013291, 51312.7643848394, 56381.8282487955, 108.070785401163, 701.575274225367, 710.300999771374, 131.891016694653 ), ( 654, 1.85171154214099, 10000.0000006508, 79274.3877787712, 84674.7969532415, 152.666321439657, 731.74234614811, 740.383986683351, 136.217634112586 ), ( 693, 1.74508245518476, 10000.0000003299, 108382.424926731, 114112.813178942, 196.379544289608, 760.428231777161, 769.009656662551, 140.379354221218 ), ( 732, 1.65033628321241, 10000.0000001714, 138578.594952918, 144637.966065275, 239.225790543798, 787.593229588158, 796.130169597148, 144.39885621705 ), ( 771, 1.56553171511322, 10000.0000000904, 169803.669896387, 176191.276039113, 281.216573574141, 813.233916986332, 821.737049351726, 148.293214281189 ), ( 810, 1.48914455244593, 10000.000000048, 201998.789571331, 208714.054374619, 322.362062726507, 837.375457346377, 845.852239537806, 152.075750218935 ), ( 849, 1.41995660865111, 10000.0000000254, 235106.458010273, 242148.926730162, 362.672573201467, 860.064150884088, 868.519935679205, 155.757174763156 ), ( 888, 1.3569798028848, 10000.0000000133, 269071.255111843, 276440.561551596, 402.159380590615, 881.360929749464, 889.799658773623, 159.346315368054 ), ( 927, 1.29940263657713, 10000.0000000068, 303840.310587913, 311536.154600011, 440.835090958972, 901.33602738729, 909.760672324543, 162.850596293311 ), ( 966, 1.24655144441327, 10000.0000000034, 339363.588880069, 347385.720694059, 478.713730533235, 920.06480515736, 928.477654825482, 166.276365803287 ), ( 275, 3121.74408056478, 15000.0000007919, -248217.876093662, -248213.071087354, -567.684417585466, 511.798651898581, 619.123151785222, 1499.20482742603 ), ( 300, 3057.19402417432, 14999.9999991556, -232748.020955956, -232743.114496019, -513.842125289367, 520.406700823566, 619.417446080111, 1403.47037113321 ), ( 325, 2995.23407929312, 15000.0000004047, -217207.449365544, -217202.441409704, -464.088146140334, 531.683468900003, 624.50723887965, 1316.19421206265 ), ( 350, 2935.09448313099, 14999.9999978003, -201494.079621494, -201488.969053475, -417.512323102683, 544.825422455886, 633.06619567462, 1235.21515626145 ), ( 375, 2876.12240357603, 14999.9999992461, -185532.676464437, -185527.461109214, -373.467543975175, 559.333753488617, 644.234806318925, 1158.93053439777 ), ( 400, 2817.7411341043, 15000.0000005727, -169265.645774276, -169260.322361199, -331.477844256495, 574.876723110346, 657.437809518348, 1086.15496786581 ), ( 425, 2759.41515148215, 15000.0000050167, -152647.424281531, -152641.988347037, -291.183180035915, 591.210451844854, 672.274311265021, 1015.99820339334 ), ( 450, 2700.61824297128, 15000.0000189453, -135640.976004677, -135635.421720928, -252.304850647224, 608.13723193451, 688.455625516053, 947.771352571244 ), ( 475, 2640.80178875059, 15000.0000399638, -118215.435480378, -118209.75538727, -214.622774942082, 625.485871786901, 705.773338876097, 880.920213805837 ), ( 500, 2579.35960093793, 15000.0000581648, -100344.293828045, -100338.478431055, -177.959723031394, 643.103931093746, 724.086421613947, 814.980432173866 ), ( 525, 2515.58439223133, 15000.0000533855, -82003.7365767492, -81997.7737475554, -142.169698575411, 660.855841115778, 743.321350907629, 749.549148318684 ), ( 550, 2448.60840914901, 15000.0000272589, -63170.8376656802, -63164.711737185, -107.128760403271, 678.62373487145, 763.483583299129, 684.269080216893 ), ( 553.024156761166, 2440.23945509469, 15000.0000233678, -60858.1795738249, -60852.0326360758, -102.935413559456, 680.769209762906, 765.989326821275, 676.366993628698 ), ( 575, 3.1914581242119, 15000.0000151175, 23807.174508665, 28507.2205162628, 57.8867294206764, 669.436618866458, 678.571902671414, 126.536214723383 ), ( 625, 2.92236755262821, 15000.0000056728, 58310.0538855378, 63442.8784654517, 116.123413528276, 709.607387557503, 718.510139177025, 132.481109165825 ), ( 675, 2.69729356703433, 15000.0000022973, 94760.1518674221, 100321.281803601, 172.868795908094, 747.479439067723, 756.23686795125, 138.06474231751 ), ( 725, 2.50562007782162, 15000.0000009779, 133039.902509896, 139026.444577366, 228.170379526468, 782.899405565606, 791.56071430049, 143.365395148901 ), ( 775, 2.34009929304501, 15000.0000004284, 173026.261370012, 179436.245786063, 282.057902765241, 815.826751941345, 824.42122060728, 148.433785869549 ), ( 825, 2.19554283187892, 15000.0000001896, 214596.011015079, 221428.034413754, 334.554822372515, 846.305897163612, 854.851843330477, 153.305080960459 ), ( 875, 2.0681032149409, 15000.0000000833, 257629.485493955, 264882.508404861, 385.684375429379, 874.438968332698, 882.948394864834, 158.00507010246 ), ( 925, 1.95484897087358, 15000.0000000356, 302012.961068681, 309686.188117691, 435.472387746063, 900.36332615538, 908.84443562853, 162.55353454318 ), ( 975, 1.8534980165152, 15000.0000000145, 347640.022005137, 355732.828075799, 483.948220848002, 924.23465643299, 932.693267045807, 166.96619096553 ), ( 275, 3121.90047823794, 99999.9999977652, -248224.219757398, -248192.187986785, -567.707488808834, 511.829923982341, 619.12586558433, 1499.45158892159 ), ( 300, 3057.369612117, 100000.000000929, -232754.90623755, -232722.198383189, -513.865079828328, 520.436937496984, 619.417325591532, 1403.74451085074 ), ( 325, 2995.43108958208, 100000.000001091, -217214.951218468, -217181.567042031, -464.111232649335, 531.713110869759, 624.503957844526, 1316.49829347888 ), ( 350, 2935.31575789411, 99999.9999999364, -201502.288480577, -201468.220595467, -417.535781204819, 544.854868195824, 633.059319819694, 1235.55271014741 ), ( 375, 2876.37155336235, 99999.999998054, -185541.701530162, -185506.935507017, -373.491615434502, 559.36335379822, 644.223736413864, 1159.3060789368 ), ( 400, 2818.02275847772, 100000.000001708, -169275.620247493, -169240.134373683, -331.502785537263, 574.906784683636, 657.421705104431, 1086.57408436506 ), ( 425, 2759.73515698998, 100000.00000684, -152658.513176557, -152622.277815438, -291.209277238036, 591.241246734597, 672.251985307454, 1016.46769850164 ), ( 450, 2700.98431153117, 100000.000018653, -135653.387582201, -135616.364042452, -252.332438342016, 608.169009152452, 688.425388828005, 948.29953056564 ), ( 475, 2641.22408228848, 100000.000041465, -118229.438100942, -118191.576868072, -214.652261470707, 625.518868098742, 705.732757370386, 881.517288545086 ), ( 500, 2579.85184828766, 100000.000059716, -100360.241351001, -100321.479435224, -177.99162658199, 643.138378432842, 724.031920950833, 815.659125714163 ), ( 525, 2516.16561756287, 100000.000056329, -82022.1078320264, -81982.3648201363, -142.204701496429, 660.891966939096, 743.247546308304, 750.325554085254 ), ( 550, 2449.30578365821, 100000.00002892, -63192.3001418572, -63151.4722465833, -107.167795238688, 678.661747821479, 763.382091826632, 685.163923337972 ), ( 575, 2378.16950039918, 100000.000000349, -43846.8160646, -43804.7669171429, -72.7714721482913, 696.349711414191, 784.540720745085, 619.862609758818 ), ( 600, 2301.2755763262, 100000.000000005, -23957.2782741787, -23913.8241129175, -38.9128234425456, 713.881263048391, 806.980890029434, 554.150952124645 ), ( 625, 2216.53388995054, 100000.000000234, -3485.99537410163, -3440.87988976204, -5.48632980686321, 731.211343701244, 831.217909654896, 487.791426283345 ), ( 627.525297269034, 2207.42830099226, 100000.000000202, -1383.85591544431, -1338.55433081063, -2.12938967680633, 732.950079529958, 833.799214345199, 481.042919683797 ), ( 650, 19.9645600106202, 100000, 75323.6438298837, 80332.5195550088, 127.390910182558, 731.188998118455, 743.709436833441, 126.823485993775 ), ( 700, 18.1607324556306, 100000, 112883.497258363, 118389.883096287, 183.782128254912, 767.010525435536, 778.355361059426, 134.345910361679 ), ( 750, 16.7115827795308, 100000, 152155.810817671, 158139.684476992, 238.61810992644, 800.68929145666, 811.315359604934, 141.009782290194 ), ( 800, 15.5080198890586, 100000, 193038.941026317, 199487.217512637, 291.977550312276, 832.080983568269, 842.231138363071, 147.083987754084 ), ( 850, 14.4852279814191, 99999.9999999997, 235423.30763802, 242326.892457553, 343.911521240374, 861.181046030036, 870.996691415582, 152.723311018841 ), ( 900, 13.6012562150382, 100000.000094284, 279199.151616666, 286551.413680792, 394.460337945764, 888.066607106579, 897.63605314876, 158.024763475215 ), ( 950, 12.8272256274751, 100000.000037947, 324260.66848729, 332056.586555789, 443.661108814099, 912.860241607527, 922.241837984669, 163.053315906546 ), ( 1000, 12.1423238881564, 100000.000014195, 370508.159297898, 378743.815086304, 491.550967185889, 935.70701180232, 944.941136892507, 167.854843815447 ), ( 275, 3121.90291572404, 101325.000000625, -248224.318614244, -248191.86244801, -567.707848379819, 511.830411367964, 619.125907989413, 1499.45543476553 ), ( 300, 3057.37234859934, 101324.999998967, -232755.013530589, -232721.872326821, -513.865437570019, 520.4374087319, 619.417323853003, 1403.74878324512 ), ( 325, 2995.43415980939, 101325.000000533, -217215.068114387, -217181.241632283, -464.111592435068, 531.713572820094, 624.503906891105, 1316.50303231427 ), ( 350, 2935.31920610661, 101324.999997702, -201502.416386802, -201467.897142766, -417.536146766278, 544.85532706839, 633.059212902222, 1235.55797036555 ), ( 375, 2876.3754357521, 101324.999999194, -185541.842145818, -185506.615520413, -373.491990535549, 559.363815055679, 644.223564221011, 1159.31193083465 ), ( 400, 2818.02714661418, 101325.000001134, -169275.775644638, -169239.819638989, -331.503174169183, 574.907253099945, 657.421454579208, 1086.58061476063 ), ( 425, 2759.74014275569, 101325.00000584, -152658.685921399, -152621.970508076, -291.209683851539, 591.241726542189, 672.251638014116, 1016.47501324077 ), ( 450, 2700.99001438846, 101325.000019547, -135653.580912389, -135616.066889945, -252.332868139522, 608.169504222514, 688.424918542633, 948.307758732253 ), ( 475, 2641.23066020434, 101325.000040881, -118229.656186734, -118191.29338807, -214.652720798515, 625.519382108756, 705.732126325168, 881.526588828254 ), ( 500, 2579.8595145716, 101325.000059564, -100360.489688514, -100321.214294064, -177.99212348891, 643.138914981277, 724.031073724379, 815.669695650429 ), ( 525, 2516.17466761527, 101325.000056491, -82022.3938537119, -81982.1243917542, -142.20524657372, 660.892529550171, 743.246399483399, 750.337643363597 ), ( 550, 2449.31663904317, 101325.000028646, -63192.6342001571, -63151.2655186181, -107.168402948593, 678.662339721827, 763.38051569447, 685.17785318237 ), ( 575, 2378.18278474376, 101325.000000274, -43847.2130897454, -43804.60702908, -72.7721630380039, 696.35033480449, 784.538505138023, 619.878802061395 ), ( 600, 2301.29225341348, 101325.000000075, -23957.7607301303, -23913.7311203101, -38.9136280641173, 713.881917189434, 806.977675749263, 554.169976073215 ), ( 625, 2216.55553392816, 101325.000000193, -3486.59894633561, -3440.8861282044, -5.4872962319691, 731.21202005443, 831.21303574921, 487.814082737611 ), ( 628.129108153121, 2205.2567209833, 101325.000000068, -880.878694211392, -834.931662722519, -1.32817855715992, 733.366182299299, 834.415567793111, 479.451107530383 ), ( 650, 20.2513954886568, 101325, 75307.4675386988, 80310.8264458296, 127.256158409213, 731.228466050992, 743.820472296121, 126.682514015663 ), ( 700, 18.4156677269995, 101325, 112870.574310303, 118372.682705289, 183.654052844684, 767.035307302477, 778.428025290229, 134.242639041376 ), ( 750, 16.9425930290963, 101325, 152145.043295119, 158125.532812042, 238.49424980533, 800.705680181964, 811.366536616695, 140.931959697561 ), ( 800, 15.7200865746462, 101325, 193029.697333734, 199475.272523086, 291.856543028883, 832.092359019767, 842.269227416745, 147.024521821329 ), ( 850, 14.6817455878114, 101325, 235415.197874327, 242316.625187175, 343.792550775048, 861.189306951248, 871.026279897196, 152.677703795167 ), ( 900, 13.7846815811104, 101325.000099155, 279191.9211365, 286542.471782371, 394.342884184014, 888.072859297133, 897.659822971931, 157.989967744036 ), ( 950, 12.9994162343023, 101325.000039883, 324254.142847833, 332048.723636201, 443.544822812548, 912.86515012421, 922.261445148928, 163.027162711901 ), ( 1000, 12.3047308078919, 101325.00001491, 370502.213948636, 378736.851633674, 491.435604593731, 935.710988990629, 944.957652636183, 167.835729665971 ), ( 275, 3121.93175817317, 117004.153924766, -248225.488350152, -248188.01022347, -567.712103139666, 511.836178547817, 619.126410019448, 1499.50094217533 ), ( 300, 3057.40472882734, 117004.153922515, -232756.28307915, -232718.013970445, -513.869670659043, 520.44298477081, 619.417303605691, 1403.7993376343 ), ( 325, 2995.47048890335, 117004.153924459, -217216.451277428, -217177.390918009, -464.11584968131, 531.719038958487, 624.503304390148, 1316.55910555853 ), ( 350, 2935.3600074276, 117004.153925352, -201503.929813511, -201464.069573667, -417.540472319557, 544.86075674257, 633.057948330071, 1235.62021238334 ), ( 375, 2876.42137402922, 117004.153924745, -185543.505935228, -185502.828948545, -373.496428923624, 559.369272893835, 644.221527462555, 1159.38117316168 ), ( 400, 2818.0790684506, 117004.153928259, -169277.614306057, -169236.09518928, -331.507772607049, 574.912795577941, 657.418491229794, 1086.65788431288 ), ( 425, 2759.79913498499, 117004.153931905, -152660.72980748, -152618.333912631, -291.214494984745, 591.247403724251, 672.247530075717, 1016.56156192682 ), ( 450, 2701.05748998375, 117004.153945469, -135655.868314899, -135612.550409086, -252.337953499874, 608.175361893313, 688.419355948827, 948.405113195035 ), ( 475, 2641.30848741886, 117004.153967453, -118232.236423447, -118187.938623881, -214.658155439654, 625.525463754295, 705.72466256417, 881.636625662769 ), ( 500, 2579.9502159425, 117004.153986645, -100363.427750479, -100318.076428092, -177.998002588042, 643.145263144038, 724.021053664128, 815.794750564125 ), ( 525, 2516.28173603476, 117004.153983229, -82025.7776180613, -81979.2787891315, -142.21169535541, 660.899185883654, 743.232837230605, 750.480668271148 ), ( 550, 2449.44505840782, 117004.153955993, -63196.5860488831, -63148.8184316612, -107.175592376576, 678.669342348206, 763.361878599618, 685.342644956619 ), ( 575, 2378.3399262758, 117004.153927139, -43851.9094845732, -43802.7137608525, -72.7803359556863, 696.357709704982, 784.51231061056, 620.070346151414 ), ( 600, 2301.48950570754, 117004.153927082, -23963.4670993004, -23912.6286515747, -38.9231454552911, 713.889655597034, 806.939682579991, 554.394996032885 ), ( 625, 2216.81149046334, 117004.153926758, -3493.73677051714, -3440.95639003368, -5.49872584881242, 731.220021099531, 831.155444502248, 488.082033710963 ), ( 634.816982250148, 2180.78930863309, 117004.153927066, 4714.4836743134, 4768.13587879913, 7.53352978938138, 737.967533015547, 841.349047629068, 461.814875406455 ), ( 650, 23.6973604297308, 117004.153926862, 75113.4433851399, 80050.877420201, 125.755851974991, 731.703287280307, 745.183448613641, 124.990800867456 ), ( 700, 21.4638197933025, 117004.153926862, 112716.322600297, 118167.549597803, 182.235211059111, 767.331744716514, 779.309449792389, 133.011607247337 ), ( 750, 19.6965165411471, 117004.153926862, 152016.897157471, 157957.244714991, 237.126353515447, 800.900983428183, 811.982811409711, 140.00812726594 ), ( 800, 18.2431480319706, 117004.153926862, 192919.897390794, 199333.491893334, 290.522917061789, 832.227561119336, 842.725669865754, 146.320610881592 ), ( 850, 17.0165061646801, 117004.153926862, 235318.993618635, 242194.914726913, 342.483291216853, 861.287303404443, 871.379641065274, 152.139001551236 ), ( 900, 15.9616230980202, 117004.153926862, 279106.227675995, 286436.569534611, 393.051715149997, 888.146923212805, 897.942984423561, 157.579706826028 ), ( 950, 15.0414010318172, 117004.15399539, 324176.855768777, 331955.662659696, 442.267551770861, 912.923237946141, 922.494580676984, 162.719325283278 ), ( 1000, 14.2295080412334, 117004.15395228, 370431.835604907, 378654.477850389, 490.169305289161, 935.758021424941, 945.153749543446, 167.611164233565 ), ( 275, 3123.55276430185, 1000000.00000086, -248291.15871783, -247971.01045223, -567.951241854416, 512.160337303367, 619.155382893627, 1502.05870209195 ), ( 300, 3059.22396282843, 999999.999997237, -232827.52857637, -232500.648291649, -514.107517470909, 520.7563070663, 619.417123792313, 1406.63975731677 ), ( 325, 2997.51079019713, 999999.999999274, -217294.037497827, -216960.427355949, -464.354966655052, 532.026074515123, 624.470693258217, 1319.70828281805 ), ( 350, 2937.65041480859, 1000000.00000034, -201588.778697467, -201248.370596163, -417.783321108377, 545.165609151326, 632.988549537477, 1239.1140866062 ), ( 375, 2878.99870730637, 999999.999998467, -185636.728107708, -185289.385124378, -373.745484343343, 559.67554301352, 644.109340530444, 1163.2656618171 ), ( 400, 2820.99012161022, 1000000.00000202, -169380.560715121, -169026.075248355, -331.765649183134, 575.223617310297, 657.255119901004, 1090.98956215804 ), ( 425, 2763.10382215476, 1000000.00000621, -152775.06858352, -152413.156739315, -291.484095936975, 591.565539699217, 672.021155516579, 1021.40918258004 ), ( 450, 2704.83345247088, 1000000.00002165, -135783.696612904, -135413.988082751, -252.622656551181, 608.503319991641, 688.113236848917, 953.852183837808 ), ( 475, 2645.65797385136, 1000000.0000464, -118376.244027747, -117998.266220362, -214.962059417838, 625.865603942734, 705.314821150367, 887.785284817743 ), ( 500, 2585.01059764355, 1000000.00006925, -100527.141241602, -100140.295632156, -178.326274632963, 643.49986825606, 723.472555507591, 822.771335635426 ), ( 525, 2522.24203611939, 1000000.00007302, -82213.9352384919, -81817.4625821201, -142.571086267581, 661.270459974091, 742.49358373987, 758.443595635899 ), ( 550, 2456.57282263501, 1000000.00004677, -63415.7333674152, -63008.662186446, -107.575239489117, 679.059263770513, 762.35182280325, 694.493620918576 ), ( 575, 2387.02669927755, 1000000.00001382, -44111.3855446237, -43692.4543276765, -73.2330763598169, 696.767573514536, 783.103780929795, 630.670688882837 ), ( 600, 2312.3316842002, 999999.999999931, -24277.1220542905, -23844.6581448813, -39.4477859441377, 714.31891339488, 804.919077195538, 566.790706523563 ), ( 625, 2230.7636189857, 999999.999998959, -3883.13381384577, -3434.85682407953, -6.12425705312448, 731.663450949307, 828.141303401161, 502.747049275871 ), ( 650, 2139.87550476147, 999999.999998724, 17112.1270746716, 17579.4439806194, 26.8403391195689, 748.785636228339, 853.428955907337, 438.492355590502 ), ( 675, 2035.94938153398, 999999.999997334, 38773.6266603767, 39264.7980073008, 59.5734305785066, 765.71863277761, 882.161037980477, 373.883581769755 ), ( 700, 1912.5566247233, 999999.999995503, 61221.3244680366, 61744.1848043365, 92.2704025946513, 782.576940423502, 917.923634279543, 308.060669808703 ), ( 725, 1755.14485401019, 999999.9999911, 84749.19571899, 85318.9492625259, 125.355528016984, 799.673611126428, 973.988545654181, 237.343441023782 ), ( 750, 1502.81408368092, 999999.999999768, 110646.580049965, 111311.99835477, 160.587415564191, 818.503695867526, 1162.0281085211, 145.764040041865 ), ( 752.716516624252, 1457.19466485224, 1000000.00000001, 113868.788054107, 114555.038164762, 164.90358196027, 820.998258558343, 1230.94865967001, 131.925271597893 ), ( 775, 256.720967045214, 1000000, 162797.320292349, 166692.600103382, 233.702537716697, 830.599052450846, 933.016367139911, 90.8594303735065 ), ( 825, 197.022847543882, 1000000, 207042.515921837, 212118.069404421, 290.511913274052, 854.830857891283, 900.935638564568, 116.930459372307 ), ( 875, 168.050522450151, 1000000, 251427.560158951, 257378.151596693, 343.771260948691, 880.135311624395, 911.617327775101, 132.955819077841 ), ( 925, 149.255506909628, 999999.999999997, 296687.310488231, 303387.230784006, 394.901064121625, 904.48660609568, 929.233639853368, 145.070490879375 ), ( 975, 135.546740973178, 1000000, 342946.202995133, 350323.731903761, 444.314913560639, 927.394438423716, 948.27927730014, 155.027326461516 ), ( 303, 3052.60719938496, 1437447.06379596, -231004.987547973, -230534.095955997, -508.059694132159, 522.141387679377, 619.801127242087, 1397.22797287964 ), ( 342, 2957.73369740717, 1437447.06379399, -206678.715018413, -206192.71891097, -432.502770152381, 540.942836093626, 629.918349704703, 1265.98787038377 ), ( 381, 2866.34480388394, 1437447.0637943, -181811.767829006, -181310.276500452, -363.621443550297, 563.473974306428, 647.03789988676, 1147.59405424419 ), ( 420, 2776.27913734068, 1437447.06379304, -156180.888165768, -155663.127885665, -299.550212842022, 588.399298715755, 668.851673532438, 1037.47365678992 ), ( 459, 2685.60983298649, 1437447.06378091, -129631.625176025, -129096.38470806, -239.079389464348, 614.87620304877, 694.024523973333, 932.709923714654 ), ( 498, 2592.37402053821, 1437447.06374157, -102050.898034419, -101496.407419888, -181.382578377484, 642.255447337911, 721.732620507097, 831.317763298594 ), ( 537, 2494.28883879094, 1437447.06367669, -73350.7079603106, -72774.4126085768, -125.868955318696, 669.998811526281, 751.516487980383, 731.854540528507 ), ( 576, 2388.37168343361, 1437447.06368887, -43454.282160346, -42852.4298298819, -72.0917801956002, 697.672640355835, 783.293133803381, 633.269023813057 ), ( 615, 2270.32382276387, 1437447.06379476, -12279.4658203526, -11646.3195487142, -19.6820547330126, 724.964838567566, 817.500538645098, 534.926830090418 ), ( 654, 2133.3618844144, 1437447.06379503, 20287.6257089933, 20961.4200025431, 31.7134110264803, 751.718837627694, 855.5343627604, 436.706572514609 ), ( 693, 1965.36095062716, 1437447.06379355, 54454.3198670653, 55185.7107412632, 82.5303811710172, 778.008894822346, 901.619969829883, 338.441858193033 ), ( 732, 1736.27110191943, 1437447.0637947, 90800.9544789687, 91628.847693459, 133.673083506775, 804.40260867932, 977.057707653329, 234.931811193441 ), ( 771, 1185.90403184104, 1437447.06379479, 134881.281175855, 136093.391958178, 192.73456659377, 837.364153725328, 1794.31876001622, 84.7443879277982 ), ( 810, 367.442053223321, 1437447.06379478, 188586.444852624, 192498.482277805, 264.48751105612, 853.46906602517, 980.478346103205, 95.0514584831924 ), ( 849, 290.678841970157, 1437447.06379478, 224619.899211962, 229565.037475387, 309.188937282274, 870.587175111774, 935.31980432218, 115.982827878756 ), ( 888, 250.383949671136, 1437447.06379478, 260210.884438646, 265951.855717687, 351.092394163762, 888.957522813969, 933.491775785605, 130.377940177794 ), ( 927, 223.762986148308, 1437447.06379478, 296078.164731289, 302502.136311835, 391.373097599257, 907.151882822658, 941.775298027661, 141.637070306728 ), ( 966, 204.218221740384, 1437447.06379478, 332414.485273332, 339453.264925532, 430.416717701072, 924.709976649824, 953.47693863428, 151.019711583145 ), ( 303, 3070.01877511056, 10000000.0000008, -231675.365801754, -228418.056732157, -510.306986886773, 525.094145165805, 619.865380169804, 1424.38799458383 ), ( 342, 2978.42033348192, 9999999.99999909, -207440.266122984, -204082.781657953, -434.768454580803, 543.808510871116, 629.529617473877, 1297.66020219233 ), ( 381, 2890.98510649452, 10000000.0000006, -182684.73852173, -179225.70997899, -365.956852306476, 566.332842385972, 646.106769545082, 1184.59232192879 ), ( 420, 2805.8280855786, 9999999.99999877, -157191.721884095, -153627.711654317, -302.007897365742, 591.312373780388, 667.23140782544, 1080.89165542273 ), ( 459, 2721.42379145379, 9999999.99999594, -130815.835386321, -127141.288249856, -241.719338776586, 617.889745538245, 691.475648294726, 983.949874167394 ), ( 498, 2636.42264334192, 9999999.99998846, -103457.847030389, -99664.8284772971, -184.280077971151, 645.40549465288, 717.865324801975, 892.161259817377 ), ( 537, 2549.52315591049, 9999999.99997865, -75051.5501321002, -71129.2480432582, -129.125921689248, 673.312427383604, 745.687510084591, 804.567661906387 ), ( 576, 2459.38379091118, 9999999.99997616, -45555.5948216624, -41489.5356580085, -75.8549352599422, 701.162145723412, 774.411699152234, 720.720095258335 ), ( 615, 2364.57512939401, 9999999.99998625, -14947.6714052333, -10718.5818425139, -24.1744440664141, 728.606760241551, 803.64298208727, 640.670107217173 ), ( 654, 2263.59468138578, 9999999.99999713, 16779.4586251098, 21197.2106556434, 26.1328259025839, 755.396962704811, 833.075175481162, 565.009334196646 ), ( 693, 2154.98119385935, 9999999.99999946, 49620.1166012552, 54260.5283266543, 75.2301224848886, 781.370326978864, 862.451421327805, 494.820539528523 ), ( 732, 2037.52235028015, 9999999.99999989, 83557.3866012603, 88465.30822412, 123.241542658346, 806.425309290172, 891.596421304838, 431.327348943702 ), ( 771, 1910.39651980117, 9999999.99999986, 118568.25975771, 123802.775156137, 170.268172074382, 830.479945644977, 920.578866113846, 375.215260988123 ), ( 810, 1773.08649176161, 10000000.0000001, 154632.682031557, 160272.564827159, 216.406714606658, 853.430671655984, 949.700545952077, 326.387209879232 ), ( 849, 1625.84167960775, 10000000.0000435, 191723.680010154, 197874.340388387, 261.740435704103, 875.139365899084, 978.30204355923, 285.375688927108 ), ( 888, 1472.7742330142, 9999999.99975398, 229731.256540197, 236521.163489674, 306.242222007394, 895.459648328262, 1002.27574474141, 255.243714237994 ), ( 927, 1325.26284720672, 9999999.99999932, 268374.613636199, 275920.286572761, 349.661738922611, 914.314884724333, 1016.45714335769, 238.765095388617 ), ( 966, 1195.49710691485, 10000000.0000001, 307336.699604317, 315701.42080871, 391.696527620193, 931.797932461001, 1022.80156313751, 233.260319330719 ), }; // TestData contains: // 0. Temperature (Kelvin) // 1. Pressure (Pa) // 2. Saturated liquid density (mol/m³ // 3. Saturated vapor density (mol/m³) _testDataSaturatedProperties = new (double temperature, double pressure, double saturatedLiquidMoleDensity, double saturatedVaporMoleDensity)[] { ( 287.81875, 7.29543066433176E-05, 3088.23974608475, 3.04857705780834E-08 ), ( 356.9875, 0.382719805185252, 2918.47972401371, 0.00012894201895611 ), ( 426.15625, 67.501611920041, 2756.6536735836, 0.0190552835858837 ), ( 495.325, 1973.67810299881, 2590.93027542427, 0.481115415281294 ), ( 564.49375, 20346.7067307031, 2407.93705364818, 4.44509250753434 ), ( 633.6625, 111747.188053914, 2185.02511817058, 23.3481806821181 ), ( 702.83125, 422357.189357605, 1869.27536075426, 96.7400943319196 ), }; } [Fact] public override void CASNumberAttribute_Test() { base.CASNumberAttribute_Test(); } [Fact] public override void ConstantsAndCharacteristicPoints_Test() { base.ConstantsAndCharacteristicPoints_Test(); } [Fact] public override void EquationOfState_Test() { base.EquationOfState_Test(); } [Fact] public override void SaturatedVaporPressure_TestMonotony() { base.SaturatedVaporPressure_TestMonotony(); } [Fact] public override void SaturatedVaporPressure_TestInverseIteration() { base.SaturatedVaporPressure_TestInverseIteration(); } [Fact] public override void SaturatedVaporProperties_TestData() { base.SaturatedVaporProperties_TestData(); } [Fact] public override void MeltingPressure_TestImplemented() { base.MeltingPressure_TestImplemented(); } [Fact] public override void SublimationPressure_TestImplemented() { base.SublimationPressure_TestImplemented(); } } }
gpl-3.0
tutao/tutanota
src/api/entities/tutanota/ReceiveInfoServiceData.ts
1182
import {create} from "../../common/utils/EntityUtils.js" import {TypeRef, downcast} from "@tutao/tutanota-utils" import type {TypeModel} from "../../common/EntityTypes.js" export const ReceiveInfoServiceDataTypeRef: TypeRef<ReceiveInfoServiceData> = new TypeRef("tutanota", "ReceiveInfoServiceData") export const _TypeModel: TypeModel = { "name": "ReceiveInfoServiceData", "since": 12, "type": "DATA_TRANSFER_TYPE", "id": 570, "rootId": "CHR1dGFub3RhAAI6", "versioned": false, "encrypted": false, "values": { "_format": { "id": 571, "type": "Number", "cardinality": "One", "final": false, "encrypted": false }, "language": { "id": 1121, "type": "String", "cardinality": "One", "final": true, "encrypted": false } }, "associations": {}, "app": "tutanota", "version": "49" } export function createReceiveInfoServiceData(values?: Partial<ReceiveInfoServiceData>): ReceiveInfoServiceData { return Object.assign(create(_TypeModel, ReceiveInfoServiceDataTypeRef), downcast<ReceiveInfoServiceData>(values)) } export type ReceiveInfoServiceData = { _type: TypeRef<ReceiveInfoServiceData>; _format: NumberString; language: string; }
gpl-3.0
b03605079/darkstar
scripts/zones/Western_Altepa_Desert/Zone.lua
2558
----------------------------------- -- -- Zone: Western_Altepa_Desert (125) -- ----------------------------------- package.loaded["scripts/zones/Western_Altepa_Desert/TextIDs"] = nil; require("scripts/zones/Western_Altepa_Desert/TextIDs"); require("scripts/globals/icanheararainbow"); require("scripts/globals/weather"); require("scripts/globals/zone"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17289795,17289796,17289797}; SetFieldManual(manuals); -- King Vinegarroon SetRespawnTime(17289575, 900, 10800); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) cs = -1; if( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( -19.901, 13.607, 440.058, 78); end if( triggerLightCutscene( player)) then -- Quest: I Can Hear A Rainbow cs = 0x0002; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if( csid == 0x0002) then lightCutsceneUpdate( player); -- Quest: I Can Hear A Rainbow end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0002) then lightCutsceneFinish( player); -- Quest: I Can Hear A Rainbow end end; function onZoneWeatherChange(weather) if(GetMobAction(17289575) == 24 and (weather == WEATHER_DUST_STORM or weather == WEATHER_SAND_STORM)) then SpawnMob(17289575); -- King Vinegarroon elseif(GetMobAction(17289575) == 16 and (weather ~= WEATHER_DUST_STORM and weather ~= WEATHER_SAND_STORM)) then DespawnMob(17289575); end end;
gpl-3.0
rg2796/ModTest
src/main/java/com/robert/elevators/init/Recipes.java
812
package com.robert.elevators.init; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import java.rmi.registry.Registry; /** * Created by Robert on 07/09/2014. */ public class Recipes { public static void init() { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.mapleLeaf), " s ","sss"," s ",'s',"stickWood")); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(ModBlocks.flag),new ItemStack(Items.dye, 1, 1),new ItemStack(Items.dye, 1, 11),new ItemStack(Blocks.lapis_block),new ItemStack(Blocks.wool))); } }
gpl-3.0
amenonsen/ansible
lib/ansible/modules/network/fortios/fortios_system_snmp_community.py
19814
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # 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 <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_system_snmp_community short_description: SNMP community configuration in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify system_snmp feature and community category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.5 version_added: "2.9" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate IP address. type: str required: false username: description: - FortiOS or FortiGate username. type: str required: false password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol. type: bool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true state: description: - Indicates whether to create or remove the object. type: str required: true choices: - present - absent system_snmp_community: description: - SNMP community configuration. default: null type: dict suboptions: events: description: - SNMP trap events. type: str choices: - cpu-high - mem-low - log-full - intf-ip - vpn-tun-up - vpn-tun-down - ha-switch - ha-hb-failure - ips-signature - ips-anomaly - av-virus - av-oversize - av-pattern - av-fragmented - fm-if-change - fm-conf-change - bgp-established - bgp-backward-transition - ha-member-up - ha-member-down - ent-conf-change - av-conserve - av-bypass - av-oversize-passed - av-oversize-blocked - ips-pkg-update - ips-fail-open - faz-disconnect - wc-ap-up - wc-ap-down - fswctl-session-up - fswctl-session-down - load-balance-real-server-down - device-new - per-cpu-high hosts: description: - Configure IPv4 SNMP managers (hosts). type: list suboptions: ha_direct: description: - Enable/disable direct management of HA cluster members. type: str choices: - enable - disable host_type: description: - Control whether the SNMP manager sends SNMP queries, receives SNMP traps, or both. type: str choices: - any - query - trap id: description: - Host entry ID. required: true type: int ip: description: - IPv4 address of the SNMP manager (host). type: str source_ip: description: - Source IPv4 address for SNMP traps. type: str hosts6: description: - Configure IPv6 SNMP managers. type: list suboptions: ha_direct: description: - Enable/disable direct management of HA cluster members. type: str choices: - enable - disable host_type: description: - Control whether the SNMP manager sends SNMP queries, receives SNMP traps, or both. type: str choices: - any - query - trap id: description: - Host6 entry ID. required: true type: int ipv6: description: - SNMP manager IPv6 address prefix. type: str source_ipv6: description: - Source IPv6 address for SNMP traps. type: str id: description: - Community ID. required: true type: int name: description: - Community name. type: str query_v1_port: description: - SNMP v1 query port (default = 161). type: int query_v1_status: description: - Enable/disable SNMP v1 queries. type: str choices: - enable - disable query_v2c_port: description: - SNMP v2c query port (default = 161). type: int query_v2c_status: description: - Enable/disable SNMP v2c queries. type: str choices: - enable - disable status: description: - Enable/disable this SNMP community. type: str choices: - enable - disable trap_v1_lport: description: - SNMP v1 trap local port (default = 162). type: int trap_v1_rport: description: - SNMP v1 trap remote port (default = 162). type: int trap_v1_status: description: - Enable/disable SNMP v1 traps. type: str choices: - enable - disable trap_v2c_lport: description: - SNMP v2c trap local port (default = 162). type: int trap_v2c_rport: description: - SNMP v2c trap remote port (default = 162). type: int trap_v2c_status: description: - Enable/disable SNMP v2c traps. type: str choices: - enable - disable ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: SNMP community configuration. fortios_system_snmp_community: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" state: "present" system_snmp_community: events: "cpu-high" hosts: - ha_direct: "enable" host_type: "any" id: "7" ip: "<your_own_value>" source_ip: "84.230.14.43" hosts6: - ha_direct: "enable" host_type: "any" id: "13" ipv6: "<your_own_value>" source_ipv6: "<your_own_value>" id: "16" name: "default_name_17" query_v1_port: "18" query_v1_status: "enable" query_v2c_port: "20" query_v2c_status: "enable" status: "enable" trap_v1_lport: "23" trap_v1_rport: "24" trap_v1_status: "enable" trap_v2c_lport: "26" trap_v2c_rport: "27" trap_v2c_status: "enable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG def login(data, fos): host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_system_snmp_community_data(json): option_list = ['events', 'hosts', 'hosts6', 'id', 'name', 'query_v1_port', 'query_v1_status', 'query_v2c_port', 'query_v2c_status', 'status', 'trap_v1_lport', 'trap_v1_rport', 'trap_v1_status', 'trap_v2c_lport', 'trap_v2c_rport', 'trap_v2c_status'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for elem in data: elem = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def system_snmp_community(data, fos): vdom = data['vdom'] state = data['state'] system_snmp_community_data = data['system_snmp_community'] filtered_data = underscore_to_hyphen(filter_system_snmp_community_data(system_snmp_community_data)) if state == "present": return fos.set('system.snmp', 'community', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('system.snmp', 'community', mkey=filtered_data['id'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_system_snmp(data, fos): if data['system_snmp_community']: resp = system_snmp_community(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "system_snmp_community": { "required": False, "type": "dict", "default": None, "options": { "events": {"required": False, "type": "str", "choices": ["cpu-high", "mem-low", "log-full", "intf-ip", "vpn-tun-up", "vpn-tun-down", "ha-switch", "ha-hb-failure", "ips-signature", "ips-anomaly", "av-virus", "av-oversize", "av-pattern", "av-fragmented", "fm-if-change", "fm-conf-change", "bgp-established", "bgp-backward-transition", "ha-member-up", "ha-member-down", "ent-conf-change", "av-conserve", "av-bypass", "av-oversize-passed", "av-oversize-blocked", "ips-pkg-update", "ips-fail-open", "faz-disconnect", "wc-ap-up", "wc-ap-down", "fswctl-session-up", "fswctl-session-down", "load-balance-real-server-down", "device-new", "per-cpu-high"]}, "hosts": {"required": False, "type": "list", "options": { "ha_direct": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "host_type": {"required": False, "type": "str", "choices": ["any", "query", "trap"]}, "id": {"required": True, "type": "int"}, "ip": {"required": False, "type": "str"}, "source_ip": {"required": False, "type": "str"} }}, "hosts6": {"required": False, "type": "list", "options": { "ha_direct": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "host_type": {"required": False, "type": "str", "choices": ["any", "query", "trap"]}, "id": {"required": True, "type": "int"}, "ipv6": {"required": False, "type": "str"}, "source_ipv6": {"required": False, "type": "str"} }}, "id": {"required": True, "type": "int"}, "name": {"required": False, "type": "str"}, "query_v1_port": {"required": False, "type": "int"}, "query_v1_status": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "query_v2c_port": {"required": False, "type": "int"}, "query_v2c_status": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "status": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "trap_v1_lport": {"required": False, "type": "int"}, "trap_v1_rport": {"required": False, "type": "int"}, "trap_v1_status": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "trap_v2c_lport": {"required": False, "type": "int"}, "trap_v2c_rport": {"required": False, "type": "int"}, "trap_v2c_status": {"required": False, "type": "str", "choices": ["enable", "disable"]} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) # legacy_mode refers to using fortiosapi instead of HTTPAPI legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_system_snmp(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_system_snmp(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
gpl-3.0
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Recyclable.java
1395
/* * Copyright (C) 2013-2022 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre (contact@b3dgs.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.b3dgs.lionengine.game.feature; import com.b3dgs.lionengine.game.Feature; /** * Recyclable marker. * <p> * Allows to recycle a {@link Featurable} and all its {@link Feature} when using * {@link Factory#create(com.b3dgs.lionengine.Media)} or {@link Factory#create(com.b3dgs.lionengine.Media, Class)}. * </p> * <p> * Should be used if object creation is too much time consuming, and only if reuse can be intensive (such as effects or * bullets). * </p> */ public interface Recyclable { /** * Recycle feature, to make it ready for reuse. */ void recycle(); }
gpl-3.0
ihmc/nomads
aci/cpp/netProxy/TCPSocketAdapter.cpp
16031
/* * TCPSocketAdapter.cpp * * This file is part of the IHMC NetProxy Library/Component * Copyright (c) 2010-2018 IHMC. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 (GPLv3) as published by the Free Software Foundation. * * U.S. Government agencies and organizations may redistribute * and/or modify this program under terms equivalent to * "Government Purpose Rights" as defined by DFARS * 252.227-7014(a)(12) (February 2014). * Alternative licenses that allow for use within commercial products may be * available. Contact Niranjan Suri at IHMC (nsuri@ihmc.us) for details. */ #include "Logger.h" #include "TCPSocketAdapter.h" #define checkAndLogMsg(_f_name_, _log_level_, ...) \ if (NOMADSUtil::pLogger && (NOMADSUtil::pLogger->getDebugLevel() >= _log_level_)) \ NOMADSUtil::pLogger->logMsg (_f_name_, _log_level_, __VA_ARGS__) namespace ACMNetProxy { int TCPSocketAdapter::receiveMessage (void * const pBuf, uint32 ui32BufSize) { (void) ui32BufSize; int rc=0, headerLen=0, payLoadLen=0; if ((rc = receive (pBuf, 1)) < 0) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "receive() of 1 byte from socket failed with rc = %d\n", rc); return rc; } headerLen = rc; ProxyMessage * pMsg = reinterpret_cast<ProxyMessage*> (pBuf); uint8 * const ui8Buf = reinterpret_cast<uint8 * const> (pBuf); switch (pMsg->getMessageType()) { case PacketType::PMT_InitializeConnection: { const auto * const pICPM = reinterpret_cast<const InitializeConnectionProxyMessage *> (pMsg); if (0 != (rc = receiveProxyHeader (pICPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_InitializeConnection - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } while (((rc = receive (ui8Buf + headerLen + payLoadLen, pICPM->getPayloadLen() - payLoadLen)) + payLoadLen) < pICPM->getPayloadLen()) { if (rc < 0) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_InitializeConnection - receive() of %u/%u bytes from socket failed with rc = %d\n", payLoadLen, pICPM->getPayloadLen(), rc); return rc; } payLoadLen += rc; } payLoadLen += rc; break; } case PacketType::PMT_ConnectionInitialized: { const auto * const pCIPM = reinterpret_cast<const ConnectionInitializedProxyMessage *> (pMsg); if (0 != (rc = receiveProxyHeader (pCIPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_ConnectionInitialized - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } while (((rc = receive (ui8Buf + headerLen + payLoadLen, pCIPM->getPayloadLen() - payLoadLen)) + payLoadLen) < pCIPM->getPayloadLen()) { if (rc < 0) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_ConnectionInitialized - receive() of %u/%u bytes from socket failed with rc = %d\n", payLoadLen, pCIPM->getPayloadLen(), rc); return rc; } payLoadLen += rc; } payLoadLen += rc; break; } case PacketType::PMT_ICMPMessage: { const auto * const pICMPPM = reinterpret_cast<const ICMPProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pICMPPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_ICMPMessage - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } while (((rc = receive (ui8Buf + headerLen + payLoadLen, pICMPPM->getPayloadLen() - payLoadLen)) + payLoadLen) < pICMPPM->getPayloadLen()) { if (rc < 0) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_ICMPMessage - receive() of %u/%u bytes from socket failed with rc = %d\n", payLoadLen, pICMPPM->getPayloadLen(), rc); return rc; } payLoadLen += rc; } payLoadLen += rc; break; } case PacketType::PMT_UDPUnicastData: { const auto * const pUDPUDPM = reinterpret_cast<const UDPUnicastDataProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pUDPUDPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_UDPUnicastData - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } while (((rc = receive (ui8Buf + headerLen + payLoadLen, pUDPUDPM->getPayloadLen() - payLoadLen)) + payLoadLen) < pUDPUDPM->getPayloadLen()) { if (rc < 0) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_UDPUnicastData - receive() of %u/%u bytes from socket failed with rc = %d\n", payLoadLen, pUDPUDPM->getPayloadLen(), rc); return rc; } payLoadLen += rc; } payLoadLen += rc; break; } case PacketType::PMT_MultipleUDPDatagrams: { const auto * const pMUDPDPM = reinterpret_cast<const MultipleUDPDatagramsProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pMUDPDPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_MultipleUDPDatagrams - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } while (((rc = receive (ui8Buf + headerLen + payLoadLen, pMUDPDPM->getPayloadLen() - payLoadLen)) + payLoadLen) < pMUDPDPM->getPayloadLen()) { if (rc < 0) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_MultipleUDPDatagrams - receive() of %u/%u bytes from socket failed with rc = %d\n", payLoadLen, pMUDPDPM->getPayloadLen(), rc); return rc; } payLoadLen += rc; } payLoadLen += rc; break; } case PacketType::PMT_UDPBCastMCastData: { const auto * const pUDPBMDPM = reinterpret_cast<const UDPBCastMCastDataProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pUDPBMDPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_UDPBCastMCastData - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } while (((rc = receive (ui8Buf + headerLen + payLoadLen, pUDPBMDPM->getPayloadLen() - payLoadLen)) + payLoadLen) < pUDPBMDPM->getPayloadLen()) { if (rc < 0) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_UDPBCastMCastData - receive() of %u/%u bytes from socket failed with rc = %d\n", payLoadLen, pUDPBMDPM->getPayloadLen(), rc); return rc; } payLoadLen += rc; } payLoadLen += rc; break; } case PacketType::PMT_TCPOpenConnection: { const auto * const pOTCPCPM = reinterpret_cast<const OpenTCPConnectionProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pOTCPCPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_TCPOpenConnection - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } break; } case PacketType::PMT_TCPConnectionOpened: { const auto * const pTCPCOPM = reinterpret_cast<const TCPConnectionOpenedProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pTCPCOPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_TCPConnectionOpened - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } break; } case PacketType::PMT_TCPData: { const auto * const pTCPDPM = reinterpret_cast<const TCPDataProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pTCPDPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_TCPData - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } while (((rc = receive (ui8Buf + headerLen + payLoadLen, pTCPDPM->getPayloadLen() - payLoadLen)) + payLoadLen) < pTCPDPM->getPayloadLen()) { if (rc < 0) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "L%hu-R%hu: PMT_TCPData - receive() of %u/%u bytes from socket failed with rc = %d\n", pTCPDPM->_ui16RemoteID, pTCPDPM->_ui16LocalID, payLoadLen, pTCPDPM->getPayloadLen(), rc); return rc; } payLoadLen += rc; } payLoadLen += rc; break; } case PacketType::PMT_TCPCloseConnection: { const auto * const pCTCPCPM = reinterpret_cast<const CloseTCPConnectionProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pCTCPCPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_TCPCloseConnection - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } break; } case PacketType::PMT_TCPResetConnection: { const auto * const pRTCPCPM = reinterpret_cast<const ResetTCPConnectionProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pRTCPCPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_TCPResetConnection - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } break; } case PacketType::PMT_TunnelPacket: { const auto * const pTPPM = reinterpret_cast<const TunnelPacketProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pTPPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_TunnelPacket - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } while (((rc = receive (ui8Buf + headerLen + payLoadLen, pTPPM->getPayloadLen() - payLoadLen)) + payLoadLen) < pTPPM->getPayloadLen()) { if (rc < 0) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_TunnelPacket - receive() of %u/%u bytes from socket failed with rc = %d\n", payLoadLen, pTPPM->getPayloadLen(), rc); return rc; } payLoadLen += rc; } payLoadLen += rc; break; } case PacketType::PMT_ConnectionError: { const auto * const pCEPM = reinterpret_cast<const ConnectionErrorProxyMessage *> (pBuf); if (0 != (rc = receiveProxyHeader (pCEPM, headerLen))) { checkAndLogMsg ("TCPSocketAdapter::receiveMessage", NOMADSUtil::Logger::L_MildError, "PMT_ConnectionError - rcvProxyHeader() from socket failed with rc = %d\n", rc); return rc; } break; } } return headerLen + payLoadLen; } int TCPSocketAdapter::gsend (const NOMADSUtil::InetAddr * const pInetAddr, uint32 ui32SourceIPAddr, uint32 ui32DestinationIPAddr, bool bReliable, bool bSequenced, const void *pBuf1, uint32 ui32BufSize1, va_list valist1, va_list valist2) { (void) pInetAddr; (void) ui32SourceIPAddr; (void) ui32DestinationIPAddr; (void) bReliable; (void) bSequenced; if (!pBuf1) { if (ui32BufSize1 > 0) { return -1; } return 0; } uint32 ui32TotalBytes = ui32BufSize1; while (va_arg (valist1, const void*) != nullptr) { ui32TotalBytes += va_arg (valist1, uint32); } if (ui32TotalBytes > _ui16BufferSize) { return -2; } const void *pBuf = pBuf1; uint32 ui32BufSize = ui32BufSize1, ui32CopiedBytes = 0; std::lock_guard<std::mutex> lg{_mtx}; while (pBuf) { memcpy (_upui8Buffer.get() + ui32CopiedBytes, pBuf, ui32BufSize); ui32CopiedBytes += ui32BufSize; pBuf = va_arg (valist2, const void*); ui32BufSize = va_arg (valist2, uint32); } int rc = _upTCPSocket->send (_upui8Buffer.get(), ui32TotalBytes); return (rc == ui32TotalBytes) ? 0 : rc; } // retrieves the header of an incoming packet sent by a remote NetProxy template <class T> int TCPSocketAdapter::receiveProxyHeader (T * const pMess, int & iReceived) { int rc=0; uint8 * const ui8Buf = (uint8 * const) pMess; while ((rc = _upTCPSocket->receive (ui8Buf + iReceived, sizeof(T) - iReceived)) + iReceived < sizeof(T)) { if (rc < 0) { return rc; } iReceived += rc; } iReceived += rc; return 0; } }
gpl-3.0
bodoba/Roomberry
tools/Drive.cpp
2667
/* * --------------------------------------------------------------------------------------- * Copyright 2014 by Bodo Bauer <bb@bb-zone.com> * * This Roomba Open Interface class 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 Roomba Open Interface class 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 file. If not, see <http://www.gnu.org/licenses/>. * -------------------------------------------------------------------------------------- */ #include <string.h> #include <sys/time.h> #include <sys/types.h> #include "Roomberry.h" uint64_t getUsecTime(void); int main ( int argc, char* argv[] ) { Roomberry Roomba("/dev/ttyAMA0"); uint16_t speed = 250; int16_t msec = 100; uint64_t endTime, now; roomberryBumper_t bumper; bool stop = FALSE; if ( argc >= 3 ) { speed = atoi(argv[2]); if ( speed < 0 ) { speed = 0; } else if ( speed > 500 ) { speed = 500; } } if ( argc >= 2 ) { msec = atoi(argv[1]); if ( msec < 0 ) { speed *= -1; msec *= -1; } } Roomba.safeMode(); now = getUsecTime(); endTime = now + ( msec * 10000 ); Roomba.driveStraight(speed); while ( ! stop ) { now = getUsecTime(); Roomba.getBumper ( &bumper ); if ( now >= endTime || bumper.right || bumper.left ) { stop = TRUE; } else { usleep(10000); } } Roomba.stop(); Roomba.passiveMode(); if ( bumper.right & bumper.left ) { printf ("Emergency Stop! (Full frontal hit)\n"); } else if ( bumper.right ) { printf ("Emergency Stop! (Right side hit)\n"); } else if ( bumper.left ) { printf ("Emergency Stop! (Left side hit)\n"); } return(0); } uint64_t getUsecTime(void) { struct timeval tp; uint64_t sec, usec; gettimeofday( &tp, NULL ); sec = (uint64_t)( tp.tv_sec ); usec = (uint64_t)(( tp.tv_usec )); return ( sec * 1000000 + usec); }
gpl-3.0
dundertext/dundertext
ui/src/main/scala/dundertext/ui/keyboard/GlobalKeyboardHandler.scala
793
package dundertext.ui.keyboard import org.scalajs.dom import org.scalajs.dom.KeyboardEvent class GlobalKeyboardHandler extends Keyboard { dom.document.onkeydown = onKeyDown _ dom.document.onkeypress = onKeyPress _ var listeners: Set[KeyboardListener] = Set.empty def onKeyDown(e: KeyboardEvent): Unit = { val chord = KeyChord(e.keyCode, shift = e.shiftKey, ctrl = e.ctrlKey || e.metaKey, alt = e.altKey) for (l <- listeners) { val handled = l.onKeyDown(chord) if (handled) e.preventDefault() } } def onKeyPress(e: KeyboardEvent): Unit = { for (l <- listeners) { val handled = l.onKeyPress(e.keyCode.toChar) if (handled) e.preventDefault() } } override def listen(listener: KeyboardListener) = { listeners += listener } }
gpl-3.0
ranchoManuel/Ancheta
DataStructures/Enlazadas/source/listasCYP/ILista.java
794
package listasCYP; import java.io.Serializable; import exceptions.ElementoRepetidoException; public interface ILista<T> extends Serializable, Iterable<T>{ /** * * @param elemento * @throws ElementoRepetidoException */ public void agregar(T elemento) throws ElementoRepetidoException; /** * * @param elemento * @return */ public T eliminar(T elemento); /** * * @param elemento * @return */ public T buscar(T elemento); /** * * @return */ public boolean esVacia(); /** * * @return */ public boolean vaciar(); /** * * @return */ public Object[] darEnArreglo(); /** * * @return */ public int darCantidadDeElementos(); /** * * @return */ public Object[] sort(); }
gpl-3.0
jarmond/Curves
curves/nanoscope.py
12251
# Curves force analysis software # JWA (c)2009 # Import Nanoscope force curve import re from numpy import * class NanoscopeFileReadError(Exception): def __init__(self,err,line): self.err = err self.line = line def __str__(self): return repr(self.err) + ': ' + repr(self.line) def is_nanoscope_file(filename): """Returns True if filename refers to a force curve file. Force curve files are identified by the line \*Force file list at the beginning.""" infile = open(filename,"r") line = infile.readline().strip() return line.startswith("\*Force file list") def read_params(filename): # Create dictionary of parameters, indexed by parameter list section # and parameter name infile = open(filename,"r") raw_param = {} # TODO: check nanoscope and version while infile: line = infile.readline().strip() # Stop at end marker if line.startswith("\*File list end"): pass #print "Finished scanning parameters." break # If begins with \* then is a section header elif line.startswith("\*"): regex_str = r"(\\\*)([\w ]+)" match_obj = re.search(regex_str,line) if match_obj: list_name = cleanKey(match_obj.group(2)) #print "Section header: " + list_name raw_param[list_name] = {} else: raise NanoscopeFileReadError('Section header',line) # Is a parameter, parse, add to dictionary elif len(line)>0: # Ignore empty lines # Format is: \Parameter name: values #print line regex_str = r"(\\)((@\d:)?[\w @\-\./\(\),\[\]]*)(\t*:) *(.*)" match_obj = re.search(regex_str,line) # Grp 1 = \ # Grp 2 = Param name including @? prefix = # Grp 3 = @? prefix # Grp 4 = : # Grp 5 = Values if match_obj: #print "Parsing: " + match_obj.group(3) values = match_obj.group(5) #print "Values: " + match_obj.group(5) raw_param[list_name][cleanKey(match_obj.group(2))] = values else: raise NanoscopeFileReadError('Parameter read',line) else: # Ignore pass infile.close() return raw_param def read_curve_data(filename,std_params): # Open in binary mode infile = open(filename,"rb") # Seek to data offset data_offset = std_params["DataOffset"] data_length = std_params["DataLength"] bytes_per_point = std_params["BytesPerPoint"] point_count = data_length/bytes_per_point points_per_curve = point_count/std_params['NumCurves'] infile.seek(data_offset) # Some curves are truncated, and are preceded with junk data. So we need # to work out how many bytes to skip approach_skip = (points_per_curve - std_params['ApproachPoints'])*bytes_per_point retract_skip = (points_per_curve - std_params['RetractPoints'])*bytes_per_point # Read raw data and shape # \todo allow for different integer lengths if bytes_per_point!=2: print "Bytes/point != 2" approach = fromfile(file=infile,dtype=int16,count=std_params['ApproachPoints']) infile.seek(approach_skip,1) # 1 indicates relative seek retract = fromfile(file=infile,dtype=int16,count=std_params['RetractPoints']) # Convert raw deflection data to Volts approach = approach * std_params["HardScale"] retract = retract * std_params["HardScale"] # Apply Z range ramp_offset = std_params["RampOffset"] ramp_size = std_params["RampSize"] z = linspace(ramp_offset,ramp_offset+ramp_size,max(len(approach),len(retract))) return (z,approach,retract) def read_curve_info(raw_params): """Return a dictionary of parameters with standardised string keys""" # G1: soft scale param, G2: hard scale, G3: hard value regex_hard = r"V \[([\w \.]+)\] \(([\d\.]+) V/LSB\) ([-\d\.]+)" # V [param] (value V/LSB) # G1: soft value regex_soft = r"V ([\d\.]+)" # V soft value regex_time = r"([\d\:]+ (PM|AM)) ([\w ]+)" # 1: time, 2: AM or PM, 3: date regex_version = r"0x0(\d)(\d\d)" # 1: major version, 2: minor regex_samples = r"([\d]+) ([\d]+)" std_params = {} # Decide which nanoscope version m = re.search(regex_version,raw_params['forcefilelist']['version']) if m: std_params['Version'] = m.group(1) + '.' + m.group(2) else: raise NanoscopeFileReadError('Version',raw_params['forcefilelist']['version']) version = float(std_params['Version']) if version >= 7 and version < 8: ns = ns7 elif version >= 6: ns = ns6 else: raise NanoscopeFileReadError('Version %f not supported' % version) # Some minor versions annoyingly differ in spaces between words in keys, e.g. Z Limit vs ZLimit # Clean key strings ns = dict(zip(ns.keys(),map(cleanKey, ns.values()))) # Nanoscope 7 gives AFM for this # if raw_params['Ciao force image list']['Data type'].strip() != 'FORCE': # print('Expected data type = FORCE. Possibly not force curve.') std_params['Software'] = 'Nanoscope' # Data scaling parameters m = re.search(regex_hard,raw_params[ns['ImageList']][ns['HardScale']]) if m: soft_param = m.group(1) #std_params['HardScale'] = float(m.group(3))/65536 # change made here (divide by 65536 and use group 3), cf manual std_params['HardScale'] = float(m.group(2)) else: raise NanoscopeFileReadError('Z scale',raw_params[ns['ImageList']][ns['HardScale']]) m = re.search(regex_soft,raw_params[ns['ScanList']][cleanKey('@' + soft_param)]) if m: std_params['DeflSens'] = float(m.group(1)) else: raise NanoscopeFileReadError('Z scale',raw_params[ns['ScanList']]['@' + soft_param]) m = re.search(regex_hard,raw_params[ns['ForceList']][ns['RampSize']]) # identify zsens param if m: ramp_soft_param = m.group(1) else: raise NanoscopeFileReadError('Z scan size',raw_params[list_name][ns['RampSize']]) m = re.search(regex_soft,raw_params[ns['ScannerList']][cleanKey('@' + ramp_soft_param)]) if m: std_params['ZSens'] = float(m.group(1)) else: raise NanoscopeFileReadError('Z sens',raw_params[ns['ScannerList']][cleanKey('@' + ramp_soft_param)]) m = re.search(regex_hard,raw_params[ns['ScanList']][ns['ZRange']]) if m: std_params['ZRange'] = float(m.group(3)) * std_params['ZSens'] else: raise NanoscopeFileReadError('Z range',raw_params[ns['ScanList']][ns['ZRange']]) # Force experimental parameters list_name = ns['ForceList'] std_params['ScanRate'] = float(raw_params[list_name][ns['ScanRate']]) std_params['ForwardVelocity'] = float(raw_params[list_name][ns['ForwardVelocity']])*std_params['ZSens'] std_params['ReverseVelocity'] = float(raw_params[list_name][ns['ReverseVelocity']])*std_params['ZSens'] m = re.search(regex_hard,raw_params[list_name][ns['RampSize']]) std_params['RampSize'] = float(m.group(3))*std_params['ZSens'] m = re.search(regex_hard,raw_params[list_name][ns['RampOffset']]) std_params['RampOffset'] = float(m.group(3))*std_params['ZSens'] std_params['SurfaceDelay'] = float(raw_params[list_name][ns['SurfaceDelay']]) std_params['RetractDelay'] = float(raw_params[list_name][ns['RetractDelay']]) # Parameters std_params['SpringConst'] = float(raw_params[ns['ImageList']][ns['SpringConst']]) # Information list_name = ns['FileList'] m = re.search(regex_time,raw_params[list_name][ns['Date']]) if m: std_params['Date'] = m.group(3) std_params['Time'] = m.group(1) else: raise NanoscopeFileReadError('Date and time',raw_params[list_name][ns['Date']]) list_name = ns['EquipmentList'] std_params['Microscope'] = raw_params[list_name][ns['Microscope']] if 'Controller' in ns: std_params['Controller'] = 'Nanoscope ' + raw_params[list_name][ns['Controller']] else: std_params['Controller'] = '' list_name = ns['ScannerList'] std_params['ScannerType'] = raw_params[list_name][ns['ScannerType']] std_params['PiezoSize'] = raw_params[list_name][ns['PiezoSize']] list_name = ns['ScanList'] std_params['TipNumber'] = raw_params[list_name][ns['TipNumber']] list_name = ns['ImageList'] std_params['DataOffset'] = int(raw_params[list_name][ns['DataOffset']],10) std_params['DataLength'] = int(raw_params[list_name][ns['DataLength']],10) std_params['BytesPerPoint'] = int(raw_params[list_name][ns['BytesPerPoint']],10) m = re.search(regex_samples,raw_params[list_name][ns['SamplesPerLine']]) if m: std_params['RetractPoints'] = int(m.group(1)) std_params['ApproachPoints'] = int(m.group(2)) std_params['NumCurves'] = len(m.groups()) else: raise NanoscopeFileReadError('Samps/line',raw_params[list_name][ns['SamplesPerLine']]) return std_params def cleanKey(key): try: return key.strip().replace(' ','').lower() except AttributeError: return key # Nanoscope software keys # Nanoscope v6.11 - v6.13 ns6 = { 'Version' : 6, 'Date' : 'Date', 'Microscope' : 'Microscope', 'ForceList' : 'Ciao force list', 'ImageList' : 'Ciao force image list', 'FileList' : 'Force file list', 'EquipmentList' : 'Equipment list', 'ScannerList' : 'Scanner list', 'ScanList' : 'Ciao scan list', 'ScanRate' : 'Scan rate', 'ForwardVelocity' : 'Forward vel.', 'ReverseVelocity' : 'Reverse vel.', # 'RampSize' : '@Z scan size', 'RampSize' : '@4:Ramp size Zsweep', # 'RampOffset' : '@Z scan start', 'RampOffset' : '@4:Ramp offset Zsweep', 'SpringConst' : 'Spring Constant', 'Controller' : 'Controller', 'ScannerType' : 'Scanner type', 'PiezoSize' : 'Piezo size', 'TipNumber' : 'Tip serial number', 'HardScale' : '@4:Z scale', 'ZRange' : '@1:Z limit', 'DataOffset' : 'Data offset', 'DataLength' : 'Data length', 'BytesPerPoint' : 'Bytes/pixel', 'SamplesPerLine' : 'Samps/line', 'DataType' : 'FORCE', 'SurfaceDelay' : 'Ramp delay', 'RetractDelay' : 'Reverse delay' } # Nanoscope v7.3 ns7 = { 'Version' : 7, 'Date' : 'Date', 'Microscope' : 'Microscope', 'ForceList' : 'Ciao force list', 'ImageList' : 'Ciao force image list', 'FileList' : 'Force file list', 'EquipmentList' : 'Equipment list', 'ScannerList' : 'Scanner list', 'ScanList' : 'Ciao scan list', 'ScanRate' : 'Scan rate', 'ForwardVelocity' : 'Forward vel.', 'ReverseVelocity' : 'Reverse vel.', 'RampSize' : '@Z scan size', 'RampOffset' : '@Z scan start', 'SpringConst' : 'Spring Constant', 'ScannerType' : 'Scanner type', 'PiezoSize' : 'Piezo size', 'TipNumber' : 'Tip Serial Number', 'HardScale' : '@4:Z scale', # maybe not but have to divide by 65536 (2^16): this might include spring const and 'Z magnify force' 'ZRange' : '@1:Z Limit', 'DataOffset' : 'Data offset', 'DataLength' : 'Data length', 'BytesPerPoint' : 'Bytes/pixel', 'SamplesPerLine' : 'Samps/line', 'DataType' : 'AFM', 'SurfaceDelay' : 'Ramp delay', 'RetractDelay' : 'Reverse delay' } # Units ns_units = { 'Version' : '', 'Date' : '', 'Time' : '', 'Microscope' : '', 'Software' : '', 'TipNumber' : '', 'ScanRate' : 'Hz', 'ForwardVelocity' : 'nm/s', 'ReverseVelocity' : 'nm/s', 'RampSize' : 'nm', 'RampOffset' : 'nm', 'SpringConst' : 'N/m', 'Controller' : '', 'ScannerType' : '', 'PiezoSize' : '', 'TipNumber' : '', 'HardScale' : 'V/LSB', 'ZRange' : 'nm', 'ZSens' : 'nm/V', 'DataOffset' : 'bytes', 'DataLength' : 'bytes', 'BytesPerPoint' : 'bytes', 'SamplesPerLine' : 'Samps/line', 'SurfaceDelay' : 's', 'RetractDelay' : 's', 'DeflSens': 'nm/V', 'RetractPoints' : '', 'ApproachPoints' : '', 'NumCurves': '', }
gpl-3.0
imr/Electric8
com/sun/electric/tool/simulation/test/SiliconChip.java
1434
/* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: SiliconChip.java * Written by Jonathan Gainsley, Sun Microsystems. * * Copyright (c) 2004 Sun Microsystems and Static Free Software * * Electric(tm) 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. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.simulation.test; import java.util.List; import java.util.Date; public class SiliconChip implements ChipModel { public SiliconChip() { } public void wait(float seconds) { Infrastructure.wait(seconds); } public void waitNS(double nanoseconds) { Infrastructure.wait((float)(nanoseconds/1e9)); } public void waitPS(double picoseconds) { Infrastructure.wait((float)(picoseconds/1e12)); } }
gpl-3.0
YashdalfTheGray/iot-control
public/views/loginUserView/loginUserView.js
1487
/* global angular */ angular.module('iotControl') .controller('LoginUserViewCtrl', [ '$state', 'toastSvc', 'userSvc', function($state, toastSvc, userSvc) { "use strict"; var vm = this; vm.login = function() { var SHA512 = new Hashes.SHA512(); userSvc.loginUser(vm.email, SHA512.hex(vm.password)) .then( function(result) { if (result.firstName === 'New User') { $state.go('dashboard'); } else { $state.go('home'); } }, function(error) { console.log(error); } ); }; vm.signup = function() { $state.go('createuser'); }; vm.resetPassword = function() { if (!vm.email) { toastSvc.show('Please enter an email to reset your password.'); } else { userSvc.resetPassword(vm.email).then(function() { toastSvc.show('Password reset email sent successfully!'); }).catch(function(error) { console.log(error); }); } } } ] );
gpl-3.0
chriswmackey/BEnMap
assets/js/main.js
14270
// // page state var state = { filter: "All", metric: "Site EUI (kBTU/sf)", }; // // objects/variables that need to be accessed within functions var style = {}; var table = {}; var statTable = {}; var olMap = {}; var vectorLayer = {}; var vectorSource = {}; var key = 'PARCEL_ID'; var types = []; var typeKey = 'Property Type'; var domain = []; // other variables var coordsBoston = [42.3568138, -71.0524385]; // // color scale for reuse var colorScaleList = ['rgba(0,128,0,1)', 'rgba(245,239,103,1)', 'rgba(234,123,0,1)', 'rgba(234,38,0,1)'] var reversedColorList = colorScaleList.slice().reverse() // Building Type List. var typeList = [ "All", "Office", "Residential", "Healthcare", "Education", "Laboratory", "Mercantile", "Grocery", "Public Assembly", "Public Safety and Utilities", "Warehouse and Storage", "Industrial Plant", ] // Dictionary of default legend boundaries. var legBound = { "Site EUI (kBTU/sf)": { "All": [0,200], "Other": [0,200], "Education": [0,200], "Healthcare": [100,450], "Grocery": [0,300], "Mercantile": [0,140], "Office": [0,200], "Residential": [0,120], "Warehouse and Storage": [0,200], "Industrial Plant": [0,500], "Laboratory": [0,600], }, "Source EUI (kBTU/sf)": { "All": [0,400], "Other": [0,400], "Education": [0,350], "Healthcare": [200,800], "Grocery": [0,600], "Mercantile": [0,280], "Office": [0,400], "Residential": [0,240], "Warehouse and Storage": [0,400], "Industrial Plant": [0,800], "Laboratory": [0,1000], }, "Water Intensity (gal/sf)": { "All": [0,100], "Other": [0,100], "Education": [0,50], "Healthcare": [0,50], "Grocery": [0,50], "Mercantile": [0,100], "Office": [0,50], "Residential": [0,100], "Public Assembly": [0,100], "Public Safety and Utilities": [0,50], "Warehouse and Storage": [0,100], "Industrial Plant": [0,50], "Laboratory": [0,100], }, }; // // we put the FUN in functions var validIdsFromString = function(unverified) { var splitBy = new RegExp('[^0-9]{1,}', 'i'); // 123456780 var pad = "000000000"; return unverified .split(splitBy) .filter(function(i) { return ((i) ? true : false); }) .map(function(p) { return pad.substring(0, pad.length - p.length) + p }); }; var updateSelectors = function() { types.sort(); for (i = 1; i < typeList.length; i++) { $('#filter').append('<option value="' + typeList[i] + '">' + typeList[i] + '</option>'); } types.map(function(type) { if (typeList.indexOf(type) < 0 && type != "Other") { $('#filter').append('<option value="' + type + '">' + type + '</option>'); } }); $('#filter').append('<option value="' + "Other" + '">' + "Other" + '</option>'); }; var updateLayers = function() { vectorLayer.setStyle(setStyles); updateLegend(); }; var updateLegend = function() { var maxWidth = 250; var height = 20; var svgContainer = d3.select("svg") .style("max-height", "40px") svgContainer.selectAll("svg > *").remove(); var svg = svgContainer.append("g") .attr("transform", "translate(10, 0)") .attr("width", "100%"); svg.data(domain); var defs = svg.append("defs"); var linearGradient = defs.append("linearGradient") .attr("id", "linear-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); if (state.metric == "Energy Star Score"){ var colorList = reversedColorList } else{ var colorList = colorScaleList } //Set the color for the start (0%) linearGradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorList[0]); //Set the color for 33% linearGradient.append("stop") .attr("offset", "33%") .attr("stop-color", colorList[1]); //Set the color for 66% linearGradient.append("stop") .attr("offset", "66%") .attr("stop-color", colorList[2]); //Set the color for the end (100%) linearGradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorList[3]); //Create the bar svg.append("rect") .attr("width", maxWidth) .attr("height", height) .attr("y", 5) .style("fill", "url(#linear-gradient)"); //Set scale for x-axis var xScale = d3.scale.linear() .range([0, maxWidth]) .domain([0, d3.max(domain)]) .nice(); //Define x-axis var xAxis = d3.svg.axis() .orient("bottom") .ticks(5) // .tickFormat(formatPercent) .scale(xScale); //Set up X axis svg.append("g") .attr("class", "axis") .attr("transform", "translate(0," + (20) + ")") .call(xAxis); } var handleData = function(values) { var localData = table; // values is an array: // [0] csv file string // [1] json file string var csvRaw = values.shift(); var rows = Papa.parse(csvRaw, { header: true }).data; var json = values.shift(); if (typeof json == "string") { json = JSON.parse(json); } var typeMap = {}; rows.map(function(row) { if (!row[key]) { return; } var type = 'unknown'; if (row[typeKey]) { type = row[typeKey]; typeMap[type] = true; } var ids = validIdsFromString(row[key]); ids.map(function(id) { localData[id] = row; Object.keys(row).map(function(col) { var val = parseFloat(row[col]); if (isNaN(val)) { return; } if (!statTable[col]) { return statTable[col] = { all: { max: val, min: val }, byType: {} }; } var stat = statTable[col]; if (val > stat.all.max) { stat.all.max = val; } if (val < stat.all.min) { stat.all.min = val; } if (!stat.byType[type]) { stat.byType[type] = { max: val, min: val }; } if (val > stat.byType[type].max) { stat.byType[type].max = val; } if (val < stat.byType[type].min) { stat.byType[type].min = val; } }); }); }); types = Object.keys(typeMap); updateSelectors(); try { domain = [legBound[state.metric][state.filter][0], legBound[state.metric][state.filter][1]]; } catch(err) { domain = [statTable[state.metric].all.min, statTable[state.metric].all.max]; } updateLegend(); json.features.map(function(feature) { setStyles(feature); }) vectorSource = new ol.source.Vector({ features: (new ol.format.GeoJSON()).readFeatures(json) }); vectorLayer = new ol.layer.Vector({ source: vectorSource, style: styleFunction, projection: 'EPSG:4326' }); // debugger; olMap.addLayer(vectorLayer); }; var setStyles = function(feature) { // get feature ID var id; if (feature.properties) { id = feature.properties[key]; } else if (feature.T) { id = feature.T[key]; } // get row from table table by ID var row = {}; if (table[id]) { row = table[id]; } else { row[state.metric] = 0; } if (state.filter === "All") { alphaStroke = 1; alphaFill = 0.8; } else { // logic here for filter (set alpha to 0 if not pass filter?) var featureFilter = row[typeKey]; var alphaStroke = 0; var alphaFill = 0; if (featureFilter == state.filter) { alphaStroke = 1; alphaFill = 0.8; } } // get value from row var value = row[state.metric]; // build color scale = chroma.scale(colorScaleList).domain(domain); var color = scale(value).rgb(); var rgba = "rgba(" + color[0].toFixed(0) + "," + color[1].toFixed(0) + "," + color[2].toFixed(0); var rgbaStroke = rgba + "," + alphaStroke + ")"; var rgbaFill = rgba + "," + alphaFill + ")"; return style[id] = new ol.style.Style({ stroke: new ol.style.Stroke({ color: rgbaStroke, width: 2 }), fill: new ol.style.Fill({ color: rgbaFill }) }) }; var styleFunction = function(feature) { return style[feature.getProperties()["PARCEL_ID"]]; } function create2DMap () { olMap = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.Stamen({ layer: "toner-lite" }) }) ], // overlays: [overlay], target: 'map', controls: ol.control.defaults({ attributionOptions: { collapsible: false } }), view: new ol.View({ center: [coordsBoston[1], coordsBoston[0]], zoom: 13, projection: 'EPSG:4326' }) }); } function add2DInteraction (){ var geocoder = new Geocoder('nominatim', { provider: 'osm', key: '__some_key__', lang: 'en-US', //en-US, fr-FR placeholder: 'Search for ...', limit: 5, autocomplete: true, keepOpen: true }); geocoder.on('addresschosen', function(evt) { var feature = evt.feature, coord = evt.coordinate, address = evt.address; olMap.setView(new ol.View({ center: [coord[0], coord[1]], zoom: 16, projection: 'EPSG:4326' })); }); olMap.addControl(geocoder); var select = null; // ref to currently selected interaction // select interaction working on "click" var selectClick = new ol.interaction.Select({ condition: ol.events.condition.click }); var changeInteraction = function() { if (select !== null) { olMap.removeInteraction(select); } select = selectClick; if (select !== null) { olMap.addInteraction(select); select.on('select', function(e) { if (!e.selected[0]) document.getElementById("details").style.display = "none"; else { document.getElementById("details").style.display = "block"; var properties = e.selected[0].getProperties(); var id; if (properties) { id = properties[key]; } else if (e.selected[0].T) { id = e.selected[0].T[key]; } // get row from table table by ID var row = {}; if (table[id]) { row = table[id]; //find the way to bind the front end? document.getElementById("name").innerHTML = row["Property Name"]; document.getElementById("address").innerHTML = row["Address"]; document.getElementById("siteEUI").innerHTML = row["Site EUI (kBTU/sf)"]; document.getElementById("sourceEUI").innerHTML = Math.round(row["Source EUI (kBTU/sf)"]* 10 ) / 10; document.getElementById("GHGIntensity").innerHTML = row["GHG Intensity (kgCO2/sf)"]; document.getElementById("EnergyStar").innerHTML = row["Energy Star Score"]; document.getElementById("waterIntensity").innerHTML = row["Water Intensity (gal/sf)"]; document.getElementById("floorArea").innerHTML = row["Gross Area (sq ft)"].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); document.getElementById("yearBuilt").innerHTML = row["Year Built"]; document.getElementById("propertyType").innerHTML = row["Specific Property Type"]; document.getElementById("propertyUses").innerHTML = row["Property Uses"]; } } }); } }; /** * onchange callback on the select element. */ changeInteraction(); } // // jQuery page listeners $(document).on('change', '#metric', function(e) { state.metric = $(e.target).val(); try { domain = [legBound[state.metric][state.filter][0], legBound[state.metric][state.filter][1]]; } catch(err) { if(state.filter=='All'){ domain = [statTable[state.metric].all.min, statTable[state.metric].all.max]; }else{ domain = [statTable[state.metric].byType[state.filter].min, statTable[state.metric].byType[state.filter].max]; } } if (state.metric == "Energy Star Score"){ domain = [domain[1],domain[0]] } updateLayers(); }); $(document).on('change', '#filter', function(e) { state.filter = $(e.target).val(); try { domain = [legBound[state.metric][state.filter][0], legBound[state.metric][state.filter][1]]; } catch(err) { if(state.filter=='All'){ domain = [statTable[state.metric].all.min, statTable[state.metric].all.max]; }else{ domain = [statTable[state.metric].byType[state.filter].min, statTable[state.metric].byType[state.filter].max]; } } if (state.metric == "Energy Star Score"){ domain = [domain[1],domain[0]] } updateLayers(); }); $(document).ready(function() { create2DMap(); // handle data retrieved via ajax Promise.all(['./assets/data/data.csv', "./assets/data/geometry.geojson"].map($.get)).then(handleData); add2DInteraction(); })
gpl-3.0
seapub/SourceCode
android_applets-master/api_guide/ui/style_theme/02_theme/ThemeTest/src/com/skw/themetest/ThemeTest.java
483
package com.skw.themetest; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.content.Intent; public class ThemeTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void sendMessage(View view) { Intent intent = new Intent(this, CustomTheme.class); startActivity(intent); } }
gpl-3.0
imr/Electric8
com/sun/electric/tool/user/dialogs/LayoutImage.java
17981
/* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: LayoutImage.java * * Copyright (c) 2009 Sun Microsystems and Static Free Software * * Electric(tm) 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. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.user.dialogs; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.prototype.NodeProto; import com.sun.electric.database.text.TextUtils; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.technology.Technology; import com.sun.electric.tool.Job; import com.sun.electric.tool.JobException; import com.sun.electric.tool.io.FileType; import com.sun.electric.tool.user.User; import com.sun.electric.tool.user.ui.WindowFrame; import javax.imageio.stream.ImageInputStream; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.swing.*; import java.awt.Canvas; import java.awt.Frame; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Toolkit; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.Raster; import java.util.Iterator; import java.io.File; /** * Class to handle the "Layout Image" dialog. There is still a ton of * overlap left in here from LayoutText.java; at some point I will * either merge the two or else remove that overlap. In particular, * LayoutText could benefit from "backporting" the new support for * grayscale images (which would give us antialiased layout text!) * * @author Adam Megacz <adam.megacz@sun.com>, derived from LayoutText.java */ public class LayoutImage extends EDialog { /** Creates new form LayoutImage */ public LayoutImage(Frame parent) { super(parent, true); initComponents(); // make all text fields select-all when entered EDialog.makeTextFieldSelectAllOnTab(largestDotWidth); EDialog.makeTextFieldSelectAllOnTab(smallestDotWidth); EDialog.makeTextFieldSelectAllOnTab(minimumGutter); EDialog.makeTextFieldSelectAllOnTab(fileName); largestDotWidth.setText("32"); smallestDotWidth.setText("22"); minimumGutter.setText("16"); // fileName.setText("/Users/megacz/proj/fleet/marina/logo/marina-logo.png"); monochrome.setSelected(false); reverseVideo.setSelected(false); Technology tech = Technology.getCurrent(); for(Iterator<PrimitiveNode> it = tech.getNodes(); it.hasNext(); ) { PrimitiveNode np = it.next(); if (np.getFunction() == PrimitiveNode.Function.NODE) textLayer.addItem(np.getName()); } finishInitialization(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; cancel = new javax.swing.JButton(); ok = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); smallestDotWidth = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); largestDotWidth = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); minimumGutter = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); textLayer = new javax.swing.JComboBox(); reverseVideo = new javax.swing.JCheckBox(); monochrome = new javax.swing.JCheckBox(); fileName = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); openFileButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Layout Image"); getContentPane().setLayout(new java.awt.GridBagLayout()); cancel.setText("Cancel"); cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancel(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 9; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(cancel, gridBagConstraints); ok.setText("OK"); ok.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ok(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 9; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(ok, gridBagConstraints); jLabel1.setText("Width of smallest dot:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(jLabel1, gridBagConstraints); smallestDotWidth.setColumns(8); smallestDotWidth.setText(" "); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(smallestDotWidth, gridBagConstraints); jLabel2.setText("Width of largest dot:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(jLabel2, gridBagConstraints); largestDotWidth.setColumns(8); largestDotWidth.setText(" "); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(largestDotWidth, gridBagConstraints); jLabel3.setText("Minimum gutter between dots:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(jLabel3, gridBagConstraints); minimumGutter.setColumns(8); minimumGutter.setText(" "); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(minimumGutter, gridBagConstraints); jLabel5.setText("Layer:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(jLabel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(textLayer, gridBagConstraints); reverseVideo.setText("Reverse-video"); reverseVideo.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); reverseVideo.setMargin(new java.awt.Insets(0, 0, 0, 0)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(reverseVideo, gridBagConstraints); monochrome.setText("Monochrome"); monochrome.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); monochrome.setMargin(new java.awt.Insets(0, 0, 0, 0)); monochrome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { monochromeActionPerford(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 8; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(monochrome, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 1, 4); getContentPane().add(fileName, gridBagConstraints); jLabel4.setText("Image file name:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); getContentPane().add(jLabel4, gridBagConstraints); openFileButton.setText("Load"); openFileButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openFileButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(1, 4, 12, 4); getContentPane().add(openFileButton, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void cancel(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancel setVisible(false); dispose(); }//GEN-LAST:event_cancel private void ok(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ok final Cell curCell = WindowFrame.needCurCell(); if (curCell == null) return; final Technology tech = Technology.getCurrent(); final int minimumGutter = (int)TextUtils.atofDistance(this.minimumGutter.getText(), tech); final int largestDotWidth = (int)TextUtils.atofDistance(this.largestDotWidth.getText(), tech); final int smallestDotWidth = (int)TextUtils.atofDistance(this.smallestDotWidth.getText(), tech); // final boolean reverseVideo = this.reverseVideo.isSelected(); final String layer = (String)textLayer.getSelectedItem(); // determine the primitive to use for the layout final NodeProto primNode = Technology.getCurrent().findNodeProto(layer); if (primNode == null) { System.out.println("Cannot find " + layer + " primitive"); return; } try { // Checking if the file is actually a JPEG file File fileURL = new File(fileName.getText()); ImageInputStream iis = ImageIO.createImageInputStream(fileURL); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); boolean validFormat = false; while (readers.hasNext()) { ImageReader read = readers.next(); // Another way to detect this could be "read instanceof JPEGImageReader String format = read.getFormatName().toLowerCase(); // so far jpeg and png are the only valid formats tested. validFormat = format.equals("jpeg") || format.equals("png"); if (validFormat) break; } if (!validFormat) { String msg = "'" + fileName.getText() + "' is not a JPEG file"; JOptionPane.showMessageDialog(null, msg, "Erorr in LoadImage", JOptionPane.ERROR_MESSAGE); return; } Image img = Toolkit.getDefaultToolkit().createImage(fileName.getText()); // dumb hack to force AWT to load the image MediaTracker mediatracker = new MediaTracker(new Canvas()); mediatracker.addImage(img, 1); try { mediatracker.waitForAll(); } catch (InterruptedException e) { } mediatracker.removeImage(img); BufferedImage textImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_BYTE_GRAY); textImage.getGraphics().drawImage(img, 0, 0, null); Raster ras = textImage.getData(); DataBufferByte dbb = (DataBufferByte)ras.getDataBuffer(); setVisible(false); dispose(); new LayoutImageJob(ras.getWidth(), ras.getHeight(), ras.getWidth()/2, -ras.getHeight()/2, dbb.getData(), largestDotWidth+minimumGutter, largestDotWidth, smallestDotWidth, primNode, curCell); } catch (Exception e) { throw new RuntimeException(e); } }//GEN-LAST:event_ok private static class LayoutImageJob extends Job { int width; int height; int xOffset; int yOffset; byte[] samples; int scale; int largestDotWidth; int smallestDotWidth; NodeProto primNode; Cell curCell; public LayoutImageJob(int width, int height, int xOffset, int yOffset, byte[] samples, int scale, int largestDotWidth, int smallestDotWidth, NodeProto primNode, Cell curCell) { super("Create Layout Image", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER); this.xOffset = xOffset; this.yOffset = yOffset; this.width = width; this.height = height; this.samples = samples; this.scale = scale; this.largestDotWidth = largestDotWidth; this.smallestDotWidth = smallestDotWidth; this.primNode = primNode; this.curCell = curCell; startJob(); } public boolean doIt() throws JobException { int samp = 0; for(int y=0; y<height; y++) { for(int x=0; x<width; x++) { int w = ((int)(((255-(samples[samp++] & 0xff)) / 255f) * ((largestDotWidth-smallestDotWidth))))+smallestDotWidth; Point2D center = new Point2D.Double((x-xOffset)*scale, -(y+yOffset)*scale); NodeInst.newInstance(primNode, center, w, w, curCell); } } return true; } } private void monochromeActionPerford(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_monochromeActionPerford // TODO add your handling code here: }//GEN-LAST:event_monochromeActionPerford private void openFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openFileButtonActionPerformed String fn = OpenFile.chooseInputFile(FileType.ANY, null); if (fn == null) return; fileName.setText(fn); }//GEN-LAST:event_openFileButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancel; private javax.swing.JTextField fileName; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField largestDotWidth; private javax.swing.JTextField minimumGutter; private javax.swing.JCheckBox monochrome; private javax.swing.JButton ok; private javax.swing.JButton openFileButton; private javax.swing.JCheckBox reverseVideo; private javax.swing.JTextField smallestDotWidth; private javax.swing.JComboBox textLayer; // End of variables declaration//GEN-END:variables }
gpl-3.0
DimChristodoulou/PicIt
PicIt/app/src/main/java/com/example/android/picit/SchemaClasses/User.java
1801
package com.example.android.picit.SchemaClasses; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import com.example.android.picit.ServerHandler.ServerClient; import com.example.android.picit.ServerHandler.ServerInterface; import com.google.gson.annotations.SerializedName; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by DimitrisLPC on 14/10/2017. */ public class User { @SerializedName("UserId") private int userId; public static int getUserId(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); return prefs.getInt("usertoken", -1); } public static void setUserId(final Context context) { ServerInterface serverService = ServerClient.getClient(context).create(ServerInterface.class); final SharedPreferences.Editor prefsedit = PreferenceManager.getDefaultSharedPreferences(context).edit(); Call<Integer> addUserCall = serverService.addUser(); addUserCall.enqueue(new Callback<Integer>() { @Override public void onResponse(Call<Integer> call, Response<Integer> response) { if (response.code() < 300) { prefsedit.putInt("usertoken", response.body()); prefsedit.apply(); } } @Override public void onFailure(Call<Integer> call, Throwable t) { Log.d("ONLOGINERROR", t.toString()); Toast.makeText(context, "Something went wrong. Try again later.", Toast.LENGTH_SHORT).show(); } }); } }
gpl-3.0
egglestn/quiz
app/assets/javascripts/content.js
416
$(document).ready(function() { $('#content_category').change(function(event) { var $content = $('.content'); var $answers = $content.find(".answers"); console.log("."); // Hard-coded value, needs to match the "Question" option in the category enum in content.rb if (event.target.options.selectedIndex == 1) { $answers.hide(); } else { $answers.show(); } }); });
gpl-3.0
reitzig/2015_apportionment
src/de/unikl/cs/agak/appportionment/experiments/ApportionmentInstanceFactory.java
3134
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.unikl.cs.agak.appportionment.experiments; import de.unikl.cs.agak.appportionment.ApportionmentInstance; import de.unikl.cs.agak.appportionment.util.SedgewickRandom; /** * Samples apportionment instances randomly. * * @author Raphael Reitzig (reitzig@cs.uni-kl.de) */ public class ApportionmentInstanceFactory { static final VoteFactory UniformVotes = new VoteFactory() { @Override public double next(SedgewickRandom r) { return r.uniform(1.0, 3.0); } }; static final VoteFactory ExponentialVotes = new VoteFactory() { @Override public double next(SedgewickRandom r) { return 1.0 + r.exp(1.0); } }; static final VoteFactory PoissonVotes = new VoteFactory() { @Override public double next(SedgewickRandom r) { return 1.0 + r.poisson(100)/100.0; } }; static final VoteFactory Pareto1_5Votes = new VoteFactory() { @Override public double next(SedgewickRandom r) { return 1.0 + r.pareto(1.5); } }; @Deprecated static final VoteFactory Pareto2Votes = new VoteFactory() { @Override public double next(SedgewickRandom r) { return 1.0 + r.pareto(2.0); } }; @Deprecated static final VoteFactory Pareto3Votes = new VoteFactory() { @Override public double next(SedgewickRandom r) { return 1.0 + r.pareto(3.0); } }; static ApportionmentInstance randomInstance(final SedgewickRandom random, final VoteFactory vf, final int n, final KFactory k) { final double[] votes = new double[n]; for ( int i = 0; i < votes.length; i++ ) { votes[i] = vf.next(random); } return new ApportionmentInstance(votes, k.sampleFactor(random) * n); } public interface VoteFactory { double next(SedgewickRandom r); } public static class KFactory { int minK; int maxK; /** * Creates a factory that always samples k*n. */ public KFactory(int k) { minK = k; maxK = k; } /** * Creates a factory that samples uniformly from interval [min*n,max*n]. */ public KFactory(int min, int max) { assert min <= max; minK = min; maxK = max; } public int sampleFactor(SedgewickRandom r) { if ( minK == maxK ) return minK; else return r.uniform(minK, maxK); } @Override public String toString() { if ( minK == maxK ) return Integer.toString(minK) + "*n"; else return "U[" + minK + "*n, " + maxK + "*n]"; } } }
gpl-3.0
Exarchiasghost/openemr
version.php
813
<?php // Software version identification. // This is used for display purposes, and also the major/minor/patch // numbers are stored in the database and used to determine which sql // upgrade file is the starting point for the next upgrade. $v_major = '4'; $v_minor = '1'; $v_patch = '1'; $v_tag = ''; // minor revision number, should be empty for production releases // A real patch identifier. This is incremented when release a patch for a // production release. Not the above $v_patch variable is a misnomer and actually // stores release version information. $v_realpatch = '0'; // Database version identifier, this is to be incremented whenever there // is a database change in the course of development. It is used // internally to determine when a database upgrade is needed. // $v_database = 80; ?>
gpl-3.0
ErikViWe/accounting-manager
src/Main.java
306
import gui.GUI; import helperMethods.SettingsHelper; public class Main { /** * Main class for starting the Program only. * @param args * @author Erik Weinstock * @version 1.0 */ public static void main(String[] args) { SettingsHelper.checkForExistence(); GUI mainGUI = new GUI(); } }
gpl-3.0
IonAgorria/Ouroboros
src/com/agorria/ouroboros/simulation/action/ActionType.java
413
package com.agorria.ouroboros.simulation.action; import com.agorria.ouroboros.core.Utilities; /** * Created on 10/12/2017. * @author Ion Agorria * * Stores action types */ public enum ActionType { Message, PlayerJoin, PlayerLeave, SubmitOrder, RemoveOrder, Pause, MessageServer, ; private static final long serialVersionUID = Utilities.getClassUID(ActionType.class); }
gpl-3.0
CNESmeteo/cnesmeteo
user/models/Throttle.php
262
<?php namespace CnesMeteo\User\Models; use October\Rain\Auth\Models\Throttle as ThrottleBase; class Throttle extends ThrottleBase { /** * @var array Relations */ public $belongsTo = [ 'user' => ['CnesMeteo\User\Models\User'] ]; }
gpl-3.0
coolme200/NodeBB
src/privileges.js
742
"use strict"; var privileges = {}; privileges.userPrivilegeList = [ 'find', 'read', 'topics:read', 'topics:create', 'topics:reply', 'upload:post:image', 'upload:post:file', 'purge', 'mods' ]; privileges.groupPrivilegeList = [ 'groups:find', 'groups:read', 'groups:topics:read', 'groups:topics:create', 'groups:topics:reply', 'groups:upload:post:image', 'groups:upload:post:file', 'groups:purge', 'groups:moderate' ]; privileges.privilegeList = privileges.userPrivilegeList.concat(privileges.groupPrivilegeList); require('./privileges/categories')(privileges); require('./privileges/topics')(privileges); require('./privileges/posts')(privileges); require('./privileges/users')(privileges); module.exports = privileges;
gpl-3.0
KWARC/deprecated-LLaMaPUn
src/scripts/run_libsvm_experiment.py
2901
#!/usr/bin/bash import os import subprocess import sys #as beryl doesn't support python3: if sys.version_info[0] < 3: input = raw_input def getReadableFileName(msg): s = input(msg) if not os.path.isfile(s): print("Error: File doesn't exist") return getReadableFileName(msg) elif not os.access(s, os.R_OK): print("Error: File isn't readable") return getReadableFileName(msg) else: return s print("Script for running SVM experiments") print("\nNote: This is a simple tool, we assume the user knows what is going on,") print("so we're not checking for everything that might go wrong") print("(especially, older results can be overwritten)\n") libsvmDir = input("LibSVM directory (e.g. \"/arXMLiv/experiments/libsvm-318\"):\n") trainDataFileName = getReadableFileName("File name for training data: ") testDataFileName = getReadableFileName("File name for test data: ") subsetSize = int(input("Size of subset (e.g. 50000): ")) assert subsetSize > 0 def printAndCall(string): print(string) return subprocess.call(string, shell=True) #STEP 1 print("Validating data") if printAndCall("python " + os.path.join(libsvmDir, "tools/checkdata.py") + " " + trainDataFileName): print(trainDataFileName + " doesn't appear to be a valid input file.") sys.exit(1) elif printAndCall("python " + os.path.join(libsvmDir, "tools/checkdata.py") + " " + testDataFileName): print(testDataFileName + " doesn't appear to be a valid input file.") sys.exit(1) def commonPrefix(s1, s2): """Returns the maximal common prefix of s1 and s2""" prefix = "" for i in range(len(s1)): if i >= len(s2) or s1[i] != s2[i]: break else: prefix += s1[i] return prefix #STEP 2 print("Scaling the data (train set)") #let's try to use meaningful names for files we created scalingFileName = commonPrefix(trainDataFileName, testDataFileName) + "_scaling.txt" trainScaledFileName = trainDataFileName + ".scaled" if printAndCall(os.path.join(libsvmDir, "./svm-scale") + " -l 0 -s " + scalingFileName + " " + \ trainDataFileName + " > " + trainScaledFileName): print("An error occured while we were trying to scale the training set (fatal, exiting)") sys.exit(1) print("Apply scaling to the test set") testScaledFileName = testDataFileName + ".scaled" if printAndCall(os.path.join(libsvmDir, "./svm-scale") + " -l 0 -r " + scalingFileName + " " + \ testDataFileName + " > " + testScaledFileName): print("An error occured while scaling the test set (fatal, exiting)") sys.exit(1) #STEP 3 print("Generating a subset of the train data for parameter estimation") subsetFileName = trainScaledFileName + ".subset" if printAndCall("python " + os.path.join(libsvmDir, "tools/subset.py") + " -s 1 " + \ trainScaledFileName + " " + str(subsetSize) + " " + subsetFileName): print("An error occured while generating the subset (fatal, exiting)") sys.exit(1)
gpl-3.0
monobogdan/novasocial
zo.php
2632
<?php session_start(); error_reporting(E_ALL^E_DEPRECATED); include "sys/system.page.php"; include "sys/system.db.php"; include "sys/system.auth.php"; include "sys/system.files.php"; include "sys/system.ad.php"; class Page { var $gen; var $auth; var $db; var $files; function __construct() { global $gen; global $auth; global $db; global $files; $gen = new PageGenerator(); $db = new Database; $auth = new Authorization; $files = new Files; if($auth->IsUserAuthorized()) { if($_SESSION["userpassword"] != $auth->GetUserInformation($db, $auth->GetUserID($db, $_SESSION["username"]))["password"]) { $auth->Logout(); } } } function __destruct() { global $gen; global $db; $ad = new Ad; if($ad->ShowAds($db)) { $ad->RenderAd($db); } } function Render() { global $gen; global $auth; global $db; global $files; if($_GET["razdel"] == "programs") { $gen->CreateText("Зона обмена: Программы"); $res = $files->GetFilesByCategory($db, "programs"); if($res == 0) { $gen->CreateText("Нет файлов!"); $gen->CreateLinkWithIcon("home", "Домой", "index.php"); exit; } for($i = 1; $i < count($res) + 1; $i++) { $gen->CreateLinkWithIcon("cloud-download", $res[$i]["name"], "files.php?fileid=" . $res[$i]["id"]); } $gen->CreateLinkWithIcon("home", "Домой", "index.php"); } if($_GET["razdel"] == "music") { $gen->CreateText("Зона обмена: Музыка"); $res = $files->GetFilesByCategory($db, "music"); if($res == 0) { $gen->CreateText("Нет файлов!"); $gen->CreateLinkWithIcon("home", "Домой", "index.php"); exit; } for($i = 1; $i < count($res) + 1; $i++) { $gen->CreateLinkWithIcon("cloud-download", $res[$i]["name"], "files.php?fileid=" . $res[$i]["id"]); } $gen->CreateLinkWithIcon("home", "Домой", "index.php"); } if($_GET["razdel"] == "photo") { $gen->CreateText("Зона обмена: Фото"); $res = $files->GetFilesByCategory($db, "pictures"); if($res == 0) { $gen->CreateText("Нет файлов!"); $gen->CreateLinkWithIcon("home", "Домой", "index.php"); exit; } for($i = 1; $i < count($res) + 1; $i++) { $gen->CreateLinkWithIcon("cloud-download", $res[$i]["name"], "files.php?fileid=" . $res[$i]["id"]); } $gen->CreateLinkWithIcon("home", "Домой", "index.php"); } } } $index = new Page; $index->Render(); ?>
gpl-3.0
pompomJuice/cpp-ethereum
libsolidity/Types.cpp
45484
/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity data types */ #include <libsolidity/Types.h> #include <limits> #include <boost/range/adaptor/reversed.hpp> #include <libdevcore/CommonIO.h> #include <libdevcore/CommonData.h> #include <libdevcore/SHA3.h> #include <libsolidity/Utils.h> #include <libsolidity/AST.h> using namespace std; namespace dev { namespace solidity { void StorageOffsets::computeOffsets(TypePointers const& _types) { bigint slotOffset = 0; unsigned byteOffset = 0; map<size_t, pair<u256, unsigned>> offsets; for (size_t i = 0; i < _types.size(); ++i) { TypePointer const& type = _types[i]; if (!type->canBeStored()) continue; if (byteOffset + type->getStorageBytes() > 32) { // would overflow, go to next slot ++slotOffset; byteOffset = 0; } if (slotOffset >= bigint(1) << 256) BOOST_THROW_EXCEPTION(TypeError() << errinfo_comment("Object too large for storage.")); offsets[i] = make_pair(u256(slotOffset), byteOffset); solAssert(type->getStorageSize() >= 1, "Invalid storage size."); if (type->getStorageSize() == 1 && byteOffset + type->getStorageBytes() <= 32) byteOffset += type->getStorageBytes(); else { slotOffset += type->getStorageSize(); byteOffset = 0; } } if (byteOffset > 0) ++slotOffset; if (slotOffset >= bigint(1) << 256) BOOST_THROW_EXCEPTION(TypeError() << errinfo_comment("Object too large for storage.")); m_storageSize = u256(slotOffset); swap(m_offsets, offsets); } pair<u256, unsigned> const* StorageOffsets::getOffset(size_t _index) const { if (m_offsets.count(_index)) return &m_offsets.at(_index); else return nullptr; } MemberList& MemberList::operator=(MemberList&& _other) { m_memberTypes = std::move(_other.m_memberTypes); m_storageOffsets = std::move(_other.m_storageOffsets); return *this; } std::pair<u256, unsigned> const* MemberList::getMemberStorageOffset(string const& _name) const { if (!m_storageOffsets) { TypePointers memberTypes; memberTypes.reserve(m_memberTypes.size()); for (auto const& member: m_memberTypes) memberTypes.push_back(member.type); m_storageOffsets.reset(new StorageOffsets()); m_storageOffsets->computeOffsets(memberTypes); } for (size_t index = 0; index < m_memberTypes.size(); ++index) if (m_memberTypes[index].name == _name) return m_storageOffsets->getOffset(index); return nullptr; } u256 const& MemberList::getStorageSize() const { // trigger lazy computation getMemberStorageOffset(""); return m_storageOffsets->getStorageSize(); } TypePointer Type::fromElementaryTypeName(Token::Value _typeToken) { char const* tokenCstr = Token::toString(_typeToken); solAssert(Token::isElementaryTypeName(_typeToken), "Expected an elementary type name but got " + ((tokenCstr) ? std::string(Token::toString(_typeToken)) : "")); if (Token::Int <= _typeToken && _typeToken <= Token::Bytes32) { int offset = _typeToken - Token::Int; int bytes = offset % 33; if (bytes == 0 && _typeToken != Token::Bytes0) bytes = 32; int modifier = offset / 33; switch(modifier) { case 0: return make_shared<IntegerType>(bytes * 8, IntegerType::Modifier::Signed); case 1: return make_shared<IntegerType>(bytes * 8, IntegerType::Modifier::Unsigned); case 2: return make_shared<FixedBytesType>(bytes); default: solAssert(false, "Unexpected modifier value. Should never happen"); return TypePointer(); } } else if (_typeToken == Token::Byte) return make_shared<FixedBytesType>(1); else if (_typeToken == Token::Address) return make_shared<IntegerType>(0, IntegerType::Modifier::Address); else if (_typeToken == Token::Bool) return make_shared<BoolType>(); else if (_typeToken == Token::Bytes) return make_shared<ArrayType>(ReferenceType::Location::Storage); else if (_typeToken == Token::String) return make_shared<ArrayType>(ReferenceType::Location::Storage, true); else BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unable to convert elementary typename " + std::string(Token::toString(_typeToken)) + " to type.")); } TypePointer Type::fromElementaryTypeName(string const& _name) { return fromElementaryTypeName(Token::fromIdentifierOrKeyword(_name)); } TypePointer Type::fromUserDefinedTypeName(UserDefinedTypeName const& _typeName) { Declaration const* declaration = _typeName.getReferencedDeclaration(); if (StructDefinition const* structDef = dynamic_cast<StructDefinition const*>(declaration)) return make_shared<StructType>(*structDef); else if (EnumDefinition const* enumDef = dynamic_cast<EnumDefinition const*>(declaration)) return make_shared<EnumType>(*enumDef); else if (FunctionDefinition const* function = dynamic_cast<FunctionDefinition const*>(declaration)) return make_shared<FunctionType>(*function); else if (ContractDefinition const* contract = dynamic_cast<ContractDefinition const*>(declaration)) return make_shared<ContractType>(*contract); return TypePointer(); } TypePointer Type::fromMapping(ElementaryTypeName& _keyType, TypeName& _valueType) { TypePointer keyType = _keyType.toType(); if (!keyType) BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Error resolving type name.")); TypePointer valueType = _valueType.toType(); if (!valueType) BOOST_THROW_EXCEPTION(_valueType.createTypeError("Invalid type name.")); return make_shared<MappingType>(keyType, valueType); } TypePointer Type::fromArrayTypeName(TypeName& _baseTypeName, Expression* _length) { TypePointer baseType = _baseTypeName.toType(); if (!baseType) BOOST_THROW_EXCEPTION(_baseTypeName.createTypeError("Invalid type name.")); if (baseType->getStorageBytes() == 0) BOOST_THROW_EXCEPTION(_baseTypeName.createTypeError("Illegal base type of storage size zero for array.")); if (_length) { if (!_length->getType()) _length->checkTypeRequirements(nullptr); auto const* length = dynamic_cast<IntegerConstantType const*>(_length->getType().get()); if (!length) BOOST_THROW_EXCEPTION(_length->createTypeError("Invalid array length.")); return make_shared<ArrayType>(ReferenceType::Location::Storage, baseType, length->literalValue(nullptr)); } else return make_shared<ArrayType>(ReferenceType::Location::Storage, baseType); } TypePointer Type::forLiteral(Literal const& _literal) { switch (_literal.getToken()) { case Token::TrueLiteral: case Token::FalseLiteral: return make_shared<BoolType>(); case Token::Number: return make_shared<IntegerConstantType>(_literal); case Token::StringLiteral: //@todo put larger strings into dynamic strings return FixedBytesType::smallestTypeForLiteral(_literal.getValue()); default: return shared_ptr<Type>(); } } TypePointer Type::commonType(TypePointer const& _a, TypePointer const& _b) { if (_b->isImplicitlyConvertibleTo(*_a)) return _a; else if (_a->isImplicitlyConvertibleTo(*_b)) return _b; else return TypePointer(); } const MemberList Type::EmptyMemberList; IntegerType::IntegerType(int _bits, IntegerType::Modifier _modifier): m_bits(_bits), m_modifier(_modifier) { if (isAddress()) m_bits = 160; solAssert(m_bits > 0 && m_bits <= 256 && m_bits % 8 == 0, "Invalid bit number for integer type: " + dev::toString(_bits)); } bool IntegerType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo.getCategory() != getCategory()) return false; IntegerType const& convertTo = dynamic_cast<IntegerType const&>(_convertTo); if (convertTo.m_bits < m_bits) return false; if (isAddress()) return convertTo.isAddress(); else if (isSigned()) return convertTo.isSigned(); else return !convertTo.isSigned() || convertTo.m_bits > m_bits; } bool IntegerType::isExplicitlyConvertibleTo(Type const& _convertTo) const { return _convertTo.getCategory() == getCategory() || _convertTo.getCategory() == Category::Contract || _convertTo.getCategory() == Category::Enum || _convertTo.getCategory() == Category::FixedBytes; } TypePointer IntegerType::unaryOperatorResult(Token::Value _operator) const { // "delete" is ok for all integer types if (_operator == Token::Delete) return make_shared<VoidType>(); // no further unary operators for addresses else if (isAddress()) return TypePointer(); // for non-address integers, we allow +, -, ++ and -- else if (_operator == Token::Add || _operator == Token::Sub || _operator == Token::Inc || _operator == Token::Dec || _operator == Token::After || _operator == Token::BitNot) return shared_from_this(); else return TypePointer(); } bool IntegerType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; IntegerType const& other = dynamic_cast<IntegerType const&>(_other); return other.m_bits == m_bits && other.m_modifier == m_modifier; } string IntegerType::toString() const { if (isAddress()) return "address"; string prefix = isSigned() ? "int" : "uint"; return prefix + dev::toString(m_bits); } TypePointer IntegerType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const { if (_other->getCategory() != Category::IntegerConstant && _other->getCategory() != getCategory()) return TypePointer(); auto commonType = dynamic_pointer_cast<IntegerType const>(Type::commonType(shared_from_this(), _other)); if (!commonType) return TypePointer(); // All integer types can be compared if (Token::isCompareOp(_operator)) return commonType; // Nothing else can be done with addresses if (commonType->isAddress()) return TypePointer(); return commonType; } const MemberList IntegerType::AddressMemberList({ {"balance", make_shared<IntegerType >(256)}, {"call", make_shared<FunctionType>(strings(), strings{"bool"}, FunctionType::Location::Bare, true)}, {"callcode", make_shared<FunctionType>(strings(), strings{"bool"}, FunctionType::Location::BareCallCode, true)}, {"send", make_shared<FunctionType>(strings{"uint"}, strings{"bool"}, FunctionType::Location::Send)} }); IntegerConstantType::IntegerConstantType(Literal const& _literal) { m_value = bigint(_literal.getValue()); switch (_literal.getSubDenomination()) { case Literal::SubDenomination::Wei: case Literal::SubDenomination::Second: case Literal::SubDenomination::None: break; case Literal::SubDenomination::Szabo: m_value *= bigint("1000000000000"); break; case Literal::SubDenomination::Finney: m_value *= bigint("1000000000000000"); break; case Literal::SubDenomination::Ether: m_value *= bigint("1000000000000000000"); break; case Literal::SubDenomination::Minute: m_value *= bigint("60"); break; case Literal::SubDenomination::Hour: m_value *= bigint("3600"); break; case Literal::SubDenomination::Day: m_value *= bigint("86400"); break; case Literal::SubDenomination::Week: m_value *= bigint("604800"); break; case Literal::SubDenomination::Year: m_value *= bigint("31536000"); break; } } bool IntegerConstantType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (auto targetType = dynamic_cast<IntegerType const*>(&_convertTo)) { if (m_value == 0) return true; int forSignBit = (targetType->isSigned() ? 1 : 0); if (m_value > 0) { if (m_value <= (u256(-1) >> (256 - targetType->getNumBits() + forSignBit))) return true; } else if (targetType->isSigned() && -m_value <= (u256(1) << (targetType->getNumBits() - forSignBit))) return true; return false; } else if (_convertTo.getCategory() == Category::FixedBytes) { FixedBytesType const& fixedBytes = dynamic_cast<FixedBytesType const&>(_convertTo); return fixedBytes.getNumBytes() * 8 >= getIntegerType()->getNumBits(); } else return false; } bool IntegerConstantType::isExplicitlyConvertibleTo(Type const& _convertTo) const { TypePointer integerType = getIntegerType(); return integerType && integerType->isExplicitlyConvertibleTo(_convertTo); } TypePointer IntegerConstantType::unaryOperatorResult(Token::Value _operator) const { bigint value; switch (_operator) { case Token::BitNot: value = ~m_value; break; case Token::Add: value = m_value; break; case Token::Sub: value = -m_value; break; case Token::After: return shared_from_this(); default: return TypePointer(); } return make_shared<IntegerConstantType>(value); } TypePointer IntegerConstantType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const { if (_other->getCategory() == Category::Integer) { shared_ptr<IntegerType const> integerType = getIntegerType(); if (!integerType) return TypePointer(); return integerType->binaryOperatorResult(_operator, _other); } else if (_other->getCategory() != getCategory()) return TypePointer(); IntegerConstantType const& other = dynamic_cast<IntegerConstantType const&>(*_other); if (Token::isCompareOp(_operator)) { shared_ptr<IntegerType const> thisIntegerType = getIntegerType(); shared_ptr<IntegerType const> otherIntegerType = other.getIntegerType(); if (!thisIntegerType || !otherIntegerType) return TypePointer(); return thisIntegerType->binaryOperatorResult(_operator, otherIntegerType); } else { bigint value; switch (_operator) { case Token::BitOr: value = m_value | other.m_value; break; case Token::BitXor: value = m_value ^ other.m_value; break; case Token::BitAnd: value = m_value & other.m_value; break; case Token::Add: value = m_value + other.m_value; break; case Token::Sub: value = m_value - other.m_value; break; case Token::Mul: value = m_value * other.m_value; break; case Token::Div: if (other.m_value == 0) return TypePointer(); value = m_value / other.m_value; break; case Token::Mod: if (other.m_value == 0) return TypePointer(); value = m_value % other.m_value; break; case Token::Exp: if (other.m_value < 0) return TypePointer(); else if (other.m_value > std::numeric_limits<unsigned int>::max()) return TypePointer(); else value = boost::multiprecision::pow(m_value, other.m_value.convert_to<unsigned int>()); break; default: return TypePointer(); } return make_shared<IntegerConstantType>(value); } } bool IntegerConstantType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; return m_value == dynamic_cast<IntegerConstantType const&>(_other).m_value; } string IntegerConstantType::toString() const { return "int_const " + m_value.str(); } u256 IntegerConstantType::literalValue(Literal const*) const { u256 value; // we ignore the literal and hope that the type was correctly determined solAssert(m_value <= u256(-1), "Integer constant too large."); solAssert(m_value >= -(bigint(1) << 255), "Integer constant too small."); if (m_value >= 0) value = u256(m_value); else value = s2u(s256(m_value)); return value; } TypePointer IntegerConstantType::getRealType() const { auto intType = getIntegerType(); solAssert(!!intType, "getRealType called with invalid integer constant " + toString()); return intType; } shared_ptr<IntegerType const> IntegerConstantType::getIntegerType() const { bigint value = m_value; bool negative = (value < 0); if (negative) // convert to positive number of same bit requirements value = ((-value) - 1) << 1; if (value > u256(-1)) return shared_ptr<IntegerType const>(); else return make_shared<IntegerType>( max(bytesRequired(value), 1u) * 8, negative ? IntegerType::Modifier::Signed : IntegerType::Modifier::Unsigned ); } shared_ptr<FixedBytesType> FixedBytesType::smallestTypeForLiteral(string const& _literal) { if (_literal.length() <= 32) return make_shared<FixedBytesType>(_literal.length()); return shared_ptr<FixedBytesType>(); } FixedBytesType::FixedBytesType(int _bytes): m_bytes(_bytes) { solAssert(m_bytes >= 0 && m_bytes <= 32, "Invalid byte number for fixed bytes type: " + dev::toString(m_bytes)); } bool FixedBytesType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (_convertTo.getCategory() != getCategory()) return false; FixedBytesType const& convertTo = dynamic_cast<FixedBytesType const&>(_convertTo); return convertTo.m_bytes >= m_bytes; } bool FixedBytesType::isExplicitlyConvertibleTo(Type const& _convertTo) const { return _convertTo.getCategory() == Category::Integer || _convertTo.getCategory() == Category::Contract || _convertTo.getCategory() == getCategory(); } TypePointer FixedBytesType::unaryOperatorResult(Token::Value _operator) const { // "delete" and "~" is okay for FixedBytesType if (_operator == Token::Delete) return make_shared<VoidType>(); else if (_operator == Token::BitNot) return shared_from_this(); return TypePointer(); } TypePointer FixedBytesType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const { auto commonType = dynamic_pointer_cast<FixedBytesType const>(Type::commonType(shared_from_this(), _other)); if (!commonType) return TypePointer(); // FixedBytes can be compared and have bitwise operators applied to them if (Token::isCompareOp(_operator) || Token::isBitOp(_operator)) return commonType; return TypePointer(); } bool FixedBytesType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; FixedBytesType const& other = dynamic_cast<FixedBytesType const&>(_other); return other.m_bytes == m_bytes; } u256 FixedBytesType::literalValue(const Literal* _literal) const { solAssert(_literal, ""); u256 value = 0; for (char c: _literal->getValue()) value = (value << 8) | byte(c); return value << ((32 - _literal->getValue().length()) * 8); } bool BoolType::isExplicitlyConvertibleTo(Type const& _convertTo) const { // conversion to integer is fine, but not to address // this is an example of explicit conversions being not transitive (though implicit should be) if (_convertTo.getCategory() == getCategory()) { IntegerType const& convertTo = dynamic_cast<IntegerType const&>(_convertTo); if (!convertTo.isAddress()) return true; } return isImplicitlyConvertibleTo(_convertTo); } u256 BoolType::literalValue(Literal const* _literal) const { solAssert(_literal, ""); if (_literal->getToken() == Token::TrueLiteral) return u256(1); else if (_literal->getToken() == Token::FalseLiteral) return u256(0); else BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Bool type constructed from non-boolean literal.")); } TypePointer BoolType::unaryOperatorResult(Token::Value _operator) const { if (_operator == Token::Delete) return make_shared<VoidType>(); return (_operator == Token::Not) ? shared_from_this() : TypePointer(); } TypePointer BoolType::binaryOperatorResult(Token::Value _operator, TypePointer const& _other) const { if (getCategory() != _other->getCategory()) return TypePointer(); if (Token::isCompareOp(_operator) || _operator == Token::And || _operator == Token::Or) return _other; else return TypePointer(); } bool ContractType::isImplicitlyConvertibleTo(Type const& _convertTo) const { if (*this == _convertTo) return true; if (_convertTo.getCategory() == Category::Integer) return dynamic_cast<IntegerType const&>(_convertTo).isAddress(); if (_convertTo.getCategory() == Category::Contract) { auto const& bases = getContractDefinition().getLinearizedBaseContracts(); if (m_super && bases.size() <= 1) return false; return find(m_super ? ++bases.begin() : bases.begin(), bases.end(), &dynamic_cast<ContractType const&>(_convertTo).getContractDefinition()) != bases.end(); } return false; } bool ContractType::isExplicitlyConvertibleTo(Type const& _convertTo) const { return isImplicitlyConvertibleTo(_convertTo) || _convertTo.getCategory() == Category::Integer || _convertTo.getCategory() == Category::Contract; } TypePointer ContractType::unaryOperatorResult(Token::Value _operator) const { return _operator == Token::Delete ? make_shared<VoidType>() : TypePointer(); } bool ArrayType::isImplicitlyConvertibleTo(const Type& _convertTo) const { if (_convertTo.getCategory() != getCategory()) return false; auto& convertTo = dynamic_cast<ArrayType const&>(_convertTo); // let us not allow assignment to memory arrays for now if (convertTo.location() != Location::Storage) return false; if (convertTo.isByteArray() != isByteArray() || convertTo.isString() != isString()) return false; if (!getBaseType()->isImplicitlyConvertibleTo(*convertTo.getBaseType())) return false; if (convertTo.isDynamicallySized()) return true; return !isDynamicallySized() && convertTo.getLength() >= getLength(); } TypePointer ArrayType::unaryOperatorResult(Token::Value _operator) const { if (_operator == Token::Delete) return make_shared<VoidType>(); return TypePointer(); } bool ArrayType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; ArrayType const& other = dynamic_cast<ArrayType const&>(_other); if ( other.m_location != m_location || other.isByteArray() != isByteArray() || other.isString() != isString() || other.isDynamicallySized() != isDynamicallySized() ) return false; return isDynamicallySized() || getLength() == other.getLength(); } unsigned ArrayType::getCalldataEncodedSize(bool _padded) const { if (isDynamicallySized()) return 0; bigint size = bigint(getLength()) * (isByteArray() ? 1 : getBaseType()->getCalldataEncodedSize(_padded)); size = ((size + 31) / 32) * 32; solAssert(size <= numeric_limits<unsigned>::max(), "Array size does not fit unsigned."); return unsigned(size); } u256 ArrayType::getStorageSize() const { if (isDynamicallySized()) return 1; bigint size; unsigned baseBytes = getBaseType()->getStorageBytes(); if (baseBytes == 0) size = 1; else if (baseBytes < 32) { unsigned itemsPerSlot = 32 / baseBytes; size = (bigint(getLength()) + (itemsPerSlot - 1)) / itemsPerSlot; } else size = bigint(getLength()) * getBaseType()->getStorageSize(); if (size >= bigint(1) << 256) BOOST_THROW_EXCEPTION(TypeError() << errinfo_comment("Array too large for storage.")); return max<u256>(1, u256(size)); } unsigned ArrayType::getSizeOnStack() const { if (m_location == Location::CallData) // offset [length] (stack top) return 1 + (isDynamicallySized() ? 1 : 0); else if (m_location == Location::Storage) // storage_key storage_offset return 2; else // offset return 1; } string ArrayType::toString() const { if (isString()) return "string"; else if (isByteArray()) return "bytes"; string ret = getBaseType()->toString() + "["; if (!isDynamicallySized()) ret += getLength().str(); return ret + "]"; } TypePointer ArrayType::externalType() const { if (m_arrayKind != ArrayKind::Ordinary) return shared_from_this(); if (!m_baseType->externalType()) return TypePointer(); if (m_baseType->getCategory() == Category::Array && m_baseType->isDynamicallySized()) return TypePointer(); if (isDynamicallySized()) return std::make_shared<ArrayType>(Location::CallData, m_baseType->externalType()); else return std::make_shared<ArrayType>(Location::CallData, m_baseType->externalType(), m_length); } TypePointer ArrayType::copyForLocation(ReferenceType::Location _location) const { auto copy = make_shared<ArrayType>(_location); copy->m_arrayKind = m_arrayKind; if (auto ref = dynamic_cast<ReferenceType const*>(m_baseType.get())) copy->m_baseType = ref->copyForLocation(_location); else copy->m_baseType = m_baseType; copy->m_hasDynamicLength = m_hasDynamicLength; copy->m_length = m_length; return copy; } const MemberList ArrayType::s_arrayTypeMemberList({{"length", make_shared<IntegerType>(256)}}); bool ContractType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; ContractType const& other = dynamic_cast<ContractType const&>(_other); return other.m_contract == m_contract && other.m_super == m_super; } string ContractType::toString() const { return "contract " + string(m_super ? "super " : "") + m_contract.getName(); } MemberList const& ContractType::getMembers() const { // We need to lazy-initialize it because of recursive references. if (!m_members) { // All address members and all interface functions MemberList::MemberMap members( IntegerType::AddressMemberList.begin(), IntegerType::AddressMemberList.end() ); if (m_super) { // add the most derived of all functions which are visible in derived contracts for (ContractDefinition const* base: m_contract.getLinearizedBaseContracts()) for (ASTPointer<FunctionDefinition> const& function: base->getDefinedFunctions()) { if (!function->isVisibleInDerivedContracts()) continue; auto functionType = make_shared<FunctionType>(*function, true); bool functionWithEqualArgumentsFound = false; for (auto const& member: members) { if (member.name != function->getName()) continue; auto memberType = dynamic_cast<FunctionType const*>(member.type.get()); solAssert(!!memberType, "Override changes type."); if (!memberType->hasEqualArgumentTypes(*functionType)) continue; functionWithEqualArgumentsFound = true; break; } if (!functionWithEqualArgumentsFound) members.push_back(MemberList::Member( function->getName(), functionType, function.get() )); } } else for (auto const& it: m_contract.getInterfaceFunctions()) members.push_back(MemberList::Member( it.second->getDeclaration().getName(), it.second, &it.second->getDeclaration() )); m_members.reset(new MemberList(members)); } return *m_members; } shared_ptr<FunctionType const> const& ContractType::getConstructorType() const { if (!m_constructorType) { FunctionDefinition const* constructor = m_contract.getConstructor(); if (constructor) m_constructorType = make_shared<FunctionType>(*constructor); else m_constructorType = make_shared<FunctionType>(TypePointers(), TypePointers()); } return m_constructorType; } vector<tuple<VariableDeclaration const*, u256, unsigned>> ContractType::getStateVariables() const { vector<VariableDeclaration const*> variables; for (ContractDefinition const* contract: boost::adaptors::reverse(m_contract.getLinearizedBaseContracts())) for (ASTPointer<VariableDeclaration> const& variable: contract->getStateVariables()) if (!variable->isConstant()) variables.push_back(variable.get()); TypePointers types; for (auto variable: variables) types.push_back(variable->getType()); StorageOffsets offsets; offsets.computeOffsets(types); vector<tuple<VariableDeclaration const*, u256, unsigned>> variablesAndOffsets; for (size_t index = 0; index < variables.size(); ++index) if (auto const* offset = offsets.getOffset(index)) variablesAndOffsets.push_back(make_tuple(variables[index], offset->first, offset->second)); return variablesAndOffsets; } TypePointer StructType::unaryOperatorResult(Token::Value _operator) const { return _operator == Token::Delete ? make_shared<VoidType>() : TypePointer(); } bool StructType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; StructType const& other = dynamic_cast<StructType const&>(_other); return other.m_struct == m_struct; } u256 StructType::getStorageSize() const { return max<u256>(1, getMembers().getStorageSize()); } bool StructType::canLiveOutsideStorage() const { for (auto const& member: getMembers()) if (!member.type->canLiveOutsideStorage()) return false; return true; } string StructType::toString() const { return string("struct ") + m_struct.getName(); } MemberList const& StructType::getMembers() const { // We need to lazy-initialize it because of recursive references. if (!m_members) { MemberList::MemberMap members; for (ASTPointer<VariableDeclaration> const& variable: m_struct.getMembers()) members.push_back(MemberList::Member(variable->getName(), variable->getType(), variable.get())); m_members.reset(new MemberList(members)); } return *m_members; } TypePointer StructType::copyForLocation(ReferenceType::Location _location) const { auto copy = make_shared<StructType>(m_struct); copy->m_location = _location; return copy; } pair<u256, unsigned> const& StructType::getStorageOffsetsOfMember(string const& _name) const { auto const* offsets = getMembers().getMemberStorageOffset(_name); solAssert(offsets, "Storage offset of non-existing member requested."); return *offsets; } TypePointer EnumType::unaryOperatorResult(Token::Value _operator) const { return _operator == Token::Delete ? make_shared<VoidType>() : TypePointer(); } bool EnumType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; EnumType const& other = dynamic_cast<EnumType const&>(_other); return other.m_enum == m_enum; } unsigned EnumType::getStorageBytes() const { size_t elements = m_enum.getMembers().size(); if (elements <= 1) return 1; else return dev::bytesRequired(elements - 1); } string EnumType::toString() const { return string("enum ") + m_enum.getName(); } bool EnumType::isExplicitlyConvertibleTo(Type const& _convertTo) const { return _convertTo.getCategory() == getCategory() || _convertTo.getCategory() == Category::Integer; } unsigned int EnumType::getMemberValue(ASTString const& _member) const { unsigned int index = 0; for (ASTPointer<EnumValue> const& decl: m_enum.getMembers()) { if (decl->getName() == _member) return index; ++index; } BOOST_THROW_EXCEPTION(m_enum.createTypeError("Requested unknown enum value ." + _member)); } FunctionType::FunctionType(FunctionDefinition const& _function, bool _isInternal): m_location(_isInternal ? Location::Internal : Location::External), m_isConstant(_function.isDeclaredConst()), m_declaration(&_function) { TypePointers params; vector<string> paramNames; TypePointers retParams; vector<string> retParamNames; params.reserve(_function.getParameters().size()); paramNames.reserve(_function.getParameters().size()); for (ASTPointer<VariableDeclaration> const& var: _function.getParameters()) { paramNames.push_back(var->getName()); params.push_back(var->getType()); } retParams.reserve(_function.getReturnParameters().size()); retParamNames.reserve(_function.getReturnParameters().size()); for (ASTPointer<VariableDeclaration> const& var: _function.getReturnParameters()) { retParamNames.push_back(var->getName()); retParams.push_back(var->getType()); } swap(params, m_parameterTypes); swap(paramNames, m_parameterNames); swap(retParams, m_returnParameterTypes); swap(retParamNames, m_returnParameterNames); } FunctionType::FunctionType(VariableDeclaration const& _varDecl): m_location(Location::External), m_isConstant(true), m_declaration(&_varDecl) { TypePointers paramTypes; vector<string> paramNames; auto returnType = _varDecl.getType(); while (true) { if (auto mappingType = dynamic_cast<MappingType const*>(returnType.get())) { paramTypes.push_back(mappingType->getKeyType()); paramNames.push_back(""); returnType = mappingType->getValueType(); } else if (auto arrayType = dynamic_cast<ArrayType const*>(returnType.get())) { returnType = arrayType->getBaseType(); paramNames.push_back(""); paramTypes.push_back(make_shared<IntegerType>(256)); } else break; } TypePointers retParams; vector<string> retParamNames; if (auto structType = dynamic_cast<StructType const*>(returnType.get())) { for (auto const& member: structType->getMembers()) if (member.type->getCategory() != Category::Mapping && member.type->getCategory() != Category::Array) { retParamNames.push_back(member.name); retParams.push_back(member.type); } } else { retParams.push_back(returnType); retParamNames.push_back(""); } swap(paramTypes, m_parameterTypes); swap(paramNames, m_parameterNames); swap(retParams, m_returnParameterTypes); swap(retParamNames, m_returnParameterNames); } FunctionType::FunctionType(const EventDefinition& _event): m_location(Location::Event), m_isConstant(true), m_declaration(&_event) { TypePointers params; vector<string> paramNames; params.reserve(_event.getParameters().size()); paramNames.reserve(_event.getParameters().size()); for (ASTPointer<VariableDeclaration> const& var: _event.getParameters()) { paramNames.push_back(var->getName()); params.push_back(var->getType()); } swap(params, m_parameterTypes); swap(paramNames, m_parameterNames); } bool FunctionType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; FunctionType const& other = dynamic_cast<FunctionType const&>(_other); if (m_location != other.m_location) return false; if (m_isConstant != other.isConstant()) return false; if (m_parameterTypes.size() != other.m_parameterTypes.size() || m_returnParameterTypes.size() != other.m_returnParameterTypes.size()) return false; auto typeCompare = [](TypePointer const& _a, TypePointer const& _b) -> bool { return *_a == *_b; }; if (!equal(m_parameterTypes.cbegin(), m_parameterTypes.cend(), other.m_parameterTypes.cbegin(), typeCompare)) return false; if (!equal(m_returnParameterTypes.cbegin(), m_returnParameterTypes.cend(), other.m_returnParameterTypes.cbegin(), typeCompare)) return false; //@todo this is ugly, but cannot be prevented right now if (m_gasSet != other.m_gasSet || m_valueSet != other.m_valueSet) return false; return true; } string FunctionType::toString() const { string name = "function ("; for (auto it = m_parameterTypes.begin(); it != m_parameterTypes.end(); ++it) name += (*it)->toString() + (it + 1 == m_parameterTypes.end() ? "" : ","); name += ") returns ("; for (auto it = m_returnParameterTypes.begin(); it != m_returnParameterTypes.end(); ++it) name += (*it)->toString() + (it + 1 == m_returnParameterTypes.end() ? "" : ","); return name + ")"; } u256 FunctionType::getStorageSize() const { BOOST_THROW_EXCEPTION( InternalCompilerError() << errinfo_comment("Storage size of non-storable function type requested.")); } unsigned FunctionType::getSizeOnStack() const { Location location = m_location; if (m_location == Location::SetGas || m_location == Location::SetValue) { solAssert(m_returnParameterTypes.size() == 1, ""); location = dynamic_cast<FunctionType const&>(*m_returnParameterTypes.front()).m_location; } unsigned size = 0; if (location == Location::External || location == Location::CallCode) size = 2; else if (location == Location::Bare || location == Location::BareCallCode) size = 1; else if (location == Location::Internal) size = 1; if (m_gasSet) size++; if (m_valueSet) size++; return size; } FunctionTypePointer FunctionType::externalFunctionType() const { TypePointers paramTypes; TypePointers retParamTypes; for (auto type: m_parameterTypes) { if (!type->externalType()) return FunctionTypePointer(); paramTypes.push_back(type->externalType()); } for (auto type: m_returnParameterTypes) { if (!type->externalType()) return FunctionTypePointer(); retParamTypes.push_back(type->externalType()); } return make_shared<FunctionType>(paramTypes, retParamTypes, m_parameterNames, m_returnParameterNames, m_location, m_arbitraryParameters); } MemberList const& FunctionType::getMembers() const { switch (m_location) { case Location::External: case Location::Creation: case Location::ECRecover: case Location::SHA256: case Location::RIPEMD160: case Location::Bare: case Location::BareCallCode: if (!m_members) { MemberList::MemberMap members{ { "value", make_shared<FunctionType>( parseElementaryTypeVector({"uint"}), TypePointers{copyAndSetGasOrValue(false, true)}, strings(), strings(), Location::SetValue, false, m_gasSet, m_valueSet ) } }; if (m_location != Location::Creation) members.push_back( MemberList::Member( "gas", make_shared<FunctionType>( parseElementaryTypeVector({"uint"}), TypePointers{copyAndSetGasOrValue(true, false)}, strings(), strings(), Location::SetGas, false, m_gasSet, m_valueSet ) ) ); m_members.reset(new MemberList(members)); } return *m_members; default: return EmptyMemberList; } } bool FunctionType::canTakeArguments(TypePointers const& _argumentTypes) const { TypePointers const& parameterTypes = getParameterTypes(); if (takesArbitraryParameters()) return true; else if (_argumentTypes.size() != parameterTypes.size()) return false; else return std::equal( _argumentTypes.cbegin(), _argumentTypes.cend(), parameterTypes.cbegin(), [](TypePointer const& argumentType, TypePointer const& parameterType) { return argumentType->isImplicitlyConvertibleTo(*parameterType); } ); } bool FunctionType::hasEqualArgumentTypes(FunctionType const& _other) const { if (m_parameterTypes.size() != _other.m_parameterTypes.size()) return false; return equal( m_parameterTypes.cbegin(), m_parameterTypes.cend(), _other.m_parameterTypes.cbegin(), [](TypePointer const& _a, TypePointer const& _b) -> bool { return *_a == *_b; } ); } bool FunctionType::isBareCall() const { switch (m_location) { case Location::Bare: case Location::BareCallCode: case Location::ECRecover: case Location::SHA256: case Location::RIPEMD160: return true; default: return false; } } string FunctionType::externalSignature(std::string const& _name) const { std::string funcName = _name; if (_name == "") { solAssert(m_declaration != nullptr, "Function type without name needs a declaration"); funcName = m_declaration->getName(); } string ret = funcName + "("; FunctionTypePointer external = externalFunctionType(); solAssert(!!external, "External function type requested."); TypePointers externalParameterTypes = external->getParameterTypes(); for (auto it = externalParameterTypes.cbegin(); it != externalParameterTypes.cend(); ++it) { solAssert(!!(*it), "Parameter should have external type"); ret += (*it)->toString() + (it + 1 == externalParameterTypes.cend() ? "" : ","); } return ret + ")"; } u256 FunctionType::externalIdentifier() const { return FixedHash<4>::Arith(FixedHash<4>(dev::sha3(externalSignature()))); } TypePointers FunctionType::parseElementaryTypeVector(strings const& _types) { TypePointers pointers; pointers.reserve(_types.size()); for (string const& type: _types) pointers.push_back(Type::fromElementaryTypeName(type)); return pointers; } TypePointer FunctionType::copyAndSetGasOrValue(bool _setGas, bool _setValue) const { return make_shared<FunctionType>( m_parameterTypes, m_returnParameterTypes, m_parameterNames, m_returnParameterNames, m_location, m_arbitraryParameters, m_gasSet || _setGas, m_valueSet || _setValue ); } vector<string> const FunctionType::getParameterTypeNames() const { vector<string> names; for (TypePointer const& t: m_parameterTypes) names.push_back(t->toString()); return names; } vector<string> const FunctionType::getReturnParameterTypeNames() const { vector<string> names; for (TypePointer const& t: m_returnParameterTypes) names.push_back(t->toString()); return names; } ASTPointer<ASTString> FunctionType::getDocumentation() const { auto function = dynamic_cast<Documented const*>(m_declaration); if (function) return function->getDocumentation(); return ASTPointer<ASTString>(); } bool MappingType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; MappingType const& other = dynamic_cast<MappingType const&>(_other); return *other.m_keyType == *m_keyType && *other.m_valueType == *m_valueType; } string MappingType::toString() const { return "mapping(" + getKeyType()->toString() + " => " + getValueType()->toString() + ")"; } u256 VoidType::getStorageSize() const { BOOST_THROW_EXCEPTION( InternalCompilerError() << errinfo_comment("Storage size of non-storable void type requested.")); } bool TypeType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; TypeType const& other = dynamic_cast<TypeType const&>(_other); return *getActualType() == *other.getActualType(); } u256 TypeType::getStorageSize() const { BOOST_THROW_EXCEPTION( InternalCompilerError() << errinfo_comment("Storage size of non-storable type type requested.")); } MemberList const& TypeType::getMembers() const { // We need to lazy-initialize it because of recursive references. if (!m_members) { MemberList::MemberMap members; if (m_actualType->getCategory() == Category::Contract && m_currentContract != nullptr) { ContractDefinition const& contract = dynamic_cast<ContractType const&>(*m_actualType).getContractDefinition(); vector<ContractDefinition const*> currentBases = m_currentContract->getLinearizedBaseContracts(); if (find(currentBases.begin(), currentBases.end(), &contract) != currentBases.end()) // We are accessing the type of a base contract, so add all public and protected // members. Note that this does not add inherited functions on purpose. for (Declaration const* decl: contract.getInheritableMembers()) members.push_back(MemberList::Member(decl->getName(), decl->getType(), decl)); } else if (m_actualType->getCategory() == Category::Enum) { EnumDefinition const& enumDef = dynamic_cast<EnumType const&>(*m_actualType).getEnumDefinition(); auto enumType = make_shared<EnumType>(enumDef); for (ASTPointer<EnumValue> const& enumValue: enumDef.getMembers()) members.push_back(MemberList::Member(enumValue->getName(), enumType)); } m_members.reset(new MemberList(members)); } return *m_members; } ModifierType::ModifierType(const ModifierDefinition& _modifier) { TypePointers params; params.reserve(_modifier.getParameters().size()); for (ASTPointer<VariableDeclaration> const& var: _modifier.getParameters()) params.push_back(var->getType()); swap(params, m_parameterTypes); } u256 ModifierType::getStorageSize() const { BOOST_THROW_EXCEPTION( InternalCompilerError() << errinfo_comment("Storage size of non-storable type type requested.")); } bool ModifierType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; ModifierType const& other = dynamic_cast<ModifierType const&>(_other); if (m_parameterTypes.size() != other.m_parameterTypes.size()) return false; auto typeCompare = [](TypePointer const& _a, TypePointer const& _b) -> bool { return *_a == *_b; }; if (!equal(m_parameterTypes.cbegin(), m_parameterTypes.cend(), other.m_parameterTypes.cbegin(), typeCompare)) return false; return true; } string ModifierType::toString() const { string name = "modifier ("; for (auto it = m_parameterTypes.begin(); it != m_parameterTypes.end(); ++it) name += (*it)->toString() + (it + 1 == m_parameterTypes.end() ? "" : ","); return name + ")"; } MagicType::MagicType(MagicType::Kind _kind): m_kind(_kind) { switch (m_kind) { case Kind::Block: m_members = MemberList({ {"coinbase", make_shared<IntegerType>(0, IntegerType::Modifier::Address)}, {"timestamp", make_shared<IntegerType>(256)}, {"blockhash", make_shared<FunctionType>(strings{"uint"}, strings{"bytes32"}, FunctionType::Location::BlockHash)}, {"difficulty", make_shared<IntegerType>(256)}, {"number", make_shared<IntegerType>(256)}, {"gaslimit", make_shared<IntegerType>(256)} }); break; case Kind::Message: m_members = MemberList({ {"sender", make_shared<IntegerType>(0, IntegerType::Modifier::Address)}, {"gas", make_shared<IntegerType>(256)}, {"value", make_shared<IntegerType>(256)}, {"data", make_shared<ArrayType>(ReferenceType::Location::CallData)}, {"sig", make_shared<FixedBytesType>(4)} }); break; case Kind::Transaction: m_members = MemberList({ {"origin", make_shared<IntegerType>(0, IntegerType::Modifier::Address)}, {"gasprice", make_shared<IntegerType>(256)} }); break; default: BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of magic.")); } } bool MagicType::operator==(Type const& _other) const { if (_other.getCategory() != getCategory()) return false; MagicType const& other = dynamic_cast<MagicType const&>(_other); return other.m_kind == m_kind; } string MagicType::toString() const { switch (m_kind) { case Kind::Block: return "block"; case Kind::Message: return "msg"; case Kind::Transaction: return "tx"; default: BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown kind of magic.")); } } } }
gpl-3.0
DaniSagan/Game_13w33
src/gui/Gui.cpp
8711
/* * Hyperopolis: Megacities building game. Copyright (C) 2014 Daniel Fernández Villanueva 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/>. * Gui.cpp * * Created on: Aug 20, 2013 * Author: daniel */ #include "Gui.h" namespace dfv { Gui::Gui(): fps(0), quadrant(0), selected_tool(none), test_text(nullptr) { this->minimap.create(128); this->font.loadFromFile("res/font/Ubuntu-L.ttf"); assert(this->assets.load()); /*Button b1("res/gui/button_road.png", sf::Vector2f(0, 0)); b1.SetCommand(std::string("button_road_cmd")); this->button_list.push_back(b1); Button b2("res/gui/button_select.png", sf::Vector2f(0, 32)); b2.SetCommand(std::string("button_select_cmd")); this->button_list.push_back(b2); Button b3("res/gui/button_copy.png", sf::Vector2f(0, 64)); b3.SetCommand(std::string("button_copy_cmd")); this->button_list.push_back(b3);*/ /*TextButton tb1; tb1.setPosition(sf::Vector2f(0.0, 0.0)); tb1.setText(std::string("Clear props")); tb1.setCommand(std::string("clear prop")); this->text_button_list.push_back(tb1); TextButton tb2; tb2.setPosition(sf::Vector2f(0.0, 32.0)); tb2.setText(std::string("Clear roads")); tb2.setCommand(std::string("clear road")); this->text_button_list.push_back(tb2); TextButton tb3; tb3.setPosition(sf::Vector2f(0.0, 64.0)); tb3.setText(std::string("Clear buildings")); tb3.setCommand(std::string("clear building")); this->text_button_list.push_back(tb3); this->test_text.bg_color = sf::Color(32, 32, 32, 192); this->test_text.setPosition(sf::Vector2f(400.f, 400.f)); this->test_text.text = std::string("This is a test text."); this->test_text.txt_size = 20.f; this->test_text.size = {200.f, 50.f}; this->test_text.visible = false;*/ //this->test_text.margin = 5.f; //this->text_button.setPosition(sf::Vector2f(1.f, 1.f)); //this->text_button.setText(std::string("Test")); } Gui::~Gui() { // TODO Auto-generated destructor stub } void Gui::draw(sf::RenderWindow& window, const Camera& camera) const { //this->drawShapes(window); sf::Text text("", this->font); std::stringstream ss; ss << "FPS: " << floor(this->fps + 0.5) << ", Quadrant: " << camera.getQuadrant() << ", RPY: " << camera.getRpy().x << ", " << camera.getRpy().y << ", " << camera.getRpy().z; text.setString(ss.str()); text.setCharacterSize(14.0); text.setPosition(5, 35); window.draw(text); ss.str(std::string("")); ss << "Map pos: " << this->map_pos.x << ", " << this->map_pos.y << "," << this->map_pos.z; text.setString(ss.str()); text.setPosition(5, 50); window.draw(text); if(camera.getMode() == Camera::Driving) { ss.str(std::string("")); ss << floor(camera.getCarTorque()) << " Nm, " << floor(camera.getCarPower()/746.0) << " bhp"; text.setString(ss.str()); text.setPosition(window.getSize().x - 200, window.getSize().y - 195); window.draw(text); ss.str(std::string("")); ss << floor(camera.getCarSpeed()*3.6) << " km/h"; text.setCharacterSize(40); text.setString(ss.str()); text.setPosition(window.getSize().x - 200, window.getSize().y - 175); window.draw(text); ss.str(std::string("")); ss << floor(camera.getMotorRPM()) << " rpm"; text.setString(ss.str()); text.setPosition(window.getSize().x - 200, window.getSize().y - 125); window.draw(text); ss.str(std::string("")); ss << "Gear " << camera.getCarGear() + 1; text.setString(ss.str()); text.setPosition(window.getSize().x - 200, window.getSize().y - 75); window.draw(text); } sf::ConvexShape shape; shape.setPointCount(4); shape.setPoint(0, this->selected_tile_vertices[0]); shape.setPoint(1, this->selected_tile_vertices[1]); shape.setPoint(2, this->selected_tile_vertices[2]); shape.setPoint(3, this->selected_tile_vertices[3]); shape.setFillColor(sf::Color(255, 255, 255, 64)); window.draw(shape); // toolbar this->minimap.draw(window, camera); /*std::list<Button>::const_iterator it; for(it = this->button_list.begin(); it != this->button_list.end(); it++) { it->Draw(window); }*/ //this->text_button.onDraw(window, this->font); std::vector<TextButton>::const_iterator it; for(it = this->text_button_list.begin(); it != this->text_button_list.end(); it++) { it->onDraw(window, this->font); } this->test_text.draw(window, assets); } void Gui::setFps(float fps) { this->fps = fps; } void Gui::setQuadrant(unsigned int quadrant) { this->quadrant = quadrant; } void Gui::setMapPos(const sf::Vector3f& map_pos) { this->map_pos = map_pos; } void Gui::setSelectedTileVertices(const std::vector<sf::Vector2f>& selected_tile_vertices) { this->selected_tile_vertices = selected_tile_vertices; } void Gui::setSelectedShapes(std::vector<sf::ConvexShape>& shapes) { this->selected_shapes.clear(); this->selected_shapes.resize(shapes.size()); this->selected_shapes = shapes; } /*std::vector<std::string> Gui::HandleInput(const sf::Event& event, std::vector<std::string>& commands) { if(event.type == sf::Event::KeyPressed) { if(event.key.code == sf::Keyboard::B) { } } /*std::vector<std::string> button_commands; std::list<Button>::iterator it; for(it = this->button_list.begin(); it != this->button_list.end(); it++) { it->HandleInput(button_commands, event); } if(button_commands.size() == 0) { std::stringstream ss; if(this->selected_tool == road) { // if left click if(event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left) { // command : build_road <x> <y> ss << "build_road " << floor(this->map_pos.x) << " " << floor(this->map_pos.y); std::cout << "Command: " << ss.str() << std::endl; commands.push_back(ss.str()); } // if right click if(event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Right) { // command : rotate_road <x> <y> ss << "rotate_road " << floor(this->map_pos.x) << " " << floor(this->map_pos.y); std::cout << "Command: " << ss.str() << std::endl; commands.push_back(ss.str()); } } else if(this->selected_tool == select) { } else if(this->selected_tool == copy) { // if left click if(event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left) { // command : copy_road <x> <y> ss << "copy_road " << floor(this->map_pos.x) << " " << floor(this->map_pos.y); std::cout << "Command: " << ss.str() << std::endl; commands.push_back(ss.str()); } } } else { for(unsigned int i = 0; i < button_commands.size(); i++) { if(button_commands[i] == "button_road_cmd") { this->selected_tool = road; std::cout << "Selected road tool" << std::endl; } else if(button_commands[i] == "button_select_cmd") { this->selected_tool = select; std::cout << "Selected select tool" << std::endl; } else if(button_commands[i] == "button_copy_cmd") { this->selected_tool = copy; std::cout << "Selected copy tool" << std::endl; } } } std::vector<TextButton>::iterator it; for(it = this->text_button_list.begin(); it != this->text_button_list.end(); it++) { it->handleInput(event, command); } return commands; }*/ void Gui::handleInput(const sf::Event& event, std::string& command) { std::vector<TextButton>::iterator it; for(it = this->text_button_list.begin(); it != this->text_button_list.end(); it++) { it->handleInput(event, command); } } std::vector<std::string>& Gui::handleButtonInput(const sf::Event& event, std::vector<std::string>& commands) { std::list<Button>::iterator it; for(it = this->button_list.begin(); it != this->button_list.end(); it++) { it->handleInput(commands, event); } return commands; } void Gui::update(const Map& map, const sf::Vector2f& position) { int range = static_cast<int>(2.f*cameraInstance.getPosition().z) + 8; this->minimap.generateFromMap(map, position, range); } void Gui::drawShapes(sf::RenderWindow& window) const { std::vector<sf::ConvexShape>::const_iterator it; for(it = this->selected_shapes.begin(); it != this->selected_shapes.end(); it++) { window.draw(*it); } } } /* namespace dfv */
gpl-3.0
MikeMatt16/Abide
Abide Tag Definitions/Generated/Library/MultiplayerInformationBlock.Generated.cs
3285
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Abide.HaloLibrary.Halo2.Retail.Tag.Generated { using System; using Abide.HaloLibrary; using Abide.HaloLibrary.Halo2.Retail.Tag; /// <summary> /// Represents the generated multiplayer_information_block tag block. /// </summary> public sealed class MultiplayerInformationBlock : Block { /// <summary> /// Initializes a new instance of the <see cref="MultiplayerInformationBlock"/> class. /// </summary> public MultiplayerInformationBlock() { this.Fields.Add(new TagReferenceField("flag", 1769235821)); this.Fields.Add(new TagReferenceField("unit", 1970170228)); this.Fields.Add(new BlockField<VehiclesBlock>("vehicles", 20)); this.Fields.Add(new TagReferenceField("hill shader", 1936220516)); this.Fields.Add(new TagReferenceField("flag shader", 1936220516)); this.Fields.Add(new TagReferenceField("ball", 1769235821)); this.Fields.Add(new BlockField<SoundsBlock>("sounds", 60)); this.Fields.Add(new TagReferenceField("in game text", 1970170211)); this.Fields.Add(new PadField("", 40)); this.Fields.Add(new BlockField<GameEngineGeneralEventBlock>("general events", 128)); this.Fields.Add(new BlockField<GameEngineSlayerEventBlock>("slayer events", 128)); this.Fields.Add(new BlockField<GameEngineCtfEventBlock>("ctf events", 128)); this.Fields.Add(new BlockField<GameEngineOddballEventBlock>("oddball events", 128)); this.Fields.Add(new BlockField<GNullBlock>("", 0)); this.Fields.Add(new BlockField<GameEngineKingEventBlock>("king events", 128)); } /// <summary> /// Gets and returns the name of the multiplayer_information_block tag block. /// </summary> public override string BlockName { get { return "multiplayer_information_block"; } } /// <summary> /// Gets and returns the display name of the multiplayer_information_block tag block. /// </summary> public override string DisplayName { get { return "multiplayer_information_block"; } } /// <summary> /// Gets and returns the maximum number of elements allowed of the multiplayer_information_block tag block. /// </summary> public override int MaximumElementCount { get { return 1; } } /// <summary> /// Gets and returns the alignment of the multiplayer_information_block tag block. /// </summary> public override int Alignment { get { return 4; } } } }
gpl-3.0
labscoop/xortify
server/4.11 RC/htdocs/modules/xortify/class/emails_links.php
2778
<?php /* * Prevents Spam, Harvesting, Human Rights Abuse, Captcha Abuse etc. * basic statistic of them in XOOPS Copyright (C) 2012 Simon Roberts * Contact: wishcraft - simon@labs.coop * * 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/>. * See /docs/license.pdf for full license. * * Shouts:- Mamba (www.xoops.org), flipse (www.nlxoops.nl) * Many thanks for your additional work with version 1.01 * * Version: 3.10 Final (Stable) * Published: Chronolabs * Download: http://code.google.com/p/chronolabs * This File: emails_links.php * Description: Emails Linking Registrar in Xortify Cloud * Date: 30/03/2012 19:34 AEST * License: GNU3 * * Table: * * CREATE TABLE `xortify_emails_links` ( * `elid` mediumint(64) unsigned NOT NULL AUTO_INCREMENT, * `eid` mediumint(32) unsigned NOT NULL DEFAULT '0', * `uid` int(13) NOT NULL DEFAULT '0', * `ip` varchar(128) NOT NULL DEFAULT '127.0.0.1', * ) ENGINE=INNODB DEFAULT CHARSET=utf8; * */ if (!defined('XOOPS_ROOT_PATH')) { exit(); } /** * Class for Blue Room Xortify Emails Linking * @author Simon Roberts <simon@xoops.org> * @copyright copyright (c) 2009-2003 XOOPS.org * @package xortify */ class XortifyEmails_links extends XoopsObject { function XortifyEmails_links($id = null) { $this->initVar('elid', XOBJ_DTYPE_INT, null, false); $this->initVar('eid', XOBJ_DTYPE_INT, 0, false); $this->initVar('uid', XOBJ_DTYPE_INT, 0, false); $this->initVar('ip', XOBJ_DTYPE_TXTBOX, '127.0.0.1', false, 128); } function toArray() { $ret = parent::toArray(); foreach($ret as $key => $value) $ret[str_replace('-', '_', $key)] = $value; return $ret; } } /** * XOOPS Xortify Emails Linking handler class. * This class is responsible for providing data access mechanisms to the data source * of XOOPS user class objects. * * @author Simon Roberts <simon@labs.coop> * @package xortify */ class XortifyEmails_linksHandler extends XoopsPersistableObjectHandler { function __construct(&$db) { $this->db = $db; parent::__construct($db, 'xortify_emails_links', 'XortifyEmails_links', "elid", "eid"); } } ?>
gpl-3.0
SrNativee/BotDeUmBot
node_modules/csvtojson/libs/core/Result.js
1107
var Writable = require("stream").Writable; var util = require("util"); function Result(csvParser) { Writable.call(this); this.parser = csvParser; this.param = csvParser.param; this.buffer = this.param.toArrayString?"":"["+csvParser.getEol(); this.started = false; var self = this; this.parser.on("end", function() { if (!self.param.toArrayString){ self.buffer += self.parser.getEol() + "]"; } }); } util.inherits(Result, Writable); Result.prototype._write = function(data, encoding, cb) { if (encoding === "buffer") { encoding = "utf8"; } if (this.param.toArrayString){ this.buffer+=data.toString(encoding); }else{ if (this.started) { this.buffer += "," + this.parser.getEol(); } else { this.started = true; } this.buffer += data.toString(encoding); } cb(); }; Result.prototype.getBuffer = function() { // console.log(this.buffer); return JSON.parse(this.buffer); }; Result.prototype.disableConstruct = function() { this._write = function(d, e, cb) { cb(); //do nothing just dropit }; }; module.exports = Result;
gpl-3.0
qt-haiku/LibreOffice
odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/ViewContainer.java
8531
/************************************************************************* * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright 2000, 2010 Oracle and/or its affiliates. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ // __________ Imports __________ import java.util.*; // __________ Implementation __________ /** * It's implement a static container which hold * all opened documents and her views alive. * It's possible to register/deregister such views, * to get information about these and it provides * some global functionality - like termination of * this demo application. * */ public class ViewContainer extends Thread { /** * provides a singleton view container * Necessary for terminate(9 functionality to be able * to call Runtime.runFinilization(). * * @return a reference to the singleton ViewContainer instance */ public static synchronized ViewContainer getGlobalContainer() { if (maSingleton==null) maSingleton=new ViewContainer(); return maSingleton; } /** * ctor * It's private - because nobody should create any instance * expect the only global one, which wil be created by ourself! */ private ViewContainer() { mlViews = new ArrayList<Object>(); mlListener = new ArrayList<IShutdownListener>(); mbShutdownActive = false ; Runtime.getRuntime().addShutdownHook(this); } /** * This register a new view inside this global container * (if it doesn't already exist). * * @param aView view which wish to be registered inside this container */ public void addView(Object aView) { synchronized(mlViews) { if(mlViews.contains(aView)==false) mlViews.add(aView); } } /** * This deregister a view from this global container. * Normaly it should be the last reference to the view * and her finalize() method should be called. * If last view will be closed here - we terminate these * java application too. Because there is no further * visible frame anymore. * * @param aView * view object which wish to be deregistered */ public void removeView(Object aView) { int nViewCount = 0; synchronized(mlViews) { if(mlViews.contains(aView)==true) mlViews.remove(aView); nViewCount = mlViews.size(); if (nViewCount<1) mlViews = null; } // If this view is a registered shutdown listener on this view container // too, we must call his interface and forget him as possible listener. // It's necessary to guarantee his dead ... boolean bShutdownView = false; synchronized(mlListener) { bShutdownView = mlListener.contains(aView); if (bShutdownView==true) mlListener.remove(aView); } if (bShutdownView==true) ((IShutdownListener)aView).shutdown(); // We use a system.exit() to finish the whole application. // And further we have registered THIS instance as a possible shutdown // hook at the runtime class. So our run() method will be called. // Our view container should be empty - but // our listener container can include some references. // These objects will be informed then and release e.g. some // remote references. if (nViewCount<1) { boolean bNecessary = false; synchronized(this) { bNecessary = ! mbShutdownActive; } if (bNecessary==true) { System.out.println("call exit(0)!"); System.exit(0); } } } /** * add/remove listener for possibe shutdown events */ public void addListener( IShutdownListener rListener ) { synchronized(mlListener) { if ( ! mlListener.contains(rListener) ) mlListener.add(rListener); } } public void removeListener( IShutdownListener rListener ) { synchronized(mlListener) { if ( mlListener.contains(rListener) ) mlListener.remove(rListener); } } /** * Is called from current runtime system of the java machine * on shutdown. We inform all current registered listener and * views. They should deinitialize her internal things then. */ public void run() { synchronized(this) { if (mbShutdownActive) return; mbShutdownActive=true; } while( true ) { IShutdownListener aListener = null; synchronized(mlListener) { if (!mlListener.isEmpty()) aListener = mlListener.get(0); } if (aListener==null) break; aListener.shutdown(); // May this listener has dergeistered himself. // But if not we must do it for him. Our own // method "removeListener()" ignore requests for // already gone listener objects. removeListener(aListener); } if (mlViews!=null) { synchronized(mlViews) { mlViews.clear(); mlViews = null; } } if (mlListener!=null) { synchronized(mlListener) { mlListener.clear(); mlListener = null; } } } /** * @const BASICNAME it's used to create uinque names for all regieterd views */ private static final String BASICNAME = "Document View "; /** * @member mbInplace indicates using of inplace office frames instead of outplace ones * @member maSingleton singleton instance of this view container * @member mlViews list of all currently registered document views * @member mlListener list of all currently registered shutdown listener * @member mbShutdownActive if this shutdown hook already was started it's not a good idea to * call System.exit() again for other conditions. * We suppress it by using this variable! */ public static boolean mbInplace = false ; private static ViewContainer maSingleton = null ; private ArrayList<Object> mlViews ; private ArrayList<IShutdownListener> mlListener ; private boolean mbShutdownActive ; }
gpl-3.0
sailfish-sdk/sailfish-qtcreator
src/libs/utils/environmentmodel.cpp
13171
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "environmentmodel.h" #include <utils/algorithm.h> #include <utils/environment.h> #include <utils/hostosinfo.h> #include <QString> #include <QFont> namespace Utils { namespace Internal { class EnvironmentModelPrivate { public: void updateResultEnvironment() { m_resultEnvironment = m_baseEnvironment; m_resultEnvironment.modify(m_items); // Add removed variables again and mark them as "<UNSET>" so // that the user can actually see those removals: foreach (const EnvironmentItem &item, m_items) { if (item.operation == EnvironmentItem::Unset) m_resultEnvironment.set(item.name, EnvironmentModel::tr("<UNSET>")); } } int findInChanges(const QString &name) const { for (int i=0; i<m_items.size(); ++i) if (m_items.at(i).name == name) return i; return -1; } int findInResultInsertPosition(const QString &name) const { Environment::const_iterator it; int i = 0; for (it = m_resultEnvironment.constBegin(); it != m_resultEnvironment.constEnd(); ++it, ++i) if (m_resultEnvironment.key(it) > name) return i; return m_resultEnvironment.size(); } int findInResult(const QString &name) const { Environment::const_iterator it; int i = 0; for (it = m_resultEnvironment.constBegin(); it != m_resultEnvironment.constEnd(); ++it, ++i) if (m_resultEnvironment.key(it) == name) return i; return -1; } Environment m_baseEnvironment; Environment m_resultEnvironment; QList<EnvironmentItem> m_items; }; } // namespace Internal EnvironmentModel::EnvironmentModel(QObject *parent) : QAbstractTableModel(parent), d(new Internal::EnvironmentModelPrivate) { } EnvironmentModel::~EnvironmentModel() { delete d; } QString EnvironmentModel::indexToVariable(const QModelIndex &index) const { return d->m_resultEnvironment.key(d->m_resultEnvironment.constBegin() + index.row()); } void EnvironmentModel::setBaseEnvironment(const Environment &env) { if (d->m_baseEnvironment == env) return; beginResetModel(); d->m_baseEnvironment = env; d->updateResultEnvironment(); endResetModel(); } int EnvironmentModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return d->m_resultEnvironment.size(); } int EnvironmentModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return 2; } bool EnvironmentModel::changes(const QString &name) const { return d->findInChanges(name) >= 0; } Environment EnvironmentModel::baseEnvironment() const { return d->m_baseEnvironment; } QVariant EnvironmentModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::ToolTipRole) { if (index.column() == 0) { return d->m_resultEnvironment.key(d->m_resultEnvironment.constBegin() + index.row()); } else if (index.column() == 1) { // Do not return "<UNSET>" when editing a previously unset variable: if (role == Qt::EditRole) { int pos = d->findInChanges(indexToVariable(index)); if (pos >= 0) return d->m_items.at(pos).value; } QString value = d->m_resultEnvironment.value(d->m_resultEnvironment.constBegin() + index.row()); if (role == Qt::ToolTipRole && value.length() > 80) { // Use html to enable text wrapping value = value.toHtmlEscaped(); value.prepend(QLatin1String("<html><body>")); value.append(QLatin1String("</body></html>")); } return value; } } if (role == Qt::FontRole) { // check whether this environment variable exists in d->m_items if (changes(d->m_resultEnvironment.key(d->m_resultEnvironment.constBegin() + index.row()))) { QFont f; f.setBold(true); return QVariant(f); } return QFont(); } return QVariant(); } Qt::ItemFlags EnvironmentModel::flags(const QModelIndex &index) const { Q_UNUSED(index) return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled; } QVariant EnvironmentModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Vertical || role != Qt::DisplayRole) return QVariant(); return section == 0 ? tr("Variable") : tr("Value"); } /// ***************** /// Utility functions /// ***************** QModelIndex EnvironmentModel::variableToIndex(const QString &name) const { int row = d->findInResult(name); if (row == -1) return QModelIndex(); return index(row, 0); } bool EnvironmentModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid() || role != Qt::EditRole) return false; // ignore changes to already set values: if (data(index, role) == value) return true; const QString oldName = data(this->index(index.row(), 0, QModelIndex())).toString(); const QString oldValue = data(this->index(index.row(), 1, QModelIndex()), Qt::EditRole).toString(); int changesPos = d->findInChanges(oldName); if (index.column() == 0) { //fail if a variable with the same name already exists const QString &newName = HostOsInfo::isWindowsHost() ? value.toString().toUpper() : value.toString(); if (newName.isEmpty() || newName.contains('=')) return false; // Does the new name exist already? if (d->m_resultEnvironment.hasKey(newName) || newName.isEmpty()) return false; EnvironmentItem newVariable(newName, oldValue); if (changesPos != -1) resetVariable(oldName); // restore the original base variable again QModelIndex newIndex = addVariable(newVariable); // add the new variable emit focusIndex(newIndex.sibling(newIndex.row(), 1)); // hint to focus on the value return true; } else if (index.column() == 1) { // We are changing an existing value: const QString stringValue = value.toString(); if (changesPos != -1) { // We have already changed this value if (d->m_baseEnvironment.hasKey(oldName) && stringValue == d->m_baseEnvironment.value(oldName)) { // ... and now went back to the base value d->m_items.removeAt(changesPos); } else { // ... and changed it again d->m_items[changesPos].value = stringValue; d->m_items[changesPos].operation = EnvironmentItem::Set; } } else { // Add a new change item: d->m_items.append(EnvironmentItem(oldName, stringValue)); } d->updateResultEnvironment(); emit dataChanged(index, index); emit userChangesChanged(); return true; } return false; } QModelIndex EnvironmentModel::addVariable() { //: Name when inserting a new variable return addVariable(EnvironmentItem(tr("<VARIABLE>"), //: Value when inserting a new variable tr("<VALUE>"))); } QModelIndex EnvironmentModel::addVariable(const EnvironmentItem &item) { // Return existing index if the name is already in the result set: int pos = d->findInResult(item.name); if (pos >= 0 && pos < d->m_resultEnvironment.size()) return index(pos, 0, QModelIndex()); int insertPos = d->findInResultInsertPosition(item.name); int changePos = d->findInChanges(item.name); if (d->m_baseEnvironment.hasKey(item.name)) { // We previously unset this! Q_ASSERT(changePos >= 0); // Do not insert a line here as we listed the variable as <UNSET> before! Q_ASSERT(d->m_items.at(changePos).name == item.name); Q_ASSERT(d->m_items.at(changePos).operation == EnvironmentItem::Unset); Q_ASSERT(d->m_items.at(changePos).value.isEmpty()); d->m_items[changePos] = item; emit dataChanged(index(insertPos, 0, QModelIndex()), index(insertPos, 1, QModelIndex())); } else { // We add something that is not in the base environment // Insert a new line! beginInsertRows(QModelIndex(), insertPos, insertPos); Q_ASSERT(changePos < 0); d->m_items.append(item); d->updateResultEnvironment(); endInsertRows(); } emit userChangesChanged(); return index(insertPos, 0, QModelIndex()); } void EnvironmentModel::resetVariable(const QString &name) { int rowInChanges = d->findInChanges(name); if (rowInChanges < 0) return; int rowInResult = d->findInResult(name); if (rowInResult < 0) return; if (d->m_baseEnvironment.hasKey(name)) { d->m_items.removeAt(rowInChanges); d->updateResultEnvironment(); emit dataChanged(index(rowInResult, 0, QModelIndex()), index(rowInResult, 1, QModelIndex())); emit userChangesChanged(); } else { // Remove the line completely! beginRemoveRows(QModelIndex(), rowInResult, rowInResult); d->m_items.removeAt(rowInChanges); d->updateResultEnvironment(); endRemoveRows(); emit userChangesChanged(); } } void EnvironmentModel::unsetVariable(const QString &name) { // This does not change the number of rows as we will display a <UNSET> // in place of the original variable! int row = d->findInResult(name); if (row < 0) return; // look in d->m_items for the variable int pos = d->findInChanges(name); if (pos != -1) { d->m_items[pos].operation = EnvironmentItem::Unset; d->m_items[pos].value.clear(); d->updateResultEnvironment(); emit dataChanged(index(row, 0, QModelIndex()), index(row, 1, QModelIndex())); emit userChangesChanged(); return; } d->m_items.append(EnvironmentItem(name, QString(), EnvironmentItem::Unset)); d->updateResultEnvironment(); emit dataChanged(index(row, 0, QModelIndex()), index(row, 1, QModelIndex())); emit userChangesChanged(); } bool EnvironmentModel::canUnset(const QString &name) { int pos = d->findInChanges(name); if (pos != -1) return d->m_items.at(pos).operation == EnvironmentItem::Unset; else return false; } bool EnvironmentModel::canReset(const QString &name) { return d->m_baseEnvironment.hasKey(name); } QList<EnvironmentItem> EnvironmentModel::userChanges() const { return d->m_items; } void EnvironmentModel::setUserChanges(const QList<EnvironmentItem> &list) { QList<EnvironmentItem> filtered = Utils::filtered(list, [](const EnvironmentItem &i) { return i.name != "export " && !i.name.contains('='); }); // We assume nobody is reordering the items here. if (filtered == d->m_items) return; beginResetModel(); d->m_items = filtered; for (EnvironmentItem &item : d->m_items) { QString &name = item.name; name = name.trimmed(); if (name.startsWith("export ")) name = name.mid(7).trimmed(); if (d->m_baseEnvironment.osType() == OsTypeWindows) { // Environment variable names are case-insensitive under windows, but we still // want to preserve the case of pre-existing variables. auto it = d->m_baseEnvironment.constFind(name); if (it != d->m_baseEnvironment.constEnd()) name = d->m_baseEnvironment.key(it); } } d->updateResultEnvironment(); endResetModel(); emit userChangesChanged(); } } // namespace Utils
gpl-3.0
DarthFeder/Reliquary
reliquary_common/xreliquary/Config.java
6452
package xreliquary; import java.io.File; import java.util.logging.Level; import net.minecraftforge.common.Configuration; import xreliquary.lib.Indexes; import xreliquary.lib.Reference; import cpw.mods.fml.common.FMLLog; public class Config { // items public static int handgunID; public static int shellID; public static int slugID; public static int chaliceID; public static int glowBreadID; public static int glowWaterID; public static int condensedPotionID; public static int enderStaffID; public static int gunPartID; public static int sojournerStaffID; public static int mercyCrossID; public static int fortuneCoinID; public static int midasTouchstoneID; public static int iceRodID; public static int magicbaneID; public static int witherlessRoseID; public static int holyHandGrenadeID; public static int letheTearID; public static int destructionCatalystID; public static int alkahestID; public static int alkahestryTomeID; public static int salamanderEyeID; public static int wraithEyeID; public static int satchelID; public static int emptyVoidTearID; public static int voidTearID; public static int altarActiveID; public static int altarIdleID; public static int wraithNodeID; public static int lilypadID; public static int alchemicalGunmetalID; public static int apothecaryMortarID; public static int gunsmithCrucibleID; public static int alembicID; public static int potionEssenceID; public static int stackedEssenceID; // options public static boolean disableCoinAudio; public static boolean disableGunItems; public static boolean disablePotionItems; public static void init(File configFile) { Configuration config = new Configuration(configFile); try { config.load(); // block and item ID configurations. handgunID = config.getItem("Handgun", Indexes.HANDGUN_DEFAULT_ID).getInt(Indexes.HANDGUN_DEFAULT_ID); slugID = config.getItem("Slug", Indexes.SLUG_DEFAULT_ID).getInt(Indexes.SLUG_DEFAULT_ID); shellID = config.getItem("Shell", Indexes.SHELL_DEFAULT_ID).getInt(Indexes.SHELL_DEFAULT_ID); chaliceID = config.getItem("Chalice", Indexes.CHALICE_DEFAULT_ID).getInt(Indexes.CHALICE_DEFAULT_ID); glowBreadID = config.getItem("Bread", Indexes.BREAD_DEFAULT_ID).getInt(Indexes.BREAD_DEFAULT_ID); glowWaterID = config.getItem("Water", Indexes.WATER_DEFAULT_ID).getInt(Indexes.WATER_DEFAULT_ID); condensedPotionID = config.getItem("CondensedPotion", Indexes.CONDENSED_POTION_DEFAULT_ID).getInt(Indexes.CONDENSED_POTION_DEFAULT_ID); enderStaffID = config.getItem("EnderStaff", Indexes.ENDER_STAFF_DEFAULT_ID).getInt(Indexes.ENDER_STAFF_DEFAULT_ID); gunPartID = config.getItem("GunPart", Indexes.GUNPART_DEFAULT_ID).getInt(Indexes.GUNPART_DEFAULT_ID); sojournerStaffID = config.getItem("Torch", Indexes.TORCH_DEFAULT_ID).getInt(Indexes.TORCH_DEFAULT_ID); mercyCrossID = config.getItem("Cross", Indexes.CROSS_DEFAULT_ID).getInt(Indexes.CROSS_DEFAULT_ID); fortuneCoinID = config.getItem("Coin", Indexes.COIN_DEFAULT_ID).getInt(Indexes.COIN_DEFAULT_ID); midasTouchstoneID = config.getItem("Touchstone", Indexes.TOUCHSTONE_DEFAULT_ID).getInt(Indexes.TOUCHSTONE_DEFAULT_ID); iceRodID = config.getItem("IceRod", Indexes.ICE_ROD_DEFAULT_ID).getInt(Indexes.ICE_ROD_DEFAULT_ID); magicbaneID = config.getItem("Magicbane", Indexes.MAGICBANE_DEFAULT_ID).getInt(Indexes.MAGICBANE_DEFAULT_ID); witherlessRoseID = config.getItem("Rose", Indexes.WITHERLESS_ROSE_DEFAULT_ID).getInt(Indexes.WITHERLESS_ROSE_DEFAULT_ID); holyHandGrenadeID = config.getItem("Grenade", Indexes.GRENADE_DEFAULT_ID).getInt(Indexes.GRENADE_DEFAULT_ID); letheTearID = config.getItem("Tear", Indexes.EMPTY_VOID_TEAR_DEFAULT_ID).getInt(Indexes.EMPTY_VOID_TEAR_DEFAULT_ID); destructionCatalystID = config.getItem("Catalyst", Indexes.DESTRUCTION_CATALYST_DEFAULT_ID).getInt(Indexes.DESTRUCTION_CATALYST_DEFAULT_ID); alkahestID = config.getItem("Alkahest", Indexes.ALKAHEST_DEFAULT_ID).getInt(Indexes.ALKAHEST_DEFAULT_ID); alkahestryTomeID = config.getItem("Tome", Indexes.TOME_DEFAULT_ID).getInt(Indexes.TOME_DEFAULT_ID); salamanderEyeID = config.getItem("SalamanderEye", Indexes.SALAMANDER_EYE_DEFAULT_ID).getInt(Indexes.SALAMANDER_EYE_DEFAULT_ID); wraithEyeID = config.getItem("WraithEye", Indexes.WRAITH_EYE_DEFAULT_ID).getInt(Indexes.WRAITH_EYE_DEFAULT_ID); voidTearID = config.getItem("VoidTear", Indexes.VOID_TEAR_DEFAULT_ID).getInt(Indexes.VOID_TEAR_DEFAULT_ID); emptyVoidTearID = config.getItem("EmptyVoidTear", Indexes.EMPTY_VOID_TEAR_DEFAULT_ID).getInt(Indexes.EMPTY_VOID_TEAR_DEFAULT_ID); satchelID = config.getItem("Satchel", Indexes.SATCHEL_DEFAULT_ID).getInt(Indexes.SATCHEL_DEFAULT_ID); alembicID = config.getItem("Alembic", Indexes.ALEMBIC_DEFAULT_ID).getInt(Indexes.ALEMBIC_DEFAULT_ID); apothecaryMortarID = config.getItem("Mortar", Indexes.APOTHECARY_MORTAR_DEFAULT_ID).getInt(Indexes.APOTHECARY_MORTAR_DEFAULT_ID); gunsmithCrucibleID = config.getItem("Crucible", Indexes.GUNSMITH_CRUCIBLE_DEFAULT_ID).getInt(Indexes.GUNSMITH_CRUCIBLE_DEFAULT_ID); potionEssenceID = config.getItem("Essence", Indexes.POTION_ESSENCE_DEFAULT_ID).getInt(Indexes.POTION_ESSENCE_DEFAULT_ID); stackedEssenceID = config.getItem("StackedEssence", Indexes.STACKED_ESSENCE_DEFAULT_ID).getInt(Indexes.STACKED_ESSENCE_DEFAULT_ID); // blocks altarActiveID = config.getBlock("AltarActive", Indexes.ALTAR_ACTIVE_DEFAULT_ID).getInt(Indexes.ALTAR_ACTIVE_DEFAULT_ID); altarIdleID = config.getBlock("AltarIdle", Indexes.ALTAR_IDLE_DEFAULT_ID).getInt(Indexes.ALTAR_IDLE_DEFAULT_ID); wraithNodeID = config.getBlock("WraithNode", Indexes.WRAITH_NODE_DEFAULT_ID).getInt(Indexes.WRAITH_NODE_DEFAULT_ID); lilypadID = config.getBlock("Lilypad", Indexes.LILYPAD_DEFAULT_ID).getInt(Indexes.LILYPAD_DEFAULT_ID); // miscellaneous options disableCoinAudio = config.get("Misc_Options", "disableCoinAudio", false).getBoolean(Reference.DISABLE_COIN_AUDIO_DEFAULT); // item disabling features disableGunItems = config.get("Item_Disabling", "disableGunItems", false).getBoolean(Reference.DISABLE_GUN_ITEMS_DEFAULT); disablePotionItems = config.get("Item_Disabling", "disablePotionItems", false).getBoolean(Reference.DISABLE_POTION_ITEMS_DEFAULT); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, Reference.MOD_NAME + " had a problem while loading its configuration."); } finally { config.save(); } } // other configs (ID and Flags) }
gpl-3.0
reatlat/wp-campaign-url-builder
source/admin/views/partial/reatlat_cub-admin-settings.php
3836
<div class="reatlat_cub_container reatlat_cub_tab reatlat_cub_tab-2"> <form method="POST" class="reatlat_cub_form"> <h2 class="title"><?php _e('Add', 'campaign-url-builder'); ?></h2> <table class="form-table"> <tr> <th scope="row"><label for="new_campaign_source"><?php _e('Add new Campaign Source', 'campaign-url-builder'); ?></label></th> <td><input name="new_campaign_source" placeholder="<?php _e('The referrer: (e.g. google, newsletter)', 'campaign-url-builder'); ?>" type="text" id="new_campaign_source" value="" class="regular-text"> <p class="description"><?php _e('The Campaign Source will be formatted once submitted.', 'campaign-url-builder'); ?></p> </td> </tr> <tr> <th scope="row"><label for="new_campaign_medium"><?php _e('Add new Campaign Medium', 'campaign-url-builder'); ?></label></th> <td><input name="new_campaign_medium" placeholder="<?php _e('Marketing medium: (e.g. cpc, banner, email)', 'campaign-url-builder'); ?>" type="text" id="new_campaign_medium" value="" class="regular-text"> <p class="description"><?php _e('The Campaign Medium will be formatted once submitted.', 'campaign-url-builder'); ?></p> </td> </tr> </table> <h2 class="title"><?php _e('Remove', 'campaign-url-builder'); ?></h2> <?php if ( current_user_can('administrator') || ! get_option( $this->plugin_name . '_admin_only' ) ) : ?> <table class="form-table"> <tr> <th scope="row"><label for="remove_campaign_source"><?php _e('Remove Campaign Source', 'campaign-url-builder'); ?></label></th> <td> <select name="remove_campaign_source"> <option value=""><?php _e('Select', 'campaign-url-builder'); ?></option> <?php $sources = $plugin->get_sources(); foreach ($sources as $source) { ?> <option value="<?php echo esc_attr( $source->source_name ); ?>"><?php echo esc_attr( $source->source_name ); ?></option> <?php } ?> </select> </td> </tr> <tr> <th scope="row"> <label for="remove_campaign_medium"><?php _e('Remove Campaign Medium', 'campaign-url-builder'); ?></label> </th> <td> <select name="remove_campaign_medium"> <option value=""><?php _e('Select', 'campaign-url-builder'); ?></option> <?php $mediums = $plugin->get_mediums(); foreach ($mediums as $medium) { ?> <option value="<?php echo esc_attr( $medium->medium_name ); ?>"><?php echo esc_attr( $medium->medium_name ); ?></option> <?php } ?> </select> </td> </tr> </table> <?php else : ?> <h3 class="alert"><span class="dashicons dashicons-lock alert"></span><?php _e('Remove option available only for Administrator', 'campaign-url-builder'); ?></h3> <?php endif; ?> <?php wp_nonce_field('submit_settings', 'Campaign-URL-Builder__submit_settings--nonce'); ?> <p class="submit"> <input type="submit" name="submit_settings" id="submit" class="button button-primary" value="<?php _e('Save Changes', 'campaign-url-builder'); ?>"> </p> </form> </div>
gpl-3.0
GeraldWodni/theforth.net
data.js
1195
module.exports = { setup: function _setup( k ) { var db = k.getDb(); var users = k.crud.sql( db, { table: "users", key: "id", foreignName: "name", wheres: { "name": { where: "`name`=?" } } } ); var legacyUsers = k.crud.sql( db, { table: "openidUsers", key: "uin", foreignName: "name", wheres: { "link": { where: "`link`=?" } } } ); var tags = k.crud.sql( db, { table: "tagNames", key: "id", foreignName: "name", wheres: { "name": { where: "`name`=?" } } } ); var packages = k.crud.sql( db, { table: "packages", key: "id", foreignName: "name", wheres: { "name": { where: "`name`=?" }, "search": { where: "`name` LIKE CONCAT('%',?,'%') OR `description` LIKE CONCAT('%',?,'%')" }, "user": { where: "`user`=?" } } } ); return { legacyUsers: legacyUsers, packages: packages, tags: tags, users: users }; } }
gpl-3.0
0359xiaodong/JAdventure
src/main/java/com/jadventure/game/navigation/Location.java
4399
package com.jadventure.game.navigation; import com.jadventure.game.items.Item; import com.jadventure.game.entities.NPC; import com.jadventure.game.monsters.Monster; import com.jadventure.game.QueueProvider; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.Arrays; /** * The location class mostly deals with getting and setting variables. * It also contains the method to print a location's details. */ public class Location implements ILocation { private Coordinate coordinate; private String title; private String description; private LocationType locationType; private ArrayList<String> items; private ArrayList<String> npcs; private ArrayList<Monster> monsters = new ArrayList<Monster>(); public Location() { } public Coordinate getCoordinate() { return coordinate; } public void setCoordinate(Coordinate coordinate) { this.coordinate = coordinate; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public LocationType getLocationType() { return locationType; } public void setLocationType(LocationType locationType) { this.locationType = locationType; } // It checks each direction for an exit and adds it to the exits hashmap if it exists. public Map<Direction, ILocation> getExits() { Map<Direction, ILocation> exits = new HashMap<Direction, ILocation>(); ILocation borderingLocation; for(Direction direction: Direction.values()) { borderingLocation = LocationManager.getLocation(getCoordinate().getBorderingCoordinate(direction)); if (borderingLocation != null) { exits.put(direction, borderingLocation); } } return exits; } public void setItems(ArrayList items) { this.items = items; } public ArrayList<Item> getItems() { ArrayList<Item> items = new ArrayList<Item>(); for (String itemId : this.items) { Item itemName = new Item(itemId); items.add(itemName); } return items; } public void setNPCs(ArrayList npcs) { this.npcs = npcs; } public ArrayList<NPC> getNPCs() { ArrayList<NPC> npcs = new ArrayList<NPC>(); for (String npcID : this.npcs) { NPC npc = new NPC(npcID); npcs.add(npc); } return npcs; } public void setMonsters(Monster monster) { ArrayList<Monster> list = this.monsters; list.add(monster); this.monsters = list; } public ArrayList<Monster> getMonsters() { return this.monsters; } public void removePublicItem(String itemID) { ArrayList<String> items = this.items; items.remove(itemID); setItems(items); } public void addPublicItem(String itemID) { ArrayList<String> items = this.items; items.add(itemID); setItems(items); } public void print() { QueueProvider.offer(getTitle() + ":"); QueueProvider.offer(getDescription()); ArrayList<Item> publicItems = getItems(); if (!publicItems.isEmpty()) { QueueProvider.offer("Items:"); for (Item item : publicItems) { QueueProvider.offer(" "+item.getName()); } } ArrayList<NPC> npcs = getNPCs(); if (!npcs.isEmpty()) { QueueProvider.offer("NPCs:"); for (NPC npc : npcs) { QueueProvider.offer(" "+npc.getName()); } } QueueProvider.offer(""); for (Map.Entry<Direction,ILocation> direction : getExits().entrySet()) { System.out.print(direction.getKey().getDescription() + ", "); QueueProvider.offer(direction.getValue().getDescription()); } QueueProvider.offer(""); } }
gpl-3.0
lostjared/PSP.Homebrew
apps/SDL3D/mx3d.cpp
17150
#include "mx3d.h" float z_pos = 0.0f; LPDIRECTSOUND8 m_pDS = 0; LPDIRECTSOUND3DLISTENER g_pDSListener = 0; int mxApp::InitLoop() { MSG msg; go = true; while(go == true) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if(msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } else if(active) { screen.pd3d_dev->Clear(NULL,NULL,D3DCLEAR_ZBUFFER | D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0),1.0f,NULL); this->render(cur_screen); screen.pd3d_dev->Present(NULL,NULL,NULL,NULL); } else if(!active) { WaitMessage(); } } return (int) msg.wParam; } mxHwnd::mxHwnd(const char *title, int x, int y, int w ,int h, bool fullscreen, WNDPROC wndProc, HICON hIcon ) { if(Init(title,fullscreen,x,y,w,h,wndProc, hIcon) == true) { if(InitDX(fullscreen,32) == true) { } } } mxHwnd::mxHwnd() { hwnd = 0, w = h = 0; } bool mxHwnd::Init(const char *title, bool full, int x, int y, int w, int h, WNDPROC WndProc, HICON hIcon) { WNDCLASSEX wc; wc.cbSize = sizeof(WNDCLASSEX); wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH); wc.hInstance = GetModuleHandle(0); wc.hIcon = hIcon; wc.hIconSm = hIcon; wc.hCursor = LoadCursor(NULL,IDC_ARROW); wc.lpfnWndProc = (WNDPROC) WndProc; wc.lpszClassName = title; wc.lpszMenuName = NULL; wc.style = CS_HREDRAW | CS_VREDRAW; RegisterClassEx(&wc); this->hwnd = CreateWindow(title,title,(full == true) ? WS_POPUPWINDOW : WS_SYSMENU | WS_MINIMIZEBOX, x,y,w,h,NULL,NULL,GetModuleHandle(0),NULL); if(!hwnd) { ErrorMsg("Couldnt create window!.\n"); return false; } ShowWindow(hwnd,SW_SHOW); UpdateWindow(hwnd); this->w = w; this->h = h; this->screen.w = w; this->screen.h = h; return true; } bool mxHwnd::InitDX(bool fullscreen, int bpp) { screen.pd3d = Direct3DCreate9(D3D_SDK_VERSION); if(!screen.pd3d) { ErrorMsg("Error couldnt create Direct3D Device."); return false; } D3DPRESENT_PARAMETERS dpp; ZeroMemory(&dpp, sizeof(dpp)); dpp.BackBufferCount = 1; dpp.BackBufferWidth = this->w; dpp.BackBufferHeight = this->h; if( bpp == 16 ) dpp.BackBufferFormat = D3DFMT_R5G6B5; else if( bpp == 24 ) dpp.BackBufferFormat = D3DFMT_X8R8G8B8; else if( bpp == 32 ) dpp.BackBufferFormat = D3DFMT_A8R8G8B8; else ErrorMsg("Invalid Format for BackBuffer you choose %d", bpp); dpp.SwapEffect = D3DSWAPEFFECT_COPY; dpp.MultiSampleQuality = 0; dpp.MultiSampleType = D3DMULTISAMPLE_NONE; dpp.hDeviceWindow = this->hwnd; dpp.Windowed = (fullscreen == true) ? FALSE : TRUE; dpp.EnableAutoDepthStencil = TRUE; dpp.AutoDepthStencilFormat = D3DFMT_D16; dpp.FullScreen_RefreshRateInHz = (fullscreen == false) ? 0 : D3DPRESENT_RATE_DEFAULT; dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; dpp.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; HRESULT rt = screen.pd3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING,&dpp,&screen.pd3d_dev ); if(FAILED(rt)) { ErrorMsg("Error couldnt create Device.\n"); return false; } screen.scr_rc.top = screen.scr_rc.left = 0; screen.scr_rc.right = this->w; screen.scr_rc.bottom = this->h; screen.pd3d_dev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &screen.pback ); if(!screen.pback) { ErrorMsg("Error couldnt retrive the back buffer!\n"); return false; } text.Init(&screen); paint.init(&screen); input.Init(this->hwnd); return true; } int mxHwnd::InitLoop(void(*render)(int screen)) { MSG msg; go = true; SetFocus(hwnd); while(go == true) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if(msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } else if(active) { input.Update(); screen.pd3d_dev->Clear(NULL,NULL,D3DCLEAR_ZBUFFER | D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0),1.0f,NULL); render(cur_screen); screen.pd3d_dev->Present(NULL,NULL,NULL,NULL); } else if(!active) WaitMessage(); } input.Free(); return (int) msg.wParam; } mxScreen::~mxScreen() { SafeFree<LPDIRECT3DSURFACE9>(this->pback); SafeFree<LPDIRECT3DDEVICE9>(this->pd3d_dev); SafeFree<LPDIRECT3D9>(this->pd3d); } void __fastcall mxPaint::Lock() { mxscr->pback->LockRect(&rect,NULL,NULL); data = (DWORD*) rect.pBits; } void __fastcall mxPaint::UnLock() { mxscr->pback->UnlockRect(); } void __fastcall mxPaint::fast_sp(int x, int y, int pitch, D3DCOLOR color) { if(x >= 0 && x < mxscr->w-1 && y >= 0 && y < mxscr->h-1) data[(((pitch/4) * y) + x)] = color; } DWORD __fastcall mxPaint::fast_gp(int x, int y) { int pitch = this->rect.Pitch; return data[((pitch/4) * y) +x]; } void __fastcall mxPaint::setpixel(int i, int z,D3DCOLOR color) { mxscr->pback->LockRect(&rect,NULL,NULL); DWORD *pdata = (DWORD*) rect.pBits; int pitch = rect.Pitch; pdata[(((pitch/4) * z) + i)] = color; mxscr->pback->UnlockRect(); } void Swap(int& a, int& b) { int temp = a; a = b; b = temp; } void Swap(float& a, float& b) { float temp = a; a = b; b = temp; } static int max_clip_x = 640, min_clip_x = 0, max_clip_y = 480, min_clip_y = 0; void __fastcall mxPaint::drawbottomtri(int x1, int y1, int x2, int y2, int x3, int y3, D3DCOLOR color) { float dx_right,dx_left,xs,xe,height; int temp_x,temp_y,right,left; if (x3 < x2) { temp_x = x2; x2 = x3; x3 = temp_x; } height = float(y3-y1); dx_left = (x2-x1)/height; dx_right = (x3-x1)/height; xs = (float)x1; xe = (float)x1; if (y1 < min_clip_y) { xs = xs+dx_left*(float)(-y1+min_clip_y); xe = xe+dx_right*(float)(-y1+min_clip_y); y1 = min_clip_y; } if (y3 > max_clip_y) y3 = max_clip_y; if (x1>=min_clip_x && x1<=max_clip_x && x2>=min_clip_x && x2<=max_clip_x && x3>=min_clip_x && x3<=max_clip_x) { for (temp_y=y1; temp_y<=y3; temp_y++) { drawhline(int(xs),(int)xs+(int(xe-xs+1)),temp_y,color); xs+=dx_left; xe+=dx_right; } } else { for (temp_y=y1; temp_y<=y3; temp_y++) { left = (int)xs; right = (int)xe; xs+=dx_left; xe+=dx_right; if (left < min_clip_x){ left = min_clip_x; if (right < min_clip_x) continue; } if (right > max_clip_x) { right = max_clip_x; if (left > max_clip_x) continue; } drawhline(int(left),(int)left+(int(right-left+1)),temp_y,color); } } } void __fastcall mxPaint::drawtoptri(int x1, int y1,int x2, int y2, int x3, int y3, D3DCOLOR color) { float dx_right,dx_left,xs,xe,height; int temp_x,temp_y,right,left; if (x2 < x1) { temp_x = x2; x2 = x1; x1 = temp_x; } height = float(y3-y1); dx_left = (x3-x1)/height; dx_right = (x3-x2)/height; xs = (float)x1; xe = (float)x2; if (y1 < min_clip_y) { xs = xs+dx_left*(float)(-y1+min_clip_y); xe = xe+dx_right*(float)(-y1+min_clip_y); y1=min_clip_y; } if (y3>max_clip_y) y3=max_clip_y; if (x1>=min_clip_x && x1<=max_clip_x && x2>=min_clip_x && x2<=max_clip_x && x3>=min_clip_x && x3<=max_clip_x) { for (temp_y=y1; temp_y<=y3; temp_y++) { drawhline(int(xs),int(xs+(int)xe-xs+1),temp_y,color); xs+=dx_left; xe+=dx_right; } } else { for (temp_y=y1; temp_y<=y3; temp_y++) { left = (int)xs; right = (int)xe; xs+=dx_left; xe+=dx_right; if (left < min_clip_x) { left = min_clip_x; if (right < min_clip_x) continue; } if (right > max_clip_x) { right = max_clip_x; if (left > max_clip_x) continue; } drawhline((int)left,(int)left+(int)right-left+1,temp_y,color); } } } void __fastcall mxPaint::drawtoptri2(float x1, float y1, float x2, float y2, float x3, float y3, D3DCOLOR color) { } void __fastcall mxPaint::drawbottomtri2(float x1, float y1, float x2, float y2, float x3, float y3, D3DCOLOR color) { } void __fastcall mxPaint::drawtri(int x1, int y1,int x2, int y2, int x3, int y3, D3DCOLOR color) { int temp_x,temp_y,new_x; if ((x1==x2 && x2==x3) || (y1==y2 && y2==y3)) return; if (y2<y1) { temp_x = x2; temp_y = y2; x2 = x1; y2 = y1; x1 = temp_x; y1 = temp_y; } if (y3<y1) { temp_x = x3; temp_y = y3; x3 = x1; y3 = y1; x1 = temp_x; y1 = temp_y; } if (y3<y2) { temp_x = x3; temp_y = y3; x3 = x2; y3 = y2; x2 = temp_x; y2 = temp_y; } if ( y3<min_clip_y || y1>max_clip_y || (x1<min_clip_x && x2<min_clip_x && x3<min_clip_x) || (x1>max_clip_x && x2>max_clip_x && x3>max_clip_x) ) return; if (y1==y2) { this->drawtoptri(x1,y1,x2,y2,x3,y3,color); } else if (y2==y3){ this->drawbottomtri(x1,y1,x2,y2,x3,y3,color); } else { new_x = x1 + (int)(0.5+(float)(y2-y1)*(float)(x3-x1)/(float)(y3-y1)); this->drawbottomtri(x1,y1,new_x,y2,x2,y2,color); this->drawtoptri(x2,y2,new_x,y2,x3,y3,color); } } void __fastcall mxPaint::filltri(POINT &p1, POINT &p2, POINT &p3, D3DCOLOR color) { } void __fastcall mxPaint::drawhline(int x,int x2, int y, D3DCOLOR color) { for(int p = x; p <= x2; p++) fast_sp(p,y,rect.Pitch,color); } void __fastcall mxPaint::drawtri2(float x1, float y1, float x2, float y2, float x3, float y3, D3DCOLOR color) { } void __fastcall mxPaint::drawgentri(int x0, int y0, int x1, int y1, int x2, int y2, D3DCOLOR color) { if( y1 < y0 ) { Swap(y1, y0); Swap(x1, x0); } if( y2 < y0 ) { Swap(y2, y0); Swap(x2, x0); } if( y1 < y2 ) { Swap(y2, y1); Swap(x2, x1); } float xl_edge = (float)x0; float xr_edge = (float)x0; float dxldy; float dxrdy; float dxdy1 = (float)(x2-x0)/(y2-y0); float dxdy2 = (float)(x1-x0)/(y1-y0); if( dxdy1 < dxdy2 ) { dxldy = dxdy1; dxrdy = dxdy2; } else { dxldy = dxdy2; dxrdy = dxdy1; } for(int y=y0; y<y2; y++) { for(int x=int(xl_edge); x<int(xr_edge); x++) { this->fast_sp(x, y, this->rect.Pitch, color); } xl_edge = xl_edge + dxldy; xr_edge = xr_edge + dxrdy; } if( dxdy1 < dxdy2 ) { dxldy = (float)(x2-x1)/(y2-y1); } else { dxrdy = (float)(x2-x1)/(y2-y1); } for(int y=y2; y<y1; y++) { for(int x=int(xl_edge); x<int(xr_edge); x++) { this->fast_sp(x,y,this->rect.Pitch,color); } xl_edge = xl_edge + dxldy; xr_edge = xr_edge + dxrdy; } } void __fastcall mxPaint::drawrect(int x, int y, int w , int h, D3DCOLOR color) { D3DRECT rc = { x,y,w,h }; mxscr->pd3d_dev->Clear(1,&rc,D3DCLEAR_ZBUFFER | D3DCLEAR_TARGET, color,1.0f,NULL); } void __fastcall mxPaint::drawroundrect(int x, int y, int x2, int y2, int ch, int cw, COLORREF fill, COLORREF outline) { HDC dc; mxscr->pback->GetDC(&dc); HBRUSH hNewBrush,hOldBrush; HPEN hNewPen,hOldPen; hNewBrush = (HBRUSH)CreateSolidBrush(fill); hOldBrush = (HBRUSH)SelectObject(dc,(HBRUSH)hNewBrush); hNewPen = CreatePen(PS_SOLID,2,outline); hOldPen= (HPEN__*)SelectObject(dc,(HPEN__*)hNewPen); RoundRect(dc,x,y,x2,y2,cw,ch); SelectObject(dc,hOldPen); SelectObject(dc,hOldBrush); DeleteObject(hNewBrush); DeleteObject(hNewPen); mxscr->pback->ReleaseDC(dc); } void __fastcall mxPaint::drawpie(int x, int y, int x2, int y2, int nx, int ny, int nx2, int ny2, COLORREF fill, COLORREF outline) { HDC dc; mxscr->pback->GetDC(&dc); HBRUSH hNewBrush,hOldBrush; HPEN hNewPen,hOldPen; hNewBrush = (HBRUSH)CreateSolidBrush(fill); hOldBrush = (HBRUSH)SelectObject(dc,(HBRUSH)hNewBrush); hNewPen = CreatePen(PS_SOLID,2,outline); hOldPen= (HPEN__*)SelectObject(dc,(HPEN__*)hNewPen); Pie(dc,x,y,x2,y2,nx,ny,nx2,ny2); SelectObject(dc,hOldPen); SelectObject(dc,hOldBrush); DeleteObject(hNewBrush); DeleteObject(hNewPen); mxscr->pback->ReleaseDC(dc); } void __fastcall mxPaint::drawchord(int x, int y, int x2, int y2, int nx, int ny, int nx2, int ny2,COLORREF fill,COLORREF outline) { HDC dc; mxscr->pback->GetDC(&dc); HBRUSH hNewBrush,hOldBrush; HPEN hNewPen,hOldPen; hNewBrush = (HBRUSH)CreateSolidBrush(fill); hOldBrush = (HBRUSH)SelectObject(dc,(HBRUSH)hNewBrush); hNewPen = CreatePen(PS_SOLID,2,outline); hOldPen= (HPEN__*)SelectObject(dc,(HPEN__*)hNewPen); Chord(dc,x,y,x2,y2,nx,ny,nx2,ny2); SelectObject(dc,hOldPen); SelectObject(dc,hOldBrush); DeleteObject(hNewBrush); DeleteObject(hNewPen); mxscr->pback->ReleaseDC(dc); } void __fastcall mxPaint::drawellipse(int x, int y, int x2, int y2,COLORREF fill,COLORREF outline) { HDC dc; mxscr->pback->GetDC(&dc); HBRUSH hNewBrush,hOldBrush; HPEN hNewPen,hOldPen; hNewBrush = (HBRUSH)CreateSolidBrush(fill); hOldBrush = (HBRUSH)SelectObject(dc,(HBRUSH)hNewBrush); hNewPen = CreatePen(PS_SOLID,2,outline); hOldPen= (HPEN__*)SelectObject(dc,(HPEN__*)hNewPen); Ellipse(dc,x,y,x2,y2); SelectObject(dc,hOldPen); SelectObject(dc,hOldBrush); DeleteObject(hNewBrush); DeleteObject(hNewPen); mxscr->pback->ReleaseDC(dc); } void __fastcall mxPaint::drawpolygon(CONST POINT* point,int n_points,COLORREF fill,COLORREF outline) { HDC dc; mxscr->pback->GetDC(&dc); HBRUSH hNewBrush,hOldBrush; HPEN hNewPen,hOldPen; hNewBrush = (HBRUSH)CreateSolidBrush(fill); hOldBrush = (HBRUSH)SelectObject(dc,(HBRUSH)hNewBrush); hNewPen = CreatePen(PS_SOLID,2,outline); hOldPen= (HPEN__*)SelectObject(dc,(HPEN__*)hNewPen); Polygon(dc,point,n_points); SelectObject(dc,hOldPen); SelectObject(dc,hOldBrush); DeleteObject(hNewBrush); DeleteObject(hNewPen); mxscr->pback->ReleaseDC(dc); } void __fastcall mxPaint::drawanglearc(int x, int y, long radius, float startangle,float sweepangle,COLORREF fill,COLORREF outline) { HDC dc; mxscr->pback->GetDC(&dc); HBRUSH hNewBrush,hOldBrush; HPEN hNewPen,hOldPen; hNewBrush = (HBRUSH)CreateSolidBrush(fill); hOldBrush = (HBRUSH)SelectObject(dc,(HBRUSH)hNewBrush); hNewPen = CreatePen(PS_SOLID,2,outline); hOldPen= (HPEN__*)SelectObject(dc,(HPEN__*)hNewPen); AngleArc(dc,x,y,radius,startangle,sweepangle); SelectObject(dc,hOldPen); SelectObject(dc,hOldBrush); DeleteObject(hNewBrush); DeleteObject(hNewPen); mxscr->pback->ReleaseDC(dc); } void __fastcall mxPaint::drawarc(int x1, int x2, int x3, int x4,int x5, int x6,int x7, int x8,COLORREF fill,COLORREF outline) { HDC dc; mxscr->pback->GetDC(&dc); HBRUSH hNewBrush,hOldBrush; HPEN hNewPen,hOldPen; hNewBrush = (HBRUSH)CreateSolidBrush(fill); hOldBrush = (HBRUSH)SelectObject(dc,(HBRUSH)hNewBrush); hNewPen = CreatePen(PS_SOLID,2,outline); hOldPen= (HPEN__*)SelectObject(dc,(HPEN__*)hNewPen); Arc(dc,x1,x2,x3,x4,x5,x6,x7,x8); SelectObject(dc,hOldPen); SelectObject(dc,hOldBrush); DeleteObject(hNewBrush); DeleteObject(hNewPen); mxscr->pback->ReleaseDC(dc); } void __fastcall mxPaint::drawlineto(int x, int y,COLORREF fill,COLORREF outline) { HDC dc; mxscr->pback->GetDC(&dc); HBRUSH hNewBrush,hOldBrush; HPEN hNewPen,hOldPen; hNewBrush = (HBRUSH)CreateSolidBrush(fill); hOldBrush = (HBRUSH)SelectObject(dc,(HBRUSH)hNewBrush); hNewPen = CreatePen(PS_SOLID,2,outline); hOldPen= (HPEN__*)SelectObject(dc,(HPEN__*)hNewPen); LineTo(dc,x,y); SelectObject(dc,hOldPen); SelectObject(dc,hOldBrush); DeleteObject(hNewBrush); DeleteObject(hNewPen); mxscr->pback->ReleaseDC(dc); } void __fastcall mxPaint::drawpixel(int x, int y, COLORREF color) { HDC dc; this->mxscr->pback->GetDC(&dc); SetPixel(dc,x,y,color); this->mxscr->pback->ReleaseDC(dc); } COLORREF __fastcall mxPaint::drawgetpixel(int x, int y) { HDC dc; this->mxscr->pback->GetDC(&dc); COLORREF color = GetPixel(dc,x,y); this->mxscr->pback->ReleaseDC(dc); return color; } void __fastcall mxPaint::drawline(int start_x, int start_y, int stop_x, int stop_y, D3DCOLOR color) { //Lock(); assumes its locked int y_unit,x_unit; int ydiff = stop_y-start_y; if(ydiff<0) { ydiff = -ydiff; y_unit=-1; } else { y_unit =1; } int xdiff=stop_x-start_x; if(xdiff<0) { xdiff=-xdiff; x_unit = -1; } else { x_unit = 1; } int error_term=0; if(xdiff>ydiff) { int length=xdiff+1; for(int i = 0; i <length; i++) { //SetPixel(dc,start_x,start_y,color); fast_sp(start_x,start_y,rect.Pitch,color); start_x += x_unit; error_term+=ydiff; if(error_term>xdiff) { error_term-=xdiff; start_y+=y_unit; } } } else { int length = ydiff+1; for(int i = 0; i < length; i++) { //SetPixel(dc,start_x,start_y,color); fast_sp(start_x,start_y,rect.Pitch,color); start_y += y_unit; error_term+=xdiff; if(error_term>0) { error_term-=ydiff; start_x += x_unit; } } } } LPDIRECTINPUTDEVICE8 p_joy = 0; LPDIRECTINPUT8 pdi = 0; bool joy_exisits; char joy_name[256];
gpl-3.0
MeteoricGames/pioneer
src/LuaSpace.cpp
21171
// Copyright © 2008-2014 Pioneer Developers. See AUTHORS.txt for details // Licensed under the terms of the GPL v3. See licenses/GPL-3.txt #include "LuaObject.h" #include "LuaSpace.h" #include "LuaManager.h" #include "LuaUtils.h" #include "Space.h" #include "Ship.h" #include "HyperspaceCloud.h" #include "Pi.h" #include "SpaceStation.h" #include "Player.h" #include "Game.h" #include "MathUtil.h" #include "Frame.h" /* * Interface: Space * * Various functions to create and find objects in the current physics space. */ static void _unpack_hyperspace_args(lua_State *l, int index, SystemPath* &path, double &due) { if (lua_isnone(l, index)) return; luaL_checktype(l, index, LUA_TTABLE); LUA_DEBUG_START(l); lua_pushinteger(l, 1); lua_gettable(l, index); if (!(path = LuaObject<SystemPath>::GetFromLua(-1))) luaL_error(l, "bad value for hyperspace path at position 1 (SystemPath expected, got %s)", luaL_typename(l, -1)); lua_pop(l, 1); lua_pushinteger(l, 2); lua_gettable(l, index); if (!(lua_isnumber(l, -1))) luaL_error(l, "bad value for hyperspace exit time at position 2 (%s expected, got %s)", lua_typename(l, LUA_TNUMBER), luaL_typename(l, -1)); due = lua_tonumber(l, -1); if (due < 0) luaL_error(l, "bad value for hyperspace exit time at position 2 (must be >= 0)"); lua_pop(l, 1); LUA_DEBUG_END(l, 0); } static Body *_maybe_wrap_ship_with_cloud(Ship *ship, SystemPath *path, double due) { if (!path) { return ship; } HyperspaceCloud *cloud = Pi::game->GetSpace()->GetFreePermaHyperspaceCloud(); if(cloud) { // Spawn in permanent cloud cloud->ReceiveShip(ship, due); } else { // Use normal spawn cloud because perma clouds are all in use cloud = Pi::game->GetSpace()->CreateHyperspaceCloud(ship, due); } ship->SetHyperspaceDest(path); ship->SetFlightState(Ship::HYPERSPACE); return cloud; } /* * Function: SpawnShip * * Create a ship and place it somewhere in space. * * > ship = Space.SpawnShip(type, min, max, hyperspace) * * Parameters: * * type - the name of the ship * * min - minimum distance from the system centre (usually the primary star) * to place the ship, in AU * * max - maximum distance to place the ship * * hyperspace - optional table containing hyperspace entry information. If * this is provided the ship will not spawn directly. Instead, * a hyperspace cloud will be created that the ship will exit * from. The table contains two elements, a <SystemPath> for * the system the ship is travelling from, and the due * date/time that the ship should emerge from the cloud. * In this case min and max arguments are ignored. * * Return: * * ship - a <Ship> object for the new ship * * Examples: * * > -- spawn a ship 5-6AU from the system centre * > local ship = Ship.Spawn("eagle_lrf", 5, 6) * * > -- spawn a ship in the ~11AU hyperspace area and make it appear that it * > -- came from Sol and will arrive in ten minutes * > local ship = Ship.Spawn( * > "flowerfairy", 9, 11, * > { SystemPath:New(0,0,0), Game.time + 600 } * > ) * * Availability: * * alpha 10 * * Status: * * experimental */ static int l_space_spawn_ship(lua_State *l) { if (!Pi::game) luaL_error(l, "Game is not started"); LUA_DEBUG_START(l); const char *type = luaL_checkstring(l, 1); if (! ShipType::Get(type)) luaL_error(l, "Unknown ship type '%s'", type); float min_dist = luaL_checknumber(l, 2); float max_dist = luaL_checknumber(l, 3); SystemPath *path = 0; double due = -1; _unpack_hyperspace_args(l, 4, path, due); Ship *ship = new Ship(type); assert(ship); Body *thing = _maybe_wrap_ship_with_cloud(ship, path, due); if (!path) { // Thing is a ship thing->SetPosition(MathUtil::RandomPointOnSphere(min_dist, max_dist)*AU); // XXX protect against spawning inside the body thing->SetFrame(Pi::game->GetSpace()->GetRootFrame()); thing->SetVelocity(vector3d(0, 0, 0)); Pi::game->GetSpace()->AddBody(thing); } else { // Thing is a hyperspace cloud auto hc = static_cast<HyperspaceCloud*>(thing); if(hc->IsPermanent()) { // Permanent ship handles it, no need to do anything. } else { // Normal temp cloud thing->SetFrame(Pi::game->GetSpace()->GetRootFrame()); thing->SetPosition(Pi::game->GetSpace()->GetHyperspaceExitPoint(*path)); thing->SetVelocity(vector3d(0, 0, 0)); Pi::game->GetSpace()->AddBody(thing); // XXX broken. this ^ is ignoring min_dist & max_dist. otoh, what's the // correct behaviour given there's now a fixed hyperspace exit point? } } LuaObject<Ship>::PushToLua(ship); LUA_DEBUG_END(l, 1); return 1; } /* * Function: SpawnShipNear * * Create a ship and place it in space near the given <Body>. * * > ship = Space.SpawnShip(type, body, min, max, hyperspace) * * Parameters: * * type - the name of the ship * * body - the <Body> near which the ship should be spawned * * min - minimum distance from the body to place the ship, in Km * * max - maximum distance to place the ship * * hyperspace - optional table containing hyperspace entry information. If * this is provided the ship will not spawn directly. Instead, * a hyperspace cloud will be created that the ship will exit * from. The table contains two elements, a <SystemPath> for * the system the ship is travelling from, and the due * date/time that the ship should emerge from the cloud. * * Return: * * ship - a <Ship> object for the new ship * * Example: * * > -- spawn a ship 10km from the player * > local ship = Ship.SpawnNear("viper_police_craft", Game.player, 10, 10) * * Availability: * * alpha 10 * * Status: * * experimental */ static int l_space_spawn_ship_near(lua_State *l) { if (!Pi::game) luaL_error(l, "Game is not started"); LUA_DEBUG_START(l); const char *type = luaL_checkstring(l, 1); if (! ShipType::Get(type)) luaL_error(l, "Unknown ship type '%s'", type); Body *nearbody = LuaObject<Body>::CheckFromLua(2); float min_dist = luaL_checknumber(l, 3); float max_dist = luaL_checknumber(l, 4); SystemPath *path = 0; double due = -1; _unpack_hyperspace_args(l, 5, path, due); Ship *ship = new Ship(type); assert(ship); Body *thing = _maybe_wrap_ship_with_cloud(ship, path, due); bool perma = path && static_cast<HyperspaceCloud*>(thing)->IsPermanent(); if(!perma) { // XXX protect against spawning inside the body Frame * newframe = nearbody->GetFrame(); const vector3d newPosition = (MathUtil::RandomPointOnSphere(min_dist, max_dist) * 1000.0) + nearbody->GetPosition(); // If the frame is rotating and the chosen position is too far, use non-rotating parent. // Otherwise the ship will be given a massive initial velocity when it's bumped out of the // rotating frame in the next update if (newframe->IsRotFrame() && newframe->GetRadius() < newPosition.Length()) { assert(newframe->GetParent()); newframe = newframe->GetParent(); } thing->SetFrame(newframe);; thing->SetPosition(newPosition); thing->SetVelocity(vector3d(0,0,0)); Pi::game->GetSpace()->AddBody(thing); } else { // Permanent cloud handles it, no need to do anything } LuaObject<Ship>::PushToLua(ship); LUA_DEBUG_END(l, 1); return 1; } /* * Function: SpawnShipDocked * * Create a ship and place it inside the given <SpaceStation>. * * > ship = Space.SpawnShipDocked(type, station) * * Parameters: * * type - the name of the ship * * station - the <SpaceStation> to place the ship inside * * Return: * * ship - a <Ship> object for the new ship, or nil if there was no space * inside the station * * Availability: * * alpha 10 * * Status: * * stable */ static int l_space_spawn_ship_docked(lua_State *l) { if (!Pi::game) luaL_error(l, "Game is not started"); LUA_DEBUG_START(l); const char *type = luaL_checkstring(l, 1); if (! ShipType::Get(type)) luaL_error(l, "Unknown ship type '%s'", type); SpaceStation *station = LuaObject<SpaceStation>::CheckFromLua(2); if(!station->HasFreeDockingPort()) { return 0; } Ship *ship = new Ship(type); assert(ship); int port = station->GetFreeDockingPort(ship); // pass in the ship to get a port we fit into if(port < 0) { delete ship; return 0; } ship->SetFrame(station->GetFrame()); Pi::game->GetSpace()->AddBody(ship); ship->SetDockedWith(station, port); LuaObject<Ship>::PushToLua(ship); LUA_DEBUG_END(l, 1); return 1; } /* * Function: SpawnShipParked * * Create a ship and place it in one of the given <SpaceStation's> parking spots. * * > ship = Space.SpawnShipParked(type, station) * * For orbital stations the parking spots are some distance from the door, out * of the path of ships entering and leaving the station. For group stations * the parking spots are directly above the station, usually some distance * away. * * Parameters: * * type - the name of the ship * * station - the <SpaceStation> to place the near * * Return: * * ship - a <Ship> object for the new ship, or nil if there was no space * inside the station * Availability: * * alpha 10 * * Status: * * experimental */ static int l_space_spawn_ship_parked(lua_State *l) { if (!Pi::game) luaL_error(l, "Game is not started"); LUA_DEBUG_START(l); const char *type = luaL_checkstring(l, 1); if (! ShipType::Get(type)) luaL_error(l, "Unknown ship type '%s'", type); SpaceStation *station = LuaObject<SpaceStation>::CheckFromLua(2); int slot; if (!station->AllocateStaticSlot(slot)) return 0; Ship *ship = new Ship(type); assert(ship); double parkDist = station->GetStationType()->parkingDistance*0.5; parkDist -= ship->GetPhysRadius(); // park inside parking radius double parkOffset = 0.5 * station->GetStationType()->parkingGapSize; parkOffset += ship->GetPhysRadius(); // but outside the docking gap double xpos = (slot == 0 || slot == 3) ? -parkOffset : parkOffset; double zpos = (slot == 0 || slot == 1) ? -parkOffset : parkOffset; vector3d parkPos = vector3d(xpos, parkDist, zpos); parkPos = station->GetPosition() + station->GetOrient() * parkPos; // orbital stations have Y as axis of rotation matrix3x3d rot = matrix3x3d::RotateX(0.0) * station->GetOrient(); ship->SetFrame(station->GetFrame()); ship->SetVelocity(vector3d(0.0)); ship->SetPosition(parkPos); ship->SetOrient(rot); Pi::game->GetSpace()->AddBody(ship); ship->SetJuice(40); ship->AIHoldPosition(); LuaObject<Ship>::PushToLua(ship); LUA_DEBUG_END(l, 1); return 1; } /* * Function: SpawnShipLanded * * Create a ship and place it landed on the given <Body>. * * > ship = Space.SpawnShipLanded(type, body, lat, long) * * Parameters: * * type - the name of the ship * * body - the <Body> near which the ship should be spawned * * lat - latitude in radians (like in custom body defintions) * * long - longitude in radians (like in custom body definitions) * * Return: * * ship - a <Ship> object for the new ship * * Example: * * > -- spawn 16km from L.A. when in Sol system * > local earth = Space.GetBody(3) * > local ship = Space.SpawnShipLanded("viper_police", earth, math.deg2rad(34.06473923), math.deg2rad(-118.1591568)) * * Availability: * * TBD * * Status: * * experimental */ static int l_space_spawn_ship_landed(lua_State *l) { if (!Pi::game) luaL_error(l, "Game is not started"); LUA_DEBUG_START(l); const char *type = luaL_checkstring(l, 1); if (! ShipType::Get(type)) luaL_error(l, "Unknown ship type '%s'", type); Planet *planet = LuaObject<Planet>::CheckFromLua(2); if (planet->GetSystemBody()->GetSuperType() != SystemBody::SUPERTYPE_ROCKY_PLANET) luaL_error(l, "Body is not a rocky planet"); float latitude = luaL_checknumber(l, 3); float longitude = luaL_checknumber(l, 4); Ship *ship = new Ship(type); assert(ship); Pi::game->GetSpace()->AddBody(ship); ship->SetLandedOn(planet, latitude, longitude); LuaObject<Ship>::PushToLua(ship); LUA_DEBUG_END(l, 1); return 1; } /* * Function: SpawnShipLandedNear * * Create a ship and place it on the surface near the given <Body>. * * > ship = Space.SpawnShipLandedNear(type, body, min, max) * * Parameters: * * type - the name of the ship * * body - the <Body> near which the ship should be spawned. It must be on the ground or close to it, * i.e. it must be in the rotating frame of the planetary body. * * min - minimum distance from the surface point below the body to place the ship, in Km * * max - maximum distance to place the ship * * Return: * * ship - a <Ship> object for the new ship * * Example: * * > -- spawn a ship 10km from the player * > local ship = Ship.SpawnShipLandedNear("viper_police", Game.player, 10, 10) * * Availability: * * alpha 10 * * Status: * * experimental */ static int l_space_spawn_ship_landed_near(lua_State *l) { if (!Pi::game) luaL_error(l, "Game is not started"); LUA_DEBUG_START(l); const char *type = luaL_checkstring(l, 1); if (! ShipType::Get(type)) luaL_error(l, "Unknown ship type '%s'", type); Body *nearbody = LuaObject<Body>::CheckFromLua(2); const float min_dist = luaL_checknumber(l, 3); const float max_dist = luaL_checknumber(l, 4); if (min_dist > max_dist) luaL_error(l, "min_dist must not be larger than max_dist"); Ship *ship = new Ship(type); assert(ship); // XXX protect against spawning inside the body Frame * newframe = nearbody->GetFrame()->GetRotFrame(); if (!newframe->IsRotFrame()) luaL_error(l, "Body must be in rotating frame"); SystemBody *sbody = newframe->GetSystemBody(); if (sbody->GetSuperType() != SystemBody::SUPERTYPE_ROCKY_PLANET) luaL_error(l, "Body is not on a rocky planet"); if (max_dist > sbody->GetRadius()) luaL_error(l, "max_dist too large for planet radius"); // We assume that max_dist is much smaller than the planet radius, i.e. that our area is reasonably flat // So, we const vector3d up = nearbody->GetPosition().Normalized(); vector3d x; vector3d y; // Calculate a orthonormal basis for a horizontal plane. For numerical reasons we do that determining the smallest // coordinate and take the cross product with (1,0,0), (0,1,0) or (0,0,1) respectively to calculate the first vector. // The second vector is just the cross product of the up-vector and out first vector. if (up.x <= up.y && up.x <= up.z) { x = vector3d(0.0, up.z, -up.y).Normalized(); y = vector3d(-up.y*up.y - up.z*up.z, up.x*up.y, up.x*up.z).Normalized(); } else if (up.y <= up.x && up.y <= up.z) { x = vector3d(-up.z, 0.0, up.x).Normalized(); y = vector3d(up.x*up.y, -up.x*up.x - up.z*up.z, up.y*up.z).Normalized(); } else { x = vector3d(up.y, -up.x, 0.0).Normalized(); y = vector3d(up.x*up.z, up.y*up.z, -up.x*up.x - up.y*up.y).Normalized(); } Planet *planet = static_cast<Planet*>(newframe->GetBody()); const double radius = planet->GetSystemBody()->GetRadius(); const vector3d planar = MathUtil::RandomPointInCircle(min_dist * 1000.0, max_dist * 1000.0); vector3d pos = (radius * up + x * planar.x + y * planar.y).Normalized(); float latitude = atan2(pos.y, sqrt(pos.x*pos.x + pos.z * pos.z)); float longitude = atan2(pos.x, pos.z); Pi::game->GetSpace()->AddBody(ship); ship->SetLandedOn(planet, latitude, longitude); LuaObject<Ship>::PushToLua(ship); LUA_DEBUG_END(l, 1); return 1; } /* * Function: SpawnShipParkedOffset * * Create a ship and place it in one of the given <SpaceStation's> parking spots. * * > ship = Space.SpawnShipParkedOffset(type, station) * * For orbital stations the parking spots are some distance from the door, out * of the path of ships entering and leaving the station. For group stations * the parking spots are 0.26 x physical radius above the station, usually some distance * away. * * Parameters: * * type - the name of the ship * * station - the <SpaceStation> to place the near * * Return: * * ship - a <Ship> object for the new ship, or nil if there was no space * inside the station * Availability: * * June 2013 * * Status: * * experimental */ static int l_space_spawn_ship_parked_offset(lua_State *l) { if (!Pi::game) luaL_error(l, "Game is not started"); LUA_DEBUG_START(l); const char *type = luaL_checkstring(l, 1); if (! ShipType::Get(type)) luaL_error(l, "Unknown ship type '%s'", type); SpaceStation *station = LuaObject<SpaceStation>::CheckFromLua(2); int slot; if (!station->AllocateStaticSlot(slot)) return 0; Ship *ship = new Ship(type); assert(ship); double dist = station->GetFrame()->GetBody()->GetPhysRadius()*0.26; double parkDist = station->GetStationType()->parkingDistance*0.5+dist; parkDist -= ship->GetPhysRadius(); // park inside parking radius double parkOffset = 0.5 * station->GetStationType()->parkingGapSize; parkOffset += ship->GetPhysRadius(); // but outside the docking gap double xpos = (slot == 0 || slot == 3) ? -parkOffset : parkOffset; double zpos = (slot == 0 || slot == 1) ? -parkOffset : parkOffset; vector3d parkPos = vector3d(xpos, parkDist, zpos); parkPos = station->GetPosition() + station->GetOrient() * parkPos; // orbital stations have Y as axis of rotation matrix3x3d rot = matrix3x3d::RotateX(0.0) * station->GetOrient(); ship->SetFrame(station->GetFrame()); ship->SetVelocity(vector3d(0.0)); ship->SetPosition(parkPos); ship->SetOrient(rot); Pi::game->GetSpace()->AddBody(ship); ship->SetJuice(40); ship->AIHoldPosition(); ship->SetWheelState(true); LuaObject<Ship>::PushToLua(ship); LUA_DEBUG_END(l, 1); return 1; } /* * Function: GetBody * * Get the <Body> with the specificed body index. * * > body = Space.GetBody(index) * * Parameters: * * index - the body index * * Return: * * body - the <Body> object for the requested body, or nil if no such body * exists * * Availability: * * alpha 10 * * Status: * * stable */ static int l_space_get_body(lua_State *l) { if (!Pi::game) luaL_error(l, "Game is not started"); int id = luaL_checkinteger(l, 1); SystemPath path = Pi::game->GetSpace()->GetStarSystem()->GetPath(); path.bodyIndex = id; Body *b = Pi::game->GetSpace()->FindBodyForPath(&path); if (!b) return 0; LuaObject<Body>::PushToLua(b); return 1; } /* * Function: GetBodies * * Get all the <Body> objects that match the specified filter * * bodies = Space.GetBodies(filter) * * Parameters: * * filter - an option function. If specificed the function will be called * once for each body with the <Body> object as the only parameter. * If the filter function returns true then the <Body> will be * included in the array returned by <GetBodies>, otherwise it will * be omitted. If no filter function is specified then all bodies * are returned. * * Return: * * bodies - an array containing zero or more <Body> objects that matched the * filter * * Example: * * > -- get all the ground-based stations * > local stations = Space.GetBodies(function (body) * > return body.type == "STARPORT_SURFACE" * > end) * * Availability: * * alpha 10 * * Status: * * stable */ static int l_space_get_bodies(lua_State *l) { if (!Pi::game) luaL_error(l, "Game is not started"); LUA_DEBUG_START(l); bool filter = false; if (lua_gettop(l) >= 1) { luaL_checktype(l, 1, LUA_TFUNCTION); // any type of function filter = true; } lua_newtable(l); for (Body* b : Pi::game->GetSpace()->GetBodies()) { if (filter) { lua_pushvalue(l, 1); LuaObject<Body>::PushToLua(b); if (int ret = lua_pcall(l, 1, 1, 0)) { const char *errmsg( "Unknown error" ); if (ret == LUA_ERRRUN) errmsg = lua_tostring(l, -1); else if (ret == LUA_ERRMEM) errmsg = "memory allocation failure"; else if (ret == LUA_ERRERR) errmsg = "error in error handler function"; luaL_error(l, "Error in filter function: %s", errmsg); } if (!lua_toboolean(l, -1)) { lua_pop(l, 1); continue; } lua_pop(l, 1); } lua_pushinteger(l, lua_rawlen(l, -1)+1); LuaObject<Body>::PushToLua(b); lua_rawset(l, -3); } LUA_DEBUG_END(l, 1); return 1; } void LuaSpace::Register() { lua_State *l = Lua::manager->GetLuaState(); LUA_DEBUG_START(l); static const luaL_Reg l_methods[] = { { "SpawnShip", l_space_spawn_ship }, { "SpawnShipNear", l_space_spawn_ship_near }, { "SpawnShipDocked", l_space_spawn_ship_docked }, { "SpawnShipParked", l_space_spawn_ship_parked }, { "SpawnShipLanded", l_space_spawn_ship_landed }, { "SpawnShipLandedNear", l_space_spawn_ship_landed_near }, { "SpawnShipParkedOffset", l_space_spawn_ship_parked_offset }, { "GetBody", l_space_get_body }, { "GetBodies", l_space_get_bodies }, { 0, 0 } }; lua_getfield(l, LUA_REGISTRYINDEX, "CoreImports"); LuaObjectBase::CreateObject(l_methods, 0, 0); lua_setfield(l, -2, "Space"); lua_pop(l, 1); LUA_DEBUG_END(l, 0); }
gpl-3.0
ObjectiveTruth/UoitDCLibraryBooking
app/src/main/java/com/objectivetruth/uoitlibrarybooking/MainActivity.java
4788
package com.objectivetruth.uoitlibrarybooking; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentTransaction; import android.view.MenuItem; import com.objectivetruth.uoitlibrarybooking.app.UOITLibraryBookingApp; import com.objectivetruth.uoitlibrarybooking.data.models.BookingInteractionModel; import com.objectivetruth.uoitlibrarybooking.data.models.bookinginteractionmodel.BookingInteractionScreenLoadEvent; import com.objectivetruth.uoitlibrarybooking.userinterface.BookingInteraction.BookingInteraction; import com.objectivetruth.uoitlibrarybooking.userinterface.calendar.whatsnew.WhatsNewDialog; import com.objectivetruth.uoitlibrarybooking.userinterface.common.ActivityBase; import rx.Observable; import rx.functions.Action1; import rx.subscriptions.CompositeSubscription; import timber.log.Timber; import javax.inject.Inject; import static com.objectivetruth.uoitlibrarybooking.common.constants.SHARED_PREFERENCES_KEYS.HAS_DISMISSED_WHATSNEW_DIALOG_THIS_VERSION; public class MainActivity extends ActivityBase { private boolean isFirstLoadThisSession = false; private CompositeSubscription subscriptions = new CompositeSubscription(); @Inject SharedPreferences mDefaultSharedPreferences; @Inject SharedPreferences.Editor mDefaultSharedPreferencesEditor; @Inject BookingInteractionModel bookingInteractionModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState == null) {isFirstLoadThisSession = true; Timber.i("First time opening app this session");} ((UOITLibraryBookingApp) getApplication()).getComponent().inject(this); setContentView(R.layout.app_root); initializeAllMainFragmentsAndPreloadToView(); setupToolbar(R.id.toolbar); setupDrawer(R.id.drawer_layout); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); if(isFirstLoadThisSession) { _goToScreenByMenuID(R.id.drawer_menu_item_calendar); }else if(areOnlyDrawerRelatedScreensShowing()){ // A hack for the time being, use git blame to find out more _goToScreenByMenuID(getLastMenuItemIDRequested()); } if(_hasNOTDismissedWhatsNewDialogThisVersion()) { WhatsNewDialog .show(this) .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit() .putBoolean(HAS_DISMISSED_WHATSNEW_DIALOG_THIS_VERSION, true) .apply(); } });} } private boolean _hasNOTDismissedWhatsNewDialogThisVersion() { return !PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .getBoolean(HAS_DISMISSED_WHATSNEW_DIALOG_THIS_VERSION, false); } @Override public boolean onOptionsItemSelected(MenuItem item) { return getActionBarDrawerToggle().onOptionsItemSelected(item); } private void _goToScreenByMenuID(int menuItemResourceID) { MenuItem initialMenuItem = getDrawerView().getMenu().findItem(menuItemResourceID); selectDrawerItem(initialMenuItem); } @Override protected void onStart() { super.onStart(); _bindBookingInteractionEventToLoadingBookingInteractionScreen( bookingInteractionModel.getBookingInteractionScreenLoadEventObservable()); } @Override protected void onStop() { subscriptions.unsubscribe(); super.onStop(); } private void _bindBookingInteractionEventToLoadingBookingInteractionScreen( Observable<BookingInteractionScreenLoadEvent> bookingInteractionEventObservable) { subscriptions .add(bookingInteractionEventObservable .subscribe(new Action1<BookingInteractionScreenLoadEvent>() { @Override public void call(BookingInteractionScreenLoadEvent bookingInteractionScreenLoadEvent) { addHidingOfAllCurrentFragmentsToTransaction(getSupportFragmentManager().beginTransaction()) .add(R.id.mainactivity_content_frame, BookingInteraction.newInstance()) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .addToBackStack(null) .commit(); } })); } }
gpl-3.0
Roguehfhf/SPO
GeometricFigures(full)/GeometricsFigureView/AddFigureForm.cs
1720
using GeometricFigures; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GeometricsFigureView { public partial class AddFigureForm : Form { public AddFigureForm() { InitializeComponent(); } public IFigures Figure { get { try { var cathThrowFigure = figureControl1.Figure; } catch (FormatException exception) { MessageBox.Show(exception.Message); return null; } return figureControl1.Figure; } set { try { figureControl1.Figure = value; } catch (Exception exception) { MessageBox.Show(exception.Message); throw; } } } private void OkButton_Click(object sender, EventArgs e) { try { DialogResult = DialogResult.OK; Close(); } catch (Exception A) { MessageBox.Show(A.Message, @"Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void CanselButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } } }
gpl-3.0
gohdan/DFC
known_files/hashes/bitrix/modules/sale/ru/payment/yandex/.description.php
61
Bitrix 16.5 Business Demo = 0d462cfb37504ad7f92434dfe7d974a4
gpl-3.0
marcobotteri/3i-compiti-per-casa
es41pag156furbo.cpp
282
#include <iostream> #define N 100 using namespace std; int main(){ int a[]={0, 7, -1, 0,5,4,10,1,9,2,-43,-2}; int dim=15; int somme[15]; int appoggio=0; for (int i=0; i< dim; i++) appoggio+=a[i]; for( int i=0;i<dim;i++){ somme[i]=appoggio; appoggio-=a[i]; } return 0; }
gpl-3.0
xingh/bsn-modulestore
bsn.ModuleStore.Parser/Sql/Script/Sequence.cs
9133
// bsn ModuleStore database versioning // ----------------------------------- // // Copyright 2010 by Arsène von Wyss - avw@gmx.ch // // Development has been supported by Sirius Technologies AG, Basel // // Source: // // https://bsn-modulestore.googlecode.com/hg/ // // License: // // The library is distributed under the GNU Lesser General Public License: // http://www.gnu.org/licenses/lgpl.html // // 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 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 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, see <http://www.gnu.org/licenses/>. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using bsn.GoldParser.Semantic; using bsn.ModuleStore.Sql.Script.Tokens; namespace bsn.ModuleStore.Sql.Script { public class Sequence<T>: SqlToken, IEnumerable<T> where T: SqlToken { private readonly T item; private readonly Sequence<T> next; [Rule("<CursorOptionList> ::=", typeof(Identifier))] [Rule("<ForeignKeyActionList> ::=", typeof(ForeignKeyAction))] [Rule("<ColumnConstraintList> ::=", typeof(ColumnConstraint))] [Rule("<ComputedColumnConstraintList> ::=", typeof(ColumnConstraint))] [Rule("<JoinChain> ::=", typeof(Join))] [Rule("<XmlDirectiveList> ::=", typeof(XmlDirective))] public Sequence(): this(null, null) {} [Rule("<SetValueList> ::= <SetValue>", typeof(SqlScriptableToken))] [Rule("<ColumnNameList> ::= <ColumnName>", typeof(ColumnName))] [Rule("<StatementList> ::= <StatementGroup>", typeof(Statement))] [Rule("<StatementList> ::= <StatementGroup> ~<Terminator>", typeof(Statement))] [Rule("<StatementList> ::= <Label>", typeof(Statement))] [Rule("<StatementList> ::= <Label> ~<Terminator>", typeof(Statement))] [Rule("<OpenxmlColumnList> ::= <OpenxmlColumn>", typeof(OpenxmlColumn))] [Rule("<DeclareItemList> ::= <DeclareItem>", typeof(DeclareItem))] [Rule("<FulltextColumnList> ::= <FulltextColumn>", typeof(FulltextColumn))] [Rule("<FunctionParameterList> ::= <FunctionParameter>", typeof(Parameter))] [Rule("<NamedFunctionList> ::= <NamedFunction>", typeof(NamedFunction))] [Rule("<ProcedureParameterList> ::= <ProcedureParameter>", typeof(ProcedureParameter))] [Rule("<ExecuteParameterList> ::= <ExecuteParameter>", typeof(ExecuteParameter))] [Rule("<TableDefinitionList> ::= <TableDefinition>", typeof(TableDefinition))] [Rule("<IndexColumnList> ::= <IndexColumn>", typeof(IndexColumn))] [Rule("<IndexOptionList> ::= <IndexOption>", typeof(IndexOption))] [Rule("<TriggerOperationList> ::= <TriggerOperation>", typeof(DmlOperationToken))] [Rule("<TriggerNameQualifiedList> ::= <TriggerNameQualified>", typeof(Qualified<SchemaName, TriggerName>))] [Rule("<ColumnNameQualifiedList> ::= <ColumnNameQualified>", typeof(Qualified<SqlName, ColumnName>))] [Rule("<CTEList> ::= <CTE>", typeof(CommonTableExpression))] [Rule("<ColumnItemList> ::= <ColumnItem>", typeof(ColumnItem))] [Rule("<OrderList> ::= <Order>", typeof(OrderExpression))] [Rule("<ExpressionList> ::= <Expression>", typeof(Expression))] [Rule("<UpdateItemList> ::= <UpdateItem>", typeof(UpdateItem))] [Rule("<CaseWhenExpressionList> ::= <CaseWhenExpression>", typeof(CaseWhen<Expression>))] [Rule("<CaseWhenPredicateList> ::= <CaseWhenPredicate>", typeof(CaseWhen<Predicate>))] [Rule("<XmlNamespaceList> ::= <XmlNamespace>", typeof(XmlNamespace))] [Rule("<TableHintList> ::= <TableHint>", typeof(TableHint))] [Rule("<IndexValueList> ::= IntegerLiteral", typeof(IntegerLiteral))] [Rule("<MergeWhenMatchedList> ::= <MergeWhenMatched>", typeof(MergeWhenMatched))] [Rule("<ValuesList> ::= ~'(' <ExpressionList> ~')'", typeof(Sequence<Expression>))] [Rule("<QueryHintOptionList> ::= <QueryHintOption>", typeof(QueryHintOption))] [Rule("<VariableNameList> ::= <VariableName>", typeof(VariableName))] [Rule("<RaiserrorOptionList> ::= <RaiserrorOption>", typeof(UnreservedKeyword))] public Sequence(T item): this(item, null) {} [Rule("<CursorOptionList> ::= Id <CursorOptionList>", typeof(Identifier))] [Rule("<ForeignKeyActionList> ::= <ForeignKeyAction> <ForeignKeyActionList>", typeof(ForeignKeyAction))] [Rule("<ColumnConstraintList> ::= <ColumnConstraint> <ColumnConstraintList>", typeof(ColumnConstraint))] [Rule("<ComputedColumnConstraintList> ::= <ComputedColumnConstraint> <ComputedColumnConstraintList>", typeof(ColumnConstraint))] [Rule("<JoinChain> ::= <Join> <JoinChain>", typeof(Join))] [Rule("<SetValueList> ::= <SetValue> <SetValueList>", typeof(SqlScriptableToken))] [Rule("<ColumnNameList> ::= <ColumnName> ~',' <ColumnNameList>", typeof(ColumnName))] [Rule("<StatementList> ::= <StatementGroup> ~<Terminator> <StatementList>", typeof(Statement))] [Rule("<StatementList> ::= <Label> <StatementList>", typeof(Statement))] [Rule("<StatementList> ::= <Label> ~<Terminator> <StatementList>", typeof(Statement))] [Rule("<OpenxmlColumnList> ::= <OpenxmlColumn> ~',' <OpenxmlColumnList>", typeof(OpenxmlColumn))] [Rule("<DeclareItemList> ::= <DeclareItem> ~',' <DeclareItemList>", typeof(DeclareItem))] [Rule("<FulltextColumnList> ::= <FulltextColumn> ~',' <FulltextColumnList>", typeof(FulltextColumn))] [Rule("<FunctionParameterList> ::= <FunctionParameter> ~',' <FunctionParameterList>", typeof(Parameter))] [Rule("<NamedFunctionList> ::= <NamedFunction> ~'.' <NamedFunctionList>", typeof(NamedFunction))] [Rule("<ProcedureParameterList> ::= <ProcedureParameter> ~',' <ProcedureParameterList>", typeof(ProcedureParameter))] [Rule("<ExecuteParameterList> ::= <ExecuteParameter> ~',' <ExecuteParameterList>", typeof(ExecuteParameter))] [Rule("<TableDefinitionList> ::= <TableDefinition> ~',' <TableDefinitionList>", typeof(TableDefinition))] [Rule("<IndexColumnList> ::= <IndexColumn> ~',' <IndexColumnList>", typeof(IndexColumn))] [Rule("<IndexOptionList> ::= <IndexOption> ~',' <IndexOptionList>", typeof(IndexOption))] [Rule("<TriggerOperationList> ::= <TriggerOperation> ~',' <TriggerOperationList>", typeof(DmlOperationToken))] [Rule("<TriggerNameQualifiedList> ::= <TriggerNameQualified> ~',' <TriggerNameQualifiedList>", typeof(Qualified<SchemaName, TriggerName>))] [Rule("<ColumnNameQualifiedList> ::= <ColumnNameQualified> ~',' <ColumnNameQualifiedList>", typeof(Qualified<SqlName, ColumnName>))] [Rule("<CTEList> ::= <CTE> ~',' <CTEList>", typeof(CommonTableExpression))] [Rule("<ColumnItemList> ::= <ColumnItem> ~',' <ColumnItemList>", typeof(ColumnItem))] [Rule("<OrderList> ::= <Order> ~',' <OrderList>", typeof(OrderExpression))] [Rule("<ExpressionList> ::= <Expression> ~',' <ExpressionList>", typeof(Expression))] [Rule("<XmlDirectiveList> ::= ~',' <XmlDirective> <XmlDirectiveList>", typeof(XmlDirective))] [Rule("<UpdateItemList> ::= <UpdateItem> ~',' <UpdateItemList>", typeof(UpdateItem))] [Rule("<CaseWhenExpressionList> ::= <CaseWhenExpression> <CaseWhenExpressionList>", typeof(CaseWhen<Expression>))] [Rule("<CaseWhenPredicateList> ::= <CaseWhenPredicate> <CaseWhenPredicateList>", typeof(CaseWhen<Predicate>))] [Rule("<XmlNamespaceList> ::= <XmlNamespace> ~',' <XmlNamespaceList>", typeof(XmlNamespace))] [Rule("<TableHintList> ::= <TableHint> ~',' <TableHintList>", typeof(TableHint))] [Rule("<IndexValueList> ::= IntegerLiteral ~',' <IndexValueList>", typeof(IntegerLiteral))] [Rule("<MergeWhenMatchedList> ::= <MergeWhenMatched> <MergeWhenMatchedList>", typeof(MergeWhenMatched))] [Rule("<ValuesList> ::= ~'(' <ExpressionList> ~')' ~',' <ValuesList>", typeof(Sequence<Expression>))] [Rule("<QueryHintOptionList> ::= <QueryHintOption> ~',' <QueryHintOptionList>", typeof(QueryHintOption))] [Rule("<VariableNameList> ::= <VariableName> ~',' <VariableNameList>", typeof(VariableName))] [Rule("<RaiserrorOptionList> ::= <RaiserrorOption> ~',' <RaiserrorOptionList>", typeof(UnreservedKeyword))] public Sequence(T item, Sequence<T> next) { if (next != null) { if (next.Item != null) { this.next = next; } else { Debug.Assert(next.Next == null); } } this.item = item; } public T Item { get { return item; } } public Sequence<T> Next { get { return next; } } public IEnumerator<T> GetEnumerator() { for (Sequence<T> sequence = this; sequence != null; sequence = sequence.Next) { if (sequence.Item != null) { yield return sequence.Item; } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
gpl-3.0