repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
hesenrre/Forge
src/org/lainsoft/forge/view/form/Image_Tag.java
5662
/** * Image_Tag.java is part of Forge Project. * * Copyright 2004,2006 LainSoft Foundation, Israel Buitron * * You may distribute under the terms of either the GNU General Public * License or the Artistic License, as specified in the README file. * */ package org.lainsoft.forge.view.form; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; /** * TagLibrary represeting an input image_tag. * * @jsp.tag name="image_tag" * description="Image tag." */ public class Image_Tag extends GenericInputTag { /** * <code>align</code> tag attribute. */ private String align; /** * <code>alt</code> tag attribute. */ private String alt; /** * <code>disabled</code> tag attribute. */ private String disabled; /** * <code>size</code> tag attribute. */ private String size; /** * <code>src</code> tag attribute. */ private String src; /** * <code>value</code> tag attribute. */ private String value; /** * Gets <code>align</code> tag attribute. * @return <code>align</code> tag attribute value. * @jsp.attribute required="true" * rtexprvalue="true" */ public String getAlign() { return this.align; } /** * Sets <code>align</code> tag attribute. * If the new value is empty the attribute is assigned a new * <code>String</code>, if not the attribute is assigned * the new value. * @param align New <i>align</i> attribute value. */ public void setAlign(String align) { this.align = isEmpty(align) ? "" : align; } /** * Gets <code>alt</code> tag attribute. * @return <code>alt</code> tag attribute value. * @jsp.attribute required="true" * rtexprvalue="true" */ public String getAlt() { return this.alt; } /** * Sets <code>alt</code> tag attribute. * If the new value is empty the attribute is assigned a new * <code>String</code>, if not the attribute is assigned * the new value. * @param alt New <i>alt</i> attribute value. */ public void setAlt(String alt) { this.alt = isEmpty(alt) ? "" : alt; } /** * Gets <code>src</code> tag attribute. * @return <code>src</code> tag attribute value. * @jsp.attribute required="true" * rtexprvalue="true" */ public String getSrc() { return this.src; } /** * Sets <code>src</code> tag attribute. * If the new value is empty the attribute is assigned a new * <code>String</code>, if not the attribute is assigned * the new value. * @param src New <i>src</i> attribute value. */ public void setSrc(String src) { this.src = isEmpty(src) ? "" : src.trim(); } /** * Gets <code>disabled</code> tag attribute. * @return <code>disabled</code> tag attribute value. * @jsp.attribute required="false" * rtexprvalue="true" */ public String getDisabled(){ return disabled; } /** * Sets <code>disabled</code> tag attribute. * @param disabled New <i>disabled</i> attribute value. */ public void setDisabled(String disabled){ boolean d = (new Boolean(disabled)).booleanValue(); this.disabled = !d ? "" : Boolean.toString(d) ; } /** * Gets <code>size</code> tag attribute. * @return <code>size</code> tag attribute value. * @jsp.attribute required="false" * rtexprvalue="true" */ public String getSize() { return this.size; } /** * Sets <code>size</code> tag attribute. * @param size New <i>size</i> attribute value. */ public void setSize(String size) { try { int i = (new Integer(size)).intValue(); this.size = (i>=0 ? Integer.toString(i) : ""); } catch(NumberFormatException e) { this.size = ""; } } /** * Gets <code>value</code> tag attribute. * @return <code>value</code> tag attribute value. * @jsp.attribute required="false" * rtexprvalue="true" */ public String getValue() { return this.value; } /** * Sets <code>value</code> tag attribute. * If the new value is empty the attribute is assigned a new * <code>String</code>, if not the attribute is assigned * the new value. * @param value New <i>value</i> attribute value. */ public void setValue(String value) { this.value = isEmpty(value) ? "" : value; } /** * Gets all attributes and their values. * If one attribute is not valued (null ore empty) it is not * included in the list. * @return <code>String</code> with all valued attributes. */ public String getModifiers() { return super.getModifiers() + (isEmpty(src) ? "" : "src=\'" + src + "\' ") + (isEmpty(alt) ? "" : "alt=\'" + alt + "\' ") + (isEmpty(align) ? "": "align=\'" + align + "\' ") + (isEmpty(disabled) ? "" : "disabled ") + (isEmpty(size) ? "" : "size=\'" + size + "\' ") + (isEmpty(value) ? "": "value=\'" + value + "\' "); } public int doStartTag(){ JspWriter writer = pageContext.getOut(); try{ render_tag("<input type=\'image\' " + this.getModifiers() + ">"); } catch(IOException ioe){ ioe.printStackTrace(); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } }
gpl-2.0
trife/Coordinate
app/src/main/java/org/wheatgenetics/coordinate/model/GridModel.java
5679
package org.wheatgenetics.coordinate.model; /** * Uses: * androidx.annotation.IntRange * androidx.annotation.Nullable * androidx.annotation.RestrictTo * androidx.annotation.RestrictTo.Scope * * org.wheatgenetics.androidlibrary.Utils * * org.wheatgenetics.coordinate.Utils * * org.wheatgenetics.coordinate.optionalField.NonNullOptionalFields * * org.wheatgenetics.coordinate.model.Model */ public class GridModel extends org.wheatgenetics.coordinate.model.Model { // region Fields @androidx.annotation.IntRange(from = 1) private final long templateId; @androidx.annotation.IntRange(from = 0) private final long projectId ; private final java.lang.String person ; @androidx.annotation.IntRange(from = 0) private int activeRow, activeCol; @androidx.annotation.Nullable private final org.wheatgenetics.coordinate.optionalField.NonNullOptionalFields nonNullOptionalFieldsInstance; @androidx.annotation.IntRange(from = 0) private final long timestamp; // endregion // region Constructors /** Used by first JoinedGridModel constructor. */ @androidx.annotation.RestrictTo(androidx.annotation.RestrictTo.Scope.SUBCLASSES) GridModel( @androidx.annotation.IntRange(from = 1) final long templateId, @androidx.annotation.IntRange(from = 0) final long projectId , final java.lang.String person , @androidx.annotation.Nullable final org.wheatgenetics.coordinate.optionalField.NonNullOptionalFields optionalFields) { super(); this.templateId = org.wheatgenetics.coordinate.model.Model.valid(templateId); this.projectId = org.wheatgenetics.coordinate.model.Model.illegal(projectId) ? 0 : projectId; this.person = person; this.activeRow = this.activeCol = 0; this.nonNullOptionalFieldsInstance = optionalFields ; this.timestamp = java.lang.System.currentTimeMillis(); } /** Used by second JoinedGridModel constructor. */ @androidx.annotation.RestrictTo(androidx.annotation.RestrictTo.Scope.SUBCLASSES) GridModel( @androidx.annotation.IntRange(from = 1) final long id , @androidx.annotation.IntRange(from = 1) final long templateId , @androidx.annotation.IntRange(from = 0) final long projectId , final java.lang.String person , @androidx.annotation.IntRange(from = 0) final int activeRow , @androidx.annotation.IntRange(from = 0) final int activeCol , @androidx.annotation.Nullable java.lang.String optionalFields , @androidx.annotation.IntRange(from = 0) final long timestamp ) { super(id); this.templateId = org.wheatgenetics.coordinate.model.Model.valid(templateId); this.projectId = org.wheatgenetics.coordinate.model.Model.illegal(projectId) ? 0 : projectId; this.person = person; this.setActiveRow(activeRow); this.setActiveCol(activeCol); if (null != optionalFields) optionalFields = optionalFields.trim(); this.nonNullOptionalFieldsInstance = null == optionalFields ? null : optionalFields.equals("") ? null : new org.wheatgenetics.coordinate.optionalField.NonNullOptionalFields(optionalFields); this.timestamp = timestamp; } // endregion // region Package Methods @androidx.annotation.RestrictTo(androidx.annotation.RestrictTo.Scope.SUBCLASSES) void setActiveRow(@androidx.annotation.IntRange(from = 0) final int activeRow) { this.activeRow = org.wheatgenetics.coordinate.Utils.valid(activeRow,0); } @androidx.annotation.RestrictTo(androidx.annotation.RestrictTo.Scope.SUBCLASSES) void setActiveCol(@androidx.annotation.IntRange(from = 0) final int activeCol) { this.activeCol = org.wheatgenetics.coordinate.Utils.valid(activeCol,0); } // endregion // region Public Methods @androidx.annotation.IntRange(from = 1) public long getTemplateId() { return this.templateId; } @androidx.annotation.IntRange(from = 0) public long getProjectId () { return this.projectId ; } public java.lang.String getPerson() { return this.person; } @androidx.annotation.IntRange(from = 0) public int getActiveRow() { return this.activeRow; } @androidx.annotation.IntRange(from = 0) public int getActiveCol() { return this.activeCol; } @androidx.annotation.IntRange(from = 0) public long getTimestamp() { return this.timestamp; } public java.lang.CharSequence getFormattedTimestamp() { return org.wheatgenetics.androidlibrary.Utils.formatDate(this.getTimestamp()); } // region optionalFields Public Methods @androidx.annotation.Nullable public org.wheatgenetics.coordinate.optionalField.NonNullOptionalFields optionalFields() { return this.nonNullOptionalFieldsInstance; } @androidx.annotation.Nullable public java.lang.String optionalFieldsAsJson() { return null == this.nonNullOptionalFieldsInstance ? null : this.nonNullOptionalFieldsInstance.toJson(); } @androidx.annotation.Nullable public java.lang.String getFirstOptionalFieldDatedValue() { return null == this.nonNullOptionalFieldsInstance ? null : this.nonNullOptionalFieldsInstance.getDatedFirstValue(); } // endregion // endregion }
gpl-2.0
SkidJava/BaseClient
lucid_1.8.8/org/newdawn/slick/TrueTypeFont.java
11456
package org.newdawn.slick; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.newdawn.slick.opengl.GLUtils; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.renderer.Renderer; import org.newdawn.slick.opengl.renderer.SGL; import org.newdawn.slick.util.BufferedImageUtil; /** * A TrueType font implementation for Slick * * @author James Chambers (Jimmy) * @author Jeremy Adams (elias4444) * @author Kevin Glass (kevglass) * @author Peter Korzuszek (genail) */ public class TrueTypeFont implements org.newdawn.slick.Font { /** The renderer to use for all GL operations */ private static final SGL GL = Renderer.get(); /** Array that holds necessary information about the font characters */ private IntObject[] charArray = new IntObject[256]; /** Map of user defined font characters (Character <-> IntObject) */ private Map customChars = new HashMap(); /** Boolean flag on whether AntiAliasing is enabled or not */ private boolean antiAlias; /** Font's size */ private int fontSize = 0; /** Font's height */ private int fontHeight = 0; /** Texture used to cache the font 0-255 characters */ private Texture fontTexture; /** Default font texture width */ private int textureWidth = 512; /** Default font texture height */ private int textureHeight = 512; /** A reference to Java's AWT Font that we create our font texture from */ private java.awt.Font font; /** The font metrics for our Java AWT font */ private FontMetrics fontMetrics; /** * This is a special internal class that holds our necessary information for * the font characters. This includes width, height, and where the character * is stored on the font texture. */ private class IntObject { /** Character's width */ public int width; /** Character's height */ public int height; /** Character's stored x position */ public int storedX; /** Character's stored y position */ public int storedY; } /** * Constructor for the TrueTypeFont class Pass in the preloaded standard * Java TrueType font, and whether you want it to be cached with * AntiAliasing applied. * * @param font * Standard Java AWT font * @param antiAlias * Whether or not to apply AntiAliasing to the cached font * @param additionalChars * Characters of font that will be used in addition of first 256 (by unicode). */ public TrueTypeFont(java.awt.Font font, boolean antiAlias, char[] additionalChars) { GLUtils.checkGLContext(); this.font = font; this.fontSize = font.getSize(); this.antiAlias = antiAlias; createSet( additionalChars ); } /** * Constructor for the TrueTypeFont class Pass in the preloaded standard * Java TrueType font, and whether you want it to be cached with * AntiAliasing applied. * * @param font * Standard Java AWT font * @param antiAlias * Whether or not to apply AntiAliasing to the cached font */ public TrueTypeFont(java.awt.Font font, boolean antiAlias) { this( font, antiAlias, null ); } /** * Create a standard Java2D BufferedImage of the given character * * @param ch * The character to create a BufferedImage for * * @return A BufferedImage containing the character */ private BufferedImage getFontImage(char ch) { // Create a temporary image to extract the character's size BufferedImage tempfontImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) tempfontImage.getGraphics(); if (antiAlias == true) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } g.setFont(font); fontMetrics = g.getFontMetrics(); int charwidth = fontMetrics.charWidth(ch); if (charwidth <= 0) { charwidth = 1; } int charheight = fontMetrics.getHeight(); if (charheight <= 0) { charheight = fontSize; } // Create another image holding the character we are creating BufferedImage fontImage; fontImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB); Graphics2D gt = (Graphics2D) fontImage.getGraphics(); if (antiAlias == true) { gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } gt.setFont(font); gt.setColor(Color.WHITE); int charx = 0; int chary = 0; gt.drawString(String.valueOf(ch), (charx), (chary) + fontMetrics.getAscent()); return fontImage; } /** * Create and store the font * * @param customCharsArray Characters that should be also added to the cache. */ private void createSet( char[] customCharsArray ) { // If there are custom chars then I expand the font texture twice if (customCharsArray != null && customCharsArray.length > 0) { textureWidth *= 2; } // In any case this should be done in other way. Texture with size 512x512 // can maintain only 256 characters with resolution of 32x32. The texture // size should be calculated dynamicaly by looking at character sizes. try { BufferedImage imgTemp = new BufferedImage(textureWidth, textureHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) imgTemp.getGraphics(); g.setColor(new Color(255,255,255,1)); g.fillRect(0,0,textureWidth,textureHeight); int rowHeight = 0; int positionX = 0; int positionY = 0; int customCharsLength = ( customCharsArray != null ) ? customCharsArray.length : 0; for (int i = 0; i < 256 + customCharsLength; i++) { // get 0-255 characters and then custom characters char ch = ( i < 256 ) ? (char) i : customCharsArray[i-256]; BufferedImage fontImage = getFontImage(ch); IntObject newIntObject = new IntObject(); newIntObject.width = fontImage.getWidth(); newIntObject.height = fontImage.getHeight(); if (positionX + newIntObject.width >= textureWidth) { positionX = 0; positionY += rowHeight; rowHeight = 0; } newIntObject.storedX = positionX; newIntObject.storedY = positionY; if (newIntObject.height > fontHeight) { fontHeight = newIntObject.height; } if (newIntObject.height > rowHeight) { rowHeight = newIntObject.height; } // Draw it here g.drawImage(fontImage, positionX, positionY, null); positionX += newIntObject.width; if( i < 256 ) { // standard characters charArray[i] = newIntObject; } else { // custom characters customChars.put( new Character( ch ), newIntObject ); } fontImage = null; } fontTexture = BufferedImageUtil .getTexture(font.toString(), imgTemp); } catch (IOException e) { System.err.println("Failed to create font."); e.printStackTrace(); } } /** * Draw a textured quad * * @param drawX * The left x position to draw to * @param drawY * The top y position to draw to * @param drawX2 * The right x position to draw to * @param drawY2 * The bottom y position to draw to * @param srcX * The left source x position to draw from * @param srcY * The top source y position to draw from * @param srcX2 * The right source x position to draw from * @param srcY2 * The bottom source y position to draw from */ private void drawQuad(float drawX, float drawY, float drawX2, float drawY2, float srcX, float srcY, float srcX2, float srcY2) { float DrawWidth = drawX2 - drawX; float DrawHeight = drawY2 - drawY; float TextureSrcX = srcX / textureWidth; float TextureSrcY = srcY / textureHeight; float SrcWidth = srcX2 - srcX; float SrcHeight = srcY2 - srcY; float RenderWidth = (SrcWidth / textureWidth); float RenderHeight = (SrcHeight / textureHeight); GL.glTexCoord2f(TextureSrcX, TextureSrcY); GL.glVertex2f(drawX, drawY); GL.glTexCoord2f(TextureSrcX, TextureSrcY + RenderHeight); GL.glVertex2f(drawX, drawY + DrawHeight); GL.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY + RenderHeight); GL.glVertex2f(drawX + DrawWidth, drawY + DrawHeight); GL.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY); GL.glVertex2f(drawX + DrawWidth, drawY); } /** * Get the width of a given String * * @param whatchars * The characters to get the width of * * @return The width of the characters */ public int getWidth(String whatchars) { int totalwidth = 0; IntObject intObject = null; int currentChar = 0; for (int i = 0; i < whatchars.length(); i++) { currentChar = whatchars.charAt(i); if (currentChar < 256) { intObject = charArray[currentChar]; } else { intObject = (IntObject)customChars.get( new Character( (char) currentChar ) ); } if( intObject != null ) totalwidth += intObject.width; } return totalwidth; } /** * In this case equal to {@link org.newdawn.slick.Font#getLogicalWidth(String)} * @see org.newdawn.slick.Font#getLogicalWidth(String) */ public int getLogicalWidth(String str) { return getWidth(str); } /** * Get the font's height * * @return The height of the font */ public int getHeight() { return fontHeight; } /** * Get the height of a String * * @return The height of a given string */ public int getHeight(String HeightString) { return fontHeight; } /** * Get the font's line height * * @return The line height of the font */ public int getLineHeight() { return fontHeight; } /** * Draw a string * * @param x * The x position to draw the string * @param y * The y position to draw the string * @param whatchars * The string to draw * @param color * The color to draw the text */ public void drawString(float x, float y, String whatchars, org.newdawn.slick.Color color) { drawString(x,y,whatchars,color,0,whatchars.length()-1); } /** * @see Font#drawString(float, float, String, org.newdawn.slick.Color, int, int) */ public void drawString(float x, float y, String whatchars, org.newdawn.slick.Color color, int startIndex, int endIndex) { color.bind(); fontTexture.bind(); IntObject intObject = null; int charCurrent; GL.glBegin(SGL.GL_QUADS); int totalwidth = 0; for (int i = 0; i < whatchars.length(); i++) { charCurrent = whatchars.charAt(i); if (charCurrent < 256) { intObject = charArray[charCurrent]; } else { intObject = (IntObject)customChars.get( new Character( (char) charCurrent ) ); } if( intObject != null ) { if ((i >= startIndex) || (i <= endIndex)) { drawQuad((x + totalwidth), y, (x + totalwidth + intObject.width), (y + intObject.height), intObject.storedX, intObject.storedY, intObject.storedX + intObject.width, intObject.storedY + intObject.height); } totalwidth += intObject.width; } } GL.glEnd(); } /** * Draw a string * * @param x * The x position to draw the string * @param y * The y position to draw the string * @param whatchars * The string to draw */ public void drawString(float x, float y, String whatchars) { drawString(x, y, whatchars, org.newdawn.slick.Color.white); } }
gpl-2.0
s2sprodotti/SDS
SistemaDellaSicurezza/src/com/apconsulting/luna/ejb/Nazionalita/Nazionalita_Names_View.java
1655
/** ======================================================================== */ /** */ /** @copyright Copyright (c) 2010-2015, S2S s.r.l. */ /** @license http://www.gnu.org/licenses/gpl-2.0.html GNU Public License v.2 */ /** @version 6.0 */ /** This file is part of SdS - Sistema della Sicurezza . */ /** SdS - Sistema della Sicurezza 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. */ /** SdS - Sistema della Sicurezza 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 SdS - Sistema della Sicurezza . If not, see <http://www.gnu.org/licenses/gpl-2.0.html> GNU Public License v.2 */ /** */ /** ======================================================================== */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.apconsulting.luna.ejb.Nazionalita; /** * * @author Dario */ public class Nazionalita_Names_View implements java.io.Serializable { public long COD_STA; public String NOM_STA; // public String IMG_NAZ; }
gpl-2.0
easyxu/toolkit-sandbox
toolkit-sandbox-common/src/main/java/com/phoenix/common/resource/Resource.java
410
package com.phoenix.common.resource; import java.io.File; import java.io.IOException; import java.net.URL; public interface Resource extends InputStreamSource{ boolean exists(); boolean isOpen(); URL getURL() throws IOException; File getFile() throws IOException; Resource createRelative(String relativePath) throws IOException; String getFilename(); String getDescription(); }
gpl-2.0
smeny/JPC
src/main/java/com/github/smeny/jpc/emulator/pci/peripheral/EthernetCard.java
38361
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Release Version 2.4 A project from the Physics Dept, The University of Oxford Copyright (C) 2007-2010 The University of Oxford This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ Conceived and Developed by: Rhys Newman, Ian Preston, Chris Dennis End of licence header */ package com.github.smeny.jpc.emulator.pci.peripheral; import com.github.smeny.jpc.emulator.pci.*; import com.github.smeny.jpc.emulator.motherboard.IOPortHandler; import com.github.smeny.jpc.emulator.AbstractHardwareComponent; import java.io.*; import java.net.*; import java.util.Random; import java.util.logging.*; import com.github.smeny.jpc.support.*; /** Realtek 8029 (AS) Emulation * * based on the Bochs ne2000 emulation * @author Chris Dennis * @author Ian Preston */ public class EthernetCard extends AbstractPCIDevice { private static final Logger LOGGING = Logger.getLogger(EthernetCard.class.getName()); private static final int IRQ = 9; //Static Device Constants private static final int MAX_ETH_FRAME_SIZE = 1514; private static final int E8390_CMD = 0x00; // The command register (for all pages) */ /* Page 0 register offsets. */ private static final int EN0_CLDALO = 0x01; // Low byte of current local dma addr RD */ private static final int EN0_STARTPG = 0x01; // Starting page of ring bfr WR */ private static final int EN0_CLDAHI = 0x02; // High byte of current local dma addr RD */ private static final int EN0_STOPPG = 0x02; // Ending page +1 of ring bfr WR */ private static final int EN0_BOUNDARY = 0x03; // Boundary page of ring bfr RD WR */ private static final int EN0_TSR = 0x04; // Transmit status reg RD */ private static final int EN0_TPSR = 0x04; // Transmit starting page WR */ private static final int EN0_NCR = 0x05; // Number of collision reg RD */ private static final int EN0_TCNTLO = 0x05; // Low byte of tx byte count WR */ private static final int EN0_FIFO = 0x06; // FIFO RD */ private static final int EN0_TCNTHI = 0x06; // High byte of tx byte count WR */ private static final int EN0_ISR = 0x07; // Interrupt status reg RD WR */ private static final int EN0_CRDALO = 0x08; // low byte of current remote dma address RD */ private static final int EN0_RSARLO = 0x08; // Remote start address reg 0 */ private static final int EN0_CRDAHI = 0x09; // high byte, current remote dma address RD */ private static final int EN0_RSARHI = 0x09; // Remote start address reg 1 */ private static final int EN0_ID0 = 0x0a; //RTL 8029 ID0 private static final int EN0_ID1 = 0x0b; //RTL 8029 ID1 private static final int EN0_RCNTLO = 0x0a; // Remote byte count reg WR */ private static final int EN0_RCNTHI = 0x0b; // Remote byte count reg WR */ private static final int EN0_RSR = 0x0c; // rx status reg RD */ private static final int EN0_RXCR = 0x0c; // RX configuration reg WR */ private static final int EN0_TXCR = 0x0d; // TX configuration reg WR */ private static final int EN0_COUNTER0 = 0x0d; // Rcv alignment error counter RD */ private static final int EN0_DCFG = 0x0e; // Data configuration reg WR */ private static final int EN0_COUNTER1 = 0x0e; // Rcv CRC error counter RD */ private static final int EN0_IMR = 0x0f; // Interrupt mask reg WR */ private static final int EN0_COUNTER2 = 0x0f; // Rcv missed frame error counter RD */ private static final int EN1_PHYS = 0x11; private static final int EN1_CURPAG = 0x17; private static final int EN1_MULT = 0x18; /* Register accessed at EN_CMD, the 8390 base addr. */ private static final byte E8390_STOP = (byte) 0x01; // Stop and reset the chip */ private static final byte E8390_START = (byte) 0x02; // Start the chip, clear reset */ private static final byte E8390_TRANS = (byte) 0x04; // Transmit a frame */ private static final byte E8390_RREAD = (byte) 0x08; // Remote read */ private static final byte E8390_RWRITE = (byte) 0x10; // Remote write */ private static final byte E8390_NODMA = (byte) 0x20; // Remote DMA */ private static final byte E8390_PAGE0 = (byte) 0x00; // Select page chip registers */ private static final byte E8390_PAGE1 = (byte) 0x40; // using the two high-order bits */ private static final byte E8390_PAGE2 = (byte) 0x80; // Page 3 is invalid. */ /* Bits in EN0_ISR - Interrupt status register */ private static final byte ENISR_RX = (byte) 0x01; // Receiver, no error */ private static final byte ENISR_TX = (byte) 0x02; // Transmitter, no error */ private static final byte ENISR_RX_ERR = (byte) 0x04; // Receiver, with error */ private static final byte ENISR_TX_ERR = (byte) 0x08; // Transmitter, with error */ private static final byte ENISR_OVER = (byte) 0x10; // Receiver overwrote the ring */ private static final byte ENISR_COUNTERS = (byte) 0x20; // Counters need emptying */ private static final byte ENISR_RDC = (byte) 0x40; // remote dma complete */ private static final byte ENISR_RESET = (byte) 0x80; // Reset completed */ private static final byte ENISR_ALL = (byte) 0x3f; // Interrupts we will enable */ /* Bits in received packet status byte and EN0_RSR*/ private static final byte ENRSR_RXOK = (byte) 0x01; // Received a good packet */ private static final byte ENRSR_CRC = (byte) 0x02; // CRC error */ private static final byte ENRSR_FAE = (byte) 0x04; // frame alignment error */ private static final byte ENRSR_FO = (byte) 0x08; // FIFO overrun */ private static final byte ENRSR_MPA = (byte) 0x10; // missed pkt */ private static final byte ENRSR_PHY = (byte) 0x20; // physical/multicast address */ private static final byte ENRSR_DIS = (byte) 0x40; // receiver disable. set in monitor mode */ private static final byte ENRSR_DEF = (byte) 0x80; // deferring */ /* Transmitted packet status, EN0_TSR. */ private static final byte ENTSR_PTX = (byte) 0x01; // Packet transmitted without error */ private static final byte ENTSR_ND = (byte) 0x02; // The transmit wasn't deferred. */ private static final byte ENTSR_COL = (byte) 0x04; // The transmit collided at least once. */ private static final byte ENTSR_ABT = (byte) 0x08; // The transmit collided 16 times, and was deferred. */ private static final byte ENTSR_CRS = (byte) 0x10; // The carrier sense was lost. */ private static final byte ENTSR_FU = (byte) 0x20; // A "FIFO underrun" occurred during transmit. */ private static final byte ENTSR_CDH = (byte) 0x40; // The collision detect "heartbeat" signal was lost. */ private static final byte ENTSR_OWC = (byte) 0x80; // There was an out-of-window collision. */ private static final int NE2000_PMEM_SIZE = (32 * 1024); private static final int NE2000_PMEM_START = (16 * 1024); private static final int NE2000_PMEM_END = (NE2000_PMEM_SIZE + NE2000_PMEM_START); private static final int NE2000_MEM_SIZE = NE2000_PMEM_END; //Instance (State) Properties private byte command; private int start; private int stop; private byte boundary; private byte tsr; private byte tpsr; private byte txcr; private short tcnt; private short rcnt; private int rsar; private volatile int rxcr; private byte rsr; private volatile byte isr; private byte dcfg; private volatile byte imr; private byte phys[]; /* mac address */ private byte curpag; private byte mult[]; /* multicast mask array */ //public volatile int ethPacketsWaiting = 0; EthernetOutput outputDevice; private byte[] memory; private EthernetIORegion ioRegion; public EthernetCard() { this(null); } public EthernetCard(EthernetOutput output) { setIRQIndex(IRQ); putConfigWord(PCI_CONFIG_VENDOR_ID, (short) 0x10ec); // Realtek putConfigWord(PCI_CONFIG_DEVICE_ID, (short) 0x8029); // 8029 putConfigWord(PCI_CONFIG_CLASS_DEVICE, (short) 0x0200); // ethernet network controller putConfigByte(PCI_CONFIG_HEADER, (byte) 0x00); // header_type putConfigByte(PCI_CONFIG_INTERRUPT_PIN, (byte) 0x01); // interrupt pin 0 ioRegion = new EthernetIORegion(); outputDevice = output; if (outputDevice == null) outputDevice = new EthernetProxy(); memory = new byte[NE2000_MEM_SIZE]; phys = new byte[6]; mult = new byte[8]; //generate random MAC address Random random = new Random(); random.nextBytes(phys); phys[0] = (byte) 0x4a; phys[1] = (byte) 0x50; phys[2] = (byte) 0x43; System.arraycopy(phys, 0, memory, 0, phys.length); internalReset(); } public void saveState(DataOutput output) throws IOException { output.writeByte(command); output.writeInt(start); output.writeInt(stop); output.writeByte(boundary); output.writeByte(tsr); output.writeByte(tpsr); output.writeShort(tcnt); output.writeShort(rcnt); output.writeInt(rsar); output.writeByte(rsr); output.writeByte(isr); output.writeByte(dcfg); output.writeByte(imr); output.writeInt(phys.length); output.write(phys); output.writeByte(curpag); output.writeInt(mult.length); output.write(mult); output.writeInt(memory.length); output.write(memory); ioRegion.saveState(output); //dump output device //let's ignore it for now } public void loadState(DataInput input) throws IOException { command = input.readByte(); start = input.readInt(); stop = input.readInt(); boundary = input.readByte(); tsr = input.readByte(); tpsr = input.readByte(); tcnt = input.readShort(); rcnt = input.readShort(); rsar = input.readInt(); rsr = input.readByte(); isr = input.readByte(); dcfg = input.readByte(); imr = input.readByte(); int len = input.readInt(); phys = new byte[len]; input.readFully(phys, 0, len); curpag = input.readByte(); len = input.readInt(); mult = new byte[len]; input.readFully(mult, 0, len); len = input.readInt(); memory = new byte[len]; input.readFully(memory, 0, len); ioRegion.loadState(input); //load output device //apparently this is another whole kettle of fish... so let's ignore it } public void checkForPackets() { receivePacket(outputDevice.getPacket()); } public void setOutputDevice(EthernetOutput out) { this.outputDevice = out; } public void loadIOPorts(IOPortHandler ioportHandler, DataInput input) throws IOException { loadState(input); ioportHandler.registerIOPortCapable(ioRegion); } public void reset() { putConfigWord(PCI_CONFIG_VENDOR_ID, (short) 0x10ec); // Realtek putConfigWord(PCI_CONFIG_DEVICE_ID, (short) 0x8029); // 8029 putConfigWord(PCI_CONFIG_CLASS_DEVICE, (short) 0x0200); // ethernet network controller putConfigByte(PCI_CONFIG_HEADER, (byte) 0x00); // header_type putConfigByte(PCI_CONFIG_INTERRUPT_PIN, (byte) 0x01); // interrupt pin 0 memory = new byte[NE2000_MEM_SIZE]; // phys = new byte[6]; // mult = new byte[8]; internalReset(); super.reset(); } private void internalReset() { isr = ENISR_RESET; memory[0x0e] = (byte) 0x57; memory[0x0f] = (byte) 0x57; System.arraycopy(phys, 0, memory, 0, phys.length); for (int i = 15; i >= 0; i--) { memory[2 * i] = memory[i]; memory[2 * i + 1] = memory[i]; } } private void updateIRQ() { int interruptService = isr & imr; if (interruptService != 0) { this.getIRQBouncer().setIRQ(this, IRQ, 1); } else this.getIRQBouncer().setIRQ(this, IRQ, 0); } private int canReceive() { if (command == E8390_STOP) return 1; return 0; } //PCIDevice Methods //IOPort Registration Aids public IORegion[] getIORegions() { return new IORegion[] { ioRegion }; } public IORegion getIORegion(int index) { if (index == 0) return ioRegion; else return null; } class EthernetIORegion extends AbstractHardwareComponent implements IOPortIORegion { private int address; public EthernetIORegion() { address = -1; } public void saveState(DataOutput output) throws IOException { output.writeInt(address); } public void loadState(DataInput input) throws IOException { address = input.readInt(); } //IORegion Methods public int getAddress() { return address; } public long getSize() { return 0x100; } public int getType() { return PCI_ADDRESS_SPACE_IO; } public int getRegionNumber() { return 0; } public void setAddress(int address) { this.address = address; LOGGING.log(Level.FINE, "Ethernet IO address is "+Integer.toHexString(address)); } //IODevice Methods public void ioPortWrite8(int address, int data) { switch (address - this.getAddress()) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: EthernetCard.this.ioPortWrite(address, (byte) data); break; case 0x10: // May do a 16 bit write, so must only narrow to short EthernetCard.this.asicIOPortWriteByte(address, (short) data); break; case 0x1f: //this.resetIOPortWrite(address); //end of reset pulse break; default: //this is invalid, but happens under win 95 device detection break; } } public void ioPortWrite16(int address, int data) { switch (address - this.getAddress()) { case 0x10: case 0x11: EthernetCard.this.asicIOPortWriteWord(address, (short) data); break; default: // should do two byte access break; } } public void ioPortWrite32(int address, int data) { switch (address - this.getAddress()) { case 0x10: case 0x11: case 0x12: case 0x13: EthernetCard.this.asicIOPortWriteLong(address, data); break; default: break; } } public int ioPortRead8(int address) { switch (address - this.getAddress()) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: return EthernetCard.this.ioPortRead(address); case 0x10: return 0xffff & EthernetCard.this.asicIOPortReadByte(address); case 0x1f: return EthernetCard.this.resetIOPortRead(address); default: return (byte) 0xff; } } public int ioPortRead16(int address) { switch (address - this.getAddress()) { case 0x10: case 0x11: return EthernetCard.this.asicIOPortReadWord(address); default: return (short) 0xffff; //should do two byte access } } public int ioPortRead32(int address) { switch (address - this.getAddress()) { case 0x10: case 0x11: case 0x12: case 0x13: return EthernetCard.this.asicIOPortReadLong(address); default: return 0xffffffff; } } public int[] ioPortsRequested() { int addr = this.getAddress(); int[] temp = new int[32]; for (int i = 0; i < 32; i++) temp[i] = addr + i; return temp; } } private void ioPortWrite(int address, byte data) { address &= 0xf; if (address == E8390_CMD) { /* control register */ if ((data & 0x38) == 0) { System.out.println("Invalid DMA command"); data |= 0x20; } //test for s/w reset if ((data & 0x1) != 0) { isr |= ENISR_RESET; command |= E8390_STOP; } else { command &= ~E8390_STOP; } //update remote DMA command command = (byte) ((data & 0x38) | (command & ~0x38)); if (((command & E8390_START) == 0) && (0 != (data & E8390_START))) { isr = (byte) (isr & ~ENISR_RESET); } //set start, and page select command = (byte) ((command & ~0xc2) | (data & 0xc2)); //check for send packet command if ((command & 0x38) == 0x18) { //setup dma read from receive ring rsar = ((short) boundary) << 8; rcnt = (short) (2); System.out.println("After send packet command, setting rcnt to " + 2); } //check for start tx if ((0 != (data & E8390_TRANS)) && ((txcr & 0x6) != 0)) { int loop_control = (txcr & 0x6); if (loop_control != 2) { System.out.println("ETH: Loop mode " + (loop_control >> 1) + " not supported."); } else { byte[] packet = new byte[tcnt]; System.arraycopy(memory, (tpsr & 0xff ) << 8, packet, 0, tcnt); receivePacket(packet); } } else if (0 != (data & E8390_TRANS)) { if ((0 != (command & E8390_STOP)) || ((0 == (command & E8390_START)) && (!initialised()))) { if (tcnt == 0) { return; } throw new IllegalStateException("ETH0: command write, tx start, device in reset"); } if (tcnt == 0) { throw new IllegalStateException("ETH0: command - tx start, tx bytes == 0"); } //now send the packet command |= 0x4; int index = ((tpsr & 0xFF) << 8); outputDevice.sendPacket(memory, index, tcnt); /* signal end of transfer */ tsr = ENTSR_PTX; isr = (byte) (isr | ENISR_TX); this.updateIRQ(); //linux probes for an interrupt by setting up a remote dma read of 0 bytes //with remote dma completion interrupts enabled if ((rcnt == 0) && (0 != (command & E8390_START)) && ((command & 0x38) == 0x8)) { isr = (byte) (isr |ENISR_RDC); this.updateIRQ(); } } // /* test specific case: zero length transfer */ // if ((0 != (data & (E8390_RREAD | E8390_RWRITE))) && (rcnt == 0)) // { // check operators // isr = (byte) (isr | ENISR_RDC); // this.updateIRQ(); // } // if (0 != (data & E8390_TRANS)) // { // int index = ((tpsr & 0xFF) << 8); // outputDevice.sendPacket(memory, index, tcnt); // /* signal end of transfer */ // tsr = ENTSR_PTX; // isr = (byte) (isr | ENISR_TX); // this.updateIRQ(); // } } else { int page = command >> 6; int offset = address | (page << 4); switch (offset) { case EN0_STARTPG: start = data & 0xFF; break; case EN0_STOPPG: stop = data & 0xFF; break; case EN0_BOUNDARY: boundary = data; break; case EN0_TPSR: tpsr = data; break; case EN0_TCNTLO: tcnt = (short) ((tcnt & 0xff00) | data); break; case EN0_TCNTHI: tcnt = (short) ((tcnt & 0x00ff) | (((short) data) << 8)); break; case EN0_ISR: isr = (byte) (isr & ~(data & 0x7f)); this.updateIRQ(); break; case EN0_RSARLO: rsar = ((rsar & 0xff00) | data); break; case EN0_RSARHI: rsar = ((rsar & 0x00ff) | (data << 8)); break; case EN0_RCNTLO: rcnt = (short) ((rcnt & 0xff00) | data); break; case EN0_RCNTHI: rcnt = (short) ((rcnt & 0x00ff) | (((short) data) << 8)); break; case EN0_RXCR: if ((data & 0xc0) != 0) System.out.println("ETH: Reserved bits of rxcr set"); rxcr = data; break; case EN0_TXCR: if ((data & 0xe0) != 0) System.out.println("ETH: Reserved bits of txcr set"); //test loop mode (not supported) if ((data & 0x6) != 0) { System.out.println("ETH: Loop mode " + ((data & 0x6) >> 1) + " not supported."); txcr |= (data & 0x6); } else { txcr &= ~0x6; } //stop CRC if ((data & 0x1) != 0) throw new IllegalStateException("ETH: TCR write - CRC not supported"); //stop auto-transmit disable if ((data & 0x8) != 0) throw new IllegalStateException("ETH: TCR write - auto transmit disable not supported"); // should set txcr bit 4 here, but we don't use it break; case EN0_DCFG: dcfg = data; break; case EN0_IMR: imr = data; this.updateIRQ(); break; case EN1_PHYS: case EN1_PHYS + 1: case EN1_PHYS + 2: case EN1_PHYS + 3: case EN1_PHYS + 4: case EN1_PHYS + 5: phys[offset - EN1_PHYS] = data; if (offset == EN1_PHYS + 5) System.out.println("ETH: MAC address set to: " + Integer.toHexString(phys[0] & 0xFF) + Integer.toHexString(phys[1] & 0xFF) + Integer.toHexString(phys[2] & 0xFF) + Integer.toHexString(phys[3] & 0xFF) + Integer.toHexString(phys[4] & 0xFF) + Integer.toHexString(phys[5] & 0xFF)); break; case EN1_CURPAG: curpag = data; break; case EN1_MULT: case EN1_MULT + 1: case EN1_MULT + 2: case EN1_MULT + 3: case EN1_MULT + 4: case EN1_MULT + 5: case EN1_MULT + 6: case EN1_MULT + 7: mult[offset - EN1_MULT] = data; break; default: throw new IllegalStateException("ETH: invalid write address: " + Integer.toHexString(address) + "page: " + page); } } } private void asicIOPortWriteByte(int address, short data) { if (rcnt == 0) return; if (0 != (dcfg & 0x01)) { /* 16 bit access */ this.memoryWriteWord(rsar, data); this.dmaUpdate(2); } else { /* 8 bit access */ this.memoryWriteByte(rsar, (byte) data); this.dmaUpdate(1); } } private void asicIOPortWriteWord(int address, short data) { if (rcnt == 0) return; if (0 != (dcfg & 0x01)) { /* 16 bit access */ this.memoryWriteWord(rsar, data); this.dmaUpdate(2); } else { /* 8 bit access */ this.memoryWriteByte(rsar, (byte) data); this.dmaUpdate(1); } } private void asicIOPortWriteLong(int address, int data) { if (rcnt == 0) return; this.memoryWriteLong(rsar, data); this.dmaUpdate(4); } private byte ioPortRead(int address) { address &= 0xf; if (address == E8390_CMD) return command; int page = command >> 6; int offset = address | (page << 4); switch (offset) { case EN0_BOUNDARY: return boundary; case EN0_TSR: return tsr; case EN0_ISR: return isr; case EN0_RSARLO: return (byte) (rsar & 0x00ff); case EN0_RSARHI: return (byte) (rsar >> 8); case EN0_ID0: if (initialised()) return (byte) 0x50; else return (byte) 0xFF; case EN0_ID1: if (initialised()) return (byte) 0x43; else return (byte) 0xFF; case EN0_RSR: return rsr; case EN1_PHYS: case EN1_PHYS + 1: case EN1_PHYS + 2: case EN1_PHYS + 3: case EN1_PHYS + 4: case EN1_PHYS + 5: return phys[offset - EN1_PHYS]; case EN1_CURPAG: return curpag; case EN1_MULT: case EN1_MULT + 1: case EN1_MULT + 2: case EN1_MULT + 3: case EN1_MULT + 4: case EN1_MULT + 5: case EN1_MULT + 6: case EN1_MULT + 7: return mult[offset - EN1_MULT]; default: return 0x00; } } // this is the high 16 bytes of IO space - the low 16 are for the DS8390 private short asicIOPortReadByte(int address) { short ret; if (0 != (dcfg & 0x01)) { /* 16 bit access */ ret = this.memoryReadWord(rsar); this.dmaUpdate(2); } else { /* 8 bit access */ ret = (short) this.memoryReadByte(rsar); ret &= 0xff; this.dmaUpdate(1); } return ret; } private short asicIOPortReadWord(int address) { short ret; if (0 != (dcfg & 0x01)) { /* 16 bit access */ ret = this.memoryReadWord(rsar); this.dmaUpdate(2); } else { /* 8 bit access */ ret = (short) this.memoryReadByte(rsar); ret &= 0xff; this.dmaUpdate(1); } return ret; } private int asicIOPortReadLong(int address) { int ret = this.memoryReadLong(rsar); this.dmaUpdate(4); return ret; } private byte resetIOPortRead(int address) { this.internalReset(); return 0x00; } private void dmaUpdate(int length) { rsar += length; if (rsar == stop) rsar = start; if (rcnt <= length) { rcnt = (short) 0; /* signal end of transfer */ isr = (byte) (isr | ENISR_RDC); this.updateIRQ(); } else rcnt = (short) (rcnt - length); } private void memoryWriteByte(int address, byte data) { if (address >= NE2000_PMEM_START && address < NE2000_MEM_SIZE) memory[address] = data; else { System.out.println("Out of bounds ETH chip memory write: " + Integer.toHexString(address)); } } private void memoryWriteWord(int address, short data) { address &= ~1; if (address >= NE2000_PMEM_START && address < NE2000_MEM_SIZE) { memory[address] = (byte) data; memory[address + 1] = (byte) (data >> 8); } else { System.out.println("Out of bounds ETH chip memory write: " + Integer.toHexString(address)); } } private void memoryWriteLong(int address, int data) { address &= ~1; if (address >= NE2000_PMEM_START && address < NE2000_MEM_SIZE) { memory[address] = (byte) data; memory[address + 1] = (byte) (data >> 8); memory[address + 2] = (byte) (data >> 16); memory[address + 3] = (byte) (data >> 24); } else { System.out.println("Out of bounds ETH chip memory write: " + Integer.toHexString(address)); } } private byte memoryReadByte(int address) { if (address < 32 || (address >= NE2000_PMEM_START && address < NE2000_MEM_SIZE)) { return memory[address]; } else { System.out.println("Out of bounds ETH chip memory read: " + Integer.toHexString(address)); return (byte) 0xff; } } private short memoryReadWord(int address) { address &= ~1; if (address < 32 || (address >= NE2000_PMEM_START && address < NE2000_MEM_SIZE)) { short val = (short) (0xff & memory[address]); val |= memory[address + 1] << 8; return val; } else { System.out.println("Out of bounds ETH chip memory read: " + Integer.toHexString(address)); return (short) 0xffff; } } private int memoryReadLong(int address) { address &= ~1; if (address < 32 || (address >= NE2000_PMEM_START && address < NE2000_MEM_SIZE)) { int val = (0xff & memory[address]); val |= (0xff & memory[address + 1]) << 8; val |= (0xff & memory[address + 2]) << 16; val |= (0xff & memory[address + 3]) << 24; return val; } else { System.out.println("Out of bounds ETH chip memory read: " + Integer.toHexString(address)); return 0xffffffff; } } public void testPacket() { imr = (byte) 0xff; isr = (byte) (isr | ENISR_RX); this.updateIRQ(); } private int computeCRC(byte[] buf) { //based on FreeBSD int crc, carry, index = 0; byte b; int POLYNOMIAL = 0x04c11db6; crc = 0xFFFFFFFF; for (int i = 0; i < 6; i++) { b = buf[index++]; for (int j = 0; j < 8; j++) { carry = (((crc & 0x80000000L) != 0) ? 1 : 0) ^ (b & 0x01); crc = crc << 1; b = (byte) (b >>> 1); if (carry > 0) crc = ((crc ^ POLYNOMIAL) | carry); } } return crc >>> 26; } public static void printPacket(byte[] oldpacket, int offset, int length) { byte[] packet =new byte[length]; System.arraycopy(oldpacket, offset, packet, 0, length); for (int j = 0; j< packet.length / 16; j++) { for (int i=0; i< 16; i++) System.out.print(Integer.toHexString(packet[16*j + i] & 0xFF)); System.out.println(); } int remainder = packet.length % 16; if (remainder != 0) { for (int i=packet.length-remainder; i< packet.length; i++) System.out.print(Integer.toHexString(packet[i] & 0xFF)); System.out.println(); } } public void receivePacket(byte[] packet) { if (packet == null) return; int totalLen, index, mcastIdx; if ((command & E8390_STOP) == 1) { System.out.print("ETH told to stop"); return; } //check this if ((rxcr & 0x10) != 0) { System.out.println("Receiving packet in prom mode"); //promiscuous: receive all } else if ((packet[0] == 0xFF) && (packet[1] == 0xFF) && (packet[2] == 0xFF) && (packet[3] == 0xFF) && (packet[4] == 0xFF) && (packet[5] == 0xFF)) { //broadcast address if ((rxcr & 0x04) == 0) return; } else if ((packet[0] & 1) != 0) { //multicast //if ((rxcr & 0x08) == 0) // return; //mcastIdx = computeCRC(packet); //if ((mult[mcastIdx >>> 3] & (1 << (mcastIdx & 7))) == 0) // return; } else if ((memory[0] == packet[0]) && (memory[2] == packet[1]) && (memory[4] == packet[2]) && (memory[6] == packet[3]) && (memory[8] == packet[4]) && (memory[10] == packet[5])) { //this is us! } else { System.out.println("Weird ETH packet recieved"); printPacket(packet, 0, packet.length); return; } //if buffer is too small expand it!!!!!!!!!!!! // System.out.println("Packet got through"); index = (curpag & 0xFF) << 8; //4 bytes for header totalLen = packet.length + 4; /* address for next packet (4 bytes for CRC) */ int pages = (totalLen + 4 + 255)/256; int next = curpag + pages; // int avail; //don't emulate partial receives // if (avail < pages) // return; if (next >= stop) next -= (stop - start); //prepare packet header rsr = ENRSR_RXOK; // receive status //check this if ((packet[0] & 1) != 0) rsr |= ENRSR_PHY; memory[index] = 1;// (was rsr) if ((packet[0] & 1) != 0) memory[index] |= 0x20; memory[index + 1] = (byte) (next); memory[index + 2] = (byte) totalLen; memory[index + 3] = (byte) (totalLen >>> 8); index += 4; //write packet data if ((next > curpag) || (curpag + pages == stop)) { System.arraycopy(packet, 0, memory, index, packet.length); System.arraycopy(phys, 0, memory, index, 6); } else { int endSize = (stop - curpag) << 8; System.arraycopy(packet, 0, memory, index, endSize - 4); int startIndex = start * 256; System.arraycopy(packet, endSize -4, memory, startIndex, packet.length + 4 - (endSize - 4)); } curpag = (byte) next; //signal that we have a packet isr |= ENISR_RX; updateIRQ(); } private class DefaultOutput extends EthernetOutput { DataOutputStream dos; public void sendPacket(byte[] data, int offset, int length) { LOGGING.log(Level.FINE, "Sent packet on default output"); try { if (length <= 0) return; File file = new File("ethernetout.bin"); FileOutputStream fos = new FileOutputStream(file); dos = new DataOutputStream(fos); dos.write(data, offset, length); dos.close(); } catch (IOException e) { LOGGING.log(Level.INFO, "Error sending packet", e); } } public byte[] getPacket() { return null; } } }
gpl-2.0
rac021/blazegraph_1_5_3_cluster_2_nodes
bigdata-rdf/src/java/com/bigdata/rdf/sparql/ast/eval/SearchInSearchServiceFactory.java
24974
/** Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved. Contact: SYSTAP, LLC 2501 Calvert ST NW #106 Washington, DC 20008 licenses@systap.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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Created on Sep 9, 2011 */ package com.bigdata.rdf.sparql.ast.eval; import java.io.Serializable; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.openrdf.model.Literal; import org.openrdf.model.URI; import com.bigdata.bop.BOp; import com.bigdata.bop.BOpUtility; import com.bigdata.bop.IBindingSet; import com.bigdata.bop.IVariable; import com.bigdata.bop.Var; import com.bigdata.btree.IIndex; import com.bigdata.cache.ConcurrentWeakValueCacheWithTimeout; import com.bigdata.rdf.internal.IV; import com.bigdata.rdf.lexicon.ITextIndexer; import com.bigdata.rdf.lexicon.ITextIndexer.FullTextQuery; import com.bigdata.rdf.sparql.ast.ConstantNode; import com.bigdata.rdf.sparql.ast.GroupNodeBase; import com.bigdata.rdf.sparql.ast.IGroupMemberNode; import com.bigdata.rdf.sparql.ast.StatementPatternNode; import com.bigdata.rdf.sparql.ast.TermNode; import com.bigdata.rdf.sparql.ast.VarNode; import com.bigdata.rdf.sparql.ast.service.BigdataNativeServiceOptions; import com.bigdata.rdf.sparql.ast.service.BigdataServiceCall; import com.bigdata.rdf.sparql.ast.service.IServiceOptions; import com.bigdata.rdf.sparql.ast.service.ServiceCallCreateParams; import com.bigdata.rdf.sparql.ast.service.ServiceFactory; import com.bigdata.rdf.sparql.ast.service.ServiceNode; import com.bigdata.rdf.spo.ISPO; import com.bigdata.rdf.spo.SPOKeyOrder; import com.bigdata.rdf.store.AbstractTripleStore; import com.bigdata.rdf.store.BD; import com.bigdata.rdf.store.BDS; import com.bigdata.relation.accesspath.EmptyCloseableIterator; import com.bigdata.relation.accesspath.ThickCloseableIterator; import com.bigdata.search.Hiterator; import com.bigdata.search.IHit; import cutthecrap.utils.striterators.ICloseableIterator; /** * A factory for a "search in search" service. * It accepts a group that have a single triple pattern in it: * * service bd:searchInSearch { * ?s bd:searchInSearch "search" . * } * * This service will then use the full text index to filter out incoming * bindings for ?s that do not link to a Literal that is found via the full * text index with the supplied search string. If there are no incoming * bindings (or none that have ?s bound), this service will produce no output. */ public class SearchInSearchServiceFactory extends AbstractServiceFactoryBase { private static final Logger log = Logger .getLogger(SearchInSearchServiceFactory.class); /* * Note: This could extend the base class to allow for search service * configuration options. */ private final BigdataNativeServiceOptions serviceOptions; public SearchInSearchServiceFactory() { serviceOptions = new BigdataNativeServiceOptions(); // serviceOptions.setRunFirst(true); } @Override public BigdataNativeServiceOptions getServiceOptions() { return serviceOptions; } public BigdataServiceCall create(final ServiceCallCreateParams params) { if (params == null) throw new IllegalArgumentException(); final AbstractTripleStore store = params.getTripleStore(); if (store == null) throw new IllegalArgumentException(); final ServiceNode serviceNode = params.getServiceNode(); if (serviceNode == null) throw new IllegalArgumentException(); /* * Validate the search predicates for a given search variable. */ final Map<IVariable<?>, Map<URI, StatementPatternNode>> map = verifyGraphPattern( store, serviceNode.getGraphPattern()); if (map == null) throw new RuntimeException("Not a search request."); if (map.size() != 1) throw new RuntimeException( "Multiple search requests may not be combined."); final Map.Entry<IVariable<?>, Map<URI, StatementPatternNode>> e = map .entrySet().iterator().next(); final IVariable<?> searchVar = e.getKey(); final Map<URI, StatementPatternNode> statementPatterns = e.getValue(); validateSearch(searchVar, statementPatterns); /* * Create and return the ServiceCall object which will execute this * query. */ return new SearchCall(store, searchVar, statementPatterns, getServiceOptions()); } /** * Validate the search request. This looks for search magic predicates and * returns them all. It is an error if anything else is found in the group. * All such search patterns are reported back by this method, but the * service can only be invoked for one a single search variable at a time. * The caller will detect both the absence of any search and the presence of * more than one search and throw an exception. */ private Map<IVariable<?>, Map<URI, StatementPatternNode>> verifyGraphPattern( final AbstractTripleStore database, final GroupNodeBase<IGroupMemberNode> group) { // lazily allocate iff we find some search predicates in this group. Map<IVariable<?>, Map<URI, StatementPatternNode>> tmp = null; final int arity = group.arity(); for (int i = 0; i < arity; i++) { final BOp child = group.get(i); if (child instanceof GroupNodeBase<?>) { throw new RuntimeException("Nested groups are not allowed."); } if (child instanceof StatementPatternNode) { final StatementPatternNode sp = (StatementPatternNode) child; final TermNode p = sp.p(); if (!p.isConstant()) throw new RuntimeException("Expecting search predicate: " + sp); final URI uri = (URI) ((ConstantNode) p).getValue(); if (!uri.stringValue().startsWith(BDS.NAMESPACE)) throw new RuntimeException("Expecting search predicate: " + sp); /* * Some search predicate. */ if (!ASTSearchOptimizer.searchUris.contains(uri) && !BDS.SEARCH_IN_SEARCH.equals(uri)) { throw new RuntimeException("Unknown search predicate: " + uri); } final TermNode s = sp.s(); if (!s.isVariable()) throw new RuntimeException( "Subject of search predicate is constant: " + sp); final IVariable<?> searchVar = ((VarNode) s) .getValueExpression(); // Lazily allocate map. if (tmp == null) { tmp = new LinkedHashMap<IVariable<?>, Map<URI, StatementPatternNode>>(); } // Lazily allocate set for that searchVar. Map<URI, StatementPatternNode> statementPatterns = tmp .get(searchVar); if (statementPatterns == null) { tmp.put(searchVar, statementPatterns = new LinkedHashMap<URI, StatementPatternNode>()); } // Add search predicate to set for that searchVar. statementPatterns.put(uri, sp); } } return tmp; } /** * Validate the search. There must be exactly one {@link BD#SEARCH} * predicate. There should not be duplicates of any of the search predicates * for a given searchVar. */ private void validateSearch(final IVariable<?> searchVar, final Map<URI, StatementPatternNode> statementPatterns) { final Set<URI> uris = new LinkedHashSet<URI>(); for(StatementPatternNode sp : statementPatterns.values()) { final URI uri = (URI)(sp.p()).getValue(); if (!uris.add(uri)) throw new RuntimeException( "Search predicate appears multiple times for same search variable: predicate=" + uri + ", searchVar=" + searchVar); if (uri.equals(BDS.SEARCH_IN_SEARCH)) { assertObjectIsLiteral(sp); } else if (uri.equals(BDS.RELEVANCE) || uri.equals(BDS.RANK)) { assertObjectIsVariable(sp); } else if(uri.equals(BDS.MIN_RANK) || uri.equals(BDS.MAX_RANK)) { assertObjectIsLiteral(sp); } else if (uri.equals(BDS.MIN_RELEVANCE) || uri.equals(BDS.MAX_RELEVANCE)) { assertObjectIsLiteral(sp); } else if(uri.equals(BDS.MATCH_ALL_TERMS)) { assertObjectIsLiteral(sp); } else if(uri.equals(BDS.MATCH_EXACT)) { assertObjectIsLiteral(sp); } else if(uri.equals(BDS.SEARCH_TIMEOUT)) { assertObjectIsLiteral(sp); } else if(uri.equals(BDS.MATCH_REGEX)) { // a variable for the object is equivalent to regex = null // assertObjectIsLiteral(sp); } else { throw new AssertionError("Unverified search predicate: " + sp); } } if (!uris.contains(BDS.SEARCH_IN_SEARCH)) { throw new RuntimeException("Required search predicate not found: " + BDS.SUBJECT_SEARCH + " for searchVar=" + searchVar); } } private void assertObjectIsLiteral(final StatementPatternNode sp) { final TermNode o = sp.o(); if (!o.isConstant() || !(((ConstantNode) o).getValue() instanceof Literal)) { throw new IllegalArgumentException("Object is not literal: " + sp); } } private void assertObjectIsVariable(final StatementPatternNode sp) { final TermNode o = sp.o(); if (!o.isVariable()) { throw new IllegalArgumentException("Object must be variable: " + sp); } } /** * * Note: This has the {@link AbstractTripleStore} reference attached. This * is not a {@link Serializable} object. It MUST run on the query * controller. */ private static class SearchCall implements BigdataServiceCall { private final AbstractTripleStore store; private final IIndex osp; private final IServiceOptions serviceOptions; private final Literal query; private final IVariable<?>[] vars; private final Literal minRank; private final Literal maxRank; private final Literal minRelevance; private final Literal maxRelevance; private final boolean matchAllTerms; private final boolean matchExact; private final Literal searchTimeout; private final Literal matchRegex; public SearchCall( final AbstractTripleStore store, final IVariable<?> searchVar, final Map<URI, StatementPatternNode> statementPatterns, final IServiceOptions serviceOptions) { if(store == null) throw new IllegalArgumentException(); if(searchVar == null) throw new IllegalArgumentException(); if(statementPatterns == null) throw new IllegalArgumentException(); if(serviceOptions == null) throw new IllegalArgumentException(); this.store = store; this.osp = store.getSPORelation().getIndex(SPOKeyOrder.OSP); this.serviceOptions = serviceOptions; /* * Unpack the "search" magic predicate: * * [?searchVar bd:search objValue] */ final StatementPatternNode sp = statementPatterns.get(BDS.SEARCH_IN_SEARCH); query = (Literal) sp.o().getValue(); /* * Unpack the search service request parameters. */ IVariable<?> relVar = null; IVariable<?> rankVar = null; Literal minRank = null; Literal maxRank = null; Literal minRelevance = null; Literal maxRelevance = null; boolean matchAllTerms = false; boolean matchExact = false; Literal searchTimeout = null; Literal matchRegex = null; for (StatementPatternNode meta : statementPatterns.values()) { final URI p = (URI) meta.p().getValue(); final Literal oVal = meta.o().isConstant() ? (Literal) meta.o() .getValue() : null; final IVariable<?> oVar = meta.o().isVariable() ? (IVariable<?>) meta .o().getValueExpression() : null; if (BDS.RELEVANCE.equals(p)) { relVar = oVar; } else if (BDS.RANK.equals(p)) { rankVar = oVar; } else if (BDS.MIN_RANK.equals(p)) { minRank = (Literal) oVal; } else if (BDS.MAX_RANK.equals(p)) { maxRank = (Literal) oVal; } else if (BDS.MIN_RELEVANCE.equals(p)) { minRelevance = (Literal) oVal; } else if (BDS.MAX_RELEVANCE.equals(p)) { maxRelevance = (Literal) oVal; } else if (BDS.MATCH_ALL_TERMS.equals(p)) { matchAllTerms = ((Literal) oVal).booleanValue(); } else if (BDS.MATCH_EXACT.equals(p)) { matchExact = ((Literal) oVal).booleanValue(); } else if (BDS.SEARCH_TIMEOUT.equals(p)) { searchTimeout = (Literal) oVal; } else if (BDS.MATCH_REGEX.equals(p)) { matchRegex = (Literal) oVal; } } this.vars = new IVariable[] {// searchVar,// relVar == null ? Var.var() : relVar,// must be non-null. rankVar == null ? Var.var() : rankVar // must be non-null. }; this.minRank = minRank; this.maxRank = maxRank; this.minRelevance = minRelevance; this.maxRelevance = maxRelevance; this.matchAllTerms = matchAllTerms; this.matchExact = matchExact; this.searchTimeout = searchTimeout; this.matchRegex = matchRegex; } @SuppressWarnings({ "rawtypes", "unchecked" }) private Hiterator<IHit<?>> getHiterator() { // final IValueCentricTextIndexer<IHit> textIndex = (IValueCentricTextIndexer) store // .getLexiconRelation().getSearchEngine(); final ITextIndexer<IHit> textIndex = (ITextIndexer) store.getLexiconRelation().getSearchEngine(); if (textIndex == null) throw new UnsupportedOperationException("No free text index?"); String s = query.getLabel(); final boolean prefixMatch; if (s.indexOf('*') >= 0) { prefixMatch = true; s = s.replaceAll("\\*", ""); } else { prefixMatch = false; } return (Hiterator) textIndex.search(new FullTextQuery( s,// query.getLanguage(),// prefixMatch,// matchRegex == null ? null : matchRegex.stringValue(), matchAllTerms, matchExact, minRelevance == null ? BDS.DEFAULT_MIN_RELEVANCE : minRelevance.doubleValue()/* minCosine */, maxRelevance == null ? BDS.DEFAULT_MAX_RELEVANCE : maxRelevance.doubleValue()/* maxCosine */, minRank == null ? BDS.DEFAULT_MIN_RANK/*1*/ : minRank.intValue()/* minRank */, maxRank == null ? BDS.DEFAULT_MAX_RANK/*Integer.MAX_VALUE*/ : maxRank.intValue()/* maxRank */, searchTimeout == null ? BDS.DEFAULT_TIMEOUT/*0L*/ : searchTimeout.longValue()/* timeout */, TimeUnit.MILLISECONDS )); } private static final ConcurrentWeakValueCacheWithTimeout<String, Set<IV>> cache = new ConcurrentWeakValueCacheWithTimeout<String, Set<IV>>( 10, 1000*60); private Set<IV> getSubjects() { final String s = query.getLabel(); if (cache.containsKey(s)) { return cache.get(s); } if (log.isInfoEnabled()) { log.info("entering full text search..."); } // query the full text index final Hiterator<IHit<?>> src = getHiterator(); if (log.isInfoEnabled()) { log.info("done with full text search."); } if (log.isInfoEnabled()) { log.info("starting subject collection..."); } final Set<IV> subjects = new LinkedHashSet<IV>(); while (src.hasNext()) { final IV o = (IV) src.next().getDocId(); final Iterator<ISPO> it = store.getAccessPath((IV)null, (IV)null, o).iterator(); while (it.hasNext()) { subjects.add(it.next().s()); } } if (log.isInfoEnabled()) { log.info("done with subject collection: " + subjects.size()); } cache.put(s, subjects); return subjects; } /** * {@inheritDoc} * * Iterate the incoming binding set. If it does not contain a binding * for the searchVar, prune it. Then iterate the full text search * results. For each result (O binding), test the incoming binding sets * to see if there is a link between the binding for the searchVar and * the O. If there is, add the binding set to the output and remove it * from the set to be tested against subsequent O bindings. */ @Override public ICloseableIterator<IBindingSet> call( final IBindingSet[] bindingsClause) { if (log.isInfoEnabled()) { log.info(bindingsClause.length); log.info(Arrays.toString(bindingsClause)); } final IVariable<?> searchVar = vars[0]; // final IBindingSet[] tmp = new IBindingSet[bindingsClause.length]; // System.arraycopy(bindingsClause, 0, tmp, 0, bindingsClause.length); // final boolean[] tmp = new boolean[bindingsClause.length]; boolean foundOne = false; /* * We are filtering out incoming binding sets that don't have a * binding for the search var */ for (int i = 0; i < bindingsClause.length; i++) { final IBindingSet bs = bindingsClause[i]; if (bs.isBound(searchVar)) { // we need to test this binding set // tmp[i] = true; // we have at least one binding set to test foundOne = true; } } // filtered everything out if (!foundOne) { return new EmptyCloseableIterator<IBindingSet>(); } final IBindingSet[] out = new IBindingSet[bindingsClause.length]; int numAccepted = 0; // if (log.isInfoEnabled()) { // log.info("entering full text search..."); // } // // // query the full text index // final Hiterator<IHit<?>> src = getHiterator(); // // if (log.isInfoEnabled()) { // log.info("done with full text search."); // } // // while (src.hasNext()) { // // final IV o = (IV) src.next().getDocId(); // // for (int i = 0; i < bindingsClause.length; i++) { // // /* // * The binding set has either been filtered out or already // * accepted. // */ // if (!tmp[i]) // continue; // // /* // * We know it's bound. If it weren't it would have been // * filtered out above. // */ // final IV s = (IV) bindingsClause[i].get(searchVar).get(); // // final IKeyBuilder kb = KeyBuilder.newInstance(); // o.encode(kb); // s.encode(kb); // // final byte[] fromKey = kb.getKey(); // final byte[] toKey = SuccessorUtil.successor(fromKey.clone()); // // if (log.isInfoEnabled()) { // log.info("starting range count..."); // } // // final long rangeCount = osp.rangeCount(fromKey, toKey); // // if (log.isInfoEnabled()) { // log.info("done with range count: " + rangeCount); // } // // /* // * Test the OSP index to see if we have a link. // */ //// if (!store.getAccessPath(s, null, o).isEmpty()) { // if (rangeCount > 0) { // // // add the binding set to the output // out[numAccepted++] = bindingsClause[i]; // // // don't need to test this binding set again // tmp[i] = false; // // } // // } // // } final Set<IV> subjects = getSubjects(); for (int i = 0; i < bindingsClause.length; i++) { /* * We know it's bound. If it weren't it would have been * filtered out above. */ final IV s = (IV) bindingsClause[i].get(searchVar).get(); if (subjects.contains(s)) { // add the binding set to the output out[numAccepted++] = bindingsClause[i]; } } if (log.isInfoEnabled()) { log.info("finished search in search."); } return new ThickCloseableIterator<IBindingSet>(out, numAccepted); } @Override public IServiceOptions getServiceOptions() { return serviceOptions; } } }
gpl-2.0
smarr/Truffle
sulong/projects/com.oracle.truffle.llvm.runtime/src/com/oracle/truffle/llvm/runtime/nodes/intrinsics/llvm/x86/X86_64BitVarArgs.java
2217
/* * Copyright (c) 2016, 2020, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.oracle.truffle.llvm.runtime.nodes.intrinsics.llvm.x86; class X86_64BitVarArgs { // see https://refspecs.linuxbase.org/elf/x86_64-abi-0.99.pdf public static final int GP_OFFSET = 0; public static final int FP_OFFSET = 4; public static final int OVERFLOW_ARG_AREA = 8; public static final int REG_SAVE_AREA = 16; public static final int GP_LIMIT = 48; public static final int GP_STEP = 8; public static final int FP_LIMIT = 176; public static final int FP_STEP = 16; public static final int STACK_STEP = 8; public static final int GP_REG_COUNT = GP_LIMIT / GP_STEP; }
gpl-2.0
piaolinzhi/fight
drools/cookbook/Chapter01/timer-based-rules/src/main/java/drools/cookbook/chapter01/ServerAlert.java
546
package drools.cookbook.chapter01; import java.util.ArrayList; import java.util.List; /** * * @author Lucas Amador * */ public class ServerAlert { private List<ServerEvent> events; public void addEvent(ServerEvent serverEvent) { getEvents().add(serverEvent); } public List<ServerEvent> getEvents() { if (events==null) { events = new ArrayList<ServerEvent>(); } return events; } public void setEvents(List<ServerEvent> events) { this.events = events; } }
gpl-2.0
saces/fred
src/freenet/node/simulator/LongTermPushPullTest.java
14444
package freenet.node.simulator; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.TreeMap; import java.util.Map.Entry; import com.db4o.ObjectContainer; import freenet.client.ClientMetadata; import freenet.client.FetchException; import freenet.client.HighLevelSimpleClient; import freenet.client.InsertBlock; import freenet.client.InsertException; import freenet.client.async.ClientContext; import freenet.client.events.ClientEvent; import freenet.client.events.ClientEventListener; import freenet.crypt.RandomSource; import freenet.keys.FreenetURI; import freenet.node.Node; import freenet.node.NodeStarter; import freenet.node.Version; import freenet.support.Fields; import freenet.support.Logger; import freenet.support.PooledExecutor; import freenet.support.Logger.LogLevel; import freenet.support.api.Bucket; import freenet.support.io.FileUtil; /** * Push / Pull test over long period of time * * <p> * This class push a series of keys in the format of * <code>KSK@&lt;unique identifier&gt;-DATE-n</code>. It will then try to pull them after (2^n - 1) * days. * <p> * The result is recorded as a CSV file in the format of: * * <pre> * DATE, VERSION, SEED-TIME-1, PUSH-TIME-#0, ... , PUSH-TIME-#N, SEED-TIME-2, PULL-TIME-#0, ... , PULL-TIME-#N * </pre> * * @author sdiz */ public class LongTermPushPullTest { private static final int TEST_SIZE = 64 * 1024; private static final int EXIT_NO_SEEDNODES = 257; private static final int EXIT_FAILED_TARGET = 258; private static final int EXIT_THREW_SOMETHING = 261; private static final int DARKNET_PORT1 = 5010; private static final int OPENNET_PORT1 = 5011; private static final int DARKNET_PORT2 = 5012; private static final int OPENNET_PORT2 = 5013; private static final int MAX_N = 8; private static final DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd", Locale.US); static { dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } private static final Calendar today = Calendar.getInstance(TimeZone.getTimeZone("GMT")); public static void main(String[] args) { if (args.length < 0 || args.length > 2) { System.err.println("Usage: java freenet.node.simulator.LongTermPushPullTest <unique identifier>"); System.exit(1); } String uid = args[0]; if(args.length == 2 && (args[1].equalsIgnoreCase("--dump") || args[1].equalsIgnoreCase("-dump") || args[1].equalsIgnoreCase("dump"))) { try { dumpStats(uid); } catch (IOException e) { System.err.println("IO ERROR: "+e); e.printStackTrace(); System.exit(1); } catch (ParseException e) { System.err.println("PARSE ERROR: "+e); e.printStackTrace(); System.exit(2); } System.exit(0); } List<String> csvLine = new ArrayList<String>(3 + 2 * MAX_N); System.out.println("DATE:" + dateFormat.format(today.getTime())); csvLine.add(dateFormat.format(today.getTime())); System.out.println("Version:" + Version.buildNumber()); csvLine.add(String.valueOf(Version.buildNumber())); int exitCode = 0; Node node = null; Node node2 = null; try { final File dir = new File("longterm-push-pull-test-" + uid); FileUtil.removeAll(dir); RandomSource random = NodeStarter.globalTestInit(dir.getPath(), false, LogLevel.ERROR, "", false); File seednodes = new File("seednodes.fref"); if (!seednodes.exists() || seednodes.length() == 0 || !seednodes.canRead()) { System.err.println("Unable to read seednodes.fref, it doesn't exist, or is empty"); System.exit(EXIT_NO_SEEDNODES); } final File innerDir = new File(dir, Integer.toString(DARKNET_PORT1)); innerDir.mkdir(); FileInputStream fis = new FileInputStream(seednodes); FileUtil.writeTo(fis, new File(innerDir, "seednodes.fref")); fis.close(); // Create one node node = NodeStarter.createTestNode(DARKNET_PORT1, OPENNET_PORT1, dir.getPath(), false, Node.DEFAULT_MAX_HTL, 0, random, new PooledExecutor(), 1000, 4 * 1024 * 1024, true, true, true, true, true, true, true, 12 * 1024, true, true, false, false, null); Logger.getChain().setThreshold(LogLevel.ERROR); // Start it node.start(true); long t1 = System.currentTimeMillis(); if (!TestUtil.waitForNodes(node)) { exitCode = EXIT_FAILED_TARGET; return; } long t2 = System.currentTimeMillis(); System.out.println("SEED-TIME:" + (t2 - t1)); csvLine.add(String.valueOf(t2 - t1)); // PUSH N+1 BLOCKS for (int i = 0; i <= MAX_N; i++) { Bucket data = randomData(node); HighLevelSimpleClient client = node.clientCore.makeClient((short) 0); FreenetURI uri = new FreenetURI("KSK@" + uid + "-" + dateFormat.format(today.getTime()) + "-" + i); System.out.println("PUSHING " + uri); client.addEventHook(new ClientEventListener() { @Override public void onRemoveEventProducer(ObjectContainer container) { // Ignore } @Override public void receive(ClientEvent ce, ObjectContainer maybeContainer, ClientContext context) { System.out.println(ce.getDescription()); } }); try { InsertBlock block = new InsertBlock(data, new ClientMetadata(), uri); t1 = System.currentTimeMillis(); client.insert(block, false, null); t2 = System.currentTimeMillis(); System.out.println("PUSH-TIME-" + i + ":" + (t2 - t1)); csvLine.add(String.valueOf(t2 - t1)); } catch (InsertException e) { e.printStackTrace(); csvLine.add("N/A"); } data.free(); } node.park(); // Node 2 File innerDir2 = new File(dir, Integer.toString(DARKNET_PORT2)); innerDir2.mkdir(); fis = new FileInputStream(seednodes); FileUtil.writeTo(fis, new File(innerDir2, "seednodes.fref")); fis.close(); node2 = NodeStarter.createTestNode(DARKNET_PORT2, OPENNET_PORT2, dir.getPath(), false, Node.DEFAULT_MAX_HTL, 0, random, new PooledExecutor(), 1000, 5 * 1024 * 1024, true, true, true, true, true, true, true, 12 * 1024, false, true, false, false, null); node2.start(true); t1 = System.currentTimeMillis(); if (!TestUtil.waitForNodes(node2)) { exitCode = EXIT_FAILED_TARGET; return; } t2 = System.currentTimeMillis(); System.out.println("SEED-TIME:" + (t2 - t1)); csvLine.add(String.valueOf(t2 - t1)); // PULL N+1 BLOCKS for (int i = 0; i <= MAX_N; i++) { HighLevelSimpleClient client = node2.clientCore.makeClient((short) 0); Calendar targetDate = (Calendar) today.clone(); targetDate.add(Calendar.DAY_OF_MONTH, -((1 << i) - 1)); FreenetURI uri = new FreenetURI("KSK@" + uid + "-" + dateFormat.format(targetDate.getTime()) + "-" + i); System.out.println("PULLING " + uri); try { t1 = System.currentTimeMillis(); client.fetch(uri); t2 = System.currentTimeMillis(); System.out.println("PULL-TIME-" + i + ":" + (t2 - t1)); csvLine.add(String.valueOf(t2 - t1)); } catch (FetchException e) { if (e.getMode() != FetchException.ALL_DATA_NOT_FOUND && e.getMode() != FetchException.DATA_NOT_FOUND) e.printStackTrace(); csvLine.add(FetchException.getShortMessage(e.getMode())); } } } catch (Throwable t) { t.printStackTrace(); exitCode = EXIT_THREW_SOMETHING; } finally { try { if (node != null) node.park(); } catch (Throwable t1) { } try { if (node2 != null) node2.park(); } catch (Throwable t1) { } try { File file = new File(uid + ".csv"); FileOutputStream fos = new FileOutputStream(file, true); PrintStream ps = new PrintStream(fos); ps.println(Fields.commaList(csvLine.toArray())); ps.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); exitCode = EXIT_THREW_SOMETHING; } System.exit(exitCode); } } private static void dumpStats(String uid) throws IOException, ParseException { File file = new File(uid + ".csv"); FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line = null; Calendar prevDate = null; TreeMap<GregorianCalendar,DumpElement> map = new TreeMap<GregorianCalendar,DumpElement>(); while((line = br.readLine()) != null) { DumpElement element; //System.out.println("LINE: "+line); String[] split = line.split(","); Date date = dateFormat.parse(split[0]); GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT")); calendar.setTime(date); System.out.println("Date: "+dateFormat.format(calendar.getTime())); if(prevDate != null) { long now = calendar.getTimeInMillis(); long prev = prevDate.getTimeInMillis(); long dist = (now - prev) / (24 * 60 * 60 * 1000); if(dist != 1) System.out.println(""+dist+" days since last report"); } prevDate = calendar; int version = Integer.parseInt(split[1]); if(split.length > 2) { long seedTime = Long.parseLong(split[2]); int[] pushTimes = new int[MAX_N+1]; String[] pushFailures = new String[MAX_N+1]; for(int i=0;i<=MAX_N;i++) { String s = split[3+i]; try { pushTimes[i] = Integer.parseInt(s); } catch (NumberFormatException e) { pushFailures[i] = s; } } if(split.length > 3 + MAX_N+1) { int[] pullTimes = new int[MAX_N+1]; String[] pullFailures = new String[MAX_N+1]; for(int i=0;i<=MAX_N;i++) { String s = split[3+MAX_N+2+i]; try { pullTimes[i] = Integer.parseInt(s); } catch (NumberFormatException e) { pullFailures[i] = s; } } element = new DumpElement(calendar, version, pushTimes, pushFailures, pullTimes, pullFailures); } else { element = new DumpElement(calendar, version, pushTimes, pushFailures); } } else { element = new DumpElement(calendar, version); } calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); map.put(calendar, element); } fis.close(); for(int i=0;i<=MAX_N;i++) { int delta = ((1<<i)-1); System.out.println("Checking delta: "+delta+" days"); int failures = 0; int successes = 0; long successTime = 0; int noMatch = 0; int insertFailure = 0; Map<String,Integer> failureModes = new HashMap<String,Integer>(); for(Entry<GregorianCalendar,DumpElement> entry : map.entrySet()) { GregorianCalendar date = entry.getKey(); DumpElement element = entry.getValue(); if(element.pullTimes != null) { date = (GregorianCalendar) date.clone(); date.add(Calendar.DAY_OF_MONTH, -delta); System.out.println("Checking "+date.getTime()+" for "+element.date.getTime()+" delta "+delta); DumpElement inserted = map.get(date); if(inserted == null) { System.out.println("No match"); noMatch++; continue; } if(inserted.pushTimes == null || inserted.pushTimes[i] == 0) { System.out.println("Insert failure"); if(element.pullTimes[i] != 0) { System.err.println("Fetched it anyway??!?!?: time "+element.pullTimes[i]); } insertFailure++; } if(element.pullTimes[i] == 0) { String failureMode = element.pullFailures[i]; Integer count = failureModes.get(failureMode); if(count == null) failureModes.put(failureMode, 1); else failureModes.put(failureMode, count+1); failures++; } else { successes++; successTime += element.pullTimes[i]; } } } System.out.println("Successes: "+successes); if(successes != 0) System.out.println("Average success time "+(successTime / successes)); System.out.println("Failures: "+failures); for(Map.Entry<String,Integer> entry : failureModes.entrySet()) System.out.println(entry.getKey()+" : "+entry.getValue()); System.out.println("No match: "+noMatch); System.out.println("Insert failure: "+insertFailure); double psuccess = (successes*1.0 / (1.0*(successes + failures))); System.out.println("Success rate for "+delta+" days: "+psuccess+" ("+(successes+failures)+" samples)"); if(delta != 0) { double halfLifeEstimate = -1*Math.log(2)/(Math.log(psuccess)/delta); System.out.println("Half-life estimate: "+halfLifeEstimate+" days"); } System.out.println(); } } static class DumpElement { public DumpElement(GregorianCalendar date, int version) { this.date = date; this.version = version; this.seedTime = -1; this.pushTimes = null; this.pushFailures = null; this.pullTimes = null; this.pullFailures = null; } public DumpElement(GregorianCalendar date, int version, int[] pushTimes, String[] pushFailures) { this.date = date; this.version = version; this.seedTime = -1; this.pushTimes = pushTimes; this.pushFailures = pushFailures; this.pullTimes = null; this.pullFailures = null; } public DumpElement(GregorianCalendar date, int version, int[] pushTimes, String[] pushFailures, int[] pullTimes, String[] pullFailures) { this.date = date; this.version = version; this.seedTime = -1; this.pushTimes = pushTimes; this.pushFailures = pushFailures; this.pullTimes = pullTimes; this.pullFailures = pullFailures; } final GregorianCalendar date; final int version; final long seedTime; final int[] pushTimes; // 0 = failure, look up in pushFailures final String[] pushFailures; final int[] pullTimes; final String[] pullFailures; } private static Bucket randomData(Node node) throws IOException { Bucket data = node.clientCore.tempBucketFactory.makeBucket(TEST_SIZE); OutputStream os = data.getOutputStream(); byte[] buf = new byte[4096]; for (long written = 0; written < TEST_SIZE;) { node.fastWeakRandom.nextBytes(buf); int toWrite = (int) Math.min(TEST_SIZE - written, buf.length); os.write(buf, 0, toWrite); written += toWrite; } os.close(); return data; } }
gpl-2.0
ferrybig/Minecraft-Overview-Mapper
src/main/java/me/ferrybig/java/minecraft/overview/mapper/textures/variant/VariantModel.java
2110
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package me.ferrybig.java.minecraft.overview.mapper.textures.variant; import java.util.Objects; import me.ferrybig.java.minecraft.overview.mapper.textures.Model; public class VariantModel { private final Model model; private final double xRotation; private final double yRotation; private final boolean uvLock; public VariantModel(Model model, double xRotation, double yRotation, boolean uvLock) { this.model = model; this.xRotation = xRotation; this.yRotation = yRotation; this.uvLock = uvLock; } @Override public int hashCode() { int hash = 5; hash = 29 * hash + Objects.hashCode(this.model); hash = 29 * hash + (int) (Double.doubleToLongBits(this.xRotation) ^ (Double.doubleToLongBits(this.xRotation) >>> 32)); hash = 29 * hash + (int) (Double.doubleToLongBits(this.yRotation) ^ (Double.doubleToLongBits(this.yRotation) >>> 32)); hash = 29 * hash + (this.uvLock ? 1 : 0); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final VariantModel other = (VariantModel) obj; if (Double.doubleToLongBits(this.xRotation) != Double.doubleToLongBits(other.xRotation)) { return false; } if (Double.doubleToLongBits(this.yRotation) != Double.doubleToLongBits(other.yRotation)) { return false; } if (this.uvLock != other.uvLock) { return false; } if (!Objects.equals(this.model, other.model)) { return false; } return true; } @Override public String toString() { return "VariantModel{" + "model=" + model + ", xRotation=" + xRotation + ", yRotation=" + yRotation + ", uvLock=" + uvLock + '}'; } public Model getModel() { return model; } public double getxRotation() { return xRotation; } public double getyRotation() { return yRotation; } public boolean isUvLock() { return uvLock; } }
gpl-2.0
asiekierka/Chisel-1.7.2
src/main/java/info/jbcs/minecraft/utilities/General.java
3191
package info.jbcs.minecraft.utilities; import java.util.HashMap; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; public class General { public static Random rand = new Random(); public static void propelTowards(Entity what, Entity whereTo, double force) { double dx = whereTo.posX - what.posX; double dy = whereTo.posY - what.posY; double dz = whereTo.posZ - what.posZ; double total = Math.sqrt(dx * dx + dy * dy + dz * dz); if (total == 0) { what.motionX = 0; what.motionY = 0; what.motionZ = 0; } else { what.motionX = dx / total * force; what.motionY = dy / total * force; what.motionZ = dz / total * force; } } public static boolean isInRange(double distance, double x1, double y1, double z1, double x2, double y2, double z2) { double x = x1 - x2; double y = y1 - y2; double z = z1 - z2; return x * x + y * y + z * z < distance * distance; } public static Item getItem(ItemStack stack) { if (stack == null) return null; if (stack.getItem() == null) return null; return stack.getItem(); } public static String getUnlocalizedName(Block block) { String name=block.getUnlocalizedName(); if(name.startsWith("tile.")) name=name.substring(5); return name; } public static String getName(Block block){ String res=block.getUnlocalizedName(); return res.substring(5); } public static MovingObjectPosition getMovingObjectPositionFromPlayer(World par1World, EntityPlayer par2EntityPlayer, boolean par3) { float var4 = 1.0F; float var5 = par2EntityPlayer.prevRotationPitch + (par2EntityPlayer.rotationPitch - par2EntityPlayer.prevRotationPitch) * var4; float var6 = par2EntityPlayer.prevRotationYaw + (par2EntityPlayer.rotationYaw - par2EntityPlayer.prevRotationYaw) * var4; double var7 = par2EntityPlayer.prevPosX + (par2EntityPlayer.posX - par2EntityPlayer.prevPosX) * var4; double var9 = par2EntityPlayer.prevPosY + (par2EntityPlayer.posY - par2EntityPlayer.prevPosY) * var4 + 1.62D - par2EntityPlayer.yOffset; double var11 = par2EntityPlayer.prevPosZ + (par2EntityPlayer.posZ - par2EntityPlayer.prevPosZ) * var4; Vec3 var13 = par1World.getWorldVec3Pool().getVecFromPool(var7, var9, var11); float var14 = MathHelper.cos(-var6 * 0.017453292F - (float) Math.PI); float var15 = MathHelper.sin(-var6 * 0.017453292F - (float) Math.PI); float var16 = -MathHelper.cos(-var5 * 0.017453292F); float var17 = MathHelper.sin(-var5 * 0.017453292F); float var18 = var15 * var16; float var20 = var14 * var16; double var21 = 5.0D; if (par2EntityPlayer instanceof EntityPlayerMP) { var21 = ((EntityPlayerMP) par2EntityPlayer).theItemInWorldManager.getBlockReachDistance(); } Vec3 var23 = var13.addVector(var18 * var21, var17 * var21, var20 * var21); return par1World.rayTraceBlocks(var13, var23, par3); } }
gpl-2.0
profosure/porogram
TMessagesProj/src/main/java/com/porogram/profosure1/messenger/exoplayer2/extractor/mp4/Track.java
3665
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.porogram.profosure1.messenger.exoplayer2.extractor.mp4; import android.support.annotation.IntDef; import com.porogram.profosure1.messenger.exoplayer2.C; import com.porogram.profosure1.messenger.exoplayer2.Format; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Encapsulates information describing an MP4 track. */ public final class Track { /** * The transformation to apply to samples in the track, if any. */ @Retention(RetentionPolicy.SOURCE) @IntDef({TRANSFORMATION_NONE, TRANSFORMATION_CEA608_CDAT}) public @interface Transformation {} /** * A no-op sample transformation. */ public static final int TRANSFORMATION_NONE = 0; /** * A transformation for caption samples in cdat atoms. */ public static final int TRANSFORMATION_CEA608_CDAT = 1; /** * The track identifier. */ public final int id; /** * One of {@link C#TRACK_TYPE_AUDIO}, {@link C#TRACK_TYPE_VIDEO} and {@link C#TRACK_TYPE_TEXT}. */ public final int type; /** * The track timescale, defined as the number of time units that pass in one second. */ public final long timescale; /** * The movie timescale. */ public final long movieTimescale; /** * The duration of the track in microseconds, or {@link C#TIME_UNSET} if unknown. */ public final long durationUs; /** * The format. */ public final Format format; /** * One of {@code TRANSFORMATION_*}. Defines the transformation to apply before outputting each * sample. */ @Transformation public final int sampleTransformation; /** * Track encryption boxes for the different track sample descriptions. Entries may be null. */ public final TrackEncryptionBox[] sampleDescriptionEncryptionBoxes; /** * Durations of edit list segments in the movie timescale. Null if there is no edit list. */ public final long[] editListDurations; /** * Media times for edit list segments in the track timescale. Null if there is no edit list. */ public final long[] editListMediaTimes; /** * For H264 video tracks, the length in bytes of the NALUnitLength field in each sample. -1 for * other track types. */ public final int nalUnitLengthFieldLength; public Track(int id, int type, long timescale, long movieTimescale, long durationUs, Format format, @Transformation int sampleTransformation, TrackEncryptionBox[] sampleDescriptionEncryptionBoxes, int nalUnitLengthFieldLength, long[] editListDurations, long[] editListMediaTimes) { this.id = id; this.type = type; this.timescale = timescale; this.movieTimescale = movieTimescale; this.durationUs = durationUs; this.format = format; this.sampleTransformation = sampleTransformation; this.sampleDescriptionEncryptionBoxes = sampleDescriptionEncryptionBoxes; this.nalUnitLengthFieldLength = nalUnitLengthFieldLength; this.editListDurations = editListDurations; this.editListMediaTimes = editListMediaTimes; } }
gpl-2.0
mobile-event-processing/Asper
source/src/com/espertech/esper/core/context/mgr/ContextControllerConditionFilter.java
4769
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.core.context.mgr; import com.espertech.esper.client.EventBean; import com.espertech.esper.core.context.util.AgentInstanceContext; import com.espertech.esper.core.context.util.StatementAgentInstanceUtil; import com.espertech.esper.core.service.EPServicesContext; import com.espertech.esper.core.service.EPStatementHandleCallback; import com.espertech.esper.epl.spec.ContextDetailConditionFilter; import com.espertech.esper.filter.FilterHandleCallback; import com.espertech.esper.filter.FilterValueSet; import com.espertech.esper.filter.FilterValueSetParam; import com.espertech.esper.pattern.MatchedEventMap; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; public class ContextControllerConditionFilter implements ContextControllerCondition { private final EPServicesContext servicesContext; private final AgentInstanceContext agentInstanceContext; private final ContextDetailConditionFilter endpointFilterSpec; private final ContextControllerConditionCallback callback; private final ContextInternalFilterAddendum filterAddendum; private EPStatementHandleCallback filterHandle; public ContextControllerConditionFilter(EPServicesContext servicesContext, AgentInstanceContext agentInstanceContext, ContextDetailConditionFilter endpointFilterSpec, ContextControllerConditionCallback callback, ContextInternalFilterAddendum filterAddendum) { this.servicesContext = servicesContext; this.agentInstanceContext = agentInstanceContext; this.endpointFilterSpec = endpointFilterSpec; this.callback = callback; this.filterAddendum = filterAddendum; } public void activate(EventBean optionalTriggeringEvent, MatchedEventMap priorMatches, long timeOffset, boolean isRecoveringResilient) { FilterHandleCallback filterCallback = new FilterHandleCallback() { public String getStatementId() { return agentInstanceContext.getStatementContext().getStatementId(); } public void matchFound(EventBean theEvent, Collection<FilterHandleCallback> allStmtMatches) { filterMatchFound(theEvent); } public boolean isSubSelect() { return false; } }; // determine addendum, if any List<FilterValueSetParam> addendum = null; if (filterAddendum != null) { addendum = filterAddendum.getFilterAddendum(endpointFilterSpec.getFilterSpecCompiled()); } filterHandle = new EPStatementHandleCallback(agentInstanceContext.getEpStatementAgentInstanceHandle(), filterCallback); FilterValueSet filterValueSet = endpointFilterSpec.getFilterSpecCompiled().getValueSet(null, null, addendum); servicesContext.getFilterService().add(filterValueSet, filterHandle); if (optionalTriggeringEvent != null) { boolean match = StatementAgentInstanceUtil.evaluateFilterForStatement(servicesContext, optionalTriggeringEvent, agentInstanceContext, filterHandle); if (match) { filterMatchFound(optionalTriggeringEvent); } } } private void filterMatchFound(EventBean theEvent) { Map<String, Object> props = Collections.emptyMap(); if (endpointFilterSpec.getOptionalFilterAsName() != null) { props = Collections.<String, Object>singletonMap(endpointFilterSpec.getOptionalFilterAsName(), theEvent); } callback.rangeNotification(props, this, theEvent, null, filterAddendum); } public void deactivate() { if (filterHandle != null) { servicesContext.getFilterService().remove(filterHandle); filterHandle = null; } } public boolean isRunning() { return filterHandle != null; } public Long getExpectedEndTime() { return null; } }
gpl-2.0
otmarjr/jtreg-fork
src/share/test/javatest/regtest/data/basic/main/BadTag.java
2147
/* * Copyright (c) 1998, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test * @summary Error: Parse Exception: No class provided for `main' * @run main */ /* @test * @summary Error: Parse Exception: Arguments to `manual' option not supported: bad_arg * @run main/manual=bad_arg BadTag */ /* @test * @summary Error: Parse Exception: Bad integer specification: bruno * @run main/timeout=bruno BadTag */ /* @test * @summary Error: Parse Exception: Bad option for main: bad_opt * @run main/bad_opt BadTag */ /* @test * @summary Error: Parse Exception: -vmopt: vm option(s) found, need to specify /othervm * @run main -vmopt BadTag */ /* @test * @summary Error: Parse Exception: No class provided for `main' * @run main/othervm -vmopt */ // NOTE: The following two tests should fail for different reasons when the test // version of JDK is changed to JDK1.2. /* @test * @summary Error: Parse Exception: Option not allowed using provided test JDK: secure * @run main/secure=secure BadTag */ /* @test * @summary Error: Parse Exception: Option not allowed using provided test JDK: policy * @run main/policy=strict.policy BadTag */
gpl-2.0
ormanli/SQL2NoSQL
src/main/java/com/sql2nosql/node/where/QueryCondition.java
564
package com.sql2nosql.node.where; import org.bson.conversions.Bson; public interface QueryCondition { public String getTableName(); public void setTableName(String tableName); public String getColumnName(); public void setColumnName(String columnName); public NoQueryConditionOperator getOperator(); public void setOperator(NoQueryConditionOperator operator); public Object getValue(); public void setValue(Object value); public NoQueryConditionChain getChain(); public void setChain(NoQueryConditionChain chain); public Bson getBson(); }
gpl-2.0
formeppe/NewAge-JGrass
jgrassgears/src/main/java/org/jgrasstools/gears/io/geopaparazzi/forms/items/ItemConnectedCombo.java
3561
/* * This file is part of JGrasstools (http://www.jgrasstools.org) * (C) HydroloGIS - www.hydrologis.com * * JGrasstools 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.jgrasstools.gears.io.geopaparazzi.forms.items; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.Set; /** * A connected combos item. * * @author Andrea Antonello (www.hydrologis.com) */ public class ItemConnectedCombo implements Item { private String description; private boolean isMandatory; private String defaultValue; private LinkedHashMap<String, List<String>> dataMap; public ItemConnectedCombo( String description, LinkedHashMap<String, List<String>> dataMap, String defaultValue, boolean isMandatory ) { this.dataMap = dataMap; if (defaultValue == null) { defaultValue = ""; } this.description = description; this.defaultValue = defaultValue; this.isMandatory = isMandatory; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" {\n"); sb.append(" \"key\": \"").append(description).append("\",\n"); sb.append(" \"values\": {\n"); StringBuilder tmp = new StringBuilder(); Set<Entry<String, List<String>>> entrySet = dataMap.entrySet(); for( Entry<String, List<String>> entry : entrySet ) { String itemName = entry.getKey(); List<String> items = entry.getValue(); tmp.append(" \"" + itemName + "\": [\n"); StringBuilder tmp2 = new StringBuilder(); for( String itemString : items ) { tmp2.append(" {\"item\": \"" + itemString + "\"},\n"); } String substring = removeLastComma(tmp2); tmp.append(substring).append("\n"); tmp.append(" ],\n"); } String substring = removeLastComma(tmp); sb.append(substring).append("\n"); sb.append(" },\n"); sb.append(" \"value\": \"").append(defaultValue).append("\",\n"); sb.append(" \"type\": \"").append("connectedstringcombo").append("\",\n"); sb.append(" \"mandatory\": \"").append(isMandatory ? "yes" : "no").append("\"\n"); sb.append(" }\n"); return sb.toString(); } private String removeLastComma( StringBuilder tmp ) { String tmpStr = tmp.toString(); int lastIndexOf = tmpStr.lastIndexOf(','); String substring = tmp.substring(0, lastIndexOf); return substring; } @Override public String getKey() { return description; } @Override public void setValue( String value ) { defaultValue = value; } @Override public String getValue() { return defaultValue; } }
gpl-2.0
lclsdu/CS
Client/android/android_verync/src/net/shopnc/android/adapter/MyExpandableListAdapter.java
3608
/** * ClassName: MyExpandableListAdapter.java * created on 2012-3-7 * Copyrights 2011-2012 qjyong All rights reserved. * site: http://blog.csdn.net/qjyong * email: qjyong@gmail.com */ package net.shopnc.android.adapter; import java.util.ArrayList; import net.shopnc.android.R; import net.shopnc.android.model.Board; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; /** * 可展开的ListView的适配器 * @author qjyong */ public class MyExpandableListAdapter extends BaseExpandableListAdapter { private ArrayList<Board> boards; private int size; public Context context; private LayoutInflater childInflater; private LayoutInflater groupInflater; private GroupViewHolder gvh; private ChildViewHolder cvh; public MyExpandableListAdapter(Context ctx, ArrayList<Board> boards) { this.context = ctx; this.childInflater = LayoutInflater.from(ctx); this.groupInflater = LayoutInflater.from(ctx); this.boards = boards; this.size = boards == null ? 0 : boards.size(); } public int getGroupCount() { return size; } public int getChildrenCount(int groupPosition) { return boards.get(groupPosition).getSubBoards().size(); } public Object getGroup(int groupPosition) { return boards.get(groupPosition); } public Object getChild(int groupPosition, int childPosition) { return boards.get(groupPosition).getSubBoards().get(childPosition); } public long getGroupId(int groupPosition) { return boards.get(groupPosition).getFid(); } public long getChildId(int groupPosition, int childPosition) { return boards.get(groupPosition).getSubBoards().get(childPosition).getFid(); } public boolean hasStableIds() { return false; } public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if (convertView == null){ convertView = this.groupInflater.inflate(R.layout.listview_item_board, null); gvh = new GroupViewHolder(); gvh.txt_title = (TextView)convertView.findViewById(R.id.father_title); gvh.txt_selector = (TextView)convertView.findViewById(R.id.board_selector); convertView.setTag(gvh); }else{ gvh = (GroupViewHolder)convertView.getTag(); } gvh.txt_title.setText(this.boards.get(groupPosition).getName()); if(isExpanded){ gvh.txt_selector.setBackgroundResource(R.drawable.selector_2); }else{ gvh.txt_selector.setBackgroundResource(R.drawable.selector_1); } return convertView; } public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if (convertView == null){ convertView = this.childInflater.inflate(R.layout.listview_item_sub_board, null); cvh = new ChildViewHolder(); cvh.txt_title = (TextView)convertView.findViewById(R.id.sub_title); convertView.setTag(cvh); }else{ cvh = (ChildViewHolder)convertView.getTag(); } cvh.txt_title.setText(this.boards.get(groupPosition).getSubBoards().get(childPosition).getName()); return convertView; } public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } @Override public void onGroupCollapsed(int groupPosition) { super.onGroupCollapsed(groupPosition); } @Override public void onGroupExpanded(int groupPosition) { super.onGroupExpanded(groupPosition); } class GroupViewHolder{ TextView txt_title; TextView txt_selector; } class ChildViewHolder{ TextView txt_title; } }
gpl-2.0
smarr/Truffle
truffle/src/com.oracle.truffle.api.instrumentation.test/src/com/oracle/truffle/api/instrumentation/test/GradualInstrumentationTest.java
24510
/* * Copyright (c) 2020, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.truffle.api.instrumentation.test; import static com.oracle.truffle.api.instrumentation.test.InstrumentationTestLanguage.ID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Source; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.instrumentation.EventBinding; import com.oracle.truffle.api.instrumentation.EventContext; import com.oracle.truffle.api.instrumentation.ExecutionEventListener; import com.oracle.truffle.api.instrumentation.InstrumentableNode; import com.oracle.truffle.api.instrumentation.SourceSectionFilter; import com.oracle.truffle.api.instrumentation.StandardTags; import com.oracle.truffle.api.instrumentation.TruffleInstrument; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.test.GCUtils; public class GradualInstrumentationTest { private Context context; private TruffleInstrument.Env instrumentEnv; @Before public void setup() { context = Context.create(ID); instrumentEnv = context.getEngine().getInstruments().get("InstrumentationUpdateInstrument").lookup(TruffleInstrument.Env.class); } @After public void teardown() { if (context != null) { context.close(); } } /** * Test that retired subtree is till reachable allowing us to add new execution listeners to * nodes that are still executing but are not reachable in the current AST. */ @Test public void testRetiredTreeStillReachable() throws InterruptedException { Source source = Source.create(ID, "ROOT(MATERIALIZE_CHILD_EXPRESSION(LOOP(3, STATEMENT(EXPRESSION))))"); RecordingExecutionEventListener listener1 = new RecordingExecutionEventListener(true); EventBinding<ExecutionEventListener> binding = attachRecordingListener(listener1, StandardTags.StatementTag.class); // no materialization happens on first execution because the expression tag is not specified Thread t = evalInNewThread(source, listener1); listener1.go("$START", "+S", "+S", "-S"); listener1.waitUntilStopped(); RecordingExecutionEventListener listener2 = attachRecordingListener(); listener1.go("+S", "-S"); listener1.waitUntilStopped(); RecordingExecutionEventListener listener3 = attachRecordingListener(); listener1.go("+S", "-S", "-S", "$END"); t.join(); binding.dispose(); RecordingExecutionEventListener listener4 = attachRecordingListener(); context.eval(source); assertEquals("+E-E-S+S+E-E-S-S+R+S+E-E+L+S+E-E-S+S+E-E-S+S+E-E-S-L-S-R", listener2.getRecording()); assertEquals("+E-E-S-S+R+S+E-E+L+S+E-E-S+S+E-E-S+S+E-E-S-L-S-R", listener3.getRecording()); assertEquals("+R+S+E-E+L+S+E-E-S+S+E-E-S+S+E-E-S-L-S-R", listener4.getRecording()); } private RecordingExecutionEventListener attachRecordingListener() { RecordingExecutionEventListener listener = new RecordingExecutionEventListener(); instrumentEnv.getInstrumenter().attachExecutionEventListener(SourceSectionFilter.ANY, listener); return listener; } private RecordingExecutionEventListener attachRecordingListener(Class<?>... tags) { return attachRecordingListener(false, tags); } private RecordingExecutionEventListener attachRecordingListener(boolean stepping, Class<?>... tags) { RecordingExecutionEventListener listener = new RecordingExecutionEventListener(stepping); instrumentEnv.getInstrumenter().attachExecutionEventListener(SourceSectionFilter.newBuilder().tagIs(tags).build(), listener); return listener; } private EventBinding<ExecutionEventListener> attachRecordingListener(ExecutionEventListener listener, Class<?> tags) { return instrumentEnv.getInstrumenter().attachExecutionEventListener(SourceSectionFilter.newBuilder().tagIs(tags).build(), listener); } private Thread evalInNewThread(Source source, RecordingExecutionEventListener listener1) { Thread t = new Thread(() -> { listener1.start(); try { context.eval(source); } finally { listener1.end(); } }); t.start(); return t; } /** * Test that instrumentation wrappers are created even for nodes which do not emit any * instrumentation events when those wrappers are needed to store references to retired nodes. */ @Test public void testForcedCreationOfWrappers() throws InterruptedException { Source source = Source.create(ID, "ROOT(MATERIALIZE_CHILD_EXPRESSION(LOOP(0, STATEMENT), LOOP(3, STATEMENT(EXPRESSION))))"); /* * No materialization happens on first execution because the expression tag is not * specified, MATERIALIZE_CHILD_EXPRESSION node is not instrumented because the statement * tag is not specified. */ RecordingExecutionEventListener listener1 = attachRecordingListener(true, InstrumentationTestLanguage.LoopTag.class); Thread t = evalInNewThread(source, listener1); listener1.go("$START", "+L"); RecordingExecutionEventListener listener2 = attachRecordingListener(StandardTags.ExpressionTag.class); RecordingExecutionEventListener listener3 = attachRecordingListener(StandardTags.StatementTag.class); listener1.go("-L", "+L", "-L", "$END"); t.join(); assertEquals("+E-E+E-E+E-E", listener2.getRecording()); assertEquals("+S-S+S-S+S-S", listener3.getRecording()); } /** * Test that even if a binding that causes a certain node to be instrumented is disposed leading * to no instrumentation events being emitted for that node. The wrapper is still not removed * when it contains a reference to a retired subtree that is still executing. */ @Test public void testProbesWithRetiredNodeReferencesAreNotDisposed() throws InterruptedException { Source source = Source.create(ID, "ROOT(MATERIALIZE_CHILD_EXPRESSION(LOOP(0, STATEMENT), LOOP(3, STATEMENT(EXPRESSION))))"); /* * No materialization happens on first execution because the expression tag is not * specified, MATERIALIZE_CHILD_EXPRESSION node is not instrumented because the statement * tag is not specified. */ RecordingExecutionEventListener listener1 = attachRecordingListener(true, InstrumentationTestLanguage.LoopTag.class); Thread t = evalInNewThread(source, listener1); listener1.go("$START", "+L"); listener1.disableSteppingWhileWaiting(); RecordingExecutionEventListener listener2 = new RecordingExecutionEventListener(); EventBinding<ExecutionEventListener> binding = attachRecordingListener(listener2, StandardTags.ExpressionTag.class); binding.dispose(); context.eval(source); RecordingExecutionEventListener listener3 = attachRecordingListener(StandardTags.StatementTag.class); listener1.go("-L"); t.join(); assertEquals("+L+L-L+L-L-L+L-L", listener1.getRecording()); assertEquals("+S-S+S-S+S-S", listener3.getRecording()); } /** * Test that problems caused by a single node being reachable both from the retired nodes and * new materialized subtree are not present when the subtree is cloned during materialization. */ @Test public void testRepeatedInstrumentationDoesNotChangeParentsInMaterializedTree() { Source source = Source.create(ID, "ROOT(MATERIALIZE_CHILD_STMT_AND_EXPR(EXPRESSION(EXPRESSION)))"); // execute first so that the next execution cannot take advantage of the "onFirstExecution" // optimization context.eval(source); RecordingExecutionEventListener listener1 = new RecordingExecutionEventListener(); EventBinding<ExecutionEventListener> binding = attachRecordingListener(listener1, StandardTags.StatementTag.class); context.eval(source); assertEquals("+S+S-S-S", listener1.getRecording()); binding.dispose(); RecordingExecutionEventListener listener2 = attachRecordingListener(StandardTags.StatementTag.class, StandardTags.ExpressionTag.class); context.eval(source); /* * Each materialized node, which itself is a statement, has an extra statement. If the * materialized node has an expression as a child and the children of that expression * consist of only one expression, then the nested expression is connected as a child * directly to the materialized node in place of its parent and for each expression which is * ommited this way, one child expression is added to the extra statement node. */ assertEquals("+S+S+E-E-S+E-E-S", listener2.getRecording()); } /** * Test that a single node being reachable both from the retired nodes and new materialized * subtree can lead to some nodes in the new tree not be materialized. */ @Test public void testRepeatedInstrumentationChangesParentsInMaterializedTreeIfSubtreesAreNotCloned() { Source source = Source.create(ID, "ROOT(MATERIALIZE_CHILD_STMT_AND_EXPR_NC(EXPRESSION(EXPRESSION)))"); // execute first so that the next execution cannot take advantage of the "onFirstExecution" // optimization context.eval(source); RecordingExecutionEventListener listener1 = new RecordingExecutionEventListener(); EventBinding<ExecutionEventListener> binding = attachRecordingListener(listener1, StandardTags.StatementTag.class); context.eval(source); assertEquals("+S+S-S-S", listener1.getRecording()); binding.dispose(); RecordingExecutionEventListener listener2 = attachRecordingListener(StandardTags.StatementTag.class, StandardTags.ExpressionTag.class); context.eval(source); /* * Each materialized node, which itself is a statement, has an extra statement. If the * materialized node has an expression as a child and the children of that expression * consist of only one expression, then the nested expression is connected as a child * directly to the materialized node in place of its parent and for each expression which is * ommited this way, one child expression is added to the extra statement node. Since the NC * node erroneously does not clone the subtree on materialization, the repeated * instrumentation changes the parent of the nested expression to its original expression * parent, and so in the new materialized tree, the nested expression node which is now a * direct child of the materialized NC node is not instrumented in the new tree, because it * was already instrumented in the old tree (it already has instrumentation wrapper). */ assertEquals("+S+S+E-E-S-S", listener2.getRecording()); } @Test public void testMultipleMaterializationNode() { Source source = Source.create(ID, "ROOT(MATERIALIZE_CHILD_STMT_AND_EXPR_SEPARATELY(STATEMENT(EXPRESSION)))"); RecordingExecutionEventListener listener1 = attachRecordingListener(); context.eval(source); assertEquals("+R+S+S-S+E-E+S+E-E-S-S-R", listener1.getRecording()); } /** * Test that a retired subtree is still reachable even though the materialized node that caused * the first subtree to be retired is retired during further materializaton. */ @Test public void testRetiredTreeStillReachableOnMultipleMaterializationOfTheSameNode() throws InterruptedException { Source source = Source.create(ID, "ROOT(MATERIALIZE_CHILD_STMT_AND_EXPR_SEPARATELY(BLOCK, LOOP(0, STATEMENT), LOOP(3, STATEMENT(CONSTANT(42)))))"); RecordingExecutionEventListener listener1 = attachRecordingListener(true, InstrumentationTestLanguage.LoopTag.class); Thread t1 = evalInNewThread(source, listener1); listener1.go("$START", "+L"); listener1.disableSteppingWhileWaiting(); attachRecordingListener(StandardTags.StatementTag.class); RecordingExecutionEventListener listener2 = attachRecordingListener(true, InstrumentationTestLanguage.BlockTag.class); Thread t2 = evalInNewThread(source, listener2); listener2.go("$START", "+BL"); listener2.disableSteppingWhileWaiting(); attachRecordingListener(StandardTags.ExpressionTag.class); RecordingExecutionEventListener listener5 = attachRecordingListener(InstrumentationTestLanguage.ConstantTag.class); listener1.go("-L"); t1.join(); listener2.go("-BL"); t2.join(); context.eval(source); assertEquals("+C-C+C-C+C-C+C-C+C-C+C-C+C-C+C-C+C-C", listener5.getRecording()); } /** * Test that when a tree that already contains reference to a retired subtree is retired, the * first retired subtree is still reachable and can be instrumented. */ @Test public void testRetiredTreeOfRetiredTreeStillReachable() throws InterruptedException { Source source = Source.create(ID, "ROOT(MATERIALIZE_CHILD_STATEMENT(MATERIALIZE_CHILD_EXPRESSION(LOOP(0, STATEMENT), LOOP(3, STATEMENT(CONSTANT(42))))))"); RecordingExecutionEventListener listener1 = attachRecordingListener(true, InstrumentationTestLanguage.LoopTag.class); Thread t1 = evalInNewThread(source, listener1); listener1.go("$START", "+L"); listener1.disableSteppingWhileWaiting(); attachRecordingListener(StandardTags.ExpressionTag.class); attachRecordingListener(StandardTags.StatementTag.class); RecordingExecutionEventListener listener4 = attachRecordingListener(InstrumentationTestLanguage.ConstantTag.class); listener1.go("-L"); t1.join(); assertEquals("+C-C+C-C+C-C", listener4.getRecording()); } /** * Test that instrumentation wrappers can be removed even if their probe nodes contain * references to retired nodes. When retired nodes are no longer executing the weak references * should be cleared which should allow the wrappers to be removed. */ @SuppressWarnings("unchecked") @Test public void testWrappersAreRemoved() throws InterruptedException, NoSuchFieldException, IllegalAccessException { Source source = Source.create(ID, "ROOT(MATERIALIZE_CHILD_STATEMENT(LOOP(0, STATEMENT), LOOP(3, STATEMENT(CONSTANT(42)))))"); RecordingExecutionEventListener listener1 = attachRecordingListener(true, InstrumentationTestLanguage.LoopTag.class); Thread t1 = evalInNewThread(source, listener1); listener1.go("$START", "+L"); listener1.disableSteppingWhileWaiting(); RecordingExecutionEventListener listener2 = new RecordingExecutionEventListener(false, true); EventBinding<ExecutionEventListener> binding = attachRecordingListener(listener2, StandardTags.StatementTag.class); context.eval(source); listener1.go("-L"); t1.join(); assertEquals("+S+S-S+S-S+S-S+S-S-S+S-S+S-S+S-S", listener2.getRecording()); List<Node> enteredMaterializedStatementNodes = listener2.getEnteredNodes().stream().filter(node -> node instanceof InstrumentationTestLanguage.MaterializedChildStatementNode).collect( Collectors.toList()); // only the materialized node with reference to the retired tree assertEquals(1, enteredMaterializedStatementNodes.size()); List<WeakReference<Node>> retiredStatementNodes = new ArrayList<>(); for (Node enteredNode : enteredMaterializedStatementNodes) { assertTrue(enteredNode.getParent() instanceof InstrumentableNode.WrapperNode); InstrumentableNode.WrapperNode wrapperNode = (InstrumentableNode.WrapperNode) enteredNode.getParent(); Class<?> probeNodeClass = wrapperNode.getProbeNode().getClass(); Field retiredNodeReferenceField = probeNodeClass.getDeclaredField("retiredNodeReference"); retiredNodeReferenceField.setAccessible(true); Object retiredNodeReference = retiredNodeReferenceField.get(wrapperNode.getProbeNode()); assertNotNull(retiredNodeReference); Class<?> retiredNodeReferenceClass = retiredNodeReference.getClass(); Field retiredNodeWeakReferenceField = retiredNodeReferenceClass.getDeclaredField("node"); retiredNodeWeakReferenceField.setAccessible(true); Object retiredNodeWeakReference = retiredNodeWeakReferenceField.get(retiredNodeReference); assertNotNull(retiredNodeWeakReference); assertTrue(retiredNodeWeakReference instanceof WeakReference); retiredStatementNodes.add((WeakReference<Node>) retiredNodeWeakReference); } /* * Clear entered nodes before calling gc so that the old subtree root is no longer reachable * via parents. */ listener2.clearEnteredNodes(); for (WeakReference<Node> retiredStatementNodeWeakReference : retiredStatementNodes) { GCUtils.assertGc("Retired node is was not collected!", retiredStatementNodeWeakReference); } binding.dispose(); context.eval(source); for (Node enteredNode : enteredMaterializedStatementNodes) { assertFalse(enteredNode.getParent() instanceof InstrumentableNode.WrapperNode); } assertEquals("+L+L-L+L-L-L+L-L+L-L+L-L", listener1.getRecording()); } public static class RecordingExecutionEventListener implements ExecutionEventListener { private volatile boolean error; private volatile String waiting = ""; private boolean stepping; private final boolean recordEnteredNodes; private final StringBuilder sb = new StringBuilder(); private final Object sync = new Object(); private List<Node> enteredNodes = new ArrayList<>(); public RecordingExecutionEventListener() { this(false, false); } public RecordingExecutionEventListener(boolean stepping) { this(stepping, false); } public RecordingExecutionEventListener(boolean stepping, boolean recordEnteredNodes) { this.stepping = stepping; this.recordEnteredNodes = recordEnteredNodes; } public void disableSteppingWhileWaiting() { if (stepping) { synchronized (sync) { while (waiting.isEmpty()) { try { sync.wait(1000); } catch (InterruptedException ie) { } } stepping = false; } } else { throw new IllegalStateException("Cannot disable stepping if it is not enabled!"); } } private String getStepId(String prefix, EventContext c) { if (recordEnteredNodes && "+".equals(prefix)) { enteredNodes.add(c.getInstrumentedNode()); } return prefix + ((InstrumentationTestLanguage.BaseNode) c.getInstrumentedNode()).getShortId(); } public List<Node> getEnteredNodes() { return Collections.unmodifiableList(enteredNodes); } public void clearEnteredNodes() { enteredNodes.clear(); } public void go(String... stepIds) { for (String stepId : stepIds) { synchronized (sync) { while (waiting.isEmpty()) { try { sync.wait(1000); } catch (InterruptedException ie) { } } try { assertEquals("Unexpected step encountered!", stepId, waiting); } catch (AssertionError ae) { error = true; throw ae; } finally { waiting = ""; sync.notifyAll(); } } } } public void waitUntilStopped() { synchronized (sync) { while (waiting.isEmpty()) { try { sync.wait(1000); } catch (InterruptedException ie) { } } } } public void start() { waitBeforeStep("$START"); } public void end() { waitBeforeStep("$END"); } private void waitBeforeStep(String stepId) { if (stepping && !error) { synchronized (sync) { waiting = stepId; while (!waiting.isEmpty()) { sync.notifyAll(); try { sync.wait(1000); } catch (InterruptedException ie) { } } } } } @Override public void onEnter(EventContext context, VirtualFrame frame) { String stepId = getStepId("+", context); waitBeforeStep(stepId); sb.append(stepId); } @Override public void onReturnValue(EventContext context, VirtualFrame frame, Object result) { String stepId = getStepId("-", context); waitBeforeStep(stepId); sb.append(stepId); } @Override public void onReturnExceptional(EventContext context, VirtualFrame frame, Throwable exception) { String stepId = getStepId("*", context); waitBeforeStep(stepId); sb.append(stepId); } public String getRecording() { return sb.toString(); } } }
gpl-2.0
BiglySoftware/BiglyBT
core/src/com/biglybt/core/messenger/browser/listeners/MessageCompletionListener.java
994
/* * Copyright (C) Azureus Software, Inc, All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ package com.biglybt.core.messenger.browser.listeners; /** * @author TuxPaper * @created Oct 10, 2006 * */ public interface MessageCompletionListener { public void completed(boolean success, Object data); }
gpl-2.0
Fernando-Marquardt/mcarchitect
MCArchitect/src/com/fmsware/LZWEncoder.java
7712
package com.fmsware; import java.io.OutputStream; import java.io.IOException; //============================================================================== // Adapted from Jef Poskanzer's Java port by way of J. M. G. Elliott. // K Weiner 12/00 class LZWEncoder { private static final int EOF = -1; private int imgW, imgH; private byte[] pixAry; private int initCodeSize; private int remaining; private int curPixel; // GIFCOMPR.C - GIF Image compression routines // // Lempel-Ziv compression based on 'compress'. GIF modifications by // David Rowley (mgardi@watdcsu.waterloo.edu) // General DEFINEs static final int BITS = 12; static final int HSIZE = 5003; // 80% occupancy // GIF Image compression - modified 'compress' // // Based on: compress.c - File compression ala IEEE Computer, June 1984. // // By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) // Jim McKie (decvax!mcvax!jim) // Steve Davies (decvax!vax135!petsd!peora!srd) // Ken Turkowski (decvax!decwrl!turtlevax!ken) // James A. Woods (decvax!ihnp4!ames!jaw) // Joe Orost (decvax!vax135!petsd!joe) int n_bits; // number of bits/code int maxbits = BITS; // user settable max # bits/code int maxcode; // maximum code, given n_bits int maxmaxcode = 1 << BITS; // should NEVER generate this code int[] htab = new int[HSIZE]; int[] codetab = new int[HSIZE]; int hsize = HSIZE; // for dynamic table sizing int free_ent = 0; // first unused entry // block compression parameters -- after all codes are used up, // and compression rate changes, start over. boolean clear_flg = false; // Algorithm: use open addressing double hashing (no chaining) on the // prefix code / next character combination. We do a variant of Knuth's // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime // secondary probe. Here, the modular division first probe is gives way // to a faster exclusive-or manipulation. Also do block compression with // an adaptive reset, whereby the code table is cleared when the compression // ratio decreases, but after the table fills. The variable-length output // codes are re-sized at this point, and a special CLEAR code is generated // for the decompressor. Late addition: construct the table according to // file size for noticeable speed improvement on small files. Please direct // questions about this implementation to ames!jaw. int g_init_bits; int ClearCode; int EOFCode; // output // // Output the given code. // Inputs: // code: A n_bits-bit integer. If == -1, then EOF. This assumes // that n_bits =< wordsize - 1. // Outputs: // Outputs code to the file. // Assumptions: // Chars are 8 bits long. // Algorithm: // Maintain a BITS character long buffer (so that 8 codes will // fit in it exactly). Use the VAX insv instruction to insert each // code in turn. When the buffer fills up empty it and start over. int cur_accum = 0; int cur_bits = 0; int masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; // Number of characters so far in this 'packet' int a_count; // Define the storage for the packet accumulator byte[] accum = new byte[256]; //---------------------------------------------------------------------------- LZWEncoder(int width, int height, byte[] pixels, int color_depth) { imgW = width; imgH = height; pixAry = pixels; initCodeSize = Math.max(2, color_depth); } // Add a character to the end of the current packet, and if it is 254 // characters, flush the packet to disk. void char_out(byte c, OutputStream outs) throws IOException { accum[a_count++] = c; if (a_count >= 254) flush_char(outs); } // Clear out the hash table // table clear for block compress void cl_block(OutputStream outs) throws IOException { cl_hash(hsize); free_ent = ClearCode + 2; clear_flg = true; output(ClearCode, outs); } // reset code table void cl_hash(int hsize) { for (int i = 0; i < hsize; ++i) htab[i] = -1; } void compress(int init_bits, OutputStream outs) throws IOException { int fcode; int i /* = 0 */; int c; int ent; int disp; int hsize_reg; int hshift; // Set up the globals: g_init_bits - initial number of bits g_init_bits = init_bits; // Set up the necessary values clear_flg = false; n_bits = g_init_bits; maxcode = MAXCODE(n_bits); ClearCode = 1 << (init_bits - 1); EOFCode = ClearCode + 1; free_ent = ClearCode + 2; a_count = 0; // clear packet ent = nextPixel(); hshift = 0; for (fcode = hsize; fcode < 65536; fcode *= 2) ++hshift; hshift = 8 - hshift; // set hash code range bound hsize_reg = hsize; cl_hash(hsize_reg); // clear hash table output(ClearCode, outs); outer_loop : while ((c = nextPixel()) != EOF) { fcode = (c << maxbits) + ent; i = (c << hshift) ^ ent; // xor hashing if (htab[i] == fcode) { ent = codetab[i]; continue; } else if (htab[i] >= 0) // non-empty slot { disp = hsize_reg - i; // secondary hash (after G. Knott) if (i == 0) disp = 1; do { if ((i -= disp) < 0) i += hsize_reg; if (htab[i] == fcode) { ent = codetab[i]; continue outer_loop; } } while (htab[i] >= 0); } output(ent, outs); ent = c; if (free_ent < maxmaxcode) { codetab[i] = free_ent++; // code -> hashtable htab[i] = fcode; } else cl_block(outs); } // Put out the final code. output(ent, outs); output(EOFCode, outs); } //---------------------------------------------------------------------------- void encode(OutputStream os) throws IOException { os.write(initCodeSize); // write "initial code size" byte remaining = imgW * imgH; // reset navigation variables curPixel = 0; compress(initCodeSize + 1, os); // compress and write the pixel data os.write(0); // write block terminator } // Flush the packet to disk, and reset the accumulator void flush_char(OutputStream outs) throws IOException { if (a_count > 0) { outs.write(a_count); outs.write(accum, 0, a_count); a_count = 0; } } final int MAXCODE(int n_bits) { return (1 << n_bits) - 1; } //---------------------------------------------------------------------------- // Return the next pixel from the image //---------------------------------------------------------------------------- private int nextPixel() { if (remaining == 0) return EOF; --remaining; byte pix = pixAry[curPixel++]; return pix & 0xff; } void output(int code, OutputStream outs) throws IOException { cur_accum &= masks[cur_bits]; if (cur_bits > 0) cur_accum |= (code << cur_bits); else cur_accum = code; cur_bits += n_bits; while (cur_bits >= 8) { char_out((byte) (cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } // If the next entry is going to be too big for the code size, // then increase it, if possible. if (free_ent > maxcode || clear_flg) { if (clear_flg) { maxcode = MAXCODE(n_bits = g_init_bits); clear_flg = false; } else { ++n_bits; if (n_bits == maxbits) maxcode = maxmaxcode; else maxcode = MAXCODE(n_bits); } } if (code == EOFCode) { // At EOF, write the rest of the buffer. while (cur_bits > 0) { char_out((byte) (cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } flush_char(outs); } } }
gpl-2.0
DiscourseDB/discoursedb-core
discoursedb-model/src/main/java/edu/cmu/cs/lti/discoursedb/core/service/user/package-info.java
1410
/******************************************************************************* * Copyright (C) 2015 - 2016 Carnegie Mellon University * Author: Oliver Ferschke * * This file is part of DiscourseDB. * * DiscourseDB 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. * * DiscourseDB 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 DiscourseDB. If not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA *******************************************************************************/ /** * Contains service-layer classes that provide a higher level of abstraction for the DiscourseDB user repositories defined in {@link edu.cmu.cs.lti.discoursedb.core.repository.user}. * * @see <a href="http://projects.spring.io/spring-data-jpa/">Spring Data JPA</a> * * @author Oliver Ferschke */ package edu.cmu.cs.lti.discoursedb.core.service.user;
gpl-2.0
zzlnewair/android_study
4Broadcast/06BcastRecStickyInt/src/com/zzl/broadcastreceiver/stickyintent/StickyIntentBroadcastReceiverActivity.java
1218
package com.zzl.broadcastreceiver.stickyintent; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.os.Bundle; import android.widget.TextView; // Note: Sticky Intents have been deprecated public class StickyIntentBroadcastReceiverActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView currentStateView = (TextView) findViewById(R.id.level); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) { String age = "Reading taken recently"; if (isInitialStickyBroadcast()) { age = "Reading may be stale"; } currentStateView.setText("Current Battery Level:" + String.valueOf(intent.getIntExtra( BatteryManager.EXTRA_LEVEL, -1)) + System.getProperty("line.separator") + age); } } }, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); } }
gpl-2.0
lizziesilver/tetrad
tetrad-lib/src/main/java/edu/cmu/tetrad/graph/EndpointMatrixGraph.java
59665
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetrad.graph; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.ObjectInputStream; import java.util.*; /** * <p>Stores a graph a list of lists of edges adjacent to each node in the * graph, with an additional list storing all of the edges in the graph. The * edges are of the form N1 *-# N2. Multiple edges may be added per node pair to * this graph, with the caveat that all edges of the form N1 *-# N2 will be * considered equal. For randomUtil, if the edge X --> Y is added to the graph, * another edge X --> Y may not be added, although an edge Y --> X may be added. * Edges from nodes to themselves may also be added.</p> * * @author Joseph Ramsey * @author Erin Korber additions summer 2004 * @see Endpoint */ public class EndpointMatrixGraph implements Graph { static final long serialVersionUID = 23L; private short[][] graphMatrix = new short[0][0]; /** * A list of the nodes in the graph, in the order in which they were added. * * @serial */ private List<Node> nodes; /** * Set of ambiguous triples. Note the name can't be changed due to * serialization. */ private Set<Triple> ambiguousTriples = new HashSet<>(); /** * @serial */ private Set<Triple> underLineTriples = new HashSet<>(); /** * @serial */ private Set<Triple> dottedUnderLineTriples = new HashSet<>(); /** * True iff nodes were removed since the last call to an accessor for ambiguous, underline, or dotted underline * triples. If there are triples in the lists involving removed nodes, these need to be removed from the lists * first, so as not to cause confusion. */ private boolean stuffRemovedSinceLastTripleAccess = false; /** * The set of highlighted edges. */ private Set<Edge> highlightedEdges = new HashSet<>(); /** * A hash from node names to nodes; */ private Map<String, Node> namesHash = new HashMap<>(); private HashMap<Node, Integer> nodesHash; private HashMap<Short, Endpoint> shortsToEndpoints; private HashMap<Endpoint, Short> endpointsToShorts; private int numEdges = 0; //==============================CONSTUCTORS===========================// /** * Constructs a new (empty) EdgeListGraph. */ public EndpointMatrixGraph() { this.nodes = new ArrayList<>(); } /** * Constructs a EdgeListGraph using the nodes and edges of the given graph. * If this cannot be accomplished successfully, an exception is thrown. Note * that any graph constraints from the given graph are forgotten in the new * graph. * * @param graph the graph from which nodes and edges are is to be * extracted. * @throws IllegalArgumentException if a duplicate edge is added. */ public EndpointMatrixGraph(Graph graph) throws IllegalArgumentException { this(); if (graph == null) { throw new NullPointerException("Graph must not be null."); } transferNodesAndEdges(graph); this.ambiguousTriples = graph.getAmbiguousTriples(); this.underLineTriples = graph.getUnderLines(); this.dottedUnderLineTriples = graph.getDottedUnderlines(); for (Edge edge : graph.getEdges()) { if (graph.isHighlighted(edge)) { setHighlighted(edge, true); } } for (Node node : nodes) { namesHash.put(node.getName(), node); } initHashes(); } /** * Constructs a new graph, with no edges, using the the given variable * names. */ private EndpointMatrixGraph(List<Node> nodes) { this(); if (nodes == null) { throw new NullPointerException(); } for (Object variable : nodes) { if (!addNode((Node) variable)) { throw new IllegalArgumentException(); } } this.graphMatrix = new short[nodes.size()][nodes.size()]; for (Node node : nodes) { namesHash.put(node.getName(), node); } initHashes(); } // Makes a copy with the same object identical edges in it. If you make changes to those edges they will be // reflected here. public static Graph shallowCopy(EndpointMatrixGraph graph) { EndpointMatrixGraph _graph = new EndpointMatrixGraph(); _graph.graphMatrix = copy(graph.graphMatrix); _graph.nodes = new ArrayList<>(graph.nodes); _graph.ambiguousTriples = new HashSet<>(graph.ambiguousTriples); _graph.underLineTriples = new HashSet<>(graph.underLineTriples); _graph.dottedUnderLineTriples = new HashSet<>(graph.dottedUnderLineTriples); _graph.stuffRemovedSinceLastTripleAccess = graph.stuffRemovedSinceLastTripleAccess; _graph.highlightedEdges = new HashSet<>(graph.highlightedEdges); _graph.namesHash = new HashMap<>(graph.namesHash); return _graph; } private static short[][] copy(short[][] graphMatrix) { short[][] copy = new short[graphMatrix.length][graphMatrix[0].length]; if (copy.length == 0) { return new short[0][0]; } for (int i = 0; i < copy.length; i++) { System.arraycopy(graphMatrix[i], 0, copy[i], 0, copy[0].length); } return copy; } private void initHashes() { nodesHash = new HashMap<>(); for (Node node : nodes) { nodesHash.put(node, nodes.indexOf(node)); } endpointsToShorts = new HashMap<>(); endpointsToShorts.put(Endpoint.TAIL, (short) 1); endpointsToShorts.put(Endpoint.ARROW, (short) 2); endpointsToShorts.put(Endpoint.CIRCLE, (short) 3); shortsToEndpoints = new HashMap<>(); shortsToEndpoints.put((short) 1, Endpoint.TAIL); shortsToEndpoints.put((short) 2, Endpoint.ARROW); shortsToEndpoints.put((short) 3, Endpoint.CIRCLE); } /** * Generates a simple exemplar of this class to test serialization. */ public static EndpointMatrixGraph serializableInstance() { return new EndpointMatrixGraph(); } //===============================PUBLIC METHODS========================// /** * Adds a directed edge to the graph from node A to node B. * * @param node1 the "from" node. * @param node2 the "to" node. */ public boolean addDirectedEdge(Node node1, Node node2) { int i = nodesHash.get(node1); int j = nodesHash.get(node2); if (graphMatrix[i][j] != 0) { return false; } graphMatrix[j][i] = 1; graphMatrix[i][j] = 2; numEdges++; return true; } /** * Adds an undirected edge to the graph from node A to node B. * * @param node1 the "from" node. * @param node2 the "to" node. */ public boolean addUndirectedEdge(Node node1, Node node2) { return addEdge(Edges.undirectedEdge(node1, node2)); } /** * Adds a nondirected edge to the graph from node A to node B. * * @param node1 the "from" node. * @param node2 the "to" node. */ public boolean addNondirectedEdge(Node node1, Node node2) { return addEdge(Edges.nondirectedEdge(node1, node2)); } /** * Adds a partially oriented edge to the graph from node A to node B. * * @param node1 the "from" node. * @param node2 the "to" node. */ public boolean addPartiallyOrientedEdge(Node node1, Node node2) { return addEdge(Edges.partiallyOrientedEdge(node1, node2)); } /** * Adds a bidirected edge to the graph from node A to node B. * * @param node1 the "from" node. * @param node2 the "to" node. */ public boolean addBidirectedEdge(Node node1, Node node2) { return addEdge(Edges.bidirectedEdge(node1, node2)); } public boolean existsDirectedCycle() { for (Node node : getNodes()) { if (existsDirectedPathFromTo(node, node)) { return true; } } return false; } public boolean isDirectedFromTo(Node node1, Node node2) { List<Edge> edges = getEdges(node1, node2); if (edges.size() != 1) return false; Edge edge = edges.get(0); return edge.pointsTowards(node2); } public boolean isUndirectedFromTo(Node node1, Node node2) { Edge edge = getEdge(node1, node2); return edge != null && edge.getEndpoint1() == Endpoint.TAIL && edge.getEndpoint2() == Endpoint.TAIL; // return getEdges(node1, node2).size() == 1 // && getEndpoint(node2, node1) == Endpoint.TAIL // && getEndpoint(node1, node2) == Endpoint.TAIL; } /** * added by ekorber, 2004/06/11 * * @return true if the given edge is definitely visible (Jiji, pg 25) * @throws IllegalArgumentException if the given edge is not a directed edge * in the graph */ public boolean defVisible(Edge edge) { if (containsEdge(edge)) { Node A = Edges.getDirectedEdgeTail(edge); Node B = Edges.getDirectedEdgeHead(edge); List<Node> adjToA = getAdjacentNodes(A); while (!adjToA.isEmpty()) { Node Curr = adjToA.remove(0); if (!((getAdjacentNodes(Curr)).contains(B)) && ((getEdge(Curr, A)).getProximalEndpoint(A) == Endpoint .ARROW)) { return true; } } return false; } else { throw new IllegalArgumentException( "Given edge is not in the graph."); } } /** * IllegalArgument exception raised (by isDirectedFromTo(getEndpoint) or by * getEdge) if there are multiple edges between any of the node pairs. */ public boolean isDefNoncollider(Node node1, Node node2, Node node3) { List<Edge> edges = getEdges(node2); boolean circle12 = false; boolean circle32 = false; for (Edge edge : edges) { boolean _node1 = edge.getDistalNode(node2) == node1; boolean _node3 = edge.getDistalNode(node2) == node3; if (_node1 && edge.pointsTowards(node1)) return true; if (_node3 && edge.pointsTowards(node3)) return true; if (_node1 && edge.getProximalEndpoint(node2) == Endpoint.CIRCLE) circle12 = true; if (_node3 && edge.getProximalEndpoint(node2) == Endpoint.CIRCLE) circle32 = true; if (circle12 && circle32 && !isAdjacentTo(node1, node2)) return true; } return false; // if (isDirectedFromTo(node2, node1) || isDirectedFromTo(node2, node3)) { // return true; // } else if (!isAdjacentTo(node1, node3)) { // boolean endpt1 = getEndpoint(node1, node2) == Endpoint.CIRCLE; // boolean endpt2 = getEndpoint(node3, node2) == Endpoint.CIRCLE; // return (endpt1 && endpt2); //// } else if (getEndpoint(node1, node2) == Endpoint.TAIL && getEndpoint(node3, node2) == Endpoint.TAIL){ //// return true; // } else { // return false; // } } public boolean isDefCollider(Node node1, Node node2, Node node3) { Edge edge1 = getEdge(node1, node2); Edge edge2 = getEdge(node2, node3); if (edge1 == null) { throw new NullPointerException(); } if (edge2 == null) { throw new NullPointerException(); } return edge1.getProximalEndpoint(node2) == Endpoint.ARROW && edge2.getProximalEndpoint(node2) == Endpoint.ARROW; } /** * @return true iff there is a directed path from node1 to node2. * a */ public boolean existsDirectedPathFromTo(Node node1, Node node2) { return existsDirectedPathVisit(node1, node2, new LinkedList<Node>()); } public boolean existsUndirectedPathFromTo(Node node1, Node node2) { return existsUndirectedPathVisit(node1, node2, new LinkedList<Node>()); } public boolean existsSemiDirectedPathFromTo(Node node1, Set<Node> nodes) { return existsSemiDirectedPathVisit(node1, nodes, new LinkedList<Node>()); } /** * Determines whether a trek exists between two nodes in the graph. A trek * exists if there is a directed path between the two nodes or else, for * some third node in the graph, there is a path to each of the two nodes in * question. */ public boolean existsTrek(Node node1, Node node2) { for (Node node3 : getNodes()) { Node node = (node3); if (isAncestorOf(node, node1) && isAncestorOf(node, node2)) { return true; } } return false; } /** * @return the list of children for a node. */ public List<Node> getChildren(Node node) { int i = nodesHash.get(node); List<Node> children = new ArrayList<>(); for (int j = 0; j < nodes.size(); j++) { int m1 = graphMatrix[j][i]; int m2 = graphMatrix[i][j]; if (m1 == 1 && m2 == 2) { children.add(nodes.get(j)); } } return children; } public int getConnectivity() { int connectivity = 0; List<Node> nodes = getNodes(); for (Node node : nodes) { int n = getNumEdges(node); if (n > connectivity) { connectivity = n; } } return connectivity; } public List<Node> getDescendants(List<Node> nodes) { HashSet<Node> descendants = new HashSet<>(); for (Object node1 : nodes) { Node node = (Node) node1; collectDescendantsVisit(node, descendants); } return new LinkedList<>(descendants); } /** * @return the edge connecting node1 and node2, provided a unique such edge * exists. */ public Edge getEdge(Node node1, Node node2) { int i = nodesHash.get(node1); int j = nodesHash.get(node2); Endpoint e1 = shortsToEndpoints.get(graphMatrix[j][i]); Endpoint e2 = shortsToEndpoints.get(graphMatrix[i][j]); if (e1 != null) { return new Edge(node1, node2, e1, e2); } else { return null; } } public Edge getDirectedEdge(Node node1, Node node2) { List<Edge> edges = getEdges(node1, node2); if (edges == null) return null; if (edges.size() == 0) { return null; } for (Edge edge : edges) { if (Edges.isDirectedEdge(edge) && edge.getProximalEndpoint(node2) == Endpoint.ARROW) { return edge; } } return null; } /** * @return the list of parents for a node. */ public List<Node> getParents(Node node) { int j = nodesHash.get(node); List<Node> parents = new ArrayList<>(); for (int i = 0; i < nodes.size(); i++) { int m1 = graphMatrix[j][i]; int m2 = graphMatrix[i][j]; if (m1 == 1 && m2 == 2) { parents.add(nodes.get(i)); } } return parents; } /** * @return the number of edges into the given node. */ public int getIndegree(Node node) { return getParents(node).size(); } @Override public int getDegree(Node node) { return 0; } /** * @return the number of edges out of the given node. */ public int getOutdegree(Node node) { return getChildren(node).size(); } /** * Determines whether some edge or other exists between two nodes. */ public boolean isAdjacentTo(Node node1, Node node2) { int i = nodesHash.get(node1); int j = nodesHash.get(node2); return graphMatrix[i][j] != 0; } /** * Determines whether one node is an ancestor of another. */ public boolean isAncestorOf(Node node1, Node node2) { return (node1 == node2) || isProperAncestorOf(node1, node2); } public boolean possibleAncestor(Node node1, Node node2) { return existsSemiDirectedPathFromTo(node1, Collections.singleton(node2)); } /** * @return true iff node1 is a possible ancestor of at least one member of * nodes2 */ private boolean possibleAncestorSet(Node node1, List<Node> nodes2) { for (Object aNodes2 : nodes2) { if (possibleAncestor(node1, (Node) aNodes2)) { return true; } } return false; } public List<Node> getAncestors(List<Node> nodes) { HashSet<Node> ancestors = new HashSet<>(); for (Object node1 : nodes) { Node node = (Node) node1; collectAncestorsVisit(node, ancestors); } return new ArrayList<>(ancestors); } /** * Determines whether one node is a child of another. */ public boolean isChildOf(Node node1, Node node2) { for (Object o : getEdges(node2)) { Edge edge = (Edge) (o); Node sub = Edges.traverseDirected(node2, edge); if (sub == node1) { return true; } } return false; } /** * Determines whether one node is a descendent of another. */ public boolean isDescendentOf(Node node1, Node node2) { return (node1 == node2) || isProperDescendentOf(node1, node2); } /** * added by ekorber, 2004/06/12 * * @return true iff node2 is a definite nondecendent of node1 */ public boolean defNonDescendent(Node node1, Node node2) { return !(possibleAncestor(node1, node2)); } // Assume acyclicity. public boolean isDConnectedTo(Node x, Node y, List<Node> z) { Set<Node> zAncestors = zAncestors2(z); Queue<Pair> Q = new ArrayDeque<>(); Set<Pair> V = new HashSet<>(); for (Node node : getAdjacentNodes(x)) { if (node == y) return true; Pair edge = new Pair(x, node); Q.offer(edge); V.add(edge); } while (!Q.isEmpty()) { Pair t = Q.poll(); Node b = t.getY(); Node a = t.getX(); for (Node c : getAdjacentNodes(b)) { if (c == a) continue; boolean collider = isDefCollider(a, b, c); if (!((collider && zAncestors.contains(b)) || (!collider && !z.contains(b)))) continue; if (c == y) return true; Pair u = new Pair(b, c); if (V.contains(u)) continue; V.add(u); Q.offer(u); } } return false; } private boolean isDConnectedTo(List<Node> x, List<Node> y, List<Node> z) { Set<Node> zAncestors = zAncestors2(z); Queue<Pair> Q = new ArrayDeque<>(); Set<Pair> V = new HashSet<>(); for (Node _x : x) { for (Node node : getAdjacentNodes(_x)) { // if (node == y) return true; if (y.contains(node)) return true; Pair edge = new Pair(_x, node); // System.out.println("Edge " + edge); Q.offer(edge); V.add(edge); } } while (!Q.isEmpty()) { Pair t = Q.poll(); Node b = t.getY(); Node a = t.getX(); for (Node c : getAdjacentNodes(b)) { if (c == a) continue; boolean collider = isDefCollider(a, b, c); if (!((collider && zAncestors.contains(b)) || (!collider && !z.contains(b)))) continue; // if (c == y) return true; if (y.contains(c)) return true; Pair u = new Pair(b, c); if (V.contains(u)) continue; // System.out.println("u = " + u); V.add(u); Q.offer(u); } } return false; } public boolean isDSeparatedFrom(List<Node> x, List<Node> y, List<Node> z) { return !isDConnectedTo(x, y, z); } @Override public List<String> getTriplesClassificationTypes() { return null; } @Override public List<List<Triple>> getTriplesLists(Node node) { return null; } private static class Pair { private Node x; private Node y; public Pair(Node x, Node y) { this.x = x; this.y = y; } public Node getX() { return x; } public Node getY() { return y; } public int hashCode() { return x.hashCode() + 17 * y.hashCode(); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Pair)) return false; Pair pair = (Pair) o; return x == pair.getX() && y == pair.getY(); } public String toString() { return "(" + x.toString() + ", " + y.toString() + ")"; } } private Set<Node> zAncestors2(List<Node> z) { Queue<Node> Q = new ArrayDeque<>(); Set<Node> V = new HashSet<>(); for (Node node : z) { Q.offer(node); V.add(node); } while (!Q.isEmpty()) { Node t = Q.poll(); for (Node c : getParents(t)) { if (V.contains(c)) continue; V.add(c); Q.offer(c); } } return V; } /** * Determines whether one n ode is d-separated from another. According to * Spirtes, Richardson & Meek, two nodes are d- connected given some * conditioning set Z if there is an acyclic undirected path U between them, * such that every collider on U is an ancestor of some element in Z and * every non-collider on U is not in Z. Two elements are d-separated just * in case they are not d-connected. A collider is a node which two edges * hold in common for which the endpoints leading into the node are both * arrow endpoints. * * @param node1 the first node. * @param node2 the second node. * @param z the conditioning set. * @return true if node1 is d-separated from node2 given set t, false if * not. * @see #isDConnectedTo */ public boolean isDSeparatedFrom(Node node1, Node node2, List<Node> z) { return !isDConnectedTo(node1, node2, z); } //added by ekorber, June 2004 public boolean possDConnectedTo(Node node1, Node node2, List<Node> condNodes) { LinkedList<Node> allNodes = new LinkedList<>(getNodes()); int sz = allNodes.size(); int[][] edgeStage = new int[sz][sz]; int stage = 1; int n1x = allNodes.indexOf(node1); int n2x = allNodes.indexOf(node2); edgeStage[n1x][n1x] = 1; edgeStage[n2x][n2x] = 1; List<int[]> currEdges; List<int[]> nextEdges = new LinkedList<>(); int[] temp1 = new int[2]; temp1[0] = n1x; temp1[1] = n1x; nextEdges.add(temp1); int[] temp2 = new int[2]; temp2[0] = n2x; temp2[1] = n2x; nextEdges.add(temp2); while (true) { currEdges = nextEdges; nextEdges = new LinkedList<>(); for (int[] edge : currEdges) { Node center = allNodes.get(edge[1]); List<Node> adj = new LinkedList<>(getAdjacentNodes(center)); for (Node anAdj : adj) { // check if we've hit this edge before int testIndex = allNodes.indexOf(anAdj); if (edgeStage[edge[1]][testIndex] != 0) { continue; } // if the edge pair violates possible d-connection, // then go to the next adjacent node. Node X = allNodes.get(edge[0]); Node Y = allNodes.get(edge[1]); Node Z = allNodes.get(testIndex); if (!((isDefNoncollider(X, Y, Z) && !(condNodes.contains(Y))) || ( isDefCollider(X, Y, Z) && possibleAncestorSet(Y, condNodes)))) { continue; } // if it gets here, then it's legal, so: // (i) if this is the one we want, we're done if (anAdj.equals(node2)) { return true; } // (ii) if we need to keep going, // add the edge to the nextEdges list int[] nextEdge = new int[2]; nextEdge[0] = edge[1]; nextEdge[1] = testIndex; nextEdges.add(nextEdge); // (iii) set the edgeStage array edgeStage[edge[1]][testIndex] = stage; edgeStage[testIndex][edge[1]] = stage; } } // find out if there's any reason to move to the next stage if (nextEdges.size() == 0) { break; } stage++; } return false; } /** * Determines whether an inducing path exists between node1 and node2, given * a set O of observed nodes and a set sem of conditioned nodes. * * @param node1 the first node. * @param node2 the second node. * @return true if an inducing path exists, false if not. */ public boolean existsInducingPath(Node node1, Node node2) { return GraphUtils.existsInducingPath(node1, node2, this); } /** * Determines whether one node is a parent of another. * * @param node1 the first node. * @param node2 the second node. * @return true if node1 is a parent of node2, false if not. * @see #isChildOf * @see #getParents * @see #getChildren */ public boolean isParentOf(Node node1, Node node2) { for (Edge edge1 : getEdges(node1)) { Edge edge = (edge1); Node sub = Edges.traverseDirected(node1, edge); if (sub == node2) { return true; } } return false; } /** * Determines whether one node is a proper ancestor of another. */ public boolean isProperAncestorOf(Node node1, Node node2) { return existsDirectedPathFromTo(node1, node2); } /** * Determines whether one node is a proper decendent of another */ public boolean isProperDescendentOf(Node node1, Node node2) { return existsDirectedPathFromTo(node2, node1); } /** * Transfers nodes and edges from one graph to another. One way this is * used is to change graph types. One constructs a new graph based on the * old graph, and this method is called to transfer the nodes and edges of * the old graph to the new graph. * * @param graph the graph from which nodes and edges are to be pilfered. * @throws IllegalArgumentException This exception is thrown if adding some * node or edge violates one of the * basicConstraints of this graph. */ public void transferNodesAndEdges(Graph graph) throws IllegalArgumentException { if (graph == null) { throw new NullPointerException("No graph was provided."); } // System.out.println("TANSFER BEFORE " + graph.getEdges()); for (Node node : graph.getNodes()) { if (!addNode(node)) { throw new IllegalArgumentException(); } } for (Edge edge : graph.getEdges()) { if (!addEdge(edge)) { throw new IllegalArgumentException(); } } // System.out.println("TANSFER AFTER " + getEdges()); } /** * Determines whether a node in a graph is exogenous. */ public boolean isExogenous(Node node) { return getIndegree(node) == 0; } /** * @return the set of nodes adjacent to the given node. If there are multiple edges between X and Y, Y will show * up twice in the list of adjacencies for X, for optimality; simply create a list an and array from these to * eliminate the duplication. */ public List<Node> getAdjacentNodes(Node node) { int j = nodesHash.get(node); List<Node> adj = new ArrayList<>(); for (int i = 0; i < nodes.size(); i++) { if (graphMatrix[i][j] != (short) 0) { adj.add(nodes.get(i)); } } return adj; } /** * Removes the edge connecting the two given nodes. */ public boolean removeEdge(Node node1, Node node2) { List<Edge> edges = getEdges(node1, node2); if (edges.size() > 1) { throw new IllegalStateException( "There is more than one edge between " + node1 + " and " + node2); } numEdges--; return removeEdges(edges); } /** * @return the endpoint along the edge from node to node2 at the node2 end. */ public Endpoint getEndpoint(Node node1, Node node2) { List<Edge> edges = getEdges(node2); for (Edge edge : edges) { if (edge.getDistalNode(node2) == node1) return edge.getProximalEndpoint(node2); } return null; // List<Edge> edges = getEdges(node1, node2); // // if (edges.size() == 0) { // retu rn null; // } // // if (edges.size() > 1) { // throw new IllegalArgumentException( // "More than one edge between " + node1 + " and " + node2); // } // // return (edges.get(0)).getProximalEndpoint(node2); } /** * If there is currently an edge from node1 to node2, sets the endpoint at * node2 to the given endpoint; if there is no such edge, adds an edge --# * where # is the given endpoint. Setting an endpoint to null, provided * there is exactly one edge connecting the given nodes, removes the edge. * (If there is more than one edge, an exception is thrown.) * * @throws IllegalArgumentException if the edge with the revised endpoint * cannot be added to the graph. */ public boolean setEndpoint(Node from, Node to, Endpoint endPoint) throws IllegalArgumentException { List<Edge> edges = getEdges(from, to); if (endPoint == null) { throw new NullPointerException(); } else if (edges.size() == 0) { // removeEdge(from, to); addEdge(new Edge(from, to, Endpoint.TAIL, endPoint)); return true; } else if (edges.size() == 1) { Edge edge = edges.get(0); Edge newEdge = new Edge(from, to, edge.getProximalEndpoint(from), endPoint); try { removeEdge(edge); addEdge(newEdge); return true; } catch (IllegalArgumentException e) { return false; } } else { throw new NullPointerException( "An endpoint between node1 and node2 " + "may not be set in this graph if there is more than one " + "edge between node1 and node2."); } } /** * Nodes adjacent to the given node with the given proximal endpoint. */ public List<Node> getNodesInTo(Node node, Endpoint endpoint) { List<Node> nodes = new ArrayList<>(4); List<Edge> edges = getEdges(node); for (Object edge1 : edges) { Edge edge = (Edge) edge1; if (edge.getProximalEndpoint(node) == endpoint) { nodes.add(edge.getDistalNode(node)); } } return nodes; } /** * Nodes adjacent to the given node with the given distal endpoint. */ public List<Node> getNodesOutTo(Node node, Endpoint endpoint) { List<Node> nodes = new ArrayList<>(4); List<Edge> edges = getEdges(node); for (Object edge1 : edges) { Edge edge = (Edge) edge1; if (edge.getDistalEndpoint(node) == endpoint) { nodes.add(edge.getDistalNode(node)); } } return nodes; } /** * @return a matrix of endpoints for the nodes in this graph, with nodes in * the same order as getNodes(). */ public Endpoint[][] getEndpointMatrix() { int size = nodes.size(); Endpoint[][] endpoints = new Endpoint[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (i == j) { continue; } Node nodei = nodes.get(i); Node nodej = nodes.get(j); endpoints[i][j] = getEndpoint(nodei, nodej); } } return endpoints; } /** * Adds an edge to the graph if the grpah constraints permit it. * * @param edge the edge to be added * @return true if the edge was added, false if not. */ public boolean addEdge(Edge edge) { int i = nodesHash.get(edge.getNode1()); int j = nodesHash.get(edge.getNode2()); if (graphMatrix[i][j] != 0) { return false; } short e1 = endpointsToShorts.get(edge.getEndpoint1()); short e2 = endpointsToShorts.get(edge.getEndpoint2()); graphMatrix[j][i] = e1; graphMatrix[i][j] = e2; numEdges++; return true; } /** * Throws unsupported operation exception. */ public void addPropertyChangeListener(PropertyChangeListener l) { throw new UnsupportedOperationException(); } /** * Adds a node to the graph. Precondition: The proposed name of the node * cannot already be used by any other node in the same graph. * * @param node the node to be added. * @return true if the the node was added, false if not. */ public boolean addNode(Node node) { if (node == null) { throw new NullPointerException(); } if (!(getNode(node.getName()) == null)) { return false; // This is problematic for the sem updater. jdramsey 7/23/2005 // throw new IllegalArgumentException("A node by name " + // node.getNode() + " has already been added to the graph."); } if (nodes.contains(node)) { return false; } List<Node> _nodes = new ArrayList<>(); nodes.add(node); namesHash.put(node.getName(), node); reconstituteGraphMatrix(_nodes, nodes); initHashes(); return true; } private void reconstituteGraphMatrix(List<Node> nodes, List<Node> nodes1) { short[][] newGraphMatrix = new short[nodes1.size()][nodes1.size()]; for (int i = 0; i < nodes1.size(); i++) { for (int j = 0; j < nodes1.size(); j++) { int i1 = nodes.indexOf(nodes1.get(i)); int j1 = nodes.indexOf(nodes1.get(i)); if (i1 != -1 && j1 != -1) newGraphMatrix[i][j] = graphMatrix[i1][j1]; } } this.graphMatrix = newGraphMatrix; } /** * @return the list of edges in the graph. No particular ordering of the * edges in the list is guaranteed. */ public Set<Edge> getEdges() { HashSet<Edge> edges = new HashSet<>(); for (int i = 0; i < nodes.size(); i++) { for (int j = i + 1; j < nodes.size(); j++) { final Edge edge = getEdge(nodes.get(i), nodes.get(j)); if (edge != null) { edges.add(edge); } } } return edges; } /** * Determines if the graph contains a particular edge. */ public boolean containsEdge(Edge edge) { int i = nodesHash.get(edge.getNode1()); int j = nodesHash.get(edge.getNode2()); return graphMatrix[i][j] != 0; } /** * Determines whether the graph contains a particular node. */ public boolean containsNode(Node node) { return nodes.contains(node); } /** * @return the list of edges connected to a particular node. No particular * ordering of the edges in the list is guaranteed. */ public List<Edge> getEdges(Node node) { List<Node> adj = getAdjacentNodes(node); List<Edge> edges = new ArrayList<>(); for (Node _node : adj) { edges.add(getEdge(node, _node)); } return edges; } public int hashCode() { int hashCode = 0; int sum = 0; for (Node node : getNodes()) { sum += node.hashCode(); } hashCode += 23 * sum; sum = 0; for (Edge edge : getEdges()) { sum += edge.hashCode(); } hashCode += 41 * sum; return hashCode; } /** * @return true iff the given object is a graph that is equal to this graph, * in the sense that it contains the same nodes and the edges are * isomorphic. */ public boolean equals(Object o) { if (!(o instanceof EndpointMatrixGraph)) { return false; } EndpointMatrixGraph graph = (EndpointMatrixGraph) o; if (!graph.nodes.equals(this.nodes)) return false; for (int i = 0; i < nodes.size(); i++) { for (int j = 0; j < nodes.size(); j++) { if (graph.graphMatrix[i][j] != this.graphMatrix[i][j]) { return false; } } } return true; } /** * Resets the graph so that it is fully connects it using #-# edges, where # * is the given endpoint. */ public void fullyConnect(Endpoint endpoint) { short s = endpointsToShorts.get(endpoint); for (int i = 0; i < nodes.size(); i++) { for (int j = 0; j < nodes.size(); j++) { graphMatrix[i][j] = s; } } } public void reorientAllWith(Endpoint endpoint) { short s = endpointsToShorts.get(endpoint); for (int i = 0; i < nodes.size(); i++) { for (int j = 0; j < nodes.size(); j++) { if (i == j) continue; if (graphMatrix[i][j] != 0) { graphMatrix[i][j] = s; } } } } /** * @return the node with the given name, or null if no such node exists. */ public Node getNode(String name) { Node node = namesHash.get(name); if (node == null /*|| !name.equals(node.getNode())*/) { namesHash = new HashMap<>(); for (Node _node : nodes) { namesHash.put(_node.getName(), _node); } node = namesHash.get(name); } return node; // for (Node node : nodes) { // if (node.getNode().equals(name)) { // return node; // } // } // // return namesHash.get(name); // return null; } /** * @return the number of nodes in the graph. */ public int getNumNodes() { return nodes.size(); } /** * @return the number of edges in the (entire) graph. */ public int getNumEdges() { return numEdges; } /** * @return the number of edges connected to a particular node in the graph. */ public int getNumEdges(Node node) { return getEdges(node).size(); } public List<Node> getNodes() { return new ArrayList<>(nodes); } /** * Removes all nodes (and therefore all edges) from the graph. */ public void clear() { for (int i = 0; i < nodes.size(); i++) { for (int j = 0; j < nodes.size(); j++) { graphMatrix[i][j] = 0; } } } /** * Removes an edge from the graph. (Note: It is dangerous to make a * recursive call to this method (as it stands) from a method containing * certain types of iterators. The problem is that if one uses an iterator * that iterates over the edges of node A or node B, and tries in the * process to remove those edges using this method, a concurrent * modification exception will be thrown.) * * @param edge the edge to remove. * @return true if the edge was removed, false if not. */ public boolean removeEdge(Edge edge) { int i = nodesHash.get(edge.getNode1()); int j = nodesHash.get(edge.getNode2()); graphMatrix[i][j] = 0; graphMatrix[j][i] = 0; return true; } /** * Removes any relevant edge objects found in this collection. G * * @param edges the collection of edges to remove. * @return true if any edges in the collection were removed, false if not. */ public boolean removeEdges(Collection<Edge> edges) { boolean change = false; for (Edge edge : edges) { boolean _change = removeEdge(edge); change = change || _change; } return change; } /** * Removes all edges connecting node A to node B. * * @param node1 the first node., * @param node2 the second node. * @return true if edges were removed between A and B, false if not. */ public boolean removeEdges(Node node1, Node node2) { return removeEdges(getEdges(node1, node2)); } /** * Removes a node from the graph. */ public boolean removeNode(Node node) { if (nodes.contains(node)) { return false; } List<Node> _nodes = new ArrayList<>(nodes); nodes.remove(node); namesHash.remove(node.getName()); reconstituteGraphMatrix(_nodes, nodes); initHashes(); stuffRemovedSinceLastTripleAccess = true; return true; } /** * Removes any relevant node objects found in this collection. * * @param newNodes the collection of nodes to remove. * @return true if nodes from the collection were removed, false if not. */ public boolean removeNodes(List<Node> newNodes) { boolean changed = false; for (Object newNode : newNodes) { boolean _changed = removeNode((Node) newNode); changed = changed || _changed; } return changed; } /** * @return a string representation of the graph. */ public String toString() { StringBuilder buf = new StringBuilder(); buf.append("\nGraph Nodes:\n"); for (int i = 0; i < nodes.size(); i++) { // buf.append("\n" + (i + 1) + ". " + nodes.get(i)); buf.append(nodes.get(i)).append(" "); if ((i + 1) % 30 == 0) buf.append("\n"); } buf.append("\n\nGraph Edges: "); List<Edge> edges = new ArrayList<>(getEdges()); Edges.sortEdges(edges); for (int i = 0; i < edges.size(); i++) { Edge edge = edges.get(i); buf.append("\n").append(i + 1).append(". ").append(edge); } buf.append("\n"); buf.append("\n"); // Set<Triple> ambiguousTriples = getAmbiguousTriples(); if (!ambiguousTriples.isEmpty()) { buf.append("Ambiguous triples (i.e. list of triples for which there is ambiguous data" + "\nabout whether they are colliders or not): \n"); for (Triple triple : ambiguousTriples) { buf.append(triple).append("\n"); } } if (!underLineTriples.isEmpty()) { buf.append("Underline triples: \n"); for (Triple triple : underLineTriples) { buf.append(triple).append("\n"); } } if (!dottedUnderLineTriples.isEmpty()) { buf.append("Dotted underline triples: \n"); for (Triple triple : dottedUnderLineTriples) { buf.append(triple).append("\n"); } } // // buf.append("\nNode positions\n"); // // for (Node node : getNodes()) { // buf.append("\n" + node + ": (" + node.getCenterX() + ", " + node.getCenterY() + ")"); // } return buf.toString(); } public Graph subgraph(List<Node> nodes) { Graph graph = new EndpointMatrixGraph(nodes); Set<Edge> edges = getEdges(); for (Object edge1 : edges) { Edge edge = (Edge) edge1; if (nodes.contains(edge.getNode1()) && nodes.contains(edge.getNode2())) { graph.addEdge(edge); } } return graph; } /** * @return the edges connecting node1 and node2. */ public List<Edge> getEdges(Node node1, Node node2) { List<Edge> edges = getEdges(node1); List<Edge> _edges = new ArrayList<>(); for (Edge edge : edges) { if (edge.getDistalNode(node1) == node2) { _edges.add(edge); } } return _edges; } public Set<Triple> getAmbiguousTriples() { removeTriplesNotInGraph(); return new HashSet<>(ambiguousTriples); } public Set<Triple> getUnderLines() { removeTriplesNotInGraph(); return new HashSet<>(underLineTriples); } public Set<Triple> getDottedUnderlines() { removeTriplesNotInGraph(); return new HashSet<>(dottedUnderLineTriples); } /** * States whether r-s-r is an underline triple or not. */ public boolean isAmbiguousTriple(Node x, Node y, Node z) { Triple triple = new Triple(x, y, z); if (!triple.alongPathIn(this)) { throw new IllegalArgumentException("<" + x + ", " + y + ", " + z + "> is not along a path."); } removeTriplesNotInGraph(); return ambiguousTriples.contains(triple); } /** * States whether r-s-r is an underline triple or not. */ public boolean isUnderlineTriple(Node x, Node y, Node z) { removeTriplesNotInGraph(); return underLineTriples.contains(new Triple(x, y, z)); } /** * States whether r-s-r is an underline triple or not. */ public boolean isDottedUnderlineTriple(Node x, Node y, Node z) { Triple triple = new Triple(x, y, z); if (!triple.alongPathIn(this)) { throw new IllegalArgumentException("<" + x + ", " + y + ", " + z + "> is not along a path."); } removeTriplesNotInGraph(); return dottedUnderLineTriples.contains(new Triple(x, y, z)); } public void addAmbiguousTriple(Node x, Node y, Node z) { Triple triple = new Triple(x, y, z); if (!triple.alongPathIn(this)) { throw new IllegalArgumentException("<" + x + ", " + y + ", " + z + "> must lie along a path in the graph."); } ambiguousTriples.add(new Triple(x, y, z)); } public void addUnderlineTriple(Node x, Node y, Node z) { Triple triple = new Triple(x, y, z); if (!triple.alongPathIn(this)) { throw new IllegalArgumentException("<" + x + ", " + y + ", " + z + "> must lie along a path in the graph."); } underLineTriples.add(new Triple(x, y, z)); } public void addDottedUnderlineTriple(Node x, Node y, Node z) { Triple triple = new Triple(x, y, z); if (!triple.alongPathIn(this)) { throw new IllegalArgumentException("<" + x + ", " + y + ", " + z + "> must lie along a path in the graph."); } dottedUnderLineTriples.add(triple); } public void removeAmbiguousTriple(Node x, Node y, Node z) { ambiguousTriples.remove(new Triple(x, y, z)); } public void removeUnderlineTriple(Node x, Node y, Node z) { underLineTriples.remove(new Triple(x, y, z)); } public void removeDottedUnderlineTriple(Node x, Node y, Node z) { dottedUnderLineTriples.remove(new Triple(x, y, z)); } public void setAmbiguousTriples(Set<Triple> triples) { ambiguousTriples.clear(); for (Triple triple : triples) { addAmbiguousTriple(triple.getX(), triple.getY(), triple.getZ()); } } public void setUnderLineTriples(Set<Triple> triples) { underLineTriples.clear(); for (Triple triple : triples) { addUnderlineTriple(triple.getX(), triple.getY(), triple.getZ()); } } public void setDottedUnderLineTriples(Set<Triple> triples) { dottedUnderLineTriples.clear(); for (Triple triple : triples) { addDottedUnderlineTriple(triple.getX(), triple.getY(), triple.getZ()); } } public List<String> getNodeNames() { List<String> names = new ArrayList<>(); for (Node node : getNodes()) { names.add(node.getName()); } return names; } //===============================PRIVATE METHODS======================// public void removeTriplesNotInGraph() { if (!stuffRemovedSinceLastTripleAccess) return; for (Triple triple : new HashSet<>(ambiguousTriples)) { if (!containsNode(triple.getX()) || !containsNode(triple.getY()) || !containsNode(triple.getZ())) { ambiguousTriples.remove(triple); continue; } if (!isAdjacentTo(triple.getX(), triple.getY()) || !isAdjacentTo(triple.getY(), triple.getZ())) { ambiguousTriples.remove(triple); } } for (Triple triple : new HashSet<>(underLineTriples)) { if (!containsNode(triple.getX()) || !containsNode(triple.getY()) || !containsNode(triple.getZ())) { underLineTriples.remove(triple); continue; } if (!isAdjacentTo(triple.getX(), triple.getY()) || !isAdjacentTo(triple.getY(), triple.getZ())) { underLineTriples.remove(triple); } } for (Triple triple : new HashSet<>(dottedUnderLineTriples)) { if (!containsNode(triple.getX()) || !containsNode(triple.getY()) || !containsNode(triple.getZ())) { dottedUnderLineTriples.remove(triple); continue; } if (!isAdjacentTo(triple.getX(), triple.getY()) || !isAdjacentTo(triple.getY(), triple.getZ())) { dottedUnderLineTriples.remove(triple); } } stuffRemovedSinceLastTripleAccess = false; } @Override public List<Node> getSepset(Node n1, Node n2) { throw new UnsupportedOperationException(); } @Override public void setNodes(List<Node> nodes) { if (nodes.size() != this.nodes.size()) { throw new IllegalArgumentException("Sorry, there is a mismatch in the number of variables " + "you are trying to set."); } this.nodes = nodes; } private void collectAncestorsVisit(Node node, Set<Node> ancestors) { ancestors.add(node); List<Node> parents = getParents(node); if (!parents.isEmpty()) { for (Object parent1 : parents) { Node parent = (Node) parent1; doParentClosureVisit(parent, ancestors); } } } private void collectDescendantsVisit(Node node, Set<Node> descendants) { descendants.add(node); List<Node> children = getChildren(node); if (!children.isEmpty()) { for (Object aChildren : children) { Node child = (Node) aChildren; doChildClosureVisit(child, descendants); } } } /** * closure under the child relation */ private void doChildClosureVisit(Node node, Set<Node> closure) { if (!closure.contains(node)) { closure.add(node); for (Edge edge1 : getEdges(node)) { Node sub = Edges.traverseDirected(node, edge1); if (sub == null) { continue; } doChildClosureVisit(sub, closure); } } } /** * This is a simple auxiliary visit method for the isDConnectedTo() method * used to find the closure of a conditioning set of nodes under the parent * relation. * * @param node the node in question * @param closure the closure of the conditioning set uner the parent * relation (to be calculated recursively). */ private void doParentClosureVisit(Node node, Set<Node> closure) { if (closure.contains(node)) return; closure.add(node); for (Edge edge : getEdges(node)) { Node sub = Edges.traverseReverseDirected(node, edge); if (sub != null) { doParentClosureVisit(sub, closure); } } } /** * @return true iff there is a directed path from node1 to node2. */ private boolean existsUndirectedPathVisit(Node node1, Node node2, LinkedList<Node> path) { path.addLast(node1); for (Edge edge : getEdges(node1)) { Node child = Edges.traverse(node1, edge); if (child == null) { continue; } if (child == node2) { return true; } if (path.contains(child)) { continue; } if (existsUndirectedPathVisit(child, node2, path)) { return true; } } path.removeLast(); return false; } private boolean existsDirectedPathVisit(Node node1, Node node2, LinkedList<Node> path) { path.addLast(node1); for (Edge edge : getEdges(node1)) { Node child = Edges.traverseDirected(node1, edge); if (child == null) { continue; } if (child == node2) { return true; } if (path.contains(child)) { continue; } if (existsDirectedPathVisit(child, node2, path)) { return true; } } path.removeLast(); return false; } /** * @return true iff there is a semi-directed path from node1 to node2 */ private boolean existsSemiDirectedPathVisit(Node node1, Set<Node> nodes2, LinkedList<Node> path) { path.addLast(node1); for (Edge edge : getEdges(node1)) { Node child = Edges.traverseSemiDirected(node1, edge); if (child == null) { continue; } if (nodes2.contains(child)) { return true; } if (path.contains(child)) { continue; } if (existsSemiDirectedPathVisit(child, nodes2, path)) { return true; } } path.removeLast(); return false; } public List<Node> getCausalOrdering() { return GraphUtils.getCausalOrdering(this); } public void setHighlighted(Edge edge, boolean highlighted) { highlightedEdges.add(edge); } public boolean isHighlighted(Edge edge) { return highlightedEdges.contains(edge); } public boolean isParameterizable(Node node) { return true; } public boolean isTimeLagModel() { return false; } public TimeLagGraph getTimeLagGraph() { return null; } /** * Adds semantic checks to the default deserialization method. This method * must have the standard signature for a readObject method, and the body of * the method must begin with "s.defaultReadObject();". Other than that, any * semantic checks can be specified and do not need to stay the same from * version to version. A readObject method of this form may be added to any * class, even if Tetrad sessions were previously saved out using a version * of the class that didn't include it. (That's what the * "s.defaultReadObject();" is for. See J. Bloch, Effective Java, for help. * * @throws java.io.IOException * @throws ClassNotFoundException */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); if (nodes == null) { throw new NullPointerException(); } if (ambiguousTriples == null) { ambiguousTriples = new HashSet<>(); } if (highlightedEdges == null) { highlightedEdges = new HashSet<>(); } if (underLineTriples == null) { underLineTriples = new HashSet<>(); } if (dottedUnderLineTriples == null) { dottedUnderLineTriples = new HashSet<>(); } } }
gpl-2.0
logicmoo/uabcl
src/org/armedbear/lisp/Fixnum.java
27165
/* * Fixnum.java * * Copyright (C) 2002-2006 Peter Graves * $Id: Fixnum.java 11754 2009-04-12 10:53:39Z vvoutilainen $ * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under * terms of your choice, provided that you also meet, for each linked * independent module, the terms and conditions of the license of that * module. An independent module is a module which is not derived from * or based on this library. If you modify this library, you may extend * this exception to your version of the library, but you are not * obligated to do so. If you do not wish to do so, delete this * exception statement from your version. */ package org.armedbear.lisp; import static org.armedbear.lisp.Nil.NIL; import static org.armedbear.lisp.Lisp.*; import java.math.BigInteger; public final class Fixnum extends LispInteger { public static final int MAX_POS_CACHE = 256;//just like before - however never set this to less than 256 public static final Fixnum[] constants = new Fixnum[MAX_POS_CACHE]; static { for (int i = 0; i < MAX_POS_CACHE; i++) constants[i] = new Fixnum(i); } public static final Fixnum ZERO = constants[0]; public static final Fixnum ONE = constants[1]; public static final Fixnum TWO = constants[2]; public static final Fixnum THREE = constants[3]; public static final Fixnum MINUS_ONE = new Fixnum(-1); public static Fixnum makeFixnum(int n) { return (n >= 0 && n < MAX_POS_CACHE) ? constants[n] :(n==-1?MINUS_ONE:new Fixnum(n)); } private final int value; // set to private to hunt down sneaky creators private Fixnum(int value) { this.value = value; } public boolean isFixnum() { return true; } @Override public Object javaInstance() { return Integer.valueOf(intValue()); } @Override public Object javaInstance(Class c) { String cn = c.getName(); if (cn.equals("java.lang.Byte") || cn.equals("byte")) return Byte.valueOf((byte)intValue()); if (cn.equals("java.lang.Short") || cn.equals("short")) return Short.valueOf((short)intValue()); if (cn.equals("java.lang.Long") || cn.equals("long")) return Long.valueOf((long)intValue()); return javaInstance(); } @Override public LispObject typeOf() { if (intValue() == 0 || intValue() == 1) return SymbolConstants.BIT; if (intValue() > 1) return list(SymbolConstants.INTEGER, ZERO, Fixnum.makeFixnum(Integer.MAX_VALUE)); return SymbolConstants.FIXNUM; } @Override public LispObject classOf() { return BuiltInClass.FIXNUM; } @Override public LispObject getDescription() { StringBuffer sb = new StringBuffer("The fixnum "); sb.append(intValue()); return new SimpleString(sb); } @Override public LispObject typep(LispObject type) throws ConditionThrowable { if (type instanceof Symbol) { if (type == SymbolConstants.FIXNUM) return T; if (type == SymbolConstants.INTEGER) return T; if (type == SymbolConstants.RATIONAL) return T; if (type == SymbolConstants.REAL) return T; if (type == SymbolConstants.NUMBER) return T; if (type == SymbolConstants.SIGNED_BYTE) return T; if (type == SymbolConstants.UNSIGNED_BYTE) return intValue() >= 0 ? T : NIL; if (type == SymbolConstants.BIT) return (intValue() == 0 || intValue() == 1) ? T : NIL; } else if (type instanceof LispClass) { if (type == BuiltInClass.FIXNUM) return T; if (type == BuiltInClass.INTEGER) return T; if (type == BuiltInClass.RATIONAL) return T; if (type == BuiltInClass.REAL) return T; if (type == BuiltInClass.NUMBER) return T; } else if (type instanceof Cons) { if (type.equal(UNSIGNED_BYTE_8)) return (intValue() >= 0 && intValue() <= 255) ? T : NIL; if (type.equal(UNSIGNED_BYTE_16)) return (intValue() >= 0 && intValue() <= 65535) ? T : NIL; if (type.equal(UNSIGNED_BYTE_32)) return intValue() >= 0 ? T : NIL; } return super.typep(type); } @Override public LispObject NUMBERP() { return T; } @Override public boolean isNumber() { return true; } @Override public LispObject INTEGERP() { return T; } @Override public boolean isInteger() { return true; } @Override public boolean rationalp() { return true; } @Override public boolean realp() { return true; } @Override public boolean eql(int n) { return intValue() == n; } @Override public boolean eql(LispObject obj) { if (this == obj) return true; if (obj instanceof Fixnum) { if (intValue() == obj.intValue()) return true; } return false; } @Override public boolean equal(int n) { return intValue() == n; } @Override public boolean equal(LispObject obj) { if (this == obj) return true; if (obj instanceof Fixnum) { if (intValue() == obj.intValue()) return true; } return false; } @Override public boolean equalp(int n) { return intValue() == n; } @Override public boolean equalp(LispObject obj) { if (obj instanceof Fixnum) return intValue() == obj.intValue(); if (obj instanceof SingleFloat) return intValue() == obj.floatValue(); if (obj instanceof DoubleFloat) return intValue() == obj.doubleValue(); return false; } @Override public LispObject ABS() { if (intValue() >= 0) return this; return LispInteger.getInteger(-(long)intValue()); } @Override public LispObject NUMERATOR() { return this; } @Override public LispObject DENOMINATOR() { return ONE; } @Override public boolean isEven() throws ConditionThrowable { return (intValue() & 0x01) == 0; } @Override public boolean isOdd() throws ConditionThrowable { return (intValue() & 0x01) != 0; } @Override public boolean isPositive() { return intValue() > 0; } @Override public boolean isNegative() { return intValue() < 0; } @Override public boolean isZero() { return intValue() == 0; } // public static int getValue(LispObject obj) throws ConditionThrowable // { // return obj.intValue(); //// if (obj instanceof Fixnum) return ((Fixnum)obj).value; //// type_error(obj, SymbolConstants.FIXNUM); //// // Not reached. //// return 0; // } @Override public float floatValue() { return (float)intValue(); } @Override public double doubleValue() { return (double)intValue(); } // public static int getInt(LispObject obj) throws ConditionThrowable // { // if (obj instanceof Fixnum) return obj.intValue(); // type_error(obj, SymbolConstants.FIXNUM); // // Not reached. // return 0; // } public static BigInteger getBigInteger(LispObject obj) throws ConditionThrowable { return obj.bigIntegerValue(); // if (obj instanceof Fixnum) return BigInteger.valueOf(obj.intValue()); // type_error(obj, SymbolConstants.FIXNUM); // Not reached. // return null; } @Override public int intValue() { return value; } @Override public long longValue() { return (long) intValue(); } public final BigInteger bigIntegerValue() { return BigInteger.valueOf(intValue()); } @Override public final LispObject incr() { return LispInteger.getInteger(1 + (long)intValue()); } @Override public final LispObject decr() { return LispInteger.getInteger(-1 + (long)intValue()); } @Override public LispObject negate() { return LispInteger.getInteger((-(long)intValue())); } @Override public LispObject add(int n) { return LispInteger.getInteger((long) intValue() + n); } @Override public LispObject add(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) { long result = (long) intValue() + obj.intValue(); return LispInteger.getInteger(result); } if (obj instanceof Bignum) return number(bigIntegerValue().add(obj.bigIntegerValue())); if (obj instanceof Ratio) { BigInteger numerator = ((Ratio)obj).numerator(); BigInteger denominator = ((Ratio)obj).denominator(); return number(bigIntegerValue().multiply(denominator).add(numerator), denominator); } if (obj instanceof SingleFloat) return NumericLispObject.createSingleFloat(intValue() + obj.floatValue()); if (obj instanceof DoubleFloat) return NumericLispObject.createDoubleFloat(intValue() + obj.doubleValue()); if (obj instanceof Complex) { Complex c = (Complex) obj; return Complex.getInstance(add(c.getRealPart()), c.getImaginaryPart()); } return type_error(obj, SymbolConstants.NUMBER); } @Override public LispObject subtract(int n) { return LispInteger.getInteger((long)intValue() - n); } @Override public LispObject subtract(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return number((long) intValue() - obj.intValue()); if (obj instanceof Bignum) return number(bigIntegerValue().subtract(obj.bigIntegerValue())); if (obj instanceof Ratio) { BigInteger numerator = ((Ratio)obj).numerator(); BigInteger denominator = ((Ratio)obj).denominator(); return number( bigIntegerValue().multiply(denominator).subtract(numerator), denominator); } if (obj instanceof SingleFloat) return NumericLispObject.createSingleFloat(intValue() - obj.floatValue()); if (obj instanceof DoubleFloat) return NumericLispObject.createDoubleFloat(intValue() - obj.doubleValue()); if (obj instanceof Complex) { Complex c = (Complex) obj; return Complex.getInstance(subtract(c.getRealPart()), ZERO.subtract(c.getImaginaryPart())); } return type_error(obj, SymbolConstants.NUMBER); } @Override public LispObject multiplyBy(int n) { long result = (long) intValue() * n; return LispInteger.getInteger(result); } @Override public LispObject multiplyBy(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) { long result = (long) intValue() * obj.intValue(); return LispInteger.getInteger(result); } if (obj instanceof Bignum) return number(bigIntegerValue().multiply(obj.bigIntegerValue())); if (obj instanceof Ratio) { BigInteger numerator = ((Ratio)obj).numerator(); BigInteger denominator = ((Ratio)obj).denominator(); return number( bigIntegerValue().multiply(numerator), denominator); } if (obj instanceof SingleFloat) return NumericLispObject.createSingleFloat(intValue() * obj.floatValue()); if (obj instanceof DoubleFloat) return NumericLispObject.createDoubleFloat(intValue() * obj.doubleValue()); if (obj instanceof Complex) { Complex c = (Complex) obj; return Complex.getInstance(multiplyBy(c.getRealPart()), multiplyBy(c.getImaginaryPart())); } return type_error(obj, SymbolConstants.NUMBER); } @Override public LispObject divideBy(LispObject obj) throws ConditionThrowable { try { if (obj instanceof Fixnum) { final int divisor = obj.intValue(); // (/ MOST-NEGATIVE-FIXNUM -1) is a bignum. if (intValue() > Integer.MIN_VALUE) if (intValue() % divisor == 0) return Fixnum.makeFixnum(intValue() / divisor); return number(BigInteger.valueOf(intValue()), BigInteger.valueOf(divisor)); } if (obj instanceof Bignum) return number(bigIntegerValue(), obj.bigIntegerValue()); if (obj instanceof Ratio) { BigInteger numerator = ((Ratio)obj).numerator(); BigInteger denominator = ((Ratio)obj).denominator(); return number(bigIntegerValue().multiply(denominator), numerator); } if (obj instanceof SingleFloat) return NumericLispObject.createSingleFloat(intValue() / obj.floatValue()); if (obj instanceof DoubleFloat) return NumericLispObject.createDoubleFloat(intValue() / obj.doubleValue()); if (obj instanceof Complex) { Complex c = (Complex) obj; LispObject realPart = c.getRealPart(); LispObject imagPart = c.getImaginaryPart(); LispObject denominator = realPart.multiplyBy(realPart).add(imagPart.multiplyBy(imagPart)); return Complex.getInstance(multiplyBy(realPart).divideBy(denominator), Fixnum.ZERO.subtract(multiplyBy(imagPart).divideBy(denominator))); } return type_error(obj, SymbolConstants.NUMBER); } catch (ArithmeticException e) { if (obj.isZero()) return error(new DivisionByZero()); return error(new ArithmeticError(e.getMessage())); } } @Override public boolean isEqualTo(int n) { return intValue() == n; } @Override public boolean isEqualTo(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return intValue() == obj.intValue(); if (obj instanceof SingleFloat) return isEqualTo(obj.rational()); if (obj instanceof DoubleFloat) return intValue() == obj.doubleValue(); if (obj instanceof Complex) return obj.isEqualTo(this); if (obj.isNumber()) return false; type_error(obj, SymbolConstants.NUMBER); // Not reached. return false; } @Override public boolean isNotEqualTo(int n) { return intValue() != n; } @Override public boolean isNotEqualTo(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return intValue() != obj.intValue(); // obj is not a fixnum. if (obj instanceof SingleFloat) return isNotEqualTo(obj.rational()); if (obj instanceof DoubleFloat) return intValue() != obj.doubleValue(); if (obj instanceof Complex) return obj.isNotEqualTo(this); if (obj.isNumber()) return true; type_error(obj, SymbolConstants.NUMBER); // Not reached. return false; } @Override public boolean isLessThan(int n) { return intValue() < n; } @Override public boolean isLessThan(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return intValue() < obj.intValue(); if (obj instanceof Bignum) return bigIntegerValue().compareTo(obj.bigIntegerValue()) < 0; if (obj instanceof Ratio) { BigInteger n = bigIntegerValue().multiply(((Ratio)obj).denominator()); return n.compareTo(((Ratio)obj).numerator()) < 0; } if (obj .floatp()) return isLessThan(obj.rational()); type_error(obj, SymbolConstants.REAL); // Not reached. return false; } @Override public boolean isGreaterThan(int n) throws ConditionThrowable { return intValue() > n; } @Override public boolean isGreaterThan(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return intValue() > obj.intValue(); if (obj instanceof Bignum) return bigIntegerValue().compareTo(obj.bigIntegerValue()) > 0; if (obj instanceof Ratio) { BigInteger n = bigIntegerValue().multiply(((Ratio)obj).denominator()); return n.compareTo(((Ratio)obj).numerator()) > 0; } if (obj .floatp()) return isGreaterThan(obj.rational()); type_error(obj, SymbolConstants.REAL); // Not reached. return false; } @Override public boolean isLessThanOrEqualTo(int n) { return intValue() <= n; } @Override public boolean isLessThanOrEqualTo(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return intValue() <= obj.intValue(); if (obj instanceof Bignum) return bigIntegerValue().compareTo(obj.bigIntegerValue()) <= 0; if (obj instanceof Ratio) { BigInteger n = bigIntegerValue().multiply(((Ratio)obj).denominator()); return n.compareTo(((Ratio)obj).numerator()) <= 0; } if (obj .floatp()) return isLessThanOrEqualTo(obj.rational()); type_error(obj, SymbolConstants.REAL); // Not reached. return false; } @Override public boolean isGreaterThanOrEqualTo(int n) { return intValue() >= n; } @Override public boolean isGreaterThanOrEqualTo(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return intValue() >= obj.intValue(); if (obj instanceof Bignum) return bigIntegerValue().compareTo(obj.bigIntegerValue()) >= 0; if (obj instanceof Ratio) { BigInteger n = bigIntegerValue().multiply(((Ratio)obj).denominator()); return n.compareTo(((Ratio)obj).numerator()) >= 0; } if (obj .floatp()) return isGreaterThanOrEqualTo(obj.rational()); type_error(obj, SymbolConstants.REAL); // Not reached. return false; } @Override public LispObject truncate(LispObject obj) throws ConditionThrowable { final LispThread thread = LispThread.currentThread(); final LispObject value1, value2; try { if (obj instanceof Fixnum) { int divisor = obj.intValue(); int quotient = intValue() / divisor; int remainder = intValue() % divisor; value1 = Fixnum.makeFixnum(quotient); value2 = remainder == 0 ? Fixnum.ZERO : Fixnum.makeFixnum(remainder); } else if (obj instanceof Bignum) { BigInteger val = bigIntegerValue(); BigInteger divisor = obj.bigIntegerValue(); BigInteger[] results = val.divideAndRemainder(divisor); BigInteger quotient = results[0]; BigInteger remainder = results[1]; value1 = number(quotient); value2 = (remainder.signum() == 0) ? Fixnum.ZERO : number(remainder); } else if (obj instanceof Ratio) { Ratio divisor = (Ratio) obj; LispObject quotient = multiplyBy(divisor.DENOMINATOR()).truncate(divisor.NUMERATOR()); LispObject remainder = subtract(quotient.multiplyBy(divisor)); value1 = quotient; value2 = remainder; } else if (obj instanceof SingleFloat) { // "When rationals and floats are combined by a numerical function, // the rational is first converted to a float of the same format." // 12.1.4.1 return NumericLispObject.createSingleFloat((float)intValue()).truncate(obj); } else if (obj instanceof DoubleFloat) { // "When rationals and floats are combined by a numerical function, // the rational is first converted to a float of the same format." // 12.1.4.1 return NumericLispObject.createDoubleFloat((double)intValue()).truncate(obj); } else return type_error(obj, SymbolConstants.REAL); } catch (ArithmeticException e) { if (obj.isZero()) return error(new DivisionByZero()); else return error(new ArithmeticError(e.getMessage())); } return thread.setValues(value1, value2); } @Override public LispObject MOD(LispObject divisor) throws ConditionThrowable { if (divisor instanceof Fixnum) return MOD(divisor.intValue()); return super.MOD(divisor); } @Override public LispObject MOD(int divisor) throws ConditionThrowable { final int r; try { r = intValue() % divisor; } catch (ArithmeticException e) { return error(new ArithmeticError("Division by zero.")); } if (r == 0) return Fixnum.ZERO; if (divisor < 0) { if (intValue() > 0) return Fixnum.makeFixnum(r + divisor); } else { if (intValue() < 0) return Fixnum.makeFixnum(r + divisor); } return Fixnum.makeFixnum(r); } @Override public LispObject ash(int shift) { if (intValue() == 0) return this; if (shift == 0) return this; long n = intValue(); if (shift <= -32) { // Right shift. return n >= 0 ? Fixnum.ZERO : Fixnum.MINUS_ONE; } if (shift < 0) return Fixnum.makeFixnum((int)(n >> -shift)); if (shift <= 32) { n = n << shift; return LispInteger.getInteger(n); } // BigInteger.shiftLeft() succumbs to a stack overflow if shift // is Integer.MIN_VALUE, so... if (shift == Integer.MIN_VALUE) return n >= 0 ? Fixnum.ZERO : Fixnum.MINUS_ONE; return number(BigInteger.valueOf(intValue()).shiftLeft(shift)); } @Override public LispObject ash(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return ash(obj.intValue()); if (obj instanceof Bignum) { if (intValue() == 0) return this; BigInteger n = BigInteger.valueOf(intValue()); BigInteger shift = obj.bigIntegerValue(); if (shift.signum() > 0) return error(new LispError("Can't represent result of left shift.")); if (shift.signum() < 0) return n.signum() >= 0 ? Fixnum.ZERO : Fixnum.MINUS_ONE; Debug.bug(); // Shouldn't happen. } return type_error(obj, SymbolConstants.INTEGER); } @Override public LispObject LOGNOT() { return Fixnum.makeFixnum(~intValue()); } @Override public LispObject LOGAND(int n) throws ConditionThrowable { return Fixnum.makeFixnum(intValue() & n); } @Override public LispObject LOGAND(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return Fixnum.makeFixnum(intValue() & obj.intValue()); if (obj instanceof Bignum) { if (intValue() >= 0) { int n2 = (obj.bigIntegerValue()).intValue(); return Fixnum.makeFixnum(intValue() & n2); } else { BigInteger n1 = bigIntegerValue(); BigInteger n2 = obj.bigIntegerValue(); return number(n1.and(n2)); } } return type_error(obj, SymbolConstants.INTEGER); } @Override public LispObject LOGIOR(int n) throws ConditionThrowable { return Fixnum.makeFixnum(intValue() | n); } @Override public LispObject LOGIOR(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return Fixnum.makeFixnum(intValue() | obj.intValue()); if (obj instanceof Bignum) { BigInteger n1 = bigIntegerValue(); BigInteger n2 = obj.bigIntegerValue(); return number(n1.or(n2)); } return type_error(obj, SymbolConstants.INTEGER); } @Override public LispObject LOGXOR(int n) throws ConditionThrowable { return Fixnum.makeFixnum(intValue() ^ n); } @Override public LispObject LOGXOR(LispObject obj) throws ConditionThrowable { if (obj instanceof Fixnum) return Fixnum.makeFixnum(intValue() ^ obj.intValue()); if (obj instanceof Bignum) { BigInteger n1 = bigIntegerValue(); BigInteger n2 = obj.bigIntegerValue(); return number(n1.xor(n2)); } return type_error(obj, SymbolConstants.INTEGER); } @Override public LispObject LDB(int size, int position) { long n = (long) intValue() >> position; long mask = (1L << size) - 1; return number(n & mask); } final static BigInteger BIGINTEGER_TWO = new BigInteger ("2"); /** Computes fixnum^bignum, returning a fixnum or a bignum. */ public LispObject pow(LispObject obj) throws ConditionThrowable { BigInteger y = obj.bigIntegerValue(); if (y.compareTo (BigInteger.ZERO) < 0) return (Fixnum.makeFixnum(1)).divideBy(this.pow(Bignum.getInteger(y.negate()))); if (y.compareTo(BigInteger.ZERO) == 0) // No need to test base here; CLHS says 0^0 == 1. return Fixnum.makeFixnum(1); int x = this.intValue(); if (x == 0) return Fixnum.makeFixnum(0); if (x == 1) return Fixnum.makeFixnum(1); BigInteger xy = BigInteger.ONE; BigInteger term = BigInteger.valueOf((long) x); while (! y.equals(BigInteger.ZERO)) { if (y.testBit(0)) xy = xy.multiply(term); term = term.multiply(term); y = y.shiftLeft(1); } return Bignum.getInteger(xy); } @Override public int clHash() { return intValue(); } @Override public String writeToString() throws ConditionThrowable { final LispThread thread = LispThread.currentThread(); int base = SymbolConstants.PRINT_BASE.symbolValue(thread).intValue(); String s = Integer.toString(intValue(), base).toUpperCase(); if (SymbolConstants.PRINT_RADIX.symbolValue(thread) != NIL) { FastStringBuffer sb = new FastStringBuffer(); switch (base) { case 2: sb.append("#b"); sb.append(s); break; case 8: sb.append("#o"); sb.append(s); break; case 10: sb.append(s); sb.append('.'); break; case 16: sb.append("#x"); sb.append(s); break; default: sb.append('#'); sb.append(String.valueOf(base)); sb.append('r'); sb.append(s); break; } s = sb.toString(); } return s; } }
gpl-2.0
ZiXian92/MyGitHubIssueTracker
src/misc/FailedRequestException.java
319
package misc; /** * Defines the exception thrown when HTTP request to GitHub API fails. * @author ZiXian92 */ public class FailedRequestException extends Exception { private static final long serialVersionUID = -3825977909398565551L; public FailedRequestException(){ super(Constants.ERROR_FAILEDREQUEST); } }
gpl-2.0
proyecto-adalid/adalid
source/adalid-core/src/adalid/core/annotations/OwnerProperty.java
745
/* * Este programa es software libre; usted puede redistribuirlo y/o modificarlo bajo los terminos * de la licencia "GNU General Public License" publicada por la Fundacion "Free Software Foundation". * Este programa se distribuye con la esperanza de que pueda ser util, pero SIN NINGUNA GARANTIA; * vea la licencia "GNU General Public License" para obtener mas informacion. */ package adalid.core.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Jorge Campins */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface OwnerProperty { // String reference() default ""; }
gpl-2.0
ezScrum/ezScrum
java/ntut/csie/ezScrum/dao/UnplannedDAO.java
9019
package ntut.csie.ezScrum.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import ntut.csie.ezScrum.issue.sql.service.core.IQueryValueSet; import ntut.csie.ezScrum.issue.sql.service.internal.MySQLQuerySet; import ntut.csie.ezScrum.web.dataObject.SerialNumberObject; import ntut.csie.ezScrum.web.dataObject.UnplannedObject; import ntut.csie.ezScrum.web.databasEnum.UnplannedEnum; import ntut.csie.ezScrum.web.databaseEnum.IssuePartnerRelationEnum; import ntut.csie.ezScrum.web.databaseEnum.IssueTypeEnum; /** * @author AllenHuang 2015/08/21 */ public class UnplannedDAO extends AbstractDAO<UnplannedObject, UnplannedObject> { private static UnplannedDAO sInstance = null; public static UnplannedDAO getInstance() { if (sInstance == null) { sInstance = new UnplannedDAO(); } return sInstance; } @Override public long create(UnplannedObject unplanned) { IQueryValueSet valueSet = new MySQLQuerySet(); long currentTime = System.currentTimeMillis(); SerialNumberObject serialNumber = SerialNumberDAO.getInstance().get( unplanned.getProjectId()); long unplannedId = serialNumber.getUnplannedId() + 1; valueSet.addTableName(UnplannedEnum.TABLE_NAME); valueSet.addInsertValue(UnplannedEnum.SERIAL_ID, unplannedId); valueSet.addInsertValue(UnplannedEnum.NAME, unplanned.getName()); valueSet.addInsertValue(UnplannedEnum.HANDLER_ID, unplanned.getHandlerId()); valueSet.addInsertValue(UnplannedEnum.ESTIMATE, unplanned.getEstimate()); valueSet.addInsertValue(UnplannedEnum.ACTUAL, unplanned.getActual()); valueSet.addInsertValue(UnplannedEnum.NOTES, unplanned.getNotes()); valueSet.addInsertValue(UnplannedEnum.STATUS, unplanned.getStatus()); valueSet.addInsertValue(UnplannedEnum.PROJECT_ID, unplanned.getProjectId()); valueSet.addInsertValue(UnplannedEnum.SPRINT_ID, unplanned.getSprintId()); if (unplanned.getCreateTime() > 0) { valueSet.addInsertValue(UnplannedEnum.CREATE_TIME, unplanned.getCreateTime()); valueSet.addInsertValue(UnplannedEnum.UPDATE_TIME, unplanned.getCreateTime()); } else { valueSet.addInsertValue(UnplannedEnum.CREATE_TIME, currentTime); valueSet.addInsertValue(UnplannedEnum.UPDATE_TIME, currentTime); } String query = valueSet.getInsertQuery(); long id = mControl.executeInsert(query); serialNumber.setUnplannedId(unplannedId); serialNumber.save(); return id; } @Override public UnplannedObject get(long id) { IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(UnplannedEnum.TABLE_NAME); valueSet.addEqualCondition(UnplannedEnum.ID, id); String query = valueSet.getSelectQuery(); ResultSet result = mControl.executeQuery(query); UnplannedObject unplanned = null; try { if (result.next()) { unplanned = convert(result); } } catch (SQLException e) { e.printStackTrace(); } finally { closeResultSet(result); } return unplanned; } @Override public boolean update(UnplannedObject unplanned) { IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(UnplannedEnum.TABLE_NAME); valueSet.addInsertValue(UnplannedEnum.NAME, unplanned.getName()); valueSet.addInsertValue(UnplannedEnum.HANDLER_ID, unplanned.getHandlerId()); valueSet.addInsertValue(UnplannedEnum.ESTIMATE, unplanned.getEstimate()); valueSet.addInsertValue(UnplannedEnum.ACTUAL, unplanned.getActual()); valueSet.addInsertValue(UnplannedEnum.NOTES, unplanned.getNotes()); valueSet.addInsertValue(UnplannedEnum.STATUS, unplanned.getStatus()); valueSet.addInsertValue(UnplannedEnum.SPRINT_ID, unplanned.getSprintId()); valueSet.addInsertValue(UnplannedEnum.UPDATE_TIME, unplanned.getUpdateTime()); valueSet.addEqualCondition(UnplannedEnum.ID, unplanned.getId()); String query = valueSet.getUpdateQuery(); return mControl.executeUpdate(query); } @Override public boolean delete(long id) { IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(UnplannedEnum.TABLE_NAME); valueSet.addEqualCondition(UnplannedEnum.ID, id); String query = valueSet.getDeleteQuery(); return mControl.executeUpdate(query); } public ArrayList<UnplannedObject> getUnplannedBySprintId(long sprintId) { IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(UnplannedEnum.TABLE_NAME); valueSet.addEqualCondition(UnplannedEnum.SPRINT_ID, sprintId); String query = valueSet.getSelectQuery(); ResultSet result = mControl.executeQuery(query); ArrayList<UnplannedObject> unplanneds = new ArrayList<UnplannedObject>(); try { while (result.next()) { unplanneds.add(convert(result)); } } catch (SQLException e) { e.printStackTrace(); } finally { closeResultSet(result); } return unplanneds; } /** * Get all unplanneds. * * @param projectId * @return All unplanneds which in this project */ public ArrayList<UnplannedObject> getUnplannedsByProjectId(long projectId) { IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(UnplannedEnum.TABLE_NAME); valueSet.addEqualCondition(UnplannedEnum.PROJECT_ID, projectId); String query = valueSet.getSelectQuery(); ResultSet result = mControl.executeQuery(query); ArrayList<UnplannedObject> unplanneds = new ArrayList<UnplannedObject>(); try { while (result.next()) { unplanneds.add(convert(result)); } } catch (SQLException e) { e.printStackTrace(); } finally { closeResultSet(result); } return unplanneds; } public ArrayList<Long> getPartnersId(long unplannedId) { IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(IssuePartnerRelationEnum.TABLE_NAME); valueSet.addEqualCondition(IssuePartnerRelationEnum.ISSUE_ID, Long.toString(unplannedId)); valueSet.addEqualCondition(IssuePartnerRelationEnum.ISSUE_TYPE, IssueTypeEnum.TYPE_UNPLANNED); valueSet.setOrderBy(IssuePartnerRelationEnum.ID, IQueryValueSet.ASC_ORDER); String query = valueSet.getSelectQuery(); ArrayList<Long> partnersId = new ArrayList<Long>(); ResultSet result = mControl.executeQuery(query); try { while (result.next()) { partnersId.add(result .getLong(IssuePartnerRelationEnum.ACCOUNT_ID)); } } catch (SQLException e) { e.printStackTrace(); } finally { closeResultSet(result); } return partnersId; } public long addPartner(long unplannedId, long partnerId) { long id = -1; if (!partnerExists(unplannedId, partnerId)) { IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(IssuePartnerRelationEnum.TABLE_NAME); valueSet.addInsertValue(IssuePartnerRelationEnum.ISSUE_ID, unplannedId); valueSet.addInsertValue(IssuePartnerRelationEnum.ACCOUNT_ID, partnerId); valueSet.addInsertValue(IssuePartnerRelationEnum.ISSUE_TYPE, IssueTypeEnum.TYPE_UNPLANNED); String query = valueSet.getInsertQuery(); id = mControl.executeInsert(query); } return id; } public boolean removePartner(long unplannedId, long partnerId) { IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(IssuePartnerRelationEnum.TABLE_NAME); valueSet.addEqualCondition(IssuePartnerRelationEnum.ISSUE_ID, unplannedId); valueSet.addEqualCondition(IssuePartnerRelationEnum.ACCOUNT_ID, partnerId); valueSet.addEqualCondition(IssuePartnerRelationEnum.ISSUE_TYPE, IssueTypeEnum.TYPE_UNPLANNED); String query = valueSet.getDeleteQuery(); return mControl.executeUpdate(query); } public boolean partnerExists(long unplannedId, long partnerId) { IQueryValueSet valueSet = new MySQLQuerySet(); valueSet.addTableName(IssuePartnerRelationEnum.TABLE_NAME); valueSet.addEqualCondition(IssuePartnerRelationEnum.ISSUE_TYPE, IssueTypeEnum.TYPE_UNPLANNED); valueSet.addEqualCondition(IssuePartnerRelationEnum.ISSUE_ID, unplannedId); valueSet.addEqualCondition(IssuePartnerRelationEnum.ACCOUNT_ID, partnerId); String query = valueSet.getSelectQuery(); int size = 0; ResultSet result = mControl.executeQuery(query); try { while (result.next()) { size++; } } catch (SQLException e) { e.printStackTrace(); } finally { closeResultSet(result); } if (size > 0) { return true; } return false; } public static UnplannedObject convert(ResultSet result) throws SQLException { UnplannedObject unplanned = new UnplannedObject(result.getLong(UnplannedEnum.ID), result.getLong(UnplannedEnum.SERIAL_ID), result.getLong(UnplannedEnum.PROJECT_ID)); unplanned.setName(result.getString(UnplannedEnum.NAME)) .setHandlerId(result.getLong(UnplannedEnum.HANDLER_ID)) .setEstimate(result.getInt(UnplannedEnum.ESTIMATE)) .setActual(result.getInt(UnplannedEnum.ACTUAL)) .setStatus(result.getInt(UnplannedEnum.STATUS)) .setNotes(result.getString(UnplannedEnum.NOTES)) .setSprintId(result.getLong(UnplannedEnum.SPRINT_ID)) .setCreateTime(result.getLong(UnplannedEnum.CREATE_TIME)) .setUpdateTime(result.getLong(UnplannedEnum.UPDATE_TIME)); return unplanned; } }
gpl-2.0
piaolinzhi/fight
dubbo/pay/pay-facade-remit/src/main/java/wusc/edu/pay/facade/remit/entity/RemitBatch.java
6216
package wusc.edu.pay.facade.remit.entity; import java.math.BigDecimal; import java.util.Date; import wusc.edu.pay.common.entity.BaseEntity; /** * * @Title: 打款处理批次实体 * @Description: * @author zzh * @date 2014-7-22 上午11:38:45 */ public class RemitBatch extends BaseEntity { private static final long serialVersionUID = 1L; private String batchNo; // 打款批次号 private Integer status; // 状态:1-待处理,2-处理中,3-处理完成 private Integer totalNum = 0; // 总笔数 private BigDecimal totalAmount = BigDecimal.ZERO; // 总金额 private Integer acceptSucNum = 0; // 受理成功笔数 private BigDecimal acceptSucAmount = BigDecimal.ZERO; // 受理成功金额 private Integer acceptFailNum = 0; // 受理失败笔数 private BigDecimal acceptFailAmount = BigDecimal.ZERO; // 受理失败金额 private Integer processSucNum = 0; // 处理成功笔数 private BigDecimal processSucAmount = BigDecimal.ZERO; // 处理成功金额 private Integer processFailNum = 0; // 处理失败笔数 private BigDecimal processFailAmount = BigDecimal.ZERO; // 处理失败金额 private Date createDate; // 创建时间 private Date acceptDate; // 受理时间 private Date processDate; // 处理时间 private String confirm; private Date confirmDate; /** * 打款通道编号 */ private String remitChannelCode; /** * 是否支持自动打款:100-是,101-否 */ private Integer isAutoRemit; /** * 付款银行账户 */ private String remitBankAccountNo; public String getRemitBankAccountNo() { return remitBankAccountNo; } public void setRemitBankAccountNo(String remitBankAccountNo) { this.remitBankAccountNo = remitBankAccountNo; } public Integer getIsAutoRemit() { return isAutoRemit; } public void setIsAutoRemit(Integer isAutoRemit) { this.isAutoRemit = isAutoRemit; } public String getRemitChannelCode() { return remitChannelCode; } public void setRemitChannelCode(String remitChannelCode) { this.remitChannelCode = remitChannelCode; } public String getConfirm() { return confirm; } public void setConfirm(String confirm) { this.confirm = confirm; } public Date getConfirmDate() { return confirmDate; } public void setConfirmDate(Date confirmDate) { this.confirmDate = confirmDate; } /** * @return 打款批次号 */ public String getBatchNo() { return batchNo; } /** * @param 打款批次号 */ public void setBatchNo(String batchNo) { this.batchNo = batchNo; } /** * @return 状态:1-待处理,2-处理中,3-处理完成 */ public Integer getStatus() { return status; } /** * @param 状态 * :1-待处理,2-处理中,3-处理完成 */ public void setStatus(Integer status) { this.status = status; } /** * @return 总笔数 */ public Integer getTotalNum() { return totalNum; } /** * @param 总笔数 */ public void setTotalNum(Integer totalNum) { this.totalNum = totalNum; } /** * @return 总金额 */ public BigDecimal getTotalAmount() { return totalAmount; } /** * @param 总金额 */ public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; } /** * @return 受理成功笔数 */ public Integer getAcceptSucNum() { return acceptSucNum; } /** * @param 受理成功笔数 */ public void setAcceptSucNum(Integer acceptSucNum) { this.acceptSucNum = acceptSucNum; } /** * @return 受理成功金额 */ public BigDecimal getAcceptSucAmount() { return acceptSucAmount; } /** * @param 受理成功金额 */ public void setAcceptSucAmount(BigDecimal acceptSucAmount) { this.acceptSucAmount = acceptSucAmount; } /** * @return 受理失败笔数 */ public Integer getAcceptFailNum() { return acceptFailNum; } /** * @param 受理失败笔数 */ public void setAcceptFailNum(Integer acceptFailNum) { this.acceptFailNum = acceptFailNum; } /** * @return 受理失败金额 */ public BigDecimal getAcceptFailAmount() { return acceptFailAmount; } /** * @param 受理失败金额 */ public void setAcceptFailAmount(BigDecimal acceptFailAmount) { this.acceptFailAmount = acceptFailAmount; } /** * @return 处理成功笔数 */ public Integer getProcessSucNum() { return processSucNum; } /** * @param 处理成功笔数 */ public void setProcessSucNum(Integer processSucNum) { this.processSucNum = processSucNum; } /** * @return 处理成功金额 */ public BigDecimal getProcessSucAmount() { return processSucAmount; } /** * @param 处理成功金额 */ public void setProcessSucAmount(BigDecimal processSucAmount) { this.processSucAmount = processSucAmount; } /** * @return 处理失败笔数 */ public Integer getProcessFailNum() { return processFailNum; } /** * @param 处理失败笔数 */ public void setProcessFailNum(Integer processFailNum) { this.processFailNum = processFailNum; } /** * @return 处理失败金额 */ public BigDecimal getProcessFailAmount() { return processFailAmount; } /** * @param 处理失败金额 */ public void setProcessFailAmount(BigDecimal processFailAmount) { this.processFailAmount = processFailAmount; } /** * @return 创建时间 */ public Date getCreateDate() { return createDate; } /** * @param 创建时间 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * @return 受理时间 */ public Date getAcceptDate() { return acceptDate; } /** * @param 受理时间 */ public void setAcceptDate(Date acceptDate) { this.acceptDate = acceptDate; } /** * @return 处理时间 */ public Date getProcessDate() { return processDate; } /** * @param 处理时间 */ public void setProcessDate(Date processDate) { this.processDate = processDate; } }
gpl-2.0
abnervr/VRaptorEclipsePlugin
src/main/java/org/abner/vraptor/jsp/Jsp.java
2492
package org.abner.vraptor.jsp; import java.util.ArrayList; import java.util.List; import org.abner.vraptor.jsp.dom.Document; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; public class Jsp { private IFile file; private IJavaProject project; private Document document; public Jsp(IFile file) throws CoreException { this.file = file; if (project == null && file.getProject().hasNature("org.eclipse.jdt.core.javanature")) { project = JavaCore.create(file.getProject()); } } public boolean isInJavaProject() { return project != null; } public IJavaProject getProject() { return project; } public void setDocument(Document document) { this.document = document; } public Document getDocument() { return document; } public IFile getFile() { return file; } public String getCurrentDirectory() { IPath fullPath = file.getFullPath(); return fullPath.segment(fullPath.segmentCount() - 2); } public String getPath() { String path = null; if (!getCurrentDirectory().equals("jsp")) { IPath fullPath = file.getFullPath(); int i = 3; while (i < fullPath.segmentCount() && !fullPath.segment(fullPath.segmentCount() - i).equals("jsp")) { if (path == null) { path = fullPath.segment(fullPath.segmentCount() - i); } else { path = fullPath.segment(fullPath.segmentCount() - i) + "/" + path; } i++; } } return path; } public String getName() { String name = file.getName(); int extensionIndexOf = name.lastIndexOf("." + file.getFileExtension()); if (extensionIndexOf != -1) { return name.substring(0, extensionIndexOf); } else { return name; } } private List<ContextObject> contextObjects = new ArrayList<>(); public List<ContextObject> getContextObjects() { return contextObjects; } public void addContextObject(ContextObject object) { contextObjects.add(object); } public void removeContextObject(ContextObject object) { contextObjects.remove(object); } }
gpl-2.0
siperteam/core-android
core-android/src/main/java/ir/siper/core/Config.java
796
package ir.siper.core; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") public class Config { @SerializedName("proxy_addr") private String mProxyAddr; @SerializedName("proxy_port") private String mProxyPort; @SerializedName("transport") private String mTransport; public String getProxyAddr() { return mProxyAddr; } public void setProxyAddr(String proxyAddr) { mProxyAddr = proxyAddr; } public String getProxyPort() { return mProxyPort; } public void setProxyPort(String proxyPort) { mProxyPort = proxyPort; } public String getTransport() { return mTransport; } public void setTransport(String transport) { mTransport = transport; } }
gpl-2.0
imclab/WebImageBrowser
WIB/src/java/edu/ucsd/ncmir/WIB/client/plugins/SLASHPlugin/messages/ProcessContoursMessage.java
201
package edu.ucsd.ncmir.WIB.client.plugins.SLASHPlugin.messages; import edu.ucsd.ncmir.WIB.client.core.message.Message; /** * * @author spl */ public class ProcessContoursMessage extends Message {}
gpl-2.0
cst316/spring16project-Team-Flagstaff
src/net/sf/memoranda/History.java
7033
/** * History.java * Created on 23.02.2003, 0:27:33 Alex * Package: net.sf.memoranda * * @author Alex V. Alishevskikh, alex@openmechanics.net * Copyright (c) 2003 Memoranda Team. http://memoranda.sf.net */ package net.sf.memoranda; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.KeyStroke; import net.sf.memoranda.util.Local; /** * */ /*$Id: History.java,v 1.7 2006/10/31 15:34:14 hglas Exp $*/ public class History { static Vector _list = new Vector(); static int p = -1; static Vector historyListeners = new Vector(); static Object next = null; static Object prev = null; public static void add(HistoryItem item) { if (prev != null) if (item.equals(prev)) return; if (p < _list.size() - 1) _list.setSize(p + 1); _list.add(item); p = _list.size() - 1; if (p > 0) prev = _list.get(p-1); else prev = null; next = null; historyBackAction.update(); historyForwardAction.update(); /*System.out.println(); for (int i = 0; i < _list.size(); i++) System.out.println(((HistoryItem)_list.get(i)).getDate().toString()); System.out.println(item.getDate().toShortString()+ " added");*/ if (_list.size() > 99) _list.remove(0); } public static HistoryItem rollBack() { Object n = prev; if (p > 1) { p--; prev = _list.get(p-1); } else if (p > 0) { p--; prev = null; } else prev = null; if (p < _list.size() - 1) next = _list.get(p+1); else next = null; return (HistoryItem)n; } public static HistoryItem rollForward() { Object n = next; if (p < _list.size() - 1) { p++; if (p == 1) p++; next = _list.get(p); } else next = null; if (p > 0) prev = _list.get(p-1); else prev = null; return (HistoryItem)n; } public static boolean canRollBack() { return prev != null; } public static boolean canRollForward() { return next != null; } public static void addHistoryListener(IHistoryListener hl) { historyListeners.add(hl); } public static void removeProjectHistory(IProject prj) { Vector list = new Vector(); String id; for (int i = 0; i < _list.size(); i++) { id = (((HistoryItem) _list.elementAt(i)).getProject()).getID(); if (id.equals(prj.getID())) { list.add(_list.elementAt(i)); p--; if (_list.elementAt(i).equals(prev)) { if (p > 0) prev = _list.get(p - 1); else prev = null; } } } if (!list.isEmpty()) { _list.removeAll(list); if (p < 0) { p = 0; } _list.setSize(p); next = null; historyBackAction.update(); historyForwardAction.update(); } } private static void notifyListeners(HistoryItem n) { for (int i = 0; i < historyListeners.size(); i++) ((IHistoryListener) historyListeners.get(i)).historyWasRolledTo(n); } public static HistoryBackAction historyBackAction = new HistoryBackAction(); public static HistoryForwardAction historyForwardAction = new HistoryForwardAction(); static class HistoryBackAction extends AbstractAction { public HistoryBackAction() { super(Local.getString("History back"), new ImageIcon(net.sf.memoranda.ui.AppFrame.class. getResource("resources/icons/hist_back.png"))); putValue(Action.ACCELERATOR_KEY, KeyStroke. getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.ALT_MASK)); setEnabled(false); } public void actionPerformed(ActionEvent e) { notifyListeners(rollBack()); update(); historyForwardAction.update(); } /*public boolean isEnabled() { return canRollBack(); }*/ void update() { if (canRollBack()) { setEnabled(true); SimpleDateFormat sdf = new SimpleDateFormat(); sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT); Date date = ((HistoryItem) prev).getDate().getDate(); putValue( Action.SHORT_DESCRIPTION, Local.getString("Back to") + " " + sdf.format(date)); // putValue(Action.SHORT_DESCRIPTION, Local.getString("Back to") + " " + ((HistoryItem) prev).getDate().toString()); } else { setEnabled(false); putValue(Action.SHORT_DESCRIPTION, Local.getString("Back")); } } } static class HistoryForwardAction extends AbstractAction { public HistoryForwardAction() { super(Local.getString("History forward"), new ImageIcon(net.sf.memoranda.ui.AppFrame.class. getResource("resources/icons/hist_forward.png"))); putValue(Action.ACCELERATOR_KEY, KeyStroke. getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.ALT_MASK)); setEnabled(false); } public void actionPerformed(ActionEvent e) { notifyListeners(rollForward()); update(); historyBackAction.update(); } /*public boolean isEnabled() { return canRollForward(); }*/ void update() { if (canRollForward()) { setEnabled(true); SimpleDateFormat sdf = new SimpleDateFormat(); sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT); Date date = ((HistoryItem) next).getDate().getDate(); putValue( Action.SHORT_DESCRIPTION, // Local.getString("Forward to") + " " + //((HistoryItem) next).getDate().toString()); Local.getString("Forward to") + " " + sdf.format(date)); } else { setEnabled(false); putValue(Action.SHORT_DESCRIPTION, Local.getString("Forward")); } } } }
gpl-2.0
rjsingh/graal
graal/com.oracle.graal.hotspot/src/com/oracle/graal/hotspot/replacements/AbstractMethodHandleNode.java
13229
/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.hotspot.replacements; import java.lang.reflect.Modifier; import java.util.Arrays; import com.oracle.graal.api.meta.Constant; import com.oracle.graal.api.meta.JavaType; import com.oracle.graal.api.meta.ResolvedJavaField; import com.oracle.graal.api.meta.ResolvedJavaMethod; import com.oracle.graal.api.meta.ResolvedJavaType; import com.oracle.graal.graph.GraalInternalError; import com.oracle.graal.graph.NodeInputList; import com.oracle.graal.hotspot.meta.HotSpotResolvedJavaMethod; import com.oracle.graal.hotspot.meta.HotSpotResolvedObjectType; import com.oracle.graal.hotspot.meta.HotSpotSignature; import com.oracle.graal.nodes.CallTargetNode; import com.oracle.graal.nodes.Invoke; import com.oracle.graal.nodes.InvokeNode; import com.oracle.graal.nodes.PiNode; import com.oracle.graal.nodes.ValueNode; import com.oracle.graal.nodes.java.MethodCallTargetNode; import com.oracle.graal.nodes.java.MethodCallTargetNode.InvokeKind; import com.oracle.graal.nodes.java.SelfReplacingMethodCallTargetNode; import com.oracle.graal.nodes.spi.Canonicalizable; import com.oracle.graal.nodes.type.StampFactory; import com.oracle.graal.replacements.nodes.MacroNode; /** * Common base class for method handle invoke nodes. */ public abstract class AbstractMethodHandleNode extends MacroNode implements Canonicalizable { private static final ResolvedJavaField methodHandleFormField; private static final ResolvedJavaField lambdaFormVmentryField; private static final ResolvedJavaField memberNameClazzField; private static final ResolvedJavaField memberNameVmtargetField; // Replacement method data private ResolvedJavaMethod replacementTargetMethod; private JavaType replacementReturnType; @Input private final NodeInputList<ValueNode> replacementArguments; /** * Search for an instance field with the given name in a class. * * @param className name of the class to search in * @param fieldName name of the field to be searched * @return resolved java field * @throws ClassNotFoundException */ private static ResolvedJavaField findFieldInClass(String className, String fieldName) throws ClassNotFoundException { Class<?> clazz = Class.forName(className); ResolvedJavaType type = HotSpotResolvedObjectType.fromClass(clazz); ResolvedJavaField[] fields = type.getInstanceFields(false); for (ResolvedJavaField field : fields) { if (field.getName().equals(fieldName)) { return field; } } return null; } static { try { methodHandleFormField = findFieldInClass("java.lang.invoke.MethodHandle", "form"); lambdaFormVmentryField = findFieldInClass("java.lang.invoke.LambdaForm", "vmentry"); memberNameClazzField = findFieldInClass("java.lang.invoke.MemberName", "clazz"); memberNameVmtargetField = findFieldInClass("java.lang.invoke.MemberName", "vmtarget"); } catch (ClassNotFoundException | SecurityException ex) { throw GraalInternalError.shouldNotReachHere(); } } public AbstractMethodHandleNode(Invoke invoke) { super(invoke); // See if we need to save some replacement method data. CallTargetNode callTarget = invoke.callTarget(); if (callTarget instanceof SelfReplacingMethodCallTargetNode) { SelfReplacingMethodCallTargetNode selfReplacingMethodCallTargetNode = (SelfReplacingMethodCallTargetNode) callTarget; replacementTargetMethod = selfReplacingMethodCallTargetNode.replacementTargetMethod(); replacementReturnType = selfReplacingMethodCallTargetNode.replacementReturnType(); replacementArguments = selfReplacingMethodCallTargetNode.replacementArguments(); } else { // NodeInputList can't be null. replacementArguments = new NodeInputList<>(this); } } /** * Get the receiver of a MethodHandle.invokeBasic call. * * @return the receiver argument node */ private ValueNode getReceiver() { return arguments.first(); } /** * Get the MemberName argument of a MethodHandle.linkTo* call. * * @return the MemberName argument node (which is the last argument) */ private ValueNode getMemberName() { return arguments.last(); } /** * Used from {@link MethodHandleInvokeBasicNode} to get the target {@link InvokeNode} if the * method handle receiver is constant. * * @return invoke node for the {@link java.lang.invoke.MethodHandle} target */ protected InvokeNode getInvokeBasicTarget() { ValueNode methodHandleNode = getReceiver(); if (methodHandleNode.isConstant() && !methodHandleNode.isNullConstant()) { // Get the data we need from MethodHandle.LambdaForm.MemberName Constant methodHandle = methodHandleNode.asConstant(); Constant lambdaForm = methodHandleFormField.readValue(methodHandle); Constant memberName = lambdaFormVmentryField.readValue(lambdaForm); return getTargetInvokeNode(memberName); } return null; } /** * Used from {@link MethodHandleLinkToStaticNode}, {@link MethodHandleLinkToSpecialNode}, * {@link MethodHandleLinkToVirtualNode}, and {@link MethodHandleLinkToInterfaceNode} to get the * target {@link InvokeNode} if the member name argument is constant. * * @return invoke node for the member name target */ protected InvokeNode getLinkToTarget() { ValueNode memberNameNode = getMemberName(); if (memberNameNode.isConstant() && !memberNameNode.isNullConstant()) { Constant memberName = memberNameNode.asConstant(); return getTargetInvokeNode(memberName); } return null; } /** * Helper function to get the {@link InvokeNode} for the vmtarget of a * java.lang.invoke.MemberName. * * @param memberName constant member name node * @return invoke node for the member name target */ private InvokeNode getTargetInvokeNode(Constant memberName) { // Get the data we need from MemberName Constant clazz = memberNameClazzField.readValue(memberName); Constant vmtarget = memberNameVmtargetField.readValue(memberName); // Create a method from the vmtarget pointer Class<?> c = (Class<?>) clazz.asObject(); HotSpotResolvedObjectType holderClass = (HotSpotResolvedObjectType) HotSpotResolvedObjectType.fromClass(c); HotSpotResolvedJavaMethod targetMethod = holderClass.createMethod(vmtarget.asLong()); // In lamda forms we erase signature types to avoid resolving issues // involving class loaders. When we optimize a method handle invoke // to a direct call we must cast the receiver and arguments to its // actual types. HotSpotSignature signature = targetMethod.getSignature(); final boolean isStatic = Modifier.isStatic(targetMethod.getModifiers()); final int receiverSkip = isStatic ? 0 : 1; // Cast receiver to its type. if (!isStatic) { JavaType receiverType = holderClass; maybeCastArgument(0, receiverType); } // Cast reference arguments to its type. for (int index = 0; index < signature.getParameterCount(false); index++) { JavaType parameterType = signature.getParameterType(index, holderClass); maybeCastArgument(receiverSkip + index, parameterType); } // Try to get the most accurate receiver type if (this instanceof MethodHandleLinkToVirtualNode || this instanceof MethodHandleLinkToInterfaceNode) { ResolvedJavaType receiverType = getReceiver().objectStamp().type(); if (receiverType != null) { ResolvedJavaMethod concreteMethod = receiverType.findUniqueConcreteMethod(targetMethod); if (concreteMethod != null) { return createTargetInvokeNode(concreteMethod); } } } if (targetMethod.canBeStaticallyBound()) { return createTargetInvokeNode(targetMethod); } ResolvedJavaMethod concreteMethod = targetMethod.uniqueConcreteMethod(); if (concreteMethod != null) { return createTargetInvokeNode(concreteMethod); } return null; } /** * Inserts a node to cast the argument at index to the given type if the given type is more * concrete than the argument type. * * @param index of the argument to be cast * @param type the type the argument should be cast to */ private void maybeCastArgument(int index, JavaType type) { if (type instanceof ResolvedJavaType) { ResolvedJavaType targetType = (ResolvedJavaType) type; if (!targetType.isPrimitive()) { ValueNode argument = arguments.get(index); ResolvedJavaType argumentType = argument.objectStamp().type(); if (argumentType == null || (argumentType.isAssignableFrom(targetType) && !argumentType.equals(targetType))) { PiNode piNode = graph().unique(new PiNode(argument, StampFactory.declared(targetType))); arguments.set(index, piNode); } } } } /** * Creates an {@link InvokeNode} for the given target method. The {@link CallTargetNode} passed * to the InvokeNode is in fact a {@link SelfReplacingMethodCallTargetNode}. * * @param targetMethod the method the be called * @return invoke node for the member name target */ private InvokeNode createTargetInvokeNode(ResolvedJavaMethod targetMethod) { InvokeKind invokeKind = Modifier.isStatic(targetMethod.getModifiers()) ? InvokeKind.Static : InvokeKind.Special; JavaType returnType = targetMethod.getSignature().getReturnType(null); // MethodHandleLinkTo* nodes have a trailing MemberName argument which // needs to be popped. ValueNode[] originalArguments = arguments.toArray(new ValueNode[arguments.size()]); ValueNode[] targetArguments; if (this instanceof MethodHandleInvokeBasicNode) { targetArguments = originalArguments; } else { assert this instanceof MethodHandleLinkToStaticNode || this instanceof MethodHandleLinkToSpecialNode || this instanceof MethodHandleLinkToVirtualNode || this instanceof MethodHandleLinkToInterfaceNode : this; targetArguments = Arrays.copyOfRange(originalArguments, 0, arguments.size() - 1); } // If there is already replacement information, use that instead. MethodCallTargetNode callTarget; if (replacementTargetMethod == null) { callTarget = new SelfReplacingMethodCallTargetNode(invokeKind, targetMethod, targetArguments, returnType, getTargetMethod(), originalArguments, getReturnType()); } else { ValueNode[] args = replacementArguments.toArray(new ValueNode[replacementArguments.size()]); callTarget = new SelfReplacingMethodCallTargetNode(invokeKind, targetMethod, targetArguments, returnType, replacementTargetMethod, args, replacementReturnType); } graph().add(callTarget); // The call target can have a different return type than the invoker, // e.g. the target returns an Object but the invoker void. In this case // we need to use the stamp of the invoker. Note: always using the // invoker's stamp would be wrong because it's a less concrete type // (usually java.lang.Object). InvokeNode invoke; if (callTarget.returnStamp().kind() != stamp().kind()) { invoke = new InvokeNode(callTarget, getBci(), stamp()); } else { invoke = new InvokeNode(callTarget, getBci()); } graph().add(invoke); invoke.setStateAfter(stateAfter()); return invoke; } }
gpl-2.0
loverdos/javac-openjdk7
src/main/java/openjdk7/com/sun/tools/classfile/Method.java
2443
/* * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package openjdk7.com.sun.tools.classfile; import java.io.IOException; /* * <p><b>This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> */ public class Method { Method(ClassReader cr) throws IOException { access_flags = new AccessFlags(cr); name_index = cr.readUnsignedShort(); descriptor = new Descriptor(cr); attributes = new Attributes(cr); } public Method(AccessFlags access_flags, int name_index, Descriptor descriptor, Attributes attributes) { this.access_flags = access_flags; this.name_index = name_index; this.descriptor = descriptor; this.attributes = attributes; } public int byteLength() { return 6 + attributes.byteLength(); } public String getName(ConstantPool constant_pool) throws ConstantPoolException { return constant_pool.getUTF8Value(name_index); } public final AccessFlags access_flags; public final int name_index; public final Descriptor descriptor; public final Attributes attributes; }
gpl-2.0
jvmvik/Next
SCCM-mock/src/com/arm/nimbus/sccm/websocket/ClientsRepository.java
1323
package com.arm.nimbus.sccm.websocket; import java.io.IOException; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.List; /** * This repository takes care of registering connected clients and of course removing them when they * disconnect. */ public class ClientsRepository { private List<ChatMessageInbound> clients = new ArrayList<>(); /** * Add a new client to the repository. * * @param messageInbound ChatMessageInbound that is the actual client */ public void addClient(ChatMessageInbound messageInbound) { this.clients.add(messageInbound); } /** * Removes the provided client from the repository. * * @param messageInbound ChatMessageInbound that is the actual client */ public void removeClient(ChatMessageInbound messageInbound) { clients.remove(messageInbound); } /** * Send a message to all clients. * * @param message CharBuffer containing the message to send to all clients */ public void sendMessageToAll(CharBuffer message) { try { for (ChatMessageInbound client : clients) { CharBuffer buffer = CharBuffer.wrap(message); client.getWsOutbound().writeTextMessage(buffer); client.getWsOutbound().flush(); } } catch (IOException e) { e.printStackTrace(); } } }
gpl-2.0
FelixResch/HTTPGUI
src/at/resch/html/components/HImage.java
431
package at.resch.html.components; import at.resch.html.elements.IMG; public class HImage extends HComponent<IMG> { /** * */ private static final long serialVersionUID = -6681263549540678207L; public HImage(String id, String url) { super(new IMG(), id); setImageUrl(url); } public void setImageUrl(String url) { parent.setSrc(url); } public String getImageUrl(String url) { return parent.getSrc(); } }
gpl-2.0
klst-com/metasfresh
de.metas.handlingunits.client/src/main/java/de/metas/handlingunits/client/terminal/misc/model/WebCamReceiptScheduleModel.java
3859
/** * */ package de.metas.handlingunits.client.terminal.misc.model; /* * #%L * de.metas.handlingunits.client * %% * Copyright (C) 2015 metas GmbH * %% * 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, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.awt.Dimension; import java.awt.image.BufferedImage; import java.beans.PropertyChangeListener; import java.util.UUID; import org.adempiere.exceptions.AdempiereException; import org.adempiere.model.InterfaceWrapperHelper; import org.adempiere.util.Check; import org.adempiere.util.Services; import org.adempiere.util.beans.WeakPropertyChangeSupport; import com.github.sarxos.webcam.Webcam; import de.metas.adempiere.form.terminal.IDisposable; import de.metas.adempiere.form.terminal.context.ITerminalContext; import de.metas.handlingunits.model.I_M_ReceiptSchedule; import de.metas.handlingunits.receiptschedule.IHUReceiptScheduleBL; /** * * @author metas-dev <dev@metasfresh.com> * */ public class WebCamReceiptScheduleModel implements IDisposable { private static final String ERR_WEBCAM_NOT_FOUND = "WebcamNotFound"; private final ITerminalContext terminalContext; private final WeakPropertyChangeSupport pcs; private Webcam webcam; private Object referencedModel; private boolean disposed = false; /** * * @param terminalContext * @param referenceModel this model will be used to attach to it */ public WebCamReceiptScheduleModel(final ITerminalContext terminalContext, final Object referenceModel) { super(); Check.assumeNotNull(terminalContext, "terminalContext not null"); this.terminalContext = terminalContext; pcs = terminalContext.createPropertyChangeSupport(this); referencedModel = referenceModel; terminalContext.addToDisposableComponents(this); } public ITerminalContext getTerminalContext() { return terminalContext; } public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { pcs.addPropertyChangeListener(propertyName, listener); } public Webcam getWebcam() { if (webcam == null) { webcam = Webcam.getDefault(); if (webcam == null) { throw new AdempiereException("@" + ERR_WEBCAM_NOT_FOUND + "@"); } // // Set to maximum allowed size (if any) final Dimension[] viewSizes = webcam.getViewSizes(); if (viewSizes != null && viewSizes.length > 0) { // they're ordered by size, so get the last one (maximum) final Dimension viewSize = viewSizes[viewSizes.length - 1]; webcam.setViewSize(viewSize); } } return webcam; } public double getFPS() { return 25; } public void savePicture() { webcam.open(); final I_M_ReceiptSchedule receiptSchedule = InterfaceWrapperHelper.create(getReferencedModel(), I_M_ReceiptSchedule.class); final String filename = "Photo_" + UUID.randomUUID() + ".pdf"; final BufferedImage image = webcam.getImage(); Services.get(IHUReceiptScheduleBL.class).attachPhoto(receiptSchedule, filename, image); } @Override public void dispose() { if (webcam != null) { webcam.close(); webcam = null; } referencedModel = null; disposed = true; } @Override public boolean isDisposed() { return disposed; } public Object getReferencedModel() { return referencedModel; } }
gpl-2.0
bedatadriven/renjin
core/src/main/java/org/renjin/invoke/codegen/GeneratorDefinitionException.java
1431
/* * Renjin : JVM-based interpreter for the R language for the statistical analysis * Copyright © 2010-2019 BeDataDriven Groep B.V. and contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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, a copy is available at * https://www.gnu.org/licenses/gpl-2.0.txt */ package org.renjin.invoke.codegen; /** * Exception thrown when there is a problem in the way that * the (renjin) developer has defined or annotated a primitive method. * * @author alex * */ public class GeneratorDefinitionException extends RuntimeException { public GeneratorDefinitionException() { super(); } public GeneratorDefinitionException(String message, Throwable cause) { super(message, cause); } public GeneratorDefinitionException(String message) { super(message); } public GeneratorDefinitionException(Throwable cause) { super(cause); } }
gpl-2.0
SaiPradeepDandem/javafx-demos
src/main/java/com/ezest/javafx/demogallery/panes/ScrollPaneCustomScrollBarDemo.java
2102
package com.ezest.javafx.demogallery.panes; import java.util.HashMap; import com.javafx.experiments.scenicview.ScenicView; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPaneBuilder; import javafx.scene.layout.StackPane; import javafx.scene.layout.StackPaneBuilder; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Screen; import javafx.stage.Stage; public class ScrollPaneCustomScrollBarDemo extends Application { Stage stage; Scene scene; StackPane root; public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) throws Exception { this.stage = stage; configureScene(); configureStage(); ScrollPane bodyScroll = ScrollPaneBuilder.create().fitToHeight(true) .fitToWidth(true) .minHeight(40) .build(); VBox testvb = new VBox(); for (int i = 0; i < 30; i++) { testvb.getChildren().add(new Label("hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello ")); } bodyScroll.setContent(testvb); StackPane sp = new StackPane(); sp.setMaxHeight(200); sp.getChildren().add(bodyScroll); StackPane sp1 = StackPaneBuilder.create().translateY(20).style("-fx-background-color:#86032B;").opacity(.59).maxHeight(200).maxWidth(200).build(); root.getChildren().addAll(sp,sp1); } private void configureStage(){ stage.setTitle(this.getClass().getSimpleName()); stage.setX(0); stage.setY(0); stage.setWidth(Screen.getPrimary().getVisualBounds().getWidth()); stage.setHeight(Screen.getPrimary().getVisualBounds().getHeight()); stage.setScene(this.scene); stage.show(); } private void configureScene(){ root = new StackPane(); root.autosize(); root.maxHeight(200); this.scene = new Scene(root, Color.WHITE); scene.getStylesheets().add("styles/customScrollBar.css"); ScenicView.show(scene); } }
gpl-2.0
BiglySoftware/BiglyBT
core/src/com/biglybt/pifimpl/local/torrent/TorrentAttributeCategoryImpl.java
3779
/* * Created on 23-Jun-2004 * Created by Paul Gardner * Copyright (C) Azureus Software, Inc, All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ package com.biglybt.pifimpl.local.torrent; /** * @author parg * */ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.biglybt.core.category.Category; import com.biglybt.core.category.CategoryManager; import com.biglybt.core.category.CategoryManagerListener; import com.biglybt.pif.torrent.TorrentAttribute; import com.biglybt.pif.torrent.TorrentAttributeEvent; import com.biglybt.pif.utils.StaticUtilities; public class TorrentAttributeCategoryImpl extends BaseTorrentAttributeImpl { protected TorrentAttributeCategoryImpl() { CategoryManager.addCategoryManagerListener( new CategoryManagerListener() { @Override public void categoryAdded( final Category category ) { TorrentAttributeEvent ev = new TorrentAttributeEvent() { @Override public int getType() { return( TorrentAttributeEvent.ET_ATTRIBUTE_VALUE_ADDED ); } @Override public TorrentAttribute getAttribute() { return( TorrentAttributeCategoryImpl.this ); } @Override public Object getData() { return( category.getName()); } }; TorrentAttributeCategoryImpl.this.notifyListeners(ev); } @Override public void categoryChanged(Category category) { } @Override public void categoryRemoved( final Category category ) { TorrentAttributeEvent ev = new TorrentAttributeEvent() { @Override public int getType() { return( TorrentAttributeEvent.ET_ATTRIBUTE_VALUE_REMOVED ); } @Override public TorrentAttribute getAttribute() { return( TorrentAttributeCategoryImpl.this ); } @Override public Object getData() { return( category.getName()); } }; TorrentAttributeCategoryImpl.this.notifyListeners(ev); } }); } @Override public String getName() { return( TA_CATEGORY ); } @Override public String[] getDefinedValues() { Category[] categories = CategoryManager.getCategories(); List v = new ArrayList(); for (int i=0;i<categories.length;i++){ Category cat = categories[i]; if ( cat.getType() == Category.TYPE_USER ){ v.add( cat.getName()); } } String[] res = new String[v.size()]; v.toArray( res ); // make it nice for clients Arrays.sort( res, StaticUtilities.getFormatters().getAlphanumericComparator( true )); return( res ); } @Override public void addDefinedValue( String name ) { CategoryManager.createCategory( name ); } @Override public void removeDefinedValue( String name ) { Category cat = CategoryManager.getCategory( name ); if ( cat != null ){ CategoryManager.removeCategory( cat ); } } }
gpl-2.0
jvmvik/Next
SCCM-mock/src/com/arm/nimbus/sccm/config/HibernateSessionFactory.java
628
package com.arm.nimbus.sccm.config; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * Hibernate Session Factory * * - Ensure that the configuration is called once. * * @author vicben01 */ public class HibernateSessionFactory { static SessionFactory sessionFactory; public static SessionFactory start() { if (sessionFactory == null) { sessionFactory = new Configuration() .configure() .buildSessionFactory(); } return sessionFactory; } public static void stop() { if(sessionFactory != null) sessionFactory.close(); } }
gpl-2.0
LeNiglo/TinyTank
ClientTinyTank/src/main/java/com/lefrantguillaume/components/networkComponent/networkGame/messages/msg/MessageObstacleUpdateState.java
819
package com.lefrantguillaume.components.networkComponent.networkGame.messages.msg; import com.lefrantguillaume.components.networkComponent.networkGame.messages.MessageModel; /** * Created by andres_k on 25/03/2015. */ public class MessageObstacleUpdateState extends MessageModel { private float currentLife; private String obstacleId; public MessageObstacleUpdateState() {} public MessageObstacleUpdateState(String pseudo, String id, String obstacleId, float currentLife){ this.currentLife = currentLife; this.obstacleId = obstacleId; this.playerAction = false; this.id = id; this.pseudo = pseudo; } public String getObstacleId() { return this.obstacleId; } public float getCurrentLife() { return this.currentLife; } }
gpl-2.0
fc7/jabref
src/test/java/net/sf/jabref/importer/OpenDatabaseActionTest.java
4580
package net.sf.jabref.importer; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.Collection; import net.sf.jabref.Globals; import net.sf.jabref.JabRefPreferences; import net.sf.jabref.model.database.BibDatabase; import net.sf.jabref.model.entry.BibEntry; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class OpenDatabaseActionTest { private final Charset defaultEncoding = StandardCharsets.UTF_8; private final File bibNoHeader; private final File bibWrongHeader; private final File bibHeader; private final File bibHeaderAndSignature; private final File bibEncodingWithoutNewline; public OpenDatabaseActionTest() throws URISyntaxException { bibNoHeader = Paths.get(OpenDatabaseActionTest.class.getResource("headerless.bib").toURI()).toFile(); bibWrongHeader = Paths.get(OpenDatabaseActionTest.class.getResource("wrong-header.bib").toURI()).toFile(); bibHeader = Paths.get(OpenDatabaseActionTest.class.getResource("encoding-header.bib").toURI()).toFile(); bibHeaderAndSignature = Paths.get(OpenDatabaseActionTest.class.getResource("jabref-header.bib").toURI()) .toFile(); bibEncodingWithoutNewline = Paths .get(OpenDatabaseActionTest.class.getResource("encodingWithoutNewline.bib").toURI()).toFile(); } @BeforeClass public static void setUpGlobalsPrefs() { // otherwise FieldContentParser (called by BibtexParser) crashes Globals.prefs = JabRefPreferences.getInstance(); } @Test public void useFallbackEncodingIfNoHeader() throws IOException { ParserResult result = OpenDatabaseAction.loadDatabase(bibNoHeader, defaultEncoding); Assert.assertEquals(defaultEncoding, result.getMetaData().getEncoding()); } @Test public void useFallbackEncodingIfUnknownHeader() throws IOException { ParserResult result = OpenDatabaseAction.loadDatabase(bibWrongHeader, defaultEncoding); Assert.assertEquals(defaultEncoding, result.getMetaData().getEncoding()); } @Test public void useSpecifiedEncoding() throws IOException { ParserResult result = OpenDatabaseAction.loadDatabase(bibHeader, StandardCharsets.US_ASCII); Assert.assertEquals(StandardCharsets.UTF_8, result.getMetaData().getEncoding()); } @Test public void useSpecifiedEncodingWithSignature() throws IOException { ParserResult result = OpenDatabaseAction.loadDatabase(bibHeaderAndSignature, StandardCharsets.US_ASCII); Assert.assertEquals(StandardCharsets.UTF_8, result.getMetaData().getEncoding()); } @Test public void entriesAreParsedNoHeader() throws IOException { ParserResult result = OpenDatabaseAction.loadDatabase(bibNoHeader, defaultEncoding); BibDatabase db = result.getDatabase(); // Entry Assert.assertEquals(1, db.getEntryCount()); Assert.assertEquals("2014", db.getEntryByKey("1").getField("year")); } @Test public void entriesAreParsedHeader() throws IOException { ParserResult result = OpenDatabaseAction.loadDatabase(bibHeader, defaultEncoding); BibDatabase db = result.getDatabase(); // Entry Assert.assertEquals(1, db.getEntryCount()); Assert.assertEquals("2014", db.getEntryByKey("1").getField("year")); } @Test public void entriesAreParsedHeaderAndSignature() throws IOException { ParserResult result = OpenDatabaseAction.loadDatabase(bibHeaderAndSignature, defaultEncoding); BibDatabase db = result.getDatabase(); // Entry Assert.assertEquals(1, db.getEntryCount()); Assert.assertEquals("2014", db.getEntryByKey("1").getField("year")); } /** * Test for #669 */ @Test public void correctlyParseEncodingWithoutNewline() throws IOException { ParserResult result = OpenDatabaseAction.loadDatabase(bibEncodingWithoutNewline, defaultEncoding); Assert.assertEquals(StandardCharsets.US_ASCII, result.getMetaData().getEncoding()); BibDatabase db = result.getDatabase(); Assert.assertEquals("testPreamble", db.getPreamble()); Collection<BibEntry> entries = db.getEntries(); Assert.assertEquals(1, entries.size()); BibEntry entry = entries.iterator().next(); Assert.assertEquals("testArticle", entry.getCiteKey()); } }
gpl-2.0
izzi-abd/HQDefender
src/DefenceHQ/Missile.java
435
package DefenceHQ; /** * * @author Abdurrahman Izzi */ public class Missile { private int position; private String state; String getState() { return state; } int getPosition() { return position; } void setState(String p_state) { state = p_state; } void intercept(Radar RDR) { setState("fly"); position=RDR.getERPosition(); } }
gpl-2.0
petersalomonsen/frinika
src/uk/org/toot/audio/eq/ParametricEQ.java
2307
// Copyright (C) 2006 Steve Taylor. // Distributed under the Toot Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.toot.org.uk/LICENSE_1_0.txt) package uk.org.toot.audio.eq; import uk.org.toot.control.ControlLaw; import uk.org.toot.control.LinearLaw; import uk.org.toot.control.LogLaw; import uk.org.toot.dsp.filter.FilterShape; import static uk.org.toot.misc.Localisation.*; /** * A parametric EQ. */ public class ParametricEQ extends AbstractSerialEQ { /** * Creates a default ParametricEQ object. */ public ParametricEQ() { this(new Controls()); } /** * Creates a ParemetricEQ object with the specified controls. */ public ParametricEQ(Controls spec) { super(spec, false); // true means relative levels (to input) } /** * The Controls for a 4 band ParametricEQ. */ static public class Controls extends EQ.Controls { private final static float R = 15f; // dB range, +/- private final static ControlLaw GAIN_LAW = new LinearLaw(-R, R, "dB"); // lin(dB) is log(val) ! private final static ControlLaw Q_LAW = new LogLaw(0.5f, 10f, ""); public Controls() { super(EQIds.PARAMETRIC_EQ_ID, getString("Parametric.EQ")); add(new ClassicFilterControls(getString("Low"), 0, FilterShape.LSH, true, 40f, 3000f, 80, false, Q_LAW, 1f, true, GAIN_LAW, 0f, false)); add(new ClassicFilterControls(getString("Lo.Mid"), 4, FilterShape.PEQ, true, 40f, 3000f, 600, false, Q_LAW, 1f, false, GAIN_LAW, 0f, false)); add(new ClassicFilterControls(getString("Hi.Mid"), 8, FilterShape.PEQ, true, 3000f, 20000f, 4000, false, Q_LAW, 1f, false, GAIN_LAW, 0f, false)); add(new ClassicFilterControls(getString("High"), 16, FilterShape.HSH, true, 3000f, 20000f, 12000, false, Q_LAW, 1f, true, GAIN_LAW, 0f, false)); } } }
gpl-2.0
carvalhomb/tsmells
guess/guess-src/com/hp/hpl/guess/layout/Radial.java
8070
// $Id: Radial.java,v 1.1 2005/10/05 20:19:39 eytanadar Exp $ package com.hp.hpl.guess.layout; import java.util.*; import com.hp.hpl.guess.*; import java.awt.geom.*; import edu.uci.ics.jung.visualization.AbstractLayout; import edu.uci.ics.jung.visualization.Coordinates; import edu.uci.ics.jung.graph.Vertex; /** * The layout computePositions method follows the algorithm * as given by Eades in his paper "Drawing Free Trees", * Bulletin of the Institute for Combinatorics and its Applications, * vol. 5, 10-36, 1992. * * Note: as described by Eades, the algorithm does not allow variable * node size. * * @author Hacked by Eytan Adar for Guess */ public class Radial extends AbstractLayout { protected double layerDistance = 10; Node center = null; Graph tree = null; HashSet ve = null; HashMap locations = new HashMap(); /** * Constructor */ public Radial(Graph tree, Node center, HashSet ve) { super(tree); this.tree = tree; this.center = center; this.ve = ve; Iterator it = tree.getNodes().iterator(); while(it.hasNext()) { Node n = (Node)it.next(); locations.put(n, new Coordinates(n.getX(), n.getY())); } } public Radial(Graph tree, Node center) { this(tree,center,null); } private Graph graph = null; Hashtable coords = new Hashtable(); Hashtable radialWidth = new Hashtable(); HashSet seen = new HashSet(); HashSet validEdges = new HashSet(); // this one takes into account a predefined set of edges public Vector getNextLayerEdgesPredef(Node center) { Vector frontier = new Vector(); Iterator it = center.getOutEdges().iterator(); seen.add(center); while(it.hasNext()) { Edge e = (Edge)it.next(); if (validEdges.contains(e)) { Node n = (Node)e.getOpposite(center); if ((n != center) && (!seen.contains(n))) { //e.getRep().set("width",new Double(5)); frontier.addElement(n); seen.add(n); } } } return(frontier); } public Vector getNextLayer(Node center) { Vector frontier = new Vector(); Iterator it = center.getOutEdges().iterator(); seen.add(center); while(it.hasNext()) { Edge e = (Edge)it.next(); Node n = (Node)e.getOpposite(center); if ((n != center) && (!seen.contains(n))) { validEdges.add(e); //e.getRep().set("width",new Double(5)); frontier.addElement(n); seen.add(n); } } return(frontier); } public void advancePositions() { if (done) return; boolean predef = false; if (ve != null) { predef = true; validEdges = ve; } Vector front = null; if (!predef) { front = getNextLayer(center); } else { front = getNextLayerEdgesPredef(center); } while(front.size() > 0) { Vector nextLayer = new Vector(); for (int i = 0 ; i < front.size() ; i++) { if (!predef) { nextLayer.addAll((Vector)getNextLayer((Node)front.elementAt(i))); } else { nextLayer.addAll((Vector)getNextLayerEdgesPredef((Node)front.elementAt(i))); } } front = nextLayer; } seen.clear(); Iterator it = tree.getNodes().iterator(); while(it.hasNext()) { Node n = (Node)it.next(); layerDistance = Math.max(Math.max(layerDistance,n.getWidth()*5), n.getHeight()*5); } graph = tree; double baseX = 0.0; //System.out.println("\tsetting width prop..."); defineWidthProperty(center,null); //System.out.println("\tsetting laying out..."); double rho = 0.0; double alpha1 = 0.0; double alpha2 = 2 * Math.PI; Point2D nodeCoord = polarToCartesian(rho, (alpha1 + alpha2) / 2, baseX); coords.put(center,nodeCoord); int centerWidth = ((Integer)radialWidth.get(center)).intValue(); rho += layerDistance; Iterator neighbors = ((Node)center).getOutEdges().iterator(); while (neighbors.hasNext()) { Edge e = (Edge)neighbors.next(); if (!validEdges.contains(e)) { continue; } Node neighbor = (Node)e.getOpposite(center); int neighborWidth = ((Integer)radialWidth.get(neighbor)).intValue(); alpha2 = alpha1 + (2* Math.PI * neighborWidth / centerWidth); RadialSubTreeUndirected((Node)center, neighbor, neighborWidth, rho, alpha1, alpha2, tree, baseX); alpha1 = alpha2; } it = tree.getNodes().iterator(); while(it.hasNext()) { Node n = (Node)it.next(); Point2D loc = (Point2D)coords.get(n); if (loc != null) { locations.put(n, new Coordinates(loc.getX(), loc.getY())); } else { //System.out.println("oops... "); } } done = true; } protected void RadialSubTreeUndirected(Node forbiddenNeighbor, Node node, double width, double rho, double alpha1, double alpha2, Graph tree, double baseX) { Point2D nodeCoord = polarToCartesian(rho, (alpha1 + alpha2) / 2, baseX); coords.put(node,nodeCoord); double tau = 2 * Math.acos(rho / (rho + layerDistance)); double alpha = 0.0; double s = 0.0; if (tau < (alpha2 - alpha1)) { alpha = (alpha1 + alpha2 - tau) / 2.0; s = tau / width; //System.out.println("1: " + node + " " + s); } else { alpha = alpha1; s = (alpha2 - alpha1) / width; //System.out.println("2: " + node + " " + s); } Iterator neighbors = node.getOutEdges().iterator(); while (neighbors.hasNext()) { Edge e = (Edge)neighbors.next(); if (!validEdges.contains(e)) { continue; } Node neighbor = (Node)e.getOpposite(node); if (neighbor != forbiddenNeighbor) { int neighborWidth = ((Integer)radialWidth.get(neighbor)).intValue(); if (neighborWidth == 0) { System.out.println(neighbor); } RadialSubTreeUndirected(node, neighbor, neighborWidth, rho + layerDistance, alpha, alpha += s * neighborWidth, tree, baseX); } } } private Point2D polarToCartesian(double rho, double alpha, double Xtranslation) { //System.out.println(rho + " " + alpha + Xtranslation); return new Point2D.Double(rho * Math.cos(alpha) + Xtranslation, rho * Math.sin(alpha)); } /** * This method is actually called only once with the center of the * graph as a parameter. */ private int defineWidthProperty(Node center, Node enteringFrom) { //System.out.println("at: " + center); if (radialWidth.containsKey(center)) { // System.out.println(center + " " + radialWidth.get(center)); //System.out.println("\treturning...\n"); return ((Integer)radialWidth.get(center)).intValue(); } //System.out.println("\trecursing\n"); int width = 0; Iterator edges = ((Node)center).getOutEdges().iterator(); int validNeighbors = 0; while (edges.hasNext()) { Edge edge = (Edge)edges.next(); if (!validEdges.contains(edge)) { continue; } Node goingTo = (Node)edge.getOpposite(center); if (enteringFrom == goingTo) { continue; } validNeighbors++; width += defineWidthProperty(goingTo,center); } if (validNeighbors != 0) { radialWidth.put(center,new Integer(width)); return(width); } else { radialWidth.put(center,new Integer(1)); return(1); } } public double getX(Vertex n) { Coordinates d2d = (Coordinates)locations.get(n); return(d2d.getX()); } public double getY(Vertex n) { Coordinates d2d = (Coordinates)locations.get(n); return(d2d.getY()); } public Coordinates getCoordinates(Node v) { return((Coordinates)locations.get(v)); } public boolean done = false; public boolean incrementsAreDone() { return(done); } public void initialize_local_vertex(edu.uci.ics.jung.graph.Vertex v) { } public void initialize_local() { } public boolean isIncremental() { return(false); } }
gpl-2.0
shamim2014/ResultManagement
src/java/WebApp/repository/StudentDAO.java
810
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package WebApp.repository; import WebApp.Model.Student; import java.util.List; /** * * @author shamim */ public interface StudentDAO { public void saveStudent(Student student); public List<Student> getStudentByYearSemesterAndSession(String year, String semester,String session); public List<Student> getStudentByBatch(String batch); public Student getStudent(String regiSession,String registration); public List<Student> getStudents(); public List<Student> getStudents(String courseCode,String session); public void updateExamRoll(String regiSession,String registration,String examRoll); }
gpl-2.0
inilabs/flashy
src/main/java/com/inivation/operations/EraseOperations.java
3206
package com.inivation.operations; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.usb4java.BufferUtils; import com.inivation.UsbDevice; import javafx.concurrent.Task; public class EraseOperations extends Operations { public static final String PREF_ERASE_SERIAL_NUMBER = "eraseSerialNumber"; private static final byte VR_DEVNAME = (byte) 0xC2; public static final int SNUM_MAX_SIZE = 4; private static final byte VR_EEPROM = (byte) 0xA2; private static final int MAX_TRANSFER_SIZE = 4096; private static final int MAX_EEPROM_SIZE = 32 * 1024; public static Task<Void> serialNumberToROM(final UsbDevice dev, final String serialNumber) { final SerialNumberToROMTask serialNumberToROMTask = new SerialNumberToROMTask(dev, serialNumber.getBytes()); serialNumberToROMTask.start(); return (serialNumberToROMTask); } private static class SerialNumberToROMTask extends InstantTask { private final UsbDevice usbDevice; private final byte[] sNumArray; public SerialNumberToROMTask(final UsbDevice dev, final byte[] sNumArray) { usbDevice = dev; this.sNumArray = sNumArray; } @Override protected void runCall() throws Exception { final ByteBuffer sNum = BufferUtils.allocateByteBuffer(EraseOperations.SNUM_MAX_SIZE); sNum.order(ByteOrder.LITTLE_ENDIAN); // Get the bytes from the input array. sNum.position(EraseOperations.SNUM_MAX_SIZE - sNumArray.length); sNum.put(sNumArray, 0, sNumArray.length); // Pad with zeros at the front, if shorter. for (int i = 0; i < (EraseOperations.SNUM_MAX_SIZE - sNumArray.length); i++) { sNum.put(i, (byte) '0'); } sNum.position(0); // Reset position to initial value. // Write new serial number to RAM and ROM. usbDevice.sendVendorRequest(EraseOperations.VR_DEVNAME, (short) 0x00, (short) 0x00, sNum); } } public static Task<Void> eraseEEPROM(final UsbDevice dev) { final EraseEEPROMTask eraseEEPROMTask = new EraseEEPROMTask(dev); eraseEEPROMTask.start(); return (eraseEEPROMTask); } private static class EraseEEPROMTask extends ProgressTask { private final UsbDevice usbDevice; public EraseEEPROMTask(final UsbDevice dev) { usbDevice = dev; } @Override protected void runCall() throws Exception { // Generate empty ByteBuffer (all zeros) to send to EEPROM. final ByteBuffer eraser = BufferUtils.allocateByteBuffer(EraseOperations.MAX_TRANSFER_SIZE); eraser.put(new byte[EraseOperations.MAX_TRANSFER_SIZE]); eraser.position(0); // Reset position to initial value. // Send out the actual data to the FX2 EEPROM, in 4 KB chunks. int fwLength = EraseOperations.MAX_EEPROM_SIZE; int fwOffset = 0; // Support progress counter (98% allocated to app). updateProgress(2, 100); final double progressPerKB = 98.0 / (fwLength / 1024.0); while (fwLength > 0) { usbDevice.sendVendorRequest(EraseOperations.VR_EEPROM, (short) (fwOffset & 0xFFFF), (short) 0, eraser); fwLength -= EraseOperations.MAX_TRANSFER_SIZE; fwOffset += EraseOperations.MAX_TRANSFER_SIZE; // Update progress based on index (reached length). updateProgress((long) (((fwOffset / 1024.0) * progressPerKB) + 2.0), 100); } } } }
gpl-2.0
lukaspj/PvC-Projekt
src/com/pik_ant/projectslug/Map.java
4399
package com.pik_ant.projectslug; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.location.LocationManager; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Vibrator; import android.view.Menu; import android.view.View; import android.widget.Toast; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.LatLng; /** * @author baljenurface * */ public class Map extends Activity{ private LocationManager locationManager; private GoogleMap gMap; private MapModifier modifier; private BluetoothAdapter adapter; private WifiManager wifiManager; private List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>(); private HashMap<String, Location> bssidLocationMap = new HashMap<String, Location>(); private String bluetoothTarget = null; private Vibrator vibrator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); getActionBar().hide(); MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); gMap = mapFragment.getMap(); gMap.setMyLocationEnabled(true); vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); adapter = BluetoothAdapter.getDefaultAdapter(); modifier = new MapModifier(gMap, locationManager, this, getFragmentManager()); modifier.getLocation(); modifier.getLocationMarkers(); IntentFilter filter = new IntentFilter(android.bluetooth.BluetoothDevice.ACTION_FOUND); IntentFilter filter2 = new IntentFilter(android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED); registerReceiver(mReceiver, filter); registerReceiver(mReceiver, filter2); wifiManager.setWifiEnabled(true); wifiManager.startScan(); List<ScanResult> scanResult = wifiManager.getScanResults(); for(ScanResult s : scanResult){ if (s.level >= 15){ bssidLocationMap.put(s.BSSID , modifier.getCurLocation()); } } if (!adapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); } adapter.startDiscovery(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.map, menu); return true; } @Override protected void onResume(){ super.onResume(); } //The BroadcastReceiver that listens for bluetooth broadcasts private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (BluetoothDevice.ACTION_FOUND.equals(action)) { devices.add(device); if(device.getAddress().equals(bluetoothTarget)){ vibrator.vibrate(100); Toast.makeText(context, "Your target is in range", Toast.LENGTH_LONG).show(); } } } }; //we use degrees as range so 0.01 degrees is around public void findNewTarget(View v){ User u = new User(); LatLng ln = modifier.userMarkersMap.get("tubidibidu").getPosition(); u.lat = ln.latitude; u.lng = ln.longitude; CloudInterface.radiusSearch(u, 0.3, new CloudCallback(){ public void RadiusSearchRecieved(List<User> lis){ if(!lis.isEmpty()){ int i = new Random().nextInt(lis.size()-1); modifier.setTargetIcon(lis.get(i).Username); bluetoothTarget = lis.get(i).BluetoothID; } } }); } public void addDevice(BluetoothDevice d){ devices.add(d); } }
gpl-2.0
tigerisadandan/tianyu
wndjsbg-1.1/src/main/java/com/ccthanking/business/dtgl/wxy/dao/impl/WxySjkGcDaoImpl.java
3408
/* ================================================================== * 版权: kcit 版权所有 (c) 2013 * 文件: com.ccthanking.business.dtgl.wxy.WxySjkGcDao.java * 创建日期: 2015-05-08 下午 04:33:53 * 功能: 深基坑过程管理 * 所含类: {包含的类} * 修改记录: * 日期 作者 内容 * ================================================================== * 2015-05-08 下午 04:33:53 曹伟杰 创建文件,实现基本功能 * * ================================================================== */ package com.ccthanking.business.dtgl.wxy.dao.impl; import java.sql.Connection; import java.util.Map; import org.springframework.stereotype.Component; import com.ccthanking.business.dtgl.wxy.dao.WxySjkGcDao; import com.ccthanking.business.dtgl.wxy.vo.WxySjkGcVO; import com.ccthanking.common.BusinessUtil; import com.ccthanking.framework.common.BaseResultSet; import com.ccthanking.framework.common.DBUtil; import com.ccthanking.framework.common.PageManager; import com.ccthanking.framework.common.User; import com.ccthanking.framework.dao.impl.BsBaseDaoTJdbc; import com.ccthanking.framework.handle.ActionContext; import com.ccthanking.framework.util.RequestUtil; import com.copj.modules.utils.exception.DaoException; /** * <p> WxySjkGcDao.java </p> * <p> 功能:深基坑过程管理 </p> * * <p><a href="WxySjkGcDao.java.html"><i>查看源代码</i></a></p> * * @author <a href="mailto:caochennihao1@163.com">曹伟杰</a> * @version 0.1 * @since 2015-05-08 * */ @Component public class WxySjkGcDaoImpl extends BsBaseDaoTJdbc implements WxySjkGcDao { public String queryCondition(String json, WxySjkGcVO vo, Map map){ User user = ActionContext.getCurrentUserInThread(); Connection conn = DBUtil.getConnection(); String domresult = ""; try { // 组织查询条件 PageManager page = RequestUtil.getPageManager(json); String condition = RequestUtil.getConditionList(json).getConditionWhere(); String orderFilter = RequestUtil.getOrderFilter(json); condition += BusinessUtil.getCommonCondition(user, null); condition += orderFilter; if (page == null) page = new PageManager(); page.setFilter(condition); String sql = "SELECT * FROM " + "WXY_SJK_GC t "; BaseResultSet bs = DBUtil.query(conn, sql, page); // 合同表 // bs.setFieldTranslater("HTID", "合同表", "ID", "NAME"); // 项目下达库 // bs.setFieldTranslater("XDKID", "GC_TCJH_XMXDK", "ID", "XMMC"); // 标段表 // bs.setFieldTranslater("BDID", "GC_XMBD", "GC_XMBD_ID", "BDMC"); // 设置字典 // 设置查询条件 // bs.setFieldDateFormat("JLRQ", "yyyy-MM");// 计量月份 // bs.setFieldThousand("DYJLSDZ"); domresult = bs.getJson(); } catch (Exception e) { DaoException.handleMessageException("*********查询出错!*********"); } finally { DBUtil.closeConnetion(conn); } return domresult; } // 在此可加入其它方法 }
gpl-2.0
tigerisadandan/tianyu
wndjsbg-1.1/src/main/java/com/ccthanking/business/ywlz/service/BuSpYwlzService.java
2846
/* ================================================================== * 版权: kcit 版权所有 (c) 2013 * 文件: ywlz.service.BuSpYwlzService.java * 创建日期: 2014-06-19 下午 04:51:04 * 功能: 接口:审批业务流转实例 * 所含类: {包含的类} * 修改记录: * 日期 作者 内容 * ================================================================== * 2014-06-19 下午 04:51:04 隆楚雄 创建文件,实现基本功能 * * ================================================================== */ package com.ccthanking.business.ywlz.service; import java.util.Map; import javax.servlet.http.HttpServletResponse; import com.ccthanking.business.ywlz.vo.BuSpYwlzVO; import com.ccthanking.framework.service.IBaseService; /** * <p> BuSpYwlzService.java </p> * <p> 功能:审批业务流转实例 </p> * * <p><a href="BuSpYwlzService.java.html"><i>查看源代码</i></a></p> * * @author <a href="mailto:longchuxiong@kzcpm.com">隆楚雄</a> * @version 0.1 * @since 2014-06-19 * */ public interface BuSpYwlzService extends IBaseService<BuSpYwlzVO, String> { /** * 根据条件查询记录. * * @param json * @param user * @return * @throws Exception * @since v1.00 */ String queryCondition(String json,String spyw_uid_res) throws Exception; String queryClType(String json) throws Exception; String queryByProjectsid(String json) throws Exception; /** * 新增记录. * * @param json * @param user * @return * @throws Exception * @since v1.00 */ String insert(String json) throws Exception; /** * 修改记录. * * @param json * @param user * @return * @throws Exception * @since v1.00 */ String update(String json) throws Exception; /** * 删除记录. * * @param json * @param user * @return * @throws Exception * @since v1.00 */ String delete(String json) throws Exception; public BuSpYwlzVO updateVo(BuSpYwlzVO vo) throws Exception; /** * 获取材料记录. */ public String queryYwcl(Map map) throws Exception; public String getSpCount(String spywuid) throws Exception; public String sfysp(String ywlzuid)throws Exception; public String getAllDsCount() throws Exception; String downloadGc(HttpServletResponse response,String json,String bh) throws Exception; String downloadJz(HttpServletResponse response,String json) throws Exception; String downloadSz(HttpServletResponse response,String json) throws Exception; }
gpl-2.0
rajdeeprath/poor-man-transcoder
ffmpeg-transcoder/src/main/java/com/flashvisions/server/rtmp/transcoder/interfaces/IFrameRate.java
125
package com.flashvisions.server.rtmp.transcoder.interfaces; public interface IFrameRate extends IPassThru, IParameter { }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest18384.java
2162
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark 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, version 2. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest18384") public class BenchmarkTest18384 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> names = request.getParameterNames(); if (names.hasMoreElements()) { param = names.nextElement(); // just grab first element } String bar = doSomething(param); // javax.servlet.http.HttpSession.putValue(java.lang.String^,java.lang.Object) request.getSession().putValue( bar, "foo"); } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar; // Simple ? condition that assigns constant to bar on true condition int i = 106; bar = (7*18) + i > 200 ? "This_should_always_happen" : param; return bar; } }
gpl-2.0
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java-gen/org/eevolution/model/X_PP_Order_BOM.java
12583
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU 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., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.eevolution.model; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.Properties; import org.compiere.model.*; import org.compiere.util.KeyNamePair; /** Generated Model for PP_Order_BOM * @author Adempiere (generated) * @version Release 3.5.4a - $Id$ */ public class X_PP_Order_BOM extends PO implements I_PP_Order_BOM, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_PP_Order_BOM (Properties ctx, int PP_Order_BOM_ID, String trxName) { super (ctx, PP_Order_BOM_ID, trxName); /** if (PP_Order_BOM_ID == 0) { setC_UOM_ID (0); setM_Product_ID (0); setName (null); setPP_Order_BOM_ID (0); setPP_Order_ID (0); setValidFrom (new Timestamp( System.currentTimeMillis() )); setValue (null); } */ } /** Load Constructor */ public X_PP_Order_BOM (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 3 - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_PP_Order_BOM[") .append(get_ID()).append("]"); return sb.toString(); } /** BOMType AD_Reference_ID=347 */ public static final int BOMTYPE_AD_Reference_ID=347; /** Current Active = A */ public static final String BOMTYPE_CurrentActive = "A"; /** Make-To-Order = O */ public static final String BOMTYPE_Make_To_Order = "O"; /** Previous = P */ public static final String BOMTYPE_Previous = "P"; /** Previous, Spare = S */ public static final String BOMTYPE_PreviousSpare = "S"; /** Future = F */ public static final String BOMTYPE_Future = "F"; /** Maintenance = M */ public static final String BOMTYPE_Maintenance = "M"; /** Repair = R */ public static final String BOMTYPE_Repair = "R"; /** Product Configure = C */ public static final String BOMTYPE_ProductConfigure = "C"; /** Make-To-Kit = K */ public static final String BOMTYPE_Make_To_Kit = "K"; /** Set BOM Type. @param BOMType Type of BOM */ public void setBOMType (String BOMType) { set_Value (COLUMNNAME_BOMType, BOMType); } /** Get BOM Type. @return Type of BOM */ public String getBOMType () { return (String)get_Value(COLUMNNAME_BOMType); } /** BOMUse AD_Reference_ID=348 */ public static final int BOMUSE_AD_Reference_ID=348; /** Master = A */ public static final String BOMUSE_Master = "A"; /** Engineering = E */ public static final String BOMUSE_Engineering = "E"; /** Manufacturing = M */ public static final String BOMUSE_Manufacturing = "M"; /** Planning = P */ public static final String BOMUSE_Planning = "P"; /** Quality = Q */ public static final String BOMUSE_Quality = "Q"; /** Set BOM Use. @param BOMUse The use of the Bill of Material */ public void setBOMUse (String BOMUse) { set_Value (COLUMNNAME_BOMUse, BOMUse); } /** Get BOM Use. @return The use of the Bill of Material */ public String getBOMUse () { return (String)get_Value(COLUMNNAME_BOMUse); } /** Set Copy From. @param CopyFrom Copy From Record */ public void setCopyFrom (String CopyFrom) { set_Value (COLUMNNAME_CopyFrom, CopyFrom); } /** Get Copy From. @return Copy From Record */ public String getCopyFrom () { return (String)get_Value(COLUMNNAME_CopyFrom); } public I_C_UOM getC_UOM() throws RuntimeException { return (I_C_UOM)MTable.get(getCtx(), I_C_UOM.Table_Name) .getPO(getC_UOM_ID(), get_TrxName()); } /** Set UOM. @param C_UOM_ID Unit of Measure */ public void setC_UOM_ID (int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, Integer.valueOf(C_UOM_ID)); } /** Get UOM. @return Unit of Measure */ public int getC_UOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_UOM_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Document No. @param DocumentNo Document sequence number of the document */ public void setDocumentNo (String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } /** Get Document No. @return Document sequence number of the document */ public String getDocumentNo () { return (String)get_Value(COLUMNNAME_DocumentNo); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } public I_M_AttributeSetInstance getM_AttributeSetInstance() throws RuntimeException { return (I_M_AttributeSetInstance)MTable.get(getCtx(), I_M_AttributeSetInstance.Table_Name) .getPO(getM_AttributeSetInstance_ID(), get_TrxName()); } /** Set Attribute Set Instance. @param M_AttributeSetInstance_ID Product Attribute Set Instance */ public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID)); } /** Get Attribute Set Instance. @return Product Attribute Set Instance */ public int getM_AttributeSetInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_ChangeNotice getM_ChangeNotice() throws RuntimeException { return (I_M_ChangeNotice)MTable.get(getCtx(), I_M_ChangeNotice.Table_Name) .getPO(getM_ChangeNotice_ID(), get_TrxName()); } /** Set Change Notice. @param M_ChangeNotice_ID Bill of Materials (Engineering) Change Notice (Version) */ public void setM_ChangeNotice_ID (int M_ChangeNotice_ID) { if (M_ChangeNotice_ID < 1) set_Value (COLUMNNAME_M_ChangeNotice_ID, null); else set_Value (COLUMNNAME_M_ChangeNotice_ID, Integer.valueOf(M_ChangeNotice_ID)); } /** Get Change Notice. @return Bill of Materials (Engineering) Change Notice (Version) */ public int getM_ChangeNotice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeNotice_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Manufacturing Order BOM. @param PP_Order_BOM_ID Manufacturing Order BOM */ public void setPP_Order_BOM_ID (int PP_Order_BOM_ID) { if (PP_Order_BOM_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_BOM_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_BOM_ID, Integer.valueOf(PP_Order_BOM_ID)); } /** Get Manufacturing Order BOM. @return Manufacturing Order BOM */ public int getPP_Order_BOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_BOM_ID); if (ii == null) return 0; return ii.intValue(); } public org.eevolution.model.I_PP_Order getPP_Order() throws RuntimeException { return (org.eevolution.model.I_PP_Order)MTable.get(getCtx(), org.eevolution.model.I_PP_Order.Table_Name) .getPO(getPP_Order_ID(), get_TrxName()); } /** Set Manufacturing Order. @param PP_Order_ID Manufacturing Order */ public void setPP_Order_ID (int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID)); } /** Get Manufacturing Order. @return Manufacturing Order */ public int getPP_Order_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Revision. @param Revision Revision */ public void setRevision (String Revision) { set_Value (COLUMNNAME_Revision, Revision); } /** Get Revision. @return Revision */ public String getRevision () { return (String)get_Value(COLUMNNAME_Revision); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
gpl-2.0
edijman/SOEN_6431_Colonization_Game
src/net/sf/freecol/client/gui/panel/FreeColChoiceDialog.java
3070
/** * Copyright (C) 2002-2015 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.client.gui.panel; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JFrame; import net.sf.freecol.client.FreeColClient; import net.sf.freecol.client.gui.ChoiceItem; import net.sf.freecol.common.i18n.Messages; /** * A simple modal choice dialog. */ public class FreeColChoiceDialog<T> extends FreeColDialog<T> { /** * Internal constructor. * * @param freeColClient The <code>FreeColClient</code> for the game. * @param frame The owner frame. */ protected FreeColChoiceDialog(FreeColClient freeColClient, JFrame frame) { super(freeColClient, frame); } /** * Create a new <code>FreeColChoiceDialog</code> with a text and a * ok/cancel option. * * @param freeColClient The <code>FreeColClient</code> for the game. * @param frame The owner frame. * @param modal True if this dialog should be modal. * @param obj An object that explains the choice for the user. * @param icon An optional icon to display. * @param cancelKey Key for the text of the optional cancel button. * @param choices A list of <code>ChoiceItem</code>s to create buttons for. */ public FreeColChoiceDialog(final FreeColClient freeColClient, JFrame frame, boolean modal, Object obj, ImageIcon icon, String cancelKey, List<ChoiceItem<T>> choices) { this(freeColClient, frame); initializeChoiceDialog(frame, modal, obj, icon, cancelKey, choices); } /** * @param frame The owner frame. * @param modal True if this dialog should be modal. * @param obj An object that explains the choice for the user. * @param icon An optional icon to display. * @param cancelKey Key for the text of the optional cancel button. * @param choices A list of <code>ChoiceItem</code>s to create buttons for. */ protected final void initializeChoiceDialog(JFrame frame, boolean modal, Object obj, ImageIcon icon, String cancelKey, List<ChoiceItem<T>> choices) { if (cancelKey != null) { choices.add(new ChoiceItem<>(Messages.message(cancelKey), (T)null) .cancelOption().defaultOption()); } initializeDialog(frame, DialogType.PLAIN, modal, obj, icon, choices); } }
gpl-2.0
marcoargenti/Cleaner
src/main/java/schema/mysql/enums/DbEventPriv.java
821
/** * This class is generated by jOOQ */ package schema.mysql.enums; /** * This class is generated by jOOQ. */ @javax.annotation.Generated( value = { "http://www.jooq.org", "jOOQ version:3.5.4" }, comments = "This class is generated by jOOQ" ) @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public enum DbEventPriv implements org.jooq.EnumType { N("N"), Y("Y"); private final java.lang.String literal; private DbEventPriv(java.lang.String literal) { this.literal = literal; } /** * {@inheritDoc} */ @Override public org.jooq.Schema getSchema() { return null; } /** * {@inheritDoc} */ @Override public java.lang.String getName() { return "db_Event_priv"; } /** * {@inheritDoc} */ @Override public java.lang.String getLiteral() { return literal; } }
gpl-2.0
android-plugin/uexGestureUnlock
src/org/zywx/wbpalmstar/plugin/uexgestureunlock/EUExGestureUnlock.java
13731
package org.zywx.wbpalmstar.plugin.uexgestureunlock; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.ViewGroup; import android.widget.RelativeLayout; import org.zywx.wbpalmstar.base.BUtility; import org.zywx.wbpalmstar.engine.DataHelper; import org.zywx.wbpalmstar.engine.EBrowserView; import org.zywx.wbpalmstar.engine.universalex.EUExBase; import org.zywx.wbpalmstar.engine.universalex.EUExCallback; import org.zywx.wbpalmstar.engine.universalex.EUExUtil; import org.zywx.wbpalmstar.plugin.uexgestureunlock.fragment.GestureCreateFragment; import org.zywx.wbpalmstar.plugin.uexgestureunlock.fragment.GestureVerifyFragment; import org.zywx.wbpalmstar.plugin.uexgestureunlock.vo.ConfigGestureVO; import org.zywx.wbpalmstar.plugin.uexgestureunlock.vo.CreateGestureVO; import org.zywx.wbpalmstar.plugin.uexgestureunlock.vo.ResultEventVO; import org.zywx.wbpalmstar.plugin.uexgestureunlock.vo.ResultFailedVO; import org.zywx.wbpalmstar.plugin.uexgestureunlock.vo.ResultIsGestureSetVO; import org.zywx.wbpalmstar.plugin.uexgestureunlock.vo.ResultVerifyVO; public class EUExGestureUnlock extends EUExBase { private static final String PRES_KEY = "uexGestureUnlock_data_code"; private static final String PRES_DATA_GESTURE = "uexGestureUnlock_data_code"; private static final String TAG_GESTURE_VERIFY = "uexGestureUnlock_verify"; private static final String TAG_GESTURE_CREATE = "uexGestureUnlock_create"; private GestureVerifyFragment mGestureVerifyFragment; private GestureCreateFragment mGestureCreateFragment; private SharedPreferences mPres; private ConfigGestureVO mData; public EUExGestureUnlock(Context context, EBrowserView eBrowserView) { super(context, eBrowserView); mPres = mContext.getSharedPreferences(PRES_KEY, Activity.MODE_PRIVATE); } @Override protected boolean clean() { return false; } public boolean isGestureCodeSet(String[] params) { boolean isGestureCodeSet = !TextUtils.isEmpty(getGestureData()); ResultIsGestureSetVO result = new ResultIsGestureSetVO(); result.setResult(isGestureCodeSet); callBackPluginJs(JsConst.CALLBACK_IS_GESTURE_CODE_SET, DataHelper.gson.toJson(result)); return isGestureCodeSet; } public void resetGestureCode(String[] params) { mPres.edit().remove(PRES_DATA_GESTURE).apply(); } public void config(String[] params) { String json = params[0]; if (TextUtils.isEmpty(json)) return; mData = DataHelper.gson.fromJson(json, ConfigGestureVO.class); if (!TextUtils.isEmpty(mData.getBackgroundImage())){ String path = BUtility.makeRealPath( BUtility.makeUrl(mBrwView.getCurrentUrl(), mData.getBackgroundImage()), mBrwView.getCurrentWidget().m_widgetPath, mBrwView.getCurrentWidget().m_wgtType); mData.setBackgroundImage(path); } if (!TextUtils.isEmpty(mData.getIconImage())){ String path = BUtility.makeRealPath( BUtility.makeUrl(mBrwView.getCurrentUrl(), mData.getIconImage()), mBrwView.getCurrentWidget().m_widgetPath, mBrwView.getCurrentWidget().m_wgtType); mData.setIconImage(path); } } public void verify(String[] params) { int callbackId=-1; if (params!=null&&params.length>0){ callbackId= Integer.parseInt(params[0]); } final String gestureCode = getGestureData(); if (TextUtils.isEmpty(gestureCode)){ ResultFailedVO result = new ResultFailedVO(); result.setErrorCode(JsConst.ERROR_CODE_NONE_GESTURE); result.setErrorString(EUExUtil .getString("plugin_uexGestureUnlock_errorCodeNoneGesture")); callBackVerify(result, callbackId); return; } openVerifyGestureLayout(false, gestureCode, callbackId); } public void create(String[] params) { boolean isNeedVerifyBeforeCreate = true; if (params != null && params.length > 0) { CreateGestureVO dataVO = DataHelper.gson.fromJson(params[0], CreateGestureVO.class); if(dataVO != null){ isNeedVerifyBeforeCreate = dataVO.isNeedVerifyBeforeCreate(); } } int callbackId=-1; if (params!=null&&params.length>1){ callbackId= Integer.parseInt(params[1]); } if (isNeedVerifyBeforeCreate && !TextUtils.isEmpty(getGestureData())){ openVerifyGestureLayout(true, getGestureData(), callbackId); }else{ openCreateGestureLayout(callbackId); } } private void openVerifyGestureLayout(boolean isHasCreate, String gestureCode, int callbackId) { if (mGestureVerifyFragment != null){ closeVerifyFragment(); } mGestureVerifyFragment = new GestureVerifyFragment(); mGestureVerifyListener.callbackId=callbackId; mGestureVerifyListener.isCreate=isHasCreate; mGestureVerifyFragment.setGestureVerifyListener(mGestureVerifyListener); mGestureVerifyFragment.setGestureCodeData(gestureCode); mGestureVerifyFragment.setData(mData); mGestureVerifyFragment.setIsHasCreate(isHasCreate); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); addFragmentToCurrentWindow(mGestureVerifyFragment, lp, TAG_GESTURE_VERIFY); } private void openCreateGestureLayout(int callbackId) { if (mGestureVerifyFragment != null){ closeCreateFragment(); } mGestureCreateFragment = new GestureCreateFragment(); mGestureCreateListener.callbackId=callbackId; mGestureCreateFragment.setGestureCreateListener(mGestureCreateListener); mGestureCreateFragment.setData(mData); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); addFragmentToCurrentWindow(mGestureCreateFragment, lp, TAG_GESTURE_CREATE); } public void cancel(String[] params) { if (mGestureVerifyFragment != null){ closeVerifyFragment(); ResultFailedVO result =new ResultFailedVO(); result.setIsFinished(false); result.setErrorCode(JsConst.ERROR_CODE_CANCEL_OUTSIDE); result.setErrorString(EUExUtil .getString("plugin_uexGestureUnlock_errorCodeCancelOutside")); callBackVerify(result,mGestureVerifyListener.callbackId); } if (mGestureCreateFragment != null){ closeCreateFragment(); ResultFailedVO result =new ResultFailedVO(); result.setIsFinished(false); result.setErrorCode(JsConst.ERROR_CODE_CANCEL_OUTSIDE); result.setErrorString(EUExUtil .getString("plugin_uexGestureUnlock_errorCodeCancelOutside")); callBackCreate(result, mGestureCreateListener.callbackId); } } private void callBackPluginJs(String methodName, String jsonData){ String js = SCRIPT_HEADER + "if(" + methodName + "){" + methodName + "('" + jsonData + "');}"; onCallback(js); } MyGestureVerifyListener mGestureVerifyListener=new MyGestureVerifyListener(); public class MyGestureVerifyListener implements GestureVerifyListener{ public boolean isCreate=false; public int callbackId=-1; @Override public void onVerifyResult(ResultVerifyVO result) { callBackVerify(result,callbackId); } @Override public void closeLayout() { closeVerifyFragment(); } @Override public void onStartCreate() { openCreateGestureLayout(callbackId); } @Override public void onCancel() { ResultFailedVO result = new ResultFailedVO(); result.setIsFinished(false); result.setErrorCode(JsConst.ERROR_CODE_CANCEL_VERIFY); result.setErrorString(EUExUtil .getString("plugin_uexGestureUnlock_errorCodeCancelVerify")); if (isCreate){ callBackCreate(result,mGestureCreateListener.callbackId); }else{ callBackVerify(result,callbackId); callBackEvent(JsConst.EVENT_CANCEL_VERIFY); this.closeLayout(); } } @Override public void onEventOccur(int eventCode) { callBackEvent(eventCode); } }; private void callBackEvent(int code){ ResultEventVO result = new ResultEventVO(); result.setEventCode(code); callBackPluginJs(JsConst.ON_EVENT_OCCUR, DataHelper.gson.toJson(result)); } private void callBackVerify(ResultVerifyVO result,int callbackId) { if(callbackId!=-1){ if (result.isFinished()){ callbackToJs(callbackId,false, EUExCallback.F_C_SUCCESS); }else { ResultFailedVO failedVO = (ResultFailedVO) result; callbackToJs(callbackId,false, failedVO.getErrorCode(), failedVO.getErrorString()); } }else{ callBackPluginJs(JsConst.CALLBACK_VERIFY, DataHelper.gson.toJson(result)); } } private void callBackCreate(ResultFailedVO result, int callbackId) { if(callbackId!=-1){ if (result.isFinished()){ callbackToJs(callbackId,false, EUExCallback.F_C_SUCCESS); }else { callbackToJs(callbackId,false, result.getErrorCode(), result.getErrorString()); } }else{ callBackPluginJs(JsConst.CALLBACK_CREATE, DataHelper.gson.toJson(result)); } } MyGestureCreateListener mGestureCreateListener=new MyGestureCreateListener(); public class MyGestureCreateListener implements GestureCreateListener{ private int callbackId=-1; @Override public void onCreateFinished(String gestureCode) { ResultVerifyVO result; if (!TextUtils.isEmpty(gestureCode)){ setGestureData(gestureCode); result = new ResultVerifyVO(); result.setIsFinished(true); }else { result = new ResultFailedVO(); result.setIsFinished(false); } if(callbackId!=-1){ if (result.isFinished()){ callbackToJs(callbackId,false, EUExCallback.F_C_SUCCESS); }else { ResultFailedVO failedVO = (ResultFailedVO) result; callbackToJs(callbackId,false, failedVO.getErrorCode(), failedVO.getErrorString()); } }else { callBackPluginJs(JsConst.CALLBACK_CREATE, DataHelper.gson.toJson(result)); } closeCreateFragment(); } @Override public void onCreateFailed(ResultVerifyVO result) { } @Override public void closeLayout() { closeCreateFragment(); } @Override public void onCancel() { ResultFailedVO result = new ResultFailedVO(); result.setIsFinished(false); result.setErrorCode(JsConst.ERROR_CODE_CANCEL_CREATE); result.setErrorString(EUExUtil .getString("plugin_uexGestureUnlock_errorCodeCancelCreate")); callBackCreate(result, mGestureCreateListener.callbackId); callBackEvent(JsConst.EVENT_CANCEL_CREATE); this.closeLayout(); } @Override public void onEventOccur(int eventCode) { callBackEvent(eventCode); } }; public interface GestureVerifyListener{ public void onVerifyResult(ResultVerifyVO result); public void closeLayout(); public void onStartCreate(); public void onCancel(); public void onEventOccur(int eventCode); } public interface GestureCreateListener{ public void onCreateFinished(String gestureCode); public void onCreateFailed(ResultVerifyVO result); public void closeLayout(); public void onCancel(); public void onEventOccur(int eventCode); } private String getGestureData(){ return mPres.getString(PRES_DATA_GESTURE, ""); } private void setGestureData(String code){ SharedPreferences.Editor editor = mPres.edit(); editor.putString(PRES_DATA_GESTURE, code); editor.commit(); } private void closeCreateFragment() { if (mGestureCreateFragment != null){ removeFragmentFromWindow(mGestureCreateFragment); mGestureCreateFragment = null; } } private void closeVerifyFragment() { if (mGestureVerifyFragment != null){ removeFragmentFromWindow(mGestureVerifyFragment); mGestureVerifyFragment = null; } } }
gpl-2.0
marcoargenti/Cleaner
src/main/java/cleandb/mysql/tables/Event.java
8138
/** * This class is generated by jOOQ */ package cleandb.mysql.tables; /** * Events */ @javax.annotation.Generated( value = { "http://www.jooq.org", "jOOQ version:3.5.4" }, comments = "This class is generated by jOOQ" ) @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Event extends org.jooq.impl.TableImpl<cleandb.mysql.tables.records.EventRecord> { private static final long serialVersionUID = -13383248; /** * The reference instance of <code>mysql.event</code> */ public static final cleandb.mysql.tables.Event EVENT = new cleandb.mysql.tables.Event(); /** * The class holding records for this type */ @Override public java.lang.Class<cleandb.mysql.tables.records.EventRecord> getRecordType() { return cleandb.mysql.tables.records.EventRecord.class; } /** * The column <code>mysql.event.db</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.lang.String> DB = createField("db", org.jooq.impl.SQLDataType.CHAR.length(64).nullable(false).defaulted(true), this, ""); /** * The column <code>mysql.event.name</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.lang.String> NAME = createField("name", org.jooq.impl.SQLDataType.CHAR.length(64).nullable(false).defaulted(true), this, ""); /** * The column <code>mysql.event.body</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, byte[]> BODY = createField("body", org.jooq.impl.SQLDataType.BLOB.nullable(false), this, ""); /** * The column <code>mysql.event.definer</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.lang.String> DEFINER = createField("definer", org.jooq.impl.SQLDataType.CHAR.length(77).nullable(false).defaulted(true), this, ""); /** * The column <code>mysql.event.execute_at</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.sql.Timestamp> EXECUTE_AT = createField("execute_at", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * The column <code>mysql.event.interval_value</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.lang.Integer> INTERVAL_VALUE = createField("interval_value", org.jooq.impl.SQLDataType.INTEGER, this, ""); /** * The column <code>mysql.event.interval_field</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, cleandb.mysql.enums.EventIntervalField> INTERVAL_FIELD = createField("interval_field", org.jooq.util.mysql.MySQLDataType.VARCHAR.asEnumDataType(cleandb.mysql.enums.EventIntervalField.class), this, ""); /** * The column <code>mysql.event.created</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.sql.Timestamp> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaulted(true), this, ""); /** * The column <code>mysql.event.modified</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.sql.Timestamp> MODIFIED = createField("modified", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaulted(true), this, ""); /** * The column <code>mysql.event.last_executed</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.sql.Timestamp> LAST_EXECUTED = createField("last_executed", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * The column <code>mysql.event.starts</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.sql.Timestamp> STARTS = createField("starts", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * The column <code>mysql.event.ends</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.sql.Timestamp> ENDS = createField("ends", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); /** * The column <code>mysql.event.status</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, cleandb.mysql.enums.EventStatus> STATUS = createField("status", org.jooq.util.mysql.MySQLDataType.VARCHAR.asEnumDataType(cleandb.mysql.enums.EventStatus.class), this, ""); /** * The column <code>mysql.event.on_completion</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, cleandb.mysql.enums.EventOnCompletion> ON_COMPLETION = createField("on_completion", org.jooq.util.mysql.MySQLDataType.VARCHAR.asEnumDataType(cleandb.mysql.enums.EventOnCompletion.class), this, ""); /** * The column <code>mysql.event.sql_mode</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.lang.String> SQL_MODE = createField("sql_mode", org.jooq.impl.SQLDataType.VARCHAR.length(478).nullable(false).defaulted(true), this, ""); /** * The column <code>mysql.event.comment</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.lang.String> COMMENT = createField("comment", org.jooq.impl.SQLDataType.CHAR.length(64).nullable(false).defaulted(true), this, ""); /** * The column <code>mysql.event.originator</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, org.jooq.types.UInteger> ORIGINATOR = createField("originator", org.jooq.impl.SQLDataType.INTEGERUNSIGNED.nullable(false), this, ""); /** * The column <code>mysql.event.time_zone</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.lang.String> TIME_ZONE = createField("time_zone", org.jooq.impl.SQLDataType.CHAR.length(64).nullable(false).defaulted(true), this, ""); /** * The column <code>mysql.event.character_set_client</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.lang.String> CHARACTER_SET_CLIENT = createField("character_set_client", org.jooq.impl.SQLDataType.CHAR.length(32), this, ""); /** * The column <code>mysql.event.collation_connection</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.lang.String> COLLATION_CONNECTION = createField("collation_connection", org.jooq.impl.SQLDataType.CHAR.length(32), this, ""); /** * The column <code>mysql.event.db_collation</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, java.lang.String> DB_COLLATION = createField("db_collation", org.jooq.impl.SQLDataType.CHAR.length(32), this, ""); /** * The column <code>mysql.event.body_utf8</code>. */ public final org.jooq.TableField<cleandb.mysql.tables.records.EventRecord, byte[]> BODY_UTF8 = createField("body_utf8", org.jooq.impl.SQLDataType.BLOB, this, ""); /** * Create a <code>mysql.event</code> table reference */ public Event() { this("event", null); } /** * Create an aliased <code>mysql.event</code> table reference */ public Event(java.lang.String alias) { this(alias, cleandb.mysql.tables.Event.EVENT); } private Event(java.lang.String alias, org.jooq.Table<cleandb.mysql.tables.records.EventRecord> aliased) { this(alias, aliased, null); } private Event(java.lang.String alias, org.jooq.Table<cleandb.mysql.tables.records.EventRecord> aliased, org.jooq.Field<?>[] parameters) { super(alias, cleandb.mysql.Mysql.MYSQL, aliased, parameters, "Events"); } /** * {@inheritDoc} */ @Override public org.jooq.UniqueKey<cleandb.mysql.tables.records.EventRecord> getPrimaryKey() { return cleandb.mysql.Keys.KEY_EVENT_PRIMARY; } /** * {@inheritDoc} */ @Override public java.util.List<org.jooq.UniqueKey<cleandb.mysql.tables.records.EventRecord>> getKeys() { return java.util.Arrays.<org.jooq.UniqueKey<cleandb.mysql.tables.records.EventRecord>>asList(cleandb.mysql.Keys.KEY_EVENT_PRIMARY); } /** * {@inheritDoc} */ @Override public cleandb.mysql.tables.Event as(java.lang.String alias) { return new cleandb.mysql.tables.Event(alias, this); } /** * Rename this table */ public cleandb.mysql.tables.Event rename(java.lang.String name) { return new cleandb.mysql.tables.Event(name, null); } }
gpl-2.0
dpisarenko/pcc-logic
src/main/java/co/altruix/pcc/api/incomingqueuechannel/IncomingQueueChannel.java
513
/** * This file is part of Project Control Center (PCC). * * PCC (Project Control Center) project is intellectual property of * Dmitri Anatol'evich Pisarenko. * * Copyright 2010, 2011 Dmitri Anatol'evich Pisarenko * All rights reserved * **/ package co.altruix.pcc.api.incomingqueuechannel; import co.altruix.pcc.api.channels.IncomingWorkerChannel; /** * @author DP118M * */ public interface IncomingQueueChannel extends IncomingWorkerChannel { void setQueueName(final String aQueueName); }
gpl-2.0
mulesoft/mule-tooling-incubator
org.mule.tooling.incubator.gradle/src/org/mule/tooling/incubator/gradle/jobs/AbstractDependencyJob.java
1839
package org.mule.tooling.incubator.gradle.jobs; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.mule.tooling.core.model.IMuleProject; import org.mule.tooling.core.module.ExternalContributionMuleModule; import org.mule.tooling.incubator.gradle.Activator; import org.mule.tooling.incubator.gradle.GradlePluginConstants; public abstract class AbstractDependencyJob extends WorkspaceJob { protected final ExternalContributionMuleModule module; protected final IMuleProject project; public AbstractDependencyJob(String jobName, ExternalContributionMuleModule module, IMuleProject project) { super(jobName); this.module = module; this.project = project; } @Override public final IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { try { IFile f = project.getFile(GradlePluginConstants.MAIN_BUILD_FILE); if (!f.exists()) { return Status.OK_STATUS; } return runTask(monitor, f); } catch (Exception ex) { Activator.logError("Error while updating dependencies on the build script...", ex); return Status.CANCEL_STATUS; } } public void configureAndSchedule() { super.setUser(false); super.setPriority(Job.DECORATE); super.setRule(project.getJavaProject().getProject()); super.schedule(); } protected abstract IStatus runTask(IProgressMonitor monitor, IFile buildScript) throws Exception; }
gpl-2.0
ezScrum/ezScrum_1.7.2_export
java/ntut/csie/ezScrum/web/action/backlog/AjaxGetSprintIndexInfoAction.java
4637
package ntut.csie.ezScrum.web.action.backlog; import java.io.IOException; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ntut.csie.ezScrum.iteration.core.ScrumEnum; import ntut.csie.ezScrum.pic.core.IUserSession; import ntut.csie.ezScrum.web.control.TaskBoard; import ntut.csie.ezScrum.web.helper.ReleasePlanHelper; import ntut.csie.ezScrum.web.logic.SprintBacklogLogic; import ntut.csie.ezScrum.web.mapper.SprintBacklogMapper; import ntut.csie.ezScrum.web.support.SessionManager; import ntut.csie.ezScrum.web.support.Translation; import ntut.csie.jcis.resource.core.IProject; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class AjaxGetSprintIndexInfoAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { IProject project = (IProject) SessionManager.getProject(request); IUserSession session = (IUserSession) request.getSession().getAttribute("UserSession"); String sprintID = request.getParameter("sprintID"); // ITSPrefsStorage prefs = new ITSPrefsStorage(project, session); // String mantisUrl = prefs.getServerUrl(); String result = ""; // SprintBacklogMapper backlog = null; // TaskBoard board = null; SprintBacklogLogic sprintBacklogLogic = new SprintBacklogLogic(project, session, sprintID); SprintBacklogMapper sprintBacklogMapper = sprintBacklogLogic.getSprintBacklogMapper(); TaskBoard board = new TaskBoard(sprintBacklogLogic, sprintBacklogMapper); // try { // // sprint 不存在,回傳最近的一個 sprint 或 空的 sprint // if (sprintID == null || sprintID.equals("")) { // backlog = new SprintBacklogMapper(project, session); // board = new TaskBoard(backlog); // } else { // backlog = new SprintBacklogMapper(project, session, Integer.parseInt(sprintID)); // board = new TaskBoard(new SprintBacklogMapper(project, session, Integer.parseInt(sprintID))); // } // } catch (Exception e) { // backlog = null; // // 已經處理過不必輸出 Exception // // System.out.println("class: ShowSprintBacklogAction, method: execute, exception: " + e.toString()); // } // 建立 thisSprintStore 的資料 int currentSprintID = 0; int releaseID = 0; double initialPoint = 0.0d; double currentPoint = 0.0d; double initialHours = 0.0d; double currentHours = 0.0d; String SprintGoal = ""; String StoryChartUrl = ""; String TaskChartUrl = ""; boolean isCurrentSprint=false; //如果Sprint存在的話,那麼就取出此Sprint的資料以回傳 if ( (sprintBacklogMapper != null) && (sprintBacklogMapper.getSprintPlanId() > 0) ) { currentSprintID = sprintBacklogMapper.getSprintPlanId(); initialPoint = sprintBacklogLogic.getCurrentPoint(ScrumEnum.STORY_ISSUE_TYPE); currentPoint = sprintBacklogLogic.getCurrentUnclosePoint(ScrumEnum.STORY_ISSUE_TYPE); initialHours = sprintBacklogLogic.getCurrentPoint(ScrumEnum.TASK_ISSUE_TYPE); currentHours = sprintBacklogLogic.getCurrentUnclosePoint(ScrumEnum.TASK_ISSUE_TYPE); // initialPoint = backlog.getCurrentPoint(ScrumEnum.STORY_ISSUE_TYPE); // currentPoint = backlog.getCurrentUnclosePoint(ScrumEnum.STORY_ISSUE_TYPE); // initialHours = backlog.getCurrentPoint(ScrumEnum.TASK_ISSUE_TYPE); // currentHours = backlog.getCurrentUnclosePoint(ScrumEnum.TASK_ISSUE_TYPE); ReleasePlanHelper rpHelper = new ReleasePlanHelper(project); releaseID = Integer.parseInt(rpHelper.getReleaseID(Integer.toString(currentSprintID))); SprintGoal = sprintBacklogMapper.getSprintGoal(); StoryChartUrl = board.getStoryChartLink(); TaskChartUrl = board.getTaskChartLink(); if(sprintBacklogMapper.getSprintEndDate().getTime() > (new Date()).getTime()) isCurrentSprint = true; } // result = new Translation(mantisUrl).translateSprintInfoToJson( // currentSprintID, initialPoint, currentPoint, initialHours, currentHours, releaseID, SprintGoal, // StoryChartUrl, TaskChartUrl,isCurrentSprint); result = new Translation().translateSprintInfoToJson( currentSprintID, initialPoint, currentPoint, initialHours, currentHours, releaseID, SprintGoal, StoryChartUrl, TaskChartUrl,isCurrentSprint); try { response.setContentType("text/html; charset=utf-8"); response.getWriter().write(result); response.getWriter().close(); } catch (IOException e) { e.printStackTrace(); } return null; } }
gpl-2.0
ClubEngine/casemate-game-jam-lumiere
src/components/TextureComponent.java
358
package components; import org.jsfml.graphics.ConstTexture; /** * */ public class TextureComponent extends AbstractTextureComponent { private final ConstTexture texture; public TextureComponent(ConstTexture texture) { this.texture = texture; } @Override public ConstTexture getTexture() { return texture; } }
gpl-2.0
jpcaruana/jsynthlib
src/main/java/org/jsynthlib/drivers/yamaha/ub99/YamahaUB99BankDriver.java
5485
/* * Copyright 2005 Ton Holsink * * This file is part of JSynthLib. * * JSynthLib 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. * * JSynthLib 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 JSynthLib; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package org.jsynthlib.drivers.yamaha.ub99; import java.io.UnsupportedEncodingException; import org.jsynthlib.core.BankDriver; import org.jsynthlib.core.DriverUtil; import org.jsynthlib.core.Patch; import org.jsynthlib.core.SysexHandler; public class YamahaUB99BankDriver extends BankDriver { private static final SysexHandler BANKDUMP_REQ = new SysexHandler("F0 43 7D 50 55 42 30 01 ** F7"); private final YamahaUB99Driver singleDriver; public YamahaUB99BankDriver(YamahaUB99Driver singleDriver) { super("Bank", "Ton Holsink <a.j.m.holsink@chello.nl>", YamahaUB99Const.NUM_PATCH, YamahaUB99Const.NUM_COLUMNS); this.singleDriver = singleDriver; patchNameSize = YamahaUB99Const.NAME_SIZE; bankNumbers = new String[] {"User"}; patchNumbers = new String[YamahaUB99Const.NUM_PATCH]; System.arraycopy(DriverUtil.generateNumbers(1, YamahaUB99Const.NUM_PATCH, "##"), 0, patchNumbers, 0, YamahaUB99Const.NUM_PATCH); patchSize = YamahaUB99Const.BANK_SIZE; sysexID = "F04239392056312E3030"; singleSysexID = null; singleSize = YamahaUB99Const.SINGLE_SIZE; } public String getPatchName(Patch p, int patchNum) { int nameOfst = YamahaUB99Const.NAME_SIZE * patchNum + YamahaUB99Const.BANK_NAME_OFFSET; try { return new String(((Patch)p).sysex, nameOfst, patchNameSize, "US-ASCII"); } catch (UnsupportedEncodingException e) { return "---"; } } public void setPatchName(Patch p, int patchNum, String name) { int banknameOfst = YamahaUB99Const.NAME_SIZE * patchNum + YamahaUB99Const.BANK_NAME_OFFSET; int nameOfst = YamahaUB99Const.BANK_PATCH_OFFSET + singleSize * patchNum + YamahaUB99Const.NAME_OFFSET; while (name.length() < patchNameSize) name = name + " "; byte[] namebytes = name.getBytes(); for (int i = 0; i < patchNameSize; i++) { p.sysex[banknameOfst + i] = namebytes[i]; p.sysex[nameOfst + i] = namebytes[i]; } } public void calculateChecksum (Patch p) { } protected boolean canHoldPatch(Patch p) { if ((singleSize != p.sysex.length) && (singleSize != 0)) return false; return true; } public void putPatch(Patch bank, Patch p, int patchNum) { System.arraycopy(((Patch)p).sysex, 0, ((Patch)bank).sysex, YamahaUB99Const.BANK_PATCH_OFFSET + singleSize * patchNum, singleSize); } public Patch getPatch(Patch bank, int patchNum) { byte[] sysex = new byte[singleSize]; System.arraycopy(((Patch)bank).sysex, YamahaUB99Const.BANK_PATCH_OFFSET + singleSize * patchNum, sysex, 0, singleSize); return new Patch(sysex, singleDriver); } public Patch createNewPatch() { byte[] header = {85, 66, 57, 57, 32, 86, 49, 46, 48, 48}; byte[] sysex = new byte[YamahaUB99Const.BANK_SIZE]; System.arraycopy(header, 0, sysex, 0, header.length); System.arraycopy(header, 0, sysex, 64, header.length); byte[] b = singleDriver.createNewPatchArray(); for (int i = 0; i < YamahaUB99Const.NUM_PATCH; i++) { System.arraycopy(YamahaUB99Const.NEW_PATCH_NAME, 0, sysex, YamahaUB99Const.BANK_NAME_OFFSET + i*YamahaUB99Const.NAME_SIZE, YamahaUB99Const.NAME_SIZE); System.arraycopy(b, 0, sysex, YamahaUB99Const.BANK_PATCH_OFFSET + i*YamahaUB99Const.SINGLE_SIZE, YamahaUB99Const.SINGLE_SIZE); } Patch bank = new Patch(sysex, this); return bank; } public void requestPatchDump(int bankNum, int patchNum) { for (int i = 0; i < YamahaUB99Const.NUM_PATCH; i++) { send(BANKDUMP_REQ.toSysexMessage( -1, i)); try {Thread.sleep(100); } catch (Exception e){} } } public void storePatch (Patch p, int bankNum, int patchNum) { Patch single; byte[] buf = new byte[] {(byte)0xF0,(byte)0x43,(byte)(0x7D),(byte)0x30,(byte)0x55,(byte)0x42,(byte)0x39,(byte)0x39,(byte)0x00,(byte)0x00,(byte)0x30,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0xF7}; DriverUtil.calculateChecksum(buf, YamahaUB99Const.CHECKSUMSTART, buf.length-3, buf.length-2); send(buf); try {Thread.sleep(100); } catch (Exception e){} for (int i = 0; i < YamahaUB99Const.NUM_PATCH; i++) { single = getPatch(p, i); singleDriver.sendThisPatch(single, i, 0x01); } try {Thread.sleep(100); } catch (Exception e){} buf[11] = 0x10; DriverUtil.calculateChecksum(buf, YamahaUB99Const.CHECKSUMSTART, buf.length-3, buf.length-2); send(buf); } }
gpl-2.0
selcukcihan/raytracer.v2
src/com/selcukcihan/raytracer/vision/sampling/Sample.java
309
/** * @date : 28.Mar.2009 * @author : selcuk * @project : RayTracer * @package : com.selcukcihan.raytracer.vision.sampling */ package com.selcukcihan.raytracer.vision.sampling; /** * @author selcuk * */ public class Sample { public int imgX; public int imgY; public float x; public float y; }
gpl-2.0
TheMartinLab/GlobalPackages
Fitting/fitting/NonLinearFitting_1.java
6872
/** * @author Eric D. Dill eddill@ncsu.edu * @author James D. Martin jdmartin@ncsu.edu * Copyright © 2010-2013 North Carolina State University. All rights reserved */ package fitting; import java.util.Arrays; import java.util.Vector; import jama.Matrix; import equations_1d.Avrami; import equations_1d.Equation1; public class NonLinearFitting_1 implements Runnable { private double[] data; private double[] time; private Equation1 e; private Constraint[] c; private boolean[] isFittable; private int numFittable = 0; private double delta = 1e-6; private double minTime, maxTime; private double[] param_stdDev; private Matrix corr, covar; public NonLinearFitting_1(double[] data, double[] time, Equation1 e, Constraint[] c, boolean[] isFittable) { this.data = data; this.time = time; this.e = e; this.c = c; this.isFittable = isFittable; } public NonLinearFitting_1(double[][] dataAndTime, Equation1 e, Constraint[] c, boolean[] isFittable) { data = new double[dataAndTime.length]; time = new double[dataAndTime.length]; for(int i = 0; i < dataAndTime.length; i++) { data[i] = dataAndTime[i][1]; time[i] = dataAndTime[i][0]; } this.e = e; this.c = c; this.isFittable = isFittable; minTime = e.getParam(1); maxTime = find50Percent(); } public void run() { double[] newParams; Vector<double[]> paramsList = new Vector<double[]>(); paramsList.add(e.getParams()); System.out.println("Initial params: " + Arrays.toString(e.getParams())); double oldSumSq, newSumSq; newSumSq = sumOfSquares(); int idx = 0; do { idx++; oldSumSq = newSumSq; newParams = step(); paramsList.add(newParams); e.setParams(newParams); newSumSq = sumOfSquares(); System.out.println("Params at step " + idx + ": " + Arrays.toString(newParams)); } while(!isConverged(oldSumSq, newSumSq)); determineError(); paramsList.add(newParams); System.out.println(paramsList.toString()); } private void determineError() { double var_est = 1/((double) getDegreesOfFreedom()) * sumOfSquares(); Matrix J = calcJ(); Matrix JT = J.transpose(); Matrix err = (JT.times(J)).inverse(); covar = err.times(var_est); param_stdDev = new double[numFittable]; double[][] matrixVals = new double[numFittable][numFittable]; for(int i = 0; i < numFittable; i++) { param_stdDev[i] = Math.sqrt(covar.get(i, i)); matrixVals[i][i] = param_stdDev[i]; } for(int i = 0; i < numFittable; i++) { for(int j = i; j < numFittable; j++) { matrixVals[i][j] = covar.get(i, j) / (matrixVals[i][i] * matrixVals[j][j]); } } corr = new Matrix(matrixVals); } private int getDegreesOfFreedom() { int numData = 0; for(int i = 0; i < data.length; i++) { if(!(time[i] <= minTime || time[i] >= maxTime)) { numData++; } } return numData-numFittable; } private double find50Percent() { double half = .5; boolean found = false; int idx = 0; while(!found) { if(data[idx] > half) { return time[idx]; } idx++; } return 0; } private Matrix calcJ() { int numFittable = 0; for(int i = 0; i < isFittable.length; i++) { if(isFittable[i]) { numFittable++; } } this.numFittable=numFittable; double[][] matrixVals = new double[data.length][numFittable]; double[] originalFit = getFit(); // fill out the matrix for(int j = 0; j < matrixVals[0].length && isFittable[j]; j++) { e.incrementParam(delta, j); double[] fit = getFit(); for(int i = 0; i < matrixVals.length; i++) { matrixVals[i][j] = (fit[i] - originalFit[i])/delta; } e.decrementParam(delta, j); } return new Matrix(matrixVals); } private double[] getResiduals() { double[] originalFit = getFit(); double[] resid = new double[data.length]; for(int i = 0; i < resid.length; i++) { resid[i] = data[i]-originalFit[i]; } return resid; } private double[] step() { double[] initialParams = e.getParams(); Matrix J = calcJ(); Matrix JT = J.transpose(); Matrix inv = (JT.times(J)).inverse(); Matrix JDagger = inv.times(JT); Matrix isOne = JDagger.times(J); Matrix newParams = JDagger.times(toMatrix(getResiduals())); int idx = Math.min(newParams.getRowDimension(), newParams.getColumnDimension()); double[] betterParams = new double[initialParams.length]; double[][] mat = newParams.getArray(); idx = 0; for(int i = 0; i < initialParams.length; i++, idx++) { if(isFittable[i]) { betterParams[i] = mat[idx][0]+initialParams[i]; } else { betterParams[i] = initialParams[i]; } System.out.print("param " + i + ": " + betterParams[i]); } double initSumSq = sumOfSquares(); e.setParams(betterParams); double finalSumSq = sumOfSquares(); System.out.println("init: " + initSumSq + " final: " + finalSumSq + " difference: " + (initSumSq-finalSumSq)); return betterParams; } public Matrix toMatrix(double[] d) { double[][] mat = new double[d.length][1]; for(int i = 0; i < mat.length; i++) { mat[i][0] = d[i]; } return new Matrix(mat); } private boolean isConverged(double oldSumSq, double newSumSq) { if(Math.abs(oldSumSq - newSumSq) < delta/2) { return true; } return false; } private double sumOfSquares() { double[] fit = getFit(); double sumSquares = 0; for(int i = 0; i < fit.length; i++) { if(!(time[i] < minTime || time[i] > maxTime)) { sumSquares += Math.pow(fit[i]-data[i], 2); } } return sumSquares; } public double[][] getTimeDataFit() { double[][] timeDataFit = new double[time.length][3]; double[] fit = getFit(); for(int i = 0; i < timeDataFit.length; i++) { timeDataFit[i][0] = time[i]; timeDataFit[i][0] = data[i]; timeDataFit[i][0] = fit[i]; } return timeDataFit; } public double[] getFit() { double[] fit = new double[time.length]; for(int i = 0; i < fit.length; i++) { fit[i] = e.evaluate(time[i]); } return fit; } /* * Setters */ public void setDelta(double delta) { this.delta = delta; } public void setIsFittable(boolean[] isFittable) { this.isFittable = isFittable; } public void setIsFittable(boolean b, int idx) { isFittable[idx] = b; } public void setData(double[] data) { this.data = data; } public void setConstraint(Constraint[] c) { this.c = c; } public void setConstraint(Constraint c, int idx) { this.c[idx] = c; } public void setTime(double[] t) { time = t; } /* * Getters */ public double[] getData() { return data; } public double getDelta() { return delta; } public Equation1 getEquation() { return e; } public Constraint[] getConstraints() { return c; } public boolean[] getIsFittable() { return isFittable; } public double[] getTime() { return time; } public Matrix getCovar() { return covar; } public Matrix getCorr() { return corr; } public double[] getStdDev() { return param_stdDev; } public double[] getParams() { return e.getParams(); } }
gpl-2.0
scoophealth/oscar
src/main/java/org/oscarehr/ws/rest/to/model/PrintPointTo1.java
1573
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.ws.rest.to.model; public class PrintPointTo1 { private Integer fontSize; private Integer x; private Integer y; private String text; public int getFontSize() { return fontSize; } public void setFontSize(int fontSize) { this.fontSize = fontSize; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
gpl-2.0
santanche/java2learn
src/java/src/pt/c03java/s01pacote/s02lista/bibliotecaLista/Lista.java
528
package pt.c03java.s01pacote.s02lista.bibliotecaLista; public class Lista { protected int vlista[]; protected int ultimo = -1; public Lista(int tamanho) { vlista = new int[tamanho]; } public void adicionar(int item) { if (ultimo+1 < vlista.length) { ultimo++; vlista[ultimo] = item; } } public String toString() { String str = ""; for (int l = 0; l <= ultimo; l++) str += vlista[l] + ((l < ultimo) ? ", " : ""); return str; } }
gpl-2.0
mviitanen/marsmod
mcp/src/minecraft/net/minecraft/client/renderer/entity/RenderXPOrb.java
4737
package net.minecraft.client.renderer.entity; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; public class RenderXPOrb extends Render { private static final ResourceLocation experienceOrbTextures = new ResourceLocation("textures/entity/experience_orb.png"); private static final String __OBFID = "CL_00000993"; public RenderXPOrb() { this.shadowSize = 0.15F; this.shadowOpaque = 0.75F; } /** * Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then * handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic * (Render<T extends Entity) and this method has signature public void doRender(T entity, double d, double d1, * double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that. */ public void doRender(EntityXPOrb p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_) { GL11.glPushMatrix(); GL11.glTranslatef((float)p_76986_2_, (float)p_76986_4_, (float)p_76986_6_); this.bindEntityTexture(p_76986_1_); int var10 = p_76986_1_.getTextureByXP(); float var11 = (float)(var10 % 4 * 16 + 0) / 64.0F; float var12 = (float)(var10 % 4 * 16 + 16) / 64.0F; float var13 = (float)(var10 / 4 * 16 + 0) / 64.0F; float var14 = (float)(var10 / 4 * 16 + 16) / 64.0F; float var15 = 1.0F; float var16 = 0.5F; float var17 = 0.25F; int var18 = p_76986_1_.getBrightnessForRender(p_76986_9_); int var19 = var18 % 65536; int var20 = var18 / 65536; OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float)var19 / 1.0F, (float)var20 / 1.0F); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); float var26 = 255.0F; float var27 = ((float)p_76986_1_.xpColor + p_76986_9_) / 2.0F; var20 = (int)((MathHelper.sin(var27 + 0.0F) + 1.0F) * 0.5F * var26); int var21 = (int)var26; int var22 = (int)((MathHelper.sin(var27 + 4.1887903F) + 1.0F) * 0.1F * var26); int var23 = var20 << 16 | var21 << 8 | var22; GL11.glRotatef(180.0F - this.renderManager.playerViewY, 0.0F, 1.0F, 0.0F); GL11.glRotatef(-this.renderManager.playerViewX, 1.0F, 0.0F, 0.0F); float var24 = 0.3F; GL11.glScalef(var24, var24, var24); Tessellator var25 = Tessellator.instance; var25.startDrawingQuads(); var25.setColorRGBA_I(var23, 128); var25.setNormal(0.0F, 1.0F, 0.0F); var25.addVertexWithUV((double)(0.0F - var16), (double)(0.0F - var17), 0.0D, (double)var11, (double)var14); var25.addVertexWithUV((double)(var15 - var16), (double)(0.0F - var17), 0.0D, (double)var12, (double)var14); var25.addVertexWithUV((double)(var15 - var16), (double)(1.0F - var17), 0.0D, (double)var12, (double)var13); var25.addVertexWithUV((double)(0.0F - var16), (double)(1.0F - var17), 0.0D, (double)var11, (double)var13); var25.draw(); GL11.glDisable(GL11.GL_BLEND); GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); } /** * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityXPOrb p_110775_1_) { return experienceOrbTextures; } /** * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(Entity p_110775_1_) { return this.getEntityTexture((EntityXPOrb)p_110775_1_); } /** * Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then * handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic * (Render<T extends Entity) and this method has signature public void doRender(T entity, double d, double d1, * double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that. */ public void doRender(Entity p_76986_1_, double p_76986_2_, double p_76986_4_, double p_76986_6_, float p_76986_8_, float p_76986_9_) { this.doRender((EntityXPOrb)p_76986_1_, p_76986_2_, p_76986_4_, p_76986_6_, p_76986_8_, p_76986_9_); } }
gpl-2.0
mattlisiv/CompLing-Data-Gathering-Software
Annotation Reader/src/reader/SymbolTagger.java
5915
package reader; import java.util.ArrayList; import java.util.Scanner; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.IOException; import java.io.FileNotFoundException; import java.net.URISyntaxException; import java.net.URL; /** * @author Nicholas Moss <nbmoss@uga.edu> * For the CompLing @ UGA research group. * Annotator program, matches words in a document to words on a list, and marks them if it finds a match * Outputs a new annotated file with < > following each word marked * To invoke the program: java Annotator document wordlist1 wordlist2 ... * All files should be in the same directory as the program, and all ouput files are placed in this directory as well * TODO Want to change this to have a lists directory, documents directory, and output directory to allow for mass use * TODO write a shell script that allows entire directories to be fed in or enable the program to do this via a command line flag. */ public class SymbolTagger { //the wordlist read from standard in private ArrayList<String> wordList; private PrintWriter outputStream; public SymbolTagger(){ wordList = new ArrayList<String>(); } /** * readList - reads a list of words and stores them in the program * @param name String, name of the file to open may also need to include path * @return void * @throws URISyntaxException */ public void readList(String name) throws IOException, URISyntaxException{ Scanner reader; InputStream in = getClass().getResourceAsStream(name); reader = new Scanner(new BufferedReader(new InputStreamReader(in))); while(reader.hasNext()){ String next = reader.next(); wordList.add(next); } reader.close(); } /** * findMatch - checks a string to see if it appears on the word list * @param word String checks this word to see if it appears on the word list * @return boolean */ public boolean findMatch(String word){ for(int i=0; i<wordList.size(); i++){ if(word.equalsIgnoreCase(wordList.get(i))){ return true; } } return false; } /** * annotate - reads the document, checks each token to see if it appears on a word list and marks it with < >. * Should maintain overall structure of the input document such as spacing and formatting. * Outputs a new annotated file, some of the whitespace is more condensed. * @param name String name of the document * @return */ public File annotate(String name)throws IOException{ int i = name.indexOf("."); String outName = name.substring(0, i) + "_ant.txt"; File file = new File(outName); try { if(file.exists()){ file.delete(); } file.createNewFile(); } catch(IOException e){ System.out.println("Error creating file..."); } try{ outputStream = new PrintWriter(new FileOutputStream(outName, true)); }catch(FileNotFoundException e){} Scanner reader; try{ reader = new Scanner(new BufferedReader(new FileReader(name))); while(reader.hasNextLine()){ String line = reader.nextLine(); String m =""; while(!line.isEmpty()){ if(line.indexOf(" ") == -1){ m = line.substring(0); line = ""; } else{ m = line.substring(0, line.indexOf(" ")); line = line.substring(m.length()); } line = line.trim(); String o = ""; if(m.contains(".") || m.contains("!") || m.contains("?") || m.contains(";") || m.contains(",")){ if(m.contains(".") && (m.indexOf(".") == m.length()-1)){ o = "."; } if(m.contains("!")){ o= "!"; } if(m.contains("?")){ o="?"; } if(m.contains(",")){ o=","; } if(m.contains(";")){ o=";"; } m = m.substring(0, m.length()-1); } if(findMatch(m)){ String w = m + "< >"; outputStream.print(w + o + " " ); } else { outputStream.print(m + o + " "); } } outputStream.println(); } outputStream.close(); reader.close(); return file; }catch(IOException e){ System.out.println("Problem with document."); System.exit(0); } return null; } public static File tagHTML(String[] args)throws IOException, URISyntaxException{ SymbolTagger a = new SymbolTagger(); File taggedHTML = null; if(args == null){ System.out.println("Need the arguments: document list1 list2 ..."); } for(int i=1; i<args.length; i++){ a.readList(args[i]); } if(args != null){ System.out.println(args[0]); taggedHTML =a.annotate(args[0]); } return taggedHTML; } }
gpl-2.0
CHmoonKa/json-libraries-jmh
src/main/java/com/iwendy/json/reader/JsonSimpleReader.java
438
package com.iwendy.json.reader; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class JsonSimpleReader { private static JSONParser parser = new JSONParser(); public static JSONObject parse(final String json) { try { Object obj = parser.parse(json); JSONObject jsonObject = (JSONObject) obj; return jsonObject; } catch (Exception e) { e.printStackTrace(); return null; } } }
gpl-2.0
favedit/MoPlatform
mo-3-logic/src/logic-java/org/mo/logic/process/common/XTaskCondition.java
157
package org.mo.logic.process.common; import org.mo.logic.process.base.XBaseTaskCondition; public class XTaskCondition extends XBaseTaskCondition { }
gpl-2.0
saces/fred
src/freenet/clients/http/wizardsteps/BANDWIDTH_MONTHLY.java
4585
package freenet.clients.http.wizardsteps; import freenet.clients.http.FirstTimeWizardToadlet; import freenet.config.Config; import freenet.config.InvalidConfigValueException; import freenet.l10n.NodeL10n; import freenet.node.NodeClientCore; import freenet.support.*; import freenet.support.api.HTTPRequest; /** * Allows the user to set bandwidth limits with an emphasis on capping to a monthly total. */ public class BANDWIDTH_MONTHLY extends BandwidthManipulator implements Step { private long[] caps; private final long GB = 1000000000; public BANDWIDTH_MONTHLY(NodeClientCore core, Config config) { super(core, config); caps = new long[] { 25*GB, 50*GB, 100*GB, 150*GB }; } @Override public void getStep(HTTPRequest request, PageHelper helper) { HTMLNode contentNode = helper.getPageContent(WizardL10n.l10n("bandwidthLimit")); if (request.isParameterSet("parseError")) { parseErrorBox(contentNode, helper, request.getParam("parseTarget")); } //Box for prettiness and explanation of function. HTMLNode infoBox = helper.getInfobox("infobox-normal", WizardL10n.l10n("bandwidthLimitMonthlyTitle"), contentNode, null, false); NodeL10n.getBase().addL10nSubstitution(infoBox, "FirstTimeWizardToadlet.bandwidthLimitMonthly", new String[] { "bold", "coreSettings" }, new HTMLNode[] { HTMLNode.STRONG, new HTMLNode("#", NodeL10n.getBase().getString("ConfigToadlet.node"))}); //TODO: Might want to detect bandwidth limit and hide those too high to reach. //TODO: The user can always set a custom limit. At least one limit should be displayed in order to //TODO: demonstrate how to specify the limit, though. //Table header HTMLNode table = infoBox.addChild("table"); HTMLNode headerRow = table.addChild("tr"); headerRow.addChild("th", WizardL10n.l10n("bandwidthLimitMonthlyTitle")); headerRow.addChild("th", WizardL10n.l10n("bandwidthSelect")); //Row for each cap for (long cap : caps) { HTMLNode row = table.addChild("tr"); //ISPs are likely to list limits in GB instead of GiB, so display GB here. row.addChild("td", String.valueOf(cap/GB)+" GB"); HTMLNode selectForm = helper.addFormChild(row.addChild("td"), ".", "limit"); selectForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "capTo", String.valueOf(cap)}); selectForm.addChild("input", new String[] { "type", "value" }, new String[] { "submit", WizardL10n.l10n("bandwidthSelect")}); } //Row for custom entry HTMLNode customForm = helper.addFormChild(table.addChild("tr"), ".", "custom-form"); customForm.addChild("td").addChild("input", new String[]{"type", "name"}, new String[]{"text", "capTo"}); customForm.addChild("td").addChild("input", new String[]{"type", "value"}, new String[]{"submit", WizardL10n.l10n("bandwidthSelect")}); HTMLNode backForm = helper.addFormChild(infoBox, ".", "backForm"); backForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "back", NodeL10n.getBase().getString("Toadlet.back")}); } @Override public String postStep(HTTPRequest request) { long bytesMonth; String capTo = request.getPartAsStringFailsafe("capTo", 4096); try { bytesMonth = Fields.parseLong(capTo); } catch (NumberFormatException e) { StringBuilder target = new StringBuilder(FirstTimeWizardToadlet.TOADLET_URL); target.append("?step=BANDWIDTH_MONTHLY&parseError=true&parseTarget="); target.append(URLEncoder.encode(capTo, true)); return target.toString(); } //Linear from 0.5 at 25 GB to 0.8 at 100 GB. bytesMonth is divided by the number of bytes in a GiB. double downloadFraction = 0.004*(bytesMonth/GB) + 0.4; if (downloadFraction < 0.4) downloadFraction = 0.4; if (downloadFraction > 0.8) downloadFraction = 0.8; //Seconds in 30 days double bytesSecondTotal = bytesMonth/2592000d; String downloadLimit = String.valueOf(bytesSecondTotal*downloadFraction); String uploadLimit = String.valueOf(bytesSecondTotal*(1-downloadFraction)); try { setBandwidthLimit(downloadLimit, false); } catch (InvalidConfigValueException e) { freenet.support.Logger.error(this, "Failed to set download limit "+downloadLimit+": "+e); } try { setBandwidthLimit(uploadLimit, true); } catch (InvalidConfigValueException e) { freenet.support.Logger.error(this, "Failed to set upload limit "+uploadLimit+": "+e); } setWizardComplete(); return FirstTimeWizardToadlet.WIZARD_STEP.COMPLETE.name(); } }
gpl-2.0
dkarlinsky/azsmrc
remote/src/main/java/lbms/azsmrc/remote/client/plugins/event/PluginClientListener.java
817
package lbms.azsmrc.remote.client.plugins.event; import org.jdom.Element; /** * @author Damokles * */ public interface PluginClientListener { /** * The Listener needs to identify himself. * * Only events that match the id will be routed here. * * @return PluginID */ public String getID(); /** * @param status the response status @see RemoteConstants.IPC_* * @param senderID the ID of the caller * @param pluginID the called pluginID * @param method the method that was called * @param parameter null or a parameter Element */ public void handleIPCResponse (int status, String senderID, String pluginID, String method, Element parameter); /** * This way the remote Client can tell the local one something. * * @param e */ public void handleRemoteEvent (Element e); }
gpl-2.0
Esleelkartea/aonGTA
aongta_v1.0.0_src/Fuentes y JavaDoc/aon-product/src/com/code/aon/product/strategy/PriceStrategyFactory.java
407
package com.code.aon.product.strategy; /** * Factory for the price strategy. * * @author Consulting & Development. * @since 1.0 * */ public class PriceStrategyFactory { /** * Creates a new instance of an object that implements IPriceStrategy * * @return BasicPriceStrategy */ public static IPriceStrategy getPriceStrategy(){ return new BasicPriceStrategy(); } }
gpl-2.0
luciano-sabenca/MC437_Grupo3
src/main/java/mc437/bean/TestCaseExecutingOutputMutantlist.java
1422
package mc437.bean; public class TestCaseExecutingOutputMutantlist { private String mutantKey; private boolean dead; private int deathIndex; private boolean evalFailed; private int idTestCaseResults; private int idTestSetResults; private int idITestResults; private int id_seq; public String getMutantKey() { return mutantKey; } public void setMutantKey(String mutantKey) { this.mutantKey = mutantKey; } public boolean isDead() { return dead; } public void setDead(boolean dead) { this.dead = dead; } public int getDeathIndex() { return deathIndex; } public void setDeathIndex(int deathIndex) { this.deathIndex = deathIndex; } public boolean isEvalFailed() { return evalFailed; } public void setEvalFailed(boolean evalFailed) { this.evalFailed = evalFailed; } public int getIdTestCaseResults() { return idTestCaseResults; } public void setIdTestCaseResults(int idTestCaseResults) { this.idTestCaseResults = idTestCaseResults; } public int getIdTestSetResults() { return idTestSetResults; } public void setIdTestSetResults(int idTestSetResults) { this.idTestSetResults = idTestSetResults; } public int getIdITestResults() { return idITestResults; } public void setIdITestResults(int idITestResults) { this.idITestResults = idITestResults; } public int getId_seq() { return id_seq; } public void setId_seq(int id_seq) { this.id_seq = id_seq; } }
gpl-2.0
XuezheMax/MaxParser
src/maxparser/trainer/MLETrainer.java
10069
package maxparser.trainer; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import maxparser.DependencyInstance; import maxparser.FeatureVector; import maxparser.Pair; import maxparser.exception.TrainingException; import maxparser.io.DependencyReader; import maxparser.io.DependencyWriter; import maxparser.io.ObjectReader; import maxparser.model.ParserModel; import maxparser.parser.decoder.Decoder; import maxparser.parser.manager.Manager; import maxparser.trainer.lbfgs.LBFGS.ExceptionWithIflag; import maxparser.trainer.lbfgs.SimpleLBFGS; public class MLETrainer extends Trainer { @Override public void train(Manager manager, Decoder decoder, ParserModel model, String trainfile, String devfile, String logfile, String modelfile, int numTrainInst, int numDevInst) throws TrainingException, ClassNotFoundException, InstantiationException, IllegalAccessException, IOException { System.out.println("Num Sentences: " + numTrainInst); System.out.println("Num Threads: " + model.threadNum()); System.out.println("Cost: " + model.cost()); final double eta = 1e-6; final int maxIter = model.maxIter(); int threadNum = model.threadNum(); Manager[] managers = createManagers(manager, trainfile, threadNum, numTrainInst, model); double cost = model.cost(); String trainforest = model.trainforest(); int nsize = model.featureSize(); double bestAcc = 0.0; double bestC = 0.0; PrintWriter logWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(logfile))); for (double c = ((devfile != null && cost > 0.005) ? 0.005 : cost); c <= cost; c += 0.005) { double old_obj = 1e+37; int converge = 0; SimpleLBFGS lbfgs = new SimpleLBFGS(nsize); System.out.println(String.format("current cost: %.3f", c)); for (int itr = 0; itr < maxIter; ++itr) { System.out.flush(); long clock = System.currentTimeMillis() / 1000; GradientCollectThread[] threads = new GradientCollectThread[threadNum]; int unit = (numTrainInst % threadNum == 0) ? numTrainInst / threadNum : numTrainInst / threadNum + 1; for (int i = 0; i < threadNum; ++i) { int start = unit * i; int end = start + unit; if (end > numTrainInst) { end = numTrainInst; } String[] tokens = trainforest.split("\\."); String forestfile = tokens[0] + i + "." + tokens[1]; threads[i] = new GradientCollectThread(start, end, managers[i], decoder, forestfile, model); } for (int i = 0; i < threadNum; ++i) { threads[i].start(); } for (int i = 0; i < threadNum; ++i) { try { threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); System.exit(0); } } for (int i = 1; i < threadNum; ++i) { threads[0].obj += threads[i].obj; } for (int i = 1; i < threadNum; ++i) { for (int j = 0; j < nsize; ++j) { threads[0].gradient[j] += threads[i].gradient[j]; } } threads[0].obj *= c; for (int j = 0; j < nsize; ++j) { threads[0].obj += model.paramAt(j) * model.paramAt(j) / 2.0;// (2.0 // * // c); threads[0].gradient[j] *= c; threads[0].gradient[j] += model.paramAt(j);// / c; } double diff = itr == 0 ? 1.0 : Math.abs(old_obj - threads[0].obj) / old_obj; System.out.println("iter=" + itr + " obj=" + String.format("%.8f", threads[0].obj) + " diff=" + String.format("%.8f", diff) + " time=" + (System.currentTimeMillis() / 1000 - clock) + "s."); old_obj = threads[0].obj; if (diff < eta) { converge++; } else { converge = 0; } if (itr > maxIter || converge == 3) { break; } try { if (model.update(lbfgs, threads[0].obj, threads[0].gradient) == 0) { break; } } catch (ExceptionWithIflag e) { e.printStackTrace(); System.exit(0); } } System.out.print("Saving Model..."); long clock = System.currentTimeMillis() / 1000; saveModel(model, modelfile); System.out.println("Done. Took: " + (System.currentTimeMillis() / 1000 - clock) + "s."); if (devfile != null) { // calc current accuracy logWriter.println(String.format("Cost: %.3f", c)); double acc = evalCurrentAcc(manager, decoder, model, devfile, logWriter, numDevInst); logWriter.println("------------------------------------------"); logWriter.flush(); if (bestAcc < acc) { bestAcc = acc; saveModel(model, modelfile); bestC = c; } } } logWriter.close(); System.out.println("Final Dev Accuracy: " + bestAcc + "% (Cost: " + bestC + ")"); } protected double evalCurrentAcc(Manager manager, Decoder decoder, ParserModel tempModel, String devfile, PrintWriter logWriter, int numDevInst) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException { ObjectReader in = new ObjectReader(tempModel.devforest()); String tempfile = "tmp/result.tmp"; DependencyWriter tempWriter = DependencyWriter.createDependencyWriter(tempModel.getWriter()); tempWriter.startWriting(tempfile); for (int j = 0; j < numDevInst; ++j) { DependencyInstance inst = null; inst = manager.readInstance(in, tempModel); Pair<FeatureVector, String>[] d = decoder.decode(manager, inst, 1, tempModel); String[] res = d[0].second.split(" "); int[] heads = new int[inst.length()]; String[] types = new String[inst.length()]; heads[0] = -1; types[0] = "<no-type>"; for (int k = 1; k < inst.length(); k++) { String[] trip = res[k - 1].split("[\\|:]"); heads[k] = Integer.parseInt(trip[0]); types[k] = tempModel.getType(Integer.parseInt(trip[2])); } tempWriter.write(inst, heads, types); } // close in & tempWriter in.close(); tempWriter.close(); // evaluate current acc return maxparser.Evaluator.evaluate(devfile, tempfile, logWriter, tempModel); } private Manager[] createManagers(Manager manager, String trainfile, int threadNum, int numTrainInst, ParserModel model) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException { DependencyReader reader = DependencyReader.createDependencyReader(model.getReader()); reader.startReading(trainfile); int unit = (numTrainInst % threadNum == 0) ? numTrainInst / threadNum : numTrainInst / threadNum + 1; int i = 0; int[] maxLength = new int[threadNum]; int wh = 0; for (int j = 0; j < numTrainInst; ++j) { if (j % unit == 0 && j != 0) { ++i; } DependencyInstance instance = reader.getNext(model); if (instance.length() > maxLength[i]) { maxLength[i] = instance.length(); if (maxLength[i] > maxLength[wh]) { wh = i; } } } reader.close(); Manager[] managers = new Manager[threadNum]; for (int j = 0; j < threadNum; ++j) { managers[j] = j == wh ? manager : manager.clone(maxLength[j], model.typeSize()); } return managers; } class GradientCollectThread extends Thread { private int start; private int end; private Manager manager; private Decoder decoder; private String forestfile; private ParserModel model; public double obj; public double[] gradient = null; public GradientCollectThread(int start, int end, Manager manager, Decoder decoder, String forestfile, ParserModel model) { this.start = start; this.end = end; this.manager = manager; this.decoder = decoder; this.forestfile = forestfile; this.model = model; gradient = new double[model.featureSize()]; } public void run() { try { obj = 0.0; ObjectReader in1 = new ObjectReader(forestfile); ObjectReader in2 = new ObjectReader(forestfile); for (int i = start; i < end; ++i) { obj += decoder.calcLogLinearGradient(gradient, manager, model, in1, in2); } in1.close(); in2.close(); } catch (TrainingException | IOException | ClassNotFoundException e) { e.printStackTrace(); } } } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest13952.java
2851
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark 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, version 2. * * The Benchmark 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 * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest13952") public class BenchmarkTest13952 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheValue("foo"); String bar = new Test().doSomething(param); try { java.util.Random numGen = java.security.SecureRandom.getInstance("SHA1PRNG"); // Get 40 random bytes byte[] randomBytes = new byte[40]; getNextNumber(numGen, randomBytes); response.getWriter().println("Random bytes are: " + new String(randomBytes)); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing SecureRandom.nextBytes() - TestCase"); throw new ServletException(e); } finally { response.getWriter().println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed"); } } void getNextNumber(java.util.Random generator, byte[] barray) { generator.nextBytes(barray); } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { String bar; // Simple if statement that assigns param to bar on true condition int i = 196; if ( (500/42) + i > 200 ) bar = param; else bar = "This should never happen"; return bar; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest10012.java
2353
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark 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, version 2. * * The Benchmark 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 * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest10012") public class BenchmarkTest10012 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getParameter("foo"); String bar = new Test().doSomething(param); int length = 1; if (bar != null) { length = bar.length(); response.getWriter().write(bar, 0, length - 1); } } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { String bar = "safe!"; java.util.HashMap<String,Object> map28195 = new java.util.HashMap<String,Object>(); map28195.put("keyA-28195", "a Value"); // put some stuff in the collection map28195.put("keyB-28195", param.toString()); // put it in a collection map28195.put("keyC", "another Value"); // put some stuff in the collection bar = (String)map28195.get("keyB-28195"); // get it back out return bar; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest15216.java
2267
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark 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, version 2. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest15216") public class BenchmarkTest15216 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getHeader("foo"); String bar = doSomething(param); try { double rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextDouble(); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing SecureRandom.nextDouble() - TestCase"); throw new ServletException(e); } response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed"); } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar; // Simple ? condition that assigns param to bar on false condition int i = 106; bar = (7*42) - i > 200 ? "This should never happen" : param; return bar; } }
gpl-2.0
nnjeremy/m1-miage-2013-abd
Java/Projet/administrateur/GestionPlageAccesBat.java
2497
package administrateur; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Scanner; import database.BdQuery; public class GestionPlageAccesBat extends GestionPlageAcces { public GestionPlageAccesBat(Scanner sc, BdQuery bd, Administrateur admin) { super(sc, bd, admin); } public void afficherMenu() { System.out.println("*** Gestion des Plages pour les bâtiments ***"); System.out.println("1. Ajout d'une plage semaine"); System.out.println("2. Ajout d'une plage horaire"); System.out.println("3. Ajout d'une période d'acces"); System.out.println("4. Ajout d'une autorisation"); System.out.println(""); switch (this.sc.nextInt()) { case 1: this.ajouterPlageSemaine(); break; case 2: this.ajouterPlageHoraire(); break; case 3: this.ajouterPeriodeAcces(); break; case 4: this.ajouterAutorisation(); break; } } private void ajouterAutorisation() { try { System.out.println("*** Affichage des groupes de bâtiment (n¡ ID_GROUPEBAT, n¡ NOMGROUPEBAT) ***"); PreparedStatement psSelectGB = this.connection.prepareStatement("SELECT * FROM GROUPE_BATIMENTS"); this.bd.afficherResultatRequete(psSelectGB.executeQuery()); System.out.println("ID_GROUPEBAT: "); int idgrbat = sc.nextInt(); System.out.println("*** Affichage des periodes d'acces (n¡ LIBELLE_PLAGE_ACCES, n¡ LIBELLE_PLAGE_HORAIRE, n¡ ferie, n¡ ouvre) ***"); PreparedStatement psSelectPA = this.connection.prepareStatement("SELECT * FROM PERIODE_ACCES"); this.bd.afficherResultatRequete(psSelectPA.executeQuery()); System.out.println("libelle periode d'acces: "); String libellePA = sc.next(); int idgpers=0; PreparedStatement psSelectGPERS = connection.prepareStatement("SELECT ID_GROUPEPERS FROM GROUPE G, GROUPE_BATIMENTS GB WHERE GB.ID_GROUPEBAT=? AND G.NOMGROUPEPERS=GB.NOMGROUPEBAT"); psSelectGPERS.setInt(1, idgrbat); ResultSet rs = psSelectGPERS.executeQuery(); if(rs.next()) idgpers = rs.getInt(1); PreparedStatement psInsert = connection.prepareStatement("INSERT INTO AUTORISATION VALUES (?,?,?)"); psInsert.setInt(1, idgrbat); psInsert.setInt(2, idgpers); psInsert.setString(3, libellePA); psInsert.executeUpdate(); this.bd.validerTransaction(); } catch (SQLException e) { //e.printStackTrace(); e.getMessage(); this.bd.annulerTransaction(); } this.afficherMenu(); } }
gpl-2.0
Nerzal/Castle-Invaders
Castle_Invaders/src/com/noobygames/nerzal/castleinvaders/spells/Freeze.java
775
package com.noobygames.nerzal.castleinvaders.spells; import com.noobygames.castleinvaders.GameLiving; /** This Spelleffect should root the target and apply a snare effect afterwards. * * @author Nerzal * */ public class Freeze extends SpellEffect { public Freeze(float x, float y, float width, float height, GameLiving caster, GameLiving target, Spell spell) { super(x, y, width, height, caster, target, spell); this.setEffectDmg((float) (0)); //TODO add StoreObject to add initial damage ! this.setEffectDuration((float)(2.0)); this.setTickDamage((float) (0)); // No tick dmg this.setTickDuration((float) (0)); this.setConditionDuration((float) 2.0); //Guess condition duration is not really needed TODO this.setCondition(Condition.root); } }
gpl-2.0
antivo/Playground
Java/ANFIS3/src/hr/fer/zemris/nenr/anfis3/dataset/Dataset.java
975
package hr.fer.zemris.nenr.anfis3.dataset; public class Dataset { static private final int low = -4; static private final int high = 4; private double[] f; public Dataset() { int size = 81; this.f = new double[size]; int idx = 0; for(int x = low; x <= high; ++x) { for(int y = low; y <= high; ++y) { this.f[idx++] = f(x, y); } } } public double get(int x, int y) throws IndexOutOfBoundsException { if(x >= low && x <= high) { if(y >= low && y <= high) { int idx = (x - low) * 9 + y - low; return f[idx]; } } throw new IndexOutOfBoundsException(); } static public int getSize() { return 81; } static public int getLow() { return low; } static public int getHigh() { return high; } static public double f(int x, int y) { int x_1 = x - 1; x_1 *= x_1; int y_2 = y + 2; y_2 *= y_2; int b1 = x_1 + y_2 - 5 * x * y + 3; double b2 = Math.cos(x/5); b2 *= b2; return b1*b2; } }
gpl-2.0
angelorohit/lwuitstripped
src/com/sun/lwuit/Painter.java
1848
/* * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.lwuit; import com.sun.lwuit.geom.*; /** * Painter can be used to draw on components backgrounds. * The use of such painter allows reuse of a background painters for various * components. * Note in order to view the painter drawing, component need to have some level * of transparency. * * @author Chen Fishbein */ public interface Painter { /** * Draws inside the given rectangle clipping area. * * @param g the {@link Graphics} object * @param rect the given rectangle cliping area */ public void paint(Graphics g, Rectangle rect); }
gpl-2.0
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java/de/metas/adempiere/util/cache/CacheModelIdParamDescriptor.java
2633
package de.metas.adempiere.util.cache; import java.lang.annotation.Annotation; import org.adempiere.model.InterfaceWrapperHelper; import org.slf4j.Logger; import de.metas.adempiere.util.CacheModelId; import de.metas.adempiere.util.CacheTrx; import de.metas.logging.LogManager; /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2016 metas GmbH * %% * 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, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ /** * Handles {@link CacheModelId} annotation. * * @author metas-dev <dev@metas-fresh.com> * */ public class CacheModelIdParamDescriptor implements ICachedMethodPartDescriptor { private static final Logger logger = LogManager.getLogger(CacheModelIdParamDescriptor.class); private final int parameterIndex; public CacheModelIdParamDescriptor(final Class<?> parameterType, final int parameterIndex, final Annotation annotation) { super(); this.parameterIndex = parameterIndex; if (InterfaceWrapperHelper.isModelInterface(parameterType)) { // nothing to do } else { throw new CacheIntrospectionException("Parameter has unsupported type") .setParameter(parameterIndex, parameterType); } } @Override public void extractKeyParts(final CacheKeyBuilder keyBuilder, final Object targetObject, final Object[] params) { final Object modelObj = params[parameterIndex]; int id = -1; Exception errorException = null; if (modelObj != null) { try { id = InterfaceWrapperHelper.getId(modelObj); } catch (final Exception ex) { id = -1; errorException = ex; } } if (id < 0 || errorException != null) { keyBuilder.setSkipCaching(); final CacheGetException ex = new CacheGetException("Invalid parameter type.") .addSuppressIfNotNull(errorException) .setTargetObject(targetObject) .setMethodArguments(params) .setInvalidParameter(parameterIndex, modelObj) .setAnnotation(CacheTrx.class); logger.warn("Invalid parameter. Skip caching", ex); return; } keyBuilder.add(id); } }
gpl-2.0
ron190/jsql-injection
view/src/main/java/com/jsql/view/swing/ui/CheckBoxIcon.java
2785
package com.jsql.view.swing.ui; import java.awt.Component; import java.awt.Graphics; import java.io.Serializable; import javax.swing.ButtonModel; import javax.swing.Icon; import javax.swing.JCheckBoxMenuItem; import javax.swing.plaf.UIResource; import javax.swing.plaf.metal.MetalLookAndFeel; @SuppressWarnings("serial") public class CheckBoxIcon implements Icon, UIResource, Serializable { private static final int CONTROL_SIZE = 12; private void paintOceanIcon(Component c, Graphics g, int x, int y) { ButtonModel model = ((JCheckBoxMenuItem) c).getModel(); g.translate(x, y); int w = this.getIconWidth(); int h = this.getIconHeight(); if (model.isEnabled()) { if (model.isPressed() && model.isArmed()) { g.setColor(MetalLookAndFeel.getControlShadow()); g.fillRect(0, 0, w, h); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.fillRect(0, 0, w, 2); g.fillRect(0, 2, 2, h - 2); g.fillRect(w - 1, 1, 1, h - 1); g.fillRect(1, h - 1, w - 2, 1); } else if (model.isRollover()) { g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 1, h - 1); g.setColor(MetalLookAndFeel.getPrimaryControl()); g.drawRect(1, 1, w - 3, h - 3); g.drawRect(2, 2, w - 5, h - 5); } else { g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 1, h - 1); } g.setColor( MetalLookAndFeel.getControlInfo() ); } else { g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 1, h - 1); } g.translate(-x, -y); if (model.isSelected()) { this.drawCheck(g, x, y); } } protected void drawCheck(Graphics g, int x, int y) { g.fillRect(x + 3, y + 5, 2, CheckBoxIcon.CONTROL_SIZE - 8); g.drawLine(x + CheckBoxIcon.CONTROL_SIZE - 4, y + 3, x + 5, y + CheckBoxIcon.CONTROL_SIZE - 6); g.drawLine(x + CheckBoxIcon.CONTROL_SIZE - 4, y + 4, x + 5, y + CheckBoxIcon.CONTROL_SIZE - 5); } @Override public void paintIcon(Component c, Graphics g, int x, int y) { this.paintOceanIcon(c, g, x, y); } @Override public int getIconWidth() { return CheckBoxIcon.CONTROL_SIZE; } @Override public int getIconHeight() { return CheckBoxIcon.CONTROL_SIZE; } }
gpl-2.0
ITman1/ScriptBox
src/main/java/org/fit/cssbox/scriptbox/resource/content/ErrorHandler.java
1597
/** * ErrorHandler.java * (c) Radim Loskot and Radek Burget, 2013-2014 * * ScriptBox 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. * * ScriptBox 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 ScriptBox. If not, see <http://www.gnu.org/licenses/>. * */ package org.fit.cssbox.scriptbox.resource.content; import java.net.URL; import org.fit.cssbox.scriptbox.navigation.NavigationAttempt; /** * Abstract class for all error handlers that reports error for a given navigation attempt. * * @author Radim Loskot * @version 0.9 * @since 0.9 - 21.4.2014 */ public class ErrorHandler { protected NavigationAttempt navigationAttempt; /** * Constructs error handler for a given navigation attempt. * * @param navigationAttempt Navigation attempt which invoked this content handler. */ public ErrorHandler(NavigationAttempt navigationAttempt) { this.navigationAttempt = navigationAttempt; } /** * Handles an error. * * @param url Location of the resource which was unable to fetch. */ public void handle(URL url) { } }
gpl-2.0
piaolinzhi/fight
dubbo/pay/pay-service-remit/src/main/java/wusc/edu/pay/core/remit/biz/RemitBiz.java
7190
package wusc.edu.pay.core.remit.biz; import java.util.Date; import java.util.List; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import wusc.edu.pay.common.enums.PublicStatusEnum; import wusc.edu.pay.core.remit.biz.sub.AccountBiz; import wusc.edu.pay.core.remit.dao.RemitBatchDao; import wusc.edu.pay.core.remit.dao.RemitProcessDao; import wusc.edu.pay.core.remit.dao.RemitRequestDao; import wusc.edu.pay.facade.notify.util.NotifyUtil; import wusc.edu.pay.facade.remit.entity.RemitBatch; import wusc.edu.pay.facade.remit.entity.RemitProcess; import wusc.edu.pay.facade.remit.entity.RemitRequest; import wusc.edu.pay.facade.remit.enums.RemitBatchStatusEnum; import wusc.edu.pay.facade.remit.enums.RemitProcessStatusEnum; import wusc.edu.pay.facade.remit.enums.RemitRequestStatusEnum; import wusc.edu.pay.facade.remit.enums.TradeSourcesEnum; import wusc.edu.pay.facade.remit.exceptions.RemitBizException; /** * 打款业务处理核心类 * * @author Administrator * */ @Component("remitBiz") public class RemitBiz { @Autowired private RemitProcessDao remitProcessDao; @Autowired private RemitRequestDao remitRequestDao; @Autowired private RemitBatchDao remitBatchDao; @Autowired private AccountBiz accountBiz; @Autowired private JmsTemplate notifyJmsTemplate; private static final Log log = LogFactory.getLog(RemitBiz.class); /** * 打款成功 * * @param batchNo * @param loginName */ public void remitSuccess(String batchNo, String loginName) { log.info("==>remitSuccess"); // 1. 批次是否存在 RemitBatch remitBatch = remitBatchDao.getByBatchNo(batchNo); if (remitBatch == null) { throw RemitBizException.REMIT_BATCH_RECORD_NOT_EXIST.print(); } // 处理中,或处理完成 if (remitBatch.getStatus() == RemitBatchStatusEnum.SOLVED.getValue()) { throw RemitBizException.REMIT_BATCH_IS_COMPLETED.print(); } // 2. 打款请求是否存在 List<RemitRequest> listRemitRequest = remitRequestDao.listByBatchNo(batchNo); if (listRemitRequest == null) { throw RemitBizException.REMIT_REQUEST_RECORD_NOT_EXIST.print(); } // 3. 打款处理记录是否存在 List<RemitProcess> listRemitProcess = remitProcessDao.listByBatchNo(batchNo); if (listRemitProcess == null) { throw RemitBizException.REMIT_PROCESS_RECORD_NOT_EXIST.print(); } // 4. 填充, 保存 remitBatch.setStatus(RemitBatchStatusEnum.SOLVED.getValue()); // 处理完成 remitBatch.setProcessSucAmount(remitBatch.getTotalAmount()); remitBatch.setProcessSucNum(remitBatch.getTotalNum()); remitBatch.setProcessDate(new Date()); remitBatch.setConfirm(loginName); remitBatch.setConfirmDate(new Date()); remitBatchDao.update(remitBatch); for (int i = 0; i < listRemitRequest.size(); i++) { listRemitRequest.get(i).setStatus(RemitRequestStatusEnum.REMIT_SUCCESS.getValue()); // 打款成功 remitRequestDao.update(listRemitRequest.get(i)); } for (int i = 0; i < listRemitProcess.size(); i++) { listRemitProcess.get(i).setStatus(RemitProcessStatusEnum.REMIT_SUCCESS.getValue()); // 打款成功 listRemitProcess.get(i).setProcessDate(new Date()); remitProcessDao.update(listRemitProcess.get(i)); } // 5. 备付金,虚拟账户处理 accountBiz.remitSuccess(remitBatch); // 6. 异步通知结算系统 for (int i = 0; i < listRemitRequest.size(); i++) { final RemitRequest remitRequest = listRemitRequest.get(i); // 通知结算 if (remitRequest.getTradeInitiator() != TradeSourcesEnum.BOSS_SYSTEM.getValue()) { notifyJmsTemplate.send(new MessageCreator() { public Message createMessage(Session session) throws JMSException { return session.createTextMessage(NotifyUtil.formatRemitComplete(remitRequest.getRequestNo(), remitRequest.getConfirmDate(), PublicStatusEnum.ACTIVE.getValue(), "")); } }); } } log.info("==>remitSuccess<=="); } /** * 打款失败 * * @param batchNo * @param loginName * @param remitRemark */ @Transactional(rollbackFor = Exception.class) public void remitFail(String batchNo, String loginName, String remitRemark) { log.info("==>remitFail"); // 1. 批次是否存在 RemitBatch remitBatch = remitBatchDao.getByBatchNo(batchNo); if (remitBatch == null) { throw RemitBizException.REMIT_BATCH_RECORD_NOT_EXIST.print(); } // 处理中,或处理完成 if (remitBatch.getStatus() == RemitBatchStatusEnum.SOLVED.getValue()) { throw RemitBizException.REMIT_BATCH_IS_COMPLETED.print(); } // 2. 打款请求是否存在 List<RemitRequest> listRemitRequest = remitRequestDao.listByBatchNo(batchNo); if (listRemitRequest == null) { throw RemitBizException.REMIT_REQUEST_RECORD_NOT_EXIST.print(); } // 3. 打款处理记录是否存在 List<RemitProcess> listRemitProcess = remitProcessDao.listByBatchNo(batchNo); if (listRemitProcess == null) { throw RemitBizException.REMIT_PROCESS_RECORD_NOT_EXIST.print(); } // 4. 填充, 保存 remitBatch.setStatus(RemitBatchStatusEnum.SOLVED.getValue()); // 处理完成 remitBatch.setProcessFailAmount(remitBatch.getTotalAmount()); remitBatch.setProcessFailNum(remitBatch.getTotalNum()); remitBatch.setProcessDate(new Date()); remitBatch.setConfirm(loginName); remitBatch.setConfirmDate(new Date()); remitBatchDao.update(remitBatch); for (int i = 0; i < listRemitRequest.size(); i++) { listRemitRequest.get(i).setStatus(RemitRequestStatusEnum.REMIT_FAILURE.getValue()); // 打款失败 listRemitRequest.get(i).setBankRemark(remitRemark); remitRequestDao.update(listRemitRequest.get(i)); } for (int i = 0; i < listRemitProcess.size(); i++) { listRemitProcess.get(i).setStatus(RemitProcessStatusEnum.REMIT_FAILURE.getValue()); // 打款失败 listRemitProcess.get(i).setProcessDate(new Date()); listRemitProcess.get(i).setBankRemark(remitRemark); remitProcessDao.update(listRemitProcess.get(i)); } // 5. 备付金,虚拟账户处理 accountBiz.remitFail(remitBatch); // 6. 异步通知结算系统 for (int i = 0; i < listRemitRequest.size(); i++) { final RemitRequest remitRequest = listRemitRequest.get(i); // 通知结算 if (remitRequest.getTradeInitiator() != TradeSourcesEnum.BOSS_SYSTEM.getValue()) { notifyJmsTemplate.send(new MessageCreator() { public Message createMessage(Session session) throws JMSException { return session.createTextMessage(NotifyUtil.formatRemitComplete(remitRequest.getRequestNo(), remitRequest.getConfirmDate(), PublicStatusEnum.INACTIVE.getValue(), "")); } }); } } log.info("==>remitFail<=="); } }
gpl-2.0
BrettsProjects/ITC205-Assign3
src/library/entities/Book.java
5912
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package library.entities; import library.interfaces.entities.EBookState; import library.interfaces.entities.IBook; import library.interfaces.entities.ILoan; /** * * @author Brett.Smith */ public class Book implements IBook { private final String author_; private final String title_; private final String callNumber_; private final int bookId_; private ILoan loanAssociated_; private EBookState eBookState_; /** * Default constructor for book. Throws IllegalArgumentException if any of * parameters are invalid. i.e. objects are null OR bookId is less than or * equal to 0. * * @param author * @param title * @param callNumber * @param bookId * * @throws IllegalArgumentException */ public Book(String author, String title, String callNumber, int bookId) throws IllegalArgumentException { if (author == null || author.isEmpty()) { throw new IllegalArgumentException("Author cannot be null or empty string."); } else { author_ = author; } if (title == null || title.isEmpty()) { throw new IllegalArgumentException("Title cannot be null or empty string."); } else { title_ = title; } if (callNumber == null || callNumber.isEmpty()) { throw new IllegalArgumentException("Call Number cannot be null or empty string."); } else { callNumber_ = callNumber; } if (bookId <= 0 ) { throw new IllegalArgumentException("Book ID cannot be 0 or less than 0."); } else { bookId_ = bookId; } eBookState_ = eBookState_.AVAILABLE; } @Override /** * Allows a book to be borrowed by a particular Loan object. The book first * checks its present status and if it is AVAILABLE then the book * is allowed to be borrowed by the loan. */ public void borrow(ILoan loanAssociated) { if (loanAssociated == null) { throw new RuntimeException("The associated loan cannot be null."); } else if (eBookState_ == eBookState_.AVAILABLE && loanAssociated_ == null) { loanAssociated_ = loanAssociated; // Associates the loan eBookState_ = eBookState_.ON_LOAN; // Sets the book status to on loan. } else { throw new RuntimeException("This book has already been borrowed by " + loanAssociated_.getID()); } } @Override /** * Returns the associated loan object with this book. If the book isnt * presently on loan then null is returned. */ public ILoan getLoan() { if (eBookState_ == eBookState_.ON_LOAN) { return loanAssociated_; } else { return null; } } @Override /** * Return book allows a book to be returned from a loan. If the book is * damanged, then the book is put into the DAMAGED state, otherwise it * is AVAILABLE. */ public void returnBook(boolean damaged) { if (eBookState_ == eBookState_.ON_LOAN) { if (damaged) { eBookState_ = eBookState_.DAMAGED; } else { eBookState_ = eBookState_.AVAILABLE; loanAssociated_ = null; } } else { throw new RuntimeException("This book was not presently on loan."); } } @Override /** * If the book is lost whilst on loan, then it may be set to LOST. */ public void lose() { if (eBookState_ == eBookState_.ON_LOAN) { eBookState_ = eBookState_.LOST; loanAssociated_ = null; } else { throw new RuntimeException("The book was not on loan."); } } @Override /** * If the book is damaged, then it may be set to AVAILABLE. */ public void repair() { if (eBookState_ == eBookState_.DAMAGED) { eBookState_ = eBookState_.AVAILABLE; } else { throw new RuntimeException("The book was not damaged."); } } @Override /** * If the book is damaged, lost, or available and we choose to remove it * we can. */ public void dispose() { if (eBookState_ == eBookState_.AVAILABLE || eBookState_ == eBookState_.LOST || eBookState_ == eBookState_.DAMAGED) // If the book is AVAILABLE, LOST, DAMAGED then we may dispose of // it. { eBookState_ = eBookState_.DISPOSED; } else { throw new RuntimeException("The book was not in a state to be" + " disposed."); } } @Override /** * Returns the current state of the book. */ public EBookState getState() { return eBookState_; } @Override /** * Returns the author of the book. */ public String getAuthor() { return author_; } @Override /** * Returns the title of the book. */ public String getTitle() { return title_; } @Override /** * Returns the call number of the book. */ public String getCallNumber() { return callNumber_; } @Override /** * Returns the ID of the book. */ public int getID() { return bookId_; } }
gpl-2.0
GollumTeam/JammyFurniture
src/main/java/com/gollum/jammyfurniture/client/render/BathRenderer.java
1427
package com.gollum.jammyfurniture.client.render; import com.gollum.jammyfurniture.client.model.ModelBath; import net.minecraft.tileentity.TileEntity; public class BathRenderer extends JFTileEntitySpecialRenderer { private static final ModelBath modelBath = new ModelBath(); protected void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f, int metadata) { float rotation = 0; switch (metadata) { default: rotation = 0; break; case 0: case 10: rotation = 90; break; case 3: case 9: rotation = 180; break; case 2: case 8: rotation = 270; break; } if (this.isInventory) { renderInInventory(x, y, z); } else { if (metadata > 7) { renderModel(x, y, z, rotation, false); } else { renderModel(x, y, z, rotation, true); } } } private void renderModel(double x, double y, double z, float rotation, boolean left) { this.beforeRender("bath", x, y, z, rotation); if (left) { this.modelBath.renderModelLeft(0.0625F); } else { this.modelBath.renderModelRight(0.0625F); } this.endRender(); } private void renderInInventory(double x, double y, double z) { this.beforeRender("bath", x, y, z-0.3F, 90.0F); this.modelBath.renderModelLeft(0.0625F); this.endRender(); this.beforeRender("bath", x, y, z + 0.7F, 270.0F); this.modelBath.renderModelRight(0.0625F); this.endRender(); } }
gpl-2.0