code
stringlengths
4
1.01M
language
stringclasses
2 values
## Introduction <b>vedgTools/QtWidgetsUtilities</b> is a general-purpose C++ library, which depends on QtCore and QtWidgets/QtGui libraries. Both Qt4 and Qt5 are supported. It also depends on vedgTools/CMakeModules and vedgTools/QtCoreUtilities libraries, which are present as submodules in this git repository. ## License Copyright (C) 2014 Igor Kushnir <igorkuo AT Google mail> vedgTools/QtWidgetsUtilities is licensed under the <b>GNU GPLv3+</b> license, a copy of which can be found in the `COPYING` file. vedgTools/QtWidgetsUtilities 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. vedgTools/QtWidgetsUtilities 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 vedgTools/QtWidgetsUtilities. If not, see <http://www.gnu.org/licenses/>.
Java
----------------------------------------- -- Spell: Protect ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local power = 15; local duration = 1800; duration = calculateDurationForLvl(duration, 7, target:getMainLvl()); if (caster:hasStatusEffect(EFFECT_PERPETUANCE)) then duration = duration * 2; end local typeEffect = EFFECT_PROTECT; local subPower = 0; if ((caster:getID() == target:getID()) and target:getEffectsCount(EFFECT_TELLUS) >= 1) then power = power * 1.25; subPower = 10; end power, duration = applyEmbolden(caster, power, duration); if (target:addStatusEffect(typeEffect, power, 0, duration, 0, subPower)) then spell:setMsg(230); else spell:setMsg(75); -- no effect end return typeEffect; end;
Java
/* ============================================================================== This file is part of the JUCE examples. Copyright (c) 2017 - ROLI Ltd. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ /******************************************************************************* The block below describes the properties of this PIP. A PIP is a short snippet of code that can be read by the Projucer and used to generate a JUCE project. BEGIN_JUCE_PIP_METADATA name: OpenGLAppDemo version: 1.0.0 vendor: JUCE website: http://juce.com description: Simple OpenGL application. dependencies: juce_core, juce_data_structures, juce_events, juce_graphics, juce_gui_basics, juce_gui_extra, juce_opengl exporters: xcode_mac, vs2017, xcode_iphone moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1 type: Component mainClass: OpenGLAppDemo useLocalCopy: 1 END_JUCE_PIP_METADATA *******************************************************************************/ #pragma once #include "../Assets/DemoUtilities.h" #include "../Assets/WavefrontObjParser.h" //============================================================================== /* This component lives inside our window, and this is where you should put all your controls and content. */ class OpenGLAppDemo : public OpenGLAppComponent { public: //============================================================================== OpenGLAppDemo() { setSize (800, 600); } ~OpenGLAppDemo() { shutdownOpenGL(); } void initialise() override { createShaders(); } void shutdown() override { shader .reset(); shape .reset(); attributes.reset(); uniforms .reset(); } Matrix3D<float> getProjectionMatrix() const { auto w = 1.0f / (0.5f + 0.1f); auto h = w * getLocalBounds().toFloat().getAspectRatio (false); return Matrix3D<float>::fromFrustum (-w, w, -h, h, 4.0f, 30.0f); } Matrix3D<float> getViewMatrix() const { Matrix3D<float> viewMatrix ({ 0.0f, 0.0f, -10.0f }); Matrix3D<float> rotationMatrix = viewMatrix.rotation ({ -0.3f, 5.0f * std::sin (getFrameCounter() * 0.01f), 0.0f }); return rotationMatrix * viewMatrix; } void render() override { jassert (OpenGLHelpers::isContextActive()); auto desktopScale = (float) openGLContext.getRenderingScale(); OpenGLHelpers::clear (getLookAndFeel().findColour (ResizableWindow::backgroundColourId)); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glViewport (0, 0, roundToInt (desktopScale * getWidth()), roundToInt (desktopScale * getHeight())); shader->use(); if (uniforms->projectionMatrix.get() != nullptr) uniforms->projectionMatrix->setMatrix4 (getProjectionMatrix().mat, 1, false); if (uniforms->viewMatrix.get() != nullptr) uniforms->viewMatrix->setMatrix4 (getViewMatrix().mat, 1, false); shape->draw (openGLContext, *attributes); // Reset the element buffers so child Components draw correctly openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, 0); openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0); } void paint (Graphics& g) override { // You can add your component specific drawing code here! // This will draw over the top of the openGL background. g.setColour (getLookAndFeel().findColour (Label::textColourId)); g.setFont (20); g.drawText ("OpenGL Example", 25, 20, 300, 30, Justification::left); g.drawLine (20, 20, 170, 20); g.drawLine (20, 50, 170, 50); } void resized() override { // This is called when this component is resized. // If you add any child components, this is where you should // update their positions. } void createShaders() { vertexShader = "attribute vec4 position;\n" "attribute vec4 sourceColour;\n" "attribute vec2 textureCoordIn;\n" "\n" "uniform mat4 projectionMatrix;\n" "uniform mat4 viewMatrix;\n" "\n" "varying vec4 destinationColour;\n" "varying vec2 textureCoordOut;\n" "\n" "void main()\n" "{\n" " destinationColour = sourceColour;\n" " textureCoordOut = textureCoordIn;\n" " gl_Position = projectionMatrix * viewMatrix * position;\n" "}\n"; fragmentShader = #if JUCE_OPENGL_ES "varying lowp vec4 destinationColour;\n" "varying lowp vec2 textureCoordOut;\n" #else "varying vec4 destinationColour;\n" "varying vec2 textureCoordOut;\n" #endif "\n" "void main()\n" "{\n" #if JUCE_OPENGL_ES " lowp vec4 colour = vec4(0.95, 0.57, 0.03, 0.7);\n" #else " vec4 colour = vec4(0.95, 0.57, 0.03, 0.7);\n" #endif " gl_FragColor = colour;\n" "}\n"; std::unique_ptr<OpenGLShaderProgram> newShader (new OpenGLShaderProgram (openGLContext)); String statusText; if (newShader->addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (vertexShader)) && newShader->addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (fragmentShader)) && newShader->link()) { shape .reset(); attributes.reset(); uniforms .reset(); shader.reset (newShader.release()); shader->use(); shape .reset (new Shape (openGLContext)); attributes.reset (new Attributes (openGLContext, *shader)); uniforms .reset (new Uniforms (openGLContext, *shader)); statusText = "GLSL: v" + String (OpenGLShaderProgram::getLanguageVersion(), 2); } else { statusText = newShader->getLastError(); } } private: //============================================================================== struct Vertex { float position[3]; float normal[3]; float colour[4]; float texCoord[2]; }; //============================================================================== // This class just manages the attributes that the shaders use. struct Attributes { Attributes (OpenGLContext& openGLContext, OpenGLShaderProgram& shaderProgram) { position .reset (createAttribute (openGLContext, shaderProgram, "position")); normal .reset (createAttribute (openGLContext, shaderProgram, "normal")); sourceColour .reset (createAttribute (openGLContext, shaderProgram, "sourceColour")); textureCoordIn.reset (createAttribute (openGLContext, shaderProgram, "textureCoordIn")); } void enable (OpenGLContext& glContext) { if (position.get() != nullptr) { glContext.extensions.glVertexAttribPointer (position->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof (Vertex), nullptr); glContext.extensions.glEnableVertexAttribArray (position->attributeID); } if (normal.get() != nullptr) { glContext.extensions.glVertexAttribPointer (normal->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 3)); glContext.extensions.glEnableVertexAttribArray (normal->attributeID); } if (sourceColour.get() != nullptr) { glContext.extensions.glVertexAttribPointer (sourceColour->attributeID, 4, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 6)); glContext.extensions.glEnableVertexAttribArray (sourceColour->attributeID); } if (textureCoordIn.get() != nullptr) { glContext.extensions.glVertexAttribPointer (textureCoordIn->attributeID, 2, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 10)); glContext.extensions.glEnableVertexAttribArray (textureCoordIn->attributeID); } } void disable (OpenGLContext& glContext) { if (position.get() != nullptr) glContext.extensions.glDisableVertexAttribArray (position->attributeID); if (normal.get() != nullptr) glContext.extensions.glDisableVertexAttribArray (normal->attributeID); if (sourceColour.get() != nullptr) glContext.extensions.glDisableVertexAttribArray (sourceColour->attributeID); if (textureCoordIn.get() != nullptr) glContext.extensions.glDisableVertexAttribArray (textureCoordIn->attributeID); } std::unique_ptr<OpenGLShaderProgram::Attribute> position, normal, sourceColour, textureCoordIn; private: static OpenGLShaderProgram::Attribute* createAttribute (OpenGLContext& openGLContext, OpenGLShaderProgram& shader, const char* attributeName) { if (openGLContext.extensions.glGetAttribLocation (shader.getProgramID(), attributeName) < 0) return nullptr; return new OpenGLShaderProgram::Attribute (shader, attributeName); } }; //============================================================================== // This class just manages the uniform values that the demo shaders use. struct Uniforms { Uniforms (OpenGLContext& openGLContext, OpenGLShaderProgram& shaderProgram) { projectionMatrix.reset (createUniform (openGLContext, shaderProgram, "projectionMatrix")); viewMatrix .reset (createUniform (openGLContext, shaderProgram, "viewMatrix")); } std::unique_ptr<OpenGLShaderProgram::Uniform> projectionMatrix, viewMatrix; private: static OpenGLShaderProgram::Uniform* createUniform (OpenGLContext& openGLContext, OpenGLShaderProgram& shaderProgram, const char* uniformName) { if (openGLContext.extensions.glGetUniformLocation (shaderProgram.getProgramID(), uniformName) < 0) return nullptr; return new OpenGLShaderProgram::Uniform (shaderProgram, uniformName); } }; //============================================================================== /** This loads a 3D model from an OBJ file and converts it into some vertex buffers that we can draw. */ struct Shape { Shape (OpenGLContext& glContext) { if (shapeFile.load (loadEntireAssetIntoString ("teapot.obj")).wasOk()) for (auto* shapeVertices : shapeFile.shapes) vertexBuffers.add (new VertexBuffer (glContext, *shapeVertices)); } void draw (OpenGLContext& glContext, Attributes& glAttributes) { for (auto* vertexBuffer : vertexBuffers) { vertexBuffer->bind(); glAttributes.enable (glContext); glDrawElements (GL_TRIANGLES, vertexBuffer->numIndices, GL_UNSIGNED_INT, nullptr); glAttributes.disable (glContext); } } private: struct VertexBuffer { VertexBuffer (OpenGLContext& context, WavefrontObjFile::Shape& aShape) : openGLContext (context) { numIndices = aShape.mesh.indices.size(); openGLContext.extensions.glGenBuffers (1, &vertexBuffer); openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer); Array<Vertex> vertices; createVertexListFromMesh (aShape.mesh, vertices, Colours::green); openGLContext.extensions.glBufferData (GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (static_cast<size_t> (vertices.size()) * sizeof (Vertex)), vertices.getRawDataPointer(), GL_STATIC_DRAW); openGLContext.extensions.glGenBuffers (1, &indexBuffer); openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer); openGLContext.extensions.glBufferData (GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr> (static_cast<size_t> (numIndices) * sizeof (juce::uint32)), aShape.mesh.indices.getRawDataPointer(), GL_STATIC_DRAW); } ~VertexBuffer() { openGLContext.extensions.glDeleteBuffers (1, &vertexBuffer); openGLContext.extensions.glDeleteBuffers (1, &indexBuffer); } void bind() { openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer); openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer); } GLuint vertexBuffer, indexBuffer; int numIndices; OpenGLContext& openGLContext; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VertexBuffer) }; WavefrontObjFile shapeFile; OwnedArray<VertexBuffer> vertexBuffers; static void createVertexListFromMesh (const WavefrontObjFile::Mesh& mesh, Array<Vertex>& list, Colour colour) { auto scale = 0.2f; WavefrontObjFile::TextureCoord defaultTexCoord { 0.5f, 0.5f }; WavefrontObjFile::Vertex defaultNormal { 0.5f, 0.5f, 0.5f }; for (auto i = 0; i < mesh.vertices.size(); ++i) { const auto& v = mesh.vertices.getReference (i); const auto& n = i < mesh.normals.size() ? mesh.normals.getReference (i) : defaultNormal; const auto& tc = i < mesh.textureCoords.size() ? mesh.textureCoords.getReference (i) : defaultTexCoord; list.add ({ { scale * v.x, scale * v.y, scale * v.z, }, { scale * n.x, scale * n.y, scale * n.z, }, { colour.getFloatRed(), colour.getFloatGreen(), colour.getFloatBlue(), colour.getFloatAlpha() }, { tc.x, tc.y } }); } } }; const char* vertexShader; const char* fragmentShader; std::unique_ptr<OpenGLShaderProgram> shader; std::unique_ptr<Shape> shape; std::unique_ptr<Attributes> attributes; std::unique_ptr<Uniforms> uniforms; String newVertexShader, newFragmentShader; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLAppDemo) };
Java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn 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. * * Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.engine.backgroundtasks.config; /** * <p> * Class containing strings that describe the Kafka queues and groups * </p> * * @author Denis Lobanov, alexandraorth */ public interface KafkaTerms { String TASK_RUNNER_GROUP = "task-runners"; String SCHEDULERS_GROUP = "schedulers"; String WORK_QUEUE_TOPIC = "work-queue"; String NEW_TASKS_TOPIC = "new-tasks"; String LOG_TOPIC = "logs"; }
Java
use sha1::{Sha1, Digest}; use std::fs; let mut file = fs::File::open(&path)?; let hash = Sha1::digest_reader(&mut file)?;
Java
abstract class Adjunction[F[_], U[_]]( implicit val F: Functor[F], val U: Representable[U] ){ def unit[A](a: A): U[F[A]] def counit[A](a: F[U[A]]): A }
Java
function HistoryAssistant() { } HistoryAssistant.prototype.setup = function() { this.appMenuModel = { visible: true, items: [ { label: $L("About"), command: 'about' }, { label: $L("Help"), command: 'tutorial' }, ] }; this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel); var attributes = {}; this.model = { //backgroundImage : 'images/glacier.png', background: 'black', onLeftFunction : this.wentLeft.bind(this), onRightFunction : this.wentRight.bind(this) } this.controller.setupWidget('historydiv', attributes, this.model); this.myPhotoDivElement = $('historydiv'); this.timestamp = new Date().getTime(); var env = Mojo.Environment.DeviceInfo; if (env.screenHeight <= 400) this.myPhotoDivElement.style.height = "372px"; } HistoryAssistant.prototype.wentLeft = function(event){ this.timestamp = this.timestamp - (1000*60*60*24); var timenow = new Date(this.timestamp); var timenowstring = ""; var Ayear = timenow.getUTCFullYear(); var Amonth = timenow.getUTCMonth()+1; if(Amonth.toString().length < 2) Amonth = "0" + Amonth; var Aday = timenow.getUTCDate(); if(Aday.toString().length < 2) Aday = "0" + Aday; /*var Ahours = timenow.getUTCHours(); if(Ahours.toString().length < 2) Ahours = "0" + Ahours;*/ Ahours = "00"; if (this.timestamp > 1276146000000) { if (this.timestamp > 1276146000000 + (1000 * 60 * 60 * 24)) { this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday - 1) + Ahours + ".png"); } this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png"); this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday + 1) + Ahours + ".png"); } $('text').innerHTML = "<center>Histoy Of Pixels&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;" + Ayear + " / " + Amonth + " / " + Aday + "</center>"; } HistoryAssistant.prototype.wentRight = function(event){ this.timestamp = this.timestamp + (1000*60*60*24); var timenow = new Date(this.timestamp); var timenowstring = ""; var Ayear = timenow.getUTCFullYear(); var Amonth = timenow.getUTCMonth()+1; if(Amonth.toString().length < 2) Amonth = "0" + Amonth; var Aday = timenow.getUTCDate(); if(Aday.toString().length < 2) Aday = "0" + Aday; /*var Ahours = timenow.getUTCHours(); if(Ahours.toString().length < 2) Ahours = "0" + Ahours;*/ Ahours = "00"; if (this.timestamp < new Date().getTime()) { this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday - 1) + Ahours + ".png"); this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png"); if (this.timestamp + (1000*60*60*24) < new Date().getTime()) { this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday + 1) + Ahours + ".png"); } } $('text').innerHTML = "<center>Histoy Of Pixels&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;" + Ayear + " / " + Amonth + " / " + Aday + "</center>"; } HistoryAssistant.prototype.activate = function(event) { var timenow = new Date(this.timestamp); var timenowstring = ""; var Ayear = timenow.getUTCFullYear(); var Amonth = timenow.getUTCMonth()+1; if(Amonth.toString().length < 2) Amonth = "0" + Amonth; var Aday = timenow.getUTCDate(); if(Aday.toString().length < 2) Aday = "0" + Aday; /*var Ahours = timenow.getUTCHours(); if(Ahours.toString().length < 2) Ahours = "0" + Ahours;*/ Ahours = "00"; this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday-1) + Ahours + ".png"); this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png"); //this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday+1) + Ahours + ".png"); $('text').innerHTML = "<center>Histoy Of Pixels&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;" + Ayear + " / " + Amonth + " / " + Aday + "</center>"; } HistoryAssistant.prototype.deactivate = function(event) { } HistoryAssistant.prototype.cleanup = function(event) { } HistoryAssistant.prototype.handleCommand = function(event){ if(event.type == Mojo.Event.command) { switch (event.command) { case 'about': Mojo.Controller.stageController.pushScene("about"); break; case 'tutorial': this.controller.showAlertDialog({ onChoose: function(value) {}, title:"Help", message:"This is the history of all pixels user have every created. Every night there is made a new snapshot.<br><br>Flip the image left or right to go through the history. Zoom into the image for more details.", allowHTMLMessage: true, choices:[ {label:'OK', value:'OK', type:'color'} ] }); break; } } }
Java
# -*- coding: utf-8 -*- import logging from pprint import pformat from time import clock, sleep try: import unittest2 as unittest except ImportError: import unittest import config from event_stack import TimeOutReached from database_reception import Database_Reception from static_agent_pools import Receptionists, Customers logging.basicConfig (level = logging.INFO) class Test_Case (unittest.TestCase): Caller = None Receptionist = None Receptionist_2 = None Callee = None Reception_Database = None Reception = None Start_Time = None Next_Step = 1 def Preconditions (self, Reception): self.Start_Time = clock () self.Next_Step = 1 self.Log ("Incoming calls test case: Setting up preconditions...") self.Log ("Requesting a customer (caller)...") self.Caller = Customers.request () self.Log ("Requesting a receptionist...") self.Receptionist = Receptionists.request () self.Log ("Requesting a second receptionist...") self.Receptionist_2 = Receptionists.request () self.Log ("Requesting a customer (callee)...") self.Callee = Customers.request () self.Log ("Select which reception to test...") self.Reception = Reception self.Log ("Select a reception database connection...") self.Reception_Database = Database_Reception (uri = config.reception_server_uri, authtoken = self.Receptionist.call_control.authtoken) def Postprocessing (self): self.Log ("Incoming calls test case: Cleaning up after test...") if not self.Caller is None: self.Caller.release () if not self.Receptionist is None: self.Receptionist.release () if not self.Receptionist_2 is None: self.Receptionist_2.release () if not self.Callee is None: self.Callee.release () def Step (self, Message, Delay_In_Seconds = 0.0): if self.Next_Step is None: self.Next_Step = 1 if self.Start_Time is None: self.Start_Time = clock () logging.info ("Step " + str (self.Next_Step) + ": " + Message) sleep (Delay_In_Seconds) self.Next_Step += 1 def Log (self, Message, Delay_In_Seconds = 0.0): if self.Next_Step is None: self.Next_Step = 1 if self.Start_Time is None: self.Start_Time = clock () logging.info (" " + str (self.Next_Step - 1) + ": " + Message) sleep (Delay_In_Seconds) def Caller_Places_Call (self, Number): self.Step (Message = "Caller places call to " + str (Number) + "...") self.Log (Message = "Dialling through caller agent...") self.Caller.dial (Number) def Receptionist_Places_Call (self, Number): self.Step (Message = "Receptionist places call to " + str (Number) + "...") self.Log (Message = "Dialling through receptionist agent...") self.Receptionist.dial (Number) def Caller_Hears_Dialtone (self): self.Step (Message = "Caller hears dial-tone...") self.Log (Message = "Caller agent waits for dial-tone...") self.Caller.sip_phone.Wait_For_Dialtone () def Receptionist_Hears_Dialtone (self): self.Step (Message = "Receptionist hears dial-tone...") self.Log (Message = "Receptionist agent waits for dial-tone...") self.Receptionist.sip_phone.Wait_For_Dialtone () def Call_Announced (self): self.Step (Message = "Receptionist's client waits for 'call_offer'...") try: self.Receptionist.event_stack.WaitFor ("call_offer") except TimeOutReached: logging.critical (self.Receptionist.event_stack.dump_stack ()) self.fail ("Call offer didn't arrive from Call-Flow-Control.") if not self.Receptionist.event_stack.stack_contains (event_type="call_offer", destination=self.Reception): logging.critical (self.Receptionist.event_stack.dump_stack ()) self.fail ("The arrived call offer was not for the expected reception (destination).") return self.Receptionist.event_stack.Get_Latest_Event (Event_Type="call_offer", Destination=self.Reception)['call']['id'],\ self.Receptionist.event_stack.Get_Latest_Event (Event_Type="call_offer", Destination=self.Reception)['call']['reception_id'] def Call_Announced_As_Locked (self, Call_ID): self.Step (Message = "Call-Flow-Control sends out 'call_lock'...") try: self.Receptionist.event_stack.WaitFor (event_type = "call_lock", call_id = Call_ID, timeout = 20.0) except TimeOutReached: logging.critical (self.Receptionist.event_stack.dump_stack ()) self.fail ("No 'call_lock' event arrived from Call-Flow-Control.") if not self.Receptionist.event_stack.stack_contains (event_type = "call_lock", destination = self.Reception, call_id = Call_ID): logging.critical (self.Receptionist.event_stack.dump_stack ()) self.fail ("The arrived 'call_lock' event was not for the expected reception (destination).") def Call_Announced_As_Unlocked (self, Call_ID): self.Step (Message = "Call-Flow-Control sends out 'call_unlock'...") try: self.Receptionist.event_stack.WaitFor (event_type = "call_unlock", call_id = Call_ID) except TimeOutReached: logging.critical (self.Receptionist.event_stack.dump_stack ()) self.fail ("No 'call_unlock' event arrived from Call-Flow-Control.") if not self.Receptionist.event_stack.stack_contains (event_type = "call_unlock", destination = self.Reception, call_id = Call_ID): logging.critical (self.Receptionist.event_stack.dump_stack ()) self.fail ("The arrived 'call_unlock' event was not for the expected reception (destination).") def Request_Information (self, Reception_ID): self.Step (Message = "Requesting (updated) information about reception " + str (Reception_ID)) Data_On_Reception = self.Reception_Database.Single (Reception_ID) self.Step (Message = "Received information on reception " + str (Reception_ID)) return Data_On_Reception def Offer_To_Pick_Up_Call (self, Call_Flow_Control, Call_ID): self.Step (Message = "Client offers to answer call...") try: Call_Flow_Control.PickupCall (call_id = Call_ID) except: self.Log (Message = "Pick-up call returned an error of some kind.") def Call_Allocation_Acknowledgement (self, Call_ID, Receptionist_ID): self.Step (Message = "Receptionist's client waits for 'call_pickup'...") try: self.Receptionist.event_stack.WaitFor (event_type = "call_pickup", call_id = Call_ID) except TimeOutReached: logging.critical (self.Receptionist.event_stack.dump_stack ()) self.fail ("No 'call_pickup' event arrived from Call-Flow-Control.") try: Event = self.Receptionist.event_stack.Get_Latest_Event (Event_Type = "call_pickup", Call_ID = Call_ID) except: logging.critical (self.Receptionist.event_stack.dump_stack ()) self.fail ("Could not extract the received 'call_pickup' event from the Call-Flow-Control client.") try: if not Event['call']['assigned_to'] == Receptionist_ID: logging.critical (self.Receptionist.event_stack.dump_stack ()) self.fail ("The arrived 'call_pickup' event was for " + str (Event['call']['assigned_to']) + ", and not for " + str (Receptionist_ID) + " as expected.") except: logging.critical (self.Receptionist.event_stack.dump_stack ()) raise self.Log (Message = "Call picked up: " + pformat (Event)) return Event def Receptionist_Answers (self, Call_Information, Reception_Information, After_Greeting_Played): self.Step (Message = "Receptionist answers...") if Call_Information['call']['greeting_played']: try: self.Log (Message = "Receptionist says '" + Reception_Information['short_greeting'] + "'.") except: self.fail ("Reception information missing 'short_greeting'.") else: try: self.Log (Message = "Receptionist says '" + Reception_Information['greeting'] + "'.") except: self.fail ("Reception information missing 'greeting'.") if After_Greeting_Played: if not Call_Information['call']['greeting_played']: self.fail ("It appears that the receptionist didn't wait long enough to allow the caller to hear the recorded message.") else: if Call_Information['call']['greeting_played']: self.fail ("It appears that the receptionist waited too long, and allowed the caller to hear the recorded message.")
Java
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Transaction data structure. use std::ops::Deref; use rlp::*; use util::sha3::Hashable; use util::{H256, Address, U256, Bytes, HeapSizeOf}; use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError}; use error::*; use evm::Schedule; use header::BlockNumber; use ethjson; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] /// Transaction action type. pub enum Action { /// Create creates new contract. Create, /// Calls contract at given address. /// In the case of a transfer, this is the receiver's address.' Call(Address), } impl Default for Action { fn default() -> Action { Action::Create } } impl Decodable for Action { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let rlp = decoder.as_rlp(); if rlp.is_empty() { Ok(Action::Create) } else { Ok(Action::Call(rlp.as_val()?)) } } } /// Transaction activation condition. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub enum Condition { /// Valid at this block number or later. Number(BlockNumber), /// Valid at this unix time or later. Timestamp(u64), } /// A set of information describing an externally-originating message call /// or contract creation operation. #[derive(Default, Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct Transaction { /// Nonce. pub nonce: U256, /// Gas price. pub gas_price: U256, /// Gas paid up front for transaction execution. pub gas: U256, /// Action, can be either call or contract create. pub action: Action, /// Transfered value. pub value: U256, /// Transaction data. pub data: Bytes, } impl Transaction { /// Append object with a without signature into RLP stream pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream, network_id: Option<u64>) { s.begin_list(if network_id.is_none() { 6 } else { 9 }); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); match self.action { Action::Create => s.append_empty_data(), Action::Call(ref to) => s.append(to) }; s.append(&self.value); s.append(&self.data); if let Some(n) = network_id { s.append(&n); s.append(&0u8); s.append(&0u8); } } } impl HeapSizeOf for Transaction { fn heap_size_of_children(&self) -> usize { self.data.heap_size_of_children() } } impl From<ethjson::state::Transaction> for SignedTransaction { fn from(t: ethjson::state::Transaction) -> Self { let to: Option<ethjson::hash::Address> = t.to.into(); let secret = Secret::from_slice(&t.secret.0).expect("Valid secret expected."); Transaction { nonce: t.nonce.into(), gas_price: t.gas_price.into(), gas: t.gas_limit.into(), action: match to { Some(to) => Action::Call(to.into()), None => Action::Create }, value: t.value.into(), data: t.data.into(), }.sign(&secret, None) } } impl From<ethjson::transaction::Transaction> for UnverifiedTransaction { fn from(t: ethjson::transaction::Transaction) -> Self { let to: Option<ethjson::hash::Address> = t.to.into(); UnverifiedTransaction { unsigned: Transaction { nonce: t.nonce.into(), gas_price: t.gas_price.into(), gas: t.gas_limit.into(), action: match to { Some(to) => Action::Call(to.into()), None => Action::Create }, value: t.value.into(), data: t.data.into(), }, r: t.r.into(), s: t.s.into(), v: t.v.into(), hash: 0.into(), }.compute_hash() } } impl Transaction { /// The message hash of the transaction. pub fn hash(&self, network_id: Option<u64>) -> H256 { let mut stream = RlpStream::new(); self.rlp_append_unsigned_transaction(&mut stream, network_id); stream.as_raw().sha3() } /// Signs the transaction as coming from `sender`. pub fn sign(self, secret: &Secret, network_id: Option<u64>) -> SignedTransaction { let sig = ::ethkey::sign(secret, &self.hash(network_id)) .expect("data is valid and context has signing capabilities; qed"); SignedTransaction::new(self.with_signature(sig, network_id)) .expect("secret is valid so it's recoverable") } /// Signs the transaction with signature. pub fn with_signature(self, sig: Signature, network_id: Option<u64>) -> UnverifiedTransaction { UnverifiedTransaction { unsigned: self, r: sig.r().into(), s: sig.s().into(), v: sig.v() as u64 + if let Some(n) = network_id { 35 + n * 2 } else { 27 }, hash: 0.into(), }.compute_hash() } /// Useful for test incorrectly signed transactions. #[cfg(test)] pub fn invalid_sign(self) -> UnverifiedTransaction { UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash() } /// Specify the sender; this won't survive the serialize/deserialize process, but can be cloned. pub fn fake_sign(self, from: Address) -> SignedTransaction { SignedTransaction { transaction: UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash(), sender: from, public: Public::default(), } } /// Get the transaction cost in gas for the given params. pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 { data.iter().fold( (if is_create {schedule.tx_create_gas} else {schedule.tx_gas}) as u64, |g, b| g + (match *b { 0 => schedule.tx_data_zero_gas, _ => schedule.tx_data_non_zero_gas }) as u64 ) } /// Get the transaction cost in gas for this transaction. pub fn gas_required(&self, schedule: &Schedule) -> u64 { Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule) } } /// Signed transaction information. #[derive(Debug, Clone, Eq, PartialEq)] #[cfg_attr(feature = "ipc", binary)] pub struct UnverifiedTransaction { /// Plain Transaction. unsigned: Transaction, /// The V field of the signature; the LS bit described which half of the curve our point falls /// in. The MS bits describe which network this transaction is for. If 27/28, its for all networks. v: u64, /// The R field of the signature; helps describe the point on the curve. r: U256, /// The S field of the signature; helps describe the point on the curve. s: U256, /// Hash of the transaction hash: H256, } impl Deref for UnverifiedTransaction { type Target = Transaction; fn deref(&self) -> &Self::Target { &self.unsigned } } impl Decodable for UnverifiedTransaction { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let d = decoder.as_rlp(); if d.item_count() != 9 { return Err(DecoderError::RlpIncorrectListLen); } let hash = decoder.as_raw().sha3(); Ok(UnverifiedTransaction { unsigned: Transaction { nonce: d.val_at(0)?, gas_price: d.val_at(1)?, gas: d.val_at(2)?, action: d.val_at(3)?, value: d.val_at(4)?, data: d.val_at(5)?, }, v: d.val_at(6)?, r: d.val_at(7)?, s: d.val_at(8)?, hash: hash, }) } } impl Encodable for UnverifiedTransaction { fn rlp_append(&self, s: &mut RlpStream) { self.rlp_append_sealed_transaction(s) } } impl UnverifiedTransaction { /// Used to compute hash of created transactions fn compute_hash(mut self) -> UnverifiedTransaction { let hash = (&*self.rlp_bytes()).sha3(); self.hash = hash; self } /// Append object with a signature into RLP stream fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) { s.begin_list(9); s.append(&self.nonce); s.append(&self.gas_price); s.append(&self.gas); match self.action { Action::Create => s.append_empty_data(), Action::Call(ref to) => s.append(to) }; s.append(&self.value); s.append(&self.data); s.append(&self.v); s.append(&self.r); s.append(&self.s); } /// Reference to unsigned part of this transaction. pub fn as_unsigned(&self) -> &Transaction { &self.unsigned } /// 0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid. pub fn standard_v(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => ((v - 1) % 2) as u8, _ => 4 } } /// The `v` value that appears in the RLP. pub fn original_v(&self) -> u64 { self.v } /// The network ID, or `None` if this is a global transaction. pub fn network_id(&self) -> Option<u64> { match self.v { v if v > 36 => Some((v - 35) / 2), _ => None, } } /// Construct a signature object from the sig. pub fn signature(&self) -> Signature { Signature::from_rsv(&self.r.into(), &self.s.into(), self.standard_v()) } /// Checks whether the signature has a low 's' value. pub fn check_low_s(&self) -> Result<(), Error> { if !self.signature().is_low_s() { Err(EthkeyError::InvalidSignature.into()) } else { Ok(()) } } /// Get the hash of this header (sha3 of the RLP). pub fn hash(&self) -> H256 { self.hash } /// Recovers the public key of the sender. pub fn recover_public(&self) -> Result<Public, Error> { Ok(recover(&self.signature(), &self.unsigned.hash(self.network_id()))?) } /// Do basic validation, checking for valid signature and minimum gas, // TODO: consider use in block validation. #[cfg(test)] #[cfg(feature = "json-tests")] pub fn validate(self, schedule: &Schedule, require_low: bool, allow_network_id_of_one: bool) -> Result<UnverifiedTransaction, Error> { if require_low && !self.signature().is_low_s() { return Err(EthkeyError::InvalidSignature.into()) } match self.network_id() { None => {}, Some(1) if allow_network_id_of_one => {}, _ => return Err(TransactionError::InvalidNetworkId.into()), } self.recover_public()?; if self.gas < U256::from(self.gas_required(&schedule)) { Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into()) } else { Ok(self) } } } /// A `UnverifiedTransaction` with successfully recovered `sender`. #[derive(Debug, Clone, Eq, PartialEq)] pub struct SignedTransaction { transaction: UnverifiedTransaction, sender: Address, public: Public, } impl HeapSizeOf for SignedTransaction { fn heap_size_of_children(&self) -> usize { self.transaction.unsigned.heap_size_of_children() } } impl Encodable for SignedTransaction { fn rlp_append(&self, s: &mut RlpStream) { self.transaction.rlp_append_sealed_transaction(s) } } impl Deref for SignedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { &self.transaction } } impl From<SignedTransaction> for UnverifiedTransaction { fn from(tx: SignedTransaction) -> Self { tx.transaction } } impl SignedTransaction { /// Try to verify transaction and recover sender. pub fn new(transaction: UnverifiedTransaction) -> Result<Self, Error> { let public = transaction.recover_public()?; let sender = public_to_address(&public); Ok(SignedTransaction { transaction: transaction, sender: sender, public: public, }) } /// Returns transaction sender. pub fn sender(&self) -> Address { self.sender } /// Returns a public key of the sender. pub fn public_key(&self) -> Public { self.public } } /// Signed Transaction that is a part of canon blockchain. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct LocalizedTransaction { /// Signed part. pub signed: UnverifiedTransaction, /// Block number. pub block_number: BlockNumber, /// Block hash. pub block_hash: H256, /// Transaction index within block. pub transaction_index: usize, /// Cached sender pub cached_sender: Option<Address>, } impl LocalizedTransaction { /// Returns transaction sender. /// Panics if `LocalizedTransaction` is constructed using invalid `UnverifiedTransaction`. pub fn sender(&mut self) -> Address { if let Some(sender) = self.cached_sender { return sender; } let sender = public_to_address(&self.recover_public() .expect("LocalizedTransaction is always constructed from transaction from blockchain; Blockchain only stores verified transactions; qed")); self.cached_sender = Some(sender); sender } } impl Deref for LocalizedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { &self.signed } } /// Queued transaction with additional information. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct PendingTransaction { /// Signed transaction data. pub transaction: SignedTransaction, /// To be activated at this condition. `None` for immediately. pub condition: Option<Condition>, } impl PendingTransaction { /// Create a new pending transaction from signed transaction. pub fn new(signed: SignedTransaction, condition: Option<Condition>) -> Self { PendingTransaction { transaction: signed, condition: condition, } } } impl Deref for PendingTransaction { type Target = SignedTransaction; fn deref(&self) -> &SignedTransaction { &self.transaction } } impl From<SignedTransaction> for PendingTransaction { fn from(t: SignedTransaction) -> Self { PendingTransaction { transaction: t, condition: None, } } } #[test] fn sender_test() { let t: UnverifiedTransaction = decode(&::rustc_serialize::hex::FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); assert_eq!(t.data, b""); assert_eq!(t.gas, U256::from(0x5208u64)); assert_eq!(t.gas_price, U256::from(0x01u64)); assert_eq!(t.nonce, U256::from(0x00u64)); if let Action::Call(ref to) = t.action { assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".into()); } else { panic!(); } assert_eq!(t.value, U256::from(0x0au64)); assert_eq!(public_to_address(&t.recover_public().unwrap()), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".into()); assert_eq!(t.network_id(), None); } #[test] fn signing() { use ethkey::{Random, Generator}; let key = Random.generate().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), None); assert_eq!(Address::from(key.public().sha3()), t.sender()); assert_eq!(t.network_id(), None); } #[test] fn fake_signing() { let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.fake_sign(Address::from(0x69)); assert_eq!(Address::from(0x69), t.sender()); assert_eq!(t.network_id(), None); let t = t.clone(); assert_eq!(Address::from(0x69), t.sender()); assert_eq!(t.network_id(), None); } #[test] fn should_recover_from_network_specific_signing() { use ethkey::{Random, Generator}; let key = Random.generate().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), gas_price: U256::from(3000), gas: U256::from(50_000), value: U256::from(1), data: b"Hello!".to_vec() }.sign(&key.secret(), Some(69)); assert_eq!(Address::from(key.public().sha3()), t.sender()); assert_eq!(t.network_id(), Some(69)); } #[test] fn should_agree_with_vitalik() { use rustc_serialize::hex::FromHex; let test_vector = |tx_data: &str, address: &'static str| { let signed = decode(&FromHex::from_hex(tx_data).unwrap()); let signed = SignedTransaction::new(signed).unwrap(); assert_eq!(signed.sender(), address.into()); flushln!("networkid: {:?}", signed.network_id()); }; test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "0xf0f6f18bca1b28cd68e4357452947e021241e9ce"); test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "0x23ef145a395ea3fa3deb533b8a9e1b4c6c25d112"); test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "0x2e485e0c23b4c3c542628a5f672eeab0ad4888be"); test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "0x82a88539669a3fd524d669e858935de5e5410cf0"); test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "0xf9358f2538fd5ccfeb848b64a96b743fcc930554"); test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "0xa8f7aba377317440bc5b26198a363ad22af1f3a4"); test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "0xf1f571dc362a0e5b2696b8e775f8491d3e50de35"); test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "0xd37922162ab7cea97c97a87551ed02c9a38b7332"); test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "0x9bddad43f934d313c2b79ca28a432dd2b7281029"); test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "0x3c24d7329e92f84f08556ceb6df1cdb0104ca49f"); }
Java
#pragma once #include <ros/assert.h> #include <iostream> #include <eigen3/Eigen/Dense> #include "../utility/utility.h" #include "../parameters.h" #include "integration_base.h" #include <ceres/ceres.h> class IMUFactor : public ceres::SizedCostFunction<15, 7, 9, 7, 9> { public: IMUFactor() = delete; IMUFactor(IntegrationBase* _pre_integration):pre_integration(_pre_integration) { } virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const { Eigen::Vector3d Pi(parameters[0][0], parameters[0][1], parameters[0][2]); Eigen::Quaterniond Qi(parameters[0][6], parameters[0][3], parameters[0][4], parameters[0][5]); Eigen::Vector3d Vi(parameters[1][0], parameters[1][1], parameters[1][2]); Eigen::Vector3d Bai(parameters[1][3], parameters[1][4], parameters[1][5]); Eigen::Vector3d Bgi(parameters[1][6], parameters[1][7], parameters[1][8]); Eigen::Vector3d Pj(parameters[2][0], parameters[2][1], parameters[2][2]); Eigen::Quaterniond Qj(parameters[2][6], parameters[2][3], parameters[2][4], parameters[2][5]); Eigen::Vector3d Vj(parameters[3][0], parameters[3][1], parameters[3][2]); Eigen::Vector3d Baj(parameters[3][3], parameters[3][4], parameters[3][5]); Eigen::Vector3d Bgj(parameters[3][6], parameters[3][7], parameters[3][8]); //Eigen::Matrix<double, 15, 15> Fd; //Eigen::Matrix<double, 15, 12> Gd; //Eigen::Vector3d pPj = Pi + Vi * sum_t - 0.5 * g * sum_t * sum_t + corrected_delta_p; //Eigen::Quaterniond pQj = Qi * delta_q; //Eigen::Vector3d pVj = Vi - g * sum_t + corrected_delta_v; //Eigen::Vector3d pBaj = Bai; //Eigen::Vector3d pBgj = Bgi; //Vi + Qi * delta_v - g * sum_dt = Vj; //Qi * delta_q = Qj; //delta_p = Qi.inverse() * (0.5 * g * sum_dt * sum_dt + Pj - Pi); //delta_v = Qi.inverse() * (g * sum_dt + Vj - Vi); //delta_q = Qi.inverse() * Qj; #if 0 if ((Bai - pre_integration->linearized_ba).norm() > 0.10 || (Bgi - pre_integration->linearized_bg).norm() > 0.01) { pre_integration->repropagate(Bai, Bgi); } #endif Eigen::Map<Eigen::Matrix<double, 15, 1>> residual(residuals); residual = pre_integration->evaluate(Pi, Qi, Vi, Bai, Bgi, Pj, Qj, Vj, Baj, Bgj); Eigen::Matrix<double, 15, 15> sqrt_info = Eigen::LLT<Eigen::Matrix<double, 15, 15>>(pre_integration->covariance.inverse()).matrixL().transpose(); //sqrt_info.setIdentity(); residual = sqrt_info * residual; if (jacobians) { double sum_dt = pre_integration->sum_dt; Eigen::Matrix3d dp_dba = pre_integration->jacobian.template block<3, 3>(O_P, O_BA); Eigen::Matrix3d dp_dbg = pre_integration->jacobian.template block<3, 3>(O_P, O_BG); Eigen::Matrix3d dq_dbg = pre_integration->jacobian.template block<3, 3>(O_R, O_BG); Eigen::Matrix3d dv_dba = pre_integration->jacobian.template block<3, 3>(O_V, O_BA); Eigen::Matrix3d dv_dbg = pre_integration->jacobian.template block<3, 3>(O_V, O_BG); if (pre_integration->jacobian.maxCoeff() > 1e8 || pre_integration->jacobian.minCoeff() < -1e8) { ROS_WARN("numerical unstable in preintegration"); //std::cout << pre_integration->jacobian << std::endl; /// ROS_BREAK(); } if (jacobians[0]) { Eigen::Map<Eigen::Matrix<double, 15, 7, Eigen::RowMajor>> jacobian_pose_i(jacobians[0]); jacobian_pose_i.setZero(); jacobian_pose_i.block<3, 3>(O_P, O_P) = -Qi.inverse().toRotationMatrix(); jacobian_pose_i.block<3, 3>(O_P, O_R) = Utility::skewSymmetric(Qi.inverse() * (0.5 * G * sum_dt * sum_dt + Pj - Pi - Vi * sum_dt)); #if 0 jacobian_pose_i.block<3, 3>(O_R, O_R) = -(Qj.inverse() * Qi).toRotationMatrix(); #else Eigen::Quaterniond corrected_delta_q = pre_integration->delta_q * Utility::deltaQ(dq_dbg * (Bgi - pre_integration->linearized_bg)); jacobian_pose_i.block<3, 3>(O_R, O_R) = -(Utility::Qleft(Qj.inverse() * Qi) * Utility::Qright(corrected_delta_q)).bottomRightCorner<3, 3>(); #endif jacobian_pose_i.block<3, 3>(O_V, O_R) = Utility::skewSymmetric(Qi.inverse() * (G * sum_dt + Vj - Vi)); jacobian_pose_i = sqrt_info * jacobian_pose_i; if (jacobian_pose_i.maxCoeff() > 1e8 || jacobian_pose_i.minCoeff() < -1e8) { ROS_WARN("numerical unstable in preintegration"); //std::cout << sqrt_info << std::endl; //ROS_BREAK(); } } if (jacobians[1]) { Eigen::Map<Eigen::Matrix<double, 15, 9, Eigen::RowMajor>> jacobian_speedbias_i(jacobians[1]); jacobian_speedbias_i.setZero(); jacobian_speedbias_i.block<3, 3>(O_P, O_V - O_V) = -Qi.inverse().toRotationMatrix() * sum_dt; jacobian_speedbias_i.block<3, 3>(O_P, O_BA - O_V) = -dp_dba; jacobian_speedbias_i.block<3, 3>(O_P, O_BG - O_V) = -dp_dbg; #if 0 jacobian_speedbias_i.block<3, 3>(O_R, O_BG - O_V) = -dq_dbg; #else //Eigen::Quaterniond corrected_delta_q = pre_integration->delta_q * Utility::deltaQ(dq_dbg * (Bgi - pre_integration->linearized_bg)); //jacobian_speedbias_i.block<3, 3>(O_R, O_BG - O_V) = -Utility::Qleft(Qj.inverse() * Qi * corrected_delta_q).bottomRightCorner<3, 3>() * dq_dbg; jacobian_speedbias_i.block<3, 3>(O_R, O_BG - O_V) = -Utility::Qleft(Qj.inverse() * Qi * pre_integration->delta_q).bottomRightCorner<3, 3>() * dq_dbg; #endif jacobian_speedbias_i.block<3, 3>(O_V, O_V - O_V) = -Qi.inverse().toRotationMatrix(); jacobian_speedbias_i.block<3, 3>(O_V, O_BA - O_V) = -dv_dba; jacobian_speedbias_i.block<3, 3>(O_V, O_BG - O_V) = -dv_dbg; jacobian_speedbias_i.block<3, 3>(O_BA, O_BA - O_V) = -Eigen::Matrix3d::Identity(); jacobian_speedbias_i.block<3, 3>(O_BG, O_BG - O_V) = -Eigen::Matrix3d::Identity(); jacobian_speedbias_i = sqrt_info * jacobian_speedbias_i; //ROS_ASSERT(fabs(jacobian_speedbias_i.maxCoeff()) < 1e8); //ROS_ASSERT(fabs(jacobian_speedbias_i.minCoeff()) < 1e8); } if (jacobians[2]) { Eigen::Map<Eigen::Matrix<double, 15, 7, Eigen::RowMajor>> jacobian_pose_j(jacobians[2]); jacobian_pose_j.setZero(); jacobian_pose_j.block<3, 3>(O_P, O_P) = Qi.inverse().toRotationMatrix(); #if 0 jacobian_pose_j.block<3, 3>(O_R, O_R) = Eigen::Matrix3d::Identity(); #else Eigen::Quaterniond corrected_delta_q = pre_integration->delta_q * Utility::deltaQ(dq_dbg * (Bgi - pre_integration->linearized_bg)); jacobian_pose_j.block<3, 3>(O_R, O_R) = Utility::Qleft(corrected_delta_q.inverse() * Qi.inverse() * Qj).bottomRightCorner<3, 3>(); #endif jacobian_pose_j = sqrt_info * jacobian_pose_j; //ROS_ASSERT(fabs(jacobian_pose_j.maxCoeff()) < 1e8); //ROS_ASSERT(fabs(jacobian_pose_j.minCoeff()) < 1e8); } if (jacobians[3]) { Eigen::Map<Eigen::Matrix<double, 15, 9, Eigen::RowMajor>> jacobian_speedbias_j(jacobians[3]); jacobian_speedbias_j.setZero(); jacobian_speedbias_j.block<3, 3>(O_V, O_V - O_V) = Qi.inverse().toRotationMatrix(); jacobian_speedbias_j.block<3, 3>(O_BA, O_BA - O_V) = Eigen::Matrix3d::Identity(); jacobian_speedbias_j.block<3, 3>(O_BG, O_BG - O_V) = Eigen::Matrix3d::Identity(); jacobian_speedbias_j = sqrt_info * jacobian_speedbias_j; //ROS_ASSERT(fabs(jacobian_speedbias_j.maxCoeff()) < 1e8); //ROS_ASSERT(fabs(jacobian_speedbias_j.minCoeff()) < 1e8); } } return true; } //bool Evaluate_Direct(double const *const *parameters, Eigen::Matrix<double, 15, 1> &residuals, Eigen::Matrix<double, 15, 30> &jacobians); //void checkCorrection(); //void checkTransition(); //void checkJacobian(double **parameters); IntegrationBase* pre_integration; };
Java
/*! * \file GPS_L1_CA.h * \brief Defines system parameters for GPS L1 C/A signal and NAV data * \author Javier Arribas, 2011. jarribas(at)cttc.es * * ------------------------------------------------------------------------- * * Copyright (C) 2010-2015 (see AUTHORS file for a list of contributors) * * GNSS-SDR is a software defined Global Navigation * Satellite Systems receiver * * This file is part of GNSS-SDR. * * GNSS-SDR 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. * * GNSS-SDR 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 GNSS-SDR. If not, see <http://www.gnu.org/licenses/>. * * ------------------------------------------------------------------------- */ #ifndef GNSS_SDR_GPS_L1_CA_H_ #define GNSS_SDR_GPS_L1_CA_H_ #include <vector> #include <utility> // std::pair #include "MATH_CONSTANTS.h" #include "gnss_frequencies.h" #define GPS_L1_CA_CN0_ESTIMATION_SAMPLES 20 #define GPS_L1_CA_MINIMUM_VALID_CN0 25 #define GPS_L1_CA_MAXIMUM_LOCK_FAIL_COUNTER 50 #define GPS_L1_CA_CARRIER_LOCK_THRESHOLD 0.85 // Physical constants const double GPS_C_m_s = SPEED_OF_LIGHT; //!< The speed of light, [m/s] const double GPS_C_m_ms = 299792.4580; //!< The speed of light, [m/ms] const double GPS_PI = 3.1415926535898; //!< Pi as defined in IS-GPS-200E const double GPS_TWO_PI = 6.283185307179586;//!< 2Pi as defined in IS-GPS-200E const double OMEGA_EARTH_DOT = DEFAULT_OMEGA_EARTH_DOT; //!< Earth rotation rate, [rad/s] const double GM = 3.986005e14; //!< Universal gravitational constant times the mass of the Earth, [m^3/s^2] const double F = -4.442807633e-10; //!< Constant, [s/(m)^(1/2)] // carrier and code frequencies const double GPS_L1_FREQ_HZ = FREQ1; //!< L1 [Hz] const double GPS_L1_CA_CODE_RATE_HZ = 1.023e6; //!< GPS L1 C/A code rate [chips/s] const double GPS_L1_CA_CODE_LENGTH_CHIPS = 1023.0; //!< GPS L1 C/A code length [chips] const double GPS_L1_CA_CODE_PERIOD = 0.001; //!< GPS L1 C/A code period [seconds] const double GPS_L1_CA_CHIP_PERIOD = 9.7752e-07; //!< GPS L1 C/A chip period [seconds] /*! * \brief Maximum Time-Of-Arrival (TOA) difference between satellites for a receiver operated on Earth surface is 20 ms * * According to the GPS orbit model described in [1] Pag. 32. * It should be taken into account to set the buffer size for the PRN start timestamp in the pseudoranges block. * [1] J. Bao-Yen Tsui, Fundamentals of Global Positioning System Receivers. A Software Approach, John Wiley & Sons, * Inc., Hoboken, NJ, 2nd edition, 2005. */ const double MAX_TOA_DELAY_MS = 20; //#define NAVIGATION_SOLUTION_RATE_MS 1000 // this cannot go here const double GPS_STARTOFFSET_ms = 68.802; //[ms] Initial sign. travel time (this cannot go here) // OBSERVABLE HISTORY DEEP FOR INTERPOLATION const int GPS_L1_CA_HISTORY_DEEP = 500; // NAVIGATION MESSAGE DEMODULATION AND DECODING #define GPS_PREAMBLE {1, 0, 0, 0, 1, 0, 1, 1} const int GPS_CA_PREAMBLE_LENGTH_BITS = 8; const int GPS_CA_PREAMBLE_LENGTH_SYMBOLS = 160; const double GPS_CA_PREAMBLE_DURATION_S = 0.160; const int GPS_CA_TELEMETRY_RATE_BITS_SECOND = 50; //!< NAV message bit rate [bits/s] const int GPS_CA_TELEMETRY_SYMBOLS_PER_BIT = 20; const int GPS_CA_TELEMETRY_RATE_SYMBOLS_SECOND = GPS_CA_TELEMETRY_RATE_BITS_SECOND*GPS_CA_TELEMETRY_SYMBOLS_PER_BIT; //!< NAV message bit rate [symbols/s] const int GPS_WORD_LENGTH = 4; //!< CRC + GPS WORD (-2 -1 0 ... 29) Bits = 4 bytes const int GPS_SUBFRAME_LENGTH = 40; //!< GPS_WORD_LENGTH x 10 = 40 bytes const int GPS_SUBFRAME_BITS = 300; //!< Number of bits per subframe in the NAV message [bits] const int GPS_SUBFRAME_SECONDS = 6; //!< Subframe duration [seconds] const int GPS_SUBFRAME_MS = 6000; //!< Subframe duration [seconds] const int GPS_WORD_BITS = 30; //!< Number of bits per word in the NAV message [bits] // GPS NAVIGATION MESSAGE STRUCTURE // NAVIGATION MESSAGE FIELDS POSITIONS (from IS-GPS-200E Appendix II) // SUBFRAME 1-5 (TLM and HOW) const std::vector<std::pair<int,int> > TOW( { {31,17} } ); const std::vector<std::pair<int,int> > INTEGRITY_STATUS_FLAG({{23,1}}); const std::vector<std::pair<int,int> > ALERT_FLAG({{48,1}}); const std::vector<std::pair<int,int> > ANTI_SPOOFING_FLAG({{49,1}}); const std::vector<std::pair<int,int> > SUBFRAME_ID({{50,3}}); // SUBFRAME 1 const std::vector<std::pair<int,int>> GPS_WEEK({{61,10}}); const std::vector<std::pair<int,int>> CA_OR_P_ON_L2({{71,2}}); //* const std::vector<std::pair<int,int>> SV_ACCURACY({{73,4}}); const std::vector<std::pair<int,int>> SV_HEALTH ({{77,6}}); const std::vector<std::pair<int,int>> L2_P_DATA_FLAG ({{91,1}}); const std::vector<std::pair<int,int>> T_GD({{197,8}}); const double T_GD_LSB = TWO_N31; const std::vector<std::pair<int,int>> IODC({{83,2},{211,8}}); const std::vector<std::pair<int,int>> T_OC({{219,16}}); const double T_OC_LSB = TWO_P4; const std::vector<std::pair<int,int>> A_F2({{241,8}}); const double A_F2_LSB = TWO_N55; const std::vector<std::pair<int,int>> A_F1({{249,16}}); const double A_F1_LSB = TWO_N43; const std::vector<std::pair<int,int>> A_F0({{271,22}}); const double A_F0_LSB = TWO_N31; // SUBFRAME 2 const std::vector<std::pair<int,int>> IODE_SF2({{61,8}}); const std::vector<std::pair<int,int>> C_RS({{69,16}}); const double C_RS_LSB = TWO_N5; const std::vector<std::pair<int,int>> DELTA_N({{91,16}}); const double DELTA_N_LSB = PI_TWO_N43; const std::vector<std::pair<int,int>> M_0({{107,8},{121,24}}); const double M_0_LSB = PI_TWO_N31; const std::vector<std::pair<int,int>> C_UC({{151,16}}); const double C_UC_LSB = TWO_N29; const std::vector<std::pair<int,int>> E({{167,8},{181,24}}); const double E_LSB = TWO_N33; const std::vector<std::pair<int,int>> C_US({{211,16}}); const double C_US_LSB = TWO_N29; const std::vector<std::pair<int,int>> SQRT_A({{227,8},{241,24}}); const double SQRT_A_LSB = TWO_N19; const std::vector<std::pair<int,int>> T_OE({{271,16}}); const double T_OE_LSB = TWO_P4; const std::vector<std::pair<int,int>> FIT_INTERVAL_FLAG({{271,1}}); const std::vector<std::pair<int,int>> AODO({{272,5}}); const int AODO_LSB = 900; // SUBFRAME 3 const std::vector<std::pair<int,int>> C_IC({{61,16}}); const double C_IC_LSB = TWO_N29; const std::vector<std::pair<int,int>> OMEGA_0({{77,8},{91,24}}); const double OMEGA_0_LSB = PI_TWO_N31; const std::vector<std::pair<int,int>> C_IS({{121,16}}); const double C_IS_LSB = TWO_N29; const std::vector<std::pair<int,int>> I_0({{137,8},{151,24}}); const double I_0_LSB = PI_TWO_N31; const std::vector<std::pair<int,int>> C_RC({{181,16}}); const double C_RC_LSB = TWO_N5; const std::vector<std::pair<int,int>> OMEGA({{197,8},{211,24}}); const double OMEGA_LSB = PI_TWO_N31; const std::vector<std::pair<int,int>> OMEGA_DOT({{241,24}}); const double OMEGA_DOT_LSB = PI_TWO_N43; const std::vector<std::pair<int,int>> IODE_SF3({{271,8}}); const std::vector<std::pair<int,int>> I_DOT({{279,14}}); const double I_DOT_LSB = PI_TWO_N43; // SUBFRAME 4-5 const std::vector<std::pair<int,int>> SV_DATA_ID({{61,2}}); const std::vector<std::pair<int,int>> SV_PAGE({{63,6}}); // SUBFRAME 4 //! \todo read all pages of subframe 4 // Page 18 - Ionospheric and UTC data const std::vector<std::pair<int,int>> ALPHA_0({{69,8}}); const double ALPHA_0_LSB = TWO_N30; const std::vector<std::pair<int,int>> ALPHA_1({{77,8}}); const double ALPHA_1_LSB = TWO_N27; const std::vector<std::pair<int,int>> ALPHA_2({{91,8}}); const double ALPHA_2_LSB = TWO_N24; const std::vector<std::pair<int,int>> ALPHA_3({{99,8}}); const double ALPHA_3_LSB = TWO_N24; const std::vector<std::pair<int,int>> BETA_0({{107,8}}); const double BETA_0_LSB = TWO_P11; const std::vector<std::pair<int,int>> BETA_1({{121,8}}); const double BETA_1_LSB = TWO_P14; const std::vector<std::pair<int,int>> BETA_2({{129,8}}); const double BETA_2_LSB = TWO_P16; const std::vector<std::pair<int,int>> BETA_3({{137,8}}); const double BETA_3_LSB = TWO_P16; const std::vector<std::pair<int,int>> A_1({{151,24}}); const double A_1_LSB = TWO_N50; const std::vector<std::pair<int,int>> A_0({{181,24},{211,8}}); const double A_0_LSB = TWO_N30; const std::vector<std::pair<int,int>> T_OT({{219,8}}); const double T_OT_LSB = TWO_P12; const std::vector<std::pair<int,int>> WN_T({{227,8}}); const double WN_T_LSB = 1; const std::vector<std::pair<int,int>> DELTAT_LS({{241,8}}); const double DELTAT_LS_LSB = 1; const std::vector<std::pair<int,int>> WN_LSF({{249,8}}); const double WN_LSF_LSB = 1; const std::vector<std::pair<int,int>> DN({{257,8}}); const double DN_LSB = 1; const std::vector<std::pair<int,int>> DELTAT_LSF({{271,8}}); const double DELTAT_LSF_LSB = 1; // Page 25 - Antispoofing, SV config and SV health (PRN 25 -32) const std::vector<std::pair<int,int>> HEALTH_SV25({{229,6}}); const std::vector<std::pair<int,int>> HEALTH_SV26({{241,6}}); const std::vector<std::pair<int,int>> HEALTH_SV27({{247,6}}); const std::vector<std::pair<int,int>> HEALTH_SV28({{253,6}}); const std::vector<std::pair<int,int>> HEALTH_SV29({{259,6}}); const std::vector<std::pair<int,int>> HEALTH_SV30({{271,6}}); const std::vector<std::pair<int,int>> HEALTH_SV31({{277,6}}); const std::vector<std::pair<int,int>> HEALTH_SV32({{283,6}}); // SUBFRAME 5 //! \todo read all pages of subframe 5 // page 25 - Health (PRN 1 - 24) const std::vector<std::pair<int,int>> T_OA({{69,8}}); const double T_OA_LSB = TWO_P12; const std::vector<std::pair<int,int>> WN_A({{77,8}}); const std::vector<std::pair<int,int>> HEALTH_SV1({{91,6}}); const std::vector<std::pair<int,int>> HEALTH_SV2({{97,6}}); const std::vector<std::pair<int,int>> HEALTH_SV3({{103,6}}); const std::vector<std::pair<int,int>> HEALTH_SV4({{109,6}}); const std::vector<std::pair<int,int>> HEALTH_SV5({{121,6}}); const std::vector<std::pair<int,int>> HEALTH_SV6({{127,6}}); const std::vector<std::pair<int,int>> HEALTH_SV7({{133,6}}); const std::vector<std::pair<int,int>> HEALTH_SV8({{139,6}}); const std::vector<std::pair<int,int>> HEALTH_SV9({{151,6}}); const std::vector<std::pair<int,int>> HEALTH_SV10({{157,6}}); const std::vector<std::pair<int,int>> HEALTH_SV11({{163,6}}); const std::vector<std::pair<int,int>> HEALTH_SV12({{169,6}}); const std::vector<std::pair<int,int>> HEALTH_SV13({{181,6}}); const std::vector<std::pair<int,int>> HEALTH_SV14({{187,6}}); const std::vector<std::pair<int,int>> HEALTH_SV15({{193,6}}); const std::vector<std::pair<int,int>> HEALTH_SV16({{199,6}}); const std::vector<std::pair<int,int>> HEALTH_SV17({{211,6}}); const std::vector<std::pair<int,int>> HEALTH_SV18({{217,6}}); const std::vector<std::pair<int,int>> HEALTH_SV19({{223,6}}); const std::vector<std::pair<int,int>> HEALTH_SV20({{229,6}}); const std::vector<std::pair<int,int>> HEALTH_SV21({{241,6}}); const std::vector<std::pair<int,int>> HEALTH_SV22({{247,6}}); const std::vector<std::pair<int,int>> HEALTH_SV23({{253,6}}); const std::vector<std::pair<int,int>> HEALTH_SV24({{259,6}}); #endif /* GNSS_SDR_GPS_L1_CA_H_ */
Java
/* Copyright 2016 Devon Call, Zeke Hunter-Green, Paige Ormiston, Joe Renner, Jesse Sliter This file is part of Myrge. Myrge 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. Myrge 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 Myrge. If not, see <http://www.gnu.org/licenses/>. */ app.controller('NavCtrl', [ '$scope', '$state', 'auth', function($scope, $state, auth){ $scope.isLoggedIn = auth.isLoggedIn; $scope.currentUser = auth.currentUser; $scope.logOut = auth.logOut; $scope.loggedin = auth.isLoggedIn(); if($scope.loggedin){ auth.validate(auth.getToken()).success(function(data){ if(!data.valid){ auth.logOut(); $state.go("login"); } }); } }]);
Java
# Topydo - A todo.txt client written in Python. # Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ This module provides the Todo class. """ from datetime import date from topydo.lib.Config import config from topydo.lib.TodoBase import TodoBase from topydo.lib.Utils import date_string_to_date class Todo(TodoBase): """ This class adds common functionality with respect to dates to the Todo base class, mainly by interpreting the start and due dates of task. """ def __init__(self, p_str): TodoBase.__init__(self, p_str) self.attributes = {} def get_date(self, p_tag): """ Given a date tag, return a date object. """ string = self.tag_value(p_tag) result = None try: result = date_string_to_date(string) if string else None except ValueError: pass return result def start_date(self): """ Returns a date object of the todo's start date. """ return self.get_date(config().tag_start()) def due_date(self): """ Returns a date object of the todo's due date. """ return self.get_date(config().tag_due()) def is_active(self): """ Returns True when the start date is today or in the past and the task has not yet been completed. """ start = self.start_date() return not self.is_completed() and (not start or start <= date.today()) def is_overdue(self): """ Returns True when the due date is in the past and the task has not yet been completed. """ return not self.is_completed() and self.days_till_due() < 0 def days_till_due(self): """ Returns the number of days till the due date. Returns a negative number of days when the due date is in the past. Returns 0 when the task has no due date. """ due = self.due_date() if due: diff = due - date.today() return diff.days return 0 def length(self): """ Returns the length (in days) of the task, by considering the start date and the due date. When there is no start date, its creation date is used. Returns 0 when one of these dates is missing. """ start = self.start_date() or self.creation_date() due = self.due_date() if start and due and start < due: diff = due - start return diff.days else: return 0
Java
/* Copyright (c) Colorado School of Mines, 1996.*/ /* All rights reserved. */ /* segy.h - include file for SEGY traces * * declarations for: * typedef struct {} segy - the trace identification header * typedef struct {} bhed - binary header * * Note: * If header words are added, run the makefile in this directory * to recreate hdr.h. * * Reference: * K. M. Barry, D. A. Cavers and C. W. Kneale, "Special Report: * Recommended Standards for Digital Tape Formats", * Geophysics, vol. 40, no. 2 (April 1975), P. 344-352. * * $Author: koehn $ * $Source: /home/tbohlen/CVSROOT/DENISE/src/segy.h,v $ * $Revision: 1.1.1.1 $ ; $Date: 2007/11/21 22:44:52 $ */ #ifndef SEGY_H #define SEGY_H #define SU_NFLTS 32768 /* Arbitrary limit on data array size */ /* TYPEDEFS */ #ifdef _CRAY typedef struct { /* segy - trace identification header */ signed tracl :32; /* trace sequence number within line */ signed tracr :32; /* trace sequence number within reel */ signed fldr :32; /* field record number */ signed tracf :32; /* trace number within field record */ signed ep :32; /* energy source point number */ signed cdp :32; /* CDP ensemble number */ signed cdpt :32; /* trace number within CDP ensemble */ signed trid :16; /* trace identification code: 1 = seismic data 2 = dead 3 = dummy 4 = time break 5 = uphole 6 = sweep 7 = timing 8 = water break 9---, N = optional use (N = 32,767) Following are CWP id flags: 9 = autocorrelation 10 = Fourier transformed - no packing xr[0],xi[0], ..., xr[N-1],xi[N-1] 11 = Fourier transformed - unpacked Nyquist xr[0],xi[0],...,xr[N/2],xi[N/2] 12 = Fourier transformed - packed Nyquist even N: xr[0],xr[N/2],xr[1],xi[1], ..., xr[N/2 -1],xi[N/2 -1] (note the exceptional second entry) odd N: xr[0],xr[(N-1)/2],xr[1],xi[1], ..., xr[(N-1)/2 -1],xi[(N-1)/2 -1],xi[(N-1)/2] (note the exceptional second & last entries) 13 = Complex signal in the time domain xr[0],xi[0], ..., xr[N-1],xi[N-1] 14 = Fourier transformed - amplitude/phase a[0],p[0], ..., a[N-1],p[N-1] 15 = Complex time signal - amplitude/phase a[0],p[0], ..., a[N-1],p[N-1] 16 = Real part of complex trace from 0 to Nyquist 17 = Imag part of complex trace from 0 to Nyquist 18 = Amplitude of complex trace from 0 to Nyquist 19 = Phase of complex trace from 0 to Nyquist 21 = Wavenumber time domain (k-t) 22 = Wavenumber frequency (k-omega) 23 = Envelope of the complex time trace 24 = Phase of the complex time trace 25 = Frequency of the complex time trace 30 = Depth-Range (z-x) traces 101 = Seismic data packed to bytes (by supack1) 102 = Seismic data packed to 2 bytes (by supack2) */ signed nvs :16; /* number of vertically summed traces (see vscode in bhed structure) */ signed nhs :16; /* number of horizontally summed traces (see vscode in bhed structure) */ signed duse :16; /* data use: 1 = production 2 = test */ signed offset :32; /* distance from source point to receiver group (negative if opposite to direction in which the line was shot) */ signed gelev :32; /* receiver group elevation from sea level (above sea level is positive) */ signed selev :32; /* source elevation from sea level (above sea level is positive) */ signed sdepth :32; /* source depth (positive) */ signed gdel :32; /* datum elevation at receiver group */ signed sdel :32; /* datum elevation at source */ signed swdep :32; /* water depth at source */ signed gwdep :32; /* water depth at receiver group */ signed scalel :16; /* scale factor for previous 7 entries with value plus or minus 10 to the power 0, 1, 2, 3, or 4 (if positive, multiply, if negative divide) */ signed scalco :16; /* scale factor for next 4 entries with value plus or minus 10 to the power 0, 1, 2, 3, or 4 (if positive, multiply, if negative divide) */ signed sx :32; /* X source coordinate */ signed sy :32; /* Y source coordinate */ signed gx :32; /* X group coordinate */ signed gy :32; /* Y group coordinate */ signed counit :16; /* coordinate units code: for previous four entries 1 = length (meters or feet) 2 = seconds of arc (in this case, the X values are longitude and the Y values are latitude, a positive value designates the number of seconds east of Greenwich or north of the equator */ signed wevel :16; /* weathering velocity */ signed swevel :16; /* subweathering velocity */ signed sut :16; /* uphole time at source */ signed gut :16; /* uphole time at receiver group */ signed sstat :16; /* source static correction */ signed gstat :16; /* group static correction */ signed tstat :16; /* total static applied */ signed laga :16; /* lag time A, time in ms between end of 240- byte trace identification header and time break, positive if time break occurs after end of header, time break is defined as the initiation pulse which maybe recorded on an auxiliary trace or as otherwise specified by the recording system */ signed lagb :16; /* lag time B, time in ms between the time break and the initiation time of the energy source, may be positive or negative */ signed delrt :16; /* delay recording time, time in ms between initiation time of energy source and time when recording of data samples begins (for deep water work if recording does not start at zero time) */ signed muts :16; /* mute time--start */ signed mute :16; /* mute time--end */ unsigned ns :16; /* number of samples in this trace */ unsigned dt :16; /* sample interval; in micro-seconds */ signed gain :16; /* gain type of field instruments code: 1 = fixed 2 = binary 3 = floating point 4 ---- N = optional use */ signed igc :16; /* instrument gain constant */ signed igi :16; /* instrument early or initial gain */ signed corr :16; /* correlated: 1 = no 2 = yes */ signed sfs :16; /* sweep frequency at start */ signed sfe :16; /* sweep frequency at end */ signed slen :16; /* sweep length in ms */ signed styp :16; /* sweep type code: 1 = linear 2 = cos-squared 3 = other */ signed stas :16; /* sweep trace length at start in ms */ signed stae :16; /* sweep trace length at end in ms */ signed tatyp :16; /* taper type: 1=linear, 2=cos^2, 3=other */ signed afilf :16; /* alias filter frequency if used */ signed afils :16; /* alias filter slope */ signed nofilf :16; /* notch filter frequency if used */ signed nofils :16; /* notch filter slope */ signed lcf :16; /* low cut frequency if used */ signed hcf :16; /* high cut frequncy if used */ signed lcs :16; /* low cut slope */ signed hcs :16; /* high cut slope */ signed year :16; /* year data recorded */ signed day :16; /* day of year */ signed hour :16; /* hour of day (24 hour clock) */ signed minute :16; /* minute of hour */ signed sec :16; /* second of minute */ signed timbas :16; /* time basis code: 1 = local 2 = GMT 3 = other */ signed trwf :16; /* trace weighting factor, defined as 1/2^N volts for the least sigificant bit */ signed grnors :16; /* geophone group number of roll switch position one */ signed grnofr :16; /* geophone group number of trace one within original field record */ signed grnlof :16; /* geophone group number of last trace within original field record */ signed gaps :16; /* gap size (total number of groups dropped) */ signed otrav :16; /* overtravel taper code: 1 = down (or behind) 2 = up (or ahead) */ /* local assignments */ /* signed pad :32; */ /* double word alignment for Cray 64-bit floats */ float d1; /* sample spacing for non-seismic data */ float f1; /* first sample location for non-seismic data */ float d2; /* sample spacing between traces */ float f2; /* first trace location */ float ungpow; /* negative of power used for dynamic range compression */ float unscale; /* reciprocal of scaling factor to normalize range */ signed ntr :32; /* number of traces */ signed mark :16; /* mark selected traces */ signed unass :16; /* unassigned values */ float data[SU_NFLTS]; } segy; typedef struct { /* bhed - binary header */ int jobid :32; /* job identification number */ int lino :32; /* line number (only one line per reel) */ int reno :32; /* reel number */ short ntrpr :16; /* number of data traces per record */ short nart :16; /* number of auxiliary traces per record */ short hdt :16; /* sample interval in micro secs for this reel */ short dto :16; /* same for original field recording */ short hns :16; /* number of samples per trace for this reel */ short nso :16; /* same for original field recording */ short format :16; /* data sample format code: 1 = floating point (4 bytes) 2 = fixed point (4 bytes) 3 = fixed point (2 bytes) 4 = fixed point w/gain code (4 bytes) */ short fold :16; /* CDP fold expected per CDP ensemble */ short tsort :16; /* trace sorting code: 1 = as recorded (no sorting) 2 = CDP ensemble 3 = single fold continuous profile 4 = horizontally stacked */ short vscode :16; /* vertical sum code: 1 = no sum 2 = two sum ... N = N sum (N = 32,767) */ short hsfs :16; /* sweep frequency at start */ short hsfe :16; /* sweep frequency at end */ short hslen :16; /* sweep length (ms) */ short hstyp :16; /* sweep type code: 1 = linear 2 = parabolic 3 = exponential 4 = other */ short schn :16; /* trace number of sweep channel */ short hstas :16; /* sweep trace taper length at start if tapered (the taper starts at zero time and is effective for this length) */ short hstae :16; /* sweep trace taper length at end (the ending taper starts at sweep length minus the taper length at end) */ short htatyp :16; /* sweep trace taper type code: 1 = linear 2 = cos-squared 3 = other */ short hcorr :16; /* correlated data traces code: 1 = no 2 = yes */ short bgrcv :16; /* binary gain recovered code: 1 = yes 2 = no */ short rcvm :16; /* amplitude recovery method code: 1 = none 2 = spherical divergence 3 = AGC 4 = other */ short mfeet :16; /* measurement system code: 1 = meters 2 = feet */ short polyt :16; /* impulse signal polarity code: 1 = increase in pressure or upward geophone case movement gives negative number on tape 2 = increase in pressure or upward geophone case movement gives positive number on tape */ short vpol :16; /* vibratory polarity code: code seismic signal lags pilot by 1 337.5 to 22.5 degrees 2 22.5 to 67.5 degrees 3 67.5 to 112.5 degrees 4 112.5 to 157.5 degrees 5 157.5 to 202.5 degrees 6 202.5 to 247.5 degrees 7 247.5 to 292.5 degrees 8 293.5 to 337.5 degrees */ signed pad :32; /* double word alignment pad */ double hunass[21]; /* unassigned, double is portable! */ } bhed; #else /* bit fields may not be portable! */ typedef struct { /* segy - trace identification header */ int tracl ; /* trace sequence number within line */ int tracr ; /* trace sequence number within reel */ int fldr ; /* field record number */ int tracf ; /* trace number within field record */ int ep ; /* energy source point number */ int cdp ; /* CDP ensemble number */ int cdpt ; /* trace number within CDP ensemble */ short trid ; /* trace identification code: 1 = seismic data 2 = dead 3 = dummy 4 = time break 5 = uphole 6 = sweep 7 = timing 8 = water break 9---, N = optional use (N = 32,767) Following are CWP id flags: 9 = autocorrelation 10 = Fourier transformed - no packing xr[0],xi[0], ..., xr[N-1],xi[N-1] 11 = Fourier transformed - unpacked Nyquist xr[0],xi[0],...,xr[N/2],xi[N/2] 12 = Fourier transformed - packed Nyquist even N: xr[0],xr[N/2],xr[1],xi[1], ..., xr[N/2 -1],xi[N/2 -1] (note the exceptional second entry) odd N: xr[0],xr[(N-1)/2],xr[1],xi[1], ..., xr[(N-1)/2 -1],xi[(N-1)/2 -1],xi[(N-1)/2] (note the exceptional second & last entries) 13 = Complex signal in the time domain xr[0],xi[0], ..., xr[N-1],xi[N-1] 14 = Fourier transformed - amplitude/phase a[0],p[0], ..., a[N-1],p[N-1] 15 = Complex time signal - amplitude/phase a[0],p[0], ..., a[N-1],p[N-1] 16 = Real part of complex trace from 0 to Nyquist 17 = Imag part of complex trace from 0 to Nyquist 18 = Amplitude of complex trace from 0 to Nyquist 19 = Phase of complex trace from 0 to Nyquist 21 = Wavenumber time domain (k-t) 22 = Wavenumber frequency (k-omega) 23 = Envelope of the complex time trace 24 = Phase of the complex time trace 25 = Frequency of the complex time trace 30 = Depth-Range (z-x) traces 101 = Seismic data packed to bytes (by supack1) 102 = Seismic data packed to 2 bytes (by supack2) */ short nvs ; /* number of vertically summed traces (see vscode in bhed structure) */ short nhs ; /* number of horizontally summed traces (see vscode in bhed structure) */ short duse ; /* data use: 1 = production 2 = test */ int offset ; /* distance from source point to receiver group (negative if opposite to direction in which the line was shot) */ int gelev ; /* receiver group elevation from sea level (above sea level is positive) */ int selev ; /* source elevation from sea level (above sea level is positive) */ int sdepth ; /* source depth (positive) */ int gdel ; /* datum elevation at receiver group */ int sdel ; /* datum elevation at source */ int swdep ; /* water depth at source */ int gwdep ; /* water depth at receiver group */ short scalel ; /* scale factor for previous 7 entries with value plus or minus 10 to the power 0, 1, 2, 3, or 4 (if positive, multiply, if negative divide) */ short scalco ; /* scale factor for next 4 entries with value plus or minus 10 to the power 0, 1, 2, 3, or 4 (if positive, multiply, if negative divide) */ int sx ; /* X source coordinate */ int sy ; /* Y source coordinate */ int gx ; /* X group coordinate */ int gy ; /* Y group coordinate */ short counit ; /* coordinate units code: for previous four entries 1 = length (meters or feet) 2 = seconds of arc (in this case, the X values are longitude and the Y values are latitude, a positive value designates the number of seconds east of Greenwich or north of the equator */ short wevel ; /* weathering velocity */ short swevel ; /* subweathering velocity */ short sut ; /* uphole time at source */ short gut ; /* uphole time at receiver group */ short sstat ; /* source static correction */ short gstat ; /* group static correction */ short tstat ; /* total static applied */ short laga ; /* lag time A, time in ms between end of 240- byte trace identification header and time break, positive if time break occurs after end of header, time break is defined as the initiation pulse which maybe recorded on an auxiliary trace or as otherwise specified by the recording system */ short lagb ; /* lag time B, time in ms between the time break and the initiation time of the energy source, may be positive or negative */ short delrt ; /* delay recording time, time in ms between initiation time of energy source and time when recording of data samples begins (for deep water work if recording does not start at zero time) */ short muts ; /* mute time--start */ short mute ; /* mute time--end */ unsigned short ns ; /* number of samples in this trace */ unsigned short dt ; /* sample interval; in micro-seconds */ short gain ; /* gain type of field instruments code: 1 = fixed 2 = binary 3 = floating point 4 ---- N = optional use */ short igc ; /* instrument gain constant */ short igi ; /* instrument early or initial gain */ short corr ; /* correlated: 1 = no 2 = yes */ short sfs ; /* sweep frequency at start */ short sfe ; /* sweep frequency at end */ short slen ; /* sweep length in ms */ short styp ; /* sweep type code: 1 = linear 2 = cos-squared 3 = other */ short stas ; /* sweep trace length at start in ms */ short stae ; /* sweep trace length at end in ms */ short tatyp ; /* taper type: 1=linear, 2=cos^2, 3=other */ short afilf ; /* alias filter frequency if used */ short afils ; /* alias filter slope */ short nofilf ; /* notch filter frequency if used */ short nofils ; /* notch filter slope */ short lcf ; /* low cut frequency if used */ short hcf ; /* high cut frequncy if used */ short lcs ; /* low cut slope */ short hcs ; /* high cut slope */ short year ; /* year data recorded */ short day ; /* day of year */ short hour ; /* hour of day (24 hour clock) */ short minute ; /* minute of hour */ short sec ; /* second of minute */ short timbas ; /* time basis code: 1 = local 2 = GMT 3 = other */ short trwf ; /* trace weighting factor, defined as 1/2^N volts for the least sigificant bit */ short grnors ; /* geophone group number of roll switch position one */ short grnofr ; /* geophone group number of trace one within original field record */ short grnlof ; /* geophone group number of last trace within original field record */ short gaps ; /* gap size (total number of groups dropped) */ short otrav ; /* overtravel taper code: 1 = down (or behind) 2 = up (or ahead) */ /* local assignments */ float d1; /* sample spacing for non-seismic data */ float f1; /* first sample location for non-seismic data */ float d2; /* sample spacing between traces */ float f2; /* first trace location */ float ungpow; /* negative of power used for dynamic range compression */ float unscale; /* reciprocal of scaling factor to normalize range */ int ntr ; /* number of traces */ short mark ; /* mark selected traces */ short unass[15]; /* unassigned values */ float data[SU_NFLTS]; } segy; typedef struct { /* bhed - binary header */ int jobid ; /* job identification number */ int lino ; /* line number (only one line per reel) */ int reno ; /* reel number */ short ntrpr ; /* number of data traces per record */ short nart ; /* number of auxiliary traces per record */ short hdt ; /* sample interval in micro secs for this reel */ short dto ; /* same for original field recording */ short hns ; /* number of samples per trace for this reel */ short nso ; /* same for original field recording */ short format ; /* data sample format code: 1 = floating point (4 bytes) 2 = fixed point (4 bytes) 3 = fixed point (2 bytes) 4 = fixed point w/gain code (4 bytes) */ short fold ; /* CDP fold expected per CDP ensemble */ short tsort ; /* trace sorting code: 1 = as recorded (no sorting) 2 = CDP ensemble 3 = single fold continuous profile 4 = horizontally stacked */ short vscode ; /* vertical sum code: 1 = no sum 2 = two sum ... N = N sum (N = 32,767) */ short hsfs ; /* sweep frequency at start */ short hsfe ; /* sweep frequency at end */ short hslen ; /* sweep length (ms) */ short hstyp ; /* sweep type code: 1 = linear 2 = parabolic 3 = exponential 4 = other */ short schn ; /* trace number of sweep channel */ short hstas ; /* sweep trace taper length at start if tapered (the taper starts at zero time and is effective for this length) */ short hstae ; /* sweep trace taper length at end (the ending taper starts at sweep length minus the taper length at end) */ short htatyp ; /* sweep trace taper type code: 1 = linear 2 = cos-squared 3 = other */ short hcorr ; /* correlated data traces code: 1 = no 2 = yes */ short bgrcv ; /* binary gain recovered code: 1 = yes 2 = no */ short rcvm ; /* amplitude recovery method code: 1 = none 2 = spherical divergence 3 = AGC 4 = other */ short mfeet ; /* measurement system code: 1 = meters 2 = feet */ short polyt ; /* impulse signal polarity code: 1 = increase in pressure or upward geophone case movement gives negative number on tape 2 = increase in pressure or upward geophone case movement gives positive number on tape */ short vpol ; /* vibratory polarity code: code seismic signal lags pilot by 1 337.5 to 22.5 degrees 2 22.5 to 67.5 degrees 3 67.5 to 112.5 degrees 4 112.5 to 157.5 degrees 5 157.5 to 202.5 degrees 6 202.5 to 247.5 degrees 7 247.5 to 292.5 degrees 8 293.5 to 337.5 degrees */ char pad[4] ; /* double word alignment pad */ int hunass[42]; /* unassigned */ } bhed; #endif /* end of ifdef CRAY, the bit fields are not portable */ /* DEFINES */ #define gettr(x) fgettr(stdin, (x)) #define vgettr(x) fvgettr(stdin, (x)) #define puttr(x) fputtr(stdout, (x)) #define gettra(x, y) fgettra(stdin, (x), (y)) /* The following refer to the trid field in segy.h */ /* CHARPACK represents byte packed seismic data from supack1 */ #define CHARPACK 101 /* SHORTPACK represents 2 byte packed seismic data from supack2 */ #define SHORTPACK 102 /* TREAL represents real time traces */ #define TREAL 1 /* TDEAD represents dead time traces */ #define TDEAD 2 /* TDUMMY represents dummy time traces */ #define TDUMMY 3 /* TBREAK represents time break traces */ #define TBREAK 4 /* UPHOLE represents uphole traces */ #define UPHOLE 5 /* SWEEP represents sweep traces */ #define SWEEP 6 /* TIMING represents timing traces */ #define TIMING 7 /* WBREAK represents timing traces */ #define WBREAK 8 /* TCMPLX represents complex time traces */ #define TCMPLX 13 /* TAMPH represents time domain data in amplitude/phase form */ #define TAMPH 15 /* FPACK represents packed frequency domain data */ #define FPACK 12 /* FUNPACKNYQ represents complex frequency domain data */ #define FUNPACKNYQ 11 /* FCMPLX represents complex frequency domain data */ #define FCMPLX 10 /* FAMPH represents freq domain data in amplitude/phase form */ #define FAMPH 14 /* REALPART represents the real part of a trace to Nyquist */ #define REALPART 16 /* IMAGPART represents the imaginary part of a trace to Nyquist */ #define IMAGPART 17 /* AMPLITUDE represents the amplitude of a trace to Nyquist */ #define AMPLITUDE 18 /* PHASE represents the phase of a trace to Nyquist */ #define PHASE 19 /* KT represents wavenumber-time domain data */ #define KT 21 /* KOMEGA represents wavenumber-frequency domain data */ #define KOMEGA 22 /* ENVELOPE represents the envelope of the complex time trace */ #define ENVELOPE 23 /* INSTPHASE represents the phase of the complex time trace */ #define INSTPHASE 24 /* INSTFREQ represents the frequency of the complex time trace */ #define INSTFREQ 25 /* DEPTH represents traces in depth-range (z-x) */ #define TRID_DEPTH 30 #define ISSEISMIC(id) ( (id)==0 || (id)==TREAL || (id)==TDEAD || (id)==TDUMMY ) /* FUNCTION PROTOTYPES */ #ifdef __cplusplus /* if C++, specify external linkage to C functions */ extern "C" { #endif int fgettr(FILE *fp, segy *tp); int fvgettr(FILE *fp, segy *tp); void fputtr(FILE *fp, segy *tp); int fgettra(FILE *fp, segy *tp, int itr); /* hdrpkge */ /* void gethval(const segy *tp, int index, Value *valp); void puthval(segy *tp, int index, Value *valp); void getbhval(const bhed *bhp, int index, Value *valp); void putbhval(bhed *bhp, int index, Value *valp); void gethdval(const segy *tp, char *key, Value *valp); void puthdval(segy *tp, char *key, Value *valp); char *hdtype(const char *key); char *getkey(const int index); int getindex(const char *key); void swaphval(segy *tp, int index); void swapbhval(bhed *bhp, int index); void printheader(const segy *tp); */ void tabplot(segy *tp, int itmin, int itmax); #ifdef __cplusplus /* if C++, end external linkage specification */ } #endif #endif
Java
/* * File: tstGenericDBObject.cpp * Author: volker * * Created on March 2, 2014, 3:46 PM */ #include <QString> #include "tstScore.h" #include "Score.h" using namespace QTournament; //---------------------------------------------------------------------------- void tstScore::testGameScore_IsValidScore() { printStartMsg("tstScore::testGameScore_IsValidScore"); int tstScore[][3] = { {-1, 10, 0}, {21, -6, 0}, {29, 31, 0}, {32, 10, 0}, {21, 21, 0}, {12, 12, 0}, {30, 29, 1}, {29, 30, 1}, {20, 21, 0}, {21, 20, 0}, {13, 21, 1}, {21, 0, 1}, {23, 21, 1}, {28, 26, 1}, {28, 3, 0}, }; for (auto score : tstScore) { bool expectedResult = (score[2] == 1); // test the static function isValidScore() CPPUNIT_ASSERT(GameScore::isValidScore(score[0], score[1]) == expectedResult); // test the factory function fromScore() auto g = GameScore::fromScore(score[0], score[1]); CPPUNIT_ASSERT((g == nullptr) == !expectedResult); if (expectedResult) { auto sc = g->getScore(); CPPUNIT_ASSERT(get<0>(sc) == score[0]); CPPUNIT_ASSERT(get<1>(sc) == score[1]); } // test the factory function fromString() QString s = QString::number(score[0]) + ":" + QString::number(score[1]); g = GameScore::fromString(s); CPPUNIT_ASSERT((g == nullptr) == !expectedResult); if (expectedResult) { auto sc = g->getScore(); CPPUNIT_ASSERT(get<0>(sc) == score[0]); CPPUNIT_ASSERT(get<1>(sc) == score[1]); } } printEndMsg(); } //---------------------------------------------------------------------------- void tstScore::testGameScore_ToString() { printStartMsg("tstScore::testGameScore_ToString"); auto gs = GameScore::fromScore(12, 21); CPPUNIT_ASSERT(gs->toString() == "12:21"); gs = GameScore::fromScore(21, 0); CPPUNIT_ASSERT(gs->toString() == "21:0"); printEndMsg(); } //---------------------------------------------------------------------------- void tstScore::testGameScore_GetWinner() { printStartMsg("tstScore::testGameScore_GetWinner"); int tstScore[][3] = { {30, 29, 1}, {29, 30, 2}, {13, 21, 2}, {21, 0, 1}, {23, 21, 1}, {28, 26, 1}, }; for (auto score : tstScore) { auto gs = GameScore::fromScore(score[0], score[1]); CPPUNIT_ASSERT(gs->getWinner() == score[2]); int loser = (score[2] == 1) ? 2 : 1; CPPUNIT_ASSERT(gs->getLoser() == loser); } printEndMsg(); } //---------------------------------------------------------------------------- //------------------MatchScore------------------------------------------------ //---------------------------------------------------------------------------- void tstScore::testMatchScore_FactoryFuncs_ToString() { constexpr int MAX_NUM_GAMES = 5; printStartMsg("tstScore::testMatchScore_FactoryFuncs_ToString"); int gameScore[][2] = { {30, 29}, // 0 {29, 30}, // 1 {13, 21}, // 2 {21, 0}, // 3 {21, 18}, // 4 {23, 21}, // 5 {28, 26}, // 6 }; int gameCombinations[][MAX_NUM_GAMES + 5] = { // game1, game2, game3, game4, game5, numWinGames, allowDraw, isValid, winner, loser // +0 , +1 , +2 , +3 , +4 {0, 1, -1, -1, -1, 2, 0, 0, -1, -1}, // invalid draw {0, 0, -1, -1, -1, 2, 0, 1, 1, 2}, // two games, player 1 wins {2, 4, 2, 2, -1, 2, 0, 0, -1, -1}, // four games but only two win games ==> invalid {2, 4, 2, 2, -1, 3, 0, 1, 2, 1}, // four games, three win games ==> valid {2, 4, 4, 2, 2, 3, 0, 1, 2, 1}, // five games, three win games ==> valid {2, 4, 4, -1, -1, 3, 0, 0, -1, -1}, // three games, three win games ==> invalid {2, 4, 4, -1, -1, 2, 0, 1, 1, 2}, // three games, two win games ==> valid {2, 4, 4, -1, -1, 3, 1, 0, -1, -1}, // three games, three win games, draw allowed ==> invalid {2, 4, -1, -1, -1, 2, 1, 1, 0, 0}, // two games, two win games, draw allowed ==> valid {2, 4, 2, 4, -1, 3, 1, 1, 0, 0}, // four games, three win games, draw allowed ==> valid }; for (auto combi : gameCombinations) { GameScoreList gsl; QString scoreString; for (int gameCount = 0; gameCount < MAX_NUM_GAMES; ++gameCount) { if (combi[gameCount] != -1) { auto game = GameScore::fromScore(gameScore[combi[gameCount]][0], gameScore[combi[gameCount]][1]); CPPUNIT_ASSERT(game != nullptr); gsl.append(*game); scoreString += game->toString() + ","; } } scoreString = scoreString.left(scoreString.length() - 1); int numWinGames = combi[MAX_NUM_GAMES]; bool allowDraw = (combi[MAX_NUM_GAMES+1] == 1); bool isValidMatch = (combi[MAX_NUM_GAMES+2] == 1); // test the factory function fromGameScoreList() auto match = MatchScore::fromGameScoreList(gsl, numWinGames, allowDraw); if (!isValidMatch) { CPPUNIT_ASSERT(match == nullptr); continue; } CPPUNIT_ASSERT(match != nullptr); // test the factory function fromString() auto match1 = MatchScore::fromString(scoreString, numWinGames, allowDraw); if (!isValidMatch) { CPPUNIT_ASSERT(match1 == nullptr); continue; } CPPUNIT_ASSERT(match1 != nullptr); // test the static isValidScore() function CPPUNIT_ASSERT(MatchScore::isValidScore(gsl, numWinGames, allowDraw) == isValidMatch); // test the toString() function CPPUNIT_ASSERT(match->toString() == scoreString); CPPUNIT_ASSERT(match1->toString() == scoreString); } printEndMsg(); } //---------------------------------------------------------------------------- void tstScore::testMatchScore_GetWinner_GetLoser() { constexpr int MAX_NUM_GAMES = 5; printStartMsg("tstScore::testMatchScore_GetWinner_GetLoser"); int gameScore[][2] = { {30, 29}, // 0 {29, 30}, // 1 {13, 21}, // 2 {21, 0}, // 3 {21, 18}, // 4 {23, 21}, // 5 {28, 26}, // 6 }; int gameCombinations[][MAX_NUM_GAMES + 5] = { // game1, game2, game3, game4, game5, numWinGames, allowDraw, isValid, winner, loser // +0 , +1 , +2 , +3 , +4 {0, 0, -1, -1, -1, 2, 0, 1, 1, 2}, // two games, player 1 wins {2, 4, 2, 2, -1, 3, 0, 1, 2, 1}, // four games, three win games ==> valid {2, 4, 4, 2, 2, 3, 0, 1, 2, 1}, // five games, three win games ==> valid {2, 4, 4, -1, -1, 2, 0, 1, 1, 2}, // three games, two win games ==> valid {2, 4, -1, -1, -1, 2, 1, 1, 0, 0}, // two games, two win games, draw allowed ==> valid {2, 4, 2, 4, -1, 3, 1, 1, 0, 0}, // four games, three win games, draw allowed ==> valid }; for (auto combi : gameCombinations) { GameScoreList gsl; for (int gameCount = 0; gameCount < MAX_NUM_GAMES; ++gameCount) { if (combi[gameCount] != -1) { auto game = GameScore::fromScore(gameScore[combi[gameCount]][0], gameScore[combi[gameCount]][1]); CPPUNIT_ASSERT(game != nullptr); gsl.append(*game); } } int numWinGames = combi[MAX_NUM_GAMES]; bool allowDraw = (combi[MAX_NUM_GAMES+1] == 1); auto match = MatchScore::fromGameScoreList(gsl, numWinGames, allowDraw); CPPUNIT_ASSERT(match != nullptr); // test getWinner() and getLoser() CPPUNIT_ASSERT(match->getWinner() == combi[MAX_NUM_GAMES+3]); CPPUNIT_ASSERT(match->getLoser() == combi[MAX_NUM_GAMES+4]); } printEndMsg(); } //---------------------------------------------------------------------------- void tstScore::testRandomMatchGeneration() { constexpr int MATCH_COUNT = 1000; constexpr double PROBABILITY_MARGIN = 0.05; printStartMsg("tstScore::testRandomMatchGeneration"); // a lambda as a match generator auto matchGenerator = [](int count, int numWinGames, bool drawAllowed) { MatchScoreList result; for (int i=0; i < count; ++i) { result.append(*(MatchScore::genRandomScore(numWinGames, drawAllowed))); } return result; }; // a lambda to compare an actual count with an expected count // including a margin auto isCountInRange = [](int expected, int actual, double margin) { int absMargin = static_cast<int>(expected * margin); int minCount = expected - absMargin; int maxCount = expected + absMargin; return ((actual <= maxCount) && (actual >= minCount)); }; // Generate matches with 2 win games and no draw MatchScoreList msl = matchGenerator(MATCH_COUNT, 2, false); CPPUNIT_ASSERT(msl.count() == MATCH_COUNT); // gather some statistics int p1Wins = 0; int p2Wins = 0; int gamesCount = 0; int gamesBeyond21 = 0; for (MatchScore ms : msl) { if (ms.getWinner() == 1) ++p1Wins; if (ms.getWinner() == 2) ++p2Wins; int cnt = ms.getNumGames(); for (int i=0; i < cnt; ++i) { ++gamesCount; auto gs = ms.getGame(i); if (gs->getWinnerScore() > 21) ++gamesBeyond21; } CPPUNIT_ASSERT(ms.isValidScore(2, false)); } // make sure that wins are equally distributed among players CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT / 2, p1Wins, PROBABILITY_MARGIN)); CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT / 2, p2Wins, PROBABILITY_MARGIN)); CPPUNIT_ASSERT(isCountInRange(gamesCount * 0.3, gamesBeyond21, PROBABILITY_MARGIN)); // Generate matches with 3 win games and draw msl.clear(); msl = matchGenerator(MATCH_COUNT, 3, true); CPPUNIT_ASSERT(msl.count() == MATCH_COUNT); // gather some statistics p1Wins = 0; p2Wins = 0; int draws = 0; gamesCount = 0; gamesBeyond21 = 0; for (MatchScore ms : msl) { if (ms.getWinner() == 0) ++draws; if (ms.getWinner() == 1) ++p1Wins; if (ms.getWinner() == 2) ++p2Wins; int cnt = ms.getNumGames(); for (int i=0; i < cnt; ++i) { ++gamesCount; auto gs = ms.getGame(i); if (gs->getWinnerScore() > 21) ++gamesBeyond21; } if (ms.getWinner() == 0) { CPPUNIT_ASSERT(ms.getNumGames() == 4); // 4 = (numWinGames - 1) * 2 } CPPUNIT_ASSERT(ms.isValidScore(3, true)); } // make sure that wins are equally distributed among players CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT * 0.3, draws, PROBABILITY_MARGIN)); CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT * 0.35, p1Wins, PROBABILITY_MARGIN)); CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT * 0.35, p2Wins, PROBABILITY_MARGIN)); CPPUNIT_ASSERT(isCountInRange(gamesCount * 0.3, gamesBeyond21, PROBABILITY_MARGIN)); printEndMsg(); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //----------------------------------------------------------------------------
Java
CC = gcc CFLAGS = -g -Wall -Werror -D_GNU_SOURCE -I../include LDFLAGS = -ljson-c HEADERS = ../include/json.h ../include/error.h ../include/account.h ../include/util.h SRC = assignfee.c ../lib/json.c ../lib/account.c ../lib/error.c ../lib/util.c assignfee: $(SRC) $(HEADERS) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) -o$@ clean: rm -f assignfee .PHONY: clean
Java
import java.util.Scanner; public class FeetMeters { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Number of feet: "); float feet = keyboard.nextInt(); float foottometers = (float) .305; System.out.println(""); System.out.print("Number of meters: "); float meters = (float) .305 * feet; System.out.println(meters); } }
Java
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Web service functions relating to point grades and grading. * * @package core_grades * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ declare(strict_types = 1); namespace core_grades\grades\grader\gradingpanel\point\external; use coding_exception; use context; use core_user; use core_grades\component_gradeitem as gradeitem; use core_grades\component_gradeitems; use external_api; use external_function_parameters; use external_multiple_structure; use external_single_structure; use external_value; use external_warnings; use moodle_exception; use required_capability_exception; /** * External grading panel point API * * @package core_grades * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class store extends external_api { /** * Describes the parameters for fetching the grading panel for a simple grade. * * @return external_function_parameters * @since Moodle 3.8 */ public static function execute_parameters(): external_function_parameters { return new external_function_parameters ([ 'component' => new external_value( PARAM_ALPHANUMEXT, 'The name of the component', VALUE_REQUIRED ), 'contextid' => new external_value( PARAM_INT, 'The ID of the context being graded', VALUE_REQUIRED ), 'itemname' => new external_value( PARAM_ALPHANUM, 'The grade item itemname being graded', VALUE_REQUIRED ), 'gradeduserid' => new external_value( PARAM_INT, 'The ID of the user show', VALUE_REQUIRED ), 'notifyuser' => new external_value( PARAM_BOOL, 'Wheteher to notify the user or not', VALUE_DEFAULT, false ), 'formdata' => new external_value( PARAM_RAW, 'The serialised form data representing the grade', VALUE_REQUIRED ), ]); } /** * Fetch the data required to build a grading panel for a simple grade. * * @param string $component * @param int $contextid * @param string $itemname * @param int $gradeduserid * @param bool $notifyuser * @param string $formdata * @return array * @throws \dml_exception * @throws \invalid_parameter_exception * @throws \restricted_context_exception * @throws coding_exception * @throws moodle_exception * @since Moodle 3.8 */ public static function execute(string $component, int $contextid, string $itemname, int $gradeduserid, bool $notifyuser, string $formdata): array { global $USER; [ 'component' => $component, 'contextid' => $contextid, 'itemname' => $itemname, 'gradeduserid' => $gradeduserid, 'notifyuser' => $notifyuser, 'formdata' => $formdata, ] = self::validate_parameters(self::execute_parameters(), [ 'component' => $component, 'contextid' => $contextid, 'itemname' => $itemname, 'gradeduserid' => $gradeduserid, 'notifyuser' => $notifyuser, 'formdata' => $formdata, ]); // Validate the context. $context = context::instance_by_id($contextid); self::validate_context($context); // Validate that the supplied itemname is a gradable item. if (!component_gradeitems::is_valid_itemname($component, $itemname)) { throw new coding_exception("The '{$itemname}' item is not valid for the '{$component}' component"); } // Fetch the gradeitem instance. $gradeitem = gradeitem::instance($component, $context, $itemname); // Validate that this gradeitem is actually enabled. if (!$gradeitem->is_grading_enabled()) { throw new moodle_exception("Grading is not enabled for {$itemname} in this context"); } // Fetch the record for the graded user. $gradeduser = \core_user::get_user($gradeduserid); // Require that this user can save grades. $gradeitem->require_user_can_grade($gradeduser, $USER); if (!$gradeitem->is_using_direct_grading()) { throw new moodle_exception("The {$itemname} item in {$component}/{$contextid} is not configured for direct grading"); } // Parse the serialised string into an object. $data = []; parse_str($formdata, $data); // Grade. $gradeitem->store_grade_from_formdata($gradeduser, $USER, (object) $data); $hasgrade = $gradeitem->user_has_grade($gradeduser); // Notify. if ($notifyuser) { // Send notification. $gradeitem->send_student_notification($gradeduser, $USER); } // Fetch the updated grade back out. $grade = $gradeitem->get_grade_for_user($gradeduser, $USER); return fetch::get_fetch_data($grade, $hasgrade, 0); } /** * Describes the data returned from the external function. * * @return external_single_structure * @since Moodle 3.8 */ public static function execute_returns(): external_single_structure { return fetch::execute_returns(); } }
Java
from pupa.scrape import Jurisdiction, Organization from .bills import MNBillScraper from .committees import MNCommitteeScraper from .people import MNPersonScraper from .vote_events import MNVoteScraper from .events import MNEventScraper from .common import url_xpath """ Minnesota legislative data can be found at the Office of the Revisor of Statutes: https://www.revisor.mn.gov/ Votes: There are not detailed vote data for Senate votes, simply yes and no counts. Bill pages have vote counts and links to House details, so it makes more sense to get vote data from the bill pages. """ class Minnesota(Jurisdiction): division_id = "ocd-division/country:us/state:mn" classification = "government" name = "Minnesota" url = "http://state.mn.us/" check_sessions = True scrapers = { "bills": MNBillScraper, "committees": MNCommitteeScraper, "people": MNPersonScraper, "vote_events": MNVoteScraper, "events": MNEventScraper, } parties = [{'name': 'Republican'}, {'name': 'Democratic-Farmer-Labor'}] legislative_sessions = [ { '_scraped_name': '86th Legislature, 2009-2010', 'classification': 'primary', 'identifier': '2009-2010', 'name': '2009-2010 Regular Session' }, { '_scraped_name': '86th Legislature, 2010 1st Special Session', 'classification': 'special', 'identifier': '2010 1st Special Session', 'name': '2010, 1st Special Session' }, { '_scraped_name': '86th Legislature, 2010 2nd Special Session', 'classification': 'special', 'identifier': '2010 2nd Special Session', 'name': '2010, 2nd Special Session' }, { '_scraped_name': '87th Legislature, 2011-2012', 'classification': 'primary', 'identifier': '2011-2012', 'name': '2011-2012 Regular Session' }, { '_scraped_name': '87th Legislature, 2011 1st Special Session', 'classification': 'special', 'identifier': '2011s1', 'name': '2011, 1st Special Session' }, { '_scraped_name': '87th Legislature, 2012 1st Special Session', 'classification': 'special', 'identifier': '2012s1', 'name': '2012, 1st Special Session' }, { '_scraped_name': '88th Legislature, 2013-2014', 'classification': 'primary', 'identifier': '2013-2014', 'name': '2013-2014 Regular Session' }, { '_scraped_name': '88th Legislature, 2013 1st Special Session', 'classification': 'special', 'identifier': '2013s1', 'name': '2013, 1st Special Session' }, { '_scraped_name': '89th Legislature, 2015-2016', 'classification': 'primary', 'identifier': '2015-2016', 'name': '2015-2016 Regular Session' }, { '_scraped_name': '89th Legislature, 2015 1st Special Session', 'classification': 'special', 'identifier': '2015s1', 'name': '2015, 1st Special Session' }, { '_scraped_name': '90th Legislature, 2017-2018', 'classification': 'primary', 'identifier': '2017-2018', 'name': '2017-2018 Regular Session' }, ] ignored_scraped_sessions = [ '85th Legislature, 2007-2008', '85th Legislature, 2007 1st Special Session', '84th Legislature, 2005-2006', '84th Legislature, 2005 1st Special Session', '83rd Legislature, 2003-2004', '83rd Legislature, 2003 1st Special Session', '82nd Legislature, 2001-2002', '82nd Legislature, 2002 1st Special Session', '82nd Legislature, 2001 1st Special Session', '81st Legislature, 1999-2000', '80th Legislature, 1997-1998', '80th Legislature, 1998 1st Special Session', '80th Legislature, 1997 3rd Special Session', '80th Legislature, 1997 2nd Special Session', '80th Legislature, 1997 1st Special Session', '79th Legislature, 1995-1996', '79th Legislature, 1995 1st Special Session', '89th Legislature, 2015-2016', ] def get_organizations(self): legis = Organization('Minnesota Legislature', classification='legislature') upper = Organization('Minnesota Senate', classification='upper', parent_id=legis._id) lower = Organization('Minnesota House of Representatives', classification='lower', parent_id=legis._id) for n in range(1, 68): upper.add_post(label=str(n), role='Senator', division_id='ocd-division/country:us/state:mn/sldu:{}'.format(n)) lower.add_post(label=str(n) + 'A', role='Representative', division_id='ocd-division/country:us/state:mn/sldl:{}a'.format(n)) lower.add_post(label=str(n) + 'B', role='Representative', division_id='ocd-division/country:us/state:mn/sldl:{}b'.format(n)) yield legis yield upper yield lower def get_session_list(self): return url_xpath('https://www.revisor.mn.gov/revisor/pages/' 'search_status/status_search.php?body=House', '//select[@name="session"]/option/text()')
Java
<?php namespace Test\FlexiPeeHP; use FlexiPeeHP\Nastaveni; /** * Generated by PHPUnit_SkeletonGenerator on 2016-04-27 at 17:32:11. */ class NastaveniTest extends FlexiBeeROTest { /** * @var Nastaveni */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp(): void { $this->object = new Nastaveni(); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown(): void { } /** * @covers FlexiPeeHP\Nastaveni::getFlexiData */ public function testGetFlexiData() { if ($this->object->url == 'https://demo.flexibee.eu') { $this->markTestSkipped('Public demo site does not allow read here'); } else { $flexidata = $this->object->getFlexiData(); $this->assertArrayHasKey(0, $flexidata); $this->assertArrayHasKey('id', $flexidata[0]); $filtrered = $this->object->getFlexiData(null, key($flexidata[0])." = ".current($flexidata[0])); $this->assertArrayHasKey(0, $filtrered); $this->assertArrayHasKey('id', $filtrered[0]); } } }
Java
#pragma once #include <fstream> #include <iomanip> #include <map> #include <sstream> #include <string> #include "jw.hpp" namespace Zee { class Report { public: Report(std::string title, std::string rowTitle) : title_(title), rowTitle_(rowTitle) { rowSize_ = rowTitle_.size(); } void addColumn(std::string colName, std::string texName = "") { columns_.push_back(colName); if (!texName.empty()) columnsTex_.push_back(texName); else columnsTex_.push_back(colName); columnWidth_[colName] = colName.size(); } void addRow(std::string row) { entries_[row] = std::map<std::string, std::string>(); if (row.size() > rowSize_) { rowSize_ = row.size(); } } template <typename T> void addResult(std::string row, std::string column, T result) { if (entries_.find(row) == entries_.end()) { JWLogError << "Trying to add result to non-existing row" << endLog; return; } std::stringstream ss; ss << std::fixed << std::setprecision(1) << result; entries_[row][column] = ss.str(); entriesTex_[row][column] = ss.str(); if (ss.str().size() > columnWidth_[column]) { columnWidth_[column] = ss.str().size(); } } void addResult(std::string row, std::string column, std::string result, std::string texResult) { addResult(row, column, result); entriesTex_[row][column] = texResult; } void print() { JWLogResult << title_ << endLog; unsigned int lineSize = rowSize_ + 4; for (auto col : columnWidth_) { lineSize += col.second + 2; } std::string hline = ""; for (unsigned int i = 0; i < lineSize; ++i) hline.push_back('-'); auto addElement = [](int width, std::stringstream& result, std::string entry) { result << std::left << std::setprecision(1) << std::setw(width) << std::setfill(' ') << entry; }; std::stringstream ss; addElement(rowSize_ + 2, ss, rowTitle_); ss << "| "; for (auto& col : columns_) addElement(columnWidth_[col] + 2, ss, col); JWLogInfo << hline << endLog; JWLogInfo << ss.str() << endLog; JWLogInfo << hline << endLog; for (auto& rowCols : entries_) { std::stringstream rowSs; addElement(rowSize_ + 2, rowSs, rowCols.first); rowSs << "| "; for (auto& col : columns_) { addElement(columnWidth_[col] + 2, rowSs, rowCols.second[col]); } JWLogInfo << rowSs.str() << endLog; } JWLogInfo << hline << endLog; } void saveToCSV(); void readFromCSV(); void saveToTex(std::string filename) { auto replaceTex = [](std::string entry) { std::string texEntry = entry; auto pos = entry.find("+-"); if (pos != std::string::npos) { texEntry = texEntry.substr(0, pos) + "\\pm" + texEntry.substr(pos + 2); } pos = entry.find("%"); if (pos != std::string::npos) { texEntry = texEntry.substr(0, pos) + "\\%" + texEntry.substr(pos + 1); } return texEntry; }; std::ofstream fout(filename); fout << "\\begin{table}" << std::endl; fout << "\\centering" << std::endl; fout << "\\begin{tabular}{|l|"; for (unsigned int i = 0; i < columns_.size(); ++i) { fout << "l"; fout << ((i < (columns_.size() - 1)) ? " " : "|}"); } fout << std::endl << "\\hline" << std::endl; fout << "\\textbf{" << rowTitle_ << "} & "; for (unsigned int i = 0; i < columns_.size(); ++i) { fout << "$" << columnsTex_[i] << "$"; fout << ((i < (columns_.size() - 1)) ? " & " : "\\\\"); } fout << std::endl; fout << "\\hline" << std::endl; for (auto& rowCols : entriesTex_) { fout << "\\verb|" << rowCols.first << "| & "; for (unsigned int i = 0; i < columns_.size(); ++i) { fout << "$" << replaceTex(rowCols.second[columns_[i]]) << "$"; fout << ((i < (columns_.size() - 1)) ? " & " : "\\\\"); } fout << std::endl; } fout << "\\hline" << std::endl; fout << "\\end{tabular}" << std::endl; ; fout << "\\caption{\\ldots}" << std::endl; fout << "\\end{table}" << std::endl; } private: std::string title_; std::string rowTitle_; std::map<std::string, std::map<std::string, std::string>> entries_; std::map<std::string, std::map<std::string, std::string>> entriesTex_; std::vector<std::string> columns_; std::vector<std::string> columnsTex_; std::map<std::string, unsigned int> columnWidth_; unsigned int rowSize_; }; } // namespace Zee
Java
package ProxyPattern; public class GumballMachineTestDrive { public static void main(String[] args) { int count = 0; if (args .length < 2) { System.out.println("GumballMachine <name> <inventory>"); System.exit(1); } count = Integer.parseInt(args[1]); GumballMachine gumballMachine = new GumballMachine(args[0], count); GumballMonitor monitor = new GumballMonitor(gumballMachine); monitor.report(); } }
Java
<?php /** * OpenSKOS * * LICENSE * * This source file is subject to the GPLv3 license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.gnu.org/licenses/gpl-3.0.txt * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category OpenSKOS * @package OpenSKOS * @copyright Copyright (c) 2011 Pictura Database Publishing. (http://www.pictura-dp.nl) * @author Mark Lindeman * @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 */ class OpenSKOS_Solr_Document implements Countable, ArrayAccess, Iterator { protected $fieldnames = array(); protected $data = array(); protected $position = 0; public function __set($fieldname, $value) { //this differs from self::offsetSet: // - if a field has been set before, make this field multiValued $offsetExists = $this->offsetExists($fieldname); $value = !is_array($value) ? array($value) : $value; if (!$offsetExists) { $this->fieldnames[] = $fieldname; $this->data[$fieldname] = $value; } else { if (is_array($this->data[$fieldname])) { $this->data[$fieldname] = array_merge($this->data[$fieldname], $value); } else { $this->data[$fieldname] = array_merge(array($this->data[$fieldname]), $value); } } } public function offsetSet($fieldname, $value) { $newField = false; if (!$this->offsetExists($fieldname)) { $this->fieldnames[] = $fieldname; $newField = true; } if (!is_array($value)) { if (false === $newField) { $this->data[$fieldname][] = $value; } else { $this->data[$fieldname] = array($value); } } else { if (false === $newField) { $this->data[$fieldname] = $this->data[$fieldname] + $value; } else { $this->data[$fieldname] = $value; } } } public function offsetExists($fieldname) { return in_array($fieldname, $this->fieldnames); } public function offsetUnset($fieldname) { if (!$this->offsetExists($fieldname)) { trigger_error('Undefined index: '.$fieldname, E_USER_NOTICE); return; } unset ( $this->data[$fieldname]); $ix = array_search($fieldname, $this->fieldnames); unset($this->fieldnames[$ix]); $fieldnames = array(); foreach ($this->fieldnames as $fieldname) $fieldnames[] = $fieldname; $this->fieldnames = $fieldnames; $this->rewind(); } public function offsetGet($fieldname) { return $this->offsetExists($fieldname) ? $this->data [$fieldname] : null; } public function count() { return count($this->fieldnames); } public function rewind() { $this->position = 0; } public function current() { return $this->data[$this->fieldnames[$this->position]]; } public function key() { return $this->fieldnames[$this->position]; } public function next() { ++$this->position; } public function valid() { return isset($this->data[$this->fieldnames[$this->position]]); } public function toArray() { return $this->data; } /** * @return OpenSKOS_Solr */ protected function solr() { return Zend_Registry::get('OpenSKOS_Solr'); } public function save($commit = null) { $this->solr()->add(new OpenSKOS_Solr_Documents($this), $commit); return $this; } /** * Registers the notation of the document in the database, or generates one if the document does not have notation. * * @return OpenSKOS_Solr */ public function registerOrGenerateNotation() { if ((isset($this->data['class']) && $this->data['class'] == 'Concept') || (isset($this->data['class'][0]) && $this->data['class'][0] == 'Concept')) { $currentNotation = ''; if (isset($this->data['notation']) && isset($this->data['notation'][0])) { $currentNotation = $this->data['notation'][0]; } if (empty($currentNotation)) { $this->fieldnames[] = 'notation'; $this->data['notation'] = array(OpenSKOS_Db_Table_Notations::getNext()); // Adds the notation to the xml. At the end just before </rdf:Description> $closingTag = '</rdf:Description>'; $notationTag = '<skos:notation>' . $this->data['notation'][0] . '</skos:notation>'; $xml = $this->data['xml']; $xml = str_replace($closingTag, $notationTag . $closingTag, $xml); $this->data['xml'] = $xml; } else { if ( ! OpenSKOS_Db_Table_Notations::isRegistered($currentNotation)) { // If we do not have the notation registered - register it. OpenSKOS_Db_Table_Notations::register($currentNotation); } } } return $this; } /** * Generates uri if it can. Alters the document to put it in, also alters the xml to put rdf:about * @param OpenSKOS_Db_Table_Row_Collection $collection From where to get the basic uri. * @throws OpenSKOS_Rdf_Parser_Exception */ public function autoGenerateUri(OpenSKOS_Db_Table_Row_Collection $collection) { if (!((isset($this->data['class']) && $this->data['class'] == 'Concept') || (isset($this->data['class'][0]) && $this->data['class'][0] == 'Concept'))) { throw new OpenSKOS_Rdf_Parser_Exception( 'Auto generate uri is for concepts only. Not working for concept schemas.' ); } if ($collection === null) { throw new OpenSKOS_Rdf_Parser_Exception( 'Auto generate uri is set to true, but collection is not provided.' ); } $baseUri = $collection->getConceptsBaseUri(); if (empty($baseUri)) { throw new OpenSKOS_Rdf_Parser_Exception( 'Auto generate uri is set to true, but collection is not provided.' ); } if (!preg_match('/\/$/', $baseUri) && !preg_match('/=$/', $baseUri)) { $baseUri .= '/'; } $this->registerOrGenerateNotation(); $uri = $baseUri . $this->data['notation'][0]; // Write in the xml. if (strpos($this->data['xml'][0], 'rdf:about') !== false) { throw new OpenSKOS_Rdf_Parser_Exception( 'Can not auto generate uri if rdf about is set.' ); } $this->data['xml'] = str_replace( '<rdf:Description', '<rdf:Description rdf:about="' . $uri . '"', $this->data['xml'] ); $this->uri = $uri; } /** * * @throws OpenSKOS_Rdf_Parser_Exception */ public function updateStatusInGeneratedXml() { if (isset($this->data['status']) && isset($this->data['status'][0])) { $statusTag = '<openskos:status>' . $this->data['status'][0] . '</openskos:status>'; if (strpos($this->data['xml'][0], 'openskos:status') === false) { // Adds the status to the xml. At the end just before </rdf:Description> $closingTag = '</rdf:Description>'; $xml = $this->data['xml']; $xml = str_replace($closingTag, $statusTag . $closingTag, $xml); $this->data['xml'] = $xml; } else { $xml = $this->data['xml']; $xml = preg_replace('/<openskos:status>.*<\/openskos:status>/i', $statusTag, $xml); $this->data['xml'] = $xml; } } } public function __toString() { $doc = new DOMDocument(); $doc->loadXML('<doc/>'); foreach ($this->fieldnames as $fieldname) { foreach ($this->data[$fieldname] as $value) { $node = $doc->documentElement->appendChild($doc->createElement('field')); $htmlSafeValue = htmlspecialchars($value); if ($htmlSafeValue == $value) { $node->appendChild($doc->createTextNode($htmlSafeValue)); } else { $node->appendChild($doc->createCDataSection($value)); } $node->setAttribute('name', $fieldname); } } return $doc->saveXml($doc->documentElement); } }
Java
#ifndef SQLCONNECTDIALOG_H #define SQLCONNECTDIALOG_H #include <QDialog> #include <QtSql> namespace Ui { class SQLConnectDialog; } class SQLConnectDialog : public QDialog { Q_OBJECT public: explicit SQLConnectDialog(QWidget *parent = 0); ~SQLConnectDialog(); QSqlDatabase connect(QSqlDatabase db); private slots: void on_ConnectButton_clicked(); private: Ui::SQLConnectDialog *ui; QSqlDatabase tmp; }; #endif // SQLCONNECTDIALOG_H
Java
// This code is part of the CPCC-NG project. // // Copyright (c) 2009-2016 Clemens Krainer <clemens.krainer@gmail.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. package cpcc.demo.setup.builder; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.tuple.Pair; import cpcc.core.entities.SensorDefinition; import cpcc.core.entities.SensorType; import cpcc.core.entities.SensorVisibility; import cpcc.core.entities.TopicCategory; /** * Sensor Constants implementation. */ public final class SensorConstants { private static final String SENSOR_MSGS_NAV_SAT_FIX = "sensor_msgs/NavSatFix"; private static final String SENSOR_MSGS_IMAGE = "sensor_msgs/Image"; private static final String STD_MSGS_FLOAT32 = "std_msgs/Float32"; private static final Date now = new Date(); private static final SensorDefinition[] SENSOR_DEFINITIONS = { new SensorDefinitionBuilder() .setId(1) .setDescription("Altimeter") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.ALTIMETER) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(2) .setDescription("Area of Operations") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.AREA_OF_OPERATIONS) .setVisibility(SensorVisibility.PRIVILEGED_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(3) .setDescription("Barometer") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.BAROMETER) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(4) .setDescription("Battery") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.BATTERY) .setVisibility(SensorVisibility.PRIVILEGED_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(5) .setDescription("Belly Mounted Camera 640x480") .setLastUpdate(now) .setMessageType(SENSOR_MSGS_IMAGE) .setParameters("width=640 height=480 yaw=0 down=1.571 alignment=''north''") .setType(SensorType.CAMERA) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), // new SensorDefinitionBuilder() // .setId(6) // .setDescription("FPV Camera 640x480") // .setLastUpdate(now) // .setMessageType("sensor_msgs/Image") // .setParameters("width=640 height=480 yaw=0 down=0 alignment=''heading''") // .setType(SensorType.CAMERA) // .setVisibility(SensorVisibility.ALL_VV) // .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(7) .setDescription("CO2") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.CO2) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(9) .setDescription("GPS") .setLastUpdate(now) .setMessageType(SENSOR_MSGS_NAV_SAT_FIX) .setParameters(null) .setType(SensorType.GPS) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(10) .setDescription("Hardware") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.HARDWARE) .setVisibility(SensorVisibility.PRIVILEGED_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(11) .setDescription("NOx") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.NOX) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build(), new SensorDefinitionBuilder() .setId(12) .setDescription("Thermometer") .setLastUpdate(now) .setMessageType(STD_MSGS_FLOAT32) .setParameters(null) .setType(SensorType.THERMOMETER) .setVisibility(SensorVisibility.ALL_VV) .setDeleted(false).build() }; public static final Map<TopicCategory, SensorType> TOPIC_SENSOR_MAP = Collections.unmodifiableMap(Stream .of(Pair.of(TopicCategory.ALTITUDE_OVER_GROUND, SensorType.ALTIMETER), Pair.of(TopicCategory.CAMERA, SensorType.CAMERA), Pair.of(TopicCategory.CAMERA_INFO, SensorType.CAMERA), Pair.of(TopicCategory.GPS_POSITION_PROVIDER, SensorType.GPS)) .collect(Collectors.toMap(Pair::getLeft, Pair::getRight))); private SensorConstants() { // Intentionally empty. } /** * @param type the required sensor types. * @return all sensor definitions specified in type. */ public static List<SensorDefinition> byType(SensorType... type) { Set<SensorType> types = Stream.of(type).collect(Collectors.toSet()); return Stream.of(SENSOR_DEFINITIONS).filter(x -> types.contains(x.getType())).collect(Collectors.toList()); } /** * @return all sensor definitions. */ public static List<SensorDefinition> all() { return Arrays.asList(SENSOR_DEFINITIONS); } }
Java
<?php namespace App\Console\Commands; use App\App; use Illuminate\Console\Command; use Illuminate\Support\Facades\Artisan; use Imperium\File\File; class Venus extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'app:secure'; /** * The console command description. * * @var string */ protected $description = 'Configure app'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $db = database_path('venus'); if (!File::exist($db)) { if (File::create($db)) { File::copy('.env.example', '.env'); Artisan::call('key:generate'); } } return App::cryptEnv(); } }
Java
/* * Decompiled with CFR 0_114. * * Could not load the following classes: * com.stimulsoft.base.drawing.StiBrush * com.stimulsoft.base.drawing.StiColor * com.stimulsoft.base.drawing.StiSolidBrush * com.stimulsoft.base.drawing.enums.StiPenStyle * com.stimulsoft.base.serializing.annotations.StiDefaulValue * com.stimulsoft.base.serializing.annotations.StiSerializable */ package com.stimulsoft.report.chart.view.series.radar; import com.stimulsoft.base.drawing.StiBrush; import com.stimulsoft.base.drawing.StiColor; import com.stimulsoft.base.drawing.StiSolidBrush; import com.stimulsoft.base.drawing.enums.StiPenStyle; import com.stimulsoft.base.serializing.annotations.StiDefaulValue; import com.stimulsoft.base.serializing.annotations.StiSerializable; import com.stimulsoft.report.chart.core.series.StiSeriesCoreXF; import com.stimulsoft.report.chart.core.series.radar.StiRadarAreaSeriesCoreXF; import com.stimulsoft.report.chart.interfaces.series.IStiSeries; import com.stimulsoft.report.chart.interfaces.series.radar.IStiRadarAreaSeries; import com.stimulsoft.report.chart.view.areas.radar.StiRadarAreaArea; import com.stimulsoft.report.chart.view.series.radar.StiRadarSeries; public class StiRadarAreaSeries extends StiRadarSeries implements IStiRadarAreaSeries { private StiColor lineColor = StiColor.Black; private StiPenStyle lineStyle = StiPenStyle.Solid; private boolean lighting = true; private float lineWidth = 2.0f; private StiBrush brush = new StiSolidBrush(StiColor.Gainsboro); @StiSerializable public StiColor getLineColor() { return this.lineColor; } public void setLineColor(StiColor stiColor) { this.lineColor = stiColor; } @StiDefaulValue(value="Solid") @StiSerializable public StiPenStyle getLineStyle() { return this.lineStyle; } public void setLineStyle(StiPenStyle stiPenStyle) { this.lineStyle = stiPenStyle; } @StiDefaulValue(value="true") @StiSerializable public boolean getLighting() { return this.lighting; } public void setLighting(boolean bl) { this.lighting = bl; } @StiDefaulValue(value="2.0") @StiSerializable public float getLineWidth() { return this.lineWidth; } public void setLineWidth(float f) { if (f > 0.0f) { this.lineWidth = f; } } @StiSerializable(shortName="bh") public final StiBrush getBrush() { return this.brush; } public final void setBrush(StiBrush stiBrush) { this.brush = stiBrush; } public Class GetDefaultAreaType() { return StiRadarAreaArea.class; } public StiRadarAreaSeries() { this.setCore(new StiRadarAreaSeriesCoreXF(this)); } }
Java
/* Copyright (C) 2011-2017 Michael Goffioul This file is part of Octave. Octave 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. Octave 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 Octave; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. */ #if ! defined (octave_PushButtonControl_h) #define octave_PushButtonControl_h 1 #include "ButtonControl.h" class QPushButton; namespace QtHandles { class PushButtonControl : public ButtonControl { public: PushButtonControl (const graphics_object& go, QPushButton* btn); ~PushButtonControl (void); static PushButtonControl* create (const graphics_object& go); protected: void update (int pId); }; } #endif
Java
package com.base.engine.math; public class Vector2f { private float x, y; public Vector2f(float x, float y) { this.x = x; this.y = y; } public Vector2f normalized() { float len = length(); float x_ = x / len; float y_ = y / len; return new Vector2f(x_, y_); } public float length() { return (float)Math.sqrt(x * x + y * y); } public Vector2f add(Vector2f r) { return new Vector2f(x + r.getX(), y + r.getY()); } public Vector2f add(float r) { return new Vector2f(x + r, y + r); } public Vector2f sub(Vector2f r) { return new Vector2f(x - r.getX(), y - r.getY()); } public Vector2f sub(float r) { return new Vector2f(x - r, y - r); } public Vector2f mul(Vector2f r) { return new Vector2f(x * r.getX(), y * r.getY()); } public Vector2f mul(float r) { return new Vector2f(x * r, y * r); } public Vector2f div(Vector2f r) { return new Vector2f(x / r.getX(), y / r.getY()); } public Vector2f div(float r) { return new Vector2f(x / r, y / r); } public Vector2f abs() { return new Vector2f(Math.abs(x), Math.abs(y)); } @Override public String toString() { return "(" + x + ", " + y + ")"; } public float getX() { return this.x; } public void setX(float x) { this.x = x; } public float getY() { return this.y; } public void setY(float y) { this.y = y; } }
Java
/* * Twidere - Twitter client for Android * * Copyright (C) 2012 Mariotaku Lee <mariotaku.lee@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mariotaku.twidere.util; import java.io.File; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Environment; public final class EnvironmentAccessor { public static File getExternalCacheDir(final Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) return GetExternalCacheDirAccessorFroyo.getExternalCacheDir(context); final File ext_storage_dir = Environment.getExternalStorageDirectory(); if (ext_storage_dir != null && ext_storage_dir.isDirectory()) { final String ext_cache_path = ext_storage_dir.getAbsolutePath() + "/Android/data/" + context.getPackageName() + "/cache/"; final File ext_cache_dir = new File(ext_cache_path); if (ext_cache_dir.isDirectory() || ext_cache_dir.mkdirs()) return ext_cache_dir; } return null; } @TargetApi(Build.VERSION_CODES.FROYO) private static class GetExternalCacheDirAccessorFroyo { @TargetApi(Build.VERSION_CODES.FROYO) private static File getExternalCacheDir(final Context context) { return context.getExternalCacheDir(); } } }
Java
#include "toString.h" vector<string> splitString(string s, char c) { stringstream ss(s); string token; vector<string> res; while (std::getline(ss, token, c)) res.push_back(token); return res; } string toString(string s) { return s; } string toString(bool b) { stringstream ss; ss << b; return ss.str(); } string toString(int i) { stringstream ss; ss << i; return ss.str(); } string toString(size_t i) { stringstream ss; ss << i; return ss.str(); } string toString(unsigned int i) { stringstream ss; ss << i; return ss.str(); } string toString(float f) { stringstream ss; ss << f; return ss.str(); } string toString(double f) { stringstream ss; ss << f; return ss.str(); } string toString(OSG::Vec2f v) { stringstream ss; ss << v[0] << " " << v[1]; return ss.str(); } string toString(OSG::Pnt3f v) { return toString(OSG::Vec3f(v)); } string toString(OSG::Vec3f v) { stringstream ss; ss << v[0] << " " << v[1] << " " << v[2]; return ss.str(); } string toString(OSG::Vec4f v) { stringstream ss; ss << v[0] << " " << v[1] << " " << v[2] << " " << v[3]; return ss.str(); } string toString(OSG::Vec3i v) { stringstream ss; ss << v[0] << " " << v[1] << " " << v[2]; return ss.str(); } bool toBool(string s) { stringstream ss; ss << s; bool b; ss >> b; return b; } int toInt(string s) { stringstream ss; ss << s; int i; ss >> i; return i; } float toFloat(string s) { stringstream ss; ss << s; float i; ss >> i; return i; } OSG::Vec2f toVec2f(string s) { OSG::Vec2f v; stringstream ss(s); ss >> v[0]; ss >> v[1]; return v; } OSG::Vec3f toVec3f(string s) { OSG::Vec3f v; stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; return v; } OSG::Vec4f toVec4f(string s) { OSG::Vec4f v; stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; ss >> v[3]; return v; } OSG::Pnt3f toPnt3f(string s) { OSG::Pnt3f v; stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; return v; } OSG::Vec3i toVec3i(string s) { OSG::Vec3i v; stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; return v; } void toValue(string s, string& s2) { s2 = s; } void toValue(string s, bool& b) { stringstream ss(s); ss >> b; } void toValue(string s, int& i) { stringstream ss(s); ss >> i; } void toValue(string s, float& f) { stringstream ss(s); ss >> f; } void toValue(string s, OSG::Vec2f& v) { stringstream ss(s); ss >> v[0]; ss >> v[1]; } void toValue(string s, OSG::Vec3f& v) { stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; } void toValue(string s, OSG::Vec4f& v) { stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; ss >> v[3]; } void toValue(string s, OSG::Vec3i& v) { stringstream ss(s); ss >> v[0]; ss >> v[1]; ss >> v[2]; }
Java
<!DOCTYPE html><html><head><link rel="canonical" href="http://raph.es/blog/2011/06/mapping-network-drives-for-teamcity-build-agents/"/><meta http-equiv="content-type" content="text/html; charset=utf-8" /><meta http-equiv="refresh" content="0;url=http://raph.es/blog/2011/06/mapping-network-drives-for-teamcity-build-agents/" /></head></html>
Java
<?php class NivelSni extends AppModel { var $name = 'NivelSni'; var $displayField = 'nombre'; var $validate = array( 'nombre' => array( 'minlength' => array( 'rule' => array('minlength', 1), 'message' => 'Valor muy pequeño.', 'allowEmpty' => false ), ), 'descripcion' => array( 'minlength' => array( 'rule' => array('minlength',1), 'message' => 'Ingrese una descripción mas detallada.', 'allowEmpty' => false ), ), ); var $hasMany = array( 'DatosProfesionales' => array( 'className' => 'DatosProfesionales', 'foreignKey' => 'nivel_sni_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ) ); }
Java
''' Copyright 2015 This file is part of Orbach. Orbach 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. Orbach 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 Orbach. If not, see <http://www.gnu.org/licenses/>. ''' from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from orbach.core import views router = DefaultRouter() router.register(r'galleries', views.GalleryViewSet) router.register(r'image_files', views.ImageFileViewSet) router.register(r'users', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), ]
Java
public class Silver extends Piece { public Silver(int owner) { super(owner); setSymbol("S"); setType("Silver"); } public boolean canMove(Square from, Square to, Board b) { if(promoted) { //Gold movement code if((Math.abs(from.getR() - to.getR()) <= 1 && (Math.abs(from.getC() - to.getC()) <= 1))) { if(owner == 1) { //If Piece is moving backwards check for diagonal if(from.getR() - to.getR() == 1) { if(from.getC() != to.getC()) { return false; } } } else if(owner == 2) { //If Piece is moving backwards check for diagonal if(from.getR() - to.getR() == -1) { if(from.getC() != to.getC()) { return false; } } } if(to.getPiece() != null) { if(from.getPiece().getOwner() == to.getPiece().getOwner()) { return false; } } return true; } return false; } if((Math.abs(from.getR() - to.getR()) <= 1 && (Math.abs(from.getC() - to.getC()) <= 1))) { if(owner == 1) { //If Piece is moving backwards p1 if(from.getR() - to.getR() == 1) { if(from.getC() == to.getC()) { return false; } } } else if(owner == 2) { //If Piece is moving backwards p2 if(from.getR() - to.getR() == -1) { if(from.getC() == to.getC()) { return false; } } } //moving sideways if(from.getR() == to.getR()) { return false; } if(to.getPiece() != null) { if(from.getPiece().getOwner() == to.getPiece().getOwner()) { return false; } } return true; } return false; } }
Java
/* * This file is part of the OTHERobjects Content Management System. * * Copyright 2007-2009 OTHER works Limited. * * OTHERobjects 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. * * OTHERobjects 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 OTHERobjects. If not, see <http://www.gnu.org/licenses/>. */ package org.otherobjects.cms.tools; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import javax.annotation.Resource; import org.otherobjects.cms.model.User; import org.otherobjects.cms.model.UserDao; import org.otherobjects.cms.views.Tool; import org.springframework.stereotype.Component; /** * Generates URL to Gravatar images based on user email address. * * <p>For more info on Gravatars see <a href="http://en.gravatar.com/">http://en.gravatar.com/</a>. Details of * the algorithm are available at <a href="http://en.gravatar.com/site/implement/url">http://en.gravatar.com/site/implement/url</a>. * * @author rich */ @Component @Tool public class GravatarTool { private static final String GRAVATAR_SERVER = "http://www.gravatar.com/avatar/"; private static final String GRAVATAR_SECURE_SERVER = "https://secure.gravatar.com/avatar/"; @Resource protected UserDao userDao; /** * Generates url of Gravatar image for provided user. Username must be valid. * * @param username the username for the required user * @param size width in pixels of required image * @return the url to the image */ public String getUrl(String username, int size, boolean ssl) { return getUrl(username, size, null, ssl); } /** * Generates url of Gravatar image for provided user. Username must be valid. * If the user does not have a Gravatar image then the provided placeholder image url * is returned. * * @param username the username for the required user * @param size width in pixels of required image * @param placeholder the url of image to use when no Gravatar is available * @return the url to the image */ public String getUrl(String username, int size, String placeholder, boolean ssl) { User user = (User) userDao.loadUserByUsername(username); return getUrlForEmail(user.getEmail(), size, null, ssl); } /** * Generates url of Gravatar image for provided user. The email address does not * need to be for a user in OTHERobjects. * * If the user does not have a Gravatar image then the provided placeholder image url * is returned (provide a null placeholder to use the default Gravatar one). * * @param email the email address for the required user * @param size width in pixels of required image * @param placeholder the url of image to use when no Gravatar is available * @param ssl whether or not to get an image from a secure Gravatar url * @return the url to the image */ public String getUrlForEmail(String email, int size, String placeholder, boolean ssl) { StringBuffer url = new StringBuffer(ssl ? GRAVATAR_SECURE_SERVER : GRAVATAR_SERVER); // Add image name url.append(md5Hex(email)); url.append(".jpg"); // Add options StringBuffer options = new StringBuffer(); if (size > 0) { options.append("s=" + size); } try { if (placeholder != null) { if (options.length() > 0) { options.append("&"); } options.append("d=" + URLEncoder.encode(placeholder, "UTF-8")); } } catch (UnsupportedEncodingException e) { // Ignore -- UTF-8 must be supported } if (options.length() > 0) { url.append("?" + options.toString()); } return url.toString(); } public String getUrlForEmail(String email, int size, String placeholder) { return getUrlForEmail(email, size, placeholder, false); } private static String hex(byte[] array) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } private static String md5Hex(String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return hex(md.digest(message.getBytes("CP1252"))); } catch (Exception e) { // Ignore } return null; } }
Java
package com.baobaotao.transaction.nestcall; public class BaseService { }
Java
import kivy kivy.require('1.9.1') from kivy.uix.popup import Popup from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.metrics import dp from kivy.app import Builder from kivy.properties import StringProperty, ObjectProperty from kivy.clock import Clock from kivy.metrics import sp from kivy.metrics import dp from iconbutton import IconButton __all__ = ('alertPopup, confirmPopup, okPopup, editor_popup') Builder.load_string(''' <ConfirmPopup>: cols:1 Label: text: root.text GridLayout: cols: 2 size_hint_y: None height: '44sp' spacing: '5sp' IconButton: text: u'\uf00c' on_press: root.dispatch('on_answer', True) IconButton: text: u'\uf00d' color: ColorScheme.get_primary() on_release: root.dispatch('on_answer', False) <OkPopup>: cols:1 Label: text: root.text GridLayout: cols: 2 size_hint_y: None height: '44sp' spacing: '5sp' IconButton: text: u'\uf00c' on_press: root.dispatch('on_answer', True) <EditorPopup>: id: editor_popup cols:1 BoxLayout: id: content GridLayout: id: buttons cols: 2 size_hint_y: None height: '44sp' spacing: '5sp' IconButton: text: u'\uf00c' on_press: root.dispatch('on_answer', True) IconButton: text: u'\uf00d' color: ColorScheme.get_primary() on_release: root.dispatch('on_answer', False) ''') def alertPopup(title, msg): popup = Popup(title = title, content=Label(text = msg), size_hint=(None, None), size=(dp(600), dp(200))) popup.open() def confirmPopup(title, msg, answerCallback): content = ConfirmPopup(text=msg) content.bind(on_answer=answerCallback) popup = Popup(title=title, content=content, size_hint=(None, None), size=(dp(600),dp(200)), auto_dismiss= False) popup.open() return popup class ConfirmPopup(GridLayout): text = StringProperty() def __init__(self,**kwargs): self.register_event_type('on_answer') super(ConfirmPopup,self).__init__(**kwargs) def on_answer(self, *args): pass def editor_popup(title, content, answerCallback): content = EditorPopup(content=content) content.bind(on_answer=answerCallback) popup = Popup(title=title, content=content, size_hint=(0.7, 0.8), auto_dismiss= False, title_size=sp(18)) popup.open() return popup class EditorPopup(GridLayout): content = ObjectProperty(None) def __init__(self,**kwargs): self.register_event_type('on_answer') super(EditorPopup,self).__init__(**kwargs) def on_content(self, instance, value): Clock.schedule_once(lambda dt: self.ids.content.add_widget(value)) def on_answer(self, *args): pass def okPopup(title, msg, answerCallback): content = OkPopup(text=msg) content.bind(on_ok=answerCallback) popup = Popup(title=title, content=content, size_hint=(None, None), size=(dp(600),dp(200)), auto_dismiss= False) popup.open() return popup class OkPopup(GridLayout): text = StringProperty() def __init__(self,**kwargs): self.register_event_type('on_ok') super(OkPopup,self).__init__(**kwargs) def on_ok(self, *args): pass
Java
class CheckBase(object): """ Base class for checks. """ hooks = [] # pylint: disable=W0105 """Git hooks to which this class applies. A list of strings.""" def execute(self, hook): """ Executes the check. :param hook: The name of the hook being run. :type hook: :class:`str` :returns: ``True`` if the check passed, ``False`` if not. :rtype: :class:`bool` """ pass
Java
<?php /* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2009 Regis Houssin <regis.houssin@capnetworks.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * \file htdocs/product/stock/index.php * \ingroup stock * \brief Home page of stock area */ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; $langs->load("stocks"); // Security check $result=restrictedArea($user,'stock'); /* * View */ $help_url='EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks'; llxHeader("",$langs->trans("Stocks"),$help_url); print_fiche_titre($langs->trans("StocksArea")); //print '<table border="0" width="100%" class="notopnoleftnoright">'; //print '<tr><td valign="top" width="30%" class="notopnoleft">'; print '<div class="fichecenter"><div class="fichethirdleft">'; /* * Zone recherche entrepot */ print '<form method="post" action="'.DOL_URL_ROOT.'/product/stock/liste.php">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<table class="noborder nohover" width="100%">'; print "<tr class=\"liste_titre\">"; print '<td colspan="3">'.$langs->trans("Search").'</td></tr>'; print "<tr ".$bc[false]."><td>"; print $langs->trans("Ref").':</td><td><input class="flat" type="text" size="18" name="sref"></td><td rowspan="2"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td></tr>'; print "<tr ".$bc[false]."><td>".$langs->trans("Other").':</td><td><input type="text" name="sall" class="flat" size="18"></td>'; print "</table></form><br>"; $sql = "SELECT e.label, e.rowid, e.statut"; $sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e"; $sql.= " WHERE e.statut in (0,1)"; $sql.= " AND e.entity = ".$conf->entity; $sql.= $db->order('e.statut','DESC'); $sql.= $db->plimit(15, 0); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); $i = 0; print '<table class="noborder" width="100%">'; print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Warehouses").'</td></tr>'; if ($num) { $entrepot=new Entrepot($db); $var=True; while ($i < $num) { $objp = $db->fetch_object($result); $var=!$var; print "<tr $bc[$var]>"; print "<td><a href=\"fiche.php?id=$objp->rowid\">".img_object($langs->trans("ShowStock"),"stock")." ".$objp->label."</a></td>\n"; print '<td align="right">'.$entrepot->LibStatut($objp->statut,5).'</td>'; print "</tr>\n"; $i++; } $db->free($result); } print "</table>"; } else { dol_print_error($db); } //print '</td><td valign="top" width="70%" class="notopnoleftnoright">'; print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; // Last movements $max=10; $sql = "SELECT p.rowid, p.label as produit,"; $sql.= " e.label as stock, e.rowid as entrepot_id,"; $sql.= " m.value, m.datem"; $sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e"; $sql.= ", ".MAIN_DB_PREFIX."stock_mouvement as m"; $sql.= ", ".MAIN_DB_PREFIX."product as p"; $sql.= " WHERE m.fk_product = p.rowid"; $sql.= " AND m.fk_entrepot = e.rowid"; $sql.= " AND e.entity = ".$conf->entity; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql.= " AND p.fk_product_type = 0"; $sql.= $db->order("datem","DESC"); $sql.= $db->plimit($max,0); dol_syslog("Index:list stock movements sql=".$sql, LOG_DEBUG); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); print '<table class="noborder" width="100%">'; print "<tr class=\"liste_titre\">"; print '<td>'.$langs->trans("LastMovements",min($num,$max)).'</td>'; print '<td>'.$langs->trans("Product").'</td>'; print '<td>'.$langs->trans("Warehouse").'</td>'; print '<td align="right"><a href="'.DOL_URL_ROOT.'/product/stock/mouvement.php">'.$langs->trans("FullList").'</a></td>'; print "</tr>\n"; $var=True; $i=0; while ($i < min($num,$max)) { $objp = $db->fetch_object($resql); $var=!$var; print "<tr $bc[$var]>"; print '<td>'.dol_print_date($db->jdate($objp->datem),'dayhour').'</td>'; print "<td><a href=\"../fiche.php?id=$objp->rowid\">"; print img_object($langs->trans("ShowProduct"),"product").' '.$objp->produit; print "</a></td>\n"; print '<td><a href="fiche.php?id='.$objp->entrepot_id.'">'; print img_object($langs->trans("ShowWarehouse"),"stock").' '.$objp->stock; print "</a></td>\n"; print '<td align="right">'; if ($objp->value > 0) print '+'; print $objp->value.'</td>'; print "</tr>\n"; $i++; } $db->free($resql); print "</table>"; } //print '</td></tr></table>'; print '</div></div></div>'; llxFooter(); $db->close(); ?>
Java
<?php require_once ('getConnection.php'); $stmt = $connect -> stmt_init(); $query = "SELECT c_token FROM t_course WHERE c_id = ?"; if (!($stmt -> prepare($query))) { echo "Prepare failed: " . $connect -> errno . $connect -> error; } if (!($stmt -> bind_param("d", $_POST["course"]))) { echo "Bind failed: " . $connect -> errno . $connect -> error; } if (!$stmt -> execute()) { echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error; } if (!($result = $stmt -> get_result())) { echo "Result failed: (" . $connect -> errno . ") " . $connect -> error; } while ($row = $result -> fetch_array(MYSQLI_NUM)) { $course_token = $row[0]; } $stmt -> close(); $stmt = $connect -> stmt_init(); $query = "SELECT p_token FROM t_prof WHERE p_id = ?"; if (!($stmt -> prepare($query))) { echo "Prepare failed: " . $connect -> errno . $connect -> error; } if (!($stmt -> bind_param("d", $_POST['prof']))) { echo "Bind failed: " . $connect -> errno . $connect -> error; } if (!$stmt -> execute()) { echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error; } if (!($result = $stmt -> get_result())) { echo "Result failed: (" . $connect -> errno . ") " . $connect -> error; } while ($row = $result -> fetch_array(MYSQLI_NUM)) { $prof_token = $row[0]; } $stmt -> close(); for ($i = 1; $i <= $_POST['count_tan']; $i++) { do { $stmt = $connect -> stmt_init(); $query = "SELECT t_tan FROM t_tan"; if (!($stmt -> prepare($query))) { echo "Prepare failed: " . $connect -> errno . $connect -> error; } if (!$stmt -> execute()) { echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error; } if (!($result = $stmt -> get_result())) { echo "Result failed: (" . $connect -> errno . ") " . $connect -> error; } while ($row = $result -> fetch_array(MYSQLI_NUM)) { $generated_tans[] = $row[0]; } $stmt -> close(); $tan_pruef = generate($prof_token, $course_token); if (!empty($generated_tans)) { $pruef = in_array($tan_pruef, $generated_tans); } else { $pruef = false; } } while ($pruef); $tan[] = $tan_pruef; } echo "<h1>generated TANs</h1>"; echo "\n"; foreach ($tan as $t) { $stmt = $connect -> stmt_init(); $query = "INSERT into t_tan(t_course, t_prof,t_tan) VALUES(?,?,?)"; if (!($stmt -> prepare($query))) { echo "Prepare failed: " . $connect -> errno . $connect -> error; } if (!($stmt -> bind_param("dds", $_POST['course'], $_POST['prof'], $t))) { echo "Bind failed: " . $connect -> errno . $connect -> error; } if (!$stmt -> execute()) { echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error; } $stmt -> close(); echo '<p>' . $t . '</p>'; echo "\n"; } unset($_POST); echo '<a href="admin_tan.html"><img src="../images/buttons/button_back.jpg" alt="back" id="button" width = 300 height = 150/></a>'; echo "\n"; mysqli_close($connect); function generate($token1, $token2) { $token = rand(100000, 999999); $TAN = $token1 . $token . $token2; return $TAN; }; ?>
Java
/* This project 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. Deviation 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 Deviation. If not, see <http://www.gnu.org/licenses/>. */ #define OVERRIDE_PLACEMENT #include "common.h" #include "pages.h" #include "gui/gui.h" #include "config/model.h" #include "config/ini.h" #include <stdlib.h> enum { LABELNUM_X = 0, LABELNUM_WIDTH = 16, LABEL_X = 17, LABEL_WIDTH = 0, }; #include "../128x64x1/model_loadsave.c"
Java
/* Copyright (C) 2013 Jason Gowan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.gowan.plugin; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jface.viewers.IStructuredSelection; public class SelectionToICompilationUnitList implements List<ICompilationUnit> { private List<ICompilationUnit> list; public SelectionToICompilationUnitList(IStructuredSelection selection){ List<ICompilationUnit> localList = new ArrayList<ICompilationUnit>(); List<Object> selectionList = selection.toList(); for (Object object : selectionList) { localList.addAll( delegate(object) ); } this.list = localList; } protected List<ICompilationUnit> delegate(Object selected){ List<ICompilationUnit> compilationUnits = new ArrayList<ICompilationUnit>(); if( selected instanceof ICompilationUnit ){ compilationUnits.add((ICompilationUnit)selected); }else if ( selected instanceof IPackageFragment){ compilationUnits.addAll(get((IPackageFragment)selected)); }else if( selected instanceof IPackageFragmentRoot){ compilationUnits.addAll(get((IPackageFragmentRoot)selected)); }else if( selected instanceof IJavaProject){ compilationUnits.addAll(get((IJavaProject)selected)); } return compilationUnits; } protected List<ICompilationUnit> get(IJavaProject selected) { List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); IPackageFragmentRoot[] packageRoots; try { packageRoots = selected.getAllPackageFragmentRoots(); for(int i=0; i<packageRoots.length; i++){ result.addAll(get(packageRoots[i])); } } catch (JavaModelException e) { e.printStackTrace(); } return result; } protected List<ICompilationUnit> get(IPackageFragment frag){ List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); try { result = Arrays.asList(frag.getCompilationUnits()); } catch (JavaModelException e) { e.printStackTrace(); } return result; } protected List<ICompilationUnit> get(IPackageFragmentRoot root){ List<ICompilationUnit> result = new ArrayList<ICompilationUnit>(); try { for (IJavaElement frag : Arrays.asList(root.getChildren())) { if( frag instanceof IPackageFragment ){ result.addAll(get((IPackageFragment) frag)); } } } catch (JavaModelException e) { e.printStackTrace(); } return result; } @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public boolean contains(Object o) { return list.contains(o); } @Override public Iterator<ICompilationUnit> iterator() { return list.iterator(); } @Override public Object[] toArray() { return list.toArray(); } @Override public <T> T[] toArray(T[] a) { return list.toArray(a); } @Override public boolean add(ICompilationUnit e) { return list.add(e); } @Override public boolean remove(Object o) { return list.remove(o); } @Override public boolean containsAll(Collection<?> c) { return list.contains(c); } @Override public boolean addAll(Collection<? extends ICompilationUnit> c) { return list.addAll(c); } @Override public boolean addAll(int index, Collection<? extends ICompilationUnit> c) { return list.addAll(c); } @Override public boolean removeAll(Collection<?> c) { return list.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return list.retainAll(c); } @Override public void clear() { list.clear(); } @Override public ICompilationUnit get(int index) { return list.get(index); } @Override public ICompilationUnit set(int index, ICompilationUnit element) { return list.set(index, element); } @Override public void add(int index, ICompilationUnit element) { list.add(index, element); } @Override public ICompilationUnit remove(int index) { return list.remove(index); } @Override public int indexOf(Object o) { return list.indexOf(o); } @Override public int lastIndexOf(Object o) { return list.lastIndexOf(o); } @Override public ListIterator<ICompilationUnit> listIterator() { return list.listIterator(); } @Override public ListIterator<ICompilationUnit> listIterator(int index) { return list.listIterator(index); } @Override public List<ICompilationUnit> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } }
Java
<?php namespace DB; final class mPDO { private $connection = null; private $statement = null; public function __construct($hostname, $username, $password, $database, $port = '3306') { try { $dsn = "mysql:host={$hostname};port={$port};dbname={$database};charset=UTF8"; $options = array( \PDO::ATTR_PERSISTENT => true, \PDO::ATTR_TIMEOUT => 15, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ); $this->connection = new \PDO($dsn, $username, $password, $options); } catch (\PDOException $e) { throw new \Exception('Failed to connect to database. Reason: \'' . $e->getMessage() . '\''); } $this->connection->exec("SET NAMES 'utf8'"); $this->connection->exec("SET CHARACTER SET utf8"); $this->connection->exec("SET CHARACTER_SET_CONNECTION=utf8"); $this->connection->exec("SET SQL_MODE = ''"); $this->rowCount = 0; } public function prepare($sql) { $this->statement = $this->connection->prepare($sql); } public function bindParam($parameter, $variable, $data_type = \PDO::PARAM_STR, $length = 0) { if ($length) { $this->statement->bindParam($parameter, $variable, $data_type, $length); } else { $this->statement->bindParam($parameter, $variable, $data_type); } } public function execute() { try { if ($this->statement && $this->statement->execute()) { $data = array(); while ($row = $this->statement->fetch(\PDO::FETCH_ASSOC)) { $data[] = $row; } $result = new \stdClass(); $result->row = (isset($data[0])) ? $data[0] : array(); $result->rows = $data; $result->num_rows = $this->statement->rowCount(); } } catch (\PDOException $e) { throw new \Exception('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode()); } } public function query($sql, $params = array()) { $this->statement = $this->connection->prepare($sql); $result = false; try { if ($this->statement && $this->statement->execute($params)) { $data = array(); $this->rowCount = $this->statement->rowCount(); if ($this->rowCount > 0) { try { $data = $this->statement->fetchAll(\PDO::FETCH_ASSOC); } catch (\Exception $ex) { } } // free up resources $this->statement->closeCursor(); $this->statement = null; $result = new \stdClass(); $result->row = (isset($data[0]) ? $data[0] : array()); $result->rows = $data; $result->num_rows = $this->rowCount; } } catch (\PDOException $e) { throw new \Exception('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode() . ' <br />' . $sql); } if ($result) { return $result; } else { $result = new \stdClass(); $result->row = array(); $result->rows = array(); $result->num_rows = 0; return $result; } } public function escape($value) { return str_replace(array( "\\", "\0", "\n", "\r", "\x1a", "'", '"' ), array( "\\\\", "\\0", "\\n", "\\r", "\Z", "\'", '\"' ), $value); } public function countAffected() { if ($this->statement) { return $this->statement->rowCount(); } else { return $this->rowCount; } } public function getLastId() { return $this->connection->lastInsertId(); } public function isConnected() { if ($this->connection) { return true; } else { return false; } } public function __destruct() { $this->connection = null; } }
Java
/** * copyright * Inubit AG * Schoeneberger Ufer 89 * 10785 Berlin * Germany */ package com.inubit.research.textToProcess.textModel; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Rectangle2D; import net.frapu.code.visualization.ProcessNode; import net.frapu.code.visualization.ProcessUtils; import net.frapu.code.visualization.ProcessUtils.Orientation; /** * @author ff * */ public class WordNode extends ProcessNode { /** * */ public static final Color HIGHLIGHT_COLOR = new Color(255,255,224); private static final int PADDING = 3; //pixels /** * */ public WordNode(String word) { setText(word.replaceAll("\\/", "/")); setBackground(Color.WHITE); } /** * */ public WordNode() { // TODO Auto-generated constructor stub } @Override protected Shape getOutlineShape() { Rectangle2D outline = new Rectangle2D.Float(getPos().x - (getSize().width / 2), getPos().y - (getSize().height / 2), getSize().width, getSize().height); return outline; } @Override protected void paintInternal(Graphics g) { Graphics2D _g = (Graphics2D) g; Shape _s = getOutlineShape(); if(isSelected()) { _g.setColor(WordNode.HIGHLIGHT_COLOR); }else { _g.setColor(getBackground()); _g.setStroke(ProcessUtils.defaultStroke); } _g.fill(_s); _g.setColor(Color.LIGHT_GRAY); _g.draw(_s); _g.setColor(Color.BLACK); if(getText() == null) { ProcessUtils.drawText(_g, getPos().x, getPos().y, getSize().width, "Word", Orientation.CENTER); }else { ProcessUtils.drawText(_g, getPos().x, getPos().y, getSize().width, getText(), Orientation.CENTER); } } @Override public void setSize(int w, int h) { return; } @Override public void setPos(int x, int y) { return; } /** * @return */ public String getWord() { return getText(); } /** * @param stringBounds */ public void setBounds(Rectangle2D b) { super.setSize((int)b.getWidth() + 2* PADDING, (int)b.getHeight() + 2* PADDING); } /** * @param _wx * @param y */ public void setLocation(int x, int y) { super.setPos(x,y); } @Override public String toString() { return "WordNode ("+getText()+")"; } }
Java
<?php /* * $result->groups * $result->auditories * $result->lectors * $result->calendars */ ?> <h1>Додати календар</h1> <div class="uk-margin"> <div class="uk-form"> <?php if(mysqli_num_rows($result->groups) > 0){ echo '<select>'; while($row = mysqli_fetch_assoc($result->groups)) { echo '<option value="'.$row->id.'">'.$row->name.'</option>'; } echo '</select>'; } ?> <?php if(mysqli_num_rows($result->auditories) > 0){ echo '<select>'; while($row = mysqli_fetch_assoc($result->auditories)) { echo '<option value="'.$row->id.'">'.$row->name.'</option>'; } echo '</select>'; } ?> <?php if(mysqli_num_rows($result->lectors) > 0){ echo '<select>'; while($row = mysqli_fetch_assoc($result->lectors)) { echo '<option value="'.$row->id.'">'.$row->name.'</option>'; } echo '</select>'; } ?> </div> </div>
Java
<?php /* Scripts and styles options */ /** * Renders the Scripts and styles options section. */ function electric_thop_render_scripts_section(){ echo "<p>" . __('You are not forced to use everything that the theme includes. If you are not going to use a feature (because you don\'t like it or because you prefer a different solution, just uncheck it. You will save some kb to load.','electric') . "</p>" ; echo "<p>" . __('If you use these styles/scripts they will be loaded individually. If you want to boost performance, you can combine them into a single file using a plugin (W3 Total Cache is suggested, but you can use any option or do it manually)','electric') . "</p>" ; } /** * Renders the Icon Fonts checkbox setting field. */ function electric_sfield_use_icon_fonts() { $options = electric_thop_get_options(); ?> <label for="use-icon-fonts" class="description"> <input type="checkbox" name="electric_theme_options[use_icon_fonts]" id="use-icon-fonts" <?php checked('on', $options['use_icon_fonts']); ?> /> <?php _e('Check this if you want to use the icon font.', 'electric'); ?> </label> <p class="description"><?php _e('You can customize the icons uploading the file electric/fonts/fonts/electric.dev.svg to <a href="http://icomoon.io">icomoon.io</a>.', 'electric'); ?></p> <?php } /** * Renders the Google Fonts checkbox setting field. */ function electric_sfield_use_google_fonts() { $options = electric_thop_get_options(); ?> <label for="use-google-fonts" class="description"> <input type="checkbox" name="electric_theme_options[use_google_fonts]" id="use-google-fonts" <?php checked('on', $options['use_google_fonts']); ?> /> <?php _e('Check this if you want to use fonts from Google Web Fonts', 'electric'); ?> </label> <p class="description"><?php _e('Allows you to use fonts from <a href="http://www.google.com/webfonts">Google Web Fonts</a>', 'electric') ?></p> <?php } /** * Renders the Google Fonts Family input setting field. */ function electric_sfield_google_fonts_choice() { $options = electric_thop_get_options(); ?> <input type="text" name="electric_theme_options[google_fonts_choice]" id="google-fonts-choice" value="<?php echo esc_attr($options['google_fonts_choice']); ?>" /> <label class="description" for="google-fonts-choice"><?php _e('Your font family choice', 'electric'); ?></label> <p class="description"><?php _e('If you want to use a different set than the default (Comfortaa + Open Sans):', 'electric') ?></p> <ol class="description"> <li><?php _e('Choose the font(s) you like and click "Use"', 'electric') ?></li> <li><?php _e('Choose the style(s) you want and character set(s) at point 1 and 2', 'electric') ?></li> <li><?php _e('Copy the code at the "Standard" tab at point 3 ', 'electric') ?></li> </ol> <?php } /** * Renders the tooltip checkbox setting field. */ function electric_sfield_use_tooltip_js() { $options = electric_thop_get_options(); ?> <label for="use-tooltip-js" class="description"> <input type="checkbox" name="electric_theme_options[use_tooltip_js]" id="use-tooltip-js" <?php checked('on', $options['use_tooltip_js']); ?> /> <?php _e('Uncheck this if you don\'t want to load the Tooltip script', 'electric'); ?> </label> <p class="description"><?php _e('This script is used to display a tooltip in the menus and in the availability widget. If you don\'t want them, don\'t include the plugin and save some kb', 'electric') ?></p> <p class="description"><?php _e('More info about this tooltip <a href="http://jquerytools.org/demos/tooltip/index.html">here</a>', 'electric') ?></p> <?php }
Java
#ifndef __PROCESSOR_H__ #define __PROCESSOR_H__ #include <gctypes.h> #include "asm.h" #define __stringify(rn) #rn #define ATTRIBUTE_ALIGN(v) __attribute__((aligned(v))) // courtesy of Marcan #define STACK_ALIGN(type, name, cnt, alignment) u8 _al__##name[((sizeof(type)*(cnt)) + (alignment) + (((sizeof(type)*(cnt))%(alignment)) > 0 ? ((alignment) - ((sizeof(type)*(cnt))%(alignment))) : 0))]; \ type *name = (type*)(((u32)(_al__##name)) + ((alignment) - (((u32)(_al__##name))&((alignment)-1)))) #define _sync() asm volatile("sync") #define _nop() asm volatile("nop") #define ppcsync() asm volatile("sc") #define ppchalt() ({ \ asm volatile("sync"); \ while(1) { \ asm volatile("nop"); \ asm volatile("li 3,0"); \ asm volatile("nop"); \ } \ }) #define mfpvr() ({register u32 _rval; \ asm volatile("mfpvr %0" : "=r"(_rval)); _rval;}) #define mfdcr(_rn) ({register u32 _rval; \ asm volatile("mfdcr %0," __stringify(_rn) \ : "=r" (_rval)); _rval;}) #define mtdcr(rn, val) asm volatile("mtdcr " __stringify(rn) ",%0" : : "r" (val)) #define mfmsr() ({register u32 _rval; \ asm volatile("mfmsr %0" : "=r" (_rval)); _rval;}) #define mtmsr(val) asm volatile("mtmsr %0" : : "r" (val)) #define mfdec() ({register u32 _rval; \ asm volatile("mfdec %0" : "=r" (_rval)); _rval;}) #define mtdec(_val) asm volatile("mtdec %0" : : "r" (_val)) #define mfspr(_rn) \ ({ register u32 _rval = 0; \ asm volatile("mfspr %0," __stringify(_rn) \ : "=r" (_rval));\ _rval; \ }) #define mtspr(_rn, _val) asm volatile("mtspr " __stringify(_rn) ",%0" : : "r" (_val)) #define mfwpar() mfspr(WPAR) #define mtwpar(_val) mtspr(WPAR,_val) #define mfmmcr0() mfspr(MMCR0) #define mtmmcr0(_val) mtspr(MMCR0,_val) #define mfmmcr1() mfspr(MMCR1) #define mtmmcr1(_val) mtspr(MMCR1,_val) #define mfpmc1() mfspr(PMC1) #define mtpmc1(_val) mtspr(PMC1,_val) #define mfpmc2() mfspr(PMC2) #define mtpmc2(_val) mtspr(PMC2,_val) #define mfpmc3() mfspr(PMC3) #define mtpmc3(_val) mtspr(PMC3,_val) #define mfpmc4() mfspr(PMC4) #define mtpmc4(_val) mtspr(PMC4,_val) #define mfhid0() mfspr(HID0) #define mthid0(_val) mtspr(HID0,_val) #define mfhid1() mfspr(HID1) #define mthid1(_val) mtspr(HID1,_val) #define mfhid2() mfspr(HID2) #define mthid2(_val) mtspr(HID2,_val) #define mfhid4() mfspr(HID4) #define mthid4(_val) mtspr(HID4,_val) #define __lhbrx(base,index) \ ({ register u16 res; \ __asm__ volatile ("lhbrx %0,%1,%2" : "=r"(res) : "b%"(index), "r"(base) : "memory"); \ res; }) #define __lwbrx(base,index) \ ({ register u32 res; \ __asm__ volatile ("lwbrx %0,%1,%2" : "=r"(res) : "b%"(index), "r"(base) : "memory"); \ res; }) #define __sthbrx(base,index,value) \ __asm__ volatile ("sthbrx %0,%1,%2" : : "r"(value), "b%"(index), "r"(base) : "memory") #define __stwbrx(base,index,value) \ __asm__ volatile ("stwbrx %0,%1,%2" : : "r"(value), "b%"(index), "r"(base) : "memory") #define cntlzw(_val) ({register u32 _rval; \ asm volatile("cntlzw %0, %1" : "=r"((_rval)) : "r"((_val))); _rval;}) #define _CPU_MSR_GET( _msr_value ) \ do { \ _msr_value = 0; \ asm volatile ("mfmsr %0" : "=&r" ((_msr_value)) : "0" ((_msr_value))); \ } while (0) #define _CPU_MSR_SET( _msr_value ) \ { asm volatile ("mtmsr %0" : "=&r" ((_msr_value)) : "0" ((_msr_value))); } #define _CPU_ISR_Enable() \ { register u32 _val = 0; \ __asm__ __volatile__ ( \ "mfmsr %0\n" \ "ori %0,%0,0x8000\n" \ "mtmsr %0" \ : "=&r" ((_val)) : "0" ((_val)) \ ); \ } #define _CPU_ISR_Disable( _isr_cookie ) \ { register u32 _disable_mask = 0; \ _isr_cookie = 0; \ __asm__ __volatile__ ( \ "mfmsr %0\n" \ "rlwinm %1,%0,0,17,15\n" \ "mtmsr %1\n" \ "extrwi %0,%0,1,16" \ : "=&r" ((_isr_cookie)), "=&r" ((_disable_mask)) \ : "0" ((_isr_cookie)), "1" ((_disable_mask)) \ ); \ } #define _CPU_ISR_Restore( _isr_cookie ) \ { register u32 _enable_mask = 0; \ __asm__ __volatile__ ( \ " cmpwi %0,0\n" \ " beq 1f\n" \ " mfmsr %1\n" \ " ori %1,%1,0x8000\n" \ " mtmsr %1\n" \ "1:" \ : "=r"((_isr_cookie)),"=&r" ((_enable_mask)) \ : "0"((_isr_cookie)),"1" ((_enable_mask)) \ ); \ } #define _CPU_ISR_Flash( _isr_cookie ) \ { register u32 _flash_mask = 0; \ __asm__ __volatile__ ( \ " cmpwi %0,0\n" \ " beq 1f\n" \ " mfmsr %1\n" \ " ori %1,%1,0x8000\n" \ " mtmsr %1\n" \ " rlwinm %1,%1,0,17,15\n" \ " mtmsr %1\n" \ "1:" \ : "=r" ((_isr_cookie)), "=&r" ((_flash_mask)) \ : "0" ((_isr_cookie)), "1" ((_flash_mask)) \ ); \ } #define _CPU_FPR_Enable() \ { register u32 _val = 0; \ asm volatile ("mfmsr %0; ori %0,%0,0x2000; mtmsr %0" : \ "=&r" (_val) : "0" (_val));\ } #define _CPU_FPR_Disable() \ { register u32 _val = 0; \ asm volatile ("mfmsr %0; rlwinm %0,%0,0,19,17; mtmsr %0" : \ "=&r" (_val) : "0" (_val));\ } #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ static inline u16 bswap16(u16 val) { u16 tmp = val; return __lhbrx(&tmp,0); } static inline u32 bswap32(u32 val) { u32 tmp = val; return __lwbrx(&tmp,0); } static inline u64 bswap64(u64 val) { union ullc { u64 ull; u32 ul[2]; } outv; u64 tmp = val; outv.ul[0] = __lwbrx(&tmp,4); outv.ul[1] = __lwbrx(&tmp,0); return outv.ull; } // Basic I/O static inline u32 read32(u32 addr) { u32 x; asm volatile("lwz %0,0(%1) ; sync" : "=r"(x) : "b"(0xc0000000 | addr)); return x; } static inline void write32(u32 addr, u32 x) { asm("stw %0,0(%1) ; eieio" : : "r"(x), "b"(0xc0000000 | addr)); } static inline void mask32(u32 addr, u32 clear, u32 set) { write32(addr, (read32(addr)&(~clear)) | set); } static inline u16 read16(u32 addr) { u16 x; asm volatile("lhz %0,0(%1) ; sync" : "=r"(x) : "b"(0xc0000000 | addr)); return x; } static inline void write16(u32 addr, u16 x) { asm("sth %0,0(%1) ; eieio" : : "r"(x), "b"(0xc0000000 | addr)); } static inline u8 read8(u32 addr) { u8 x; asm volatile("lbz %0,0(%1) ; sync" : "=r"(x) : "b"(0xc0000000 | addr)); return x; } static inline void write8(u32 addr, u8 x) { asm("stb %0,0(%1) ; eieio" : : "r"(x), "b"(0xc0000000 | addr)); } static inline void writef32(u32 addr, f32 x) { asm("stfs %0,0(%1) ; eieio" : : "f"(x), "b"(0xc0000000 | addr)); } #ifdef __cplusplus } #endif /* __cplusplus */ #endif
Java
'use strict'; angular.module('ldrWebApp') /** * @name pageSkipper * @param config * @param pages * @type element * @description Skip to page directive * @requires $scope */ .directive('pageSkipper', function () { return { restrict: 'E', templateUrl: 'components/page-skipper/page-skipper.template.html', scope: {'config': '=', 'pages': '='}, controller: function ($scope) { /** * @name pageSkipper#generateArray * @param {Number} start * @param {Number} end * @description generate an array in form {start} to {end} * @returns {Array} */ function generateArray(start, end) { var list = []; for (var i = start; i <= end; i++) { list.push(i); } return list; } /** * @name pageSkipper#skipToPage * @param {Number} item * @description get the desired page * @return {Undefined} */ $scope.skipToPage = function (item) { $scope.config.page = (item === undefined) ? 1 : item; }; $scope.selectedPage = 1; $scope.pagesList = generateArray(1, $scope.pages); } }; });
Java
odoo.define('point_of_sale.DB', function (require) { "use strict"; var core = require('web.core'); var utils = require('web.utils'); /* The PosDB holds reference to data that is either * - static: does not change between pos reloads * - persistent : must stay between reloads ( orders ) */ var PosDB = core.Class.extend({ name: 'openerp_pos_db', //the prefix of the localstorage data limit: 100, // the maximum number of results returned by a search init: function(options){ options = options || {}; this.name = options.name || this.name; this.limit = options.limit || this.limit; if (options.uuid) { this.name = this.name + '_' + options.uuid; } //cache the data in memory to avoid roundtrips to the localstorage this.cache = {}; this.product_by_id = {}; this.product_by_barcode = {}; this.product_by_category_id = {}; this.product_packaging_by_barcode = {}; this.partner_sorted = []; this.partner_by_id = {}; this.partner_by_barcode = {}; this.partner_search_string = ""; this.partner_write_date = null; this.category_by_id = {}; this.root_category_id = 0; this.category_products = {}; this.category_ancestors = {}; this.category_childs = {}; this.category_parent = {}; this.category_search_string = {}; }, /** * sets an uuid to prevent conflict in locally stored data between multiple PoS Configs. By * using the uuid of the config the local storage from other configs will not get effected nor * loaded in sessions that don't belong to them. * * @param {string} uuid Unique identifier of the PoS Config linked to the current session. */ set_uuid: function(uuid){ this.name = this.name + '_' + uuid; }, /* returns the category object from its id. If you pass a list of id as parameters, you get * a list of category objects. */ get_category_by_id: function(categ_id){ if(categ_id instanceof Array){ var list = []; for(var i = 0, len = categ_id.length; i < len; i++){ var cat = this.category_by_id[categ_id[i]]; if(cat){ list.push(cat); }else{ console.error("get_category_by_id: no category has id:",categ_id[i]); } } return list; }else{ return this.category_by_id[categ_id]; } }, /* returns a list of the category's child categories ids, or an empty list * if a category has no childs */ get_category_childs_ids: function(categ_id){ return this.category_childs[categ_id] || []; }, /* returns a list of all ancestors (parent, grand-parent, etc) categories ids * starting from the root category to the direct parent */ get_category_ancestors_ids: function(categ_id){ return this.category_ancestors[categ_id] || []; }, /* returns the parent category's id of a category, or the root_category_id if no parent. * the root category is parent of itself. */ get_category_parent_id: function(categ_id){ return this.category_parent[categ_id] || this.root_category_id; }, /* adds categories definitions to the database. categories is a list of categories objects as * returned by the openerp server. Categories must be inserted before the products or the * product/ categories association may (will) not work properly */ add_categories: function(categories){ var self = this; if(!this.category_by_id[this.root_category_id]){ this.category_by_id[this.root_category_id] = { id : this.root_category_id, name : 'Root', }; } categories.forEach(function(cat){ self.category_by_id[cat.id] = cat; }); categories.forEach(function(cat){ var parent_id = cat.parent_id[0]; if(!(parent_id && self.category_by_id[parent_id])){ parent_id = self.root_category_id; } self.category_parent[cat.id] = parent_id; if(!self.category_childs[parent_id]){ self.category_childs[parent_id] = []; } self.category_childs[parent_id].push(cat.id); }); function make_ancestors(cat_id, ancestors){ self.category_ancestors[cat_id] = ancestors; ancestors = ancestors.slice(0); ancestors.push(cat_id); var childs = self.category_childs[cat_id] || []; for(var i=0, len = childs.length; i < len; i++){ make_ancestors(childs[i], ancestors); } } make_ancestors(this.root_category_id, []); }, category_contains: function(categ_id, product_id) { var product = this.product_by_id[product_id]; if (product) { var cid = product.pos_categ_id[0]; while (cid && cid !== categ_id){ cid = this.category_parent[cid]; } return !!cid; } return false; }, /* loads a record store from the database. returns default if nothing is found */ load: function(store,deft){ if(this.cache[store] !== undefined){ return this.cache[store]; } var data = localStorage[this.name + '_' + store]; if(data !== undefined && data !== ""){ data = JSON.parse(data); this.cache[store] = data; return data; }else{ return deft; } }, /* saves a record store to the database */ save: function(store,data){ localStorage[this.name + '_' + store] = JSON.stringify(data); this.cache[store] = data; }, _product_search_string: function(product){ var str = product.display_name; if (product.barcode) { str += '|' + product.barcode; } if (product.default_code) { str += '|' + product.default_code; } if (product.description) { str += '|' + product.description; } if (product.description_sale) { str += '|' + product.description_sale; } str = product.id + ':' + str.replace(/:/g,'') + '\n'; return str; }, add_products: function(products){ var stored_categories = this.product_by_category_id; if(!products instanceof Array){ products = [products]; } for(var i = 0, len = products.length; i < len; i++){ var product = products[i]; if (product.id in this.product_by_id) continue; if (product.available_in_pos){ var search_string = utils.unaccent(this._product_search_string(product)); var categ_id = product.pos_categ_id ? product.pos_categ_id[0] : this.root_category_id; product.product_tmpl_id = product.product_tmpl_id[0]; if(!stored_categories[categ_id]){ stored_categories[categ_id] = []; } stored_categories[categ_id].push(product.id); if(this.category_search_string[categ_id] === undefined){ this.category_search_string[categ_id] = ''; } this.category_search_string[categ_id] += search_string; var ancestors = this.get_category_ancestors_ids(categ_id) || []; for(var j = 0, jlen = ancestors.length; j < jlen; j++){ var ancestor = ancestors[j]; if(! stored_categories[ancestor]){ stored_categories[ancestor] = []; } stored_categories[ancestor].push(product.id); if( this.category_search_string[ancestor] === undefined){ this.category_search_string[ancestor] = ''; } this.category_search_string[ancestor] += search_string; } } this.product_by_id[product.id] = product; if(product.barcode){ this.product_by_barcode[product.barcode] = product; } } }, add_packagings: function(product_packagings){ var self = this; _.map(product_packagings, function (product_packaging) { if (_.find(self.product_by_id, {'id': product_packaging.product_id[0]})) { self.product_packaging_by_barcode[product_packaging.barcode] = product_packaging; } }); }, _partner_search_string: function(partner){ var str = partner.name || ''; if(partner.barcode){ str += '|' + partner.barcode; } if(partner.address){ str += '|' + partner.address; } if(partner.phone){ str += '|' + partner.phone.split(' ').join(''); } if(partner.mobile){ str += '|' + partner.mobile.split(' ').join(''); } if(partner.email){ str += '|' + partner.email; } if(partner.vat){ str += '|' + partner.vat; } str = '' + partner.id + ':' + str.replace(':', '').replace(/\n/g, ' ') + '\n'; return str; }, add_partners: function(partners){ var updated_count = 0; var new_write_date = ''; var partner; for(var i = 0, len = partners.length; i < len; i++){ partner = partners[i]; var local_partner_date = (this.partner_write_date || '').replace(/^(\d{4}-\d{2}-\d{2}) ((\d{2}:?){3})$/, '$1T$2Z'); var dist_partner_date = (partner.write_date || '').replace(/^(\d{4}-\d{2}-\d{2}) ((\d{2}:?){3})$/, '$1T$2Z'); if ( this.partner_write_date && this.partner_by_id[partner.id] && new Date(local_partner_date).getTime() + 1000 >= new Date(dist_partner_date).getTime() ) { // FIXME: The write_date is stored with milisec precision in the database // but the dates we get back are only precise to the second. This means when // you read partners modified strictly after time X, you get back partners that were // modified X - 1 sec ago. continue; } else if ( new_write_date < partner.write_date ) { new_write_date = partner.write_date; } if (!this.partner_by_id[partner.id]) { this.partner_sorted.push(partner.id); } this.partner_by_id[partner.id] = partner; updated_count += 1; } this.partner_write_date = new_write_date || this.partner_write_date; if (updated_count) { // If there were updates, we need to completely // rebuild the search string and the barcode indexing this.partner_search_string = ""; this.partner_by_barcode = {}; for (var id in this.partner_by_id) { partner = this.partner_by_id[id]; if(partner.barcode){ this.partner_by_barcode[partner.barcode] = partner; } partner.address = (partner.street ? partner.street + ', ': '') + (partner.zip ? partner.zip + ', ': '') + (partner.city ? partner.city + ', ': '') + (partner.state_id ? partner.state_id[1] + ', ': '') + (partner.country_id ? partner.country_id[1]: ''); this.partner_search_string += this._partner_search_string(partner); } this.partner_search_string = utils.unaccent(this.partner_search_string); } return updated_count; }, get_partner_write_date: function(){ return this.partner_write_date || "1970-01-01 00:00:00"; }, get_partner_by_id: function(id){ return this.partner_by_id[id]; }, get_partner_by_barcode: function(barcode){ return this.partner_by_barcode[barcode]; }, get_partners_sorted: function(max_count){ max_count = max_count ? Math.min(this.partner_sorted.length, max_count) : this.partner_sorted.length; var partners = []; for (var i = 0; i < max_count; i++) { partners.push(this.partner_by_id[this.partner_sorted[i]]); } return partners; }, search_partner: function(query){ try { query = query.replace(/[\[\]\(\)\+\*\?\.\-\!\&\^\$\|\~\_\{\}\:\,\\\/]/g,'.'); query = query.replace(/ /g,'.+'); var re = RegExp("([0-9]+):.*?"+utils.unaccent(query),"gi"); }catch(e){ return []; } var results = []; for(var i = 0; i < this.limit; i++){ var r = re.exec(this.partner_search_string); if(r){ var id = Number(r[1]); results.push(this.get_partner_by_id(id)); }else{ break; } } return results; }, /* removes all the data from the database. TODO : being able to selectively remove data */ clear: function(){ for(var i = 0, len = arguments.length; i < len; i++){ localStorage.removeItem(this.name + '_' + arguments[i]); } }, /* this internal methods returns the count of properties in an object. */ _count_props : function(obj){ var count = 0; for(var prop in obj){ if(obj.hasOwnProperty(prop)){ count++; } } return count; }, get_product_by_id: function(id){ return this.product_by_id[id]; }, get_product_by_barcode: function(barcode){ if(this.product_by_barcode[barcode]){ return this.product_by_barcode[barcode]; } else if (this.product_packaging_by_barcode[barcode]) { return this.product_by_id[this.product_packaging_by_barcode[barcode].product_id[0]]; } return undefined; }, get_product_by_category: function(category_id){ var product_ids = this.product_by_category_id[category_id]; var list = []; if (product_ids) { for (var i = 0, len = Math.min(product_ids.length, this.limit); i < len; i++) { const product = this.product_by_id[product_ids[i]]; if (!(product.active && product.available_in_pos)) continue; list.push(product); } } return list; }, /* returns a list of products with : * - a category that is or is a child of category_id, * - a name, package or barcode containing the query (case insensitive) */ search_product_in_category: function(category_id, query){ try { query = query.replace(/[\[\]\(\)\+\*\?\.\-\!\&\^\$\|\~\_\{\}\:\,\\\/]/g,'.'); query = query.replace(/ /g,'.+'); var re = RegExp("([0-9]+):.*?"+utils.unaccent(query),"gi"); }catch(e){ return []; } var results = []; for(var i = 0; i < this.limit; i++){ var r = re.exec(this.category_search_string[category_id]); if(r){ var id = Number(r[1]); const product = this.get_product_by_id(id); if (!(product.active && product.available_in_pos)) continue; results.push(product); }else{ break; } } return results; }, /* from a product id, and a list of category ids, returns * true if the product belongs to one of the provided category * or one of its child categories. */ is_product_in_category: function(category_ids, product_id) { if (!(category_ids instanceof Array)) { category_ids = [category_ids]; } var cat = this.get_product_by_id(product_id).pos_categ_id[0]; while (cat) { for (var i = 0; i < category_ids.length; i++) { if (cat == category_ids[i]) { // The == is important, ids may be strings return true; } } cat = this.get_category_parent_id(cat); } return false; }, /* paid orders */ add_order: function(order){ var order_id = order.uid; var orders = this.load('orders',[]); // if the order was already stored, we overwrite its data for(var i = 0, len = orders.length; i < len; i++){ if(orders[i].id === order_id){ orders[i].data = order; this.save('orders',orders); return order_id; } } // Only necessary when we store a new, validated order. Orders // that where already stored should already have been removed. this.remove_unpaid_order(order); orders.push({id: order_id, data: order}); this.save('orders',orders); return order_id; }, remove_order: function(order_id){ var orders = this.load('orders',[]); orders = _.filter(orders, function(order){ return order.id !== order_id; }); this.save('orders',orders); }, remove_all_orders: function(){ this.save('orders',[]); }, get_orders: function(){ return this.load('orders',[]); }, get_order: function(order_id){ var orders = this.get_orders(); for(var i = 0, len = orders.length; i < len; i++){ if(orders[i].id === order_id){ return orders[i]; } } return undefined; }, /* working orders */ save_unpaid_order: function(order){ var order_id = order.uid; var orders = this.load('unpaid_orders',[]); var serialized = order.export_as_JSON(); for (var i = 0; i < orders.length; i++) { if (orders[i].id === order_id){ orders[i].data = serialized; this.save('unpaid_orders',orders); return order_id; } } orders.push({id: order_id, data: serialized}); this.save('unpaid_orders',orders); return order_id; }, remove_unpaid_order: function(order){ var orders = this.load('unpaid_orders',[]); orders = _.filter(orders, function(o){ return o.id !== order.uid; }); this.save('unpaid_orders',orders); }, remove_all_unpaid_orders: function(){ this.save('unpaid_orders',[]); }, get_unpaid_orders: function(){ var saved = this.load('unpaid_orders',[]); var orders = []; for (var i = 0; i < saved.length; i++) { orders.push(saved[i].data); } return orders; }, /** * Return the orders with requested ids if they are unpaid. * @param {array<number>} ids order_ids. * @return {array<object>} list of orders. */ get_unpaid_orders_to_sync: function(ids){ var saved = this.load('unpaid_orders',[]); var orders = []; saved.forEach(function(o) { if (ids.includes(o.id)){ orders.push(o); } }); return orders; }, /** * Add a given order to the orders to be removed from the server. * * If an order is removed from a table it also has to be removed from the server to prevent it from reapearing * after syncing. This function will add the server_id of the order to a list of orders still to be removed. * @param {object} order object. */ set_order_to_remove_from_server: function(order){ if (order.server_id !== undefined) { var to_remove = this.load('unpaid_orders_to_remove',[]); to_remove.push(order.server_id); this.save('unpaid_orders_to_remove', to_remove); } }, /** * Get a list of server_ids of orders to be removed. * @return {array<number>} list of server_ids. */ get_ids_to_remove_from_server: function(){ return this.load('unpaid_orders_to_remove',[]); }, /** * Remove server_ids from the list of orders to be removed. * @param {array<number>} ids */ set_ids_removed_from_server: function(ids){ var to_remove = this.load('unpaid_orders_to_remove',[]); to_remove = _.filter(to_remove, function(id){ return !ids.includes(id); }); this.save('unpaid_orders_to_remove', to_remove); }, set_cashier: function(cashier) { // Always update if the user is the same as before this.save('cashier', cashier || null); }, get_cashier: function() { return this.load('cashier'); } }); return PosDB; });
Java
<div class="container"> <div class="row jumbotron indexBKGD"> <div class="col-xs-12 col-sm-10 col-sm-offset-1"> <div class="row"> <div class="col-12 col-sm-12 col-lg-12" style="text-align: center;"> <div class="panel panel-default"> <div class="panel-body"> <h2 style="text-align: center;"><strong>Nathaniel Buechler</strong></h2> <h6 style="text-align: center;"><i>Multifaceted Specialist</i></h6> <h6 style="text-align: center;"> <a class="btn btn-default" href="https://github.com/nbuechler"><i class="fa fa-2x fa-github"></i></a> <a class="btn btn-default" href="https://www.linkedin.com/in/nathaniel-buechler"><i class="fa fa-2x fa-linkedin-square"></i></a> <a class="btn btn-default" href="mailto:natebuechler@gmail.com?Subject=Hello%20Nathaniel"><i class="fa fa-2x fa-envelope"></i></a> <a class="btn btn-default" href="/resume/Nathaniel_Buechler-Sr_UX_Engineer.pdf"><i class="fa fa-2x fa-file-text"></i></a> </h6> <hr></hr> <h6 class="well" style="text-align: center;"> <i>Where is my attention?</i><br></br> My talents as a Full-Stack JavaScript Engineer combined with my Python experience allow me to actively experiment with basic ML, AC, NLP, IoT, and microservices to solve real problems. </h6> <h6 style="text-align: center;"> I'm passionate about connecting many different themes with many "lenses" of knowledge. If you would like to learn more about me, below you will see a few different clickable icons to spark your interest about my interests. Please, enjoy my website! </h6> </div> </div> </div> </div> <div class="row"> <div class="col-sm-12 col-lg-5 mobile" style="text-align: center; padding-bottom: 5%; padding-top: 6%;"> <a href="http://nathanielbuechler.com/"><img style="height: 220px; cursor: default;" onclick="alert('You found the secret!!')" src="images/default-hex.png" alt="Nathaniel" /></a> </div> <div class="col-xs-12 mobile" id="roleBarMobile"> <div class="hextopshift"> <a ui-sref="artist"><img class="roleIcon-hex" src="images/web-rdy_icons/artist-hex.png" alt="artist" /></a> <a ui-sref="painter"><img class="roleIcon-hex" src="images/web-rdy_icons/painter-hex.png" alt="painter" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="photographer"><img class="roleIcon-hex" src="images/web-rdy_icons/photographer-hex.png" alt="photographer" /></a> </div> <div class="hextopshift"> <a ui-sref="graphic-designer"><img class="roleIcon-hex" src="images/web-rdy_icons/graphic-designer-hex.png" alt="graphic-designer" /></a> <a ui-sref="sound-designer"><img class="roleIcon-hex" src="images/web-rdy_icons/sound-designer-hex.png" alt="sound-designer" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="musician"><img class="roleIcon-hex" src="images/web-rdy_icons/musician-hex.png" alt="musician" /></a> </div> <div class="hextopshift"> <a ui-sref="journalist"><img class="roleIcon-hex" src="images/web-rdy_icons/journalist-hex.png" alt="journalist" /></a> <a ui-sref="world-historian"><img class="roleIcon-hex" src="images/web-rdy_icons/world-historian-hex.png" alt="world historian" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="political-economist"><img class="roleIcon-hex" src="images/web-rdy_icons/political-economist-hex.png" alt="political economist" /></a> </div> <div class="hextopshift"> <a ui-sref="social-activist"><img class="roleIcon-hex" src="images/web-rdy_icons/social-activist-hex.png" alt="social activist" /></a> <a ui-sref="social-scientist"><img class="roleIcon-hex" src="images/web-rdy_icons/social-scientist-hex.png" alt="social_scientist" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="comparative-institutionalist"><img class="roleIcon-hex" src="images/web-rdy_icons/comparative-institutionalist-hex.png" alt="comparative institutionalist"/></a> </div> <div class="hextopshift"> <a ui-sref="cultural-anthropologist"><img class="roleIcon-hex" src="images/web-rdy_icons/cultural-anthropologist-hex.png" alt="cultural_anthropologist" /></a> <a ui-sref="linguist"><img class="roleIcon-hex" src="images/web-rdy_icons/linguist-hex.png" alt="linguist" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="computer-programmer"><img class="roleIcon-hex" src="images/web-rdy_icons/computer-programmer-hex.png" alt="computer_programmer" /></a> </div> <div class="hextopshift"> <a ui-sref="back-end-developer"><img class="roleIcon-hex" src="images/web-rdy_icons/back-end-developer-hex.png" alt="back-end developer"/></a> <a ui-sref="front-end-developer"><img class="roleIcon-hex" src="images/web-rdy_icons/front-end-developer-hex.png" alt="front-end developer" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="natural-scientist"><img class="roleIcon-hex" src="images/web-rdy_icons/natural-scientist-hex.png" alt="natural_scientist" /></a> </div> <div class="hextopshift"> <a ui-sref="engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/engineer-hex.png" alt="engineer" /></a> <a ui-sref="biologist"><img class="roleIcon-hex" src="images/web-rdy_icons/biologist-hex.png" alt="biologist" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="affective-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/affective-engineer-hex.png" alt="affective-engineer"/></a> </div> <div class="hextopshift"> <a ui-sref="software-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/software-engineer-hex.png" alt="software-engineer" /></a> <a ui-sref="botanist"><img class="roleIcon-hex" src="images/web-rdy_icons/botanist-hex.png" alt="botanist" /></a> </div> <!-- <div class="hextopshift hexrightshift"> <a ui-sref="hardware-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/hardware-engineer-hex.png" alt="hardware-engineer" /></a> <a ui-sref="chemist"><img class="roleIcon-hex" src="images/web-rdy_icons/chemist-hex.png" alt="chemist" /></a> </div> --> </div> <!-- Mobile above, desktop below --> <div class="col-sm-12 col-lg-5 desktop" style="text-align: center; padding-bottom: 5%; padding-top: 6%;"> <a href="http://nathanielbuechler.com/"><img style="height: 320px; cursor: default;" onclick="alert('You found the secret!!')" src="images/default-hex.png" alt="Nathaniel" /></a> </div> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-7 desktop" id="roleBarDesktop"> <div class="hextopshift"> <a ui-sref="artist"><img class="roleIcon-hex" src="images/web-rdy_icons/artist-hex.png" alt="artist" /></a> <a ui-sref="painter"><img class="roleIcon-hex" src="images/web-rdy_icons/painter-hex.png" alt="painter" /></a> <a ui-sref="photographer"><img class="roleIcon-hex" src="images/web-rdy_icons/photographer-hex.png" alt="photographer" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="graphic-designer"><img class="roleIcon-hex" src="images/web-rdy_icons/graphic-designer-hex.png" alt="graphic-designer" /></a> <a ui-sref="sound-designer"><img class="roleIcon-hex" src="images/web-rdy_icons/sound-designer-hex.png" alt="sound-designer" /></a> </div> <div class="hextopshift"> <a ui-sref="musician"><img class="roleIcon-hex" src="images/web-rdy_icons/musician-hex.png" alt="musician" /></a> <a ui-sref="journalist"><img class="roleIcon-hex" src="images/web-rdy_icons/journalist-hex.png" alt="journalist" /></a> <a ui-sref="world-historian"><img class="roleIcon-hex" src="images/web-rdy_icons/world-historian-hex.png" alt="world historian" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="political-economist"><img class="roleIcon-hex" src="images/web-rdy_icons/political-economist-hex.png" alt="political economist" /></a> <a ui-sref="social-activist"><img class="roleIcon-hex" src="images/web-rdy_icons/social-activist-hex.png" alt="social activist" /></a> </div> <div class="hextopshift"> <a ui-sref="social-scientist"><img class="roleIcon-hex" src="images/web-rdy_icons/social-scientist-hex.png" alt="social_scientist" /></a> <a ui-sref="comparative-institutionalist"><img class="roleIcon-hex" src="images/web-rdy_icons/comparative-institutionalist-hex.png" alt="comparative institutionalist"/></a> <a ui-sref="cultural-anthropologist"><img class="roleIcon-hex" src="images/web-rdy_icons/cultural-anthropologist-hex.png" alt="cultural_anthropologist" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="linguist"><img class="roleIcon-hex" src="images/web-rdy_icons/linguist-hex.png" alt="linguist" /></a> <a ui-sref="computer-programmer"><img class="roleIcon-hex" src="images/web-rdy_icons/computer-programmer-hex.png" alt="computer_programmer" /></a> </div> <div class="hextopshift"> <a ui-sref="back-end-developer"><img class="roleIcon-hex" src="images/web-rdy_icons/back-end-developer-hex.png" alt="back-end developer"/></a> <a ui-sref="front-end-developer"><img class="roleIcon-hex" src="images/web-rdy_icons/front-end-developer-hex.png" alt="front-end developer" /></a> <a ui-sref="natural-scientist"><img class="roleIcon-hex" src="images/web-rdy_icons/natural-scientist-hex.png" alt="natural_scientist" /></a> </div> <div class="hextopshift hexrightshift"> <a ui-sref="engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/engineer-hex.png" alt="engineer" /></a> <a ui-sref="biologist"><img class="roleIcon-hex" src="images/web-rdy_icons/biologist-hex.png" alt="biologist" /></a> </div> <div class="hextopshift"> <a ui-sref="affective-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/affective-engineer-hex.png" alt="affective-engineer"/></a> <a ui-sref="software-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/software-engineer-hex.png" alt="software-engineer" /></a> <a ui-sref="botanist"><img class="roleIcon-hex" src="images/web-rdy_icons/botanist-hex.png" alt="botanist" /></a> </div> <!-- <div class="hextopshift hexrightshift"> <a ui-sref="hardware-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/hardware-engineer-hex.png" alt="hardware-engineer" /></a> <a ui-sref="chemist"><img class="roleIcon-hex" src="images/web-rdy_icons/chemist-hex.png" alt="chemist" /></a> </div> --> </div> </div> <br></br> <div class="row"> <div class="col-12 col-sm-12 col-lg-12" style="text-align: center;"> <div class="panel panel-default"> <div class="panel-body"> <h2 style="text-align: center;"><strong>>30 Seconds</strong></h2> <h6 style="text-align: center;"><i>About Me</i></h6> <hr></hr> <h6 style="text-align: center;"> A dream job would be working on trying to solve societal and institutional problems. For more information on that, consider reading <i><a style="color: #A1A1A1;" href="https://books.google.com/books/about/Philosophy_and_the_Social_Problem_Schola.html?id=pw48rgEACAAJ&hl=en">'Philosophy and the Social Problem'</a></i> by Will Durant. It's available for free on Google Books. If your familiar with some of these ideas, then you might become more aware of some of my personal motivations. If you aren't familiar, I can summarize my goals by stating that I'm interested in working on software that improves the emotional intelligence of people. </h6> <hr></hr> <h6 style="text-align: center;"> In a technology sense, my latest intrigue is focused on the field of <i><a style="color: #A1A1A1;" href="https://en.wikipedia.org/wiki/Affective_computing">Affective Computing.</a></i> I'm learning Tensorflow and other machine learning tools as a way to get a working knowledge. Additionally, I am interested in more conventional programming languages, but my main expertise is actually in JavaScript. I have been considering the next wave of JavaScript, and React.js is where I am focusing my time. </h6> <hr></hr> <h6 style="text-align: center;"> As for other technologies, I prefer using Flask and configuration based frameworks, but I am additionally looking into polyglot programming and polyglot persistence as it pertains to microservices. If you want more information on that, Google <i><a style="color: #A1A1A1;" href="http://lmgtfy.com/?q=Netflix+microservices">'Netflix microservices'</a></i> and the first few articles do a good job of explaining the concept. I try to continue learning tools and tech, so as time goes on, my interests will change. </h6> <hr></hr> <h6 style="text-align: center;"> Lastly, I had some experience watching others program with iOS and Android, and I'm continuing to pay attention to the intersection of mobile and cloud computing. This is one area which is very nebulous to me, but I would be interested in discovering more about the 'Internet of Things' ecosystem. I've made a plan to begin experimenting with a Raspberry Pi, but haven't been able to do much with it. </h6> <hr></hr> <h6> <h5 class="well" style="text-align: center;"><strong>Still Interested?</strong> <a class="btn btn-md btn-default" href="/resume/Nathaniel_Buechler-Sr_UX_Engineer.pdf" style="color: white; margin: 10px;">Download my Résumé</a></h5> </h6> </div> </div> </div> </div> </div><!--/span--> </div><!--/row--> </div><!--/container--> <div class="row jumbotron mainBKGD"> <div class="container"> <div class="col-xs-12"> <div class="panel panel-default"> <div class="panel-heading">Role Perspective</div> <div class="panel-body"> <div id="roleFocus" class="well col-lg-3 col-md-12 col-sm-12" style="text-align: center; height: 420px"> <div style='margin-top: 80px'><span><img height="150" src="images/default-hex.png" alt="Nathaniel" /><br><h6 class="well">Multifaceted Specialist</h6></div> </div> <div class="col-lg-9 col-md-12 col-sm-12 content canvasHolderBkgd"> <div id="roleChart" style="font: white; text-align: center;"></div> </div> </div> </div> </div> </div> </div> <div ng-controller="homeController"> <div ui-view="artist"></div> <div ui-view="social-scientist"></div> <div ui-view="computer-programmer"></div> <div ui-view="natural-scientist"></div> <div ui-view="engineer"></div> </div> <div class="row jumbotron mainBKGD"> <div class="container"> <div class="col-xs-12"> <div class="panel panel-default"> <div class="panel-heading">Skill Perspective</div> <div class="panel-body"> <div id="skillFocus" class="well col-lg-3 col-md-12 col-sm-12" style="text-align: center; height: 460px"> <div style='margin-top: 80px'><span><img height="150" src="images/default-hex.png" alt="Nathaniel" /><br><h6 class="well">Multifaceted Specialist</h6></div> </div> <div class="col-lg-9 col-md-12 col-sm-12 content canvasHolderBkgd"> <div id="navSunBurst" style="font: white; text-align: center;"></div> </div> </div> </div> </div> </div> </div> <div class="row jumbotron mainBKGD"> <div class="container"> <div class="col-xs-12"> <div class="row"> <div class="col-12 col-sm-12 col-lg-12" style="text-align: center;"> <div class="panel panel-default"> <div class="panel-body"> <h2 style="text-align: center;"><strong>Software Documentation</strong></h2> <h6 style="text-align: center;"><i>Project Notes from Nathaniel Buechler</i></h6> <hr></hr> <div class="well"> <div class="row"> <h6>Maybe one day, someone else will want to use some of my code, and I want to make it easier for them. Also, I want to make it easier for myself to use as a reference in the distant future.</h6> <h6>Over 25 repositories are show on this site, but some of the projects more documented due to their importance and complexity. My hope is that this documentation makes it easier for you to understand the projects that I have created.</h6> </div> </div> <hr></hr> <h5 class="well" style="text-align: center;"> <a href="http://nathanielbuechler.io/" class="btn btn-default"> <i class="fa fa-book fa-2x" aria-hidden="true" style="vertical-align: middle;"></i> <span style="display: inline-block; vertical-align: middle;"> View the project documentation </span> </a> </h5> </div> </div> </div> </div> </div><!--/span--> </div><!--/row--> </div><!--/container--> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-10 col-sm-offset-1"> <div class="row"> <div class="col-12 col-sm-12 col-lg-12" style="text-align: center;"> <div class="panel panel-default"> <div class="panel-body"> <h2 style="text-align: center;"><strong>Recap</strong></h2> <h6 style="text-align: center;"><i>Roles of this Multifaceted Specialist</i></h6> <hr></hr> <div class="well"> <div class="row"> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="affective-engineer">Affective Engineer</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="artist">Artist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="back-end-developer">Back-End Developer</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="biologist">Biologist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="botanist">Botanist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="comparative-institutionalist">Comparative Institutionalist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="computer-programmer">Computer Programmer</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="cultural-anthropologist">Cultural Anthropologist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="engineer">Engineer</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="front-end-developer">Front-End Developer</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="graphic-designer">Graphic Designer</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="journalist">Journalist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="linguist">Linguist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="musician">Musician</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="natural-scientist">Natural Scientist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="painter">Painter</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="photographer">Photographer</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="political-economist">Political Economist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="social-activist">Social Activist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="social-scientist">Social Scientist</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="software-engineer">Software Engineer</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="sound-designer">Sound Designer</a> <a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="world-historian">World Historian</a> </div> </div> <hr></hr> <h5 class="well" style="text-align: center;"> <a class="btn btn-default" href="https://github.com/nbuechler"><i class="fa fa-2x fa-github"></i></a> <a class="btn btn-default" href="https://www.linkedin.com/in/nathaniel-buechler-87a29226"><i class="fa fa-2x fa-linkedin-square"></i></a> <a class="btn btn-default" href="mailto:natebuechler@gmail.com?Subject=Hello%20Nathaniel"><i class="fa fa-2x fa-envelope"></i></a> <a class="btn btn-default" href="/resume/Nathaniel_Buechler-Sr_Software_Engineer.pdf"><i class="fa fa-2x fa-file-text"></i></a> </h5> </div> </div> </div> </div> </div><!--/span--> </div><!--/row--> </div><!--/container--> <!--d3, application JavaScript Files--> <script type="text/javascript" src="js/d3-charts/roleTimeline.js"></script> <script type="text/javascript" src="js/d3-charts/skillBurst.js"></script>
Java
.PHONY: all help build run builddocker rundocker kill rm-image rm clean enter logs all: help help: @echo "" @echo "-- Help Menu" @echo "" This is merely a base image for usage read the README file @echo "" 1. make run - build and run docker container @echo "" 2. make build - build docker container @echo "" 3. make clean - kill and remove docker container @echo "" 4. make enter - execute an interactive bash in docker container @echo "" 3. make logs - follow the logs of docker container build: NAME TAG builddocker # run a plain container run: TZ PORT LOGDIR DATADIR rundocker prod: run temp: init init: DATADIR TZ PORT config pull initdocker auto: init next initdocker: $(eval TMP := $(shell mktemp -d --suffix=DOCKERTMP)) $(eval NAME := $(shell cat NAME)) $(eval PORT := $(shell cat PORT)) $(eval TAG := $(shell cat TAG)) $(eval DOMOTICZ_OPTS := $(shell cat DOMOTICZ_OPTS)) $(eval TZ := $(shell cat TZ)) chmod 777 $(TMP) @docker run --name=$(NAME)-init \ --cidfile="cid" \ -e TZ=$(TZ) \ -e DOMOTICZ_OPTS=$(DOMOTICZ_OPTS) \ -v $(TMP):/tmp \ --device=/dev/ttyUSB0 \ --device=/dev/pts/0 \ --privileged \ --device=/dev/ttyUSB0 \ --device=/dev/pts/0 \ -d \ -p $(PORT):8080 \ -t $(TAG) debugdocker: $(eval TMP := $(shell mktemp -d --suffix=DOCKERTMP)) $(eval NAME := $(shell cat NAME)) $(eval PORT := $(shell cat PORT)) $(eval TAG := $(shell cat TAG)) $(eval DOMOTICZ_OPTS := $(shell cat DOMOTICZ_OPTS)) $(eval TZ := $(shell cat TZ)) chmod 777 $(TMP) @docker run --name=$(NAME)-init \ --cidfile="cid" \ -e TZ=$(TZ) \ -e DOMOTICZ_OPTS=$(DOMOTICZ_OPTS) \ -v $(TMP):/tmp \ --privileged \ --device=/dev/ttyUSB0 \ --device=/dev/pts/0 \ -d \ -p $(PORT):8080 \ -t $(TAG) /bin/bash rundocker: $(eval TMP := $(shell mktemp -d --suffix=DOCKERTMP)) $(eval NAME := $(shell cat NAME)) $(eval TZ := $(shell cat TZ)) $(eval DOMOTICZ_OPTS := $(shell cat DOMOTICZ_OPTS)) $(eval DATADIR := $(shell cat DATADIR)) $(eval LOGDIR := $(shell cat LOGDIR)) $(eval PORT := $(shell cat PORT)) $(eval TAG := $(shell cat TAG)) chmod 777 $(TMP) @docker run --name=$(NAME) \ --cidfile="cid" \ -v $(TMP):/tmp \ -e TZ=$(TZ) \ -e DOMOTICZ_OPTS=$(DOMOTICZ_OPTS) \ --privileged \ -d \ --device=/dev/ttyUSB0 \ --device=/dev/pts/0 \ -p $(PORT):8080 \ -v $(DATADIR)/config:/config \ -v $(LOGDIR)/log:/log \ -t $(TAG) builddocker: docker build -t `cat TAG` . kill: -@docker kill `cat cid` rm-image: -@docker rm `cat cid` -@rm cid rm: kill rm-image clean: rm enter: docker exec -i -t `cat cid` /bin/bash logs: docker logs -f `cat cid` rmall: rm config: datadir/domoticz.db datadir/domoticz.db: tar jxvf domoticz.db.tz2 mkdir -p datadir mv domoticz.db datadir/ TZ: @while [ -z "$$TZ" ]; do \ read -r -p "Enter the timezone you wish to associate with this container [America/Denver]: " TZ; echo "$$TZ">>TZ; cat TZ; \ done ; DOMOTICZ_OPTS: @while [ -z "$$DOMOTICZ_OPTS" ]; do \ read -r -p "Enter the domoticz options you wish to associate with this container: " DOMOTICZ_OPTS; echo "$$DOMOTICZ_OPTS">>DOMOTICZ_OPTS; cat DOMOTICZ_OPTS; \ done ; PORT: @while [ -z "$$PORT" ]; do \ read -r -p "Enter the port you wish to associate with this container [PORT]: " PORT; echo "$$PORT">>PORT; cat PORT; \ done ; LOGDIR: @while [ -z "$$LOGDIR" ]; do \ read -r -p "Enter the datadir you wish to associate with this container (i.e. /exports/mkdomoticz) [LOGDIR]: " LOGDIR; echo "$$LOGDIR">>LOGDIR; cat LOGDIR; \ done ; DATADIR: @while [ -z "$$DATADIR" ]; do \ read -r -p "Enter the datadir you wish to associate with this container (i.e. /exports/mkdomoticz) [DATADIR]: " DATADIR; echo "$$DATADIR">>DATADIR; cat DATADIR; \ done ; REGISTRY: @while [ -z "$$REGISTRY" ]; do \ read -r -p "Enter the registry you wish to associate with this container [REGISTRY]: " REGISTRY; echo "$$REGISTRY">>REGISTRY; cat REGISTRY; \ done ; REGISTRY_PORT: @while [ -z "$$REGISTRY_PORT" ]; do \ read -r -p "Enter the port of the registry you wish to associate with this container, usually 5000 [REGISTRY_PORT]: " REGISTRY_PORT; echo "$$REGISTRY_PORT">>REGISTRY_PORT; cat REGISTRY_PORT; \ done ; grab: DATADIR GRABDATADIR GRABDATADIR: -@mkdir -p datadir/domoticz docker cp `cat cid`:/config - |sudo tar -C datadir/ -pxf - push: TAG REGISTRY REGISTRY_PORT $(eval TAG := $(shell cat TAG)) $(eval REGISTRY := $(shell cat REGISTRY)) $(eval REGISTRY_PORT := $(shell cat REGISTRY_PORT)) docker tag $(TAG) $(REGISTRY):$(REGISTRY_PORT)/$(TAG) docker push $(REGISTRY):$(REGISTRY_PORT)/$(TAG) pull: docker pull `cat TAG` next: waitforport grab clean place run place: $(eval DATADIR := $(shell cat DATADIR)) mkdir -p $(DATADIR) sudo mv datadir $(DATADIR)/ echo "$(DATADIR)/datadir" > DATADIR sync @echo "Moved datadir to $(DATADIR)" waitforport: $(eval PORT := $(shell cat PORT)) @echo "Waiting for port to become available" @while ! curl --output /dev/null --silent --head --fail http://127.0.0.1:$(PORT); do sleep 10 && echo -n .; done; @echo "check port $(PORT), it appears that now it is up!"
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" type="text/css" href="assets/style.css"></link> </head> <body> <div class="content"> <h1><a href="page_rationale.html"><span class="mute">wi</span><span class="bright">doh</span></a></h1> <ul class="menu"> <li><a href="list_persons.html">People</a></li> <li><a href="list_projects.html">Projects</a></li> <li><a href="page_rationale.html">Rationale</a></li> <li><a href="page_index.html">About</a></li> </ul> <div class="page"> <div> <h2>2008-11-17</h2> <p> <p><a href="project_bjax.html">BJax - javascript for managers</a></p> <p><a href="project_geodevice.html">Geographical Tracking Device</a></p> <p><a href="project_hillsearch.html">Paragliding Hill Gazetteer</a></p> <p><a href="project_trainclock.html">Train Clock</a></p> </p> </div> <div> <h2>2008-11-10</h2> <p> <p><a href="project_foleyfeet.html">Foley Footsteps</a></p> <p><a href="project_onepixelwebcam.html">One Pixel Webcam</a></p> <p><a href="project_semaphoresms.html">Semaphore to SMS Gateway</a></p> <p><a href="project_trainmodelling.html">Statistical Distributions of Train Delays</a></p> </p> </div> </div> <div class="menu"> <div> <h2>Widoh Projects</h2> <p>Whatever the technology project, the more playful the better. No business cases required.</p> </div> </div> <div class="footer"> CSS copyright: © 2008, Cefn Hoile, inspired by Adam Particka's orangray. </div> </div> </body> </html>
Java
// // 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/>. // // // BSRunKeeperLoginSegue.h // BeSport Mobile // // Created by François-Xavier Thomas on 5/18/12. // Copyright (c) 2012 BeSport. All rights reserved. // #import "BSLoginSegue.h" @interface BSRunKeeperLoginSegue : BSLoginSegue @end
Java
var searchData= [ ['a',['a',['../structRREP.html#abe45cd7d5c14dc356ecab531b2176242',1,'RREP']]], ['ack_5ftimer',['ack_timer',['../structrt__table.html#a4b5c6baab186ae8733b48cf2d5172852',1,'rt_table']]], ['active',['active',['../classNA__NesgLog.html#a0ce1b63fe991dc4304cb30d703aadcd6',1,'NA_NesgLog']]], ['active_5froute_5ftimeout',['active_route_timeout',['../classNA__AODVUU.html#ae7108fca58788a241d1319cde34a7dde',1,'NA_AODVUU::active_route_timeout()'],['../main_8c.html#a1b01d3369a884952b1b133647b6f8972',1,'active_route_timeout():&#160;main.c'],['../NA__nl_8c.html#a1b01d3369a884952b1b133647b6f8972',1,'active_route_timeout():&#160;main.c']]], ['aodvnl',['aodvnl',['../NA__nl_8c.html#a1932512e3a0f6559a876627efde22cff',1,'NA_nl.c']]], ['aodvrttablemap',['aodvRtTableMap',['../classNA__AODVUU.html#ae0d6f9d77438a52f9c571a77e2151a48',1,'NA_AODVUU']]], ['aodvtimermap',['aodvTimerMap',['../classNA__AODVUU.html#ab1245e4e87b93a0416f42606da162489',1,'NA_AODVUU']]], ['attacktype',['attackType',['../classNA__Attack.html#ac4cf8ddfd1c47f348f057f49382f5323',1,'NA_Attack']]], ['avhopcount',['avHopCount',['../classNA__UDPBasicBurst.html#a8c9180eebb4ba6a44ab2ca3bc5052426',1,'NA_UDPBasicBurst']]] ];
Java
/* This file is part of My Nes * * A Nintendo Entertainment System / Family Computer (Nes/Famicom) * Emulator written in C#. * * Copyright © Ala Ibrahim Hadid 2009 - 2014 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace MyNes.Core { class VRC6PulseSoundChannel { private int dutyForm; private int dutyStep; private bool enabled = true; private bool mode = false; public byte output; private byte volume; private int freqTimer; private int frequency; private int cycles; public void HardReset() { dutyForm = 0; dutyStep = 0xF; enabled = true; mode = false; output = 0; } public void Write0(ref byte data) { mode = (data & 0x80) == 0x80; dutyForm = ((data & 0x70) >> 4); volume = (byte)(data & 0xF); } public void Write1(ref byte data) { frequency = (frequency & 0x0F00) | data; } public void Write2(ref byte data) { frequency = (frequency & 0x00FF) | ((data & 0xF) << 8); enabled = (data & 0x80) == 0x80; } public void ClockSingle() { if (--cycles <= 0) { cycles = (frequency << 1) + 2; if (enabled) { if (mode) output = volume; else { dutyStep--; if (dutyStep < 0) dutyStep = 0xF; if (dutyStep <= dutyForm) output = volume; else output = 0; } } else output = 0; } } /// <summary> /// Save state /// </summary> /// <param name="stream">The stream that should be used to write data</param> public void SaveState(System.IO.BinaryWriter stream) { stream.Write(dutyForm); stream.Write(dutyStep); stream.Write(enabled); stream.Write(mode); stream.Write(output); stream.Write(volume); stream.Write(freqTimer); stream.Write(frequency); stream.Write(cycles); } /// <summary> /// Load state /// </summary> /// <param name="stream">The stream that should be used to read data</param> public void LoadState(System.IO.BinaryReader stream) { dutyForm = stream.ReadInt32(); dutyStep = stream.ReadInt32(); enabled = stream.ReadBoolean(); mode = stream.ReadBoolean(); output = stream.ReadByte(); volume = stream.ReadByte(); freqTimer = stream.ReadInt32(); frequency = stream.ReadInt32(); cycles = stream.ReadInt32(); } } }
Java
# - Find the OpenGL Extension Wrangler Library (GLEW) # This module defines the following variables: # GLEW_INCLUDE_DIRS - include directories for GLEW # GLEW_LIBRARIES - libraries to link against GLEW # GLEW_FOUND - true if GLEW has been found and can be used #============================================================================= # Copyright 2012 Benjamin Eikel # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) find_path(GLEW_INCLUDE_DIR GL/glew.h) find_library(GLEW_LIBRARY NAMES GLEW glew32 glew glew32s PATH_SUFFIXES lib64) set(GLEW_INCLUDE_DIRS ${GLEW_INCLUDE_DIR}) set(GLEW_LIBRARIES ${GLEW_LIBRARY}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GLEW GLEW_INCLUDE_DIR GLEW_LIBRARY) mark_as_advanced(GLEW_INCLUDE_DIR GLEW_LIBRARY)
Java
/* * Neon, a roguelike engine. * Copyright (C) 2017-2018 - Maarten Driesen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package neon.editor.ui; import java.io.IOException; import java.util.logging.Logger; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.Window; import neon.common.files.NeonFileSystem; import neon.common.resources.ResourceManager; import neon.editor.LoadEvent; import neon.editor.controllers.CreatureHandler; import neon.editor.controllers.ItemHandler; import neon.editor.controllers.MapHandler; import neon.editor.controllers.MenuHandler; import neon.editor.controllers.TerrainHandler; import neon.editor.resource.CEditor; /** * The {@code UserInterface} takes care of most ui-related editor functionality. * * @author mdriesen * */ public final class UserInterface { private static final Logger logger = Logger.getGlobal(); private final CreatureHandler creatureHandler; private final MapHandler mapHandler; private final MenuHandler menuHandler; private final ItemHandler itemHandler; private final TerrainHandler terrainHandler; private Stage stage; private Scene scene; /** * Initializes the {@code UserInterface}. * * @param files * @param resources * @param bus * @param config */ public UserInterface(NeonFileSystem files, ResourceManager resources, EventBus bus, CEditor config) { // separate handlers for all the different ui elements menuHandler = new MenuHandler(resources, bus, this); bus.register(menuHandler); mapHandler = new MapHandler(resources, bus, config); bus.register(mapHandler); creatureHandler = new CreatureHandler(resources, bus); bus.register(creatureHandler); itemHandler = new ItemHandler(resources, bus); bus.register(itemHandler); terrainHandler = new TerrainHandler(resources, bus); bus.register(terrainHandler); // load the user interface FXMLLoader loader = new FXMLLoader(getClass().getResource("Editor.fxml")); loader.setControllerFactory(this::getController); try { scene = new Scene(loader.load()); scene.getStylesheets().add(getClass().getResource("editor.css").toExternalForm()); } catch (IOException e) { logger.severe("failed to load editor ui: " + e.getMessage()); } } /** * Returns the correct controller for a JavaFX node. * * @param type * @return */ private Object getController(Class<?> type) { if(type.equals(MenuHandler.class)) { return menuHandler; } else if (type.equals(MapHandler.class)) { return mapHandler; } else if (type.equals(CreatureHandler.class)) { return creatureHandler; } else if (type.equals(ItemHandler.class)) { return itemHandler; } else if (type.equals(TerrainHandler.class)) { return terrainHandler; } else { throw new IllegalArgumentException("No controller found for class " + type + "!"); } } /** * * @return the main window of the editor */ public Window getWindow() { return stage; } /** * Shows the main window on screen. * * @param stage */ public void start(Stage stage) { this.stage = stage; stage.setTitle("The Neon Roguelike Editor"); stage.setScene(scene); stage.setWidth(1440); stage.setMinWidth(800); stage.setHeight(720); stage.setMinHeight(600); stage.show(); stage.centerOnScreen(); stage.setOnCloseRequest(event -> System.exit(0)); } /** * Sets the title of the main window. * * @param event */ @Subscribe private void onModuleLoad(LoadEvent event) { stage.setTitle("The Neon Roguelike Editor - " + event.id); } /** * Checks if any resources are still opened and should be saved. This * method should be called when saving a module or exiting the editor. */ public void saveResources() { // check if any maps are still opened mapHandler.saveMaps(); } }
Java
// This file has been generated by the GUI designer. Do not modify. public partial class WinCryptoSec2Config { private global::Gtk.VBox vbox2; private global::Gtk.Button btnDatabase; private global::Gtk.Button btnFtp; private global::Gtk.Button btnString; private global::Gtk.Button btnXml; private global::Gtk.Button btnCancel; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget WinCryptoSec2Config this.Name = "WinCryptoSec2Config"; this.Title = global::Mono.Unix.Catalog.GetString ("InCrtyptoSec2 Modes"); this.Icon = global::Gdk.Pixbuf.LoadFromResource ("InGtkCryptoSec2.icons.keys_16x16.png"); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); this.Modal = true; // Internal child WinCryptoSec2Config.VBox global::Gtk.VBox w1 = this.VBox; w1.Name = "dialog1_VBox"; w1.BorderWidth = ((uint)(2)); // Container child dialog1_VBox.Gtk.Box+BoxChild this.vbox2 = new global::Gtk.VBox (); this.vbox2.Name = "vbox2"; this.vbox2.Spacing = 10; this.vbox2.BorderWidth = ((uint)(5)); // Container child vbox2.Gtk.Box+BoxChild this.btnDatabase = new global::Gtk.Button (); this.btnDatabase.TooltipMarkup = "InCryptoSec2 module for Database security."; this.btnDatabase.CanFocus = true; this.btnDatabase.Name = "btnDatabase"; this.btnDatabase.UseUnderline = true; this.btnDatabase.Label = global::Mono.Unix.Catalog.GetString ("Database"); global::Gtk.Image w2 = new global::Gtk.Image (); w2.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("InGtkCryptoSec2.icons.database1_32x32.png"); this.btnDatabase.Image = w2; this.vbox2.Add (this.btnDatabase); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.btnDatabase])); w3.Position = 0; w3.Expand = false; w3.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.btnFtp = new global::Gtk.Button (); this.btnFtp.TooltipMarkup = "InCryptoSec2 module for FTP security."; this.btnFtp.CanFocus = true; this.btnFtp.Name = "btnFtp"; this.btnFtp.UseUnderline = true; this.btnFtp.Label = global::Mono.Unix.Catalog.GetString ("FTP"); global::Gtk.Image w4 = new global::Gtk.Image (); w4.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("InGtkCryptoSec2.icons.server_client_32x32.png"); this.btnFtp.Image = w4; this.vbox2.Add (this.btnFtp); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.btnFtp])); w5.Position = 1; w5.Expand = false; w5.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.btnString = new global::Gtk.Button (); this.btnString.TooltipMarkup = "InCryptoSec2 module for String security."; this.btnString.CanFocus = true; this.btnString.Name = "btnString"; this.btnString.UseUnderline = true; this.btnString.Label = global::Mono.Unix.Catalog.GetString ("String"); global::Gtk.Image w6 = new global::Gtk.Image (); w6.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("InGtkCryptoSec2.icons.text_32x32.png"); this.btnString.Image = w6; this.vbox2.Add (this.btnString); global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.btnString])); w7.Position = 2; w7.Expand = false; w7.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.btnXml = new global::Gtk.Button (); this.btnXml.TooltipMarkup = "InCryptoSec2 module for XML security."; this.btnXml.CanFocus = true; this.btnXml.Name = "btnXml"; this.btnXml.UseUnderline = true; this.btnXml.Label = global::Mono.Unix.Catalog.GetString ("XML"); global::Gtk.Image w8 = new global::Gtk.Image (); w8.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("InGtkCryptoSec2.icons.text_tree_32x32.png"); this.btnXml.Image = w8; this.vbox2.Add (this.btnXml); global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.vbox2 [this.btnXml])); w9.Position = 3; w9.Expand = false; w9.Fill = false; w1.Add (this.vbox2); global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(w1 [this.vbox2])); w10.Position = 0; w10.Expand = false; w10.Fill = false; // Internal child WinCryptoSec2Config.ActionArea global::Gtk.HButtonBox w11 = this.ActionArea; w11.Name = "dialog1_Action"; w11.Spacing = 10; w11.BorderWidth = ((uint)(5)); w11.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(4)); // Container child dialog1_Action.Gtk.ButtonBox+ButtonBoxChild this.btnCancel = new global::Gtk.Button (); this.btnCancel.CanDefault = true; this.btnCancel.CanFocus = true; this.btnCancel.Name = "btnCancel"; this.btnCancel.UseStock = true; this.btnCancel.UseUnderline = true; this.btnCancel.Label = "gtk-cancel"; this.AddActionWidget (this.btnCancel, -6); global::Gtk.ButtonBox.ButtonBoxChild w12 = ((global::Gtk.ButtonBox.ButtonBoxChild)(w11 [this.btnCancel])); w12.Expand = false; w12.Fill = false; if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 246; this.DefaultHeight = 276; this.Show (); this.btnDatabase.Clicked += new global::System.EventHandler (this.btnDatabase_OnClick); this.btnFtp.Clicked += new global::System.EventHandler (this.btnFtp_OnClick); this.btnString.Clicked += new global::System.EventHandler (this.btnString_OnClick); this.btnXml.Clicked += new global::System.EventHandler (this.btnXml_OnClick); } }
Java
<?php use HebrewParseTrainer\Root; use HebrewParseTrainer\Stem; use HebrewParseTrainer\Tense; ?> @extends('layouts.with_sidebar') @section('sidebar') <form id="hebrewparsetrainer-settings"> <input type="hidden" id="csrf" value="{{ csrf_token() }}"/> <div class="form-group"> <h3>Stems</h3> @foreach (Stem::all() as $stem) <div class="checkbox"> <label><input class="reload-verb" type="checkbox" name="stem" value="{{{ $stem->name }}}" checked="checked"/> {{{ $stem->name }}}</label> </div> @endforeach </div> <div class="form-group"> <h3>Tenses</h3> @foreach (Tense::all() as $tense) <div class="checkbox"> <label><input class="reload-verb" type="checkbox" name="tense" value="{{{ $tense->name }}}" checked="checked"/> {{{ $tense->name }}}</label> </div> @endforeach </div> <div class="form-group"> <h3>Roots</h3> <select name="root" class="reload-verb form-control hebrew ltr" multiple="multiple"> @foreach (Root::orderBy('root_kind_id')->orderBy('root')->get() as $root) @if ($root->verbs()->where('active', 1)->count() > 0) <option value="{{{ $root->root }}}" selected="selected">{{{ $root->root }}} ({{{ $root->kind->name }}})</option> @endif @endforeach </select> </div> <div class="form-group"> <h3>Settings</h3> <div class="checkbox"> <label><input type="checkbox" id="settings-audio" checked="checked"/> Audio</label> </div> </div> </form> @endsection @section('content') <div id="trainer"> <div id="trainer-input-container"> <p class="bg-danger" id="trainer-404">There are no verbs matching the criteria in our database.</p> <p class="lead"><span class="hebrew hebrew-large" id="trainer-verb"></span><span id="trainer-answer"></span></p> </div> <div id="trainer-input-fancy"></div> <div class="text-muted"> <div> <!-- id="trainer-input-help" --> <p>Parse the verb and enter the answer as described below or using the buttons. Press return. If your answer was correct and there are multiple possible parsings, an extra input field will appear. After the first incorrect answer or after entering all possible answers, you can continue to the next verb by pressing return once more.</p> <p> <strong>Stems</strong>: either use the full name or a significant beginning (i.e. <code>Q</code> for Qal and <code>N</code>, <code>Pi</code>, <code>Pu</code>, <code>Hit</code>, <code>Hip</code>, and <code>Hop</code> for the derived stems).<br/> <strong>Tenses</strong>: use the abbreviations <code>pf</code>, <code>ipf</code>, <code>coh</code>, <code>imp</code>, <code>jus</code>, <code>infcs</code>, <code>infabs</code>, <code>ptc</code> and <code>ptcp</code>.<br/> <strong>Person</strong>: <code>1</code>, <code>2</code>, <code>3</code> or none (infinitives and participles).<br/> <strong>Gender</strong>: <code>m</code>, <code>f</code> or none (infinitives).<br/> <strong>Number</strong>: <code>s</code>, <code>p</code> or none (infinitives). </p> <p>Examples: <code>Q pf 3ms</code>, <code>ni ptc fp</code>, <code>pi infabs</code>.</p> <h5>Notes:</h5> <ul> <li>There is no 'common' gender. Instead, enter the masculine and feminine forms separately. The <code>N/A</code> option is for infinitives.</li> <li>The <code>ptcp</code> option is only for the passive participle of the qal. All other participles should be entered with <code>ptc</code> (including participles of the passive stems).</li> </ul> </div> <button type="button" class="btn btn-default btn-xs" id="show-hide-help">Show help</button> </div> </div> <hr/> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">About</h3> </div> <div class="panel-body"> <p>&copy; 2015&ndash;{!! date('y') !!} <a href="https://camilstaps.nl">Camil Staps</a>. Licensed under <a href="http://www.gnu.org/licenses/gpl-3.0.en.html">GPL 3.0</a>. Source is on <a href="https://github.com/HebrewTools/ParseTrainer">GitHub</a>.</p> <p>Please report any mistakes to <a href="mailto:info@camilstaps.nl">info@camilstaps.nl</a>.</p> </div> </div> </div> </div> <script type="text/javascript"> var reload_on_load = true; </script> @endsection
Java
package net.minecraft.server; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; // CraftBukkit start import org.bukkit.craftbukkit.event.CraftEventFactory; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.SpawnerSpawnEvent; // CraftBukkit end public abstract class MobSpawnerAbstract { public int spawnDelay = 20; private String mobName = "Pig"; private List mobs; private TileEntityMobSpawnerData spawnData; public double c; public double d; private int minSpawnDelay = 200; private int maxSpawnDelay = 800; private int spawnCount = 4; private Entity j; private int maxNearbyEntities = 6; private int requiredPlayerRange = 16; private int spawnRange = 4; public MobSpawnerAbstract() {} public String getMobName() { if (this.i() == null) { if (this.mobName.equals("Minecart")) { this.mobName = "MinecartRideable"; } return this.mobName; } else { return this.i().c; } } public void setMobName(String s) { this.mobName = s; } public boolean f() { return this.a().findNearbyPlayer((double) this.b() + 0.5D, (double) this.c() + 0.5D, (double) this.d() + 0.5D, (double) this.requiredPlayerRange) != null; } public void g() { if (this.f()) { double d0; if (this.a().isStatic) { double d1 = (double) ((float) this.b() + this.a().random.nextFloat()); double d2 = (double) ((float) this.c() + this.a().random.nextFloat()); d0 = (double) ((float) this.d() + this.a().random.nextFloat()); this.a().addParticle("smoke", d1, d2, d0, 0.0D, 0.0D, 0.0D); this.a().addParticle("flame", d1, d2, d0, 0.0D, 0.0D, 0.0D); if (this.spawnDelay > 0) { --this.spawnDelay; } this.d = this.c; this.c = (this.c + (double) (1000.0F / ((float) this.spawnDelay + 200.0F))) % 360.0D; } else { if (this.spawnDelay == -1) { this.j(); } if (this.spawnDelay > 0) { --this.spawnDelay; return; } boolean flag = false; for (int i = 0; i < this.spawnCount; ++i) { Entity entity = EntityTypes.createEntityByName(this.getMobName(), this.a()); if (entity == null) { return; } int j = this.a().a(entity.getClass(), AxisAlignedBB.a((double) this.b(), (double) this.c(), (double) this.d(), (double) (this.b() + 1), (double) (this.c() + 1), (double) (this.d() + 1)).grow((double) (this.spawnRange * 2), 4.0D, (double) (this.spawnRange * 2))).size(); if (j >= this.maxNearbyEntities) { this.j(); return; } d0 = (double) this.b() + (this.a().random.nextDouble() - this.a().random.nextDouble()) * (double) this.spawnRange; double d3 = (double) (this.c() + this.a().random.nextInt(3) - 1); double d4 = (double) this.d() + (this.a().random.nextDouble() - this.a().random.nextDouble()) * (double) this.spawnRange; EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; entity.setPositionRotation(d0, d3, d4, this.a().random.nextFloat() * 360.0F, 0.0F); if (entityinsentient == null || entityinsentient.canSpawn()) { this.a(entity); this.a().triggerEffect(2004, this.b(), this.c(), this.d(), 0); if (entityinsentient != null) { entityinsentient.s(); } flag = true; } } if (flag) { this.j(); } } } } public Entity a(Entity entity) { if (this.i() != null) { NBTTagCompound nbttagcompound = new NBTTagCompound(); entity.d(nbttagcompound); Iterator iterator = this.i().b.c().iterator(); while (iterator.hasNext()) { String s = (String) iterator.next(); NBTBase nbtbase = this.i().b.get(s); nbttagcompound.set(s, nbtbase.clone()); } entity.f(nbttagcompound); if (entity.world != null) { // CraftBukkit start - call SpawnerSpawnEvent, abort if cancelled SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity, this.b(), this.c(), this.d()); if (!event.isCancelled()) { entity.world.addEntity(entity, CreatureSpawnEvent.SpawnReason.SPAWNER); // CraftBukkit // Spigot Start if ( entity.world.spigotConfig.nerfSpawnerMobs ) { entity.fromMobSpawner = true; } // Spigot End } // CraftBukkit end } NBTTagCompound nbttagcompound1; for (Entity entity1 = entity; nbttagcompound.hasKeyOfType("Riding", 10); nbttagcompound = nbttagcompound1) { nbttagcompound1 = nbttagcompound.getCompound("Riding"); Entity entity2 = EntityTypes.createEntityByName(nbttagcompound1.getString("id"), entity.world); if (entity2 != null) { NBTTagCompound nbttagcompound2 = new NBTTagCompound(); entity2.d(nbttagcompound2); Iterator iterator1 = nbttagcompound1.c().iterator(); while (iterator1.hasNext()) { String s1 = (String) iterator1.next(); NBTBase nbtbase1 = nbttagcompound1.get(s1); nbttagcompound2.set(s1, nbtbase1.clone()); } entity2.f(nbttagcompound2); entity2.setPositionRotation(entity1.locX, entity1.locY, entity1.locZ, entity1.yaw, entity1.pitch); // CraftBukkit start - call SpawnerSpawnEvent, skip if cancelled SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity2, this.b(), this.c(), this.d()); if (event.isCancelled()) { continue; } if (entity.world != null) { entity.world.addEntity(entity2, CreatureSpawnEvent.SpawnReason.SPAWNER); // CraftBukkit } entity1.mount(entity2); } entity1 = entity2; } } else if (entity instanceof EntityLiving && entity.world != null) { ((EntityInsentient) entity).prepare((GroupDataEntity) null); // Spigot start - call SpawnerSpawnEvent, abort if cancelled SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity, this.b(), this.c(), this.d()); if (!event.isCancelled()) { this.a().addEntity(entity, CreatureSpawnEvent.SpawnReason.SPAWNER); // CraftBukkit // Spigot Start if ( entity.world.spigotConfig.nerfSpawnerMobs ) { entity.fromMobSpawner = true; } // Spigot End } // Spigot end } return entity; } private void j() { if (this.maxSpawnDelay <= this.minSpawnDelay) { this.spawnDelay = this.minSpawnDelay; } else { int i = this.maxSpawnDelay - this.minSpawnDelay; this.spawnDelay = this.minSpawnDelay + this.a().random.nextInt(i); } if (this.mobs != null && this.mobs.size() > 0) { this.a((TileEntityMobSpawnerData) WeightedRandom.a(this.a().random, (Collection) this.mobs)); } this.a(1); } public void a(NBTTagCompound nbttagcompound) { this.mobName = nbttagcompound.getString("EntityId"); this.spawnDelay = nbttagcompound.getShort("Delay"); if (nbttagcompound.hasKeyOfType("SpawnPotentials", 9)) { this.mobs = new ArrayList(); NBTTagList nbttaglist = nbttagcompound.getList("SpawnPotentials", 10); for (int i = 0; i < nbttaglist.size(); ++i) { this.mobs.add(new TileEntityMobSpawnerData(this, nbttaglist.get(i))); } } else { this.mobs = null; } if (nbttagcompound.hasKeyOfType("SpawnData", 10)) { this.a(new TileEntityMobSpawnerData(this, nbttagcompound.getCompound("SpawnData"), this.mobName)); } else { this.a((TileEntityMobSpawnerData) null); } if (nbttagcompound.hasKeyOfType("MinSpawnDelay", 99)) { this.minSpawnDelay = nbttagcompound.getShort("MinSpawnDelay"); this.maxSpawnDelay = nbttagcompound.getShort("MaxSpawnDelay"); this.spawnCount = nbttagcompound.getShort("SpawnCount"); } if (nbttagcompound.hasKeyOfType("MaxNearbyEntities", 99)) { this.maxNearbyEntities = nbttagcompound.getShort("MaxNearbyEntities"); this.requiredPlayerRange = nbttagcompound.getShort("RequiredPlayerRange"); } if (nbttagcompound.hasKeyOfType("SpawnRange", 99)) { this.spawnRange = nbttagcompound.getShort("SpawnRange"); } if (this.a() != null && this.a().isStatic) { this.j = null; } } public void b(NBTTagCompound nbttagcompound) { nbttagcompound.setString("EntityId", this.getMobName()); nbttagcompound.setShort("Delay", (short) this.spawnDelay); nbttagcompound.setShort("MinSpawnDelay", (short) this.minSpawnDelay); nbttagcompound.setShort("MaxSpawnDelay", (short) this.maxSpawnDelay); nbttagcompound.setShort("SpawnCount", (short) this.spawnCount); nbttagcompound.setShort("MaxNearbyEntities", (short) this.maxNearbyEntities); nbttagcompound.setShort("RequiredPlayerRange", (short) this.requiredPlayerRange); nbttagcompound.setShort("SpawnRange", (short) this.spawnRange); if (this.i() != null) { nbttagcompound.set("SpawnData", this.i().b.clone()); } if (this.i() != null || this.mobs != null && this.mobs.size() > 0) { NBTTagList nbttaglist = new NBTTagList(); if (this.mobs != null && this.mobs.size() > 0) { Iterator iterator = this.mobs.iterator(); while (iterator.hasNext()) { TileEntityMobSpawnerData tileentitymobspawnerdata = (TileEntityMobSpawnerData) iterator.next(); nbttaglist.add(tileentitymobspawnerdata.a()); } } else { nbttaglist.add(this.i().a()); } nbttagcompound.set("SpawnPotentials", nbttaglist); } } public boolean b(int i) { if (i == 1 && this.a().isStatic) { this.spawnDelay = this.minSpawnDelay; return true; } else { return false; } } public TileEntityMobSpawnerData i() { return this.spawnData; } public void a(TileEntityMobSpawnerData tileentitymobspawnerdata) { this.spawnData = tileentitymobspawnerdata; } public abstract void a(int i); public abstract World a(); public abstract int b(); public abstract int c(); public abstract int d(); }
Java
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2016-2021 hyStrath \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of hyStrath, a derivative work of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::energyScalingFunction Description SourceFiles energyScalingFunction.C newEnergyScalingFunction.C \*---------------------------------------------------------------------------*/ #ifndef energyScalingFunction_H #define energyScalingFunction_H #include "IOdictionary.H" #include "typeInfo.H" #include "runTimeSelectionTables.H" #include "autoPtr.H" #include "pairPotentialModel.H" #include "reducedUnits.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class energyScalingFunction Declaration \*---------------------------------------------------------------------------*/ class energyScalingFunction { protected: // Protected data word name_; dictionary energyScalingFunctionProperties_; const pairPotentialModel& pairPot_; const reducedUnits& rU_; // Private Member Functions //- Disallow copy construct energyScalingFunction(const energyScalingFunction&); //- Disallow default bitwise assignment void operator=(const energyScalingFunction&); public: //- Runtime type information TypeName("energyScalingFunction"); // Declare run-time constructor selection table declareRunTimeSelectionTable ( autoPtr, energyScalingFunction, dictionary, ( const word& name, const dictionary& energyScalingFunctionProperties, const pairPotentialModel& pairPot, const reducedUnits& rU ), (name, energyScalingFunctionProperties, pairPot, rU) ); // Selectors //- Return a reference to the selected viscosity model static autoPtr<energyScalingFunction> New ( const word& name, const dictionary& energyScalingFunctionProperties, const pairPotentialModel& pairPot, const reducedUnits& rU ); // Constructors //- Construct from components energyScalingFunction ( const word& name, const dictionary& energyScalingFunctionProperties, const pairPotentialModel& pairPot, const reducedUnits& rU ); // Destructor virtual ~energyScalingFunction() {} // Member Functions virtual void scaleEnergy(scalar& e, const scalar r) const = 0; const dictionary& energyScalingFunctionProperties() const { return energyScalingFunctionProperties_; } //- Read energyScalingFunction dictionary virtual bool read ( const dictionary& energyScalingFunctionProperties ) = 0; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
Java
#!/usr/bin/python3 ### rev: 5.0 ### author: <zhq> ### features: ### errors included ### up to 63 bases (2 to 64) ### caps recognition and same output format (deprecated) ### for the function parameters, `cur` represents the current (input) base, `res` represents the result (output) base, and `num` represents the current (input) number. def scale(cur, res, num): # int, int, str -> str # Default Settings num = str(num) iscaps = False positive = True # Input if cur == res: return num if num == "0": return "0" assert cur in range(2, 65) and res in range(2, 65), "Base not defined." if num[0] == "-": positive = False num = num[1:] result = 0 unit = 1 if cur != 10: for i in num[::-1]: value = ord(i) if value in range(48, 58): value -= 48 elif value in range(65, 92): value -= 55 elif value in range(97, 123): value -= 61 elif value == 64: value = 62 elif value == 95: value = 63 assert value <= cur, "Digit larger than original base. v:%d(%s) b:%d\nCall: scale(%d, %d, %s)" % (value, i, cur, cur, res, num) result += value * unit unit *= cur result = str(result) # Output if res != 10: num = int(result or num) result = "" while num > 0: num, value = divmod(num, res) if value < 10: digit = value + 48 elif value < 36: digit = value + 55 elif value < 62: digit = value + 61 elif value == 62: digit = 64 elif value == 63: digit = 95 result = chr(digit) + result if not positive: result = "-" + result return result
Java
<?php /** * OpenEyes * * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011 * (C) OpenEyes Foundation, 2011-2012 * This file is part of OpenEyes. * OpenEyes 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. * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @package OpenEyes * @link http://www.openeyes.org.uk * @author OpenEyes <info@openeyes.org.uk> * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust * @copyright Copyright (c) 2011-2012, OpenEyes Foundation * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0 */ /** * This is the model class for table "family_history". * * The followings are the available columns in table 'family_history': * @property integer $id * @property string $name */ class FamilyHistory extends BaseActiveRecordVersioned { /** * Returns the static model of the specified AR class. * @return FamilyHistory the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'family_history'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('patient_id, relative_id, side_id, condition_id, comments','safe'), array('patient_id, relative_id, side_id, condition_id','required'), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, name', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'relative' => array(self::BELONGS_TO, 'FamilyHistoryRelative', 'relative_id'), 'side' => array(self::BELONGS_TO, 'FamilyHistorySide', 'side_id'), 'condition' => array(self::BELONGS_TO, 'FamilyHistoryCondition', 'condition_id'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'name' => 'Name', ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id,true); $criteria->compare('name',$this->name,true); return new CActiveDataProvider(get_class($this), array( 'criteria'=>$criteria, )); } }
Java
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; // manager for the gondola spawning public class GondolaManager : MonoBehaviour { private static int N = 50; private static int DELAY = 4; private static float OFFSET = -1.8f; // the offet between the rope center and a gondola center private int count = 0; // the count of ropes in the scene private DateTime curr; // the current time for second counting use public GameObject rope; // the rope object public GameObject gondola;// the gondola object public GameObject currentRope; // the last rope spawned public Transform firstRope; // the first rope in the scene private static GondolaManager instance; // the instance of the GondolaManager public static GondolaManager Instance { get { // an instance getter if (instance == null) { instance = GameObject.FindObjectOfType<GondolaManager> (); } return instance; } } void Start () { curr = DateTime.Now; // the time now // initialization of ropes and gondolas for (int i = 0; i < N; i++) { count++; SpawnRope (); if (count % 3 == 0) { SpawnGondola (currentRope.transform); } } SpawnGondola (firstRope); } void FixedUpdate () { DateTime now = DateTime.Now; if ((now - curr).TotalSeconds >= DELAY) { // if the interval has passed SpawnGondola (firstRope); // spawn fondola in the first rope for (int i = 0; i < N / 10; i++) { // spawn N/10 ropes SpawnRope (); count++; } curr = now; } } // spawns a rope object in the scene private void SpawnRope() { GameObject tmp = Instantiate (rope); tmp.transform.position = currentRope.transform.GetChild (0).position; // creates the link between the current and new rope currentRope.GetComponent<Rope> ().next = tmp.transform; currentRope = tmp; currentRope.GetComponent<Rope> ().next = firstRope.transform; } private void SpawnGondola(Transform parent) { GameObject gon = Instantiate (gondola); // new location of the gondole minus the offset between its senter and location of the parent gon.transform.localPosition = new Vector3 (0,OFFSET,0) + parent.position; } }
Java
module BaseControllerHelper end
Java
import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Http } from '@angular/http'; import { ActionSheetController } from 'ionic-angular'; import { NotifikasiPage } from '../notifikasi/notifikasi'; import { ArtikelBacaPage } from '../artikel-baca/artikel-baca'; import { TulisArtikelPage } from '../tulis-artikel/tulis-artikel'; import { TulisDiskusiPage } from '../tulis-diskusi/tulis-diskusi'; import '../../providers/user-data'; /* Generated class for the Cari page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-cari', templateUrl: 'cari.html' }) export class CariPage { public searchQuery = ""; public posts; public limit = 0; public httpErr = false; constructor(public navCtrl: NavController, public actionSheetCtrl: ActionSheetController, public http: Http, public toastCtrl: ToastController) { this.getData(); } ionViewDidLoad() { console.log('Hello CariPage Page'); } notif() { this.navCtrl.push(NotifikasiPage); } getData() { this.limit = 0; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = res.json(); console.log('dapet data'); this.httpErr = false; }, err => {this.showAlert(err.status)}); } getItems(searchbar){ this.getData(); } doInfinite(infiniteScroll) { console.log('Begin async operation'); setTimeout(() => { this.limit = this.limit+5; this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => { this.posts = this.posts.concat(res.json()); }); console.log('Async operation has ended'); infiniteScroll.complete(); }, 2000); } baca(idArtikel){ this.navCtrl.push(ArtikelBacaPage, idArtikel); } presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Pilihan', buttons: [ { text: 'Tulis Artikel', role: 'tulisArtikel', handler: () => { console.log('Tulis Artikel clicked'); this.navCtrl.push(TulisArtikelPage); } },{ text: 'Tanya/Diskusi', role: 'tulisDiskusi', handler: () => { console.log('Tulis Diskusi clicked'); this.navCtrl.push(TulisDiskusiPage); } },{ text: 'Batal', role: 'cancel', handler: () => { console.log('Cancel clicked'); } } ] }); actionSheet.present(); } showAlert(status){ if(status == 0){ let toast = this.toastCtrl.create({ message: 'Tidak ada koneksi. Cek kembali sambungan Internet perangkat Anda.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); }else{ let toast = this.toastCtrl.create({ message: 'Tidak dapat menyambungkan ke server. Mohon muat kembali halaman ini.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); } this.httpErr = true; } }
Java
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'events.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui from collections import * from functools import * import os, glob import pandas as pd try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_SamplesDialog(QtGui.QDialog): def __init__(self, parent=None, datafolder=None): """ Constructor """ QtGui.QDialog.__init__(self, parent) # self.filelist = filelist self.datafolder = datafolder # labels font self.font_labels = QtGui.QFont("Arial", 12, QtGui.QFont.Bold) self.font_edits = QtGui.QFont("Arial", 12) self.font_buttons = QtGui.QFont("Arial", 10, QtGui.QFont.Bold) self.setupUi(self) self.exec_() def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(1000, 400) self.gridLayout = QtGui.QGridLayout(Dialog) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) # list of Events self.prepare_form(Dialog) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def load_data(self): print(self.datafolder) self.samplefile = glob.glob(os.path.join(self.datafolder, "*_SAMPLES.csv"))[0] if os.path.isfile(self.samplefile): self.samplesdf = pd.read_csv(self.samplefile, encoding='ISO-8859-1') else: print("File not found: ", self.samplefile) self.samplesdf = None self.combodefaults = {'cuvette': ['600', '2000', '4000']} def prepare_form(self, Dialog): # load or reload data self.load_data() # form dicts edit_list = ['date', 'time', 'samplename', 'filename', 'smoothing', 'cal32', 'cal44', 'cons32', 'cons44', 'zero44', 'zero45', 'zero46', 'zero47', 'zero49'] combo_list = ['user', 'membrane', 'cuvette'] self.labels = defaultdict(defaultdict) self.edits = defaultdict(defaultdict) self.radios = defaultdict(defaultdict) self.combobox = defaultdict(defaultdict) self.labs = defaultdict(defaultdict) self.labs = {"time": "Time", "date": "Date", "samplename": "Sample Name", "filename": "File Name", "smoothing": "Smoothing", "cuvette": "Cuvette", "user": "User", "membrane": "Membrane", "cal44": "Calibration 44", "cal32": "Calibration 32", "cons32": "Consumption 32", "cons44": "Consumption 44", "zero32": "Zero 32", "zero44": "Zero 44", "zero45": "Zero 45", "zero46": "Zero 46", "zero47": "Zero 47", "zero49": "Zero 49"} self.buttons = OrderedDict(sorted({'Apply': defaultdict(object), 'Delete': defaultdict(object)}.items())) xpos, ypos = 1, 0 for row in self.samplesdf.iterrows(): row_index = row[0] r = row[1] self.radios[row_index] = QtGui.QRadioButton(Dialog) self.radios[row_index].setObjectName(_fromUtf8("_".join(["radio", str(row_index)]))) self.gridLayout.addWidget(self.radios[row_index], ypos+1, 0, 1, 1) for k in ['samplename', 'date', 'time', 'cuvette']: # create labels if ypos == 0: self.labels[k] = QtGui.QLabel(Dialog) self.labels[k].setObjectName(_fromUtf8("_".join(["label", k]))) self.labels[k].setText(str(self.labs[k])) self.labels[k].setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter) self.labels[k].setFont(self.font_labels) self.gridLayout.addWidget(self.labels[k], 0, xpos, 1, 1) if k in edit_list: self.edits[k][row_index] = QtGui.QLineEdit(Dialog) self.edits[k][row_index].setObjectName(_fromUtf8("_".join(["edit", k, str(row_index)]))) self.edits[k][row_index].setText(str(r[k])) self.edits[k][row_index].setFont(self.font_edits) if k in ['time', 'date']: self.edits[k][row_index].setFixedWidth(80) self.gridLayout.addWidget(self.edits[k][row_index], ypos+1, xpos, 1, 1) elif k in combo_list: self.combobox[k][row_index] = QtGui.QComboBox(Dialog) self.combobox[k][row_index].setObjectName(_fromUtf8("_".join(["combo", k, str(row_index)]))) self.combobox[k][row_index].addItems(self.combodefaults[k]) self.combobox[k][row_index].setCurrentIndex(self.combobox[k][row_index].findText(str(r[k]), QtCore.Qt.MatchFixedString)) self.combobox[k][row_index].setFont(self.font_edits) self.gridLayout.addWidget(self.combobox[k][row_index], ypos+1, xpos, 1, 1) xpos += 1 # create buttons for k in self.buttons.keys(): # if ypos > 0: self.buttons[k][row_index] = QtGui.QPushButton(Dialog) self.buttons[k][row_index].setObjectName(_fromUtf8("_".join(["event", k, "button", str(row_index)]))) self.buttons[k][row_index].setText(_translate("Dialog", k + str(row_index), None)) self.buttons[k][row_index].setFont(self.font_buttons) if k == 'Apply': self.buttons[k][row_index].clicked.connect(partial(self.ask_apply_changes, [row_index, Dialog])) self.buttons[k][row_index].setStyleSheet("background-color: #ffeedd") elif k == 'Delete': self.buttons[k][row_index].clicked.connect(partial(self.ask_delete_confirm1, [row_index, Dialog])) self.buttons[k][row_index].setStyleSheet("background-color: #ffcddd") self.gridLayout.addWidget(self.buttons[k][row_index], ypos+1, xpos, 1, 1) xpos += 1 # increments ypos += 1 xpos = 1 Dialog.resize(1000, 70 + (30 * ypos)) # self.add_row(Dialog) def ask_delete_confirm1(self, args): sid = args[0] Dialog = args[1] # check if radio button is checked. if self.radios[sid].isChecked(): msg = "Are you sure you want to delete the following sample : \n\n" details = "" for c in self.samplesdf.columns: details += str(c) + ": " + str(self.samplesdf.at[sid, c]) + "\n" reply = QtGui.QMessageBox.warning(self, 'Confirmation #1', msg + details, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: msg2 = "Are you sure REALLY REALLY sure you want to delete the following sample ? \n\n" + \ "This is the last confirmation message. After confirming, the files will be PERMANENTLY deleted and the data WILL be lost ! \n\n" msgbox = QtGui.QMessageBox.critical(self, 'Confirmation #2', msg2 + details, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) reply2 = msgbox if reply2 == QtGui.QMessageBox.Yes: # deletion confirmed self.delete_confirmed(sid) self.update_form( Dialog) else: QtGui.QMessageBox.question(self, 'Error', 'Please select the sample you want to delete on the left', QtGui.QMessageBox.Ok) def delete_confirmed(self, sid): # sample file filename = self.samplesdf.loc[sid, 'filename'] # delete row in samplesdf self.samplesdf = self.samplesdf.drop(self.samplesdf.index[sid]) self.samplesdf.to_csv(self.samplefile, index=False, encoding='ISO-8859-1') # delete file in rawdata if os.path.isfile(os.path.join(self.datafolder, "rawdata", filename)): os.remove(os.path.join(self.datafolder, "rawdata", filename)) # print(" delete: ", os.path.join(self.datafolder, "rawdata", filename)) # delete file in data if os.path.isfile(os.path.join(self.datafolder, filename)): os.remove(os.path.join(self.datafolder, filename)) # print(" delete: ", os.path.join(self.datafolder, filename)) def ask_apply_changes(self, args): sid = args[0] Dialog = args[1] newdata=defaultdict(str) for k in self.edits.keys(): newdata[k] = self.edits[k][sid].text() for k in self.combobox.keys(): newdata[k] = self.combobox[k][sid].currentText() details = "" for k in newdata: details += str(self.samplesdf.at[sid, k]) + '\t --> \t' + str(newdata[k]) + "\n" msg = "Are you sure you want to apply the changes to sample " + str(self.samplesdf.at[sid, 'samplename']) + " ?\n\n" reply = QtGui.QMessageBox.question(self, 'Modify a sample', msg + details, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.apply_changes_confirmed(sid, newdata) self.update_form(Dialog) else: print('cancel modification') def apply_changes_confirmed(self, sid, newdata): # rename files newdata['filename'] = str(newdata['date']) + "_" + str(newdata['samplename']) + ".csv" os.rename(os.path.join(self.datafolder, str(self.samplesdf.at[sid, 'filename'])), os.path.join(self.datafolder, str(newdata['filename']))) os.rename(os.path.join(self.datafolder, "rawdata", str(self.samplesdf.at[sid, 'filename'])), os.path.join(self.datafolder, "rawdata", str(newdata['filename']))) for k in newdata.keys(): self.samplesdf.at[sid, k] = newdata[k] self.samplesdf.to_csv(self.samplefile, index=False, encoding='ISO-8859-1') def update_form(self, Dialog): # empty variables self.edits = None self.combobox = None self.buttons = None self.radios = None self.labs = None self.labels = None # empty layout for i in reversed(range(self.gridLayout.count())): self.gridLayout.itemAt(i).widget().setParent(None) self.prepare_form(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(_translate("Dialog", "Samples Manager", None)) # self.label.setText(_translate("Dialog", "File", None))
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.16"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>linalg: linalg_immutable::eigen_results Type Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(initResizable); /* @license-end */</script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">linalg &#160;<span id="projectnumber">1.6.0</span> </div> <div id="projectbrief">A linear algebra library that provides a user-friendly interface to several BLAS and LAPACK routines.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.16 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(function(){initNavTree('structlinalg__immutable_1_1eigen__results.html','');}); /* @license-end */ </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#pri-attribs">Private Attributes</a> &#124; <a href="structlinalg__immutable_1_1eigen__results-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">linalg_immutable::eigen_results Type Reference</div> </div> </div><!--header--> <div class="contents"> <p>Defines a container for the output of an Eigen analysis of a square matrix. <a href="structlinalg__immutable_1_1eigen__results.html#details">More...</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pri-attribs"></a> Private Attributes</h2></td></tr> <tr class="memitem:abb60901ab160c6fd232cfb46ed0bf3cc"><td class="memItemLeft" align="right" valign="top"><a id="abb60901ab160c6fd232cfb46ed0bf3cc"></a> complex(real64), dimension(:), allocatable&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structlinalg__immutable_1_1eigen__results.html#abb60901ab160c6fd232cfb46ed0bf3cc">values</a></td></tr> <tr class="memdesc:abb60901ab160c6fd232cfb46ed0bf3cc"><td class="mdescLeft">&#160;</td><td class="mdescRight">An N-element array containing the eigenvalues. <br /></td></tr> <tr class="separator:abb60901ab160c6fd232cfb46ed0bf3cc"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a982607b9c3ff93504bb4524dcd31a442"><td class="memItemLeft" align="right" valign="top"><a id="a982607b9c3ff93504bb4524dcd31a442"></a> complex(real64), dimension(:,:), allocatable&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structlinalg__immutable_1_1eigen__results.html#a982607b9c3ff93504bb4524dcd31a442">vectors</a></td></tr> <tr class="memdesc:a982607b9c3ff93504bb4524dcd31a442"><td class="mdescLeft">&#160;</td><td class="mdescRight">An N-by-N matrix containing the N right eigenvectors (one per column). <br /></td></tr> <tr class="separator:a982607b9c3ff93504bb4524dcd31a442"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Defines a container for the output of an Eigen analysis of a square matrix. </p> <p class="definition">Definition at line <a class="el" href="linalg__immutable_8f90_source.html#l00187">187</a> of file <a class="el" href="linalg__immutable_8f90_source.html">linalg_immutable.f90</a>.</p> </div><hr/>The documentation for this type was generated from the following file:<ul> <li>C:/Users/jchri/Documents/github/linalg/src/<a class="el" href="linalg__immutable_8f90_source.html">linalg_immutable.f90</a></li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespacelinalg__immutable.html">linalg_immutable</a></li><li class="navelem"><a class="el" href="structlinalg__immutable_1_1eigen__results.html">eigen_results</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.16 </li> </ul> </div> </body> </html>
Java
/* * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com> * * This file is part of CasparCG (www.casparcg.com). * * CasparCG 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. * * CasparCG 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 CasparCG. If not, see <http://www.gnu.org/licenses/>. * * Author: Helge Norberg, helge.norberg@svt.se */ #include "../../StdAfx.h" #include "synchronizing_consumer.h" #include <common/log/log.h> #include <common/diagnostics/graph.h> #include <common/concurrency/future_util.h> #include <core/video_format.h> #include <boost/range/adaptor/transformed.hpp> #include <boost/range/algorithm/min_element.hpp> #include <boost/range/algorithm/max_element.hpp> #include <boost/range/algorithm/for_each.hpp> #include <boost/range/algorithm/count_if.hpp> #include <boost/range/numeric.hpp> #include <boost/algorithm/string/join.hpp> #include <boost/thread/future.hpp> #include <functional> #include <vector> #include <queue> #include <utility> #include <tbb/atomic.h> namespace caspar { namespace core { using namespace boost::adaptors; class delegating_frame_consumer : public frame_consumer { safe_ptr<frame_consumer> consumer_; public: delegating_frame_consumer(const safe_ptr<frame_consumer>& consumer) : consumer_(consumer) { } frame_consumer& get_delegate() { return *consumer_; } const frame_consumer& get_delegate() const { return *consumer_; } virtual void initialize( const video_format_desc& format_desc, int channel_index) override { get_delegate().initialize(format_desc, channel_index); } virtual int64_t presentation_frame_age_millis() const { return get_delegate().presentation_frame_age_millis(); } virtual boost::unique_future<bool> send( const safe_ptr<read_frame>& frame) override { return get_delegate().send(frame); } virtual std::wstring print() const override { return get_delegate().print(); } virtual boost::property_tree::wptree info() const override { return get_delegate().info(); } virtual bool has_synchronization_clock() const override { return get_delegate().has_synchronization_clock(); } virtual size_t buffer_depth() const override { return get_delegate().buffer_depth(); } virtual int index() const override { return get_delegate().index(); } }; const std::vector<int>& diag_colors() { static std::vector<int> colors = boost::assign::list_of<int> (diagnostics::color(0.0f, 0.6f, 0.9f)) (diagnostics::color(0.6f, 0.3f, 0.3f)) (diagnostics::color(0.3f, 0.6f, 0.3f)) (diagnostics::color(0.4f, 0.3f, 0.8f)) (diagnostics::color(0.9f, 0.9f, 0.5f)) (diagnostics::color(0.2f, 0.9f, 0.9f)); return colors; } class buffering_consumer_adapter : public delegating_frame_consumer { std::queue<safe_ptr<read_frame>> buffer_; tbb::atomic<size_t> buffered_; tbb::atomic<int64_t> duplicate_next_; public: buffering_consumer_adapter(const safe_ptr<frame_consumer>& consumer) : delegating_frame_consumer(consumer) { buffered_ = 0; duplicate_next_ = 0; } boost::unique_future<bool> consume_one() { if (!buffer_.empty()) { buffer_.pop(); --buffered_; } return get_delegate().send(buffer_.front()); } virtual boost::unique_future<bool> send( const safe_ptr<read_frame>& frame) override { if (duplicate_next_) { --duplicate_next_; } else if (!buffer_.empty()) { buffer_.pop(); --buffered_; } buffer_.push(frame); ++buffered_; return get_delegate().send(buffer_.front()); } void duplicate_next(int64_t to_duplicate) { duplicate_next_ += to_duplicate; } size_t num_buffered() const { return buffered_ - 1; } virtual std::wstring print() const override { return L"buffering[" + get_delegate().print() + L"]"; } virtual boost::property_tree::wptree info() const override { boost::property_tree::wptree info; info.add(L"type", L"buffering-consumer-adapter"); info.add_child(L"consumer", get_delegate().info()); info.add(L"buffered-frames", num_buffered()); return info; } }; static const uint64_t MAX_BUFFERED_OUT_OF_MEMORY_GUARD = 5; struct synchronizing_consumer::implementation { private: std::vector<safe_ptr<buffering_consumer_adapter>> consumers_; size_t buffer_depth_; bool has_synchronization_clock_; std::vector<boost::unique_future<bool>> results_; boost::promise<bool> promise_; video_format_desc format_desc_; safe_ptr<diagnostics::graph> graph_; int64_t grace_period_; tbb::atomic<int64_t> current_diff_; public: implementation(const std::vector<safe_ptr<frame_consumer>>& consumers) : grace_period_(0) { BOOST_FOREACH(auto& consumer, consumers) consumers_.push_back(make_safe<buffering_consumer_adapter>(consumer)); current_diff_ = 0; auto buffer_depths = consumers | transformed(std::mem_fn(&frame_consumer::buffer_depth)); std::vector<size_t> depths(buffer_depths.begin(), buffer_depths.end()); buffer_depth_ = *boost::max_element(depths); has_synchronization_clock_ = boost::count_if(consumers, std::mem_fn(&frame_consumer::has_synchronization_clock)) > 0; diagnostics::register_graph(graph_); } boost::unique_future<bool> send(const safe_ptr<read_frame>& frame) { results_.clear(); BOOST_FOREACH(auto& consumer, consumers_) results_.push_back(consumer->send(frame)); promise_ = boost::promise<bool>(); promise_.set_wait_callback(std::function<void(boost::promise<bool>&)>([this](boost::promise<bool>& promise) { BOOST_FOREACH(auto& result, results_) { result.get(); } auto frame_ages = consumers_ | transformed(std::mem_fn(&frame_consumer::presentation_frame_age_millis)); std::vector<int64_t> ages(frame_ages.begin(), frame_ages.end()); auto max_age_iter = boost::max_element(ages); auto min_age_iter = boost::min_element(ages); int64_t min_age = *min_age_iter; if (min_age == 0) { // One of the consumers have yet no measurement, wait until next // frame until we make any assumptions. promise.set_value(true); return; } int64_t max_age = *max_age_iter; int64_t age_diff = max_age - min_age; current_diff_ = age_diff; for (unsigned i = 0; i < ages.size(); ++i) graph_->set_value( narrow(consumers_[i]->print()), static_cast<double>(ages[i]) / *max_age_iter); bool grace_period_over = grace_period_ == 1; if (grace_period_) --grace_period_; if (grace_period_ == 0) { int64_t frame_duration = static_cast<int64_t>(1000 / format_desc_.fps); if (age_diff >= frame_duration) { CASPAR_LOG(info) << print() << L" Consumers not in sync. min: " << min_age << L" max: " << max_age; auto index = min_age_iter - ages.begin(); auto to_duplicate = age_diff / frame_duration; auto& consumer = *consumers_.at(index); auto currently_buffered = consumer.num_buffered(); if (currently_buffered + to_duplicate > MAX_BUFFERED_OUT_OF_MEMORY_GUARD) { CASPAR_LOG(info) << print() << L" Protecting from out of memory. Duplicating less frames than calculated"; to_duplicate = MAX_BUFFERED_OUT_OF_MEMORY_GUARD - currently_buffered; } consumer.duplicate_next(to_duplicate); grace_period_ = 10 + to_duplicate + buffer_depth_; } else if (grace_period_over) { CASPAR_LOG(info) << print() << L" Consumers resynced. min: " << min_age << L" max: " << max_age; } } blocking_consume_unnecessarily_buffered(); promise.set_value(true); })); return promise_.get_future(); } void blocking_consume_unnecessarily_buffered() { auto buffered = consumers_ | transformed(std::mem_fn(&buffering_consumer_adapter::num_buffered)); std::vector<size_t> num_buffered(buffered.begin(), buffered.end()); auto min_buffered = *boost::min_element(num_buffered); if (min_buffered) CASPAR_LOG(info) << print() << L" " << min_buffered << L" frames unnecessarily buffered. Consuming and letting channel pause during that time."; while (min_buffered) { std::vector<boost::unique_future<bool>> results; BOOST_FOREACH(auto& consumer, consumers_) results.push_back(consumer->consume_one()); BOOST_FOREACH(auto& result, results) result.get(); --min_buffered; } } void initialize(const video_format_desc& format_desc, int channel_index) { for (size_t i = 0; i < consumers_.size(); ++i) { auto& consumer = consumers_.at(i); consumer->initialize(format_desc, channel_index); graph_->set_color( narrow(consumer->print()), diag_colors().at(i % diag_colors().size())); } graph_->set_text(print()); format_desc_ = format_desc; } int64_t presentation_frame_age_millis() const { int64_t result = 0; BOOST_FOREACH(auto& consumer, consumers_) result = std::max(result, consumer->presentation_frame_age_millis()); return result; } std::wstring print() const { return L"synchronized[" + boost::algorithm::join(consumers_ | transformed(std::mem_fn(&frame_consumer::print)), L"|") + L"]"; } boost::property_tree::wptree info() const { boost::property_tree::wptree info; info.add(L"type", L"synchronized-consumer"); BOOST_FOREACH(auto& consumer, consumers_) info.add_child(L"consumer", consumer->info()); info.add(L"age-diff", current_diff_); return info; } bool has_synchronization_clock() const { return has_synchronization_clock_; } size_t buffer_depth() const { return buffer_depth_; } int index() const { return boost::accumulate(consumers_ | transformed(std::mem_fn(&frame_consumer::index)), 10000); } }; synchronizing_consumer::synchronizing_consumer(const std::vector<safe_ptr<frame_consumer>>& consumers) : impl_(new implementation(consumers)) { } boost::unique_future<bool> synchronizing_consumer::send(const safe_ptr<read_frame>& frame) { return impl_->send(frame); } void synchronizing_consumer::initialize(const video_format_desc& format_desc, int channel_index) { impl_->initialize(format_desc, channel_index); } int64_t synchronizing_consumer::presentation_frame_age_millis() const { return impl_->presentation_frame_age_millis(); } std::wstring synchronizing_consumer::print() const { return impl_->print(); } boost::property_tree::wptree synchronizing_consumer::info() const { return impl_->info(); } bool synchronizing_consumer::has_synchronization_clock() const { return impl_->has_synchronization_clock(); } size_t synchronizing_consumer::buffer_depth() const { return impl_->buffer_depth(); } int synchronizing_consumer::index() const { return impl_->index(); } }}
Java
package nest.util; import android.text.TextUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; import timber.log.Timber; public class TraceTree extends Timber.HollowTree { private final DebugTree debugTree; public TraceTree(boolean useTraces) { debugTree = new DebugTree(useTraces); } @Override public void v(String message, Object... args) { debugTree.v(message, args); } @Override public void v(Throwable t, String message, Object... args) { debugTree.v(t, message, args); } @Override public void d(String message, Object... args) { debugTree.d(message, args); } @Override public void d(Throwable t, String message, Object... args) { debugTree.d(t, message, args); } @Override public void i(String message, Object... args) { debugTree.i(message, args); } @Override public void i(Throwable t, String message, Object... args) { debugTree.i(t, message, args); } @Override public void w(String message, Object... args) { debugTree.w(message, args); } @Override public void w(Throwable t, String message, Object... args) { debugTree.w(t, message, args); } @Override public void e(String message, Object... args) { debugTree.e(message, args); } @Override public void e(Throwable t, String message, Object... args) { debugTree.e(t, message, args); } private static class DebugTree extends Timber.DebugTree { private static final Pattern ANONYMOUS_CLASS = Pattern.compile("\\$\\d+$"); private static final int STACK_POSITION = 6; private final boolean useTraces; private StackTraceElement lastTrace; private DebugTree(boolean useTraces) { this.useTraces = useTraces; } @Override protected String createTag() { String tag; if (!useTraces) { tag = nextTag(); if (tag != null) { return tag; } } StackTraceElement[] stackTrace = new Throwable().getStackTrace(); if (stackTrace.length < STACK_POSITION) { return "---"; } if (useTraces) { lastTrace = stackTrace[STACK_POSITION]; } tag = stackTrace[STACK_POSITION].getClassName(); Matcher m = ANONYMOUS_CLASS.matcher(tag); if (m.find()) { tag = m.replaceAll(""); } return tag.substring(tag.lastIndexOf('.') + 1); } @Override protected void logMessage(int priority, String tag, String message) { if (lastTrace != null) { message = (TextUtils.isEmpty(message) ? "" : message +" ") + "at "+ lastTrace; lastTrace = null; } super.logMessage(priority, tag, message); } } }
Java
/* * Copyright (C) 2012 Carl Green * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package info.carlwithak.mpxg2.sysex.effects.algorithms; import info.carlwithak.mpxg2.model.effects.algorithms.DetuneStereo; /** * Class to parse parameter data for Detune (S) effect. * * @author Carl Green */ public class DetuneStereoParser { public static DetuneStereo parse(byte[] effectParameters) { DetuneStereo detuneStereo = new DetuneStereo(); int mix = effectParameters[0] + effectParameters[1] * 16; detuneStereo.mix.setValue(mix); int level = effectParameters[2] + effectParameters[3] * 16; detuneStereo.level.setValue(level); int tune = effectParameters[4] + effectParameters[5] * 16; detuneStereo.tune.setValue(tune); int optimize = effectParameters[6] + effectParameters[7] * 16; detuneStereo.optimize.setValue(optimize); int preDelay = effectParameters[8] + effectParameters[9] * 16; detuneStereo.preDelay.setValue(preDelay); return detuneStereo; } }
Java
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend 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. foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "faceTriangulation.H" #include "plane.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // const Foam::scalar Foam::faceTriangulation::edgeRelTol = 1E-6; // Edge to the right of face vertex i Foam::label Foam::faceTriangulation::right(const label, label i) { return i; } // Edge to the left of face vertex i Foam::label Foam::faceTriangulation::left(const label size, label i) { return i ? i-1 : size-1; } // Calculate (normalized) edge vectors. // edges[i] gives edge between point i+1 and i. Foam::tmp<Foam::vectorField> Foam::faceTriangulation::calcEdges ( const face& f, const pointField& points ) { tmp<vectorField> tedges(new vectorField(f.size())); vectorField& edges = tedges(); forAll(f, i) { point thisPt = points[f[i]]; point nextPt = points[f[f.fcIndex(i)]]; vector vec(nextPt - thisPt); vec /= mag(vec) + VSMALL; edges[i] = vec; } return tedges; } // Calculates half angle components of angle from e0 to e1 void Foam::faceTriangulation::calcHalfAngle ( const vector& normal, const vector& e0, const vector& e1, scalar& cosHalfAngle, scalar& sinHalfAngle ) { // truncate cos to +-1 to prevent negative numbers scalar cos = max(-1, min(1, e0 & e1)); scalar sin = (e0 ^ e1) & normal; if (sin < -ROOTVSMALL) { // 3rd or 4th quadrant cosHalfAngle = - Foam::sqrt(0.5*(1 + cos)); sinHalfAngle = Foam::sqrt(0.5*(1 - cos)); } else { // 1st or 2nd quadrant cosHalfAngle = Foam::sqrt(0.5*(1 + cos)); sinHalfAngle = Foam::sqrt(0.5*(1 - cos)); } } // Calculate intersection point between edge p1-p2 and ray (in 2D). // Return true and intersection point if intersection between p1 and p2. Foam::pointHit Foam::faceTriangulation::rayEdgeIntersect ( const vector& normal, const point& rayOrigin, const vector& rayDir, const point& p1, const point& p2, scalar& posOnEdge ) { // Start off from miss pointHit result(p1); // Construct plane normal to rayDir and intersect const vector y = normal ^ rayDir; posOnEdge = plane(rayOrigin, y).normalIntersect(p1, (p2-p1)); // Check intersection to left of p1 or right of p2 if ((posOnEdge < 0) || (posOnEdge > 1)) { // Miss } else { // Check intersection behind rayOrigin point intersectPt = p1 + posOnEdge * (p2 - p1); if (((intersectPt - rayOrigin) & rayDir) < 0) { // Miss } else { // Hit result.setHit(); result.setPoint(intersectPt); result.setDistance(mag(intersectPt - rayOrigin)); } } return result; } // Return true if triangle given its three points (anticlockwise ordered) // contains point bool Foam::faceTriangulation::triangleContainsPoint ( const vector& n, const point& p0, const point& p1, const point& p2, const point& pt ) { scalar area01Pt = triPointRef(p0, p1, pt).normal() & n; scalar area12Pt = triPointRef(p1, p2, pt).normal() & n; scalar area20Pt = triPointRef(p2, p0, pt).normal() & n; if ((area01Pt > 0) && (area12Pt > 0) && (area20Pt > 0)) { return true; } else if ((area01Pt < 0) && (area12Pt < 0) && (area20Pt < 0)) { FatalErrorIn("triangleContainsPoint") << abort(FatalError); return false; } else { return false; } } // Starting from startIndex find diagonal. Return in index1, index2. // Index1 always startIndex except when convex polygon void Foam::faceTriangulation::findDiagonal ( const pointField& points, const face& f, const vectorField& edges, const vector& normal, const label startIndex, label& index1, label& index2 ) { const point& startPt = points[f[startIndex]]; // Calculate angle at startIndex const vector& rightE = edges[right(f.size(), startIndex)]; const vector leftE = -edges[left(f.size(), startIndex)]; // Construct ray which bisects angle scalar cosHalfAngle = GREAT; scalar sinHalfAngle = GREAT; calcHalfAngle(normal, rightE, leftE, cosHalfAngle, sinHalfAngle); vector rayDir ( cosHalfAngle*rightE + sinHalfAngle*(normal ^ rightE) ); // rayDir should be normalized already but is not due to rounding errors // so normalize. rayDir /= mag(rayDir) + VSMALL; // // Check all edges (apart from rightE and leftE) for nearest intersection // label faceVertI = f.fcIndex(startIndex); pointHit minInter(false, vector::zero, GREAT, true); label minIndex = -1; scalar minPosOnEdge = GREAT; for (label i = 0; i < f.size() - 2; i++) { scalar posOnEdge; pointHit inter = rayEdgeIntersect ( normal, startPt, rayDir, points[f[faceVertI]], points[f[f.fcIndex(faceVertI)]], posOnEdge ); if (inter.hit() && inter.distance() < minInter.distance()) { minInter = inter; minIndex = faceVertI; minPosOnEdge = posOnEdge; } faceVertI = f.fcIndex(faceVertI); } if (minIndex == -1) { //WarningIn("faceTriangulation::findDiagonal") // << "Could not find intersection starting from " << f[startIndex] // << " for face " << f << endl; index1 = -1; index2 = -1; return; } const label leftIndex = minIndex; const label rightIndex = f.fcIndex(minIndex); // Now ray intersects edge from leftIndex to rightIndex. // Check for intersection being one of the edge points. Make sure never // to return two consecutive points. if (mag(minPosOnEdge) < edgeRelTol && f.fcIndex(startIndex) != leftIndex) { index1 = startIndex; index2 = leftIndex; return; } if ( mag(minPosOnEdge - 1) < edgeRelTol && f.fcIndex(rightIndex) != startIndex ) { index1 = startIndex; index2 = rightIndex; return; } // Select visible vertex that minimizes // angle to bisection. Visibility checking by checking if inside triangle // formed by startIndex, leftIndex, rightIndex const point& leftPt = points[f[leftIndex]]; const point& rightPt = points[f[rightIndex]]; minIndex = -1; scalar maxCos = -GREAT; // all vertices except for startIndex and ones to left and right of it. faceVertI = f.fcIndex(f.fcIndex(startIndex)); for (label i = 0; i < f.size() - 3; i++) { const point& pt = points[f[faceVertI]]; if ( (faceVertI == leftIndex) || (faceVertI == rightIndex) || (triangleContainsPoint(normal, startPt, leftPt, rightPt, pt)) ) { // pt inside triangle (so perhaps visible) // Select based on minimal angle (so guaranteed visible). vector edgePt0 = pt - startPt; edgePt0 /= mag(edgePt0); scalar cos = rayDir & edgePt0; if (cos > maxCos) { maxCos = cos; minIndex = faceVertI; } } faceVertI = f.fcIndex(faceVertI); } if (minIndex == -1) { // no vertex found. Return startIndex and one of the intersected edge // endpoints. index1 = startIndex; if (f.fcIndex(startIndex) != leftIndex) { index2 = leftIndex; } else { index2 = rightIndex; } return; } index1 = startIndex; index2 = minIndex; } // Find label of vertex to start splitting from. Is: // 1] flattest concave angle // 2] flattest convex angle if no concave angles. Foam::label Foam::faceTriangulation::findStart ( const face& f, const vectorField& edges, const vector& normal ) { const label size = f.size(); scalar minCos = GREAT; label minIndex = -1; forAll(f, fp) { const vector& rightEdge = edges[right(size, fp)]; const vector leftEdge = -edges[left(size, fp)]; if (((rightEdge ^ leftEdge) & normal) < ROOTVSMALL) { scalar cos = rightEdge & leftEdge; if (cos < minCos) { minCos = cos; minIndex = fp; } } } if (minIndex == -1) { // No concave angle found. Get flattest convex angle minCos = GREAT; forAll(f, fp) { const vector& rightEdge = edges[right(size, fp)]; const vector leftEdge = -edges[left(size, fp)]; scalar cos = rightEdge & leftEdge; if (cos < minCos) { minCos = cos; minIndex = fp; } } } return minIndex; } // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // // Split face f into triangles. Handles all simple (convex & concave) // polygons. bool Foam::faceTriangulation::split ( const bool fallBack, const pointField& points, const face& f, const vector& normal, label& triI ) { const label size = f.size(); if (size <= 2) { WarningIn ( "split(const bool, const pointField&, const face&" ", const vector&, label&)" ) << "Illegal face:" << f << " with points " << UIndirectList<point>(points, f)() << endl; return false; } else if (size == 3) { // Triangle. Just copy. triFace& tri = operator[](triI++); tri[0] = f[0]; tri[1] = f[1]; tri[2] = f[2]; return true; } else { // General case. Start splitting for -flattest concave angle // -or flattest convex angle if no concave angles. tmp<vectorField> tedges(calcEdges(f, points)); const vectorField& edges = tedges(); label startIndex = findStart(f, edges, normal); // Find diagonal to split face across label index1 = -1; label index2 = -1; for (label iter = 0; iter < f.size(); iter++) { findDiagonal ( points, f, edges, normal, startIndex, index1, index2 ); if (index1 != -1 && index2 != -1) { // Found correct diagonal break; } // Try splitting from next startingIndex. startIndex = f.fcIndex(startIndex); } if (index1 == -1 || index2 == -1) { if (fallBack) { // Do naive triangulation. Find smallest angle to start // triangulating from. label maxIndex = -1; scalar maxCos = -GREAT; forAll(f, fp) { const vector& rightEdge = edges[right(size, fp)]; const vector leftEdge = -edges[left(size, fp)]; scalar cos = rightEdge & leftEdge; if (cos > maxCos) { maxCos = cos; maxIndex = fp; } } WarningIn ( "split(const bool, const pointField&, const face&" ", const vector&, label&)" ) << "Cannot find valid diagonal on face " << f << " with points " << UIndirectList<point>(points, f)() << nl << "Returning naive triangulation starting from " << f[maxIndex] << " which might not be correct for a" << " concave or warped face" << endl; label fp = f.fcIndex(maxIndex); for (label i = 0; i < size-2; i++) { label nextFp = f.fcIndex(fp); triFace& tri = operator[](triI++); tri[0] = f[maxIndex]; tri[1] = f[fp]; tri[2] = f[nextFp]; fp = nextFp; } return true; } else { WarningIn ( "split(const bool, const pointField&, const face&" ", const vector&, label&)" ) << "Cannot find valid diagonal on face " << f << " with points " << UIndirectList<point>(points, f)() << nl << "Returning empty triFaceList" << endl; return false; } } // Split into two subshapes. // face1: index1 to index2 // face2: index2 to index1 // Get sizes of the two subshapes label diff = 0; if (index2 > index1) { diff = index2 - index1; } else { // folded round diff = index2 + size - index1; } label nPoints1 = diff + 1; label nPoints2 = size - diff + 1; if (nPoints1 == size || nPoints2 == size) { FatalErrorIn ( "split(const bool, const pointField&, const face&" ", const vector&, label&)" ) << "Illegal split of face:" << f << " with points " << UIndirectList<point>(points, f)() << " at indices " << index1 << " and " << index2 << abort(FatalError); } // Collect face1 points face face1(nPoints1); label faceVertI = index1; for (int i = 0; i < nPoints1; i++) { face1[i] = f[faceVertI]; faceVertI = f.fcIndex(faceVertI); } // Collect face2 points face face2(nPoints2); faceVertI = index2; for (int i = 0; i < nPoints2; i++) { face2[i] = f[faceVertI]; faceVertI = f.fcIndex(faceVertI); } // Decompose the split faces //Pout<< "Split face:" << f << " into " << face1 << " and " << face2 // << endl; //string oldPrefix(Pout.prefix()); //Pout.prefix() = " " + oldPrefix; bool splitOk = split(fallBack, points, face1, normal, triI) && split(fallBack, points, face2, normal, triI); //Pout.prefix() = oldPrefix; return splitOk; } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Null constructor Foam::faceTriangulation::faceTriangulation() : triFaceList() {} // Construct from components Foam::faceTriangulation::faceTriangulation ( const pointField& points, const face& f, const bool fallBack ) : triFaceList(f.size()-2) { vector avgNormal = f.normal(points); avgNormal /= mag(avgNormal) + VSMALL; label triI = 0; bool valid = split(fallBack, points, f, avgNormal, triI); if (!valid) { setSize(0); } } // Construct from components Foam::faceTriangulation::faceTriangulation ( const pointField& points, const face& f, const vector& n, const bool fallBack ) : triFaceList(f.size()-2) { label triI = 0; bool valid = split(fallBack, points, f, n, triI); if (!valid) { setSize(0); } } // Construct from Istream Foam::faceTriangulation::faceTriangulation(Istream& is) : triFaceList(is) {} // ************************************************************************* //
Java
<?php /* Smarty version Smarty-3.1.19, created on 2016-03-17 14:44:03 compiled from "/Users/Evergreen/Documents/workspace/licpresta/admin/themes/default/template/controllers/shop/helpers/list/list_action_delete.tpl" */ ?> <?php /*%%SmartyHeaderCode:154545909656eab4a3d7e136-98563971%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_valid = $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( 'cbf2ed399b76a836e7562130658957cc92238d15' => array ( 0 => '/Users/Evergreen/Documents/workspace/licpresta/admin/themes/default/template/controllers/shop/helpers/list/list_action_delete.tpl', 1 => 1452095428, 2 => 'file', ), ), 'nocache_hash' => '154545909656eab4a3d7e136-98563971', 'function' => array ( ), 'variables' => array ( 'href' => 0, 'action' => 0, 'id_shop' => 0, 'shops_having_dependencies' => 0, 'confirm' => 0, ), 'has_nocache_code' => false, 'version' => 'Smarty-3.1.19', 'unifunc' => 'content_56eab4a3e7ff77_59198683', ),false); /*/%%SmartyHeaderCode%%*/?> <?php if ($_valid && !is_callable('content_56eab4a3e7ff77_59198683')) {function content_56eab4a3e7ff77_59198683($_smarty_tpl) {?> <a href="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['href']->value, ENT_QUOTES, 'UTF-8', true);?> " class="delete" title="<?php echo htmlspecialchars($_smarty_tpl->tpl_vars['action']->value, ENT_QUOTES, 'UTF-8', true);?> " <?php if (in_array($_smarty_tpl->tpl_vars['id_shop']->value,$_smarty_tpl->tpl_vars['shops_having_dependencies']->value)) {?> onclick="jAlert('<?php echo smartyTranslate(array('s'=>'You cannot delete this shop\'s (customer and/or order dependency)','js'=>1),$_smarty_tpl);?> '); return false;" <?php } elseif (isset($_smarty_tpl->tpl_vars['confirm']->value)) {?> onclick="if (confirm('<?php echo $_smarty_tpl->tpl_vars['confirm']->value;?> ')){return true;}else{event.stopPropagation(); event.preventDefault();};" <?php }?>> <i class="icon-trash"></i> <?php echo htmlspecialchars($_smarty_tpl->tpl_vars['action']->value, ENT_QUOTES, 'UTF-8', true);?> </a><?php }} ?>
Java
<?php namespace UJM\ExoBundle\Installation; use Claroline\InstallationBundle\Additional\AdditionalInstaller as BaseInstaller; use UJM\ExoBundle\Installation\Updater\Updater060000; use UJM\ExoBundle\Installation\Updater\Updater060001; use UJM\ExoBundle\Installation\Updater\Updater060200; use UJM\ExoBundle\Installation\Updater\Updater070000; use UJM\ExoBundle\Installation\Updater\Updater090000; use UJM\ExoBundle\Installation\Updater\Updater090002; class AdditionalInstaller extends BaseInstaller { public function preUpdate($currentVersion, $targetVersion) { if (version_compare($currentVersion, '6.0.0', '<=')) { $updater = new Updater060000($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->preUpdate(); } if (version_compare($currentVersion, '6.0.0', '=')) { $updater = new Updater060001($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->preUpdate(); } if (version_compare($currentVersion, '6.2.0', '<')) { $updater = new Updater060200($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->preUpdate(); } if (version_compare($currentVersion, '7.0.0', '<=')) { $updater = new Updater070000($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->preUpdate(); } } public function postUpdate($currentVersion, $targetVersion) { if (version_compare($currentVersion, '6.0.0', '<=')) { $updater = new Updater060000($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->postUpdate(); } if (version_compare($currentVersion, '6.2.0', '<')) { $updater = new Updater060200($this->container->get('doctrine.dbal.default_connection')); $updater->setLogger($this->logger); $updater->postUpdate(); } if (version_compare($currentVersion, '9.0.0', '<')) { $updater = new Updater090000( $this->container->get('doctrine.dbal.default_connection'), $this->container->get('claroline.persistence.object_manager'), $this->container->get('ujm_exo.serializer.exercise'), $this->container->get('ujm_exo.serializer.step'), $this->container->get('ujm_exo.serializer.item') ); $updater->setLogger($this->logger); $updater->postUpdate(); } if (version_compare($currentVersion, '9.0.2', '<')) { $updater = new Updater090002( $this->container->get('doctrine.dbal.default_connection') ); $updater->setLogger($this->logger); $updater->postUpdate(); } } }
Java
/* * Copyright 2014 Erik Wilson <erikwilson@magnorum.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.tritania.stables; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.Bukkit; import org.tritania.stables.Stables; import org.tritania.stables.util.Message; import org.tritania.stables.util.Log; public class RaceSystem { public Stables ht; public RaceSystem(Stables ht) { this.ht = ht; } }
Java
// This is a generated file. Not intended for manual editing. package org.modula.parsing.definition.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static org.modula.parsing.definition.psi.ModulaTypes.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import org.modula.parsing.definition.psi.*; public class DefinitionFormalParametersImpl extends ASTWrapperPsiElement implements DefinitionFormalParameters { public DefinitionFormalParametersImpl(ASTNode node) { super(node); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof DefinitionVisitor) ((DefinitionVisitor)visitor).visitFormalParameters(this); else super.accept(visitor); } @Override @NotNull public List<DefinitionFPSection> getFPSectionList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, DefinitionFPSection.class); } @Override @Nullable public DefinitionQualident getQualident() { return findChildByClass(DefinitionQualident.class); } }
Java
class MeetingQuery < Query self.queried_class = Meeting self.available_columns = [ QueryColumn.new(:subject, :sortable => "#{Meeting.table_name}.subject",:groupable => true), QueryColumn.new(:location_online, :sortable => "#{Meeting.table_name}.location_online",:groupable => true, caption: 'location'), QueryColumn.new(:date, :sortable => "#{Meeting.table_name}.date",:groupable => true), QueryColumn.new(:end_date, :sortable => "#{Meeting.table_name}.end_date",:groupable => true), QueryColumn.new(:start_time, :sortable => "#{Meeting.table_name}.start_time",:groupable => true), QueryColumn.new(:status, :sortable => "#{Meeting.table_name}.status",:groupable => true), ] def initialize(attributes=nil, *args) super attributes self.filters ||= {} add_filter('subject', '*') unless filters.present? end def initialize_available_filters add_available_filter "subject", :type => :string, :order => 0 add_available_filter "date", :type => :string, :order => 1 add_available_filter "end_date", :type => :string, :order => 1 add_available_filter "start_time", :type => :string, :order => 2 add_available_filter "location_online", :type => :string, :order => 3 add_available_filter "status", :type => :string, :order => 4 # add_custom_fields_filters(MeetingCustomField.where(:is_filter => true)) end def available_columns return @available_columns if @available_columns @available_columns = self.class.available_columns.dup # @available_columns += CustomField.where(:type => 'MeetingCustomField').all.map {|cf| QueryCustomFieldColumn.new(cf) } @available_columns end def default_columns_names @default_columns_names ||= [:subject, :date, :end_date, :start_time, :location_online, :status] end def results_scope(options={}) order_option = [group_by_sort_order, options[:order]].flatten.reject(&:blank?) Meeting.visible. where(statement).where(project_id: options[:project_id]). order(order_option). joins(joins_for_order_statement(order_option.join(','))) end def meetings end end
Java
cd paperbak-1.10.src del PAPERBAK.RES del PaperBak.bpr ren paperbak.h paperback.h ren paperbak.mak paperback.mak cd .. patch -p0 -E -i PaperBack-1.20.RA0193.EN.patch
Java
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** -- Odin JavaScript -------------------------------------------------------------------------------- Konpei - Showa Town(801000000) -- By --------------------------------------------------------------------------------------------- Information -- Version Info ----------------------------------------------------------------------------------- 1.1 - Fixed by Moogra 1.0 - First Version by Information --------------------------------------------------------------------------------------------------- **/ function start() { cm.sendSimple ("What do you want from me?\r #L0##bGather up some information on the hideout.#l\r\n#L1#Take me to the hideout#l\r\n#L2#Nothing#l#k"); } function action(mode, type, selection) { if (mode < 1) { cm.dispose(); } else { status++; if (status == 1) { if (selection == 0) { cm.sendNext("I can take you to the hideout, but the place is infested with thugs looking for trouble. You'll need to be both incredibly strong and brave to enter the premise. At the hideaway, you'll find the Boss that controls all the other bosses around this area. It's easy to get to the hideout, but the room on the top floor of the place can only be entered ONCE a day. The Boss's Room is not a place to mess around. I suggest you don't stay there for too long; you'll need to swiftly take care of the business once inside. The boss himself is a difficult foe, but you'll run into some incredibly powerful enemies on you way to meeting the boss! It ain't going to be easy."); cm.dispose(); } else if (selection == 1) cm.sendNext("Oh, the brave one. I've been awaiting your arrival. If these\r\nthugs are left unchecked, there's no telling what going to\r\nhappen in this neighborhood. Before that happens, I hope\r\nyou take care of all them and beat the boss, who resides\r\non the 5th floor. You'll need to be on alert at all times, since\r\nthe boss is too tough for even wisemen to handle.\r\nLooking at your eyes, however, I can see that eye of the\r\ntiger, the eyes that tell me you can do this. Let's go!"); else { cm.sendOk("I'm a busy person! Leave me alone if that's all you need!"); cm.dispose(); } } else { cm.warp(801040000); cm.dispose(); } } }
Java
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CloudWatchLogs.PutLogEvents -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Uploads a batch of log events to the specified log stream. -- -- Every PutLogEvents request must include the 'sequenceToken' obtained from the -- response of the previous request. An upload in a newly created log stream -- does not require a 'sequenceToken'. -- -- The batch of events must satisfy the following constraints: The maximum -- batch size is 32,768 bytes, and this size is calculated as the sum of all -- event messages in UTF-8, plus 26 bytes for each log event. None of the log -- events in the batch can be more than 2 hours in the future. None of the log -- events in the batch can be older than 14 days or the retention period of the -- log group. The log events in the batch must be in chronological ordered by -- their 'timestamp'. The maximum number of log events in a batch is 1,000. -- -- <http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html> module Network.AWS.CloudWatchLogs.PutLogEvents ( -- * Request PutLogEvents -- ** Request constructor , putLogEvents -- ** Request lenses , pleLogEvents , pleLogGroupName , pleLogStreamName , pleSequenceToken -- * Response , PutLogEventsResponse -- ** Response constructor , putLogEventsResponse -- ** Response lenses , plerNextSequenceToken ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.CloudWatchLogs.Types import qualified GHC.Exts data PutLogEvents = PutLogEvents { _pleLogEvents :: List1 "logEvents" InputLogEvent , _pleLogGroupName :: Text , _pleLogStreamName :: Text , _pleSequenceToken :: Maybe Text } deriving (Eq, Read, Show) -- | 'PutLogEvents' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'pleLogEvents' @::@ 'NonEmpty' 'InputLogEvent' -- -- * 'pleLogGroupName' @::@ 'Text' -- -- * 'pleLogStreamName' @::@ 'Text' -- -- * 'pleSequenceToken' @::@ 'Maybe' 'Text' -- putLogEvents :: Text -- ^ 'pleLogGroupName' -> Text -- ^ 'pleLogStreamName' -> NonEmpty InputLogEvent -- ^ 'pleLogEvents' -> PutLogEvents putLogEvents p1 p2 p3 = PutLogEvents { _pleLogGroupName = p1 , _pleLogStreamName = p2 , _pleLogEvents = withIso _List1 (const id) p3 , _pleSequenceToken = Nothing } pleLogEvents :: Lens' PutLogEvents (NonEmpty InputLogEvent) pleLogEvents = lens _pleLogEvents (\s a -> s { _pleLogEvents = a }) . _List1 pleLogGroupName :: Lens' PutLogEvents Text pleLogGroupName = lens _pleLogGroupName (\s a -> s { _pleLogGroupName = a }) pleLogStreamName :: Lens' PutLogEvents Text pleLogStreamName = lens _pleLogStreamName (\s a -> s { _pleLogStreamName = a }) -- | A string token that must be obtained from the response of the previous 'PutLogEvents' request. pleSequenceToken :: Lens' PutLogEvents (Maybe Text) pleSequenceToken = lens _pleSequenceToken (\s a -> s { _pleSequenceToken = a }) newtype PutLogEventsResponse = PutLogEventsResponse { _plerNextSequenceToken :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'PutLogEventsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'plerNextSequenceToken' @::@ 'Maybe' 'Text' -- putLogEventsResponse :: PutLogEventsResponse putLogEventsResponse = PutLogEventsResponse { _plerNextSequenceToken = Nothing } plerNextSequenceToken :: Lens' PutLogEventsResponse (Maybe Text) plerNextSequenceToken = lens _plerNextSequenceToken (\s a -> s { _plerNextSequenceToken = a }) instance ToPath PutLogEvents where toPath = const "/" instance ToQuery PutLogEvents where toQuery = const mempty instance ToHeaders PutLogEvents instance ToJSON PutLogEvents where toJSON PutLogEvents{..} = object [ "logGroupName" .= _pleLogGroupName , "logStreamName" .= _pleLogStreamName , "logEvents" .= _pleLogEvents , "sequenceToken" .= _pleSequenceToken ] instance AWSRequest PutLogEvents where type Sv PutLogEvents = CloudWatchLogs type Rs PutLogEvents = PutLogEventsResponse request = post "PutLogEvents" response = jsonResponse instance FromJSON PutLogEventsResponse where parseJSON = withObject "PutLogEventsResponse" $ \o -> PutLogEventsResponse <$> o .:? "nextSequenceToken"
Java
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2015, Joyent, Inc. */ var test = require('./test-namer')('vm-to-zones'); var util = require('util'); var bunyan = require('bunyan'); var utils = require('../../lib/utils'); var buildZonesFromVm = require('../../lib/vm-to-zones'); var log = bunyan.createLogger({name: 'cns'}); test('basic single container', function (t) { var config = { forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['abc123.inst.def432']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['abc123.inst.def432.foo']} ]); t.end(); }); test('cloudapi instance', function (t) { var config = { forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', services: [ { name: 'cloudapi', ports: [] } ], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'admin' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), [ 'abc123.inst.def432', 'cloudapi.svc.def432', 'cloudapi']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['cloudapi']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4'], src: 'abc123'}, {constructor: 'TXT', args: ['abc123'], src: 'abc123'} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['abc123.inst.def432.foo']} ]); t.end(); }); test('with use_alias', function (t) { var config = { use_alias: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'test.inst.def432']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.def432']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.def432.foo']} ]); t.end(); }); test('with use_login', function (t) { var config = { use_login: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'abc123.inst.bar']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['abc123.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['abc123.inst.bar.foo']} ]); t.end(); }); test('with use_alias and use_login', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'abc123.inst.bar', 'test.inst.def432', 'test.inst.bar']); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.foo']} ]); t.end(); }); test('using a PTR name', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], ptrname: 'test.something.com', listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.something.com']} ]); t.end(); }); test('multi-zone', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {}, 'bar': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] }, { ip: '3.2.1.4', zones: ['bar'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones).sort(), ['1.2.3.in-addr.arpa', '3.2.1.in-addr.arpa', 'bar', 'foo']); t.deepEqual(Object.keys(zones['foo']).sort(), ['abc123.inst.bar', 'abc123.inst.def432', 'test.inst.bar', 'test.inst.def432']); t.deepEqual(Object.keys(zones['bar']).sort(), Object.keys(zones['foo']).sort()); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); t.deepEqual(Object.keys(zones['1.2.3.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.foo']} ]); var rev2 = zones['1.2.3.in-addr.arpa']['4']; t.deepEqual(rev2, [ {constructor: 'PTR', args: ['test.inst.bar.bar']} ]); t.end(); }); test('multi-zone, single PTRs', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foo': {}, 'bar': {}, 'baz': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foo', 'bar'] }, { ip: '3.2.1.4', zones: ['baz'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones).sort(), ['1.2.3.in-addr.arpa', '3.2.1.in-addr.arpa', 'bar', 'baz', 'foo']); t.deepEqual(Object.keys(zones['foo']).sort(), ['abc123.inst.bar', 'abc123.inst.def432', 'test.inst.bar', 'test.inst.def432']); t.deepEqual(Object.keys(zones['bar']).sort(), Object.keys(zones['foo']).sort()); t.deepEqual(Object.keys(zones['3.2.1.in-addr.arpa']), ['4']); t.deepEqual(Object.keys(zones['1.2.3.in-addr.arpa']), ['4']); var fwd = zones['foo']['test.inst.bar']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.foo']} ]); var rev2 = zones['1.2.3.in-addr.arpa']['4']; t.deepEqual(rev2, [ {constructor: 'PTR', args: ['test.inst.bar.baz']} ]); t.end(); }); test('multi-zone, shortest zone priority PTR', function (t) { var config = { use_alias: true, use_login: true, forward_zones: { 'foobarbaz': {}, 'foobar': {}, 'baz': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [], listInstance: true, listServices: true, owner: { uuid: 'def432', login: 'bar' }, nics: [ { ip: '1.2.3.4', zones: ['foobar', 'foobarbaz', 'baz'] } ] }; var zones = buildZonesFromVm(vm, config, log); var rev = zones['3.2.1.in-addr.arpa']['4']; t.deepEqual(rev, [ {constructor: 'PTR', args: ['test.inst.bar.baz']} ]); t.end(); }); test('service with srvs', function (t) { var config = { use_alias: true, forward_zones: { 'foo': {} }, reverse_zones: {} }; var vm = { uuid: 'abc123', alias: 'test', services: [ { name: 'svc1', ports: [1234, 1235] } ], listInstance: true, listServices: true, owner: { uuid: 'def432' }, nics: [ { ip: '1.2.3.4', zones: ['foo'] } ] }; var zones = buildZonesFromVm(vm, config, log); t.deepEqual(Object.keys(zones), ['foo', '3.2.1.in-addr.arpa']); t.deepEqual(Object.keys(zones['foo']), ['abc123.inst.def432', 'test.inst.def432', 'svc1.svc.def432']); var fwd = zones['foo']['test.inst.def432']; t.deepEqual(fwd, [ {constructor: 'A', args: ['1.2.3.4']}, {constructor: 'TXT', args: ['abc123']} ]); var svc = zones['foo']['svc1.svc.def432']; t.deepEqual(svc, [ {constructor: 'A', args: ['1.2.3.4'], src: 'abc123'}, {constructor: 'TXT', args: ['abc123'], src: 'abc123'}, {constructor: 'SRV', args: ['test.inst.def432.foo', 1234], src: 'abc123'}, {constructor: 'SRV', args: ['test.inst.def432.foo', 1235], src: 'abc123'} ]); t.end(); });
Java
from cProfile import Profile from optparse import make_option from django.conf import settings from django.core.management.base import (BaseCommand, CommandError) from treeherder.etl.buildapi import (Builds4hJobsProcess, PendingJobsProcess, RunningJobsProcess) from treeherder.etl.pushlog import HgPushlogProcess from treeherder.model.derived import RefDataManager class Command(BaseCommand): """Management command to ingest data from a single push.""" help = "Ingests a single push into treeherder" args = '<project> <changeset>' option_list = BaseCommand.option_list + ( make_option('--profile-file', action='store', dest='profile_file', default=None, help='Profile command and write result to profile file'), make_option('--filter-job-group', action='store', dest='filter_job_group', default=None, help="Only process jobs in specified group symbol " "(e.g. 'T')") ) def _handle(self, *args, **options): if len(args) != 2: raise CommandError("Need to specify (only) branch and changeset") (project, changeset) = args # get reference to repo rdm = RefDataManager() repos = filter(lambda x: x['name'] == project, rdm.get_all_repository_info()) if not repos: raise CommandError("No project found named '%s'" % project) repo = repos[0] # make sure all tasks are run synchronously / immediately settings.CELERY_ALWAYS_EAGER = True # get hg pushlog pushlog_url = '%s/json-pushes/?full=1&version=2' % repo['url'] # ingest this particular revision for this project process = HgPushlogProcess() # Use the actual push SHA, in case the changeset specified was a tag # or branch name (eg tip). HgPushlogProcess returns the full SHA, but # job ingestion expects the short version, so we truncate it. push_sha = process.run(pushlog_url, project, changeset=changeset)[0:12] Builds4hJobsProcess().run(filter_to_project=project, filter_to_revision=push_sha, filter_to_job_group=options['filter_job_group']) PendingJobsProcess().run(filter_to_project=project, filter_to_revision=push_sha, filter_to_job_group=options['filter_job_group']) RunningJobsProcess().run(filter_to_project=project, filter_to_revision=push_sha, filter_to_job_group=options['filter_job_group']) def handle(self, *args, **options): if options['profile_file']: profiler = Profile() profiler.runcall(self._handle, *args, **options) profiler.dump_stats(options['profile_file']) else: self._handle(*args, **options)
Java
<header class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Chamilo Messaging</a> </div> <div class="collapse navbar-collapse" id="navbar-collapse"> <ul class="nav navbar-nav navbar-right"> <li> <a href="#" id="messages-update"> <i class="glyphicon glyphicon-refresh"></i> Actualizar </a> </li> <li> <a href="#logout"> <i class="glyphicon glyphicon-log-out"></i> Cerrar sesión </a> </li> </ul> </div> </div> </div> </header> <div class="container"> <div class="list-group" id="messages-list"></div> </div>
Java
<?php return function ($bh) { $bh->match('progressbar', function($ctx, $json) { $val = $json->val ?: 0; $ctx ->js([ 'val' => $val ]) ->content([ 'elem' => 'bar', 'attrs' => [ 'style' => 'width:' . $val . '%' ] ]); }); };
Java
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Management Agent API // // API for Management Agent Cloud Service // package managementagent // EditModesEnum Enum with underlying type: string type EditModesEnum string // Set of constants representing the allowable values for EditModesEnum const ( EditModesReadOnly EditModesEnum = "READ_ONLY" EditModesWritable EditModesEnum = "WRITABLE" EditModesExtensible EditModesEnum = "EXTENSIBLE" ) var mappingEditModes = map[string]EditModesEnum{ "READ_ONLY": EditModesReadOnly, "WRITABLE": EditModesWritable, "EXTENSIBLE": EditModesExtensible, } // GetEditModesEnumValues Enumerates the set of values for EditModesEnum func GetEditModesEnumValues() []EditModesEnum { values := make([]EditModesEnum, 0) for _, v := range mappingEditModes { values = append(values, v) } return values }
Java
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "p12plcy.h" #include "secoid.h" #include "secport.h" #include "secpkcs5.h" #define PKCS12_NULL 0x0000 typedef struct pkcs12SuiteMapStr { SECOidTag algTag; unsigned int keyLengthBits; /* in bits */ unsigned long suite; PRBool allowed; PRBool preferred; } pkcs12SuiteMap; static pkcs12SuiteMap pkcs12SuiteMaps[] = { { SEC_OID_RC4, 40, PKCS12_RC4_40, PR_FALSE, PR_FALSE }, { SEC_OID_RC4, 128, PKCS12_RC4_128, PR_FALSE, PR_FALSE }, { SEC_OID_RC2_CBC, 40, PKCS12_RC2_CBC_40, PR_FALSE, PR_TRUE }, { SEC_OID_RC2_CBC, 128, PKCS12_RC2_CBC_128, PR_FALSE, PR_FALSE }, { SEC_OID_DES_CBC, 64, PKCS12_DES_56, PR_FALSE, PR_FALSE }, { SEC_OID_DES_EDE3_CBC, 192, PKCS12_DES_EDE3_168, PR_FALSE, PR_FALSE }, { SEC_OID_UNKNOWN, 0, PKCS12_NULL, PR_FALSE, PR_FALSE }, { SEC_OID_UNKNOWN, 0, 0L, PR_FALSE, PR_FALSE } }; /* determine if algid is an algorithm which is allowed */ PRBool SEC_PKCS12DecryptionAllowed(SECAlgorithmID *algid) { unsigned int keyLengthBits; SECOidTag algId; int i; algId = SEC_PKCS5GetCryptoAlgorithm(algid); if (algId == SEC_OID_UNKNOWN) { return PR_FALSE; } keyLengthBits = (unsigned int)(SEC_PKCS5GetKeyLength(algid) * 8); i = 0; while (pkcs12SuiteMaps[i].algTag != SEC_OID_UNKNOWN) { if ((pkcs12SuiteMaps[i].algTag == algId) && (pkcs12SuiteMaps[i].keyLengthBits == keyLengthBits)) { return pkcs12SuiteMaps[i].allowed; } i++; } return PR_FALSE; } /* is any encryption allowed? */ PRBool SEC_PKCS12IsEncryptionAllowed(void) { int i; i = 0; while (pkcs12SuiteMaps[i].algTag != SEC_OID_UNKNOWN) { if (pkcs12SuiteMaps[i].allowed == PR_TRUE) { return PR_TRUE; } i++; } return PR_FALSE; } SECStatus SEC_PKCS12EnableCipher(long which, int on) { int i; i = 0; while (pkcs12SuiteMaps[i].suite != 0L) { if (pkcs12SuiteMaps[i].suite == (unsigned long)which) { if (on) { pkcs12SuiteMaps[i].allowed = PR_TRUE; } else { pkcs12SuiteMaps[i].allowed = PR_FALSE; } return SECSuccess; } i++; } return SECFailure; } SECStatus SEC_PKCS12SetPreferredCipher(long which, int on) { int i; PRBool turnedOff = PR_FALSE; PRBool turnedOn = PR_FALSE; i = 0; while (pkcs12SuiteMaps[i].suite != 0L) { if (pkcs12SuiteMaps[i].preferred == PR_TRUE) { pkcs12SuiteMaps[i].preferred = PR_FALSE; turnedOff = PR_TRUE; } if (pkcs12SuiteMaps[i].suite == (unsigned long)which) { pkcs12SuiteMaps[i].preferred = PR_TRUE; turnedOn = PR_TRUE; } i++; } if ((turnedOn) && (turnedOff)) { return SECSuccess; } return SECFailure; }
Java
//***************************************************************************** // // startup_gcc.c - Startup code for use with GNU tools. // // Copyright (c) 2012-2013 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 2.0.1.11577 of the EK-TM4C123GXL Firmware Package. // //***************************************************************************** #include <stdint.h> #include "inc/hw_nvic.h" #include "inc/hw_types.h" //***************************************************************************** // // Forward declaration of the default fault handlers. // //***************************************************************************** void ResetISR(void); static void NmiSR(void); static void FaultISR(void); static void IntDefaultHandler(void); //***************************************************************************** // // External declarations for the interrupt handlers used by the application. // //***************************************************************************** extern void SysTickIntHandler(void); extern void USBUARTIntHandler(void); extern void USB0DeviceIntHandler(void); //***************************************************************************** // // The entry point for the application. // //***************************************************************************** extern int main(void); //***************************************************************************** // // Reserve space for the system stack. // //***************************************************************************** static uint32_t pui32Stack[256]; //***************************************************************************** // // The vector table. Note that the proper constructs must be placed on this to // ensure that it ends up at physical address 0x0000.0000. // //***************************************************************************** __attribute__ ((section(".isr_vector"))) void (* const g_pfnVectors[])(void) = { (void (*)(void))((uint32_t)pui32Stack + sizeof(pui32Stack)), // The initial stack pointer ResetISR, // The reset handler NmiSR, // The NMI handler FaultISR, // The hard fault handler IntDefaultHandler, // The MPU fault handler IntDefaultHandler, // The bus fault handler IntDefaultHandler, // The usage fault handler 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved IntDefaultHandler, // SVCall handler IntDefaultHandler, // Debug monitor handler 0, // Reserved IntDefaultHandler, // The PendSV handler SysTickIntHandler, // The SysTick handler IntDefaultHandler, // GPIO Port A IntDefaultHandler, // GPIO Port B IntDefaultHandler, // GPIO Port C IntDefaultHandler, // GPIO Port D IntDefaultHandler, // GPIO Port E USBUARTIntHandler, // UART0 Rx and Tx IntDefaultHandler, // UART1 Rx and Tx IntDefaultHandler, // SSI0 Rx and Tx IntDefaultHandler, // I2C0 Master and Slave IntDefaultHandler, // PWM Fault IntDefaultHandler, // PWM Generator 0 IntDefaultHandler, // PWM Generator 1 IntDefaultHandler, // PWM Generator 2 IntDefaultHandler, // Quadrature Encoder 0 IntDefaultHandler, // ADC Sequence 0 IntDefaultHandler, // ADC Sequence 1 IntDefaultHandler, // ADC Sequence 2 IntDefaultHandler, // ADC Sequence 3 IntDefaultHandler, // Watchdog timer IntDefaultHandler, // Timer 0 subtimer A IntDefaultHandler, // Timer 0 subtimer B IntDefaultHandler, // Timer 1 subtimer A IntDefaultHandler, // Timer 1 subtimer B IntDefaultHandler, // Timer 2 subtimer A IntDefaultHandler, // Timer 2 subtimer B IntDefaultHandler, // Analog Comparator 0 IntDefaultHandler, // Analog Comparator 1 IntDefaultHandler, // Analog Comparator 2 IntDefaultHandler, // System Control (PLL, OSC, BO) IntDefaultHandler, // FLASH Control IntDefaultHandler, // GPIO Port F IntDefaultHandler, // GPIO Port G IntDefaultHandler, // GPIO Port H IntDefaultHandler, // UART2 Rx and Tx IntDefaultHandler, // SSI1 Rx and Tx IntDefaultHandler, // Timer 3 subtimer A IntDefaultHandler, // Timer 3 subtimer B IntDefaultHandler, // I2C1 Master and Slave IntDefaultHandler, // Quadrature Encoder 1 IntDefaultHandler, // CAN0 IntDefaultHandler, // CAN1 IntDefaultHandler, // CAN2 0, // Reserved IntDefaultHandler, // Hibernate USB0DeviceIntHandler, // USB0 IntDefaultHandler, // PWM Generator 3 IntDefaultHandler, // uDMA Software Transfer IntDefaultHandler, // uDMA Error IntDefaultHandler, // ADC1 Sequence 0 IntDefaultHandler, // ADC1 Sequence 1 IntDefaultHandler, // ADC1 Sequence 2 IntDefaultHandler, // ADC1 Sequence 3 0, // Reserved 0, // Reserved IntDefaultHandler, // GPIO Port J IntDefaultHandler, // GPIO Port K IntDefaultHandler, // GPIO Port L IntDefaultHandler, // SSI2 Rx and Tx IntDefaultHandler, // SSI3 Rx and Tx IntDefaultHandler, // UART3 Rx and Tx IntDefaultHandler, // UART4 Rx and Tx IntDefaultHandler, // UART5 Rx and Tx IntDefaultHandler, // UART6 Rx and Tx IntDefaultHandler, // UART7 Rx and Tx 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved IntDefaultHandler, // I2C2 Master and Slave IntDefaultHandler, // I2C3 Master and Slave IntDefaultHandler, // Timer 4 subtimer A IntDefaultHandler, // Timer 4 subtimer B 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved IntDefaultHandler, // Timer 5 subtimer A IntDefaultHandler, // Timer 5 subtimer B IntDefaultHandler, // Wide Timer 0 subtimer A IntDefaultHandler, // Wide Timer 0 subtimer B IntDefaultHandler, // Wide Timer 1 subtimer A IntDefaultHandler, // Wide Timer 1 subtimer B IntDefaultHandler, // Wide Timer 2 subtimer A IntDefaultHandler, // Wide Timer 2 subtimer B IntDefaultHandler, // Wide Timer 3 subtimer A IntDefaultHandler, // Wide Timer 3 subtimer B IntDefaultHandler, // Wide Timer 4 subtimer A IntDefaultHandler, // Wide Timer 4 subtimer B IntDefaultHandler, // Wide Timer 5 subtimer A IntDefaultHandler, // Wide Timer 5 subtimer B IntDefaultHandler, // FPU 0, // Reserved 0, // Reserved IntDefaultHandler, // I2C4 Master and Slave IntDefaultHandler, // I2C5 Master and Slave IntDefaultHandler, // GPIO Port M IntDefaultHandler, // GPIO Port N IntDefaultHandler, // Quadrature Encoder 2 0, // Reserved 0, // Reserved IntDefaultHandler, // GPIO Port P (Summary or P0) IntDefaultHandler, // GPIO Port P1 IntDefaultHandler, // GPIO Port P2 IntDefaultHandler, // GPIO Port P3 IntDefaultHandler, // GPIO Port P4 IntDefaultHandler, // GPIO Port P5 IntDefaultHandler, // GPIO Port P6 IntDefaultHandler, // GPIO Port P7 IntDefaultHandler, // GPIO Port Q (Summary or Q0) IntDefaultHandler, // GPIO Port Q1 IntDefaultHandler, // GPIO Port Q2 IntDefaultHandler, // GPIO Port Q3 IntDefaultHandler, // GPIO Port Q4 IntDefaultHandler, // GPIO Port Q5 IntDefaultHandler, // GPIO Port Q6 IntDefaultHandler, // GPIO Port Q7 IntDefaultHandler, // GPIO Port R IntDefaultHandler, // GPIO Port S IntDefaultHandler, // PWM 1 Generator 0 IntDefaultHandler, // PWM 1 Generator 1 IntDefaultHandler, // PWM 1 Generator 2 IntDefaultHandler, // PWM 1 Generator 3 IntDefaultHandler // PWM 1 Fault }; //***************************************************************************** // // The following are constructs created by the linker, indicating where the // the "data" and "bss" segments reside in memory. The initializers for the // for the "data" segment resides immediately following the "text" segment. // //***************************************************************************** extern uint32_t _etext; extern uint32_t _data; extern uint32_t _edata; extern uint32_t _bss; extern uint32_t _ebss; //***************************************************************************** // // This is the code that gets called when the processor first starts execution // following a reset event. Only the absolutely necessary set is performed, // after which the application supplied entry() routine is called. Any fancy // actions (such as making decisions based on the reset cause register, and // resetting the bits in that register) are left solely in the hands of the // application. // //***************************************************************************** void ResetISR(void) { uint32_t *pui32Src, *pui32Dest; // // Copy the data segment initializers from flash to SRAM. // pui32Src = &_etext; for(pui32Dest = &_data; pui32Dest < &_edata; ) { *pui32Dest++ = *pui32Src++; } // // Zero fill the bss segment. // __asm(" ldr r0, =_bss\n" " ldr r1, =_ebss\n" " mov r2, #0\n" " .thumb_func\n" "zero_loop:\n" " cmp r0, r1\n" " it lt\n" " strlt r2, [r0], #4\n" " blt zero_loop"); // // Enable the floating-point unit. This must be done here to handle the // case where main() uses floating-point and the function prologue saves // floating-point registers (which will fault if floating-point is not // enabled). Any configuration of the floating-point unit using DriverLib // APIs must be done here prior to the floating-point unit being enabled. // // Note that this does not use DriverLib since it might not be included in // this project. // HWREG(NVIC_CPAC) = ((HWREG(NVIC_CPAC) & ~(NVIC_CPAC_CP10_M | NVIC_CPAC_CP11_M)) | NVIC_CPAC_CP10_FULL | NVIC_CPAC_CP11_FULL); // // Call the application's entry point. // main(); } //***************************************************************************** // // This is the code that gets called when the processor receives a NMI. This // simply enters an infinite loop, preserving the system state for examination // by a debugger. // //***************************************************************************** static void NmiSR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives a fault // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void FaultISR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives an unexpected // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void IntDefaultHandler(void) { // // Go into an infinite loop. // while(1) { } }
Java
package de.maxgb.vertretungsplan.manager; import android.content.Context; import android.os.AsyncTask; import de.maxgb.android.util.Logger; import de.maxgb.vertretungsplan.util.Constants; import de.maxgb.vertretungsplan.util.Stunde; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class StundenplanManager { public static final int BEGINN_NACHMITTAG = 8; public static final int ANZAHL_SAMSTAG = 4; public static final int ANZAHL_NACHMITTAG = 2; private static StundenplanManager instance; public static synchronized StundenplanManager getInstance(Context context) { if (instance == null) { instance = new StundenplanManager(context); } return instance; } private final String TAG = "StundenplanManager"; private int lastResult = 0; private ArrayList<Stunde[]> woche; private Context context; // Listener------------- private ArrayList<OnUpdateListener> listener = new ArrayList<OnUpdateListener>(); private StundenplanManager(Context context) { this.context = context; auswerten(); } public void asyncAuswerten() { AuswertenTask task = new AuswertenTask(); task.execute(); } public void auswerten() { lastResult = dateiAuswerten(); if (lastResult == -1) { } else { woche = null; } } public void auswertenWithNotify() { auswerten(); notifyListener(); } public ArrayList<Stunde[]> getClonedStundenplan() { if (woche == null) return null; ArrayList<Stunde[]> clone; try { clone = new ArrayList<Stunde[]>(woche.size()); for (Stunde[] item : woche) { Stunde[] clone2 = new Stunde[item.length]; for (int i = 0; i < item.length; i++) { clone2[i] = item[i].clone(); } clone.add(clone2); } return clone; } catch (NullPointerException e) { Logger.e(TAG, "Failed to clone stundenplan", e); return null; } } public String getLastResult() { switch (lastResult) { case -1: return "Erfolgreich ausgewertet"; case 1: return "Datei existiert nicht"; case 2: return "Kann Datei nicht lesen"; case 3: return "Zugriffsfehler"; case 4: return "Parsingfehler"; default: return "Noch nicht ausgewertet"; } } public ArrayList<Stunde[]> getStundenplan() { return woche; } public void notifyListener() { for (int i = 0; i < listener.size(); i++) { if (listener.get(i) != null) { listener.get(i).onStundenplanUpdate(); } } } public void registerOnUpdateListener(OnUpdateListener listener) { this.listener.add(listener); } public void unregisterOnUpdateListener(OnUpdateListener listener) { this.listener.remove(listener); } private Stunde[] convertJSONArrayToStundenArray(JSONArray tag) throws JSONException { Stunde[] result = new Stunde[BEGINN_NACHMITTAG - 1 + ANZAHL_NACHMITTAG]; for (int i = 0; i < BEGINN_NACHMITTAG - 1 + ANZAHL_NACHMITTAG; i++) { JSONArray stunde = tag.getJSONArray(i); if (i >= BEGINN_NACHMITTAG - 1) { result[i] = new Stunde(stunde.getString(0), stunde.getString(1), i + 1, stunde.getString(2)); } else { result[i] = new Stunde(stunde.getString(0), stunde.getString(1), i + 1); } } return result; } /** * Wertet die Stundenplandatei aus * * @return Fehlercode -1 bei Erfolg,1 Datei existiert nicht, 2 Datei kann nicht gelesen werden,3 Fehler beim Lesen,4 Fehler * beim Parsen * */ private int dateiAuswerten() { File loadoutFile = new File(context.getFilesDir(), Constants.SP_FILE_NAME); ArrayList<Stunde[]> w = new ArrayList<Stunde[]>(); if (!loadoutFile.exists()) { Logger.w(TAG, "Stundenplan file doesn´t exist"); return 1; } if (!loadoutFile.canRead()) { Logger.w(TAG, "Can´t read Stundenplan file"); return 2; } try { BufferedReader br = new BufferedReader(new FileReader(loadoutFile)); String line = br.readLine(); br.close(); JSONObject stundenplan = new JSONObject(line); JSONArray mo = stundenplan.getJSONArray("mo"); JSONArray di = stundenplan.getJSONArray("di"); JSONArray mi = stundenplan.getJSONArray("mi"); JSONArray d = stundenplan.getJSONArray("do"); JSONArray fr = stundenplan.getJSONArray("fr"); JSONObject sa = stundenplan.getJSONObject("sa"); // Samstag Stunde[] samstag = new Stunde[9]; JSONArray eins = sa.getJSONArray("0"); JSONArray zwei = sa.getJSONArray("1"); JSONArray drei = sa.getJSONArray("2"); JSONArray vier = sa.getJSONArray("3"); JSONArray acht = sa.getJSONArray("7"); JSONArray neun = sa.getJSONArray("8"); samstag[0] = new Stunde(eins.getString(0), eins.getString(1), 1); samstag[1] = new Stunde(zwei.getString(0), zwei.getString(1), 2); samstag[2] = new Stunde(drei.getString(0), drei.getString(1), 3); samstag[3] = new Stunde(vier.getString(0), vier.getString(1), 4); samstag[4] = new Stunde("", "", 5); samstag[5] = new Stunde("", "", 6); samstag[6] = new Stunde("", "", 7); samstag[7] = new Stunde(acht.getString(0), acht.getString(1), 8, acht.getString(2)); samstag[8] = new Stunde(neun.getString(0), neun.getString(1), 9, neun.getString(2)); w.add(convertJSONArrayToStundenArray(mo)); w.add(convertJSONArrayToStundenArray(di)); w.add(convertJSONArrayToStundenArray(mi)); w.add(convertJSONArrayToStundenArray(d)); w.add(convertJSONArrayToStundenArray(fr)); w.add(samstag); /* * for(int i=0;i<w.size();i++){ for(int j=0;j<w.get(i).length;j++){ System.out.println(w.get(i)[j].toString()); } } */ } catch (IOException e) { Logger.e(TAG, "Fehler beim Lesen der Datei", e); return 3; } catch (JSONException e) { Logger.e(TAG, "Fehler beim Parsen der Datei", e); return 4; } woche = w; return -1; } public interface OnUpdateListener { void onStundenplanUpdate(); } // ------------------------ private class AuswertenTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { auswerten(); return null; } @Override protected void onPostExecute(Void v) { notifyListener(); } } }
Java
import tape from 'tape' import Common, { Chain, Hardfork } from '@ethereumjs/common' import { FeeMarketEIP1559Transaction } from '@ethereumjs/tx' import { Block } from '@ethereumjs/block' import { PeerPool } from '../../lib/net/peerpool' import { TxPool } from '../../lib/sync/txpool' import { Config } from '../../lib/config' tape('[TxPool]', async (t) => { const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London }) const config = new Config({ transports: [] }) const A = { address: Buffer.from('0b90087d864e82a284dca15923f3776de6bb016f', 'hex'), privateKey: Buffer.from( '64bf9cc30328b0e42387b3c82c614e6386259136235e20c1357bd11cdee86993', 'hex' ), } const B = { address: Buffer.from('6f62d8382bf2587361db73ceca28be91b2acb6df', 'hex'), privateKey: Buffer.from( '2a6e9ad5a6a8e4f17149b8bc7128bf090566a11dbd63c30e5a0ee9f161309cd6', 'hex' ), } const createTx = (from = A, to = B, nonce = 0, value = 1) => { const txData = { nonce, maxFeePerGas: 1000000000, maxInclusionFeePerGas: 100000000, gasLimit: 100000, to: to.address, value, } const tx = FeeMarketEIP1559Transaction.fromTxData(txData, { common }) const signedTx = tx.sign(from.privateKey) return signedTx } const txA01 = createTx() // A -> B, nonce: 0, value: 1 const txA02 = createTx(A, B, 0, 2) // A -> B, nonce: 0, value: 2 (different hash) const txB01 = createTx(B, A) // B -> A, nonce: 0, value: 1 const txB02 = createTx(B, A, 1, 5) // B -> A, nonce: 1, value: 5 t.test('should initialize correctly', (t) => { const config = new Config({ transports: [] }) const pool = new TxPool({ config }) t.equal(pool.pool.size, 0, 'pool empty') t.notOk((pool as any).opened, 'pool not opened yet') pool.open() t.ok((pool as any).opened, 'pool opened') pool.start() t.ok((pool as any).running, 'pool running') pool.stop() t.notOk((pool as any).running, 'pool not running anymore') pool.close() t.notOk((pool as any).opened, 'pool not opened anymore') t.end() }) t.test('should open/close', async (t) => { t.plan(3) const config = new Config({ transports: [] }) const pool = new TxPool({ config }) pool.open() pool.start() t.ok((pool as any).opened, 'pool opened') t.equals(pool.open(), false, 'already opened') pool.stop() pool.close() t.notOk((pool as any).opened, 'closed') }) t.test('announcedTxHashes() -> add single tx / knownByPeer / getByHash()', async (t) => { // Safeguard that send() method from peer2 gets called t.plan(12) const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { id: '1', eth: { getPooledTransactions: () => { return [null, [txA01]] }, send: () => { t.fail('should not send to announcing peer') }, }, } let sentToPeer2 = 0 const peer2: any = { id: '2', eth: { send: () => { sentToPeer2++ t.equal(sentToPeer2, 1, 'should send once to non-announcing peer') }, }, } const peerPool = new PeerPool({ config }) peerPool.add(peer) peerPool.add(peer2) await pool.handleAnnouncedTxHashes([txA01.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') t.equal((pool as any).pending.length, 0, 'cleared pending txs') t.equal((pool as any).handled.size, 1, 'added to handled txs') t.equal((pool as any).knownByPeer.size, 2, 'known tx hashes size 2 (entries for both peers)') t.equal((pool as any).knownByPeer.get(peer.id).length, 1, 'one tx added for peer 1') t.equal( (pool as any).knownByPeer.get(peer.id)[0].hash, txA01.hash().toString('hex'), 'new known tx hashes entry for announcing peer' ) const txs = pool.getByHash([txA01.hash()]) t.equal(txs.length, 1, 'should get correct number of txs by hash') t.equal( txs[0].serialize().toString('hex'), txA01.serialize().toString('hex'), 'should get correct tx by hash' ) pool.pool.clear() await pool.handleAnnouncedTxHashes([txA01.hash()], peer, peerPool) t.equal(pool.pool.size, 0, 'should not add a once handled tx') t.equal( (pool as any).knownByPeer.get(peer.id).length, 1, 'should add tx only once to known tx hashes' ) t.equal((pool as any).knownByPeer.size, 2, 'known tx hashes size 2 (entries for both peers)') pool.stop() pool.close() }) t.test('announcedTxHashes() -> TX_RETRIEVAL_LIMIT', async (t) => { const pool = new TxPool({ config }) const TX_RETRIEVAL_LIMIT: number = (pool as any).TX_RETRIEVAL_LIMIT pool.open() pool.start() const peer = { eth: { getPooledTransactions: (res: any) => { t.equal(res['hashes'].length, TX_RETRIEVAL_LIMIT, 'should limit to TX_RETRIEVAL_LIMIT') return [null, []] }, }, } const peerPool = new PeerPool({ config }) const hashes = [] for (let i = 1; i <= TX_RETRIEVAL_LIMIT + 1; i++) { // One more than TX_RETRIEVAL_LIMIT hashes.push(Buffer.from(i.toString().padStart(64, '0'), 'hex')) // '0000000000000000000000000000000000000000000000000000000000000001',... } await pool.handleAnnouncedTxHashes(hashes, peer as any, peerPool) pool.stop() pool.close() }) t.test('announcedTxHashes() -> add two txs (different sender)', async (t) => { const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01, txB01]] }, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxHashes([txA01.hash(), txB01.hash()], peer, peerPool) t.equal(pool.pool.size, 2, 'pool size 2') pool.stop() pool.close() }) t.test('announcedTxHashes() -> add two txs (same sender and nonce)', async (t) => { const config = new Config({ transports: [] }) const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01, txA02]] }, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxHashes([txA01.hash(), txA02.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') const address = A.address.toString('hex') const poolContent = pool.pool.get(address)! t.equal(poolContent.length, 1, 'only one tx') t.deepEqual(poolContent[0].tx.hash(), txA02.hash(), 'only later-added tx') pool.stop() pool.close() }) t.test('announcedTxs()', async (t) => { const config = new Config({ transports: [] }) const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { send: () => {}, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxs([txA01], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') const address = A.address.toString('hex') const poolContent = pool.pool.get(address)! t.equal(poolContent.length, 1, 'one tx') t.deepEqual(poolContent[0].tx.hash(), txA01.hash(), 'correct tx') pool.stop() pool.close() }) t.test('newBlocks() -> should remove included txs', async (t) => { const config = new Config({ transports: [] }) const pool = new TxPool({ config }) pool.open() pool.start() let peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01]] }, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxHashes([txA01.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') // Craft block with tx not in pool let block = Block.fromBlockData({ transactions: [txA02] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 1, 'pool size 1') // Craft block with tx in pool block = Block.fromBlockData({ transactions: [txA01] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 0, 'pool should be empty') peer = { eth: { getPooledTransactions: () => { return [null, [txB01, txB02]] }, }, } await pool.handleAnnouncedTxHashes([txB01.hash(), txB02.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') const address = B.address.toString('hex') let poolContent = pool.pool.get(address)! t.equal(poolContent.length, 2, 'two txs') // Craft block with tx not in pool block = Block.fromBlockData({ transactions: [txA02] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 1, 'pool size 1') poolContent = pool.pool.get(address)! t.equal(poolContent.length, 2, 'two txs') // Craft block with tx in pool block = Block.fromBlockData({ transactions: [txB01] }, { common }) pool.removeNewBlockTxs([block]) poolContent = pool.pool.get(address)! t.equal(poolContent.length, 1, 'only one tx') // Craft block with tx in pool block = Block.fromBlockData({ transactions: [txB02] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 0, 'pool size 0') pool.stop() pool.close() }) t.test('cleanup()', async (t) => { const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01, txB01]] }, }, send: () => {}, } const peerPool = new PeerPool({ config }) peerPool.add(peer) await pool.handleAnnouncedTxHashes([txA01.hash(), txB01.hash()], peer, peerPool) t.equal(pool.pool.size, 2, 'pool size 2') t.equal((pool as any).handled.size, 2, 'handled size 2') t.equal((pool as any).knownByPeer.size, 1, 'known by peer size 1') t.equal((pool as any).knownByPeer.get(peer.id).length, 2, '2 known txs') pool.cleanup() t.equal( pool.pool.size, 2, 'should not remove txs from pool (POOLED_STORAGE_TIME_LIMIT within range)' ) t.equal( (pool as any).knownByPeer.size, 1, 'should not remove txs from known by peer map (POOLED_STORAGE_TIME_LIMIT within range)' ) t.equal( (pool as any).handled.size, 2, 'should not remove txs from handled (HANDLED_CLEANUP_TIME_LIMIT within range)' ) const address = txB01.getSenderAddress().toString().slice(2) const poolObj = pool.pool.get(address)![0] poolObj.added = Date.now() - pool.POOLED_STORAGE_TIME_LIMIT * 60 - 1 pool.pool.set(address, [poolObj]) const knownByPeerObj1 = (pool as any).knownByPeer.get(peer.id)[0] const knownByPeerObj2 = (pool as any).knownByPeer.get(peer.id)[1] knownByPeerObj1.added = Date.now() - pool.POOLED_STORAGE_TIME_LIMIT * 60 - 1 ;(pool as any).knownByPeer.set(peer.id, [knownByPeerObj1, knownByPeerObj2]) const hash = txB01.hash().toString('hex') const handledObj = (pool as any).handled.get(hash) handledObj.added = Date.now() - pool.HANDLED_CLEANUP_TIME_LIMIT * 60 - 1 ;(pool as any).handled.set(hash, handledObj) pool.cleanup() t.equal( pool.pool.size, 1, 'should remove txs from pool (POOLED_STORAGE_TIME_LIMIT before range)' ) t.equal( (pool as any).knownByPeer.get(peer.id).length, 1, 'should remove one tx from known by peer map (POOLED_STORAGE_TIME_LIMIT before range)' ) t.equal( (pool as any).handled.size, 1, 'should remove txs from handled (HANDLED_CLEANUP_TIME_LIMIT before range)' ) pool.stop() pool.close() }) })
Java
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.GamesConfiguration.AchievementConfigurations.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves the metadata of the achievement configuration with the given -- ID. -- -- /See:/ <https://developers.google.com/games/ Google Play Game Services Publishing API Reference> for @gamesConfiguration.achievementConfigurations.get@. module Network.Google.Resource.GamesConfiguration.AchievementConfigurations.Get ( -- * REST Resource AchievementConfigurationsGetResource -- * Creating a Request , achievementConfigurationsGet , AchievementConfigurationsGet -- * Request Lenses , acgXgafv , acgUploadProtocol , acgAchievementId , acgAccessToken , acgUploadType , acgCallback ) where import Network.Google.GamesConfiguration.Types import Network.Google.Prelude -- | A resource alias for @gamesConfiguration.achievementConfigurations.get@ method which the -- 'AchievementConfigurationsGet' request conforms to. type AchievementConfigurationsGetResource = "games" :> "v1configuration" :> "achievements" :> Capture "achievementId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] AchievementConfiguration -- | Retrieves the metadata of the achievement configuration with the given -- ID. -- -- /See:/ 'achievementConfigurationsGet' smart constructor. data AchievementConfigurationsGet = AchievementConfigurationsGet' { _acgXgafv :: !(Maybe Xgafv) , _acgUploadProtocol :: !(Maybe Text) , _acgAchievementId :: !Text , _acgAccessToken :: !(Maybe Text) , _acgUploadType :: !(Maybe Text) , _acgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementConfigurationsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acgXgafv' -- -- * 'acgUploadProtocol' -- -- * 'acgAchievementId' -- -- * 'acgAccessToken' -- -- * 'acgUploadType' -- -- * 'acgCallback' achievementConfigurationsGet :: Text -- ^ 'acgAchievementId' -> AchievementConfigurationsGet achievementConfigurationsGet pAcgAchievementId_ = AchievementConfigurationsGet' { _acgXgafv = Nothing , _acgUploadProtocol = Nothing , _acgAchievementId = pAcgAchievementId_ , _acgAccessToken = Nothing , _acgUploadType = Nothing , _acgCallback = Nothing } -- | V1 error format. acgXgafv :: Lens' AchievementConfigurationsGet (Maybe Xgafv) acgXgafv = lens _acgXgafv (\ s a -> s{_acgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). acgUploadProtocol :: Lens' AchievementConfigurationsGet (Maybe Text) acgUploadProtocol = lens _acgUploadProtocol (\ s a -> s{_acgUploadProtocol = a}) -- | The ID of the achievement used by this method. acgAchievementId :: Lens' AchievementConfigurationsGet Text acgAchievementId = lens _acgAchievementId (\ s a -> s{_acgAchievementId = a}) -- | OAuth access token. acgAccessToken :: Lens' AchievementConfigurationsGet (Maybe Text) acgAccessToken = lens _acgAccessToken (\ s a -> s{_acgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). acgUploadType :: Lens' AchievementConfigurationsGet (Maybe Text) acgUploadType = lens _acgUploadType (\ s a -> s{_acgUploadType = a}) -- | JSONP acgCallback :: Lens' AchievementConfigurationsGet (Maybe Text) acgCallback = lens _acgCallback (\ s a -> s{_acgCallback = a}) instance GoogleRequest AchievementConfigurationsGet where type Rs AchievementConfigurationsGet = AchievementConfiguration type Scopes AchievementConfigurationsGet = '["https://www.googleapis.com/auth/androidpublisher"] requestClient AchievementConfigurationsGet'{..} = go _acgAchievementId _acgXgafv _acgUploadProtocol _acgAccessToken _acgUploadType _acgCallback (Just AltJSON) gamesConfigurationService where go = buildClient (Proxy :: Proxy AchievementConfigurationsGetResource) mempty
Java
SystemK Design Doc ================== # Introduction SystemK is a userspace process running with PID 0. It is the first process invocated by the kernel in userspace mode and its duty during its life-time is an infinite main-loop that spawns new userspace processes and manages their respective life-time. # Abstract Design Userspace process daemons are prone to failure in a great number of ways. To protect SystemK's critical data structures we model its behaviour and internal mechanism in a pure way and wrap this up by lifting its operational semantics into an IO () monad via IO () action primitives. These IO () action primitives serve as the SystemK API. A high-level view looks something like this: ''' +---------------------------------+ | IO Monad | | +---------------------------+ | | | KMonad = ReaderT + StateT | |<------* | | +-----------------+ | | \ | | | pure functional | | | ------>= Evil daemons | | | data structures | | | | | +-----------------+ | | | +---------------------------+ | +---------------------------------+ ''' # K Repository At the pure core of SystemK is the service configuration repository, which is cached in memory and stored on-disk in the form of JSON files. The repository provides a persistent way to toggle services, a consistent view of service states, and a unified interface to atomically manipulate service configuration properties. The repository is ACID compliant and so guarantees repository transactions are processed reliably and known good configurations are always accessible. Configuration repository transactions are mediated by the k.configd service via inter-process communication. # K Restarter Upon invocation, the SystemK main loop spawns a restart daemon thread called k.startd. The k.startd daemon queries the K repository to define the dependency chain of system services and invocate them in the appropriate order. Each chain is started asynchronously with respect to each entry-point service. In addition to spawning services, the k.startd service keeps track of state of services failures and dependency events. The k.startd service uses inter-process communication to interact with k.configd as to become stateful. It should be remarked here that the k.startd service itself is stateless, represented as the IO Monad. This allows SystemK to recover from service or service dependency failures, even critical failure in k.startd itself shall not bring down the system, however manual intervention would be required to restart it. NOTES: http://www.cns.nyu.edu/~fan/sun-docs/talks/practical-solaris10-security.pdf http://home.mit.bme.hu/~meszaros/edu/oprendszerek/segedlet/unix/5_solaris/Service%20Management%20Facility%20%28SMF%29%20in%20the%20Solaris%2010%20OS.pdf http://acid-state.seize.it/ http://acid-state.seize.it/safecopy https://www.usenix.org/legacy/event/lisa05/tech/full_papers/adams/adams.pdf
Java
package minejava.reg.util.concurrent; public interface RunnableFuture<V> extends Runnable, Future<V>{ @Override void run(); }
Java
<!DOCTYPE html> <meta charset="utf-8"> <title>CSS Color 4: predefined colorspaces, rec2020, percent values</title> <link rel="author" title="Chris Lilley" href="mailto:chris@w3.org"> <link rel="help" href="https://drafts.csswg.org/css-color-4/#predefined"> <link rel="match" href="greensquare-ref.html"> <meta name="assert" content="Color function with explicit rec2020 value as percent matches sRGB #009900"> <style> .test { background-color: red; width: 12em; height: 6em; margin-top:0} .ref { background-color: #009900; width: 12em; height: 6em; margin-bottom: 0} .test {background-color: color(rec2020 33.033% 55.976% 14.863%)} </style> <body> <p>Test passes if you see a green square, and no red.</p> <p class="ref"> </p> <p class="test"> </p> </body>
Java
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Editor configuration settings. * * Follow this link for more information: * http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options */ FCKConfig.CustomConfigurationsPath = '' ; FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ; FCKConfig.EditorAreaStyles = '' ; FCKConfig.ToolbarComboPreviewCSS = '' ; FCKConfig.DocType = '' ; FCKConfig.BaseHref = '' ; FCKConfig.FullPage = false ; // The following option determines whether the "Show Blocks" feature is enabled or not at startup. FCKConfig.StartupShowBlocks = false ; FCKConfig.Debug = false ; FCKConfig.AllowQueryStringDebug = true ; FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/default/' ; FCKConfig.SkinEditorCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ; FCKConfig.SkinDialogCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ; FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ; FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ; // FCKConfig.Plugins.Add( 'autogrow' ) ; // FCKConfig.Plugins.Add( 'dragresizetable' ); FCKConfig.AutoGrowMax = 400 ; // FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%> // FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code // FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control> FCKConfig.AutoDetectLanguage = true ; FCKConfig.DefaultLanguage = 'en' ; FCKConfig.ContentLangDirection = 'ltr' ; FCKConfig.ProcessHTMLEntities = true ; FCKConfig.IncludeLatinEntities = true ; FCKConfig.IncludeGreekEntities = true ; FCKConfig.ProcessNumericEntities = false ; FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'" FCKConfig.FillEmptyBlocks = true ; FCKConfig.FormatSource = true ; FCKConfig.FormatOutput = true ; FCKConfig.FormatIndentator = ' ' ; FCKConfig.EMailProtection = 'encode' ; // none | encode | function FCKConfig.EMailProtectionFunction = 'mt(NAME,DOMAIN,SUBJECT,BODY)' ; FCKConfig.StartupFocus = false ; FCKConfig.ForcePasteAsPlainText = false ; FCKConfig.AutoDetectPasteFromWord = true ; // IE only. FCKConfig.ShowDropDialog = true ; FCKConfig.ForceSimpleAmpersand = false ; FCKConfig.TabSpaces = 0 ; FCKConfig.ShowBorders = true ; FCKConfig.SourcePopup = false ; FCKConfig.ToolbarStartExpanded = true ; FCKConfig.ToolbarCanCollapse = true ; FCKConfig.IgnoreEmptyParagraphValue = true ; FCKConfig.FloatingPanelsZIndex = 10000 ; FCKConfig.HtmlEncodeOutput = false ; FCKConfig.TemplateReplaceAll = true ; FCKConfig.TemplateReplaceCheckbox = true ; FCKConfig.ToolbarLocation = 'In' ; FCKConfig.ToolbarSets["Default"] = [ ['Source','DocProps','-','Save','NewPage','Preview','-','Templates'], ['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'], '/', ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'], ['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'], '/', ['Style','FontFormat','FontName','FontSize'], ['TextColor','BGColor'], ['FitWindow','ShowBlocks','-','About'] // No comma for the last row. ] ; FCKConfig.ToolbarSets["Basic"] = [ ['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About'] ] ; FCKConfig.EnterMode = 'p' ; // p | div | br FCKConfig.ShiftEnterMode = 'br' ; // p | div | br FCKConfig.Keystrokes = [ [ CTRL + 65 /*A*/, true ], [ CTRL + 67 /*C*/, true ], [ CTRL + 70 /*F*/, true ], [ CTRL + 83 /*S*/, true ], [ CTRL + 84 /*T*/, true ], [ CTRL + 88 /*X*/, true ], [ CTRL + 86 /*V*/, 'Paste' ], [ CTRL + 45 /*INS*/, true ], [ SHIFT + 45 /*INS*/, 'Paste' ], [ CTRL + 88 /*X*/, 'Cut' ], [ SHIFT + 46 /*DEL*/, 'Cut' ], [ CTRL + 90 /*Z*/, 'Undo' ], [ CTRL + 89 /*Y*/, 'Redo' ], [ CTRL + SHIFT + 90 /*Z*/, 'Redo' ], [ CTRL + 76 /*L*/, 'Link' ], [ CTRL + 66 /*B*/, 'Bold' ], [ CTRL + 73 /*I*/, 'Italic' ], [ CTRL + 85 /*U*/, 'Underline' ], [ CTRL + SHIFT + 83 /*S*/, 'Save' ], [ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ], [ SHIFT + 32 /*SPACE*/, 'Nbsp' ] ] ; FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form','DivContainer'] ; FCKConfig.BrowserContextMenuOnCtrl = false ; FCKConfig.BrowserContextMenu = false ; FCKConfig.EnableMoreFontColors = true ; FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ; FCKConfig.FontFormats = 'p;h1;h2;h3;h4;h5;h6;pre;address;div' ; FCKConfig.FontNames = 'Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ; FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ; FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ; FCKConfig.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ; FCKConfig.SpellChecker = 'ieSpell' ; // 'ieSpell' | 'SpellerPages' FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ; FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl FCKConfig.FirefoxSpellChecker = false ; FCKConfig.MaxUndoLevels = 15 ; FCKConfig.DisableObjectResizing = false ; FCKConfig.DisableFFTableHandles = true ; FCKConfig.LinkDlgHideTarget = false ; FCKConfig.LinkDlgHideAdvanced = false ; FCKConfig.ImageDlgHideLink = false ; FCKConfig.ImageDlgHideAdvanced = false ; FCKConfig.FlashDlgHideAdvanced = false ; FCKConfig.ProtectedTags = '' ; // This will be applied to the body element of the editor FCKConfig.BodyId = '' ; FCKConfig.BodyClass = '' ; FCKConfig.DefaultStyleLabel = '' ; FCKConfig.DefaultFontFormatLabel = '' ; FCKConfig.DefaultFontLabel = '' ; FCKConfig.DefaultFontSizeLabel = '' ; FCKConfig.DefaultLinkTarget = '' ; // The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word FCKConfig.CleanWordKeepsStructure = false ; // Only inline elements are valid. FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ; // Attributes that will be removed FCKConfig.RemoveAttributes = 'class,style,lang,width,height,align,hspace,valign' ; FCKConfig.CustomStyles = { 'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } } }; // Do not add, rename or remove styles here. Only apply definition changes. FCKConfig.CoreStyles = { // Basic Inline Styles. 'Bold' : { Element : 'strong', Overrides : 'b' }, 'Italic' : { Element : 'em', Overrides : 'i' }, 'Underline' : { Element : 'u' }, 'StrikeThrough' : { Element : 'strike' }, 'Subscript' : { Element : 'sub' }, 'Superscript' : { Element : 'sup' }, // Basic Block Styles (Font Format Combo). 'p' : { Element : 'p' }, 'div' : { Element : 'div' }, 'pre' : { Element : 'pre' }, 'address' : { Element : 'address' }, 'h1' : { Element : 'h1' }, 'h2' : { Element : 'h2' }, 'h3' : { Element : 'h3' }, 'h4' : { Element : 'h4' }, 'h5' : { Element : 'h5' }, 'h6' : { Element : 'h6' }, // Other formatting features. 'FontFace' : { Element : 'span', Styles : { 'font-family' : '#("Font")' }, Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ] }, 'Size' : { Element : 'span', Styles : { 'font-size' : '#("Size","fontSize")' }, Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ] }, 'Color' : { Element : 'span', Styles : { 'color' : '#("Color","color")' }, Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ] }, 'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } }, 'SelectionHighlight' : { Element : 'span', Styles : { 'background-color' : 'navy', 'color' : 'white' } } }; // The distance of an indentation step. FCKConfig.IndentLength = 40 ; FCKConfig.IndentUnit = 'px' ; // Alternatively, FCKeditor allows the use of CSS classes for block indentation. // This overrides the IndentLength/IndentUnit settings. FCKConfig.IndentClasses = [] ; // [ Left, Center, Right, Justified ] FCKConfig.JustifyClasses = [] ; // The following value defines which File Browser connector and Quick Upload // "uploader" to use. It is valid for the default implementaion and it is here // just to make this configuration file cleaner. // It is not possible to change this value using an external file or even // inline when creating the editor instance. In that cases you must set the // values of LinkBrowserURL, ImageBrowserURL and so on. // Custom implementations should just ignore it. var _FileBrowserLanguage = 'aspx' ; // asp | aspx | cfm | lasso | perl | php | py var _QuickUploadLanguage = 'aspx' ; // asp | aspx | cfm | lasso | perl | php | py // Don't care about the following two lines. It just calculates the correct connector // extension to use for the default File Browser (Perl uses "cgi"). var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ; var _QuickUploadExtension = _QuickUploadLanguage == 'perl' ? 'cgi' : _QuickUploadLanguage ; FCKConfig.LinkBrowser = true ; FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% FCKConfig.ImageBrowser = true ; FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ; FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ; FCKConfig.FlashBrowser = true ; FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ; FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ; FCKConfig.LinkUpload = true ; FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension ; FCKConfig.LinkUploadAllowedExtensions = ".(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$" ; // empty for all FCKConfig.LinkUploadDeniedExtensions = "" ; // empty for no one FCKConfig.ImageUpload = true ; FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Image' ; FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one FCKConfig.FlashUpload = true ; FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Flash' ; FCKConfig.FlashUploadAllowedExtensions = ".(swf|flv)$" ; // empty for all FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ; FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ; FCKConfig.SmileyColumns = 8 ; FCKConfig.SmileyWindowWidth = 320 ; FCKConfig.SmileyWindowHeight = 210 ; FCKConfig.BackgroundBlockerColor = '#ffffff' ; FCKConfig.BackgroundBlockerOpacity = 0.50 ; FCKConfig.MsWebBrowserControlCompat = false ; FCKConfig.PreventSubmitHandler = false ;
Java
**Reminder - no plan survives breakfast.** [Episode guide](https://mikeconley.github.io/joy-of-coding-episode-guide/) - Feel free to send [pull requests](https://help.github.com/articles/about-pull-requests/) to the [repo](https://github.com/mikeconley/joy-of-coding-episode-guide)! - [Here’s a contributing guide!](https://github.com/mikeconley/joy-of-coding-episode-guide/blob/master/CONTRIBUTE.md) - [Here’s the guide for creating pull requests that smurfd used and recommends](https://akrabat.com/the-beginners-guide-to-contributing-to-a-github-project/%20)! **Today** - Taking a holiday break! Back on January 9th! - Things to look forward to in 2019 - Probably more Windows development! - Faster builds, because OBS will be running on a different machine - Renewed effort on auto-transcriptions - Self-check: is everything working? - promiseDocumentFlushed bug - Process Priority Manager investigation - **We'd love for other people in the Mozilla community to start livehacking! Come talk to mconley on **[irc.mozilla.org](http://irc.mozilla.org/)** #livehacking.** **Rate this episode: **https://goo.gl/forms/Om3S7MidMokDnYBy1 **Chat** - [IRC](https://wiki.mozilla.org/IRC) - We're in [irc.mozilla.org](http://irc.mozilla.org/) in [#livehacking](http://client00.chat.mibbit.com/?channel=%23livehacking&server=irc.mozilla.org). - I’ve also got my IRC client signed into the Twitch chat - [This is a link to a web client that you can use to chat with me from your browser](https://client00.chat.mibbit.com/?channel=%23livehacking&server=irc.mozilla.org) **Links** - [The Joy of Coding: Community-Run Episode guide](https://mikeconley.github.io/joy-of-coding-episode-guide/) - Feel free to send [pull requests](https://help.github.com/articles/about-pull-requests/) to the [repo](https://github.com/mikeconley/joy-of-coding-episode-guide)! - [Here’s the guide for creating pull requests that smurfd used and recommends](https://akrabat.com/the-beginners-guide-to-contributing-to-a-github-project/%20)! - [Check out my colleague Josh Marinacci](https://twitter.com/joshmarinacci) hacking on [Firefox Reality, our nascent VR browser](https://www.twitch.tv/joshmarinacci)! - [Les Orchard hacks on Firefox Color](https://www.twitch.tv/lmorchard/videos/all) - [Solving Bugs with Sean Prashad](https://www.youtube.com/channel/UCRxijHyajcDWdjRK_9jmLYw) - The Joy of Diagnosis!: https://www.youtube.com/watch?v=UL44ErfqJXs - [The Joy of Automation with Armen](https://www.youtube.com/channel/UCBgCmdvPaoYyha7JI33rfDQ) - [I've been mirroring the episodes to YouTube](https://www.youtube.com/playlist?list=PLmaFLMwlbk8wKMvfEEzp9Hfdlid8VYpL5) - [The Joy of Illustrating - Episode 1](https://www.youtube.com/watch?v=5g82nBPNVbc) - Watch @mart3ll blow your mind with designs from the Mozilla Creative team! - [Lost in Data](https://air.mozilla.org/lost-in-data-episode-1/) - sheriffing performance regressions in pushes for Firefox - [The Hour of Design](https://www.youtube.com/watch?v=8_Ld4hOU1QU) - watch one of our designers demystify the design process! - [Code Therapy with Danny O’Brien](https://www.youtube.com/channel/UCDShi-SQdFVRnQrMla9G_kQ) - Watch a developer put together a Windows game from scratch (no third-part engines) - really great explanations: https://handmadehero.org/ - [/r/WatchPeopleCode](https://www.reddit.com/r/WatchPeopleCode) for more livehacking! - [Watch @mrrrgn code to techno](https://www.youtube.com/channel/UC9ggHzjP5TepAxkrQyQCyJg) **Glossary** - BHR - “Background Hang Reporter”, a thing that records information about when Firefox performs poorly and sends it over Telemetry - e10s ("ee ten ESS") - short for [Electrolysis, which is the multi-process Firefox project](https://wiki.mozilla.org/Electrolysis) - CPOW ("ka-POW" or sometimes "SEE-pow") = Cross-Process Object Wrapper. [See this blog post.](http://mikeconley.ca/blog/2015/02/17/on-unsafe-cpow-usage-in-firefox-desktop-and-why-is-my-nightly-so-sluggish-with-e10s-enabled/) - Deserialize - "turn a serialized object back into the complex object” - Serialize - "turn a complex object into something that can be represented as primitives, like strings, integers, etc - Regression - something that made behaviour worse rather than better. Regress means to “go backward”, more or less. **Feedback** - [@mconley@mastodon.social on Mastodon](https://mastodon.social/@mconley) - [@mike_conley on Twitter](https://twitter.com/mike_conley) - mconley in IRC on [irc.mozilla.org](http://irc.mozilla.org/) - [mikeconley.ca/blog](http://mikeconley.ca/blog/)
Java
package testtravis; import static org.junit.Assert.*; import org.junit.Test; public class Operar_unit { @Test public void testSumar() { System.out.println("Sumar dos numeros"); int numero1 = 6; int numero2 = 6; Operaciones instance = new Operaciones(); int expResult = 12; int result = instance.sumar(numero1, numero2); assertEquals(expResult, result); } @Test public void testRestar() { System.out.println("Restar dos numeros"); int numero1 = 4; int numero2 = 2; Operaciones instance = new Operaciones(); int expResult = 2; int result = instance.restar(numero1, numero2); assertEquals(expResult, result); } @Test public void testMultiplicar() { System.out.println("Multiplicar dos numeros"); int numero1 = 3; int numero2 =3; Operaciones instance = new Operaciones(); int expResult = 9; int result = instance.multiplicar(numero1, numero2); assertEquals(expResult, result); } @Test public void testDividir() { System.out.println("Dividir Dos numeros"); int numero1 = 6; int numero2 = 3; Operaciones instance = new Operaciones(); int expResult = 2; int result = instance.dividir(numero1, numero2); assertEquals(expResult, result); } }
Java
#ifndef METHOD_ARGUMENT_H_VCZAR2ZT #define METHOD_ARGUMENT_H_VCZAR2ZT #include "ast_node.h" #include "ast_node_visitor.h" #include <string> namespace fparser { namespace ast { class MethodArgument : public ast::ASTNode { public: virtual void accept(ASTNodeVisitor& visitor) override; public: MethodArgument(); virtual ~MethodArgument(); }; } // namespace ast } // namespace fparser #endif /* end of include guard: METHOD_ARGUMENT_H_VCZAR2ZT */
Java
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef MOZILLA_MEDIASOURCEUTILS_H_ #define MOZILLA_MEDIASOURCEUTILS_H_ #include "nsString.h" #include "TimeUnits.h" namespace mozilla { nsCString DumpTimeRanges(const media::TimeIntervals& aRanges); } // namespace mozilla #endif /* MOZILLA_MEDIASOURCEUTILS_H_ */
Java
//***************************************************************************** // // pushbutton.c - Various types of push buttons. // // Copyright (c) 2008-2013 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 2.0.1.11577 of the Tiva Graphics Library. // //***************************************************************************** #include <stdint.h> #include <stdbool.h> #include "driverlib/debug.h" #include "grlib/grlib.h" #include "grlib/widget.h" #include "grlib/pushbutton.h" //***************************************************************************** // //! \addtogroup pushbutton_api //! @{ // //***************************************************************************** //***************************************************************************** // //! Draws a rectangular push button. //! //! \param psWidget is a pointer to the push button widget to be drawn. //! //! This function draws a rectangular push button on the display. This is //! called in response to a \b #WIDGET_MSG_PAINT message. //! //! \return None. // //***************************************************************************** static void RectangularButtonPaint(tWidget *psWidget) { const uint8_t *pui8Image; tPushButtonWidget *pPush; tContext sCtx; int32_t i32X, i32Y; // // Check the arguments. // ASSERT(psWidget); // // Convert the generic widget pointer into a push button widget pointer. // pPush = (tPushButtonWidget *)psWidget; // // Initialize a drawing context. // GrContextInit(&sCtx, psWidget->psDisplay); // // Initialize the clipping region based on the extents of this rectangular // push button. // GrContextClipRegionSet(&sCtx, &(psWidget->sPosition)); // // See if the push button fill style is selected. // if(pPush->ui32Style & PB_STYLE_FILL) { // // Fill the push button with the fill color. // GrContextForegroundSet(&sCtx, ((pPush->ui32Style & PB_STYLE_PRESSED) ? pPush->ui32PressFillColor : pPush->ui32FillColor)); GrRectFill(&sCtx, &(psWidget->sPosition)); } // // See if the push button outline style is selected. // if(pPush->ui32Style & PB_STYLE_OUTLINE) { // // Outline the push button with the outline color. // GrContextForegroundSet(&sCtx, pPush->ui32OutlineColor); GrRectDraw(&sCtx, &(psWidget->sPosition)); } // // See if the push button text or image style is selected. // if(pPush->ui32Style & (PB_STYLE_TEXT | PB_STYLE_IMG)) { // // Compute the center of the push button. // i32X = (psWidget->sPosition.i16XMin + ((psWidget->sPosition.i16XMax - psWidget->sPosition.i16XMin + 1) / 2)); i32Y = (psWidget->sPosition.i16YMin + ((psWidget->sPosition.i16YMax - psWidget->sPosition.i16YMin + 1) / 2)); // // If the push button outline style is selected then shrink the // clipping region by one pixel on each side so that the outline is not // overwritten by the text or image. // if(pPush->ui32Style & PB_STYLE_OUTLINE) { sCtx.sClipRegion.i16XMin++; sCtx.sClipRegion.i16YMin++; sCtx.sClipRegion.i16XMax--; sCtx.sClipRegion.i16YMax--; } // // See if the push button image style is selected. // if(pPush->ui32Style & PB_STYLE_IMG) { // // Set the foreground and background colors to use for 1 BPP // images. // GrContextForegroundSet(&sCtx, pPush->ui32TextColor); GrContextBackgroundSet(&sCtx, ((pPush->ui32Style & PB_STYLE_PRESSED) ? pPush->ui32PressFillColor : pPush->ui32FillColor)); // // Get the image to be drawn. // pui8Image = (((pPush->ui32Style & PB_STYLE_PRESSED) && pPush->pui8PressImage) ? pPush->pui8PressImage : pPush->pui8Image); // // Draw the image centered in the push button. // GrImageDraw(&sCtx, pui8Image, i32X - (GrImageWidthGet(pui8Image) / 2), i32Y - (GrImageHeightGet(pui8Image) / 2)); } // // See if the push button text style is selected. // if(pPush->ui32Style & PB_STYLE_TEXT) { // // Draw the text centered in the middle of the push button. // GrContextFontSet(&sCtx, pPush->psFont); GrContextForegroundSet(&sCtx, pPush->ui32TextColor); GrContextBackgroundSet(&sCtx, ((pPush->ui32Style & PB_STYLE_PRESSED) ? pPush->ui32PressFillColor : pPush->ui32FillColor)); GrStringDrawCentered(&sCtx, pPush->pcText, -1, i32X, i32Y, pPush->ui32Style & PB_STYLE_TEXT_OPAQUE); } } } //***************************************************************************** // //! Handles pointer events for a rectangular push button. //! //! \param psWidget is a pointer to the push button widget. //! \param ui32Msg is the pointer event message. //! \param i32X is the X coordinate of the pointer event. //! \param i32Y is the Y coordinate of the pointer event. //! //! This function processes pointer event messages for a rectangular push //! button. This is called in response to a \b #WIDGET_MSG_PTR_DOWN, //! \b #WIDGET_MSG_PTR_MOVE, and \b #WIDGET_MSG_PTR_UP messages. //! //! If the \b #WIDGET_MSG_PTR_UP message is received with a position within the //! extents of the push button, the push button's OnClick callback function is //! called. //! //! \return Returns 1 if the coordinates are within the extents of the push //! button and 0 otherwise. // //***************************************************************************** static int32_t RectangularButtonClick(tWidget *psWidget, uint32_t ui32Msg, int32_t i32X, int32_t i32Y) { tPushButtonWidget *pPush; // // Check the arguments. // ASSERT(psWidget); // // Convert the generic widget pointer into a push button widget pointer. // pPush = (tPushButtonWidget *)psWidget; // // See if this is a pointer up message. // if(ui32Msg == WIDGET_MSG_PTR_UP) { // // Indicate that this push button is no longer pressed. // pPush->ui32Style &= ~(PB_STYLE_PRESSED); // // If filling is enabled for this push button, or if an image is being // used and a pressed button image is provided, then redraw the push // button to show it in its non-pressed state. // if((pPush->ui32Style & PB_STYLE_FILL) || ((pPush->ui32Style & PB_STYLE_IMG) && pPush->pui8PressImage)) { RectangularButtonPaint(psWidget); } // // If the pointer is still within the button bounds, and it is a // release notify button, call the notification function here. // if(GrRectContainsPoint(&psWidget->sPosition, i32X, i32Y) && (pPush->ui32Style & PB_STYLE_RELEASE_NOTIFY) && pPush->pfnOnClick) { pPush->pfnOnClick(psWidget); } } // // See if the given coordinates are within the extents of the push button. // if(GrRectContainsPoint(&psWidget->sPosition, i32X, i32Y)) { // // See if this is a pointer down message. // if(ui32Msg == WIDGET_MSG_PTR_DOWN) { // // Indicate that this push button is pressed. // pPush->ui32Style |= PB_STYLE_PRESSED; // // If filling is enabled for this push button, or if an image is // being used and a pressed button image is provided, then redraw // the push button to show it in its pressed state. // if((pPush->ui32Style & PB_STYLE_FILL) || ((pPush->ui32Style & PB_STYLE_IMG) && pPush->pui8PressImage)) { RectangularButtonPaint(psWidget); } } // // See if there is an OnClick callback for this widget. // if(pPush->pfnOnClick) { // // If the pointer was just pressed then call the callback. // if((ui32Msg == WIDGET_MSG_PTR_DOWN) && !(pPush->ui32Style & PB_STYLE_RELEASE_NOTIFY)) { pPush->pfnOnClick(psWidget); } // // See if auto-repeat is enabled for this widget. // if(pPush->ui32Style & PB_STYLE_AUTO_REPEAT) { // // If the pointer was just pressed, reset the auto-repeat // count. // if(ui32Msg == WIDGET_MSG_PTR_DOWN) { pPush->ui32AutoRepeatCount = 0; } // // See if the pointer was moved. // else if(ui32Msg == WIDGET_MSG_PTR_MOVE) { // // Increment the auto-repeat count. // pPush->ui32AutoRepeatCount++; // // If the auto-repeat count exceeds the auto-repeat delay, // and it is a multiple of the auto-repeat rate, then // call the callback. // if((pPush->ui32AutoRepeatCount >= pPush->ui16AutoRepeatDelay) && (((pPush->ui32AutoRepeatCount - pPush->ui16AutoRepeatDelay) % pPush->ui16AutoRepeatRate) == 0)) { pPush->pfnOnClick(psWidget); } } } } // // These coordinates are within the extents of the push button widget. // return(1); } // // These coordinates are not within the extents of the push button widget. // return(0); } //***************************************************************************** // //! Handles messages for a rectangular push button widget. //! //! \param psWidget is a pointer to the push button widget. //! \param ui32Msg is the message. //! \param ui32Param1 is the first parameter to the message. //! \param ui32Param2 is the second parameter to the message. //! //! This function receives messages intended for this push button widget and //! processes them accordingly. The processing of the message varies based on //! the message in question. //! //! Unrecognized messages are handled by calling WidgetDefaultMsgProc(). //! //! \return Returns a value appropriate to the supplied message. // //***************************************************************************** int32_t RectangularButtonMsgProc(tWidget *psWidget, uint32_t ui32Msg, uint32_t ui32Param1, uint32_t ui32Param2) { // // Check the arguments. // ASSERT(psWidget); // // Determine which message is being sent. // switch(ui32Msg) { // // The widget paint request has been sent. // case WIDGET_MSG_PAINT: { // // Handle the widget paint request. // RectangularButtonPaint(psWidget); // // Return one to indicate that the message was successfully // processed. // return(1); } // // One of the pointer requests has been sent. // case WIDGET_MSG_PTR_DOWN: case WIDGET_MSG_PTR_MOVE: case WIDGET_MSG_PTR_UP: { // // Handle the pointer request, returning the appropriate value. // return(RectangularButtonClick(psWidget, ui32Msg, ui32Param1, ui32Param2)); } // // An unknown request has been sent. // default: { // // Let the default message handler process this message. // return(WidgetDefaultMsgProc(psWidget, ui32Msg, ui32Param1, ui32Param2)); } } } //***************************************************************************** // //! Initializes a rectangular push button widget. //! //! \param psWidget is a pointer to the push button widget to initialize. //! \param psDisplay is a pointer to the display on which to draw the push //! button. //! \param i32X is the X coordinate of the upper left corner of the push //! button. //! \param i32Y is the Y coordinate of the upper left corner of the push //! button. //! \param i32Width is the width of the push button. //! \param i32Height is the height of the push button. //! //! This function initializes the provided push button widget so that it will //! be a rectangular push button. //! //! \return None. // //***************************************************************************** void RectangularButtonInit(tPushButtonWidget *psWidget, const tDisplay *psDisplay, int32_t i32X, int32_t i32Y, int32_t i32Width, int32_t i32Height) { uint32_t ui32Idx; // // Check the arguments. // ASSERT(psWidget); ASSERT(psDisplay); // // Clear out the widget structure. // for(ui32Idx = 0; ui32Idx < sizeof(tPushButtonWidget); ui32Idx += 4) { ((uint32_t *)psWidget)[ui32Idx / 4] = 0; } // // Set the size of the push button widget structure. // psWidget->sBase.i32Size = sizeof(tPushButtonWidget); // // Mark this widget as fully disconnected. // psWidget->sBase.psParent = 0; psWidget->sBase.psNext = 0; psWidget->sBase.psChild = 0; // // Save the display pointer. // psWidget->sBase.psDisplay = psDisplay; // // Set the extents of this rectangular push button. // psWidget->sBase.sPosition.i16XMin = i32X; psWidget->sBase.sPosition.i16YMin = i32Y; psWidget->sBase.sPosition.i16XMax = i32X + i32Width - 1; psWidget->sBase.sPosition.i16YMax = i32Y + i32Height - 1; // // Use the rectangular push button message handler to process messages to // this push button. // psWidget->sBase.pfnMsgProc = RectangularButtonMsgProc; } //***************************************************************************** // //! Draws a circular push button. //! //! \param psWidget is a pointer to the push button widget to be drawn. //! //! This function draws a circular push button on the display. This is called //! in response to a \b #WIDGET_MSG_PAINT message. //! //! \return None. // //***************************************************************************** static void CircularButtonPaint(tWidget *psWidget) { const uint8_t *pui8Image; tPushButtonWidget *pPush; tContext sCtx; int32_t i32X, i32Y, i32R; // // Check the arguments. // ASSERT(psWidget); // // Convert the generic widget pointer into a push button widget pointer. // pPush = (tPushButtonWidget *)psWidget; // // Initialize a drawing context. // GrContextInit(&sCtx, psWidget->psDisplay); // // Initialize the clipping region based on the extents of this circular // push button. // GrContextClipRegionSet(&sCtx, &(psWidget->sPosition)); // // Get the radius of the circular push button, along with the X and Y // coordinates for its center. // i32R = (psWidget->sPosition.i16XMax - psWidget->sPosition.i16XMin + 1) / 2; i32X = psWidget->sPosition.i16XMin + i32R; i32Y = psWidget->sPosition.i16YMin + i32R; // // See if the push button fill style is selected. // if(pPush->ui32Style & PB_STYLE_FILL) { // // Fill the push button with the fill color. // GrContextForegroundSet(&sCtx, ((pPush->ui32Style & PB_STYLE_PRESSED) ? pPush->ui32PressFillColor : pPush->ui32FillColor)); GrCircleFill(&sCtx, i32X, i32Y, i32R); } // // See if the push button outline style is selected. // if(pPush->ui32Style & PB_STYLE_OUTLINE) { // // Outline the push button with the outline color. // GrContextForegroundSet(&sCtx, pPush->ui32OutlineColor); GrCircleDraw(&sCtx, i32X, i32Y, i32R); } // // See if the push button text or image style is selected. // if(pPush->ui32Style & (PB_STYLE_TEXT | PB_STYLE_IMG)) { // // If the push button outline style is selected then shrink the // clipping region by one pixel on each side so that the outline is not // overwritten by the text or image. // if(pPush->ui32Style & PB_STYLE_OUTLINE) { sCtx.sClipRegion.i16XMin++; sCtx.sClipRegion.i16YMin++; sCtx.sClipRegion.i16XMax--; sCtx.sClipRegion.i16YMax--; } // // See if the push button image style is selected. // if(pPush->ui32Style & PB_STYLE_IMG) { // // Set the foreground and background colors to use for 1 BPP // images. // GrContextForegroundSet(&sCtx, pPush->ui32TextColor); GrContextBackgroundSet(&sCtx, ((pPush->ui32Style & PB_STYLE_PRESSED) ? pPush->ui32PressFillColor : pPush->ui32FillColor)); // // Get the image to be drawn. // pui8Image = (((pPush->ui32Style & PB_STYLE_PRESSED) && pPush->pui8PressImage) ? pPush->pui8PressImage : pPush->pui8Image); // // Draw the image centered in the push button. // GrImageDraw(&sCtx, pui8Image, i32X - (GrImageWidthGet(pui8Image) / 2), i32Y - (GrImageHeightGet(pui8Image) / 2)); } // // See if the push button text style is selected. // if(pPush->ui32Style & PB_STYLE_TEXT) { // // Draw the text centered in the middle of the push button. // GrContextFontSet(&sCtx, pPush->psFont); GrContextForegroundSet(&sCtx, pPush->ui32TextColor); GrContextBackgroundSet(&sCtx, ((pPush->ui32Style & PB_STYLE_PRESSED) ? pPush->ui32PressFillColor : pPush->ui32FillColor)); GrStringDrawCentered(&sCtx, pPush->pcText, -1, i32X, i32Y, pPush->ui32Style & PB_STYLE_TEXT_OPAQUE); } } } //***************************************************************************** // //! Handles pointer events for a circular push button. //! //! \param psWidget is a pointer to the push button widget. //! \param ui32Msg is the pointer event message. //! \param i32X is the X coordinate of the pointer event. //! \param i32Y is the Y coordinate of the pointer event. //! //! This function processes pointer event messages for a circular push button. //! This is called in response to a \b #WIDGET_MSG_PTR_DOWN, //! \b #WIDGET_MSG_PTR_MOVE, and \b #WIDGET_MSG_PTR_UP messages. //! //! If the \b #WIDGET_MSG_PTR_UP message is received with a position within the //! extents of the push button, the push button's OnClick callback function is //! called. //! //! \return Returns 1 if the coordinates are within the extents of the push //! button and 0 otherwise. // //***************************************************************************** static int32_t CircularButtonClick(tWidget *psWidget, uint32_t ui32Msg, int32_t i32X, int32_t i32Y) { tPushButtonWidget *pPush; int32_t i32Xc, i32Yc, i32R; // // Check the arguments. // ASSERT(psWidget); // // Convert the generic widget pointer into a push button widget pointer. // pPush = (tPushButtonWidget *)psWidget; // // See if this is a pointer up message. // if(ui32Msg == WIDGET_MSG_PTR_UP) { // // Indicate that this push button is no longer pressed. // pPush->ui32Style &= ~(PB_STYLE_PRESSED); // // If filling is enabled for this push button, or if an image is being // used and a pressed button image is provided, then redraw the push // button to show it in its non-pressed state. // if((pPush->ui32Style & PB_STYLE_FILL) || ((pPush->ui32Style & PB_STYLE_IMG) && pPush->pui8PressImage)) { CircularButtonPaint(psWidget); } } // // Get the radius of the circular push button, along with the X and Y // coordinates for its center. // i32R = (psWidget->sPosition.i16XMax - psWidget->sPosition.i16XMin + 1) / 2; i32Xc = psWidget->sPosition.i16XMin + i32R; i32Yc = psWidget->sPosition.i16YMin + i32R; // // See if the given coordinates are within the radius of the push button. // if((((i32X - i32Xc) * (i32X - i32Xc)) + ((i32Y - i32Yc) * (i32Y - i32Yc))) <= (i32R * i32R)) { // // See if this is a pointer down message. // if(ui32Msg == WIDGET_MSG_PTR_DOWN) { // // Indicate that this push button is pressed. // pPush->ui32Style |= PB_STYLE_PRESSED; // // If filling is enabled for this push button, or if an image is // being used and a pressed button image is provided, then redraw // the push button to show it in its pressed state. // if((pPush->ui32Style & PB_STYLE_FILL) || ((pPush->ui32Style & PB_STYLE_IMG) && pPush->pui8PressImage)) { CircularButtonPaint(psWidget); } } // // See if there is an OnClick callback for this widget. // if(pPush->pfnOnClick) { // // If the pointer was just pressed or if the pointer was released // and this button is set for release notification then call the // callback. // if(((ui32Msg == WIDGET_MSG_PTR_DOWN) && !(pPush->ui32Style & PB_STYLE_RELEASE_NOTIFY)) || ((ui32Msg == WIDGET_MSG_PTR_UP) && (pPush->ui32Style & PB_STYLE_RELEASE_NOTIFY))) { pPush->pfnOnClick(psWidget); } // // See if auto-repeat is enabled for this widget. // if(pPush->ui32Style & PB_STYLE_AUTO_REPEAT) { // // If the pointer was just pressed, reset the auto-repeat // count. // if(ui32Msg == WIDGET_MSG_PTR_DOWN) { pPush->ui32AutoRepeatCount = 0; } // // See if the pointer was moved. // else if(ui32Msg == WIDGET_MSG_PTR_MOVE) { // // Increment the auto-repeat count. // pPush->ui32AutoRepeatCount++; // // If the auto-repeat count exceeds the auto-repeat delay, // and it is a multiple of the auto-repeat rate, then // call the callback. // if((pPush->ui32AutoRepeatCount >= pPush->ui16AutoRepeatDelay) && (((pPush->ui32AutoRepeatCount - pPush->ui16AutoRepeatDelay) % pPush->ui16AutoRepeatRate) == 0)) { pPush->pfnOnClick(psWidget); } } } } // // These coordinates are within the extents of the push button widget. // return(1); } // // These coordinates are not within the extents of the push button widget. // return(0); } //***************************************************************************** // //! Handles messages for a circular push button widget. //! //! \param psWidget is a pointer to the push button widget. //! \param ui32Msg is the message. //! \param ui32Param1 is the first parameter to the message. //! \param ui32Param2 is the second parameter to the message. //! //! This function receives messages intended for this push button widget and //! processes them accordingly. The processing of the message varies based on //! the message in question. //! //! Unrecognized messages are handled by calling WidgetDefaultMsgProc(). //! //! \return Returns a value appropriate to the supplied message. // //***************************************************************************** int32_t CircularButtonMsgProc(tWidget *psWidget, uint32_t ui32Msg, uint32_t ui32Param1, uint32_t ui32Param2) { // // Check the arguments. // ASSERT(psWidget); // // Determine which message is being sent. // switch(ui32Msg) { // // The widget paint request has been sent. // case WIDGET_MSG_PAINT: { // // Handle the widget paint request. // CircularButtonPaint(psWidget); // // Return one to indicate that the message was successfully // processed. // return(1); } // // One of the pointer requests has been sent. // case WIDGET_MSG_PTR_DOWN: case WIDGET_MSG_PTR_MOVE: case WIDGET_MSG_PTR_UP: { // // Handle the pointer request, returning the appropriate value. // return(CircularButtonClick(psWidget, ui32Msg, ui32Param1, ui32Param2)); } // // An unknown request has been sent. // default: { // // Let the default message handler process this message. // return(WidgetDefaultMsgProc(psWidget, ui32Msg, ui32Param1, ui32Param2)); } } } //***************************************************************************** // //! Initializes a circular push button widget. //! //! \param psWidget is a pointer to the push button widget to initialize. //! \param psDisplay is a pointer to the display on which to draw the push //! button. //! \param i32X is the X coordinate of the upper left corner of the push //! button. //! \param i32Y is the Y coordinate of the upper left corner of the push //! button. //! \param i32R is the radius of the push button. //! //! This function initializes the provided push button widget so that it will //! be a circular push button. //! //! \return None. // //***************************************************************************** void CircularButtonInit(tPushButtonWidget *psWidget, const tDisplay *psDisplay, int32_t i32X, int32_t i32Y, int32_t i32R) { uint32_t ui32Idx; // // Check the arguments. // ASSERT(psWidget); ASSERT(psDisplay); // // Clear out the widget structure. // for(ui32Idx = 0; ui32Idx < sizeof(tPushButtonWidget); ui32Idx += 4) { ((uint32_t *)psWidget)[ui32Idx / 4] = 0; } // // Set the size of the push button widget structure. // psWidget->sBase.i32Size = sizeof(tPushButtonWidget); // // Mark this widget as fully disconnected. // psWidget->sBase.psParent = 0; psWidget->sBase.psNext = 0; psWidget->sBase.psChild = 0; // // Save the display pointer. // psWidget->sBase.psDisplay = psDisplay; // // Set the extents of this circular push button. // psWidget->sBase.sPosition.i16XMin = i32X - i32R; psWidget->sBase.sPosition.i16YMin = i32Y - i32R; psWidget->sBase.sPosition.i16XMax = i32X + i32R; psWidget->sBase.sPosition.i16YMax = i32Y + i32R; // // Use the circular push button message handler to processes messages to // this push button. // psWidget->sBase.pfnMsgProc = CircularButtonMsgProc; } //***************************************************************************** // // Close the Doxygen group. //! @} // //*****************************************************************************
Java