repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
rforge/biocep | src_aws_client/com/amazonaws/ec2/doc/_2008_12_01/DescribeAvailabilityZonesType.java | 1820 |
package com.amazonaws.ec2.doc._2008_12_01;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for DescribeAvailabilityZonesType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="DescribeAvailabilityZonesType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="availabilityZoneSet" type="{http://ec2.amazonaws.com/doc/2008-12-01/}DescribeAvailabilityZonesSetType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DescribeAvailabilityZonesType", propOrder = {
"availabilityZoneSet"
})
public class DescribeAvailabilityZonesType {
@XmlElement(required = true)
protected DescribeAvailabilityZonesSetType availabilityZoneSet;
/**
* Gets the value of the availabilityZoneSet property.
*
* @return
* possible object is
* {@link DescribeAvailabilityZonesSetType }
*
*/
public DescribeAvailabilityZonesSetType getAvailabilityZoneSet() {
return availabilityZoneSet;
}
/**
* Sets the value of the availabilityZoneSet property.
*
* @param value
* allowed object is
* {@link DescribeAvailabilityZonesSetType }
*
*/
public void setAvailabilityZoneSet(DescribeAvailabilityZonesSetType value) {
this.availabilityZoneSet = value;
}
}
| gpl-3.0 |
sethten/MoDesserts | mcp50/temp/src/minecraft/net/minecraft/src/CompressedStreamTools.java | 4390 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
// Referenced classes of package net.minecraft.src:
// NBTBase, NBTTagCompound
public class CompressedStreamTools
{
public CompressedStreamTools()
{
}
public static NBTTagCompound func_1138_a(InputStream p_1138_0_)
throws IOException
{
DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(p_1138_0_)));
try
{
NBTTagCompound nbttagcompound = func_1141_a(datainputstream);
return nbttagcompound;
}
finally
{
datainputstream.close();
}
}
public static void func_1143_a(NBTTagCompound p_1143_0_, OutputStream p_1143_1_)
throws IOException
{
DataOutputStream dataoutputstream = new DataOutputStream(new GZIPOutputStream(p_1143_1_));
try
{
func_1139_a(p_1143_0_, dataoutputstream);
}
finally
{
dataoutputstream.close();
}
}
public static NBTTagCompound func_40592_a(byte p_40592_0_[])
throws IOException
{
DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(p_40592_0_))));
try
{
NBTTagCompound nbttagcompound = func_1141_a(datainputstream);
return nbttagcompound;
}
finally
{
datainputstream.close();
}
}
public static byte[] func_40591_a(NBTTagCompound p_40591_0_)
throws IOException
{
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
DataOutputStream dataoutputstream = new DataOutputStream(new GZIPOutputStream(bytearrayoutputstream));
try
{
func_1139_a(p_40591_0_, dataoutputstream);
}
finally
{
dataoutputstream.close();
}
return bytearrayoutputstream.toByteArray();
}
public static void func_35621_a(NBTTagCompound p_35621_0_, File p_35621_1_)
throws IOException
{
File file = new File((new StringBuilder()).append(p_35621_1_.getAbsolutePath()).append("_tmp").toString());
if(file.exists())
{
file.delete();
}
func_35620_b(p_35621_0_, file);
if(p_35621_1_.exists())
{
p_35621_1_.delete();
}
if(p_35621_1_.exists())
{
throw new IOException((new StringBuilder()).append("Failed to delete ").append(p_35621_1_).toString());
} else
{
file.renameTo(p_35621_1_);
return;
}
}
public static void func_35620_b(NBTTagCompound p_35620_0_, File p_35620_1_)
throws IOException
{
DataOutputStream dataoutputstream = new DataOutputStream(new FileOutputStream(p_35620_1_));
try
{
func_1139_a(p_35620_0_, dataoutputstream);
}
finally
{
dataoutputstream.close();
}
}
public static NBTTagCompound func_35622_a(File p_35622_0_)
throws IOException
{
if(!p_35622_0_.exists())
{
return null;
}
DataInputStream datainputstream = new DataInputStream(new FileInputStream(p_35622_0_));
try
{
NBTTagCompound nbttagcompound = func_1141_a(datainputstream);
return nbttagcompound;
}
finally
{
datainputstream.close();
}
}
public static NBTTagCompound func_1141_a(DataInput p_1141_0_)
throws IOException
{
NBTBase nbtbase = NBTBase.func_734_b(p_1141_0_);
if(nbtbase instanceof NBTTagCompound)
{
return (NBTTagCompound)nbtbase;
} else
{
throw new IOException("Root tag must be a named compound tag");
}
}
public static void func_1139_a(NBTTagCompound p_1139_0_, DataOutput p_1139_1_)
throws IOException
{
NBTBase.func_738_a(p_1139_0_, p_1139_1_);
}
}
| gpl-3.0 |
Sleis/ReversiGamewithJavaFX | src/main/java/Model/Position.java | 2542 | package Model;
/*
* #%L
* Reversi
* %%
* Copyright (C) 2016 University of Debrecen, Faculty of Informatics
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
/**
* Adott cella pozíciót tartalmazó osztály.
*
* @author Iványi Dániel
*/
public class Position {
/**
* A cella sorszáma.
*/
private int sor;
/**
* A cella oszlopszáma.
*/
private int oszlop;
/**
* Létrehoz egy <code>Position</code> objektumot üres <code>sor</code> és
* <code>oszlop</code> tulajdonsággal.
*/
public Position() {
}
/**
* Létrehoz egy <code>Position</code> objektumot adott <code>sor</code> és
* <code>oszlop</code> tulajdonsággal.
*
* @param sor az objektum <code>sor</code> tulajdonsága
* @param oszlop az objektum <code>oszlop</code> tulajdonsága
*/
public Position(int sor, int oszlop) {
this.sor = sor;
this.oszlop = oszlop;
}
/**
* Visszaadja az objektum <code>sor</code> tulajdonságát.
*
* @return az objektum <code>sor</code> tulajdonsága
*/
public int getSor() {
return sor;
}
/**
* Visszaadja az objektum <code>oszlop</code> tulajdonságát.
*
* @return az objektum <code>oszlop</code> tulajdonsága
*/
public int getOszlop() {
return oszlop;
}
/**
* Beállítja az objektum <code>sor</code> tulajdonságát.
*
* @param sor az objektum <code>sor</code> tulajdonsága
*/
public void setSor(int sor) {
this.sor = sor;
}
/**
* Beállítja az objektum <code>oszlop</code> tulajdonságát.
*
* @param oszlop az objektum <code>oszlop</code> tulajdonsága
*/
public void setOszlop(int oszlop) {
this.oszlop = oszlop;
}
}
| gpl-3.0 |
MHTaleb/Encologim | lib/JasperReport/src/net/sf/jasperreports/charts/xml/JRBarChartFactory.java | 1642 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2016 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.charts.xml;
import net.sf.jasperreports.engine.JRChart;
import net.sf.jasperreports.engine.design.JRDesignChart;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRBaseFactory;
import org.xml.sax.Attributes;
/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
*/
public class JRBarChartFactory extends JRBaseFactory
{
@Override
public Object createObject(Attributes atts)
{
JasperDesign jasperDesign = (JasperDesign)digester.peek(digester.getCount() - 2);
JRDesignChart chart = new JRDesignChart(jasperDesign, JRChart.CHART_TYPE_BAR);
return chart;
}
}
| gpl-3.0 |
adhuc-projects/cena | src/main/java/org/adhuc/cena/menu/ingredients/IngredientConsultationImpl.java | 1516 | /*
* Copyright (C) 2019-2020 Alexandre Carbenay
*
* This file is part of Cena Project.
*
* Cena Project is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* Cena Project 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 Cena Project. If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.adhuc.cena.menu.ingredients;
import java.util.List;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.adhuc.cena.menu.common.ApplicationService;
/**
* An {@link IngredientConsultation} implementation.
*
* @author Alexandre Carbenay
* @version 0.3.0
* @since 0.1.0
*/
@RequiredArgsConstructor
@ApplicationService("ingredientConsultation")
class IngredientConsultationImpl implements IngredientConsultation {
@NonNull
private IngredientRepository repository;
@Override
public List<Ingredient> getIngredients() {
return List.copyOf(repository.findAll());
}
@Override
public Ingredient getIngredient(@NonNull IngredientId ingredientId) {
return repository.findNotNullById(ingredientId);
}
}
| gpl-3.0 |
pablodanielrey/java | document/documentModel/src/main/java/ar/com/dcsys/model/DocumentsManagerBean.java | 1041 | package ar.com.dcsys.model;
import java.util.List;
import javax.inject.Inject;
import ar.com.dcsys.data.document.Document;
import ar.com.dcsys.data.document.DocumentDAO;
import ar.com.dcsys.exceptions.DocumentException;
public class DocumentsManagerBean implements DocumentsManager {
private final DocumentDAO documentDAO;
@Inject
public DocumentsManagerBean(DocumentDAO documentDAO) {
this.documentDAO = documentDAO;
}
@Override
public void persist(Document d) throws DocumentException {
documentDAO.persist(d);
}
@Override
public List<String> findAll() throws DocumentException {
return documentDAO.findAll();
}
@Override
public Document findById(String id) throws DocumentException {
if (id == null) {
throw new DocumentException("id == null");
}
return documentDAO.findById(id);
}
@Override
public Document findByIdWithoutContent(String id) throws DocumentException {
if (id == null) {
throw new DocumentException("id == null");
}
return documentDAO.findByIdWithoutContent(id);
}
}
| gpl-3.0 |
ccem-dev/otus-api | source/otus-business/src/main/java/br/org/otus/security/services/SecurityContextServiceBean.java | 2414 | package br.org.otus.security.services;
import br.org.otus.security.context.SecurityContext;
import br.org.otus.security.context.SessionIdentifier;
import br.org.otus.security.dtos.JWTClaimSetBuilder;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.SignedJWT;
import org.ccem.otus.exceptions.webservice.common.DataNotFoundException;
import org.ccem.otus.exceptions.webservice.security.TokenException;
import javax.ejb.Stateless;
import javax.inject.Inject;
import java.security.SecureRandom;
import java.text.ParseException;
import java.util.NoSuchElementException;
@Stateless
public class SecurityContextServiceBean implements SecurityContextService {
@Inject
private SecurityContext securityContext;
@Override
public String generateToken(JWTClaimSetBuilder claimSetBuilder, byte[] secretKey) throws TokenException {
try {
JWSSigner signer = new MACSigner(secretKey);
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256),
claimSetBuilder.buildClaimSet());
signedJWT.sign(signer);
return signedJWT.serialize();
} catch (JOSEException e) {
throw new TokenException(e);
}
}
@Override
public byte[] generateSecretKey() {
SecureRandom secureRandom = new SecureRandom();
byte[] sharedSecret = new byte[32];
secureRandom.nextBytes(sharedSecret);
return sharedSecret;
}
@Override
public void addSession(SessionIdentifier sessionIdentifier) {
securityContext.addSession(sessionIdentifier);
}
@Override
public void removeToken(String token) {
securityContext.removeSession(token);
}
@Override
public void validateToken(String token) throws TokenException {
try {
if (securityContext.hasToken(token)) {
securityContext.verifySignature(token);
} else {
throw new TokenException(new DataNotFoundException());
}
} catch (ParseException | JOSEException e) {
throw new TokenException(e);
}
}
@Override
public SessionIdentifier getSession(String token) {
try {
return securityContext.getSession(token);
} catch (NoSuchElementException e) {
return null;
}
}
}
| gpl-3.0 |
sealfoss/Neuronium | Neuron.java | 3013 |
import java.io.*;
import java.util.ArrayList;
public class Neuron implements Serializable {
//static final long serialVersionUID = 31337L;
private int neuronIndex;
private int layerIndex;
private ArrayList<Axon> inputs;
private ArrayList<Axon> outputs;
private double threshold;
private double inputSum;
private boolean excited;
public Neuron(double threshold, double inputSum, boolean excited, int neuronIndex, int layerIndex) {
this.threshold = threshold;
this.inputSum = inputSum;
this.excited = excited;
inputs = new ArrayList<Axon>();
outputs = new ArrayList<Axon>();
this.neuronIndex = neuronIndex;
this.layerIndex = layerIndex;
}
public Neuron(int neuronIndex, int layerIndex) {
this(0, 0, false, neuronIndex, layerIndex);
}
public Neuron() {
this(0, 0, false, 0, 0);
}
public void compute() {
if(excited) {
System.out.print("\nNeuron " + getName() + " going from excited to... ");
}
else {
System.out.print("\nNeuron " + getName() + " going from grounded to... ");
}
inputSum = 0;
for(int i = 0; i < inputs.size(); i++) {
inputSum += inputs.get(i).getOutput();
}
if(inputSum >= threshold) {
excited = true;
System.out.print("EXCITED!");
}
else {
excited = false;
System.out.print("GROUNDED!");
}
}
public void push() {
//set up boolean to make sure all of the input axions have reported before pushing forward
if(layerIndex > 0) {
compute();
}
for(int i = 0; i < outputs.size(); i++) {
outputs.get(i).push(excited);
}
}
//Accessors
public double getThreshold() {
return(threshold);
}
public double getInputSum() {
return(inputSum);
}
public boolean getState() {
return(excited);
}
public String stateToString() {
if(excited) {
return("L" + layerIndex + "N" + neuronIndex + ": Excited ");
}
else {
return("L" + layerIndex + "N" + neuronIndex + ": Grounded");
}
}
public String getName() {
return("L" + layerIndex + "N" + neuronIndex);
}
public int getLayerIndex() {
return(layerIndex);
}
public int getNeuronIndex() {
return(neuronIndex);
}
public int tabulateInputs() {
return(inputs.size());
}
public int tabulateOutputs() {
return(outputs.size());
}
public ArrayList<Axon> getOutputs() {
return(outputs);
}
//Mutators
public void setState(boolean state) {
this.excited = state;
}
public void setThreshold(double threshold){
this.threshold = threshold;
}
public void setInputSum(double inputSum) {
this.inputSum = inputSum;
}
public void buildLink(Neuron distantEnd) {
Axon link = new Axon(this, distantEnd);
outputs.add(link);
System.out.println("Link built between L" + layerIndex + "N" + neuronIndex +
", and L" + distantEnd.getLayerIndex() + "N" + distantEnd.getNeuronIndex());
}
public void receiveLink(Axon link) {
inputs.add(link);
}
public void removeInput(Axon link) {
inputs.remove(link);
}
public void removeOutput(Axon link) {
outputs.remove(link);
}
}
| gpl-3.0 |
powerstackers/FTC-5029-Res-Q | FtcRobotController/src/main/java/com/powerstackers/resq/opmodes/teleop/TeleopBlue.java | 370 | package com.powerstackers.resq.opmodes.teleop;
import com.powerstackers.resq.common.enums.PublicEnums.AllianceColor;
import org.swerverobotics.library.interfaces.TeleOp;
/**
* @author Jonathan
*/
@TeleOp(name = "Teleop Blue", group = "Powerstackers")
public class TeleopBlue extends ResqTeleop {
public TeleopBlue() {
super(AllianceColor.BLUE);
}
}
| gpl-3.0 |
Binnette/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/QuestController.java | 14741 | package de.westnordost.streetcomplete.data;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Provider;
import de.westnordost.osmapi.map.data.LatLon;
import de.westnordost.osmapi.map.data.OsmElement;
import de.westnordost.streetcomplete.ApplicationConstants;
import de.westnordost.streetcomplete.data.changesets.OpenChangesetsDao;
import de.westnordost.streetcomplete.data.download.QuestDownloadService;
import de.westnordost.streetcomplete.data.osm.OsmQuest;
import de.westnordost.streetcomplete.data.osm.changes.StringMapChanges;
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder;
import de.westnordost.streetcomplete.data.osm.persist.ElementGeometryDao;
import de.westnordost.streetcomplete.data.osm.persist.MergedElementDao;
import de.westnordost.streetcomplete.data.osm.persist.OsmQuestDao;
import de.westnordost.streetcomplete.data.osm.persist.UndoOsmQuestDao;
import de.westnordost.streetcomplete.data.osmnotes.CreateNote;
import de.westnordost.streetcomplete.data.osmnotes.CreateNoteDao;
import de.westnordost.streetcomplete.data.osmnotes.OsmNoteQuest;
import de.westnordost.streetcomplete.data.osmnotes.OsmNoteQuestDao;
import de.westnordost.streetcomplete.data.upload.QuestChangesUploadService;
import de.westnordost.streetcomplete.quests.note_discussion.NoteDiscussionForm;
import de.westnordost.streetcomplete.util.SlippyMapMath;
import de.westnordost.osmapi.map.data.BoundingBox;
import de.westnordost.osmapi.map.data.Element;
import static android.content.Context.BIND_AUTO_CREATE;
public class QuestController
{
private static final String TAG = "QuestController";
private final OsmQuestDao osmQuestDB;
private final UndoOsmQuestDao undoOsmQuestDB;
private final MergedElementDao osmElementDB;
private final ElementGeometryDao geometryDB;
private final OsmNoteQuestDao osmNoteQuestDB;
private final CreateNoteDao createNoteDB;
private final OpenChangesetsDao openChangesetsDao;
private final Context context;
private final VisibleQuestRelay relay;
private final Provider<List<QuestType>> questTypesProvider;
private boolean downloadServiceIsBound;
private QuestDownloadService.Interface downloadService;
private final ServiceConnection downloadServiceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
downloadService = ((QuestDownloadService.Interface)service);
downloadService.setQuestListener(relay);
}
public void onServiceDisconnected(ComponentName className)
{
downloadService = null;
}
};
private boolean uploadServiceIsBound;
private QuestChangesUploadService.Interface uploadService;
private final ServiceConnection uploadServiceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
uploadService = ((QuestChangesUploadService.Interface)service);
uploadService.setQuestListener(relay);
}
public void onServiceDisconnected(ComponentName className)
{
uploadService = null;
}
};
private Handler workerHandler;
private HandlerThread worker;
@Inject public QuestController(OsmQuestDao osmQuestDB, UndoOsmQuestDao undoOsmQuestDB,
MergedElementDao osmElementDB, ElementGeometryDao geometryDB,
OsmNoteQuestDao osmNoteQuestDB, CreateNoteDao createNoteDB,
OpenChangesetsDao openChangesetsDao,
Provider<List<QuestType>> questTypesProvider, Context context)
{
this.osmQuestDB = osmQuestDB;
this.undoOsmQuestDB = undoOsmQuestDB;
this.osmElementDB = osmElementDB;
this.geometryDB = geometryDB;
this.osmNoteQuestDB = osmNoteQuestDB;
this.createNoteDB = createNoteDB;
this.openChangesetsDao = openChangesetsDao;
this.questTypesProvider = questTypesProvider;
this.context = context;
this.relay = new VisibleQuestRelay();
}
public void onCreate()
{
worker = new HandlerThread("QuestControllerThread");
worker.start();
workerHandler = new Handler(worker.getLooper());
}
public void onStart(VisibleQuestListener questListener)
{
relay.setListener(questListener);
downloadServiceIsBound = context.bindService(
new Intent(context, QuestDownloadService.class),
downloadServiceConnection, BIND_AUTO_CREATE);
uploadServiceIsBound = context.bindService(
new Intent(context, QuestChangesUploadService.class),
uploadServiceConnection, BIND_AUTO_CREATE);
}
public void onStop()
{
relay.setListener(null);
if(downloadServiceIsBound) context.unbindService(downloadServiceConnection);
if(downloadService != null) downloadService.setQuestListener(null);
if(uploadServiceIsBound) context.unbindService(uploadServiceConnection);
if(uploadService != null) uploadService.setQuestListener(null);
}
public void onDestroy()
{
worker.quit();
}
/** Create a note for the given OSM Quest instead of answering it. The quest will turn
* invisible.
* @return true if successful */
public boolean createNote(long osmQuestId, String questTitle, String text, ArrayList<String> imagePaths)
{
OsmQuest q = osmQuestDB.get(osmQuestId);
// race condition: another thread may have removed the element already (#288)
if(q == null || q.getStatus() != QuestStatus.NEW) return false;
CreateNote createNote = new CreateNote();
createNote.position = q.getMarkerLocation();
createNote.text = text;
createNote.questTitle = questTitle;
createNote.elementType = q.getElementType();
createNote.elementId = q.getElementId();
createNote.imagePaths = imagePaths;
createNoteDB.add(createNote);
/* The quests that reference the same element for which the user was not able to
answer the question are removed because the to-be-created note blocks quest
creation for other users, so those quests should be removed from the user's
own display as well. As soon as the note is resolved, the quests will be re-
created next time they are downloaded */
List<OsmQuest> questsForThisOsmElement = osmQuestDB.getAll(null, QuestStatus.NEW, null,
q.getElementType(), q.getElementId());
List<Long> questIdsForThisOsmElement = new ArrayList<>(questsForThisOsmElement.size());
for(OsmQuest quest : questsForThisOsmElement)
{
questIdsForThisOsmElement.add(quest.getId());
}
osmQuestDB.deleteAll(questIdsForThisOsmElement);
workerHandler.post(() -> relay.onQuestsRemoved(questIdsForThisOsmElement, QuestGroup.OSM));
osmElementDB.deleteUnreferenced();
geometryDB.deleteUnreferenced();
return true;
}
public void createNote(String text, ArrayList<String> imagePaths, LatLon position)
{
CreateNote createNote = new CreateNote();
createNote.position = position;
createNote.text = text;
createNote.imagePaths = imagePaths;
createNoteDB.add(createNote);
}
/** Apply the user's answer to the given quest. (The quest will turn invisible.)
* @return true if successful */
public boolean solve(long questId, QuestGroup group, Bundle answer, String source)
{
boolean success = false;
if (group == QuestGroup.OSM)
{
success = solveOsmQuest(questId, answer, source);
}
else if (group == QuestGroup.OSM_NOTE)
{
success = solveOsmNoteQuest(questId, answer);
}
workerHandler.post(() -> relay.onQuestRemoved(questId, group));
return success;
}
public OsmQuest getLastSolvedOsmQuest()
{
return osmQuestDB.getLastSolved();
}
public OsmElement getOsmElement(OsmQuest quest)
{
return (OsmElement) osmElementDB.get(quest.getElementType(), quest.getElementId());
}
@Nullable public Quest getNextAt(long questId, QuestGroup group)
{
if (group == QuestGroup.OSM)
{
return osmQuestDB.getNextNewAt(questId, getQuestTypeNames());
}
return null;
}
public void undo(final OsmQuest quest)
{
if(quest == null) return;
// not uploaded yet -> simply revert to NEW
if(quest.getStatus() == QuestStatus.ANSWERED || quest.getStatus() == QuestStatus.HIDDEN)
{
quest.setStatus(QuestStatus.NEW);
quest.setChanges(null, null);
osmQuestDB.update(quest);
// inform relay that the quest is visible again
workerHandler.post(() -> relay.onQuestsCreated(Collections.singletonList(quest), QuestGroup.OSM));
}
// already uploaded! -> create change to reverse the previous change
else if(quest.getStatus() == QuestStatus.CLOSED)
{
quest.setStatus(QuestStatus.REVERT);
osmQuestDB.update(quest);
OsmQuest reversedQuest = new OsmQuest(
quest.getOsmElementQuestType(),
quest.getElementType(),
quest.getElementId(),
quest.getGeometry());
reversedQuest.setChanges(quest.getChanges().reversed(), quest.getChangesSource());
reversedQuest.setStatus(QuestStatus.ANSWERED);
undoOsmQuestDB.add(reversedQuest);
}
else
{
throw new IllegalStateException("Tried to undo a quest that hasn't been answered yet");
}
}
private boolean solveOsmNoteQuest(long questId, Bundle answer)
{
OsmNoteQuest q = osmNoteQuestDB.get(questId);
if(q == null || q.getStatus() != QuestStatus.NEW) return false;
ArrayList<String> imagePaths = answer.getStringArrayList(NoteDiscussionForm.IMAGE_PATHS);
String comment = answer.getString(NoteDiscussionForm.TEXT);
if(comment != null && !comment.isEmpty())
{
q.setComment(comment);
q.setStatus(QuestStatus.ANSWERED);
q.setImagePaths(imagePaths);
osmNoteQuestDB.update(q);
return true;
}
else
{
throw new RuntimeException(
"NoteQuest has been answered with an empty comment!");
}
}
private boolean solveOsmQuest(long questId, Bundle answer, String source)
{
// race condition: another thread (i.e. quest download thread) may have removed the
// element already (#282). So in this case, just ignore
OsmQuest q = osmQuestDB.get(questId);
if(q == null || q.getStatus() != QuestStatus.NEW) return false;
Element element = osmElementDB.get(q.getElementType(), q.getElementId());
if(element == null) return false;
StringMapChanges changes;
try
{
StringMapChangesBuilder changesBuilder = new StringMapChangesBuilder(element.getTags());
q.getOsmElementQuestType().applyAnswerTo(answer, changesBuilder);
changes = changesBuilder.create();
}
catch (IllegalArgumentException e)
{
// if applying the changes results in an error (=a conflict), the data the quest(ion)
// was based on is not valid anymore -> like with other conflicts, silently drop the
// user's change (#289) and the quest
osmQuestDB.delete(questId);
return false;
}
if(!changes.isEmpty())
{
Log.d(TAG, "Solved a "+q.getType().getClass().getSimpleName() + " quest: " + changes.toString());
q.setChanges(changes, source);
q.setStatus(QuestStatus.ANSWERED);
osmQuestDB.update(q);
openChangesetsDao.setLastQuestSolvedTimeToNow();
return true;
}
else
{
throw new RuntimeException(
"OsmQuest " + questId + " (" + q.getType().getClass().getSimpleName() +
") has been answered by the user but the changeset is empty!");
}
}
/** Make the given quest invisible (per user interaction). */
public void hide(long questId, QuestGroup group)
{
if(group == QuestGroup.OSM)
{
OsmQuest q = osmQuestDB.get(questId);
if(q == null || q.getStatus() != QuestStatus.NEW) return;
q.setStatus(QuestStatus.HIDDEN);
osmQuestDB.update(q);
workerHandler.post(() -> relay.onQuestRemoved(q.getId(), group));
}
else if(group == QuestGroup.OSM_NOTE)
{
OsmNoteQuest q = osmNoteQuestDB.get(questId);
if(q == null || q.getStatus() != QuestStatus.NEW) return;
q.setStatus(QuestStatus.HIDDEN);
osmNoteQuestDB.update(q);
workerHandler.post(() -> relay.onQuestRemoved(q.getId(), group));
}
}
/** Retrieve the given quest from local database */
@Nullable public Quest get(long questId, QuestGroup group)
{
if(group == QuestGroup.OSM) return osmQuestDB.get(questId);
else if(group == QuestGroup.OSM_NOTE) return osmNoteQuestDB.get(questId);
return null;
}
/** Retrieve all visible (=new) quests in the given bounding box from local database
* asynchronously. */
public void retrieve(BoundingBox bbox)
{
workerHandler.post(() ->
{
List<String> questTypeNames = getQuestTypeNames();
List<OsmQuest> osmQuests = osmQuestDB.getAll(bbox, QuestStatus.NEW, questTypeNames);
if(!osmQuests.isEmpty()) relay.onQuestsCreated(osmQuests, QuestGroup.OSM);
List<OsmNoteQuest> osmNoteQuests = osmNoteQuestDB.getAll(bbox, QuestStatus.NEW);
if(!osmNoteQuests.isEmpty()) relay.onQuestsCreated(osmNoteQuests, QuestGroup.OSM_NOTE);
});
}
private List<String> getQuestTypeNames()
{
List<QuestType> questTypes = questTypesProvider.get();
List<String> questTypeNames = new ArrayList<>(questTypes.size());
for (QuestType questType : questTypes)
{
questTypeNames.add(questType.getClass().getSimpleName());
}
return questTypeNames;
}
/** Download quests in at least the given bounding box asynchronously. The next-bigger rectangle
* in a (z14) tiles grid that encloses the given bounding box will be downloaded.
*
* @param bbox the minimum area to download
* @param maxQuestTypesToDownload download at most the given number of quest types. null for
* unlimited
* @param isPriority whether this shall be a priority download (cancels previous downloads and
* puts itself in the front)
*/
public void download(BoundingBox bbox, Integer maxQuestTypesToDownload, boolean isPriority)
{
Rect tilesRect = SlippyMapMath.enclosingTiles(bbox, ApplicationConstants.QUEST_TILE_ZOOM);
Intent intent = new Intent(context, QuestDownloadService.class);
intent.putExtra(QuestDownloadService.ARG_TILES_RECT, tilesRect);
if(maxQuestTypesToDownload != null)
{
intent.putExtra(QuestDownloadService.ARG_MAX_QUEST_TYPES, maxQuestTypesToDownload);
}
if(isPriority)
{
intent.putExtra(QuestDownloadService.ARG_IS_PRIORITY, true);
}
context.startService(intent);
}
/** @return true if a quest download triggered by the user is running */
public boolean isPriorityDownloadRunning()
{
return downloadService != null &&
downloadService.isDownloading() &&
downloadService.currentDownloadHasPriority();
}
/** Collect and upload all changes made by the user */
public void upload()
{
context.startService(new Intent(context, QuestChangesUploadService.class));
}
}
| gpl-3.0 |
sklintyg/webcert | web/src/main/java/se/inera/intyg/webcert/web/web/controller/facade/dto/CertificateDTO.java | 2107 | /*
* Copyright (C) 2022 Inera AB (http://www.inera.se)
*
* This file is part of sklintyg (https://github.com/sklintyg).
*
* sklintyg 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.
*
* sklintyg 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 se.inera.intyg.webcert.web.web.controller.facade.dto;
import java.util.Map;
import se.inera.intyg.common.support.facade.model.Certificate;
import se.inera.intyg.common.support.facade.model.CertificateDataElement;
import se.inera.intyg.common.support.facade.model.metadata.CertificateMetadata;
public class CertificateDTO {
private CertificateMetadata metadata;
private Map<String, CertificateDataElement> data;
private ResourceLinkDTO[] links;
public static CertificateDTO create(Certificate certificate, ResourceLinkDTO[] links) {
final var certificateDTO = new CertificateDTO();
certificateDTO.setMetadata(certificate.getMetadata());
certificateDTO.setData(certificate.getData());
certificateDTO.setLinks(links);
return certificateDTO;
}
public CertificateMetadata getMetadata() {
return metadata;
}
public void setMetadata(CertificateMetadata metadata) {
this.metadata = metadata;
}
public Map<String, CertificateDataElement> getData() {
return data;
}
public void setData(Map<String, CertificateDataElement> data) {
this.data = data;
}
public ResourceLinkDTO[] getLinks() {
return links;
}
public void setLinks(ResourceLinkDTO[] links) {
this.links = links;
}
}
| gpl-3.0 |
Hoppix/MacroEdit | src/startupGUI/RecordAlertDialog.java | 3475 | package startupGUI;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.border.MatteBorder;
public class RecordAlertDialog
{
String _message;
private JDialog dialog;
/**
* Launch the application.
*/
/**
* Create the dialog.
*/
public RecordAlertDialog(String message)
{
_message = message;
initDialog();
}
public void initDialog()
{
dialog = new JDialog((Frame) null);
dialog.getContentPane()
.setBackground(new Color(51, 102, 204));
//dialog.getContentPane().setSize(new Dimension(200, 100));
dialog.setModalityType(Dialog.DEFAULT_MODALITY_TYPE);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setResizable(false);
dialog.setSize(250, 130);
dialog.setUndecorated(true);
dialog.getContentPane()
.setLayout(null);
JLabel label = new JLabel("");
label.setBorder(
new MatteBorder(1, 1, 1, 1, (Color) new Color(51, 102, 204)));
label.setIcon(new ImageIcon(RecordAlertDialog.class
.getResource("/images/ss (2016-11-18 at 12.44.35).png")));
label.setBounds(0, 0, 250, 28);
dialog.getContentPane()
.add(label);
JButton btnNewButton = new JButton("X");
btnNewButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
dialog.dispose();
}
});
btnNewButton.setFont(new Font("Arimo", Font.BOLD, 14));
btnNewButton.setForeground(new Color(255, 255, 255));
btnNewButton.setBackground(new Color(51, 102, 204));
btnNewButton.setBounds(220, 0, 30, 28);
dialog.getContentPane()
.add(btnNewButton);
JLabel lblRecordInProgress = new JLabel(_message);
lblRecordInProgress.setFont(new Font("Arimo", Font.BOLD, 16));
lblRecordInProgress.setForeground(new Color(255, 255, 255));
lblRecordInProgress.setHorizontalAlignment(SwingConstants.CENTER);
lblRecordInProgress.setBorder(
new MatteBorder(1, 1, 1, 1, (Color) new Color(255, 255, 255)));
lblRecordInProgress.setBounds(10, 42, 230, 40);
dialog.getContentPane()
.add(lblRecordInProgress);
JButton btnDone = new JButton("Ok");
btnDone.setFont(new Font("Arimo", Font.BOLD, 14));
btnDone.setForeground(new Color(51, 102, 204));
btnDone.setBackground(new Color(255, 255, 255));
btnDone.setBounds(20, 96, 89, 23);
dialog.getContentPane()
.add(btnDone);
JButton btnCancel = new JButton("Cancel");
btnCancel.setBackground(new Color(255, 255, 255));
btnCancel.setFont(new Font("Arimo", Font.BOLD, 14));
btnCancel.setForeground(new Color(51, 102, 204));
btnCancel.setBounds(129, 96, 89, 23);
dialog.getContentPane()
.add(btnCancel);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}
| gpl-3.0 |
shamoxiaoniqiu2008/jeecg-framework | src/main/java/org/jeecgframework/web/demo/controller/test/JeecgBlobDataController.java | 6937 | package org.jeecgframework.web.demo.controller.test;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecgframework.web.demo.entity.test.JeecgBlobDataEntity;
import org.jeecgframework.web.demo.service.test.JeecgBlobDataServiceI;
import org.jeecgframework.web.system.service.SystemService;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
/**
* @Title: Controller
* @Description: Blob型数据操作例子
* @author Quainty
* @date 2013-06-07 14:46:08
* @version V1.0
*
*/
@Controller
@RequestMapping("/jeecgBlobDataController")
public class JeecgBlobDataController extends BaseController {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(JeecgBlobDataController.class);
@Autowired
private JeecgBlobDataServiceI jeecgBlobDataService;
@Autowired
private SystemService systemService;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* Blob型数据操作例子列表 页面跳转
*
* @return
*/
@RequestMapping(params = "jeecgBlobData")
public ModelAndView jeecgBlobData(HttpServletRequest request) {
return new ModelAndView("jeecg/demo/test/jeecgBlobDataList");
}
/**
* easyui AJAX请求数据
*
* @param request
* @param response
* @param dataGrid
* @param user
*/
@RequestMapping(params = "datagrid")
public void datagrid(JeecgBlobDataEntity jeecgBlobData,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
CriteriaQuery cq = new CriteriaQuery(JeecgBlobDataEntity.class, dataGrid);
//查询条件组装器
org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, jeecgBlobData);
this.jeecgBlobDataService.getDataGridReturn(cq, true);
TagUtil.datagrid(response, dataGrid);
}
/**
* 删除Blob型数据操作例子
*
* @return
*/
@RequestMapping(params = "del")
@ResponseBody
public AjaxJson del(JeecgBlobDataEntity jeecgBlobData, HttpServletRequest request) {
AjaxJson j = new AjaxJson();
jeecgBlobData = systemService.getEntity(JeecgBlobDataEntity.class, jeecgBlobData.getId());
message = "删除成功";
jeecgBlobDataService.delete(jeecgBlobData);
systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
j.setMsg(message);
return j;
}
@RequestMapping(params = "download")
public void exportXls(HttpServletRequest request, String fileId, HttpServletResponse response) {
// 从数据库取得数据
JeecgBlobDataEntity obj = systemService.getEntity(JeecgBlobDataEntity.class, fileId);
try {
Blob attachment = obj.getAttachmentcontent();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename="
+ new String((obj.getAttachmenttitle()+"."+obj.getExtend()).getBytes("GBK"), "ISO8859-1"));
//从数据库中读取出来 , 输出给下载用
InputStream bis = attachment.getBinaryStream();
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
long lTotalLen = 0;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
lTotalLen += bytesRead;
}
response.setHeader("Content-Length", String.valueOf(lTotalLen));
bos.flush();
bos.close();
} catch (Exception e){
e.printStackTrace();
}
}
@RequestMapping(params = "upload")
@ResponseBody
public AjaxJson upload(HttpServletRequest request, String documentTitle, HttpServletResponse response) {
AjaxJson j = new AjaxJson();
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
MultipartFile file = entity.getValue();// 获取上传文件对象
try {
jeecgBlobDataService.saveObj(documentTitle, file);
j.setMsg("文件导入成功!");
} catch (Exception e) {
j.setMsg("文件导入失败!");
logger.error(ExceptionUtil.getExceptionMessage(e));
}
//break; // 不支持多个文件导入?
}
return j;
}
/**
* 添加Blob型数据操作例子
*
* @param ids
* @return
*/
@RequestMapping(params = "save")
@ResponseBody
public AjaxJson save(JeecgBlobDataEntity jeecgBlobData, HttpServletRequest request) {
AjaxJson j = new AjaxJson();
if (StringUtil.isNotEmpty(jeecgBlobData.getId())) {
message = "更新成功";
JeecgBlobDataEntity t = jeecgBlobDataService.get(JeecgBlobDataEntity.class, jeecgBlobData.getId());
try {
MyBeanUtils.copyBeanNotNull2Bean(jeecgBlobData, t);
jeecgBlobDataService.saveOrUpdate(t);
systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
} catch (Exception e) {
e.printStackTrace();
}
} else {
message = "添加成功";
jeecgBlobDataService.save(jeecgBlobData);
systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
}
return j;
}
/**
* Blob型数据操作例子列表页面跳转
*
* @return
*/
@RequestMapping(params = "addorupdate")
public ModelAndView addorupdate(JeecgBlobDataEntity jeecgBlobData, HttpServletRequest req) {
if (StringUtil.isNotEmpty(jeecgBlobData.getId())) {
jeecgBlobData = jeecgBlobDataService.getEntity(JeecgBlobDataEntity.class, jeecgBlobData.getId());
req.setAttribute("jeecgBlobDataPage", jeecgBlobData);
}
return new ModelAndView("jeecg/demo/test/jeecgBlobData");
}
}
| gpl-3.0 |
instytut-badan-edukacyjnych/platforma-testow | LoremIpsum/src/main/java/pl/edu/ibe/loremipsum/tablet/base/BaseServiceFragment.java | 2392 | /************************************
* This file is part of Test Platform.
*
* Test Platform 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.
*
* Test Platform 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 Test Platform; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Ten plik jest częścią Platformy Testów.
*
* Platforma Testów jest wolnym oprogramowaniem; możesz go rozprowadzać dalej
* i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU,
* wydanej przez Fundację Wolnego Oprogramowania - według wersji 2 tej
* Licencji lub (według twojego wyboru) którejś z późniejszych wersji.
*
* Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on
* użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej
* gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH
* ZASTOSOWAŃ. W celu uzyskania bliższych informacji sięgnij do
* Powszechnej Licencji Publicznej GNU.
*
* Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz
* Powszechnej Licencji Publicznej GNU (GNU General Public License);
* jeśli nie - napisz do Free Software Foundation, Inc., 59 Temple
* Place, Fifth Floor, Boston, MA 02110-1301 USA
************************************/
package pl.edu.ibe.loremipsum.tablet.base;
import android.app.Activity;
import android.support.v4.app.Fragment;
import pl.edu.ibe.loremipsum.tablet.LoremIpsumApp;
/**
* Created by adam on 28.03.14.
* Base class for all @link{Fragment} in app
*/
public class BaseServiceFragment extends Fragment {
private ServiceProvider serviceProvider;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
serviceProvider = LoremIpsumApp.obtain().getServiceProvider();
}
public ServiceProvider getServiceProvider() {
return serviceProvider;
}
}
| gpl-3.0 |
mewin/PerkShop | src/main/java/com/mewin/perkshop/PerkShopPlugin.java | 12675 | /*
* Copyright (C) 2012 mewin <mewin001@hotmail.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mewin.perkShop;
import com.mewin.perkShop.events.PlayerListener;
import com.mewin.perkShop.shop.Order;
import com.mewin.perkShop.shop.Perk;
import com.mewin.util.FileOutputHandler;
import com.mewin.util.ShopUtils;
import com.mewin.util.Utils;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
/**
*
* @author mewin<mewin001@hotmail.de>
*/
public class PerkShopPlugin extends JavaPlugin {
private Map<String, Object> config;
private FileOutputHandler logHandler;
private DatabaseConnector db;
private ExpireChecker checker;
private int scheduledTaskId;
private PlayerListener listener;
@Override
public void onEnable()
{
config = Utils.getConfig(this);
logHandler = new FileOutputHandler(Utils.getLogFile(this), (String) getConfig("log-time-format", "dd.MM.yyyy - hh:mm:ss"));
getLogger().addHandler(logHandler);
logHandler.publish(new LogRecord(Level.INFO, "[PerkShop] Enabling PerkShop v" + this.getDescription().getVersion()));
db = new DatabaseConnector();
db.init(getConfig("sql.dns", ""), getConfig("sql.username", ""), getConfig("sql.password", ""), getConfig("sql.prefix", ""), this);
db.connect();
checker = new ExpireChecker(this);
scheduledTaskId = getServer().getScheduler().scheduleAsyncRepeatingTask(this, checker, 1200L, getConfig("perk-check-time", 300));
listener = new PlayerListener(this, db);
//replaceCommand();
}
@Override
public void onDisable()
{
config = null;
getLogger().removeHandler(logHandler);
logHandler.close();
logHandler = null;
db.destroy();
db = null;
getServer().getScheduler().cancelTask(scheduledTaskId);
scheduledTaskId = -1;
checker = null;
listener = null;
}
@Override
public boolean onCommand(CommandSender cs, Command cmd, String cmdLabel, String[] params)
{
if (cmdLabel.equalsIgnoreCase("perk"))
{
String completeCmd = "/" + cmdLabel;
for (String param : params)
{
completeCmd += " " + param;
}
logToFile(Level.INFO, "[PerkShop] " + cs.getName() + " tried to use " + completeCmd);
if (params.length < 1)
{
cs.sendMessage(ChatColor.AQUA + cmd.getUsage());
}
else if("list".startsWith(params[0].toLowerCase()))
{
if (!(cs instanceof Player))
{
cs.sendMessage("You don't have any perks.");
}
else if (cs.hasPermission("perks.list"))
{
boolean showExpired = params.length > 1 && params[1].equalsIgnoreCase("all");
printPlayerPerks((Player) cs, showExpired);
}
else
{
cs.sendMessage(ChatColor.RED + cmd.getPermissionMessage());
}
}
else if ("info".startsWith(params[0].toLowerCase()))
{
if (!(cs instanceof Player))
{
cs.sendMessage("You don't have any perks.");
}
else if (params.length < 2)
{
cs.sendMessage(ChatColor.AQUA + cmd.getUsage());
}
else if (cs.hasPermission("perks.info"))
{
String restParams = "";
for (int i = 1; i < params.length; i++)
{
restParams += params[i] + " ";
}
printPlayerPerkInfo((Player) cs, restParams.trim());
}
else
{
cs.sendMessage(ChatColor.RED + cmd.getPermissionMessage());
}
}
else if ("reload".startsWith(params[0].toLowerCase()))
{
if (!(cs instanceof Player))
{
reloadAllOrders();
}
else if (cs.hasPermission("perks.reload"))
{
if (params.length > 1 && "all".startsWith(params[1].toLowerCase()))
{
if (cs.hasPermission("perks.reload.all"))
{
cs.sendMessage(ChatColor.GREEN + getConfig("messages.perk-reload-all", "Updating all perks"));
reloadAllOrders();
}
else
{
cs.sendMessage(cmd.getPermissionMessage());
}
}
else
{
cs.sendMessage(ChatColor.GREEN + getConfig("messages.perk-reload", "Updating perks"));
reloadOrdersForPlayer((Player) cs);
}
}
else
{
cs.sendMessage(cmd.getPermissionMessage());
}
}
else
{
cs.sendMessage(cmd.getUsage());
}
return true;
}
return false;
}
public void reloadAllOrders()
{
for (Player player : getServer().getOnlinePlayers())
{
reloadOrdersForPlayer(player);
}
}
public void reloadOrdersForPlayer(Player player)
{
Set<Order> playerOrders = db.getOrdersForMember(player.getName());
getLogger().log(Level.INFO, "Loading orders for player {0}", player.getName());
for (Order order : playerOrders)
{
if (!order.activated() && order.isPaid())
{
getLogger().log(Level.INFO, "Activating order {0} (from {2}) for player {1}",
new String[] {
Integer.toString(order.id),
player.getName(),
ShopUtils.sdf.format(order.purchased)
});
order.activate(player, this, db);
if (!order.updatePerksActivated(db))
{
getLogger().log(Level.WARNING, "Could not save perks for order {0}.", order.id);
}
}
}
ShopUtils.checkExpiredPerks(player, db, this);
}
public void logToFile(Level level, String msg)
{
LogRecord record = new LogRecord(level, msg);
logHandler.publish(record);
}
public void printPlayerPerks(Player player, boolean showExpired)
{
Set<Perk> perks = ShopUtils.getActivePerks(player.getName(), db, showExpired);
if (perks.size() < 1)
{
player.sendMessage(ChatColor.GRAY + getConfig("messages.no-perk-active", "There is currently no perk active on you."));
}
else
{
player.sendMessage(ChatColor.GRAY + getConfig("messages.current-perks", "Your current perks:"));
if (player.hasPermission("perks.info"))
{
player.sendMessage(ChatColor.WHITE + getConfig("messages.type-info", "Type /perk info [perk] to get more information."));
}
String perkList = "";
Iterator<Perk> itr = perks.iterator();
while (itr.hasNext())
{
Perk perk = itr.next();
if (!perk.canExpire() || !perk.expired)
{
perkList += ChatColor.AQUA;
}
else
{
perkList += ChatColor.GRAY;
}
perkList += perk.name;
if (itr.hasNext())
{
perkList += ChatColor.WHITE + ", ";
}
}
player.sendMessage(perkList);
}
}
public void printPlayerPerkInfo(Player player, String name)
{
Set<Perk> perks = ShopUtils.getActivePerks(player.getName(), db, true);
Perk thePerk = null;
for(Perk perk : perks)
{
if (perk.name.equalsIgnoreCase(name))
{
thePerk = perk;
if (!perk.expired)
{
break;
}
}
if (perk.name.toLowerCase().startsWith(name.toLowerCase()))
{
if (thePerk == null || thePerk.expired)
{
thePerk = perk;
}
}
}
if (thePerk == null)
{
player.sendMessage(ChatColor.RED + getConfig("messages.no-perk", "You don't have a perk \"{0}\"").replace("{0}", name));
}
else
{
player.sendMessage(getConfig("messages.perk-info", "§bname§f: §6{name}\n" +
"§bdescription§f: §6{description}\n" +
"§bexpires§f: §6{expires}").replace("{name}", thePerk.name)
.replace("{description}", thePerk.description)
.replace("{expires}", ShopUtils.getPerkExpireString(thePerk)));
}
}
public Object getConfig(String name, Object def)
{
return getConfig(name, def, config);
}
private Object getConfig(String name, Object def, Map<String, Object> map)
{
int dot = name.indexOf(".");
if (dot > 0)
{
Map subMap = (Map) map.get(name.substring(0, dot));
return getConfig(name.substring(dot + 1), def, subMap);
}
if (!map.containsKey(name))
{
return def;
}
else
{
return map.get(name);
}
}
public String getConfig(String name, String def)
{
return (String) getConfig(name, (Object) def);
}
public int getConfig(String name, int def)
{
return (Integer) getConfig(name, (Object) def);
}
public double getConfig(String name, double def)
{
return (Double) getConfig(name, (Object) def);
}
private Object getPrivateValue(Object obj, String name)
{
try
{
Field field = obj.getClass().getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
}
catch(NoSuchFieldException ex)
{
return null;
}
catch(SecurityException ex)
{
return null;
}
catch(IllegalArgumentException ex)
{
return null;
}
catch(IllegalAccessException ex)
{
return null;
}
}
private class ExpireChecker implements Runnable
{
private PerkShopPlugin plugin;
public ExpireChecker(PerkShopPlugin plugin)
{
this.plugin = plugin;
}
@Override
public void run() {
for (Player player : getServer().getOnlinePlayers())
{
ShopUtils.checkExpiredPerks(player, db, plugin);
}
}
}
}
| gpl-3.0 |
toxeh/ExecuteQuery | java/src/org/executequery/gui/browser/nodes/DatabaseCatalogNode.java | 3400 | /*
* DatabaseCatalogNode.java
*
* Copyright (C) 2002-2013 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.executequery.gui.browser.nodes;
import java.util.ArrayList;
import java.util.List;
import org.executequery.databaseobjects.DatabaseCatalog;
import org.executequery.databaseobjects.DatabaseMetaTag;
import org.executequery.databaseobjects.DatabaseSchema;
import org.underworldlabs.jdbc.DataSourceException;
/**
*
* @author Takis Diakoumis
* @version $Revision: 161 $
* @date $Date: 2013-04-25 16:00:50 +0400 (чт, 25 апр 2013) $
*/
public class DatabaseCatalogNode extends DatabaseObjectNode {
/** the direct descendants of this object */
private List<DatabaseObjectNode> children;
/** Creates a new instance of DatabaseCatalogNode */
public DatabaseCatalogNode(DatabaseCatalog catalog) {
super(catalog);
}
/**
* Returns the children associated with this node.
*
* @return a list of children for this node
*/
public List<DatabaseObjectNode> getChildObjects() throws DataSourceException {
if (children != null) {
return children;
}
// check for schemas - then meta tags
DatabaseCatalog catalog = (DatabaseCatalog)getDatabaseObject();
// check for schemas
List _children = catalog.getSchemas();
if (_children == null || _children.isEmpty()) {
// otherwise get meta tags
_children = catalog.getMetaObjects();
}
else {
int count = _children.size();
children = new ArrayList<DatabaseObjectNode>(count);
for (int i = 0; i < count; i++) {
DatabaseSchema schema = (DatabaseSchema)_children.get(i);
children.add(new DatabaseSchemaNode(schema));
}
return children;
}
// check we have meta tags
if (_children != null && !_children.isEmpty()) {
int count = _children.size();
children = new ArrayList<DatabaseObjectNode>(count);
for (int i = 0; i < count; i++) {
DatabaseMetaTag metaTag = (DatabaseMetaTag)_children.get(i);
children.add(new DatabaseObjectNode(metaTag));
}
return children;
}
return null;
}
/**
* Override to return true.
*/
public boolean allowsChildren() {
return true;
}
/**
* Indicates whether this node is a leaf node.
*
* @return true | false
*/
public boolean isLeaf() {
return false;
}
/**
* Clears out the children of this node.
*/
public void reset() {
super.reset();
children = null;
}
}
| gpl-3.0 |
RobotSquid/MoltenCraft | src/main/java/com/robotsquid/moltencraft/tool/sword/SwordWither.java | 665 | package com.robotsquid.moltencraft.tool.sword;
import com.robotsquid.moltencraft.init.ModMaterials;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
public class SwordWither extends SwordMC
{
public SwordWither()
{
super(ModMaterials.STICKIUM, "witherStick");
}
@Override
public boolean hitEntity(ItemStack currentItem, EntityLivingBase target, EntityLivingBase player)
{
target.addPotionEffect(new PotionEffect(Potion.wither.id, 9600, 0));
return super.hitEntity(currentItem, target, player);
}
}
| gpl-3.0 |
BenObiWan/game | src/game_core/src/game/communication/event/AbstractGameCtrlEvent.java | 1416 | package game.communication.event;
/**
* Implementation of the {@link AbstractGameCtrlEvent} interface describing all
* event that can happened during the creation and the course of games.
*
* @author benobiwan
*
*/
public abstract class AbstractGameCtrlEvent extends AbstractEvent implements
IGameCtrlEvent
{
/**
* serialVersionUID for Serialization.
*/
private static final long serialVersionUID = -3276431974266073866L;
/**
* Id of the game concerned with the action.
*/
protected final int _iGameId;
/**
* Id of the player concerned by the event. The id is given by the client.
*/
protected final int _iPlayerId;
/**
* Type of this game creation event.
*/
protected final GameCtrlEventType _type;
/**
* Creates a new AbstractGameCtrlEvent.
*
* @param iGameId
* id of the game concerned by the event.
* @param iPlayerId
* the id of the player concerned by the event.
* @param type
* type of this game control event.
*/
protected AbstractGameCtrlEvent(final int iGameId, final int iPlayerId,
final GameCtrlEventType type)
{
super();
_iGameId = iGameId;
_type = type;
_iPlayerId = iPlayerId;
}
@Override
public final int getGameId()
{
return _iGameId;
}
@Override
public final GameCtrlEventType getType()
{
return _type;
}
@Override
public final int getPlayerId()
{
return _iPlayerId;
}
}
| gpl-3.0 |
arraydev/snap-desktop | snap-rcp/src/main/java/org/esa/snap/rcp/statistics/DensityPlotTopComponent.java | 2255 | /*
* Copyright (C) 2012 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.statistics;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
@TopComponent.Description(
preferredID = "DensityPlotTopComponent",
iconBase = "org/esa/snap/rcp/icons/DensityPlot.gif",
persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define
)
@TopComponent.Registration(
mode = "ScatterPlot",
openAtStartup = false,
position = 40
)
@ActionID(category = "Window", id = "org.esa.snap.rcp.statistics.DensityPlotTopComponent")
@ActionReferences({
@ActionReference(path = "Menu/Analysis"),
@ActionReference(path = "Toolbars/Analysis")
})
@TopComponent.OpenActionRegistration(
displayName = "#CTL_DensityPlotTopComponent_Name",
preferredID = "DensityPlotTopComponent"
)
@NbBundle.Messages({
"CTL_DensityPlotTopComponent_Name=Scatter Plot",
"CTL_DensityPlotTopComponent_HelpId=densityPlotDialog"
})
/**
* The tool view containing a density plot
*
* @author Marco Zuehlke
*/
public class DensityPlotTopComponent extends AbstractStatisticsTopComponent {
@Override
protected PagePanel createPagePanel() {
return new DensityPlotPanel(this, Bundle.CTL_DensityPlotTopComponent_HelpId());
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(Bundle.CTL_DensityPlotTopComponent_HelpId());
}
}
| gpl-3.0 |
andreynovikov/maptrek | app/src/main/java/mobi/maptrek/util/FileList.java | 2748 | /*
* Copyright 2018 Andrey Novikov
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package mobi.maptrek.util;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public final class FileList {
/**
* Recursively walk a directory tree and return a List of all
* files found; the List is sorted using File.compareTo().
*
* @param startingDir root directory, must be valid directory which can be read.
* @param filter <code>FilenameFilter</code> to filter files.
* @return <code>List</code> containing found <code>File</code> objects or empty <code>List</code> otherwise.
*/
static public List<File> getFileListing(final File startingDir, final FilenameFilter filter) {
List<File> result = getFileListingNoSort(startingDir, filter);
Collections.sort(result);
return result;
}
static private List<File> getFileListingNoSort(final File startingDir, final FilenameFilter filter) {
List<File> result = new ArrayList<>();
// find files
File[] files = startingDir.listFiles(filter);
if (files != null)
result.addAll(Arrays.asList(files));
// go deeper
DirFileFilter dirFilter = new DirFileFilter();
File[] dirs = startingDir.listFiles(dirFilter);
if (dirs != null) {
for (File dir : dirs) {
List<File> deeperList = getFileListingNoSort(dir, filter);
result.addAll(deeperList);
}
}
// if nothing find may be it empty and can be deleted,
// current logic does not remove nested empty dirs
//noinspection ConstantConditions
if (startingDir.isDirectory() && (files == null || files.length == 0) && (dirs == null || dirs.length == 0)) {
String[] items = startingDir.list();
if (items == null || items.length == 0)
//noinspection ResultOfMethodCallIgnored
startingDir.delete();
}
return result;
}
}
| gpl-3.0 |
ramsodev/DitaManagement | dita/dita.task/src/net/ramso/dita/task/StepxmpClass.java | 19720 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.02 at 08:08:55 PM CEST
//
package net.ramso.dita.task;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for stepxmp.class complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="stepxmp.class">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{}stepxmp.content"/>
* </sequence>
* <attGroup ref="{}stepxmp.attributes"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "stepxmp.class", propOrder = {
"content"
})
@XmlSeeAlso({
Stepxmp.class
})
public class StepxmpClass {
@XmlElementRefs({
@XmlElementRef(name = "q", type = Q.class, required = false),
@XmlElementRef(name = "filepath", type = Filepath.class, required = false),
@XmlElementRef(name = "dl", type = Dl.class, required = false),
@XmlElementRef(name = "imagemap", type = Imagemap.class, required = false),
@XmlElementRef(name = "data-about", type = DataAbout.class, required = false),
@XmlElementRef(name = "xref", type = Xref.class, required = false),
@XmlElementRef(name = "apiname", type = Apiname.class, required = false),
@XmlElementRef(name = "fig", type = Fig.class, required = false),
@XmlElementRef(name = "note", type = Note.class, required = false),
@XmlElementRef(name = "userinput", type = Userinput.class, required = false),
@XmlElementRef(name = "foreign", type = Foreign.class, required = false),
@XmlElementRef(name = "msgph", type = Msgph.class, required = false),
@XmlElementRef(name = "lq", type = Lq.class, required = false),
@XmlElementRef(name = "keyword", type = Keyword.class, required = false),
@XmlElementRef(name = "p", type = P.class, required = false),
@XmlElementRef(name = "fn", type = Fn.class, required = false),
@XmlElementRef(name = "option", type = Option.class, required = false),
@XmlElementRef(name = "table", type = Table.class, required = false),
@XmlElementRef(name = "pre", type = Pre.class, required = false),
@XmlElementRef(name = "boolean", type = Boolean.class, required = false),
@XmlElementRef(name = "tt", type = Tt.class, required = false),
@XmlElementRef(name = "systemoutput", type = Systemoutput.class, required = false),
@XmlElementRef(name = "codeph", type = Codeph.class, required = false),
@XmlElementRef(name = "parmname", type = Parmname.class, required = false),
@XmlElementRef(name = "syntaxdiagram", type = Syntaxdiagram.class, required = false),
@XmlElementRef(name = "parml", type = Parml.class, required = false),
@XmlElementRef(name = "uicontrol", type = Uicontrol.class, required = false),
@XmlElementRef(name = "cmdname", type = Cmdname.class, required = false),
@XmlElementRef(name = "tm", type = Tm.class, required = false),
@XmlElementRef(name = "term", type = Term.class, required = false),
@XmlElementRef(name = "msgblock", type = Msgblock.class, required = false),
@XmlElementRef(name = "unknown", type = Unknown.class, required = false),
@XmlElementRef(name = "codeblock", type = Codeblock.class, required = false),
@XmlElementRef(name = "synph", type = Synph.class, required = false),
@XmlElementRef(name = "state", type = State.class, required = false),
@XmlElementRef(name = "image", type = Image.class, required = false),
@XmlElementRef(name = "data", type = Data.class, required = false),
@XmlElementRef(name = "ph", type = Ph.class, required = false),
@XmlElementRef(name = "i", type = I.class, required = false),
@XmlElementRef(name = "screen", type = Screen.class, required = false),
@XmlElementRef(name = "u", type = U.class, required = false),
@XmlElementRef(name = "varname", type = Varname.class, required = false),
@XmlElementRef(name = "sl", type = Sl.class, required = false),
@XmlElementRef(name = "wintitle", type = Wintitle.class, required = false),
@XmlElementRef(name = "menucascade", type = Menucascade.class, required = false),
@XmlElementRef(name = "object", type = net.ramso.dita.task.Object.class, required = false),
@XmlElementRef(name = "ul", type = Ul.class, required = false),
@XmlElementRef(name = "b", type = B.class, required = false),
@XmlElementRef(name = "required-cleanup", type = RequiredCleanup.class, required = false),
@XmlElementRef(name = "hazardstatement", type = Hazardstatement.class, required = false),
@XmlElementRef(name = "sub", type = Sub.class, required = false),
@XmlElementRef(name = "indextermref", type = Indextermref.class, required = false),
@XmlElementRef(name = "cite", type = Cite.class, required = false),
@XmlElementRef(name = "simpletable", type = Simpletable.class, required = false),
@XmlElementRef(name = "sup", type = Sup.class, required = false),
@XmlElementRef(name = "indexterm", type = Indexterm.class, required = false),
@XmlElementRef(name = "ol", type = Ol.class, required = false),
@XmlElementRef(name = "draft-comment", type = DraftComment.class, required = false),
@XmlElementRef(name = "msgnum", type = Msgnum.class, required = false),
@XmlElementRef(name = "lines", type = Lines.class, required = false),
@XmlElementRef(name = "abbreviated-form", type = AbbreviatedForm.class, required = false)
})
@XmlMixed
protected List<java.lang.Object> content;
@XmlAttribute(name = "outputclass")
protected String outputclass;
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String id;
@XmlAttribute(name = "conref")
protected String conref;
@XmlAttribute(name = "conrefend")
protected String conrefend;
@XmlAttribute(name = "conaction")
protected ConactionAttClass conaction;
@XmlAttribute(name = "conkeyref")
protected String conkeyref;
@XmlAttribute(name = "translate")
protected YesnoAttClass translate;
@XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
protected String lang;
@XmlAttribute(name = "dir")
protected DirAttsClass dir;
@XmlAttribute(name = "base")
protected String base;
@XmlAttribute(name = "rev")
protected String rev;
@XmlAttribute(name = "importance")
protected ImportanceAttsClass importance;
@XmlAttribute(name = "status")
protected StatusAttsClass status;
@XmlAttribute(name = "props")
protected String props;
@XmlAttribute(name = "platform")
protected String platform;
@XmlAttribute(name = "product")
protected String product;
@XmlAttribute(name = "audience")
protected String audienceMod;
@XmlAttribute(name = "otherprops")
protected String otherprops;
@XmlAttribute(name = "xtrc")
protected String xtrc;
@XmlAttribute(name = "xtrf")
protected String xtrf;
/**
* Gets the value of the content property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the content property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Q }
* {@link Filepath }
* {@link Dl }
* {@link Imagemap }
* {@link DataAbout }
* {@link Xref }
* {@link Apiname }
* {@link Fig }
* {@link Note }
* {@link Userinput }
* {@link Foreign }
* {@link Msgph }
* {@link Lq }
* {@link Keyword }
* {@link P }
* {@link Fn }
* {@link Option }
* {@link Table }
* {@link Pre }
* {@link Boolean }
* {@link Tt }
* {@link Systemoutput }
* {@link Codeph }
* {@link Parmname }
* {@link Syntaxdiagram }
* {@link Parml }
* {@link Uicontrol }
* {@link Cmdname }
* {@link Tm }
* {@link Term }
* {@link Msgblock }
* {@link String }
* {@link Unknown }
* {@link Codeblock }
* {@link Synph }
* {@link State }
* {@link Image }
* {@link Data }
* {@link Ph }
* {@link I }
* {@link Screen }
* {@link U }
* {@link Varname }
* {@link Sl }
* {@link Wintitle }
* {@link Menucascade }
* {@link net.ramso.dita.task.Object }
* {@link Ul }
* {@link B }
* {@link RequiredCleanup }
* {@link Hazardstatement }
* {@link Sub }
* {@link Indextermref }
* {@link Cite }
* {@link Sup }
* {@link Simpletable }
* {@link Indexterm }
* {@link Ol }
* {@link DraftComment }
* {@link Msgnum }
* {@link Lines }
* {@link AbbreviatedForm }
*
*
*/
public List<java.lang.Object> getContent() {
if (content == null) {
content = new ArrayList<java.lang.Object>();
}
return this.content;
}
/**
* Gets the value of the outputclass property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOutputclass() {
return outputclass;
}
/**
* Sets the value of the outputclass property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOutputclass(String value) {
this.outputclass = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the conref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConref() {
return conref;
}
/**
* Sets the value of the conref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConref(String value) {
this.conref = value;
}
/**
* Gets the value of the conrefend property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConrefend() {
return conrefend;
}
/**
* Sets the value of the conrefend property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConrefend(String value) {
this.conrefend = value;
}
/**
* Gets the value of the conaction property.
*
* @return
* possible object is
* {@link ConactionAttClass }
*
*/
public ConactionAttClass getConaction() {
return conaction;
}
/**
* Sets the value of the conaction property.
*
* @param value
* allowed object is
* {@link ConactionAttClass }
*
*/
public void setConaction(ConactionAttClass value) {
this.conaction = value;
}
/**
* Gets the value of the conkeyref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConkeyref() {
return conkeyref;
}
/**
* Sets the value of the conkeyref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConkeyref(String value) {
this.conkeyref = value;
}
/**
* Gets the value of the translate property.
*
* @return
* possible object is
* {@link YesnoAttClass }
*
*/
public YesnoAttClass getTranslate() {
return translate;
}
/**
* Sets the value of the translate property.
*
* @param value
* allowed object is
* {@link YesnoAttClass }
*
*/
public void setTranslate(YesnoAttClass value) {
this.translate = value;
}
/**
* Gets the value of the lang property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLang() {
return lang;
}
/**
* Sets the value of the lang property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLang(String value) {
this.lang = value;
}
/**
* Gets the value of the dir property.
*
* @return
* possible object is
* {@link DirAttsClass }
*
*/
public DirAttsClass getDir() {
return dir;
}
/**
* Sets the value of the dir property.
*
* @param value
* allowed object is
* {@link DirAttsClass }
*
*/
public void setDir(DirAttsClass value) {
this.dir = value;
}
/**
* Gets the value of the base property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBase() {
return base;
}
/**
* Sets the value of the base property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBase(String value) {
this.base = value;
}
/**
* Gets the value of the rev property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRev() {
return rev;
}
/**
* Sets the value of the rev property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRev(String value) {
this.rev = value;
}
/**
* Gets the value of the importance property.
*
* @return
* possible object is
* {@link ImportanceAttsClass }
*
*/
public ImportanceAttsClass getImportance() {
return importance;
}
/**
* Sets the value of the importance property.
*
* @param value
* allowed object is
* {@link ImportanceAttsClass }
*
*/
public void setImportance(ImportanceAttsClass value) {
this.importance = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link StatusAttsClass }
*
*/
public StatusAttsClass getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link StatusAttsClass }
*
*/
public void setStatus(StatusAttsClass value) {
this.status = value;
}
/**
* Gets the value of the props property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProps() {
return props;
}
/**
* Sets the value of the props property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProps(String value) {
this.props = value;
}
/**
* Gets the value of the platform property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPlatform() {
return platform;
}
/**
* Sets the value of the platform property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPlatform(String value) {
this.platform = value;
}
/**
* Gets the value of the product property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProduct() {
return product;
}
/**
* Sets the value of the product property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProduct(String value) {
this.product = value;
}
/**
* Gets the value of the audienceMod property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAudienceMod() {
return audienceMod;
}
/**
* Sets the value of the audienceMod property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAudienceMod(String value) {
this.audienceMod = value;
}
/**
* Gets the value of the otherprops property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOtherprops() {
return otherprops;
}
/**
* Sets the value of the otherprops property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOtherprops(String value) {
this.otherprops = value;
}
/**
* Gets the value of the xtrc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXtrc() {
return xtrc;
}
/**
* Sets the value of the xtrc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXtrc(String value) {
this.xtrc = value;
}
/**
* Gets the value of the xtrf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXtrf() {
return xtrf;
}
/**
* Sets the value of the xtrf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXtrf(String value) {
this.xtrf = value;
}
}
| gpl-3.0 |
ursfassler/rizzly | src/ast/data/type/template/TypeTemplate.java | 976 | /**
* This file is part of Rizzly.
*
* Rizzly 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.
*
* Rizzly 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 Rizzly. If not, see <http://www.gnu.org/licenses/>.
*/
package ast.data.type.template;
import ast.data.type.Type;
import ast.meta.MetaList;
abstract public class TypeTemplate extends Type {
public TypeTemplate(String name) {
super(name);
}
@Deprecated
public TypeTemplate(MetaList info, String name) {
super(info, name);
}
}
| gpl-3.0 |
filipemb/siesp | app/br/com/core/modelo/instituicao/Instituicao.java | 4758 | /*******************************************************************************
* This file is part of Educatio.
*
* Educatio 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.
*
* Educatio 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 Educatio. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Filipe Marinho de Brito - filipe.marinho.brito@gmail.com
* Rodrigo de Souza Ataides - rodrigoataides@gmail.com
*******************************************************************************/
package br.com.core.modelo.instituicao;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import br.com.core.modelo.publico.Estado;
import br.com.core.modelo.publico.Municipio;
import br.com.core.modelo.publico.enumerator.CorporacoesSSP;
@Entity
@Table(schema="instituicao")
public class Instituicao implements Serializable {
public Instituicao(){}
public Instituicao(Long id){
this.id = id;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Version
@Column(name = "version")
private Integer version;
@NotNull
@ManyToOne
private Estado estado;
@NotNull
@Enumerated(EnumType.STRING)
private CorporacoesSSP corporacaoSsp;
@NotNull
private String nome;
@NotNull
private String responsavel;
private String cargo;
@NotNull
@ManyToOne
private Municipio municipio;
@NotNull
private String endereco;
private String cep;
private String telefone1;
private String telefone2;
private String fax1;
private String fax2;
private String email1;
private String email2;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public Estado getEstado() {
return estado;
}
public void setEstado(Estado estado) {
this.estado = estado;
}
public CorporacoesSSP getCorporacaoSsp() {
return corporacaoSsp;
}
public void setCorporacaoSsp(CorporacoesSSP corporacaoSsp) {
this.corporacaoSsp = corporacaoSsp;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getResponsavel() {
return responsavel;
}
public void setResponsavel(String responsavel) {
this.responsavel = responsavel;
}
public Municipio getMunicipio() {
return municipio;
}
public void setMunicipio(Municipio municipio) {
this.municipio = municipio;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getTelefone1() {
return telefone1;
}
public void setTelefone1(String telefone1) {
this.telefone1 = telefone1;
}
public String getTelefone2() {
return telefone2;
}
public void setTelefone2(String telefone2) {
this.telefone2 = telefone2;
}
public String getFax1() {
return fax1;
}
public void setFax1(String fax1) {
this.fax1 = fax1;
}
public String getFax2() {
return fax2;
}
public void setFax2(String fax2) {
this.fax2 = fax2;
}
public String getEmail1() {
return email1;
}
public void setEmail1(String email1) {
this.email1 = email1;
}
public String getEmail2() {
return email2;
}
public void setEmail2(String email2) {
this.email2 = email2;
}
public String getCargo() {
return cargo;
}
public void setCargo(String cargo) {
this.cargo = cargo;
}
private static final long serialVersionUID = 1L;
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
| gpl-3.0 |
nurv/lirec | libs/cmion/cmionAddOns/src/cmion/addOns/manipulators/RemoteActionSimulator.java | 6753 | package cmion.addOns.manipulators;
import ion.Meta.EventHandler;
import ion.Meta.IEvent;
import ion.Meta.Simulation;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import cmion.architecture.CmionComponent;
import cmion.architecture.IArchitecture;
import cmion.level3.EventRemoteAction;
import cmion.level3.MindAction;
public class RemoteActionSimulator extends CmionComponent
{
/** the gui for the simulator */
SimulatorWindow window;
/** create a new simulator */
public RemoteActionSimulator(IArchitecture architecture)
{
super(architecture);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Remote Action Simulator");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
//Add contents to the window.
window = new SimulatorWindow();
frame.add(window);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public void newRA(final MindAction ma)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
window.addRA(ma);
}
});
}
@Override
public void registerHandlers()
{
// create a new handler
HandleRemoteActionEvent handler = new HandleRemoteActionEvent();
// listen to any remote action events (any source)
Simulation.instance.getEventHandlers().add(handler);
}
/** internal event handler class for listening to any event */
public class HandleRemoteActionEvent extends EventHandler {
public HandleRemoteActionEvent() {
super(EventRemoteAction.class);
}
@Override
public void invoke(IEvent evt)
{
if (evt instanceof EventRemoteAction)
{
EventRemoteAction evt1 = (EventRemoteAction) evt;
newRA(evt1.getRemoteAction());
}
}
}
/** frame to display events */
private class SimulatorWindow extends JPanel implements ActionListener, ListSelectionListener
{
private static final long serialVersionUID = 1L;
protected LinkedList<MindAction> remoteActions;
protected JList list;
protected JPanel toolBar;
protected JTextField txtSubject;
protected JTextField txtActionName;
protected JTextField txtParameters;
protected JButton btnPerform;
public SimulatorWindow() {
super(new BorderLayout());
remoteActions = new LinkedList<MindAction>();
list = new JList();
//Listen for when the selection changes.
list.addListSelectionListener(this);
toolBar = new JPanel();
JScrollPane scrollPane = new JScrollPane(list);
// create toolbar
JLabel lblSubject = new JLabel("subject: ");
Font f =lblSubject.getFont();
lblSubject.setFont(f.deriveFont(f.getStyle() ^ Font.BOLD));
toolBar.add(lblSubject);
txtSubject = new JTextField();
txtSubject.setPreferredSize(new Dimension(70,25));
toolBar.add(txtSubject);
JLabel lblAction = new JLabel(" action name: ");
f =lblAction.getFont();
lblAction.setFont(f.deriveFont(f.getStyle() ^ Font.BOLD));
toolBar.add(lblAction);
txtActionName = new JTextField();
txtActionName.setPreferredSize(new Dimension(70,25));
toolBar.add(txtActionName);
JLabel lblParameters = new JLabel(" parameters (space separated): ");
f =lblParameters.getFont();
lblParameters.setFont(f.deriveFont(f.getStyle() ^ Font.BOLD));
toolBar.add(lblParameters);
txtParameters = new JTextField();
txtParameters.setPreferredSize(new Dimension(70,25));
toolBar.add(txtParameters);
btnPerform = new JButton("perform");
btnPerform.addActionListener(this);
toolBar.add(btnPerform);
//Add components to this panel.
add(toolBar, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
}
public void addRA(MindAction ma)
{
remoteActions.addLast(ma);
if (remoteActions.size() > 100) remoteActions.removeFirst();
list.setListData(remoteActions.toArray());
}
@Override
public void actionPerformed(ActionEvent arg0)
{
if (arg0.getSource() == this.btnPerform)
{
String subjectName = this.txtSubject.getText().trim();
String actionName = this.txtActionName.getText().trim();
String parametersStr = this.txtParameters.getText().trim();
if (subjectName.equals(""))
{
JOptionPane.showMessageDialog(this, "Cannot perform action with no subject");
return;
}
if (actionName.equals(""))
{
JOptionPane.showMessageDialog(this, "Cannot perform action, no action name specified");
return;
}
StringTokenizer st = new StringTokenizer(parametersStr);
ArrayList<String> parameters = new ArrayList<String>();
while (st.hasMoreTokens()) parameters.add(st.nextToken());
MindAction ma = new MindAction(subjectName,actionName,parameters);
RemoteActionSimulator.this.raise(new EventRemoteAction(ma));
}
}
@Override
public void valueChanged(ListSelectionEvent arg0)
{
if (list.getSelectedValue()==null) return;
if (!(list.getSelectedValue() instanceof MindAction)) return;
MindAction ma = (MindAction) list.getSelectedValue();
txtSubject.setText(ma.getSubject());
txtActionName.setText(ma.getName());
String pStr = "";
for (String parameter : ma.getParameters())
pStr = pStr + parameter + " ";
txtParameters.setText(pStr.trim());
}
}
}
| gpl-3.0 |
Mapleroid/cm-server | server-5.11.0.src/com/cloudera/server/web/cmf/RoleInstanceConfigImpl.java | 5038 | package com.cloudera.server.web.cmf;
import com.cloudera.cmf.model.ConfigStalenessStatus;
import com.cloudera.cmf.model.DbRole;
import com.cloudera.cmf.model.DbService;
import com.cloudera.cmf.service.ValidationCollection;
import com.cloudera.server.web.cmf.include.ConfigForm;
import com.cloudera.server.web.cmf.include.ConfigFormBase.Fragment_alertBlock;
import com.cloudera.server.web.cmf.include.SwitchToServiceConfigDialog;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import java.util.Set;
import org.jamon.AbstractRenderer;
import org.jamon.AbstractTemplateImpl;
import org.jamon.Renderer;
import org.jamon.TemplateManager;
import org.jamon.emit.StandardEmitter;
import org.jamon.escaping.Escaping;
public class RoleInstanceConfigImpl extends RoleInstanceBaseImpl
implements RoleInstanceConfig.Intf
{
private final CmfPath.Type selectedPathType;
private final DbRole role;
private final Map<ConfigContext, ValidationCollection> contextToVC;
private final String message;
private final ConfigWidgetManager configWidgetManager;
private final String groupParent;
private final String searchQuery;
private final String groupKey;
private final boolean peerless;
private final Set<String> requiredAuthorities;
protected static RoleInstanceConfig.ImplData __jamon_setOptionalArguments(RoleInstanceConfig.ImplData p_implData)
{
if (!p_implData.getSelectedPathType__IsNotDefault())
{
p_implData.setSelectedPathType(CmfPath.Type.CONFIG);
}
if (!p_implData.getGroupParent__IsNotDefault())
{
p_implData.setGroupParent("");
}
if (!p_implData.getSearchQuery__IsNotDefault())
{
p_implData.setSearchQuery("");
}
if (!p_implData.getGroupKey__IsNotDefault())
{
p_implData.setGroupKey("");
}
if (!p_implData.getPeerless__IsNotDefault())
{
p_implData.setPeerless(false);
}
if (!p_implData.getRequiredAuthorities__IsNotDefault())
{
p_implData.setRequiredAuthorities(null);
}
RoleInstanceBaseImpl.__jamon_setOptionalArguments(p_implData);
return p_implData;
}
public RoleInstanceConfigImpl(TemplateManager p_templateManager, RoleInstanceConfig.ImplData p_implData) {
super(p_templateManager, __jamon_setOptionalArguments(p_implData));
this.selectedPathType = p_implData.getSelectedPathType();
this.role = p_implData.getRole();
this.contextToVC = p_implData.getContextToVC();
this.message = p_implData.getMessage();
this.configWidgetManager = p_implData.getConfigWidgetManager();
this.groupParent = p_implData.getGroupParent();
this.searchQuery = p_implData.getSearchQuery();
this.groupKey = p_implData.getGroupKey();
this.peerless = p_implData.getPeerless();
this.requiredAuthorities = p_implData.getRequiredAuthorities();
}
protected void child_render_4(Writer jamonWriter)
throws IOException
{
ConfigForm __jamon__var_999 = new ConfigForm(getTemplateManager());
__jamon__var_999.setGroupParent(this.groupParent);
__jamon__var_999.setSearchQuery(this.searchQuery);
__jamon__var_999.setGroupKey(this.groupKey);
__jamon__var_999.setService(this.role.getService());
__jamon__var_999.renderNoFlush(jamonWriter, this.message, CmfPath.to(CmfPath.Type.CONFIG, this.role), this.configWidgetManager, this.contextToVC, this.requiredAuthorities, new AbstractTemplateImpl(getTemplateManager())
{
public Renderer makeRenderer()
{
return new AbstractRenderer()
{
public void renderTo(Writer jamonWriter)
throws IOException
{
RoleInstanceConfigImpl.1__jamon__instanceOf__0__Fragment_alertBlock.this.renderNoFlush(jamonWriter);
}
};
}
public void renderNoFlush(Writer jamonWriter) throws IOException {
jamonWriter.write("\n");
if (RoleInstanceConfigImpl.this.message != null)
{
jamonWriter.write("\n <div class=\"alert alert-block alert-info\">\n ");
if (RoleInstanceConfigImpl.this.role.getService().getConfigStalenessStatus() != ConfigStalenessStatus.FRESH)
{
jamonWriter.write("\n <i class=\"tiny glyphicon warning_sign warn\"></i>\n ");
}
jamonWriter.write("\n ");
Escaping.HTML.write(StandardEmitter.valueOf(RoleInstanceConfigImpl.this.message), jamonWriter);
jamonWriter.write("\n </div>\n");
}
jamonWriter.write("\n");
}
});
jamonWriter.write("\n\n");
if (this.peerless)
{
jamonWriter.write("\n ");
SwitchToServiceConfigDialog __jamon__var_1000 = new SwitchToServiceConfigDialog(getTemplateManager());
__jamon__var_1000.renderNoFlush(jamonWriter, this.role, this.searchQuery);
jamonWriter.write("\n");
}
jamonWriter.write("\n");
}
} | gpl-3.0 |
pluraliseseverythings/grakn | grakn-engine/src/test/java/ai/grakn/engine/EngineTestHelper.java | 2621 | package ai.grakn.engine;
import ai.grakn.engine.util.SimpleURI;
import ai.grakn.test.GraknTestSetup;
import java.io.IOException;
import java.net.ServerSocket;
/**
* <p>
* This class instantiates an engine server-side component once, statically until the JVM exists.
* Any state cleanup needs to be done by tests themselves - more code, more work, but more performant
* test suite. So all unit tests will share the same components and will be written with that in mind.
* </p>
*
* @author borislav
*
*/
public class EngineTestHelper {
private static volatile GraknEngineConfig config = null;
public static int findAvailablePort() {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Create (once only, statically) the GraknEngineConfig as per configuration file and return it.
*/
public static synchronized GraknEngineConfig config() {
if (config != null) {
return config;
}
config = GraknEngineConfig.create();
config.setConfigProperty(GraknEngineConfig.SERVER_PORT_NUMBER, String.valueOf(findAvailablePort()));
return config;
}
private static volatile GraknEngineServer server = null;
/**
* <p>
* Creates and initializes all components for running a self-contained, embedded engine server.
* </p>
* <p>
* Make sure it's invoked before any test that needs to access engine components. It's an
* idempotent operation - it can be invoked many times without repercussions.
* </p>
*/
public static synchronized void engine() {
if (server != null) {
return;
}
GraknTestSetup.startRedisIfNeeded(new SimpleURI(config().getProperty(GraknEngineConfig.REDIS_HOST)).getPort());
server = GraknEngineServer.create(config());
server.start();
}
/**
* Similarly to {@link EngineTestHelper#engine()} it creates a test engine with the ability to write {@link ai.grakn.GraknTx} to a
* persistent backend if needed
*/
public static synchronized void engineWithKBs() {
GraknTestSetup.startCassandraIfNeeded();
engine();
}
/**
* Shutdown the engine server.
*/
public static synchronized void noEngine() {
if (server == null) {
return;
}
try {
server.close();
}
finally {
server = null;
}
}
}
| gpl-3.0 |
azeckoski/iclicker-sakai-integrate | src/main/java/org/sakaiproject/iclicker/logic/ExternalLogic.java | 12175 | /**
* Copyright (c) 2009 i>clicker (R) <http://www.iclicker.com/dnn/>
*
* This file is part of i>clicker Sakai integrate.
*
* i>clicker Sakai integrate 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.
*
* i>clicker Sakai integrate 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 i>clicker Sakai integrate. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sakaiproject.iclicker.logic;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This is the 2.6 version of the external logic service
*
* @author Aaron Zeckoski (azeckoski @ gmail.com)
*/
public class ExternalLogic extends AbstractExternalLogic {
private final static Log log = LogFactory.getLog(ExternalLogic.class);
/**
* Place any code that should run when this class is initialized by spring here
*/
public void init() {
super.init();
log.info("INIT");
}
/****************
public Gradebook getCourseGradebook(String siteId, String gbItemName) {
// The gradebookUID is the siteId, the gradebookID is a long
String gbID = siteId;
if (!gradebookService.isGradebookDefined(gbID)) {
throw new IllegalArgumentException("No gradebook found for site: " + siteId);
}
// verify permissions
String userId = getCurrentUserId();
if (userId == null
|| ! siteService.allowUpdateSite(userId)
|| ! siteService.allowViewRoster(userId) ) {
throw new SecurityException("User ("+userId+") cannot access gradebook in site ("+siteId+")");
}
Gradebook gb = new Gradebook(gbID);
gb.students = getStudentsForCourse(siteId);
Map<String, String> studentUserIds = new ConcurrentHashMap<String, String>();
for (Student student : gb.students) {
studentUserIds.put(student.userId, student.username);
}
ArrayList<String> studentIds = new ArrayList<String>(studentUserIds.keySet());
if (gbItemName == null) {
List<Assignment> gbitems = gradebookService.getAssignments(gbID);
for (Assignment assignment : gbitems) {
GradebookItem gbItem = makeGradebookItemFromAssignment(gbID, assignment, studentUserIds, studentIds);
gb.items.add(gbItem);
}
} else {
Assignment assignment = gradebookService.getAssignment(gbID, gbItemName);
if (assignment != null) {
GradebookItem gbItem = makeGradebookItemFromAssignment(gbID, assignment, studentUserIds, studentIds);
gb.items.add(gbItem);
} else {
throw new IllegalArgumentException("Invalid gradebook item name ("+gbItemName+"), no item with this name found in cource ("+siteId+")");
}
}
return gb;
}
private GradebookItem makeGradebookItemFromAssignment(String gbID, Assignment assignment,
Map<String, String> studentUserIds, ArrayList<String> studentIds) {
// build up the items listing
GradebookItem gbItem = new GradebookItem(gbID, assignment.getName(), assignment
.getPoints(), assignment.getDueDate(), assignment.getExternalAppName(),
assignment.isReleased());
gbItem.id = assignment.getId().toString();
// We have to iterate through each student and get the grades out.. 2.5 gradebook service has problems
for (String studentId : studentIds) {
// too expensive: if (gradebookService.getGradeViewFunctionForUserForStudentForItem(gbID, assignment.getId(), studentId) == null) {
Double grade = gradebookService.getAssignmentScore(gbID, assignment.getName(),
studentId);
if (grade != null) {
GradebookItemScore score = new GradebookItemScore(assignment.getId().toString(),
studentId, grade.toString() );
score.username = studentUserIds.get(studentId);
CommentDefinition cd = gradebookService.getAssignmentScoreComment(gbID, assignment
.getName(), studentId);
if (cd != null) {
score.comment = cd.getCommentText();
score.recorded = cd.getDateRecorded();
score.graderUserId = cd.getGraderUid();
}
gbItem.scores.add(score);
}
}
// This is the post 2.5 way
// List<GradeDefinition> grades = gradebookService.getGradesForStudentsForItem(siteId,
// assignment.getId(), studentIds);
// for (GradeDefinition gd : grades) {
// String studId = gd.getStudentUid();
// String studEID = studentUserIds.get(studId);
// GradebookItemScore score = new GradebookItemScore(assignment.getId().toString(),
// studId, gd.getGrade(), studEID, gd.getGraderUid(), gd.getDateRecorded(),
// gd.getGradeComment());
// gbItem.scores.add(score);
// }
return gbItem;
}
public GradebookItem saveGradebookItem(GradebookItem gbItem) {
if (gbItem == null) {
throw new IllegalArgumentException("gbItem cannot be null");
}
if (gbItem.gradebookId == null || "".equals(gbItem.gradebookId)) {
throw new IllegalArgumentException("gbItem must have the gradebookId set");
}
if (gbItem.name == null || "".equals(gbItem.name)) {
throw new IllegalArgumentException("gbItem must have the name set");
}
String gradebookUid = gbItem.gradebookId;
Assignment assignment = null;
// find by name
if (gradebookService.isAssignmentDefined(gradebookUid, gbItem.name)) {
assignment = gradebookService.getAssignment(gradebookUid, gbItem.name);
}
// in the pre-2.6 GB we can only lookup by name
if (assignment == null) {
// try to find by name
if (gradebookService.isAssignmentDefined(gradebookUid, gbItem.name)) {
assignment = gradebookService.getAssignment(gradebookUid, gbItem.name);
}
}
// now we have the item if it exists
if (assignment == null) {
// no item so create one
assignment = new Assignment();
assignment.setExternallyMaintained(false); // cannot modify it later if true
// assign values
assignment.setDueDate(gbItem.dueDate);
assignment.setExternalAppName(gbItem.type);
assignment.setExternalId(gbItem.type);
assignment.setName(gbItem.name);
assignment.setPoints(gbItem.pointsPossible);
assignment.setReleased(gbItem.released);
gradebookService.addAssignment(gradebookUid, assignment);
} else {
assignment.setExternallyMaintained(false); // cannot modify it later if true
// assign new values to existing assignment
if (gbItem.dueDate != null) {
assignment.setDueDate(gbItem.dueDate);
}
if (gbItem.type != null) {
assignment.setExternalAppName(gbItem.type);
assignment.setExternalId(gbItem.type);
}
if (gbItem.pointsPossible != null && gbItem.pointsPossible >= 0d) {
assignment.setPoints(gbItem.pointsPossible);
}
// assignment.setReleased(gbItem.released); // no mod released setting from here
gradebookService.updateAssignment(gradebookUid, assignment.getName(), assignment);
}
gbItem.id = assignment.getId().toString();
if (gbItem.scores != null && !gbItem.scores.isEmpty()) {
// now update scores if there are any to update, this will not remove scores and will
// only add new ones
Map<GradebookItemScore, String> scoreErrors = new HashMap<GradebookItemScore, String>();
for (GradebookItemScore score : gbItem.scores) {
if (isBlank(score.username) && isBlank(score.userId)) {
scoreErrors.put(score, "USER_MISSING_ERROR");
continue;
}
String studentId = score.userId;
if (studentId == null || "".equals(studentId)) {
// convert student EID to ID
try {
studentId = userDirectoryService.getUserId(score.username);
score.userId = studentId;
} catch (UserNotDefinedException e) {
scoreErrors.put(score, "UserDoesNotExistError");
continue;
}
} else {
// validate the student ID
try {
score.username = userDirectoryService.getUserEid(studentId);
} catch (UserNotDefinedException e) {
scoreErrors.put(score, "UserDoesNotExistError");
continue;
}
}
// null/blank scores are not allowed
if (isBlank(score.grade)) {
scoreErrors.put(score, "NO_SCORE_ERROR");
continue;
}
Double dScore;
try {
dScore = Double.valueOf(score.grade);
} catch (NumberFormatException e) {
scoreErrors.put(score, "SCORE_INVALID");
continue;
}
// null grade deletes the score
gradebookService.setAssignmentScore(gradebookUid, gbItem.name, studentId, dScore, "i>clicker");
if (score.comment != null && ! "".equals(score.comment)) {
gradebookService.setAssignmentScoreComment(gradebookUid, gbItem.name, studentId, score.comment);
}
score.assignId(gbItem.id, studentId);
// post-2.5 gradebook method
// try {
// gradebookService.saveGradeAndCommentForStudent(gradebookUid, gbItemId,
// studentId, score.grade, score.comment);
// } catch (InvalidGradeException e) {
// scoreErrors.put(score, "SCORE_INVALID");
// continue;
// }
// GradeDefinition gd = gradebookService.getGradeDefinitionForStudentForItem(
// gradebookUid, gbItemId, studentId);
// score.assignId(gbItem.id, gd.getStudentUid());
// score.comment = gd.getGradeComment();
// score.grade = gd.getGrade();
// score.graderUserId = gd.getGraderUid();
// score.recorded = gd.getDateRecorded();
}
// put the errors in the item
if (scoreErrors.size() > 0) {
gbItem.scoreErrors = new HashMap<String, String>();
for (Entry<GradebookItemScore, String> entry : scoreErrors.entrySet()) {
gbItem.scoreErrors.put(entry.getKey().toString(), entry.getValue());
}
}
}
return gbItem;
}
******************/
/** Not possible in the sakai 2.5 gradebook service -AZ
public boolean removeGradebookItem(String siteId, String itemName) {
boolean removed = false;
if (gradebookService.isAssignmentDefined(siteId, itemName)) {
Assignment a = gradebookService.getAssignment(siteId, itemName);
gradebookService.removeAssignment(a.getId());
}
return removed;
}
***/
}
| gpl-3.0 |
im-frizzy/MultiServer | cache/src/main/java/com/friz/cache/utility/tukaani/simple/ARMThumb.java | 1550 | /*
* BCJ filter for little endian ARM-Thumb instructions
*
* Authors: Lasse Collin <lasse.collin@tukaani.org>
* Igor Pavlov <http://7-zip.org/>
*
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package com.friz.cache.utility.tukaani.simple;
public final class ARMThumb implements SimpleFilter {
private final boolean isEncoder;
private int pos;
public ARMThumb(boolean isEncoder, int startPos) {
this.isEncoder = isEncoder;
pos = startPos + 4;
}
public int code(byte[] buf, int off, int len) {
int end = off + len - 4;
int i;
for (i = off; i <= end; i += 2) {
if ((buf[i + 1] & 0xF8) == 0xF0 && (buf[i + 3] & 0xF8) == 0xF8) {
int src = ((buf[i + 1] & 0x07) << 19)
| ((buf[i] & 0xFF) << 11)
| ((buf[i + 3] & 0x07) << 8)
| (buf[i + 2] & 0xFF);
src <<= 1;
int dest;
if (isEncoder)
dest = src + (pos + i - off);
else
dest = src - (pos + i - off);
dest >>>= 1;
buf[i + 1] = (byte)(0xF0 | ((dest >>> 19) & 0x07));
buf[i] = (byte)(dest >>> 11);
buf[i + 3] = (byte)(0xF8 | ((dest >>> 8) & 0x07));
buf[i + 2] = (byte)dest;
i += 2;
}
}
i -= off;
pos += i;
return i;
}
}
| gpl-3.0 |
shadowmage45/AncientWarfare2 | src/main/java/net/shadowmage/ancientwarfare/structure/template/plugin/defaultplugins/package-info.java | 280 | // Auto generated package-info by MCP
@ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault
package net.shadowmage.ancientwarfare.structure.template.plugin.defaultplugins;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
| gpl-3.0 |
balderdasher/competency-matrix | competency-java/src/main/java/com/mrdios/competencymatrix/java/readingnotes/JavaConcurrencyInPractice/chapter11/RestState.java | 755 | package com.mrdios.competencymatrix.java.readingnotes.JavaConcurrencyInPractice.chapter11;
import javax.annotation.Generated;
import java.util.Set;
/**
* 锁分解
* @author huxiong
* @date 2016/06/22 12:59
*/
public class RestState {
@Generated("this")
public final Set<String> users;//食客
@Generated("this")
public final Set<String> reserves;//预定
public RestState(Set<String> users, Set<String> reserves) {
this.users = users;
this.reserves = reserves;
}
public void addUser(String user){
synchronized (users){
users.add(user);
}
}
public void addReserves(String reserv){
synchronized (reserves){
reserves.add(reserv);
}
}
}
| gpl-3.0 |
jasoyode/gasneat | src/main/java/gasNEAT/geneticOperators/GasNeatPruneMutationOperator.java | 5626 | /*
* Copyright (C) 2004 Derek James and Philip Tucker
*
* This file is part of ANJI (Another NEAT Java Implementation).
*
* ANJI 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
*
* Created on Apr 6, 2004 by Philip Tucker
*/
package gasNEAT.geneticOperators;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.jgap.Allele;
import org.jgap.ChromosomeMaterial;
import org.jgap.Configuration;
import org.jgap.MutationOperator;
import com.anji.neat.NeuronType;
import com.anji.neat.PruneMutationOperator;
import com.anji.util.Properties;
import gasNEAT.geneticEncoding.GasNeatNeuronAllele;
import gasNEAT.util.GasNeatChromosomeUtility;
/**
* Removes neurons and connections that do not affect the activation of the network. This
* includes hidden neurons without inputs or outputs, connections missing source or destination
* neurons, or sub-structures of neurons and connections that are stranded. Allows additive and
* subtractive mutation operators to be less careful about what they do and require less
* coordination among them, since this operator can follow them and "clean up the mess". For
* this reason, this operator generally should be the last executed in the sequence of mutation
* operators. This operator was necessary with the addition of simplification dynamics for James
* and Tucker's "A Comparative Analysis of Simplification and Complexification in the Evolution
* of Neural Network Topologies" paper for <a
* href="http://gal4.ge.uiuc.edu:8080/GECCO-2004/">GECCO 2004 </a>.
*
* TODO - mutation rate less than 1.0 might yield unexpected results - maybe should handle nodes
* and connections differently in that case
*
* @author Philip Tucker
*/
public class GasNeatPruneMutationOperator extends PruneMutationOperator {
/**
* properties key, prune network mutation rate
*/
private static final String PRUNE_MUTATE_RATE_KEY = "gasneat.prune.mutation.rate";
/**
* default mutation rate
*/
public final static float DEFAULT_MUTATE_RATE = 1.00f;
/**
* @see com.anji.util.Configurable#init(com.anji.util.Properties)
*/
public void init( Properties props ) throws Exception {
setMutationRate( props.getFloatProperty( PRUNE_MUTATE_RATE_KEY, DEFAULT_MUTATE_RATE ) );
}
/**
* @see PruneMutationOperator#PruneMutationOperator(float)
*/
public GasNeatPruneMutationOperator() {
this( DEFAULT_MUTATE_RATE );
}
/**
* @see MutationOperator#MutationOperator(float)
*/
public GasNeatPruneMutationOperator( float newMutationRate ) {
super( newMutationRate );
if ( ! (newMutationRate == 0 || newMutationRate == 1.0) ){
System.err.println("Do not allow prune mutation rate to be anything other than 1 or 0!");
System.exit(1);
}
}
/**
* Traverse network flowing forward and backward to identify unvisited connections and neurons.
* Then, remove a number of those depending on mutation rate.
*
* @param config
* @param target chromosome material to mutate
* @param genesToAdd <code>Set</code> contains <code>Gene</code> objects
* @param genesToRemove <code>Set</code> contains <code>Gene</code> objects
* @see org.jgap.MutationOperator#mutate(org.jgap.Configuration, org.jgap.ChromosomeMaterial,
* java.util.Set, java.util.Set)
*/
protected void mutate( Configuration config, ChromosomeMaterial target, Set genesToAdd,
Set genesToRemove, int currentGeneration, int maxGenerations ) {
List candidatesToRemove = new ArrayList();
//MEGATODOBUG? #4 - decide how to change pruning or mutations
//comment this out to stop pruning
findUnvisitedAlleles( target, candidatesToRemove);
Collections.shuffle( candidatesToRemove, config.getRandomGenerator() );
for ( int i = 0; i < numMutations( config.getRandomGenerator(), candidatesToRemove.size() ); ++i ) {
genesToRemove.add( candidatesToRemove.get( i ) );
}
}
/**
* @param material target from which to remove stranded nodes and connections
* @param unvisitedAlleles <code>List</code> contains <code>Gene</code> objects, unvisited
* nodes and connections
* @param isForward traverse the network from input to output if true, output to input if false
*/
private void findUnvisitedAlleles( ChromosomeMaterial material, List unvisitedAlleles ) {
Collection<Allele> toBeRemoved= GasNeatChromosomeUtility.getAllUnactivatableAllelesFromSrcNeurons( material.getAlleles() );
for (Allele a: toBeRemoved) {
if (a instanceof GasNeatNeuronAllele ) {
if ( ((GasNeatNeuronAllele)a).getType().equals(NeuronType.INPUT) ) {
System.err.println("INPUT neurons should never be removed!");
System.exit(1);
} else if ( ((GasNeatNeuronAllele)a).getType().equals(NeuronType.OUTPUT) ) {
System.err.println("OUTPUT neurons should never be removed, even if they are not reachable!");
System.exit(1);
}
}
}
unvisitedAlleles.addAll( toBeRemoved );
}
}
| gpl-3.0 |
saketmehta/myfpl | backend/src/main/java/club/myfpl/model/ElementType.java | 2059 | package club.myfpl.model;
/**
* User: Saket
* Date: 25/11/16
* Time: 12:10 AM
*/
public enum ElementType {
GKP(1L, "Goalkeeper", "GKP", "Goalkeepers", "GKP"),
DEF(2L, "Defender", "DEF", "Defenders", "DEF"),
MID(3L, "Midfielder", "MID", "Midfielders", "MID"),
FWD(4L, "Forward", "FWD", "Forwards", "FWD");
private Long id;
private String singularName;
private String singularShortName;
private String pluralName;
private String pluralShortName;
ElementType(Long id, String singularName, String singularShortName, String pluralName, String pluralShortName) {
this.id = id;
this.singularName = singularName;
this.singularShortName = singularShortName;
this.pluralName = pluralName;
this.pluralShortName = pluralShortName;
}
public static ElementType getElementTypeFromId(Long id) {
if (id.equals(1L)) {
return ElementType.GKP;
} else if (id.equals(2L)) {
return ElementType.DEF;
} else if (id.equals(3L)) {
return ElementType.MID;
} else if (id.equals(4L)) {
return ElementType.FWD;
}
return null;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSingularName() {
return singularName;
}
public void setSingularName(String singularName) {
this.singularName = singularName;
}
public String getSingularShortName() {
return singularShortName;
}
public void setSingularShortName(String singularShortName) {
this.singularShortName = singularShortName;
}
public String getPluralName() {
return pluralName;
}
public void setPluralName(String pluralName) {
this.pluralName = pluralName;
}
public String getPluralShortName() {
return pluralShortName;
}
public void setPluralShortName(String pluralShortName) {
this.pluralShortName = pluralShortName;
}
}
| gpl-3.0 |
x-falcon/Virtual-Hosts | app/src/main/java/org/xbill/DNS/NSIDOption.java | 510 | // Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
/**
* The Name Server Identifier Option, define in RFC 5001.
*
* @see OPTRecord
*
* @author Brian Wellington
*/
public class NSIDOption extends GenericEDNSOption {
private static final long serialVersionUID = 74739759292589056L;
NSIDOption() {
super(Code.NSID);
}
/**
* Construct an NSID option.
* @param data The contents of the option.
*/
public
NSIDOption(byte [] data) {
super(Code.NSID, data);
}
}
| gpl-3.0 |
bopbruno/webstore | webstore/src/main/java/com/packt/webstore/controller/LoginController.java | 732 | package com.packt.webstore.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value="/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value="/loginfailed", method = RequestMethod.GET)
public String loginerror(Model model) {
model.addAttribute("error", "true");
return "login";
}
@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logout(Model model) {
return "login";
}
} | gpl-3.0 |
ricecakesoftware/CommunityMedicalLink | ricecakesoftware.communitymedicallink.hl7/src/org/hl7/v3/EpiduralRoute.java | 928 |
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>EpiduralRouteのJavaクラス。
*
* <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。
* <p>
* <pre>
* <simpleType name="EpiduralRoute">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="EPI"/>
* <enumeration value="EPIDURINJ"/>
* <enumeration value="EPIINJ"/>
* <enumeration value="EPINJSP"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "EpiduralRoute")
@XmlEnum
public enum EpiduralRoute {
EPI,
EPIDURINJ,
EPIINJ,
EPINJSP;
public String value() {
return name();
}
public static EpiduralRoute fromValue(String v) {
return valueOf(v);
}
}
| gpl-3.0 |
mrsalustiano/Java | CursoJava/src/com/mrsalustiano/handson/aula15/Exercicio19.java | 2140 | package com.mrsalustiano.handson.aula15;
import java.util.Scanner;
public class Exercicio19 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
System.out.println("Digite o primeiro numero");
int numero1 = scan.nextInt();
System.out.println("Digite o segundo numero");
int numero2 = scan.nextInt();
System.out.println("Digite a operacao\n(1) - Soma\n(2) - Subtração\n(3) - Divisao\n(4) - Multiplicao");
int operacao = scan.nextInt();
int resultado =0;
switch (operacao) {
case 1:
resultado = numero1 + numero2;
System.out.println("Valor da Soma " + resultado);
if (resultado % 2 == 0){
System.out.println("Numero Par");
} else{
System.out.println("Numero Impar");
}
if (resultado <= 0){
System.out.println("Negativo");
} else{
System.out.println("Positivo");
}
break;
case 2:
resultado = numero1 - numero2;
System.out.println("Valor da subtracao " + resultado);
if (resultado % 2 == 0){
System.out.println("Numero Par");
} else{
System.out.println("Numero Impar");
}
if (resultado <= 0){
System.out.println("Negativo");
} else{
System.out.println("Positivo");
}
break;
case 3:
if (numero1 == 0 || numero2 == 0){
System.out.println("Divisao por zero nao permitida");
break;
} else{
resultado = numero1 / numero2;
System.out.println("Valor da Divisao "+ resultado);
if (resultado % 2 == 0){
System.out.println("Numero Par");
} else{
System.out.println("Numero Impar");
}
if (resultado <= 0){
System.out.println("Negativo");
} else{
System.out.println("Positivo");
}
break;
}
case 4:
resultado = numero1 * numero2;
System.out.println("Valor da Multiplicacao " + resultado);
if (resultado % 2 == 0){
System.out.println("Numero Par");
} else{
System.out.println("Numero Impar");
}
if (resultado <= 0){
System.out.println("Negativo");
} else{
System.out.println("Positivo");
}
break;
default:
break;
}
}
}
| gpl-3.0 |
apruden/mica2 | mica-core/src/main/java/org/obiba/mica/core/upgrade/MicaVersionModifier.java | 1141 | /*
* Copyright (c) 2016 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* 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.obiba.mica.core.upgrade;
import java.util.Optional;
import javax.inject.Inject;
import org.obiba.mica.micaConfig.domain.MicaConfig;
import org.obiba.mica.micaConfig.service.MicaConfigService;
import org.obiba.runtime.Version;
import org.obiba.runtime.upgrade.VersionModifier;
import org.springframework.stereotype.Component;
@Component
public class MicaVersionModifier implements VersionModifier {
@Inject
private MicaConfigService micaConfigService;
@Override
public Version getVersion() {
return Optional.ofNullable(micaConfigService.getConfig().getMicaVersion()).orElse(new Version(0, 8));
}
@Override
public void setVersion(Version version) {
MicaConfig config = micaConfigService.getConfig();
config.setMicaVersion(version);
micaConfigService.save(config);
}
}
| gpl-3.0 |
ExplatCreations/sft | SniffysFlipTrip/src/com/explatcreations/sft/saving/Logger.java | 2342 | /*****************************************************************************
* Copyright 2013, see AUTHORS file.
*
* This file is part of Sniffy's Flip Trip.
*
* Sniffy's Flip Trip 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.
*
* Sniffy's Flip Trip 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 Sniffy's Flip Trip.
* If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/
package com.explatcreations.sft.saving;
import com.explatcreations.sft.hardware.HardwareInfo;
import java.io.File;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author deweyvm
*/
public class Logger {
public static void attachCrashLogger() {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread _, Throwable e) {
try {
final String dateString = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
final String filename = String.format("crash_log_%s.log", dateString);
System.err.printf("The application has crashed. Please consult %s for additional information.\n", filename);
final File file = new File(filename);
file.createNewFile();
final PrintStream stream = new PrintStream(file);
e.printStackTrace(stream);
stream.append(new HardwareInfo().toString());
stream.close();
} catch (Throwable throwable) {
System.err.println("Failed to create log file. Printing exception:");
e.printStackTrace();
throwable.printStackTrace();
}
}
});
}
}
| gpl-3.0 |
sicodetv20/dev.sicodetv2.1 | src/main/java/ve/com/fsjv/devsicodetv/models/Visit.java | 288 | /*
* 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 ve.com.fsjv.devsicodetv.models;
/**
*
* @author FAMILIA-SJ
*/
public class Visit {
}
| gpl-3.0 |
Gnat008/PerWorldInventory | src/test/java/me/gnat008/perworldinventory/ClassCollector.java | 6335 | package me.gnat008.perworldinventory;
import java.io.File;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Collects available classes by walking through a source directory.
* <p>
* This is a naive, zero dependency collector that walks through a file directory
* and loads classes from the class loader based on the .java files it encounters.
* This is a very slow approach and should be avoided for production code.
* <p>
* For more performant approaches, see e.g. <a href="https://github.com/ronmamo/reflections">org.reflections</a>.
*
* @author ljacqu
*/
public class ClassCollector {
private final String root;
private final String nonCodePath;
/**
* Constructor. The arguments make up the path from which the collector will start scanning.
*
* @param nonCodePath beginning of the starting path that are not Java packages, e.g. {@code src/main/java/}
* @param packagePath folders following {@code nonCodePath} that are packages, e.g. {@code com/project/app}
*/
public ClassCollector(String nonCodePath, String packagePath) {
if (!nonCodePath.endsWith("/") && !nonCodePath.endsWith("\\")) {
nonCodePath = nonCodePath.concat(File.separator);
}
this.root = nonCodePath + packagePath;
this.nonCodePath = nonCodePath;
}
/**
* Collects all classes from the parent folder and below.
*
* @return all classes
*/
public List<Class<?>> collectClasses() {
return collectClasses(x -> true);
}
/**
* Collects all classes from the parent folder and below which are of type {@link T}.
*
* @param parent the parent which classes need to extend (or be equal to) in order to be collected
* @param <T> the parent type
* @return list of matching classes
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> List<Class<? extends T>> collectClasses(Class<T> parent) {
List<Class<?>> classes = collectClasses(parent::isAssignableFrom);
return new ArrayList<>((List) classes);
}
/**
* Collects all classes from the parent folder and below which match the given predicate.
*
* @param filter the predicate classes need to satisfy in order to be collected
* @return list of matching classes
*/
public List<Class<?>> collectClasses(Predicate<Class<?>> filter) {
File rootFolder = new File(root);
List<Class<?>> collection = new ArrayList<>();
collectClasses(rootFolder, filter, collection);
return collection;
}
/**
* Constructs an instance of all classes which are of the provided type {@code clazz}.
* This method assumes that every class has an accessible no-args constructor for creation.
*
* @param parent the parent which classes need to extend (or be equal to) in order to be instantiated
* @param <T> the parent type
* @return collection of created objects
*/
public <T> List<T> getInstancesOfType(Class<T> parent) {
return getInstancesOfType(parent, (clz) -> {
try {
return canInstantiate(clz) ? clz.newInstance() : null;
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
});
}
/**
* Constructs an instance of all classes which are of the provided type {@code clazz}
* with the provided {@code instantiator}.
*
* @param parent the parent which classes need to extend (or be equal to) in order to be instantiated
* @param instantiator function which returns an object of the given class, or null to skip the class
* @param <T> the parent type
* @return collection of created objects
*/
public <T> List<T> getInstancesOfType(Class<T> parent, Function<Class<? extends T>, T> instantiator) {
return collectClasses(parent)
.stream()
.map(instantiator)
.filter(o -> o != null)
.collect(Collectors.toList());
}
/**
* Returns whether the given class can be instantiated, i.e. if it is not abstract, an interface, etc.
*
* @param clazz the class to process
* @return true if the class can be instantiated, false otherwise
*/
public static boolean canInstantiate(Class<?> clazz) {
return clazz != null && !clazz.isEnum() && !clazz.isInterface()
&& !clazz.isArray() && !Modifier.isAbstract(clazz.getModifiers());
}
/**
* Recursively collects the classes based on the files in the directory and in its child directories.
*
* @param folder the folder to scan
* @param filter the class predicate
* @param collection collection to add classes to
*/
private void collectClasses(File folder, Predicate<Class<?>> filter, List<Class<?>> collection) {
File[] files = folder.listFiles();
if (files == null) {
throw new IllegalStateException("Could not read files from '" + folder + "'");
}
for (File file : files) {
if (file.isDirectory()) {
collectClasses(file, filter, collection);
} else if (file.isFile()) {
Class<?> clazz = loadTaskClassFromFile(file);
if (clazz != null && filter.test(clazz)) {
collection.add(clazz);
}
}
}
}
/**
* Loads a class from the class loader based on the given file.
*
* @param file the file whose corresponding Java class should be retrieved
* @return the corresponding class, or null if not applicable
*/
private Class<?> loadTaskClassFromFile(File file) {
if (!file.getName().endsWith(".java")) {
return null;
}
String filePath = file.getPath();
String className = filePath
.substring(nonCodePath.length(), filePath.length() - 5)
.replace(File.separator, ".");
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
}
| gpl-3.0 |
gcochard/farebot | src/main/java/com/codebutler/farebot/transit/clipper/ClipperTransitData.java | 10620 | /*
* ClipperTransitData.java
*
* Copyright (C) 2011 Eric Butler
*
* Authors:
* Eric Butler <eric@codebutler.com>
*
* Thanks to:
* An anonymous contributor for reverse engineering Clipper data and providing
* most of the code here.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.farebot.transit.clipper;
import android.os.Parcel;
import com.codebutler.farebot.FareBotApplication;
import com.codebutler.farebot.R;
import com.codebutler.farebot.card.Card;
import com.codebutler.farebot.card.desfire.DesfireCard;
import com.codebutler.farebot.card.desfire.DesfireFile;
import com.codebutler.farebot.transit.Subscription;
import com.codebutler.farebot.transit.TransitData;
import com.codebutler.farebot.transit.TransitIdentity;
import com.codebutler.farebot.transit.Trip;
import com.codebutler.farebot.ui.ListItem;
import com.codebutler.farebot.util.Utils;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
public class ClipperTransitData extends TransitData {
static final int RECORD_LENGTH = 32;
private long mSerialNumber;
private short mBalance;
private ClipperTrip[] mTrips;
private ClipperRefill[] mRefills;
private static final long EPOCH_OFFSET = 0x83aa7f18;
public static boolean check(Card card) {
return (card instanceof DesfireCard) && (((DesfireCard) card).getApplication(0x9011f2) != null);
}
public static final Creator<ClipperTransitData> CREATOR = new Creator<ClipperTransitData>() {
public ClipperTransitData createFromParcel(Parcel parcel) {
return new ClipperTransitData(parcel);
}
public ClipperTransitData[] newArray(int size) {
return new ClipperTransitData[size];
}
};
public static TransitIdentity parseTransitIdentity(Card card) {
try {
byte[] data = ((DesfireCard) card).getApplication(0x9011f2).getFile(0x08).getData();
return new TransitIdentity("Clipper", String.valueOf(Utils.byteArrayToLong(data, 1, 4)));
} catch (Exception ex) {
throw new RuntimeException("Error parsing Clipper serial", ex);
}
}
public ClipperTransitData(Parcel parcel) {
mSerialNumber = parcel.readLong();
mBalance = (short) parcel.readLong();
mTrips = new ClipperTrip[parcel.readInt()];
parcel.readTypedArray(mTrips, ClipperTrip.CREATOR);
mRefills = new ClipperRefill[parcel.readInt()];
parcel.readTypedArray(mRefills, ClipperRefill.CREATOR);
}
public ClipperTransitData(Card card) {
DesfireCard desfireCard = (DesfireCard) card;
byte[] data;
try {
data = desfireCard.getApplication(0x9011f2).getFile(0x08).getData();
mSerialNumber = Utils.byteArrayToLong(data, 1, 4);
} catch (Exception ex) {
throw new RuntimeException("Error parsing Clipper serial", ex);
}
try {
data = desfireCard.getApplication(0x9011f2).getFile(0x02).getData();
mBalance = (short) (((0xFF & data[18]) << 8) | (0xFF & data[19]));
} catch (Exception ex) {
throw new RuntimeException("Error parsing Clipper balance", ex);
}
try {
mTrips = parseTrips(desfireCard);
} catch (Exception ex) {
throw new RuntimeException("Error parsing Clipper trips", ex);
}
try {
mRefills = parseRefills(desfireCard);
} catch (Exception ex) {
throw new RuntimeException("Error parsing Clipper refills", ex);
}
setBalances();
}
@Override public String getCardName() {
return "Clipper";
}
@Override public String getBalanceString() {
return NumberFormat.getCurrencyInstance(Locale.US).format(mBalance / 100.0);
}
@Override public String getSerialNumber() {
return Long.toString(mSerialNumber);
}
@Override public Trip[] getTrips() {
return mTrips;
}
public ClipperRefill[] getRefills() {
return mRefills;
}
@Override public Subscription[] getSubscriptions() {
return null;
}
@Override public List<ListItem> getInfo() {
return null;
}
private ClipperTrip[] parseTrips(DesfireCard card) {
DesfireFile file = card.getApplication(0x9011f2).getFile(0x0e);
/*
* This file reads very much like a record file but it professes to
* be only a regular file. As such, we'll need to extract the records
* manually.
*/
byte [] data = file.getData();
int pos = data.length - RECORD_LENGTH;
List<ClipperTrip> result = new ArrayList<>();
while (pos > 0) {
byte[] slice = Utils.byteArraySlice(data, pos, RECORD_LENGTH);
final ClipperTrip trip = createTrip(slice);
if (trip != null) {
// Some transaction types are temporary -- remove previous trip with the same timestamp.
ClipperTrip existingTrip = Utils.findInList(result, new Utils.Matcher<ClipperTrip>() {
@Override public boolean matches(ClipperTrip otherTrip) {
return trip.getTimestamp() == otherTrip.getTimestamp();
}
});
if (existingTrip != null) {
if (existingTrip.getExitTimestamp() != 0) {
// Old trip has exit timestamp, and is therefore better.
pos -= RECORD_LENGTH;
continue;
} else {
result.remove(existingTrip);
}
}
result.add(trip);
}
pos -= RECORD_LENGTH;
}
ClipperTrip[] useLog = new ClipperTrip[result.size()];
result.toArray(useLog);
Arrays.sort(useLog, new Trip.Comparator());
return useLog;
}
private ClipperTrip createTrip(byte[] useData) {
long timestamp, exitTimestamp, fare, agency, from, to, route;
timestamp = Utils.byteArrayToLong(useData, 0xc, 4);
exitTimestamp = Utils.byteArrayToLong(useData, 0x10, 4);
fare = Utils.byteArrayToLong(useData, 0x6, 2);
agency = Utils.byteArrayToLong(useData, 0x2, 2);
from = Utils.byteArrayToLong(useData, 0x14, 2);
to = Utils.byteArrayToLong(useData, 0x16, 2);
route = Utils.byteArrayToLong(useData, 0x1c, 2);
if (agency == 0)
return null;
// Use a magic number to offset the timestamp
timestamp -= EPOCH_OFFSET;
return new ClipperTrip(timestamp, exitTimestamp, fare, agency, from, to, route);
}
private ClipperRefill[] parseRefills(DesfireCard card) {
DesfireFile file = card.getApplication(0x9011f2).getFile(0x04);
/*
* This file reads very much like a record file but it professes to
* be only a regular file. As such, we'll need to extract the records
* manually.
*/
byte[] data = file.getData();
int pos = data.length - RECORD_LENGTH;
List<ClipperRefill> result = new ArrayList<>();
while (pos > 0) {
byte[] slice = Utils.byteArraySlice(data, pos, RECORD_LENGTH);
ClipperRefill refill = createRefill(slice);
if (refill != null)
result.add(refill);
pos -= RECORD_LENGTH;
}
ClipperRefill[] useLog = new ClipperRefill[result.size()];
useLog = result.toArray(useLog);
Arrays.sort(useLog, new Comparator<ClipperRefill>() {
public int compare(ClipperRefill r, ClipperRefill r1) {
return Long.valueOf(r1.getTimestamp()).compareTo(r.getTimestamp());
}
});
return useLog;
}
private ClipperRefill createRefill(byte[] useData) {
long timestamp, amount, agency, machineid;
timestamp = Utils.byteArrayToLong(useData, 0x4, 4);
agency = Utils.byteArrayToLong(useData, 0x2, 2);
machineid = Utils.byteArrayToLong(useData, 0x8, 4);
amount = Utils.byteArrayToLong(useData, 0xe, 2);
if (timestamp == 0)
return null;
timestamp -= EPOCH_OFFSET;
return new ClipperRefill(timestamp, amount, agency, machineid);
}
private void setBalances() {
int tripIdx = 0;
int refillIdx = 0;
long balance = (long) mBalance;
while (tripIdx < mTrips.length) {
while (refillIdx < mRefills.length && mRefills[refillIdx].getTimestamp() > mTrips[tripIdx].getTimestamp()) {
balance -= mRefills[refillIdx].mAmount;
refillIdx++;
}
mTrips[tripIdx].mBalance = balance;
balance += mTrips[tripIdx].mFare;
tripIdx++;
}
}
public static String getAgencyName(int agency) {
if (ClipperData.AGENCIES.containsKey(agency)) {
return ClipperData.AGENCIES.get(agency);
}
return FareBotApplication.getInstance().getString(R.string.unknown_format, "0x" + Long.toString(agency, 16));
}
public static String getShortAgencyName(int agency) {
if (ClipperData.SHORT_AGENCIES.containsKey(agency)) {
return ClipperData.SHORT_AGENCIES.get(agency);
}
return FareBotApplication.getInstance().getString(R.string.unknown_format, "0x" + Long.toString(agency, 16));
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeLong(mSerialNumber);
parcel.writeLong(mBalance);
parcel.writeInt(mTrips.length);
parcel.writeTypedArray(mTrips, flags);
parcel.writeInt(mRefills.length);
parcel.writeTypedArray(mRefills, flags);
}
}
| gpl-3.0 |
DaniloSI/Tecnicas-de-Programacao-Avancada | Exercicios/src/matriz/domain/Matrix.java | 4426 | package matriz.domain;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 20142bsi0186 on 16/02/2017.
*/
public class Matrix {
private List<Cell> matrix;
private int numberOfRows = 0;
private int numberOfColumns = 0;
public Matrix() {
matrix = new ArrayList<>();
}
public Matrix(int numberOfRows, int numberOfColumns) {
this.numberOfRows = numberOfRows;
this.numberOfColumns = numberOfColumns;
matrix = new ArrayList<>();
}
/**
* Responsável por adicionar um elemento na matriz em uma determinada linha e coluna.
* @param row Linha da matriz.
* @param column Coluna da matriz.
* @param value Valor que será inserido.
*/
public void add(int row, int column, double value) {
if (value != 0.0D) {
int indexCell = getIndex(row, column);
if (indexCell == matrix.size()) {
matrix.add(new Cell(row, column, value));
}
else {
matrix.get(indexCell).setValue(value);
}
}
// A quantidade de linhas será a mesma se a linha alvo for maior. Caso o contrário passa a ser a própria linha alvo.
numberOfRows = ((row + 1) > numberOfRows) ? (row + 1) : numberOfRows;
numberOfColumns = ((column + 1) > numberOfColumns) ? (column + 1) : numberOfColumns;
}
public double get(int row, int column) {
int indexCell = getIndex(row, column);
return (indexCell == matrix.size()) ? 0 : matrix.get(indexCell).getValue();
}
private int getIndex(int row, int column) {
for (int index = 0 ; index < matrix.size() ; index++) {
Cell cell = matrix.get(index);
if (cell.getRow() == row && cell.getColumn() == column) {
return index;
}
}
return matrix.size();
}
@Override
public String toString() {
String matrix = "";
for (int row = 0; row < numberOfRows; row++) {
for (int column = 0; column < numberOfColumns; column++) {
matrix += (get(row, column) + "\t");
}
matrix += ("\n");
}
return matrix;
}
public int getNumberOfRows() {
return numberOfRows;
}
public int getNumberOfColumns() {
return numberOfColumns;
}
/**
* Multiplica a matriz por uma outra matriz.
* @param matrix Matriz a ser multiplicada.
* @return Resultado da multiplicação das matrizes.
*/
public Matrix times(Matrix matrix) {
Matrix resultMatrix = null;
if (numberOfColumns == matrix.getNumberOfRows()) {
resultMatrix = new Matrix();
for (int rowFirstMatrix = 0; rowFirstMatrix < numberOfRows; rowFirstMatrix++) {
for (int columnSecondMatrix = 0; columnSecondMatrix < matrix.getNumberOfColumns() ; columnSecondMatrix++) {
int resultValue = 0;
for (int rowSecondMatrix = 0; rowSecondMatrix < matrix.getNumberOfRows() ; rowSecondMatrix++) {
resultValue += this.get(rowFirstMatrix, rowSecondMatrix) * matrix.get(rowSecondMatrix, columnSecondMatrix);
}
resultMatrix.add(rowFirstMatrix, columnSecondMatrix, resultValue);
}
}
}
return resultMatrix;
}
/**
* Duas matrizes são iguais se tiver a mesma quantidade de linhas, a mesma quantidade de colunas e os valores das células correspondentes forem iguais.
* @param object objeto.
* @return Se as matrizes são iguais ou não.
*/
@Override
public boolean equals(Object object) {
Matrix matrix = (Matrix) object;
if (matrix.getNumberOfRows() != numberOfRows || matrix.numberOfColumns != numberOfColumns) {
return false;
}
else {
for (int row = 0; row < numberOfRows; row++) {
for (int column = 0; column < numberOfColumns; column++) {
if (matrix.get(row, column) != this.get(row, column)) {
return false;
}
}
}
return true;
}
}
}
| gpl-3.0 |
rcgroot/open-gpstracker-ng | studio/features/src/test/java/nl/sogeti/android/gpstracker/ng/features/map/rendering/PathRendererTest.java | 3346 | /*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.features.map.rendering;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.util.ArrayList;
import java.util.List;
import nl.sogeti.android.gpstracker.ng.base.location.LatLng;
import static org.mockito.Matchers.anyFloat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class PathRendererTest {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
Canvas canvas;
private PathRenderer sut;
@Before
public void setup() {
sut = new PathRenderer(128, 6, null, null, null);
}
@Test
public void initCreateCorrectProjection() {
Assert.assertEquals(128.0, sut.getProjection().getTileSize(), 0.00000001);
}
@Test
public void singlePointPath() {
// Prepare
Bitmap start = mock(Bitmap.class);
Bitmap stop = mock(Bitmap.class);
List<List<LatLng>> latLng = new ArrayList<>();
List<LatLng> segment = new ArrayList<>();
latLng.add(segment);
segment.add(new LatLng(52.0, 5.0));
sut = new PathRenderer(32.0F, 2.0F, latLng, start, stop);
Paint paint = mock(Paint.class);
Path path = mock(Path.class);
// Execute
sut.drawPath(canvas, 0, 0, 0, paint, path);
// Verify
verify(canvas).drawBitmap(eq(start), anyFloat(), anyFloat(), (Paint) anyObject());
verify(canvas).drawPath(eq(path), eq(paint));
}
}
| gpl-3.0 |
terraframe/geodashboard | geoprism-server/src/main/java-gen/stub/net/geoprism/report/ReportItemViewQuery.java | 2369 | /**
* Copyright (c) 2015 TerraFrame, Inc. All rights reserved.
*
* This file is part of Geoprism(tm).
*
* Geoprism(tm) 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.
*
* Geoprism(tm) is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Geoprism(tm). If not, see <http://www.gnu.org/licenses/>.
*/
package net.geoprism.report;
/**
*
* @author Autogenerated by RunwaySDK
*/
public class ReportItemViewQuery extends net.geoprism.report.ReportItemViewQueryBase
{
public ReportItemViewQuery(com.runwaysdk.query.QueryFactory queryFactory)
{
super(queryFactory);
this.buildQuery(new DefaultReportItemViewBuilder(queryFactory));
}
public ReportItemViewQuery(com.runwaysdk.query.QueryFactory queryFactory, com.runwaysdk.query.ViewQueryBuilder viewQueryBuilder)
{
super(queryFactory, viewQueryBuilder);
}
class DefaultReportItemViewBuilder extends com.runwaysdk.query.ViewQueryBuilder
{
private ReportItemQuery query;
public DefaultReportItemViewBuilder(com.runwaysdk.query.QueryFactory queryFactory)
{
super(queryFactory);
this.query = new ReportItemQuery(queryFactory);
}
protected ReportItemViewQuery getViewQuery()
{
return (ReportItemViewQuery)super.getViewQuery();
}
/**
* build the select clause
*/
protected void buildSelectClause()
{
ReportItemViewQuery vQuery = this.getViewQuery();
vQuery.map(ReportItemView.DASHBOARDLABEL, this.query.getDashboard().getDisplayLabel().localize());
vQuery.map(ReportItemView.REPORTLABEL, this.query.getReportLabel().localize());
vQuery.map(ReportItemView.REPORTID, this.query.getOid());
vQuery.map(ReportItemView.REPORTNAME, this.query.getReportName());
}
/**
* Implement only if additional join criteria is required.
*/
protected void buildWhereClause()
{
}
}
}
| gpl-3.0 |
felipefo/poo2 | Padroes_de_Projeto/Estrutural/Adapter/AdapterSMS/src/sms/adapter/Cobranca.java | 308 | /*
* 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 sms.adapter;
/**
*
* @author felipe
*/
public interface Cobranca {
public void cobrar(int telefone);
}
| gpl-3.0 |
StaticDot/green-fifteen-gdx | core/src/main/java/com/staticdot/fifteen/logic/Position.java | 492 | package com.staticdot.fifteen.logic;
public class Position {
private int line;
private int column;
public Position(int line, int column) {
this.line = line;
this.column = column;
}
public int getLine() {
return line;
}
public void setLine(int line) {
this.line = line;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
@Override
public String toString() {
return "(" + line + ", " + column + ")";
}
}
| gpl-3.0 |
rockon999/RockEngine | src/main/java/com/sci/engine/SciGame.java | 3455 | package com.sci.engine;
import java.util.ArrayList;
import java.util.List;
import com.sci.engine.graphics.Display;
import com.sci.engine.graphics.Renderer;
import com.sci.engine.interfaces.Updatable;
/**
* SciEngine
*
* @author sci4me
* @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html)
*/
public abstract class SciGame implements Runnable
{
private Thread thread;
private volatile boolean running;
private boolean ran;
private double ns;
private int targetTPS;
private int tps;
private int fps;
private List<Updatable> updatables;
private Display display;
private Renderer renderer;
/**
* Creates a new game using the specified display
*
* @param display
*/
public SciGame(Display display)
{
this.display = display;
this.renderer = new Renderer(this.display.getWidth(), this.display.getHeight());
this.thread = new Thread(this, "SciGame-Main");
this.display.addCloseListener(new Runnable()
{
@Override
public void run()
{
SciGame.this.stop();
}
});
this.setTargetTPS(100);
this.updatables = new ArrayList<Updatable>();
}
/**
* Starts the game
*/
public synchronized final void start()
{
this.running = true;
this.display.start();
this.thread.start();
}
/**
* Stops the game
*/
public synchronized final void stop()
{
this.running = false;
this.display.stop();
}
/**
* Adds an updatable object
*
* @param updatable
*/
public final void addUpdatable(Updatable updatable)
{
this.updatables.add(updatable);
}
/**
* Removes an updatable object
*
* @param updatable
*/
public final void removeUpdatable(Updatable updatable)
{
this.updatables.remove(updatable);
}
@Override
public final void run()
{
if(!this.ran)
{
this.ran = true;
long last = System.nanoTime();
double delta = 0.0;
int ticks = 0;
int frames = 0;
long timer = System.currentTimeMillis();
this.init();
while(this.running)
{
long now = System.nanoTime();
delta += (now - last) / this.ns;
last = now;
while(delta >= 1)
{
for(Updatable u : this.updatables)
u.update();
this.update();
delta--;
ticks++;
}
this.renderer.clear();
this.render(this.renderer);
this.renderer.copy();
this.display.getDrawGraphics().drawImage(this.renderer.getImage(), 0, 0, null);
this.display.show();
frames++;
if(System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
this.tps = ticks;
this.fps = frames;
ticks = 0;
frames = 0;
}
}
this.shutdown();
}
}
/**
* Initializes the game
*/
public abstract void init();
/**
* Updates the game
*/
public abstract void update();
/**
* Renders the game
*
* @param renderer
*/
public abstract void render(Renderer renderer);
/**
* Called when the game shuts down
*/
public abstract void shutdown();
/**
* Gets the game's tick rate
*
* @return
*/
public int getTPS()
{
return this.tps;
}
/**
* Get the game's frame rate
*
* @return
*/
public int getFPS()
{
return this.fps;
}
/**
* Gets the game's target tick rate
*
* @return
*/
public int getTargetTPS()
{
return this.targetTPS;
}
/**
* Sets the game's target tick rate
*
* @param targetTPS
*/
public void setTargetTPS(int targetTPS)
{
this.targetTPS = targetTPS;
this.ns = 1000000000.0 / this.targetTPS;
}
} | gpl-3.0 |
fanruan/finereport-design | designer_base/src/com/fr/design/gui/syntax/ui/rsyntaxtextarea/DocumentRange.java | 3450 | /*
* 08/11/2009
*
* DocumentRange.java - A range of text in a document.
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package com.fr.design.gui.syntax.ui.rsyntaxtextarea;
/**
* A range of text in a document.
*
* @author Robert Futrell
* @version 1.0
*/
public class DocumentRange implements Comparable<DocumentRange> {
private int startOffs;
private int endOffs;
/**
* Constructor.
*
* @param startOffs The starting offset in the document, inclusive.
* @param endOffs The ending offset in the document, exclusive.
* @throws IllegalArgumentException If <code>endOffs</code> is less than
* <code>startOffs</code>, or either argument is less than zero.
*/
public DocumentRange(int startOffs, int endOffs) {
set(startOffs, endOffs);
}
/**
* Compares this document range to another.
*
* @param other Another document range.
* @return How the two should be sorted relative to each other.
*/
public int compareTo(DocumentRange other) {
if (other==null) {
return 1;
}
int diff = startOffs - other.startOffs;
if (diff!=0) {
return diff;
}
return endOffs - other.endOffs;
}
/**
* Returns whether this document range is equal to another one.
*
* @param other Another object, presumably a document range.
* @return Whether <code>other</code> is also a document range, and equal
* to this one.
*/
@Override
public boolean equals(Object other) {
if (other==this) {
return true;
}
if (other instanceof DocumentRange) {
return this.compareTo((DocumentRange)other)==0;
}
return false;
}
/**
* Gets the end offset of the range.
*
* @return The end offset.
* @see #getStartOffset()
*/
public int getEndOffset() {
return endOffs;
}
/**
* Gets the starting offset of the range.
*
* @return The starting offset.
* @see #getEndOffset()
*/
public int getStartOffset() {
return startOffs;
}
/**
* Overridden simply as a best practice, since {@link #equals(Object)} is
* overridden.
*
* @return The hash code for this object.
*/
@Override
public int hashCode() {
return startOffs + endOffs;
}
/**
* Sets the document range.
*
* @param start The new start value, inclusive.
* @param end The new end value, exclusive.
* @throws IllegalArgumentException If <code>end</code> is less than
* <code>start</code>, or either argument is less than zero.
*/
public void set(int start, int end) {
if (start<0 || end<0) {
throw new IllegalArgumentException ("start and end must be >= 0");
}
if (end<start) {
throw new IllegalArgumentException(
"'end' cannot be less than 'start'");
}
this.startOffs = start;
this.endOffs = end;
}
/**
* Returns a string representation of this object.
*
* @return A string representation of this object.
*/
@Override
public String toString() {
return "[DocumentRange: " + startOffs + "-" + endOffs + "]";
}
/**
* Translates this document range by a given amount.
*
* @param amount The amount to translate this range by.
* @return This (modified) range.
*/
public DocumentRange translate(int amount) {
startOffs += amount;
endOffs += amount;
return this;
}
} | gpl-3.0 |
lw4z/ListaAcessivel | app/src/main/java/mobile/listaacessivel/fafica/listaacessvel/entidades/Lista.java | 3685 | package mobile.listaacessivel.fafica.listaacessvel.entidades;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by ivan on 01/04/15.
*/
public class Lista {
private int id_lista;
private String descricao;
private String situacao;
private String data_criacao;
private String data_alteracao;
private int quantidade_total = 0;
private float valor_total = 0.0f;
private Cliente cliente;
private Estabelecimento estabelecimento;
private List<Produto> produtos;
public Lista() { }
public Lista(String descricao, String situacao, Cliente cliente, Estabelecimento estabelecimento, List<Produto> produtos) {
this.descricao = descricao;
this.situacao = situacao;
this.cliente = cliente;
this.estabelecimento = estabelecimento;
this.produtos = produtos;
}
public Lista(int id_lista, String descricao, String situacao, Cliente cliente, Estabelecimento estabelecimento, List<Produto> produtos) {
this.id_lista = id_lista;
this.descricao = descricao;
this.situacao = situacao;
this.cliente = cliente;
this.estabelecimento = estabelecimento;
this.produtos = produtos;
}
public Lista(int id_lista, String descricao, String situacao,
String data_criacao, String data_alteracao, int quantidade_total,
float valor_total, Cliente cliente,
Estabelecimento estabelecimento, List<Produto> produtos) {
super();
this.id_lista = id_lista;
this.descricao = descricao;
this.situacao = situacao;
this.data_criacao = data_criacao;
this.data_alteracao = data_alteracao;
this.quantidade_total = quantidade_total;
this.valor_total = valor_total;
this.cliente = cliente;
this.estabelecimento = estabelecimento;
this.produtos = produtos;
}
public int getId_lista() {
return id_lista;
}
public void setId_lista(int id_lista) {
this.id_lista = id_lista;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getSituacao() {
return situacao;
}
public void setSituacao(String situacao) {
this.situacao = situacao;
}
public String getData_criacao() {
return data_criacao;
}
public void setData_criacao(String data_criacao) {
this.data_criacao = data_criacao;
}
public String getData_alteracao() {
return data_alteracao;
}
public void setData_alteracao(String data_alteracao) {
this.data_alteracao = data_alteracao;
}
public int getQuantidade_total() {
return quantidade_total;
}
public void setQuantidade_total(int quantidade_total) {
this.quantidade_total = quantidade_total;
}
public float getValor_total() {
return valor_total;
}
public void setValor_total(float valor_total) {
this.valor_total = valor_total;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public Estabelecimento getEstabelecimento() {
return estabelecimento;
}
public void setEstabelecimento(Estabelecimento estabelecimento) {
this.estabelecimento = estabelecimento;
}
public List<Produto> getProdutos() {
return produtos;
}
public void setProdutos(List<Produto> produtos) {
this.produtos = produtos;
}
} | gpl-3.0 |
zyxist/opentrans | opentrans-lightweight/src/main/java/org/invenzzia/opentrans/lightweight/binding/NewProject.java | 1138 | /*
* Copyright (C) 2013 Invenzzia Group <http://www.invenzzia.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.invenzzia.opentrans.lightweight.binding;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD })
public @interface NewProject {
}
| gpl-3.0 |
komet22/proj_zesp_sem5 | AppProjZesp/src/main/java/projApp/formDTO/EventDocumentDTO.java | 1531 | package projApp.formDTO;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.web.multipart.MultipartFile;
import projApp.model.event.Event;
/**
* @authors Pawe³ Miszkiel & Rafa³ Teodorowski
*
* PW, Wydzia³ Elektryczny - Informatyka - semestr VI
*
* 2017-06-13
*/
public class EventDocumentDTO {
private Integer eventDocumentId;
private String name;
private String type;
private String path;
@NotNull
private MultipartFile eventDocument;
@NotNull
@Size(min=5, max=120)
private String description;
private Event event;
public Integer getEventDocumentId() {
return eventDocumentId;
}
public void setEventDocumentId(Integer eventDocumentId) {
this.eventDocumentId = eventDocumentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public MultipartFile getEventDocument() {
return eventDocument;
}
public void setEventDocument(MultipartFile eventDocument) {
this.eventDocument = eventDocument;
}
} | gpl-3.0 |
raymondbh/TFCraft | src/Common/com/bioxx/tfc/Items/Tools/ItemSteelBucketRed.java | 1461 | package com.bioxx.tfc.Items.Tools;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import com.bioxx.tfc.Reference;
import com.bioxx.tfc.api.TFCItems;
public class ItemSteelBucketRed extends ItemSteelBucket
{
public ItemSteelBucketRed(Block par2)
{
super(par2);
}
@Override
public void registerIcons(IIconRegister registerer)
{
String name = this.getUnlocalizedName().replace("item.", "");
name = name.replace("Salt ", "");
this.itemIcon = registerer.registerIcon(Reference.ModID + ":" + this.textureFolder + name);
}
@Override
public boolean onItemUse(ItemStack is, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ)
{
if (this.bucketContents != Blocks.air && world.getBlock(x, y, z) == Blocks.cauldron)
{
int meta = world.getBlockMetadata(x, y, z);
if (meta < 3)
{
if (!player.capabilities.isCreativeMode)
{
player.setCurrentItemOrArmor(0, new ItemStack(TFCItems.RedSteelBucketEmpty));
}
world.setBlockMetadataWithNotify(x, y, z, MathHelper.clamp_int(3, 0, 3), 2);
world.func_147453_f(x, y, z, Blocks.cauldron);
return true;
}
}
return false;
}
}
| gpl-3.0 |
klhdy/im-indepartment | src/com/sealtalk/dao/group/GroupMemberDao.java | 2259 | package com.sealtalk.dao.group;
import java.util.ArrayList;
import java.util.List;
import com.sealtalk.model.TGroup;
import com.sealtalk.model.TGroupMember;
import com.sealtalk.model.TMember;
/**
* 群组成员关系
* @author hao_dy
* @since jdk1.7
* @date 2017/01/12
*/
public interface GroupMemberDao {
/**
* 保存群组成员关系
* @param idsArr
*/
public void saveGroupMemeber(ArrayList<TGroupMember> idsArr);
/**
* 获取群组成员
* @param groupId
* @return
*/
public List<TGroupMember> getTGroupMemberList(int groupId);
/**
* 退出群组
* @param userIdsInt
* @param groupIdInt
*/
public void removeGroupMemeber(String userIdsInt, int groupIdInt);
/**
* 删除群成员
* @param groupId
*/
public int removeGroupMember(int groupId);
/**
* 获取特定群的群人数
* @param groupId
* @return
*/
public int getGroupMemberCountForGoupId(String groupId);
/**
* 转移群主
* @param userIdInt 要转移的id
* @param groupIdInt 群id
* @param integer 原群主关系记录id
* @return
*/
public int transferGroup(int userIdInt, int groupIdInt, Integer integer);
/**
* 获取群主记录
* @param groupId
* @return
*/
public TGroupMember getGroupMemberCreator(int groupId);
/**
* 获取群成员
* @param groupId
* @return
*/
public List<TGroupMember> listGroupMembers(int groupId);
/**
* 依据用户id获取群成员关系记录
* @param userId
* @return
*/
public List<TGroupMember> getGroupMemberForUserId(int userId);
/**
* 依据组id,及成员id删除成员关系
* @param groupIdInt
* @param needDelStr
*/
public void delGroupMemberForMemberIdsAndGroupId(int groupIdInt,
String needDelStr);
/**
* 根据组id获取群成员
* @param groupIds
* @return
*/
public List<TGroupMember> getGroupMemberByGroupIds(Integer[] groupIds);
public int deleteRelationByIds(String ids, String isLogic);
public TGroupMember getGroupMemberById(Integer groupMemberId);
public List<TGroupMember> getGroupMemberByMembIds(Integer[] ids);
public void updateGroupMember(TGroupMember tgm);
public TGroupMember judgeGroupCreate(Integer userIdInt, Integer groupIdInt);
public int getGroupMemberCount(int groupId);
}
| gpl-3.0 |
ckaestne/CIDE | CIDE_Language_XML_concrete/src/tmp/generated_xhtml/STag_samp.java | 762 | package tmp.generated_xhtml;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class STag_samp extends GenASTNode {
public STag_samp(ArrayList<Attribute> attribute, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyZeroOrMore<Attribute>("attribute", attribute)
}, firstToken, lastToken);
}
public STag_samp(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public ASTNode deepCopy() {
return new STag_samp(cloneProperties(),firstToken,lastToken);
}
public ArrayList<Attribute> getAttribute() {
return ((PropertyZeroOrMore<Attribute>)getProperty("attribute")).getValue();
}
}
| gpl-3.0 |
jdcasey/sjbi | api/src/main/java/org/commonjava/sjbi/model/ArtifactRef.java | 3538 | /*
* Copyright (c) 2010 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses>.
*/
package org.commonjava.sjbi.model;
import java.io.File;
public class ArtifactRef
{
private final ProjectRef projectRef;
private File artifactFile;
private final String type;
private final String classifier;
public ArtifactRef( final ProjectRef projectRef, final String type, final String classifier )
{
this.projectRef = projectRef;
this.type = type;
this.classifier = classifier;
}
public ArtifactRef( final ProjectRef projectRef, final String type )
{
this.projectRef = projectRef;
this.type = type;
classifier = null;
}
public String subKey()
{
return type + ( classifier != null ? ":" + classifier : "" );
}
public String key()
{
return projectRef.artifactKey( type, classifier );
}
public File getArtifactFile()
{
return artifactFile;
}
public void setArtifactFile( final File artifactFile )
{
this.artifactFile = artifactFile;
}
public ProjectRef getProjectRef()
{
return projectRef;
}
public String getType()
{
return type;
}
public String getClassifier()
{
return classifier;
}
@Override
public String toString()
{
return key();
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ( ( classifier == null ) ? 0 : classifier.hashCode() );
result = prime * result + ( ( projectRef == null ) ? 0 : projectRef.hashCode() );
result = prime * result + ( ( type == null ) ? 0 : type.hashCode() );
return result;
}
@Override
public boolean equals( final Object obj )
{
if ( this == obj )
{
return true;
}
if ( obj == null )
{
return false;
}
if ( getClass() != obj.getClass() )
{
return false;
}
final ArtifactRef other = (ArtifactRef) obj;
if ( classifier == null )
{
if ( other.classifier != null )
{
return false;
}
}
else if ( !classifier.equals( other.classifier ) )
{
return false;
}
if ( projectRef == null )
{
if ( other.projectRef != null )
{
return false;
}
}
else if ( !projectRef.equals( other.projectRef ) )
{
return false;
}
if ( type == null )
{
if ( other.type != null )
{
return false;
}
}
else if ( !type.equals( other.type ) )
{
return false;
}
return true;
}
}
| gpl-3.0 |
ocpsoft/socialpm | services/src/main/java/com/ocpsoft/socialpm/util/crypt/MD5PasswordEncryptor.java | 2588 | /**
* This file is part of OCPsoft SocialPM: Agile Project Management Tools (SocialPM)
*
* Copyright (c)2011 Lincoln Baxter, III <lincoln@ocpsoft.com> (OCPsoft)
* Copyright (c)2011 OCPsoft.com (http://ocpsoft.com)
*
* If you are developing and distributing open source applications under
* the GNU General Public License (GPL), then you are free to re-distribute SocialPM
* under the terms of the GPL, as follows:
*
* SocialPM 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.
*
* SocialPM 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 SocialPM. If not, see <http://www.gnu.org/licenses/>.
*
* For individuals or entities who wish to use SocialPM privately, or
* internally, the following terms do not apply:
*
* For OEMs, ISVs, and VARs who wish to distribute SocialPM with their
* products, or host their product online, OCPsoft provides flexible
* OEM commercial licenses.
*
* Optionally, Customers may choose a Commercial License. For additional
* details, contact an OCPsoft representative (sales@ocpsoft.com)
*/
package com.ocpsoft.socialpm.util.crypt;
import java.security.MessageDigest;
import javax.enterprise.inject.Typed;
import org.apache.commons.codec.binary.Base64;
@Typed(PasswordEncryptor.class)
public class MD5PasswordEncryptor implements PasswordEncryptor
{
private static final long serialVersionUID = 1422059557145039442L;
@Override
public String encodePassword(final String password, final Object salt)
{
try
{
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(salt.toString().getBytes());
byte[] passwordHash = digest.digest(password.getBytes());
Base64 encoder = new Base64();
byte[] encoded = encoder.encode(passwordHash);
return new String(encoded);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public boolean isPasswordValid(final String cypherPass, final String password, final Object salt)
{
return cypherPass.equals(this.encodePassword(password, salt));
}
} | gpl-3.0 |
idega/is.idega.idegaweb.egov.bpm | src/java/com/idega/idegaweb/egov/bpm/presentation/DefaultCasesListCustomizer.java | 6949 | package com.idega.idegaweb.egov.bpm.presentation;
import is.idega.idegaweb.egov.bpm.IWBundleStarter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import com.idega.block.process.presentation.beans.CasesListCustomizer;
import com.idega.builder.bean.AdvancedProperty;
import com.idega.core.business.DefaultSpringBean;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.idegaweb.egov.bpm.data.dao.CasesBPMDAO;
import com.idega.jbpm.bean.VariableInstanceInfo;
import com.idega.jbpm.data.VariableInstanceQuerier;
import com.idega.jbpm.utils.JBPMConstants;
import com.idega.jbpm.variables.MultipleSelectionVariablesResolver;
import com.idega.util.CoreConstants;
import com.idega.util.ListUtil;
import com.idega.util.StringUtil;
import com.idega.util.datastructures.map.MapUtil;
import com.idega.util.expression.ELUtil;
public abstract class DefaultCasesListCustomizer extends DefaultSpringBean implements CasesListCustomizer {
@Autowired
private CasesBPMDAO casesBPMDAO;
@Autowired
private VariableInstanceQuerier variablesQuerier;
protected CasesBPMDAO getCasesBPMDAO() {
if (casesBPMDAO == null)
ELUtil.getInstance().autowire(this);
return casesBPMDAO;
}
protected void setCasesBPMDAO(CasesBPMDAO casesBPMDAO) {
this.casesBPMDAO = casesBPMDAO;
}
protected VariableInstanceQuerier getVariablesQuerier() {
if (variablesQuerier == null)
ELUtil.getInstance().autowire(this);
return variablesQuerier;
}
protected void setVariablesQuerier(VariableInstanceQuerier variablesQuerier) {
this.variablesQuerier = variablesQuerier;
}
protected String getLocalizedHeader(IWResourceBundle iwrb, String key) {
return iwrb.getLocalizedString(JBPMConstants.VARIABLE_LOCALIZATION_PREFIX.concat(key), key);
}
@Override
public List<String> getHeaders(List<String> headersKeys) {
if (ListUtil.isEmpty(headersKeys))
return null;
List<String> headers = new ArrayList<String>();
IWResourceBundle iwrb = getResourceBundle(getBundle(IWBundleStarter.IW_BUNDLE_IDENTIFIER));
for (String key: headersKeys)
headers.add(getLocalizedHeader(iwrb, key));
return headers;
}
@Override
public Map<String, String> getHeadersAndVariables(List<String> headersKeys) {
if (ListUtil.isEmpty(headersKeys))
return null;
Map<String, String> headers = new LinkedHashMap<String, String>(headersKeys.size());
IWResourceBundle iwrb = getResourceBundle(getBundle(IWBundleStarter.IW_BUNDLE_IDENTIFIER));
for (String key: headersKeys)
headers.put(key, getLocalizedHeader(iwrb, key));
return headers;
}
private MultipleSelectionVariablesResolver getResolver(String name) {
Map<String, Boolean> resolvers = getCache("multipleSelectionVariablesResolverCache");
String key = MultipleSelectionVariablesResolver.BEAN_NAME_PREFIX + name;
Boolean validResolver = resolvers.get(key);
MultipleSelectionVariablesResolver resolver = null;
if (validResolver == null) {
try {
resolver = ELUtil.getInstance().getBean(key);
} catch (Exception e) {}
validResolver = resolver != null;
resolvers.put(key, validResolver);
}
if (resolver != null)
return resolver;
if (validResolver != null && validResolver)
return ELUtil.getInstance().getBean(key);
return null;
}
protected AdvancedProperty getLabel(VariableInstanceInfo variable) {
String name = variable.getName();
MultipleSelectionVariablesResolver resolver = getResolver(name);
if (resolver != null)
return new AdvancedProperty(name, resolver.isValueUsedForCaseList() ?
resolver.getPresentation(variable.getValue().toString()) :
resolver.getKeyPresentation(variable.getProcessInstanceId(), variable.getValue().toString())
);
return new AdvancedProperty(name, variable.getValue().toString());
}
@Override
public Map<String, Map<String, String>> getLabelsForHeaders(List<String> casesIds, List<String> headersKeys) {
if (ListUtil.isEmpty(casesIds) || ListUtil.isEmpty(headersKeys)) {
getLogger().warning("There are no cases IDs or/and headers provided");
return null;
}
Map<Long, List<VariableInstanceInfo>> vars = getCasesBPMDAO().getBPMValuesByCasesIdsAndVariablesNames(casesIds, headersKeys);
if (MapUtil.isEmpty(vars)) {
getLogger().warning("There are no values for cases " + casesIds + " and variables " + headersKeys);
return null;
}
// Resolving labels
Map<String, Map<String, String>> labels = new LinkedHashMap<String, Map<String,String>>();
Map<String, Long> mappings = new HashMap<String, Long>();
for (Long procId: vars.keySet()) {
List<VariableInstanceInfo> procVars = vars.get(procId);
if (ListUtil.isEmpty(procVars))
continue;
Map<String, String> caseLabels = null;
for (VariableInstanceInfo info: procVars) {
String caseId = info.getCaseId();
if (StringUtil.isEmpty(caseId))
continue;
mappings.put(caseId, procId);
caseLabels = labels.get(caseId);
if (caseLabels == null) {
caseLabels = new HashMap<String, String>();
labels.put(caseId, caseLabels);
}
Serializable value = info.getValue();
if (value == null)
continue;
AdvancedProperty label = getLabel(info);
caseLabels.put(label.getId(), label.getValue());
}
}
// Checking if everything was resolved
Map<String, List<String>> missingLabels = new HashMap<String, List<String>>();
for (String caseId: labels.keySet()) {
for (String headerKey: headersKeys) {
Map<String, String> caseLabels = labels.get(caseId);
if (caseLabels.containsKey(headerKey) && !StringUtil.isEmpty(caseLabels.get(headerKey)))
continue;
List<String> varNames = missingLabels.get(caseId);
if (varNames == null) {
varNames = new ArrayList<String>();
missingLabels.put(caseId, varNames);
}
varNames.add(headerKey);
}
}
if (!MapUtil.isEmpty(missingLabels)) {
getLogger().info("There are missing labels: " + missingLabels + " will try to resolve them");
doResolveMissingLabels(labels, missingLabels);
}
return labels;
}
/**
* Resolves missing values
*
* @param labels: case ID -> variable name: value
* @param missingLabels: case ID -> variable names
*/
protected void doResolveMissingLabels(Map<String, Map<String, String>> labels, Map<String, List<String>> missingLabels) {
if (MapUtil.isEmpty(labels) || MapUtil.isEmpty(missingLabels))
return;
for (String caseId: missingLabels.keySet()) {
List<String> varNames = missingLabels.get(caseId);
if (ListUtil.isEmpty(varNames))
continue;
getLogger().warning("Missing labels for case (" + caseId + "): " + varNames);
Map<String, String> caseLabels = labels.get(caseId);
for (String varName: varNames) {
if (!caseLabels.containsKey(varName))
caseLabels.put(varName, CoreConstants.MINUS);
}
}
}
} | gpl-3.0 |
zhonghuasheng/JAVA | springboot/springboot-basic/src/main/java/com/zhonghuasheng/basic/runner/commandline/FirstCommandLineRunner.java | 6639 | package com.zhonghuasheng.basic.runner.commandline;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.ServletOutputStream;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@Order(1)
public class FirstCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("FirstCommandLineRunner order = 1");
Map<String, String> maps = new HashMap<>();
Date now = new Date();
maps.put("${year}", "2021");
maps.put("${month}", "04");
maps.put("${day}", "19");
maps.put("${applicant}", "加盟商1号");
maps.put("${businessLicenseNum}", "9DFDD8FDS899898");
maps.put("${address}", "湖北省武汉市洪山区关山大道111号");
System.out.println("step1");
String pathPrefix = "/data/" + System.currentTimeMillis();
try {
URL url = new URL("https://jv-product-1259380639.cos.ap-shanghai.myqcloud.com/fc-store-merchants/upload/%E7%BE%8E%E5%AD%9A1%E5%8F%B7%E8%BD%A6%E5%85%BB%E6%8A%A4%E8%87%BB%E9%80%89%E5%BA%97%E7%89%B9%E8%AE%B8%E7%BB%8F%E8%90%A5%E5%8D%8F%E8%AE%AE.docx");
InputStream doc = url.openStream();
XWPFDocument document = new XWPFDocument(doc);
List<XWPFParagraph> paragraphs = document.getParagraphs();
// 填充占位符
for (XWPFParagraph paragraph : paragraphs) {
String text = paragraph.getText();
if (text.contains("${")) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
if (run.toString().contains("${")) {
run.setText(maps.get(run.text()), 0);
}
}
}
}
FileOutputStream docOut = new FileOutputStream(pathPrefix + ".docx");
document.write(docOut);
FileOutputStream docOut2 = new FileOutputStream(pathPrefix + ".txt");
document.write(docOut2);
System.out.println("step2");
// 生成PDF
//String pdfPath = "C:\\Users\\yong.chen\\Downloads\\" + System.currentTimeMillis() + ".pdf";
String pdfPath = pathPrefix + ".pdf";
PdfOptions options = PdfOptions.create();
FileOutputStream fileOutputStream = new FileOutputStream(pdfPath);
PdfConverter.getInstance().convert(document, fileOutputStream, options);
doc.close();
doc.close();
fileOutputStream.close();
// 设置PDF水印
//String pdfPath2 = "C:\\Users\\yong.chen\\Downloads\\" + System.currentTimeMillis() + "-copy-.pdf";
String pdfPath2 = pathPrefix + "-yyyyyy-.pdf";
PdfReader reader = new PdfReader(pdfPath);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdfPath2));
// 设置是支持中文的写法 使用系统字体
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
int total = reader.getNumberOfPages() + 1;
System.out.println("step3");
PdfContentByte under;
Rectangle pageRect = null;
for (int i = 1; i < total; i++) {
pageRect = stamper.getReader().getPageSizeWithRotation(i);
// 计算水印X,Y坐标
float x = 290;//
x = pageRect.getWidth() / 2;
float y = 400;//
y = pageRect.getHeight() / 2;
// 获得PDF最顶层 在内容上方加水印
under = stamper.getOverContent(i);//
under.saveState();
PdfGState gs = new PdfGState();
// 设置透明度范围为0到1
gs.setFillOpacity(0.3f);
under.setGState(gs);
under.beginText();
under.setFontAndSize(base, 90);//字体大小
under.setColorFill(BaseColor.GRAY);//字体颜色
// 水印文字成45度角倾斜
under.showTextAligned(Element.ALIGN_CENTER, "孚创合同专用", x, y, 45);
// 添加水印文字
under.endText();
under.setLineWidth(1f);
under.stroke();
}
stamper.close();
reader.close();
System.out.println("step4");
/*String fileName = URLEncoder.encode("美孚1号车养护臻选店特许经营协议", "UTF-8");
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf8");
//response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
response.setHeader("Content-Type", "application/octet-stream;charset=utf8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(pdfPath2);
// 读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
System.out.println("step5");*/
fileOutputStream.close();
/*outputStream.flush();
outputStream.close();*/
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
| gpl-3.0 |
biu-google-fuel/fuel-oracle-android | ufo/src/org/biu/ufo/control/components/RouteEstimator.java | 2844 | package org.biu.ufo.control.components;
import java.util.List;
import org.androidannotations.annotations.EBean;
import org.biu.ufo.control.monitors.TripMonitor;
import org.biu.ufo.control.utils.Calculator;
import org.biu.ufo.model.Location;
import com.directions.route.Route;
import com.directions.route.Routing;
import com.directions.route.Routing.TravelMode;
import com.directions.route.RoutingListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
@EBean
public class RouteEstimator {
private static final long MIN_INTERVAL_BETWEEN_ROUTE_REQUESTS = 2*60*1000;
long lastRouteFetchTime = 0;
public static interface EstimatedRouteResult {
void onEstimatedRouteResult(EstimatedRoute route);
}
public static class EstimatedRoute {
public Route fullRoute;
public List<LatLng> points;
public int posInPoints;
}
public double getMinDistanceFromRoute(EstimatedRoute route, Location location){
double minDistance = Double.POSITIVE_INFINITY;
if(route != null) {
double distance;
for (int i = route.posInPoints; i < route.points.size(); ++i){
Location routeLocation = new Location(route.points.get(i));
distance = Calculator.distance(location,routeLocation);
if (minDistance > distance){
minDistance = distance;
}
}
}
return minDistance;
}
public boolean isOnRoute(EstimatedRoute route, Location location) {
boolean onRoute = false;
if(route != null) {
for(int i = route.posInPoints; i < route.points.size(); ++i) {
LatLng point = route.points.get(i);
if(Calculator.distance(location, new Location(point)) < TripMonitor.CLOSE_ENOUGH_DISTANCE) {
route.posInPoints = i;
onRoute = true;
break;
} else if(i - route.posInPoints > 50) {
break;
}
}
}
return onRoute;
}
public boolean isQueryAllowed() {
return System.currentTimeMillis() - lastRouteFetchTime > MIN_INTERVAL_BETWEEN_ROUTE_REQUESTS;
}
/**
* Fetch route directions
*/
public void getNewRouteEstimation(Location source, Location dest, final EstimatedRouteResult resultHandler) {
Routing routing = new Routing(TravelMode.DRIVING);
routing.registerListener(new RoutingListener() {
@Override
public void onRoutingSuccess(Route route, PolylineOptions mPolyOptions) {
EstimatedRoute result = new EstimatedRoute();
result.fullRoute = route;
result.points = mPolyOptions.getPoints();
resultHandler.onEstimatedRouteResult(result);
}
@Override
public void onRoutingStart() {
// TODO Auto-generated method stub
}
@Override
public void onRoutingFailure() {
// TODO Auto-generated method stub
}
});
lastRouteFetchTime = System.currentTimeMillis();
routing.execute(source.getLatLng(), dest.getLatLng());
}
}
| gpl-3.0 |
ReunionDev/reunion | jreunion/src/main/java/org/reunionemu/jreunion/model/quests/ObjectiveImpl.java | 333 | package org.reunionemu.jreunion.model.quests;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
/**
* @author Aidamina
* @license http://reunion.googlecode.com/svn/trunk/license.txt
*/
@XmlTransient
@XmlType(name="objective")
public abstract class ObjectiveImpl implements Objective {
}
| gpl-3.0 |
overturetool/overture | ide/vdmpp/ui/src/main/java/org/overture/ide/vdmpp/ui/wizard/VdmPpNewClassWizard.java | 1752 | /*
* #%~
* org.overture.ide.vdmpp.ui
* %%
* Copyright (C) 2008 - 2014 Overture
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #~%
*/
package org.overture.ide.vdmpp.ui.wizard;
import org.overture.ide.ui.wizard.VdmNewFileWizard;
public class VdmPpNewClassWizard extends VdmNewFileWizard {
@Override
protected String getPageDescription() {
return "Chose new VDM++ file name and location";
}
@Override
protected String getPageName() {
return "VDM++ New Class Wizard";
}
@Override
protected String getPageTitle() {
return "VDM++ New Class Wizard";
}
@Override
protected String getFileExtension()
{
return "vdmpp";
}
@Override
protected String getFileTemplate(String fileName)
{
String className = fileName;
return "class " + className + "\n" + "types\n-- TODO Define types here\n"
+ "values\n-- TODO Define values here\n" + "instance variables\n-- TODO Define instance variables here\n"
+ "operations\n-- TODO Define operations here\n" + "functions\n-- TODO Define functions here\n"
+ "traces\n-- TODO Define Combinatorial Test Traces here\n" + "end "
+ className;
}
}
| gpl-3.0 |
WaDosCh/WaDosUtil | test/ch/judos/generic/games/navigation/model/SpaceUnit.java | 1958 | package ch.judos.generic.games.navigation.model;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import ch.judos.generic.games.pathsearch.SimpleWayPoint;
import ch.judos.generic.games.pathsearch.WayPoint;
import ch.judos.generic.games.unitCoordination.ReservingUnitCoordination;
/**
* @author Julian Schelker
* @version 1.0
* @dependsOn
*/
public class SpaceUnit extends ReservingUnitCoordination implements Unit {
private boolean paused;
public float speed;
public SpaceUnit(Map m, int gridx, int gridy) {
super(m, new SimpleWayPoint(gridx, gridy), new WaterFieldChecker(m));
this.speed = 1;
this.paused = false;
}
@Override
protected float getSpeed() {
if (this.paused)
return 0;
return this.speed;
}
@Override
public void paint(Graphics g) {
update();
g.setColor(Color.green);
for (int i = 0; i < this.targets.size(); i++) {
Point t1 = this.map.getPointFromField(this.targets.get(i)).getPoint();
if (i == 0)
g.drawLine((int) getPosition().getX(), (int) getPosition().getY(), t1.x, t1.y);
if (i < this.targets.size() - 1) {
Point t2 = this.map.getPointFromField(this.targets.get(i + 1)).getPoint();
g.drawLine(t1.x, t1.y, t2.x, t2.y);
}
g.fillRect(t1.x - 10, t1.y - 10, 20, 20);
}
g.setColor(new Color(80, 40, 0));
int x = (int) getPosition().getX() - 25;
int y = (int) getPosition().getY() - 25;
g.fillRect(x, y, 50, 50);
g.setColor(Color.white);
g.drawString("uses", x + 5, y + 15);
g.drawString("some", x + 5, y + 30);
g.drawString("space", x + 5, y + 45);
g.setColor(Color.red);
if (!this.finalTargets.isEmpty()) {
WayPoint f = this.finalTargets.get(0);
Point p = this.map.getPointFromField(f).getPoint();
int lx = p.x;
int ly = p.y;
g.drawLine(lx - 25, ly - 25, lx + 25, ly + 25);
g.drawLine(lx + 25, ly - 25, lx - 25, ly + 25);
}
}
@Override
public void pauseOrContinue() {
this.paused = !this.paused;
}
}
| gpl-3.0 |
ijlalhussain/LogGenerator | DeclareDesigner/src/nl/tue/declare/domain/Base.java | 1634 | /* Generated by Together */
package nl.tue.declare.domain;
import java.util.*;
public class Base
implements Cloneable {
private int id = 0;
protected void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
/**
* Base
*
* @param aId int
*/
public Base(int aId) {
id = aId;
}
/**
*
* @param aBase Base
*/
public Base(Base aBase) {
this(aBase.getId());
}
/**
* getIdString
*
* @return String
*/
public String getIdString() {
return Integer.toString(id);
}
/**
* equals
*
* @param anObject Object
* @return boolean
*/
public boolean equals(Object anObject) {
boolean eql = false;
if (anObject != null) {
if (anObject instanceof Base) {
eql = ( ( (Base) anObject).getId() == this.getId());
}
}
return eql;
}
/**
*
* @return int
*/
public int hashCode() {
int hash = 7;
int var_code = this.getId();
hash = 31 * hash + var_code;
return hash;
}
/**
*
* @return Base
*/
protected Base newInstance() {
return new Base(id);
}
/**
*
*/
protected void cloneAttributes() {
}
/**
* clone
*/
public Object clone() {
Base myClone = newInstance();
cloneAttributes();
return myClone;
}
public static int nextId(List<Base> list) {
if (list == null) {
return -1;
}
int id = 0;
Iterator<Base> it = list.iterator();
while (it.hasNext()) {
Base base = it.next();
if (id < base.getId()) {
id = base.getId();
}
}
return++id;
}
}
| gpl-3.0 |
lausek/brainfaq | src/eu/lausek/brainfaq/Main.java | 716 | package eu.lausek.brainfaq;
import java.io.*;
/**
*
* @author lausek
*
*/
public class Main {
public static void main(String[] args) {
Program program = null;
String path = null;
if (args.length == 0) {
Logger.error("No file specified");
}
path = args[0];
try {
Logger.log("Loading '" + path + "'");
program = new Program(path);
} catch (FileNotFoundException e) {
Logger.error("Couldn't locate file '" + path + "'");
} catch (IOException e) {
Logger.error("Cannot work with file '" + path + "'");
}
try {
program.execute();
} catch (IOException e) {
Logger.error("Error while reading input from user");
}
}
}
| gpl-3.0 |
Humbertda/TP-AG51 | src/test/java/com/humbertdany/tpproject/test/TestBinaryStack.java | 2351 | package com.humbertdany.tpproject.test;
import com.humbertdany.tpproject.util.binarystack.v1.BinaryStack;
import com.humbertdany.tpproject.util.binarystack.v1.Node;
import com.humbertdany.tpproject.util.binarystack.v2.TasBinaire;
import com.humbertdany.tpproject.util.factory.ArrayFactory;
import java.util.Arrays;
/**
*
* @author dhumbert
*/
public class TestBinaryStack extends ATest {
public TestBinaryStack(){
}
final private ArrayFactory<Ni> nArrayFactory = new ArrayFactory<Ni>() {
@Override
public Ni[] buildArray(int dimension) {
return new Ni[dimension];
}
};
final public void launch(){
// Test v1
final Ni root = new Ni(1);
final Ni n1 = new Ni(50);
final Ni n2 = new Ni(4);
final Ni n3 = new Ni(2);
final Ni n4 = new Ni(5);
final BinaryStack<Ni> l1 = new BinaryStack<>(nArrayFactory, root);
l1.add(root, n1, BinaryStack.ORIENTATION_LEFT);
l1.add(root, n2, BinaryStack.ORIENTATION_RIGHT);
l1.add(n2, n3, BinaryStack.ORIENTATION_LEFT);
l1.add(n2, n4, BinaryStack.ORIENTATION_RIGHT);
log(l1.contains(new Ni(50)));
log(l1.contains(new Ni(4)));
log(l1.contains(new Ni(55)));
l1.printInOrder();
l1.printPostOrder();
// Test v2
final TasBinaire<N> h = new TasBinaire<>(new ArrayFactory<N>() {
@Override
public N[] buildArray(int dimension) {
return new N[dimension];
}
});
h.insertAll(new N("p"), new N("r"), new N("i"), new N("a"), new N("o"));
h.insert(new N("r"));
log("Binary Stack stocked : \n " + h);
h.deleteMin();
log("Binary Stack state after deletion of min : \n " + h);
final Ni[] a = {new Ni(4), new Ni(7), new Ni(7), new Ni(7), new Ni(5), new Ni(0), new Ni(2), new Ni(3), new Ni(5), new Ni(1)};
log("Array given to sort \n " + descArray(a));
TasBinaire<Ni> tmp = new TasBinaire<>(new ArrayFactory<Ni>() {
@Override
public Ni[] buildArray(int dimension) {
return new Ni[dimension];
}
});
tmp.heapSort(a);
log("The last array sorted : \n " + descArray(a));
}
private class N extends Node<String> {
N(final String n){
super(n);
}
}
private class Ni extends Node<Integer> {
Ni(final Integer n){
super(n);
}
}
private String descArray(final Ni[] array){
return Arrays.toString(array);
}
}
| gpl-3.0 |
lhebj/provence | src/com/provence/web/dto/NewsInfoDTO.java | 830 | package com.provence.web.dto;
public class NewsInfoDTO {
private Long idNsi;
private String titleNsi;
private String contentNsi;
private String path;
private String dateCreateNsi;
public Long getIdNsi() {
return idNsi;
}
public void setIdNsi(Long idNsi) {
this.idNsi = idNsi;
}
public String getTitleNsi() {
return titleNsi;
}
public void setTitleNsi(String titleNsi) {
this.titleNsi = titleNsi;
}
public String getContentNsi() {
return contentNsi;
}
public void setContentNsi(String contentNsi) {
this.contentNsi = contentNsi;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getDateCreateNsi() {
return dateCreateNsi;
}
public void setDateCreateNsi(String dateCreateNsi) {
this.dateCreateNsi = dateCreateNsi;
}
}
| gpl-3.0 |
wwu-pi/muggl | muggl-core/src/de/wwu/muggl/instructions/bytecode/Athrow.java | 5780 | package de.wwu.muggl.instructions.bytecode;
import java.util.Stack;
import de.wwu.muggl.instructions.interfaces.Instruction;
import de.wwu.muggl.vm.Frame;
import de.wwu.muggl.vm.classfile.ClassFile;
import de.wwu.muggl.vm.exceptions.ExceptionHandler;
import de.wwu.muggl.vm.exceptions.NoExceptionHandlerFoundException;
import de.wwu.muggl.vm.exceptions.VmRuntimeException;
import de.wwu.muggl.vm.execution.ExecutionException;
import de.wwu.muggl.vm.impl.symbolic.SymbolicExecutionException;
import de.wwu.muggl.vm.impl.symbolic.exceptions.SymbolicExceptionHandler;
import de.wwu.muggl.vm.initialization.Objectref;
/**
* Implementation of the instruction <code>athrow</code>.<br />
* <br />
* Please note that athrow is a special instruction. While it always leads to an interruption in the
* program flow, it does NOT implement the interface JumpAlways as there is no jump target (pc) that
* can be determined at compile time. However, it implements JumpException even though the throwing
* of an exception at executing it is not optional but obligatory.<br />
* <br />
* If the flow through a program is analyzed, special handling of this instruction is needed.
*
* @author Tim Majchrzak
* @version 1.0.0, 2010-03-10
*/
public class Athrow extends de.wwu.muggl.instructions.general.AthrowAbstract implements Instruction {
/**
* Execute the instruction.
* @param frame The currently executed frame.
* @throws ExecutionException Thrown in case of fatal problems during the execution.
*/
@Override
public void execute(Frame frame) throws ExecutionException {
try {
Stack<Object> stack = frame.getOperandStack();
Objectref objectref = (Objectref) stack.pop();
// Runtime exception: objectref is null.
if (objectref == null)
throw new VmRuntimeException(frame.getVm().generateExc("java.lang.NullPointerException"));
// Synchronized?
ifSynchronizedExitMonitor(frame);
// Handle the exception.
ExceptionHandler handler = new ExceptionHandler(frame, objectref);
handler.handleException();
} catch (VmRuntimeException e) {
ExceptionHandler handler = new ExceptionHandler(frame, e);
try {
handler.handleException();
} catch (ExecutionException e2) {
executionFailed(e2);
}
} catch (ExecutionException e) {
executionFailed(e);
}
}
/**
* Execute the instruction symbolically.
* @param frame The currently executed frame.
* @throws NoExceptionHandlerFoundException If no handler could be found.
* @throws SymbolicExecutionException Thrown in case of fatal problems during the symbolic execution.
*/
@Override
public void executeSymbolically(Frame frame) throws NoExceptionHandlerFoundException, SymbolicExecutionException {
try {
Stack<Object> stack = frame.getOperandStack();
Objectref objectref = (Objectref) stack.pop();
// Runtime exception: objectref is null.
if (objectref == null)
throw new VmRuntimeException(frame.getVm().generateExc("java.lang.NullPointerException"));
// Synchronized?
ifSynchronizedExitMonitor(frame);
// Handle the exception.
SymbolicExceptionHandler handler = new SymbolicExceptionHandler(frame, objectref);
handler.handleException();
} catch (VmRuntimeException e) {
SymbolicExceptionHandler handler = new SymbolicExceptionHandler(frame, e);
try {
handler.handleException();
} catch (ExecutionException e2) {
executionFailedSymbolically(e2);
}
} catch (ExecutionException e) {
executionFailedSymbolically(e);
}
}
/**
* Resolve the instructions name.
* @return The instructions name as a String.
*/
@Override
public String getName() {
return "athrow";
}
/**
* Get the thrown exception types as fully qualified java names.
* @return The thrown exception types.
*/
public String[] getThrownExceptionTypes() {
String[] exceptionTypes = {};
return exceptionTypes;
}
/**
* Get the number of elements that will be popped from the stack when this instruction is
* executed.
*
* @return The number of elements that will be popped from the stack.
*/
public int getNumberOfPoppedElements() {
return 1;
}
/**
* Get the type of elements this instruction will push onto the stack.
*
* @param methodClassFile The class file of the method this instruction belongs to.
* @return The type this instruction pushes. Types are {@link ClassFile#T_BOOLEAN},
* {@link ClassFile#T_BYTE} {@link ClassFile#T_CHAR}, {@link ClassFile#T_DOUBLE},
* {@link ClassFile#T_FLOAT}, {@link ClassFile#T_INT}, {@link ClassFile#T_LONG} and
* {@link ClassFile#T_SHORT}, 0 to indicate a reference or return address type or -1 to
* indicate the pushed type cannot be determined statically.
*/
public byte getTypePushed(ClassFile methodClassFile) {
return 0;
}
/**
* Get the types of elements this instruction will pop from the stack.
*
* @param methodClassFile The class file of the method this instruction belongs to.
* @return The types this instruction pops. The length of the arrays reflects the number of
* elements pushed in the order they are pushed. Types are {@link ClassFile#T_BOOLEAN},
* {@link ClassFile#T_BYTE} {@link ClassFile#T_CHAR}, {@link ClassFile#T_DOUBLE},
* {@link ClassFile#T_FLOAT}, {@link ClassFile#T_INT}, {@link ClassFile#T_LONG} and
* {@link ClassFile#T_SHORT}, 0 to indicate a reference or return address type or -1 to
* indicate the popped type cannot be determined statically.
*/
public byte[] getTypesPopped(ClassFile methodClassFile) {
byte[] types = {0};
return types;
}
}
| gpl-3.0 |
thegedge/opgraph | common-nodes/src/main/java/ca/gedge/opgraph/nodes/general/script/OutputFields.java | 1854 | /*
* Copyright (C) 2012 Jason Gedge <http://www.gedge.ca>
*
* This file is part of the OpGraph project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
*/
package ca.gedge.opgraph.nodes.general.script;
import java.util.ArrayList;
import ca.gedge.opgraph.OpNode;
import ca.gedge.opgraph.OutputField;
/**
* Wrapper for an {@link ArrayList} of {@link OutputField}s to simplify adding
* output fields from a script.
*/
public class OutputFields extends ArrayList<OutputField> {
/** The node which this class will add output fields to */
private OpNode node;
/**
* Constructs an output fields collection which adds output fields to a
* given node.
*
* @param node the node to add input fields to
*/
public OutputFields(OpNode node) {
this.node = node;
}
/**
* Adds an output descriptor with a key, output type, and description.
*
* @param key the reference key
* @param description a description for the field
* @param isFixed whether or not this field is fixed
* @param outputType the type of object this field outputs
*/
public void add(String key, String description, boolean isFixed, Class<?> outputType) {
node.putField(new OutputField(key, description, isFixed, outputType));
}
}
| gpl-3.0 |
nipanga/learn-validusername | validusername/src/main/java/com/learn/springboot/validusername/strategies/impl/RandomSuggestionSuggestedWordsStrategy.java | 688 | package com.learn.springboot.validusername.strategies.impl;
import java.util.Arrays;
import java.util.Collection;
import com.learn.springboot.validusername.strategies.SuggestedWordsStrategy;
/**
*
* @author felipe
*
*/
public class RandomSuggestionSuggestedWordsStrategy implements SuggestedWordsStrategy {
/**
* Suggests a list of mocked words
*
* @return a list of mocked words
*/
@Override
public Collection<String> getWords() {
return Arrays.asList("user");
}
/**
* Suggests a mock word
*
* @return a mocked word
*/
@Override
public String getWord(String input) {
return "user";
}
}
| gpl-3.0 |
open-keychain/open-keychain | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/keyimport/processing/ImportKeysListener.java | 1041 | /*
* Copyright (C) 2017 Schürmann & Breitmoser GbR
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sufficientlysecure.keychain.keyimport.processing;
import org.sufficientlysecure.keychain.keyimport.ImportKeysListEntry;
import java.util.List;
public interface ImportKeysListener extends ImportKeysResultListener {
void loadKeys(LoaderState loaderState);
void importKeys(List<ImportKeysListEntry> entries);
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | frameworks/base/services/core/java/com/android/server/net/DelayedDiskWrite.java | 2931 | /*
* Copyright (C) 2014 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.android.server.net;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class DelayedDiskWrite {
private HandlerThread mDiskWriteHandlerThread;
private Handler mDiskWriteHandler;
/* Tracks multiple writes on the same thread */
private int mWriteSequence = 0;
private final String TAG = "DelayedDiskWrite";
public interface Writer {
public void onWriteCalled(DataOutputStream out) throws IOException;
}
public void write(final String filePath, final Writer w) {
if (TextUtils.isEmpty(filePath)) {
throw new IllegalArgumentException("empty file path");
}
/* Do a delayed write to disk on a separate handler thread */
synchronized (this) {
if (++mWriteSequence == 1) {
mDiskWriteHandlerThread = new HandlerThread("DelayedDiskWriteThread");
mDiskWriteHandlerThread.start();
mDiskWriteHandler = new Handler(mDiskWriteHandlerThread.getLooper());
}
}
mDiskWriteHandler.post(new Runnable() {
@Override
public void run() {
doWrite(filePath, w);
}
});
}
private void doWrite(String filePath, Writer w) {
DataOutputStream out = null;
try {
out = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(filePath)));
w.onWriteCalled(out);
} catch (IOException e) {
loge("Error writing data file " + filePath);
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {}
}
// Quit if no more writes sent
synchronized (this) {
if (--mWriteSequence == 0) {
mDiskWriteHandler.getLooper().quit();
mDiskWriteHandler = null;
mDiskWriteHandlerThread = null;
}
}
}
}
private void loge(String s) {
Log.e(TAG, s);
}
}
| gpl-3.0 |
tassadar2002/ouser | src/com/ouser/logic/ChatLogic.java | 16690 | package com.ouser.logic;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import com.ouser.cache.Cache;
import com.ouser.event.EventArgs;
import com.ouser.event.EventCenter;
import com.ouser.event.EventId;
import com.ouser.event.EventListener;
import com.ouser.logic.event.AppointEventArgs;
import com.ouser.logic.event.ChatMessageEventArgs;
import com.ouser.logic.event.ChatMessagesEventArgs;
import com.ouser.logic.event.ListMessagesEventArgs;
import com.ouser.logic.event.OusersEventArgs;
import com.ouser.module.AppointId;
import com.ouser.module.ChatId;
import com.ouser.module.ChatMessage;
import com.ouser.module.ListMessage;
import com.ouser.module.Location;
import com.ouser.module.Ouser;
import com.ouser.module.Ousers;
import com.ouser.persistor.PersistorManager;
import com.ouser.protocol.GetGroupMessageProcess;
import com.ouser.protocol.GetListMessageProcess;
import com.ouser.protocol.GetMessageBaseProcess;
import com.ouser.protocol.GetSingleMessageProcess;
import com.ouser.protocol.RemoveGroupMessagesProcess;
import com.ouser.protocol.RemoveSingleMessagesProcess;
import com.ouser.protocol.ResponseListener;
import com.ouser.protocol.SendGroupMessageProcess;
import com.ouser.protocol.SendMessageBaseProcess;
import com.ouser.protocol.SendSingleMessageProcess;
import com.ouser.pusher.Pusher;
import com.ouser.pusher.PusherManager;
import com.ouser.stat.Stat;
import com.ouser.stat.StatId;
import com.ouser.util.Const;
import com.ouser.util.FileUtil;
import com.ouser.util.ImageUtil;
import com.ouser.util.MutablePair;
import com.ouser.util.StringUtil;
public class ChatLogic extends BaseLogic {
static class Factory implements BaseLogic.Factory {
@Override
public BaseLogic create() {
return new ChatLogic();
}
}
ChatLogic() {
}
/**
* 获得我的消息列表中所有消息,会从服务器拉取
*/
public void getMyMessageFromRemote(final EventListener listener) {
final GetListMessageProcess process = new GetListMessageProcess();
process.setMyUid(Cache.self().getMyUid());
process.run(new ResponseListener() {
@Override
public void onResponse(String requestId) {
OperErrorCode errCode = Util.convertFromStatus(process.getStatus());
if (errCode == OperErrorCode.Success) {
saveMyMessage(process.getResult(), listener);
} else {
fireEvent(listener, new ListMessagesEventArgs(errCode));
}
}
});
}
/**
* 获得我的消息列表中所有消息,仅从本地获得
*
* @return
*/
public void getMyMessageFromLocal(final EventListener listener) {
List<ListMessage> messages = PersistorManager.self().getListMessages(
Cache.self().getMyUid());
continueGetMyMessage(messages, listener);
}
/**
* 保存我的消息
* @param messages
* @param listener
*/
private void saveMyMessage(final List<ListMessage> messages, final EventListener listener) {
new AsyncTask<Void, Void, Void>() {
private List<ListMessage> mMessages = null;
@Override
protected Void doInBackground(Void... params) {
PersistorManager.self().addListMessage(Cache.self().getMyUid(), messages);
mMessages = PersistorManager.self().getListMessages(Cache.self().getMyUid());
return null;
}
@Override
protected void onPostExecute(Void result) {
continueGetMyMessage(mMessages, listener);
}
}.execute();
}
/**
* 继续获取每条消息中的藕丝信息
* @param messages
* @param listener
*/
private void continueGetMyMessage(final List<ListMessage> messages, final EventListener listener) {
List<String> uids = new ArrayList<String>();
for (ListMessage message : messages) {
String uid = message.getOuser().getUid();
if(!uids.contains(uid)) {
uids.add(uid);
}
}
LogicFactory.self().getProfile().getSimples(uids, new EventListener() {
@Override
public void onEvent(EventId id, EventArgs args) {
OusersEventArgs ousersArgs = (OusersEventArgs) args;
OperErrorCode errCode = ousersArgs.getErrCode();
Ousers ousers = ousersArgs.getOusers();
ListMessagesEventArgs messageArgs = null;
if (errCode == OperErrorCode.Success) {
for (ListMessage message : messages) {
for (Ouser ouser : ousers) {
if (message.getOuser().isSame(ouser)) {
message.setOuser(ouser);
break;
}
}
}
messageArgs = new ListMessagesEventArgs(messages);
} else {
messageArgs = new ListMessagesEventArgs(errCode);
}
fireEvent(listener, messageArgs);
}
});
}
/**
* 删除我的消息列表中的某项,仅从本地删除
*
* @param chatId
*/
public void removeMyMessage(ListMessage message) {
PersistorManager.self().removeListMessage(Cache.self().getMyUid(), message.getChatId());
}
/**
* 删除我的所有未读消息,从服务器上删除
* @param listener
*/
public void removeMyMessages(final EventListener listener) {
List<ListMessage> messages = PersistorManager.self().getListMessages(
Cache.self().getMyUid());
List<String> singleUids = new ArrayList<String>();
List<AppointId> appointIds = new ArrayList<AppointId>();
for(ListMessage message : messages) {
if(message.isSingle()) {
singleUids.add(message.getChatId().getSingleId());
} else {
appointIds.add(message.getChatId().getGroupId());
}
}
final MutablePair<Boolean, Boolean> completeFlag = MutablePair.create(false, false);
final RemoveSingleMessagesProcess singleProcess = new RemoveSingleMessagesProcess();
singleProcess.setMyUid(Cache.self().getMyUid());
singleProcess.setTargetUids(singleUids);
singleProcess.run(new ResponseListener() {
@Override
public void onResponse(String requestId) {
// 不关注返回值
completeFlag.first = true;
if(completeFlag.first && completeFlag.second) {
PersistorManager.self().clearListMessagesUnreadCount(Cache.self().getMyUid());
fireStatusEvent(listener, OperErrorCode.Success);
}
}
});
final RemoveGroupMessagesProcess groupProcess = new RemoveGroupMessagesProcess();
groupProcess.setMyUid(Cache.self().getMyUid());
groupProcess.setTargetAppointIds(appointIds);
groupProcess.run(new ResponseListener() {
@Override
public void onResponse(String requestId) {
// 不关注返回值
completeFlag.second = true;
if(completeFlag.first && completeFlag.second) {
PersistorManager.self().clearListMessagesUnreadCount(Cache.self().getMyUid());
fireStatusEvent(listener, OperErrorCode.Success);
}
}
});
}
/**
* 开始聊天
*
* @param chatId
* @return
*/
public ChatHandler startChat(ChatId chatId) {
ChatHandler handler = new ChatHandler(chatId);
handler.startChat();
return handler;
}
private void getChatMessageOuser(final List<ChatMessage> messages, final EventListener listener) {
List<String> uids = new ArrayList<String>();
for(ChatMessage message : messages) {
String uid = message.getOuser().getUid();
if(!uids.contains(uid)) {
uids.add(uid);
}
}
LogicFactory.self().getProfile().getSimples(uids, new EventListener() {
@Override
public void onEvent(EventId id, EventArgs args) {
OusersEventArgs ousersArgs = (OusersEventArgs) args;
OperErrorCode errCode = ousersArgs.getErrCode();
Ousers ousers = ousersArgs.getOusers();
ChatMessagesEventArgs messageArgs = null;
if (errCode == OperErrorCode.Success) {
for (ChatMessage message : messages) {
for (Ouser ouser : ousers) {
if (message.getOuser().isSame(ouser)) {
message.setOuser(ouser);
break;
}
}
}
messageArgs = new ChatMessagesEventArgs(messages);
} else {
messageArgs = new ChatMessagesEventArgs(errCode);
}
fireEvent(listener, messageArgs);
}
});
}
/**
* 消息处理器
*
* @author hanlixin
* @remark 开启聊天界面使用
*/
public class ChatHandler {
/** 消息id */
private ChatId mChatId = null;
/** 最后一条消息 */
private ChatMessage mLastChatMessage = null;
/** 服务器消息推送器 */
private ChatMessagePusher mChatMessagePusher = null;
private String mCacheAppointContent = "";
private EventListener mListener = new EventListener() {
@Override
public void onEvent(EventId id, EventArgs args) {
ChatMessagesEventArgs chatArgs = (ChatMessagesEventArgs) args;
List<ChatMessage> messages = chatArgs.getChatMessages();
if (!messages.isEmpty()) {
mLastChatMessage = messages.get(messages.size() - 1);
}
}
};
public ChatHandler(ChatId chatId) {
mChatId = chatId;
}
public void startChat() {
// 设置消息推送监听器
mChatMessagePusher = new ChatMessagePusher(mChatId);
// 监听消息推送
PusherManager.self().startListen(mChatMessagePusher, "chat", Const.MessageChatInterval,
true);
// 关注推送事件,获取最后一条消息
EventCenter.self().addListener(EventId.ePushMessage, mListener);
}
public void stopChat() {
// 停止监听消息推送
PusherManager.self().stopListen("chat");
mChatMessagePusher = null;
// 设置列表消息中的最后一条消息
if (mLastChatMessage != null) {
saveLastListMessage();
} else {
PersistorManager.self().clearListMessageUnreadCount(Cache.self().getMyUid(),
mChatId);
}
// 取消关注推送事件
EventCenter.self().removeListener(mListener);
}
public void setCacheAppointContent(String value) {
mCacheAppointContent = value;
}
public void getAllMessage(final EventListener listener) {
final List<ChatMessage> messages =
PersistorManager.self().getChatMessages(Cache.self().getMyUid(), mChatId);
new ChatLogic().getChatMessageOuser(messages, listener);
}
public void removeMessage(List<ChatMessage> messages) {
// TODO 查找ChatMessage,如果没有了的话删除ListMessage的消息
PersistorManager.self().removeChatMessage(messages);
}
public void clearMessage() {
// TODO 删除ListMessage的消息
PersistorManager.self().clearChatMessage(Cache.self().getMyUid(), mChatId);
}
public ChatMessage sendText(String text) {
ChatMessage message = new ChatMessage();
message.setContent(text);
message.setType(ChatMessage.Type.Text);
send(message);
Stat.onEvent(mChatId.isSingle() ? StatId.SingleChatText : StatId.GroupChatText);
return message;
}
public ChatMessage sendImage(Bitmap image) {
ChatMessage message = new ChatMessage();
message.setContent(ImageUtil.toBase64(image));
message.setType(ChatMessage.Type.Image);
send(message);
Stat.onEvent(mChatId.isSingle() ? StatId.SingleChatImage : StatId.GroupChatImage);
return message;
}
public ChatMessage sendAudio(String fileName) {
ChatMessage message = new ChatMessage();
message.setContent(FileUtil.toBase64(fileName));
message.setType(ChatMessage.Type.Audio);
send(message);
Stat.onEvent(mChatId.isSingle() ? StatId.SingleChatVoice : StatId.GroupChatVoice);
return message;
}
public ChatMessage sendLocation(Location location, String place) {
ChatMessage message = new ChatMessage();
message.getLocation().setLocation(location);
message.getLocation().setPlace(place);
message.setType(ChatMessage.Type.Location);
send(message);
Stat.onEvent(mChatId.isSingle() ? StatId.SingleChatLocation : StatId.GroupChatLocation);
return message;
}
private void send(final ChatMessage message) {
message.setChatId(mChatId);
message.setTime(System.currentTimeMillis());
message.getOuser().setUid(Cache.self().getMyUid());
message.setSend(true);
PersistorManager.self().appendMessage(Cache.self().getMyUid(), message);
// 设置最后一条消息
mLastChatMessage = message;
SendMessageBaseProcess process = null;
if (mChatId.isSingle()) {
process = new SendSingleMessageProcess();
} else {
process = new SendGroupMessageProcess();
}
process.setMyUid(Cache.self().getMyUid());
process.setMessage(message);
final SendMessageBaseProcess fProcess = process;
fProcess.run(new ResponseListener() {
@Override
public void onResponse(String requestId) {
OperErrorCode errCode = Util.convertFromStatus(fProcess.getStatus());
ChatMessageEventArgs args = null;
if (errCode == OperErrorCode.Success) {
args = new ChatMessageEventArgs(message);
} else {
args = new ChatMessageEventArgs(errCode);
}
fireEvent(EventId.eSendMessage, args);
}
});
}
private void saveLastListMessage() {
ListMessage listMessage = new ListMessage();
listMessage.setChatId(mChatId);
listMessage.setContent(convertMessageContent(mLastChatMessage));
listMessage.setCount(0);
listMessage.setTime((int) (mLastChatMessage.getTime() / 1000));
if (!listMessage.isSingle()) {
// 设置友约内容
ListMessage message = PersistorManager.self().getListMessage(
Cache.self().getMyUid(), mChatId);
if (message == null) {
// 还没有进行保存
if (StringUtil.isEmpty(mCacheAppointContent)) {
AppointId appointId = mLastChatMessage.getChatId().getGroupId();
LogicFactory.self().getAppointInfo().get(appointId, new EventListener() {
@Override
public void onEvent(EventId id, EventArgs args) {
AppointEventArgs appointArgs = (AppointEventArgs) args;
if (appointArgs.getErrCode() == OperErrorCode.Success) {
if (!appointArgs.getAppoint().isDeleted()) {
PersistorManager.self()
.setListMessageLastMessageAppointContent(
Cache.self().getMyUid(), mChatId,
appointArgs.getAppoint().getContent());
fireEvent(EventId.eMessageListChanged, new EventArgs());
}
}
}
});
} else {
listMessage.getAppoint().setContent(mCacheAppointContent);
}
} else {
// 已经保存过,不必设置了,数据库不会更新友约名
}
}
// 最后说话人
String saveUid = "";
if (listMessage.isSingle()) {
saveUid = mChatId.getSingleId();
} else {
saveUid = mLastChatMessage.getOuser().getUid();
}
listMessage.getOuser().setUid(saveUid);
// 保存
PersistorManager.self().setListMessageLastMessage(Cache.self().getMyUid(), listMessage);
fireEvent(EventId.eMessageListChanged, new EventArgs());
}
private String convertMessageContent(ChatMessage message) {
switch (message.getType()) {
case Text:
return message.getContent();
case Image:
return "[图片信息]";
case Location:
return "[位置信息]";
case Audio:
return "[语音信息]";
case Invite:
return "[友约邀请]";
default:
return message.getContent();
}
}
}
private static class ChatMessagePusher implements Pusher {
private ChatId mChatId = null;
public ChatMessagePusher(ChatId value) {
mChatId = value;
}
@Override
public void onRequest() {
GetMessageBaseProcess process = null;
if (mChatId.isSingle()) {
GetSingleMessageProcess sProcess = new GetSingleMessageProcess();
sProcess.setTargetUid(mChatId.getSingleId());
process = sProcess;
} else {
GetGroupMessageProcess gProcess = new GetGroupMessageProcess();
gProcess.setAppointId(mChatId.getGroupId());
process = gProcess;
}
process.setMyUid(Cache.self().getMyUid());
final GetMessageBaseProcess fProcess = process;
fProcess.run(new ResponseListener() {
@Override
public void onResponse(String requestId) {
OperErrorCode errCode = Util.convertFromStatus(fProcess.getStatus());
if (errCode != OperErrorCode.Success) {
return;
}
List<ChatMessage> messages = fProcess.getResult();
if (messages.isEmpty()) {
return;
}
PersistorManager.self().appendMessages(Cache.self().getMyUid(), messages);
new ChatLogic().getChatMessageOuser(messages, new EventListener() {
@Override
public void onEvent(EventId id, EventArgs args) {
EventCenter.self().fireEvent(EventId.ePushMessage, args);
}
});
}
});
}
}
}
| gpl-3.0 |
shadowmage45/AncientWarfare2 | src/main/java/net/shadowmage/ancientwarfare/vehicle/registry/package-info.java | 256 | // Auto generated package-info by MCP
@ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault
package net.shadowmage.ancientwarfare.vehicle.registry;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
| gpl-3.0 |
oyekunlei/spacecard | src/java/com/spacecard/dao/ImageDAO.java | 1685 | /*
* 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 com.spacecard.dao;
import com.spacecard.image.Image;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
/**
*
* @author user
*/
public class ImageDAO extends DatabaseConnector
{
public Vector<Image> getImages() throws SQLException
{
String sql = "SELECT * FROM image";
ResultSet rs = statement.executeQuery(sql);
Vector<Image> images = new Vector<Image>();
while(rs.next())
{
images.add(new Image(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)));
}
return images;
}
public Vector<Image> getImages(String category) throws SQLException
{
String sql = "SELECT * FROM image WHERE category = '"+category+"'";
ResultSet rs = statement.executeQuery(sql);
Vector<Image> images = new Vector<Image>();
while(rs.next())
{
images.add(new Image(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)));
}
return images;
}
public Image getImage(int imageId) throws SQLException
{
String sql = "SELECT * FROM image WHERE imageId = '"+imageId+"'";
ResultSet rs = statement.executeQuery(sql);
Image image = new Image();
while(rs.next())
{
image = new Image(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4));
}
return image;
}
}
| gpl-3.0 |
opf-labs/ots-schema | src/edu/harvard/hul/ois/ots/schemas/pds/PdsDate.java | 2400 | /*
* Copyright 2010 Harvard University Library
*
* This file is part of OTS-Schemas.
*
* OTS-Schemas 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.
*
* OTS-Schemas 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 OTS-Schemas. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.harvard.hul.ois.ots.schemas.pds;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PdsDate {
private static Pattern schemaDate = Pattern.compile("\\d{4}-\\d{2}-\\d{2}(Z??|((\\+|-)\\d{2}:\\d{2}))");
private static Pattern pdsDate1 = Pattern.compile("\\d{4}");
private static Pattern pdsDate2 = Pattern.compile("\\d{4}-\\d{2}");
private static Pattern pdsDate3 = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
private String fromDate;
private String toDate;
public PdsDate() { }
public PdsDate(String fromDate, String toDate) throws PdsDateException {
setFromDate(fromDate);
setToDate(toDate);
}
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) throws PdsDateException {
if(isValid(fromDate)) {
this.fromDate = fromDate;
}
else {
throw new PdsDateException(fromDate);
}
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) throws PdsDateException {
if(isValid(toDate)) {
this.toDate = toDate;
}
else {
throw new PdsDateException(toDate);
}
}
/**
* Check if the input string matches any of the valid PREMIS date regular expressions
* @param dateString
* @return boolean
*/
public boolean isValid(String dateString) {
Matcher m = schemaDate.matcher(dateString);
if(m.matches()) {
return true;
}
m = pdsDate1.matcher(dateString);
if(m.matches()) {
return true;
}
m = pdsDate2.matcher(dateString);
if(m.matches()) {
return true;
}
m = pdsDate3.matcher(dateString);
if(m.matches()) {
return true;
}
return false;
}
}
| gpl-3.0 |
Trumeet/MiPushFramework | common/src/main/java/top/trumeet/common/event/type/NotificationType.java | 1578 | package top.trumeet.common.event.type;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import top.trumeet.common.R;
import top.trumeet.common.event.Event;
/**
* 对应 {@link top.trumeet.common.event.Event.Type#SendMessage}
*
* Created by Trumeet on 2018/2/7.
*/
public class NotificationType extends EventType {
private final String mNotificationTitle;
private final String mNotificationDetail;
public NotificationType(String mInfo, String pkg, String mNotificationTitle, String mNotificationDetail) {
super(Event.Type.Notification, mInfo, pkg);
this.mNotificationTitle = mNotificationTitle;
this.mNotificationDetail = mNotificationDetail;
}
@Override
@NonNull
public CharSequence getTitle (Context context) {
return mNotificationTitle == null ? super.getTitle(context) :
mNotificationTitle;
}
@Nullable
@Override
public CharSequence getSummary(Context context) {
return mNotificationDetail == null ? context.getString(R.string.event_push) :
mNotificationDetail;
}
public String getNotificationTitle() {
return mNotificationTitle;
}
public String getNotificationDetail() {
return mNotificationDetail;
}
@NonNull
@Override
public Event fillEvent (@NonNull Event original) {
original.setNotificationTitle(mNotificationTitle);
original.setNotificationSummary(mNotificationDetail);
return original;
}
}
| gpl-3.0 |
jacob-novosad/eHacks_2017_SIUEMAP | ClassMap2/src/classmap/ClassMap.java | 7547 | /*
* 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 classmap;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
/**
*
* @author Jacob
*/
public class ClassMap extends Application {
@Override
public void start(Stage primaryStage) throws FileNotFoundException {
// Makes a grid pane, good for multiple "slots"
GridPane gridPane = new GridPane();
//Tempory testing images
// Image building1Floor0 = new Image(new FileInputStream("peckHall0.png"));
// Image building1Floor1 = new Image(new FileInputStream("peckHall1.png"));
// Image building1Floor2 = new Image(new FileInputStream("peckHall2.png"));
// Image building1Floor3 = new Image(new FileInputStream("peckHall3.png"));
Image campus = new Image(new FileInputStream("campusMap.png"));
/***************************************
* Building 1 floor plan images
**************************************/
Image building1Floor0 = new Image(new FileInputStream("building1Floor0.png"));
Image building1Floor1 = new Image(new FileInputStream("building1Floor1.png"));
Image building1Floor2 = new Image(new FileInputStream("building1Floor2.png"));
Image building1Floor3 = new Image(new FileInputStream("building1Floor3.png"));
/**********************************************
* Possible building 2 floor plan images
**********************************************/
Image building2Floor0 = new Image(new FileInputStream("building2Floor0.png"));
Image building2Floor1 = new Image(new FileInputStream("building2Floor1.png"));
Image building2Floor2 = new Image(new FileInputStream("building2Floor2.png"));
Image building2Floor3 = new Image(new FileInputStream("building2Floor3.png"));
/***************************************************
* ImageView allows us to display an image and it
* takes an image, we will be updating this with
* new images with object.setImage with button press
***************************************************/
ImageView floor0 = new ImageView(building1Floor0);
//ImageView floor1 = new ImageView(peck1);
// ImageView floor2 = new ImageView(peck2);
// ImageView floor3 = new ImageView(peck3);
// Ratio variables used mostly for testing, but allows me to stretch/shrink
int heightWidthRatio = 600;
int widthRatio = 1200;
// Keeps the image height and width ratio change the same (like pulling on the corner of an image
floor0.setPreserveRatio(true);
floor0.setFitHeight(heightWidthRatio);
floor0.setFitWidth(widthRatio);
/*********************** Buttons ****************************/
Button campusMap = new Button("Campus Map");
Button floor0Button = new Button("B1 Basement");
Button floor1Button = new Button("B1 Floor 1");
Button floor2Button = new Button("B1 Floor 2");
Button floor3Button = new Button("B1 Floor 3");
Button floor0Button2 = new Button("B2 Basement");
Button floor1Button2 = new Button("B2 Floor 1");
Button floor2Button2 = new Button("B2 Floor 2");
Button floor3Button2 = new Button("B2 Floor 3");
// Adds default ImageView to the gridpane in column 0 row 1
gridPane.add(floor0,0,2);
// Button Triggers
floor0Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
floor0.setImage(building1Floor0);
}
});
floor1Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
floor0.setImage(building1Floor1);
}
});
floor2Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
floor0.setImage(building1Floor2);
}
});
floor3Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
floor0.setImage(building1Floor3);
}
});
floor0Button2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
floor0.setImage(building2Floor0);
}
});
floor1Button2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
floor0.setImage(building2Floor1);
}
});
floor2Button2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
floor0.setImage(building2Floor2);
}
});
floor3Button2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
floor0.setImage(building2Floor3);
}
});
campusMap.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
floor0.setImage(campus);
}
});
// Putting a frame inside the gridPane to group all my buttons together in an easy fashion
HBox hBox = new HBox();
Text title = new Text("SIUE Class Finder");
title.setFont(Font.font ("Verdana",20));
title.setFill(Color.RED);
gridPane.add(title,0,0);
// adding buttons to Hbox inside of gridPane
hBox.getChildren().add(campusMap);
hBox.getChildren().add(floor0Button);
hBox.getChildren().add(floor1Button);
hBox.getChildren().add(floor2Button);
hBox.getChildren().add(floor3Button);
hBox.getChildren().add(floor0Button2);
hBox.getChildren().add(floor1Button2);
hBox.getChildren().add(floor2Button2);
hBox.getChildren().add(floor3Button2);
gridPane.add(hBox,0,1);
// Totally not driving a white van ^^^^^^^^^ -_o
Scene scene = new Scene(gridPane,700,600);
primaryStage.setTitle("Class Map");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| gpl-3.0 |
JhonPolitecnico/Proyectos-2014 | 2014-Paradigmas Interface/src/main/Almacenable.java | 84 | package main;
public interface Almacenable {
String toXml();
String toJson();
}
| gpl-3.0 |
sethten/MoDesserts | mcp50/temp/src/minecraft_server/net/minecraft/src/EntityAIFollowOwner.java | 3605 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
// Referenced classes of package net.minecraft.src:
// EntityAIBase, EntityTameable, PathNavigate, EntityLookHelper,
// EntityLiving, MathHelper, AxisAlignedBB, World
public class EntityAIFollowOwner extends EntityAIBase
{
private EntityTameable field_48247_d;
private EntityLiving field_48248_e;
World field_48251_a;
private float field_48245_f;
private PathNavigate field_48246_g;
private int field_48252_h;
float field_48249_b;
float field_48250_c;
private boolean field_48253_i;
public EntityAIFollowOwner(EntityTameable p_i1072_1_, float p_i1072_2_, float p_i1072_3_, float p_i1072_4_)
{
field_48247_d = p_i1072_1_;
field_48251_a = p_i1072_1_.field_9093_l;
field_48245_f = p_i1072_2_;
field_48246_g = p_i1072_1_.func_48333_ak();
field_48250_c = p_i1072_3_;
field_48249_b = p_i1072_4_;
func_46087_a(3);
}
public boolean func_46090_a()
{
EntityLiving entityliving = field_48247_d.func_48368_w_();
if(entityliving == null)
{
return false;
}
if(field_48247_d.func_48371_v_())
{
return false;
}
if(field_48247_d.func_102_b(entityliving) < (double)(field_48250_c * field_48250_c))
{
return false;
} else
{
field_48248_e = entityliving;
return true;
}
}
public boolean func_46092_g()
{
return !field_48246_g.func_46034_b() && field_48247_d.func_102_b(field_48248_e) > (double)(field_48249_b * field_48249_b) && !field_48247_d.func_48371_v_();
}
public void func_46088_e()
{
field_48252_h = 0;
field_48253_i = field_48247_d.func_48333_ak().func_48649_a();
field_48247_d.func_48333_ak().func_48656_a(false);
}
public void func_46085_d()
{
field_48248_e = null;
field_48246_g.func_48662_f();
field_48247_d.func_48333_ak().func_48656_a(field_48253_i);
}
public void func_46089_b()
{
field_48247_d.func_46021_ae().func_46058_a(field_48248_e, 10F, field_48247_d.func_25018_n_());
if(field_48247_d.func_48371_v_())
{
return;
}
if(--field_48252_h > 0)
{
return;
}
field_48252_h = 10;
if(field_48246_g.func_48652_a(field_48248_e, field_48245_f))
{
return;
}
if(field_48247_d.func_102_b(field_48248_e) < 144D)
{
return;
}
int i = MathHelper.func_584_b(field_48248_e.field_322_l) - 2;
int j = MathHelper.func_584_b(field_48248_e.field_320_n) - 2;
int k = MathHelper.func_584_b(field_48248_e.field_312_v.field_963_b);
for(int l = 0; l <= 4; l++)
{
for(int i1 = 0; i1 <= 4; i1++)
{
if((l < 1 || i1 < 1 || l > 3 || i1 > 3) && field_48251_a.func_445_d(i + l, k - 1, j + i1) && !field_48251_a.func_445_d(i + l, k, j + i1) && !field_48251_a.func_445_d(i + l, k + 1, j + i1))
{
field_48247_d.func_107_c((float)(i + l) + 0.5F, k, (float)(j + i1) + 0.5F, field_48247_d.field_316_r, field_48247_d.field_315_s);
field_48246_g.func_48662_f();
return;
}
}
}
}
}
| gpl-3.0 |
STEENBRINK/Kaasmod-2-1.7.10 | src/main/java/nl/steenbrink/kaasmod/fluid/FluidCrafting.java | 3230 | package nl.steenbrink.kaasmod.fluid;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.IIcon;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import nl.steenbrink.kaasmod.init.ModFluids;
public class FluidCrafting extends Fluid {
public FluidCrafting(String fluidName) {
super(fluidName);
}
@Override
public IIcon getIcon(FluidStack stack) {
NBTTagCompound nbtTagCompound = stack.tag;
if (nbtTagCompound.hasKey("FluidPrimary")) {
FluidStack primaryFluid = FluidStack.loadFluidStackFromNBT(nbtTagCompound.getCompoundTag("FluidPrimary"));
if (primaryFluid == null) return null;
return primaryFluid.getFluid().getIcon(primaryFluid);
}
return null;
}
public static FluidStack createCraftingFluid(FluidStack primaryFluid, FluidStack secondaryFluid) {
FluidStack outputFluid = new FluidStack(ModFluids.fluidCrafting, primaryFluid.amount);
outputFluid.tag = new NBTTagCompound();
NBTTagCompound primaryFluidTagCompound = new NBTTagCompound();
primaryFluid.writeToNBT(primaryFluidTagCompound);
outputFluid.tag.setTag("FluidPrimary", primaryFluidTagCompound);
NBTTagCompound secondaryFluidTagCompound = new NBTTagCompound();
secondaryFluid.writeToNBT(secondaryFluidTagCompound);
outputFluid.tag.setTag("FluidSecondary", secondaryFluidTagCompound);
return outputFluid;
}
public static boolean compareCraftingFluid(FluidStack fluidStackA, FluidStack fluidStackB, boolean precise) {
if (fluidStackA.getFluid() != ModFluids.fluidCrafting || fluidStackB.getFluid() != ModFluids.fluidCrafting) return false;
FluidStack primaryFluidA = FluidStack.loadFluidStackFromNBT(fluidStackA.tag.getCompoundTag("FluidPrimary"));
FluidStack secondaryFluidA = FluidStack.loadFluidStackFromNBT(fluidStackA.tag.getCompoundTag("FluidSecondary"));
FluidStack primaryFluidB = FluidStack.loadFluidStackFromNBT(fluidStackB.tag.getCompoundTag("FluidPrimary"));
FluidStack secondaryFluidB = FluidStack.loadFluidStackFromNBT(fluidStackB.tag.getCompoundTag("FluidSecondary"));
if (primaryFluidA == null || secondaryFluidA == null || primaryFluidB == null || secondaryFluidB == null) return false;
if (primaryFluidA.getFluid() != primaryFluidB.getFluid()) return false;
if (secondaryFluidA.getFluid() != secondaryFluidB.getFluid()) return false;
if (!precise) return true;
if (primaryFluidA.amount != primaryFluidB.amount) return false;
if (primaryFluidA.tag != null || primaryFluidB.tag != null) {
if (!(primaryFluidA.tag != null && primaryFluidB.tag != null)) return false;
if (!primaryFluidA.tag.equals(primaryFluidB.tag)) return false;
}
if (secondaryFluidA.amount != secondaryFluidB.amount) return false;
if (secondaryFluidA.tag != null || secondaryFluidB.tag != null) {
if (!(secondaryFluidA.tag != null && secondaryFluidB.tag != null)) return false;
if (!secondaryFluidA.tag.equals(secondaryFluidB.tag)) return false;
}
return true;
}
}
| gpl-3.0 |
Kaaml/laboratoria | src/ClientServiceThread.java | 4680 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
/**
* Created by kaaml on 03.03.16.
*/
//package ClientServiceThread;
public class ClientServiceThread extends Thread {
//Thread activeThread = null;
Socket clientSocket = null;
ArrayList<ClientServiceThread> cli = null;
private PrintWriter outWrit = null;
String clientName;
IRCServer mainServer = null;
private enum Command {
NICK() {
@Override
public void run(String[] msg, IRCServer server, ClientServiceThread own) {
System.out.println(msg);
own.RegisterClient( msg[0] );
}
},
PASS(){
@Override
public void run(String[] msg, IRCServer server, ClientServiceThread own) {
System.out.println("PASS(1,4)");
own.PassToServer(msg[1] );
}
},
REG(){
@Override
public void run(String[] msg, IRCServer server, ClientServiceThread own ){
try{
server.RegisterClientOnServer(msg[0], own );
}catch( Exception e)
{
System.out.println( e.getMessage() );
}
}
};
public abstract void run(String[] msg, IRCServer server, ClientServiceThread own) ;
}
public ClientServiceThread(Socket conn, IRCServer server){
clientSocket = conn;
mainServer = server;
System.out.println( "THREAD[ " + this.getId() + " ] has started" );
}
public void run()
{
System.out.println( "CONNECTION: Accepted connection from " + clientSocket.getInetAddress() );
try(
BufferedReader in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream() ) );
) {
outWrit = new PrintWriter( clientSocket.getOutputStream() );
String msg;
while ((msg = in.readLine()) != null) {
System.out.println(msg);
if (msg.equals("exit"))
break;
if( msg.equalsIgnoreCase("send" ) )
for( ClientServiceThread i : cli )
i.send("Alle user msg");
ParseCommand( msg );
}
}catch( Exception e )
{
System.out.println( e.getMessage() );
}
finally {
System.out.println( "THREAD[ " + this.getId() + "] has been closed" );
}
}
public void send( String msg )
{
outWrit.write( msg );
outWrit.flush();
}
public void ParseCommand( String line )
{
System.out.println( "Parsing line: [" + line + " ] " );
// [:]<kto> <polecenie> <parametry>
// user MSG target message
// user joing #channel1
// user register nickname password
// pass username password
// user usei real_informations
// user msg target msg_
// user quit msg
// and more sooon ;)s
String[] tokens = line.split( " ", 2 );
if( tokens[0].equalsIgnoreCase("pass" ) ){
String[] argsOfCommand = tokens[2].split(" " );
Command x = Command.valueOf( tokens[0] );
if( x == null ){
send( "command not found" );
return;
}else {
x.run(argsOfCommand, mainServer, this);
}
}
}
public void RegisterClient(String name)
{
clientName = name;
try {
mainServer.RegisterClientOnServer(name, this);
send( "User registred as " + name );
}catch( IRCServer.UserExist e )
{
try{
mainServer.RegisterClientOnServer( name+"_" , this );
send( "User registred as " + name + "_" );
}catch( IRCServer.UserExist e2 )
{
System.out.println( "User already exist on server" );
send( "ERR_NICKNAMEINUSE" );
//send( "Nick already exist on server" );
}
}
}
public void PassToServer( String password )
{
if( ! mainServer.IsCorrectPassword( password ) )
{
send( "invalid password to server. You are disconnected!" );
try {
clientSocket.close();
}catch( Exception e )
{
System.out.println( e.getStackTrace() );
}
this.stop();
}
}
}
| gpl-3.0 |
TMMOB-BMO/TOYS | Toys/JavaSource/tr/com/arf/toys/view/converter/system/DemirbasConverter.java | 1343 | package tr.com.arf.toys.view.converter.system;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.FacesConverter;
import tr.com.arf.framework.view.converter._base.BaseConverter;
import tr.com.arf.toys.db.model.system.Demirbas;
import tr.com.arf.toys.service.application.ManagedBeanLocator;
@FacesConverter(forClass=Demirbas.class, value="demirbasConverter")
public class DemirbasConverter extends BaseConverter{
public DemirbasConverter() {
super();
}
@Override
public Object getAsObject(FacesContext facesContext,
UIComponent uIComponent, String value) {
if (value == null || value.trim().equalsIgnoreCase("")) {
return null;
}
// DBOperator dbOperator = new DBOperator();
return ManagedBeanLocator.locateSessionController().getDBOperator().find("Demirbas", "rID", value).get(0);
}
@Override
public String getAsString(FacesContext facesContext,
UIComponent uIComponent, Object value) {
if (value == null) {
return null;
}
if (value instanceof Demirbas) {
Demirbas demirbas = (Demirbas) value;
return "" + demirbas.getRID();
}
else {
throw new IllegalArgumentException("object:" + value + " of type:" +
value.getClass().getName() + "; expected type: Demirbas Model");
}
}
} // class
| gpl-3.0 |
wizjany/craftbook | src/main/java/com/sk89q/craftbook/mech/LightSwitch.java | 7493 | // $Id$
/*
* CraftBook Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not,
* see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.craftbook.mech;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.event.player.PlayerInteractEvent;
import com.sk89q.craftbook.AbstractMechanic;
import com.sk89q.craftbook.AbstractMechanicFactory;
import com.sk89q.craftbook.ChangedSign;
import com.sk89q.craftbook.LocalPlayer;
import com.sk89q.craftbook.bukkit.CraftBookPlugin;
import com.sk89q.craftbook.util.HistoryHashMap;
import com.sk89q.craftbook.util.exceptions.InsufficientPermissionsException;
import com.sk89q.craftbook.util.exceptions.InvalidMechanismException;
import com.sk89q.craftbook.util.exceptions.ProcessedMechanismException;
import com.sk89q.worldedit.BlockWorldVector;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.bukkit.BukkitUtil;
/**
* Handler for Light switches. Toggles all torches in the area from being redstone to normal torches. This is done
* every time a sign with [|] or [I]
* is right clicked by a player.
*
* @author fullwall
*/
public class LightSwitch extends AbstractMechanic {
public static class Factory extends AbstractMechanicFactory<LightSwitch> {
public Factory() {
}
@Override
public LightSwitch detect(BlockWorldVector pt) {
Block block = BukkitUtil.toBlock(pt);
// check if this looks at all like something we're interested in first
if (block.getTypeId() != BlockID.WALL_SIGN) return null;
String line = ((Sign) block.getState()).getLine(1);
if (!line.equals("[|]") && !line.equalsIgnoreCase("[I]")) return null;
// okay, now we can start doing exploration of surrounding blocks
// and if something goes wrong in here then we throw fits.
return new LightSwitch(pt);
}
/**
* Detect the mechanic at a placed sign.
*
* @throws ProcessedMechanismException
*/
@Override
public LightSwitch detect(BlockWorldVector pt, LocalPlayer player,
ChangedSign sign) throws InvalidMechanismException,
ProcessedMechanismException {
String line = sign.getLine(1);
if (line.equals("[|]") || line.equalsIgnoreCase("[I]")) {
if (!player.hasPermission("craftbook.mech.light-switch")) throw new InsufficientPermissionsException();
sign.setLine(1, "[I]");
player.print("mech.lightswitch.create");
} else return null;
throw new ProcessedMechanismException();
}
}
/**
* Store a list of recent light toggles to prevent spamming. Someone clever can just use two signs though.
*/
private final HistoryHashMap<BlockWorldVector, Long> recentLightToggles = new HistoryHashMap<BlockWorldVector,
Long>(20);
/**
* Configuration.
*/
private final BlockWorldVector pt;
/**
* Construct a LightSwitch for a location.
*
* @param pt
* @param plugin
*/
private LightSwitch(BlockWorldVector pt) {
super();
this.pt = pt;
}
@Override
public void onRightClick(PlayerInteractEvent event) {
if (!CraftBookPlugin.inst().getConfiguration().lightSwitchEnabled) return;
if (!BukkitUtil.toWorldVector(event.getClickedBlock()).equals(pt)) return; // wth? our manager is insane
toggleLights(pt);
event.setCancelled(true);
}
/**
* Toggle lights in the immediate area.
*
* @param pt
*
* @return true if the block was recogized as a lightswitch; this may or may not mean that any lights were
* actually toggled.
*/
private boolean toggleLights(BlockWorldVector pt) {
World world = BukkitUtil.toWorld(pt);
Block block = BukkitUtil.toBlock(pt);
// check if this looks at all like something we're interested in first
if (block.getTypeId() != BlockID.WALL_SIGN) return false;
int radius = 10;
int maximum = 20;
try {
radius = Integer.parseInt(((Sign) block.getState()).getLine(2));
} catch (Exception ignored) {
}
try {
maximum = Integer.parseInt(((Sign) block.getState()).getLine(3));
} catch (Exception ignored) {
}
if (radius > CraftBookPlugin.inst().getConfiguration().lightSwitchMaxRange) {
radius = CraftBookPlugin.inst().getConfiguration().lightSwitchMaxRange;
}
if (maximum > CraftBookPlugin.inst().getConfiguration().lightSwitchMaxLights) {
maximum = CraftBookPlugin.inst().getConfiguration().lightSwitchMaxLights;
}
int wx = pt.getBlockX();
int wy = pt.getBlockY();
int wz = pt.getBlockZ();
int aboveID = world.getBlockTypeIdAt(wx, wy + 1, wz);
if (aboveID == BlockID.TORCH || aboveID == BlockID.REDSTONE_TORCH_OFF || aboveID == BlockID.REDSTONE_TORCH_ON) {
// Check if block above is a redstone torch.
// Used to get what to change torches to.
boolean on = aboveID != BlockID.TORCH;
// Prevent spam
Long lastUse = recentLightToggles.remove(pt);
long currTime = System.currentTimeMillis();
if (lastUse != null && currTime - lastUse < 500) {
recentLightToggles.put(pt, lastUse);
return true;
}
recentLightToggles.put(pt, currTime);
int changed = 0;
for (int x = -radius + wx; x <= radius + wx; x++) {
for (int y = -radius + wy; y <= radius + wy; y++) {
for (int z = -radius + wz; z <= radius + wz; z++) {
int id = world.getBlockTypeIdAt(x, y, z);
if (id == BlockID.TORCH || id == BlockID.REDSTONE_TORCH_OFF || id == BlockID
.REDSTONE_TORCH_ON) {
// Limit the maximum number of changed lights
if (changed >= maximum) return true;
if (on) {
world.getBlockAt(x, y, z).setTypeId(BlockID.TORCH);
} else {
world.getBlockAt(x, y, z).setTypeId(BlockID.REDSTONE_TORCH_ON);
}
changed++;
}
}
}
}
return true;
}
return false;
}
} | gpl-3.0 |
uav-team-ut/Manual-Recognition-Station | src/org/uavteam/TargetData.java | 2311 | package org.uavteam;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* Created by jtb20 on 6/5/2017.
*/
public class TargetData {
BufferedImage target;
double lat;
double lon;
String rotation;
String shape;
String shapeColor;
String letterColor;
String letter;
String id;
String type;
String desc;
public TargetData(BufferedImage t, double lat, double lon, String rot, String shape, String sColor, String letter, String lColor, String id, String type){
target=t;
this.lat=lat;
this.lon=lon;
rotation=rot;
this.shape=shape;
this.shapeColor=sColor;
this.letter=letter;
this.letterColor=lColor;
this.id=id;
this.type=type;
this.desc="";
}
public TargetData(double lat, double lon, String id) {
target = null;
this.lat = lat;
this.lon = lon;
rotation = "n";
this.shape = "Semicircle";
this.shapeColor = "Orange";
this.letter = "A";
this.letterColor = "White";
this.id=id;
type="standard";
desc="";
}
public void addTarget(BufferedImage t ){
target=t;
}
public void setLocation(double lat, double lon){
this.lat=lat;
this.lon=lon;
}
public void setRotation(String s) {
rotation=s;
}
public void setMetaData(String s, String sColor, String l, String lColor, String t,String desc){
shape=s.toLowerCase();
shapeColor=sColor.toLowerCase();
letter=l.toLowerCase();
letterColor=lColor.toLowerCase();
type=t.toLowerCase();
this.desc=desc;
if(t.equals("standard")||t.equals("emergent")||t.equals("off-axis")) {
type = t;
}
}
public String getRotation(){return rotation;}
public String getShape(){return shape;}
public String getShapeColor(){return shapeColor;}
public String getLetterColor(){return letterColor;}
public String getLetter(){return letter;}
public double getLat(){return lat;}
public double getLon(){return lon;}
public BufferedImage getImage(){return target;}
public String getType(){return type;}
public String getId(){return id;}
public String getDesc(){return desc;}
}
| gpl-3.0 |
austindlawless/dotCMS | src/com/dotmarketing/business/DotJBCacheAdministratorLegacyImpl.java | 2826 | /**
*
*/
package com.dotmarketing.business;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.dotcms.repackage.jgroups_2_12_2_final.org.jgroups.JChannel;
import com.dotmarketing.common.business.journal.DistributedJournalAPI;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.util.Logger;
/**
* The legacy cache administrator will invalidate cache entries within a cluster
* on a put where the non legacy one will not.
* @author Jason Tesser
* @version 1.6.5
*
*/
public class DotJBCacheAdministratorLegacyImpl implements DotCacheAdministrator{
private DotCacheAdministrator cache;
private DistributedJournalAPI journalAPI;
public DotJBCacheAdministratorLegacyImpl() {
journalAPI = APILocator.getDistributedJournalAPI();
cache = CacheLocator.getCacheAdministrator();
}
/* (non-Javadoc)
* @see com.dotmarketing.business.DotCacheAdministrator#flushAll()
*/
public void flushAll() {
cache.flushAll();
}
/* (non-Javadoc)
* @see com.dotmarketing.business.DotCacheAdministrator#flushGroup(java.lang.String)
*/
public void flushGroup(String group) {
cache.flushGroup(group);
}
public void flushGroupLocalOnly(String group) {
cache.flushGroupLocalOnly(group);
}
/* (non-Javadoc)
* @see com.dotmarketing.business.DotCacheAdministrator#get(java.lang.String)
*/
public Object get(String key, String group) throws DotCacheException {
return cache.get(key, group);
}
/* (non-Javadoc)
* @see com.dotmarketing.business.DotCacheAdministrator#put(java.lang.String, java.lang.Object, java.lang.String[])
*/
public void put(String key, Object content, String group) {
cache.put(key, content, group);
try{
journalAPI.addCacheEntry(key, group);
}catch(DotDataException e){
Logger.error(this, "Unable to add journal entry for cluster", e);
}
}
/* (non-Javadoc)
* @see com.dotmarketing.business.DotCacheAdministrator#remove(java.lang.String)
*/
public void remove(String key, String group) {
cache.remove(key, group);
}
public void removeLocalOnly(String key, String group) {
cache.removeLocalOnly(key, group);
}
public void flushAlLocalOnlyl() {
cache.flushAlLocalOnlyl();
}
public Set<String> getKeys(String group) {
return cache.getKeys(group);
}
public void shutdown() {
cache.shutdown();
}
public JChannel getJGroupsChannel() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Map<String, Object>> getCacheStatsList() {
return new ArrayList<Map<String, Object>>();
}
@Override
public Class getImplementationClass() {
return DotJBCacheAdministratorLegacyImpl.class;
}
@Override
public DotCacheAdministrator getImplementationObject() {
return this;
}
}
| gpl-3.0 |
nohupYoung/leetcode | FindTheDuplicateNumber.java | 525 | public class FindTheDuplicateNumber {
public int findDuplicate(int[] nums) {
int min = 0, max = nums.length - 1;
while(min <= max){
int mid = min + (max - min) / 2;
int cnt = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] <= mid){
cnt++;
}
}
if(cnt > mid){
max = mid - 1;
} else {
min = mid + 1;
}
}
return min;
}
} | gpl-3.0 |
fanruan/finereport-design | designer_base/src/com/fr/design/editor/editor/IntegerEditor.java | 998 | package com.fr.design.editor.editor;
import com.fr.base.Utils;
import com.fr.general.Inter;
/**
* 整数编辑器
*
* @author zhou
* @since 2012-3-29下午4:02:06
*/
public class IntegerEditor extends NumberEditor<Integer> {
private static final long serialVersionUID = 1L;
public IntegerEditor() {
this(new Integer(0));
}
public IntegerEditor(Integer value) {
super(value, Inter.getLocText("FR-Designer_Parameter_Integer"));
}
@Override
public Integer getValue() {
return new Integer((int) this.numberField.getValue());
}
@Override
public boolean accept(Object object) {
return object != null && object instanceof Integer;
}
public String getIconName() {
return "type_int";
}
@Override
public void setValue(Integer value) {
if (value == null) {
value = new Integer(0);
}
this.numberField.setInteger(true);
this.numberField.setValue(value.intValue());
oldValue = Utils.objectToString(value);
}
} | gpl-3.0 |
automenta/adams-core | src/main/java/adams/gui/chooser/BaseFileChooser.java | 16950 | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* BaseFileChooser.java
* Copyright (C) 2009-2014 University of Waikato, Hamilton, New Zealand
*/
package adams.gui.chooser;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import adams.core.io.PlaceholderDirectory;
import adams.core.io.PlaceholderFile;
import adams.gui.core.ExtensionFileFilter;
import adams.gui.core.GUIHelper;
/**
* A file chooser dialog based on the one developed by the
* <a href="http://vfsjfilechooser.sourceforge.net/" target="_blank">VFSJFileChooser project</a>.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 9464 $
*/
public class BaseFileChooser
extends JFileChooser {
/** for serialization. */
private static final long serialVersionUID = -5712455182900852653L;
/** whether to ask to overwrite an existing file (using the save dialog). */
protected boolean m_PromptOverwriteFile;
/** whether to automatically append extension. */
protected boolean m_AutoAppendExtension;
/** whether glob filters (eg "*.txt") are allowed. */
protected boolean m_AllowGlobFilters;
/** the default extension. */
protected String m_DefaultExtension;
/** the bookmarks. */
protected FileChooserBookmarksPanel m_PanelBookmarks;
/**
* Constructs a <code>BaseFileChooser</code> pointing to the user's
* default directory. This default depends on the operating system.
* It is typically the "My Documents" folder on Windows, and the
* user's home directory on Unix.
*/
public BaseFileChooser() {
super();
initialize();
}
/**
* Constructs a <code>BaseFileChooser</code> using the given path.
* Passing in a <code>null</code>
* string causes the file chooser to point to the user's default directory.
* This default depends on the operating system. It is
* typically the "My Documents" folder on Windows, and the user's
* home directory on Unix.
*
* @param currentDirectoryPath a <code>String</code> giving the path
* to a file or directory
*/
public BaseFileChooser(String currentDirectoryPath) {
super(currentDirectoryPath);
initialize();
}
/**
* Constructs a <code>BaseFileChooser</code> using the given <code>File</code>
* as the path. Passing in a <code>null</code> file
* causes the file chooser to point to the user's default directory.
* This default depends on the operating system. It is
* typically the "My Documents" folder on Windows, and the user's
* home directory on Unix.
*
* @param currentDirectory a <code>File</code> object specifying
* the path to a file or directory
*/
public BaseFileChooser(File currentDirectory) {
super(currentDirectory);
initialize();
}
/**
* For initializing some stuff.
*/
protected void initialize() {
JComponent accessory;
m_PromptOverwriteFile = true;
m_AutoAppendExtension = false;
m_AllowGlobFilters = true;
m_DefaultExtension = null;
accessory = createAccessoryPanel();
if (accessory != null)
setAccessory(accessory);
}
/**
* Returns the preferred dimension.
*
* @return the dimension, null if to use default
*/
protected Dimension getDefaultAccessoryDimension() {
int height;
int width;
width = GUIHelper.getInteger("BaseFileChooser.Accessory.Width", -1);
height = GUIHelper.getInteger("BaseFileChooser.Accessory.Height", -1);
if ((width != -1) && (height != -1))
return new Dimension(width, height);
else
return null;
}
/**
* Creates an accessory panel displayed next to the files.
*
* @return the panel or null if none available
*/
protected JComponent createAccessoryPanel() {
Dimension dim;
m_PanelBookmarks = new FileChooserBookmarksPanel();
m_PanelBookmarks.setOwner(this);
m_PanelBookmarks.setBorder(BorderFactory.createEmptyBorder(2, 5, 0, 0));
dim = getDefaultAccessoryDimension();
if (dim != null) {
m_PanelBookmarks.setSize(dim);
m_PanelBookmarks.setMinimumSize(dim);
m_PanelBookmarks.setPreferredSize(dim);
}
return m_PanelBookmarks;
}
/**
* Sets whether the user gets prompted by the save dialog if the selected file
* already exists.
*
* @param value if true, then the user will get prompted if file
* already exists
*/
public void setPromptOverwriteFile(boolean value) {
m_PromptOverwriteFile = value;
}
/**
* Returns whether the user gets prompted by the save dialog if the selected
* file already exists.
*
* @return true if the user will get prompted
*/
public boolean getPromptOverwriteFile() {
return m_PromptOverwriteFile;
}
/**
* Sets whether to automatically append the currently selected file extension
* or the default one (if All-Filter is used).
*
* @param value if true, then the file extension will be added
* automatically
*/
public void setAutoAppendExtension(boolean value) {
m_AutoAppendExtension = value;
}
/**
* Returns whether to automatically append the currently selected file extension
* or the default one (if All-Filter is used).
*
* @return true if the file extension will be added
* automatically
*/
public boolean getAutoAppendExtension() {
return m_AutoAppendExtension;
}
/**
* Sets the default extension. Is used if m_AutoAppendExtension is true
* and the All-Filter is selected.
*
* @param value the extension (without dot), use null to unset
*/
public void setDefaultExtension(String value) {
m_DefaultExtension = value;
}
/**
* Returns the default extension. Is used if m_AutoAppendExtension is true
* and the All-Filter is selected.
*
* @return the extension, can be null
*/
public String getDefaultExtension() {
return m_DefaultExtension;
}
/**
* Sets whether the user can enter glob filters like "*.txt".
*
* @param value if true, then the user can enter glob filters
*/
public void setAllowGlobFilters(boolean value) {
m_AllowGlobFilters = value;
}
/**
* Returns whether the user can enter glob filters like "*.txt".
*
* @return true if the user can enter glob filters
*/
public boolean getAllowGlobFilters() {
return m_AllowGlobFilters;
}
/**
* Returns whether the filter is a "glob" filter, e.g., when the user
* enters "*.txt" manually.
*
* @param filter the filter to check
* @return true if a glob filter
*/
protected boolean isGlobFilter(FileFilter filter) {
if (filter == null)
return false;
// TODO: classname?
return filter.getClass().getName().endsWith("$GlobFilter");
}
/**
* Checks the filter whether it can be set.
*
* @param filter the filter to set
* @return true if check passed and valid
*/
protected boolean checkFilter(FileFilter filter) {
boolean result;
if (filter == null)
return true;
result = (filter instanceof ExtensionFileFilter)
|| (filter == getAcceptAllFileFilter())
|| (isGlobFilter(filter) && getAllowGlobFilters());
if (!result) {
if (isGlobFilter(filter)) {
System.err.println(
"Please select a filter from the drop-down list!");
}
else {
System.err.println(
"Only instances of " + ExtensionFileFilter.class.getName() + " are accepted!\n"
+ "Provided: " + filter.getClass().getName());
}
}
return result;
}
@Override
public void setFileFilter(FileFilter filter) {
if (checkFilter(filter))
super.setFileFilter(filter);
}
/**
* Adds the file filter. Has to be a <code>ExtensionFileFilter</code>.
*
* @param filter the filter to add
* @see ExtensionFileFilter
*/
@Override
public void addChoosableFileFilter(FileFilter filter) {
if (checkFilter(filter))
super.addChoosableFileFilter(filter);
}
/**
* Sets the selected file. If the file's parent directory is
* not the current directory, changes the current directory
* to be the file's parent directory.
*
* @beaninfo
* preferred: true
* bound: true
*
* @see #getSelectedFile
*
* @param file the selected file
*/
@Override
public void setSelectedFile(File file) {
File selFile;
selFile = null;
if (file != null)
selFile = new File(file.getAbsolutePath());
if (selFile == null)
return;
try {
// sometimes property change events result in exceptions
super.setSelectedFile(selFile);
}
catch (Exception e) {
super.setSelectedFile(selFile);
}
}
/**
* Returns the selected file as PlaceholderFile. This can be set either by the
* programmer via <code>setFile</code> or by a user action, such as
* either typing the filename into the UI or selecting the
* file from a list in the UI.
*
* @return the selected file, converted to PlaceholderFile
*/
public PlaceholderFile getSelectedPlaceholderFile() {
File file;
file = super.getSelectedFile();
if (file != null)
return new PlaceholderFile(file);
else
return null;
}
/**
* Sets the list of selected files if the file chooser is
* set to allow multiple selection.
*
* @param selectedFiles the files to select initially
* @beaninfo
* bound: true
* description: The list of selected files if the chooser is in multiple selection mode.
*/
@Override
public void setSelectedFiles(File[] selectedFiles) {
File[] files;
int i;
files = null;
if (selectedFiles != null) {
files = new File[selectedFiles.length];
for (i = 0; i < selectedFiles.length; i++)
files[i] = selectedFiles[i].getAbsoluteFile();
}
try {
// sometimes property change events result in exceptions
super.setSelectedFiles(files);
}
catch (Exception e) {
super.setSelectedFiles(files);
}
}
/**
* Returns a list of selected files if the file
* chooser is set to allow multiple selection.
* <p/>
* Fixes the problem with JFileChooser of not returning anything sometimes
* when only a single file is selected.
*
* @return the selected files
*/
@Override
public File[] getSelectedFiles() {
File[] result;
result = super.getSelectedFiles();
if ((result.length == 0) && (getSelectedFile() != null))
result = new File[]{getSelectedFile()};
return result;
}
/**
* Returns a list of selected files as PlaecholderFile objects if the file
* chooser is set to allow multiple selection.
*
* @return the selected files, converted to PlaceholderFile objects
*/
public PlaceholderFile[] getSelectedPlaceholderFiles() {
PlaceholderFile[] result;
File[] files;
int i;
files = getSelectedFiles();
result = new PlaceholderFile[files.length];
for (i = 0; i < result.length; i++)
result[i] = new PlaceholderFile(files[i]);
return result;
}
/**
* Checks the filename, whether it has an extension from the provided list.
*
* @param file the file to check
* @param extensions the extensions to check against
* @return true if valid extension
*/
protected boolean hasCorrectExtension(File file, String[] extensions) {
boolean result;
String filename;
int i;
result = false;
// open: file exists -> correct extension
if (getDialogType() == OPEN_DIALOG)
result = file.exists();
// save: all files -> correct extension
if ((getDialogType() == SAVE_DIALOG) && (getFileFilter() == getAcceptAllFileFilter()))
result = true;
// save: glob filter -> correct extension
if ((getDialogType() == SAVE_DIALOG) && (isGlobFilter(getFileFilter())))
result = true;
if (!result) {
filename = file.getAbsolutePath().toLowerCase();
for (i = 0; i < extensions.length; i++) {
if (filename.endsWith("." + extensions[i].toLowerCase())) {
result = true;
break;
}
}
}
return result;
}
/**
* Dislpays the dialog.
*
* @param parent the parent component of the dialog;
* can be <code>null</code>
* @param approveButtonText the text of the <code>ApproveButton</code>
* @return the return state of the file chooser on popdown
* @throws HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
@Override
public int showDialog(Component parent, String approveButtonText) {
int result;
int retVal;
File[] selfiles;
File selfile;
int i;
String[] extensions;
m_PanelBookmarks.reload();
parent = GUIHelper.getParentComponent(parent);
result = super.showDialog(parent, approveButtonText);
// fix extensions?
if (m_AutoAppendExtension) {
// determine extension to add
extensions = null;
if ((getFileFilter() != getAcceptAllFileFilter()) && !isGlobFilter(getFileFilter()))
extensions = ((ExtensionFileFilter) getFileFilter()).getExtensions();
else
extensions = new String[]{getDefaultExtension()};
// fix extensions if necessary
if (extensions != null) {
if (isMultiSelectionEnabled()) {
selfiles = getSelectedFiles();
for (i = 0; i < selfiles.length; i++) {
if (!hasCorrectExtension(selfiles[i], extensions))
selfiles[i] = new File(selfiles[i].getAbsolutePath() + "." + extensions[0]);
}
setSelectedFiles(selfiles);
}
else {
selfile = getSelectedFile();
if (selfile != null) {
if (!hasCorrectExtension(selfile, extensions))
selfile = new File(selfile.getAbsolutePath() + "." + extensions[0]);
setSelectedFile(selfile);
}
}
}
}
// do we have to prompt user to confirm overwriting of file?
if ( (result == APPROVE_OPTION) && (getDialogType() == SAVE_DIALOG)
&& ((getFileSelectionMode() == FILES_AND_DIRECTORIES) || (getFileSelectionMode() == FILES_ONLY)) ) {
if ( getPromptOverwriteFile() && (getSelectedFile() != null)
&& getSelectedFile().exists() && !getSelectedFile().isDirectory()) {
retVal = GUIHelper.showConfirmMessage(
parent,
"File already exists - overwrite?\n" + getSelectedFile(),
"File exists already");
switch (retVal) {
case JOptionPane.YES_OPTION:
break;
case JOptionPane.NO_OPTION:
result = showSaveDialog(parent);
break;
case JOptionPane.CANCEL_OPTION:
result = CANCEL_OPTION;
break;
}
}
}
return result;
}
/**
* Returns the current directory.
*
* @return the current directory, as PlaceholderDirectory
* @see #setCurrentDirectory
*/
public PlaceholderDirectory getCurrentPlaceholderDirectory() {
File current;
current = super.getCurrentDirectory();
if (current == null)
return null;
else
return new PlaceholderDirectory(current);
}
/**
* Sets the current directory. Passing in <code>null</code> sets the
* file chooser to point to the user's default directory.
* This default depends on the operating system. It is
* typically the "My Documents" folder on Windows, and the user's
* home directory on Unix.
*
* If the file passed in as <code>currentDirectory</code> is not a
* directory, the parent of the file will be used as the currentDirectory.
* If the parent is not traversable, then it will walk up the parent tree
* until it finds a traversable directory, or hits the root of the
* file system.
*
* @param dir the current directory to point to
* @see #getCurrentDirectory
*/
@Override
public void setCurrentDirectory(File dir) {
try {
if (dir == null)
super.setCurrentDirectory(null);
else
super.setCurrentDirectory(dir.getAbsoluteFile());
}
catch (Exception e) {
// sometimes property change events result in exceptions
if (dir == null)
super.setCurrentDirectory(null);
else
super.setCurrentDirectory(dir.getAbsoluteFile());
}
}
}
| gpl-3.0 |
vpac-innovations/rsa | src/storagemanager/src/main/java/org/vpac/ndg/storage/PostgreSQLCustomDialect.java | 1177 | package org.vpac.ndg.storage;
import java.sql.Types;
import org.hibernate.dialect.PostgreSQL94Dialect;
/**
* Hibernate's PostgreSQLDialect doesn't define mappings for the ARRAY type,
* because there is no possible one-to-one mapping. So we define new types and
* map those instead.
*
* http://stackoverflow.com/questions/37477119/infer-type-information-in-usertype
*
* @author Alex Fraser
*/
public class PostgreSQLCustomDialect extends PostgreSQL94Dialect {
public PostgreSQLCustomDialect() {
super();
this.registerColumnType(CustomTypes.FLOAT_ARRAY,
getTypeName(Types.FLOAT) + "[]");
this.registerColumnType(CustomTypes.DOUBLE_ARRAY,
getTypeName(Types.DOUBLE) + "[]");
this.registerColumnType(CustomTypes.SMALLINT_ARRAY,
getTypeName(Types.SMALLINT) + "[]");
this.registerColumnType(CustomTypes.INTEGER_ARRAY,
getTypeName(Types.INTEGER) + "[]");
this.registerColumnType(CustomTypes.BIGINT_ARRAY,
getTypeName(Types.BIGINT) + "[]");
this.registerColumnType(CustomTypes.LONGVARCHAR_ARRAY,
getTypeName(Types.LONGVARCHAR) + "[]");
}
}
| gpl-3.0 |
TeamMonumental/FissionWarfare | src/main/java/tm/fissionwarfare/entity/EntityFlakey.java | 2055 | package tm.fissionwarfare.entity;
import net.minecraft.block.BlockDirectional;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.storage.WorldInfo;
import tm.fissionwarfare.block.BlockExplosive;
import tm.fissionwarfare.init.InitBlocks;
public class EntityFlakey extends Entity {
private static final double MAX_LIFE = 20 * 10;
public EntityFlakey(World world) {
super(world);
setSize(0, 0);
}
public EntityFlakey(World world, double x, double y, double z){
super(world);
setPosition(x, y, z);
}
@Override
public void onUpdate() {
super.onUpdate();
if (ticksExisted >= MAX_LIFE) {
if (!worldObj.isRemote){
WorldInfo worldinfo = MinecraftServer.getServer().worldServers[0].getWorldInfo();
worldinfo.setThundering(false);
worldinfo.setRaining(false);
}
setDead();
}
if (ticksExisted % 20 == 0) {
doDamage();
}
}
private void doDamage() {
int posXX = (int)posX;
int posYY = (int)posY;
int posZZ = (int)posZ;
double velX = MathHelper.getRandomDoubleInRange(rand, -0.3D, 0.3D);
double velZ = MathHelper.getRandomDoubleInRange(rand, -0.3D, 0.3D);
BlockExplosive basicBomb = (BlockExplosive)InitBlocks.basic_explosive;
EntityExplosive bomb = new EntityExplosive(worldObj, posXX, posYY + 30, posZZ, basicBomb);
if (!worldObj.isRemote){
worldObj.setWorldTime(18000);
WorldInfo worldinfo = MinecraftServer.getServer().worldServers[0].getWorldInfo();
worldinfo.setRaining(true);
worldinfo.setThundering(true);
worldinfo.setThunderTime(40);
worldObj.spawnEntityInWorld(bomb);
bomb.addVelocity(velX, 0.05D, velZ);
}
}
@Override
public void entityInit() {
}
@Override
protected void readEntityFromNBT(NBTTagCompound nbt) {
}
@Override
protected void writeEntityToNBT(NBTTagCompound nbt) {
}
}
| gpl-3.0 |
Fosstrak/fosstrak-webadapters | src/main/java/org/fosstrak/webadapters/epcis/model/events/QuantityEvent.java | 4102 | /*
* Copyright (C) 2010 ETH Zurich
*
* This file is part of Fosstrak (www.fosstrak.org) and
* was developed as part of the webofthings.com initiative.
*
* Fosstrak is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* Fosstrak 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 Fosstrak; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package org.fosstrak.webadapters.epcis.model.events;
import org.fosstrak.webadapters.epcis.model.Entry;
import org.fosstrak.webadapters.epcis.ws.generated.EPCISEventType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* The JAXB class to handle Quantity Events of the EPCIS Webadapter model
* @author Mathias Mueller mathias.mueller(at)unifr.ch, <a href="http://www.guinard.org">Dominique Guinard</a>
*/
@XmlRootElement(namespace = "fosstrak.org/epcis/restadapter")
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
public class QuantityEvent extends EPCISEvent {
public QuantityEvent() {}
/**
* Constructs the event class.
*
*
* @param event
* @param index
*/
public QuantityEvent(EPCISEventType event) {
super(event);
initFillSpecificData();
super.setUp();
}
protected String getEpcClass() {
String res = "";
if (epcClass != null) {
res = epcClass;
}
return res;
}
protected String getQuantity() {
String res = "";
if (quantity != Integer.MIN_VALUE) {
res = "" + quantity;
}
return res;
}
/**
* Method description
*
*
* @return
*/
@XmlElement(name = "quantity")
public Entry getQuantityEntry() {
return quantityEntry;
}
/**
* Method description
*
*
* @param quantityEntry
*/
public void setQuantityEntry(Entry quantityEntry) {
this.quantityEntry = quantityEntry;
}
/**
* Method description
*
*
* @return
*/
@XmlElement(name = "epcClass")
public Entry getEpcClassEntry() {
return epcClassEntry;
}
/**
* Method description
*
*
* @param epcClassEntry
*/
public void setEpcClassEntry(Entry epcClassEntry) {
this.epcClassEntry = epcClassEntry;
}
/**
* Method description
*
*/
@Override
public void initFillSpecificData() {
if (!getQuantity().equals("")) {
quantityEntry = new Entry();
quantityEntry.setValue(getQuantity());
}
if (!getEpcClass().equals("")) {
epcClassEntry = new Entry();
epcClassEntry.setValue(getEpcClass());
}
}
/**
* Method description
*
*
* @param otherEvent
*
* @return
*/
@Override
public boolean isSubclassLikeEvent(EPCISEvent otherEvent) {
boolean res = true;
if (!(otherEvent instanceof QuantityEvent)) {
return false;
}
QuantityEvent otherSubclassEvent = (QuantityEvent) otherEvent;
try {
if (!(getEpcClassEntry().getValue().equals(otherSubclassEvent.getEpcClassEntry().getValue()))) {
return false;
}
} catch (Exception ex) {}
try {
if (!(getQuantityEntry().getValue().equals(otherSubclassEvent.getQuantityEntry().getValue()))) {
return false;
}
} catch (Exception ex) {}
return res;
}
}
| gpl-3.0 |
TheBasedRebel/ZoneSeek | ZoneSeek/common/entities/render/RenderPterodactyl.java | 1772 | package ZoneSeek.common.entities.render;
import ZoneSeek.common.entities.Pterodactyl;
import ZoneSeek.common.models.ModelPterodactyl;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.passive.EntityCow;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class RenderPterodactyl extends RenderLiving
{
public RenderPterodactyl(ModelPterodactyl par1ModelBase, float par2)
{
super(par1ModelBase, par2);
}
public void renderCow(Pterodactyl par1EntityCow, double par2, double par4, double par6, float par8, float par9)
{
super.doRenderLiving(par1EntityCow, par2, par4, par6, par8, par9);
}
public void doRenderLiving(EntityLiving par1EntityLiving, double par2, double par4, double par6, float par8, float par9)
{
this.renderCow((Pterodactyl)par1EntityLiving, par2, par4, par6, par8, par9);
}
/**
* 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 par1Entity, double par2, double par4, double par6, float par8, float par9)
{
this.renderCow((Pterodactyl)par1Entity, par2, par4, par6, par8, par9);
}
}
| gpl-3.0 |
dotCMS/core | dotCMS/src/test/java/com/liferay/util/ValidatorTest.java | 1014 | package com.liferay.util;
import com.dotcms.UnitTestBase;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Created by Oscar Arrieta on 6/19/17.
*/
public class ValidatorTest extends UnitTestBase {
@Test
public void testValidEmails(){
final List<String> validEmails =
Arrays.asList( "john.doe@dotcms.com", "james.sa'd@test.com",
"john+test@dotcms.com", "john+test@test.test.test.test.ag" );
for ( String validEmail : validEmails ) {
assertTrue( Validator.isEmailAddress( validEmail ) );
}
}
@Test
public void testInvalidEmails(){
final List<String> invalidEmails = Arrays.asList( null, "", "abc.example.com", "a@b@c@example.com" );
for ( String invalidEmail : invalidEmails ) {
assertFalse( Validator.isEmailAddress( invalidEmail ) );
}
}
}
| gpl-3.0 |
idega/platform2 | src/se/idega/idegaweb/commune/message/data/PrintedLetterMessageBMPBean.java | 22210 | package se.idega.idegaweb.commune.message.data;
import java.util.Collection;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import com.idega.block.process.data.AbstractCaseBMPBean;
import com.idega.block.process.data.Case;
import com.idega.block.school.data.School;
import com.idega.core.file.data.ICFile;
import com.idega.data.IDOException;
// import com.idega.data.IDOQuery;
import com.idega.data.IDORuntimeException;
import com.idega.data.query.Criteria;
import com.idega.data.query.InCriteria;
import com.idega.data.query.MatchCriteria;
import com.idega.data.query.SelectQuery;
import com.idega.user.data.Group;
import com.idega.user.data.User;
import com.idega.util.IWTimestamp;
/**
* Title: Description: Copyright: Copyright (c) 2002 Company:
*
* @author Anders Lindman
* @version 1.0
*/
public class PrintedLetterMessageBMPBean extends AbstractCaseBMPBean implements PrintedLetterMessage, PrintMessage,
Case {
private static final String COLUMN_SUBJECT = "SUBJECT";
private static final String COLUMN_BODY = "BODY";
private static final String COLUMN_MESSAGE_TYPE = "MESSAGE_TYPE";
private static final String COLUMN_MESSAGE_DATA = "MESSAGE_DATA";
private static final String COLUMN_LETTER_TYPE = "LETTER_TYPE";
private static final String COLUMN_BULK_DATA = "BULK_DATA";
private static final String COLUMN_CONTENT_CODE = "CONTENT_CODE";
private static final String CASE_CODE_KEY = "SYMEBRV";
private static final String CASE_CODE_DESCRIPTION = "Letter Message";
public String getEntityName() {
return "MSG_LETTER_MESSAGE";
}
public void initializeAttributes() {
addGeneralCaseRelation();
this.addAttribute(COLUMN_SUBJECT, "Message subject", String.class);
this.addAttribute(COLUMN_BODY, "Message body", String.class, 4000);
this.addAttribute(COLUMN_MESSAGE_TYPE, "Message type", String.class, 20);
this.addManyToOneRelationship(COLUMN_MESSAGE_DATA, "Message data", ICFile.class);
this.addAttribute(COLUMN_LETTER_TYPE, "Message SubType", String.class, 4);
this.addManyToOneRelationship(COLUMN_BULK_DATA, "Message bulk data", ICFile.class);
this.addAttribute(COLUMN_CONTENT_CODE, "Message contentcode", String.class, 20);
}
public String getCaseCodeKey() {
return CASE_CODE_KEY;
}
public String getCaseCodeDescription() {
return CASE_CODE_DESCRIPTION;
}
public void setDefaultValues() {
setLetterType(MessageConstants.LETTER_TYPE_DEFAULT);
}
public User getSender() {
throw new UnsupportedOperationException();
}
public void setSender(User sender) {
throw new UnsupportedOperationException();
}
public int getSenderID() {
throw new UnsupportedOperationException();
}
public void setSenderID(int senderID) {
throw new UnsupportedOperationException();
}
public void setSubject(String subject) {
this.setColumn(COLUMN_SUBJECT, subject);
}
public String getSubject() {
return this.getStringColumnValue(COLUMN_SUBJECT);
}
public void setBody(String body) {
this.setColumn(COLUMN_BODY, body);
}
public String getBody() {
return this.getStringColumnValue(COLUMN_BODY);
}
public String getMessageType() {
return this.getStringColumnValue(COLUMN_MESSAGE_TYPE);
}
public boolean isPrinted() {
return this.getCaseStatus().getStatus().equals(getCaseStatusReady());
}
public void setMessageType(String type) {
this.setColumn(COLUMN_MESSAGE_TYPE, type);
}
public ICFile getMessageData() {
return (ICFile) this.getColumnValue(COLUMN_MESSAGE_DATA); // Replace this
// later
}
public int getMessageDataFileID() {
return this.getIntColumnValue(COLUMN_MESSAGE_DATA);
}
public void setMessageData(ICFile file) { // Temp (test) method
this.setColumn(COLUMN_MESSAGE_DATA, file);
}
public void setMessageData(int fileID) { // Temp (test) method
this.setColumn(COLUMN_MESSAGE_DATA, fileID);
}
/*
* (non-Javadoc)
*
* @see se.idega.idegaweb.commune.message.data.PrintMessage#getContentType()
*/
public String getContentCode() {
return this.getStringColumnValue(COLUMN_CONTENT_CODE);
}
public void setContentCode(String contentCode) {
this.setColumn(COLUMN_CONTENT_CODE, contentCode);
}
public ICFile getMessageBulkData() {
return (ICFile) this.getColumnValue(COLUMN_BULK_DATA); // Replace this
// later
}
public int getMessageBulkDataFileID() {
return this.getIntColumnValue(COLUMN_BULK_DATA);
}
public void setMessageBulkData(ICFile file) { // Temp (test) method
this.setColumn(COLUMN_BULK_DATA, file);
}
public void setMessageBulkData(int fileID) { // Temp (test) method
this.setColumn(COLUMN_BULK_DATA, fileID);
}
public String getSenderName() {
return getOwner().getName();
}
public String getDateString() {
/**
* @todo: implement
*/
return "";
}
public void setLetterType(String letterType) {
setColumn(COLUMN_LETTER_TYPE, letterType);
}
public String getLetterType() {
return getStringColumnValue(COLUMN_LETTER_TYPE);
}
public void setAsPasswordLetter() {
setLetterType(MessageConstants.LETTER_TYPE_PASSWORD);
}
public Collection ejbFindMessages(User user) throws FinderException {
return super.ejbFindAllCasesByUser(user);
}
public Collection ejbFindMessagesByStatus(User user, String[] status) throws FinderException {
return super.ejbFindAllCasesByUserAndStatusArray(user, status);
}
public Collection ejbFindAllUnPrintedLetters() throws FinderException {
return super.ejbFindAllCasesByStatus(super.getCaseStatusOpen());
}
public Collection ejbFindAllPrintedLetters() throws FinderException {
return super.ejbFindAllCasesByStatus(super.getCaseStatusReady());
}
protected SelectQuery idoSelectQueryGetCountDefaultLettersWithStatus(String caseStatus) {
return idoSelectQueryGetLettersCountByStatusAndType(caseStatus, MessageConstants.LETTER_TYPE_DEFAULT);
}
protected SelectQuery idoSelectQueryGetCountPasswordLettersWithStatus(String caseStatus) {
return idoSelectQueryGetLettersCountByStatusAndType(caseStatus, COLUMN_LETTER_TYPE);
}
public String getUnPrintedCaseStatusForType(String type) {
return getCaseStatusOpen();
}
public String getPrintedCaseStatusForType(String type) {
return getCaseStatusReview();
}
/**
* Counts the number of unprinted letters of the given type.
*/
public int ejbHomeGetNumberOfUnprintedLettersByType(String letterType) {
try {
SelectQuery sql = idoSelectQueryGetLettersCountByStatusAndType(getUnPrintedCaseStatusForType(letterType),
letterType);
return super.idoGetNumberOfRecords(sql);
}
catch (IDOException sqle) {
throw new EJBException(sqle.getMessage());
}
}
/**
* Counts the number of printed letters of the given type.
*/
public int ejbHomeGetNumberOfPrintedLettersByType(String letterType) {
try {
SelectQuery sql = idoSelectQueryGetLettersCountByStatusAndType(getUnPrintedCaseStatusForType(letterType),
letterType);
return super.idoGetNumberOfRecords(sql);
}
catch (IDOException sqle) {
throw new EJBException(sqle.getMessage());
}
}
/**
* Counts the number of letters of the given type and status.
*/
public int ejbHomeGetNumberOfLettersByStatusAndType(String caseStatus, String letterType) {
try {
SelectQuery sql = idoSelectQueryGetLettersCountByStatusAndType(caseStatus, letterType);
return super.idoGetNumberOfRecords(sql);
}
catch (IDOException sqle) {
throw new EJBException(sqle.getMessage());
}
}
/**
* Counts the number of letters that are of type password and unprinted
*/
public int ejbHomeGetNumberOfUnPrintedPasswordLetters() {
try {
SelectQuery sql = idoSelectQueryGetCountPasswordLettersWithStatus(getCaseStatusOpen());
return super.idoGetNumberOfRecords(sql);
}
catch (IDOException sqle) {
throw new EJBException(sqle.getMessage());
}
}
/**
* Counts the number of letters that are of type password and printed
*/
public int ejbHomeGetNumberOfPrintedPasswordLetters() {
try {
SelectQuery sql = idoSelectQueryGetCountPasswordLettersWithStatus(getCaseStatusReview());
return super.idoGetNumberOfRecords(sql);
}
catch (IDOException sqle) {
throw new EJBException(sqle.getMessage());
}
}
/**
* Counts the number of letters that are of type default and unprinted
*/
public int ejbHomeGetNumberOfUnPrintedDefaultLetters() {
try {
SelectQuery sql = idoSelectQueryGetCountDefaultLettersWithStatus(getCaseStatusOpen());
return super.idoGetNumberOfRecords(sql);
}
catch (IDOException sqle) {
throw new EJBException(sqle.getMessage());
}
}
/**
* Counts the number of letters that are of type default and printed
*/
public int ejbHomeGetNumberOfPrintedDefaultLetters() {
try {
SelectQuery sql = idoSelectQueryGetCountDefaultLettersWithStatus(getCaseStatusReview());
return super.idoGetNumberOfRecords(sql);
}
catch (IDOException sqle) {
throw new EJBException(sqle.getMessage());
}
}
public String[] ejbHomeGetLetterTypes() {
String[] types = { MessageConstants.LETTER_TYPE_DEFAULT, MessageConstants.LETTER_TYPE_PASSWORD };
return types;
}
protected SelectQuery idoSelectQueryGetPrintedLettersByType(String letterType) {
try {
return idoSelectQueryGetLettersByStatusAndType(getCaseStatusReady(), letterType);
}
catch (Exception e) {
throw new IDORuntimeException(e, this);
}
}
protected SelectQuery idoSelectQueryGetPrintedLettersByType(String letterType, IWTimestamp from, IWTimestamp to) {
try {
return idoSelectQueryGetLettersByStatusAndType(getCaseStatusReady(), letterType, from, to);
}
catch (Exception e) {
throw new IDORuntimeException(e, this);
}
}
protected SelectQuery idoSelectQueryGetSinglePrintedLettersByType(String letterType, IWTimestamp from, IWTimestamp to) {
try {
return idoSelectQueryGetSingleLettersByStatusAndType(getCaseStatusReady(), letterType, from, to);
}
catch (Exception e) {
throw new IDORuntimeException(e, this);
}
}
protected SelectQuery idoSelectQueryGetUnPrintedLettersByType(String letterType) {
try {
return idoSelectQueryGetLettersByStatusAndType(getCaseStatusOpen(), letterType);
}
catch (Exception e) {
throw new IDORuntimeException(e, this);
}
}
protected SelectQuery idoSelectQueryGetUnPrintedLettersByType(String letterType, IWTimestamp from, IWTimestamp to) {
try {
return idoSelectQueryGetLettersByStatusAndType(getCaseStatusOpen(), letterType, from, to);
}
catch (Exception e) {
throw new IDORuntimeException(e, this);
}
}
protected SelectQuery idoSelectQueryGetSingleUnPrintedLettersByType(String letterType, IWTimestamp from,
IWTimestamp to) {
try {
return idoSelectQueryGetSingleLettersByStatusAndType(getCaseStatusOpen(), letterType, from, to);
}
catch (Exception e) {
throw new IDORuntimeException(e, this);
}
}
protected Criteria idoCriteriaForLetterType(String type) {
return new MatchCriteria(idoTableSubCase(), COLUMN_LETTER_TYPE, MatchCriteria.EQUALS, type, true);
}
protected SelectQuery idoSelectQueryGetLettersByStatusAndType(String caseStatus, String letterType) {
SelectQuery query = idoSelectQueryGetAllCasesByStatus(caseStatus);
query.addCriteria(idoCriteriaForLetterType(letterType));
return query;
}
protected SelectQuery idoSelectQueryGetLettersByStatusAndType(String caseStatus, String letterType, IWTimestamp from,
IWTimestamp to) {
SelectQuery query = idoSelectQueryGetAllCases();
query.addCriteria(idoCriteriaForStatus(caseStatus));
query.addCriteria(idoCriteriaForCreatedWithinDates(from, to));
query.addCriteria(idoCriteriaForLetterType(letterType));
query.addOrder(idoOrderByCreationDate(false));
return query;
}
protected SelectQuery idoSelectQueryGetSingleLettersByStatusAndType(String caseStatus, String letterType,
IWTimestamp from, IWTimestamp to) {
SelectQuery query = idoSelectQueryGetAllCases();
query.addCriteria(idoCriteriaForStatus(caseStatus));
query.addCriteria(idoCriteriaForCreatedWithinDates(from, to));
query.addCriteria(idoCriteriaForLetterType(letterType));
query.addOrder(idoOrderByCreationDate(false));
return query;
}
protected SelectQuery idoSelectQueryGetLettersByBulkFile(int file, String caseStatus, String letterType) {
SelectQuery query = idoSelectQueryGetAllCases();
query.addCriteria(idoCriteriaForStatus(caseStatus));
query.addCriteria(idoCriteriaForLetterType(letterType));
query.addCriteria(new MatchCriteria(idoTableSubCase(), COLUMN_BULK_DATA, MatchCriteria.EQUALS, file));
query.addOrder(idoOrderByCreationDate(false));
return query;
}
protected SelectQuery idoSelectQueryGetLettersCountByStatusAndType(String caseStatus, String letterType) {
SelectQuery query = super.idoSelectQueryGetCountCasesWithStatus(caseStatus);
query.addCriteria(idoCriteriaForLetterType(letterType));
return query;
}
public Collection ejbFindPrintedLettersByType(String letterType, int resultSize, int startingIndex)
throws FinderException {
return super.idoFindPKsByQuery(idoSelectQueryGetPrintedLettersByType(letterType), resultSize, startingIndex);
}
public Collection ejbFindPrintedLettersByType(String letterType, IWTimestamp from, IWTimestamp to, int resultSize,
int startingIndex) throws FinderException {
return super.idoFindPKsByQuery(idoSelectQueryGetPrintedLettersByType(letterType, from, to), resultSize,
startingIndex);
}
public Collection ejbFindSinglePrintedLettersByType(String letterType, IWTimestamp from, IWTimestamp to,
int resultSize, int startingIndex) throws FinderException {
SelectQuery query = idoSelectQueryGetSinglePrintedLettersByType(letterType, from, to);
return super.idoFindPKsByQuery(query, resultSize, startingIndex);
}
public Collection ejbFindByBulkFile(int file, String letterType, String status, int resultSize, int startingIndex)
throws FinderException {
return super.idoFindPKsByQuery(idoSelectQueryGetLettersByBulkFile(file, status, letterType), resultSize,
startingIndex);
}
public Collection ejbFindSingleByTypeAndStatus(String letterType, String status, IWTimestamp from, IWTimestamp to,
int resultSize, int startingIndex) throws FinderException {
return super.idoFindPKsByQuery(idoSelectQueryGetSingleLettersByStatusAndType(status, letterType, from, to),
resultSize, startingIndex);
}
public Collection ejbFindUnPrintedLettersByType(String letterType, int resultSize, int startingIndex)
throws FinderException {
return super.idoFindPKsByQuery(idoSelectQueryGetUnPrintedLettersByType(letterType), resultSize, startingIndex);
}
public Collection ejbFindUnPrintedLettersByType(String letterType, IWTimestamp from, IWTimestamp to, int resultSize,
int startingIndex) throws FinderException {
return super.idoFindPKsByQuery(idoSelectQueryGetUnPrintedLettersByType(letterType, from, to), resultSize,
startingIndex);
}
public Collection ejbFindSingleUnPrintedLettersByType(String letterType, IWTimestamp from, IWTimestamp to,
int resultSize, int startingIndex) throws FinderException {
return super.idoFindPKsByQuery(idoSelectQueryGetSingleUnPrintedLettersByType(letterType, from, to), resultSize,
startingIndex);
}
public Collection ejbFindUnPrintedPasswordLetters(int resultSize, int startingIndex) throws FinderException {
String letterType = MessageConstants.LETTER_TYPE_PASSWORD;
return ejbFindUnPrintedLettersByType(letterType, resultSize, startingIndex);
}
public Collection ejbFindPrintedPasswordLetters(int resultSize, int startingIndex) throws FinderException {
String letterType = MessageConstants.LETTER_TYPE_PASSWORD;
return ejbFindPrintedLettersByType(letterType, resultSize, startingIndex);
}
public Collection ejbFindUnPrintedDefaultLetters(int resultSize, int startingIndex) throws FinderException {
String letterType = MessageConstants.LETTER_TYPE_DEFAULT;
return ejbFindUnPrintedLettersByType(letterType, resultSize, startingIndex);
}
public Collection ejbFindPrintedDefaultLetters(int resultSize, int startingIndex) throws FinderException {
String letterType = MessageConstants.LETTER_TYPE_DEFAULT;
return ejbFindPrintedLettersByType(letterType, resultSize, startingIndex);
}
public String getPrintType() {
return getMessageType();
}
public String[] ejbHomeGetPrintMessageTypes() {
return ejbHomeGetLetterTypes();
}
// TODO Handle this in more general way...
public Collection ejbFindLettersByChildcare(int providerID, String ssn, String msgId, IWTimestamp from, IWTimestamp to)
throws FinderException {
com.idega.data.IDOQuery sql = idoQuery();
String sqlFrom = this.getEntityName() + " m, proc_case p, comm_childcare c";
if (ssn != null && !ssn.equals("")) {
sqlFrom += ", ic_user u";
}
sql.appendSelectAllFrom(sqlFrom);
sql.appendWhereEquals("m.msg_letter_message_id", "p.proc_case_id");
sql.appendAndEquals("p.parent_case_id", "c.comm_childcare_id");
sql.appendAndEquals("c.provider_id", providerID);
if (ssn != null && !ssn.equals("")) {
sql.appendAndEquals("p.user_id", "u.ic_user_id");
sql.appendAnd().append("u.personal_id").appendLike().appendWithinSingleQuotes(ssn);
}
if (msgId != null && !msgId.equals("")) {
sql.appendAndEqualsQuoted("m.msg_letter_message_id", msgId);
}
to.setHour(23);
to.setMinute(59);
to.setSecond(59);
from.setHour(0);
from.setMinute(0);
from.setSecond(0);
sql.appendAnd();
sql.append("p.created");
sql.append(" >= ");
sql.append(from.getTimestamp());
sql.append("");
sql.appendAnd();
sql.append("p.created");
sql.append(" <= ");
sql.append(to.getTimestamp());
sql.append(" ");
sql.appendOrderBy("p.created");
// System.out.println("########### SQL:" + sql.toString() + ".");
Collection tmp = this.idoFindPKsByQuery(sql);
return tmp;
}
// TODO Handle this in more general way...
public Collection ejbFindLettersByAdultEducation(School school, String ssn, String msgId, IWTimestamp from,
IWTimestamp to) throws FinderException {
com.idega.data.IDOQuery sql = idoQuery();
String sqlFrom = this.getEntityName() + " m, proc_case p, comm_vux_choice c, vux_course co";
if (ssn != null && !ssn.equals("")) {
sqlFrom += ", ic_user u";
}
sql.appendSelectAllFrom(sqlFrom);
sql.appendWhereEquals("m.msg_letter_message_id", "p.proc_case_id");
sql.appendAndEquals("p.parent_case_id", "c.comm_vux_choice_id");
sql.appendAndEquals("c.vux_course_id", "co.vux_course_id");
sql.appendAndEquals("co.sch_school_id", school);
if (ssn != null && !ssn.equals("")) {
sql.appendAndEquals("p.user_id", "u.ic_user_id");
sql.appendAnd().append("u.personal_id").appendLike().appendWithinSingleQuotes(ssn);
}
if (msgId != null && !msgId.equals("")) {
sql.appendAndEqualsQuoted("m.msg_letter_message_id", msgId);
}
to.setHour(23);
to.setMinute(59);
to.setSecond(59);
from.setHour(0);
from.setMinute(0);
from.setSecond(0);
sql.appendAnd();
sql.append("p.created");
sql.append(" >= ");
sql.append(from.getTimestamp());
sql.append("");
sql.appendAnd();
sql.append("p.created");
sql.append(" <= ");
sql.append(to.getTimestamp());
sql.append(" ");
sql.appendOrderBy("p.created");
return idoFindPKsByQuery(sql);
}
public Collection ejbFindAllLettersBySchool(int providerID, String ssn, String msgId, IWTimestamp from, IWTimestamp to)
throws FinderException {
com.idega.data.IDOQuery sql = idoQuery();
String sqlFrom = this.getEntityName() + " m, proc_case p, comm_sch_choice c";
if (ssn != null && !ssn.equals("")) {
sqlFrom += ", ic_user u";
}
sql.appendSelectAllFrom(sqlFrom);
sql.appendWhereEquals("m.msg_letter_message_id", "p.proc_case_id");
sql.appendAndEquals("p.parent_case_id", "c.comm_sch_choice_id");
sql.appendAndEquals("c.school_id", providerID);
if (ssn != null && !ssn.equals("")) {
sql.appendAndEquals("p.user_id", "u.ic_user_id");
sql.appendAnd().append("u.personal_id").appendLike().appendWithinSingleQuotes(ssn);
}
if (msgId != null && !msgId.equals("")) {
sql.appendAndEqualsQuoted("m.msg_letter_message_id", msgId);
}
to.setHour(23);
to.setMinute(59);
to.setSecond(59);
from.setHour(0);
from.setMinute(0);
from.setSecond(0);
sql.appendAnd();
sql.append("p.created");
sql.append(" >= ");
sql.append(from.getTimestamp());
sql.append(" ");
sql.appendAnd();
sql.append("p.created");
sql.append(" <= ");
sql.append(to.getTimestamp());
sql.append(" ");
sql.appendOrderBy("p.created");
return idoFindPKsByQuery(sql);
}
public Collection ejbFindLetters(String[] msgId) throws FinderException {
SelectQuery query = idoSelectQuery();
query.addCriteria(new InCriteria(idoQueryTable(), getIDColumnName(), msgId));
Collection tmp = this.idoFindPKsByQuery(query);
return tmp;
}
public java.util.Collection ejbFindMessages(com.idega.user.data.User user, String[] status)
throws javax.ejb.FinderException {
return super.ejbFindAllCasesByUserAndStatusArray(user, status);
}
public Collection ejbFindMessages(User user, String[] status, int numberOfEntries, int startingEntry)
throws FinderException {
return super.ejbFindAllCasesByUserAndStatusArray(user, status, numberOfEntries, startingEntry);
}
public Collection ejbFindMessages(Group group, String[] status) throws FinderException {
return super.ejbFindAllCasesByGroupAndStatusArray(group, status);
}
public Collection ejbFindMessages(Group group, String[] status, int numberOfEntries, int startingEntry)
throws FinderException {
return super.ejbFindAllCasesByGroupAndStatusArray(group, status, numberOfEntries, startingEntry);
}
public Collection ejbFindMessages(User user, Collection groups, String[] status, int numberOfEntries,
int startingEntry) throws FinderException {
return super.ejbFindAllCasesByUserAndGroupsAndStatusArray(user, groups, status, numberOfEntries, startingEntry);
}
public int ejbHomeGetNumberOfMessages(User user, Collection groups, String[] status) throws IDOException {
return super.ejbHomeGetCountCasesByUserAndGroupsAndStatusArray(user, groups, status);
}
public int ejbHomeGetNumberOfMessages(User user, String[] status) throws IDOException {
return super.ejbHomeGetCountCasesByUserAndStatusArray(user, status);
}
} | gpl-3.0 |
liyi-david/ePMC | plugins/constraintsolver-isat3/src/test/java/epmc/constraintsolver/isat3/ISat3TextualTest.java | 5155 | /****************************************************************************
ePMC - an extensible probabilistic model checker
Copyright (C) 2017
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
package epmc.constraintsolver.isat3;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static epmc.modelchecker.TestHelper.*;
import static epmc.value.UtilValue.newValue;
import epmc.constraintsolver.ConstraintSolver;
import epmc.constraintsolver.ConstraintSolverConfiguration;
import epmc.constraintsolver.ConstraintSolverResult;
import epmc.constraintsolver.Feature;
import epmc.constraintsolver.isat3.textual.ConstraintSolverISat3Textual;
import epmc.constraintsolver.sat3.options.OptionsISat3;
import epmc.main.options.UtilOptionsEPMC;
import epmc.modelchecker.UtilModelChecker;
import epmc.options.Options;
import epmc.plugin.OptionsPlugin;
import epmc.value.TypeInteger;
import epmc.value.TypeReal;
public class ISat3TextualTest {
/** Location of plugin directory in file system. */
private final static String PLUGIN_DIR = System.getProperty("user.dir") + "/target/classes/";
/**
* Set up the tests.
*/
@BeforeClass
public static void initialise() {
prepare();
}
/**
* Prepare options including loading JANI plugin.
*
* @return options usable for JANI model analysis
*/
private final static Options prepareISat3Options() {
Options options = UtilOptionsEPMC.newOptions();
options.set(OptionsPlugin.PLUGIN, PLUGIN_DIR);
prepareOptions(options);
return options;
}
@Test
public void iSat3ManualTest() {
Options options = prepareISat3Options();
ConstraintSolverConfiguration configuration = new ConstraintSolverConfiguration();
configuration.requireFeature(Feature.SMT);
ConstraintSolver solver = configuration.newProblem();
assert solver instanceof ConstraintSolverISat3Textual;
TypeInteger typeInteger = TypeInteger.get();
List<String> commandLine = new ArrayList<>();
commandLine.add("/Users/emhahn/isat3.sh");
commandLine.add("-I");
commandLine.add("-v");
commandLine.add("{0}");
options.set(OptionsISat3.ISAT3_COMMAND_LINE, commandLine);
solver.addVariable("a", typeInteger, newValue(typeInteger, 1), newValue(typeInteger, 100));
solver.addVariable("b", typeInteger, newValue(typeInteger, 1), newValue(typeInteger, 100));
solver.addVariable("c", typeInteger, newValue(typeInteger, 1), newValue(typeInteger, 100));
solver.addConstraint(UtilModelChecker.parseExpression("a*a + b*b = c*c"));
assertEquals(ConstraintSolverResult.SAT, solver.solve());
/* multiple solutions possible, don't test result values */
}
@Test
public void andreaTest() {
Options options = prepareISat3Options();
ConstraintSolverConfiguration configuration = new ConstraintSolverConfiguration();
configuration.requireFeature(Feature.SMT);
ConstraintSolver solver = configuration.newProblem();
assert solver instanceof ConstraintSolverISat3Textual;
TypeReal typeReal = TypeReal.get();
TypeInteger typeInteger = TypeInteger.get();
List<String> commandLine = new ArrayList<>();
commandLine.add("/Users/emhahn/isat3.sh");
commandLine.add("-I");
commandLine.add("-v");
commandLine.add("{0}");
options.set(OptionsISat3.ISAT3_COMMAND_LINE, commandLine);
solver.addVariable("s0", typeReal, newValue(typeReal, 1), newValue(typeInteger, 1));
solver.addVariable("s1", typeReal, newValue(typeReal, 0), newValue(typeInteger, 1));
solver.addVariable("s2", typeReal, newValue(typeReal, 0), newValue(typeInteger, 0));
solver.addVariable("err", typeReal, newValue(typeReal, 0), newValue(typeInteger, 10));
solver.addConstraint(UtilModelChecker.parseExpression("(s0 = (0.5*err)*s1 + (1.0-(0.5*err))*s2) & (s1 = 1)"));
assertEquals(ConstraintSolverResult.SAT, solver.solve());
assertEquals("1", solver.getResultVariablesValues()[0], 1E-100);
assertEquals("1", solver.getResultVariablesValues()[1], 1E-100);
assertEquals("0", solver.getResultVariablesValues()[2], 1E-100);
assertEquals("2", solver.getResultVariablesValues()[3], 1E-100);
}
}
| gpl-3.0 |
teapot-org/teapot-backend | src/main/java/org/teapot/backend/model/meta/TeapotAction.java | 691 | package org.teapot.backend.model.meta;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.teapot.backend.model.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
@Entity
@Table(name = "action")
@NoArgsConstructor
@AllArgsConstructor
public class TeapotAction extends BaseEntity {
@Column(nullable = false, unique = true, length = 32)
@Getter
@Setter
private String name;
@Getter
@Setter
private String usage;
@Lob
@Column(length = 512)
@Getter
@Setter
private String manual;
}
| gpl-3.0 |
TrulyFree/Modular6 | src/test/java/io/github/trulyfree/modular6/test/action/impl/SimpleActionGroup.java | 1957 | package io.github.trulyfree.modular6.test.action.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import io.github.trulyfree.modular6.action.Action;
import io.github.trulyfree.modular6.action.ActionGroup;
/* Modular6 library by TrulyFree: A general-use module-building library.
* Copyright (C) 2016 VTCAKAVSMoACE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class SimpleActionGroup<T extends Action> implements ActionGroup<T> {
private List<T> actions;
private int current;
public SimpleActionGroup(List<T> actions) {
this.actions = actions;
current = 0;
}
@Override
public boolean enactNextAction() {
return actions.get(next()).enact();
}
@Override
public int size() {
return actions.size();
}
@Override
public Collection<T> getActions() {
Collection<T> actions = new ArrayList<T>(size());
for (T action : this.actions) {
actions.add(action);
}
return actions;
}
private int next() {
final int intermediary = current;
current++;
current %= this.size();
return intermediary;
}
@Override
public void enactAllOfType(Class<? extends T> type) {
for (T action : getActions()) {
if (type.isInstance(action)) {
action.enact();
}
}
}
@Override
public void enactAll() {
for (T action : getActions()) {
action.enact();
}
}
}
| gpl-3.0 |
boost-starai/BoostSRL | code/src/edu/wisc/cs/will/FOPC/visitors/VariableCollector.java | 1289 | package edu.wisc.cs.will.FOPC.visitors;
import edu.wisc.cs.will.FOPC.Sentence;
import edu.wisc.cs.will.FOPC.Term;
import edu.wisc.cs.will.FOPC.Variable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class VariableCollector {
private static final VariableCollectorVisitor VARIABLE_COOLLECTOR_VISITOR = new VariableCollectorVisitor();
public static Set<Variable> collectVariables(Sentence sentence, Set<Variable> set) {
if (set == null) {
set = new HashSet<Variable>();
}
sentence.accept(VARIABLE_COOLLECTOR_VISITOR, set);
return set;
}
public static Set<Variable> collectVariables(Term term, Set<Variable> set) {
if (set == null) {
set = new HashSet<Variable>();
}
term.accept(VARIABLE_COOLLECTOR_VISITOR, set);
return set;
}
private static class VariableCollectorVisitor extends DefaultFOPCVisitor<Set<Variable>> {
public VariableCollectorVisitor() {
super(false);
}
@Override
public Term visitVariable(Variable variable, Set<Variable> counters) {
counters.add(variable);
return null;
}
}
private VariableCollector() {
}
}
| gpl-3.0 |
opensciencemap/open | src/test/java/com/mapzen/open/support/TestActionBar.java | 4345 | package com.mapzen.open.support;
import android.app.ActionBar;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.SpinnerAdapter;
import org.robolectric.Robolectric;
public class TestActionBar extends ActionBar {
private CharSequence title;
private boolean homeButtonEnabled = false;
private boolean showHomeAsUp = false;
private boolean isShowing = false;
@Override
public void setHomeButtonEnabled(boolean enabled) {
homeButtonEnabled = enabled;
}
public boolean getHomeButtonEnabled() {
return homeButtonEnabled;
}
@Override
public void setCustomView(View view) {
}
@Override
public void setCustomView(View view, LayoutParams layoutParams) {
}
@Override
public void setCustomView(int resId) {
}
@Override
public void setIcon(int resId) {
}
@Override
public void setIcon(Drawable icon) {
}
@Override
public void setLogo(int resId) {
}
@Override
public void setLogo(Drawable logo) {
}
@Override
public void setListNavigationCallbacks(SpinnerAdapter adapter, OnNavigationListener callback) {
}
@Override
public void setSelectedNavigationItem(int position) {
}
@Override
public int getSelectedNavigationIndex() {
return 0;
}
@Override
public int getNavigationItemCount() {
return 0;
}
@Override
public void setTitle(CharSequence title) {
this.title = title;
}
@Override
public void setTitle(int resId) {
this.title = Robolectric.application.getString(resId);
}
@Override
public void setSubtitle(CharSequence subtitle) {
}
@Override
public void setSubtitle(int resId) {
}
@Override
public void setDisplayOptions(int options) {
}
@Override
public void setDisplayOptions(int options, int mask) {
}
@Override
public void setDisplayUseLogoEnabled(boolean useLogo) {
}
@Override
public void setDisplayShowHomeEnabled(boolean showHome) {
}
@Override
public void setDisplayHomeAsUpEnabled(boolean showHomeAsUp) {
this.showHomeAsUp = showHomeAsUp;
}
public boolean getDisplayHomeAsUpEnabled() {
return showHomeAsUp;
}
@Override
public void setDisplayShowTitleEnabled(boolean showTitle) {
}
@Override
public void setDisplayShowCustomEnabled(boolean showCustom) {
}
@Override
public void setBackgroundDrawable(Drawable d) {
}
@Override
public View getCustomView() {
return null;
}
@Override
public CharSequence getTitle() {
return title;
}
@Override
public CharSequence getSubtitle() {
return null;
}
@Override
public int getNavigationMode() {
return 0;
}
@Override
public void setNavigationMode(int mode) {
}
@Override
public int getDisplayOptions() {
return 0;
}
@Override
public Tab newTab() {
return null;
}
@Override
public void addTab(Tab tab) {
}
@Override
public void addTab(Tab tab, boolean setSelected) {
}
@Override
public void addTab(Tab tab, int position) {
}
@Override
public void addTab(Tab tab, int position, boolean setSelected) {
}
@Override
public void removeTab(Tab tab) {
}
@Override
public void removeTabAt(int position) {
}
@Override
public void removeAllTabs() {
}
@Override
public void selectTab(Tab tab) {
}
@Override
public Tab getSelectedTab() {
return null;
}
@Override
public Tab getTabAt(int index) {
return null;
}
@Override
public int getTabCount() {
return 0;
}
@Override
public int getHeight() {
return 0;
}
@Override
public void show() {
isShowing = true;
}
@Override
public void hide() {
isShowing = false;
}
@Override
public boolean isShowing() {
return isShowing;
}
@Override
public void addOnMenuVisibilityListener(OnMenuVisibilityListener listener) {
}
@Override
public void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener) {
}
}
| gpl-3.0 |
buaachen1993/Sword4Offer | src/P30_KLeastNumbers/KLeastNumbers.java | 1093 | package P30_KLeastNumbers;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class KLeastNumbers {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();
int length = input.length;
if(k > length || k == 0){
return result;
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2.compareTo(o1);
}
});
//维护一个代表最小值的容器
for (int i = 0; i < length; i++) {
if (maxHeap.size() != k) {
maxHeap.offer(input[i]);
} else if (maxHeap.peek() > input[i]) {
Integer temp = maxHeap.poll();
temp = null;
maxHeap.offer(input[i]);
}
}
for (Integer integer : maxHeap) {
result.add(integer);
}
return result;
}
}
| gpl-3.0 |