repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
yaochangyu/sample.dotblog
WebAPI/Lab.PassingBSON/WebApplication1.UnitTest/UnitTest1.cs
2674
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Owin; namespace WebApplication1.UnitTest { [TestClass] public class UnitTest1 { private readonly string s_baseUri = "http://test:9999"; protected virtual async Task<HttpResponseMessage> GetAsync(string uri) { return await MsTestHook.Server.CreateRequest(uri) .GetAsync(); } protected virtual async Task<HttpResponseMessage> PostAsync<TModel>(string uri, TModel model) { return await MsTestHook.Server.CreateRequest(uri) .And(request => request.Content = new ObjectContent(typeof(TModel), model, new JsonMediaTypeFormatter())) .PostAsync(); } [TestMethod] public async Task Get_BSON() { var url = $"{this.s_baseUri}/api/values"; HttpClient client = MsTestHook.Server.HttpClient; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson")); //取得資料 var response = client.GetAsync(url).Result; //還原資料 var formatters = new MediaTypeFormatter[] {new BsonMediaTypeFormatter()}; var result = response.Content.ReadAsAsync<IEnumerable<string>>(formatters).Result; foreach (var item in result) { Console.WriteLine(item); } Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } [TestMethod] public async Task Post_BSON() { var url = $"{this.s_baseUri}/api/values"; var client = MsTestHook.Server.HttpClient; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson")); HttpContent content = new StringContent("哩來", Encoding.UTF8, "application/json"); var response = client.PostAsync(url, content).Result; Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } } public class Startup { public void Configuration(IAppBuilder app) { } } }
lgpl-3.0
oleneveu/SharpKit-SDK
Defs/Html/generated/html/HTMLDivElement.cs
3204
/******************************************************************************************************* This file was auto generated with the tool "WebIDLParser" Content was generated from IDL file: http://trac.webkit.org/browser/trunk/Source/WebCore/html/HTMLDivElement.idl PLEASE DO *NOT* MODIFY THIS FILE! This file will be overridden next generation. If you need changes: - All classes marked as "partial". Use the custom.cs in the root folder, to extend the classes. - or regenerate the project with the newest IDL files. - or modifiy the WebIDLParser tool itself. ******************************************************************************************************** Copyright (C) 2013 Sebastian Loncar, Web: http://loncar.de Copyright (C) 2009 Apple Inc. All Rights Reserved. MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************************************/ using System; namespace SharpKit.Html { using SharpKit.JavaScript; using SharpKit.Html.fileapi; using SharpKit.Html.html.shadow; using SharpKit.Html.html.track; using SharpKit.Html.inspector; using SharpKit.Html.loader.appcache; using SharpKit.Html.battery; using SharpKit.Html.filesystem; using SharpKit.Html.gamepad; using SharpKit.Html.geolocation; using SharpKit.Html.indexeddb; using SharpKit.Html.intents; using SharpKit.Html.mediasource; using SharpKit.Html.mediastream; using SharpKit.Html.navigatorcontentutils; using SharpKit.Html.networkinfo; using SharpKit.Html.notifications; using SharpKit.Html.proximity; using SharpKit.Html.quota; using SharpKit.Html.speech; using SharpKit.Html.vibration; using SharpKit.Html.webaudio; using SharpKit.Html.webdatabase; using SharpKit.Html.plugins; using SharpKit.Html.storage; using SharpKit.Html.svg; using SharpKit.Html.workers; [JsType(JsMode.Prototype, Export = false, PropertiesAsFields = true, NativeCasts = true, Name = "HTMLDivElement")] public partial class HtmlDivElement : HtmlElement { [JsMethod(OmitParanthesis = true, OmitNewOperator = true, Name = "document.createElement('div')")] public HtmlDivElement() {} public JsString align {get; set; } } }
lgpl-3.0
jontiefer/DotCoolControls
DotCoolControls.WinForms/Properties/AssemblyInfo.cs
1464
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DotCoolControls WinForm UI Controls")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tiferix Software")] [assembly: AssemblyProduct("Dot Cool Controls")] [assembly: AssemblyCopyright("Copyright © Jonathan Tiefer 2016-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6a3d5947-2fa4-476d-ba94-abc34a5afb9a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
lgpl-3.0
knowthelist/knowthelist
src/stackdisplay.cpp
2789
/* Copyright (C) 2014 Mario Stephan <mstephan@shared-files.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This 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/>. */ #include "stackdisplay.h" #include <QColor> #include <QPainter> #include <QStyleOption> class StackDisplayPrivate { public: int height; int width; int margin; int count; int indexSelected; int barHeight; QColor colorBars; }; StackDisplay::StackDisplay(QWidget* parent) : QWidget(parent) { p = new StackDisplayPrivate; p->colorBars.setRgb(200, 200, 200); p->count = 6; p->indexSelected = 1; p->barHeight = 3; p->margin = 8; } StackDisplay::~StackDisplay() { delete p; } void StackDisplay::resizeEvent(QResizeEvent* e) { Q_UNUSED(e); p->width = width(); p->height = height(); } void StackDisplay::setBarColor(QColor color) { p->colorBars = color; update(); } void StackDisplay::setCount(int value) { p->count = value; update(); } void StackDisplay::setSelected(int value) { p->indexSelected = value; update(); } void StackDisplay::setMargin(int value) { p->margin = value; } void StackDisplay::paintEvent(QPaintEvent*) { drawBars(); QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); } void StackDisplay::drawBars() { QPainter painter(this); painter.setPen(p->colorBars); if (p->count == 0) return; int space = (int)(p->height / p->count); int posY = 0; for (int i = 0; i < p->count; i++) { posY = posY + space; for (int j = 0; j < p->barHeight; j++) { //draw bars painter.drawLine(p->margin * 2, posY + j - p->barHeight, p->width - p->margin, posY + j - p->barHeight); } if (i == p->indexSelected) { //draw triancle for (int j = p->margin; j < p->margin + 5; j++) { painter.drawLine(j, posY - (p->margin + 5 - j) + 1 - p->barHeight, j, posY + (p->margin + 5 - j) - 1 - p->barHeight); } } } }
lgpl-3.0
arcualberta/Catfish
Catfish/wwwroot/assets/js/_public-facing/scripts/item-details-page-functions.js
2091
function submitDetailsWorkflowForm(suffix, successMessage, entityId, currentStatus, nextStatus, buttonName) { $("#item-details-result-message_" + suffix).hide(); $("#submissionDetailsForm_" + suffix).submit(function (event) { /* stop form from submitting normally */ event.preventDefault(); //Reguar expression for matching the variable name prefix up to the item's properties. var prefix = /^Blocks\[[0-9]+\]\.Item\.|^block.Item\./; var values = {}; var form = $('#submissionDetailsForm_' + suffix); //Handling text areas and input elements EXCLUDING checkboxes, radio buttons, and drop-down (select) menus values["entityId"] = entityId; values["buttonName"] = buttonName; values["currentStatus"] = currentStatus; values["status"] = nextStatus; /* get the action attribute from the <form action=""> element */ var $form = $(this), url = $form.attr('action'); /* Send the data using post with element id name and name2*/ var posting = $.post(url, values); var message = "Test Message"; posting.done(function (data) { $("#item-details-result-message_" + suffix).empty(); $('.modal-backdrop').remove(); console.log(data.success); if (data.success) { // $(".submission-result-message").addClass("alert alert-success"); message = successMessage !== "" ? successMessage : data.message; $("#item-details-result-message_" + suffix).append("<div class='alert alert-success' ></div>"); $("#submissionDetailsForm_" + suffix).hide();//[0].reset(); } else { $("#item-details-result-message_" + suffix).append("<div class='alert alert-danger' ></div>"); message = data.message; } $("#item-details-result-message_" + suffix + " div").text(message); $("#item-details-result-message_" + suffix).show(); }); }); }
lgpl-3.0
liuhongchao/GATE_Developer_7.0
src/gate/util/persistence/ResourcePersistence.java
3589
/* * Copyright (c) 1995-2012, The University of Sheffield. See the file * COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt * * This file is part of GATE (see http://gate.ac.uk/), and is free * software, licenced under the GNU Library General Public License, * Version 2, June 1991 (in the distribution as file licence.html, * and also available at http://gate.ac.uk/gate/licence.html). * * Valentin Tablan 25/10/2001 * * $Id: ResourcePersistence.java 15333 2012-02-07 13:18:33Z ian_roberts $ * */ package gate.util.persistence; import java.util.*; import gate.*; import gate.creole.*; import gate.persist.PersistenceException; import gate.util.NameBearer; /** * Holds the data needed to serialise and recreate a {@link Resource}. * This data is considered to be: the resource class name, the resource name, * the resource features and the resource initialistion parameters. */ class ResourcePersistence implements Persistence{ public void extractDataFromSource(Object source) throws PersistenceException{ if(! (source instanceof Resource)){ throw new UnsupportedOperationException( getClass().getName() + " can only be used for " + Resource.class.getName() + " objects!\n" + source.getClass().getName() + " is not a " + Resource.class.getName()); } Resource res = (Resource)source; resourceType = res.getClass().getName(); if(res instanceof NameBearer) resourceName = ((NameBearer)res).getName(); ResourceData rData = (ResourceData) Gate.getCreoleRegister().get(resourceType); if(rData == null) throw new PersistenceException( "Could not find CREOLE data for " + resourceType); ParameterList params = rData.getParameterList(); try{ //get the values for the init time parameters initParams = Factory.newFeatureMap(); //this is a list of lists Iterator parDisjIter = ((List)params.getInitimeParameters()).iterator(); while(parDisjIter.hasNext()){ Iterator parIter = ((List)parDisjIter.next()).iterator(); while(parIter.hasNext()){ Parameter parameter = (Parameter)parIter.next(); String parName = parameter.getName(); Object parValue = res.getParameterValue(parName); ((Map)initParams).put(parName, parValue); } } initParams = PersistenceManager.getPersistentRepresentation(initParams); //get the features if(res.getFeatures() != null){ features = Factory.newFeatureMap(); ((Map)features).putAll(res.getFeatures()); features = PersistenceManager.getPersistentRepresentation(features); } }catch(ResourceInstantiationException rie){ throw new PersistenceException(rie); } } public Object createObject()throws PersistenceException, ResourceInstantiationException { if(initParams != null) initParams = PersistenceManager.getTransientRepresentation(initParams); if(features != null) features = PersistenceManager.getTransientRepresentation(features); Resource res = Factory.createResource(resourceType, (FeatureMap)initParams, (FeatureMap)features,resourceName); return res; } protected String resourceType; protected String resourceName; protected Object initParams; protected Object features; static final long serialVersionUID = -3196664486112887875L; }
lgpl-3.0
pcolby/libqtaws
src/ecs/registercontainerinstanceresponse.cpp
4143
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "registercontainerinstanceresponse.h" #include "registercontainerinstanceresponse_p.h" #include <QDebug> #include <QNetworkReply> #include <QXmlStreamReader> namespace QtAws { namespace ECS { /*! * \class QtAws::ECS::RegisterContainerInstanceResponse * \brief The RegisterContainerInstanceResponse class provides an interace for ECS RegisterContainerInstance responses. * * \inmodule QtAwsECS * * <fullname>Amazon Elastic Container Service</fullname> * * Amazon Elastic Container Service (Amazon ECS) is a highly scalable, fast, container management service that makes it * easy to run, stop, and manage Docker containers on a cluster. You can host your cluster on a serverless infrastructure * that is managed by Amazon ECS by launching your services or tasks on AWS Fargate. For more control, you can host your * tasks on a cluster of Amazon Elastic Compute Cloud (Amazon EC2) instances that you * * manage> * * Amazon ECS makes it easy to launch and stop container-based applications with simple API calls, allows you to get the * state of your cluster from a centralized service, and gives you access to many familiar Amazon EC2 * * features> * * You can use Amazon ECS to schedule the placement of containers across your cluster based on your resource needs, * isolation policies, and availability requirements. Amazon ECS eliminates the need for you to operate your own cluster * management and configuration management systems or worry about scaling your management * * \sa EcsClient::registerContainerInstance */ /*! * Constructs a RegisterContainerInstanceResponse object for \a reply to \a request, with parent \a parent. */ RegisterContainerInstanceResponse::RegisterContainerInstanceResponse( const RegisterContainerInstanceRequest &request, QNetworkReply * const reply, QObject * const parent) : EcsResponse(new RegisterContainerInstanceResponsePrivate(this), parent) { setRequest(new RegisterContainerInstanceRequest(request)); setReply(reply); } /*! * \reimp */ const RegisterContainerInstanceRequest * RegisterContainerInstanceResponse::request() const { Q_D(const RegisterContainerInstanceResponse); return static_cast<const RegisterContainerInstanceRequest *>(d->request); } /*! * \reimp * Parses a successful ECS RegisterContainerInstance \a response. */ void RegisterContainerInstanceResponse::parseSuccess(QIODevice &response) { //Q_D(RegisterContainerInstanceResponse); QXmlStreamReader xml(&response); /// @todo } /*! * \class QtAws::ECS::RegisterContainerInstanceResponsePrivate * \brief The RegisterContainerInstanceResponsePrivate class provides private implementation for RegisterContainerInstanceResponse. * \internal * * \inmodule QtAwsECS */ /*! * Constructs a RegisterContainerInstanceResponsePrivate object with public implementation \a q. */ RegisterContainerInstanceResponsePrivate::RegisterContainerInstanceResponsePrivate( RegisterContainerInstanceResponse * const q) : EcsResponsePrivate(q) { } /*! * Parses a ECS RegisterContainerInstance response element from \a xml. */ void RegisterContainerInstanceResponsePrivate::parseRegisterContainerInstanceResponse(QXmlStreamReader &xml) { Q_ASSERT(xml.name() == QLatin1String("RegisterContainerInstanceResponse")); Q_UNUSED(xml) ///< @todo } } // namespace ECS } // namespace QtAws
lgpl-3.0
Techmentis/flinkiso-lite
app/Controller/NonConformingProductsMaterialsController.php
13200
<?php App::uses('AppController', 'Controller'); /** * NonConformingProductsMaterials Controller * * @property NonConformingProductsMaterial $NonConformingProductsMaterial */ class NonConformingProductsMaterialsController extends AppController { public function _get_system_table_id() { $this->loadModel('SystemTable'); $this->SystemTable->recursive = -1; $systemTableId = $this->SystemTable->find('first', array('conditions' => array('SystemTable.system_name' => $this->request->params['controller']))); return $systemTableId['SystemTable']['id']; } /** * index method * * @return void */ public function index() { $conditions = $this->_check_request(); $this->paginate = array('order' => array('NonConformingProductsMaterial.sr_no' => 'DESC'), 'conditions' => array($conditions)); $this->NonConformingProductsMaterial->recursive = 0; $this->set('nonConformingProductsMaterials', $this->paginate()); $this->_get_count(); } /** * adcanced_search method * Advanced search by - TGS * @return void */ public function advanced_search() { $conditions = array(); if ($this->request->query['keywords']) { $searchArray = array(); if ($this->request->query['strict_search'] == 0) { $searchKeys[] = $this->request->query['keywords']; } else { $searchKeys = explode(" ", $this->request->query['keywords']); } foreach ($searchKeys as $search_key): foreach ($this->request->query['search_fields'] as $search): if ($this->request->query['strict_search'] == 0) $searchArray[] = array('NonConformingProductsMaterial.' . $search => $search_key); else $searchArray[] = array('NonConformingProductsMaterial.' . $search . ' like ' => '%' . $search_key . '%'); endforeach; endforeach; if ($this->request->query['strict_search'] == 0) $conditions[] = array('and' => array('OR' => $searchArray)); else $conditions[] = array('or' => $searchArray); } if ($this->request->query['branch_list']) { foreach ($this->request->query['branch_list'] as $branches): $branchConditions[] = array('NonConformingProductsMaterial.branchid' => $branches); endforeach; if ($this->request->query['strict_search'] == 0) $conditions[] = array('and' => array('OR' => $branchConditions)); else $conditions[] = array('or' => $branchConditions); } if ($this->request->query['product_id'] != '-1') { $productConditions[] = array('NonConformingProductsMaterial.product_id' => $this->request->query['product_id']); if ($this->request->query['strict_search'] == 0) $conditions[] = array('and' => $productConditions); else $conditions[] = array('or' => $productConditions); } if ($this->request->query['material_id'] != '-1') { $materialConditions[] = array('NonConformingProductsMaterial.material_id' => $this->request->query['material_id']); if ($this->request->query['strict_search'] == 0) $conditions[] = array('and' => $materialConditions); else $conditions[] = array('or' => $materialConditions); } if ($this->request->query['capa_source_id'] != '-1') { $capaSourceConditions[] = array('NonConformingProductsMaterial.capa_source_id' => $this->request->query['capa_source_id']); if ($this->request->query['strict_search'] == 0) $conditions[] = array('and' => $capaSourceConditions); else $conditions[] = array('or' => $capaSourceConditions); } if ($this->request->query['corrective_preventive_action_id'] != '-1') { $capaConditions[] = array('NonConformingProductsMaterial.corrective_preventive_action_id' => $this->request->query['corrective_preventive_action_id']); if ($this->request->query['strict_search'] == 0) $conditions[] = array('and' => $capaConditions); else $conditions[] = array('or' => $capaConditions); } if (!$this->request->query['to-date']) $this->request->query['to-date'] = date('Y-m-d'); if ($this->request->query['from-date']) { $conditions[] = array('NonConformingProductsMaterial.created >' => date('Y-m-d h:i:s', strtotime($this->request->query['from-date'])), 'NonConformingProductsMaterial.created <' => date('Y-m-d h:i:s', strtotime($this->request->query['to-date']))); } $conditions = $this->advance_search_common($conditions); unset($this->request->query); if ($this->Session->read('User.is_mr') == 0) $onlyBranch = array('NonConformingProductsMaterial.branch_id' => $this->Session->read('User.branch_id')); if ($this->Session->read('User.is_view_all') == 0) $onlyOwn = array('NonConformingProductsMaterial.created_by' => $this->Session->read('User.id')); $conditions[] = array($onlyBranch, $onlyOwn); $this->NonConformingProductsMaterial->recursive = 0; $this->paginate = array('order' => array('NonConformingProductsMaterial.sr_no' => 'DESC'), 'conditions' => $conditions, 'NonConformingProductsMaterial.soft_delete' => 0); $this->set('nonConformingProductsMaterials', $this->paginate()); $this->render('index'); } /** * view method * * @throws NotFoundException * @param string $id * @return void */ public function view($id = null) { if (!$this->NonConformingProductsMaterial->exists($id)) { throw new NotFoundException(__('Invalid non conforming products material')); } $options = array('conditions' => array('NonConformingProductsMaterial.' . $this->NonConformingProductsMaterial->primaryKey => $id)); $this->set('nonConformingProductsMaterial', $this->NonConformingProductsMaterial->find('first', $options)); } /** * list method * * @return void */ public function lists() { $this->_get_count(); } /** * add_ajax method * * @return void */ public function add_ajax() { if ($this->_show_approvals()) { $this->set(array('showApprovals' => $this->_show_approvals())); } if ($this->request->is('post')) { $this->request->data['NonConformingProductsMaterial']['system_table_id'] = $this->_get_system_table_id(); $this->NonConformingProductsMaterial->create(); if ($this->NonConformingProductsMaterial->save($this->request->data)) { $this->Session->setFlash(__('The non conforming products material has been saved')); if ($this->_show_approvals()) $this->_save_approvals (); if ($this->_show_evidence() == true) $this->redirect(array('action' => 'view', $this->NonConformingProductsMaterial->id)); else $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The non conforming products material could not be saved. Please, try again.')); } } $materials = $this->NonConformingProductsMaterial->Material->find('list', array('conditions' => array('Material.publish' => 1, 'Material.soft_delete' => 0))); $products = $this->NonConformingProductsMaterial->Product->find('list', array('conditions' => array('Product.publish' => 1, 'Product.soft_delete' => 0))); $capaSources = $this->NonConformingProductsMaterial->CapaSource->find('list', array('conditions' => array('CapaSource.publish' => 1, 'CapaSource.soft_delete' => 0))); $correctivePreventiveActions = $this->NonConformingProductsMaterial->CorrectivePreventiveAction->find('list', array('conditions' => array('CorrectivePreventiveAction.publish' => 1, 'CorrectivePreventiveAction.soft_delete' => 0))); $this->set(compact('materials', 'products', 'capaSources', 'correctivePreventiveActions')); } /** * * * @throws NotFoundException * @param string $id * @return void */ public function edit($id = null) { if (!$this->NonConformingProductsMaterial->exists($id)) { throw new NotFoundException(__('Invalid non conforming products material')); } if ($this->_show_approvals()) { $this->set(array('showApprovals' => $this->_show_approvals())); } if ($this->request->is('post') || $this->request->is('put')) { $this->request->data['NonConformingProductsMaterial']['system_table_id'] = $this->_get_system_table_id(); if ($this->NonConformingProductsMaterial->save($this->request->data)) { $this->Session->setFlash(__('The non conforming products material has been saved')); if ($this->_show_approvals()) $this->_save_approvals (); if ($this->_show_evidence() == true) $this->redirect(array('action' => 'view', $id)); else $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The non conforming products material could not be saved. Please, try again.')); } } else { $options = array('conditions' => array('NonConformingProductsMaterial.' . $this->NonConformingProductsMaterial->primaryKey => $id)); $this->request->data = $this->NonConformingProductsMaterial->find('first', $options); } $materials = $this->NonConformingProductsMaterial->Material->find('list', array('conditions' => array('Material.publish' => 1, 'Material.soft_delete' => 0))); $products = $this->NonConformingProductsMaterial->Product->find('list', array('conditions' => array('Product.publish' => 1, 'Product.soft_delete' => 0))); $capaSources = $this->NonConformingProductsMaterial->CapaSource->find('list', array('conditions' => array('CapaSource.publish' => 1, 'CapaSource.soft_delete' => 0))); $correctivePreventiveActions = $this->NonConformingProductsMaterial->CorrectivePreventiveAction->find('list', array('conditions' => array('CorrectivePreventiveAction.publish' => 1, 'CorrectivePreventiveAction.soft_delete' => 0))); $this->set(compact('materials', 'products', 'capaSources', 'correctivePreventiveActions')); } /** * approve method * * @throws NotFoundException * @param string $id * @return void */ public function approve($id = null, $approvalId = null) { if (!$this->NonConformingProductsMaterial->exists($id)) { throw new NotFoundException(__('Invalid non conforming products material')); } $this->loadModel('Approval'); if (!$this->Approval->exists($approvalId)) { throw new NotFoundException(__('Invalid approval id')); } $approval = $this->Approval->read(null, $approvalId); $this->set('same', $approval['Approval']['user_id']); if ($this->_show_approvals()) { $this->set(array('showApprovals' => $this->_show_approvals())); } if ($this->request->is('post') || $this->request->is('put')) { if ($this->NonConformingProductsMaterial->save($this->request->data)) { $this->Session->setFlash(__('The non conforming products material has been saved.')); if ($this->_show_approvals()) $this->_save_approvals (); } else { $this->Session->setFlash(__('The non conforming products material could not be saved. Please, try again.')); } } else { $options = array('conditions' => array('NonConformingProductsMaterial.' . $this->NonConformingProductsMaterial->primaryKey => $id)); $this->request->data = $this->NonConformingProductsMaterial->find('first', $options); } $materials = $this->NonConformingProductsMaterial->Material->find('list', array('conditions' => array('Material.publish' => 1, 'Material.soft_delete' => 0))); $products = $this->NonConformingProductsMaterial->Product->find('list', array('conditions' => array('Product.publish' => 1, 'Product.soft_delete' => 0))); $capaSources = $this->NonConformingProductsMaterial->CapaSource->find('list', array('conditions' => array('CapaSource.publish' => 1, 'CapaSource.soft_delete' => 0))); $correctivePreventiveActions = $this->NonConformingProductsMaterial->CorrectivePreventiveAction->find('list', array('conditions' => array('CorrectivePreventiveAction.publish' => 1, 'CorrectivePreventiveAction.soft_delete' => 0))); $this->set(compact('materials', 'products', 'capaSources', 'correctivePreventiveActions')); } }
lgpl-3.0
anthonybennett/anthonybennett.github.io
level-up-your-js/js/script.js
1595
(function(win) { // Save some typing below. var mu = win.mu; // Define slides. var slides = { init: function() { // Find all sections. Start on first. this.els = mu.findAll("section"); this.count = this.els.length; this.index = 0; }, hide: function() { // Hide current element. mu.css(this.els[this.index], { display: "none" }); }, show: function() { // Force GIFs to start from the beginning. var bg = mu.find(this.els[this.index], "div.bg"), bgi = win.getComputedStyle(bg).backgroundImage.replace( /(\?rand=[^\)]+)?\)/, ("?rand=" + Math.random() + ")")); mu.css(bg, { backgroundImage: bgi }); // Show current element. mu.css(this.els[this.index], { display: "block" }); }, next: function() { // Hide current. this.hide(); // Show next (wrap around). this.index = ((this.index + 1) % this.count); this.show(); }, prev: function() { // Hide current. this.hide(); // Show previous (wrap around). this.index = ((this.index || this.count) - 1); this.show(); } }; // On DOM ready. mu.ready(function() { // Initialize slides. slides.init(); // Left/right arrow keys go to previous/next slide. mu.on(document, "keyup", function(e) { switch (e.which) { case 37: slides.prev(); break; case 39: slides.next(); break; } }); // Left click goes to next slide. mu.on(document, "click", function() { slides.next(); }); // Right click goes to previous slide. mu.on(document, "contextmenu", function(e) { slides.prev(); e.preventDefault(); }); }); }(this));
lgpl-3.0
tobato/FastDFS_Client
src/test/java/com/github/tobato/fastdfs/domain/fdfs/TrackerAddressHolderTest.java
1154
package com.github.tobato.fastdfs.domain.fdfs; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * TrackerAddressHolder测试 * * @author tobato */ public class TrackerAddressHolderTest { /** * 日志 */ protected static Logger LOGGER = LoggerFactory.getLogger(TrackerAddressHolderTest.class); @Test public void testCanTryToConnect() throws InterruptedException { TrackerAddressHolder holder = new TrackerAddressHolder(new InetSocketAddress(9988)); assertTrue(holder.isAvailable()); //连接设置为无效 holder.setInActive(); assertFalse(holder.isAvailable()); // 验证超时10秒以后,可以重新尝试连接 boolean canRetry = false; int i = 0; while (!canRetry) { i = i + 1; Thread.sleep(2000); canRetry = holder.canTryToConnect(10); LOGGER.debug("第{}次尝试重新连接..可尝试状态={}", i, canRetry); } } }
lgpl-3.0
svn2github/dynamicreports-jasper
dynamicreports-core/src/main/java/net/sf/dynamicreports/report/builder/expression/ValueExpression.java
2075
/** * DynamicReports - Free Java reporting library for creating reports dynamically * * Copyright (C) 2010 - 2015 Ricardo Mariaca * http://www.dynamicreports.org * * This file is part of DynamicReports. * * DynamicReports 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. * * DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.dynamicreports.report.builder.expression; import net.sf.dynamicreports.report.base.expression.AbstractSimpleExpression; import net.sf.dynamicreports.report.constant.Constants; import net.sf.dynamicreports.report.definition.ReportParameters; import org.apache.commons.lang3.Validate; /** * @author Ricardo Mariaca (r.mariaca@dynamicreports.org) */ public class ValueExpression<T> extends AbstractSimpleExpression<T> { private static final long serialVersionUID = Constants.SERIAL_VERSION_UID; private T value; private Class<? super T> valueClass; @SuppressWarnings("unchecked") public ValueExpression(T value) { Validate.notNull(value, "value must not be null"); this.value = value; this.valueClass = (Class<? super T>) value.getClass(); } public ValueExpression(T value, Class<? super T> valueClass) { Validate.notNull(valueClass, "valueClass must not be null"); this.value = value; this.valueClass = valueClass; } @Override public T evaluate(ReportParameters reportParameters) { return value; } @Override public Class<? super T> getValueClass() { return valueClass; } }
lgpl-3.0
almondtools/comtemplate
src/main/java/net/amygdalum/comtemplate/engine/TemplateGroupException.java
817
package net.amygdalum.comtemplate.engine; import static java.util.stream.Collectors.joining; import java.util.List; public class TemplateGroupException extends ComtemplateException { private String name; private String fileName; private List<String> messages; public TemplateGroupException(String name, List<String> messages) { this.name = name; this.messages = messages; } public void setFileName(String fileName) { this.fileName = fileName; } public List<String> getMessages() { return messages; } @Override public String getMessage() { return "parsing template group <" + name + ">" + getContext() + " failed:\n" + messages.stream().collect(joining("\n- ", "- ", "")); } private String getContext() { return fileName != null ? " in file '" + fileName + "'" : ""; } }
lgpl-3.0
Godin/sonar
server/sonar-main/src/test/java/org/sonar/application/cluster/ClusterProcessTest.java
1458
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application.cluster; import org.junit.Test; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; public class ClusterProcessTest { @Test public void test_equality() { ClusterProcess clusterProcess = new ClusterProcess("A", ProcessId.WEB_SERVER); assertThat(clusterProcess) .isNotEqualTo(null) .isEqualTo(clusterProcess) .isNotEqualTo(new ClusterProcess("B", ProcessId.WEB_SERVER)) .isNotEqualTo(new ClusterProcess("A", ProcessId.ELASTICSEARCH)) .isEqualTo(new ClusterProcess("A", ProcessId.WEB_SERVER)); } }
lgpl-3.0
TheAnswer/FirstTest
bin/scripts/creatures/objects/tatooine/creatures/wildDuneBoar.lua
4733
--Copyright (C) 2008 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. wildDuneBoar = Creature:new { objectName = "wildDuneBoar", -- Lua Object Name creatureType = "ANIMAL", gender = "", speciesName = "wild_dune_boar", stfName = "mob/creature_names", objectCRC = 277596046, socialGroup = "Zucca Boar", level = 50, combatFlags = ATTACKABLE_FLAG + ENEMY_FLAG + AGGRESSIVE_FLAG, healthMax = 12000, healthMin = 10000, strength = 0, constitution = 0, actionMax = 12000, actionMin = 10000, quickness = 0, stamina = 0, mindMax = 12000, mindMin = 10000, focus = 0, willpower = 0, height = 1, -- Size of creature armor = 1, -- 0 = None; 1 = Light; 2 = Medium; 3 = Heavy kinetic = 10, energy = 40, electricity = 0, stun = -1, blast = 10, heat = 0, cold = 0, acid = 0, lightsaber = 0, accuracy = 0, healer = 0, pack = 1, herd = 0, stalker = 0, killer = 1, ferocity = 0, aggressive = 1, invincible = 0, meleeDefense = 1, rangedDefense = 1, attackCreatureOnSight = "", -- Enter socialGroups weapon = "object/weapon/creature/shared_creature_default_weapon.iff", -- File path to weapon -> object\xxx\xxx\xx weaponName = "Creature Defualt", -- Name ex. 'a Vibrolance' weaponTemp = "creature_default_weapon", -- Weapon Template ex. 'lance_vibrolance' weaponClass = "UnarmedMeleeWeapon", -- Weapon Class ex. 'PolearmMeleeWeapon' weaponEquipped = 0, weaponMinDamage = 395, weaponMaxDamage = 500, weaponAttackSpeed = 2, weaponDamageType = "KINETIC", -- ELECTRICITY, KINETIC, etc weaponArmorPiercing = "NONE", -- LIGHT, NONE, MEDIUM, HEAVY alternateWeapon = "", -- File path to weapon -> object\xxx\xxx\xx alternateWeaponName = "", -- Name ex. 'a Vibrolance' alternateWeaponTemp = "", -- Weapon Template ex. 'lance_vibrolance' alternateWeaponClass = "", -- Weapon Class ex. 'PolearmMeleeWeapon' alternateWeaponEquipped = 0, alternateWeaponMinDamage = 0, alternateWeaponMaxDamage = 0, alternateWeaponAttackSpeed = 0, alternateWeaponDamageType = "", -- ELECTRICITY, KINETIC, etc alternateWeaponArmorPiercing = "", -- LIGHT, NONE, MEDIUM, HEAVY internalNPCDamageModifier = 0.3, -- Damage Modifier to other NPC's lootGroup = "0", -- Group it belongs to for loot tame = 0, datapadItemCRC = 0, mountCRC = 0, mountSpeed = 0, mountAcceleration = 0, milk = 0, boneType = "bone_mammal_tatooine", boneMax = 75, hideType = "hide_leathery_tatooine", hideMax = 80, meatType = "meat_herbivore_tatooine", meatMax = 90, skills = { "zuccaBoarAttack1", "zuccaBoarAttack3" }, -- skills = { " Stun attack", " Intimidation attack", "" } respawnTimer = 60, behaviorScript = "", -- Link to the behavior script for this object } Creatures:addCreature(wildDuneBoar, 277596046) -- Add to Global Table
lgpl-3.0
muk-it/muk_dms
muk_dms_field/fields/binary.py
3916
################################################################################### # # Copyright (c) 2017-2019 MuK IT GmbH. # # This file is part of MuK Documents Field # (see https://mukit.at). # # 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/>. # ################################################################################### import re import logging from odoo import _ from odoo import models, api, fields from odoo.tools import pg_varchar, ustr, human_size _logger = logging.getLogger(__name__) class DocumentBinary(fields.Field): type = 'document_binary' column_type = None _slots = { 'prefetch': False, 'filename': False, 'directory': False, 'context_dependent': True, } def read(self, records): domain = [ ('reference_model', '=', records._name), ('reference_field', '=', self.name), ('reference_id', 'in', records.ids), ] cache = records.env.cache model = records.env['muk_dms.file'].sudo() files = model.with_context(active_test=False).search(domain) file_values = {file.reference_id: file.content for file in files} for record in records: cache.set(record, self, file_values.get(record.id, False)) def create(self, record_values): if not record_values: return env = record_values[0][0].env model = env['muk_dms.file'].sudo() with env.norecompute(): for record, value in record_values: if value: model.create([{ 'name': self.filename(record) if callable(self.filename) else self.filename, 'directory': self.directory(record) if callable(self.directory) else self.directory, 'reference_model': record._name, 'reference_field': self.name, 'reference_id': record.id, 'content': value, } for record, value in record_values if value ]) def write(self, records, value): files = records.env['muk_dms.file'].sudo().search([ ('reference_model', '=', records._name), ('reference_field', '=', self.name), ('reference_id', 'in', records.ids), ]) with records.env.norecompute(): if value: files.write({'content': value}) existing_records = records.browse(files.mapped('reference_id')) if len(existing_records) < len(records): files.create([{ 'name': self.filename(record) if callable(self.filename) else self.filename, 'directory': self.directory(record) if callable(self.directory) else self.directory, 'reference_model': record._name, 'reference_field': self.name, 'reference_id': record.id, 'content': value, } for record in (records - existing_records) ]) else: files.unlink()
lgpl-3.0
metaindu/MetaphysicsIndustries.Solus
MetaphysicsIndustries.Solus.Test/ExpressionsT/DerivativeOfVariableT/ResultTest.cs
1481
/* * MetaphysicsIndustries.Solus * Copyright (C) 2006-2021 Metaphysics Industries, Inc., Richard Sartor * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA * */ using System; using MetaphysicsIndustries.Solus.Expressions; using NUnit.Framework; namespace MetaphysicsIndustries.Solus.Test.ExpressionsT.DerivativeOfVariableT { [TestFixture] public class ResultTest { [Test] public void ResultIsNotImplemented() { // given var expr = new DerivativeOfVariable("u", "v"); var env = new SolusEnvironment(); // when Assert.Throws<NotImplementedException>( () => { var result = expr.Result; }); } } }
lgpl-3.0
sikachu/jasperreports
demo/samples/openflashchart/src/net/sf/jasperreports/components/ofc/ChartXlsHandler.java
2371
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2013 Jaspersoft Corporation. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.components.ofc; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.JRPrintText; import net.sf.jasperreports.engine.JRRuntimeException; import net.sf.jasperreports.engine.export.GenericElementXlsHandler; import net.sf.jasperreports.engine.export.JRExporterGridCell; import net.sf.jasperreports.engine.export.JRGridLayout; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterContext; /** * @author Teodor Danciu (teodord@users.sourceforge.net) * @version $Id: ChartXlsHandler.java 5876 2013-01-07 19:05:05Z teodord $ */ public class ChartXlsHandler extends BaseChartHandler implements GenericElementXlsHandler { public void exportElement( JRXlsExporterContext exporterContext, JRGenericPrintElement element, JRExporterGridCell gridCell, int colIndex, int rowIndex, int emptyCols, int yCutsRow, JRGridLayout layout ) { JRXlsExporter exporter = (JRXlsExporter)exporterContext.getExporter(); JRExporterGridCell newGridCell = getGridCellReplacement(exporterContext, element, gridCell); try { exporter.exportText((JRPrintText)newGridCell.getElement(), newGridCell, colIndex, rowIndex); } catch (JRException e) { throw new JRRuntimeException(e); } } }
lgpl-3.0
mupif/mupif
examples/ssh/_test_ssh_server.py
1389
#!/usr/bin/env python3 import asyncio, asyncssh, sys, argparse, os.path, logging thisDir=os.path.dirname(os.path.abspath(__file__)) parser=argparse.ArgumentParser('Run testing SSH server') parser.add_argument('--port',default=2024,type=int,help='Listening server port') args=parser.parse_args(sys.argv[1:]) log=logging.getLogger('mupif-ssh-server') class MupifTestSSHServer(asyncssh.SSHServer): def password_auth_supported(self): return False def public_key_auth_supported(self): return True # no shell, command, sftp, scp, … def session_requested(self): return False # allow forward tunnel def connection_requested(self,dhost,dport,ohost,oport): log.info(f'connection {ohost}:{oport} → {dhost}:{dport} requested') return True # allow reverse tunnel def server_requested(self,lhost,lport): log.info(f'server {lhost}:{lport} requested') return True async def start_server(): await asyncssh.create_server(MupifTestSSHServer, '', args.port, server_host_keys=[thisDir+'/test_ssh_server_rsa_key'], authorized_client_keys=thisDir+'/test_ssh_client_rsa_key.pub') loop = asyncio.get_event_loop() try: loop.run_until_complete(start_server()) except (OSError, asyncssh.Error) as exc: sys.exit('SSH server failed: ' + str(exc)) loop.run_forever()
lgpl-3.0
NOVA-Team/NOVA-Core
modules/core/src/test/java/nova/core/block/component/BlockPropertyTest.java
3873
/* * Copyright (c) 2017 NOVA, All rights reserved. * This library is free software, licensed under GNU Lesser General Public License version 3 * * This file is part of NOVA. * * NOVA 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. * * NOVA 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 NOVA. If not, see <http://www.gnu.org/licenses/>. */ package nova.core.block.component; import nova.core.sound.Sound; import org.junit.Test; import static nova.testutils.NovaAssertions.assertThat; /** * @author ExE Boss */ public class BlockPropertyTest { @Test public void testHardness() { BlockProperty.Hardness hardness = new BlockProperty.Hardness(); assertThat(hardness.getHardness()).isEqualTo(1.0); hardness.setHardness(10.0); assertThat(hardness.getHardness()).isEqualTo(10.0); } @Test public void testResistance() { BlockProperty.Resistance resistance = new BlockProperty.Resistance(); assertThat(resistance.getResistance()).isEqualTo(1.0); resistance.setResistance(10.0); assertThat(resistance.getResistance()).isEqualTo(10.0); } @Test public void testBlockSound() { BlockProperty.BlockSound sound = new BlockProperty.BlockSound(); sound.setBlockSound(BlockProperty.BlockSound.BlockSoundTrigger.BREAK, new Sound("test", "break")); sound.setBlockSound(BlockProperty.BlockSound.BlockSoundTrigger.PLACE, new Sound("test", "place")); sound.setBlockSound(BlockProperty.BlockSound.BlockSoundTrigger.WALK, new Sound("test", "walk")); sound.setBlockSound(BlockProperty.BlockSound.BlockSoundTrigger.CUSTOM_TRIGGER, new Sound("test", "custom")); sound.setCustomBlockSound("test:custom", new Sound("test", "custom")); assertThat(sound.getSound(BlockProperty.BlockSound.BlockSoundTrigger.BREAK)).contains(new Sound("test", "break")); assertThat(sound.getSound(BlockProperty.BlockSound.BlockSoundTrigger.PLACE)).contains(new Sound("test", "place")); assertThat(sound.getSound(BlockProperty.BlockSound.BlockSoundTrigger.WALK)).contains(new Sound("test", "walk")); assertThat(sound.getSound(BlockProperty.BlockSound.BlockSoundTrigger.CUSTOM_TRIGGER)).isEmpty(); assertThat(sound.getCustomSound("test:custom")).contains(new Sound("test", "custom")); } @Test public void testOpacity() { BlockProperty.Opacity opacity = new BlockProperty.Opacity().setOpaque(); assertThat(opacity.getOpacity()).isEqualTo(1.0); assertThat(opacity.isOpaque()).isTrue(); assertThat(opacity.isTransparent()).isFalse(); opacity.setTransparent(); assertThat(opacity.getOpacity()).isEqualTo(0.0); assertThat(opacity.isOpaque()).isFalse(); assertThat(opacity.isTransparent()).isTrue(); opacity.setOpacity(0.5); assertThat(opacity.getOpacity()).isEqualTo(0.5); assertThat(opacity.isOpaque()).isFalse(); assertThat(opacity.isTransparent()).isTrue(); opacity.setOpacity(-0.5); assertThat(opacity.getOpacity()).isEqualTo(0.0); assertThat(opacity.isOpaque()).isFalse(); assertThat(opacity.isTransparent()).isTrue(); opacity.setOpacity(1.5); assertThat(opacity.getOpacity()).isEqualTo(1.0); assertThat(opacity.isOpaque()).isTrue(); assertThat(opacity.isTransparent()).isFalse(); } @Test public void testReplaceable() { BlockProperty.Replaceable replaceable = new BlockProperty.Replaceable(); assertThat(replaceable.isReplaceable()).isTrue(); replaceable.setReplaceable(() -> false); assertThat(replaceable.isReplaceable()).isFalse(); } }
lgpl-3.0
lbndev/sonarqube
server/sonar-server/src/main/java/org/sonar/server/platform/BackendCleanup.java
8387
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform; import com.google.common.collect.ImmutableMap; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.Locale; import java.util.Map; import java.util.Optional; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.log.Loggers; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.version.SqTables; import org.sonar.server.component.index.ComponentIndexDefinition; import org.sonar.server.es.BulkIndexer; import org.sonar.server.es.EsClient; import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.measure.index.ProjectMeasuresIndexDefinition; import org.sonar.server.property.InternalProperties; import org.sonar.server.view.index.ViewIndexDefinition; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; @ServerSide public class BackendCleanup { private static final String[] ANALYSIS_TABLES = { "authors", "duplications_index", "events", "issues", "issue_changes", "manual_measures", "notifications", "project_links", "project_measures", "projects", "snapshots", "file_sources" }; private static final String[] RESOURCE_RELATED_TABLES = { "group_roles", "user_roles", "properties" }; private static final Map<String, TableCleaner> TABLE_CLEANERS = ImmutableMap.of( "organizations", BackendCleanup::truncateOrganizations, "users", BackendCleanup::truncateUsers, "internal_properties", BackendCleanup::truncateInternalProperties, "schema_migrations", BackendCleanup::truncateSchemaMigrations); private final EsClient esClient; private final DbClient dbClient; public BackendCleanup(EsClient esClient, DbClient dbClient) { this.esClient = esClient; this.dbClient = dbClient; } public void clearAll() { clearDb(); clearIndexes(); } public void clearDb() { try (DbSession dbSession = dbClient.openSession(false); Connection connection = dbSession.getConnection(); Statement ddlStatement = connection.createStatement()) { for (String tableName : SqTables.TABLES) { Optional.ofNullable(TABLE_CLEANERS.get(tableName)) .orElse(BackendCleanup::truncateDefault) .clean(tableName, ddlStatement, connection); } } catch (Exception e) { throw new IllegalStateException("Fail to clear db", e); } } public void clearIndexes() { Loggers.get(getClass()).info("Truncate Elasticsearch indices"); try { esClient.prepareClearCache().get(); for (String index : esClient.prepareState().get().getState().getMetaData().concreteAllIndices()) { clearIndex(index); } } catch (Exception e) { throw new IllegalStateException("Unable to clear indexes", e); } } /** * Reset data in order to to be in same state as a fresh installation (but without having to drop db and restart the server). * * Please be careful when updating this method as it's called by Orchestrator. */ public void resetData() { try (DbSession dbSession = dbClient.openSession(false); Connection connection = dbSession.getConnection()) { truncateAnalysisTables(connection); deleteManualRules(connection); truncateInternalProperties(null, null, connection); truncateUsers(null, null, connection); truncateOrganizations(null, null, connection); } catch (SQLException e) { throw new IllegalStateException("Fail to reset data", e); } clearIndex(IssueIndexDefinition.INDEX_TYPE_ISSUE.getIndex()); clearIndex(ViewIndexDefinition.INDEX_TYPE_VIEW.getIndex()); clearIndex(ProjectMeasuresIndexDefinition.INDEX_TYPE_PROJECT_MEASURES.getIndex()); clearIndex(ComponentIndexDefinition.INDEX_TYPE_COMPONENT.getIndex()); } private static void truncateAnalysisTables(Connection connection) throws SQLException { try (Statement statement = connection.createStatement()) { // Clear inspection tables for (String table : ANALYSIS_TABLES) { statement.execute("TRUNCATE TABLE " + table.toLowerCase()); // commit is useless on some databases connection.commit(); } // Clear resource related tables for (String table : RESOURCE_RELATED_TABLES) { statement.execute("DELETE FROM " + table + " WHERE resource_id IS NOT NULL"); connection.commit(); } } } private static void deleteManualRules(Connection connection) throws SQLException { try (PreparedStatement statement = connection.prepareStatement("DELETE FROM rules WHERE rules.plugin_name='manual'")) { statement.execute(); // commit is useless on some databases connection.commit(); } } /** * Completely remove a index with all types */ public void clearIndex(String indexName) { BulkIndexer.delete(esClient, indexName, esClient.prepareSearch(indexName).setQuery(matchAllQuery())); } @FunctionalInterface private interface TableCleaner { void clean(String tableName, Statement ddlStatement, Connection connection) throws SQLException; } private static void truncateDefault(String tableName, Statement ddlStatement, Connection connection) throws SQLException { ddlStatement.execute("TRUNCATE TABLE " + tableName.toLowerCase(Locale.ENGLISH)); // commit is useless on some databases connection.commit(); } /** * Default organization must never be deleted */ private static void truncateOrganizations(String tableName, Statement ddlStatement, Connection connection) throws SQLException { try (PreparedStatement preparedStatement = connection.prepareStatement("delete from organizations where kee <> ?")) { preparedStatement.setString(1, "default-organization"); preparedStatement.execute(); // commit is useless on some databases connection.commit(); } } /** * User admin must never be deleted. */ private static void truncateUsers(String tableName, Statement ddlStatement, Connection connection) throws SQLException { try (PreparedStatement preparedStatement = connection.prepareStatement("delete from users where login <> ?")) { preparedStatement.setString(1, "admin"); preparedStatement.execute(); // commit is useless on some databases connection.commit(); } // "admin" is not flagged as root by default try (PreparedStatement preparedStatement = connection.prepareStatement("update users set is_root=?")) { preparedStatement.setBoolean(1, false); preparedStatement.execute(); // commit is useless on some databases connection.commit(); } } /** * Internal property {@link InternalProperties#DEFAULT_ORGANIZATION} must never be deleted. */ private static void truncateInternalProperties(String tableName, Statement ddlStatement, Connection connection) throws SQLException { try (PreparedStatement preparedStatement = connection.prepareStatement("delete from internal_properties where kee <> ?")) { preparedStatement.setString(1, InternalProperties.DEFAULT_ORGANIZATION); preparedStatement.execute(); // commit is useless on some databases connection.commit(); } } /** * Data in SCHEMA_MIGRATIONS table is inserted when DB is created and should not be altered afterwards. */ private static void truncateSchemaMigrations(String tableName, Statement ddlStatement, Connection connection) throws SQLException { // do nothing } }
lgpl-3.0
Bradsta/NewtonsHeist
Plugins/CustomGravityPlugin/Intermediate/Build/Win32/UE4/Development/CustomGravityPlugin/Module.CustomGravityPlugin.cpp
2000
// This file is automatically generated at compile-time to include some subset of the user-created cpp files. #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\CustomGravityPluginPrivatePCH.h" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\Actors\CustomPhysicsActor.cpp" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\Actors\PlanetActor.cpp" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\Components\CustomGravityComponent.cpp" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\Components\CustomMovementComponent.cpp" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\CustomGravityPlugin.cpp" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\Objects\CustomGravityManager.cpp" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\Pawns\CustomPawn.cpp" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\Pawns\FirstPersonCharacter.cpp" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\Pawns\PhysicsBallPawn.cpp" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\Pawns\ThirdPersonBall.cpp" #include "C:\Users\Brad\Documents\Unreal Projects\Newtons-Heist\Plugins\CustomGravityPlugin\Source\CustomGravityPlugin\Private\Pawns\ThirdPersonCharacter.cpp"
lgpl-3.0
openmag/mag-android0.3
com_anheinno_android_libs/src/com/anheinno/android/libs/mag/MAGTieredSelect.java
1615
/** * MAGTieredSelect.java * * Copyright 2007-2011 anhe. */ package com.anheinno.android.libs.mag; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.view.View; /** * 2011-2-9 * * MAGTieredselect是让用户用从多个关联的下拉列表组中选择一个选项的输入组件,关联是指选定第一个选项后,第二个下拉列表的选项会跟随变化。 * MAGTieredselect的呈现形式为提示文字后跟多个。<br> * * @author 安和创新科技(北京)有限公司 * * @version 1.0 * */ public class MAGTieredSelect extends MAGInputBase { private JSONArray _options; public MAGTieredSelect() { super(); _options = null; } public boolean fromJSON(JSONObject o) { try { if(!checkMandatory(o, "_options")) { return false; } _options = o.getJSONArray("_options"); return super.fromJSON(o); } catch (JSONException e) { } return false; } public String fetchValue() { JSONArray data = ((MAGTieredSelectField)getField()).getSelectValue(); return data.toString(); } public MAGStyle getStyle() { return style(); } public boolean validate() { return true; } public View initField(Context context) { return new MAGTieredSelectField(context, this); } public JSONArray getOptions() { return _options; } public void updateField(View f) { MAGTieredSelectField tsf = (MAGTieredSelectField)f; tsf.updateUi(); } public void onShowUi() { MAGTieredSelectField tsf = (MAGTieredSelectField)getField(); tsf.updateUi(); } }
lgpl-3.0
opentraffic/analyst-ui
src/app/tangram-scene.js
8018
/* eslint no-unused-vars: ["error", { "vars": "local" }] */ /* global feature */ import config from '../config' import { STOPS, OUTLINE_STOPS } from '../lib/route-segments' import { getColorAtIndexInVec3 } from '../lib/color-ramps' const scene = { import: [ 'https://stvno.github.io/wereldbank/refill-style.zip', 'https://stvno.github.io/wereldbank/gray.zip' ], global: { 'sdk_mapzen_api_key': config.mapzen.apiKey, 'refSpeedComparisonEnabled': false, // this is set by the "compare" toggle in the UI 'refSpeedEnabled': false // TODO }, layers: { routes: { data: { source: 'routes' }, nonzero: { // filter: function() { // return feature.speed !== 0 && feature.speed !== null && typeof feature.speed !== 'undefined' // }, draw: { otRoads: { interactive: true, order: 500, width: STOPS, color: `function () { var colorIndex = 0 if (global.refSpeedComparisonEnabled) { var percent = feature.percentDiff colorIndex = percent === null ? 0 : percent >= 40 ? 10 / 15 : percent >= 30 ? 9 / 15 : percent >= 20 ? 8 / 15 : percent >= 10 ? 7 / 15 : percent >= 0 ? 6 / 15 : percent >= -10 ? 5 / 15 : percent >= -20 ? 4 / 15 : percent >= -30 ? 3 / 15 : percent >= -40 ? 2 / 15 : percent >= -50 ? 1 / 15 : 0 } else if (global.refSpeedEnabled) { var speed = feature.refSpeed // divide by an even multiple of 255 for lossless conversion to 8 bits colorIndex = speed >= 100 ? 10 / 15 : speed >= 90 ? 9 / 15 : speed >= 80 ? 8 / 15 : speed >= 70 ? 7 / 15 : speed >= 60 ? 6 / 15 : speed >= 50 ? 5 / 15 : speed >= 40 ? 4 / 15 : speed >= 30 ? 3 / 15 : speed >= 20 ? 2 / 15 : speed > 0 ? 1 / 15 : 0 } else { var speed = feature.speed // divide by an even multiple of 255 for lossless conversion to 8 bits colorIndex = speed >= 100 ? 10 / 15 : speed >= 90 ? 9 / 15 : speed >= 80 ? 8 / 15 : speed >= 70 ? 7 / 15 : speed >= 60 ? 6 / 15 : speed >= 50 ? 5 / 15 : speed >= 40 ? 4 / 15 : speed >= 30 ? 3 / 15 : speed >= 20 ? 2 / 15 : speed > 0 ? 1 / 15 : 0 } return [ colorIndex, feature.drive_on_right, feature.oneway ] }`, cap: 'round' } }, otOutlines: { draw: { otOutlines: { order: 499, width: OUTLINE_STOPS, color: `function () { var colorIndex = 0 if (global.refSpeedComparisonEnabled) { var percent = feature.percentDiff colorIndex = percent >= 40 ? 10 / 15 : percent >= 30 ? 9 / 15 : percent >= 20 ? 8 / 15 : percent >= 10 ? 7 / 15 : percent >= 0 ? 6 / 15 : percent >= -10 ? 5 / 15 : percent >= -20 ? 4 / 15 : percent >= -30 ? 3 / 15 : percent >= -40 ? 2 / 15 : percent >= -50 ? 1 / 15 : 0 } else if (global.refSpeedEnabled) { var speed = feature.refSpeed // divide by an even multiple of 255 for lossless conversion to 8 bits colorIndex = speed >= 100 ? 10 / 15 : speed >= 90 ? 9 / 15 : speed >= 80 ? 8 / 15 : speed >= 70 ? 7 / 15 : speed >= 60 ? 6 / 15 : speed >= 50 ? 5 / 15 : speed >= 40 ? 4 / 15 : speed >= 30 ? 3 / 15 : speed >= 20 ? 2 / 15 : speed > 0 ? 1 / 15 : 0 } else { var speed = feature.speed // divide by an even multiple of 255 for lossless conversion to 8 bits colorIndex = speed >= 100 ? 10 / 15 : speed >= 90 ? 9 / 15 : speed >= 80 ? 8 / 15 : speed >= 70 ? 7 / 15 : speed >= 60 ? 6 / 15 : speed >= 50 ? 5 / 15 : speed >= 40 ? 4 / 15 : speed >= 30 ? 3 / 15 : speed >= 20 ? 2 / 15 : speed > 0 ? 1 / 15 : 0 } return [ colorIndex, feature.drive_on_right, feature.oneway ] }` } } } // }, // zeroSpeed: { // filter: function () { // return feature.speed === 0 || feature.speed === null || typeof feature.speed === 'undefined' // }, // draw: { // lines: { // order: 400, // width: STOPS, // color: '#ccc', // outline: { // width: '.5px', // color: '#222' // }, // join: 'round' // } // } } } }, styles: { otRoads: { base: 'lines', texcoords: true, lighting: false, blend: 'inlay', shaders: { blocks: { color: ` // convert back to ints from 8-bit floats int i = int(floor(v_color.r * 15.)); if (i == 0) color.rgb = vec3(${getColorAtIndexInVec3(0)}); if (i == 1) color.rgb = vec3(${getColorAtIndexInVec3(1)}); if (i == 2) color.rgb = vec3(${getColorAtIndexInVec3(2)}); if (i == 3) color.rgb = vec3(${getColorAtIndexInVec3(3)}); if (i == 4) color.rgb = vec3(${getColorAtIndexInVec3(4)}); if (i == 5) color.rgb = vec3(${getColorAtIndexInVec3(5)}); if (i == 6) color.rgb = vec3(${getColorAtIndexInVec3(6)}); if (i == 7) color.rgb = vec3(${getColorAtIndexInVec3(7)}); if (i == 8) color.rgb = vec3(${getColorAtIndexInVec3(8)}); if (i == 9) color.rgb = vec3(${getColorAtIndexInVec3(9)}); if (i == 10) color.rgb = vec3(${getColorAtIndexInVec3(10)}); // draw each half-width if it's not a one-way street color.a = floor(v_texcoord.x*2.)+v_color.b; // color = vec4(v_color.b, 0, 0, .5); ` } } }, otOutlines: { base: 'lines', mix: 'otRoads', shaders: { blocks: { color: ` color = vec4(0.); // draw outline slightly wider for single lanes color.a = floor(v_texcoord.x*2.1)+v_color.b; ` } } } } } export function getInitialTangramScene () { return scene }
lgpl-3.0
desht/ScrollingMenuSign
src/main/java/me/desht/scrollingmenusign/listeners/SMSBlockListener.java
8700
package me.desht.scrollingmenusign.listeners; import me.desht.dhutils.DHUtilsException; import me.desht.dhutils.MiscUtil; import me.desht.dhutils.PermissionUtils; import me.desht.dhutils.block.BlockUtil; import me.desht.scrollingmenusign.*; import me.desht.scrollingmenusign.expector.ExpectSwitchAddition; import me.desht.scrollingmenusign.views.SMSGlobalScrollableView; import me.desht.scrollingmenusign.views.SMSView; import me.desht.scrollingmenusign.views.action.RepaintAction; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.block.*; import org.bukkit.material.Sign; public class SMSBlockListener extends SMSListenerBase { public SMSBlockListener(ScrollingMenuSign plugin) { super(plugin); } @EventHandler(ignoreCancelled = true) public void onBlockDamage(BlockDamageEvent event) { Block b = event.getBlock(); SMSInteractableBlock iBlock = plugin.getLocationManager().getInteractableAt(b.getLocation()); if (iBlock != null) { iBlock.processEvent(plugin, event); } } @EventHandler(ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { Block b = event.getBlock(); Player player = event.getPlayer(); SMSInteractableBlock iBlock = plugin.getLocationManager().getInteractableAt(b.getLocation()); if (plugin.getViewManager().getHeldMapView(player) != null) { // avoid breaking blocks while holding active map view (mainly for benefit of creative mode) event.setCancelled(true); if (iBlock != null && iBlock instanceof SMSView) { SMSView view = (SMSView) iBlock; view.update(view.getActiveMenu(player), new RepaintAction()); } } else if (iBlock != null) { iBlock.processEvent(plugin, event); } } @EventHandler(ignoreCancelled = true) public void onBlockPhysics(BlockPhysicsEvent event) { Block b = event.getBlock(); SMSInteractableBlock iBlock = plugin.getLocationManager().getInteractableAt(b.getLocation()); if (iBlock != null) { iBlock.processEvent(plugin, event); } } @EventHandler(ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event) { Player player = event.getPlayer(); if (plugin.responseHandler.isExpecting(player, ExpectSwitchAddition.class)) { ExpectSwitchAddition swa = plugin.responseHandler.getAction(player, ExpectSwitchAddition.class); swa.setLocation(event.getBlock().getLocation()); try { swa.handleAction(player); } catch (DHUtilsException e) { MiscUtil.errorMessage(player, e.getMessage()); } } } @EventHandler public void onSignChanged(SignChangeEvent event) { try { if (event.getLine(0).equals("[sms]")) { tryToActivateSign(event); } else if (event.getLine(0).equals("[smsred]")) { placeRedstoneControlSign(event); } else if (event.getLine(0).equals("[smstooltip]")) { placeTooltipSign(event); } } catch (DHUtilsException e) { MiscUtil.errorMessage(event.getPlayer(), e.getMessage()); } } @EventHandler public void onBlockRedstoneChange(BlockRedstoneEvent event) { SMSInteractableBlock iBlock = plugin.getLocationManager().getInteractableAt(event.getBlock().getLocation()); if (iBlock != null) { iBlock.processEvent(plugin, event); } } private void placeRedstoneControlSign(SignChangeEvent event) { final Player player = event.getPlayer(); PermissionUtils.requirePerms(player, "scrollingmenusign.create.redstonecontrol"); SMSView view = plugin.getViewManager().getView(event.getLine(1)); SMSValidate.isTrue(view instanceof SMSGlobalScrollableView, view.getName() + " must be a globally scrollable view"); event.setLine(0, ChatColor.RED + "[smsred]"); final Block block = event.getBlock(); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { // get the new control sign cached @Override public void run() { try { RedstoneControlSign.getControlSign(block.getLocation()); } catch (SMSException e) { MiscUtil.errorMessage(player, e.getMessage()); } } }); } private void placeTooltipSign(SignChangeEvent event) { Player player = event.getPlayer(); PermissionUtils.requirePerms(player, "scrollingmenusign.create.tooltipsign"); // check up, down, left, right for a global scrollable view Block b = event.getBlock(); Sign sign = (Sign) b.getState().getData(); BlockFace left = BlockUtil.getLeft(sign.getAttachedFace()); BlockFace toCheck = null; if (!event.getLine(1).isEmpty()) { switch (Character.toLowerCase(event.getLine(1).charAt(0))) { case 'u': toCheck = BlockFace.UP; break; case 'd': toCheck = BlockFace.DOWN; break; case 'l': toCheck = left; break; case 'r': toCheck = left.getOppositeFace(); break; default: throw new SMSException("Invalid direction [" + event.getLine(1) + "] (want one of U,D,L,R)"); } } SMSGlobalScrollableView gsv; if (toCheck != null) { gsv = checkForGSView(b, toCheck); } else { gsv = checkForGSView(b, BlockFace.UP, left, BlockFace.DOWN, left.getOppositeFace()); } SMSValidate.notNull(gsv, "Sorry, couldn't find a suitable view for this tooltip sign."); gsv.addTooltipSign(b.getLocation()); String[] text = gsv.getTooltipText(); for (int i = 0; i < 4; i++) { event.setLine(i, text[i]); } MiscUtil.statusMessage(event.getPlayer(), String.format("Tooltip sign @ &f%s&- has been added to view &e%s&-.", MiscUtil.formatLocation(b.getLocation()), gsv.getName())); } private SMSGlobalScrollableView checkForGSView(Block b, BlockFace... faces) { for (BlockFace face : faces) { Location viewLoc = b.getRelative(face).getLocation(); SMSView view = plugin.getViewManager().getViewForLocation(viewLoc); if (view == null || !(view instanceof SMSGlobalScrollableView)) { continue; } SMSGlobalScrollableView gsv = (SMSGlobalScrollableView) view; if (gsv.getTooltipSign() != null) { continue; } return gsv; } return null; } private void tryToActivateSign(SignChangeEvent event) { final Block b = event.getBlock(); final Player player = event.getPlayer(); String menuName = event.getLine(1); SMSValidate.isFalse(menuName.isEmpty(), "Missing menu name on line 2."); String title = MiscUtil.parseColourSpec(player, event.getLine(2)); SMSHandler handler = plugin.getHandler(); SMSMenu menu; if (handler.checkMenu(menuName)) { PermissionUtils.requirePerms(player, "scrollingmenusign.commands.sync"); menu = handler.getMenu(menuName); } else if (title.length() > 0) { PermissionUtils.requirePerms(player, "scrollingmenusign.commands.create"); menu = handler.createMenu(menuName, title, player); } else { throw new SMSException("No such menu '" + menuName + "'."); } // using the scheduler here because updating the sign from its SignChangeEvent handler doesn't work final SMSMenu menu2 = menu; Bukkit.getScheduler().runTask(plugin, new Runnable() { @Override public void run() { SMSView view = plugin.getViewManager().addSignToMenu(menu2, b.getLocation(), player); MiscUtil.statusMessage(player, String.format("Added new sign view &e%s&- @ &f%s&- to menu &e%s&-.", view.getName(), MiscUtil.formatLocation(b.getLocation()), menu2.getName())); } }); } }
lgpl-3.0
IlyaKirillov/GoProject
WebSDK/Drawing/Window.js
146446
"use strict"; /** * Copyright 2014 the HtmlGoBoard project authors. * All rights reserved. * Project WebSDK * Author Ilya Kirillov * Date 13.12.14 * Time 1:13 */ function CDrawingWindow() { this.HtmlElement = { Control : null, InnerDiv : null, InnerControl : null, CloseButton : null, Caption : null, CaptionText : null, CaptionTextControl : null, HandlerL : null, HandlerR : null, HandlerB : null, HandlerT : null, HandlerLT : null, HandlerRT : null, HandlerLB : null, HandlerRB : null }; this.m_oOuterBorderColor = new CColor(166, 166, 166, 255); this.m_oInnerBorderColor = new CColor(185, 185, 185, 255); this.m_oBackColor = new CColor(217, 217, 217, 255); this.m_oDrawing = null; this.m_nW = -1; this.m_nH = -1; this.m_bVisible = false; this.m_sWindowId = null; var oThis = this; this.private_OnDragLeftHandler = function() { var CurLeft = parseInt(oThis.HtmlElement.Control.HtmlElement.style.left); var CurWidth = parseInt(oThis.HtmlElement.Control.HtmlElement.style.width); var LeftHandler = parseInt(oThis.HtmlElement.HandlerL.style.left); if (CurWidth - LeftHandler < 60) { oThis.HtmlElement.HandlerL.style.left = "0px"; } else { oThis.HtmlElement.Control.HtmlElement.style.left = CurLeft + LeftHandler + "px"; oThis.HtmlElement.Control.HtmlElement.style.width = CurWidth - LeftHandler + "px"; oThis.HtmlElement.HandlerL.style.left = "0px"; } oThis.Update_Size(); }; this.private_OnDragRightHandler = function() { var CurWidth = parseInt(oThis.HtmlElement.Control.HtmlElement.style.width); var LeftHandler = parseInt(oThis.HtmlElement.HandlerR.style.left); var Diff = (LeftHandler + 6 - CurWidth); if (CurWidth + Diff < 60) { oThis.HtmlElement.HandlerR.style.left = CurWidth - 6 + "px"; return; } oThis.HtmlElement.Control.HtmlElement.style.width = CurWidth + Diff + "px"; oThis.HtmlElement.HandlerR.style.left = CurWidth + Diff - 6 + "px"; oThis.Update_Size(); }; this.private_OnDragBottomHandler = function() { var CurHeight = parseInt(oThis.HtmlElement.Control.HtmlElement.style.height); var TopHandler = parseInt(oThis.HtmlElement.HandlerB.style.top); var Diff = (TopHandler + 6 - CurHeight); if (CurHeight + Diff < 60) { oThis.HtmlElement.HandlerB.style.top = CurHeight - 6 + "px"; return; } oThis.HtmlElement.Control.HtmlElement.style.height = CurHeight + Diff + "px"; oThis.HtmlElement.HandlerB.style.top = CurHeight + Diff - 6 + "px"; oThis.Update_Size(); }; this.private_OnDragTopHandler = function() { var CurTop = parseInt(oThis.HtmlElement.Control.HtmlElement.style.top); var CurHeight = parseInt(oThis.HtmlElement.Control.HtmlElement.style.height); var TopHandler = parseInt(oThis.HtmlElement.HandlerT.style.top); if (CurHeight - TopHandler < 60) { oThis.HtmlElement.HandlerT.style.top = "0px"; return; } oThis.HtmlElement.Control.HtmlElement.style.top = CurTop + TopHandler + "px"; oThis.HtmlElement.Control.HtmlElement.style.height = CurHeight - TopHandler + "px"; oThis.HtmlElement.HandlerT.style.top = "0px"; oThis.Update_Size(); }; this.private_OnDragLeftTopHandler = function() { var CurTop = parseInt(oThis.HtmlElement.Control.HtmlElement.style.top); var CurHeight = parseInt(oThis.HtmlElement.Control.HtmlElement.style.height); var TopHandler = parseInt(oThis.HtmlElement.HandlerLT.style.top); if (CurHeight - TopHandler < 60) { oThis.HtmlElement.HandlerLT.style.top = "0px"; } else { oThis.HtmlElement.Control.HtmlElement.style.top = CurTop + TopHandler + "px"; oThis.HtmlElement.Control.HtmlElement.style.height = CurHeight - TopHandler + "px"; oThis.HtmlElement.HandlerLT.style.top = "0px"; } var CurLeft = parseInt(oThis.HtmlElement.Control.HtmlElement.style.left); var CurWidth = parseInt(oThis.HtmlElement.Control.HtmlElement.style.width); var LeftHandler = parseInt(oThis.HtmlElement.HandlerLT.style.left); if (CurWidth - LeftHandler < 60) { oThis.HtmlElement.HandlerLT.style.left = "0px"; } else { oThis.HtmlElement.Control.HtmlElement.style.left = CurLeft + LeftHandler + "px"; oThis.HtmlElement.Control.HtmlElement.style.width = CurWidth - LeftHandler + "px"; oThis.HtmlElement.HandlerLT.style.left = "0px"; } oThis.Update_Size(); }; this.private_OnDragRightTopHandler = function() { var CurTop = parseInt(oThis.HtmlElement.Control.HtmlElement.style.top); var CurHeight = parseInt(oThis.HtmlElement.Control.HtmlElement.style.height); var TopHandler = parseInt(oThis.HtmlElement.HandlerRT.style.top); if (CurHeight - TopHandler < 60) { oThis.HtmlElement.HandlerRT.style.top = "0px"; } else { oThis.HtmlElement.Control.HtmlElement.style.top = CurTop + TopHandler + "px"; oThis.HtmlElement.Control.HtmlElement.style.height = CurHeight - TopHandler + "px"; oThis.HtmlElement.HandlerRT.style.top = "0px"; } var CurWidth = parseInt(oThis.HtmlElement.Control.HtmlElement.style.width); var LeftHandler = parseInt(oThis.HtmlElement.HandlerRT.style.left); var Diff = (LeftHandler + 6 - CurWidth); if (CurWidth + Diff < 60) { oThis.HtmlElement.HandlerRT.style.left = CurWidth - 6 + "px"; } else { oThis.HtmlElement.Control.HtmlElement.style.width = CurWidth + Diff + "px"; oThis.HtmlElement.HandlerRT.style.left = CurWidth + Diff - 6 + "px"; } oThis.Update_Size(); }; this.private_OnDragLeftBottomHandler = function() { var CurLeft = parseInt(oThis.HtmlElement.Control.HtmlElement.style.left); var CurWidth = parseInt(oThis.HtmlElement.Control.HtmlElement.style.width); var LeftHandler = parseInt(oThis.HtmlElement.HandlerLB.style.left); if (CurWidth - LeftHandler < 60) { oThis.HtmlElement.HandlerLB.style.left = "0px"; } else { oThis.HtmlElement.Control.HtmlElement.style.left = CurLeft + LeftHandler + "px"; oThis.HtmlElement.Control.HtmlElement.style.width = CurWidth - LeftHandler + "px"; oThis.HtmlElement.HandlerLB.style.left = "0px"; } var CurHeight = parseInt(oThis.HtmlElement.Control.HtmlElement.style.height); var TopHandler = parseInt(oThis.HtmlElement.HandlerLB.style.top); var Diff = (TopHandler + 6 - CurHeight); if (CurHeight + Diff < 60) { oThis.HtmlElement.HandlerLB.style.top = CurHeight - 6 + "px"; } else { oThis.HtmlElement.Control.HtmlElement.style.height = CurHeight + Diff + "px"; oThis.HtmlElement.HandlerLB.style.top = CurHeight + Diff - 6 + "px"; } oThis.Update_Size(); }; this.private_OnDragRightBottomHandler = function() { var CurWidth = parseInt(oThis.HtmlElement.Control.HtmlElement.style.width); var LeftHandler = parseInt(oThis.HtmlElement.HandlerRB.style.left); var Diff = (LeftHandler + 6 - CurWidth); if (CurWidth + Diff < 60) { oThis.HtmlElement.HandlerRB.style.left = CurWidth - 6 + "px"; } else { oThis.HtmlElement.Control.HtmlElement.style.width = CurWidth + Diff + "px"; oThis.HtmlElement.HandlerRB.style.left = CurWidth + Diff - 6 + "px"; } var CurHeight = parseInt(oThis.HtmlElement.Control.HtmlElement.style.height); var TopHandler = parseInt(oThis.HtmlElement.HandlerRB.style.top); var Diff = (TopHandler + 6 - CurHeight); if (CurHeight + Diff < 60) { oThis.HtmlElement.HandlerRB.style.top = CurHeight - 6 + "px"; } else { oThis.HtmlElement.Control.HtmlElement.style.height = CurHeight + Diff + "px"; oThis.HtmlElement.HandlerRB.style.top = CurHeight + Diff - 6 + "px"; } oThis.Update_Size(); }; } CDrawingWindow.prototype.Init = function(sDivId, bResizable) { var oThis = this; this.m_bVisible = true; this.m_sWindowId = sDivId; this.HtmlElement.Control = CreateControlContainer(sDivId); var oMainDiv = this.HtmlElement.Control.HtmlElement; var oMainControl = this.HtmlElement.Control; oMainDiv.style.border = "1px solid " + this.m_oOuterBorderColor.ToString(); oMainDiv.style.backgroundColor = this.m_oBackColor.ToString(); oMainDiv.style.boxSizing = "content-box"; oMainDiv.style.boxShadow = "0px 1px 15px rgba(0,0,0,0.8)"; oMainDiv.addEventListener("mousedown", function() { oThis.private_OnFocus(); }, false); // InnerDiv var sInnerDivId = sDivId + "_Inner"; var oInnerElement = this.protected_CreateDivElement(oMainDiv, sInnerDivId); var oInnerControl = CreateControlContainer(sInnerDivId); oInnerControl.Bounds.SetParams(6, 29, 8, 8, true, true, true, true, -1, -1); oInnerControl.Anchor = (g_anchor_top | g_anchor_left | g_anchor_bottom | g_anchor_right); oMainControl.AddControl(oInnerControl); oInnerElement.style.border = "1px solid " + this.m_oInnerBorderColor.ToString(); oInnerElement.style.backgroundColor = (new CColor(255, 255, 255, 255)).ToString(); oInnerElement.style.overflow = "hidden"; this.HtmlElement.InnerDiv = oInnerElement; this.HtmlElement.InnerControl = oInnerControl; // Caption var sCaptionId = sDivId + "_Caption"; var oCaptionElement = this.protected_CreateDivElement(oMainDiv, sCaptionId); var oCaptionControl = CreateControlContainer(sCaptionId); oCaptionControl.Bounds.SetParams(0, 0, 1000, 1000, false, false, false, false, -1, 30); oCaptionControl.Anchor = (g_anchor_top | g_anchor_left | g_anchor_right); oMainControl.AddControl(oCaptionControl); // CaptionText var sCaptionTextId = sCaptionId + "_Text"; var oCaptionTextElement = this.protected_CreateDivElement(oMainDiv, sCaptionTextId); var oCaptionTextControl = CreateControlContainer(sCaptionTextId); oCaptionTextControl.Bounds.SetParams(15, 0, 55, 1000, true, false, true, false, -1, 30); oCaptionTextControl.Anchor = (g_anchor_top | g_anchor_left | g_anchor_right | g_anchor_bottom); oCaptionControl.AddControl(oCaptionTextControl); oCaptionTextElement.style.fontFamily = "Tahoma, Sans serif"; oCaptionTextElement.style.fontSize = "13pt"; oCaptionTextElement.style.textAlign = "center"; oCaptionTextElement.style.height = "29px"; oCaptionTextElement.style.lineHeight = "29px"; oCaptionTextElement.style.overflow = "hidden"; oCaptionTextElement.style.textOverflow = "ellipsis"; oCaptionTextElement.style['-o-text-overflow'] = "ellipsis"; oCaptionTextElement.style.cursor = "default"; Common.Set_InnerTextToElement(oCaptionTextElement, "Caption"); this.HtmlElement.CaptionText = oCaptionTextElement; this.HtmlElement.CaptionTextControl = oCaptionTextControl; // Caption var sCaptionId2 = sDivId + "_Caption2"; var oCaptionElement2 = this.protected_CreateDivElement(oMainDiv, sCaptionId2); var oCaptionControl2 = CreateControlContainer(sCaptionId2); oCaptionControl2.Bounds.SetParams(0, 0, 1000, 1000, false, false, false, false, -1, 30); oCaptionControl2.Anchor = (g_anchor_top | g_anchor_left | g_anchor_right); oMainControl.AddControl(oCaptionControl2); this.HtmlElement.Caption = oCaptionElement2; function privateOnDragStart() { global_mouseEvent.LockMouse(); } function privateOnDragEnd() { global_mouseEvent.UnLockMouse(); } Common_DragHandler.Init(oCaptionElement2, null); oCaptionElement2.onDrag = function (X, Y) { var CurLeft = parseInt(oThis.HtmlElement.Control.HtmlElement.style.left); var CurTop = parseInt(oThis.HtmlElement.Control.HtmlElement.style.top); var LeftHandler = parseInt(oThis.HtmlElement.Caption.style.left); var TopHandler = parseInt(oThis.HtmlElement.Caption.style.top); oThis.HtmlElement.Control.HtmlElement.style.left = CurLeft + LeftHandler + "px"; oThis.HtmlElement.Control.HtmlElement.style.top = CurTop + TopHandler + "px"; oThis.HtmlElement.Caption.style.left = "0px"; oThis.HtmlElement.Caption.style.top = "0px"; oThis.Update_Size(); }; oCaptionElement2.onDragStart = privateOnDragStart; oCaptionElement2.onDragEnd = privateOnDragEnd; if (false !== bResizable) { // Left Handler var sLeftHandlerId = sDivId + "_LeftHandler"; var oLeftHandlerElement = this.protected_CreateDivElement(oMainDiv, sLeftHandlerId); var oLeftHandlerControl = CreateControlContainer(sLeftHandlerId); oLeftHandlerControl.Bounds.SetParams(0, 6, 1000, 6, false, true, false, true, 6, -1); oLeftHandlerControl.Anchor = (g_anchor_top | g_anchor_left | g_anchor_bottom); oMainControl.AddControl(oLeftHandlerControl); oLeftHandlerElement.style.cursor = "w-resize"; this.HtmlElement.HandlerL = oLeftHandlerElement; // Right Handler var sRightHandlerId = sDivId + "_RightHandler"; var oRightHandlerElement = this.protected_CreateDivElement(oMainDiv, sRightHandlerId); var oRightHandlerControl = CreateControlContainer(sRightHandlerId); oRightHandlerControl.Bounds.SetParams(0, 6, 0, 6, false, true, true, true, 6, -1); oRightHandlerControl.Anchor = (g_anchor_top | g_anchor_right | g_anchor_bottom); oMainControl.AddControl(oRightHandlerControl); oRightHandlerElement.style.cursor = "w-resize"; this.HtmlElement.HandlerR = oRightHandlerElement; // Bottom Handler var sBottomHandlerId = sDivId + "_BottomHandler"; var oBottomHandlerElement = this.protected_CreateDivElement(oMainDiv, sBottomHandlerId); var oBottomHandlerControl = CreateControlContainer(sBottomHandlerId); oBottomHandlerControl.Bounds.SetParams(6, 0, 6, 0, true, false, true, true, -1, 6); oBottomHandlerControl.Anchor = (g_anchor_bottom | g_anchor_right | g_anchor_left); oMainControl.AddControl(oBottomHandlerControl); oBottomHandlerElement.style.cursor = "s-resize"; this.HtmlElement.HandlerB = oBottomHandlerElement; // Top Handler var sTopHandlerId = sDivId + "_TopHandler"; var oTopHandlerElement = this.protected_CreateDivElement(oMainDiv, sTopHandlerId); var oTopHandlerControl = CreateControlContainer(sTopHandlerId); oTopHandlerControl.Bounds.SetParams(6, 0, 6, 1000, true, true, true, false, -1, 6); oTopHandlerControl.Anchor = (g_anchor_top | g_anchor_right | g_anchor_left); oMainControl.AddControl(oTopHandlerControl); oTopHandlerElement.style.cursor = "s-resize"; this.HtmlElement.HandlerT = oTopHandlerElement; // Left-Top Handler var sLeftTopHandlerId = sDivId + "_LeftTopHandler"; var oLeftTopHandlerElement = this.protected_CreateDivElement(oMainDiv, sLeftTopHandlerId); var oLeftTopHandlerControl = CreateControlContainer(sLeftTopHandlerId); oLeftTopHandlerControl.Bounds.SetParams(0, 0, 1000, 1000, false, false, false, false, 6, 6); oLeftTopHandlerControl.Anchor = (g_anchor_top | g_anchor_left); oMainControl.AddControl(oLeftTopHandlerControl); oLeftTopHandlerElement.style.cursor = "se-resize"; this.HtmlElement.HandlerLT = oLeftTopHandlerElement; // Right-Top Handler var sRightTopHandlerId = sDivId + "_RightTopHandler"; var oRightTopHandlerElement = this.protected_CreateDivElement(oMainDiv, sRightTopHandlerId); var oRightTopHandlerControl = CreateControlContainer(sRightTopHandlerId); oRightTopHandlerControl.Bounds.SetParams(0, 0, 0, 1000, false, false, true, false, 6, 6); oRightTopHandlerControl.Anchor = (g_anchor_top | g_anchor_right); oMainControl.AddControl(oRightTopHandlerControl); oRightTopHandlerElement.style.cursor = "ne-resize"; this.HtmlElement.HandlerRT = oRightTopHandlerElement; // Left-Bottom Handler var sLeftBottomHandlerId = sDivId + "_LeftBottomHandler"; var oLeftBottomHandlerElement = this.protected_CreateDivElement(oMainDiv, sLeftBottomHandlerId); var oLeftBottomHandlerControl = CreateControlContainer(sLeftBottomHandlerId); oLeftBottomHandlerControl.Bounds.SetParams(0, 0, 0, 1000, false, false, false, false, 6, 6); oLeftBottomHandlerControl.Anchor = (g_anchor_bottom | g_anchor_left); oMainControl.AddControl(oLeftBottomHandlerControl); oLeftBottomHandlerElement.style.cursor = "ne-resize"; this.HtmlElement.HandlerLB = oLeftBottomHandlerElement; // Right-Bottom Handler var sRightBottomHandlerId = sDivId + "_RightBottomHandler"; var oRightBottomHandlerElement = this.protected_CreateDivElement(oMainDiv, sRightBottomHandlerId); var oRightBottomHandlerControl = CreateControlContainer(sRightBottomHandlerId); oRightBottomHandlerControl.Bounds.SetParams(0, 0, 0, 1000, false, false, true, false, 6, 6); oRightBottomHandlerControl.Anchor = (g_anchor_bottom | g_anchor_right); oMainControl.AddControl(oRightBottomHandlerControl); oRightBottomHandlerElement.style.cursor = "se-resize"; this.HtmlElement.HandlerRB = oRightBottomHandlerElement; Common_DragHandler.Init(this.HtmlElement.HandlerL, null, null, null, null, null); this.HtmlElement.HandlerL.onDrag = this.private_OnDragLeftHandler; this.HtmlElement.HandlerL.onDragStart = privateOnDragStart; this.HtmlElement.HandlerL.onDragEnd = privateOnDragEnd; Common_DragHandler.Init(this.HtmlElement.HandlerR, null, null, null, null, null); this.HtmlElement.HandlerR.onDrag = this.private_OnDragRightHandler; this.HtmlElement.HandlerR.onDragStart = privateOnDragStart; this.HtmlElement.HandlerR.onDragEnd = privateOnDragEnd; Common_DragHandler.Init(this.HtmlElement.HandlerT, null, null, null, null, null); this.HtmlElement.HandlerT.onDrag = this.private_OnDragTopHandler; this.HtmlElement.HandlerT.onDragStart = privateOnDragStart; this.HtmlElement.HandlerT.onDragEnd = privateOnDragEnd; Common_DragHandler.Init(this.HtmlElement.HandlerB, null, null, null, null, null); this.HtmlElement.HandlerB.onDrag = this.private_OnDragBottomHandler; this.HtmlElement.HandlerB.onDragStart = privateOnDragStart; this.HtmlElement.HandlerB.onDragEnd = privateOnDragEnd; Common_DragHandler.Init(this.HtmlElement.HandlerLT, null, null, null, null, null); this.HtmlElement.HandlerLT.onDrag = this.private_OnDragLeftTopHandler; this.HtmlElement.HandlerLT.onDragStart = privateOnDragStart; this.HtmlElement.HandlerLT.onDragEnd = privateOnDragEnd; Common_DragHandler.Init(this.HtmlElement.HandlerRT, null, null, null, null, null); this.HtmlElement.HandlerRT.onDrag = this.private_OnDragRightTopHandler; this.HtmlElement.HandlerRT.onDragStart = privateOnDragStart; this.HtmlElement.HandlerRT.onDragEnd = privateOnDragEnd; Common_DragHandler.Init(this.HtmlElement.HandlerLB, null, null, null, null, null); this.HtmlElement.HandlerLB.onDrag = this.private_OnDragLeftBottomHandler; this.HtmlElement.HandlerLB.onDragStart = privateOnDragStart; this.HtmlElement.HandlerLB.onDragEnd = privateOnDragEnd; Common_DragHandler.Init(this.HtmlElement.HandlerRB, null, null, null, null, null); this.HtmlElement.HandlerRB.onDrag = this.private_OnDragRightBottomHandler; this.HtmlElement.HandlerRB.onDragStart = privateOnDragStart; this.HtmlElement.HandlerRB.onDragEnd = privateOnDragEnd; } // CloseButton var sCloseButtonId = sDivId + "_Close"; var oCloseButtonElement = this.protected_CreateDivElement(oMainDiv, sCloseButtonId); var oCloseButtonControl = CreateControlContainer(sCloseButtonId); oCloseButtonControl.Bounds.SetParams(0, 0, 6, 1000, false, true, true, false, 45, 20); oCloseButtonControl.Anchor = (g_anchor_top | g_anchor_right); oMainControl.AddControl(oCloseButtonControl); oCloseButtonElement.style.backgroundColor = (new CColor(255, 0, 0, 255)).ToString(); var oCloseButton = new CDrawingButtonClose(this.m_oDrawing); oCloseButton.Init(sCloseButtonId, this); oCloseButton.m_oNormaFColor = new CColor(199, 80, 80, 255); oCloseButton.m_oHoverFColor = new CColor(224, 67, 67, 255); oCloseButton.m_oActiveFColor = new CColor(153, 61, 61, 255); this.HtmlElement.CloseButton = oCloseButton; this.private_UpdateSize(); }; CDrawingWindow.prototype.Get_Id = function() { return this.m_sWindowId; }; CDrawingWindow.prototype.Update_Size = function(bForce) { var W = this.HtmlElement.Control.HtmlElement.clientWidth; var H = this.HtmlElement.Control.HtmlElement.clientHeight; if (W !== this.m_nW || H !== this.m_nH || true === bForce) { this.m_nW = W; this.m_nH = H; this.HtmlElement.Control.Resize(W, H); this.HtmlElement.CloseButton.Update_Size(); } this.private_CheckPosition(); }; CDrawingWindow.prototype.Close = function() { this.m_bVisible = false; var oMainDiv = this.HtmlElement.Control.HtmlElement; oMainDiv.style.display = "none"; if (this.m_oGameTree) this.m_oGameTree.Focus(); }; CDrawingWindow.prototype.Show = function(oPr) { this.m_bVisible = true; var oDiv = this.HtmlElement.Control.HtmlElement; oDiv.style.display = "block"; var nLeft = parseInt(oDiv.style.left); var nTop = parseInt(oDiv.style.top); if (oPr && oPr.Drawing) { var oDrawing = oPr.Drawing; var DrawingW = oDrawing.Get_Width(); var DrawingH = oDrawing.Get_Height(); var nThreshold = 100; if (nTop > DrawingH - nThreshold) oDiv.style.top = (DrawingH - nThreshold) + "px"; if (nLeft > DrawingW - nThreshold) oDiv.style.left = (DrawingW - nThreshold) + "px"; } if (nLeft < 0) oDiv.style.left = "0px"; if (nTop < 0) oDiv.style.top = "0px"; }; CDrawingWindow.prototype.Focus = function() { }; CDrawingWindow.prototype.Set_Caption = function(sCaption) { Common.Set_InnerTextToElement(this.HtmlElement.CaptionText, sCaption); }; CDrawingWindow.prototype.protected_CreateDivElement = function(oParentElement, sName, sTag) { var oElement = document.createElement(sTag ? sTag : "div"); if (sName) oElement.setAttribute("id", sName); oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.setAttribute("oncontextmenu", "return false;"); oParentElement.appendChild(oElement); return oElement; }; CDrawingWindow.prototype.protected_UpdateSizeAndPosition = function(oDrawing) { if (!oDrawing) return; this.m_oDrawing = oDrawing; var oWindowDiv = this.HtmlElement.Control.HtmlElement; var nWindowW = parseInt(oWindowDiv.style.width); var nWindowH = parseInt(oWindowDiv.style.height); var nX = Math.max(0, ((this.m_oDrawing.Get_Width() - nWindowW) / 2)); var nY = Math.max(0, ((this.m_oDrawing.Get_Height() - nWindowH) / 2)); oWindowDiv.style.left = nX + "px"; oWindowDiv.style.top = nY + "px"; }; CDrawingWindow.prototype.private_UpdateSize = function() { var oWindowDiv = this.HtmlElement.Control.HtmlElement; var oSize = this.Get_DefaultWindowSize(); if (null !== oSize && undefined !== oSize) { oWindowDiv.style.width = oSize.W + "px"; oWindowDiv.style.height = oSize.H + "px"; } }; CDrawingWindow.prototype.Get_DefaultWindowSize = function() { return null; }; CDrawingWindow.prototype.Is_Visible = function() { return this.m_bVisible; }; CDrawingWindow.prototype.Update = function() { }; CDrawingWindow.prototype.private_OnFocus = function() { }; CDrawingWindow.prototype.private_CheckPosition = function() { var oWindowDiv = this.HtmlElement.Control.HtmlElement; var oParentDiv = oWindowDiv.parentNode; if (!oParentDiv) return; var nOverallW = parseInt(oParentDiv.clientWidth); var nOverallH = parseInt(oParentDiv.clientHeight); var nLeft = parseInt(this.HtmlElement.Control.HtmlElement.style.left); var nTop = parseInt(this.HtmlElement.Control.HtmlElement.style.top); var nWidth = parseInt(this.HtmlElement.Control.HtmlElement.style.width); var nHeight = parseInt(this.HtmlElement.Control.HtmlElement.style.height); if (nWidth > nOverallW + 1 || nHeight > nOverallH + 1) { if (nWidth > nOverallW + 1) this.HtmlElement.Control.HtmlElement.style.width = nOverallW + "px"; if (nHeight > nOverallH + 1) this.HtmlElement.Control.HtmlElement.style.height = nOverallH + "px"; this.Update_Size(); return; } if (nLeft + nWidth > nOverallW) this.HtmlElement.Control.HtmlElement.style.left = (nOverallW - nWidth) + "px"; if (nLeft <= 0) this.HtmlElement.Control.HtmlElement.style.left = "0px"; if (nTop + nHeight > nOverallH) this.HtmlElement.Control.HtmlElement.style.top = (nOverallH - nHeight) + "px"; if (nTop <= 0) this.HtmlElement.Control.HtmlElement.style.top = "0px"; }; function CDrawingConfirmWindow() { CDrawingConfirmWindow.superclass.constructor.call(this); this.HtmlElement.OKButton = null; this.HtmlElement.CancelButton = null; this.HtmlElement.OkButtonControl = null; this.HtmlElement.CancelButtonControl = null; this.HtmlElement.OkCancelDiv = null; this.HtmlElement.ConfirmInnerDiv = null; this.HtmlElement.ConfirmInnerControl = null; } CommonExtend(CDrawingConfirmWindow, CDrawingWindow); CDrawingConfirmWindow.prototype.Init = function(_sDivId, bResizable) { CDrawingConfirmWindow.superclass.Init.call(this, _sDivId, bResizable); var oMainDiv = this.HtmlElement.InnerDiv; var oMainControl = this.HtmlElement.InnerControl; var sDivId = oMainDiv.id; var sContentDiv = sDivId + "Content"; var sButtonsDiv = sDivId + "Buttons"; var oContentDiv = this.protected_CreateDivElement(oMainDiv, sContentDiv); var oButtonsDiv = this.protected_CreateDivElement(oMainDiv, sButtonsDiv); var oContentControl = CreateControlContainer(sContentDiv); oContentControl.Bounds.SetParams(0, 0, 0, 40, true, true, true, true, -1, -1); oContentControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_bottom | g_anchor_right); oMainControl.AddControl(oContentControl); var oButtonsControl = CreateControlContainer(sButtonsDiv); oButtonsControl.Bounds.SetParams(0, 0, 0, 0, true, false, true, true, -1, 40); oButtonsControl.Anchor = (g_anchor_left |g_anchor_bottom | g_anchor_right); oMainControl.AddControl(oButtonsControl); this.HtmlElement.ConfirmInnerControl = oContentControl; this.HtmlElement.ConfirmInnerDiv = oContentDiv; // TODO: Цвета должны быть из темы oButtonsDiv.style.borderTop = "1px solid rgb(172,172,172)"; oButtonsDiv.style.backgroundColor = "rgb(240,240,240)"; this.HtmlElement.OkCancelDiv = oButtonsDiv; // Butttons OK Cancel var sButtonOk = sButtonsDiv + "OK"; var oButtonOkElement = this.protected_CreateDivElement(oButtonsDiv, sButtonOk); var oButtonOkControl = CreateControlContainer(sButtonOk); oButtonOkControl.Bounds.SetParams(0, 9, 85, 1000, false, true, true, false, 66, 21); oButtonOkControl.Anchor = (g_anchor_top | g_anchor_right); oMainControl.AddControl(oButtonOkControl); var oDrawingButttonOK = new CDrawingButtonOK(this.m_oDrawing); oDrawingButttonOK.Init(sButtonOk, this); this.HtmlElement.OKButton = oDrawingButttonOK; this.HtmlElement.OkButtonControl = oButtonOkControl; oDrawingButttonOK.m_oNormaBColor = new CColor(234, 234, 234, 255); // 229,229,229 -> 240,240,240 oDrawingButttonOK.m_oNormaFColor = new CColor(172, 172, 172, 255); oDrawingButttonOK.m_oHoverBColor = new CColor(227, 240, 252, 255); // 220,236,252 -> 236,244,252 oDrawingButttonOK.m_oHoverFColor = new CColor(126, 180, 234, 255); oDrawingButttonOK.m_oActiveBColor = new CColor(207, 230, 252, 255); // 196,224,252 -> 218,235,252 oDrawingButttonOK.m_oActiveFColor = new CColor( 86, 157, 229, 255); oDrawingButttonOK.m_oDisabledBColor = new CColor(239, 239, 239, 255); oDrawingButttonOK.m_oDisabledFColor = new CColor(217, 217, 217, 255); var sButtonCancel = sButtonsDiv + "Cancel"; var oButtonCancelElement = this.protected_CreateDivElement(oButtonsDiv, sButtonCancel); var oButtonCancelControl = CreateControlContainer(sButtonCancel); oButtonCancelControl.Bounds.SetParams(0, 9, 11, 1000, false, true, true, false, 66, 21); oButtonCancelControl.Anchor = (g_anchor_top | g_anchor_right); oMainControl.AddControl(oButtonCancelControl); var oDrawingButttonCancel = new CDrawingButtonCancel(this.m_oDrawing); oDrawingButttonCancel.Init(sButtonCancel, this); this.HtmlElement.CancelButton = oDrawingButttonCancel; this.HtmlElement.CancelButtonControl = oButtonCancelControl; oDrawingButttonCancel.m_oNormaBColor = new CColor(234, 234, 234, 255); // 229,229,229 -> 240,240,240 oDrawingButttonCancel.m_oNormaFColor = new CColor(172, 172, 172, 255); oDrawingButttonCancel.m_oHoverBColor = new CColor(227, 240, 252, 255); // 220,236,252 -> 236,244,252 oDrawingButttonCancel.m_oHoverFColor = new CColor(126, 180, 234, 255); oDrawingButttonCancel.m_oActiveBColor = new CColor(207, 230, 252, 255); // 196,224,252 -> 218,235,252 oDrawingButttonCancel.m_oActiveFColor = new CColor( 86, 157, 229, 255); oDrawingButttonCancel.m_oDisabledBColor = new CColor(239, 239, 239, 255); oDrawingButttonCancel.m_oDisabledFColor = new CColor(217, 217, 217, 255); }; CDrawingConfirmWindow.prototype.Update_Size = function(bForce) { CDrawingConfirmWindow.superclass.Update_Size.call(this, bForce); if (this.HtmlElement.OKButton) this.HtmlElement.OKButton.Update_Size(); if (this.HtmlElement.CancelButton) this.HtmlElement.CancelButton.Update_Size(); }; CDrawingConfirmWindow.prototype.Handle_Cancel = function() { this.Close(); }; CDrawingConfirmWindow.prototype.Handle_OK = function() { this.Close(); }; function CDrawingInfoWindow() { CDrawingInfoWindow.superclass.constructor.call(this); this.HtmlElement2 = {}; this.m_oGameTree = null; this.m_nBottomOffset = 10; this.m_nRowHeight = 20; this.m_nLineSpacing = 5; this.m_nLeftWidth = 100; } CommonExtend(CDrawingInfoWindow, CDrawingConfirmWindow); CDrawingInfoWindow.prototype.Init = function(_sDivId, oPr) { CDrawingInfoWindow.superclass.Init.call(this, _sDivId); var sCaption = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.caption : "Game info"; var sGameName = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.gameName : "Game name"; var sResult = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.result : "Result"; var sRules = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.rules : "Rules"; var sKomi = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.komi : "Komi"; var sHandicap = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.handicap : "Handicap"; var sTimeSettings = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.timeSettings : "Time settings"; var sBlack = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.black : "Black"; var sBlackRank = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.blackRank : "Black rank"; var sWhite = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.white : "White"; var sWhiteRank = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.whiteRank : "White rank"; var sCopyright = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.copyright : "Copyright"; var sDate = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.date : "Date"; var sEvent = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.event : "Event"; var sRound = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.round : "Round"; var sPlace = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.place : "Place"; var sAnnotator = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.annotator : "Annotator"; var sFuseki = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.fuseki : "Fuseki"; var sSource = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.source : "Source"; var sTranscriber = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.transcriber : "Transcriber"; var sGameInfo = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.gameInfo.gameInfo : "Game info"; if (window.g_oTextMeasurer) { window.g_oTextMeasurer.SetFont("15px Tahoma, 'Sans serif'"); this.m_nLeftWidth = Math.max( window.g_oTextMeasurer.Measure(sGameName), window.g_oTextMeasurer.Measure(sResult), window.g_oTextMeasurer.Measure(sRules), window.g_oTextMeasurer.Measure(sKomi), window.g_oTextMeasurer.Measure(sHandicap), window.g_oTextMeasurer.Measure(sTimeSettings), window.g_oTextMeasurer.Measure(sBlack), window.g_oTextMeasurer.Measure(sBlackRank), window.g_oTextMeasurer.Measure(sWhite), window.g_oTextMeasurer.Measure(sWhiteRank), window.g_oTextMeasurer.Measure(sCopyright), window.g_oTextMeasurer.Measure(sDate), window.g_oTextMeasurer.Measure(sEvent), window.g_oTextMeasurer.Measure(sRound), window.g_oTextMeasurer.Measure(sPlace), window.g_oTextMeasurer.Measure(sAnnotator), window.g_oTextMeasurer.Measure(sFuseki), window.g_oTextMeasurer.Measure(sSource), window.g_oTextMeasurer.Measure(sTranscriber), window.g_oTextMeasurer.Measure(sGameInfo) ) + 12; } this.protected_UpdateSizeAndPosition(oPr.Drawing); var oGameTree = oPr.GameTree; this.m_oGameTree = oGameTree; if (true !== oGameTree.Can_EditGameInfo()) this.HtmlElement.OKButton.Set_Enabled(false); this.Set_Caption(sCaption); var oMainControl = this.HtmlElement.ConfirmInnerControl; var oMainDiv = this.HtmlElement.ConfirmInnerDiv; var sDivId = this.HtmlElement.ConfirmInnerDiv.id; oMainDiv.style.overflowX = "hidden"; oMainDiv.style.overflowY = "scroll"; var RowHeight = this.m_nRowHeight; var TopOffset = 10; var LineSpacing = this.m_nLineSpacing; var BottomOffset = this.m_nBottomOffset; var bCanEdit = oGameTree.Can_EditGameInfo(); this.HtmlElement2.GameName = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sGameName, oGameTree.Get_GameName(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Result = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sResult, oGameTree.Get_Result(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Rules = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sRules, oGameTree.Get_Rules(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Komi = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sKomi, oGameTree.Get_Komi(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Handicap = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sHandicap, oGameTree.Get_Handicap(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.TimeSettings = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sTimeSettings, oGameTree.Get_TimeLimit() + (oGameTree.Get_OverTime() === "" ? "" : " + " + oGameTree.Get_OverTime()), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.BlackName = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sBlack, oGameTree.Get_BlackName(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.BlackRank = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sBlackRank, oGameTree.Get_BlackRating(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.WhiteName = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sWhite, oGameTree.Get_WhiteName(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.WhiteRank = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sWhiteRank, oGameTree.Get_WhiteRating(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Copyright = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sCopyright, oGameTree.Get_Copyright(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Date = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sDate, oGameTree.Get_DateTime(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Event = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sEvent, oGameTree.Get_GameEvent(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Round = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sRound, oGameTree.Get_GameRound(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Place = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sPlace, oGameTree.Get_GamePlace(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Annotator = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sAnnotator, oGameTree.Get_GameAnnotator(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Fuseki = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sFuseki, oGameTree.Get_GameFuseki(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Source = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sSource, oGameTree.Get_GameSource(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.Transcriber = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sTranscriber, oGameTree.Get_GameTranscriber(), TopOffset, RowHeight, bCanEdit); TopOffset += RowHeight + LineSpacing; this.HtmlElement2.GameInfo = this.private_CreateInfoAreaElement(oMainDiv, oMainControl, sDivId, sGameInfo, oGameTree.Get_GameInfo(), TopOffset, RowHeight, bCanEdit); TopOffset += 3 * RowHeight; this.protected_CreateDivElement(oMainDiv, sDivId + "Bottom"); var BottomControl = CreateControlContainer(sDivId + "Bottom"); BottomControl.Bounds.SetParams(0, TopOffset, 1000, 1000, true, true, false, false, 0, BottomOffset); BottomControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_right); oMainControl.AddControl(BottomControl); }; CDrawingInfoWindow.prototype.Update_Size = function(bForce) { CDrawingInfoWindow.superclass.Update_Size.call(this, bForce); if (this.HtmlElement.OKButton) this.HtmlElement.OKButton.Update_Size(); if (this.HtmlElement.CancelButton) this.HtmlElement.CancelButton.Update_Size(); var nOverallHeight = parseInt(this.HtmlElement.ConfirmInnerDiv.style.height) | 0; var nGameInfoY = parseInt(this.HtmlElement2.GameInfo.style.top) | 0; var nGameInfoYLimit = nOverallHeight - this.m_nBottomOffset; if (nGameInfoYLimit - nGameInfoY < 3 * this.m_nRowHeight) this.HtmlElement2.GameInfo.style.height = 3 * this.m_nRowHeight + "px"; else this.HtmlElement2.GameInfo.style.height = (nGameInfoYLimit - nGameInfoY) + "px"; }; CDrawingInfoWindow.prototype.Handle_Cancel = function() { this.Close(); }; CDrawingInfoWindow.prototype.Handle_OK = function() { if (this.m_oGameTree) { this.m_oGameTree.Set_GameName(this.HtmlElement2.GameName.value); this.m_oGameTree.Set_Result(this.HtmlElement2.Result.value); this.m_oGameTree.Set_Rules(this.HtmlElement2.Rules.value); this.m_oGameTree.Set_Komi(parseFloat(this.HtmlElement2.Komi.value)); this.m_oGameTree.Set_Handicap(this.HtmlElement2.Handicap.value); // TODO: разбить на TimeLimit и Overtime this.m_oGameTree.Set_TimeLimit(this.HtmlElement2.TimeSettings.value); this.m_oGameTree.Set_Black(this.HtmlElement2.BlackName.value); this.m_oGameTree.Set_BlackRating(this.HtmlElement2.BlackRank.value); this.m_oGameTree.Set_White(this.HtmlElement2.WhiteName.value); this.m_oGameTree.Set_WhiteRating(this.HtmlElement2.WhiteRank.value); this.m_oGameTree.Set_Copyright(this.HtmlElement2.Copyright.value); this.m_oGameTree.Set_GameInfo(this.HtmlElement2.GameInfo.value); this.m_oGameTree.Set_DateTime(this.HtmlElement2.Date.value); this.m_oGameTree.Set_GameEvent(this.HtmlElement2.Event.value); this.m_oGameTree.Set_GameRound(this.HtmlElement2.Round.value); this.m_oGameTree.Set_GamePlace(this.HtmlElement2.Place.value); this.m_oGameTree.Set_GameAnnotator(this.HtmlElement2.Annotator.value); this.m_oGameTree.Set_GameFuseki(this.HtmlElement2.Fuseki.value); this.m_oGameTree.Set_GameSource(this.HtmlElement2.Source.value); this.m_oGameTree.Set_GameTranscriber(this.HtmlElement2.Transcriber.value); } this.Close(); }; CDrawingInfoWindow.prototype.private_CreateDivElement = function(oParentElement, sName, Height) { var oElement = document.createElement("div"); oElement.setAttribute("id", sName); oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.setAttribute("oncontextmenu", "return false;"); oElement.style.fontFamily = "Tahoma, Sans serif"; oElement.style.fontSize = Height * 15 / 20 + "px"; oElement.style.lineHeight = Height + "px"; oElement.style.height = Height + "px"; oParentElement.appendChild(oElement); return oElement; }; CDrawingInfoWindow.prototype.private_CreateInputElement = function(oParentElement, sName, bCanEdit) { var oElement = document.createElement("input"); oElement.setAttribute("id", sName); oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.setAttribute("oncontextmenu", "return false;"); oElement.setAttribute("type", "text"); oElement.style.fontFamily = "Tahoma, Sans serif"; oElement.style.fontSize = "10pt"; oElement.style.outline = "none"; oElement.style.border = "1px solid rgb(169,169,169)"; if (false === bCanEdit) oElement.disabled = "disabled"; oParentElement.appendChild(oElement); return oElement; }; CDrawingInfoWindow.prototype.private_CreateInfoElement = function(oMainDiv, oMainControl, sDivId, sName, sValue, TopOffset, RowHeight, bCanEdit) { var LeftWidth = this.m_nLeftWidth; var LeftOffset = 10; var RightOffset = 10; RightOffset += 20; // Scroll var sNameId = sDivId + sName; var oNameElement = this.private_CreateDivElement(oMainDiv, sNameId, RowHeight); var oNameControl = CreateControlContainer(sNameId); oNameControl.Bounds.SetParams(LeftOffset, TopOffset, 1000, 1000, true, true, false, false, LeftWidth, RowHeight); oNameControl.Anchor = (g_anchor_left | g_anchor_top); oMainControl.AddControl(oNameControl); Common.Set_InnerTextToElement(oNameElement, sName); var sValueId = sNameId + "Value"; var oValueElement = this.private_CreateInputElement(oMainDiv, sValueId, bCanEdit); var oValueControl = CreateControlContainer(sValueId); oValueControl.Bounds.SetParams(LeftOffset + LeftWidth, TopOffset + 1, RightOffset, 1000, true, true, true, false, -1, RowHeight - 2); oValueControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_right); oMainControl.AddControl(oValueControl); oValueElement.value = sValue; return oValueElement; }; CDrawingInfoWindow.prototype.private_CreateInfoAreaElement = function(oMainDiv, oMainControl, sDivId, sName, sValue, TopOffset, RowHeight, bCanEdit) { var LeftWidth = this.m_nLeftWidth; var LeftOffset = 10; var RightOffset = 10; RightOffset += 20; // Scroll var sNameId = sDivId + sName; var oNameElement = this.private_CreateDivElement(oMainDiv, sNameId, RowHeight); var oNameControl = CreateControlContainer(sNameId); oNameControl.Bounds.SetParams(LeftOffset, TopOffset, 1000, 1000, true, true, false, false, LeftWidth, RowHeight); oNameControl.Anchor = (g_anchor_left | g_anchor_top); oMainControl.AddControl(oNameControl); Common.Set_InnerTextToElement(oNameElement, sName); var sValueId = sNameId + "Value"; var oValueElement = document.createElement("textarea"); oValueElement.setAttribute("id", sValueId); oValueElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oValueElement.setAttribute("oncontextmenu", "return false;"); oValueElement.style.fontFamily = "Tahoma, Sans serif"; oValueElement.style.fontSize = "10pt"; oValueElement.style.resize = "none"; oValueElement.style.outline = "none"; oValueElement.style.border = "1px solid rgb(169,169,169)"; oValueElement.style.height = 3 * RowHeight + "px"; this.HtmlElement2.GameInfo = oValueElement; if (false === bCanEdit) oValueElement.disabled = "disabled"; oMainDiv.appendChild(oValueElement); var oValueControl = CreateControlContainer(sValueId); oValueControl.Bounds.SetParams(LeftOffset + LeftWidth, TopOffset + 1, RightOffset, 1000, true, true, true, false, -1, 3 * RowHeight); oValueControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_right); oMainControl.AddControl(oValueControl); oValueElement.value = sValue; return oValueElement; }; CDrawingInfoWindow.prototype.Show = function(oPr) { CDrawingInfoWindow.superclass.Show.call(this, oPr); var oGameTree = this.m_oGameTree; this.HtmlElement2.GameName.value = oGameTree.Get_GameName(); this.HtmlElement2.Result.value = oGameTree.Get_Result(); this.HtmlElement2.Rules.value = oGameTree.Get_Rules(); this.HtmlElement2.Komi.value = oGameTree.Get_Komi(); this.HtmlElement2.Handicap.value = oGameTree.Get_Handicap(); this.HtmlElement2.TimeSettings.value = oGameTree.Get_TimeLimit() + (oGameTree.Get_OverTime() === "" ? "" : " + " + oGameTree.Get_OverTime()); this.HtmlElement2.BlackName.value = oGameTree.Get_BlackName(); this.HtmlElement2.BlackRank.value = oGameTree.Get_BlackRating(); this.HtmlElement2.WhiteName.value = oGameTree.Get_WhiteName(); this.HtmlElement2.WhiteRank.value = oGameTree.Get_WhiteRating(); this.HtmlElement2.Copyright.value = oGameTree.Get_Copyright(); this.HtmlElement2.Date.value = oGameTree.Get_DateTime(); this.HtmlElement2.Event.value = oGameTree.Get_GameEvent(); this.HtmlElement2.Round.value = oGameTree.Get_GameRound(); this.HtmlElement2.Place.value = oGameTree.Get_GamePlace(); this.HtmlElement2.Annotator.value = oGameTree.Get_GameAnnotator(); this.HtmlElement2.Fuseki.value = oGameTree.Get_GameFuseki(); this.HtmlElement2.Source.value = oGameTree.Get_GameSource(); this.HtmlElement2.Transcriber.value = oGameTree.Get_GameTranscriber(); this.HtmlElement2.GameInfo.value = oGameTree.Get_GameInfo(); }; function CDrawingErrorWindow() { CDrawingErrorWindow.superclass.constructor.call(this); this.m_nW = 300; this.m_nH = 100; this.m_oMainElement = null; } CommonExtend(CDrawingErrorWindow, CDrawingWindow); CDrawingErrorWindow.prototype.Init = function(_sDivId, oPr) { CDrawingErrorWindow.superclass.Init.call(this, _sDivId, false); this.protected_UpdateSizeAndPosition(oPr.Drawing); var sText = oPr.ErrorText; var sError = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.error.caption : "Error"; this.Set_Caption(oPr.Caption ? oPr.Caption : sError); this.m_oGameTree = oPr.GameTree; this.m_oDrawing = oPr.Drawing; var oMainDiv = this.HtmlElement.InnerDiv; var oMainControl = this.HtmlElement.InnerControl; var sErrorId = _sDivId + "E"; var oErrorElement = this.private_CreateDivElement(oMainDiv, sErrorId, 20); var oErrorControl = CreateControlContainer(sErrorId); oErrorControl.Bounds.SetParams(10, 5, 10, 5, true, true, true, true, -1, -1); oErrorControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_bottom | g_anchor_right); oMainControl.AddControl(oErrorControl); this.m_oMainElement = oErrorElement; this.Show(oPr); }; CDrawingErrorWindow.prototype.Close = function() { if (this.m_oDrawing) this.m_oDrawing.Enable(); CDrawingInfoWindow.superclass.Close.call(this); }; CDrawingErrorWindow.prototype.Show = function(oPr) { CDrawingErrorWindow.superclass.Show.call(this, oPr); this.m_nW = oPr.W; this.m_nH = oPr.H; Common.Set_InnerTextToElement(this.m_oMainElement, oPr.ErrorText); if (window.g_oTextMeasurer && this.m_nW - 14 > 0) { window.g_oTextMeasurer.SetFont("15px Tahoma, 'Sans serif'"); var nTextW = window.g_oTextMeasurer.Measure(oPr.ErrorText); var nW = this.m_nW - 14; var nH = (20 * Math.ceil((nTextW / nW) + 0.5)) + 10 + 30 + 7; if (this.m_nH < nH) this.m_nH = nH; this.Update_Size(true); } if (this.m_oDrawing) { this.m_oDrawing.Disable(); this.protected_UpdateSizeAndPosition(this.m_oDrawing); this.Update_Size(true); } }; CDrawingErrorWindow.prototype.private_CreateDivElement = function(oParentElement, sName, Height) { var oElement = document.createElement("div"); oElement.setAttribute("id", sName); oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.setAttribute("oncontextmenu", "return false;"); oElement.style.fontFamily = "Tahoma, Sans serif"; oElement.style.fontSize = Height * 15 / 20 + "px"; oElement.style.lineHeight = Height + "px"; oElement.style.height = Height + "px"; oParentElement.appendChild(oElement); return oElement; }; CDrawingErrorWindow.prototype.Get_DefaultWindowSize = function() { return { W : this.m_nW, H : this.m_nH }; }; function CDrawingSettingsWindow() { CDrawingSettingsWindow.superclass.constructor.call(this); this.m_oGameTree = null; this.HtmlElement2 = { Theme : { TrueColor : null, SimpleColor : null, BookStyle : null, Dark : null }, Sound : null, LoadUnfinishedSgf : null, NavigatorLabel : null, CycleThroughVariants : null, LoadShowVariants : null, ShowTarget : null }; } CommonExtend(CDrawingSettingsWindow, CDrawingConfirmWindow); CDrawingSettingsWindow.prototype.Init = function(_sDivId, oPr) { CDrawingSettingsWindow.superclass.Init.call(this, _sDivId, false); this.protected_UpdateSizeAndPosition(oPr.Drawing); this.m_oGameTree = oPr.GameTree; this.Set_Caption("Settings"); var oTabs = new CDrawingVerticalTabs(); oTabs.Init(this.HtmlElement.ConfirmInnerDiv.id, ["Appearance", "Color Scheme", "Loading Settings"], 0, 150); this.private_CreateAppearancePage(oTabs.Get_TabContent(0), oPr); this.private_CreateColorSchemePage(oTabs.Get_TabContent(1), oPr); this.private_CreateLoadingSettingsPage(oTabs.Get_TabContent(2), oPr); }; CDrawingSettingsWindow.prototype.Get_DefaultWindowSize = function() { return {W : 400, H : 210}; }; CDrawingSettingsWindow.prototype.Show = function(oPr) { CDrawingSettingsWindow.superclass.Show.call(this, oPr); // Appearance this.HtmlElement2.CycleThroughVariants.checked = this.m_oGameTree.Is_CycleThroughVariants(); this.HtmlElement2.Sound.checked = this.m_oGameTree.Is_SoundOn(); this.HtmlElement2.NavigatorLabel.selectedIndex = this.m_oGameTree.Get_NavigatorLabel(); // ColorScheme this.private_CheckColorTheme(); // LoadingSettings this.HtmlElement2.LoadUnfinishedSgf.checked = this.m_oGameTree.Is_LoadUnfinishedFilesOnLastNode(); this.HtmlElement2.LoadShowVariants.selectedIndex = this.m_oGameTree.Get_LoadShowVariants(); }; CDrawingSettingsWindow.prototype.private_CreatePage = function(oDiv) { var oDivMainPart = document.createElement("div"); oDiv.appendChild(oDivMainPart); oDivMainPart.style.margin = "0"; oDivMainPart.style.padding = "10px 20px"; oDivMainPart.style.fontFamily = "Tahoma, Arial, Verdana"; oDivMainPart.style.fontSize = "10px"; oDivMainPart.style.color = "#666"; oDivMainPart.style.background = "#fff"; return oDivMainPart; }; CDrawingSettingsWindow.prototype.private_CreateAppearancePage = function(oDiv, oPr) { var oDivMainPart = this.private_CreatePage(oDiv); var sDivId = this.HtmlElement.ConfirmInnerDiv.id + "A"; this.HtmlElement2.ShowTarget = this.private_CreateCheckBox(oDivMainPart, sDivId + "T", this.m_oGameTree.Is_ShowTarget(), "Show target"); this.HtmlElement2.CycleThroughVariants = this.private_CreateCheckBox(oDivMainPart, sDivId + "C", this.m_oGameTree.Is_CycleThroughVariants(), "Cycle through variants"); this.HtmlElement2.Sound = this.private_CreateCheckBox(oDivMainPart, sDivId + "S", this.m_oGameTree.Is_SoundOn(), "Sound"); this.HtmlElement2.NavigatorLabel = this.private_CreateSelect(oDivMainPart, sDivId + "N", this.m_oGameTree.Get_NavigatorLabel(), ["No labels", "Move numbers", "Move numbers current variant only", "Move coordinates"], "Labels in navigator"); }; CDrawingSettingsWindow.prototype.private_CreateColorSchemePage = function(oDiv, oPr) { var oDivMainPart = this.private_CreatePage(oDiv); var sDivId = this.HtmlElement.ConfirmInnerDiv.id + "CS"; var sThemeId = "ThemeId"; this.HtmlElement2.Theme.TrueColor = this.private_CreateRadioButton(oDivMainPart, sDivId + "TC", sThemeId, "TrueColor"); this.HtmlElement2.Theme.SimpleColor = this.private_CreateRadioButton(oDivMainPart, sDivId + "SC", sThemeId, "SimpleColor"); this.HtmlElement2.Theme.BookStyle = this.private_CreateRadioButton(oDivMainPart, sDivId + "BS", sThemeId, "BookStyle"); this.HtmlElement2.Theme.Dark = this.private_CreateRadioButton(oDivMainPart, sDivId + "D", sThemeId, "Dark"); this.private_CheckColorTheme(); }; CDrawingSettingsWindow.prototype.private_CreateLoadingSettingsPage = function(oDiv, oPr) { var oDivMainPart = this.private_CreatePage(oDiv); var sDivId = this.HtmlElement.ConfirmInnerDiv.id + "LS"; this.HtmlElement2.LoadUnfinishedSgf = this.private_CreateCheckBox(oDivMainPart, sDivId + "U", this.m_oGameTree.Is_LoadUnfinishedFilesOnLastNode(), "Load unfinished files on the last node"); this.HtmlElement2.LoadShowVariants = this.private_CreateSelect(oDivMainPart, sDivId + "V", this.m_oGameTree.Get_LoadShowVariants(), ["Don't show variants", "Show variations of current node (siblings)", "Show variations of successor node (children)", "Load option from file"], "Show variants"); }; CDrawingSettingsWindow.prototype.Handle_OK = function() { var eColorScheme = EColorScheme.TrueColor; if (this.HtmlElement2.Theme.SimpleColor.checked) eColorScheme = EColorScheme.SimpleColor; else if (this.HtmlElement2.Theme.BookStyle.checked) eColorScheme = EColorScheme.BookStyle; else if (this.HtmlElement2.Theme.Dark.checked) eColorScheme = EColorScheme.Dark; else // TrueColor eColorScheme = EColorScheme.TrueColor; var oSchemeChange = g_oGlobalSettings.Set_ColorScheme(eColorScheme); this.m_oGameTree.Toggle_Sound(this.HtmlElement2.Sound.checked ? true : false, false); this.m_oGameTree.Set_ShowTarget(this.HtmlElement2.ShowTarget.checked ? true : false); this.m_oGameTree.Set_LoadUnfinishedFilesOnLastNode(this.HtmlElement2.LoadUnfinishedSgf.checked ? true : false); this.m_oGameTree.Set_NavigatorLabel(this.HtmlElement2.NavigatorLabel.selectedIndex); this.m_oGameTree.Set_CycleThroughVariants(this.HtmlElement2.CycleThroughVariants.checked ? true : false); this.m_oGameTree.Set_LoadShowVariants(this.HtmlElement2.LoadShowVariants.selectedIndex); var oBoard = this.m_oGameTree.Get_DrawingBoard(); var oNavigator = this.m_oGameTree.Get_DrawingNavigator(); if (oBoard && true === oSchemeChange.Board) oBoard.Update_Size(true); if (oNavigator && true === oSchemeChange.Navigator) oNavigator.Update_All(); this.Close(); }; CDrawingSettingsWindow.prototype.private_CreateRadioButton = function(oParentElement, sName, sRadioIs, sRadioValue) { var oMainElement = document.createElement("div"); oMainElement.style.paddingLeft = "10px"; oMainElement.style.paddingBottom = "5px"; oParentElement.appendChild(oMainElement); var oElement = document.createElement("input"); oElement.type = "radio"; oElement.name = sRadioIs; oElement.value = sRadioValue; oElement.setAttribute("id", sName); oMainElement.appendChild(oElement); var oSpan = document.createElement("span"); oSpan.setAttribute("oncontextmenu", "return false;"); oSpan.style.fontFamily = "Tahoma, Sans serif"; Common.Set_InnerTextToElement(oSpan, sRadioValue); oSpan.style.fontFamily = "Tahoma, Sans serif"; oSpan.style.fontSize = "12pt"; oSpan.style.height = "15px"; oSpan.style.lineHeight = "15px"; oSpan.style.cursor = "default"; oMainElement.appendChild(oSpan); oSpan.addEventListener("click", function() { oElement.checked = true; }, false); return oElement; }; CDrawingSettingsWindow.prototype.private_CreateCheckBox = function(oParentElement, sName, bChecked, sCheckboxName) { var oMainElement = document.createElement("div"); oMainElement.style.paddingLeft = "10px"; oMainElement.style.paddingBottom = "5px"; oParentElement.appendChild(oMainElement); var oElement = document.createElement("input"); oElement.type = "checkbox"; oElement.checked = bChecked; oElement.setAttribute("id", sName); oMainElement.appendChild(oElement); var oSpan = document.createElement("span"); oSpan.setAttribute("oncontextmenu", "return false;"); oSpan.style.fontFamily = "Tahoma, Sans serif"; Common.Set_InnerTextToElement(oSpan, sCheckboxName); oSpan.style.fontFamily = "Tahoma, Sans serif"; oSpan.style.fontSize = "12pt"; oSpan.style.height = "15px"; oSpan.style.lineHeight = "15px"; oSpan.style.cursor = "default"; oMainElement.appendChild(oSpan); oSpan.addEventListener("click", function() { oElement.checked = !oElement.checked; }, false); return oElement; }; CDrawingSettingsWindow.prototype.private_CreateSelect = function(oParentElement, sName, nSelectedIndex, aElements, sLabelText) { var oMainElement = document.createElement("div"); oMainElement.style.paddingLeft = "10px"; oMainElement.style.paddingBottom = "5px"; oMainElement.style.fontFamily = "Tahoma, Sans serif"; oMainElement.style.fontSize = "9pt"; oMainElement.style.height = "12px"; oMainElement.style.lineHeight = "12px"; oParentElement.appendChild(oMainElement); var oLabel = document.createElement("div"); Common.Set_InnerTextToElement(oLabel, sLabelText); oLabel.style.paddingBottom = "5px"; oMainElement.appendChild(oLabel); var oSelect = document.createElement("select"); oSelect.style.width = "170px"; for (var nIndex = 0, nCount = aElements.length; nIndex < nCount; nIndex++) { var oOption = document.createElement("option"); oOption.value = aElements[nIndex]; Common.Set_InnerTextToElement(oOption, aElements[nIndex]); oSelect.appendChild(oOption); } oSelect.selectedIndex = nSelectedIndex; oMainElement.appendChild(oSelect); return oSelect; }; CDrawingSettingsWindow.prototype.private_CheckColorTheme = function() { var oBoardColorR = g_oGlobalSettings.m_oBoardPr.oBoardColor.r; if (231 === oBoardColorR) { // Simple or TrueColor if (g_oGlobalSettings.m_oBoardPr.bTrueColorBoard) this.HtmlElement2.Theme.TrueColor.checked = true; else this.HtmlElement2.Theme.SimpleColor.checked = true; } else if (255 === oBoardColorR) { this.HtmlElement2.Theme.BookStyle.checked = true; } else if (30 === oBoardColorR) { this.HtmlElement2.Theme.Dark.checked = true; } else { this.HtmlElement2.Theme.TrueColor.checked = true; } }; function CDrawingScoreEstimateWindow() { CDrawingScoreEstimateWindow.superclass.constructor.call(this); this.m_oDrawingBoard = null; } CommonExtend(CDrawingScoreEstimateWindow, CDrawingWindow); CDrawingScoreEstimateWindow.prototype.Init = function(_sDivId, oPr) { CDrawingScoreEstimateWindow.superclass.Init.call(this, _sDivId, true); this.protected_UpdateSizeAndPosition(oPr.Drawing); this.m_oGameTree = oPr.GameTree; this.Set_Caption("Score estimate"); var oMainDiv = this.HtmlElement.InnerDiv; var oMainControl = this.HtmlElement.InnerControl; var sMainId = this.HtmlElement.InnerDiv.id; oMainDiv.style.background = "url(\'" + g_sBackground + "\')"; var oDrawingBoard = new CDrawingBoard(); oMainControl.Set_Type(2, oDrawingBoard); var sBoard = sMainId + "B"; var oBoardElement = this.protected_CreateDivElement(oMainDiv, sBoard); var oBoardControl = CreateControlContainer(sBoard); oBoardControl.Bounds.SetParams(0, 0, 1000, 1000, true, true, false, false, -1, -1); oBoardControl.Anchor = (g_anchor_top | g_anchor_left | g_anchor_bottom | g_anchor_right); oMainControl.AddControl(oBoardControl); this.m_oBoardDiv = oBoardElement; this.m_oBoardControl = oBoardControl; oDrawingBoard.Init(sBoard, this.m_oGameTree.Copy_ForScoreEstimate()); oDrawingBoard.Set_EstimateMode(this); this.m_oDrawingBoard = oDrawingBoard; }; CDrawingScoreEstimateWindow.prototype.Update_Size = function(bForce) { CDrawingScoreEstimateWindow.superclass.Update_Size.call(this, bForce); if (this.m_oDrawingBoard) this.m_oDrawingBoard.Update_Size(bForce); }; CDrawingScoreEstimateWindow.prototype.On_EstimateEnd = function(BlackReal, WhiteReal, BlackPotential, WhitePotential, nResult) { var sCaption; if (window.g_oLocalization) sCaption = window.g_oLocalization.common.shortBlack + " " + BlackReal + "(" + BlackPotential + ") " + window.g_oLocalization.common.shortWhite + " " + WhiteReal + "(" + WhitePotential + ") " + (nResult > 0 ? window.g_oLocalization.common.shortBlack + "+" + nResult : (nResult < 0 ? window.g_oLocalization.common.shortWhite + "+" + Math.abs(nResult) : window.g_oLocalization.common.gameResult.even)); else sCaption = "B " + BlackReal + "(" + BlackPotential + ") W " + WhiteReal + "(" + WhitePotential + ") " + (nResult > 0 ? "B+" + nResult : (nResult < 0 ? "W+" + Math.abs(nResult) : "Even")); this.Set_Caption(sCaption); }; CDrawingScoreEstimateWindow.prototype.Show = function(oPr) { while (this.m_oBoardDiv.firstChild) this.m_oBoardDiv.removeChild(this.m_oBoardDiv.firstChild); if (this.m_oBoardControl) this.m_oBoardControl.Clear(); var oDrawingBoard = new CDrawingBoard(); oDrawingBoard.Init(this.m_oBoardDiv.id, oPr.GameTree.Copy_ForScoreEstimate()); oDrawingBoard.Set_EstimateMode(this); this.m_oDrawingBoard = oDrawingBoard; CDrawingScoreEstimateWindow.superclass.Show.apply(this, arguments); // Для перерисовки позиции this.Update_Size(true); }; function CDrawingCountColorsWindow() { CDrawingCountColorsWindow.superclass.constructor.call(this); this.m_nLeftWidth = 100; } CommonExtend(CDrawingCountColorsWindow, CDrawingWindow); CDrawingCountColorsWindow.prototype.Init = function(_sDivId, oPr) { CDrawingCountColorsWindow.superclass.Init.call(this, _sDivId, false); var sCaption = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.colorsCounter.caption : "Counter of colors"; var sRed = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.colorsCounter.red : "Red"; var sBlue = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.colorsCounter.blue : "Blue"; var sGreen = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.colorsCounter.green : "Green"; var sGray = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.colorsCounter.gray : "Gray"; if (window.g_oTextMeasurer) { window.g_oTextMeasurer.SetFont("15px Tahoma, 'Sans serif'"); this.m_nLeftWidth = Math.max( window.g_oTextMeasurer.Measure(sRed), window.g_oTextMeasurer.Measure(sBlue), window.g_oTextMeasurer.Measure(sGreen), window.g_oTextMeasurer.Measure(sGray) ) + 12; } this.m_oGameTree = oPr.GameTree; this.m_oDrawingBoard = oPr.DrawingBoard; this.protected_UpdateSizeAndPosition(oPr.Drawing); this.Set_Caption(sCaption); var oMainDiv = this.HtmlElement.InnerDiv; var oMainControl = this.HtmlElement.InnerControl; var sDivId = this.HtmlElement.InnerDiv.id; oMainDiv.style.overflowX = "hidden"; oMainDiv.style.overflowY = "hidden"; var RowHeight = 20; var TopOffset = 10; var LineSpacing = 5; var BottomOffset = 10; var oColorsMap = oPr.DrawingBoard.m_oColorMarks; var Red = [0, 0, 0, 0], Green = [0, 0, 0, 0], Blue = [0, 0, 0, 0], Gray = [0, 0, 0, 0]; var bRed = false, bGreen = false, bBlue = false, bGray = false; for (var oPos in oColorsMap) { var oColor = oColorsMap[oPos]; var nNum = -1; if (0 !== oColor.r && 0 !== oColor.g && 0 !== oColor.b) { bGray = true; nNum = 3; } else if (0 !== oColor.r) { bRed = true; nNum = 0; } else if (0 !== oColor.g) { bGreen = true; nNum = 1; } else if (0 !== oColor.b) { bBlue = true; nNum = 2; } var Index = 0; if (oColor.a <= 50) Index = 0; else if (oColor.a <= 100) Index = 1; else if (oColor.a <= 150) Index = 2; else Index = 3; switch (nNum) { case 0: Red[Index]++; break; case 1: Green[Index]++; break; case 2: Blue[Index]++; break; case 3: Gray[Index]++; break; } } this.Red = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sRed, "4 x " + Red[3] + "+ 3 x " + Red[2] + " + 2 x " + Red[1] + " + 1 x " + Red[0] + " =" + (4 * Red[3] + 3 * Red[2] + 2 * Red[1] + Red[0]), TopOffset, RowHeight); TopOffset += RowHeight + LineSpacing; this.Green = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sGreen, "4 x " + Green[3] + "+ 3 x " + Green[2] + " + 2 x " + Green[1] + " + 1 x " + Green[0] + " =" + (4 * Green[3] + 3 * Green[2] + 2 * Green[1] + Green[0]), TopOffset, RowHeight); TopOffset += RowHeight + LineSpacing; this.Blue = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sBlue, "4 x " + Blue[3] + "+ 3 x " + Blue[2] + " + 2 x " + Blue[1] + " + 1 x " + Blue[0] + " =" + (4 * Blue[3] + 3 * Blue[2] + 2 * Blue[1] + Blue[0]), TopOffset, RowHeight); TopOffset += RowHeight + LineSpacing; this.Gray = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, sGray, "4 x " + Gray[3] + "+ 3 x " + Gray[2] + " + 2 x " + Gray[1] + " + 1 x " + Gray[0] + " =" + (4 * Gray[3] + 3 * Gray[2] + 2 * Gray[1] + Gray[0]), TopOffset, RowHeight); TopOffset += RowHeight + LineSpacing; this.protected_CreateDivElement(oMainDiv, sDivId + "Bottom"); var BottomControl = CreateControlContainer(sDivId + "Bottom"); BottomControl.Bounds.SetParams(0, TopOffset, 1000, 1000, true, true, false, false, 0, BottomOffset); BottomControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_right); oMainControl.AddControl(BottomControl); }; CDrawingCountColorsWindow.prototype.private_CreateDivElement = function(oParentElement, sName, Height) { var oElement = document.createElement("div"); oElement.setAttribute("id", sName); oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.setAttribute("oncontextmenu", "return false;"); oElement.style.fontFamily = "Tahoma, Sans serif"; oElement.style.fontSize = Height * 15 / 20 + "px"; oElement.style.lineHeight = Height + "px"; oElement.style.height = Height + "px"; oParentElement.appendChild(oElement); return oElement; }; CDrawingCountColorsWindow.prototype.private_CreateInputElement = function(oParentElement, sName) { var oElement = document.createElement("input"); oElement.setAttribute("id", sName); oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.setAttribute("oncontextmenu", "return false;"); oElement.setAttribute("type", "text"); oElement.style.fontFamily = "Tahoma, Sans serif"; oElement.style.fontSize = "10pt"; oElement.style.outline = "none"; oElement.disabled = "disabled"; oParentElement.appendChild(oElement); return oElement; }; CDrawingCountColorsWindow.prototype.private_CreateInfoElement = function(oMainDiv, oMainControl, sDivId, sName, sValue, TopOffset, RowHeight, bCanEdit) { var LeftWidth = this.m_nLeftWidth; var LeftOffset = 10; var RightOffset = 10; RightOffset += 20; // Scroll var sNameId = sDivId + sName; var oNameElement = this.private_CreateDivElement(oMainDiv, sNameId, RowHeight); var oNameControl = CreateControlContainer(sNameId); oNameControl.Bounds.SetParams(LeftOffset, TopOffset, 1000, 1000, true, true, false, false, LeftWidth, RowHeight); oNameControl.Anchor = (g_anchor_left | g_anchor_top); oMainControl.AddControl(oNameControl); Common.Set_InnerTextToElement(oNameElement, sName); var sValueId = sNameId + "Value"; var oValueElement = this.private_CreateInputElement(oMainDiv, sValueId, bCanEdit); var oValueControl = CreateControlContainer(sValueId); oValueControl.Bounds.SetParams(LeftOffset + LeftWidth, TopOffset + 1, RightOffset, 1000, true, true, true, false, -1, RowHeight - 2); oValueControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_right); oMainControl.AddControl(oValueControl); oValueElement.value = sValue; return oValueElement; }; CDrawingCountColorsWindow.prototype.Show = function(oPr) { CDrawingCountColorsWindow.superclass.Show.call(this, oPr); this.m_oGameTree = oPr.GameTree; this.m_oDrawingBoard = oPr.DrawingBoard; this.Update(); }; CDrawingCountColorsWindow.prototype.Update = function(oPr) { if (!this.Is_Visible()) return; if (!this.m_oDrawingBoard) return; var oColorsMap = this.m_oDrawingBoard.m_oColorMarks; var Red = [0, 0, 0, 0], Green = [0, 0, 0, 0], Blue = [0, 0, 0, 0], Gray = [0, 0, 0, 0]; var bRed = false, bGreen = false, bBlue = false, bGray = false; for (var oPos in oColorsMap) { var oColor = oColorsMap[oPos]; var nNum = -1; if (0 !== oColor.r && 0 !== oColor.g && 0 !== oColor.b) { bGray = true; nNum = 3; } else if (0 !== oColor.r) { bRed = true; nNum = 0; } else if (0 !== oColor.g) { bGreen = true; nNum = 1; } else if (0 !== oColor.b) { bBlue = true; nNum = 2; } var Index = 0; if (oColor.a <= 50) Index = 0; else if (oColor.a <= 100) Index = 1; else if (oColor.a <= 150) Index = 2; else Index = 3; switch (nNum) { case 0: Red[Index]++; break; case 1: Green[Index]++; break; case 2: Blue[Index]++; break; case 3: Gray[Index]++; break; } } this.Red.value = "4 x " + Red[3] + "+ 3 x " + Red[2] + " + 2 x " + Red[1] + " + 1 x " + Red[0] + " =" + (4 * Red[3] + 3 * Red[2] + 2 * Red[1] + Red[0]); this.Green.value = "4 x " + Green[3] + "+ 3 x " + Green[2] + " + 2 x " + Green[1] + " + 1 x " + Green[0] + " =" + (4 * Green[3] + 3 * Green[2] + 2 * Green[1] + Green[0]); this.Blue.value = "4 x " + Blue[3] + "+ 3 x " + Blue[2] + " + 2 x " + Blue[1] + " + 1 x " + Blue[0] + " =" + (4 * Blue[3] + 3 * Blue[2] + 2 * Blue[1] + Blue[0]); this.Gray.value = "4 x " + Gray[3] + "+ 3 x " + Gray[2] + " + 2 x " + Gray[1] + " + 1 x " + Gray[0] + " =" + (4 * Gray[3] + 3 * Gray[2] + 2 * Gray[1] + Gray[0]); }; CDrawingCountColorsWindow.prototype.Get_DefaultWindowSize = function() { return {W : 410, H : 160}; }; function CDrawingGifWriterWindow() { CDrawingGifWriterWindow.superclass.constructor.call(this); this.m_oProgressSliderElement = null; this.m_oProgressValueElement = null; this.m_oDrawing = null; this.m_oGameTree = null; } CommonExtend(CDrawingGifWriterWindow, CDrawingWindow); CDrawingGifWriterWindow.prototype.Init = function(_sDivId, oPr) { CDrawingGifWriterWindow.superclass.Init.call(this, _sDivId, false); this.protected_UpdateSizeAndPosition(oPr.Drawing); var sCaption = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.creatingGIF.caption : "Creating Gif file..."; this.Set_Caption(sCaption); if (oPr.GameTree) this.m_oGameTree = oPr.GameTree; var oMainDiv = this.HtmlElement.InnerDiv; var oMainControl = this.HtmlElement.InnerControl; var sDivId = this.HtmlElement.InnerDiv.id; var sProgressBack = sDivId + "PB"; var oProgressBackElement = this.protected_CreateDivElement(oMainDiv, sProgressBack); var oProgressBackControl = CreateControlContainer(sProgressBack); oProgressBackControl.Bounds.SetParams(6, 30, 8, 8, true, true, true, true, -1,-1); oProgressBackControl.Anchor = (g_anchor_top | g_anchor_left | g_anchor_bottom | g_anchor_right); oMainControl.AddControl(oProgressBackControl); oProgressBackElement.style.border = "1px solid rgb(221,221,221)"; oProgressBackElement.style.backgroundColor = "rgb(140, 140, 140)"; var sProgress = sDivId + "P"; var oProgressElement = this.protected_CreateDivElement(oMainDiv, sProgress); var oProgressControl = CreateControlContainer(sProgress); oProgressControl.Bounds.SetParams(7, 31, 0, 7, true, true, false, true, 10,-1); oProgressControl.Anchor = (g_anchor_top | g_anchor_left | g_anchor_bottom); oMainControl.AddControl(oProgressControl); oProgressElement.style.backgroundColor = "rgb(54, 101, 179)"; this.m_oProgressSliderElement = oProgressElement; var sDigitProgress = sDivId + "PV"; var oDigitProgressElement = this.protected_CreateDivElement(oMainDiv, sDigitProgress); var oDigitProgressControl = CreateControlContainer(sDigitProgress); oDigitProgressControl.Bounds.SetParams(0, 7, 1000, 32, false, false, false, true, -1, -1); oDigitProgressControl.Anchor = (g_anchor_top | g_anchor_left | g_anchor_bottom); oMainControl.AddControl(oDigitProgressControl); oDigitProgressElement.style.fontFamily = "Tahoma, Sans serif"; oDigitProgressElement.style.fontSize = 20 * 15 / 20 + "px"; oDigitProgressElement.style.lineHeight = 20 + "px"; oDigitProgressElement.style.height = 20 + "px"; oDigitProgressElement.style.color = "rgb(0, 0, 0)"; oDigitProgressElement.style.textAlign = "center"; this.m_oProgressValueElement = oDigitProgressElement; }; CDrawingGifWriterWindow.prototype.Get_DefaultWindowSize = function() { return {W : 240, H : 100}; }; CDrawingGifWriterWindow.prototype.On_Progress = function(Progress) { var dWidth = 214; this.m_oProgressSliderElement.style.width = (Progress / 100 * dWidth) + "px"; var dValue = (Progress * 100 | 0) / 100; Common.Set_InnerTextToElement(this.m_oProgressValueElement, dValue + "%"); }; CDrawingGifWriterWindow.prototype.On_Start = function() { this.On_Progress(0); if (this.m_oDrawing) this.m_oDrawing.Disable(); }; CDrawingGifWriterWindow.prototype.On_End = function() { this.On_Progress(100); var oThis = this; function Close() { oThis.Close(true); } // Закрываем окно не сразу, чтобы показать 100% setTimeout(Close, 300); }; CDrawingGifWriterWindow.prototype.Close = function(bEnd) { if (true !== bEnd) { if (this.m_oGameTree) this.m_oGameTree.Abort_DownloadGid(); } if (this.m_oDrawing) this.m_oDrawing.Enable(); CDrawingGifWriterWindow.superclass.Close.apply(this); }; function CDrawingAboutWindow() { CDrawingAboutWindow.superclass.constructor.call(this); this.m_oDrawingBoard = null; } CommonExtend(CDrawingAboutWindow, CDrawingWindow); CDrawingAboutWindow.prototype.Init = function(_sDivId, oPr) { CDrawingGifWriterWindow.superclass.Init.call(this, _sDivId, true); this.protected_UpdateSizeAndPosition(oPr.Drawing); this.Set_Caption("About"); this.m_oGameTree = oPr.GameTree; var oTabs = new CDrawingVerticalTabs(); oTabs.Init(this.HtmlElement.InnerDiv.id, ["About Web Go Board", "Keyboard Shortcuts"], 0); this.private_InitAboutPage(oTabs.Get_TabContent(0)); this.private_InitKeyBoardShortcutsPage(oTabs.Get_TabContent(1), oPr); }; CDrawingAboutWindow.prototype.Get_DefaultWindowSize = function() { if (this.m_oDrawing) { var nDrawingW = this.m_oDrawing.Get_Width(); var nDrawingH = this.m_oDrawing.Get_Height(); var nWindowW = Math.max(100, Math.min(700, nDrawingW * 0.9)); var nWindowH = Math.max(100, Math.min(600, nDrawingH * 0.9)); return {W : nWindowW, H : nWindowH}; } return null; }; CDrawingAboutWindow.prototype.private_InitAboutPage = function(oDiv) { var oDivMainPart = document.createElement("div"); oDiv.appendChild(oDivMainPart); oDiv.style.overflowX = "hidden"; oDiv.style.overflowY = "scroll"; oDivMainPart.style.margin = "0"; oDivMainPart.style.padding = "10px 20px"; oDivMainPart.style.fontFamily = "Tahoma, Arial, Verdana"; oDivMainPart.style.fontSize = "12px"; oDivMainPart.style.color = "#666"; oDivMainPart.style.background = "#fff"; var oLogo = document.createElement("img"); oLogo.src = g_sLogo100; oLogo.width = 100; oLogo.height = 100; oLogo.style['float'] = "left"; oDivMainPart.appendChild(oLogo); var oMargin = document.createElement("div"); oMargin.style.width = "10px"; oMargin.style.height = "100px"; oMargin.style['float'] = "left"; oDivMainPart.appendChild(oMargin); var oHeading = document.createElement("h1"); oDivMainPart.appendChild(oHeading); Common.Set_InnerTextToElement(oHeading, "Web Go/Baduk Board"); var oVersion = document.createElement("div"); oDivMainPart.appendChild(oVersion); Common.Set_InnerTextToElement(oVersion, "Version " + GoBoardApi.Get_Version()); var oString = document.createElement("div"); oString.style.paddingTop = "40px"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "Visit our Github project for feedback and issue reports:"); oString = document.createElement("a"); oString.target = "_blank"; oString.href = "https://github.com/IlyaKirillov/GoProject"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "https://github.com/IlyaKirillov/GoProject"); oString = document.createElement("div"); oString.style.paddingTop = "20px"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "Our site:"); oString = document.createElement("a"); oString.target = "_blank"; oString.href = "http://webgoboard.net/"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "http://webgoboard.net/"); oString = document.createElement("div"); oString.style.paddingTop = "20px"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "Discussions:"); oString = document.createElement("a"); oString.target = "_blank"; oString.href = "http://www.lifein19x19.com/forum/viewtopic.php?f=18&t=11239"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "http://www.lifein19x19.com/"); oDivMainPart.appendChild(document.createElement("br")); oString = document.createElement("a"); oString.target = "_blank"; oString.href = "http://kido.com.ru/253-web-go-doska"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "http://kido.com.ru/"); oString = document.createElement("div"); oString.style.paddingTop = "20px"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "Browsers extension:"); oString = document.createElement("a"); oString.target = "_blank"; oString.href = "https://chrome.google.com/webstore/detail/web-go-board/cdmhoehokaoghadonjfdbhieajggfbmd"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "Chrome and OperaNext"); oDivMainPart.appendChild(document.createElement("br")); oString = document.createElement("a"); oString.target = "_blank"; oString.href = "https://addons.mozilla.org/ru/firefox/addon/web-gobaduk-board/"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "FireFox"); oString = document.createElement("div"); oString.style.paddingTop = "30px"; oDivMainPart.appendChild(oString); Common.Set_InnerTextToElement(oString, "© Ilya Kirillov, 2014-2021. All rights reserved."); }; CDrawingAboutWindow.prototype.private_InitKeyBoardShortcutsPage = function(oDiv, oPr) { var oMainDiv = oDiv; oMainDiv.style.overflowX = "hidden"; oMainDiv.style.overflowY = "scroll"; var oDivMainPart = document.createElement("div"); oMainDiv.appendChild(oDivMainPart); oDivMainPart.style.margin = "0"; oDivMainPart.style.padding = "10px 20px"; oDivMainPart.style.fontFamily = "Tahoma, Arial, Verdana"; oDivMainPart.style.fontSize = "12px"; oDivMainPart.style.color = "#666"; oDivMainPart.style.background = "#fff"; var oHeading = document.createElement("h1"); oDivMainPart.appendChild(oHeading); Common.Set_InnerTextToElement(oHeading, "Keyboard Shortcuts"); oHeading.style.fontSize = "16px"; oHeading.style.fontWeight = "bold"; var oTable = document.createElement("table"); oDivMainPart.appendChild(oTable); oTable.style.margin = "20px 0"; oTable.style.width = "100%"; var oTBody = document.createElement("tbody"); oTable.appendChild(oTBody); this.m_oDrawingBoard = null; if (oPr.GameTree) this.m_oDrawingBoard = oPr.GameTree.Get_DrawingBoard(); this.private_AppendTableHeading1(oTBody, "Working with Files"); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 79, ShiftKey : false}, "Open Sgf/Gib/Ngf", "Ctrl+O", "Open the Sgf/Gib/Ngf file from disk. (Not in color mode, see below)"); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 79, ShiftKey : true }, "Open Sgf", "Ctrl+Shift+O", "Open the Sgf file from source. (Not in color mode, see below)"); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 67, ShiftKey : false}, "Create new", "Ctrl+C", "Create new empty board. (not in color mode see below)"); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 83, ShiftKey : false}, "Save Sgf", "Ctrl+S", "Save Sgf file."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 72, ShiftKey : false}, "Save png shot", "Ctrl+H", "Save board shot in png format."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 72, ShiftKey : true }, "Save gif shot", "Ctrl+Shift+H", "Save board shot in gif format."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 73, ShiftKey : false}, "Save multipage gif file.", "Ctrl+I", "Save gif file for current variant."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 73, ShiftKey : true }, "Save multipage gif file.", "Ctrl+Shift+I", "Save gif file for all branches with comment RIGHT (for problem mode)."); this.private_AppendTableHeading1(oTBody, "Navigation"); this.private_AppendTableCommonString(oTBody, {CtrlKey : false, KeyCode : 39, ShiftKey : false}, "Next node", "Right arrow", "Jump to next node."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 39, ShiftKey : false}, "Next 5 node", "Ctrl+Right arrow", "Jump over 5 nodes."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 39, ShiftKey : true }, "End of the variant", "Ctrl+Shift+Right arrow", "Jump to the end of the current variant."); this.private_AppendTableCommonString(oTBody, {CtrlKey : false, KeyCode : 37, ShiftKey : false}, "Previous node", "Left arrow", "Jump to previous node."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 37, ShiftKey : false}, "Previous 5 node", "Shift+Left arrow", "Jump back over 5 nodes."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 37, ShiftKey : true }, "Start of the file", "Ctrl+Shift+Right arrow", "Jump to the start of the file."); this.private_AppendTableCommonString(oTBody, {CtrlKey : false, KeyCode : 38, ShiftKey : false}, "Previous variant", "Up arrow", "Jump to previous variant."); this.private_AppendTableCommonString(oTBody, {CtrlKey : false, KeyCode : 40, ShiftKey : false}, "Next variant", "Down arrow", "Jump to next variant."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 36, ShiftKey : true}, "Start node", "Ctrl+Shift+Home", "Jump to the start node of the file. This node can be different from the first node. See \"load unfinished files\" checkbox in settings."); this.private_AppendTableHeading2(oTBody, {CtrlKey : false, KeyCode : 112, ShiftKey : false}, "Play mode", "F1"); this.private_AppendTableCommonString(oTBody, {}, "Add move", "Left mouse click", "Set sequentially stones."); this.private_AppendTableCommonString(oTBody, {}, "Add alternative move", "Right mouse click", "Create new brunch and add alternative move."); this.private_AppendTableCommonString(oTBody, {}, "Go to the point", "Shift+Left mouse click onto a board position", "Teleports you to the moment of the game forth or back, when the stone on this position has been played."); this.private_AppendTableCommonString(oTBody, {}, "Change move order", "Ctrl+Shift+Left mouse click", "When sequentially stones are entered: changes the colour of the next stone to be set. What stone will appear on the board is shown by the tools field (useful e.g. after a problem has been set up)."); this.private_AppendTableCommonString(oTBody, {}, "Add comment with coordinates", "Ctrl+Left mouse click", "Add comment with coordinates."); this.private_AppendTableHeading2(oTBody, {CtrlKey : false, KeyCode : 113, ShiftKey : false}, "Count scores", "F2"); this.private_AppendTableCommonString(oTBody, {}, "Mark dead groups", "Left mouse click", "Mark dead groups."); this.private_AppendTableCommonString(oTBody, {}, "End count scores", "Ctrl+Left mouse click onto board", "Return to play mode."); this.private_AppendTableHeading2(oTBody, {CtrlKey : false, KeyCode : 114, ShiftKey : false}, "Set up a board position", "F3"); this.private_AppendTableCommonString(oTBody, {}, "Add black stone or remove stone", "Left mouse click", "Add black stone or remove stone."); this.private_AppendTableCommonString(oTBody, {}, "Add white stone or remove stone", "Shift+Left mouse click", "Add white stone or remove stone."); this.private_AppendTableHeading3(oTBody, {CtrlKey : false, KeyCode : 115, ShiftKey : false}, "Triangles", "F4", "Add triangles."); this.private_AppendTableHeading3(oTBody, {CtrlKey : false, KeyCode : 116, ShiftKey : false}, "Squares", "F5", "Add squares."); this.private_AppendTableHeading3(oTBody, {CtrlKey : false, KeyCode : 117, ShiftKey : false}, "Circles", "F6", "Add circles."); this.private_AppendTableHeading3(oTBody, {CtrlKey : false, KeyCode : 118, ShiftKey : false}, "X mark", "F7", "Add \"X\" mark."); this.private_AppendTableHeading2(oTBody, {CtrlKey : false, KeyCode : 119, ShiftKey : false}, "Text label", "F8"); this.private_AppendTableCommonString(oTBody, {}, "Letter", "Left mouse click", "Add letter."); this.private_AppendTableCommonString(oTBody, {}, "Text", "Shift+Left mouse click", "Add text entered by the user."); this.private_AppendTableHeading2(oTBody, {CtrlKey : false, KeyCode : 120, ShiftKey : false}, "Numeric label", "F9"); this.private_AppendTableCommonString(oTBody, {}, "Number", "Left mouse click", "Add the smallest positive number."); this.private_AppendTableCommonString(oTBody, {}, "Move number", "Shift+Left mouse click", "Add number of the first move which was played here."); this.private_AppendTableHeading2(oTBody, {CtrlKey : false, KeyCode : 121, ShiftKey : false}, "Color mode", "F10"); this.private_AppendTableCommonString(oTBody, {}, "Blue region", "Left mouse click", "Add blue region."); this.private_AppendTableCommonString(oTBody, {}, "Green region", "Shift+Left mouse click", "Add green region."); this.private_AppendTableCommonString(oTBody, {}, "Red region", "Ctrl+Left mouse click", "Add red region."); this.private_AppendTableCommonString(oTBody, {}, "Gray region", "Ctrl+Shift+Left mouse click", "Add gray region."); this.private_AppendTableCommonString(oTBody, {}, "Clear region", "Right mouse click", "Clear region."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 67, ShiftKey : false}, "Continue", "Ctrl+C", "Copy all colors from previous node."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 79, ShiftKey : false}, "Count colors", "Ctrl+O", "Count all colors with depth."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 82, ShiftKey : false}, "Clear colors", "Ctrl+R", "Clear all colors in the current node."); this.private_AppendTableHeading1(oTBody, "Miscellaneous"); this.private_AppendTableCommonString(oTBody, {CtrlKey : false, KeyCode : 8, ShiftKey : false}, "Remove node", "Backspace/Delete", "Deletes the current node and all of the following brunches."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 69, ShiftKey : false}, "Score estimator", "Ctrl+E", "Show window with score estimator (you can mark dead groups by click on them)."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 86, ShiftKey : false}, "View mode change of the next move", "Ctrl+V", "There are 3 mods: Show all next move variants, show all alternative variants of the current move, show nothing."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 82, ShiftKey : false}, "Show/Hide coordinates", "Ctrl+R", "Show/Hide coordinates. (Not in color mode, see above)"); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 77, ShiftKey : true }, "Make the current variant mainly", "Ctrl+Shift+M", "Make the current variant mainly by uplifting it to the root of the game tree."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 85, ShiftKey : true }, "Lift up the current variant", "Ctrl+Shift+U", "Lift up the current variant."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 68, ShiftKey : true }, "Lower down the current variant", "Ctrl+Shift+D", "Lower down the current variant."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 86, ShiftKey : true }, "Setting up view port", "Ctrl+Shift+V", "Setting up visible part of the board."); this.private_AppendTableCommonString(oTBody, {CtrlKey : true, KeyCode : 68, ShiftKey : false}, "Ascii Diagram", "Ctrl+D", "Make ascii diagram by current position."); }; CDrawingAboutWindow.prototype.private_AppendTR = function(oTBody) { var oTr = document.createElement("tr"); oTBody.appendChild(oTr); oTr.style.borderLeft = "0"; oTr.style.borderRight = "0"; oTr.style.borderBottom = "solid 1px #E4E4E4"; oTr.style.borderCollapse = "collapse"; oTr.style.padding = "8px"; oTr.style.fontSize = "12px"; oTr.style.textAlign = "left"; oTr.style.cursor = "default"; return oTr; }; CDrawingAboutWindow.prototype.private_AppendTD = function(oTR, sText) { var oTd = document.createElement("td"); oTR.appendChild(oTd); Common.Set_InnerTextToElement(oTd, sText); oTd.style.borderLeft = "0"; oTd.style.borderRight = "0"; oTd.style.borderBottom = "solid 1px #E4E4E4"; oTd.style.borderCollapse = "collapse"; oTd.style.padding = "8px"; oTd.style.fontSize = "12px"; oTd.style.textAlign = "left"; oTd.style.cursor = "default"; return oTd; }; CDrawingAboutWindow.prototype.private_SetEventListener = function(oElement, oEventPr) { var oDrawingBoard = this.m_oDrawingBoard; if (oDrawingBoard && oEventPr.KeyCode) { oElement.title = "Click to do it"; oElement.style.cursor = "pointer"; oElement.style.textDecoration = "underline"; oElement.addEventListener("click", function() { oDrawingBoard.private_HandleKeyDown(oEventPr); }, false); } }; CDrawingAboutWindow.prototype.private_AppendTableHeading1 = function(oTBody, sText) { var oTr = this.private_AppendTR(oTBody); var oTd = this.private_AppendTD(oTr, sText); oTd.colSpan = "3"; oTd.style.fontSize = "14px"; oTd.style.fontWeight = "bold"; oTd.style.paddingTop = "20px"; }; CDrawingAboutWindow.prototype.private_AppendTableHeading2 = function(oTBody, oEventPr, sText1, sText2) { var oTr = this.private_AppendTR(oTBody); var oTd1 = this.private_AppendTD(oTr, sText1); oTd1.style.fontWeight = "bold"; var oTd2 = this.private_AppendTD(oTr, sText2); this.private_SetEventListener(oTd2, oEventPr); oTd2.colSpan = "2"; }; CDrawingAboutWindow.prototype.private_AppendTableHeading3 = function(oTBody, oEventPr, sText1, sText2, sText3) { var oTr = this.private_AppendTR(oTBody); this.private_AppendTD(oTr, sText1).style.fontWeight = "bold"; var oTd = this.private_AppendTD(oTr, sText2); this.private_SetEventListener(oTd, oEventPr); this.private_AppendTD(oTr, sText3); }; CDrawingAboutWindow.prototype.private_AppendTableCommonString = function(oTBody, oEventPr, sText1, sText2, sText3) { var oTr = this.private_AppendTR(oTBody); this.private_AppendTD(oTr, sText1).style.width = "35%"; var oTd = this.private_AppendTD(oTr, sText2); oTd.style.width = "15%"; this.private_SetEventListener(oTd, oEventPr); this.private_AppendTD(oTr, sText3).style.width = "50%"; }; function CDrawingDiagramSLWindow() { CDrawingDiagramSLWindow.superclass.constructor.call(this); this.m_oTextArea = null; } CommonExtend(CDrawingDiagramSLWindow, CDrawingWindow); CDrawingDiagramSLWindow.prototype.Init = function(_sDivId, oPr) { CDrawingDiagramSLWindow.superclass.Init.call(this, _sDivId, true); var sCaption = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.asciiDiagram.caption : "ASCII diagram"; this.Set_Caption(sCaption); var oMainDiv = this.HtmlElement.InnerDiv; var oMainControl = this.HtmlElement.InnerControl; var sDivId = this.HtmlElement.InnerDiv.id; this.m_oGameTree = oPr.GameTree; this.private_CreateInfoAreaElement(oMainDiv, oMainControl, sDivId); this.private_FillTextArea(oPr.GameTree); this.m_oTextArea.select(); }; CDrawingDiagramSLWindow.prototype.Show = function(oPr) { CDrawingDiagramSLWindow.superclass.Show.call(this, oPr); this.private_FillTextArea(oPr.GameTree); this.m_oTextArea.select(); }; CDrawingDiagramSLWindow.prototype.private_CreateInfoAreaElement = function(oMainDiv, oMainControl, sDivId) { var oElement = document.createElement("textarea"); var sElementId = sDivId + "TA"; oElement.setAttribute("id", sElementId); oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.setAttribute("oncontextmenu", "return false;"); oElement.style.fontFamily = "Courier New, monospacef"; oElement.style.fontSize = "10pt"; oElement.style.resize = "none"; oElement.style.outline = "none"; oElement.style.border = "1px solid rgb(169,169,169)"; oElement.style.height = "100%"; oElement.style.width = "100%"; this.m_oTextArea = oElement; oMainDiv.appendChild(oElement); var oControl = CreateControlContainer(sElementId); oControl.Bounds.SetParams(0, 0, 1000, 1000, false, false, false, false, -1, -1); oControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_right | g_anchor_bottom); oMainControl.AddControl(oControl); return oElement; }; CDrawingDiagramSLWindow.prototype.private_FillTextArea = function(oGameTree) { this.m_oTextArea.value = ""; if (undefined === oGameTree) return; var oDrawingBoard = oGameTree.Get_DrawingBoard(); var oLogicBoard = oGameTree.Get_Board(); if (!oDrawingBoard || !oLogicBoard) return; var sDiagram = ""; var nSizeX = oLogicBoard.Get_Size().X; var nSizeY = oLogicBoard.Get_Size().Y; var oViewPort = oDrawingBoard.Get_ViewPort(); var X0 = oViewPort.X0; var Y0 = oViewPort.Y0; var X1 = oViewPort.X1; var Y1 = oViewPort.Y1; // Определяем какие границы нам нужны var bLeft = (0 == X0 ? true : false); var bRight = (nSizeX - 1 == X1 ? true : false); var bTop = (0 == Y0 ? true : false); var bBottom = (nSizeY - 1 == Y1 ? true : false); // Определяем очередность хода и нумерацию var arrNumbers = []; for (var nY = Y0; nY < Y1; nY++) { for (var nX = X0; nX < X1; nX++) { var Mark = oDrawingBoard.Get_Mark(nX + 1, nY + 1); var MarkType = (null != Mark ? Mark.Get_Type() : EDrawingMark.Lm); var MarkText = (null != Mark ? Mark.Get_Text() : ""); if (MarkType == EDrawingMark.Tx && Common_IsInt(MarkText)) { var nValue = parseInt(MarkText); var oElement = { Number : nValue, Value : oLogicBoard.Get(nX + 1, nY + 1) }; if (BOARD_EMPTY != oElement.Value) arrNumbers.push(oElement); } } } var bBlackFirst = true; var bCoordinates = oDrawingBoard.Get_Rulers(); var nFirstMove = -1; if (arrNumbers.length > 0) { var nMin = -1, nMinValue = BOARD_EMPTY; var nMax = -1; for (var nIndex = 0, nCount = arrNumbers.length; nIndex < nCount; nIndex++) { var oElement = arrNumbers[nIndex]; if (-1 == nMin || oElement.Number < nMin) { nMin = oElement.Number; nMinValue = oElement.Value; } if (-1 == nMax || oElement.Number > nMax) nMax = oElement.Number; } if (nMax - nMin < 10) { var bValid = true; for (var nIndex = 0, nCount = arrNumbers.length; nIndex < nCount; nIndex++) { var oElement = arrNumbers[nIndex]; var nOst = (oElement.Number - nMin) % 2; if ((0 == nOst && nMinValue != oElement.Value) || (1 == nOst && nMinValue == oElement.Value)) { bValid = false; break; } } if (true === bValid) { nFirstMove = nMin; if (BOARD_BLACK === nMinValue) bBlackFirst = true; else bBlackFirst = false; } } } var sVerticalLine = bLeft ? "$$ --" : "$$ -"; for (var nX = X0 + 1; nX <= X1; nX++) sVerticalLine += "--"; sVerticalLine += bRight ? "- \n" : "\n"; var sLineStart = bLeft ? "$$ |" : "$$"; var sLineEnd = bRight ? " |\n" : "\n"; // Header if (bBlackFirst) sDiagram += "$$B"; else sDiagram += "$$W"; if (bCoordinates) sDiagram += "c"; if (-1 != nFirstMove) sDiagram += "m" + nFirstMove; sDiagram += '\n'; // enf of header if (bTop) sDiagram += sVerticalLine; for (var nY = Y0; nY <= Y1; nY++) { sDiagram += sLineStart; for (var nX = X0; nX <= X1; nX++) { var Mark = oDrawingBoard.Get_Mark(nX + 1, nY + 1); var MarkType = (null != Mark ? Mark.Get_Type() : EDrawingMark.Lm); var MarkText = (null != Mark ? Mark.Get_Text() : ""); var Value = oLogicBoard.Get(nX + 1, nY + 1); if (BOARD_EMPTY == Value) { if (EDrawingMark.Tr === MarkType) sDiagram += " T"; else if (EDrawingMark.Cr === MarkType) sDiagram += " C"; else if (EDrawingMark.Sq === MarkType) sDiagram += " S"; else if (EDrawingMark.X === MarkType) sDiagram += " M"; else if (EDrawingMark.Tx === MarkType && 1 === MarkText.length && 97 <= MarkText.charCodeAt(0) && MarkText.charCodeAt(0) <= 122) sDiagram += String.fromCharCode(0x20, MarkText.charCodeAt(0)); else if (EDrawingMark.Tx === MarkType && 1 === MarkText.length && 65 <= MarkText.charCodeAt(0) && MarkText.charCodeAt(0) <= 90) sDiagram += String.fromCharCode(0x20, MarkText.charCodeAt(0) + 0x20); else { if (oLogicBoard.Is_HandiPoint(nX + 1, nY + 1)) sDiagram += " ,"; else sDiagram += " ."; } } else { if (-1 !== nFirstMove && MarkType == EDrawingMark.Tx && Common_IsInt(MarkText)) { var nValue = parseInt(MarkText) - nFirstMove + 1; if (10 == nValue) sDiagram += ' 0'; else sDiagram += ' ' + nValue; } else if (BOARD_BLACK == Value) { if (EDrawingMark.Tr === MarkType) sDiagram += " Y"; else if (EDrawingMark.Cr === MarkType) sDiagram += " B"; else if (EDrawingMark.Sq === MarkType) sDiagram += " #"; else if (EDrawingMark.X === MarkType) sDiagram += " Z"; else sDiagram += " X"; } else if (BOARD_WHITE == Value) { if (EDrawingMark.Tr === MarkType) sDiagram += " Q"; else if (EDrawingMark.Cr === MarkType) sDiagram += " W"; else if (EDrawingMark.Sq === MarkType) sDiagram += " @"; else if (EDrawingMark.X === MarkType) sDiagram += " P"; else sDiagram += " O"; } } } sDiagram += sLineEnd; } if (bBottom) sDiagram += sVerticalLine; this.m_oTextArea.value = sDiagram; }; function CDrawingViewPortWindow() { CDrawingViewPortWindow.superclass.constructor.call(this); this.m_oButtonReset = null; } CommonExtend(CDrawingViewPortWindow, CDrawingConfirmWindow); CDrawingViewPortWindow.prototype.Init = function(_sDivId, oPr) { CDrawingViewPortWindow.superclass.Init.call(this, _sDivId, true); this.protected_UpdateSizeAndPosition(oPr.Drawing); this.m_oGameTree = oPr.GameTree; this.m_oDrawing = oPr.Drawing; var sCaption = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.boardCropping.caption : "Crop the board..."; this.Set_Caption(sCaption); var oMainDiv = this.HtmlElement.ConfirmInnerDiv; var oMainControl = this.HtmlElement.ConfirmInnerControl; var sMainId = this.HtmlElement.ConfirmInnerDiv.id; oMainDiv.style.background = "url(\'" + g_sBackground + "\')"; var oDrawingBoard = new CDrawingBoard(); oMainControl.Set_Type(2, oDrawingBoard); var sBoard = sMainId + "B"; var oBoardElement = this.protected_CreateDivElement(oMainDiv, sBoard); var oBoardControl = CreateControlContainer(sBoard); oBoardControl.Bounds.SetParams(0, 0, 1000, 1000, true, true, false, false, -1, -1); oBoardControl.Anchor = (g_anchor_top | g_anchor_left | g_anchor_bottom | g_anchor_right); oMainControl.AddControl(oBoardControl); this.m_oBoardDiv = oBoardElement; this.m_oBoardControl = oBoardControl; oDrawingBoard.Init(sBoard, this.m_oGameTree.Copy_ForScoreEstimate()); oDrawingBoard.Set_ViewPortMode(this); this.m_oDrawingBoard = oDrawingBoard; var oButtonsDiv = this.HtmlElement.OkCancelDiv; var sReset = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.boardCropping.buttonReset : "Reset"; var nResetWidth = 100; if (window.g_oTextMeasurer) { window.g_oTextMeasurer.SetFont("16px 'Segoe UI', Helvetica, Tahoma, Geneva, Verdana, sans-serif"); nResetWidth = window.g_oTextMeasurer.Measure(sReset) + 10; } var sButtonResetId = sMainId + "R"; var oButtonResetElement = this.protected_CreateDivElement(oButtonsDiv, sButtonResetId); var oButtonResetControl = CreateControlContainerByElement(oButtonResetElement); oButtonResetControl.Bounds.SetParams(0, 9, 159, 1000, false, true, true, false, nResetWidth + 10, 21); oButtonResetControl.Anchor = (g_anchor_top | g_anchor_right); this.HtmlElement.InnerControl.AddControl(oButtonResetControl); var oThis = this; var oButttonReset = new CDrawingButtonSimpleText(sReset, function() { var oDrawingBoard = oThis.m_oGameTree.Get_DrawingBoard(); if (oDrawingBoard) { oDrawingBoard.Reset_ViewPort(); oThis.m_oDrawing.Update_Size(true); oThis.Close(); } }, ""); oButttonReset.Init(sButtonResetId, this); this.m_oButtonReset = oButttonReset; this.private_UpdateSelectionOnShow(); }; CDrawingViewPortWindow.prototype.Update_Size = function(bForce) { CDrawingViewPortWindow.superclass.Update_Size.call(this, bForce); if (this.m_oDrawingBoard) this.m_oDrawingBoard.Update_Size(bForce); if (this.m_oButtonReset) this.m_oButtonReset.Update_Size(bForce); }; CDrawingViewPortWindow.prototype.Show = function(oPr) { while (this.m_oBoardDiv.firstChild) this.m_oBoardDiv.removeChild(this.m_oBoardDiv.firstChild); if (this.m_oBoardControl) this.m_oBoardControl.Clear(); var oDrawingBoard = new CDrawingBoard(); oDrawingBoard.Init(this.m_oBoardDiv.id, oPr.GameTree.Copy_ForScoreEstimate()); oDrawingBoard.Set_ViewPortMode(this); this.m_oDrawingBoard = oDrawingBoard; CDrawingViewPortWindow.superclass.Show.apply(this, arguments); // Для перерисовки позиции this.Update_Size(true); this.private_UpdateSelectionOnShow(); }; CDrawingViewPortWindow.prototype.Handle_OK = function() { if (this.m_oGameTree) { var oDrawingBoard = this.m_oGameTree.Get_DrawingBoard(); if (oDrawingBoard) { var oViewPort = this.m_oDrawingBoard.Get_SelectedViewPort(); if (oViewPort.X1 === oViewPort.X0 && oViewPort.Y1 === oViewPort.Y0) oDrawingBoard.Reset_ViewPort(); else if (oViewPort.X1 - oViewPort.X0 < 3 || oViewPort.Y1 - oViewPort.Y0 < 3) { var oGameTree = this.m_oGameTree; var oDrawing = this.m_oDrawing; if (oDrawing) { var sMessage = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.boardCropping.errorMessage : "Sorry, the cropped part can't be so small."; CreateWindow(oDrawing.Get_MainDiv().id, EWindowType.Error, { GameTree : oGameTree, Drawing : oDrawing, ErrorText : sMessage, W : 270, H : 80 }); } return; } else oDrawingBoard.Set_ViewPort(oViewPort.X0 - 1, oViewPort.Y0 - 1, oViewPort.X1 - 1, oViewPort.Y1 - 1); this.m_oDrawing.Update_Size(true); } } this.Close(); }; CDrawingViewPortWindow.prototype.private_UpdateSelectionOnShow = function() { var oOriginDrawingBoard = this.m_oGameTree.Get_DrawingBoard(); if (oOriginDrawingBoard && this.m_oDrawingBoard) { var oViewPort = oOriginDrawingBoard.Get_ViewPort(); var oSize = this.m_oGameTree.Get_Board().Get_Size(); if (0 !== oViewPort.X0 || 0 !== oViewPort.Y0 || oSize.X - 1 !== oViewPort.X1 || oSize.Y - 1 !== oViewPort.Y1) { this.m_oDrawingBoard.Set_ViewPortSelection(oViewPort.X0, oViewPort.Y0, oViewPort.X1, oViewPort.Y1); } else { this.m_oDrawingBoard.Set_ViewPortSelection(-1, -1, -1, -1); } } }; function CDrawingCreateNewWindow() { CDrawingCreateNewWindow.superclass.constructor.call(this); } CommonExtend(CDrawingCreateNewWindow, CDrawingConfirmWindow); CDrawingCreateNewWindow.prototype.Init = function(_sDivId, oPr) { CDrawingViewPortWindow.superclass.Init.call(this, _sDivId, false); this.protected_UpdateSizeAndPosition(oPr.Drawing); this.m_oGameTree = oPr.GameTree; this.m_oDrawing = oPr.Drawing; this.Set_Caption("Create new"); var oMainDiv = this.HtmlElement.ConfirmInnerDiv; var oMainControl = this.HtmlElement.ConfirmInnerControl; var sDivId = this.HtmlElement.ConfirmInnerDiv.id; var RowHeight = 20; var LineSpacing = 5; var TopOffset = 5; this.BlackPlayer = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, "Black", "Black", TopOffset, RowHeight); TopOffset += 2 * (RowHeight + LineSpacing); this.WhitePlayer = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, "White", "White", TopOffset, RowHeight); TopOffset += 2 * (RowHeight + LineSpacing); this.BoardSize = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, "Board size", "19", TopOffset, RowHeight); TopOffset += 2 * (RowHeight + LineSpacing); this.Handicap = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, "Handicap", "0", TopOffset, RowHeight); TopOffset += 2 * (RowHeight + LineSpacing); this.Komi = this.private_CreateInfoElement(oMainDiv, oMainControl, sDivId, "Komi", "6.5", TopOffset, RowHeight); }; CDrawingCreateNewWindow.prototype.private_CreateDivElement = function(oParentElement, sName, Height) { var oElement = document.createElement("div"); oElement.setAttribute("id", sName); oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.setAttribute("oncontextmenu", "return false;"); oElement.style.fontFamily = "Tahoma, Sans serif"; oElement.style.fontSize = Height * 15 / 20 + "px"; oElement.style.lineHeight = Height + "px"; oElement.style.height = Height + "px"; oElement.style.fontWeight = 550; oParentElement.appendChild(oElement); return oElement; }; CDrawingCreateNewWindow.prototype.private_CreateInputElement = function(oParentElement, sName) { var oElement = document.createElement("input"); oElement.setAttribute("id", sName); oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.setAttribute("oncontextmenu", "return false;"); oElement.setAttribute("type", "text"); oElement.style.fontFamily = "Tahoma, Sans serif"; oElement.style.fontSize = "10pt"; oElement.style.outline = "none"; oElement.style.border = "1px solid rgb(169,169,169)"; oParentElement.appendChild(oElement); return oElement; }; CDrawingCreateNewWindow.prototype.private_CreateInfoElement = function(oMainDiv, oMainControl, sDivId, sName, sValue, TopOffset, RowHeight) { var LeftOffset = 10; var RightOffset = 10; var sNameId = sDivId + sName; var oNameElement = this.private_CreateDivElement(oMainDiv, sNameId, RowHeight); var oNameControl = CreateControlContainer(sNameId); oNameControl.Bounds.SetParams(LeftOffset + 10, TopOffset, RightOffset, 1000, true, true, false, false, -1, RowHeight); oNameControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_right); oMainControl.AddControl(oNameControl); Common.Set_InnerTextToElement(oNameElement, sName); TopOffset += RowHeight; var sValueId = sNameId + "Value"; var oValueElement = this.private_CreateInputElement(oMainDiv, sValueId); var oValueControl = CreateControlContainer(sValueId); oValueControl.Bounds.SetParams(LeftOffset, TopOffset + 1, RightOffset, 1000, true, true, true, false, -1, RowHeight - 2); oValueControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_right); oMainControl.AddControl(oValueControl); oValueElement.value = sValue; return oValueElement; }; CDrawingCreateNewWindow.prototype.Get_DefaultWindowSize = function() { return {W : 195, H : 340}; }; CDrawingCreateNewWindow.prototype.Handle_OK = function() { var sSize = this.BoardSize.value; var nSizeX = 19; var nSizeY = 19; var nPos = -1; if (-1 == (nPos = sSize.indexOf(":"))) { nSizeX = Math.min(52, Math.max(parseInt(sSize), 2)); nSizeY = nSizeX; } else { nSizeX = parseInt(sSize.substr(0, nPos)); nSizeY = parseInt(sSize.substr(nPos + 1, sSize.length - nPos - 1)); } if (isNaN(nSizeX) || nSizeX < 2 || nSizeX > 52 || isNaN(nSizeY) || nSizeY < 2 || nSizeY > 52) { CreateWindow(this.m_oDrawing.Get_MainDiv().id, EWindowType.Error, {GameTree : this.m_oGameTree, Drawing : this.m_oDrawing, ErrorText : "Size value must be an integer number from 2 to 52, or pair of such numbers separated by ':' character.", W : 300, H : 115}); return; } var nHandi = parseInt(this.Handicap.value); if (isNaN(nHandi) || nHandi < 0 || nHandi > 9) { CreateWindow(this.m_oDrawing.Get_MainDiv().id, EWindowType.Error, {GameTree : this.m_oGameTree, Drawing : this.m_oDrawing, ErrorText : "Handicap value must be an integer number from 0 to 9.", W : 300, H : 95}); return; } if (0 != nHandi && (nSizeY <= 6 || nSizeX <= 6 || nSizeX !== nSizeY)) { CreateWindow(this.m_oDrawing.Get_MainDiv().id, EWindowType.Error, {GameTree : this.m_oGameTree, Drawing : this.m_oDrawing, ErrorText : "Handicap value must be 0 for this board size.", W : 300, H : 95}); return; } if (nHandi > 5 && (nSizeX <= 10 || nSizeY <= 10)) { CreateWindow(this.m_oDrawing.Get_MainDiv().id, EWindowType.Error, {GameTree : this.m_oGameTree, Drawing : this.m_oDrawing, ErrorText : "Handicap value must be an integer number from 0 to 5 for this board size.", W : 300, H : 95}); return; } var fKomi = parseFloat(this.Komi.value); if (isNaN(fKomi) || Math.abs((2 * fKomi) - (2 * fKomi | 0)) > 0.001) { CreateWindow(this.m_oDrawing.Get_MainDiv().id, EWindowType.Error, {GameTree : this.m_oGameTree, Drawing : this.m_oDrawing, ErrorText : "Invalid komi value.", W : 175, H : 85}); return; } if (this.m_oGameTree) { var sSGF = "(;FF[4]"; sSGF += "SZ[" + (nSizeX === nSizeY ? nSizeX : nSizeX + ":" + nSizeY) + "]"; sSGF += "KM[" + fKomi + "]"; sSGF += "PB[" + this.BlackPlayer.value + "]"; sSGF += "PW[" + this.WhitePlayer.value + "]"; sSGF += "HA[" + nHandi + "]"; var aHandiPoints = []; if (nSizeX === nSizeY) { var nSize = nSizeX; var nVal0 = (nSize < 10 ? 2 : 3); var nVal1 = ((nSize + 1) / 2 | 0) - 1; var nVal2 = (nSize < 10 ? nSize - 3 : nSize - 4); switch (nHandi) { case 2: { aHandiPoints.push([nVal2, nVal0]); aHandiPoints.push([nVal0, nVal2]); break; } case 3: { aHandiPoints.push([nVal2, nVal2]); aHandiPoints.push([nVal0, nVal2]); aHandiPoints.push([nVal2, nVal0]); break; } case 4: { aHandiPoints.push([nVal0, nVal0]); aHandiPoints.push([nVal2, nVal2]); aHandiPoints.push([nVal0, nVal2]); aHandiPoints.push([nVal2, nVal0]); break; } case 5: { aHandiPoints.push([nVal0, nVal0]); aHandiPoints.push([nVal0, nVal2]); aHandiPoints.push([nVal2, nVal0]); aHandiPoints.push([nVal2, nVal2]); aHandiPoints.push([nVal1, nVal1]); break; } case 6: { aHandiPoints.push([nVal0, nVal0]); aHandiPoints.push([nVal0, nVal2]); aHandiPoints.push([nVal2, nVal0]); aHandiPoints.push([nVal2, nVal2]); aHandiPoints.push([nVal0, nVal1]); aHandiPoints.push([nVal2, nVal1]); break; } case 7: { aHandiPoints.push([nVal0, nVal0]); aHandiPoints.push([nVal0, nVal2]); aHandiPoints.push([nVal2, nVal0]); aHandiPoints.push([nVal2, nVal2]); aHandiPoints.push([nVal0, nVal1]); aHandiPoints.push([nVal2, nVal1]); aHandiPoints.push([nVal1, nVal1]); break; } case 8: { aHandiPoints.push([nVal0, nVal0]); aHandiPoints.push([nVal0, nVal2]); aHandiPoints.push([nVal2, nVal0]); aHandiPoints.push([nVal2, nVal2]); aHandiPoints.push([nVal0, nVal1]); aHandiPoints.push([nVal2, nVal1]); aHandiPoints.push([nVal1, nVal0]); aHandiPoints.push([nVal1, nVal2]); break; } case 9: { aHandiPoints.push([nVal0, nVal0]); aHandiPoints.push([nVal0, nVal2]); aHandiPoints.push([nVal2, nVal0]); aHandiPoints.push([nVal2, nVal2]); aHandiPoints.push([nVal0, nVal1]); aHandiPoints.push([nVal2, nVal1]); aHandiPoints.push([nVal1, nVal0]); aHandiPoints.push([nVal1, nVal2]); aHandiPoints.push([nVal1, nVal1]); break; } } } var nCharCodeOffsetLo = 'a'.charCodeAt(0); var nCharCodeOffsetHi = 'A'.charCodeAt(0); if (aHandiPoints.length > 0) { sSGF += "AB"; for (var nIndex = 0, nCount = aHandiPoints.length; nIndex < nCount; nIndex++) { var nX = aHandiPoints[nIndex][0]; var nY = aHandiPoints[nIndex][1]; nX += (nX <= 25 ? nCharCodeOffsetLo : nCharCodeOffsetHi - 26); nY += (nY <= 25 ? nCharCodeOffsetLo : nCharCodeOffsetHi - 26); sSGF += String.fromCharCode(91, nX, nY, 93); } } sSGF += ")"; this.m_oGameTree.Load_Sgf(sSGF, null, null, "sgf"); } this.Close(); }; function CDrawingClipboardWindow() { CDrawingClipboardWindow.superclass.constructor.call(this); this.m_oTextArea = null; } CommonExtend(CDrawingClipboardWindow, CDrawingConfirmWindow); CDrawingClipboardWindow.prototype.Init = function(_sDivId, oPr) { CDrawingClipboardWindow.superclass.Init.call(this, _sDivId, true); this.protected_UpdateSizeAndPosition(oPr.Drawing); this.Set_Caption("Load file from clipboard"); var oMainDiv = this.HtmlElement.ConfirmInnerDiv; var oMainControl = this.HtmlElement.ConfirmInnerControl; var sDivId = this.HtmlElement.ConfirmInnerDiv.id; this.m_oGameTree = oPr.GameTree; this.private_CreateInfoAreaElement(oMainDiv, oMainControl, sDivId); this.private_FillTextArea(oPr.GameTree); this.m_oTextArea.select(); }; CDrawingClipboardWindow.prototype.Show = function(oPr) { CDrawingClipboardWindow.superclass.Show.call(this, oPr); this.private_FillTextArea(); this.m_oTextArea.select(); }; CDrawingClipboardWindow.prototype.private_CreateInfoAreaElement = function(oMainDiv, oMainControl, sDivId) { var oElement = document.createElement("textarea"); var sElementId = sDivId + "TA"; oElement.setAttribute("id", sElementId); oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.setAttribute("oncontextmenu", "return false;"); oElement.style.fontFamily = "Courier New, monospacef"; oElement.style.fontSize = "10pt"; oElement.style.resize = "none"; oElement.style.outline = "none"; oElement.style.border = "1px solid rgb(169,169,169)"; oElement.style.height = "100%"; oElement.style.width = "100%"; this.m_oTextArea = oElement; oMainDiv.appendChild(oElement); var oControl = CreateControlContainer(sElementId); oControl.Bounds.SetParams(0, 0, 1000, 1000, false, false, false, false, -1, -1); oControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_right | g_anchor_bottom); oMainControl.AddControl(oControl); return oElement; }; CDrawingClipboardWindow.prototype.private_FillTextArea = function(oGameTree) { this.m_oTextArea.value = ""; if (window.clipboardData) this.m_oTextArea.value = window.clipboardData.getData('Text'); }; CDrawingClipboardWindow.prototype.Handle_OK = function() { var sFile = this.m_oTextArea.value; if (sFile && "" !== sFile) this.m_oGameTree.Load_Sgf(sFile, null, null, null); this.Close(); }; CDrawingClipboardWindow.prototype.Get_DefaultWindowSize = function() { return {W : 300, H : 200}; }; function CDrawingKifuWindow() { CDrawingKifuWindow.superclass.constructor.call(this); this.m_nKifuW = -1; this.m_nKifuH = -1; this.m_nMoveMin = -1; this.m_nMoveMax = -1; this.m_nNextW = 72; } CommonExtend(CDrawingKifuWindow, CDrawingWindow); CDrawingKifuWindow.prototype.Init = function(sDivId, oPr) { CDrawingKifuWindow.superclass.Init.call(this, sDivId, oPr); this.protected_UpdateSizeAndPosition(oPr.Drawing); var sCaption = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.kifu.caption : "Kifu"; this.Set_Caption(sCaption); var oMainDiv = this.HtmlElement.InnerDiv; var oMainControl = this.HtmlElement.InnerControl; this.HtmlElement.Canvas = this.private_CreateCanvasElement(oMainDiv, oMainControl, sDivId); this.m_oGameTree = oPr.GameTree; this.m_oDrawing = oPr.Drawing; if (this.m_oDrawing && this.m_oDrawing.Register_KifuWindow) this.m_oDrawing.Register_KifuWindow(this); }; CDrawingKifuWindow.prototype.Get_DefaultWindowSize = function() { return {W : 650, H : 730}; }; CDrawingKifuWindow.prototype.private_CreateCanvasElement = function(oMainDiv, oMainControl, sDivId) { var oElement = document.createElement("canvas"); var sElementId = sDivId + "C"; oElement.setAttribute("style", "position:absolute;padding:0;margin:0;"); oElement.id = sElementId; oMainDiv.appendChild(oElement); var oControl = CreateControlContainer(sElementId); oControl.Bounds.SetParams(0, 0, 1000, 1000, false, false, false, false, -1, -1); oControl.Anchor = (g_anchor_left | g_anchor_top | g_anchor_right | g_anchor_bottom); oMainControl.AddControl(oControl); return oElement; }; CDrawingKifuWindow.prototype.private_DrawLogicBoard = function(oContext, nWidth, nHeight, oLogicBoard) { oContext.clearRect(0, 0, nWidth, nHeight); oContext.strokeStyle = "rgba(0, 0, 0, 1)"; oContext.fillStyle = "rgba(0, 0, 0, 1)"; var nSize = 30; var nTopSize = 30; var nRepetitionHeight = this.private_DrawRepetitions(oContext, 0, nWidth, oLogicBoard, nSize, false); var nMinSize = Math.max(50, Math.min(nWidth, nHeight - nTopSize - nRepetitionHeight)); var nBoardX = (nWidth - nMinSize) / 2 | 0; var nBoardY = nTopSize; var oResult = this.private_DrawBoard(oContext, oLogicBoard, nBoardX, nBoardY, nMinSize); this.private_DrawKifuCaption(oContext, nWidth, "(" + oResult.Min + " ~ " + oResult.Max + ")"); this.private_DrawRepetitions(oContext, nHeight - nRepetitionHeight, nWidth, oLogicBoard, nSize, true); this.private_DrawNextMove(oContext, 25); }; CDrawingKifuWindow.prototype.Show = function(oPr) { CDrawingKifuWindow.superclass.Show.call(this, oPr); var W = Common.ConvertToRetinaValue(this.HtmlElement.InnerDiv.clientWidth, true); var H = Common.ConvertToRetinaValue(this.HtmlElement.InnerDiv.clientHeight, true); this.private_DrawLogicBoard(this.HtmlElement.Canvas.getContext("2d"), W, H, this.m_oGameTree.Get_LogicBoardForKifu()); }; CDrawingKifuWindow.prototype.Update_Size = function(bForce) { CDrawingKifuWindow.superclass.Update_Size.call(this, bForce); var W = Common.ConvertToRetinaValue(this.HtmlElement.InnerDiv.clientWidth, true); var H = Common.ConvertToRetinaValue(this.HtmlElement.InnerDiv.clientHeight, true); if (true === bForce || Math.abs(W - this.m_nKifuW) > 0.001 || Math.abs(H - this.m_nKifuH) > 0.001) { this.m_nKifuW = W; this.m_nKifuH = H; this.private_DrawLogicBoard(this.HtmlElement.Canvas.getContext("2d"), W, H, this.m_oGameTree.Get_LogicBoardForKifu()); } }; CDrawingKifuWindow.prototype.private_DrawStone = function(oContext, nValue, nX, nY, nRad) { if (BOARD_BLACK === nValue) { oContext.fillStyle = "rgb(0, 0, 0)"; oContext.beginPath(); oContext.arc(nX, nY, nRad, 0, 2 * Math.PI); oContext.fill(); } else if (BOARD_WHITE === nValue) { oContext.fillStyle = "rgb(255, 255, 255)"; oContext.beginPath(); oContext.arc(nX, nY, nRad, 0, 2 * Math.PI); oContext.fill(); oContext.stroke(); } }; CDrawingKifuWindow.prototype.private_DrawMoveNumber = function(oContext, nValue, nX, nY, nRad, nMoveNumber) { if (-1 === nMoveNumber) return; var Text = "" + nMoveNumber; var FontSize = nRad; var FontFamily = (Common_IsInt(Text) ? "Arial" : "Helvetica, Arial, Verdana"); var sFont = FontSize + "px " + FontFamily; oContext.fillStyle = nValue === BOARD_WHITE ? "rgb(0,0,0)" : "rgb(255,255,255)"; oContext.font = sFont; var y_offset = FontSize / 3 + 0.15 * FontSize; var x_offset = Text.length > 2 ? (2 * nRad - oContext.measureText(Text).width) / 2 - nRad : (2 * nRad - 1.4 * oContext.measureText(Text).width) / 2 - nRad; if (Text.length > 2) oContext.setTransform(1, 0, 0, 1.4, nX + x_offset, nY + y_offset); else oContext.setTransform(1.4, 0, 0, 1.4, nX + x_offset, nY + y_offset); oContext.fillText(Text, 0, 0); oContext.setTransform(1, 0, 0, 1, 0, 0); }; CDrawingKifuWindow.prototype.private_DrawBoard = function(oContext, oLogicBoard, nStartX, nStartY, nRealSize) { var oSize = oLogicBoard.Get_Size(); var nAbsBoardSize = (oSize.X - 1) * g_dBoardCellW + 2 * g_dBoardHorOffset; var dOffset = (nRealSize / nAbsBoardSize * g_dBoardHorOffset) | 0; var nCellSize = (nRealSize / nAbsBoardSize * g_dBoardCellW) | 0; var dOffsetX = dOffset + nStartX; var dOffsetY = dOffset + nStartY; oContext.lineWidth = 2; oContext.beginPath(); oContext.moveTo(dOffsetX, dOffsetY); oContext.lineTo(dOffsetX + (oSize.X - 1) * nCellSize, dOffsetY); oContext.lineTo(dOffsetX + (oSize.X - 1) * nCellSize, dOffsetY + (oSize.Y - 1) * nCellSize); oContext.lineTo(dOffsetX, dOffsetY + (oSize.Y - 1) * nCellSize); oContext.closePath(); oContext.stroke(); oContext.lineWidth = 1; oContext.beginPath(); for (var nX = 0; nX < oSize.X; ++nX) { oContext.moveTo(dOffsetX + nX * nCellSize + 0.5, dOffsetY + 0.5); oContext.lineTo(dOffsetX + nX * nCellSize + 0.5, dOffsetY + (oSize.Y - 1) * nCellSize + 0.5); } for (var nY = 0; nY < oSize.Y; ++nY) { oContext.moveTo(dOffsetX + 0.5, dOffsetY + nY * nCellSize + 0.5); oContext.lineTo(dOffsetX + (oSize.X - 1) * nCellSize + 0.5, dOffsetY + nY * nCellSize + 0.5); } oContext.stroke(); oContext.beginPath(); var oHandiPoints = oLogicBoard.Get_HandiPoints(); for (var nIndex = 0, nCount = oHandiPoints.length; nIndex < nCount; ++nIndex) { var X = oHandiPoints[nIndex][0] * nCellSize + dOffsetX; var Y = oHandiPoints[nIndex][1] * nCellSize + dOffsetY; oContext.rect(X - 3, Y - 3, 7, 7); } oContext.fill(); var dRad = nCellSize / 2 | 0; var nMinMove = -1; var nMaxMove = -1; for (var nY = 0; nY < oSize.Y; ++nY) { for (var nX = 0; nX < oSize.X; ++nX) { var Value = oLogicBoard.Get(nX + 1, nY + 1); var nMoveNumber = oLogicBoard.Get_Num(nX + 1, nY + 1); var x = nX * nCellSize + dOffsetX; var y = nY * nCellSize + dOffsetY; this.private_DrawStone(oContext, Value, x, y, dRad); if (-1 !== nMoveNumber) { this.private_DrawMoveNumber(oContext, Value, x, y, dRad, nMoveNumber); if (-1 === nMinMove || nMinMove > nMoveNumber) nMinMove = nMoveNumber; if (-1 === nMaxMove || nMaxMove < nMoveNumber) nMaxMove = nMoveNumber; } } } this.m_nMoveMin = nMinMove; this.m_nMoveMax = nMaxMove; return {Min : nMinMove, Max : nMaxMove}; }; CDrawingKifuWindow.prototype.private_DrawKifuCaption = function(oContext, nWidth, sText) { oContext.fillStyle = "rgb(0,0,0)"; oContext.font = "16px Arial"; var dMovesOffsetY = 20; var dMovesOffsetX = (nWidth - oContext.measureText(sText).width) / 2; oContext.fillText(sText, dMovesOffsetX, dMovesOffsetY); }; CDrawingKifuWindow.prototype.private_DrawRepetitions = function(oContext, nStartY, nWidth, oLogicBoard, nSize, bDraw) { // Под место с точками используем целое nSize, отступы справа, слева расстояние между элементами nSize / 2 // Расстояние между строками 5px. var nHorMargin = (nSize / 2) | 0; var nLineGap = 5; var nSpace = (nSize / 2) | 0; var nDotsSize = nSize | 0; var nVerMargin = 5; var nLimitX = nWidth - nHorMargin; var nY = nVerMargin + nStartY; var nRad = (nSize / 2) | 0; var nX = nHorMargin; function privateCheckSize(nCheckSize) { if (nX + nCheckSize < nLimitX || true === bFirstOnLine) { bFirstOnLine = false; return true; } else { nX = nHorMargin; bFirstOnLine = false; nY += nSize + nLineGap; return false; } } if (oLogicBoard.m_aRepetitions) { nY += (nSize / 2) | 0; var bFirstOnLine = true; for (var nIndex = 0, nCount = oLogicBoard.m_aRepetitions.length; nIndex < nCount; ++nIndex) { var oRepetition = oLogicBoard.m_aRepetitions[nIndex]; if (oRepetition.aReps.length <= 0) continue; for (var nRepIndex = 0, nRepsCount = oRepetition.aReps.length; nRepIndex < nRepsCount; ++nRepIndex) { var oRep = oRepetition.aReps[nRepIndex]; privateCheckSize(nSize); if (true === bDraw) { this.private_DrawStone(oContext, oRep.nValue, nX + nRad , nY, nRad); this.private_DrawMoveNumber(oContext, oRep.nValue, nX + nRad, nY, nRad, oRep.nMoveNumber); } nX += nSize; } privateCheckSize(nDotsSize); if (true === bDraw) { this.private_DrawDots(oContext, nX + nRad, nY, nSize); } nX += nDotsSize; privateCheckSize(nSize); if (true === bDraw) { this.private_DrawStone(oContext, oRepetition.nValue, nX + nRad, nY, nRad); this.private_DrawMoveNumber(oContext, oRepetition.nValue, nX + nRad, nY, nRad, oRepetition.nMoveNumber); } nX += nSize + nSpace; } nY += (nSize / 2) | 0; } nY += nVerMargin; return nY; }; CDrawingKifuWindow.prototype.private_DrawDots = function(oContext, nX, nY, nSize) { var nDotsX = (nX - nSize / 2) | 0; var nDotsRad = (nSize / 15) | 0; var nDotsSpace = (nSize / 10 * 3) | 0; var nDotsMargin = (nSize / 5) | 0; oContext.fillStyle = "rgb(0,0,0)"; oContext.beginPath(); oContext.arc(nDotsX + nDotsMargin, nY, nDotsRad, 0, 2 * Math.PI); oContext.arc(nDotsX + nDotsMargin + nDotsSpace, nY, nDotsRad, 0, 2 * Math.PI); oContext.arc(nDotsX + nDotsMargin + 2 * nDotsSpace, nY, nDotsRad, 0, 2 * Math.PI); oContext.fill(); }; CDrawingKifuWindow.prototype.private_DrawNextMove = function(oContext, nSize) { if (!this.m_oGameTree) return; var nNextMoveNumber = this.m_oGameTree.Get_MovesCount() + 1; var nValue = this.m_oGameTree.Get_NextMove(); var nRad = nSize / 2 | 0; oContext.clearRect(0, 0, this.m_nNextW, 28 + 2); if (nNextMoveNumber > 0 && nNextMoveNumber <= this.m_nMoveMax) { var sText = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.kifu.next : "Next"; oContext.fillStyle = "rgb(0,0,0)"; oContext.font = "16px Arial"; var dOffsetY = 20; var dOffsetX = 20; oContext.fillText(sText, dOffsetX, dOffsetY); var nLeft = 20; if (window.g_oTextMeasurer) { window.g_oTextMeasurer.SetFont("16px Arial"); nLeft += window.g_oTextMeasurer.Measure(sText) + 5; } else { nLeft += 50; } this.private_DrawStone(oContext, nValue, nLeft + nRad, 28 - nRad, nRad); this.private_DrawMoveNumber(oContext, nValue, nLeft + nRad, 28 - nRad, nRad, nNextMoveNumber); this.m_nNextW = nLeft + 2 * nRad + 2; } else if (nNextMoveNumber > 0) { var sText = window.g_oLocalization ? window.g_oLocalization.gameRoom.window.kifu.end : "End"; oContext.fillStyle = "rgb(0,0,0)"; oContext.font = "16px Arial"; var dOffsetY = 20; var dOffsetX = 20; oContext.fillText(sText, dOffsetX, dOffsetY); this.m_nNextW = 100; } }; CDrawingKifuWindow.prototype.Update_NextMove = function() { this.private_DrawNextMove(this.HtmlElement.Canvas.getContext("2d"), 25); }; var EWindowType = { Common : 0, Confirm : 1, Error : 2, GameInfo : 3, Settings : 4, ScoreEstimate : 5, CountColors : 6, GifWriter : 7, About : 8, DiagramSL : 9, ViewPort : 10, CreateNew : 11, Clipboard : 12, Kifu : 13 }; var g_aWindows = {}; function CreateWindow(sDrawingId, nWindowType, oPr) { if (!g_aWindows[sDrawingId]) g_aWindows[sDrawingId] = {}; var oWindows = g_aWindows[sDrawingId]; if (oWindows[nWindowType]) { var oWindow = oWindows[nWindowType]; oWindow.Show(oPr); return oWindow; } else { var sApp = "unknownwindow"; switch (nWindowType) { case EWindowType.GameInfo : sApp = "Info"; break; case EWindowType.Settings : sApp = "Settings"; break; case EWindowType.Error : sApp = "Error"; break; case EWindowType.ScoreEstimate : sApp = "ScoreEstimate"; break; case EWindowType.CountColors : sApp = "CountColors"; break; case EWindowType.GifWriter : sApp = "GifWriter"; break; case EWindowType.About : sApp = "About"; break; case EWindowType.DiagramSL : sApp = "DiagramSL"; break; case EWindowType.ViewPort : sApp = "ViewPort"; break; case EWindowType.CreateNew : sApp = "CreateNew"; break; case EWindowType.Clipboard : sApp = "Clipboard"; break; case EWindowType.Kifu : sApp = "Kifu"; break; } var sId = sDrawingId + sApp + GoBoardApi.Get_Version(); var oDiv = document.createElement("div"); oDiv.setAttribute("id", sId); oDiv.setAttribute("style", "position:absolute;padding:0;margin:0;width:500px;height:500px;left:300px;top:300px;"); oDiv.setAttribute("oncontextmenu", "return false;"); if (oPr.Drawing) { var oDrawingDiv = oPr.Drawing.Get_MainDiv(); oDrawingDiv.appendChild(oDiv); var oWindow = null; switch (nWindowType) { case EWindowType.GameInfo : oWindow = new CDrawingInfoWindow(); break; case EWindowType.Settings : oWindow = new CDrawingSettingsWindow(); break; case EWindowType.Error : oWindow = new CDrawingErrorWindow(); break; case EWindowType.ScoreEstimate : oWindow = new CDrawingScoreEstimateWindow(); break; case EWindowType.CountColors : oWindow = new CDrawingCountColorsWindow(); break; case EWindowType.GifWriter : oWindow = new CDrawingGifWriterWindow(); break; case EWindowType.About : oWindow = new CDrawingAboutWindow(); break; case EWindowType.DiagramSL : oWindow = new CDrawingDiagramSLWindow(); break; case EWindowType.ViewPort : oWindow = new CDrawingViewPortWindow(); break; case EWindowType.CreateNew : oWindow = new CDrawingCreateNewWindow(); break; case EWindowType.Clipboard : oWindow = new CDrawingClipboardWindow(); break; case EWindowType.Kifu : oWindow = new CDrawingKifuWindow(); break; } oWindows[nWindowType] = oWindow; if (null !== oWindow) { oWindow.Init(sId, oPr); oWindow.Update_Size(true); } return oWindow; } } return null; }
lgpl-3.0
xnull/WmExchBot
Test_Ebot/Config/Mapper/Bot/BehaviorMapTest.cs
1615
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using ru.xnull; using ru.xnull.XML; using ru.xnull.Config.Mapping.Bot; using System.Xml; namespace Test_Ebot.Config.Mapper.Bot { [TestFixture] class BehaviorMapTest { private BehaviorMap bMap; [SetUp] public void setUp() { XmlDocument xmlConfig = new XmlDocument(); xmlConfig.Load(@"Resources\Config.xml"); String behaviorString = xmlConfig.SelectSingleNode("//Bot/Behaviors/*").OuterXml; XmlMapper mapper = new XmlMapper(); bMap = mapper.xmlStringToClass<BehaviorMap>(behaviorString); } [Test] public void checkMappingBehaviorMap() { Assert.AreEqual(bMap.fullDirections, "WMZ_WMR__WMR_WMZ"); Assert.AreEqual(bMap.guid, "123"); Assert.AreEqual(bMap.paysMap.Count, 2); } [Test] public void checkGetMissingPays() { BehaviorMap behaviorMap = new BehaviorMap(); behaviorMap.planPayCount = 2; behaviorMap.fullDirections = "WMZ_WMR__WMR_WMZ"; BehaviorPayMap bPayMap = new BehaviorPayMap(); bPayMap.direction = "WMZ_WMR"; behaviorMap.paysMap = new List<BehaviorPayMap>(); behaviorMap.paysMap.Add(bPayMap); List<String> missingPays = behaviorMap.getMissingPays(); Assert.AreEqual(missingPays.Count, 1); Assert.AreEqual(missingPays[0], "WMR_WMZ"); } } }
lgpl-3.0
danzone/dspot
dspot/src/main/java/eu/stamp_project/utils/compilation/DSpotJDTBatchCompiler.java
3678
package eu.stamp_project.utils.compilation; import org.eclipse.jdt.internal.compiler.Compiler; import org.eclipse.jdt.internal.compiler.batch.CompilationUnit; import org.eclipse.jdt.internal.compiler.batch.FileSystem; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.util.HashtableOfObject; import org.eclipse.jdt.internal.compiler.util.Util; import spoon.support.compiler.jdt.JDTBasedSpoonCompiler; import spoon.support.compiler.jdt.JDTBatchCompiler; import java.io.File; import java.io.IOException; /** * Created by Benjamin DANGLOT * benjamin.danglot@inria.fr * on 12/23/16 */ public class DSpotJDTBatchCompiler extends JDTBatchCompiler { private FileSystem environment; public DSpotJDTBatchCompiler(JDTBasedSpoonCompiler jdtCompiler, FileSystem environment ) { super(jdtCompiler); this.environment = environment; } @Override public void performCompilation() { if(environment == null) { environment = this.getLibraryAccess(); } this.startTime = System.currentTimeMillis(); this.compilerOptions = new CompilerOptions(this.options); this.compilerOptions.performMethodsFullRecovery = false; this.compilerOptions.performStatementsRecovery = false; this.batchCompiler = new Compiler(environment, this.getHandlingPolicy(), this.compilerOptions, this.getBatchRequestor(), this.getProblemFactory(), this.out, this.progress); this.batchCompiler.remainingIterations = this.maxRepetition - this.currentRepetition; String setting = System.getProperty("jdt.compiler.useSingleThread"); this.batchCompiler.useSingleThread = setting != null && setting.equals("true"); this.compilerOptions.verbose = this.verbose; this.compilerOptions.produceReferenceInfo = this.produceRefInfo; try { this.logger.startLoggingSources(); this.batchCompiler.compile(this.getCompilationUnits()); } finally { this.logger.endLoggingSources(); } this.logger.printStats(); } @Override public CompilationUnit[] getCompilationUnits() { int fileCount = this.filenames.length; CompilationUnit[] units = new CompilationUnit[fileCount]; HashtableOfObject knownFileNames = new HashtableOfObject(fileCount); String defaultEncoding = (String)this.options.get("org.eclipse.jdt.core.encoding"); if(Util.EMPTY_STRING.equals(defaultEncoding)) { defaultEncoding = null; } for(int i = 0; i < fileCount; ++i) { char[] charName = this.filenames[i].toCharArray(); if(knownFileNames.get(charName) != null) { throw new IllegalArgumentException(this.bind("unit.more", this.filenames[i])); } knownFileNames.put(charName, charName); File file = new File(this.filenames[i]); if(!file.exists()) { throw new IllegalArgumentException(this.bind("unit.missing", this.filenames[i])); } String encoding = this.encodings[i]; if(encoding == null) { encoding = defaultEncoding; } String fileName; try { fileName = file.getCanonicalPath(); } catch (IOException var10) { fileName = this.filenames[i]; } units[i] = new CompilationUnit((char[])null, fileName, encoding, this.destinationPaths[i], false, null); } return units; } public FileSystem getEnvironment() { return environment; } }
lgpl-3.0
agentsoz/jill
jill/src/test/java/io/github/agentsoz/jill/core/testprogram/Goal7.java
1128
package io.github.agentsoz.jill.core.testprogram; import io.github.agentsoz.jill.lang.Goal; import io.github.agentsoz.jill.lang.GoalInfo; /* * #%L * Jill Cognitive Agents Platform * %% * Copyright (C) 2014 - 2019 by its authors. See AUTHORS file. * %% * 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public License along with this program. * If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ @GoalInfo(hasPlans = {"some.nonexistent.PlanClass"}) public class Goal7 extends Goal { public Goal7(String str) { super(str); // TODO Auto-generated constructor stub } }
lgpl-3.0
SAMPProjects/Open-SAMP-API
src/Open-SAMP-API/Client/RenderFunctions.hpp
2134
#pragma once #include "Client.hpp" namespace Client { namespace RenderFunctions { EXPORT int TextCreate(const char *Font, int FontSize, bool bBold, bool bItalic, int x, int y, unsigned int color, const char *text, bool bShadow, bool bShow); EXPORT int TextDestroy(int ID); EXPORT int TextSetShadow(int id, bool b); EXPORT int TextSetShown(int id, bool b); EXPORT int TextSetColor(int id, unsigned int color); EXPORT int TextSetPos(int id, int x, int y); EXPORT int TextSetString(int id, const char *str); EXPORT int TextUpdate(int id, const char *Font, int FontSize, bool bBold, bool bItalic); EXPORT int BoxCreate(int x, int y, int w, int h, unsigned int dwColor, bool bShow); EXPORT int BoxDestroy(int id); EXPORT int BoxSetShown(int id, bool bShown); EXPORT int BoxSetBorder(int id, int height, bool bShown); EXPORT int BoxSetBorderColor(int id, unsigned int dwColor); EXPORT int BoxSetColor(int id, unsigned int dwColor); EXPORT int BoxSetHeight(int id, int height); EXPORT int BoxSetPos(int id, int x, int y); EXPORT int BoxSetWidth(int id, int width); EXPORT int LineCreate(int x1, int y1, int x2, int y2, int width, unsigned int color, bool bShow); EXPORT int LineDestroy(int id); EXPORT int LineSetShown(int id, bool bShown); EXPORT int LineSetColor(int id, unsigned int color); EXPORT int LineSetWidth(int id, int width); EXPORT int LineSetPos(int id, int x1, int y1, int x2, int y2); EXPORT int ImageCreate(const char *path, int x, int y, int rotation, int align, bool bShow); EXPORT int ImageDestroy(int id); EXPORT int ImageSetShown(int id, bool bShown); EXPORT int ImageSetAlign(int id, int align); EXPORT int ImageSetPos(int id, int x, int y); EXPORT int ImageSetRotation(int id, int rotation); EXPORT int DestroyAllVisual(); EXPORT int ShowAllVisual(); EXPORT int HideAllVisual(); EXPORT int GetFrameRate(); EXPORT int GetScreenSpecs(int& width, int& height); EXPORT int SetCalculationRatio(int width, int height); EXPORT int SetOverlayPriority(int id, int priority); EXPORT int SetOverlayCalculationEnabled(int id, bool enabled); } }
lgpl-3.0
Godin/sonar
server/sonar-web/src/main/js/components/issue/popups/SetIssueTagsPopup.tsx
2599
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import * as React from 'react'; import { difference, without } from 'lodash'; import TagsSelector from '../../tags/TagsSelector'; import { searchIssueTags } from '../../../api/issues'; import { DropdownOverlay } from '../../controls/Dropdown'; import { PopupPlacement } from '../../ui/popups'; interface Props { organization: string; selectedTags: string[]; setTags: (tags: string[]) => void; } interface State { searchResult: string[]; } const LIST_SIZE = 10; export default class SetIssueTagsPopup extends React.PureComponent<Props, State> { mounted = false; state: State = { searchResult: [] }; componentDidMount() { this.mounted = true; } componentWillUnmount() { this.mounted = false; } onSearch = (query: string) => { return searchIssueTags({ q: query, ps: Math.min(this.props.selectedTags.length - 1 + LIST_SIZE, 100), organization: this.props.organization }).then( (tags: string[]) => { if (this.mounted) { this.setState({ searchResult: tags }); } }, () => {} ); }; onSelect = (tag: string) => { this.props.setTags([...this.props.selectedTags, tag]); }; onUnselect = (tag: string) => { this.props.setTags(without(this.props.selectedTags, tag)); }; render() { const availableTags = difference(this.state.searchResult, this.props.selectedTags); return ( <DropdownOverlay placement={PopupPlacement.BottomRight}> <TagsSelector listSize={LIST_SIZE} onSearch={this.onSearch} onSelect={this.onSelect} onUnselect={this.onUnselect} selectedTags={this.props.selectedTags} tags={availableTags} /> </DropdownOverlay> ); } }
lgpl-3.0
smart-facility/TransMob
model/src/main/java/hibernate/postgres/TransimsHouseholdLocationEntity.java
7833
/* This file is part of TransMob. TransMob is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TransMob 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 Public License for more details. You should have received a copy of the GNU Lesser Public License along with TransMob. If not, see <http://www.gnu.org/licenses/>. */ package hibernate.postgres; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * Transims Household Locations entity. */ @Table(name = "transims_household_location", schema = "public") @Entity @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class TransimsHouseholdLocationEntity { private int dwellingIndex; @javax.persistence.Column(name = "dwelling_index", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) @Id public int getDwellingIndex() { return dwellingIndex; } public void setDwellingIndex(int dwellingIndex) { this.dwellingIndex = dwellingIndex; } private Integer activityLocation; @javax.persistence.Column(name = "activity_location", nullable = true, insertable = true, updatable = true, length = 10, precision = 0) @Basic public Integer getActivityLocation() { return activityLocation; } public void setActivityLocation(Integer activityLocation) { this.activityLocation = activityLocation; } private Integer cdCode; @javax.persistence.Column(name = "cd_code", nullable = true, insertable = true, updatable = true, length = 10, precision = 0) @Basic public Integer getCdCode() { return cdCode; } public void setCdCode(Integer cdCode) { this.cdCode = cdCode; } private Double xCoord; @javax.persistence.Column(name = "x_coord", nullable = true, insertable = true, updatable = true, length = 17, precision = 17) @Basic public Double getxCoord() { return xCoord; } public void setxCoord(Double xCoord) { this.xCoord = xCoord; } private Double yCoord; @javax.persistence.Column(name = "y_coord", nullable = true, insertable = true, updatable = true, length = 17, precision = 17) @Basic public Double getyCoord() { return yCoord; } public void setyCoord(Double yCoord) { this.yCoord = yCoord; } private Integer blockId; @javax.persistence.Column(name = "block_id", nullable = true, insertable = true, updatable = true, length = 10, precision = 0) @Basic public Integer getBlockId() { return blockId; } public void setBlockId(Integer blockId) { this.blockId = blockId; } private Integer noteBus; @javax.persistence.Column(name = "note_bus", nullable = true, insertable = true, updatable = true, length = 10, precision = 0) @Basic public Integer getNoteBus() { return noteBus; } public void setNoteBus(Integer noteBus) { this.noteBus = noteBus; } private Integer noteTrain; @javax.persistence.Column(name = "note_train", nullable = true, insertable = true, updatable = true, length = 10, precision = 0) @Basic public Integer getNoteTrain() { return noteTrain; } public void setNoteTrain(Integer noteTrain) { this.noteTrain = noteTrain; } private Integer hholdIndex; @javax.persistence.Column(name = "hhold_index", nullable = true, insertable = true, updatable = true, length = 10, precision = 0) @Basic public Integer getHholdIndex() { return hholdIndex; } public void setHholdIndex(Integer hholdIndex) { this.hholdIndex = hholdIndex; } private Integer travelZoneId; @javax.persistence.Column(name = "travel_zone_id", nullable = true, insertable = true, updatable = true, length = 10, precision = 0) @Basic public Integer getTravelZoneId() { return travelZoneId; } public void setTravelZoneId(Integer travelZoneId) { this.travelZoneId = travelZoneId; } private Integer yearAvailable; @javax.persistence.Column(name = "year_available", nullable = true, insertable = true, updatable = true, length = 10, precision = 0) @Basic public Integer getYearAvailable() { return yearAvailable; } public void setYearAvailable(Integer yearAvailable) { this.yearAvailable = yearAvailable; } private Integer bedroomsNumber; @javax.persistence.Column(name = "bedrooms_number", nullable = true, insertable = true, updatable = true, length = 10, precision = 0) @Basic public Integer getBedroomsNumber() { return bedroomsNumber; } public void setBedroomsNumber(Integer bedroomsNumber) { this.bedroomsNumber = bedroomsNumber; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TransimsHouseholdLocationEntity that = (TransimsHouseholdLocationEntity) o; if (dwellingIndex != that.dwellingIndex) return false; if (activityLocation != null ? !activityLocation.equals(that.activityLocation) : that.activityLocation != null) return false; if (bedroomsNumber != null ? !bedroomsNumber.equals(that.bedroomsNumber) : that.bedroomsNumber != null) return false; if (blockId != null ? !blockId.equals(that.blockId) : that.blockId != null) return false; if (cdCode != null ? !cdCode.equals(that.cdCode) : that.cdCode != null) return false; if (hholdIndex != null ? !hholdIndex.equals(that.hholdIndex) : that.hholdIndex != null) return false; if (noteBus != null ? !noteBus.equals(that.noteBus) : that.noteBus != null) return false; if (noteTrain != null ? !noteTrain.equals(that.noteTrain) : that.noteTrain != null) return false; if (travelZoneId != null ? !travelZoneId.equals(that.travelZoneId) : that.travelZoneId != null) return false; if (xCoord != null ? !xCoord.equals(that.xCoord) : that.xCoord != null) return false; if (yCoord != null ? !yCoord.equals(that.yCoord) : that.yCoord != null) return false; if (yearAvailable != null ? !yearAvailable.equals(that.yearAvailable) : that.yearAvailable != null) return false; return true; } @Override public int hashCode() { int result = dwellingIndex; result = 31 * result + (activityLocation != null ? activityLocation.hashCode() : 0); result = 31 * result + (cdCode != null ? cdCode.hashCode() : 0); result = 31 * result + (xCoord != null ? xCoord.hashCode() : 0); result = 31 * result + (yCoord != null ? yCoord.hashCode() : 0); result = 31 * result + (blockId != null ? blockId.hashCode() : 0); result = 31 * result + (noteBus != null ? noteBus.hashCode() : 0); result = 31 * result + (noteTrain != null ? noteTrain.hashCode() : 0); result = 31 * result + (hholdIndex != null ? hholdIndex.hashCode() : 0); result = 31 * result + (travelZoneId != null ? travelZoneId.hashCode() : 0); result = 31 * result + (yearAvailable != null ? yearAvailable.hashCode() : 0); result = 31 * result + (bedroomsNumber != null ? bedroomsNumber.hashCode() : 0); return result; } }
lgpl-3.0
instant-solutions/shiva4j
src/at/tripwire/shiva4j/objects/Artist.java
444
package at.tripwire.shiva4j.objects; public interface Artist { /** * The object's ID. */ int getId(); /** * Artist's name */ String getName(); /** * Link to a photo of the artist. */ String getImageUrl(); /** * The URI of this resource's instance. */ String getUri(); /** * The URI to domload this artist's tracks. */ String getDownloadUri(); /** * A slug of the artist's name. */ String getSlug(); }
lgpl-3.0
EvilInteractive/happy-engine
src/HappyEngine/code/io/BinaryVisitor.cpp
1295
//HappyEngine Copyright (C) 2011 - 2014 Evil Interactive // //This file is part of HappyEngine. // // HappyEngine 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. // // HappyEngine 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 HappyEngine. If not, see <http://www.gnu.org/licenses/>. // //Author: Bastian Damman //Created: 26/01/2013 #include "HappyPCH.h" #include "BinaryVisitor.h" namespace he { namespace io { template<> void BinaryVisitor::visit(he::String& value) { uint32 length(checked_numcast<uint32>(value.size())); visit(length); if (m_OpenType == eOpenType_Read) { value.resize(length); readBuffer(&value[0], sizeof(char) * length); } else { writeBuffer(&value[0], sizeof(char) * length); } } } } //end namespace
lgpl-3.0
kakserpom/phpdaemon
PHPDaemon/Examples/ExampleAsteriskClient.php
2079
<?php namespace PHPDaemon\Examples; use PHPDaemon\Clients\Asterisk\Pool; use PHPDaemon\Core\AppInstance; /** * @package Examples * @subpackage Asterisk * * @author TyShkan <denis@tyshkan.ru> */ class ExampleAsteriskClient extends AppInstance { public $asteriskclient; public $asteriskconn; /** * Constructor. * @return void */ public function init() { if ($this->isEnabled()) { $this->asteriskclient = Pool::getInstance($this->config->asteriskclientname->value); } } /** * Called when the worker is ready to go. * @return void */ public function onReady() { if ($this->asteriskclient) { $this->asteriskclient->onReady(); $this->connect(); } } public function connect() { $this->asteriskclient->getConnection($this->config->url->value, function ($conn) { $this->asteriskconn = $conn; if ($conn->connected) { $conn->bind('disconnect', function ($conn) { \PHPDaemon\Core\Daemon::log('Connection lost... Reconnect in ' . $this->config->reconnect->value . ' sec'); $this->connect(); }); } else { \PHPDaemon\Core\Daemon::log(get_class($this) . ': couldn\'t connect to ' . $this->config->url->value); } }); } /** * Called when application instance is going to shutdown. * @return boolean Ready to shutdown? */ public function onShutdown($graceful = false) { if ($this->asteriskclient) { return $this->asteriskclient->onShutdown(); } return true; } /** * Setting default config options * Overriden from AppInstance::getConfigDefaults * @return array|false */ protected function getConfigDefaults() { return [ 'url' => 'tcp://user:password@localhost:5038', 'reconnect' => 1, 'asteriskclient-name' => '' ]; } }
lgpl-3.0
gabi2/libyui-ncurses
src/NCRichText.cc
24097
/* Copyright (C) 2000-2012 Novell, Inc This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3.0 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*-/ File: NCRichText.cc Author: Michael Andres <ma@suse.de> /-*/ #define YUILogComponent "ncurses" #include <yui/YUILog.h> #include "NCRichText.h" #include "YNCursesUI.h" #include "stringutil.h" #include "stdutil.h" #include <sstream> #include <boost/algorithm/string.hpp> #include <yui/YMenuItem.h> #include <yui/YApplication.h> using stdutil::form; const unsigned NCRichText::listindent = 4; const std::wstring NCRichText::listleveltags( L"@*+o#-%$&" );// const bool NCRichText::showLinkTarget = false; std::map<std::wstring, std::wstring> NCRichText::_charentity; const std::wstring NCRichText::entityLookup( const std::wstring & val_r ) { //strip leading '#', if any std::wstring::size_type hash = val_r.find( L"#", 0 ); std::wstring ascii = L""; if ( hash != std::wstring::npos ) { std::wstring s = val_r.substr( hash + 1 ); wchar_t *endptr; //and try to convert to int (wcstol only knows "0x" for hex) boost::replace_all( s, "x", "0x" ); long int c = std::wcstol( s.c_str(), &endptr, 0 ); //conversion succeeded if ( s.c_str() != endptr ) { std::wostringstream ws; ws << char( c ); ascii = ws.str(); } } #define REP(l,r) _charentity[l] = r if ( _charentity.empty() ) { // initialize replacement for character entities. A value of NULL // means do not replace. std::wstring product; NCstring::RecodeToWchar( YUI::app()->productName(), "UTF-8", &product ); REP( L"amp", L"&" ); REP( L"gt", L">" ); REP( L"lt", L"<" ); REP( L"nbsp", L" " ); REP( L"quot", L"\"" ); REP( L"product", product ); } std::map<std::wstring, std::wstring>::const_iterator it = _charentity.find( val_r ); if ( it != _charentity.end() ) { //known entity - already in the map return it->second; } else { if ( !ascii.empty() ) { //replace ascii code by character - e.g. #42 -> '*' //and insert into map to remember it REP( val_r, ascii ); } } return ascii; #undef REP } /** * Filter out the known &...; entities and return the text with entities * replaced **/ const std::wstring NCRichText::filterEntities( const std::wstring & text ) { std::wstring txt = text; // filter known '&..;' for ( std::wstring::size_type special = txt.find( L"&" ); special != std::wstring::npos; special = txt.find( L"&", special + 1 ) ) { std::wstring::size_type colon = txt.find( L";", special + 1 ); if ( colon == std::wstring::npos ) break; // no ';' -> no need to continue const std::wstring repl = entityLookup( txt.substr( special + 1, colon - special - 1 ) ); if ( !repl.empty() || txt.substr( special + 1, colon - special - 1 ) == L"product" ) // always replace &product; { txt.replace( special, colon - special + 1, repl ); } else yuiMilestone() << "porn.bat" << std::endl; } return txt; } void NCRichText::Anchor::draw( NCPad & pad, const chtype attr, int color ) { unsigned l = sline; unsigned c = scol; while ( l < eline ) { pad.move( l, c ); pad.chgat( -1, attr, color ); ++l; c = 0; } pad.move( l, c ); pad.chgat( ecol - c, attr, color ); } NCRichText::NCRichText( YWidget * parent, const std::string & ntext, bool plainTextMode ) : YRichText( parent, ntext, plainTextMode ) , NCPadWidget( parent ) , text( ntext ) , plainText( plainTextMode ) , textwidth( 0 ) , cl( 0 ) , cc( 0 ) , cindent( 0 ) , atbol( true ) , preTag( false ) , Tattr( 0 ) { yuiDebug() << std::endl; activeLabelOnly = true; setValue( ntext ); } NCRichText::~NCRichText() { yuiDebug() << std::endl; } int NCRichText::preferredWidth() { return wGetDefsze().W; } int NCRichText::preferredHeight() { return wGetDefsze().H; } void NCRichText::setEnabled( bool do_bv ) { NCWidget::setEnabled( do_bv ); YRichText::setEnabled( do_bv ); } void NCRichText::setSize( int newwidth, int newheight ) { wRelocate( wpos( 0 ), wsze( newheight, newwidth ) ); } void NCRichText::setLabel( const std::string & nlabel ) { // not implemented: YRichText::setLabel( nlabel ); NCPadWidget::setLabel( NCstring( nlabel ) ); } void NCRichText::setValue( const std::string & ntext ) { DelPad(); text = NCstring( ntext ); YRichText::setValue( ntext ); Redraw(); } void NCRichText::wRedraw() { if ( !win ) return; bool initial = ( !myPad() || !myPad()->Destwin() ); if ( !( plainText || anchors.empty() ) ) arm( armed ); NCPadWidget::wRedraw(); if ( initial && autoScrollDown() ) { myPad()->ScrlTo( wpos( myPad()->maxy(), 0 ) ); } return; } void NCRichText::wRecoded() { DelPad(); wRedraw(); } NCursesEvent NCRichText::wHandleInput( wint_t key ) { NCursesEvent ret; handleInput( key ); if ( !( plainText || anchors.empty() ) ) { switch ( key ) { case KEY_SPACE: case KEY_RETURN: if ( armed != Anchor::unset ) { ret = NCursesEvent::menu; std::string str; NCstring::RecodeFromWchar( anchors[armed].target, "UTF-8", &str ); yuiMilestone() << "LINK: " << str << std::endl; ret.result = str; ret.selection = NULL; } break; } } return ret; } NCPad * NCRichText::CreatePad() { wsze psze( defPadSze() ); textwidth = psze.W; NCPad * npad = new NCPad( psze.H, textwidth, *this ); return npad; } void NCRichText::DrawPad() { yuiDebug() << "Start: plain mode " << plainText << std::endl << " padsize " << myPad()->size() << std::endl << " text length " << text.str().size() << std::endl; myPad()->bkgdset( wStyle().richtext.plain ); myPad()->clear(); if ( plainText ) DrawPlainPad(); else DrawHTMLPad(); yuiDebug() << "Done" << std::endl; } void NCRichText::DrawPlainPad() { NCtext ftext( text ); yuiDebug() << "ftext is " << wsze( ftext.Lines(), ftext.Columns() ) << std::endl; AdjustPad( wsze( ftext.Lines(), ftext.Columns() ) ); cl = 0; for ( NCtext::const_iterator line = ftext.begin(); line != ftext.end(); ++line, ++cl ) { myPad()->addwstr( cl, 0, ( *line ).str().c_str() ); } } void NCRichText::PadPreTXT( const wchar_t * osch, const unsigned olen ) { std::wstring wtxt( osch, olen ); // resolve the entities even in PRE (#71718) wtxt = filterEntities( wtxt ); NCstring nctxt( wtxt ); NCtext ftext( nctxt ); // insert the text const wchar_t * sch = wtxt.data(); while ( *sch ) { myPad()->addwstr( sch, 1 ); // add one wide chararacter ++sch; } } // // DrawHTMLPad tools // inline void SkipToken( const wchar_t *& wch ) { do { ++wch; } while ( *wch && *wch != L'>' ); if ( *wch ) ++wch; } static std::wstring WStoken( L" \n\t\v\r\f" ); inline void SkipWS( const wchar_t *& wch ) { do { ++wch; } while ( *wch && WStoken.find( *wch ) != std::wstring::npos ); } static std::wstring WDtoken( L" <\n\t\v\r\f" ); // WS + TokenStart '<' inline void SkipWord( const wchar_t *& wch ) { do { ++wch; } while ( *wch && WDtoken.find( *wch ) == std::wstring::npos ); } static std::wstring PREtoken( L"<\n\v\r\f" ); // line manipulations + TokenStart '<' inline void SkipPreTXT( const wchar_t *& wch ) { do { ++wch; } while ( *wch && PREtoken.find( *wch ) == std::wstring::npos ); } // // Calculate longest line of text in <pre> </pre> tags // and adjust the pad accordingly // void NCRichText::AdjustPrePad( const wchar_t *osch ) { const wchar_t * wch = osch; std::wstring wstr( wch, 6 ); do { ++wch; wstr.assign( wch, 6 ); } while ( *wch && wstr != L"</pre>" ); std::wstring wtxt( osch, wch - osch ); // resolve the entities to get correct length for calculation of longest line wtxt = filterEntities( wtxt ); // replace <br> by \n to get appropriate lines in NCtext boost::replace_all( wtxt, L"<br>", L"\n" ); yuiDebug() << "Text: " << wtxt << " initial length: " << wch - osch << std::endl; NCstring nctxt( wtxt ); NCtext ftext( nctxt ); std::list<NCstring>::const_iterator line; size_t llen = 0; // longest line // iterate through NCtext for ( line = ftext.Text().begin(); line != ftext.Text().end(); ++line ) { size_t tmp_len = 0; tmp_len = textWidth( (*line).str() ); if ( tmp_len > llen ) llen = tmp_len; } yuiDebug() << "Longest line: " << llen << std::endl; if ( llen > textwidth ) { textwidth = llen; AdjustPad( wsze( cl + ftext.Lines(), llen ) ); // adjust pad to longest line } } void NCRichText::DrawHTMLPad() { yuiDebug() << "Start:" << std::endl; liststack = std::stack<int>(); canchor = Anchor(); anchors.clear(); armed = Anchor::unset; cl = 0; cc = 0; cindent = 0; myPad()->move( cl, cc ); atbol = true; const wchar_t * wch = ( wchar_t * )text.str().data(); const wchar_t * swch = 0; while ( *wch ) { switch ( *wch ) { case L' ': case L'\t': case L'\n': case L'\v': case L'\r': case L'\f': if ( ! preTag ) { SkipWS( wch ); PadWS(); } else { switch ( *wch ) { case L' ': // add white space case L'\t': myPad()->addwstr( wch, 1 ); break; case L'\n': case L'\f': PadNL(); // add new line break; default: yuiDebug() << "Ignoring " << *wch << std::endl; } ++wch; } break; case L'<': swch = wch; SkipToken( wch ); if ( PadTOKEN( swch, wch ) ) break; // strip token else wch = swch; // reset and fall through default: swch = wch; if ( !preTag ) { SkipWord( wch ); PadTXT( swch, wch - swch ); } else { SkipPreTXT( wch ); PadPreTXT( swch, wch - swch ); } break; } } PadBOL(); AdjustPad( wsze( cl, textwidth ) ); yuiDebug() << "Anchors: " << anchors.size() << std::endl; for ( unsigned i = 0; i < anchors.size(); ++i ) { yuiDebug() << form( " %2d: [%2d,%2d] -> [%2d,%2d]", i, anchors[i].sline, anchors[i].scol, anchors[i].eline, anchors[i].ecol ) << std::endl; } } inline void NCRichText::PadNL() { cc = cindent; if ( ++cl == ( unsigned )myPad()->height() ) { AdjustPad( wsze( myPad()->height() + defPadSze().H, textwidth ) ); } myPad()->move( cl, cc ); atbol = true; } inline void NCRichText::PadBOL() { if ( !atbol ) PadNL(); } inline void NCRichText::PadWS( const bool tab ) { if ( atbol ) return; // no WS at beginning of line if ( cc == textwidth ) { PadNL(); } else { myPad()->addwstr( L" " ); ++cc; } } inline void NCRichText::PadTXT( const wchar_t * osch, const unsigned olen ) { std::wstring txt( osch, olen ); txt = filterEntities( txt ); size_t len = textWidth( txt ); if ( !atbol && cc + len > textwidth ) PadNL(); // insert the text const wchar_t * sch = txt.data(); while ( *sch ) { myPad()->addwstr( sch, 1 ); // add one wide chararacter cc += wcwidth( *sch ); atbol = false; // at begin of line = false if ( cc >= textwidth ) { PadNL(); // add a new line } sch++; } } /** * Get the number of columns needed to print a 'std::wstring'. Only printable characters * are taken into account because otherwise 'wcwidth' would return -1 (e.g. for '\n'). * Tabs are calculated with tabsize(). * Attention: only use textWidth() to calculate space, not for iterating through a text * or to get the length of a text (real text length includes new lines). */ size_t NCRichText::textWidth( std::wstring wstr ) { size_t len = 0; std::wstring::const_iterator wstr_it; // iterator for std::wstring for ( wstr_it = wstr.begin(); wstr_it != wstr.end() ; ++wstr_it ) { // check whether char is printable if ( iswprint( *wstr_it ) ) { len += wcwidth( *wstr_it ); } else if ( *wstr_it == '\t' ) { len += myPad()->tabsize(); } } return len; } /** * Set character attributes (e.g. color, font face...) **/ inline void NCRichText::PadSetAttr() { const NCstyle::StRichtext & style( wStyle().richtext ); chtype nbg = style.plain; if ( Tattr & T_ANC ) { nbg = style.link; } else if ( Tattr & T_HEAD ) { nbg = style.title; } else { switch ( Tattr & Tfontmask ) { case T_BOLD: nbg = style.B; break; case T_IT: nbg = style.I; break; case T_TT: nbg = style.T; break; case T_BOLD|T_IT: nbg = style.BI; break; case T_BOLD|T_TT: nbg = style.BT; break; case T_IT|T_TT: nbg = style.IT; break; case T_BOLD|T_IT|T_TT: nbg = style.BIT; break; } } myPad()->bkgdset( nbg ); } void NCRichText::PadSetLevel() { cindent = listindent * liststack.size(); if ( cindent > textwidth / 2 ) cindent = textwidth / 2; if ( atbol ) { cc = cindent; myPad()->move( cl, cc ); } } void NCRichText::PadChangeLevel( bool down, int tag ) { if ( down ) { if ( liststack.size() ) liststack.pop(); } else { liststack.push( tag ); } PadSetLevel(); } void NCRichText::openAnchor( std::wstring args ) { canchor.open( cl, cc ); const wchar_t * ch = ( wchar_t * )args.data(); const wchar_t * lookupstr = L"href = "; const wchar_t * lookup = lookupstr; for ( ; *ch && *lookup; ++ch ) { wchar_t c = towlower( *ch ); switch ( c ) { case L'\t': case L' ': if ( *lookup != L' ' ) lookup = lookupstr; break; default: if ( *lookup == L' ' ) { ++lookup; if ( !*lookup ) { // ch is the 1st char after lookupstr --ch; // end of loop will ++ch break; } } if ( c == *lookup ) ++lookup; else lookup = lookupstr; break; } } if ( !*lookup ) { const wchar_t * delim = ( *ch == L'"' ) ? L"\"" : L" \t"; args = ( *ch == L'"' ) ? ++ch : ch; std::wstring::size_type end = args.find_first_of( delim ); if ( end != std::wstring::npos ) args.erase( end ); canchor.target = args; } else { yuiError() << "No value for 'HREF=' in anchor '" << args << "'" << std::endl; } } void NCRichText::closeAnchor() { canchor.close( cl, cc ); if ( canchor.valid() ) anchors.push_back( canchor ); canchor = Anchor(); } // expect "<[/]value>" bool NCRichText::PadTOKEN( const wchar_t * sch, const wchar_t *& ech ) { // "<[/]value>" if ( *sch++ != L'<' || *( ech - 1 ) != L'>' ) return false; // "[/]value>" bool endtag = ( *sch == L'/' ); if ( endtag ) ++sch; // "value>" if ( ech - sch <= 1 ) return false; std::wstring value( sch, ech - 1 - sch ); std::wstring args; std::wstring::size_type argstart = value.find_first_of( L" \t\n" ); if ( argstart != std::wstring::npos ) { args = value.substr( argstart ); value.erase( argstart ); } for ( unsigned i = 0; i < value.length(); ++i ) { if ( isupper( value[i] ) ) { value[i] = static_cast<char>( tolower( value[i] ) ); } } int leveltag = 0; int headinglevel = 0; TOKEN token = T_UNKNOWN; switch ( value.length() ) { case 1: if ( value[0] == 'b' ) token = T_BOLD; else if ( value[0] == 'i' ) token = T_IT; else if ( value[0] == 'p' ) token = T_PAR; else if ( value[0] == 'a' ) token = T_ANC; else if ( value[0] == 'u' ) token = T_BOLD; break; case 2: if ( value == L"br" ) token = T_BR; else if ( value == L"em" ) token = T_IT; else if ( value == L"h1" ) { token = T_HEAD; headinglevel = 1; } else if ( value == L"h2" ) { token = T_HEAD; headinglevel = 2; } else if ( value == L"h3" ) { token = T_HEAD; headinglevel = 3; } else if ( value == L"hr" ) token = T_IGNORE; else if ( value == L"li" ) token = T_LI; else if ( value == L"ol" ) { token = T_LEVEL; leveltag = 1; } else if ( value == L"qt" ) token = T_IGNORE; else if ( value == L"tt" ) token = T_TT; else if ( value == L"ul" ) { token = T_LEVEL; leveltag = 0; } break; case 3: if ( value == L"big" ) token = T_IGNORE; else if ( value == L"pre" ) token = T_PLAIN; break; case 4: if ( value == L"bold" ) token = T_BOLD; else if ( value == L"code" ) token = T_TT; else if ( value == L"font" ) token = T_IGNORE; break; case 5: if ( value == L"large" ) token = T_IGNORE; else if ( value == L"small" ) token = T_IGNORE; break; case 6: if ( value == L"center" ) token = T_PAR; else if ( value == L"strong" ) token = T_BOLD; break; case 10: if ( value == L"blockquote" ) token = T_PAR; break; default: token = T_UNKNOWN; break; } if ( token == T_UNKNOWN ) { yuiDebug() << "T_UNKNOWN :" << value << ":" << args << ":" << std::endl; // see bug #67319 // return false; return true; } if ( token == T_IGNORE ) return true; switch ( token ) { case T_LEVEL: PadChangeLevel( endtag, leveltag ); PadBOL(); // add new line after end of the list // (only at the very end) if ( endtag && !cindent ) PadNL(); break; case T_BR: PadNL(); break; case T_HEAD: if ( endtag ) Tattr &= ~token; else Tattr |= token; PadSetAttr(); PadBOL(); if ( headinglevel && endtag ) PadNL(); break; case T_PAR: PadBOL(); if ( !cindent ) { if ( endtag ) // add new line after closing tag (FaTE 3124) PadNL(); } break; case T_LI: PadSetLevel(); PadBOL(); if ( !endtag ) { std::wstring tag; if ( liststack.empty() ) { tag = std::wstring( listindent, L' ' ); } else { wchar_t buf[16]; if ( liststack.top() ) { swprintf( buf, 15, L"%2ld. ", liststack.top()++ ); } else { swprintf( buf, 15, L" %lc ", listleveltags[liststack.size()%listleveltags.size()] ); } tag = buf; } // outsent list tag: cc = ( tag.size() < cc ? cc - tag.size() : 0 ); myPad()->move( cl, cc ); PadTXT( tag.c_str(), tag.size() ); atbol = true; } break; case T_PLAIN: if ( !endtag ) { preTag = true; // display text preserving newlines and spaces AdjustPrePad( ech ); } else { preTag = false; PadNL(); // add new line (text may continue after </pre>) } break; case T_ANC: if ( endtag ) { closeAnchor(); } else { openAnchor( args ); } // fall through case T_BOLD: case T_IT: case T_TT: if ( endtag ) Tattr &= ~token; else Tattr |= token; PadSetAttr(); break; case T_IGNORE: case T_UNKNOWN: break; } return true; } void NCRichText::arm( unsigned i ) { if ( !myPad() ) { armed = i; return; } yuiDebug() << i << " (" << armed << ")" << std::endl; if ( i == armed ) { if ( armed != Anchor::unset ) { // just redraw anchors[armed].draw( *myPad(), wStyle().richtext.getArmed( GetState() ), 0 ); myPad()->update(); } return; } if ( armed != Anchor::unset ) { anchors[armed].draw( *myPad(), wStyle().richtext.link, ( int ) wStyle().richtext.visitedlink ); armed = Anchor::unset; } if ( i != Anchor::unset ) { armed = i; anchors[armed].draw( *myPad(), wStyle().richtext.getArmed( GetState() ), 0 ); } if ( showLinkTarget ) { if ( armed != Anchor::unset ) NCPadWidget::setLabel( NCstring( anchors[armed].target ) ); else NCPadWidget::setLabel( NCstring() ); } else { myPad()->update(); } } void NCRichText::HScroll( unsigned total, unsigned visible, unsigned start ) { NCPadWidget::HScroll( total, visible, start ); // no hyperlink handling needed, because Ritchtext does not HScroll } void NCRichText::VScroll( unsigned total, unsigned visible, unsigned start ) { NCPadWidget::VScroll( total, visible, start ); if ( plainText || anchors.empty() ) return; // <-- no links to check // Take care of hyperlinks: Check whether an armed link is visible. // If not arm the first visible link on page or none. vScrollFirstvisible = start; vScrollNextinvisible = start + visible; if ( armed != Anchor::unset ) { if ( anchors[armed].within( vScrollFirstvisible, vScrollNextinvisible ) ) return; // <-- armed link is vissble else disarm(); } for ( unsigned i = 0; i < anchors.size(); ++i ) { if ( anchors[i].within( vScrollFirstvisible, vScrollNextinvisible ) ) { arm( i ); break; } } } bool NCRichText::handleInput( wint_t key ) { if ( plainText || anchors.empty() ) { return NCPadWidget::handleInput( key ); } // take care of hyperlinks bool handled = true; switch ( key ) { case KEY_LEFT: // jump to previous link; scroll up if none { unsigned newarmed = Anchor::unset; if ( armed == Anchor::unset ) { // look for an anchor above current page for ( unsigned i = anchors.size(); i; ) { --i; if ( anchors[i].eline < vScrollFirstvisible ) { newarmed = i; break; } } } else if ( armed > 0 ) { newarmed = armed - 1; } if ( newarmed == Anchor::unset ) { handled = NCPadWidget::handleInput( KEY_UP ); } else { if ( !anchors[newarmed].within( vScrollFirstvisible, vScrollNextinvisible ) ) myPad()->ScrlLine( anchors[newarmed].sline ); arm( newarmed ); } } break; case KEY_RIGHT: // jump to next link; scroll down if none { unsigned newarmed = Anchor::unset; if ( armed == Anchor::unset ) { // look for an anchor below current page for ( unsigned i = 0; i < anchors.size(); ++i ) { if ( anchors[i].sline >= vScrollNextinvisible ) { newarmed = i; break; } } } else if ( armed + 1 < anchors.size() ) { newarmed = armed + 1; } if ( newarmed == Anchor::unset ) { handled = NCPadWidget::handleInput( KEY_DOWN ); } else { if ( !anchors[newarmed].within( vScrollFirstvisible, vScrollNextinvisible ) ) myPad()->ScrlLine( anchors[newarmed].sline ); arm( newarmed ); } } break; case KEY_UP: // arm previous visible link; scroll up if none if ( armed != Anchor::unset && armed > 0 && anchors[armed-1].within( vScrollFirstvisible, vScrollNextinvisible ) ) { arm( armed - 1 ); } else { handled = NCPadWidget::handleInput( key ); } break; case KEY_DOWN: // arm next visible link; scroll down if none if ( armed != Anchor::unset && armed + 1 < anchors.size() && anchors[armed+1].within( vScrollFirstvisible, vScrollNextinvisible ) ) { arm( armed + 1 ); } else { handled = NCPadWidget::handleInput( key ); } break; default: handled = NCPadWidget::handleInput( key ); }; return handled; }
lgpl-3.0
horazont/aioxmpp
tests/forms/test_form.py
27399
######################################################################## # File name: test_form.py # This file is part of: aioxmpp # # LICENSE # # 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/>. # ######################################################################## import abc import copy import unittest import unittest.mock import aioxmpp import aioxmpp.forms.fields as fields import aioxmpp.forms.form as form import aioxmpp.forms.xso as forms_xso class FakeDescriptor(fields.AbstractDescriptor): def __init__(self, key): self._keys = [key] def descriptor_keys(self): return self._keys class TestDescriptorClass(unittest.TestCase): def test_is_abcmeta(self): self.assertTrue(issubclass( form.DescriptorClass, abc.ABCMeta, )) def test_init(self): class Cls(metaclass=form.DescriptorClass): pass self.assertDictEqual( Cls.DESCRIPTOR_MAP, {}, ) self.assertSequenceEqual( list(Cls.DESCRIPTORS), [], ) self.assertSequenceEqual( Cls.__slots__, (), ) def test_use_slots_from_declaration(self): class Cls(metaclass=form.DescriptorClass): __slots__ = ("foo", ) self.assertSequenceEqual( Cls.__slots__, ("foo",) ) def test_inherit_slots(self): class Base(metaclass=form.DescriptorClass): __slots__ = ("foo", ) class Child(Base): pass self.assertSequenceEqual( Child.__slots__, () ) def test_disable_slots_via_kwarg(self): class Cls(metaclass=form.DescriptorClass, protect=False): pass self.assertFalse(hasattr(Cls, "__slots__")) def test_collect_descriptors(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor(("foo", "bar")) x2 = FakeDescriptor(("baz",)) self.assertDictEqual( Cls.DESCRIPTOR_MAP, { ("foo", "bar"): Cls.x1, ("baz", ): Cls.x2, } ) self.assertSetEqual( set(Cls.DESCRIPTORS), { Cls.x1, Cls.x2, } ) def test_single_inheritance(self): class ClsA(metaclass=form.DescriptorClass): x1 = FakeDescriptor("x1") class ClsB(ClsA): x2 = FakeDescriptor("x2") self.assertDictEqual( ClsA.DESCRIPTOR_MAP, { "x1": ClsA.x1, } ) self.assertSetEqual( ClsA.DESCRIPTORS, { ClsA.x1, } ) self.assertDictEqual( ClsB.DESCRIPTOR_MAP, { "x1": ClsA.x1, "x2": ClsB.x2, } ) self.assertSetEqual( ClsB.DESCRIPTORS, { ClsA.x1, ClsB.x2, } ) def test_multi_inheritance(self): class ClsA(metaclass=form.DescriptorClass): x1 = FakeDescriptor("x1") class ClsB(ClsA): x2 = FakeDescriptor("x2") class ClsC(ClsA): x3 = FakeDescriptor("x3") class ClsD(ClsB, ClsC): x4 = FakeDescriptor("x4") self.assertDictEqual( ClsD.DESCRIPTOR_MAP, { "x1": ClsD.x1, "x2": ClsD.x2, "x3": ClsD.x3, "x4": ClsD.x4, } ) self.assertSetEqual( ClsD.DESCRIPTORS, { ClsD.x1, ClsD.x2, ClsD.x3, ClsD.x4, } ) def test_reject_conflicts(self): with self.assertRaisesRegex( TypeError, "descriptor with key .* already declared at .*"): class ClsA(metaclass=form.DescriptorClass): x1 = FakeDescriptor("x1") x2 = FakeDescriptor("x1") def test_reject_conflicts_at_multi_inheritance(self): class ClsA(metaclass=form.DescriptorClass): x1 = FakeDescriptor("x1") class ClsB(metaclass=form.DescriptorClass): x2 = FakeDescriptor("x1") with self.assertRaisesRegex( TypeError, "descriptor with key .* already declared at .*"): class ClsC(ClsA, ClsB): pass def test_late_addition_of_descriptors(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("foo") Cls.x2 = FakeDescriptor("bar") self.assertDictEqual( Cls.DESCRIPTOR_MAP, { "foo": Cls.x1, "bar": Cls.x2, } ) self.assertSetEqual( Cls.DESCRIPTORS, { Cls.x1, Cls.x2, } ) def test_reject_conflict_on_late_addition_of_descriptors(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("foo") with self.assertRaisesRegex( TypeError, r"descriptor with key .* already declared at .*"): Cls.x2 = FakeDescriptor("foo") self.assertDictEqual( Cls.DESCRIPTOR_MAP, { "foo": Cls.x1, } ) self.assertSetEqual( Cls.DESCRIPTORS, { Cls.x1, } ) def test_reject_late_addition_for_subclassed(self): class ClsA(metaclass=form.DescriptorClass): x1 = FakeDescriptor("foo") class ClsB(ClsA): pass with self.assertRaisesRegex( TypeError, r"cannot add descriptors to classes with subclasses"): ClsA.x2 = FakeDescriptor("bar") def test_reject_removal_of_descriptors(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("x1") with self.assertRaisesRegex( AttributeError, r"removal of descriptors is not allowed"): del Cls.x1 def test_allow_removal_of_other_attributes(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("x1") x2 = "foo" del Cls.x2 self.assertFalse(hasattr(Cls, "x2")) def test_reject_overwriting_descriptor_attribute(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("x1") with self.assertRaisesRegex( AttributeError, r"descriptor attributes cannot be set"): Cls.x1 = "foo" def test_allow_setting_and_overwriting_other_attributes(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("x1") Cls.x2 = "foo" Cls.x3 = "bar" Cls.x2 = 10 def test_set_attribute_name_on_descriptors(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("foo") x2 = FakeDescriptor("bar") self.assertEqual(Cls.x1.attribute_name, "x1") self.assertEqual(Cls.x2.attribute_name, "x2") def test_set_root_class_on_descriptors(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("foo") x2 = FakeDescriptor("bar") self.assertIs(Cls.x1.root_class, Cls) self.assertIs(Cls.x2.root_class, Cls) def test_reject_descriptor_used_twice(self): d = FakeDescriptor("foo") class ClsA(metaclass=form.DescriptorClass): x1 = d with self.assertRaisesRegex( ValueError, r"descriptor cannot be used on multiple classes"): class ClsB(metaclass=form.DescriptorClass): x1 = d def test_register_descriptor_keys(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("foo") Cls._register_descriptor_keys( Cls.x1, ["bar", "baz"] ) self.assertDictEqual( Cls.DESCRIPTOR_MAP, { "foo": Cls.x1, "bar": Cls.x1, "baz": Cls.x1, } ) def test_reject_conflict_on__register_descriptor_keys(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("foo") x2 = FakeDescriptor("bar") with self.assertRaisesRegex( TypeError, r"descriptor with key .* already declared at .*"): Cls._register_descriptor_keys(Cls.x1, ["bar"]) def test_reject__register_descriptor_keys_for_subclassed(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("foo") class Subclass(Cls): pass with self.assertRaisesRegex( TypeError, r"descriptors cannot be modified on classes with subclasses"): Cls._register_descriptor_keys(Cls.x1, ["bar"]) def test_reject__register_descriptor_keys_if_not_root_class(self): class Cls(metaclass=form.DescriptorClass): x1 = FakeDescriptor("foo") class Subclass(Cls): pass with self.assertRaisesRegex( TypeError, r"descriptors cannot be modified on classes with subclasses"): Subclass._register_descriptor_keys( Subclass.x1, ["bar"] ) class TestFormClass(unittest.TestCase): def test_is_DescriptorClass(self): self.assertTrue(issubclass( form.FormClass, form.DescriptorClass, )) class TestForm(unittest.TestCase): def test_init(self): class F(form.Form): field = fields.TextSingle( "foovar", ) f = F() self.assertDictEqual( f._descriptor_data, {}, ) f2 = F() self.assertIsNot( f._descriptor_data, f2._descriptor_data ) self.assertIsNone( f._recv_xso, ) def test___new___creates_data_dict(self): class F(form.Form): pass f = F.__new__(F) self.assertDictEqual(f._descriptor_data, {}) def test_from_xso_checks_FORM_TYPE(self): class F(form.Form): FORM_TYPE = "foo" tree = forms_xso.Data(type_=forms_xso.DataType.FORM) tree.fields.append( forms_xso.Field( type_=forms_xso.FieldType.HIDDEN, values=["bar"], var="FORM_TYPE" ) ) with self.assertRaisesRegex( ValueError, "mismatching FORM_TYPE"): F.from_xso(tree) def test_form_xso_allows_all_data_types(self): allow = [ forms_xso.DataType.CANCEL, forms_xso.DataType.FORM, forms_xso.DataType.SUBMIT, forms_xso.DataType.RESULT, ] class F(form.Form): pass for t in forms_xso.DataType: tree = forms_xso.Data(type_=t) F.from_xso(tree) def test_from_xso_single_field(self): class F(form.Form): field = fields.TextSingle( "foobar", ) tree = forms_xso.Data(type_=forms_xso.DataType.FORM) tree.fields.append( forms_xso.Field(values=["value"], var="foobar") ) f = F.from_xso(tree) self.assertIsInstance(f, F) self.assertEqual( f.field.value, "value", ) def test_from_xso_handles_missing_type_(self): class F(form.Form): field = fields.ListSingle( "foobar", ) tree = forms_xso.Data(type_=forms_xso.DataType.FORM) tree.fields.append( forms_xso.Field(type_=None, values=["value"], var="foobar") ) f = F.from_xso(tree) self.assertIsInstance(f, F) self.assertEqual( f.field.value, "value", ) def test_copies_have_independent_descriptor_data(self): class F(form.Form): field = fields.TextSingle( "foovar", ) f = F() f.field.value = "foo" copied = copy.copy(f) self.assertDictEqual( f._descriptor_data, copied._descriptor_data, ) self.assertIsNot( f._descriptor_data, copied._descriptor_data, ) def test_deepcopy_does_not_copy_descriptors(self): class F(form.Form): field = fields.TextSingle( "foovar", ) f = F() f.field.value = "foo" copied = copy.deepcopy(f) self.assertIsNot( f._descriptor_data, copied._descriptor_data, ) self.assertIsNot( f.field, copied.field, ) def test_from_xso_complex(self): data = forms_xso.Data(type_=forms_xso.DataType.FORM) data.fields.append( forms_xso.Field( var="FORM_TYPE", type_=forms_xso.FieldType.HIDDEN, values=["some-uri"], ) ) data.fields.append( forms_xso.Field( type_=forms_xso.FieldType.FIXED, values=["This is some heading."], ) ) data.fields.append( forms_xso.Field( var="jid", type_=forms_xso.FieldType.JID_SINGLE, values=[], desc="some description", label="some label", ) ) class F(form.Form): jid = fields.JIDSingle( var="jid", ) f = F.from_xso(data) self.assertIsNone(f.jid.value) self.assertIs(f._recv_xso, data) def test_from_xso_rejects_mismatching_type(self): data = forms_xso.Data(type_=forms_xso.DataType.FORM) data.fields.append( forms_xso.Field( var="FORM_TYPE", type_=forms_xso.FieldType.HIDDEN, values=["some-uri"], ) ) data.fields.append( forms_xso.Field( type_=forms_xso.FieldType.FIXED, values=["This is some heading."], ) ) data.fields.append( forms_xso.Field( var="jid", type_=forms_xso.FieldType.JID_SINGLE, values=[], desc="some description", label="some label", ) ) class F(form.Form): jid = fields.TextSingle( var="jid", ) with self.assertRaisesRegex( ValueError, r"mismatching type (.+ != .+) on field .+"): F.from_xso(data) def test_from_xso_allows_upcast(self): data = forms_xso.Data(type_=forms_xso.DataType.FORM) data.fields.append( forms_xso.Field( var="FORM_TYPE", type_=forms_xso.FieldType.HIDDEN, values=["some-uri"], ) ) data.fields.append( forms_xso.Field( type_=forms_xso.FieldType.FIXED, values=["This is some heading."], ) ) data.fields.append( forms_xso.Field( var="jid", type_=forms_xso.FieldType.TEXT_SINGLE, values=[], desc="some description", label="some label", ) ) class F(form.Form): jid = fields.TextPrivate( var="jid", ) F.from_xso(data) def test_render_reply(self): data = forms_xso.Data(type_=forms_xso.DataType.FORM) data.fields.append( forms_xso.Field( var="FORM_TYPE", type_=forms_xso.FieldType.HIDDEN, values=["some-uri"], ) ) data.fields.append( forms_xso.Field( type_=forms_xso.FieldType.FIXED, values=["This is some heading."], ) ) data.fields.append( forms_xso.Field( var="jid", type_=forms_xso.FieldType.JID_SINGLE, values=[], desc="some description", ) ) class F(form.Form): jid = fields.JIDSingle( var="jid", label="Foobar" ) other = fields.TextSingle( var="foo", ) f = F.from_xso(data) f.jid.value = aioxmpp.JID.fromstr("foo@bar.baz") result = f.render_reply() self.assertIsInstance(result, forms_xso.Data) self.assertEqual( result.type_, forms_xso.DataType.SUBMIT, ) self.assertEqual( len(result.fields), 3 ) self.assertIs( data.fields[0], result.fields[0] ) self.assertIs( data.fields[1], result.fields[1], ) self.assertIsNot( data.fields[2], result.fields[2], ) jid_field = result.fields[2] self.assertSequenceEqual( jid_field.values, ["foo@bar.baz"] ) self.assertEqual( jid_field.desc, "some description", ) self.assertIsNone( jid_field.label ) def test_render_reply_includes_unknown_field(self): data = forms_xso.Data(type_=forms_xso.DataType.FORM) data.fields.append( forms_xso.Field( var="jid", type_=forms_xso.FieldType.JID_SINGLE, values=[], desc="some description", ) ) data.fields.append( forms_xso.Field( var="foo", type_=forms_xso.FieldType.TEXT_SINGLE, values=[], ) ) class F(form.Form): jid = fields.JIDSingle( var="jid", label="Foobar" ) f = F.from_xso(data) f.jid.value = aioxmpp.JID.fromstr("foo@bar.baz") result = f.render_reply() self.assertIsInstance(result, forms_xso.Data) self.assertEqual( len(result.fields), 2 ) self.assertIs( data.fields[1], result.fields[1] ) self.assertIsNot( data.fields[0], result.fields[0], ) jid_field = result.fields[0] self.assertSequenceEqual( jid_field.values, ["foo@bar.baz"] ) self.assertEqual( jid_field.desc, "some description", ) self.assertIsNone( jid_field.label ) def test_render_reply_emits_FORM_TYPE(self): data = forms_xso.Data(type_=forms_xso.DataType.FORM) data.fields.append( forms_xso.Field( var="FORM_TYPE", type_=forms_xso.FieldType.HIDDEN, values=["some-uri"], ) ) data.fields.append( forms_xso.Field( type_=forms_xso.FieldType.FIXED, values=["This is some heading."], ) ) data.fields.append( forms_xso.Field( var="jid", type_=forms_xso.FieldType.JID_SINGLE, values=[], desc="some description", ) ) class F(form.Form): FORM_TYPE = "some-uri" jid = fields.JIDSingle( var="jid", label="Foobar" ) other = fields.TextSingle( var="foo", ) f = F.from_xso(data) f.jid.value = aioxmpp.JID.fromstr("foo@bar.baz") result = f.render_reply() self.assertIsInstance(result, forms_xso.Data) self.assertEqual( result.type_, forms_xso.DataType.SUBMIT, ) self.assertEqual( len(result.fields), 3 ) self.assertIs( data.fields[0], result.fields[0] ) self.assertIs( data.fields[1], result.fields[1], ) self.assertIsNot( data.fields[2], result.fields[2], ) jid_field = result.fields[2] self.assertSequenceEqual( jid_field.values, ["foo@bar.baz"] ) self.assertEqual( jid_field.desc, "some description", ) self.assertIsNone( jid_field.label ) self.assertEqual( data.get_form_type(), F.FORM_TYPE, ) def test_render_request(self): class F(form.Form): jid = fields.JIDSingle( var="jid", required=True, desc="Enter a valid JID here", label="Your JID", ) something_else = fields.TextSingle( var="other", label="Something else", ) f = F() f.jid.value = aioxmpp.JID.fromstr("foo@bar.baz") f.something_else.value = "some_text" data = f.render_request() self.assertIsInstance( data, forms_xso.Data, ) self.assertEqual( len(data.fields), 2 ) for field in data.fields: self.assertIsInstance( field, forms_xso.Field, ) jid_field = [field for field in data.fields if field.var == "jid"].pop() self.assertEqual( jid_field.type_, forms_xso.FieldType.JID_SINGLE, ) self.assertEqual( jid_field.label, "Your JID" ) self.assertEqual( jid_field.desc, "Enter a valid JID here", ) self.assertIs( jid_field.required, True ) self.assertSequenceEqual( jid_field.values, ["foo@bar.baz"], ) other_field = [field for field in data.fields if field.var == "other"].pop() self.assertEqual( other_field.type_, forms_xso.FieldType.TEXT_SINGLE, ) self.assertEqual( other_field.label, "Something else" ) self.assertIsNone( other_field.desc, ) self.assertIs( other_field.required, False, ) self.assertSequenceEqual( other_field.values, ["some_text"], ) def test_render_request_includes_FORM_TYPE(self): class F(form.Form): FORM_TYPE = "some-uri" jid = fields.JIDSingle( var="jid", required=True, desc="Enter a valid JID here", label="Your JID", ) something_else = fields.TextSingle( var="other", label="Something else", ) f = F() f.jid.value = aioxmpp.JID.fromstr("foo@bar.baz") f.something_else.value = "some_text" data = f.render_request() self.assertEqual( data.get_form_type(), f.FORM_TYPE, ) def test_render_request_with_layout(self): class F(form.Form): jid = fields.JIDSingle( var="jid", required=True, desc="Enter a valid JID here", label="Your JID", ) something_else = fields.TextSingle( var="other", label="Something else", ) LAYOUT = [ "Metadata", jid, "Captcha", something_else, ] f = F() f.jid.value = aioxmpp.JID.fromstr("foo@bar.baz") f.something_else.value = "some_text" data = f.render_request() self.assertIsInstance( data, forms_xso.Data, ) self.assertEqual( len(data.fields), 4 ) for field in data.fields: self.assertIsInstance( field, forms_xso.Field, ) text_field = data.fields[0] self.assertEqual( text_field.type_, forms_xso.FieldType.FIXED, ) self.assertIsNone(text_field.var) self.assertSequenceEqual( text_field.values, ["Metadata"] ) jid_field = data.fields[1] self.assertEqual( jid_field.type_, forms_xso.FieldType.JID_SINGLE, ) self.assertEqual( jid_field.label, "Your JID" ) self.assertEqual( jid_field.desc, "Enter a valid JID here", ) self.assertIs( jid_field.required, True ) self.assertSequenceEqual( jid_field.values, ["foo@bar.baz"], ) text_field = data.fields[2] self.assertEqual( text_field.type_, forms_xso.FieldType.FIXED, ) self.assertIsNone(text_field.var) self.assertSequenceEqual( text_field.values, ["Captcha"] ) other_field = data.fields[3] self.assertEqual( other_field.type_, forms_xso.FieldType.TEXT_SINGLE, ) self.assertEqual( other_field.label, "Something else" ) self.assertIsNone( other_field.desc, ) self.assertIs( other_field.required, False, ) self.assertSequenceEqual( other_field.values, ["some_text"], )
lgpl-3.0
jruncik/Reservito
SR.Core/Rights/RightsException.cs
216
using System; namespace SR.Core.Rights { [Serializable] public class RightsException : TvException { public RightsException(string message) : base(message) { } } }
lgpl-3.0
keepkey/python-keepkey
tests/test_msg_signtx.py
50611
# This file is part of the TREZOR project. # # Copyright (C) 2012-2016 Marek Palatinus <slush@satoshilabs.com> # Copyright (C) 2012-2016 Pavol Rusnak <stick@satoshilabs.com> # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see <http://www.gnu.org/licenses/>. # # The script has been modified for KeepKey Device. import unittest import common import binascii import itertools import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types from keepkeylib.client import CallException from keepkeylib import tx_api class TestMsgSigntx(common.KeepKeyTest): def test_one_one_fee(self): self.setup_mnemonic_nopin_nopassphrase() # tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882 # input 0: 0.0039 BTC inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e # amount=390000, prev_hash=binascii.unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'), prev_index=0, ) out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', amount=390000 - 10000, script_type=proto_types.PAYTOADDRESS, ) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) # Accepted by network: tx fd79435246dee76b2f159d2db08032d666c95adc544de64c8c49f474df4a7fee self.assertEqual(binascii.hexlify(serialized_tx), '010000000182488650ef25a58fef6788bd71b8212038d7f2bbe4750bc7bcb44701e85ef6d5000000006b4830450221009a0b7be0d4ed3146ee262b42202841834698bb3ee39c24e7437df208b8b7077102202b79ab1e7736219387dffe8d615bbdba87e11477104b867ef47afed1a5ede7810121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0160cc0500000000001976a914de9b2a8da088824e8fe51debea566617d851537888ac00000000') def test_testnet_one_two_fee(self): self.setup_mnemonic_nopin_nopassphrase() # tx: 6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54 # input 1: 10.00000000 BTC inp1 = proto_types.TxInputType(address_n=[0], # mirio8q3gtv7fhdnmb3TpZ4EuafdzSs7zL # amount=1000000000, prev_hash=binascii.unhexlify('6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54'), prev_index=1, ) out1 = proto_types.TxOutputType(address='mfiGQVPcRcaEvQPYDErR34DcCovtxYvUUV', amount=1000000000 - 500000000 - 10000000, script_type=proto_types.PAYTOADDRESS, ) out2 = proto_types.TxOutputType(address_n=[2], amount=500000000, script_type=proto_types.PAYTOADDRESS, ) with self.client: self.client.set_tx_api(tx_api.TxApiTestnet) self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_FeeOverThreshold), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1, ], [out1, out2]) self.assertEqual(binascii.hexlify(serialized_tx), '0100000001549d2977998f899a63c0a9da30dedb2841e33fef561097b05822eccbc7f3906f010000006b4830450221009c2d30385519fdb13dce13d5ac038be07d7b2dad0b0f7b2c1c339d7255bcf553022056a2f5bceab3cd0ffed4d388387e631f419d67ff9ce7798e3d7dfe6a6d6ec4bd0121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0280ce341d000000001976a9140223b1a09138753c9cb0baf95a0a62c82711567a88ac0065cd1d000000001976a9142db345c36563122e2fd0f5485fb7ea9bbf7cb5a288ac00000000') def test_testnet_fee_too_high(self): self.setup_mnemonic_nopin_nopassphrase() # tx: 6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54 # input 1: 10.00000000 BTC inp1 = proto_types.TxInputType(address_n=[0], # mirio8q3gtv7fhdnmb3TpZ4EuafdzSs7zL # amount=1000000000, prev_hash=binascii.unhexlify('6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54'), prev_index=1, ) out1 = proto_types.TxOutputType(address='mfiGQVPcRcaEvQPYDErR34DcCovtxYvUUV', amount=1000000000 - 500000000 - 100000000, script_type=proto_types.PAYTOADDRESS, ) out2 = proto_types.TxOutputType(address_n=[2], amount=500000000, script_type=proto_types.PAYTOADDRESS, ) with self.client: self.client.set_tx_api(tx_api.TxApiTestnet) self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("6f90f3c7cbec2258b0971056ef3fe34128dbde30daa9c0639a898f9977299d54"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_FeeOverThreshold), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1, ], [out1, out2]) self.assertEqual(binascii.hexlify(serialized_tx), '0100000001549d2977998f899a63c0a9da30dedb2841e33fef561097b05822eccbc7f3906f010000006a47304402205ea68e9d52d4be14420ccecf7f2e11489d49b86bedb79ee99b5e9b7188884150022056219cb3384a5df8048cca286a9533403dbda1571afd84b51379cdaee6a6dea80121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff020084d717000000001976a9140223b1a09138753c9cb0baf95a0a62c82711567a88ac0065cd1d000000001976a9142db345c36563122e2fd0f5485fb7ea9bbf7cb5a288ac00000000') def test_one_two_fee(self): self.setup_mnemonic_nopin_nopassphrase() # tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882 # input 0: 0.0039 BTC inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e # amount=390000, prev_hash=binascii.unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'), prev_index=0, ) out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', amount=390000 - 80000 - 10000, script_type=proto_types.PAYTOADDRESS, ) out2 = proto_types.TxOutputType(address_n=[1], amount=80000, script_type=proto_types.PAYTOADDRESS, ) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, out2]) self.assertEqual(binascii.hexlify(serialized_tx), '010000000182488650ef25a58fef6788bd71b8212038d7f2bbe4750bc7bcb44701e85ef6d5000000006b483045022100c1400d8485d3bdcae7413e123148f35ece84806fc387ab88c66b469df89aef1702201d481d04216b319dc549ffe2333143629ba18828a4e2d1783ab719a6aa263eb70121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff02e0930400000000001976a914de9b2a8da088824e8fe51debea566617d851537888ac80380100000000001976a9140223b1a09138753c9cb0baf95a0a62c82711567a88ac00000000') def test_one_three_fee(self): self.setup_mnemonic_nopin_nopassphrase() # tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882 # input 0: 0.0039 BTC inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e # amount=390000, prev_hash=binascii.unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'), prev_index=0, ) out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', amount=390000 - 80000 - 12000 - 10000, script_type=proto_types.PAYTOADDRESS, ) out2 = proto_types.TxOutputType(address='13uaUYn6XAooo88QvAqAVsiVvr2mAXutqP', amount=12000, script_type=proto_types.PAYTOADDRESS, ) out3 = proto_types.TxOutputType(address_n=[1], amount=80000, script_type=proto_types.PAYTOADDRESS, ) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=2)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=2)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=2)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, out2, out3]) self.assertEqual(binascii.hexlify(serialized_tx), '010000000182488650ef25a58fef6788bd71b8212038d7f2bbe4750bc7bcb44701e85ef6d5000000006b483045022100e695e2c530c7c0fc32e6b79b7cff56a7f70a8c9da787534f46b4204070f914fc02207b0879a81408a11e23b11d4c7965c62b5fc6d5c2d92340f5ee2da7b40e99314a0121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0300650400000000001976a914de9b2a8da088824e8fe51debea566617d851537888ace02e0000000000001976a9141fe1d337fb81afca42818051e12fd18245d1b17288ac80380100000000001976a9140223b1a09138753c9cb0baf95a0a62c82711567a88ac00000000') def test_two_two(self): self.setup_mnemonic_nopin_nopassphrase() # tx: c6be22d34946593bcad1d2b013e12f74159e69574ffea21581dad115572e031c # input 1: 0.0010 BTC # tx: 58497a7757224d1ff1941488d23087071103e5bf855f4c1c44e5c8d9d82ca46e # input 1: 0.0011 BTC inp1 = proto_types.TxInputType(address_n=[1], # 1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb # amount=100000, prev_hash=binascii.unhexlify('c6be22d34946593bcad1d2b013e12f74159e69574ffea21581dad115572e031c'), prev_index=1, ) inp2 = proto_types.TxInputType(address_n=[2], # 15AeAhtNJNKyowK8qPHwgpXkhsokzLtUpG # amount=110000, prev_hash=binascii.unhexlify('58497a7757224d1ff1941488d23087071103e5bf855f4c1c44e5c8d9d82ca46e'), prev_index=1, ) out1 = proto_types.TxOutputType(address='15Jvu3nZNP7u2ipw2533Q9VVgEu2Lu9F2B', amount=210000 - 100000 - 10000, script_type=proto_types.PAYTOADDRESS, ) out2 = proto_types.TxOutputType(address_n=[3], # 1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5 amount=100000, script_type=proto_types.PAYTOADDRESS, ) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("c6be22d34946593bcad1d2b013e12f74159e69574ffea21581dad115572e031c"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("c6be22d34946593bcad1d2b013e12f74159e69574ffea21581dad115572e031c"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("c6be22d34946593bcad1d2b013e12f74159e69574ffea21581dad115572e031c"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("c6be22d34946593bcad1d2b013e12f74159e69574ffea21581dad115572e031c"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("58497a7757224d1ff1941488d23087071103e5bf855f4c1c44e5c8d9d82ca46e"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("58497a7757224d1ff1941488d23087071103e5bf855f4c1c44e5c8d9d82ca46e"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("58497a7757224d1ff1941488d23087071103e5bf855f4c1c44e5c8d9d82ca46e"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("58497a7757224d1ff1941488d23087071103e5bf855f4c1c44e5c8d9d82ca46e"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, inp2], [out1, out2]) # Accepted by network: tx c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb self.assertEqual(binascii.hexlify(serialized_tx), '01000000021c032e5715d1da8115a2fe4f57699e15742fe113b0d2d1ca3b594649d322bec6010000006b483045022100f773c403b2f85a5c1d6c9c4ad69c43de66930fff4b1bc818eb257af98305546a0220443bde4be439f276a6ce793664b463580e210ec6c9255d68354449ac0443c76501210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a6ffffffff6ea42cd8d9c8e5441c4c5f85bfe50311078730d2881494f11f4d2257777a4958010000006b48304502210090cff1c1911e771605358a8cddd5ae94c7b60cc96e50275908d9bf9d6367c79f02202bfa72e10260a146abd59d0526e1335bacfbb2b4401780e9e3a7441b0480c8da0121038caebd6f753bbbd2bb1f3346a43cd32140648583673a31d62f2dfb56ad0ab9e3ffffffff02a0860100000000001976a9142f4490d5263906e4887ca2996b9e207af3e7824088aca0860100000000001976a914812c13d97f9159e54e326b481b8f88a73df8507a88ac00000000') """ def test_lots_of_inputs(self): self.setup_mnemonic_nopin_nopassphrase() # Tests if device implements serialization of len(inputs) correctly # tx 4a7b7e0403ae5607e473949cfa03f09f2cd8b0f404bf99ce10b7303d86280bf7 : 100 UTXO for spending for unittests inputs = [] for i in range(100): inputs.append( proto_types.TxInputType(address_n=[4], # 1NwN6UduuVkJi6sw3gSiKZaCY5rHgVXC2h prev_hash=binascii.unhexlify('4a7b7e0403ae5607e473949cfa03f09f2cd8b0f404bf99ce10b7303d86280bf7'), prev_index=i) ) out = proto_types.TxOutputType(address='19dvDdyxxptP9dGvozYe8BP6tgFV9L4jg5', amount=100 * 26000 - 15 * 10000, script_type=proto_types.PAYTOADDRESS) with self.client: (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', inputs, [out]) # Accepted by network: tx 23d9d8eecf3abf6c0f0f3f8b0976a04792d7f1c9a4ea9b0a8931734949e27c92 # too big put in unit test """ def test_lots_of_outputs(self): self.setup_mnemonic_nopin_nopassphrase() # Tests if device implements serialization of len(outputs) correctly # tx: c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb # index 1: 0.0010 BTC # tx: 39a29e954977662ab3879c66fb251ef753e0912223a83d1dcb009111d28265e5 # index 1: 0.0254 BTC inp1 = proto_types.TxInputType(address_n=[3], # 1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5 # amount=100000, prev_hash=binascii.unhexlify('c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb'), prev_index=1, ) inp2 = proto_types.TxInputType(address_n=[3], # 1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5 # amount=2540000, prev_hash=binascii.unhexlify('39a29e954977662ab3879c66fb251ef753e0912223a83d1dcb009111d28265e5'), prev_index=1, ) outputs = [] cnt = 255 for _ in range(cnt): out = proto_types.TxOutputType(address='1NwN6UduuVkJi6sw3gSiKZaCY5rHgVXC2h', amount=int((100000 + 2540000 - 39000) / cnt), script_type=proto_types.PAYTOADDRESS, ) outputs.append(out) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("39a29e954977662ab3879c66fb251ef753e0912223a83d1dcb009111d28265e5"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("39a29e954977662ab3879c66fb251ef753e0912223a83d1dcb009111d28265e5"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("39a29e954977662ab3879c66fb251ef753e0912223a83d1dcb009111d28265e5"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("39a29e954977662ab3879c66fb251ef753e0912223a83d1dcb009111d28265e5"))), ] + [ item for items in zip( [proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=I)) for I in range(cnt)], [proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput)] * cnt ) for item in items ] + [ proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1)), ] + [ proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=I)) for I in range(cnt) ] + [ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1)), ] + [ proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=I)) for I in range(cnt) ] + [ proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=I)) for I in range(cnt) ] + [ proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, inp2], outputs) if cnt == 255: self.assertEqual(binascii.hexlify(serialized_tx), '0100000002fb792f470a58993e14964c9bd46cdf37cb4bbc3f61540cb651580c82ed243ec6010000006b483045022100969da46f94a81f34f3717b014e0c3e1826eda1b0022ec2f9ce39f3d750ab9235022026da269770993211a1503413566a339bbb4389a482fffcf8e1f76713fc3b94f5012103477b9f0f34ae85434ce795f0c5e1e90c9420e5b5fad084d7cce9a487b94a7902ffffffffe56582d2119100cb1d3da8232291e053f71e25fb669c87b32a667749959ea239010000006a473044022052e1419bb237b9db400ab5e3df16db6355619d545fde9030924a360763ae9ad40220704beab04d72ecaeb42eca7d98faca7a0941e65f2e1341f183be2b83e6b09e1c012103477b9f0f34ae85434ce795f0c5e1e90c9420e5b5fad084d7cce9a487b94a7902fffffffffdff00' + 'd8270000000000001976a914f0a2b64e56ee2ff57126232f84af6e3a41d4055088ac' * cnt + '00000000') def test_fee_too_high(self): self.setup_mnemonic_nopin_nopassphrase() # tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882 # input 0: 0.0039 BTC inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e # amount=390000, prev_hash=binascii.unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'), prev_index=0, ) out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', amount=390000 - 250000, script_type=proto_types.PAYTOADDRESS, ) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_FeeOverThreshold), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) self.assertEqual(binascii.hexlify(serialized_tx), '010000000182488650ef25a58fef6788bd71b8212038d7f2bbe4750bc7bcb44701e85ef6d5000000006b483045022100a3b17b37de3bfecca47f0d49f7bb0d0f68d45df7defe45713d57e83731f5e3d902205404b14630cea6a88b23a5f7c3a1b88494757a8ca5e1c0b0b93cf3c38231c3bd0121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff01e0220200000000001976a914de9b2a8da088824e8fe51debea566617d851537888ac00000000') def test_not_enough_funds(self): self.setup_mnemonic_nopin_nopassphrase() # tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882 # input 0: 0.0039 BTC inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e # amount=390000, prev_hash=binascii.unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'), prev_index=0, ) out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', amount=400000, script_type=proto_types.PAYTOADDRESS, ) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.Failure(code=proto_types.Failure_NotEnoughFunds) ]) try: self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) except CallException as e: self.assertEqual(e.args[0], proto_types.Failure_NotEnoughFunds) else: self.assert_(False, "types.Failure_NotEnoughFunds expected") def test_p2sh(self): self.setup_mnemonic_nopin_nopassphrase() inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e # amount=400000, prev_hash=binascii.unhexlify('54aa5680dea781f45ebb536e53dffc526d68c0eb5c00547e323b2c32382dfba3'), prev_index=1, ) out1 = proto_types.TxOutputType(address='3DKGE1pvPpBAgZj94MbCinwmksewUNNYVR', # p2sh amount=400000 - 10000, script_type=proto_types.PAYTOSCRIPTHASH, ) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("54aa5680dea781f45ebb536e53dffc526d68c0eb5c00547e323b2c32382dfba3"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("54aa5680dea781f45ebb536e53dffc526d68c0eb5c00547e323b2c32382dfba3"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("54aa5680dea781f45ebb536e53dffc526d68c0eb5c00547e323b2c32382dfba3"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("54aa5680dea781f45ebb536e53dffc526d68c0eb5c00547e323b2c32382dfba3"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) # Accepted by network: tx 8cc1f4adf7224ce855cf535a5104594a0004cb3b640d6714fdb00b9128832dd5 self.assertEqual(binascii.hexlify(serialized_tx), '0100000001a3fb2d38322c3b327e54005cebc0686d52fcdf536e53bb5ef481a7de8056aa54010000006b4830450221009e020b0390ccad533b73b552f8a99a9d827212c558e4f755503674d07c92ad4502202d606f7316990e0461c51d4add25054f19c697aa3e3c2ced4d568f0b2c57e62f0121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0170f305000000000017a9147f844bdb0b8fd54b64e3d16c85dc1170f1ff97c18700000000') def test_attack_change_outputs(self): # This unit test attempts to modify data sent during ping-pong of streaming signing. # Because device is asking for human confirmation only during first pass (first input), # device must detect that data has been modified during other passes and fail to sign # such modified data (which has not been confirmed by the user). # Test firstly prepare normal transaction and send it to device. Then it send the same # transaction again, but change amount of output 1 during signing the second input. self.setup_mnemonic_nopin_nopassphrase() inp1 = proto_types.TxInputType(address_n=[1], # 1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb # amount=100000, prev_hash=binascii.unhexlify('c6be22d34946593bcad1d2b013e12f74159e69574ffea21581dad115572e031c'), prev_index=1, ) inp2 = proto_types.TxInputType(address_n=[2], # 15AeAhtNJNKyowK8qPHwgpXkhsokzLtUpG # amount=110000, prev_hash=binascii.unhexlify('58497a7757224d1ff1941488d23087071103e5bf855f4c1c44e5c8d9d82ca46e'), prev_index=1, ) out1 = proto_types.TxOutputType(address='15Jvu3nZNP7u2ipw2533Q9VVgEu2Lu9F2B', amount=210000 - 100000 - 10000, script_type=proto_types.PAYTOADDRESS, ) out2 = proto_types.TxOutputType(address_n=[3], # 1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5 amount=100000, script_type=proto_types.PAYTOADDRESS, ) global run_attack run_attack = False def attack_processor(req, msg): global run_attack if req.details.tx_hash != b'': return msg if req.details.request_index != 1: return msg if not run_attack: run_attack = True return msg msg.outputs[0].amount = 9999999 # Sign output with another amount return msg # Test if the transaction can be signed normally (_, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, inp2], [out1, out2]) # Accepted by network: tx c63e24ed820c5851b60c54613fbc4bcb37df6cd49b4c96143e99580a472f79fb self.assertEqual(binascii.hexlify(serialized_tx), '01000000021c032e5715d1da8115a2fe4f57699e15742fe113b0d2d1ca3b594649d322bec6010000006b483045022100f773c403b2f85a5c1d6c9c4ad69c43de66930fff4b1bc818eb257af98305546a0220443bde4be439f276a6ce793664b463580e210ec6c9255d68354449ac0443c76501210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a6ffffffff6ea42cd8d9c8e5441c4c5f85bfe50311078730d2881494f11f4d2257777a4958010000006b48304502210090cff1c1911e771605358a8cddd5ae94c7b60cc96e50275908d9bf9d6367c79f02202bfa72e10260a146abd59d0526e1335bacfbb2b4401780e9e3a7441b0480c8da0121038caebd6f753bbbd2bb1f3346a43cd32140648583673a31d62f2dfb56ad0ab9e3ffffffff02a0860100000000001976a9142f4490d5263906e4887ca2996b9e207af3e7824088aca0860100000000001976a914812c13d97f9159e54e326b481b8f88a73df8507a88ac00000000') # Now run the attack, must trigger the exception self.assertRaises(CallException, self.client.sign_tx, 'Bitcoin', [inp1, inp2], [out1, out2], debug_processor=attack_processor) def test_spend_coinbase(self): # 25 TEST generated to m/1 (mfiGQVPcRcaEvQPYDErR34DcCovtxYvUUV) # tx: d6da21677d7cca5f42fbc7631d062c9ae918a0254f7c6c22de8e8cb7fd5b8236 # input 0: 25.0027823 BTC self.setup_mnemonic_nopin_nopassphrase() inp1 = proto_types.TxInputType(address_n=[1], # mfiGQVPcRcaEvQPYDErR34DcCovtxYvUUV # amount=390000, prev_hash=binascii.unhexlify('d6da21677d7cca5f42fbc7631d062c9ae918a0254f7c6c22de8e8cb7fd5b8236'), prev_index=0, ) out1 = proto_types.TxOutputType(address='mm6FM31rM5Vc3sw5D7kztiBg3jHUzyqF1g', amount=2500278230 - 10000, script_type=proto_types.PAYTOADDRESS, ) with self.client: self.client.set_tx_api(tx_api.TxApiTestnet) self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("d6da21677d7cca5f42fbc7631d062c9ae918a0254f7c6c22de8e8cb7fd5b8236"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d6da21677d7cca5f42fbc7631d062c9ae918a0254f7c6c22de8e8cb7fd5b8236"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d6da21677d7cca5f42fbc7631d062c9ae918a0254f7c6c22de8e8cb7fd5b8236"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1, ], [out1, ]) # Accepted by network: tx self.assertEqual(binascii.hexlify(serialized_tx), '010000000136825bfdb78c8ede226c7c4f25a018e99a2c061d63c7fb425fca7c7d6721dad6000000006a473044022047845c366eb24f40be315c7815a154513c444c7989eb80f7ce7ff6aeb703d26a022007c1f5efadf67c5889634fd7ac39a7ce78bffac291673e8772ecd8389c901d9f01210338d78612e990f2eea0c426b5e48a8db70b9d7ed66282b3b26511e0b1c75515a6ffffffff01c6100795000000001976a9143d2496e67f5f57a924353da42d4725b318e7a8ea88ac00000000') if __name__ == '__main__': unittest.main()
lgpl-3.0
GeirGrusom/PlatformInvoker
Platform.Invoke/ILibraryProcProvider.cs
1290
using System; namespace Platform.Invoke { /// <summary> /// Provides an interface for library internal functionality. /// </summary> public interface ILibraryProcProvider { /// <summary> /// Frees the specified library. /// </summary> /// <param name="module">Operating system provided module handle.</param> /// <returns>True if the library was successfully freed, otherwise false.</returns> bool Free(IntPtr module); /// <summary> /// Gets a function pointer for the specified function in the specified module. /// </summary> /// <param name="module">Operating system provided module handle.</param> /// <param name="procName">Library function name</param> /// <returns>Function pointer or null if the function could not be located in the specfified module.</returns> IntPtr GetProc(IntPtr module, string procName); /// <summary> /// Creates a delegate for the specified function pointer. /// </summary> /// <param name="functionPointer"></param> /// <param name="delegateType"></param> /// <returns></returns> Delegate GetDelegateFromFunctionPointer(IntPtr functionPointer, Type delegateType); } }
lgpl-3.0
bdelespierre/php-axiom
libraries/axiom/axSession.class.php
2465
<?php /** * @brief Session class file * @file axSession.class.php */ /** * @brief Session Class * * @note By default any instance of this class will point to the same $_SESSION structure for practical purposes. * * @class axSession * @author Delespierre * @ingroup Core * @copyright Copyright 2010-2011, Benjamin Delespierre (http://bdelespierre.fr) * @license http://www.gnu.org/licenses/lgpl.html Lesser General Public Licence version 3 */ class axSession { /** * @brief axSession values * @property array $_session_parameters */ protected $_session_parameters; /** * @breif Construct a new session handler instance */ public function __construct ($name) { $this->name($name); if (!$this->id()) self::start(); $this->_session_parameters = & $_SESSION; } /** * @brief Get a session reference * @param string $key * @return mixed */ public function __get ($key) { return isset($this->_session_parameters[$key]) ? $this->_session_parameters[$key] : null; } /** * @brief Set any session reference * @param string $key * @param mixed $value * @return void */ public function __set ($key, $value) { $this->_session_parameters[$key] = $value; } /** * @brief Start the session * @static * @return boolean */ public static function start () { if (!self::started()) return session_start(); return false; } /** * @brief Destroy the session * @static * @return boolean */ public static function destroy () { return session_destroy(); } /** * @brief Get or set the session id * @static * @param string $id @optional @default{false} * @return string */ public static function id ($id = false) { return $id !== false ? session_id($id) : session_id(); } /** * @brief Get or set the session name * @static * @param string $name @optional @default{false} * @return string */ public static function name ($name = false) { return $name !== false ? session_name($name) : session_name(); } /** * @brief Tell if session is started * @static * @return boolean */ public static function started () { return self::id() !== ""; } }
lgpl-3.0
jmecosta/sonar
sonar-plugin-api/src/main/java/org/sonar/api/database/model/MeasureModel.java
12696
/* * Sonar, open source software quality management tool. * Copyright (C) 2008-2012 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar 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. * * Sonar 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 Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.api.database.model; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.database.DatabaseSession; import org.sonar.api.measures.Metric; import org.sonar.api.qualitymodel.Characteristic; import org.sonar.api.rules.RulePriority; import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * This class is the Hibernate model to store a measure in the DB */ @Entity @Table(name = "project_measures") public class MeasureModel implements Cloneable { public static final int TEXT_VALUE_LENGTH = 96; @Id @Column(name = "id") @GeneratedValue private Long id; @Column(name = "value", updatable = true, nullable = true, precision = 30, scale = 20) private Double value = 0.0; @Column(name = "text_value", updatable = true, nullable = true, length = TEXT_VALUE_LENGTH) private String textValue; @Column(name = "tendency", updatable = true, nullable = true) private Integer tendency; @Column(name = "metric_id", updatable = false, nullable = false) private Integer metricId; @Column(name = "snapshot_id", updatable = true, nullable = true) private Integer snapshotId; @Column(name = "project_id", updatable = true, nullable = true) private Integer projectId; @Column(name = "description", updatable = true, nullable = true, length = 4000) private String description; @Temporal(TemporalType.TIMESTAMP) @Column(name = "measure_date", updatable = true, nullable = true) private Date measureDate; @Column(name = "rule_id", updatable = true, nullable = true) private Integer ruleId; /** * @deprecated since 2.5 See http://jira.codehaus.org/browse/SONAR-2007 */ @Deprecated @Column(name = "rules_category_id", nullable = true) private Integer rulesCategoryId;//NOSONAR this field is kept for backward-compatiblity of API @Column(name = "rule_priority", updatable = false, nullable = true) @Enumerated(EnumType.ORDINAL) private RulePriority rulePriority; @Column(name = "alert_status", updatable = true, nullable = true, length = 5) private String alertStatus; @Column(name = "alert_text", updatable = true, nullable = true, length = 4000) private String alertText; @Column(name = "variation_value_1", updatable = true, nullable = true) private Double variationValue1; @Column(name = "variation_value_2", updatable = true, nullable = true) private Double variationValue2; @Column(name = "variation_value_3", updatable = true, nullable = true) private Double variationValue3; @Column(name = "variation_value_4", updatable = true, nullable = true) private Double variationValue4; @Column(name = "variation_value_5", updatable = true, nullable = true) private Double variationValue5; @Column(name = "url", updatable = true, nullable = true, length = 2000) private String url; @OneToMany(mappedBy = "measure", fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}) private List<MeasureData> measureData = new ArrayList<MeasureData>(); @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "characteristic_id") private Characteristic characteristic; @Column(name = "person_id", updatable = true, nullable = true) private Integer personId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** * Creates a measure based on a metric and a double value */ public MeasureModel(int metricId, Double val) { if (val.isNaN() || val.isInfinite()) { throw new IllegalArgumentException("Measure value is NaN. Metric=" + metricId); } this.metricId = metricId; this.value = val; } /** * Creates a measure based on a metric and an alert level */ public MeasureModel(int metricId, Metric.Level level) { this.metricId = metricId; if (level != null) { this.textValue = level.toString(); } } /** * Creates a measure based on a metric and a string value */ public MeasureModel(int metricId, String val) { this.metricId = metricId; setData(val); } /** * Creates an empty measure */ public MeasureModel() { } /** * @return the measure double value */ public Double getValue() { return value; } /** * @return the measure description */ public String getDescription() { return description; } /** * Sets the measure description */ public void setDescription(String description) { this.description = description; } /** * Sets the measure value * * @throws IllegalArgumentException in case value is not a valid double */ public MeasureModel setValue(Double value) { if (value != null && (value.isNaN() || value.isInfinite())) { throw new IllegalArgumentException(); } this.value = value; return this; } /** * @return the measure alert level */ public Metric.Level getLevelValue() { if (textValue != null) { return Metric.Level.valueOf(textValue); } return null; } /** * Use getData() instead */ public String getTextValue() { return textValue; } /** * Use setData() instead */ public void setTextValue(String textValue) { this.textValue = textValue; } /** * @return the measure tendency */ public Integer getTendency() { return tendency; } /** * @return whether the measure is about rule */ public boolean isRuleMeasure() { return ruleId != null || rulePriority != null; } /** * Sets the measure tendency * * @return the current object */ public MeasureModel setTendency(Integer tendency) { this.tendency = tendency; return this; } public Integer getMetricId() { return metricId; } public void setMetricId(Integer metricId) { this.metricId = metricId; } /** * @return the snapshot id the measure is attached to */ public Integer getSnapshotId() { return snapshotId; } /** * Sets the snapshot id * * @return the current object */ public MeasureModel setSnapshotId(Integer snapshotId) { this.snapshotId = snapshotId; return this; } public Integer getRuleId() { return ruleId; } /** * Sets the rule for the measure * * @return the current object */ public MeasureModel setRuleId(Integer ruleId) { this.ruleId = ruleId; return this; } /** * @return the rule priority */ public RulePriority getRulePriority() { return rulePriority; } /** * Sets the rule priority */ public void setRulePriority(RulePriority rulePriority) { this.rulePriority = rulePriority; } /** * @return the project id */ public Integer getProjectId() { return projectId; } /** * Sets the project id */ public void setProjectId(Integer projectId) { this.projectId = projectId; } /** * @return the date of the measure */ public Date getMeasureDate() { return measureDate; } /** * Sets the date for the measure * * @return the current object */ public MeasureModel setMeasureDate(Date measureDate) { this.measureDate = measureDate; return this; } /** * @return the alert status if there is one, null otherwise */ public Metric.Level getAlertStatus() { if (alertStatus == null) { return null; } return Metric.Level.valueOf(alertStatus); } /** * Sets the measure alert status * * @return the current object */ public MeasureModel setAlertStatus(Metric.Level level) { if (level != null) { this.alertStatus = level.toString(); } else { this.alertStatus = null; } return this; } /** * @return the measure data */ public String getData(Metric metric) { if (this.textValue != null) { return this.textValue; } if (metric.isDataType() && !measureData.isEmpty()) { return measureData.get(0).getText(); } return null; } /** * Sets the measure data */ public final void setData(String data) { if (data == null) { this.textValue = null; measureData.clear(); } else { if (data.length() > TEXT_VALUE_LENGTH) { measureData.clear(); measureData.add(new MeasureData(this, data)); } else { this.textValue = data; } } } /** * Use getData() instead */ public MeasureData getMeasureData() { if (!measureData.isEmpty()) { return measureData.get(0); } return null; } /** * Use setData() instead */ //@Deprecated public void setMeasureData(MeasureData data) { measureData.clear(); if (data != null) { this.measureData.add(data); } } /** * @return the text of the alert */ public String getAlertText() { return alertText; } /** * Sets the text for the alert */ public void setAlertText(String alertText) { this.alertText = alertText; } /** * @return the measure URL */ public String getUrl() { return url; } /** * Sets the measure URL */ public void setUrl(String url) { this.url = url; } @Override public String toString() { return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString(); } public Double getVariationValue1() { return variationValue1; } public void setVariationValue1(Double d) { this.variationValue1 = d; } public Double getVariationValue2() { return variationValue2; } public void setVariationValue2(Double d) { this.variationValue2 = d; } public Double getVariationValue3() { return variationValue3; } public void setVariationValue3(Double d) { this.variationValue3 = d; } public Double getVariationValue4() { return variationValue4; } public void setVariationValue4(Double d) { this.variationValue4 = d; } public Double getVariationValue5() { return variationValue5; } public void setVariationValue5(Double d) { this.variationValue5 = d; } /** * Saves the current object to database * * @return the current object */ public MeasureModel save(DatabaseSession session) { MeasureData data = getMeasureData(); setMeasureData(null); session.save(this); if (data != null) { data.setMeasure(session.getEntity(MeasureModel.class, getId())); data.setSnapshotId(snapshotId); session.save(data); setMeasureData(data); } return this; } public Characteristic getCharacteristic() { return characteristic; } public MeasureModel setCharacteristic(Characteristic c) { this.characteristic = c; return this; } public Integer getPersonId() { return personId; } public MeasureModel setPersonId(Integer i) { this.personId = i; return this; } @Override public Object clone() { MeasureModel clone = new MeasureModel(); clone.setMetricId(getMetricId()); clone.setDescription(getDescription()); clone.setTextValue(getTextValue()); clone.setAlertStatus(getAlertStatus()); clone.setAlertText(getAlertText()); clone.setTendency(getTendency()); clone.setVariationValue1(getVariationValue1()); clone.setVariationValue2(getVariationValue2()); clone.setVariationValue3(getVariationValue3()); clone.setVariationValue4(getVariationValue4()); clone.setVariationValue5(getVariationValue5()); clone.setValue(getValue()); clone.setRulePriority(getRulePriority()); clone.setRuleId(getRuleId()); clone.setSnapshotId(getSnapshotId()); clone.setMeasureDate(getMeasureDate()); clone.setUrl(getUrl()); clone.setCharacteristic(getCharacteristic()); clone.setPersonId(getPersonId()); return clone; } }
lgpl-3.0
OpenSoftwareSolutions/PDFReporter-Studio
net.sf.jasperreports/src/org/oss/pdfreporter/eclipse/compilers/jeval/NumberConstant.java
2818
/******************************************************************************* * Copyright (c) 2013 Open Software Solutions GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.html * * Contributors: * Open Software Solutions GmbH - initial API and implementation ******************************************************************************/ package org.oss.pdfreporter.eclipse.compilers.jeval; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.oss.pdfreporter.eclipse.compilers.AbstractExpressionElement; import org.oss.pdfreporter.eclipse.compilers.ExpressionEvaluationException; import org.oss.pdfreporter.eclipse.compilers.IExpressionElement; public class NumberConstant extends AbstractExpressionElement implements IExpressionElement{ private static String INTEGER_MATCH = "new java\\.lang\\.Integer\\(-?\\d+\\)"; private static String LONG_MATCH = "new java\\.lang\\.Long\\(-?\\d+\\)"; private static String SHORT_MATCH = "new java\\.lang\\.Short\\(-?\\d+\\)"; private static String NUMBER_MATCH = "new java\\.lang\\.Number\\(-?\\d+\\)"; private static String BYTE_MATCH = "new java\\.lang\\.Byte\\(-?\\d+\\)"; private static Pattern NUMBER_SPLIT = Pattern.compile("-?\\d+"); private final Number number; public static boolean isNumber(String text) { return text.matches(INTEGER_MATCH) || text.matches(LONG_MATCH) || text.matches(SHORT_MATCH) || text.matches(BYTE_MATCH) || text.matches(NUMBER_MATCH); } public static NumberConstant parseNumber(String s) throws ExpressionParseException { if (s.matches(INTEGER_MATCH)) { return new NumberConstant(Integer.valueOf(extract(NUMBER_SPLIT, s))); } else if (s.matches(LONG_MATCH)) { return new NumberConstant(Long.valueOf(extract(NUMBER_SPLIT, s))); } else if (s.matches(SHORT_MATCH)) { return new NumberConstant(Short.valueOf(extract(NUMBER_SPLIT, s))); } else if (s.matches(BYTE_MATCH)) { return new NumberConstant(Byte.valueOf(extract(NUMBER_SPLIT, s))); } else if (s.matches(NUMBER_MATCH)) { return new NumberConstant(Integer.valueOf(extract(NUMBER_SPLIT, s))); } throw new ExpressionParseException("Unsupported Numberconstant " + s); } private static String extract(Pattern p, String text) throws ExpressionParseException { Matcher m = p.matcher(text); if (m.find()) { return m.group(); } throw new ExpressionParseException("Pattern: " + p + " does not match: " + text); } public NumberConstant(Number number) { this.number = number; } @Override public Object getValue() throws ExpressionEvaluationException { return number; } }
lgpl-3.0
sjas/isabel
src/main/java/isabel/tool/validators/rules/SA00017Validator.java
983
package isabel.tool.validators.rules; import isabel.tool.helper.NodeHelper; import isabel.tool.impl.Standards; import isabel.tool.impl.ValidationCollector; import isabel.tool.imports.ProcessContainer; import nu.xom.Document; import nu.xom.Node; import nu.xom.Nodes; public class SA00017Validator extends Validator { public SA00017Validator(ProcessContainer files, ValidationCollector violationCollector) { super(files, violationCollector); } @Override public void validate() { Document document = fileHandler.getBpel().getDocument(); Nodes partnerLinks = document.query("//bpel:partnerLink", Standards.CONTEXT); for (Node partnerLink : partnerLinks) { NodeHelper partnerLinkHelper = new NodeHelper(partnerLink); if (partnerLinkHelper.hasAttribute("initializePartnerRole") && partnerLinkHelper.hasNoAttribute("partnerRole")) { addViolation(partnerLink); } } } @Override public int getSaNumber() { return 17; } }
lgpl-3.0
lbndev/sonarqube
server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/period/package-info.java
996
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.computation.task.projectanalysis.period; import javax.annotation.ParametersAreNonnullByDefault;
lgpl-3.0
MastekLtd/JBEAM
supporting_libraries/stg-birt/src/main/java/com/stgmastek/birt/report/rendering/types/impl/PDFRenderOptionGenerator.java
1420
/* * Copyright (c) 2014 Mastek Ltd. All rights reserved. * * This file is part of JBEAM. JBEAM 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. * * JBEAM 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 the specific language governing permissions and * limitations. * * You should have received a copy of the GNU Lesser General Public * License along with JBEAM. If not, see <http://www.gnu.org/licenses/>. */ package com.stgmastek.birt.report.rendering.types.impl; import org.eclipse.birt.report.engine.api.IPDFRenderOption; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.api.PDFRenderOption; import org.eclipse.birt.report.engine.api.RenderOption; import com.stgmastek.birt.report.rendering.types.IReportRenderOptionGenerator; public class PDFRenderOptionGenerator implements IReportRenderOptionGenerator { public IRenderOption getRenderOption() { RenderOption renderOption = new PDFRenderOption(); renderOption.setOption(IPDFRenderOption.PDF_TEXT_WRAPPING, true); renderOption.setOutputFormat(IRenderOption.OUTPUT_FORMAT_PDF); return renderOption; } }
lgpl-3.0
pombredanne/quirinus
src/quirinus/codecs/lookup.cpp
12059
/** * @author Dmitry Selyutin * @copyright GNU General Public License v3.0+ */ #include <quirinus/core.hpp> #include <quirinus/codecs.hpp> #include "tables.cpp" namespace quirinus { namespace codecs { Codec* lookup(const Bytes& encoding) { // ASCII if ((encoding == "ASCII") || (encoding == "iso-ir-6") || (encoding == "ANSI_X3.4-1968") || (encoding == "ANSI_X3.4-1986") || (encoding == "ISO_646.irv:1991") || (encoding == "ISO646-US") || (encoding == "US-ASCII") || (encoding == "csASCII") || (encoding == "IBM367") || (encoding == "CP367")) return new Codec_ASCII; // UTF-8 else if ((encoding == "UTF-8") || (encoding == "UTF8") || (encoding == "CP65001")) return new Codec_UTF8; // UTF-16 else if ((encoding == "UTF-16") || (encoding == "UTF-16BE") || (encoding == "UTF-16LE") || (encoding == "UTF16") || (encoding == "UTF16BE") || (encoding == "UTF16LE") || (encoding == "CP1200") || (encoding == "CP1201")) return new Codec_UTF16; // UTF-32 else if ((encoding == "UTF-32") || (encoding == "UTF-32BE") || (encoding == "UTF-32LE") || (encoding == "UTF32BE") || (encoding == "UTF32LE") || (encoding == "CP12000") || (encoding == "CP12001")) return new Codec_UTF32; // ISO 8859-1 else if ((encoding == "iso-ir-100") || (encoding == "ISO_8859-1") || (encoding == "ISO-8859-1") || (encoding == "CP28591") || (encoding == "csISOLatin1") || (encoding == "IBM819") || (encoding == "CP819") || (encoding == "latin1") || (encoding == "l1")) return new Codec("ISO-8859-1", 28591, codecs::TABLE_ISO_8859_1); // ISO 8859-2 else if ((encoding == "iso-ir-101") || (encoding == "ISO_8859-2") || (encoding == "ISO-8859-2") || (encoding == "CP28592") || (encoding == "csISOLatin2") || (encoding == "latin2") || (encoding == "l2")) return new Codec("ISO-8859-2", 28592, codecs::TABLE_ISO_8859_2); // ISO 8859-3 else if ((encoding == "iso-ir-109") || (encoding == "ISO_8859-3") || (encoding == "ISO-8859-3") || (encoding == "CP28593") || (encoding == "csISOLatin3") || (encoding == "latin3") || (encoding == "l3")) return new Codec("ISO-8859-3", 28593, codecs::TABLE_ISO_8859_3); // ISO 8859-4 else if ((encoding == "iso-ir-110") || (encoding == "ISO_8859-4") || (encoding == "ISO-8859-4") || (encoding == "CP28594") || (encoding == "csISOLatin4") || (encoding == "latin4") || (encoding == "l4")) return new Codec("ISO-8859-4", 28594, codecs::TABLE_ISO_8859_4); // ISO 8859-5 else if ((encoding == "iso-ir-144") || (encoding == "ISO_8859-5") || (encoding == "ISO-8859-5") || (encoding == "CP28595") || (encoding == "csISOLatinCyrillic") || (encoding == "cyrillic")) return new Codec("ISO-8859-5", 28595, codecs::TABLE_ISO_8859_5); // ISO 8859-6 else if ((encoding == "iso-ir-127") || (encoding == "ISO_8859-6") || (encoding == "ISO-8859-6") || (encoding == "CP28596") || (encoding == "csISOLatinArabic") || (encoding == "arabic") || (encoding == "ECMA-114") || (encoding == "ASMO-708")) return new Codec("ISO-8859-6", 28596, codecs::TABLE_ISO_8859_6); // ISO 8859-7 else if ((encoding == "iso-ir-126") || (encoding == "ISO_8859-7") || (encoding == "ISO-8859-7") || (encoding == "CP28597") || (encoding == "csISOLatinGreek") || (encoding == "greek") || (encoding == "greek8") || (encoding == "ECMA-118") || (encoding == "ELOT_928")) return new Codec("ISO-8859-7", 28597, codecs::TABLE_ISO_8859_7); // ISO 8859-8 else if ((encoding == "iso-ir-138") || (encoding == "ISO_8859-8") || (encoding == "ISO-8859-8") || (encoding == "CP28598") || (encoding == "csISOLatinHebrew") || (encoding == "hebrew")) return new Codec("ISO-8859-8", 28598, codecs::TABLE_ISO_8859_8); // ISO 8859-9 else if ((encoding == "iso-ir-148") || (encoding == "ISO_8859-9") || (encoding == "ISO-8859-9") || (encoding == "CP28599") || (encoding == "csISOLatinLatin5") || (encoding == "latin5") || (encoding == "l5")) return new Codec("ISO-8859-9", 28599, codecs::TABLE_ISO_8859_9); // ISO 8859-10 else if ((encoding == "iso-ir-157") || (encoding == "ISO_8859-10") || (encoding == "ISO-8859-10") || (encoding == "csISOLatinLatin6") || (encoding == "latin6") || (encoding == "l6")) return new Codec("ISO-8859-10", 28600, codecs::TABLE_ISO_8859_10); // ISO 8859-11 else if ((encoding == "csTIS620") || (encoding == "ISO_8859-11") || (encoding == "ISO-8859-11")) return new Codec("ISO-8859-11", 28601, codecs::TABLE_ISO_8859_11); // ISO 8859-13 else if ((encoding == "csISO885913") || (encoding == "ISO_8859-13") || (encoding == "ISO-8859-13") || (encoding == "CP28603")) return new Codec("ISO-8859-13", 28603, codecs::TABLE_ISO_8859_13); // ISO 8859-14 else if ((encoding == "iso-ir-199") || (encoding == "ISO_8859-14") || (encoding == "ISO-8859-14") || (encoding == "csISO885914") || (encoding == "iso-celtic") || (encoding == "latin8") || (encoding == "l8")) return new Codec("ISO-8859-14", 28604, codecs::TABLE_ISO_8859_14); // ISO 8859-15 else if ((encoding == "csISO885915") || (encoding == "ISO_8859-15") || (encoding == "ISO-8859-15") || (encoding == "CP28605") || (encoding == "latin9") || (encoding == "l9")) return new Codec("ISO-8859-15", 28605, codecs::TABLE_ISO_8859_15); // ISO 8859-16 else if ((encoding == "iso-ir-226") || (encoding == "ISO_8859-16") || (encoding == "ISO-8859-16") || (encoding == "csISO885916") || (encoding == "latin10") || (encoding == "l10")) return new Codec("ISO-8859-16", 28606, codecs::TABLE_ISO_8859_16); // CP037 else if ((encoding == "CP037") || (encoding == "IBM037") || (encoding == "ebcdic-cp-us") || (encoding == "ebcdic-cp-ca") || (encoding == "ebcdic-cp-wt") || (encoding == "ebcdic-cp-nl") || (encoding == "csIBM037")) return new Codec("CP037", 37, codecs::TABLE_CP037); // CP437 else if ((encoding == "CP437") || (encoding == "IBM437") || (encoding == "csPC8CodePage437")) return new Codec("CP437", 437, codecs::TABLE_CP437); // CP500 else if ((encoding == "CP500") || (encoding == "IBM500") || (encoding == "ebcdic-500") || (encoding == "ebcdic-cp-be") || (encoding == "ebcdic-cp-ch") || (encoding == "csIBM500")) return new Codec("CP500", 500, codecs::TABLE_CP500); // CP737 else if (encoding == "CP737") return new Codec("CP737", 737, codecs::TABLE_CP737); // CP775 else if ((encoding == "CP775") || (encoding == "IBM775") || (encoding == "csPC775Baltic")) return new Codec("CP775", 775, codecs::TABLE_CP775); // CP775 else if ((encoding == "CP775") || (encoding == "IBM775") || (encoding == "csPC775Baltic")) return new Codec("CP775", 775, codecs::TABLE_CP775); // CP850 else if ((encoding == "CP850") || (encoding == "IBM850") || (encoding == "csPC850Multilingual")) return new Codec("CP850", 850, codecs::TABLE_CP850); // CP852 else if ((encoding == "CP852") || (encoding == "IBM852") || (encoding == "csPCp852")) return new Codec("CP852", 852, codecs::TABLE_CP852); // CP855 else if ((encoding == "CP855") || (encoding == "IBM855") || (encoding == "csIBM855")) return new Codec("CP855", 855, codecs::TABLE_CP855); // CP857 else if ((encoding == "CP857") || (encoding == "IBM857") || (encoding == "csIBM857")) return new Codec("CP857", 857, codecs::TABLE_CP857); // CP860 else if ((encoding == "CP860") || (encoding == "IBM860") || (encoding == "csIBM860")) return new Codec("CP860", 860, codecs::TABLE_CP860); // CP861 else if ((encoding == "CP860") || (encoding == "IBM860") || (encoding == "cp-is") || (encoding == "csIBM860")) return new Codec("CP861", 861, codecs::TABLE_CP861); // CP862 else if ((encoding == "CP862") || (encoding == "IBM862") || (encoding == "csPC862LatinHebrew")) return new Codec("CP862", 862, codecs::TABLE_CP862); // CP863 else if ((encoding == "CP863") || (encoding == "IBM863") || (encoding == "csIBM863")) return new Codec("CP863", 863, codecs::TABLE_CP863); // CP864 else if ((encoding == "CP864") || (encoding == "IBM864") || (encoding == "csIBM864")) return new Codec("CP864", 864, codecs::TABLE_CP864); // CP866 else if ((encoding == "CP866") || (encoding == "IBM866") || (encoding == "csIBM866")) return new Codec("CP866", 866, codecs::TABLE_CP866); // CP869 else if ((encoding == "CP869") || (encoding == "IBM869") || (encoding == "cp-gr") || (encoding == "csIBM869")) return new Codec("CP869", 869, codecs::TABLE_CP869); // CP874 else if ((encoding == "CP874") || (encoding == "windows-874") || (encoding == "cswindows874")) return new Codec("CP874", 874, codecs::TABLE_CP874); // CP875 else if ((encoding == "CP875") || (encoding == "IBM875") || (encoding == "ebcdic-875") || (encoding == "csIBM875")) return new Codec("CP875", 875, codecs::TABLE_CP875); // CP1026 else if ((encoding == "CP1026") || (encoding == "IBM1026") || (encoding == "csIBM1026")) return new Codec("CP1026", 1026, codecs::TABLE_CP1026); // CP1250 else if ((encoding == "CP1250") || (encoding == "windows-1250") || (encoding == "cswindows1250")) return new Codec("CP1250", 1250, codecs::TABLE_CP1250); // CP1251 else if ((encoding == "CP1251") || (encoding == "windows-1251") || (encoding == "cswindows1251")) return new Codec("CP1251", 1251, codecs::TABLE_CP1251); // CP1252 else if ((encoding == "CP1252") || (encoding == "windows-1252") || (encoding == "cswindows1252")) return new Codec("CP1252", 1252, codecs::TABLE_CP1252); // CP1253 else if ((encoding == "CP1253") || (encoding == "windows-1253") || (encoding == "cswindows1253")) return new Codec("CP1253", 1253, codecs::TABLE_CP1253); // CP1254 else if ((encoding == "CP1254") || (encoding == "windows-1254") || (encoding == "cswindows1254")) return new Codec("CP1254", 1254, codecs::TABLE_CP1254); // CP1255 else if ((encoding == "CP1255") || (encoding == "windows-1255") || (encoding == "cswindows1255")) return new Codec("CP1255", 1255, codecs::TABLE_CP1255); // CP1256 else if ((encoding == "CP1256") || (encoding == "windows-1256") || (encoding == "cswindows1256")) return new Codec("CP1256", 1256, codecs::TABLE_CP1256); // CP1257 else if ((encoding == "CP1257") || (encoding == "windows-1257") || (encoding == "cswindows1257")) return new Codec("CP1257", 1257, codecs::TABLE_CP1257); // CP1258 else if ((encoding == "CP1258") || (encoding == "windows-1258") || (encoding == "cswindows1258")) return new Codec("CP1258", 1258, codecs::TABLE_CP1258); // Other std::ostringstream sstream; sstream << "cannot find encoding: " << '"' << encoding << '"'; throw LookupError(sstream.str().c_str()); } } // namespace codecs } // namespace quirinus
lgpl-3.0
alessandroleite/dohko
overlay/src/main/java/br/cic/unb/chord/util/WaitingThread.java
1537
/** * Copyright (C) 2013-2014 the original author or 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, * 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 br.cic.unb.chord.util; public class WaitingThread { private boolean hasBeenWokenUp = false; private Thread thread; public WaitingThread(Thread thread) { this.thread = thread; } /** * Returns <code>true</code> when the thread has been woken up by invoking {@link #wakeUp()} * * @return */ public boolean hasBeenWokenUp() { return this.hasBeenWokenUp; } /** * Wake up the thread that is waiting for a response. */ public void wakeUp() { this.hasBeenWokenUp = true; this.thread.interrupt(); } public String toString() { return this.thread.toString() + ": Waiting? " + !this.hasBeenWokenUp(); } }
lgpl-3.0
Sinhika/akkamaddiAdditions2
src/main/java/akkamaddi/plugins/goldenglitter/Settings.java
1328
package akkamaddi.plugins.goldenglitter; import java.io.File; import alexndr.api.config.Configuration; import alexndr.api.logger.LogHelper; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; public class Settings { private static Configuration settings = new Configuration(); public static void createOrLoadSettings(FMLPreInitializationEvent event) { settings.setModName(ModInfo.NAME); File configDir = new File(event.getModConfigurationDirectory(), "akkamaddi"); File settingsFile = new File(configDir, ModInfo.ID + ".xml" ); settings.setFile(settingsFile); try { LogHelper.verbose(ModInfo.ID, "Loading Settings..."); settings.load(); settings.createHelpEntry("https://minecraft.curseforge.com/projects/akkamaddis-additions"); //Blocks //Items //Tools //Armor } catch(Exception e) { LogHelper.severe(ModInfo.ID, "Failed to load settings"); e.printStackTrace(); } finally { settings.save(); LogHelper.verbose(ModInfo.ID, "Settings loaded successfully"); } } // end createOrLoadSettings() // TODO - public static config vars here } // end class
lgpl-3.0
YorkJong/pyResourceLink
reslnk/reslnk.py
12336
# -*- coding: utf-8 -*- """ The main goal of ResLnk (Resource Link) is to link resource files into single one (link command). It provides map command to generate resource map file in C array style, id command to generate a C header file of resource ID enumeration. """ __software__ = "Resource Link" __version__ = "1.15" __author__ = "Jiang Yu-Kuan <yukuan.jiang@gmail.com>" __date__ = "2013/02/26 (initial version) ~ 2019/04/17 (last revision)" import os import sys import re import argparse from myutil import save_utf8_file, is_numeric from myutil import prefix_info, wrap_header_guard, c_identifier #----------------------------------------------------------------------------- # File Read #----------------------------------------------------------------------------- def read_lst_file(fn): """Read a resource map file and return statement list. """ def del_nonuse(lines): lines = (x.split("#", 1)[0].strip() for x in lines) return [x for x in lines if len(x) > 0] with open(fn) as f: lines = del_nonuse(f.read().splitlines()) kind_cmd_pattern = re.compile(r':\s*kind\s*=') for line in lines: if not line.startswith(':'): # check filename continue if kind_cmd_pattern.match(line): # check :kind command continue if is_numeric(line[1:]): # check :offset continue raise ValueError('syntax error -> %s' % line) return lines #----------------------------------------------------------------------------- # Misc #----------------------------------------------------------------------------- def prefix_authorship(lines, comment_mark='//'): """Prefix authorship infomation to the given lines with given comment-mark. """ return prefix_info(lines, __software__, __version__, __author__, comment_mark) def res_id_from_filename(fn): """Return resource ID from filename. """ base = os.path.basename(fn) base_main, base_ext = os.path.splitext(base) return 'RES_%s_%s' % (c_identifier(base_ext[1:]).upper(), c_identifier(base_main.replace('_', ' '))) def map_from_statements(statements, res_dir='res', align_bytes=1): """Return (offset, size, filename) tuples from statements. """ assert align_bytes >= 1 tuples = [] offset = 0 for sta in statements: if sta.startswith(':'): if not is_numeric(sta[1:]): continue val = eval(sta[1:]) if val < offset: raise ValueError('offset too small -> %s' % sta) offset = val else: fn = '{path}/{name}'.format(path=res_dir, name=sta) fsize = os.path.getsize(fn) tuples += [(offset, fsize, sta)] offset += fsize offset = (offset + align_bytes - 1) / align_bytes * align_bytes return tuples #----------------------------------------------------------------------------- # Action Functions #----------------------------------------------------------------------------- def link(statements, res_dir='res', outfile='res.bin', align_bytes=1, padding_hex=0xFF): """Link resources into single file. """ assert padding_hex <= 0xFF assert align_bytes >= 1 begins, sizes, fns = zip( *map_from_statements(statements, res_dir, align_bytes)) ends = list(begins[1:]) + [begins[-1] + sizes[-1]] spaces = [end - begin for begin, end in zip(begins, ends)] with open(outfile, 'wb') as outfile: for space, fn in zip(spaces, fns): fn = '{path}/{name}'.format(path=res_dir, name=fn) with open(fn, 'rb') as infile: raw = infile.read() padding = chr(padding_hex) * (space - len(raw)) outfile.write(raw + padding) def gen_map_ifile(statements, res_dir='res', outfile='ResMap.i', align_bytes=1): """Generate a C included file that lists map of resources. """ assert align_bytes >= 1 lines = [''] lines += ['// %8s, %8s (in bytes)' % ('offset', 'size')] lines += ['{ %8d, %8d}, // %s (%s)' % (offset, size, res_id_from_filename(fn), fn) for offset, size, fn in map_from_statements(statements, res_dir, align_bytes)] lines += [''] lines = prefix_authorship(lines) save_utf8_file(outfile, lines) def gen_map_binfile(statements, res_dir='res', outfile='ResMap.bin', align_bytes=1): """Generate a binary map file of resources. """ def str_from_val(x): """"Return char-string from a two-byte value (high byte first).""" return (chr((x >> 24) & 0xff) + chr((x >> 16) & 0xff) + chr((x >> 8) & 0xff) + chr(x & 0xff)) assert align_bytes >= 1 lines = [] for offset, size, _fn in map_from_statements(statements, res_dir, align_bytes): lines += [str_from_val(offset), str_from_val(size)] bytes = 'ResMapTb' + ''.join(lines) with open(outfile, 'wb') as f: f.write(bytes) def gen_id_hfile(statements, h_fn='ResID.h'): """Generate a C header file of resource ID enumeration. """ def group_filenames(statements): def is_kept(sta): if sta.strip() == '': return False if not sta.startswith(':'): return True if re.match(r':\s*kind\s*=', sta): return True return False def delete_space_lines(lines): return (line for line in lines if line != '') statements = [sta for sta in statements if is_kept(sta)] statements += [''] # for last empty kind statement lines = '\n'.join(statements) kinds = re.findall(r':\s*kind\s*=\s*(.*)\s*\n', lines) fns_lst = re.split(r':\s*kind\s*=.*\n', lines) if statements[0].startswith(':'): fns_lst = fns_lst[1:] else: kinds = [''] + kinds fns_lst = (delete_space_lines(lines.split('\n')) for lines in fns_lst) return zip(kinds, fns_lst) def lines_from_fns(kind, fns, id_end): ids = [res_id_from_filename(fn) for fn in fns] id_begin = res_id_from_filename('BEGIN.' + kind) lines = [] if id_end == '': lines += [' %s,' % id_begin] else: lines += [' %s = %s,' % (id_begin, id_end)] id_end = res_id_from_filename('END.' + kind) if ids: lines += [' %s = %s,' % (ids[0], id_begin)] lines += [' %s,' % id for id in ids[1:]] lines += [' %s,' % id_end] else: lines += [' %s = %s,' % (id_end, id_begin)] lines += [''] return lines, id_end lines = ['/** IDs of Resources */'] lines += ["typedef enum {"] id_end = '' for kind, fns in group_filenames(statements): tmp_lines, id_end = lines_from_fns(kind, fns, id_end) lines += tmp_lines lines += [' RES_End = %s,' % id_end] lines += [' RES_Total = RES_End'] lines += ['} ResID;'] lines = wrap_header_guard(lines, h_fn) lines = prefix_authorship(lines, comment_mark='//') save_utf8_file(h_fn, lines) #----------------------------------------------------------------------------- # Command Line Interface #----------------------------------------------------------------------------- def parse_args(args): def do_link(args): link(args.statements, args.dir, args.outfile, args.align, args.padding) def do_map(args): gen_map_ifile(args.statements, args.dir, args.outfile, args.align) def do_bmap(args): gen_map_binfile(args.statements, args.dir, args.outfile, args.align) def do_id(args): gen_id_hfile(args.statements, args.outfile) def hex_check(value): value = int(eval(value)) assert value < 256 return value # create top-level parser parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--version', action='version', version='%s v%s by %s' % (__software__, __version__, __author__)) subparsers = parser.add_subparsers(help='commands') #-------------------------------------------------------------------------- # create the parent parser of resource map file src = argparse.ArgumentParser(add_help=False) src.add_argument('statements', metavar='lst-file', type=read_lst_file, help='The list file of resources.') # create the parent parser of resource directory dir = argparse.ArgumentParser(add_help=False) dir.set_defaults(dir='.') dir.add_argument('-d', '--dir', metavar='<directory>', help="""assign the <directory> to read resource files. The default directory is "%s". """ % dir.get_default('dir')) # create the parent parser of align bytes aln = argparse.ArgumentParser(add_help=False) aln.set_defaults(align=1) aln.add_argument('-a', '--align', metavar='<number>', type=int, choices=(1, 2, 4, 8, 16, 32, 64, 128, 256), help="""specify the <number> of alignment bytes (default "%d"). """ % aln.get_default('align')) # create the parser for the "link" command sub = subparsers.add_parser('link', parents=[src, dir, aln], help='link resource files into single one.') sub.set_defaults(func=do_link, outfile='res.bin', padding=0xFF) sub.add_argument('-p', '--padding', metavar='<char hex>', type=hex_check, help='''specify the padding hex value of a char (default "0x%X"). ''' % sub.get_default('padding')) sub.add_argument('-o', '--output', metavar='<file>', dest='outfile', help='''place the output into <file>, the file after linking (default "%s"). ''' % sub.get_default('outfile')) # create the parser for the "map" command sub = subparsers.add_parser('map', parents=[src, dir, aln], help='generate a resource map file in format of C array.') sub.set_defaults(func=do_map, outfile='ResMap.i') sub.add_argument('-o', '--output', metavar='<file>', dest='outfile', help='''place the output into <file>, the C included file listing the offset, size pairs (default "%s"). ''' % sub.get_default('outfile')) # create the parser for the "bmap" command sub = subparsers.add_parser('bmap', parents=[src, dir, aln], help='generate a resource map file in binary format.') sub.set_defaults(func=do_bmap, outfile='ResMap.bin') sub.add_argument('-o', '--output', metavar='<file>', dest='outfile', help='''place the output into <file>, the binary version of resource map file listing the offset, size pairs (default "%s"). ''' % sub.get_default('outfile')) # create the parser for the "id" command sub = subparsers.add_parser('id', parents=[src], help='generate a C header file of resource ID enumeration.') sub.set_defaults(func=do_id, outfile='ResID.h') sub.add_argument('-o', '--output', metavar='<file>', dest='outfile', help='''place the output into <file>, the C header file of resource ID enumeration (default "%s"). ''' % sub.get_default('outfile')) #-------------------------------------------------------------------------- # parse args and execute functions args = parser.parse_args(args) args.func(args) def main(): """Start point of this module. """ try: parse_args(sys.argv[1:]) except IOError as err: print err except ValueError as err: print err except KeyError as key: print 'KeyError:', key if __name__ == '__main__': main() #parse_args(sys.argv[1:])
lgpl-3.0
DevMonks/dwarf
library/Dwarf/Net/Socket.php
828
<?php namespace Dwarf\Net; class Socket extends \Dwarf\Stream { protected $endPoint; protected $timeOut = 3; public function __construct( $host, $port = null, $timeOut = null ) { if( $host instanceof EndPoint ) $this->endPoint = $host; else $this->endPoint = new EndPoint( $host, $port ); if( $timeOut ) $this->timeOut = $timeOut; } public function getEndPoint() { return $this->endPoint; } public function open() { $code = null; $msg = null; parent::__construct( fsockopen( $this->endPoint->getHost(), $this->endPoint->getPort(), $code, $msg, $this->timeOut ) ); } }
lgpl-3.0
pubs/pubs
pubs/databroker.py
4150
from __future__ import unicode_literals from . import filebroker from . import endecoder from .p3 import pickle from . import __version__ class DataBroker(object): """ DataBroker class This is aimed at being a simple, high level interface to the content stored on disk. Requests are optimistically made, and exceptions are raised if something goes wrong. """ def __init__(self, pubsdir, docsdir, create=False): self.filebroker = filebroker.FileBroker(pubsdir, create=create) self.endecoder = endecoder.EnDecoder() self.docbroker = filebroker.DocBroker(docsdir, scheme='docsdir', subdir='') self.notebroker = filebroker.DocBroker(pubsdir, scheme='notesdir', subdir='notes') # cache def close(self): pass def pull_cache(self, name): """Load cache data from disk. Exceptions are handled by the caller.""" data_raw = self.filebroker.pull_cachefile(name) cache = pickle.loads(data_raw) if cache['version'] != __version__: raise ValueError('Cache not matching code version.') return cache['data'] def push_cache(self, name, data): cache_content = {'version': __version__, 'data': data} data_raw = pickle.dumps(cache_content) self.filebroker.push_cachefile(name, data_raw) # filebroker+endecoder def pull_metadata(self, citekey): metadata_raw = self.filebroker.pull_metafile(citekey) return self.endecoder.decode_metadata(metadata_raw) def pull_bibentry(self, citekey): bibdata_raw = self.filebroker.pull_bibfile(citekey) try: return self.endecoder.decode_bibdata(bibdata_raw) except self.endecoder.BibDecodingError as e: # QUESTION: do we really want to obscure a more precise error message here? e.args = "Unable to decode bibtex for paper {}.".format(citekey) raise e def push_metadata(self, citekey, metadata): metadata_raw = self.endecoder.encode_metadata(metadata) self.filebroker.push_metafile(citekey, metadata_raw) def push_bibentry(self, citekey, bibdata): bibdata_raw = self.endecoder.encode_bibdata(bibdata) self.filebroker.push_bibfile(citekey, bibdata_raw) def push(self, citekey, metadata, bibdata): self.filebroker.push(citekey, metadata, bibdata) def remove(self, citekey): self.filebroker.remove(citekey) def exists(self, citekey, meta_check=False): """ Checks wether the bibtex of a citekey exists. :param meta_check: if True, will return if both the bibtex and the meta file exists. """ return self.filebroker.exists(citekey, meta_check=meta_check) def citekeys(self): listings = self.listing(filestats=False) return set(listings['bibfiles']) def listing(self, filestats=True): return self.filebroker.listing(filestats=filestats) # docbroker def in_docsdir(self, docpath): return self.docbroker.in_docsdir(docpath) def real_docpath(self, docpath): return self.docbroker.real_docpath(docpath) def add_doc(self, citekey, source_path, overwrite=False): return self.docbroker.add_doc(citekey, source_path, overwrite=overwrite) def remove_doc(self, docpath, silent=True): return self.docbroker.remove_doc(docpath, silent=silent) def rename_doc(self, docpath, new_citekey): return self.docbroker.rename_doc(docpath, new_citekey) # notesbroker def _notepath(self, citekey, extension): return 'notesdir://{}.{}'.format(citekey, extension) def real_notepath(self, citekey, extension): return self.notebroker.real_docpath(self._notepath(citekey, extension)) def remove_note(self, citekey, extension, silent=True): return self.notebroker.remove_doc(self._notepath(citekey, extension), silent=silent) def rename_note(self, old_citekey, new_citekey, extension): return self.notebroker.rename_doc( self._notepath(old_citekey, extension), new_citekey)
lgpl-3.0
Godin/sonar
sonar-ws/src/main/java/org/sonarqube/ws/client/securityreports/SecurityReportsService.java
2108
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonarqube.ws.client.securityreports; import javax.annotation.Generated; import org.sonarqube.ws.client.BaseService; import org.sonarqube.ws.client.GetRequest; import org.sonarqube.ws.client.WsConnector; import org.sonarqube.ws.SecurityReports.ShowWsResponse; /** * @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/security_reports">Further information about this web service online</a> */ @Generated("sonar-ws-generator") public class SecurityReportsService extends BaseService { public SecurityReportsService(WsConnector wsConnector) { super(wsConnector, "api/security_reports"); } /** * * This is part of the internal API. * This is a GET request. * @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/security_reports/show">Further information about this action online (including a response example)</a> * @since 7.3 */ public ShowWsResponse show(ShowRequest request) { return call( new GetRequest(path("show")) .setParam("branch", request.getBranch()) .setParam("includeDistribution", request.getIncludeDistribution()) .setParam("project", request.getProject()) .setParam("standard", request.getStandard()), ShowWsResponse.parser()); } }
lgpl-3.0
ToBaer94/PygameTowerDefense
buttons/trap_selection_button.py
290
from button import Button class TrapButton(Button): def __init__(self, image, x, y, parent, trap): super(TrapButton, self).__init__(image, x, y, parent) self.trap = trap def get_clicked(self): print self.trap self.parent.selected_trap = self.trap
lgpl-3.0
advanced-online-marketing/AOM
vendor/facebook/php-business-sdk/src/FacebookAds/Object/AudioCopyright.php
2437
<?php /** * Copyright (c) 2015-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to * use, copy, modify, and distribute this software in source code or binary * form for use in connection with the web services and APIs provided by * Facebook. * * As with any software that integrates with the Facebook platform, your use * of this software is subject to the Facebook Developer Principles and * Policies [http://developers.facebook.com/policy/]. This copyright notice * shall be included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ namespace FacebookAds\Object; use FacebookAds\ApiRequest; use FacebookAds\Cursor; use FacebookAds\Http\RequestInterface; use FacebookAds\TypeChecker; use FacebookAds\Object\Fields\AudioCopyrightFields; /** * This class is auto-generated. * * For any issues or feature requests related to this class, please let us know * on github and we'll fix in our codegen framework. We'll not be able to accept * pull request for this class. * */ class AudioCopyright extends AbstractCrudObject { /** * @return AudioCopyrightFields */ public static function getFieldsEnum() { return AudioCopyrightFields::getInstance(); } protected static function getReferencedEnums() { $ref_enums = array(); return $ref_enums; } public function getSelf(array $fields = array(), array $params = array(), $pending = false) { $this->assureId(); $param_types = array( ); $enums = array( ); $request = new ApiRequest( $this->api, $this->data['id'], RequestInterface::METHOD_GET, '/', new AudioCopyright(), 'NODE', AudioCopyright::getFieldsEnum()->getValues(), new TypeChecker($param_types, $enums) ); $request->addParams($params); $request->addFields($fields); return $pending ? $request : $request->execute(); } }
lgpl-3.0
remhume/Hermelin
js/ui.exts_dlg.js
3466
if (typeof ui == 'undefined') var ui = {}; ui.ExtsDlg = { id: '', init: function init() { ui.ExtsDlg.id = '#prefs_exts'; }, load_ext_list: function load_ext_list() { var exts_list = $('#prefs_exts > ul').empty(); for (var ext_id in ext.exts_info) { var info = ext.exts_info[ext_id]; var li = $('<li class="mochi_list_item" ext_id="' + ext_id + '">' + '<input type="checkbox" class="mochi_toggle widget"/>' + (info.has_options ? '<a href="javascript:void(0);" class="value option"></a>' : '') + '<label class="label">' + info.name + '</label>' + '</li>'); /* var li = $('<li class="ext_item"/>').attr('id', 'ext_' + ext_id); var div = $('<div class="ext_icon_wrap"/>').appendTo(li); $('<img class="ext_icon"/>').attr('src', info.icon).appendTo(div); div = $('<div class="ext_item_body"/>').appendTo(li); $('<span class="ext_name"/>').text(info.name).appendTo(div); $(document.createTextNode(' - ' + _('version') + ' ')).appendTo(div); $('<span/>').text(info.version).appendTo(div); $('<br/>').appendTo(div); $('<span/>').text(_('author') + ': ').appendTo(div); $('<span/>').text(info.author).appendTo(div); $('<br/>').appendTo(div); $('<span/>').text(_('website') + ': ').appendTo(div); $('<a class="ext_url"/>').attr('href', info.url).text(info.url).appendTo(div); $('<br/>').appendTo(div); var d = info.description.split('\n'); var p = $('<p class="ext_description"/>').appendTo(div); $(document.createTextNode(d[0])).appendTo(p); for (var i = 1, l = d.length; i < l; i++) { $('<br/>').appendTo(p); $(document.createTextNode(d[i])).appendTo(p); } var sdiv = $('<div class="ext_ctrl" style="padding-top: 5px; border-top: 1px #ccc solid">').appendTo(div); $('<a href="javascript:void(0);" class="button enable_btn"/>').text(_('enable')).appendTo(sdiv); if (info.has_options) { $('<a href="javascript:void(0);" class="button options_btn"/>').text(_('options')).appendTo(sdiv); } */ exts_list.append(li); } var prefs = conf.get_current_profile().preferences; $('#prefs_exts .mochi_list_item').each(function (idx, obj) { var id = $(obj).attr('ext_id'); var exists = (prefs.exts_enabled.indexOf(id) != -1); ui.ExtsDlg.enable_ext_item(obj, exists); }); ui.ExtsDlg.bind_exts_btns(); }, enable_ext_item: function enable_ext_item(item, enable) { $(item).find('.widget') .attr('checked', enable).prop('checked', enable) }, bind_exts_btns: function bind_exts_btns() { var prefs = conf.get_current_profile().preferences; $('#prefs_exts .widget').click(function (event) { var item = $(this).parent().get(0); var id = $(item).attr('ext_id'); var enable = $(this).prop('checked'); ext.exts_info[id].enable = enable; if (enable) { prefs.exts_enabled.push(id) ext.enable_ext(id); } else { prefs.exts_enabled.splice(prefs.exts_enabled.indexOf(id), 1); ext.disable_ext(id); } ui.ExtsDlg.enable_ext_item(item, enable); conf.save_prefs(conf.current_name); }); $('#prefs_exts .option').click(function (event) { var item = $(this).parent().get(0); var id = $(item).attr('ext_id'); ext.config_ext(id); return false; }); } }
lgpl-3.0
SergiyKolesnikov/fuji
examples/BerkeleyDB-fuji-compilable/base/com/sleepycat/je/dbi/EnvConfigObserver.java
393
package com.sleepycat.je.dbi; import com.sleepycat.je.DatabaseException; import de.ovgu.cide.jakutil.*; /** * Implemented by observers of mutable config changes. */ public interface EnvConfigObserver { /** * Notifies the observer that one or more mutable properties have been * changed. */ void envConfigUpdate( DbConfigManager configMgr) throws DatabaseException ; }
lgpl-3.0
aploese/spsw
de.ibapl.spsw.jnhwprovider/src/test/java/de/ibapl/spsw/testsjnhw/TwoPortsBaselineRxTxTest.java
1316
/* * SPSW - Drivers for the serial port, https://github.com/aploese/spsw/ * Copyright (C) 2009-2021, Arne Plöse and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package de.ibapl.spsw.testsjnhw; import de.ibapl.spsw.tests.AbstractTwoPortsBaselineRxTxTest; import org.junit.jupiter.api.Disabled; /** * * @author Arne Plöse * */ @Disabled public class TwoPortsBaselineRxTxTest extends AbstractTwoPortsBaselineRxTxTest { }
lgpl-3.0
advanced-online-marketing/AOM
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201708/FeatureErrorReason.php
214
<?php namespace Google\AdsApi\Dfp\v201708; /** * This file was generated from WSDL. DO NOT EDIT. */ class FeatureErrorReason { const MISSING_FEATURE = 'MISSING_FEATURE'; const UNKNOWN = 'UNKNOWN'; }
lgpl-3.0
retohugi/SitecoreExtension-ClickjackingProtection
src/SitecoreExtension.ClickjackingProtection/Properties/AssemblyInfo.cs
1306
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SitecoreExtension.ClickjackingProtection")] [assembly: AssemblyDescription("A Sitecore Extension")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SitecoreExtension.ClickjackingProtection")] [assembly: AssemblyCopyright("Reto Hugi")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1caab1b8-d8ab-46f5-981e-5553fbf8707a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
lgpl-3.0
uqbar-paco/obj3-declaratividad-ruby
model/view_dsl/alumno_dsl.rb
328
require_relative '../alumno' require_relative '../alumno_agregados' require_relative 'descriptor_dsl_support' =begin The addition to the model Alumno class in order to define a descriptor based in the simple DSL defined in DesciptorDslSupport. Cfr. descriptor_dsl_support.rb. =end class Alumno extend DesciptorDslSupport end
lgpl-3.0
kyungtaekLIM/PSI-BLASTexB
src/ncbi-blast-2.5.0+/c++/include/objects/entrez2/Entrez2_docsum_field_info_.hpp
7833
/* $Id$ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * */ /// @file Entrez2_docsum_field_info_.hpp /// Data storage class. /// /// This file was generated by application DATATOOL /// using the following specifications: /// 'entrez2.asn'. /// /// ATTENTION: /// Don't edit or commit this file into CVS as this file will /// be overridden (by DATATOOL) without warning! #ifndef OBJECTS_ENTREZ2_ENTREZ2_DOCSUM_FIELD_INFO_BASE_HPP #define OBJECTS_ENTREZ2_ENTREZ2_DOCSUM_FIELD_INFO_BASE_HPP // standard includes #include <serial/serialbase.hpp> // generated includes #include <string> #include <objects/entrez2/Entrez2_docsum_field_type.hpp> BEGIN_NCBI_SCOPE #ifndef BEGIN_objects_SCOPE # define BEGIN_objects_SCOPE BEGIN_SCOPE(objects) # define END_objects_SCOPE END_SCOPE(objects) #endif BEGIN_objects_SCOPE // namespace ncbi::objects:: // generated classes ///////////////////////////////////////////////////////////////////////////// class NCBI_ENTREZ2_EXPORT CEntrez2_docsum_field_info_Base : public CSerialObject { typedef CSerialObject Tparent; public: // constructor CEntrez2_docsum_field_info_Base(void); // destructor virtual ~CEntrez2_docsum_field_info_Base(void); // type info DECLARE_INTERNAL_TYPE_INFO(); // types typedef string TField_name; typedef string TField_description; typedef int TField_type; // getters // setters /// mandatory /// typedef string TField_name /// Check whether the Field_name data member has been assigned a value. bool IsSetField_name(void) const; /// Check whether it is safe or not to call GetField_name method. bool CanGetField_name(void) const; void ResetField_name(void); const TField_name& GetField_name(void) const; void SetField_name(const TField_name& value); TField_name& SetField_name(void); /// mandatory /// typedef string TField_description /// Check whether the Field_description data member has been assigned a value. bool IsSetField_description(void) const; /// Check whether it is safe or not to call GetField_description method. bool CanGetField_description(void) const; void ResetField_description(void); const TField_description& GetField_description(void) const; void SetField_description(const TField_description& value); TField_description& SetField_description(void); /// mandatory /// typedef int TField_type /// Check whether the Field_type data member has been assigned a value. bool IsSetField_type(void) const; /// Check whether it is safe or not to call GetField_type method. bool CanGetField_type(void) const; void ResetField_type(void); TField_type GetField_type(void) const; void SetField_type(TField_type value); TField_type& SetField_type(void); /// Reset the whole object virtual void Reset(void); private: // Prohibit copy constructor and assignment operator CEntrez2_docsum_field_info_Base(const CEntrez2_docsum_field_info_Base&); CEntrez2_docsum_field_info_Base& operator=(const CEntrez2_docsum_field_info_Base&); // data Uint4 m_set_State[1]; string m_Field_name; string m_Field_description; int m_Field_type; }; /////////////////////////////////////////////////////////// ///////////////////// inline methods ////////////////////// /////////////////////////////////////////////////////////// inline bool CEntrez2_docsum_field_info_Base::IsSetField_name(void) const { return ((m_set_State[0] & 0x3) != 0); } inline bool CEntrez2_docsum_field_info_Base::CanGetField_name(void) const { return IsSetField_name(); } inline const CEntrez2_docsum_field_info_Base::TField_name& CEntrez2_docsum_field_info_Base::GetField_name(void) const { if (!CanGetField_name()) { ThrowUnassigned(0); } return m_Field_name; } inline void CEntrez2_docsum_field_info_Base::SetField_name(const CEntrez2_docsum_field_info_Base::TField_name& value) { m_Field_name = value; m_set_State[0] |= 0x3; } inline CEntrez2_docsum_field_info_Base::TField_name& CEntrez2_docsum_field_info_Base::SetField_name(void) { #ifdef _DEBUG if (!IsSetField_name()) { m_Field_name = UnassignedString(); } #endif m_set_State[0] |= 0x1; return m_Field_name; } inline bool CEntrez2_docsum_field_info_Base::IsSetField_description(void) const { return ((m_set_State[0] & 0xc) != 0); } inline bool CEntrez2_docsum_field_info_Base::CanGetField_description(void) const { return IsSetField_description(); } inline const CEntrez2_docsum_field_info_Base::TField_description& CEntrez2_docsum_field_info_Base::GetField_description(void) const { if (!CanGetField_description()) { ThrowUnassigned(1); } return m_Field_description; } inline void CEntrez2_docsum_field_info_Base::SetField_description(const CEntrez2_docsum_field_info_Base::TField_description& value) { m_Field_description = value; m_set_State[0] |= 0xc; } inline CEntrez2_docsum_field_info_Base::TField_description& CEntrez2_docsum_field_info_Base::SetField_description(void) { #ifdef _DEBUG if (!IsSetField_description()) { m_Field_description = UnassignedString(); } #endif m_set_State[0] |= 0x4; return m_Field_description; } inline bool CEntrez2_docsum_field_info_Base::IsSetField_type(void) const { return ((m_set_State[0] & 0x30) != 0); } inline bool CEntrez2_docsum_field_info_Base::CanGetField_type(void) const { return IsSetField_type(); } inline void CEntrez2_docsum_field_info_Base::ResetField_type(void) { m_Field_type = (int)(0); m_set_State[0] &= ~0x30; } inline CEntrez2_docsum_field_info_Base::TField_type CEntrez2_docsum_field_info_Base::GetField_type(void) const { if (!CanGetField_type()) { ThrowUnassigned(2); } return m_Field_type; } inline void CEntrez2_docsum_field_info_Base::SetField_type(CEntrez2_docsum_field_info_Base::TField_type value) { m_Field_type = value; m_set_State[0] |= 0x30; } inline CEntrez2_docsum_field_info_Base::TField_type& CEntrez2_docsum_field_info_Base::SetField_type(void) { #ifdef _DEBUG if (!IsSetField_type()) { memset(&m_Field_type,UnassignedByte(),sizeof(m_Field_type)); } #endif m_set_State[0] |= 0x10; return m_Field_type; } /////////////////////////////////////////////////////////// ////////////////// end of inline methods ////////////////// /////////////////////////////////////////////////////////// END_objects_SCOPE // namespace ncbi::objects:: END_NCBI_SCOPE #endif // OBJECTS_ENTREZ2_ENTREZ2_DOCSUM_FIELD_INFO_BASE_HPP
lgpl-3.0
uaithne/uaithne-generator
src/main/java/org/uaithne/generator/templates/shared/gwt/client/ChainedGroupingAsyncExecutorTemplate.java
3769
/* * Copyright 2012 and beyond, Juan Luis Paz * * This file is part of Uaithne. * * Uaithne 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. * * Uaithne 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 Uaithne. If not, see <http://www.gnu.org/licenses/>. */ package org.uaithne.generator.templates.shared.gwt.client; import java.io.IOException; import org.uaithne.generator.commons.DataTypeInfo; import org.uaithne.generator.templates.ClassTemplate; public class ChainedGroupingAsyncExecutorTemplate extends ClassTemplate { public ChainedGroupingAsyncExecutorTemplate(String sharedGwtPackageDot) { String packageName = sharedGwtPackageDot + "client"; setPackageName(packageName); addImport("com.google.gwt.user.client.rpc.AsyncCallback", packageName); addImport(DataTypeInfo.OPERATION_DATA_TYPE, packageName); setClassName("ChainedGroupingAsyncExecutor"); addImplement("AsyncExecutor"); } @Override protected void writeContent(Appendable appender) throws IOException { appender.append(" private Object executorSelector;\n" + " private AsyncExecutorGroup chainedExecutorGroup;\n" + "\n" + " /**\n" + " * @return the chainedExecutorGroup\n" + " */\n" + " public AsyncExecutorGroup getChainedExecutorGroup() {\n" + " return chainedExecutorGroup;\n" + " }\n" + "\n" + " @Override\n" + " public Object getExecutorSelector() {\n" + " return executorSelector;\n" + " }\n" + "\n" + " @Override\n" + " public ").append(OPERATION_BASE_DEFINITION).append(" void execute(OPERATION operation, AsyncCallback<RESULT> asyncCallback) {\n" + " chainedExecutorGroup.execute(operation, asyncCallback);\n" + " }\n"); if (getGenerationInfo().isIncludeExecuteOtherMethodInExecutors()) { appender.append("\n" + " @Override\n" + " public ").append(OPERATION_BASE_DEFINITION).append(" void executeOther(OPERATION operation, AsyncCallback<RESULT> asyncCallback) {\n" + " execute(operation, asyncCallback);\n" + " }\n"); } appender.append("\n" + " public ChainedGroupingAsyncExecutor(AsyncExecutorGroup chainedExecutorGroup, Object executorSelector) {\n" + " if (chainedExecutorGroup == null) {\n" + " throw new IllegalArgumentException(\"chainedExecutorGroup for the ChainedGroupingAsyncExecutor cannot be null\");\n" + " }\n" + " if (executorSelector == null) {\n" + " throw new IllegalArgumentException(\"executorSelector for the ChainedGroupingAsyncExecutor cannot be null\");\n" + " }\n" + " this.chainedExecutorGroup = chainedExecutorGroup;\n" + " this.executorSelector = executorSelector;\n" + " }"); } }
lgpl-3.0
Arcavias/arcavias-core
misc/ext-template/controller/frontend/tests/Controller/Frontend/DemoTest.php
869
<?php /** * @copyright Copyright (c) Metaways Infosystems GmbH, 2013 * @license LGPLv3, http://www.arcavias.com/en/license */ class Controller_Frontend_DemoTest extends MW_Unittest_Testcase { private $_object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @access protected */ protected function setUp() { // $this->_object = new Controller_Frontend_Demo_Default( TestHelper::getContext() ); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @access protected */ protected function tearDown() { unset( $this->_object ); Controller_Frontend_Factory::clear(); MShop_Factory::clear(); } public function testDemo() { $this->markTestIncomplete( 'Just a demo' ); } }
lgpl-3.0
awagle/hackathon
jira/com.tibco.bw.palette.jira.design/src/com/tibco/bw/palette/jira/design/preferences/PreferenceConstants.java
277
package com.tibco.bw.palette.jira.design.preferences; /** * Constant definitions for plug-in preferences */ public class PreferenceConstants { public static final String P_USER= "userNamePreference"; public static final String P_PASSWORD = "passwordNamePreference"; }
lgpl-3.0
biless/cinatra
include/cinatra/cinatra.hpp
4374
#pragma once #include <cinatra/http_server.hpp> #include <cinatra/http_router.hpp> #include <cinatra/request.hpp> #include <cinatra/response.hpp> #include <cinatra/logging.hpp> #include <cinatra/aop.hpp> #include <cinatra/body_parser.hpp> #include <boost/lexical_cast.hpp> #include <string> #include <vector> namespace cinatra { template<typename... Aspect> class Cinatra { public: template<typename F> typename std::enable_if<(function_traits<F>::arity>0), Cinatra&>::type route(const std::string& name,const F& f) { router_.route(name, f); return *this; } template<typename F, typename Self> typename std::enable_if<(function_traits<F>::arity>0), Cinatra&>::type route(const std::string& name, const F& f, Self* self) { router_.route(name, f, self); return *this; } template<typename F> typename std::enable_if<function_traits<F>::arity==0, Cinatra&>::type route(const std::string& name,const F& f) { route(name, [f](cinatra::Request& req, cinatra::Response& res) { auto r = f(); res.write(boost::lexical_cast<std::string>(r)); }); return *this; } template<typename F, typename Self> typename std::enable_if<function_traits<F>::arity == 0, Cinatra&>::type route(const std::string& name, const F& f, Self* self) { route(name, [f, self](cinatra::Request& req, cinatra::Response& res) { auto r = (*self.*f)(); res.write(boost::lexical_cast<std::string>(r)); }); return *this; } Cinatra& threads(int num) { num_threads_ = num < 1 ? 1 : num; return *this; } Cinatra& error_handler(error_handler_t error_handler) { error_handler_ = error_handler; return *this; } Cinatra& listen(const std::string& address, const std::string& port) { listen_addr_ = address; listen_port_ = port; return *this; } Cinatra& listen(const std::string& port) { listen_addr_ = "0.0.0.0"; listen_port_ = port; return *this; } Cinatra& listen(const std::string& address, unsigned short port) { listen_addr_ = address; listen_port_ = boost::lexical_cast<std::string>(port); return *this; } Cinatra& static_dir(const std::string& dir) { static_dir_ = dir; return *this; } void run() { HTTPServer s(num_threads_); s.set_request_handler([this](Request& req, Response& res) { return Invoke<sizeof...(Aspect)>(res, &Cinatra::dispatch, this, req, res); }) .set_error_handler([this](int code, const std::string& msg, Request& req, Response& res) { LOG_DBG << "Handle error:" << code << " " << msg << " with path " << req.path(); if (error_handler_ && error_handler_(code,msg,req,res)) { return true; } LOG_DBG << "In defaule error handler"; std::string html; auto s = status_header(code); html = "<html><head><title>" + s.second + "</title></head>"; html += "<body>"; html += "<h1>" + boost::lexical_cast<std::string>(s.first) + " " + s.second + " " + "</h1>"; if (!msg.empty()) { html += "<br> <h2>Message: " + msg + "</h2>"; } html += "</body></html>"; res.set_status_code(s.first); res.write(html); return true; }) .static_dir(static_dir_) .listen(listen_addr_, listen_port_) .run(); } private: template<size_t I, typename Func, typename Self, typename... Args> typename std::enable_if<I == 0, bool>::type Invoke(Response& /* res */, Func&&f, Self* self, Args&&... args) { return (*self.*f)(std::forward<Args>(args)...); } template<size_t I, typename Func, typename Self, typename... Args> typename std::enable_if < (I > 0), bool > ::type Invoke(Response& res, Func&& /* f */, Self* /* self */, Args&&... args) { return invoke<Aspect...>(res, &Cinatra::dispatch, this, args...); } bool dispatch(Request& req, Response& res) { return router_.dispatch(req, res); } private: #ifndef CINATRA_SINGLE_THREAD int num_threads_ = std::thread::hardware_concurrency(); #endif // CINATRA_SINGLE_THREAD std::string listen_addr_; std::string listen_port_; std::string static_dir_; error_handler_t error_handler_; HTTPRouter router_; }; using SimpleApp = Cinatra<>; }
lgpl-3.0
caiusb/gumtree
client/src/main/java/com/github/gumtreediff/client/Option.java
5351
/* * This file is part of GumTree. * * GumTree 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. * * GumTree 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 GumTree. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2011-2015 Jean-Rémy Falleri <jr.falleri@gmail.com> * Copyright 2011-2015 Floréal Morandat <florealm@gmail.com> */ package com.github.gumtreediff.client; import java.io.PrintStream; import java.util.ArrayList; public abstract class Option { final String description; final String key; final int paramCount; public interface Context { Option[] values(); static Option[] addValue(Option[] options, Option... newOptions) { Option[] nopts = new Option[options.length + newOptions.length]; System.arraycopy(options, 0, nopts, 0, options.length); System.arraycopy(newOptions, 0, nopts, options.length, newOptions.length); return nopts; } } public static class OptionException extends RuntimeException { final Context context; public OptionException(String msg, Context ctx) { super(msg); context = ctx; } public OptionException(String msg) { this(msg, null); } public Context getContext() { return context; } } public Option(String key, String text) { this(key, text, 0); } public Option(String key, String text, int params) { this.key = key; this.description = text; this.paramCount = params; } public static String[] processCommandLine(String[] args, Context context) { return processCommandLine(args, context.values(), context); } public static String[] processCommandLine(String[] args, Option[] availableOptions, Context ctx) { ArrayList<String> todo = new ArrayList<>(args.length); for (int i = 0; i < args.length; i++) { String arg = args[i]; boolean found = false; for (int j = 0; j < availableOptions.length && !found; j++) { if (availableOptions[j].hasOption(arg)) { int nbParams = availableOptions[j].paramCount; String[] opts = new String[nbParams]; int currentParam = 0; while (currentParam < nbParams) { try { opts[currentParam++] = args[++i]; } catch (ArrayIndexOutOfBoundsException e) { throw new OptionException(String.format( "Option '%s' expects more parameters, using null", arg), ctx); } } availableOptions[j].process(arg, opts); found = true; } } if (!found) { todo.add(arg); } } String[] rest = new String[todo.size()]; todo.toArray(rest); return rest; } protected boolean hasOption(String arg) { return key.equals(arg); } protected abstract void process(String name, String[] args); public String formatHelpText() { return String.format("%s%s\t%s", key, (paramCount > 0 ? " <" + paramCount + ">" : ""), description); } @Override public String toString() { return key; } public static void displayOptions(PrintStream out, Context ctx) { for (Option opt : ctx.values()) { out.println(opt.formatHelpText()); } } public static class Help extends Option { protected final Context context; public Help(final Context ctx) { super("--help", "Display help (this screen)"); context = ctx; } @Override public void process(String name, String[] args) { displayOptions(System.out, context); System.exit(0); } } public static class Text extends Option { public Text(String text) { super("", text); } @Override public boolean hasOption(String opt) { return false; } @Override protected void process(String name, String[] args) {} @Override public String formatHelpText() { return description; } } public static class Verbose extends Option { public static boolean verbose = false; public Verbose() { super("-v", "Verbose mode"); } @Override public boolean hasOption(String opt) { return super.hasOption(opt) || opt.equals("--verbose"); } @Override protected void process(String name, String[] opts) { verbose = true; } } }
lgpl-3.0
contao-community-alliance/dc-general
tests/DataDefinition/Palette/PaletteConditionChainTest.php
2636
<?php /** * This file is part of contao-community-alliance/dc-general. * * (c) 2013-2019 Contao Community Alliance. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * This project is provided in good faith and hope to be usable by anyone. * * @package contao-community-alliance/dc-general * @author Christian Schiffler <c.schiffler@cyberspectrum.de> * @author Sven Baumann <baumann.sv@gmail.com> * @copyright 2013-2019 Contao Community Alliance. * @license https://github.com/contao-community-alliance/dc-general/blob/master/LICENSE LGPL-3.0-or-later * @filesource */ namespace ContaoCommunityAlliance\DcGeneral\Test\DataDefinition\Palette; use ContaoCommunityAlliance\DcGeneral\Data\DefaultModel; use ContaoCommunityAlliance\DcGeneral\Data\PropertyValueBag; use ContaoCommunityAlliance\DcGeneral\DataDefinition\Palette\Condition\Palette\PaletteConditionChain; use ContaoCommunityAlliance\DcGeneral\DataDefinition\Palette\Condition\Palette\PropertyValueCondition; use ContaoCommunityAlliance\DcGeneral\Test\DataDefinition\AbstractConditionChainTestBase; class PaletteConditionChainTest extends AbstractConditionChainTestBase { public function testClone() { $condition = new PaletteConditionChain(); $condition->addCondition(new PropertyValueCondition('propname', '0')); $condition->addCondition(new PropertyValueCondition('propname2', '1')); $this->assertCloneMatch($condition); } public function testGetMatch() { $condition = new PaletteConditionChain(); $condition->setConjunction(PaletteConditionChain::AND_CONJUNCTION); $condition->addCondition(new PropertyValueCondition('prop1', '0')); $condition->addCondition(new PropertyValueCondition('prop2', '1')); $this->assertEquals(0, $condition->getMatchCount()); $model = new DefaultModel(); $model->setProperty('prop1', '0'); $model->setProperty('prop2', '1'); $this->assertEquals(2, $condition->getMatchCount($model)); $model->setProperty('prop2', '0'); $this->assertEquals(0, $condition->getMatchCount($model)); $propertyValueBag = new PropertyValueBag(); $propertyValueBag->setPropertyValue('prop1', '0'); $propertyValueBag->setPropertyValue('prop2', '1'); $this->assertEquals(2, $condition->getMatchCount(null, $propertyValueBag)); $propertyValueBag->setPropertyValue('prop2', '3'); $this->assertEquals(0, $condition->getMatchCount(null, $propertyValueBag)); } }
lgpl-3.0
UniTime/cpsolver
src/org/cpsolver/exam/reports/ExamRoomSchedule.java
3945
package org.cpsolver.exam.reports; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.cpsolver.exam.model.Exam; import org.cpsolver.exam.model.ExamModel; import org.cpsolver.exam.model.ExamPeriod; import org.cpsolver.exam.model.ExamPlacement; import org.cpsolver.exam.model.ExamRoom; import org.cpsolver.ifs.assignment.Assignment; import org.cpsolver.ifs.util.CSVFile; import org.cpsolver.ifs.util.CSVFile.CSVField; /** * Export schedule for each room into a CSV file. <br> * <br> * Usage: * <pre><code> * &nbsp;&nbsp;&nbsp;&nbsp;new ExamRoomSchedule(model).report().save(file); * </code></pre> * <br> * * @version ExamTT 1.3 (Examination Timetabling)<br> * Copyright (C) 2008 - 2014 Tomas Muller<br> * <a href="mailto:muller@unitime.org">muller@unitime.org</a><br> * <a href="http://muller.unitime.org">http://muller.unitime.org</a><br> * <br> * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. <br> * <br> * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. <br> * <br> * You should have received a copy of the GNU Lesser General Public * License along with this library; if not see * <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>. */ public class ExamRoomSchedule { ExamModel iModel = null; /** * Constructor * * @param model * examination timetabling model */ public ExamRoomSchedule(ExamModel model) { iModel = model; } public CSVFile report(Assignment<Exam, ExamPlacement> assignment) { CSVFile csv = new CSVFile(); csv.setHeader(new CSVField[] { new CSVField("Room"), new CSVField("Cap"), new CSVField("AltCap"), new CSVField("Period"), new CSVField("Date"), new CSVField("Time"), new CSVField("Exam"), new CSVField("Enrl") }); List<ExamRoom> rooms = new ArrayList<ExamRoom>(iModel.getRooms()); Collections.sort(rooms, new Comparator<ExamRoom>() { @Override public int compare(ExamRoom r1, ExamRoom r2) { int cmp = -Double.compare(r1.getSize(), r2.getSize()); if (cmp != 0) return cmp; cmp = -Double.compare(r1.getAltSize(), r2.getAltSize()); if (cmp != 0) return cmp; return r1.compareTo(r2); } }); for (ExamRoom room : rooms) { boolean first = true; int day = -1; for (ExamPeriod period : iModel.getPeriods()) { for (ExamPlacement placement: room.getPlacements(assignment, period)) { Exam exam = placement.variable(); csv.addLine(new CSVField[] { new CSVField(first ? room.getName() : ""), new CSVField(first ? "" + room.getSize() : ""), new CSVField(first ? "" + room.getAltSize() : ""), new CSVField(period.getIndex() + 1), new CSVField(day == period.getDay() ? "" : period.getDayStr()), new CSVField(period.getTimeStr()), new CSVField(exam.getName()), new CSVField(exam.getStudents().size()) }); first = false; day = period.getDay(); } } } return csv; } }
lgpl-3.0
MetaModels/core
src/DcGeneral/DataDefinition/Palette/Condition/Property/InputScreenAttributeIs.php
2392
<?php /** * This file is part of MetaModels/core. * * (c) 2012-2019 The MetaModels team. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * This project is provided in good faith and hope to be usable by anyone. * * @package MetaModels/core * @author Christian Schiffler <c.schiffler@cyberspectrum.de> * @author Sven Baumann <baumann.sv@gmail.com> * @author Cliff Parnitzky <github@cliff-parnitzky.de> * @author David Molineus <david.molineus@netzmacht.de> * @copyright 2012-2019 The MetaModels team. * @license https://github.com/MetaModels/core/blob/master/LICENSE LGPL-3.0-or-later * @filesource */ namespace MetaModels\DcGeneral\DataDefinition\Palette\Condition\Property; use Contao\System; use Doctrine\DBAL\Connection; /** * Condition for the default palette. * * @deprecated Use AttributeByIdIsOfType instead. */ class InputScreenAttributeIs extends AttributeByIdIsOfType { /** * Create a new instance. * * @param string $attributeType The attribute type name. * @param Connection|null $connection Database connection. */ public function __construct($attributeType, Connection $connection = null) { // @codingStandardsIgnoreStart @trigger_error( '"' . __CLASS__ . '" is deprecated and will get removed in MetaModels 3.0. ' . 'Use "' . AttributeByIdIsOfType::class . '" instead', E_USER_DEPRECATED ); // @codingStandardsIgnoreEnd if (null === $connection) { // @codingStandardsIgnoreStart @trigger_error( 'Connection is missing. It has to be passed in the constructor. Fallback will be dropped.', E_USER_DEPRECATED ); // @codingStandardsIgnoreEnd $connection = System::getContainer()->get('database_connection'); } parent::__construct($attributeType, $connection, 'attr_id'); } /** * Retrieve the service container. * * @return IMetaModelsServiceContainer * * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.CamelCaseVariableName) */ protected function getServiceContainer() { return $GLOBALS['container']['metamodels-service-container']; } }
lgpl-3.0
PabloPiaggi/plumed2
src/colvar/Dipole.cpp
5186
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Copyright (c) 2012-2020 The plumed team (see the PEOPLE file at the root of the distribution for a list of names) See http://www.plumed.org for more information. This file is part of plumed, version 2. plumed 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. plumed 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 plumed. If not, see <http://www.gnu.org/licenses/>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #include "Colvar.h" #include "ActionRegister.h" namespace PLMD { namespace colvar { //+PLUMEDOC COLVAR DIPOLE /* Calculate the dipole moment for a group of atoms. When running with periodic boundary conditions, the atoms should be in the proper periodic image. This is done automatically since PLUMED 2.5, by considering the ordered list of atoms and rebuilding the molecule with a procedure that is equivalent to that done in \ref WHOLEMOLECULES . Notice that rebuilding is local to this action. This is different from \ref WHOLEMOLECULES which actually modifies the coordinates stored in PLUMED. In case you want to recover the old behavior you should use the NOPBC flag. In that case you need to take care that atoms are in the correct periodic image. \par Examples The following tells plumed to calculate the dipole of the group of atoms containing the atoms from 1-10 and print it every 5 steps \plumedfile d: DIPOLE GROUP=1-10 PRINT FILE=output STRIDE=5 ARG=d \endplumedfile \attention If the total charge Q of the group in non zero, then a charge Q/N will be subtracted to every atom, where N is the number of atoms. This implies that the dipole (which for a charged system depends on the position) is computed on the geometric center of the group. */ //+ENDPLUMEDOC class Dipole : public Colvar { std::vector<AtomNumber> ga_lista; bool components; bool nopbc; public: explicit Dipole(const ActionOptions&); void calculate() override; static void registerKeywords(Keywords& keys); }; PLUMED_REGISTER_ACTION(Dipole,"DIPOLE") void Dipole::registerKeywords(Keywords& keys) { Colvar::registerKeywords(keys); keys.add("atoms","GROUP","the group of atoms we are calculating the dipole moment for"); keys.addFlag("COMPONENTS",false,"calculate the x, y and z components of the dipole separately and store them as label.x, label.y and label.z"); keys.addOutputComponent("x","COMPONENTS","the x-component of the dipole"); keys.addOutputComponent("y","COMPONENTS","the y-component of the dipole"); keys.addOutputComponent("z","COMPONENTS","the z-component of the dipole"); } Dipole::Dipole(const ActionOptions&ao): PLUMED_COLVAR_INIT(ao), components(false) { parseAtomList("GROUP",ga_lista); parseFlag("COMPONENTS",components); parseFlag("NOPBC",nopbc); checkRead(); if(components) { addComponentWithDerivatives("x"); componentIsNotPeriodic("x"); addComponentWithDerivatives("y"); componentIsNotPeriodic("y"); addComponentWithDerivatives("z"); componentIsNotPeriodic("z"); } else { addValueWithDerivatives(); setNotPeriodic(); } log.printf(" of %u atoms\n",static_cast<unsigned>(ga_lista.size())); for(unsigned int i=0; i<ga_lista.size(); ++i) { log.printf(" %d", ga_lista[i].serial()); } log.printf(" \n"); if(nopbc) log.printf(" without periodic boundary conditions\n"); else log.printf(" using periodic boundary conditions\n"); requestAtoms(ga_lista); } // calculator void Dipole::calculate() { if(!nopbc) makeWhole(); double ctot=0.; unsigned N=getNumberOfAtoms(); std::vector<double> charges(N); Vector dipje; for(unsigned i=0; i<N; ++i) { charges[i]=getCharge(i); ctot+=charges[i]; } ctot/=(double)N; for(unsigned i=0; i<N; ++i) { charges[i]-=ctot; dipje += charges[i]*getPosition(i); } if(!components) { double dipole = dipje.modulo(); double idip = 1./dipole; for(unsigned i=0; i<N; i++) { double dfunc=charges[i]*idip; setAtomsDerivatives(i,dfunc*dipje); } setBoxDerivativesNoPbc(); setValue(dipole); } else { Value* valuex=getPntrToComponent("x"); Value* valuey=getPntrToComponent("y"); Value* valuez=getPntrToComponent("z"); for(unsigned i=0; i<N; i++) { setAtomsDerivatives(valuex,i,charges[i]*Vector(1.0,0.0,0.0)); setAtomsDerivatives(valuey,i,charges[i]*Vector(0.0,1.0,0.0)); setAtomsDerivatives(valuez,i,charges[i]*Vector(0.0,0.0,1.0)); } setBoxDerivativesNoPbc(valuex); setBoxDerivativesNoPbc(valuey); setBoxDerivativesNoPbc(valuez); valuex->set(dipje[0]); valuey->set(dipje[1]); valuez->set(dipje[2]); } } } }
lgpl-3.0
sikachu/jasperreports
src/net/sf/jasperreports/components/sort/SortComponentSymbolFontFactory.java
2577
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2013 Jaspersoft Corporation. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.components.sort; import java.util.Map; import net.sf.jasperreports.engine.JRComponentElement; import net.sf.jasperreports.engine.JRFont; import net.sf.jasperreports.engine.JRStyle; import net.sf.jasperreports.engine.design.JRDesignFont; import net.sf.jasperreports.engine.design.JasperDesign; import net.sf.jasperreports.engine.xml.JRFontFactory; import net.sf.jasperreports.engine.xml.JRXmlConstants; import org.xml.sax.Attributes; /** * @author Teodor Danciu (teodord@users.sourceforge.net) * @version $Id: SortComponentSymbolFontFactory.java 5877 2013-01-07 19:51:14Z teodord $ */ public class SortComponentSymbolFontFactory extends JRFontFactory { public JRFont getFont() { int i = 0; JRComponentElement component = null; while (component == null && i < digester.getCount()) { Object obj = digester.peek(i); component = obj instanceof JRComponentElement ? (JRComponentElement)obj : null; i++; } return new JRDesignFont(component); } public void setStyle(JRFont font, Attributes atts) { JRDesignFont designFont = (JRDesignFont)font; String styleName = atts.getValue(JRXmlConstants.ATTRIBUTE_reportFont); if (styleName != null) { JasperDesign jasperDesign = (JasperDesign)digester.peek(digester.getCount() - 2); Map<String,JRStyle> stylesMap = jasperDesign.getStylesMap(); if (stylesMap.containsKey(styleName)) { JRStyle style = stylesMap.get(styleName); designFont.setStyle(style); } else { designFont.setStyleNameReference(styleName); } } } }
lgpl-3.0
vFense/vFenseAgent-nix
agent/agent.py
182
import sys import os sys.path.append(os.path.join(os.getcwd(), "src")) from core import MainCore if __name__ == "__main__": main_core = MainCore("agent") main_core.run()
lgpl-3.0
Guillaume351/Steadfast2
src/pocketmine/item/Item.php
75714
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * 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. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ /** * All the Item classes */ namespace pocketmine\item; use pocketmine\block\Block; use pocketmine\block\Flower; use pocketmine\entity\Entity; use pocketmine\entity\Squid; use pocketmine\entity\Villager; //use pocketmine\entity\Zombie; use pocketmine\inventory\Fuel; use pocketmine\item\enchantment\Enchantment; use pocketmine\level\Level; use pocketmine\nbt\tag\Enum; use pocketmine\nbt\tag\ShortTag; use pocketmine\nbt\tag\StringTag; use pocketmine\nbt\tag\IntTag; use pocketmine\Player; use pocketmine\nbt\tag\Compound; use pocketmine\nbt\NBT; class Item{ private static $cachedParser = null; private static $itemBlockClass = ItemBlock::class; /** * @param $tag * @return Compound */ private static function parseCompound($tag){ if(self::$cachedParser === null){ self::$cachedParser = new NBT(NBT::LITTLE_ENDIAN); } self::$cachedParser->read($tag); return self::$cachedParser->getData(); } /** * @param Compound $tag * @return string */ private static function writeCompound(Compound $tag){ if(self::$cachedParser === null){ self::$cachedParser = new NBT(NBT::LITTLE_ENDIAN); } self::$cachedParser->setData($tag); return self::$cachedParser->write(true); } //All Block IDs are here too const AIR = 0; const STONE = 1; const GRASS = 2; const DIRT = 3; const COBBLESTONE = 4; const COBBLE = 4; const PLANK = 5; const PLANKS = 5; const WOODEN_PLANK = 5; const WOODEN_PLANKS = 5; const SAPLING = 6; const SAPLINGS = 6; const BEDROCK = 7; const WATER = 8; const STILL_WATER = 9; const LAVA = 10; const STILL_LAVA = 11; const SAND = 12; const GRAVEL = 13; const GOLD_ORE = 14; const IRON_ORE = 15; const COAL_ORE = 16; const LOG = 17; const WOOD = 17; const TRUNK = 17; const LEAVES = 18; const LEAVE = 18; const SPONGE = 19; const GLASS = 20; const LAPIS_ORE = 21; const LAPIS_BLOCK = 22; const DISPENSER = 23; const SANDSTONE = 24; const NOTE_BLOCK = 25; const BED_BLOCK = 26; const POWERED_RAIL = 27; const DETECTOR_RAIL = 28; const STICKY_PISTON = 29; const COBWEB = 30; const TALL_GRASS = 31; const BUSH = 32; const DEAD_BUSH = 32; const WOOL = 35; const DANDELION = 37; const POPPY = 38; const ROSE = 38; const RED_FLOWER = 38; const BROWN_MUSHROOM = 39; const RED_MUSHROOM = 40; const GOLD_BLOCK = 41; const IRON_BLOCK = 42; const DOUBLE_SLAB = 43; const DOUBLE_SLABS = 43; const SLAB = 44; const SLABS = 44; const BRICKS = 45; const BRICKS_BLOCK = 45; const TNT = 46; const BOOKSHELF = 47; const MOSS_STONE = 48; const MOSSY_STONE = 48; const OBSIDIAN = 49; const TORCH = 50; const FIRE = 51; const MONSTER_SPAWNER = 52; const WOOD_STAIRS = 53; const WOODEN_STAIRS = 53; const OAK_WOOD_STAIRS = 53; const OAK_WOODEN_STAIRS = 53; const CHEST = 54; const REDSTONE_WIRE = 55; const DIAMOND_ORE = 56; const DIAMOND_BLOCK = 57; const CRAFTING_TABLE = 58; const WORKBENCH = 58; const WHEAT_BLOCK = 59; const FARMLAND = 60; const FURNACE = 61; const BURNING_FURNACE = 62; const LIT_FURNACE = 62; const SIGN_POST = 63; const DOOR_BLOCK = 64; const WOODEN_DOOR_BLOCK = 64; const WOOD_DOOR_BLOCK = 64; const LADDER = 65; const RAIL = 66; const COBBLE_STAIRS = 67; const COBBLESTONE_STAIRS = 67; const WALL_SIGN = 68; const LEVER = 69; const STONE_PRESSURE_PLATE = 70; const IRON_DOOR_BLOCK = 71; const WOODEN_PRESSURE_PLATE = 72; const REDSTONE_ORE = 73; const GLOWING_REDSTONE_ORE = 74; const LIT_REDSTONE_ORE = 74; const REDSTONE_TORCH = 75; const REDSTONE_TORCH_ACTIVE = 76; const STONE_BUTTON = 77; const SNOW = 78; const SNOW_LAYER = 78; const ICE = 79; const SNOW_BLOCK = 80; const CACTUS = 81; const CLAY_BLOCK = 82; const REEDS = 83; const SUGARCANE_BLOCK = 83; const JUKEBOX = 84; const FENCE = 85; const PUMPKIN = 86; const NETHERRACK = 87; const SOUL_SAND = 88; const GLOWSTONE = 89; const GLOWSTONE_BLOCK = 89; const PORTAL = 90; const LIT_PUMPKIN = 91; const JACK_O_LANTERN = 91; const CAKE_BLOCK = 92; const REDSTONE_REPEATER_BLOCK = 93; const REDSTONE_REPEATER_BLOCK_ACTIVE = 94; const INVISIBLE_BEDROCK = 95; const TRAPDOOR = 96; const MONSTER_EGG = 97; const STONE_BRICKS = 98; const STONE_BRICK = 98; const BROWN_MUSHROOM_BLOCK = 99; CONST RED_MUSHROOM_BLOCK = 100; const IRON_BAR = 101; const IRON_BARS = 101; const GLASS_PANE = 102; const GLASS_PANEL = 102; const MELON_BLOCK = 103; const PUMPKIN_STEM = 104; const MELON_STEM = 105; const VINE = 106; const VINES = 106; const FENCE_GATE = 107; const BRICK_STAIRS = 108; const STONE_BRICK_STAIRS = 109; const MYCELIUM = 110; const WATER_LILY = 111; const LILY_PAD = 111; const NETHER_BRICKS = 112; const NETHER_BRICK_BLOCK = 112; const NETHER_BRICK_FENCE = 113; const NETHER_BRICKS_STAIRS = 114; const NETHER_WART_BLOCK = 115; const ENCHANTING_TABLE = 116; const ENCHANT_TABLE = 116; const ENCHANTMENT_TABLE = 116; const BREWING_STAND_BLOCK = 117; const CAULDRON_BLOCK = 118; const END_PORTAL = 120; const END_STONE = 121; const DRAGON_EGG = 122; const REDSTONE_LAMP = 123; const REDSTONE_LAMP_ACTIVE = 124; const DROPPER = 125; const ACTIVATOR_RAIL = 126; const COCOA = 127; const SANDSTONE_STAIRS = 128; const EMERALD_ORE = 129; const ENDER_CHEST = 130; const TRIPWIRE_HOOK = 131; const TRIPWIRE = 132; const EMERALD_BLOCK = 133; const SPRUCE_WOOD_STAIRS = 134; const SPRUCE_WOODEN_STAIRS = 134; const BIRCH_WOOD_STAIRS = 135; const BIRCH_WOODEN_STAIRS = 135; const JUNGLE_WOOD_STAIRS = 136; const JUNGLE_WOODEN_STAIRS = 136; const BEACON = 138; const COBBLE_WALL = 139; const STONE_WALL = 139; const COBBLESTONE_WALL = 139; const FLOWER_POT_BLOCK = 140; const CARROT_BLOCK = 141; const POTATO_BLOCK = 142; const WOODEN_BUTTON = 143; const MOB_HEAD_BLOCK = 144; const ANVIL = 145; const TRAPPED_CHEST = 146; const WEIGHTED_PRESSURE_PLATE_LIGHT = 147; const WEIGHTED_PRESSURE_PLATE_HEAVY = 148; const REDSTONE_COMPARATOR_BLOCK = 149; const REDSTONE_COMPARATOR_BLOCK_POWERED = 150; const DAYLIGHT_SENSOR = 151; const REDSTONE_BLOCK = 152; const NETHER_QUARTZ_ORE = 153; const HOPPER_BLOCK = 154; const QUARTZ_BLOCK = 155; const QUARTZ_STAIRS = 156; const DOUBLE_WOOD_SLAB = 157; const DOUBLE_WOODEN_SLAB = 157; const DOUBLE_WOOD_SLABS = 157; const DOUBLE_WOODEN_SLABS = 157; const WOOD_SLAB = 158; const WOODEN_SLAB = 158; const WOOD_SLABS = 158; const WOODEN_SLABS = 158; const STAINED_CLAY = 159; const STAINED_HARDENED_CLAY = 159; const STAINED_GLASS_PANE = 160; const LEAVES2 = 161; const LEAVE2 = 161; const WOOD2 = 162; const TRUNK2 = 162; const LOG2 = 162; const ACACIA_WOOD_STAIRS = 163; const ACACIA_WOODEN_STAIRS = 163; const DARK_OAK_WOOD_STAIRS = 164; const DARK_OAK_WOODEN_STAIRS = 164; const SLIME_BLOCK = 165; const IRON_TRAPDOOR = 167; const PRISMARINE = 168; const SEA_LANTERN = 169; const HAY_BALE = 170; const CARPET = 171; const HARDENED_CLAY = 172; const COAL_BLOCK = 173; const PACKED_ICE = 174; const DOUBLE_PLANT = 175; const STANDING_BANNER = 176; const WALL_BANNER = 177; const INVERTED_DAYLIGHT_SENSOR = 178; const RED_SANDSTONE = 179; const RED_SANDSTONE_STAIRS = 180; const DOUBLE_STONE_SLAB2 = 181; const DOUBLE_RED_SANDSTONE_SLAB = 181; const STONE_SLAB2 = 182; const RED_SANDSTONE_SLAB = 182; const FENCE_GATE_SPRUCE = 183; const FENCE_GATE_BIRCH = 184; const FENCE_GATE_JUNGLE = 185; const FENCE_GATE_DARK_OAK = 186; const FENCE_GATE_ACACIA = 187; const SPRUCE_DOOR_BLOCK = 193; const BIRCH_DOOR_BLOCK = 194; const JUNGLE_DOOR_BLOCK = 195; const ACACIA_DOOR_BLOCK = 196; const DARK_OAK_DOOR_BLOCK = 197; const GRASS_PATH = 198; const ITEM_FRAME_BLOCK = 199; const CHORUS_FLOWER = 200; const PURPUR_BLOCK = 201; const END_BRICKS = 206; const END_ROD = 208; const MAGMA = 213; const NETHER_WART_BLOCK_BLOCK = 214; const RED_NETHER_BRICK = 215; const BONE_BLOCK = 216; const SHULKER_BOX = 218; const CHORUS_PLANT = 240; const STAINED_GLASS = 241; const PODZOL = 243; const BEETROOT_BLOCK = 244; const STONECUTTER = 245; const GLOWING_OBSIDIAN = 246; const NETHER_REACTOR = 247; //Normal Item IDs const IRON_SHOVEL = 256; // const IRON_PICKAXE = 257; // const IRON_AXE = 258; // const FLINT_STEEL = 259; // const FLINT_AND_STEEL = 259; // const APPLE = 260; // const BOW = 261; const ARROW = 262; const COAL = 263; // const DIAMOND = 264; // const IRON_INGOT = 265; // const GOLD_INGOT = 266; // const IRON_SWORD = 267; const WOODEN_SWORD = 268; // const WOODEN_SHOVEL = 269; // const WOODEN_PICKAXE = 270; // const WOODEN_AXE = 271; // const STONE_SWORD = 272; const STONE_SHOVEL = 273; const STONE_PICKAXE = 274; const STONE_AXE = 275; const DIAMOND_SWORD = 276; const DIAMOND_SHOVEL = 277; const DIAMOND_PICKAXE = 278; const DIAMOND_AXE = 279; const STICK = 280; // const STICKS = 280; const BOWL = 281; // const MUSHROOM_STEW = 282; const GOLD_SWORD = 283; const GOLD_SHOVEL = 284; const GOLD_PICKAXE = 285; const GOLD_AXE = 286; const GOLDEN_SWORD = 283; const GOLDEN_SHOVEL = 284; const GOLDEN_PICKAXE = 285; const GOLDEN_AXE = 286; const STRING = 287; const FEATHER = 288; // const GUNPOWDER = 289; const WOODEN_HOE = 290; const STONE_HOE = 291; const IRON_HOE = 292; // const DIAMOND_HOE = 293; const GOLD_HOE = 294; const GOLDEN_HOE = 294; const SEEDS = 295; const WHEAT_SEEDS = 295; const WHEAT = 296; const BREAD = 297; const LEATHER_CAP = 298; const LEATHER_TUNIC = 299; const LEATHER_PANTS = 300; const LEATHER_BOOTS = 301; const CHAIN_HELMET = 302; const CHAIN_CHESTPLATE = 303; const CHAIN_LEGGINGS = 304; const CHAIN_BOOTS = 305; const IRON_HELMET = 306; const IRON_CHESTPLATE = 307; const IRON_LEGGINGS = 308; const IRON_BOOTS = 309; const DIAMOND_HELMET = 310; const DIAMOND_CHESTPLATE = 311; const DIAMOND_LEGGINGS = 312; const DIAMOND_BOOTS = 313; const GOLD_HELMET = 314; const GOLD_CHESTPLATE = 315; const GOLD_LEGGINGS = 316; const GOLD_BOOTS = 317; const FLINT = 318; const RAW_PORKCHOP = 319; const COOKED_PORKCHOP = 320; const PAINTING = 321; const GOLDEN_APPLE = 322; const SIGN = 323; const WOODEN_DOOR = 324; const BUCKET = 325; const MINECART = 328; const SADDLE = 329; const IRON_DOOR = 330; const REDSTONE = 331; const REDSTONE_DUST = 331; const SNOWBALL = 332; const BOAT = 333; const LEATHER = 334; const BRICK = 336; const CLAY = 337; const SUGARCANE = 338; const SUGAR_CANE = 338; const SUGAR_CANES = 338; const PAPER = 339; const BOOK = 340; const SLIMEBALL = 341; const MINECART_WITH_CHEST = 342; const EGG = 344; const COMPASS = 345; const FISHING_ROD = 346; const CLOCK = 347; const GLOWSTONE_DUST = 348; const RAW_FISH = 349; const COOKED_FISH = 350; const DYE = 351; const BONE = 352; const SUGAR = 353; const CAKE = 354; const BED = 355; const REDSTONE_REPEATER = 356; const COOKIE = 357; const FILLED_MAP = 358; const SHEARS = 359; const MELON = 360; const MELON_SLICE = 360; const PUMPKIN_SEEDS = 361; const MELON_SEEDS = 362; const RAW_BEEF = 363; const STEAK = 364; const COOKED_BEEF = 364; const RAW_CHICKEN = 365; const COOKED_CHICKEN = 366; const ROTTEN_FLESH = 367; const ENDER_PERL = 368; const BLAZE_ROD = 369; const GHAST_TEAR = 370; const GOLD_NUGGET = 371; const GOLDEN_NUGGET = 371; const NETHER_WART = 372; const POTION = 373; const GLASS_BOTTLE = 374; const SPIDER_EYE = 375; const FERMENTED_SPIDER_EYE = 376; const BLAZE_POWDER = 377; const MAGMA_CREAM = 378; const BREWING_STAND = 379; const CAULDRON = 380; const EYE_OF_ENDER = 381; const GLISTERING_MELON = 382; const SPAWN_EGG = 383; const BOTTLE_ENCHANTING = 384; const FIRE_CHARGE = 385; const WRITABLE_BOOK = 386; const WRITTEN_BOOK = 387; const EMERALD = 388; const ITEM_FRAME = 389; const FLOWER_POT = 390; const CARROT = 391; const CARROTS = 391; const POTATO = 392; const POTATOES = 392; const BAKED_POTATO = 393; const BAKED_POTATOES = 393; const POISONOUS_POTATO = 394; const EMPTY_MAP = 395; const GOLDEN_CARROT = 396; const MOB_HEAD = 397; const CARROT_ON_STICK = 398; const NETHER_STAR = 399; const PUMPKIN_PIE = 400; const ENCHANTING_BOOK = 403; const REDSTONE_COMPARATOR = 404; const NETHER_BRICK = 405; const QUARTZ = 406; const NETHER_QUARTZ = 406; const MINECART_WITH_TNT = 407; const MINECART_WITH_HOPPER = 408; const PRISMARINE_SHARD = 409; const HOPPER = 410; const RAW_RABBIT = 411; const COOKED_RABBIT = 412; const RABBIT_STEW = 413; const RABBIT_FOOT = 414; const RABBIT_HIDE = 415; const LEATHER_HORSE_ARMOR = 416; const IRON_HORSE_ARMOR = 417; const GOLDEN_HORSE_ARMOR = 418; const DIAMOND_HORSE_ARMOR = 419; const LEAD = 420; const NAME_TAG = 421; const PRISMARINE_CRYSTAL = 422; const RAW_MUTTON = 423; const COOKED_MUTTON = 424; const END_CRYSTAL = 426; const SPRUCE_DOOR = 427; const BIRCH_DOOR = 428; const JUNGLE_DOOR = 429; const ACACIA_DOOR = 430; const DARK_OAK_DOOR = 431; const CHORUS_FRUIT = 432; const POPPED_CHORUS_FRUIT = 433; const DRAGONS_BREATH = 437; const SPLASH_POTION = 438; const LINGERING_POTION = 441; const ELYTRA = 444; const SHULKER_SHELL = 445; const TOTEM_OF_UNDYING = 450; const IRON_NUGGET = 452; const BEETROOT = 457; const BEETROOT_SEEDS = 458; const BEETROOT_SEED = 458; const BEETROOT_SOUP = 459; const RAW_SALMON = 460; const CLOWNFISH = 461; const PUFFERFISH = 462; const COOKED_SALMON = 463; const ENCHANTED_GOLDEN_APPLE = 466; const END_PEARL = 468; const CAMERA = 498; const RECORD_13 = 500; const RECORD_CAT = 501; const RECORD_BLOCKS = 502; const RECORD_CHIRP = 503; const RECORD_FAR = 504; const RECORD_MALL = 505; const RECORD_MELLOHI = 506; const RECORD_STAL = 507; const RECORD_STRAD = 508; const RECORD_WARD = 509; const RECORD_11 = 510; const RECORD_WAIT = 511; protected static $names = [ 0 => "Air", 1 => "Stone", 2 => "Grass", 3 => "Dirt", 4 => "Cobblestone", 5 => "Plank", 6 => "Sapling", 7 => "Bedrock", 8 => "Water", 9 => "Still Water", 10 => "Lava", 11 => "Still Lava", 12 => "Sand", 13 => "Gravel", 14 => "Gold Ore", 15 => "Iron Ore", 16 => "Coal Ore", 17 => "Wood", 18 => "Leaves", 19 => "Sponge", 20 => "Glass", 21 => "Lapis Ore", 22 => "Lapis Block", 24 => "Sandstone", 26 => "Bed", 30 => "Cobweb", 31 => "Tall Grass", 32 => "Bush", 35 => "Wool", 37 => "Dandelion", 38 => "Red Flower", 39 => "Brown Mushroom", 40 => "Red Mushroom", 41 => "Gold Block", 42 => "Iron Block", 43 => "Double Slab", 44 => "Slab", 45 => "Bricks", 46 => "TNT", 47 => "Bookshelf", 48 => "Moss Stone", 49 => "Obsidian", 50 => "Torch", 51 => "Fire", 52 => "Monster Spawner", 53 => "Wooden Stairs", 54 => "Chest", 56 => "Diamond Ore", 57 => "Diamond Block", 58 => "Crafting Table", 59 => "Wheat Block", 60 => "Farmland", 61 => "Furnace", 62 => "Burning Furnace", 63 => "Sign Post", 64 => "Door", 65 => "Ladder", 66 => "Rail", 67 => "Cobble Stairs", 68 => "Wall Sign", 71 => "Iron Door", 73 => "Redstone Ore", 74 => "Glowing Redstone Ore", 75 => "Redstone Torch", 76 => "Glowing Redstone Torch", 78 => "Snow", 79 => "Ice", 80 => "Snow Block", 81 => "Cactus", 82 => "Clay Block", 83 => "Sugarcane Block", 85 => "Fence", 86 => "Pumpkin Block", 87 => "Netherrack", 88 => "Soul Sand", 89 => "Glowstone", 90 => "Portal", 91 => "Jack-O'-Lantern", 92 => "Cake Block", 96 => "Trapdoor", 98 => "Stone Bricks", 99 => "Brown Mushroom Block", 100 => "Red Mushroom Block", 101 => "Iron Bar", 102 => "Glass Panel", 103 => "Melon BLock", 104 => "Pumpkin Stem", 106 => "Vine", 107 => "Fence Gate", 108 => "Brick Stairs", 109 => "Stone Brick Stairs", 110 => "Mycelium", 111 => "Water Lily", 112 => "Nether Brick", 113 => "Nether Brick Fence", 114 => "Nether Brick Stairs", 116 => "Enchantment Table", 117 => "Brewing Stand", 118 => "Cauldron Block", 120 => "End Portal", 121 => "End Stone", self::DRAGON_EGG => 'Dragon Egg', 123 => "Redstone Lamp", 124 => "Redstone Lamp Active", 125 => "Dropper", 126 => "Activator Rail", 127 => "Cocoa", 128 => "Sendstone Stairs", 129 => "Emerald Ore", self::ENDER_CHEST => 'Ender Chest', 131 => "Tripwire Hook", 132 => "Tripwire", 133 => "Emerald Block", 134 => "Spruce Wood Stairs", 135 => "Birch Wood Stairs", 136 => "Jungle Wood Stairs", 138 => "Beacon", 139 => "Cobblestone Wall", 140 => "Flower Pot", 141 => "Carrot Block", 142 => "Potato Block", 143 => "Wooden Button", 144 => "Mob Head", 145 => "Anvil", 146 => "Trapped Chest", 147 => "Weighted Pressure Plate Light", 148 => "Weighted Pressure Plate Heavy", 149 => "Redstone Comparator", 150 => "Redstone Comparator Powered", 151 => "Daylight Sensor", 152 => "Redstone Block", 153 => "Nether Quartz Ore", 154 => "Hopper", 155 => "Quartz Block", 156 => "Quartz Stairs", 157 => "Double Wood Slab", 158 => "Wooden Slab", 159 => "Stained Clay", self::STAINED_GLASS_PANE => 'Stained Glass Pane', 161 => "Leaves2", 162 => "Wood2", 163 => "Acacia Wood Stairs", 164 => "Dark Oak Wood Stairs", 165 => "Slime Block", 167 => "Iron Trapdoor", 170 => "Hay Bale", 171 => "Carpet", 172 => "Hardened CLay", 173 => "Coal BLock", 175 => "Double Plant", 178 => "Inverted Daylight Sensor", 179 => "Red Sandstone", 180 => "Red Sandstone Stairs", 181 => "Double Red Sandstone Slab", 182 => "Red Sandstone Slab", 183 => "Fence Gate Spruce", 184 => "Fence Gate Birch", 185 => "Fence Gate Jungle", 186 => "Fence Gate Dark Oak", 187 => "Fence Gate Acacia", 193 => "Wood Door Block", 194 => "Birch Door", 195 => "Jungle Door", 196 => "Acacia Door", 197 => "Dark Oak Door", 198 => "Grass Path", self::CHORUS_FLOWER => 'Chorus Flower', self::PURPUR_BLOCK => 'Purpur Block', self::END_BRICKS => 'End Brick', self::END_ROD => 'End Rod', self::CHORUS_PLANT => 'Chorus Plant', self::STAINED_GLASS => 'Stained Glass', 243 => "Podzol", 244 => "Beetroot Block", 245 => "Stonecutter", 246 => "Glowing Obsidian", 247 => "Nether Reactor", 256 => "Iron Shovel", 257 => "Iron Pickaxe", 258 => "Iron Axe", 259 => "Flint and Steel", 260 => "Apple", 261 => "Bow", 262 => "Arrow", 263 => "Coal", 264 => "Diamond", 265 => "Iron Ingot", 266 => "Gold Ingot", 267 => "Iron Sword", 268 => "Wooden Sword", 269 => "Wooden Shovel", 270 => "Wooden Pickaxe", 271 => "Wooden Axe", 272 => "Stone Sword", 273 => "Stone Shovel", 274 => "Stone Pickaxe", 275 => "Stone Axe", 276 => "Diamond Sword", 277 => "Diamond Shovel", 278 => "Diamond Pickaxe", 279 => "Diamond Axe", 280 => "Stick", 281 => "Bowl", 282 => "Mushroom Stew", 283 => "Gold Sword", 284 => "Gold Shovel", 285 => "Gold Pickaxe", 286 => "Gold Axe", 287 => "String", 288 => "Feather", 289 => "Gunpowder", 290 => "Wooden Hoe", 291 => "Stone Hoe", 292 => "Iron Hoe", 293 => "Diamond Hoe", 294 => "Gold Hoe", 295 => "Wheat Seed", 296 => "Wheat", 297 => "Bread", 298 => "Leather Cap", 299 => "Leather Tunic", 300 => "Leather Pants", 301 => "Leather Boots", 302 => "Chain Helmet", 303 => "Chain Chestplate", 304 => "Chain Leggins", 305 => "Chain Boots", 306 => "Iron Helmet", 307 => "Iron Chestplate", 308 => "Iron Leggins", 309 => "Iron Boots", 310 => "Diamond Helmet", 311 => "Diamond Chestplate", 312 => "Diamond Leggins", 313 => "Diamond Boots", 314 => "Gold Helmet", 315 => "Gold Chestplate", 316 => "Gold Leggins", 317 => "Gold Boots", 318 => "Flint", 319 => "Raw Porkchop", 320 => "Cooked Porkchop", 321 => "Painting", 322 => "Golden Apple", 323 => "Sign", 324 => "Wooden Door", 325 => "Bucket", 328 => "Minecart", 330 => "Iron Door", 331 => "Redstone", 332 => "Snowball", 334 => "Leather", 336 => "Bricks", 337 => "Clay", 338 => "Sugarcane", 339 => "Paper", 340 => "Book", 341 => "Slimeball", 344 => "Egg", 345 => "Compass", 346 => "Compass", 347 => "Clock", 348 => "Glowstone Dust", 349 => "Raw Fish", 350 => "Cooked Fish", 351 => "Dye", 352 => "Bone", 353 => "Sugar", 354 => "Cake", 355 => "Bed", 357 => "Cookie", 359 => "Shears", 360 => "Melon", 361 => "Pumpkin Seed", 362 => "Melon Seed", 363 => "Raw Beef", 364 => "Steak", 365 => "Raw Chicken", 366 => "Cooked Chicken", 369 => "Blaze Rod", 371 => "Gold Nugget", 373 => "Potion", 377 => "Blaze powder", 378 => "Magma Cream", 383 => "Spawn Egg", self::WRITABLE_BOOK => "Book & Quill", self::WRITTEN_BOOK => "Written Book", 388 => "Emerald", 390 => "Flower Pot", 391 => "Carrot", 392 => "Potato", 393 => "Baked Potato", 394 => "Poisonous Potato", 395 => "Empty Map", 396 => "Golden Carrot", 397 => "Mob Head", 398 => "Carrot on a Stick", 400 => "Pumpkin Pie", 403 => "Enchanted Book", 404 => "Redstone Comparator", 405 => "Nether Bricks", 406 => "Quartz", 407 => "Minecart with TNT", 408 => "Minecart with Hopper", 410 => "Hopper", 411 => "Raw Rabbit", 412 => "Cooked Rabbit", 414 => "Rabbit's Foot", 415 => "Rabbit Hide", 416 => "Leather Horse Armor", 417 => "Iron Horse Armor", 418 => "Golden Horse Armor", 419 => "Diamond Horse Armor", 420 => "Lead", 421 => "Name Tag", self::PRISMARINE_CRYSTAL => "Prismarine Crystal", 423 => "Raw Mutton", 424 => "Cooked Mutton", 427 => "Spruce Door", 428 => "Birch Door", 429 => "Jungle Door", 430 => "Acacia Door", 431 => "Dark Oak Door", 431 => "Chorus Fruit", 438 => "Splash Potion", 457 => "Beetroot", 458 => "Beetroot Seed", 459 => "Beetroot Soup", 460 => "Raw Salmon", 461 => "Clownfish", 462 => "Pufferfish", 463 => "Cooked Salmon", 466 => "Enchanted Golden Apple", 498 => "Camera", ]; /** @var \SplFixedArray */ public static $list = null; public static $food = null; protected $block; protected $id; protected $meta; private $tags = ""; private $cachedNBT = null; public $count; protected $durability = 0; protected $name; protected $obtainTime = 0; protected $canPlaceOnBlocks = []; protected $canDestroyBlocks = []; public function canBeActivated(){ return false; } public static function init(){ if(self::$list === null){ self::$list = new \SplFixedArray(65536); self::$list[self::SUGARCANE] = Sugarcane::class; self::$list[self::WHEAT_SEEDS] = WheatSeeds::class; self::$list[self::PUMPKIN_SEEDS] = PumpkinSeeds::class; self::$list[self::MELON_SEEDS] = MelonSeeds::class; self::$list[self::MUSHROOM_STEW] = MushroomStew::class; self::$list[self::BEETROOT_SOUP] = BeetrootSoup::class; self::$list[self::CARROT] = Carrot::class; self::$list[self::POTATO] = Potato::class; self::$list[self::BEETROOT_SEEDS] = BeetrootSeeds::class; self::$list[self::SIGN] = Sign::class; self::$list[self::WOODEN_DOOR] = WoodenDoor::class; self::$list[self::BUCKET] = Bucket::class; self::$list[self::IRON_DOOR] = IronDoor::class; self::$list[self::CAKE] = Cake::class; self::$list[self::BED] = Bed::class; self::$list[self::PAINTING] = Painting::class; self::$list[self::COAL] = Coal::class; self::$list[self::APPLE] = Apple::class; self::$list[self::SPAWN_EGG] = SpawnEgg::class; self::$list[self::DIAMOND] = Diamond::class; self::$list[self::STICK] = Stick::class; self::$list[self::SNOWBALL] = Snowball::class; self::$list[self::EGG] = Egg::class; self::$list[self::BOWL] = Bowl::class; self::$list[self::FEATHER] = Feather::class; self::$list[self::BRICK] = Brick::class; self::$list[self::LEATHER_CAP] = LeatherCap::class; self::$list[self::LEATHER_TUNIC] = LeatherTunic::class; self::$list[self::LEATHER_PANTS] = LeatherPants::class; self::$list[self::LEATHER_BOOTS] = LeatherBoots::class; self::$list[self::CHAIN_HELMET] = ChainHelmet::class; self::$list[self::CHAIN_CHESTPLATE] = ChainChestplate::class; self::$list[self::CHAIN_LEGGINGS] = ChainLeggings::class; self::$list[self::CHAIN_BOOTS] = ChainBoots::class; self::$list[self::IRON_HELMET] = IronHelmet::class; self::$list[self::IRON_CHESTPLATE] = IronChestplate::class; self::$list[self::IRON_LEGGINGS] = IronLeggings::class; self::$list[self::IRON_BOOTS] = IronBoots::class; self::$list[self::GOLD_HELMET] = GoldHelmet::class; self::$list[self::GOLD_CHESTPLATE] = GoldChestplate::class; self::$list[self::GOLD_LEGGINGS] = GoldLeggings::class; self::$list[self::GOLD_BOOTS] = GoldBoots::class; self::$list[self::DIAMOND_HELMET] = DiamondHelmet::class; self::$list[self::DIAMOND_CHESTPLATE] = DiamondChestplate::class; self::$list[self::DIAMOND_LEGGINGS] = DiamondLeggings::class; self::$list[self::DIAMOND_BOOTS] = DiamondBoots::class; self::$list[self::IRON_SWORD] = IronSword::class; self::$list[self::IRON_INGOT] = IronIngot::class; self::$list[self::GOLD_INGOT] = GoldIngot::class; self::$list[self::IRON_SHOVEL] = IronShovel::class; self::$list[self::IRON_PICKAXE] = IronPickaxe::class; self::$list[self::IRON_AXE] = IronAxe::class; self::$list[self::IRON_HOE] = IronHoe::class; self::$list[self::DIAMOND_SWORD] = DiamondSword::class; self::$list[self::DIAMOND_SHOVEL] = DiamondShovel::class; self::$list[self::DIAMOND_PICKAXE] = DiamondPickaxe::class; self::$list[self::DIAMOND_AXE] = DiamondAxe::class; self::$list[self::DIAMOND_HOE] = DiamondHoe::class; self::$list[self::GOLD_SWORD] = GoldSword::class; self::$list[self::GOLD_SHOVEL] = GoldShovel::class; self::$list[self::GOLD_PICKAXE] = GoldPickaxe::class; self::$list[self::GOLD_AXE] = GoldAxe::class; self::$list[self::GOLD_HOE] = GoldHoe::class; self::$list[self::STONE_SWORD] = StoneSword::class; self::$list[self::STONE_SHOVEL] = StoneShovel::class; self::$list[self::STONE_PICKAXE] = StonePickaxe::class; self::$list[self::STONE_AXE] = StoneAxe::class; self::$list[self::STONE_HOE] = StoneHoe::class; self::$list[self::WOODEN_SWORD] = WoodenSword::class; self::$list[self::WOODEN_SHOVEL] = WoodenShovel::class; self::$list[self::WOODEN_PICKAXE] = WoodenPickaxe::class; self::$list[self::WOODEN_AXE] = WoodenAxe::class; self::$list[self::WOODEN_HOE] = WoodenHoe::class; self::$list[self::FLINT_STEEL] = FlintSteel::class; self::$list[self::SHEARS] = Shears::class; self::$list[self::BOW] = Bow::class; self::$list[self::RAW_FISH] = Fish::class; self::$list[self::COOKED_FISH] = CookedFish::class; self::$list[self::MOB_HEAD] = MobHead::class; self::$list[self::BLAZE_POWDER] = BlazePowder::class; self::$list[self::FLOWER_POT] = FlowerPot::class; self::$list[self::ELYTRA] = Elytra::class; self::$list[self::PRISMARINE_CRYSTAL] = PrismarineCrystal::class; self::$list[self::POTION] = Potion::class; self::$list[self::BOTTLE_ENCHANTING] = BottleOEnchanting::class; self::$list[self::WRITABLE_BOOK] = WritableBook::class; self::$list[self::SPRUCE_DOOR] = SpruceDoor::class; self::$list[self::BIRCH_DOOR] = BirchDoor::class; self::$list[self::JUNGLE_DOOR] = JungleDoor::class; self::$list[self::ACACIA_DOOR] = AcaciaDoor::class; self::$list[self::DARK_OAK_DOOR] = DarkOakDoor::class; self::$list[self::SPLASH_POTION] = SplashPotion::class; // update for 1.0 self::$list[self::CHORUS_FRUIT] = ChorusFruit::class; self::$list[self::TOTEM_OF_UNDYING] = TotemOfUndying::class; // for($i = 0; $i < 256; ++$i){ // if(Block::$list[$i] !== null){ // self::$list[$i] = Block::$list[$i]; // } // } } self::initCreativeItems(); self::initFood(); } public static function registerItem($id, $class) { if (isset(self::$list[$id]) && self::$list[$id] == $class) { return; } self::$list[$id] = $class; foreach (self::$creative as $index => $itemData) { $item = $itemData['item']; if ($item->getId() == $id) { self::$creative[$index] = ['item' => Item::get($id, $item->getDamage()), 'group' => self::CREATIVE_GROUP_NONE]; } } } const CREATIVE_GROUP_NONE = 0xffffffff; const CREATIVE_GROUP_PLANKS = 0; const CREATIVE_GROUP_WALLS = 1; const CREATIVE_GROUP_FENCE = 2; const CREATIVE_GROUP_FENCEGATE = 3; const CREATIVE_GROUP_STAIRS = 4; const CREATIVE_GROUP_DOOR = 5; const CREATIVE_GROUP_TRAPDOOR = 6; const CREATIVE_GROUP_GLASS = 7; const CREATIVE_GROUP_GLASSPANE = 8; const CREATIVE_GROUP_SLAB = 9; const CREATIVE_GROUP_STONEBRICK = 10; const CREATIVE_GROUP_SANDSTONE = 11; const CREATIVE_GROUP_WOOL = 12; const CREATIVE_GROUP_WOOLCARPET = 13; const CREATIVE_GROUP_STAINEDCLAY = 14; const CREATIVE_GROUP_ORE = 15; const CREATIVE_GROUP_STONE = 16; const CREATIVE_GROUP_LOGS = 17; const CREATIVE_GROUP_LEAVES = 18; const CREATIVE_GROUP_SAPLING = 19; const CREATIVE_GROUP_SEED = 20; const CREATIVE_GROUP_CROP = 21; const CREATIVE_GROUP_GRASS = 22; const CREATIVE_GROUP_FLOWER = 23; const CREATIVE_GROUP_DYE = 24; const CREATIVE_GROUP_MUSHROOM = 25; const CREATIVE_GROUP_MOBEGG = 26; const CREATIVE_GROUP_HELMET = 27; const CREATIVE_GROUP_CHESTPLATE = 28; const CREATIVE_GROUP_LEGGINGS = 29; const CREATIVE_GROUP_BOOTS = 30; const CREATIVE_GROUP_SWORD = 31; const CREATIVE_GROUP_AXE = 32; const CREATIVE_GROUP_PICKAXE = 33; const CREATIVE_GROUP_SHOVEL = 34; const CREATIVE_GROUP_HOE = 35; const CREATIVE_GROUP_ARROW = 36; const CREATIVE_GROUP_COOKEDFOOD = 37; const CREATIVE_GROUP_MISCFOOD = 38; const CREATIVE_GROUP_BED = 39; const CREATIVE_GROUP_ANVIL = 40; const CREATIVE_GROUP_CHEST = 41; const CREATIVE_GROUP_SIGN = 42; const CREATIVE_GROUP_RAIL = 43; const CREATIVE_GROUP_MINECART = 44; private static $creativeGroupData = [ self::CREATIVE_GROUP_PLANKS => ['name' => 'itemGroup.name.planks', 'item' => self::PLANK], self::CREATIVE_GROUP_WALLS => ['name' => 'itemGroup.name.walls', 'item' => self::COBBLESTONE_WALL], self::CREATIVE_GROUP_FENCE => ['name' => 'itemGroup.name.fence', 'item' => self::FENCE], self::CREATIVE_GROUP_FENCEGATE => ['name' => 'itemGroup.name.fenceGate', 'item' => self::FENCE_GATE], self::CREATIVE_GROUP_STAIRS => ['name' => 'itemGroup.name.stairs', 'item' => self::COBBLE_STAIRS], self::CREATIVE_GROUP_DOOR => ['name' => 'itemGroup.name.door', 'item' => self::WOODEN_DOOR], self::CREATIVE_GROUP_TRAPDOOR => ['name' => 'itemGroup.name.trapdoor', 'item' => self::TRAPDOOR], self::CREATIVE_GROUP_GLASS => ['name' => 'itemGroup.name.glass', 'item' => self::GLASS], self::CREATIVE_GROUP_GLASSPANE => ['name' => 'itemGroup.name.glassPane', 'item' => self::GLASS_PANE], self::CREATIVE_GROUP_SLAB => ['name' => 'itemGroup.name.slab', 'item' => self::SLAB], self::CREATIVE_GROUP_STONEBRICK => ['name' => 'itemGroup.name.stoneBrick', 'item' => self::STONE_BRICK], self::CREATIVE_GROUP_SANDSTONE => ['name' => 'itemGroup.name.sandstone', 'item' => self::SANDSTONE], self::CREATIVE_GROUP_WOOL => ['name' => 'itemGroup.name.wool', 'item' => self::WOOL], self::CREATIVE_GROUP_WOOLCARPET => ['name' => 'itemGroup.name.woolCarpet', 'item' => self::CARPET], self::CREATIVE_GROUP_STAINEDCLAY => ['name' => 'itemGroup.name.stainedClay', 'item' => self::CLAY_BLOCK], self::CREATIVE_GROUP_ORE => ['name' => 'itemGroup.name.ore', 'item' => self::IRON_ORE], self::CREATIVE_GROUP_STONE => ['name' => 'itemGroup.name.stone', 'item' => self::STONE], self::CREATIVE_GROUP_LOGS => ['name' => 'itemGroup.name.log', 'item' => self::LOG], self::CREATIVE_GROUP_LEAVES => ['name' => 'itemGroup.name.wood', 'item' => self::LEAVES], self::CREATIVE_GROUP_SAPLING => ['name' => 'itemGroup.name.sapling', 'item' => self::SAPLING], self::CREATIVE_GROUP_SEED => ['name' => 'itemGroup.name.seed', 'item' => self::SEEDS], self::CREATIVE_GROUP_CROP => ['name' => 'itemGroup.name.crop', 'item' => self::WHEAT], self::CREATIVE_GROUP_GRASS => ['name' => 'itemGroup.name.grass', 'item' => self::TALL_GRASS], self::CREATIVE_GROUP_FLOWER => ['name' => 'itemGroup.name.flower', 'item' => self::DANDELION], self::CREATIVE_GROUP_DYE => ['name' => 'itemGroup.name.dye', 'item' => self::DYE], self::CREATIVE_GROUP_MUSHROOM => ['name' => 'itemGroup.name.mushroom', 'item' => self::BROWN_MUSHROOM], self::CREATIVE_GROUP_MOBEGG => ['name' => 'itemGroup.name.mobEgg', 'item' => self::SPAWN_EGG], self::CREATIVE_GROUP_HELMET => ['name' => 'itemGroup.name.helmet', 'item' => self::LEATHER_CAP], self::CREATIVE_GROUP_CHESTPLATE => ['name' => 'itemGroup.name.chestplate', 'item' => self::LEATHER_TUNIC], self::CREATIVE_GROUP_LEGGINGS => ['name' => 'itemGroup.name.leggings', 'item' => self::LEATHER_PANTS], self::CREATIVE_GROUP_BOOTS => ['name' => 'itemGroup.name.boots', 'item' => self::LEATHER_BOOTS], self::CREATIVE_GROUP_SWORD => ['name' => 'itemGroup.name.sword', 'item' => self::WOODEN_SWORD], self::CREATIVE_GROUP_AXE => ['name' => 'itemGroup.name.axe', 'item' => self::WOODEN_AXE], self::CREATIVE_GROUP_PICKAXE => ['name' => 'itemGroup.name.pickaxe', 'item' => self::WOODEN_PICKAXE], self::CREATIVE_GROUP_SHOVEL => ['name' => 'itemGroup.name.shovel', 'item' => self::WOODEN_SHOVEL], self::CREATIVE_GROUP_HOE => ['name' => 'itemGroup.name.hoe', 'item' => self::WOODEN_HOE], self::CREATIVE_GROUP_ARROW => ['name' => 'itemGroup.name.arrow', 'item' => self::ARROW], self::CREATIVE_GROUP_COOKEDFOOD => ['name' => 'itemGroup.name.cookedFood', 'item' => self::COOKED_CHICKEN], self::CREATIVE_GROUP_MISCFOOD => ['name' => 'itemGroup.name.miscFood', 'item' => self::BREAD], self::CREATIVE_GROUP_BED => ['name' => 'itemGroup.name.bed', 'item' => self::BED], self::CREATIVE_GROUP_ANVIL => ['name' => 'itemGroup.name.anvil', 'item' => self::ANVIL], self::CREATIVE_GROUP_CHEST => ['name' => 'itemGroup.name.chest', 'item' => self::CHEST], self::CREATIVE_GROUP_SIGN => ['name' => 'itemGroup.name.sign', 'item' => self::SIGN], self::CREATIVE_GROUP_RAIL => ['name' => 'itemGroup.name.rail', 'item' => self::RAIL], self::CREATIVE_GROUP_MINECART => ['name' => 'itemGroup.name.minecart', 'item' => self::MINECART], ]; private static $creative = []; private static function initCreativeItems(){ self::clearCreativeItems(); self::addCreativeItem(Item::get(Item::WOODEN_PLANKS, 0), self::CREATIVE_GROUP_PLANKS); self::addCreativeItem(Item::get(Item::WOODEN_PLANKS, 1), self::CREATIVE_GROUP_PLANKS); self::addCreativeItem(Item::get(Item::WOODEN_PLANKS, 2), self::CREATIVE_GROUP_PLANKS); self::addCreativeItem(Item::get(Item::WOODEN_PLANKS, 3), self::CREATIVE_GROUP_PLANKS); self::addCreativeItem(Item::get(Item::WOODEN_PLANKS, 4), self::CREATIVE_GROUP_PLANKS); self::addCreativeItem(Item::get(Item::WOODEN_PLANKS, 5), self::CREATIVE_GROUP_PLANKS); self::addCreativeItem(Item::get(Item::COBBLESTONE_WALL, 0), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::COBBLESTONE_WALL, 1), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 2), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 3), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 4), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 5), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 6), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 7), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 8), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 9), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 10), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 11), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 12), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::STONE_WALL, 13), self::CREATIVE_GROUP_WALLS); self::addCreativeItem(Item::get(Item::FENCE, 0), self::CREATIVE_GROUP_FENCE); self::addCreativeItem(Item::get(Item::FENCE, 1), self::CREATIVE_GROUP_FENCE); self::addCreativeItem(Item::get(Item::FENCE, 2), self::CREATIVE_GROUP_FENCE); self::addCreativeItem(Item::get(Item::FENCE, 3), self::CREATIVE_GROUP_FENCE); self::addCreativeItem(Item::get(Item::FENCE, 4), self::CREATIVE_GROUP_FENCE); self::addCreativeItem(Item::get(Item::FENCE, 5), self::CREATIVE_GROUP_FENCE); self::addCreativeItem(Item::get(Item::NETHER_BRICK_FENCE, 0), self::CREATIVE_GROUP_FENCE); self::addCreativeItem(Item::get(Item::FENCE_GATE, 0), self::CREATIVE_GROUP_FENCEGATE); self::addCreativeItem(Item::get(Item::FENCE_GATE_SPRUCE, 0), self::CREATIVE_GROUP_FENCEGATE); self::addCreativeItem(Item::get(Item::FENCE_GATE_BIRCH, 0), self::CREATIVE_GROUP_FENCEGATE); self::addCreativeItem(Item::get(Item::FENCE_GATE_DARK_OAK, 0), self::CREATIVE_GROUP_FENCEGATE); self::addCreativeItem(Item::get(Item::FENCE_GATE_JUNGLE, 0), self::CREATIVE_GROUP_FENCEGATE); self::addCreativeItem(Item::get(Item::FENCE_GATE_ACACIA, 0), self::CREATIVE_GROUP_FENCEGATE); self::addCreativeItem(Item::get(Item::COBBLESTONE_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::OAK_WOODEN_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::SPRUCE_WOODEN_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::BIRCH_WOODEN_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::JUNGLE_WOODEN_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::ACACIA_WOODEN_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::DARK_OAK_WOODEN_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::BRICK_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::STONE_BRICK_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::NETHER_BRICKS_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::SANDSTONE_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::QUARTZ_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::RED_SANDSTONE_STAIRS, 0), self::CREATIVE_GROUP_STAIRS); self::addCreativeItem(Item::get(Item::WOODEN_DOOR, 0), self::CREATIVE_GROUP_DOOR); self::addCreativeItem(Item::get(Item::TRAPDOOR, 0), self::CREATIVE_GROUP_TRAPDOOR); self::addCreativeItem(Item::get(Item::IRON_BARS, 0)); self::addCreativeItem(Item::get(Item::GLASS, 0), self::CREATIVE_GROUP_GLASS); self::addColoredCreativeItem(self::STAINED_GLASS, self::CREATIVE_GROUP_GLASS); self::addCreativeItem(Item::get(Item::GLASS_PANE, 0), self::CREATIVE_GROUP_GLASSPANE); self::addColoredCreativeItem(self::STAINED_GLASS_PANE, self::CREATIVE_GROUP_GLASSPANE); self::addCreativeItem(Item::get(Item::LADDER, 0)); self::addCreativeItem(Item::get(Item::SLAB, 0), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::SLAB, 3), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::WOODEN_SLAB, 0), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::WOODEN_SLAB, 1), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::WOODEN_SLAB, 2), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::WOODEN_SLAB, 3), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::WOODEN_SLAB, 4), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::WOODEN_SLAB, 5), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::SLAB, 4), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::SLAB, 5), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::SLAB, 6), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::SLAB, 1), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::SLAB, 7), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::STONE_SLAB2, 0), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::STONE_SLAB2, 1), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::STONE_SLAB2, 2), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::STONE_SLAB2, 3), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::STONE_SLAB2, 4), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::STONE_SLAB2, 5), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::STONE_SLAB2, 6), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::STONE_SLAB2, 7), self::CREATIVE_GROUP_SLAB); self::addCreativeItem(Item::get(Item::BRICKS, 0)); self::addCreativeItem(Item::get(Item::STONE_BRICKS, 0), self::CREATIVE_GROUP_STONEBRICK); self::addCreativeItem(Item::get(Item::STONE_BRICKS, 1), self::CREATIVE_GROUP_STONEBRICK); self::addCreativeItem(Item::get(Item::STONE_BRICKS, 2), self::CREATIVE_GROUP_STONEBRICK); self::addCreativeItem(Item::get(Item::STONE_BRICKS, 3), self::CREATIVE_GROUP_STONEBRICK); self::addCreativeItem(Item::get(Item::END_BRICKS, 0), self::CREATIVE_GROUP_STONEBRICK); self::addCreativeItem(Item::get(Item::PRISMARINE_CRYSTAL, 0)); self::addCreativeItem(Item::get(Item::COBBLESTONE, 0)); self::addCreativeItem(Item::get(Item::MOSS_STONE, 0)); self::addCreativeItem(Item::get(Item::SANDSTONE, 0), self::CREATIVE_GROUP_SANDSTONE); self::addCreativeItem(Item::get(Item::SANDSTONE, 1), self::CREATIVE_GROUP_SANDSTONE); self::addCreativeItem(Item::get(Item::SANDSTONE, 2), self::CREATIVE_GROUP_SANDSTONE); self::addCreativeItem(Item::get(Item::COAL_BLOCK, 0)); self::addCreativeItem(Item::get(Item::GOLD_BLOCK, 0)); self::addCreativeItem(Item::get(Item::IRON_BLOCK, 0)); self::addCreativeItem(Item::get(Item::EMERALD_BLOCK, 0)); self::addCreativeItem(Item::get(Item::DIAMOND_BLOCK, 0)); self::addCreativeItem(Item::get(Item::LAPIS_BLOCK, 0)); self::addCreativeItem(Item::get(Item::QUARTZ_BLOCK, 0)); self::addCreativeItem(Item::get(Item::QUARTZ_BLOCK, 1)); self::addCreativeItem(Item::get(Item::QUARTZ_BLOCK, 2)); self::addCreativeItem(Item::get(Item::SLIME_BLOCK, 0)); self::addCreativeItem(Item::get(Item::HAY_BALE, 0)); self::addCreativeItem(Item::get(Item::BONE_BLOCK, 0)); self::addCreativeItem(Item::get(Item::NETHER_BRICKS, 0)); self::addCreativeItem(Item::get(Item::RED_NETHER_BRICK, 0)); self::addColoredCreativeItem(Item::WOOL, self::CREATIVE_GROUP_WOOL); self::addColoredCreativeItem(Item::CARPET, self::CREATIVE_GROUP_WOOLCARPET); self::addCreativeItem(Item::get(Item::CLAY_BLOCK, 0), self::CREATIVE_GROUP_STAINEDCLAY); self::addCreativeItem(Item::get(Item::HARDENED_CLAY, 0), self::CREATIVE_GROUP_STAINEDCLAY); self::addColoredCreativeItem(Item::STAINED_CLAY, self::CREATIVE_GROUP_STAINEDCLAY); self::addCreativeItem(Item::get(Item::PURPUR_BLOCK, 0)); self::addCreativeItem(Item::get(Item::DIRT, 0)); self::addCreativeItem(Item::get(Item::GRASS, 0)); self::addCreativeItem(Item::get(Item::PODZOL, 0)); self::addCreativeItem(Item::get(Item::MYCELIUM, 0)); self::addCreativeItem(Item::get(Item::STONE, 0), self::CREATIVE_GROUP_STONE); self::addCreativeItem(Item::get(Item::STONE, 1), self::CREATIVE_GROUP_STONE); self::addCreativeItem(Item::get(Item::STONE, 2), self::CREATIVE_GROUP_STONE); self::addCreativeItem(Item::get(Item::STONE, 3), self::CREATIVE_GROUP_STONE); self::addCreativeItem(Item::get(Item::STONE, 4), self::CREATIVE_GROUP_STONE); self::addCreativeItem(Item::get(Item::STONE, 5), self::CREATIVE_GROUP_STONE); self::addCreativeItem(Item::get(Item::STONE, 6), self::CREATIVE_GROUP_STONE); self::addCreativeItem(Item::get(Item::IRON_ORE, 0), self::CREATIVE_GROUP_ORE); self::addCreativeItem(Item::get(Item::GOLD_ORE, 0), self::CREATIVE_GROUP_ORE); self::addCreativeItem(Item::get(Item::DIAMOND_ORE, 0), self::CREATIVE_GROUP_ORE); self::addCreativeItem(Item::get(Item::LAPIS_ORE, 0), self::CREATIVE_GROUP_ORE); self::addCreativeItem(Item::get(Item::REDSTONE_ORE, 0), self::CREATIVE_GROUP_ORE); self::addCreativeItem(Item::get(Item::COAL_ORE, 0), self::CREATIVE_GROUP_ORE); self::addCreativeItem(Item::get(Item::EMERALD_ORE, 0), self::CREATIVE_GROUP_ORE); self::addCreativeItem(Item::get(Item::GRAVEL, 0)); self::addCreativeItem(Item::get(Item::SAND, 0)); self::addCreativeItem(Item::get(Item::SAND, 1)); self::addCreativeItem(Item::get(Item::CACTUS, 0)); self::addCreativeItem(Item::get(Item::TRUNK, 0), self::CREATIVE_GROUP_LOGS); self::addCreativeItem(Item::get(Item::TRUNK, 1), self::CREATIVE_GROUP_LOGS); self::addCreativeItem(Item::get(Item::TRUNK, 2), self::CREATIVE_GROUP_LOGS); self::addCreativeItem(Item::get(Item::TRUNK, 3), self::CREATIVE_GROUP_LOGS); self::addCreativeItem(Item::get(Item::TRUNK2, 0), self::CREATIVE_GROUP_LOGS); self::addCreativeItem(Item::get(Item::TRUNK2, 1), self::CREATIVE_GROUP_LOGS); self::addCreativeItem(Item::get(Item::LEAVES, 0), self::CREATIVE_GROUP_LEAVES); self::addCreativeItem(Item::get(Item::LEAVES, 1), self::CREATIVE_GROUP_LEAVES); self::addCreativeItem(Item::get(Item::LEAVES, 2), self::CREATIVE_GROUP_LEAVES); self::addCreativeItem(Item::get(Item::LEAVES, 3), self::CREATIVE_GROUP_LEAVES); self::addCreativeItem(Item::get(Item::LEAVES2, 0), self::CREATIVE_GROUP_LEAVES); self::addCreativeItem(Item::get(Item::LEAVES2, 1), self::CREATIVE_GROUP_LEAVES); self::addCreativeItem(Item::get(Item::SAPLING, 0), self::CREATIVE_GROUP_SAPLING); self::addCreativeItem(Item::get(Item::SAPLING, 1), self::CREATIVE_GROUP_SAPLING); self::addCreativeItem(Item::get(Item::SAPLING, 2), self::CREATIVE_GROUP_SAPLING); self::addCreativeItem(Item::get(Item::SAPLING, 3), self::CREATIVE_GROUP_SAPLING); self::addCreativeItem(Item::get(Item::SAPLING, 4), self::CREATIVE_GROUP_SAPLING); self::addCreativeItem(Item::get(Item::SAPLING, 5), self::CREATIVE_GROUP_SAPLING); self::addCreativeItem(Item::get(Item::SEEDS, 0), self::CREATIVE_GROUP_SEED); self::addCreativeItem(Item::get(Item::PUMPKIN_SEEDS, 0), self::CREATIVE_GROUP_SEED); self::addCreativeItem(Item::get(Item::MELON_SEEDS, 0), self::CREATIVE_GROUP_SEED); self::addCreativeItem(Item::get(Item::BEETROOT_SEEDS, 0), self::CREATIVE_GROUP_SEED); self::addCreativeItem(Item::get(Item::WHEAT, 0), self::CREATIVE_GROUP_CROP); self::addCreativeItem(Item::get(Item::APPLE, 0), self::CREATIVE_GROUP_CROP); self::addCreativeItem(Item::get(Item::GOLDEN_APPLE, 0), self::CREATIVE_GROUP_CROP); self::addCreativeItem(Item::get(Item::MELON_BLOCK, 0), self::CREATIVE_GROUP_CROP); self::addCreativeItem(Item::get(Item::MELON, 0), self::CREATIVE_GROUP_CROP); self::addCreativeItem(Item::get(Item::PUMPKIN, 0), self::CREATIVE_GROUP_CROP); self::addCreativeItem(Item::get(Item::LIT_PUMPKIN, 0), self::CREATIVE_GROUP_CROP); self::addCreativeItem(Item::get(Item::TALL_GRASS, 1), self::CREATIVE_GROUP_GRASS); self::addCreativeItem(Item::get(Item::TALL_GRASS, 2), self::CREATIVE_GROUP_GRASS); self::addCreativeItem(Item::get(Item::DANDELION, 0), self::CREATIVE_GROUP_FLOWER); self::addCreativeItem(Item::get(Item::RED_FLOWER, Flower::TYPE_POPPY), self::CREATIVE_GROUP_FLOWER); self::addCreativeItem(Item::get(Item::RED_FLOWER, Flower::TYPE_BLUE_ORCHID), self::CREATIVE_GROUP_FLOWER); self::addCreativeItem(Item::get(Item::RED_FLOWER, Flower::TYPE_ALLIUM), self::CREATIVE_GROUP_FLOWER); self::addCreativeItem(Item::get(Item::RED_FLOWER, Flower::TYPE_AZURE_BLUET), self::CREATIVE_GROUP_FLOWER); self::addCreativeItem(Item::get(Item::RED_FLOWER, Flower::TYPE_RED_TULIP), self::CREATIVE_GROUP_FLOWER); self::addCreativeItem(Item::get(Item::RED_FLOWER, Flower::TYPE_ORANGE_TULIP), self::CREATIVE_GROUP_FLOWER); self::addCreativeItem(Item::get(Item::RED_FLOWER, Flower::TYPE_WHITE_TULIP), self::CREATIVE_GROUP_FLOWER); self::addCreativeItem(Item::get(Item::RED_FLOWER, Flower::TYPE_PINK_TULIP), self::CREATIVE_GROUP_FLOWER); self::addCreativeItem(Item::get(Item::RED_FLOWER, Flower::TYPE_OXEYE_DAISY), self::CREATIVE_GROUP_FLOWER); self::addColoredCreativeItem(Item::DYE, self::CREATIVE_GROUP_DYE); self::addCreativeItem(Item::get(Item::VINES, 0)); self::addCreativeItem(Item::get(Item::WATER_LILY, 0)); self::addCreativeItem(Item::get(Item::DEAD_BUSH, 0)); self::addCreativeItem(Item::get(Item::SNOW_BLOCK, 0)); self::addCreativeItem(Item::get(Item::ICE, 0)); self::addCreativeItem(Item::get(Item::SNOW_LAYER, 0)); self::addCreativeItem(Item::get(Item::BROWN_MUSHROOM, 0), self::CREATIVE_GROUP_MUSHROOM); self::addCreativeItem(Item::get(Item::RED_MUSHROOM, 0), self::CREATIVE_GROUP_MUSHROOM); self::addCreativeItem(Item::get(Item::SUGAR_CANES, 0)); self::addCreativeItem(Item::get(Item::SUGAR, 0)); self::addCreativeItem(Item::get(Item::BONE, 0)); self::addCreativeItem(Item::get(Item::COBWEB, 0)); self::addCreativeItem(Item::get(Item::MONSTER_SPAWNER, 0)); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 15), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 10), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 11), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 12), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 13), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 14), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 22), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 16), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 19), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 18), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 33), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 38), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 39), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 34), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 37), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 35), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 32), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 36), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 17), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 40), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 42), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 41), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::SPAWN_EGG, 43), self::CREATIVE_GROUP_MOBEGG); self::addCreativeItem(Item::get(Item::OBSIDIAN, 0)); self::addCreativeItem(Item::get(Item::BEDROCK, 0)); self::addCreativeItem(Item::get(Item::NETHERRACK, 0)); self::addCreativeItem(Item::get(Item::NETHER_WART_BLOCK_BLOCK, 0)); self::addCreativeItem(Item::get(Item::MAGMA, 0)); self::addCreativeItem(Item::get(Item::END_STONE, 0)); self::addCreativeItem(Item::get(Item::CHORUS_FLOWER, 0)); self::addCreativeItem(Item::get(Item::CHORUS_PLANT, 0)); self::addCreativeItem(Item::get(Item::SPONGE, 0)); self::addCreativeItem(Item::get(Item::LEATHER_CAP, 0), self::CREATIVE_GROUP_HELMET); self::addCreativeItem(Item::get(Item::CHAIN_HELMET, 0), self::CREATIVE_GROUP_HELMET); self::addCreativeItem(Item::get(Item::IRON_HELMET, 0), self::CREATIVE_GROUP_HELMET); self::addCreativeItem(Item::get(Item::DIAMOND_HELMET, 0), self::CREATIVE_GROUP_HELMET); self::addCreativeItem(Item::get(Item::GOLD_HELMET, 0), self::CREATIVE_GROUP_HELMET); self::addCreativeItem(Item::get(Item::LEATHER_TUNIC, 0), self::CREATIVE_GROUP_CHESTPLATE); self::addCreativeItem(Item::get(Item::CHAIN_CHESTPLATE, 0), self::CREATIVE_GROUP_CHESTPLATE); self::addCreativeItem(Item::get(Item::IRON_CHESTPLATE, 0), self::CREATIVE_GROUP_CHESTPLATE); self::addCreativeItem(Item::get(Item::DIAMOND_CHESTPLATE, 0), self::CREATIVE_GROUP_CHESTPLATE); self::addCreativeItem(Item::get(Item::GOLD_CHESTPLATE, 0), self::CREATIVE_GROUP_CHESTPLATE); self::addCreativeItem(Item::get(Item::LEATHER_PANTS, 0), self::CREATIVE_GROUP_LEGGINGS); self::addCreativeItem(Item::get(Item::CHAIN_LEGGINGS, 0), self::CREATIVE_GROUP_LEGGINGS); self::addCreativeItem(Item::get(Item::IRON_LEGGINGS, 0), self::CREATIVE_GROUP_LEGGINGS); self::addCreativeItem(Item::get(Item::DIAMOND_LEGGINGS, 0), self::CREATIVE_GROUP_LEGGINGS); self::addCreativeItem(Item::get(Item::GOLD_LEGGINGS, 0), self::CREATIVE_GROUP_LEGGINGS); self::addCreativeItem(Item::get(Item::LEATHER_BOOTS, 0), self::CREATIVE_GROUP_BOOTS); self::addCreativeItem(Item::get(Item::CHAIN_BOOTS, 0), self::CREATIVE_GROUP_BOOTS); self::addCreativeItem(Item::get(Item::IRON_BOOTS, 0), self::CREATIVE_GROUP_BOOTS); self::addCreativeItem(Item::get(Item::DIAMOND_BOOTS, 0), self::CREATIVE_GROUP_BOOTS); self::addCreativeItem(Item::get(Item::GOLD_BOOTS, 0), self::CREATIVE_GROUP_BOOTS); self::addCreativeItem(Item::get(Item::WOODEN_SWORD, 0), self::CREATIVE_GROUP_SWORD); self::addCreativeItem(Item::get(Item::STONE_SWORD, 0), self::CREATIVE_GROUP_SWORD); self::addCreativeItem(Item::get(Item::IRON_SWORD, 0), self::CREATIVE_GROUP_SWORD); self::addCreativeItem(Item::get(Item::DIAMOND_SWORD, 0), self::CREATIVE_GROUP_SWORD); self::addCreativeItem(Item::get(Item::GOLD_SWORD, 0), self::CREATIVE_GROUP_SWORD); self::addCreativeItem(Item::get(Item::WOODEN_AXE, 0), self::CREATIVE_GROUP_AXE); self::addCreativeItem(Item::get(Item::STONE_AXE, 0), self::CREATIVE_GROUP_AXE); self::addCreativeItem(Item::get(Item::IRON_AXE, 0), self::CREATIVE_GROUP_AXE); self::addCreativeItem(Item::get(Item::DIAMOND_AXE, 0), self::CREATIVE_GROUP_AXE); self::addCreativeItem(Item::get(Item::GOLD_AXE, 0), self::CREATIVE_GROUP_AXE); self::addCreativeItem(Item::get(Item::WOODEN_PICKAXE, 0), self::CREATIVE_GROUP_PICKAXE); self::addCreativeItem(Item::get(Item::STONE_PICKAXE, 0), self::CREATIVE_GROUP_PICKAXE); self::addCreativeItem(Item::get(Item::IRON_PICKAXE, 0), self::CREATIVE_GROUP_PICKAXE); self::addCreativeItem(Item::get(Item::DIAMOND_PICKAXE, 0), self::CREATIVE_GROUP_PICKAXE); self::addCreativeItem(Item::get(Item::GOLD_PICKAXE, 0), self::CREATIVE_GROUP_PICKAXE); self::addCreativeItem(Item::get(Item::WOODEN_SHOVEL, 0), self::CREATIVE_GROUP_SHOVEL); self::addCreativeItem(Item::get(Item::STONE_SHOVEL, 0), self::CREATIVE_GROUP_SHOVEL); self::addCreativeItem(Item::get(Item::IRON_SHOVEL, 0), self::CREATIVE_GROUP_SHOVEL); self::addCreativeItem(Item::get(Item::DIAMOND_SHOVEL, 0), self::CREATIVE_GROUP_SHOVEL); self::addCreativeItem(Item::get(Item::GOLD_SHOVEL, 0), self::CREATIVE_GROUP_SHOVEL); self::addCreativeItem(Item::get(Item::WOODEN_HOE, 0), self::CREATIVE_GROUP_HOE); self::addCreativeItem(Item::get(Item::STONE_HOE, 0), self::CREATIVE_GROUP_HOE); self::addCreativeItem(Item::get(Item::IRON_HOE, 0), self::CREATIVE_GROUP_HOE); self::addCreativeItem(Item::get(Item::DIAMOND_HOE, 0), self::CREATIVE_GROUP_HOE); self::addCreativeItem(Item::get(Item::GOLD_HOE, 0), self::CREATIVE_GROUP_HOE); self::addCreativeItem(Item::get(Item::BOW, 0)); self::addCreativeItem(Item::get(Item::ARROW, 0), self::CREATIVE_GROUP_ARROW); self::addCreativeItem(Item::get(Item::COOKED_FISH, 0), self::CREATIVE_GROUP_COOKEDFOOD); self::addCreativeItem(Item::get(Item::COOKED_FISH, 1), self::CREATIVE_GROUP_COOKEDFOOD); self::addCreativeItem(Item::get(Item::CAKE, 0), self::CREATIVE_GROUP_MISCFOOD); self::addCreativeItem(Item::get(Item::BREAD, 0), self::CREATIVE_GROUP_MISCFOOD); self::addCreativeItem(Item::get(Item::FISHING_ROD, 0)); self::addCreativeItem(Item::get(Item::SNOWBALL)); self::addCreativeItem(Item::get(Item::SHEARS, 0)); self::addCreativeItem(Item::get(Item::FLINT_AND_STEEL, 0)); self::addCreativeItem(Item::get(Item::CLOCK, 0)); self::addCreativeItem(Item::get(Item::COMPASS, 0)); self::addCreativeItem(Item::get(Item::STICKS, 0)); self::addCreativeItem(Item::get(Item::BED, 0), self::CREATIVE_GROUP_BED); self::addCreativeItem(Item::get(Item::TORCH, 0)); self::addCreativeItem(Item::get(Item::WORKBENCH, 0)); self::addCreativeItem(Item::get(Item::FURNACE, 0)); self::addCreativeItem(Item::get(Item::ANVIL, 0), self::CREATIVE_GROUP_ANVIL); self::addCreativeItem(Item::get(Item::ANVIL, 4), self::CREATIVE_GROUP_ANVIL); self::addCreativeItem(Item::get(Item::ANVIL, 8), self::CREATIVE_GROUP_ANVIL); self::addCreativeItem(Item::get(Item::ENCHANT_TABLE, 0)); self::addCreativeItem(Item::get(Item::BOOKSHELF, 0)); self::addCreativeItem(Item::get(Item::CHEST, 0), self::CREATIVE_GROUP_CHEST); self::addCreativeItem(Item::get(Item::ENDER_CHEST, 0), self::CREATIVE_GROUP_CHEST); self::addCreativeItem(Item::get(Item::GLOWSTONE_BLOCK, 0)); self::addCreativeItem(Item::get(Item::REDSTONE_LAMP, 0)); self::addCreativeItem(Item::get(Item::SIGN, 0), self::CREATIVE_GROUP_SIGN); self::addCreativeItem(Item::get(Item::PAINTING, 0)); self::addCreativeItem(Item::get(Item::BOWL, 0)); self::addCreativeItem(Item::get(Item::BUCKET, 0)); self::addCreativeItem(Item::get(Item::BUCKET, 1)); self::addCreativeItem(Item::get(Item::BUCKET, 8)); self::addCreativeItem(Item::get(Item::BUCKET, 10)); // self::addCreativeItem(Item::get(Item::STONECUTTER, 0)); // crash 1.11.0.1 self::addCreativeItem(Item::get(Item::END_PORTAL, 0)); self::addCreativeItem(Item::get(Item::COAL, 0)); self::addCreativeItem(Item::get(Item::COAL, 1)); self::addCreativeItem(Item::get(Item::DIAMOND, 0)); self::addCreativeItem(Item::get(Item::IRON_INGOT, 0)); self::addCreativeItem(Item::get(Item::GOLD_INGOT, 0)); self::addCreativeItem(Item::get(Item::EMERALD, 0)); self::addCreativeItem(Item::get(Item::QUARTZ, 0)); self::addCreativeItem(Item::get(Item::CLAY, 0)); self::addCreativeItem(Item::get(Item::STRING, 0)); self::addCreativeItem(Item::get(Item::FEATHER, 0)); self::addCreativeItem(Item::get(Item::FLINT, 0)); self::addCreativeItem(Item::get(Item::LEATHER, 0)); self::addCreativeItem(Item::get(Item::END_ROD, 0)); self::addCreativeItem(Item::get(Item::PAPER, 0)); self::addCreativeItem(Item::get(Item::RAIL, 0), self::CREATIVE_GROUP_RAIL); self::addCreativeItem(Item::get(Item::MINECART, 0), self::CREATIVE_GROUP_MINECART); self::addCreativeItem(Item::get(Item::REDSTONE, 0)); self::addCreativeItem(Item::get(Item::REDSTONE_BLOCK, 0)); self::addCreativeItem(Item::get(Item::HOPPER, 0)); self::addCreativeItem(Item::get(Item::TNT, 0)); } private static function addColoredCreativeItem($itemId, $creativeGroup) { self::addCreativeItem(Item::get($itemId, Block::COLOR_WHITE), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_ORANGE), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_MAGENTA), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_LIGHT_BLUE), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_YELLOW), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_LIME), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_PINK), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_GRAY), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_LIGHT_GRAY), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_CYAN), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_PURPLE), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_BLUE), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_BROWN), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_GREEN), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_RED), $creativeGroup); self::addCreativeItem(Item::get($itemId, Block::COLOR_BLACK), $creativeGroup); } private static function initFood(){ self::$food[] = Item::COOKIE; self::$food[] = Item::MELON; self::$food[] = Item::RAW_BEEF; self::$food[] = Item::COOKED_BEEF; self::$food[] = Item::RAW_CHICKEN; self::$food[] = Item::COOKED_CHICKEN; self::$food[] = Item::CARROT; self::$food[] = Item::POTATO; self::$food[] = Item::BAKED_POTATO; self::$food[] = Item::PUMPKIN_PIE; self::$food[] = Item::BREAD; self::$food[] = Item::APPLE; self::$food[] = Item::GOLDEN_APPLE; self::$food[] = Item::RAW_FISH; self::$food[] = Item::COOKED_FISH; self::$food[] = Item::RAW_PORKCHOP; self::$food[] = Item::COOKED_PORKCHOP; self::$food[] = Item::RAW_MUTTON; self::$food[] = Item::COOKED_MUTTON; self::$food[] = Item::RAW_RABBIT; self::$food[] = Item::COOKED_RABBIT; self::$food[] = Item::RAW_SALMON; self::$food[] = Item::COOKED_SALMON; self::$food[] = Item::RABBIT_STEW; self::$food[] = Item::CHORUS_FRUIT; } public static function clearCreativeItems(){ Item::$creative = []; } public static function getCreativeItems(){ return Item::$creative; } public static function getCreativeGroups(){ return Item::$creativeGroupData; } public static function addCreativeItem(Item $item, $creativeGroup = self::CREATIVE_GROUP_NONE){ Item::$creative[] = ['item' => Item::get($item->getId(), $item->getDamage()), 'group' => $creativeGroup]; } public static function removeCreativeItem(Item $item){ $index = self::getCreativeItemIndex($item); if($index !== -1){ unset(Item::$creative[$index]); } } public static function isCreativeItem(Item $item){ foreach(Item::$creative as $i => $d){ if($item->equals($d['item'], !$item->isTool())){ return true; } } return false; } /** * @param $index * @return Item */ public static function getCreativeItem($index){ return isset(Item::$creative[$index]) ? Item::$creative[$index]['item'] : null; } /** * @param Item $item * @return int */ public static function getCreativeItemIndex(Item $item){ foreach(Item::$creative as $i => $d){ if($item->equals($d['item'], !$item->isTool())){ return $i; } } return -1; } public static function get($id, $meta = 0, $count = 1, $tags = ""){ try{ if (!isset(self::$list[$id])) { if ($id < 256 && isset(Block::$list[$id]) && !is_null(Block::$list[$id])) { $class = Block::$list[$id]; return (new self::$itemBlockClass(new $class($meta), $meta, $count))->setCompound($tags); } return (new Item($id, $meta, $count))->setCompound($tags); } $class = self::$list[$id]; return (new $class($meta, $count))->setCompound($tags); }catch(\RuntimeException $e){ return (new Item($id, $meta, $count))->setCompound($tags); } } public static function fromString($str, $multiple = false){ if($multiple === true){ $blocks = []; foreach(explode(",", $str) as $b){ $blocks[] = self::fromString($b, false); } return $blocks; }else{ $b = explode(":", str_replace([" ", "minecraft:"], ["_", ""], trim($str))); if(!isset($b[1])){ $meta = 0; }else{ $meta = $b[1] & 0x7FFF; } if(defined(Item::class . "::" . strtoupper($b[0]))){ $item = self::get(constant(Item::class . "::" . strtoupper($b[0])), $meta); if($item->getId() === self::AIR and strtoupper($b[0]) !== "AIR"){ $item = self::get($b[0] & 0xFFFF, $meta); } }else{ $item = self::get($b[0] & 0xFFFF, $meta); } return $item; } } public function __construct($id, $meta = 0, $count = 1, $name = "Unknown", $obtainTime = null){ $this->id = $id & 0xffff; $this->meta = $meta !== null ? $meta & 0x7fff : null; $this->count = (int) $count; $this->name = $name; if($obtainTime == null){ $obtainTime = time(); } if(!isset($this->block) and $this->id <= 0xff and isset(Block::$list[$this->id])){ $this->block = Block::get($this->id, $this->meta); $this->name = $this->block->getName(); } if($this->name == "Unknown" && isset(Item::$names[$this->id])){ $this->name = Item::$names[$this->id]; } } public function setCompound($tags){ if($tags instanceof Compound){ $this->setNamedTag($tags); }else{ $this->tags = $tags; $this->cachedNBT = null; } return $this; } /** * @return string */ public function getCompound(){ return $this->tags; } public function hasCompound(){ return $this->tags !== "" and $this->tags !== null; } public function hasCustomBlockData(){ if(!$this->hasCompound()){ return false; } $tag = $this->getNamedTag(); if(isset($tag->BlockEntityTag) and $tag->BlockEntityTag instanceof Compound){ return true; } return false; } public function clearCustomBlockData(){ if(!$this->hasCompound()){ return $this; } $tag = $this->getNamedTag(); if(isset($tag->BlockEntityTag) and $tag->BlockEntityTag instanceof Compound){ unset($tag->display->BlockEntityTag); $this->setNamedTag($tag); } return $this; } public function setCustomBlockData(Compound $compound){ $tags = clone $compound; $tags->setName("BlockEntityTag"); if(!$this->hasCompound()){ $tag = new Compound("", []); }else{ $tag = $this->getNamedTag(); } $tag->BlockEntityTag = $tags; $this->setNamedTag($tag); return $this; } public function getCustomBlockData(){ if(!$this->hasCompound()){ return null; } $tag = $this->getNamedTag(); if(isset($tag->BlockEntityTag) and $tag->BlockEntityTag instanceof Compound){ return $tag->BlockEntityTag; } return null; } public function hasEnchantments(){ if(!$this->hasCompound()){ return false; } $tag = $this->getNamedTag(); if(isset($tag->ench)){ $tag = $tag->ench; if($tag instanceof Enum){ return true; } } return false; } /** * @param $id * @return Enchantment|null */ public function getEnchantment($id){ if(!$this->hasEnchantments()){ return null; } foreach($this->getNamedTag()->ench as $entry){ if($entry["id"] === $id){ $e = Enchantment::getEnchantment($entry["id"]); $e->setLevel($entry["lvl"]); return $e; } } return null; } /** * @param Enchantment $ench */ public function addEnchantment(Enchantment $ench){ if(!$this->hasCompound()){ $tag = new Compound("", []); }else{ $tag = $this->getNamedTag(); } if(!isset($tag->ench)){ $tag->ench = new Enum("ench", []); $tag->ench->setTagType(NBT::TAG_Compound); } $found = false; $maxIntIndex = -1; foreach($tag->ench as $k => $entry){ if (is_numeric($k) && $k > $maxIntIndex) { $maxIntIndex = $k; } if($entry["id"] === $ench->getId()){ $tag->ench->{$k} = new Compound("", [ "id" => new ShortTag("id", $ench->getId()), "lvl" => new ShortTag("lvl", $ench->getLevel()) ]); $found = true; break; } } if(!$found){ // $tag->ench->{count($tag->ench) + 1} = new Compound("", [ $tag->ench->{$maxIntIndex + 1} = new Compound("", [ "id" => new ShortTag("id", $ench->getId()), "lvl" => new ShortTag("lvl", $ench->getLevel()) ]); } $this->setNamedTag($tag); } /** * @return Enchantment[] */ public function getEnchantments(){ if(!$this->hasEnchantments()){ return []; } $enchantments = []; foreach($this->getNamedTag()->ench as $entry){ $e = Enchantment::getEnchantment($entry["id"]); $e->setLevel($entry["lvl"]); $enchantments[$e->getId()] = $e; } return $enchantments; } public function hasCustomName(){ if(!$this->hasCompound()){ return false; } $tag = $this->getNamedTag(); if(isset($tag->display)){ $tag = $tag->display; if($tag instanceof Compound and isset($tag->Name) and $tag->Name instanceof StringTag){ return true; } } return false; } public function getCustomName(){ if(!$this->hasCompound()){ return ""; } $tag = $this->getNamedTag(); if(isset($tag->display)){ $tag = $tag->display; if($tag instanceof Compound and isset($tag->Name) and $tag->Name instanceof StringTag){ return $tag->Name->getValue(); } } return ""; } public function setCustomName($name){ if((string) $name === ""){ $this->clearCustomName(); } if(!$this->hasCompound()){ $tag = new Compound("", []); }else{ $tag = $this->getNamedTag(); } if(isset($tag->display) and $tag->display instanceof Compound){ $tag->display->Name = new StringTag("Name", $name); }else{ $tag->display = new Compound("display", [ "Name" => new StringTag("Name", $name) ]); } $this->setCompound($tag); return $this; } public function setCustomColor($colorCode){ if(!$this->hasCompound()){ if (!is_int($colorCode)) { return $this; } $tag = new Compound("", []); }else{ $tag = $this->getNamedTag(); } if (!is_int($colorCode)) { unset($tag->customColor); } else { $tag->customColor = new IntTag("customColor", $colorCode); } $this->setCompound($tag); return $this; } public function clearCustomName(){ if(!$this->hasCompound()){ return $this; } $tag = $this->getNamedTag(); if(isset($tag->display) and $tag->display instanceof Compound){ unset($tag->display->Name); if($tag->display->getCount() === 0){ unset($tag->display); } $this->setNamedTag($tag); } return $this; } public function getNamedTagEntry($name){ $tag = $this->getNamedTag(); if($tag !== null){ return isset($tag->{$name}) ? $tag->{$name} : null; } return null; } public function getNamedTag(){ if(!$this->hasCompound()){ return null; }elseif($this->cachedNBT !== null){ return $this->cachedNBT; } return $this->cachedNBT = self::parseCompound($this->tags); } public function setNamedTag(Compound $tag){ if($tag->getCount() === 0){ return $this->clearNamedTag(); } $this->cachedNBT = $tag; $this->tags = self::writeCompound($tag); return $this; } public function clearNamedTag(){ return $this->setCompound(""); } public function getCount(){ return $this->count; } public function setCount($count){ $this->count = (int) $count; } final public function getName(){ return $this->hasCustomName() ? $this->getCustomName() : $this->name; } final public function canBePlaced(){ return $this->block !== null and $this->block->canBePlaced(); } final public function isPlaceable(){ return (($this->block instanceof Block) and $this->block->isPlaceable === true); } public function getBlock(){ if($this->block instanceof Block){ return clone $this->block; }else{ return Block::get(self::AIR); } } final public function getId(){ return $this->id; } public function getDamage(){ return $this->meta; } public function setDamage($meta){ $this->meta = $meta !== null ? $meta & 0x7FFF : null; } public function getMaxStackSize(){ return 64; } final public function getFuelTime(){ if(!isset(Fuel::$duration[$this->id])){ return null; } if($this->id !== self::BUCKET or $this->meta === 10){ return Fuel::$duration[$this->id]; } return null; } /** * @param Entity|Block $object * * @return bool */ public function useOn($object){ return false; } /** * @return bool */ public function isTool(){ return false; } /** * @return int|bool */ public function getMaxDurability(){ return false; } public function isPickaxe(){ return false; } public function isAxe(){ return false; } public function isSword(){ return false; } public function isShovel(){ return false; } public function isHoe(){ return false; } public function isShears(){ return false; } final public function __toString(){ return "Item " . $this->name . " (" . $this->id . ":" . ($this->meta === null ? "?" : $this->meta) . ")x" . $this->count . ($this->hasCompound() ? " tags:0x".bin2hex($this->getCompound()) : ""); } public function getDestroySpeed(Block $block, Player $player){ return 1; } public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ return false; } final public function equals(Item $item, $checkDamage = true, $checkCompound = true) { return $this->id === $item->getId() && ($checkDamage === false || $this->getDamage() === $item->getDamage()) && ($checkCompound === false || $this->getCompound() === $item->getCompound()); } public final function deepEquals(Item $item, $checkDamage = true, $checkCompound = true){ if($this->equals($item, $checkDamage, $checkCompound)){ return true; }elseif($item->hasCompound() and $this->hasCompound()){ return NBT::matchTree($this->getNamedTag(), $item->getNamedTag()); } return false; } public function isFood(){ return in_array($this->id, self::$food); } public function setObtainTime($time){ $this->obtainTime = $time; } public function getObtainTime(){ return $this->obtainTime; } public function isArmor(){ return false; } public function hasLore(){ if(!$this->hasCompound()){ return false; } $tag = $this->getNamedTag(); if(isset($tag->display)){ $tag = $tag->display; if($tag instanceof Compound and isset($tag->Lore) and $tag->Lore instanceof Enum){ return true; } } return false; } public function getLore(){ if(!$this->hasCompound()){ return ""; } $tag = $this->getNamedTag(); if(isset($tag->display)){ $tag = $tag->display; if($tag instanceof Compound and isset($tag->Lore) and $tag->Lore instanceof Enum){ return $tag->Lore->getValue(); } } return []; } public function setLore($lore){ if(!$this->hasCompound()){ $tag = new Compound("", []); }else{ $tag = $this->getNamedTag(); } $loreArray = []; foreach ($lore as $loreText) { $loreArray[] = new StringTag("", $loreText); } if(isset($tag->display) and $tag->display instanceof Compound){ $tag->display->Lore = new Enum("Lore", $loreArray); }else{ $tag->display = new Compound("display", [ "Lore" => new Enum("Lore", $loreArray) ]); } $this->setCompound($tag); return $this; } public static function registerItemBlock($className) { if (is_a($className, ItemBlock::class, true)) { self::$itemBlockClass = $className; } } public function getCanPlaceOnBlocks() { return $this->canPlaceOnBlocks; } public function getCanDestroyBlocks() { return $this->canDestroyBlocks; } public function addCanPlaceOnBlocks($blockName) { $this->canPlaceOnBlocks[$blockName] = $blockName; } public function addCanDestroyBlocks($blockName) { $this->canDestroyBlocks[$blockName] = $blockName; } }
lgpl-3.0
pcolby/libqtaws
src/opsworkscm/untagresourceresponse.cpp
5931
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "untagresourceresponse.h" #include "untagresourceresponse_p.h" #include <QDebug> #include <QNetworkReply> #include <QXmlStreamReader> namespace QtAws { namespace OpsWorksCM { /*! * \class QtAws::OpsWorksCM::UntagResourceResponse * \brief The UntagResourceResponse class provides an interace for OpsWorksCM UntagResource responses. * * \inmodule QtAwsOpsWorksCM * * <fullname>AWS OpsWorks CM</fullname> * * AWS OpsWorks for configuration management (CM) is a service that runs and manages configuration management servers. You * can use AWS OpsWorks CM to create and manage AWS OpsWorks for Chef Automate and AWS OpsWorks for Puppet Enterprise * servers, and add or remove nodes for the servers to * * manage> * * <b>Glossary of terms</b> * * </p <ul> <li> * * <b>Server</b>: A configuration management server that can be highly-available. The configuration management server runs * on an Amazon Elastic Compute Cloud (EC2) instance, and may use various other AWS services, such as Amazon Relational * Database Service (RDS) and Elastic Load Balancing. A server is a generic abstraction over the configuration manager that * you want to use, much like Amazon RDS. In AWS OpsWorks CM, you do not start or stop servers. After you create servers, * they continue to run until they are * * deleted> </li> <li> * * <b>Engine</b>: The engine is the specific configuration manager that you want to use. Valid values in this release * include <code>ChefAutomate</code> and * * <code>Puppet</code>> </li> <li> * * <b>Backup</b>: This is an application-level backup of the data that the configuration manager stores. AWS OpsWorks CM * creates an S3 bucket for backups when you launch the first server. A backup maintains a snapshot of a server's * configuration-related attributes at the time the backup * * starts> </li> <li> * * <b>Events</b>: Events are always related to a server. Events are written during server creation, when health checks run, * when backups are created, when system maintenance is performed, etc. When you delete a server, the server's events are * also * * deleted> </li> <li> * * <b>Account attributes</b>: Every account has attributes that are assigned in the AWS OpsWorks CM database. These * attributes store information about configuration limits (servers, backups, etc.) and your customer account. * * </p </li> </ul> * * <b>Endpoints</b> * * </p * * AWS OpsWorks CM supports the following endpoints, all HTTPS. You must connect to one of the following endpoints. Your * servers can only be accessed or managed within the endpoint in which they are * * created> <ul> <li> * * opsworks-cm.us-east-1.amazonaws.co> </li> <li> * * opsworks-cm.us-east-2.amazonaws.co> </li> <li> * * opsworks-cm.us-west-1.amazonaws.co> </li> <li> * * opsworks-cm.us-west-2.amazonaws.co> </li> <li> * * opsworks-cm.ap-northeast-1.amazonaws.co> </li> <li> * * opsworks-cm.ap-southeast-1.amazonaws.co> </li> <li> * * opsworks-cm.ap-southeast-2.amazonaws.co> </li> <li> * * opsworks-cm.eu-central-1.amazonaws.co> </li> <li> * * opsworks-cm.eu-west-1.amazonaws.co> </li> </ul> * * For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/opsworks-service.html">AWS OpsWorks * endpoints and quotas</a> in the AWS General * * Reference> * * <b>Throttling limits</b> * * </p * * All API operations allow for five requests per second with a burst of 10 requests per * * \sa OpsWorksCMClient::untagResource */ /*! * Constructs a UntagResourceResponse object for \a reply to \a request, with parent \a parent. */ UntagResourceResponse::UntagResourceResponse( const UntagResourceRequest &request, QNetworkReply * const reply, QObject * const parent) : OpsWorksCMResponse(new UntagResourceResponsePrivate(this), parent) { setRequest(new UntagResourceRequest(request)); setReply(reply); } /*! * \reimp */ const UntagResourceRequest * UntagResourceResponse::request() const { Q_D(const UntagResourceResponse); return static_cast<const UntagResourceRequest *>(d->request); } /*! * \reimp * Parses a successful OpsWorksCM UntagResource \a response. */ void UntagResourceResponse::parseSuccess(QIODevice &response) { //Q_D(UntagResourceResponse); QXmlStreamReader xml(&response); /// @todo } /*! * \class QtAws::OpsWorksCM::UntagResourceResponsePrivate * \brief The UntagResourceResponsePrivate class provides private implementation for UntagResourceResponse. * \internal * * \inmodule QtAwsOpsWorksCM */ /*! * Constructs a UntagResourceResponsePrivate object with public implementation \a q. */ UntagResourceResponsePrivate::UntagResourceResponsePrivate( UntagResourceResponse * const q) : OpsWorksCMResponsePrivate(q) { } /*! * Parses a OpsWorksCM UntagResource response element from \a xml. */ void UntagResourceResponsePrivate::parseUntagResourceResponse(QXmlStreamReader &xml) { Q_ASSERT(xml.name() == QLatin1String("UntagResourceResponse")); Q_UNUSED(xml) ///< @todo } } // namespace OpsWorksCM } // namespace QtAws
lgpl-3.0
kevoree/kevoree-library
toys/src/main/java/com/rendion/jchrome/painters/ToolbarPainter.java
848
package com.rendion.jchrome.painters; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import com.rendion.jchrome.JChromeTabbedPane; import com.rendion.jchrome.JChromeTabbedPane; public class ToolbarPainter { private static final int HEIGHT = 20; private final JChromeTabbedPane panel; private Theme theme; public ToolbarPainter(JChromeTabbedPane panel) { this.panel = panel; this.theme = panel.getTheme(); } public boolean mouseMoved(MouseEvent e) { return false; } public boolean mousePressed(MouseEvent e) { return false; } public boolean mouseReleased(MouseEvent e) { return false; } public void paint(Graphics2D g) { g.drawImage(panel.hasFocus() ? theme.TBAR : theme.TBAR_NOFOCUS, 0, theme.TABROW_HEIGHT + 1, g.getClipBounds().width, HEIGHT, null); } }
lgpl-3.0
yhqmcq/infox-cms
src/test/java/com/infocms/junit/BaseJunitCase.java
764
package com.infocms.junit; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * <strong>BaseJunitCase</strong><br> * <br> * <strong>Create on : 2012-2-10<br></strong> * <p> * <strong>Copyright (C) Ecointel Software Co.,Ltd.<br></strong> * <p> * @author peng.shi peng.shi@ecointel.com.cn<br> * @version <strong>ecointel-epp v1.0.0</strong><br> */ @ContextConfiguration(locations = { "classpath*:spring.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class BaseJunitCase { protected Logger logger = LoggerFactory.getLogger(this.getClass()); }
lgpl-3.0
Aymkdn/SharepointPlus
es5/files/checkin.js
4041
import _regeneratorRuntime from "@babel/runtime-corejs3/regenerator"; import _Promise from "@babel/runtime-corejs3/core-js-stable/promise"; import _asyncToGenerator from "@babel/runtime-corejs3/helpers/esm/asyncToGenerator"; import getURL from '../utils/getURL.js'; import ajax from '../utils/ajax.js'; import _buildBodyForSOAP from '../lists/_buildBodyForSOAP.js'; /** @name $SP().checkin @function @category files @description Checkin a file @param {Object} [setup] Options (see below) @param {String} setup.destination The full path to the file to check in @param {String} [setup.type='MajorCheckIn'] It can be 'MinorCheckIn' (incremented as a minor version), 'MajorCheckIn' (incremented as a major version), or 'OverwriteCheckIn' (overwrite the file) @param {String} [setup.comments=""] The comments related to the check in @param {String} [setup.url='current website'] The website url @return {Promise} resolve() then checked in is done, reject(error) otherwise @example // with Promise $SP().checkin({ destination:"http://mysite/Shared Documents/myfile.txt", comments:"Automatic check in with SharepointPlus" }).then(function() { alert("Done"); }).catch(function(error) { alert("Check in failed") }) */ export default function checkin(_x) { return _checkin.apply(this, arguments); } function _checkin() { _checkin = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee(setup) { var type, data, res; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.prev = 0; setup = setup || {}; if (setup.destination) { _context.next = 4; break; } throw "[SharepointPlus 'checkin'] the file destination path is required."; case 4: if (this.url && !setup.url) setup.url = this.url; if (setup.url) { _context.next = 9; break; } _context.next = 8; return getURL.call(this); case 8: setup.url = _context.sent; case 9: setup.comments = (setup.comments || "").replace(/&/g, "&amp;"); type = 1; _context.t0 = setup.type; _context.next = _context.t0 === "MinorCheckIn" ? 14 : _context.t0 === "OverwriteCheckIn" ? 16 : 18; break; case 14: type = 0; return _context.abrupt("break", 18); case 16: type = 2; return _context.abrupt("break", 18); case 18: _context.next = 20; return ajax.call(this, { url: setup.url + "/_vti_bin/Lists.asmx", body: _buildBodyForSOAP("CheckInFile", '<pageUrl>' + setup.destination + '</pageUrl><comment>' + setup.comments + '</comment><CheckinType>' + type + '</CheckinType>'), headers: { 'SOAPAction': 'http://schemas.microsoft.com/sharepoint/soap/CheckInFile' } }); case 20: data = _context.sent; res = data.getElementsByTagName('CheckInFileResult'); res = res.length > 0 ? res[0] : null; if (!(res && res.firstChild.nodeValue != "true")) { _context.next = 27; break; } return _context.abrupt("return", _Promise.reject(res)); case 27: return _context.abrupt("return", _Promise.resolve()); case 28: _context.next = 33; break; case 30: _context.prev = 30; _context.t1 = _context["catch"](0); return _context.abrupt("return", _Promise.reject(_context.t1)); case 33: case "end": return _context.stop(); } } }, _callee, this, [[0, 30]]); })); return _checkin.apply(this, arguments); }
lgpl-3.0
kwiato88/EditorPlugins
nppIncludeBrowser/Source/TreeViewFileHierarchySelector.cpp
941
#include "TreeViewFileHierarchySelector.hpp" #include "TreeDialog.hpp" namespace IncludeBrowser { namespace { WinApi::Node buildNode(const FileHierarchy& p_files) { WinApi::Node node(p_files.value, static_cast<const void*>(&p_files.value)); for (const auto& file : p_files.children) node.m_children.push_back(buildNode(file)); return node; } } TreeViewFileHierarchySelector::TreeViewFileHierarchySelector(WinApi::InstanceHandle& p_hInstance, WinApi::Handle& p_parent) : hInstance(p_hInstance), parent(p_parent) {} std::string TreeViewFileHierarchySelector::select(const FileHierarchy& p_files) const { WinApi::TreeDialog dialog(hInstance, parent, "Select file"); dialog.setTreeNodes({ buildNode(p_files) }); if (dialog.show() == WinApi::Dialog::RESULT_OK) { const auto* file = dialog.getSelectedItemContext<std::string>(); return file == nullptr ? std::string() : *file; } return ""; } }
lgpl-3.0
kbss-cvut/jopa-examples
eswc2016/src/main/webapp/src/component/message/Message.tsx
1012
import * as React from "react"; import {useCallback, useEffect} from "react"; import {Message as MessageModel} from "../../model/Types"; import {Alert} from "react-bootstrap"; import {useDispatch} from "react-redux"; import {dismissMessage} from "../../action/SyncActions"; import Constants from "../../util/Constants"; interface MessageProps { message: MessageModel; } export const Message: React.FC<MessageProps> = (props: MessageProps) => { const {message} = props; const dispatch = useDispatch(); const dismiss = useCallback( () => dispatch(dismissMessage(message)), [message, dispatch] ); useEffect(() => { const timer = setTimeout(() => { dismiss(); }, Constants.MESSAGE_DURATION); return () => clearTimeout(timer); }, [dismiss, message]); return ( <Alert variant={message.type} show={true} dismissible={true} onClose={dismiss}> {message.message} </Alert> ); }; export default Message;
lgpl-3.0
SonarSource/sonarqube
server/sonar-ce/src/main/java/org/sonar/ce/cleaning/CeCleaningExecutorService.java
1010
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.cleaning; import java.util.concurrent.ScheduledExecutorService; public interface CeCleaningExecutorService extends ScheduledExecutorService { }
lgpl-3.0
jorj1988/shift-core
src/Utilities/satomichelper.cpp
598
#include "shift/Utilities/satomichelper.h" #include "Memory/XResourceDescription.h" #include "Utilities/XAssert.h" #if defined(X_MSVC) # include "Windows.h" #endif namespace Shift { namespace AtomicHelper { bool trySet(Type *p, Type newVal, Type oldVal) { bool success = false; #if defined(X_MSVC) xAssertIsSpecificAligned(p, 8); // try to lock the updating flag, if we cant, someone else is working. success = InterlockedCompareExchange16(p, newVal, oldVal) == oldVal; #else success = __sync_val_compare_and_swap(p, oldVal, newVal) == oldVal; #endif return success; } } }
lgpl-3.0
colceriu-ovidiu/zMovies
module/MyAuth/src/MyAuth/Form/LoginForm.php
871
<?php namespace MyAuth\Form; use Zend\Form\Form; class LoginForm extends Form { public function __construct($name = null) { // we want to ignore the name passed parent::__construct('login'); $this->add(array( 'name' => 'username', 'type' => 'Text', 'options' => array( 'label' => 'Username', ), )); $this->add(array( 'name' => 'password', 'type' => 'Password', 'options' => array( 'label' => 'Password', ), )); $this->add(array( 'name' => 'submit', 'type' => 'Submit', 'attributes' => array( 'value' => 'Login', 'id' => 'submitbutton', ), )); } }
lgpl-3.0
TheAnswer/FirstTest
bin/scripts/creatures/objects/tatooine/npcs/sennex/sennexWarder.lua
4759
--Copyright (C) 2008 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. sennexWarder = Creature:new { objectName = "sennexWarder", -- Lua Object Name creatureType = "NPC", gender = "", speciesName = "sennex_warder", stfName = "mob/creature_names", objectCRC = 1772199470, socialGroup = "Sennex", level = 50, combatFlags = ATTACKABLE_FLAG + ENEMY_FLAG + AGGRESSIVE_FLAG, healthMax = 6100, healthMin = 5000, strength = 500, constitution = 500, actionMax = 6100, actionMin = 5000, quickness = 500, stamina = 500, mindMax = 6100, mindMin = 5000, focus = 500, willpower = 500, height = 1, -- Size of creature armor = 1, -- 0 = None; 1 = Light; 2 = Medium; 3 = Heavy kinetic = 0, energy = 0, electricity = 30, stun = -1, blast = 0, heat = 30, cold = -1, acid = 0, lightsaber = 0, accuracy = 300, healer = 0, pack = 1, herd = 0, stalker = 0, killer = 1, ferocity = 0, aggressive = 1, invincible = 0, meleeDefense = 1, rangedDefense = 1, attackCreatureOnSight = "", -- Enter socialGroups weapon = "object/weapon/melee/polearm/shared_polearm_vibro_axe.iff", -- File path to weapon -> object\xxx\xxx\xx weaponName = "a Long Vibro Axe", -- Name ex. 'a Vibrolance' weaponTemp = "lance_vibro_axe", -- Weapon Template ex. 'lance_vibrolance' weaponClass = "PolearmMeleeWeapon", -- Weapon Class ex. 'PolearmMeleeWeapon' weaponEquipped = 1, weaponMinDamage = 190, weaponMaxDamage = 200, weaponAttackSpeed = 2, weaponDamageType = "ELECTRICITY", -- ELECTRICITY, KINETIC, etc weaponArmorPiercing = "NONE", -- LIGHT, NONE, MEDIUM, HEAVY alternateWeapon = "object/weapon/melee/axe/shared_axe_vibroaxe.iff", -- File path to weapon -> object\xxx\xxx\xx alternateWeaponName = "a Vibro Axe", -- Name ex. 'a Vibrolance' alternateWeaponTemp = "axe_vibro", -- Weapon Template ex. 'lance_vibrolance' alternateWeaponClass = "TwoHandedMeleeWeapon", -- Weapon Class ex. 'PolearmMeleeWeapon' alternateWeaponEquipped = 1, alternateWeaponMinDamage = 190, alternateWeaponMaxDamage = 200, alternateWeaponAttackSpeed = 2, alternateWeaponDamageType = "KINETIC", -- ELECTRICITY, KINETIC, etc alternateWeaponArmorPiercing = "NONE", -- LIGHT, NONE, MEDIUM internalNPCDamageModifier = 0.3, -- Damage Modifier to other NPC's lootGroup = "0,11,15,19,33,39", -- Group it belongs to for loot tame = 0, datapadItemCRC = 0, mountCRC = 0, mountSpeed = 0, mountAcceleration = 0, milk = 0, boneType = "", boneMax = 0, hideType = "", hideMax = 0, meatType = "", meatMax = 0, skills = { "sennexattack1", "sennexattack2", "sennexattack3", "sennexattack4", "sennexattack5" }, respawnTimer = 300, behaviorScript = "", -- Link to the behavior script for this object } Creatures:addCreature(sennexWarder, 1772199470) -- Add to Global Table
lgpl-3.0
anndy201/mars-framework
mars_common/src/main/java/com/sqsoft/mars/common/iou/demo/HouseKeeper.java
3849
package com.sqsoft.mars.common.iou.demo; import java.util.Random; import org.joda.time.DateTime; import com.sqsoft.mars.common.iou.Escrow; import com.sqsoft.mars.common.iou.Iou; import com.sqsoft.mars.common.iou.RealIouEscrow; import com.sqsoft.mars.common.iou.RealIouEscrowEx; public class HouseKeeper { public static void main(String args[]) { // 初始化待处理的衣服和食物对象 Clothes clothesToWash = new ClothesImpl(); Food foodToCook = new FoodImpl(); // 设定洗衣事务 Iou clothesWashed = wash(clothesToWash); Clothes closeWashEx = washEx(clothesToWash); // 继续做其他事情 doSomethingOther(); // 设定烹饪事务 Food foodCooked = cook(foodToCook); // 继续做其他事情 doSomethingOther(); // 开始享用食物 eat(foodCooked); // 开始晾晒衣服 hangout(clothesWashed); hangoutEx(closeWashEx); } private static void hangoutEx(Clothes closeWashEx) { // TODO Auto-generated method stub logger("wash cloth ex hang out."); } private static Clothes washEx(Clothes clothesToWash) { logger("Schedule to wash ex " + clothesToWash); Escrow escrow = new RealIouEscrowEx(Clothes.class); new AsyncService("wash clothes ex.", clothesToWash, escrow).start(); return (Clothes)escrow.issueIou(); } private static Iou wash(Clothes clothes) { logger("Schedule to wash " + clothes); Escrow escrow = new RealIouEscrow(); new AsyncService("wash clothes", clothes, escrow).start(); return escrow.issueIou(); } private static Food cook(Food food) { logger("Schedule to cook " + food); Escrow escrow = new RealIouEscrowEx(Food.class); new AsyncService("cook food", food, escrow).start(); return (Food)escrow.issueIou(); } private static void eat(Food food) { logger("Be about to eat food...add some spice first..."); food.addSpice(); logger(food + " is eaten."); } private static void hangout(Iou iou) { logger("Be about to hang out clothes..."); if( !iou.closed() ) { logger("Clothes are not ready, stand by..."); iou.standBy(); } Object clothes = iou.redeem(); logger(clothes + " are hung out."); } private static void doSomethingOther() { try { Random r = new Random(DateTime.now().getMillis()); int time = (Math.abs(r.nextInt())%1000 + 0); Thread.sleep(time); logger("Do something other [" + time + " millis]"); } catch (InterruptedException e) { } } private static void logger(String message) { System.out.println("["+DateTime.now()+"] "+message); } } class AsyncService extends Thread { private Escrow escrow; private String task; private Processable o; private int time; public AsyncService(String task, Processable o, Escrow escrow) { this.escrow = escrow; this.task = task; this.o = o; } public void run() { System.out.println(" >>> Starting to " + this.task ); Object r = service(o); this.escrow.close(r); System.out.println(" <<< Finished " + this.task + " [" + time + " millis]"); } private Processable service(Processable o) { try { Random r = new Random(DateTime.now().getMillis()); time = (Math.abs(r.nextInt())%1000 + 200); sleep(time); this.o.process(); } catch(InterruptedException e) { } return this.o; } }
lgpl-3.0
TheAnswer/FirstTest
bin/scripts/object/tangible/lair/kupernug/objects.lua
6025
--Copyright (C) 2009 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. object_tangible_lair_kupernug_shared_lair_kupernug = SharedTangibleObjectTemplate:new { appearanceFilename = "appearance/poi_all_lair_nest_tree.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 25, clientDataFile = "clientdata/client_shared_lair_small.cdf", collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@lair_d:kupernug", gameObjectType = 4, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 64, objectName = "@lair_n:kupernug", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, useStructureFootprintOutline = 0 } ObjectTemplates:addTemplate(object_tangible_lair_kupernug_shared_lair_kupernug, 2658633620) object_tangible_lair_kupernug_shared_lair_kupernug_mountain = SharedTangibleObjectTemplate:new { appearanceFilename = "appearance/poi_all_lair_nest_tree.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 25, clientDataFile = "clientdata/client_shared_lair_small.cdf", collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@lair_d:kupernug_mountain", gameObjectType = 4, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 64, objectName = "@lair_n:kupernug_mountain", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, useStructureFootprintOutline = 0 } ObjectTemplates:addTemplate(object_tangible_lair_kupernug_shared_lair_kupernug_mountain, 3996614231) object_tangible_lair_kupernug_shared_lair_kupernug_wasteland = SharedTangibleObjectTemplate:new { appearanceFilename = "appearance/poi_all_lair_nest_tree.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 25, clientDataFile = "clientdata/client_shared_lair_small.cdf", collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@lair_d:kupernug_wasteland", gameObjectType = 4, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 64, objectName = "@lair_n:kupernug_wasteland", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, useStructureFootprintOutline = 0 } ObjectTemplates:addTemplate(object_tangible_lair_kupernug_shared_lair_kupernug_wasteland, 2421166667)
lgpl-3.0
northshorefiend/sshproxyj
sshproxyj-start/src/main/java/com/jamesashepherd/start/Listener.java
5650
/** * Copyright 2013 James A. Shepherd * http://www.JamesAshepherd.com/ * * LICENCE: http://www.gnu.org/licenses/lgpl.html */ package com.jamesashepherd.start; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.UUID; /** * <p> * Server, that listens for admin commands. * </p> * * <p> * Also, uses {@link Runtime.addShutdownHook} to stop the application. * </p> * * @author James A. Shepherd * @since 1.0 * */ public class Listener extends Thread { /** * Last message Listener sends client */ public static final String BYE = "<<BYE>>"; /** * Flag to say we have already started to shutdown. */ private boolean shuttingDown = false; /** * Shutdown hook that calls {@link #startable}.shutdown() */ private Thread shutdownHook; /** * Application we are listening on behalf of. */ private Startable startable; /** * code to authenticate commands with */ private String code; /** * code file to delete on exit */ private File codefile; /** * Socket we listen for commands on. */ private ServerSocket socket; /** * Should we listen on port. */ private boolean listenOnPort = false; /** * * @param startable * application to start * @param startport * port to listen to on 127.0.0.1, if 0 then a port will be * chosen and output. * @param startcode * code to authorize commands with, if null, then a code will be * chosen and output * @param startcodefile * file to hold the startcode used * @throws IOException * if can't open socket * @throws UnknownHostException * if can't open socket * @since 1.0 */ public Listener(final Startable startable, final int startport, String startcode, final File startcodefile) throws UnknownHostException, IOException { this(startable); listenOnPort = true; socket = new ServerSocket(startport, 1, InetAddress.getByName("127.0.0.1")); if (startport == 0) { System.out.println("Will listen on 127.0.0.1:" + socket.getLocalPort()); } if (startcode == null) { startcode = UUID.randomUUID().toString(); System.out.println("Will listen for code: '" + startcode + "'"); } code = startcode; codefile = startcodefile; if (codefile != null) { FileOutputStream out = null; PrintStream printer = null; try { out = new FileOutputStream(codefile); printer = new PrintStream(out); printer.println(code); printer.flush(); printer.close(); out.close(); printer = null; out = null; System.out.println("Code output to file"); } catch (final Exception e) { System.err.println("Unable to output code to file: '" + codefile + "'"); throw new IOException("Cannot open code file: " + codefile); } finally { if (printer != null) { printer.close(); } if (out != null) { try { out.close(); out = null; } catch (final IOException e) { } } } } } /** * Only listens for JVM shutdown. * * @param startable * application to start * @since 1.0 */ public Listener(final Startable startable) { super("start Listener"); this.startable = startable; setDaemon(true); shutdownHook = new Thread("start ShutdownHook") { @Override public void run() { Listener.this.shutdown(); } }; } /** * Starts up the listener and invokes the application. * * @see java.lang.Thread#run() * @since 1.0 */ @Override public void run() { Runtime.getRuntime().addShutdownHook(shutdownHook); if (listenOnPort) { listen(); } } /** * Listen for commands. * * @since 1.0 */ private void listen() { System.out.println("Listening..."); while (true) { Socket clientSocket = null; PrintWriter out = null; BufferedReader in = null; try { clientSocket = socket.accept(); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); // read code String inputLine = in.readLine(); // if code correct read command if (inputLine != null && inputLine.equals(code)) { inputLine = in.readLine(); if (inputLine != null && inputLine.equals("shutdown")) { out.println("SHUTTING DOWN: ..."); shutdown(); out.println("SHUTDOWN COMPLETED."); out.println(Listener.BYE); socket.close(); in.close(); break; } } in.close(); } catch (final IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } if (in != null) { try { in.close(); } catch (final IOException e) { } } } } } /** * Does the actual shutting down. * * @since 1.0 */ private synchronized void shutdown() { // make sure we only shutdown once if (!shuttingDown) { shuttingDown = true; // not necessary // Runtime.getRuntime().removeShutdownHook(this.shutdownHook); try { startable.shutdown(); } catch (StartException e) { e.printStackTrace(); } // delete codefile if (codefile != null) { if (codefile.delete()) { System.out.println("Code file deleted"); } else { System.err.println("ERROR: Code file NOT deleted"); } } } } }
lgpl-3.0
acnicholas/scaddins
src/RoomConverter/RoomParameter.cs
1222
// (C) Copyright 2018-2020 by Andrew Nicholas // // This file is part of SCaddins. // // SCaddins 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. // // SCaddins 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 SCaddins. If not, see <http://www.gnu.org/licenses/>. namespace SCaddins.RoomConverter { public class RoomParameter { public RoomParameter(string def, string value, string convertedValue) { Def = def; Value = value; ConvertedValue = convertedValue; } public string ConvertedValue { get; set; } public string Def { get; set; } // ReSharper disable once UnusedAutoPropertyAccessor.Local private string Value { get; set; } } }
lgpl-3.0
lbndev/sonarqube
server/sonar-web/src/main/js/apps/permissions/shared/components/GroupIcon.js
2157
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; const GroupIcon = () => { /* eslint max-len: 0 */ return ( <div style={{ padding: '4px 3px 0' }}> <svg xmlns="http://www.w3.org/2000/svg" width="30" height="28" viewBox="0 0 480 448"> <path fill="#aaa" d="M148.25 224q-40.5 1.25-66.25 32H48.5Q28 256 14 245.875T0 216.25Q0 128 31 128q1.5 0 10.875 5.25t24.375 10.625T96 149.25q16.75 0 33.25-5.75Q128 152.75 128 160q0 34.75 20.25 64zM416 383.25q0 30-18.25 47.375T349.25 448h-218.5q-30.25 0-48.5-17.375T64 383.25q0-13.25.875-25.875t3.5-27.25T75 303t10.75-24.375 15.5-20.25T122.625 245t27.875-5q2.5 0 10.75 5.375t18.25 12 26.75 12T240 274.75t33.75-5.375 26.75-12 18.25-12T329.5 240q15.25 0 27.875 5t21.375 13.375 15.5 20.25T405 303t6.625 27.125 3.5 27.25.875 25.875zM160 64q0 26.5-18.75 45.25T96 128t-45.25-18.75T32 64t18.75-45.25T96 0t45.25 18.75T160 64zm176 96q0 39.75-28.125 67.875T240 256t-67.875-28.125T144 160t28.125-67.875T240 64t67.875 28.125T336 160zm144 56.25q0 19.5-14 29.625T431.5 256H398q-25.75-30.75-66.25-32Q352 194.75 352 160q0-7.25-1.25-16.5 16.5 5.75 33.25 5.75 14.75 0 29.75-5.375t24.375-10.625T449 128q31 0 31 88.25zM448 64q0 26.5-18.75 45.25T384 128t-45.25-18.75T320 64t18.75-45.25T384 0t45.25 18.75T448 64z" /> </svg> </div> ); }; export default GroupIcon;
lgpl-3.0
iskovskikh/sadovod.local
module/Shop/Module.php
455
<?php namespace Shop; class Module { public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } }
lgpl-3.0
chenzongzhai/liepin
liepin/spiders/config.py
564
# -*- coding:utf-8 -*- import MySQLdb from DBUtils.PooledDB import PooledDB CONFIG = { 'allowed_domains': ['www.liepin.com', 'job.liepin.com'], 'start_urls': ['https://www.liepin.com/zhaopin/'], 'detail_link_rule': ['https://job.liepin.com/\d+_\d+/\?imscid=\w+'], 'list_link_rule': ['https://www.liepin.com/zhaopin/\?curPage=\d+'] } pool = PooledDB(MySQLdb, mincached=1, maxcached=62, host='xxx.xxx.xxx.xxx', port=xxxx, user='xxxx', passwd='xxxxxx', db='test', use_unicode=False, charset='utf8' )
lgpl-3.0
pcolby/libqtaws
src/devicefarm/listdevicepoolsrequest.cpp
3735
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "listdevicepoolsrequest.h" #include "listdevicepoolsrequest_p.h" #include "listdevicepoolsresponse.h" #include "devicefarmrequest_p.h" namespace QtAws { namespace DeviceFarm { /*! * \class QtAws::DeviceFarm::ListDevicePoolsRequest * \brief The ListDevicePoolsRequest class provides an interface for DeviceFarm ListDevicePools requests. * * \inmodule QtAwsDeviceFarm * * Welcome to the AWS Device Farm API documentation, which contains APIs * * for> <ul> <li> * * Testing on desktop * * browser> * * Device Farm makes it possible for you to test your web applications on desktop browsers using Selenium. The APIs for * desktop browser testing contain <code>TestGrid</code> in their names. For more information, see <a * href="https://docs.aws.amazon.com/devicefarm/latest/testgrid/">Testing Web Applications on Selenium with Device * * Farm</a>> </li> <li> * * Testing on real mobile * * device> * * Device Farm makes it possible for you to test apps on physical phones, tablets, and other devices in the cloud. For more * information, see the <a href="https://docs.aws.amazon.com/devicefarm/latest/developerguide/">Device Farm Developer * * \sa DeviceFarmClient::listDevicePools */ /*! * Constructs a copy of \a other. */ ListDevicePoolsRequest::ListDevicePoolsRequest(const ListDevicePoolsRequest &other) : DeviceFarmRequest(new ListDevicePoolsRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a ListDevicePoolsRequest object. */ ListDevicePoolsRequest::ListDevicePoolsRequest() : DeviceFarmRequest(new ListDevicePoolsRequestPrivate(DeviceFarmRequest::ListDevicePoolsAction, this)) { } /*! * \reimp */ bool ListDevicePoolsRequest::isValid() const { return false; } /*! * Returns a ListDevicePoolsResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * ListDevicePoolsRequest::response(QNetworkReply * const reply) const { return new ListDevicePoolsResponse(*this, reply); } /*! * \class QtAws::DeviceFarm::ListDevicePoolsRequestPrivate * \brief The ListDevicePoolsRequestPrivate class provides private implementation for ListDevicePoolsRequest. * \internal * * \inmodule QtAwsDeviceFarm */ /*! * Constructs a ListDevicePoolsRequestPrivate object for DeviceFarm \a action, * with public implementation \a q. */ ListDevicePoolsRequestPrivate::ListDevicePoolsRequestPrivate( const DeviceFarmRequest::Action action, ListDevicePoolsRequest * const q) : DeviceFarmRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the ListDevicePoolsRequest * class' copy constructor. */ ListDevicePoolsRequestPrivate::ListDevicePoolsRequestPrivate( const ListDevicePoolsRequestPrivate &other, ListDevicePoolsRequest * const q) : DeviceFarmRequestPrivate(other, q) { } } // namespace DeviceFarm } // namespace QtAws
lgpl-3.0
sfu-ireceptor/gateway
resources/views/job/view.blade.php
1709
@extends('template') @section('title', $job->agave_status) @section('base_title', ' ') @section('content') <div class="container job_container" data-job-id="{{ $job->id }}" data-job-status="{{ $job->status }}"> <h1> Job {{ $job->id }} <small data-toggle="tooltip" data-placement="right" title="Submitted on {{ $job->createdAtFull() }}"> <span class="submission_date_relative"> {{ $job->createdAtRelative() }} </span> </small> </h1> <div class="job_view_progress"> @include('job/progress') </div> <h2>{{ $job->app }}</h2> @if ($job->url) <p> Data from: <a href="{{ $job->url }}"> {{ $job->url }} </a> </p> @endif @if (count($files) > 0 && $job->app != 'Third-party analysis') <h2>Files</h2> <div class="result_files"> {!! $filesHTML !!} </div> @endif @if (count($files) > 0 && $job->app == 'Third-party analysis') <h2>BRepertoire</h2> <ul> @foreach ($files as $f) @if (basename($f) != 'info.txt') <li> <a href="http://mabra.biomed.kcl.ac.uk/BRepertoire/?branch=analysis&amp;tab=tab_propertyUpload&amp;delim=tab&amp;loadURL={{ config('app.url') . '/' . $f }}" class="btn btn-default" target="_blank"> {{ basename($f) }} <span class="glyphicon glyphicon-export" aria-hidden="true"></span> </a> </li> @endif @endforeach </ul> @endif <div class="job_steps"> @include('job/steps') </div> <p> <a href="/jobs/delete/{{ $job->id }}"> <button type="button" class="btn btn-default" aria-label="Delete"> <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete this job </button> </a> </p> <!-- jobs-history -V {{ $job->agave_id }} --> </div> @stop
lgpl-3.0
bunnyinc/phpstats
tests/ProbabilityDistribution/RayleighTest.php
2045
<?php require_once('lib/Stats.php'); require_once('lib/ProbabilityDistribution/ProbabilityDistribution.php'); require_once('lib/ProbabilityDistribution/Weibull.php'); require_once('lib/ProbabilityDistribution/Rayleigh.php'); use \PHPStats\ProbabilityDistribution\Rayleigh as Rayleigh; class RayleighTest extends PHPUnit_Framework_TestCase { private $testObject; public function __construct() { $this->testObject = new Rayleigh(2); } public function test_rvs() { $variates = array(); for ($i = 0; $i < 10000; $i++) $variates[] = $this->testObject->rvs(); $this->assertGreaterThanOrEqual(0.01, \PHPStats\StatisticalTests::kolmogorovSmirnov($variates, $this->testObject)); $this->assertLessThanOrEqual(0.99, \PHPStats\StatisticalTests::kolmogorovSmirnov($variates, $this->testObject)); } public function test_pdf() { $this->assertEquals(0.22062, round($this->testObject->pdf(1), 5)); $this->assertEquals(0.12115, round($this->testObject->pdf(0.5), 5)); } public function test_cdf() { $this->assertEquals(0.25, round($this->testObject->cdf(1.51706), 5)); $this->assertEquals(0.5, round($this->testObject->cdf(2.35482), 5)); } public function test_sf() { $this->assertEquals(0.75, round($this->testObject->sf(1.51706), 5)); $this->assertEquals(0.5, round($this->testObject->sf(2.35482), 5)); } public function test_ppf() { $this->assertEquals(1.51706, round($this->testObject->ppf(0.25), 5)); $this->assertEquals(2.35482, round($this->testObject->ppf(0.5), 5)); } public function test_isf() { $this->assertEquals(1.51706, round($this->testObject->isf(0.75), 5)); $this->assertEquals(2.35482, round($this->testObject->isf(0.5), 5)); } public function test_stats() { $summaryStats = $this->testObject->stats('mvsk'); $this->assertEquals(2.50663, round($summaryStats['mean'], 5)); $this->assertEquals(1.71681, round($summaryStats['variance'], 5)); $this->assertEquals(0.63111, round($summaryStats['skew'], 5)); $this->assertEquals(0.24509, round($summaryStats['kurtosis'], 5)); } } ?>
lgpl-3.0
ArticulatedSocialAgentsPlatform/HmiCore
HmiGraphics/src/hmi/graphics/examples/ColladaTestScenePupilSizeSetting.java
5190
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer 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 ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package hmi.graphics.examples; import java.awt.Component; import java.util.*; import hmi.graphics.opengl.*; import hmi.util.*; import hmi.math.*; import hmi.graphics.collada.*; import hmi.graphics.collada.scenegraph.*; import hmi.graphics.scenegraph.*; import hmi.graphics.opengl.*; import hmi.graphics.opengl.state.*; import hmi.graphics.opengl.scenegraph.*; import hmi.graphics.opengl.renderobjects.*; import hmi.animation.*; import hmi.graphics.util.*; import java.io.*; public class ColladaTestScenePupilSizeSetting implements GLClockedRenderObject { private VGLNode scene; private VJoint sceneRoot; private OpenGLState openglState; private VJoint bodyNGRootJoint; private VJoint bipRootJoint; private VJoint avatarRootJoint; private VGLNode avatarNode; private GLScene glScene; private SkeletonInterpolator ski; private SkeletonInterpolator adaptedSkel; private LightBox lights; private GLNavigation2 glNav; public ColladaTestScenePupilSizeSetting(Component canvas) { sceneRoot = new VJoint("sceneRoot"); sceneRoot.setTranslation(0.0f, 0.0f, 0.0f); // should be used for navigation scene = new VGLNode("ShadowScene"); sceneRoot.addChild(scene.getRoot()); openglState = new OpenGLState(); lights = new LightBox(3); lights.get(0).setDiffuseColor(0.8f, 0.8f, 0.8f); // The (initial) position of the light lights.get(1).setDiffuseColor(0.7f, 0.0f, 0.0f); // The (initial) position of the light lights.get(2).setDiffuseColor(0.0f, 0.0f, 0.8f); // The (initial) position of the light lights.get(0).setSpecularColor(0.1f, 0.1f, 0.1f); // The (initial) position of the light lights.get(0).setPosition(1.0f, 1.5f, 1.0f); // The (initial) position of the light lights.get(1).setPosition(0.0f, 1.0f, 0.0f); // The (initial) position of the light lights.get(2).setPosition(8.0f, 2.5f, -3.0f); // The (initial) position of the light glNav = new GLNavigation2(canvas); lights.setControl(glNav); // glNav.setPosition(0.0f, 1.65f, 3.0f); // The (initial) position of the camera glNav.setPosition(0.0f, 1.65f, 0.15f); // zoomed in on eye region glNav.setOrientation(0f, 0.0f, 0f); glNav.setLinearVelocity(0.7f); glNav.setVerticalVelocity(1.0f); glNav.setStrafeVelocity(1.0f); GLTextureLoader.addTextureDirectory("Humanoids/armandia/maps"); GLShaderProgramLoader.clearShaderPool(); GLShaderProgramLoader.addShaderDirectory("shaders"); //glScene = SceneIO.readGLScene("Humanoids/armandia/dae", "armandia-toplevel.dae", SceneIO.ARMANDIA) ; glScene = SceneIO.readGLScene("Humanoids/armandia/bin", "ArmandiaPupilSizeSetting.bin", SceneIO.NONE) ; avatarRootJoint = glScene.getToplevelVJoint(); glScene.sortGLShapeList(); GLRenderList shapeList = glScene.getGLShapeList(); avatarNode = new VGLNode(avatarRootJoint, shapeList); scene.addChild(avatarNode); GLMaterial leftPupil = glScene.getGLMaterial("Eye_L-mesh", "irisModified"); if (leftPupil != null) { leftPupil.setPupilSize(0.03f); // original/ummodified: 0.0586f } GLMaterial rightPupil = glScene.getGLMaterial("Eye_R-mesh", "irisModified"); if (rightPupil != null) { rightPupil.setPupilSize(0.05f); // original/ummodified: 0.0586f } } public synchronized void initTime(double t) { glNav.initTime(t); } public synchronized void time(double t) { glNav.time(t); sceneRoot.calculateMatrices(); glScene.deform(); } public synchronized void glInit(GLRenderContext glc) { openglState.glInit(glc); lights.glInit(glc); glNav.glInit(glc); scene.glInit(glc); } public synchronized void glRender(GLRenderContext glc) { openglState.glRender(glc); glNav.glRender(glc); lights.glRender(glc); scene.glRender(glc); hmi.graphics.opengl.GLUtil.reportGLErrors(glc); } }
lgpl-3.0
bahaa/nature-of-code
scripts/arrive.js
404
include('vehicle.js'); var vehicle = new Vehicle(); var target = new Point(0, 0); var targetCircle = new Path.Circle({ position: target, radius: 30, strokeColor: 'black', dashArray: [10, 4] }); function onMouseMove(event) { target = event.point; } function onFrame() { targetCircle.position = target; vehicle.arrive(target); vehicle.update(); vehicle.render(); }
unlicense
himesama1301/MizuMod
Source/MizuMod/CompWaterNetInput.cs
3816
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Verse; namespace MizuMod { public class CompWaterNetInput : CompWaterNet { public new CompProperties_WaterNetInput Props { get { return (CompProperties_WaterNetInput)this.props; } } public virtual float MaxInputWaterFlow { get { return this.Props.maxInputWaterFlow; } } //public virtual CompProperties_WaterNetInput.InputType InputType //{ // get // { // return this.Props.inputType; // } //} public virtual List<CompProperties_WaterNetInput.InputType> InputTypes { get { return this.Props.inputTypes; } } public virtual CompProperties_WaterNetInput.InputWaterFlowType InputWaterFlowType { get { return this.Props.inputWaterFlowType; } } public virtual List<WaterType> AcceptWaterTypes { get { return this.Props.acceptWaterTypes; } } public virtual float BaseRainFlow { get { return this.Props.baseRainFlow; } } public virtual float RoofEfficiency { get { return this.Props.roofEfficiency; } } public virtual int RoofDistance { get { return this.Props.roofDistance; } } // 水道網から流し込まれる水量 // Maxを超えていることもある public float InputWaterFlow { get; set; } public WaterType InputWaterType { get; set; } private bool HasTank { get { return this.TankComp != null; } } public bool IsReceiving { get { // 水道網から入力するタイプで、現在の入力量が0ではない⇒入力中 return this.InputTypes.Contains(CompProperties_WaterNetInput.InputType.WaterNet) && this.InputWaterFlow > 0f; } } // 入力機能が働いているか public override bool IsActivated { get { bool isOK = base.IsActivated && this.IsActivatedForWaterNet && (!this.HasTank || this.TankComp.AmountCanAccept > 0.0f); if (this.InputWaterFlowType == CompProperties_WaterNetInput.InputWaterFlowType.Constant) { isOK &= (this.InputWaterFlow >= this.MaxInputWaterFlow); } return isOK; } } public CompWaterNetInput() : base() { this.InputWaterType = WaterType.NoWater; } public override string CompInspectStringExtra() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.CompInspectStringExtra()); if (stringBuilder.ToString() != string.Empty) { stringBuilder.AppendLine(); } stringBuilder.Append(MizuStrings.InspectWaterFlowInput.Translate() + ": " + this.InputWaterFlow.ToString("F2") + " L/day"); stringBuilder.Append(string.Concat(new string[] { "(", MizuStrings.GetInspectWaterTypeString(this.InputWaterType), ")", })); return stringBuilder.ToString(); } } }
unlicense
ins-pirat-ion/chords-and-tabs
Suchy_Slitr-Praminek_vlasu.C
3212
Jiří Suchý - Pramínek vlasů https://www.youtube.com/watch?v=zOX299csGu8 Orig: E - Kapo: 4 I: 𝅘𝅥𝅮 [: bass C H A G F F F# G G A H C :] [: C Ami Dmi G6 G6 F#6 F6 :] 𝅘𝅥𝅮 whistle G F E C Ami Dmi7 F6 F#6 G6 G6 F#6 F6 C Ami Dmi7 F6 F#6 G6 G6 F#6 F6 𝅘𝅥𝅮 C C D E G G G A H C A G E D G F E C Ami Dmi7 F6 F#6 G6 G6 F#6 F6 C F7 C Dmi7 𝅘𝅥𝅮 C C D E G G G A H C C C D# D# D C G7 C Ami7 Dmi7 F6 F#6 G6 1. Když měsíc rozlije světlo své po kraji G6 F#6 F6 C Ami Dmi7 F6 F#6 G6 a hvězdy řeknou, že čas je jít spát, G6 F#6 F6 C Ami Dmi7 F6 F#6 G6 pramí nek vlasů jí ustřihnu potají, G6 F#6 F6 C F7 C G7 ko mu - no přece té, kterou mám rád. G7 C Ami7 Dmi7 F6 F#6 G6 2. Pramínek vlasů jí ustřihnu potají, G6 F#6 F6 C Ami Dmi7 F6 F#6 G6 já blá zen pod polštář chci si ho dát, G6 F#6 F6 C Ami Dmi7 F6 F#6 G6 ač ko liv sny se mi zásadně nezdají, G6 F#6 F6 C F7 C6 vě řím, že dnes v noci budou se zdát. R: B B A G# C B B A G# C O sny mě připraví teprve svítání, zpěv ptáků v oblacích a modré nebe, Ami7/5b C G#7 G76 od vlasů, jichž jsem se dotýkal ve spaní, nový den nůžkama odstřihne tebe. G7 C Ami7 Dmi7 F6 F#6 G6 4. A na bílém polštáři, do kroužku stočený, G6 F#6 F6 C Ami Dmi7 F6 F#6 G6 zbude tu po tobě pramínek vlasů, G6 F#6 F6 C Ami Dmi7 F6 F#6 G6 já ne bu du vstávat, dál chci ležet zasněný, G6 F#6 F6 C F7 C6 G76 je to tiž neděle a mám dost času, Solo: 2x trumpet, jazzy tune [:3x C Ami Dmi7 F6 F#6 G6 G6 F#6 F6 :] C F7 C Dmi7 𝅘𝅥𝅮 G A H C .... R: B B A G# C B B A G# C O sny mě připraví teprve svítání, zpěv ptáků v oblacích a modré nebe, Ami7/5b C G#7 G76 od vlasů, jichž jsem se dotýkal ve spaní, nový den nůžkama odstřihne tebe. G7 C Ami7 Dmi7 F6 F#6 G6 4. A na bílém polštáři, do kroužku stočený, G6 F#6 F6 C Ami Dmi7 F6 F#6 G6 zbude tu po tobě pramínek vlasů, G6 F#6 F6 C Ami Dmi7 F6 F#6 G6 já ne bu du vstávat, dál chci ležet zasněný, G6 F#6 F6 C F76 C6 F76 C F76 C6 F76 je to tiž neděle a mám dost času, je totiž neděle a mám dost času, C F76 C6 Ami7 Dmi7 G6 F#6 F6 Cmaj je totiž neděle a mám dost času,
unlicense
tarolandia/vinyl
lib/vinyl/rule.rb
2542
module Vinyl def self.when_route(route, *args) Rule.add(route, args[0]) end def self.acl_routes_collection Rule.acl_routes_collection end class Rule class RegExpHash < Hash def [](a) return super a if a.class == Regexp self.keys.each do |pattern| return super pattern if a.respond_to?(:match) && a.match(pattern) end return nil end end @@acl_routes_collection = RegExpHash.new def self.add(route, *args) begin method = args[0][:with_method] access_level = args[0][:get_access_level] validators = args[0][:if_pass] if(route.to_s.empty? || method.empty? || access_level.to_s.empty?) then raise InvalidAclRule, "Vinyl.rule is invalid" end rescue NoMethodError => e raise InvalidAclRule, "Vinyl.rule is invalid" rescue InvalidAclRule => e puts e.message puts e.backtrace end pattern = generate_pattern(route) @@acl_routes_collection[method] ||= RegExpHash.new @@acl_routes_collection[method][pattern] ||= Hash.new @@acl_routes_collection[method][pattern][access_level] = validators end #The ideas for this method were extracted from Sinatra's source #https://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb #Copyright (c) 2007, 2008, 2009, 2010, 2011 Blake Mizerany def self.generate_pattern(path) if path.respond_to? :to_str ignore = "" pattern = path.to_str.gsub(/[^\?\%\\\/\:\*\w]/) do |c| ignore << escaped(c).join if c.match(/[\.@]/) encoded(c) end pattern.gsub!(/((:\w+)|\*)/) do |match| if match == "*" "(.*?)" else "([^#{ignore}/?#]+)" end end /\A#{pattern}\z/ elsif path.respond_to?(:keys) && path.respond_to?(:match) path elsif path.respond_to?(:names) && path.respond_to?(:match) path elsif path.respond_to? :match path else raise TypeError, path end end def self.escaped(char, enc = URI.escape(char)) [Regexp.escape(enc), URI.escape(char, /./)] end def self.encoded(char) enc = URI.escape(char) enc = "(?:#{escaped(char, enc).join('|')})" if enc == char enc = "(?:#{enc}|#{encoded('+')})" if char == " " enc end def self.acl_routes_collection @@acl_routes_collection end end class InvalidAclRule < StandardError; end end
unlicense
ProgrammerDan/wolf-process-wrapper
WolfRandomPython.java
8561
package animals; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.OutputStreamWriter; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadPoolExecutor; /** * Remote WolfRandomPython wrapper class. */ public class WolfRandomPython extends Animal { /** * Simple test script that sends some typical commands to the * remote process. */ public static void main(String[]args){ WolfRandomPython[] wolves = new WolfRandomPython[100]; for(int i=0; i<10; i++) { wolves[i] = new WolfRandomPython(); } char map[][] = new char[3][3]; for (int i=0;i<9;i++) map[i/3][i%3]=' '; map[1][1] = 'W'; for(int i=0; i<10; i++) { wolves[i].surroundings=map; System.out.println(wolves[i].move()); } for(int i=0; i<10; i++) { System.out.println(wolves[i].fight('S')); System.out.println(wolves[i].fight('B')); System.out.println(wolves[i].fight('L')); System.out.println(wolves[i].fight('W')); } wolfProcess.endProcess(); } private static WolfProcess wolfProcess = null; private static WolfRandomPython[] wolves = new WolfRandomPython[100]; private static int nWolves = 0; private boolean isDead; private int id; /** * Sets up a remote process wolf. Note the static components. Only * a single process is generated for all Wolves of this type, new * wolves are "initialized" within the remote process, which is * maintained alongside the primary process. * Note this implementation makes heavy use of threads. */ public WolfRandomPython() { super('W'); if (WolfRandomPython.wolfProcess == null) { WolfRandomPython.wolfProcess = new WolfProcess(); WolfRandomPython.wolfProcess.start(); } if (WolfRandomPython.wolfProcess.initWolf(WolfRandomPython.nWolves, MAP_SIZE)) { this.id = WolfRandomPython.nWolves; this.isDead = false; WolfRandomPython.wolves[id] = this; } else { WolfRandomPython.wolfProcess.endProcess(); this.isDead = true; } WolfRandomPython.nWolves++; } /** * If the wolf is dead, or all the wolves of this type are dead, SUICIDE. * Otherwise, communicate an attack to the remote process and return * its attack choice. */ @Override public Attack fight(char opponent) { if (!WolfRandomPython.wolfProcess.getRunning() || isDead) { return Attack.SUICIDE; } try { Attack atk = WolfRandomPython.wolfProcess.fight(id, opponent); if (atk == Attack.SUICIDE) { this.isDead = true; } return atk; } catch (Exception e) { System.out.printf("Something terrible happened, this wolf has died: %s", e.getMessage()); isDead = true; return Attack.SUICIDE; } } /** * If the wolf is dead, or all the wolves of this type are dead, HOLD. * Otherwise, get a move from the remote process and return that. */ @Override public Move move() { if (!WolfRandomPython.wolfProcess.getRunning() || isDead) { return Move.HOLD; } try { Move mv = WolfRandomPython.wolfProcess.move(id, surroundings); return mv; } catch (Exception e) { System.out.printf("Something terrible happened, this wolf has died: %s", e.getMessage()); isDead = true; return Move.HOLD; } } /** * The shared static process manager, that synchronizes all communication * with the remote process. */ static class WolfProcess extends Thread { private Process process; private BufferedReader reader; private PrintWriter writer; private ExecutorService executor; private boolean running; public boolean getRunning() { return running; } public WolfProcess() { process = null; reader = null; writer = null; running = true; executor = Executors.newFixedThreadPool(1); } public void endProcess() { running = false; } /** * WolfProcess thread body. Keeps the remote connection alive. */ public void run() { try { System.out.println("Starting Wolf<custom-name> remote process"); ProcessBuilder pb = new ProcessBuilder("python PythonWolf.py".split(" ")); pb.redirectErrorStream(true); process = pb.start(); System.out.println("Wolf<custom-name> process begun"); // STDOUT of the process. reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); System.out.println("Wolf<custom-name> reader stream grabbed"); // STDIN of the process. writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream(), "UTF-8")); System.out.println("Wolf<custom-name> writer stream grabbed"); while(running){ this.sleep(0); } reader.close(); writer.close(); process.destroy(); // kill it with fire. executor.shutdownNow(); } catch (Exception e) { e.printStackTrace(); System.out.println("Wolf<custom-name> ended catastrophically."); } } /** * Helper that invokes a read with a timeout */ private String getReply(long timeout) throws TimeoutException, ExecutionException, InterruptedException{ Callable<String> readTask = new Callable<String>() { @Override public String call() throws Exception { return reader.readLine(); } }; Future<String> future = executor.submit(readTask); return future.get(timeout, TimeUnit.MILLISECONDS); } /** * Sends an initialization command to the remote process */ public synchronized boolean initWolf(int wolf, int map_sz) { while(writer == null){ try { this.sleep(0); }catch(Exception e){} } boolean success = false; try{ writer.printf("S%02d%d\n", wolf, map_sz); writer.flush(); String reply = getReply(5000l); if (reply != null && reply.length() >= 3 && reply.charAt(0) == 'K') { int id = Integer.valueOf(reply.substring(1)); if (wolf == id) { success = true; } } if (reply == null) { System.out.println("did not get reply"); } } catch (TimeoutException ie) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to initialize, timeout\n", wolf); } catch (Exception e) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to initialize, %s\n", wolf, e.getMessage()); } return success; } /** * Send an ATTACK command to the remote process. */ public synchronized Attack fight(int wolf, char opponent) { Attack atk = Attack.SUICIDE; try{ writer.printf("A%02d%c\n", wolf, opponent); writer.flush(); String reply = getReply(1000l); if (reply.length() >= 3) { int id = Integer.valueOf(reply.substring(1)); if (wolf == id) { switch(reply.charAt(0)) { case 'R': atk = Attack.ROCK; break; case 'P': atk = Attack.PAPER; break; case 'S': atk = Attack.SCISSORS; break; case 'D': atk = Attack.SUICIDE; break; } } } } catch (TimeoutException ie) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to attack, timeout\n", wolf); } catch (Exception e) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to attack, %s\n", wolf, e.getMessage()); } return atk; } /** * Send a MOVE command to the remote process. */ public synchronized Move move(int wolf, char[][] map) { Move move = Move.HOLD; try{ writer.printf("M%02d", wolf); for (int row=0; row<map.length; row++) { for (int col=0; col<map[row].length; col++) { writer.printf("%c", map[row][col]); } } writer.print("\n"); writer.flush(); String reply = getReply(1000l); if (reply.length() >= 3) { int id = Integer.valueOf(reply.substring(1)); if (wolf == id) { switch(reply.charAt(0)) { case 'H': move = Move.HOLD; break; case 'U': move = Move.UP; break; case 'L': move = Move.LEFT; break; case 'R': move = Move.RIGHT; break; case 'D': move = Move.DOWN; break; } } } } catch (TimeoutException ie) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to move, timeout\n", wolf); } catch (Exception e) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to move, %s\n", wolf, e.getMessage()); } return move; } } }
unlicense
g0rdan/EpubReader.Cross
Source/EpubReader.Cross/Entities/EpubTextContentFile.cs
153
namespace VersFx.Formats.Text.Epub { public class EpubTextContentFile : EpubContentFile { public string Content { get; set; } } }
unlicense