repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
krishnact/dhcpv6lib | src/java/other/org/himalay/dhcpv6/Authentication.java | 6957 | /**
Copyright (C) 2014 by
Krishna C Tripathi, Johns Creek, GA
All rights reserved.
This file is part of DHCPv6 Library.
DHCPv6 Library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
DHCPv6 Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with DHCPv6 Library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.himalay.dhcpv6;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.himalay.msgs.runtime.ByteArray;
import org.himalay.msgs.runtime.Created;
import org.himalay.msgs.runtime.DumpContext;
import org.himalay.msgs.runtime.NullStream;
@Created(date = "Fri Nov 07 11:29:35 EST 2014")
public class Authentication extends DhcpOptionFactory.DhcpOption { // Concrete
// type is
// Authentication
// members variables
// header
public DhcpOptionHeader header;
// protocol
public short protocol;
// algorithm
public short algorithm;
// rdm
public short rdm;
// replayDetection
public ReplayDetection replayDetection;
// authInfo
public ByteArray authInfo;
public Authentication() // throws Exception
{
init();
}
private void init() {
// Initialize header
header = new DhcpOptionHeader();
// Initialize protocol
// Initialize algorithm
// Initialize rdm
// Initialize replayDetection
replayDetection = new ReplayDetection();
// Initialize authInfo
authInfo = new ByteArray();
authInfo.setSizeType("EXTERNAL");
}
public int readNoHeader(DataInputStream istream) throws IOException {
preRead();
int retVal = 0;
// read protocol
{
protocol = (short) (istream.readUnsignedByte());
retVal += 1;
}
// read algorithm
{
algorithm = (short) (istream.readUnsignedByte());
retVal += 1;
}
// read rdm
{
rdm = (short) (istream.readUnsignedByte());
retVal += 1;
}
// read replayDetection
retVal += replayDetection.read(istream);
// read authInfo
{
authInfo.setSizeType("EXTERNAL");
int iRead = getHeader().length + (-11);
authInfo.setSize(iRead);
retVal += authInfo.read(istream);
}
postRead();
return retVal;
}
public int read(DataInputStream istream) throws IOException {
preRead();
int retVal = 0;
// read header
retVal += header.read(istream);
// read protocol
{
protocol = (short) (istream.readUnsignedByte());
retVal += 1;
}
// read algorithm
{
algorithm = (short) (istream.readUnsignedByte());
retVal += 1;
}
// read rdm
{
rdm = (short) (istream.readUnsignedByte());
retVal += 1;
}
// read replayDetection
retVal += replayDetection.read(istream);
// read authInfo
{
authInfo.setSizeType("EXTERNAL");
int iRead = getHeader().length + (-11);
authInfo.setSize(iRead);
retVal += authInfo.read(istream);
}
postRead();
return retVal;
}
public int write(DataOutputStream ostream) throws IOException {
preWrite();
int retVal = 0;
{
/** fix dependent sizes for header **/
}
{
/** fix dependent sizes for replayDetection **/
}
{
/** fix dependent sizes for authInfo **/
header.length = ((short) authInfo.getSize() - (-11));
}
// write header
if (header != null)
retVal += header.write(ostream);
// write protocol
ostream.writeByte(protocol);
retVal += 1;
// write algorithm
ostream.writeByte(algorithm);
retVal += 1;
// write rdm
ostream.writeByte(rdm);
retVal += 1;
// write replayDetection
if (replayDetection != null)
retVal += replayDetection.write(ostream);
// write authInfo
{
retVal += authInfo.write(ostream);
}
postWrite();
return retVal;
}
public int dump(DumpContext dc) throws IOException {
dc.indent();
dc.getPs().print("Authentication\n");
dc.increaseIndent();
int retVal = 0;
// write header
if (header != null) {
dc.indent();
dc.getPs().println("header");
retVal += header.dump(dc);
}
// write protocol
dc.indent();
dc.getPs().println(
"protocol=" + protocol + "(0x" + Integer.toHexString(protocol)
+ ")");
// write algorithm
dc.indent();
dc.getPs().println(
"algorithm=" + algorithm + "(0x"
+ Integer.toHexString(algorithm) + ")");
// write rdm
dc.indent();
dc.getPs().println(
"rdm=" + rdm + "(0x" + Integer.toHexString(rdm) + ")");
// write replayDetection
if (replayDetection != null) {
dc.indent();
dc.getPs().println("replayDetection");
retVal += replayDetection.dump(dc);
}
// write authInfo
dc.indent();
dc.getPs().print(
"authInfo: " + authInfo.getSize() + "(0x"
+ Integer.toHexString(authInfo.getSize()) + ")\n");
this.authInfo.dump(dc);
dc.decreaseIndent();
return retVal;
}
// Getter for header
// public DhcpOptionHeader getHeader()
// {
// return header ;
// }
// Setter for header
// public void setHeader(DhcpOptionHeader val)
// {
// this.header= val;
// }
// Getter for protocol
// public short getProtocol()
// {
// return protocol ;
// }
// Setter for protocol
// public void setProtocol(short val)
// {
// this.protocol= val;
// }
// Getter for algorithm
// public short getAlgorithm()
// {
// return algorithm ;
// }
// Setter for algorithm
// public void setAlgorithm(short val)
// {
// this.algorithm= val;
// }
// Getter for rdm
// public short getRdm()
// {
// return rdm ;
// }
// Setter for rdm
// public void setRdm(short val)
// {
// this.rdm= val;
// }
// Getter for replayDetection
// public ReplayDetection getReplayDetection()
// {
// return replayDetection ;
// }
// Setter for replayDetection
// public void setReplayDetection(ReplayDetection val)
// {
// this.replayDetection= val;
// }
// Getter for authInfo
// public ByteArray getAuthInfo()
// {
// return authInfo ;
// }
// Setter for authInfo
// public void setAuthInfo(ByteArray val)
// {
// this.authInfo= val;
// }
public void setAuthInfo(byte[] val) {
this.authInfo.setData(val);
}
public int getSize() throws IOException {
DataOutputStream dos = new DataOutputStream(new NullStream());
return this.write(dos);
}
public void setHeader(DhcpOptionHeader header) {
this.header = header;
}
public DhcpOptionHeader getHeader() {
return this.header;
}
}
// End of code | gpl-3.0 |
derBeukatt/AniDBTool | src/net/anidb/AnimeCharacterType.java | 2592 | /*
* Java AniDB API - A Java API for AniDB.net
* (c) Copyright 2009 grizzlyxp
* http://anidb.net/perl-bin/animedb.pl?show=userpage&uid=63935
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.anidb;
/**
* The type of the character in a specific anime.
* @author grizzlyxp
* (http://anidb.net/perl-bin/animedb.pl?show=userpage&uid=63935)
* @version <b>1.0</b>, 25.12.2009
* @see AnimeCharacter#getType()
* @see AnimeCharacter#setType(Integer)
*/
public class AnimeCharacterType {
/** Appears in. */
public final static AnimeCharacterType APPEARS_IN
= new AnimeCharacterType(0);
/** Cameo appearance in. */
public final static AnimeCharacterType CAMEO_APPEARANCE_IN
= new AnimeCharacterType(1);
/** Main character in. */
public final static AnimeCharacterType MAIN_CHARACTER_IN
= new AnimeCharacterType(2);
/** The value. */
private int value;
private AnimeCharacterType(final int value) {
super();
this.value = value;
}
/**
* Returns an instance of the class for the given value.
* @param value The value.
* @return The instance of <code>null</code>, if there is no instance for
* the given value.
*/
public static AnimeCharacterType getInstance(final int value) {
if (APPEARS_IN.value == value) {
return APPEARS_IN;
} else if (CAMEO_APPEARANCE_IN.value == value) {
return CAMEO_APPEARANCE_IN;
} else if (MAIN_CHARACTER_IN.value == value) {
return MAIN_CHARACTER_IN;
}
return null;
}
/**
* Returns the value.
* @return The value.
*/
public long getValue() {
return this.value;
}
public int hashCode() {
int result = 17;
result = 37 * result + this.value;
return result;
}
public boolean equals(final Object obj) {
AnimeCharacterType type;
if (obj instanceof AnimeCharacterType) {
type = (AnimeCharacterType) obj;
if (this.value == type.value) {
return true;
}
}
return false;
}
}
| gpl-3.0 |
SchrodingersSpy/TRHS_Club_Mod_2016 | lib/1.7.10-10.13.4.1448-1.7.10/unpacked/src/main/java/cpw/mods/fml/common/asm/FMLSanityChecker.java | 8129 | /*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.asm;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.security.cert.Certificate;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.logging.log4j.Level;
import net.minecraft.launchwrapper.LaunchClassLoader;
import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import cpw.mods.fml.common.CertificateHelper;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import cpw.mods.fml.common.patcher.ClassPatchManager;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import cpw.mods.fml.relauncher.FMLRelaunchLog;
import cpw.mods.fml.relauncher.IFMLCallHook;
import cpw.mods.fml.relauncher.Side;
public class FMLSanityChecker implements IFMLCallHook
{
private static final String FMLFINGERPRINT = "51:0A:FB:4C:AF:A4:A0:F2:F5:CF:C5:0E:B4:CC:3C:30:24:4A:E3:8E".toLowerCase().replace(":", "");
private static final String FORGEFINGERPRINT = "E3:C3:D5:0C:7C:98:6D:F7:4C:64:5C:0A:C5:46:39:74:1C:90:A5:57".toLowerCase().replace(":", "");
private static final String MCFINGERPRINT = "CD:99:95:96:56:F7:53:DC:28:D8:63:B4:67:69:F7:F8:FB:AE:FC:FC".toLowerCase().replace(":", "");
private LaunchClassLoader cl;
private boolean liveEnv;
public static File fmlLocation;
@Override
public Void call() throws Exception
{
CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
boolean goodFML = false;
boolean fmlIsJar = false;
if (codeSource.getLocation().getProtocol().equals("jar"))
{
fmlIsJar = true;
Certificate[] certificates = codeSource.getCertificates();
if (certificates!=null)
{
for (Certificate cert : certificates)
{
String fingerprint = CertificateHelper.getFingerprint(cert);
if (fingerprint.equals(FMLFINGERPRINT))
{
FMLRelaunchLog.info("Found valid fingerprint for FML. Certificate fingerprint %s", fingerprint);
goodFML = true;
}
else if (fingerprint.equals(FORGEFINGERPRINT))
{
FMLRelaunchLog.info("Found valid fingerprint for Minecraft Forge. Certificate fingerprint %s", fingerprint);
goodFML = true;
}
else
{
FMLRelaunchLog.severe("Found invalid fingerprint for FML: %s", fingerprint);
}
}
}
}
else
{
goodFML = true;
}
// Server is not signed, so assume it's good - a deobf env is dev time so it's good too
boolean goodMC = FMLLaunchHandler.side() == Side.SERVER || !liveEnv;
int certCount = 0;
try
{
Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever",false, cl);
codeSource = cbr.getProtectionDomain().getCodeSource();
}
catch (Exception e)
{
// Probably a development environment, or the server (the server is not signed)
goodMC = true;
}
JarFile mcJarFile = null;
if (fmlIsJar && !goodMC && codeSource.getLocation().getProtocol().equals("jar"))
{
try
{
String mcPath = codeSource.getLocation().getPath().substring(5);
mcPath = mcPath.substring(0, mcPath.lastIndexOf('!'));
mcPath = URLDecoder.decode(mcPath, Charsets.UTF_8.name());
mcJarFile = new JarFile(mcPath,true);
mcJarFile.getManifest();
JarEntry cbrEntry = mcJarFile.getJarEntry("net/minecraft/client/ClientBrandRetriever.class");
ByteStreams.toByteArray(mcJarFile.getInputStream(cbrEntry));
Certificate[] certificates = cbrEntry.getCertificates();
certCount = certificates != null ? certificates.length : 0;
if (certificates!=null)
{
for (Certificate cert : certificates)
{
String fingerprint = CertificateHelper.getFingerprint(cert);
if (fingerprint.equals(MCFINGERPRINT))
{
FMLRelaunchLog.info("Found valid fingerprint for Minecraft. Certificate fingerprint %s", fingerprint);
goodMC = true;
}
}
}
}
catch (Throwable e)
{
FMLRelaunchLog.log(Level.ERROR, e, "A critical error occurred trying to read the minecraft jar file");
}
finally
{
if (mcJarFile != null)
{
try
{
mcJarFile.close();
}
catch (IOException ioe)
{
// Noise
}
}
}
}
else
{
goodMC = true;
}
if (!goodMC)
{
FMLRelaunchLog.severe("The minecraft jar %s appears to be corrupt! There has been CRITICAL TAMPERING WITH MINECRAFT, it is highly unlikely minecraft will work! STOP NOW, get a clean copy and try again!",codeSource.getLocation().getFile());
if (!Boolean.parseBoolean(System.getProperty("fml.ignoreInvalidMinecraftCertificates","false")))
{
FMLRelaunchLog.severe("For your safety, FML will not launch minecraft. You will need to fetch a clean version of the minecraft jar file");
FMLRelaunchLog.severe("Technical information: The class net.minecraft.client.ClientBrandRetriever should have been associated with the minecraft jar file, " +
"and should have returned us a valid, intact minecraft jar location. This did not work. Either you have modified the minecraft jar file (if so " +
"run the forge installer again), or you are using a base editing jar that is changing this class (and likely others too). If you REALLY " +
"want to run minecraft in this configuration, add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings' in your launcher profile.");
FMLCommonHandler.instance().exitJava(1, false);
}
else
{
FMLRelaunchLog.severe("FML has been ordered to ignore the invalid or missing minecraft certificate. This is very likely to cause a problem!");
FMLRelaunchLog.severe("Technical information: ClientBrandRetriever was at %s, there were %d certificates for it", codeSource.getLocation(), certCount);
}
}
if (!goodFML)
{
FMLRelaunchLog.severe("FML appears to be missing any signature data. This is not a good thing");
}
return null;
}
@Override
public void injectData(Map<String, Object> data)
{
liveEnv = (Boolean)data.get("runtimeDeobfuscationEnabled");
cl = (LaunchClassLoader) data.get("classLoader");
File mcDir = (File)data.get("mcLocation");
fmlLocation = (File)data.get("coremodLocation");
ClassPatchManager.INSTANCE.setup(FMLLaunchHandler.side());
FMLDeobfuscatingRemapper.INSTANCE.setup(mcDir, cl, (String) data.get("deobfuscationFileName"));
}
}
| gpl-3.0 |
apruden/opal | opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/magma/view/ContinuousSummaryView.java | 5661 | /*******************************************************************************
* Copyright 2008(c) The OBiBa Consortium. 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.opal.web.gwt.app.client.magma.view;
import org.obiba.opal.web.gwt.app.client.i18n.Translations;
import org.obiba.opal.web.gwt.app.client.ui.DefaultFlexTable;
import org.obiba.opal.web.gwt.app.client.ui.SummaryFlexTable;
import org.obiba.opal.web.gwt.plot.client.HistogramChartFactory;
import org.obiba.opal.web.gwt.plot.client.NormalProbabilityChartFactory;
import org.obiba.opal.web.model.client.math.ContinuousSummaryDto;
import org.obiba.opal.web.model.client.math.DescriptiveStatsDto;
import org.obiba.opal.web.model.client.math.FrequencyDto;
import org.obiba.opal.web.model.client.math.IntervalFrequencyDto;
import com.google.common.collect.ImmutableList;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
/**
*
*/
public class ContinuousSummaryView extends Composite {
interface ContinuousSummaryViewUiBinder extends UiBinder<Widget, ContinuousSummaryView> {}
private static final ContinuousSummaryViewUiBinder uiBinder = GWT.create(ContinuousSummaryViewUiBinder.class);
private static final Translations translations = GWT.create(Translations.class);
@UiField
DefaultFlexTable grid;
@UiField
SimplePanel histogramPanel;
@UiField
SimplePanel normalProbability;
@UiField
SummaryFlexTable stats;
private HistogramChartFactory histogram;
private NormalProbabilityChartFactory qqPlot;
public ContinuousSummaryView(ContinuousSummaryDto continuous, ImmutableList<FrequencyDto> frequenciesNonMissing,
ImmutableList<FrequencyDto> frequenciesMissing, double totalNonMissing, double totalMissing) {
initWidget(uiBinder.createAndBindUi(this));
initDescriptivestats(continuous);
stats.drawHeader();
double total = totalNonMissing + totalMissing;
stats.drawValuesFrequencies(frequenciesNonMissing, translations.nonMissing(), translations.notEmpty(),
totalNonMissing, total);
stats.drawValuesFrequencies(frequenciesMissing, translations.missingLabel(), translations.naLabel(), totalMissing,
total);
stats.drawTotal(total);
}
private void initDescriptivestats(ContinuousSummaryDto continuous) {
DescriptiveStatsDto descriptiveStats = continuous.getSummary();
addDescriptiveStatistics(descriptiveStats);
if(descriptiveStats.getVariance() > 0) {
histogram = new HistogramChartFactory();
JsArray<IntervalFrequencyDto> frequencyArray = continuous.getIntervalFrequencyArray();
if(frequencyArray != null) {
int length = frequencyArray.length();
for(int i = 0; i < length; i++) {
IntervalFrequencyDto value = frequencyArray.get(i);
histogram.push(value.getDensity(), value.getLower(), value.getUpper());
}
}
qqPlot = new NormalProbabilityChartFactory(descriptiveStats.getMin(), descriptiveStats.getMax());
qqPlot.push(descriptiveStats.getPercentilesArray(), continuous.getDistributionPercentilesArray());
}
}
private void addDescriptiveStatistics(DescriptiveStatsDto descriptiveStats) {
grid.clear();
grid.setHeader(0, translations.descriptiveStatistics());
grid.setHeader(1, translations.value());
int row = 0;
addGridStat(translations.NLabel(), Math.round(descriptiveStats.getN()), row++);
addGridStat(translations.min(), descriptiveStats.getMin(), row++);
addGridStat(translations.max(), descriptiveStats.getMax(), row++);
addGridStat(translations.meanLabel(), descriptiveStats.getMean(), row++);
addGridStat(translations.geometricMeanLabel(), descriptiveStats.getGeometricMean(), row++);
addGridStat(translations.median(), descriptiveStats.getMedian(), row++);
addGridStat(translations.standardDeviationLabel(), descriptiveStats.getStdDev(), row++);
addGridStat(translations.variance(), descriptiveStats.getVariance(), row++);
addGridStat(translations.skewness(), descriptiveStats.getSkewness(), row++);
addGridStat(translations.kurtosis(), descriptiveStats.getKurtosis(), row++);
addGridStat(translations.sum(), descriptiveStats.getSum(), row++);
addGridStat(translations.sumOfSquares(), descriptiveStats.getSumsq(), row++);
}
@Override
protected void onLoad() {
super.onLoad();
if(histogram != null) {
histogramPanel.clear();
histogramPanel.add(histogram.createChart(translations.histogram(), translations.density()));
}
if(qqPlot != null) {
normalProbability.clear();
normalProbability.add(qqPlot.createChart(translations.normalProbability(), translations.theoreticalQuantiles(),
translations.sampleQuantiles()));
}
}
private void addGridStat(String title, double number, int row) {
NumberFormat nf = NumberFormat.getFormat("#.####");
grid.setWidget(row, 0, new Label(title));
grid.setWidget(row, 1, new Label(String.valueOf(nf.format(number))));
}
}
| gpl-3.0 |
PeterCassetta/pixel-dungeon-rebalanced | java/com/petercassetta/pdrebalanced/effects/particles/EnergyParticle.java | 1899 | /*
* Pixel Dungeon: Rebalanced
* Copyright (C) 2012-2015 Oleg Dolya
* Copyright (C) 2015 Peter Cassetta
*
* 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.petercassetta.pdrebalanced.effects.particles;
import com.petercassetta.noosa.particles.Emitter;
import com.petercassetta.noosa.particles.PixelParticle;
import com.petercassetta.noosa.particles.Emitter.Factory;
import com.petercassetta.utils.PointF;
import com.petercassetta.utils.Random;
public class EnergyParticle extends PixelParticle {
public static final Emitter.Factory FACTORY = new Factory() {
@Override
public void emit( Emitter emitter, int index, float x, float y ) {
((EnergyParticle)emitter.recycle( EnergyParticle.class )).reset( x, y );
}
@Override
public boolean lightMode() {
return true;
};
};
public EnergyParticle() {
super();
lifespan = 1f;
color( 0xFFFFAA );
speed.polar( Random.Float( PointF.PI2 ), Random.Float( 24, 32 ) );
}
public void reset( float x, float y ) {
revive();
left = lifespan;
this.x = x - speed.x * lifespan;
this.y = y - speed.y * lifespan;
}
@Override
public void update() {
super.update();
float p = left / lifespan;
am = p < 0.5f ? p * p * 4 : (1 - p) * 2;
size( Random.Float( 5 * left / lifespan ) );
}
} | gpl-3.0 |
Rima-B/mica2 | mica-core/src/main/java/org/obiba/mica/file/NoSuchTempFileException.java | 791 | /*
* Copyright (c) 2017 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.file;
import java.util.NoSuchElementException;
import javax.validation.constraints.NotNull;
public class NoSuchTempFileException extends NoSuchElementException {
private static final long serialVersionUID = 5887330656285998606L;
@NotNull
private final String id;
public NoSuchTempFileException(@NotNull String id) {
super("No such temp file '" + id + "'");
this.id = id;
}
public String getId() {
return id;
}
}
| gpl-3.0 |
duckofyork/mindmapsdb | mindmaps-graql/src/main/java/io/mindmaps/graql/internal/query/aggregate/MaxAggregate.java | 1527 | /*
* MindmapsDB - A Distributed Semantic Database
* Copyright (C) 2016 Mindmaps Research Ltd
*
* MindmapsDB 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.
*
* MindmapsDB 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 MindmapsDB. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package io.mindmaps.graql.internal.query.aggregate;
import io.mindmaps.core.model.Concept;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import static java.util.Comparator.naturalOrder;
/**
* Aggregate that finds maximum of a match query.
*/
public class MaxAggregate extends AbstractAggregate<Map<String, Concept>, Optional<?>> {
private final String varName;
public MaxAggregate(String varName) {
this.varName = varName;
}
@Override
public Optional<?> apply(Stream<? extends Map<String, Concept>> stream) {
return stream.map(result -> (Comparable) result.get(varName).getValue()).max(naturalOrder());
}
@Override
public String toString() {
return "max $" + varName;
}
}
| gpl-3.0 |
chvink/kilomek | megamek/src/megamek/client/ui/swing/MechTileset.java | 22214 | /*
* MegaMek - Copyright (C) 2000-2002 Ben Mazur (bmazur@sev.org)
* Copyright © 2013 Edward Cullen (eddy@obsessedcomputers.co.uk)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
/*
* MechTileset.java
*
* Created on April 15, 2002, 9:53 PM
*/
package megamek.client.ui.swing;
import java.awt.Component;
import java.awt.Image;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.util.HashMap;
import megamek.common.Aero;
import megamek.common.BattleArmor;
import megamek.common.Dropship;
import megamek.common.Entity;
import megamek.common.EntityMovementMode;
import megamek.common.EntityWeightClass;
import megamek.common.FighterSquadron;
import megamek.common.GunEmplacement;
import megamek.common.Infantry;
import megamek.common.Jumpship;
import megamek.common.Mech;
import megamek.common.Protomech;
import megamek.common.SmallCraft;
import megamek.common.SpaceStation;
import megamek.common.Tank;
import megamek.common.TeleMissile;
import megamek.common.Warship;
/**
* MechTileset is a misleading name, as this matches any unit, not just mechs
* with the appropriate image. It requires mechset.txt (in the unit images directory), the
* format of which is explained in that file.
*
* @author Ben
*/
public class MechTileset {
private String ULTRA_LIGHT_STRING = "default_ultra_light"; //$NON-NLS-1$
private String LIGHT_STRING = "default_light"; //$NON-NLS-1$
private String MEDIUM_STRING = "default_medium"; //$NON-NLS-1$
private String HEAVY_STRING = "default_heavy"; //$NON-NLS-1$
private String ASSAULT_STRING = "default_assault"; //$NON-NLS-1$
private String SUPER_HEAVY_MECH_STRING = "default_super_heavy_mech"; //$NON-NLS-1$
private String QUAD_STRING = "default_quad"; //$NON-NLS-1$
private String TRACKED_STRING = "default_tracked"; //$NON-NLS-1$
private String TRACKED_HEAVY_STRING = "default_tracked_heavy"; //$NON-NLS-1$
private String TRACKED_ASSAULT_STRING = "default_tracked_assault"; //$NON-NLS-1$
private String WHEELED_STRING = "default_wheeled"; //$NON-NLS-1$
private String WHEELED_HEAVY_STRING = "default_wheeled_heavy"; //$NON-NLS-1$
private String HOVER_STRING = "default_hover"; //$NON-NLS-1$
private String NAVAL_STRING = "default_naval"; //$NON-NLS-1$
private String SUBMARINE_STRING = "default_submarine"; //$NON-NLS-1$
private String HYDROFOIL_STRING = "default_hydrofoil"; //$NON-NLS-1$
private String VTOL_STRING = "default_vtol"; //$NON-NLS-1$
private String INF_STRING = "default_infantry"; //$NON-NLS-1$
private String BA_STRING = "default_ba"; //$NON-NLS-1$
private String PROTO_STRING = "default_proto"; //$NON-NLS-1$
private String GUN_EMPLACEMENT_STRING = "default_gun_emplacement"; //$NON-NLS-1$
private String WIGE_STRING = "default_wige"; //$NON-NLS-1$
private String AERO_STRING = "default_aero"; //$NON-NLS-1$
private String SMALL_CRAFT_AERO_STRING = "default_small_craft_aero"; //$NON-NLS-1$
private String SMALL_CRAFT_SPHERE_STRING = "default_small_craft_sphere"; //$NON-NLS-1$
private String DROPSHIP_AERO_STRING = "default_dropship_aero"; //$NON-NLS-1$
private String DROPSHIP_AERO_STRING_0 = "default_dropship_aero_0"; //$NON-NLS-1$
private String DROPSHIP_AERO_STRING_1 = "default_dropship_aero_1"; //$NON-NLS-1$
private String DROPSHIP_AERO_STRING_2 = "default_dropship_aero_2"; //$NON-NLS-1$
private String DROPSHIP_AERO_STRING_3 = "default_dropship_aero_3"; //$NON-NLS-1$
private String DROPSHIP_AERO_STRING_4 = "default_dropship_aero_4"; //$NON-NLS-1$
private String DROPSHIP_AERO_STRING_5 = "default_dropship_aero_5"; //$NON-NLS-1$
private String DROPSHIP_AERO_STRING_6 = "default_dropship_aero_6"; //$NON-NLS-1$
private String DROPSHIP_SPHERE_STRING = "default_dropship_sphere"; //$NON-NLS-1$
private String DROPSHIP_SPHERE_STRING_0 = "default_dropship_sphere_0"; //$NON-NLS-1$
private String DROPSHIP_SPHERE_STRING_1 = "default_dropship_sphere_1"; //$NON-NLS-1$
private String DROPSHIP_SPHERE_STRING_2 = "default_dropship_sphere_2"; //$NON-NLS-1$
private String DROPSHIP_SPHERE_STRING_3 = "default_dropship_sphere_3"; //$NON-NLS-1$
private String DROPSHIP_SPHERE_STRING_4 = "default_dropship_sphere_4"; //$NON-NLS-1$
private String DROPSHIP_SPHERE_STRING_5 = "default_dropship_sphere_5"; //$NON-NLS-1$
private String DROPSHIP_SPHERE_STRING_6 = "default_dropship_sphere_6"; //$NON-NLS-1$
private String JUMPSHIP_STRING = "default_jumpship"; //$NON-NLS-1$
private String WARSHIP_STRING = "default_warship"; //$NON-NLS-1$
private String SPACE_STATION_STRING = "default_space_station"; //$NON-NLS-1$
private String FIGHTER_SQUADRON_STRING = "default_fighter_squadron"; //$NON-NLS-1$
private String TELE_MISSILE_STRING = "default_tele_missile"; //$NON-NLS-1$
private MechEntry default_ultra_light;
private MechEntry default_light;
private MechEntry default_medium;
private MechEntry default_heavy;
private MechEntry default_assault;
private MechEntry default_super_heavy_mech;
private MechEntry default_quad;
private MechEntry default_tracked;
private MechEntry default_tracked_heavy;
private MechEntry default_tracked_assault;
private MechEntry default_wheeled;
private MechEntry default_wheeled_heavy;
private MechEntry default_hover;
private MechEntry default_naval;
private MechEntry default_submarine;
private MechEntry default_hydrofoil;
private MechEntry default_vtol;
private MechEntry default_inf;
private MechEntry default_ba;
private MechEntry default_proto;
private MechEntry default_gun_emplacement;
private MechEntry default_wige;
private MechEntry default_aero;
private MechEntry default_small_craft_aero;
private MechEntry default_small_craft_sphere;
private MechEntry default_dropship_aero;
private MechEntry default_dropship_aero_0;
private MechEntry default_dropship_aero_1;
private MechEntry default_dropship_aero_2;
private MechEntry default_dropship_aero_3;
private MechEntry default_dropship_aero_4;
private MechEntry default_dropship_aero_5;
private MechEntry default_dropship_aero_6;
private MechEntry default_dropship_sphere;
private MechEntry default_dropship_sphere_0;
private MechEntry default_dropship_sphere_1;
private MechEntry default_dropship_sphere_2;
private MechEntry default_dropship_sphere_3;
private MechEntry default_dropship_sphere_4;
private MechEntry default_dropship_sphere_5;
private MechEntry default_dropship_sphere_6;
private MechEntry default_jumpship;
private MechEntry default_warship;
private MechEntry default_space_station;
private MechEntry default_fighter_squadron;
private MechEntry default_tele_missile;
private HashMap<String, MechEntry> exact = new HashMap<String, MechEntry>();
private HashMap<String, MechEntry> chassis = new HashMap<String, MechEntry>();
File dir;
/**
* Creates new MechTileset.
*
* @deprecated Use {@link MechTileset(File)} instead.
*/
@Deprecated
public MechTileset(String dir_path)
{
if (dir_path == null) {
throw new IllegalArgumentException("must provide dir_path");
}
dir = new File(dir_path);
}
/**
* Creates new MechTileset.
*
* @param dir_path Path to the tileset directory.
*/
public MechTileset(File dir_path)
{
if (dir_path == null) {
throw new IllegalArgumentException("must provide dir_path");
}
dir = dir_path;
}
public Image imageFor(Entity entity, Component comp, int secondaryPos) {
MechEntry entry = entryFor(entity, secondaryPos);
if (entry == null) {
System.err
.println("Entry is null make sure that there is a default entry for "
+ entity.getShortNameRaw()
+ " in both mechset.txt and wreckset.txt. Default to "
+ LIGHT_STRING);
System.err.flush();
entry = default_light;
}
if (entry.getImage() == null) {
entry.loadImage(comp);
}
return entry.getImage();
}
/**
* Returns the MechEntry corresponding to the entity
*/
private MechEntry entryFor(Entity entity, int secondaryPos) {
// first, check for exact matches
if (secondaryPos != -1) {
if (exact.containsKey(entity.getShortNameRaw().toUpperCase()+"_"+secondaryPos)) {
return exact.get(entity.getShortNameRaw().toUpperCase()+"_"+secondaryPos);
}
// next, chassis matches
if (chassis.containsKey(entity.getChassis().toUpperCase()+"_"+secondaryPos)) {
return chassis.get(entity.getChassis().toUpperCase()+"_"+secondaryPos);
}
// last, the generic model
return genericFor(entity, secondaryPos);
}
if (exact.containsKey(entity.getShortNameRaw().toUpperCase())) {
return exact.get(entity.getShortNameRaw().toUpperCase());
}
// next, chassis matches
if (chassis.containsKey(entity.getChassis().toUpperCase())) {
return chassis.get(entity.getChassis().toUpperCase());
}
// last, the generic model
return genericFor(entity, secondaryPos);
}
public MechEntry genericFor(Entity entity, int secondaryPos) {
if (entity instanceof BattleArmor) {
return default_ba;
}
if (entity instanceof Infantry) {
return default_inf;
}
if (entity instanceof Protomech) {
return default_proto;
}
// mech, by weight
if (entity instanceof Mech) {
if (entity.getMovementMode() == EntityMovementMode.QUAD) {
return default_quad;
}
if (entity.getWeightClass() == EntityWeightClass.WEIGHT_LIGHT) {
return default_light;
} else if (entity.getWeightClass() == EntityWeightClass.WEIGHT_MEDIUM) {
return default_medium;
} else if (entity.getWeightClass() == EntityWeightClass.WEIGHT_HEAVY) {
return default_heavy;
} else if (entity.getWeightClass() == EntityWeightClass.WEIGHT_ULTRA_LIGHT) {
return default_ultra_light;
} else if (entity.getWeightClass() == EntityWeightClass.WEIGHT_SUPER_HEAVY) {
return default_super_heavy_mech;
} else {
return default_assault;
}
}
if (entity.getMovementMode() == EntityMovementMode.NAVAL) {
return default_naval;
}
if (entity.getMovementMode() == EntityMovementMode.SUBMARINE) {
return default_submarine;
}
if (entity.getMovementMode() == EntityMovementMode.HYDROFOIL) {
return default_hydrofoil;
}
if (entity instanceof Tank) {
if (entity.getMovementMode() == EntityMovementMode.TRACKED) {
if (entity.getWeightClass() == EntityWeightClass.WEIGHT_HEAVY) {
return default_tracked_heavy;
} else if (entity.getWeightClass() == EntityWeightClass.WEIGHT_ASSAULT) {
return default_tracked_assault;
} else {
return default_tracked;
}
}
if (entity.getMovementMode() == EntityMovementMode.WHEELED) {
if (entity.getWeightClass() == EntityWeightClass.WEIGHT_HEAVY) {
return default_wheeled_heavy;
}
return default_wheeled;
}
if (entity.getMovementMode() == EntityMovementMode.HOVER) {
return default_hover;
}
if (entity.getMovementMode() == EntityMovementMode.VTOL) {
return default_vtol;
}
if (entity.getMovementMode() == EntityMovementMode.WIGE) {
return default_wige;
}
}
if (entity instanceof GunEmplacement) {
return default_gun_emplacement;
}
if (entity instanceof Aero) {
if (entity instanceof SpaceStation) {
return default_space_station;
}
if (entity instanceof Warship) {
return default_warship;
}
if (entity instanceof Jumpship) {
return default_jumpship;
}
if (entity instanceof Dropship) {
Dropship ds = (Dropship) entity;
if (ds.isSpheroid()) {
switch (secondaryPos) {
case -1:
return default_dropship_sphere;
case 0:
return default_dropship_sphere_0;
case 1:
return default_dropship_sphere_1;
case 2:
return default_dropship_sphere_2;
case 3:
return default_dropship_sphere_3;
case 4:
return default_dropship_sphere_4;
case 5:
return default_dropship_sphere_5;
case 6:
return default_dropship_sphere_6;
}
} else {
switch (secondaryPos) {
case -1:
return default_dropship_aero;
case 0:
return default_dropship_aero_0;
case 1:
return default_dropship_aero_1;
case 2:
return default_dropship_aero_2;
case 3:
return default_dropship_aero_3;
case 4:
return default_dropship_aero_4;
case 5:
return default_dropship_aero_5;
case 6:
return default_dropship_aero_6;
}
}
}
if (entity instanceof FighterSquadron) {
return default_fighter_squadron;
}
if (entity instanceof SmallCraft) {
SmallCraft sc = (SmallCraft) entity;
if (sc.isSpheroid()) {
return default_small_craft_sphere;
}
return default_small_craft_aero;
}
if (entity instanceof TeleMissile) {
return default_tele_missile;
}
return default_aero;
}
// TODO: better exception?
throw new IndexOutOfBoundsException("can't find an image for that mech"); //$NON-NLS-1$
}
public void loadFromFile(String filename) throws IOException {
// make inpustream for board
Reader r = new BufferedReader(new FileReader(new File(dir, filename)));
// read board, looking for "size"
StreamTokenizer st = new StreamTokenizer(r);
st.eolIsSignificant(true);
st.commentChar('#');
st.quoteChar('"');
st.wordChars('_', '_');
while (st.nextToken() != StreamTokenizer.TT_EOF) {
String name = null;
String imageName = null;
if ((st.ttype == StreamTokenizer.TT_WORD)
&& st.sval.equalsIgnoreCase("include")) { //$NON-NLS-1$
st.nextToken();
name = st.sval;
System.out.print("Loading more unit images from "); //$NON-NLS-1$
System.out.print(name);
System.out.println("..."); //$NON-NLS-1$
try {
loadFromFile(name);
System.out.print("... finished "); //$NON-NLS-1$
System.out.print(name);
System.out.println("."); //$NON-NLS-1$
} catch (IOException ioerr) {
System.out.print("... failed: "); //$NON-NLS-1$
System.out.print(ioerr.getMessage());
System.out.println("."); //$NON-NLS-1$
}
} else if ((st.ttype == StreamTokenizer.TT_WORD)
&& st.sval.equalsIgnoreCase("chassis")) { //$NON-NLS-1$
st.nextToken();
name = st.sval;
st.nextToken();
imageName = st.sval;
// add to list
chassis.put(name.toUpperCase(), new MechEntry(name, imageName));
} else if ((st.ttype == StreamTokenizer.TT_WORD)
&& st.sval.equalsIgnoreCase("exact")) { //$NON-NLS-1$
st.nextToken();
name = st.sval;
st.nextToken();
imageName = st.sval;
// add to list
exact.put(name.toUpperCase(), new MechEntry(name, imageName));
}
}
r.close();
default_ultra_light = exact.get(ULTRA_LIGHT_STRING.toUpperCase());
default_light = exact.get(LIGHT_STRING.toUpperCase());
default_medium = exact.get(MEDIUM_STRING.toUpperCase());
default_heavy = exact.get(HEAVY_STRING.toUpperCase());
default_assault = exact.get(ASSAULT_STRING.toUpperCase());
default_super_heavy_mech = exact.get(SUPER_HEAVY_MECH_STRING.toUpperCase());
default_quad = exact.get(QUAD_STRING.toUpperCase());
default_tracked = exact.get(TRACKED_STRING.toUpperCase());
default_tracked_heavy = exact.get(TRACKED_HEAVY_STRING.toUpperCase());
default_tracked_assault = exact.get(TRACKED_ASSAULT_STRING
.toUpperCase());
default_wheeled = exact.get(WHEELED_STRING.toUpperCase());
default_wheeled_heavy = exact.get(WHEELED_HEAVY_STRING.toUpperCase());
default_hover = exact.get(HOVER_STRING.toUpperCase());
default_naval = exact.get(NAVAL_STRING.toUpperCase());
default_submarine = exact.get(SUBMARINE_STRING.toUpperCase());
default_hydrofoil = exact.get(HYDROFOIL_STRING.toUpperCase());
default_vtol = exact.get(VTOL_STRING.toUpperCase());
default_inf = exact.get(INF_STRING.toUpperCase());
default_ba = exact.get(BA_STRING.toUpperCase());
default_proto = exact.get(PROTO_STRING.toUpperCase());
default_gun_emplacement = exact.get(GUN_EMPLACEMENT_STRING
.toUpperCase());
default_wige = exact.get(WIGE_STRING.toUpperCase());
default_aero = exact.get(AERO_STRING.toUpperCase());
default_small_craft_aero = exact.get(SMALL_CRAFT_AERO_STRING.toUpperCase());
default_dropship_aero = exact.get(DROPSHIP_AERO_STRING.toUpperCase());
default_dropship_aero_0 = exact.get(DROPSHIP_AERO_STRING_0.toUpperCase());
default_dropship_aero_1 = exact.get(DROPSHIP_AERO_STRING_1.toUpperCase());
default_dropship_aero_2 = exact.get(DROPSHIP_AERO_STRING_2.toUpperCase());
default_dropship_aero_3 = exact.get(DROPSHIP_AERO_STRING_3.toUpperCase());
default_dropship_aero_4 = exact.get(DROPSHIP_AERO_STRING_4.toUpperCase());
default_dropship_aero_5 = exact.get(DROPSHIP_AERO_STRING_5.toUpperCase());
default_dropship_aero_6 = exact.get(DROPSHIP_AERO_STRING_6.toUpperCase());
default_small_craft_sphere = exact.get(SMALL_CRAFT_SPHERE_STRING.toUpperCase());
default_dropship_sphere = exact.get(DROPSHIP_SPHERE_STRING.toUpperCase());
default_dropship_sphere_0 = exact.get(DROPSHIP_SPHERE_STRING_0.toUpperCase());
default_dropship_sphere_1 = exact.get(DROPSHIP_SPHERE_STRING_1.toUpperCase());
default_dropship_sphere_2 = exact.get(DROPSHIP_SPHERE_STRING_2.toUpperCase());
default_dropship_sphere_3 = exact.get(DROPSHIP_SPHERE_STRING_3.toUpperCase());
default_dropship_sphere_4 = exact.get(DROPSHIP_SPHERE_STRING_4.toUpperCase());
default_dropship_sphere_5 = exact.get(DROPSHIP_SPHERE_STRING_5.toUpperCase());
default_dropship_sphere_6 = exact.get(DROPSHIP_SPHERE_STRING_6.toUpperCase());
default_jumpship = exact.get(JUMPSHIP_STRING.toUpperCase());
default_warship = exact.get(WARSHIP_STRING.toUpperCase());
default_space_station = exact.get(SPACE_STATION_STRING.toUpperCase());
default_fighter_squadron = exact.get(FIGHTER_SQUADRON_STRING.toUpperCase());
default_tele_missile = exact.get(TELE_MISSILE_STRING.toUpperCase());
}
/**
* Stores the name, image file name, and image (once loaded) for a mech or
* other entity
*/
private class MechEntry {
private String imageFile;
private Image image;
public MechEntry(String name, String imageFile) {
this.imageFile = imageFile;
image = null;
}
public Image getImage() {
return image;
}
public void loadImage(Component comp) {
// System.out.println("loading mech image...");
File fin = new File(dir, imageFile);
if (!fin.exists()) {
System.out.println("Warning: MechTileSet is trying to " +
"load a file that doesn't exist: "
+ fin.getPath());
}
image = comp.getToolkit().getImage(fin.toString());
}
}
}
| gpl-3.0 |
hartwigmedical/hmftools | amber/src/test/java/com/hartwig/hmftools/amber/TumorBAFFactoryTest.java | 2232 | package com.hartwig.hmftools.amber;
import static org.junit.Assert.assertEquals;
import com.hartwig.hmftools.common.amber.BaseDepth;
import com.hartwig.hmftools.common.amber.ModifiableBaseDepth;
import com.hartwig.hmftools.common.amber.ModifiableTumorBAF;
import com.hartwig.hmftools.common.samtools.SamRecordUtils;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import htsjdk.samtools.SAMRecord;
public class TumorBAFFactoryTest
{
@Test
public void useQualityOfBaseAfterDel()
{
int minQuality = SamRecordUtils.getBaseQuality('J');
final SAMRecord lowQualDel = buildSamRecord(1000, "1M1D1M", "CT", "FI");
final SAMRecord highQualDel = buildSamRecord(1000, "1M1D1M", "CT", "FJ");
final ModifiableTumorBAF victim = createDefault("5", 1001);
new TumorBAFFactory(minQuality).addEvidence(victim, lowQualDel);
assertEquals(0, victim.tumorReadDepth());
new TumorBAFFactory(minQuality).addEvidence(victim, highQualDel);
assertEquals(1, victim.tumorReadDepth());
}
@NotNull
private static ModifiableTumorBAF createDefault(@NotNull final String chromosome, final int position)
{
final ModifiableBaseDepth normal = ModifiableBaseDepth.create()
.setChromosome(chromosome)
.setPosition(position)
.setRef(BaseDepth.Base.A)
.setRefSupport(3)
.setAlt(BaseDepth.Base.T)
.setAltSupport(3)
.setReadDepth(6)
.setIndelCount(0);
return TumorBAFFactory.create(normal);
}
private SAMRecord buildSamRecord(
final int alignmentStart, @NotNull final String cigar, @NotNull final String readString, @NotNull final String qualities)
{
final SAMRecord record = new SAMRecord(null);
record.setAlignmentStart(alignmentStart);
record.setCigarString(cigar);
record.setReadString(readString);
record.setReadNegativeStrandFlag(false);
record.setBaseQualityString(qualities);
record.setMappingQuality(20);
record.setDuplicateReadFlag(false);
record.setReadUnmappedFlag(false);
return record;
}
}
| gpl-3.0 |
timgcavell/blackjack | Card.java | 1190 | import java.io.Serializable;
class Card implements Serializable {
public enum CardName {ACE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN,JACK,QUEEN,KING}
public enum CardSuite {HEART,DIAMOND,SPADE,CLUB}
public enum CardColor {RED,BLACK}
private final CardName name;
private final CardSuite suite;
private final CardColor color;
private final int rank;
private final int value;
Card(CardName name, CardSuite suite) {
this.name = name;
this.suite = suite;
this.color = (suite.equals(CardSuite.HEART) || suite.equals(CardSuite.DIAMOND)) ? CardColor.RED : CardColor.BLACK;
this.rank = name.ordinal() + 1;
if (name.ordinal() < 10) {
value = name.ordinal() + 1;
}
else {
value = 10;
}
}
public String getName() {
return name.toString();
}
@SuppressWarnings("unused")
public String getSuite() {
return suite.toString();
}
@SuppressWarnings("unused")
public String getColor() {
return color.toString();
}
@SuppressWarnings("unused")
public int getRank() {
return rank;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return getName();
}
}
| gpl-3.0 |
Bilkan/ArabicePubReader | src/src/net/uyghurdev/arabicepubreader/re/FileAdapter.java | 1487 | package net.uyghurdev.arabicepubreader.re;
import java.util.ArrayList;
import java.util.HashMap;
import net.uyghurdev.arabicepubreader.re.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class FileAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String,String>> map;
private static LayoutInflater inflater = null;
public FileAdapter(Activity a, ArrayList<HashMap<String,String>> fonts){
activity = a;
map = fonts;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return map.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return map.get(arg0);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.fontlist, null);
}
TextView color=(TextView)vi.findViewById(R.id.item);
// color.setTypeface(Properties.UIFont);
color.setText(ArabicUtilities.reshape(map.get(position).get("path")));
return vi;
}
}
| gpl-3.0 |
Jose-R-Vieira/JoseRoboExecutor | JoseRobotExecutor/src/main/java/br/com/jose/robot/archives/office/read/ReadCSVFile.java | 79 | package br.com.jose.robot.archives.office.read;
public class ReadCSVFile {
}
| gpl-3.0 |
ScaniaTV/PhantomBot | source/tv/phantombot/event/pubsub/moderation/PubSubModerationUnTimeoutEvent.java | 1057 | /*
* Copyright (C) 2016-2018 phantombot.tv
*
* 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 tv.phantombot.event.pubsub.moderation;
public class PubSubModerationUnTimeoutEvent extends PubSubModerationEvent {
/*
* Class constructor
*
* @param {String} username
* @param {String} creator
*/
public PubSubModerationUnTimeoutEvent(String username, String creator) {
super(username, creator, null);
}
}
| gpl-3.0 |
JayTea173/saiyancraft | SaiyanCraft/src/main/java/com/jaynopp/saiyancraft/gui/ScrollView.java | 3294 | package com.jaynopp.saiyancraft.gui;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.opengl.GL11;
import com.jaynopp.saiyancraft.SaiyanCraft;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
public class ScrollView {
int x, y, width, height, scrollButtonID;
SaiyanCraftGuiButton scrollButton;
final ResourceLocation bgTexture = new ResourceLocation(SaiyanCraft.modId, "textures/common/white.png");
float position;
protected List<ScrollViewItem> items;
protected ScrollViewItem hoveredItem;
public ScrollView(int x, int y, int width, int height, int scrollButtonID){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.scrollButtonID = scrollButtonID;
this.items = new ArrayList<ScrollViewItem>();
}
public ScrollViewItem AddItem(Object object, String displayText){
System.out.println("Register ScrollViewItem: " + displayText);
ScrollViewItem item = new ScrollViewItem(object, displayText);
items.add(item);
return item;
}
public void Clear(){
items.clear();
}
public void Draw(TextureManager renderer, Gui gui, int mouseX, int mouseY){
if (scrollButton.isDown){
position = (float)(mouseY - y - 3) / (float)(height-9);
if (position > 1f)
position = 1f;
if (position < 0f)
position = 0f;
}
DrawBar(gui);
DrawItems(gui, mouseX, mouseY);
}
protected void DrawItems(Gui gui, int mouseX, int mouseY){
int currY = 0;
FontRenderer fr = Minecraft.getMinecraft().fontRendererObj;
fr.FONT_HEIGHT = 8;
boolean hovering = false;
for (ScrollViewItem item : items){
gui.drawString(fr, item.displayText, x + 2, y + currY + 2, RGBToInt(255, 255 - (int)(.2f * item.hoverTime * 85), 255 - (int)(1f * item.hoverTime * 85)));
if (mouseX > x + 2 && mouseX < x + width && mouseY > y + 2 + currY && mouseY < y + 2 + currY + 10){
hovering = true;
if (hoveredItem != item)
hoveredItem = item;
}
if (item == hoveredItem){
if (item.hoverTime < 3)
item.hoverTime++;
} else if (item.hoverTime > 0)
item.hoverTime--;
currY += 12;
}
if (!hovering){
if (hoveredItem != null){
hoveredItem = null;
}
}
}
protected void DrawBar(Gui gui){
scrollButton.yPosition = y + (int)(position * (height - 9));
Minecraft.getMinecraft().renderEngine.bindTexture(bgTexture);
GL11.glPushMatrix();
GL11.glColor3f(0f, 0f, 0f);
gui.drawTexturedModalRect(x + width - 10, y, 0, 0, 10, height);
GL11.glPopMatrix();
GL11.glColor3f(1f, 1f, 1f);
}
public static int RGBToInt(int r, int g, int b){
r = Clamp(r, 0, 255);
g = Clamp(g, 0, 255);
b = Clamp(b, 0, 255);
return r + g * 256 + b * 256 * 256;
}
public static int Clamp (int val, int low, int high){
return Math.max(low, Math.min(high, val));
}
public GuiButton RegisterScrollButton(){
return scrollButton = new SaiyanCraftGuiButton(scrollButtonID, x + width - 9, y, 8, 8, "");
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java | 3304 | package org.baeldung.properties;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConfigPropertiesDemoApplication.class)
@TestPropertySource("classpath:configprops-test.properties")
public class ConfigPropertiesIntegrationTest {
@Autowired
private ConfigProperties properties;
@Test
public void whenSimplePropertyQueriedthenReturnsProperty() throws Exception {
Assert.assertEquals("Incorrectly bound hostName property", "host@mail.com", properties.getHostName());
Assert.assertEquals("Incorrectly bound port property", 9000, properties.getPort());
Assert.assertEquals("Incorrectly bound from property", "mailer@mail.com", properties.getFrom());
}
@Test
public void whenListPropertyQueriedthenReturnsProperty() throws Exception {
List<String> defaultRecipients = properties.getDefaultRecipients();
Assert.assertTrue("Couldn't bind list property!", defaultRecipients.size() == 2);
Assert.assertTrue("Incorrectly bound list property. Expected 2 entries!", defaultRecipients.size() == 2);
Assert.assertEquals("Incorrectly bound list[0] property", "admin@mail.com", defaultRecipients.get(0));
Assert.assertEquals("Incorrectly bound list[1] property", "owner@mail.com", defaultRecipients.get(1));
}
@Test
public void whenMapPropertyQueriedthenReturnsProperty() throws Exception {
Map<String, String> additionalHeaders = properties.getAdditionalHeaders();
Assert.assertTrue("Couldn't bind map property!", additionalHeaders != null);
Assert.assertTrue("Incorrectly bound map property. Expected 3 Entries!", additionalHeaders.size() == 3);
Assert.assertEquals("Incorrectly bound map[redelivery] property", "true", additionalHeaders.get("redelivery"));
Assert.assertEquals("Incorrectly bound map[secure] property", "true", additionalHeaders.get("secure"));
Assert.assertEquals("Incorrectly bound map[p3] property", "value", additionalHeaders.get("p3"));
}
@Test
public void whenObjectPropertyQueriedthenReturnsProperty() throws Exception {
Credentials credentials = properties.getCredentials();
Assert.assertTrue("Couldn't bind map property!", credentials != null);
Assert.assertEquals("Incorrectly bound object property, authMethod", "SHA1", credentials.getAuthMethod());
Assert.assertEquals("Incorrectly bound object property, username", "john", credentials.getUsername());
Assert.assertEquals("Incorrectly bound object property, password", "password", credentials.getPassword());
}
@Test
public void whenBeanMethodAnnotatedThenPropertiesCorrectlyBound(){
Item item = properties.item();
Assert.assertEquals("Incorrectly bound object property, item.name","Test item name", item.getName());
Assert.assertEquals("Incorrectly bound object property, item.size", 21, item.getSize());
}
}
| gpl-3.0 |
meek0/agate | agate-core/src/main/java/org/obiba/agate/repository/AuthorizationRepository.java | 1026 | /*
* Copyright (c) 2018 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.agate.repository;
import java.util.List;
import org.joda.time.DateTime;
import org.obiba.agate.domain.Authorization;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
* Spring Data MongoDB repository for the {@link Authorization} entity.
*/
public interface AuthorizationRepository extends MongoRepository<Authorization, String> {
List<Authorization> findByCode(String code);
List<Authorization> findByUsername(String username);
List<Authorization> findByApplication(String application);
List<Authorization> findByUsernameAndApplication(String username, String application);
List<Authorization> findByCreatedDateBefore(DateTime localDate);
}
| gpl-3.0 |
KevBP/Distributed-white-board | whiteboard/src/gui/FormeRectangle.java | 1338 | package gui;
import java.awt.Color;
import java.awt.Graphics2D;
/**
* Implementation de Forme pour le dessin d'un rectangle.
*/
public class FormeRectangle extends Forme {
/**
* Constructeur.
*
* @param bg
* L'arriere plan.
* @param fg
* L'avant plan.
* @param trait
* L'épaisseur du trait.
*/
public FormeRectangle(Color bg, Color fg, float trait) {
super(bg, fg, trait);
}
/**
* Méthode de dessin de l'arriere plan.
*
* @param g
* Le contexte de le dessin.
*/
public void dessineArrierePlan(Graphics2D g) {
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int width = Math.abs(p1.x - p2.x);
int height = Math.abs(p1.y - p2.y);
g.fillRect(x, y, width, height);
}
/**
* Méthode de dessin de l'avant plan.
*
* @param g
* Le contexte de le dessin.
*/
public void dessineAvantPlan(Graphics2D g) {
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int width = Math.abs(p1.x - p2.x);
int height = Math.abs(p1.y - p2.y);
g.drawRect(x, y, width, height);
}
/**
* Retourne vrai si cette forme est définit par 2 points, faux pour un
* point.
*
* @return vrai si cette forme est définit par 2 points, faux pour un point.
*/
public boolean aDeuxPoints() {
return true;
}
}
| gpl-3.0 |
AperiStudios/OpenGrave | src/main/java/com/opengrave/common/xml/XML.java | 2277 | /*
* Copyright 2016 Nathan Howard
*
* This file is part of OpenGrave
*
* OpenGrave 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.
*
* OpenGrave 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 OpenGrave. If not, see <http://www.gnu.org/licenses/>.
*/
package com.opengrave.common.xml;
import java.util.ArrayList;
import javax.xml.xpath.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.opengrave.common.DebugExceptionHandler;
public class XML {
public static Element getElementById(Document document, String id) {
try {
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//*[@id = '" + id + "']");
Element result = (Element) expr.evaluate(document, XPathConstants.NODE);
return result;
} catch (XPathExpressionException e) {
new DebugExceptionHandler(e);
return null;
}
}
public static ArrayList<Element> getChildren(Node parent, String tag) {
ArrayList<Element> children = new ArrayList<Element>();
NodeList nodes = parent.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeName().equalsIgnoreCase(tag)) {
children.add((Element) node);
}
}
return children;
}
public static Element getChild(Node parent, String tag) {
ArrayList<Element> children = getChildren(parent, tag);
if (children.size() == 0) {
return null;
}
return children.get(0);
}
public static int getChildCount(Element parent, String string) {
int i = 0;
NodeList nodes = parent.getChildNodes();
for (int j = 0; j < nodes.getLength(); j++) {
Node node = nodes.item(j);
if (node.getNodeName().equalsIgnoreCase(string)) {
i++;
}
}
return i;
}
}
| gpl-3.0 |
robpayn/resources | src/main/java/org/payn/resources/water/channel/boundary/dynamicwave/downstream/WaterFlow.java | 4484 | package org.payn.resources.water.channel.boundary.dynamicwave.downstream;
import org.payn.chsm.values.ValueDouble;
import org.payn.chsm.values.ValueString;
import org.payn.neoch.HolonBoundary;
import org.payn.neoch.processors.ProcessorDoubleLoadInit;
import org.payn.resources.water.ResourceWater;
/**
* Calculates the flow of water out the downstream end of
* a channel model
*
* @author robpayn
*
*/
public class WaterFlow extends ProcessorDoubleLoadInit {
/**
* Bed slope
*/
private ValueDouble bedSlope;
/**
* Hydraulic gradient
*/
private ValueDouble hydraulicGradient;
/**
* Cross-sectional area of channel flow
*/
private ValueDouble xSectionArea;
/**
* Hydraulic radius
*/
private ValueDouble hydraulicRadius;
/**
* Velocity exponent for Chezey equation
*/
private double velocityExponent;
/**
* Radius exponent for Chezey equation
*/
private double radiusExponent;
/**
* Chezey coefficient
*/
private ValueDouble chezey;
@Override
public void setInitDependencies() throws Exception
{
}
@Override
public void initialize() throws Exception
{
if (value.isNoValue())
{
value.n = 0.0;
}
}
@Override
public void setUpdateDependenciesDelta() throws Exception
{
// Get the next boundary upstream
HolonBoundary thisBoundary =
((HolonBoundary)state.getParentHolon());
ValueString upstreamBoundaryName = (ValueString)createDependencyOnValue(
ResourceWater.DEFAULT_NAME_UPSTREAM_BOUNDARY_NAME
);
HolonBoundary upstreamBoundary = thisBoundary.getCell().getBoundary(
upstreamBoundaryName.string
);
hydraulicGradient = (ValueDouble)createDependencyOnValue(
upstreamBoundary,
ResourceWater.DEFAULT_NAME_HYDR_GRAD
);
xSectionArea = (ValueDouble)createDependencyOnValue(
upstreamBoundary,
ResourceWater.DEFAULT_NAME_WETTED_XSECT_AREA
);
hydraulicRadius = (ValueDouble)createDependencyOnValue(
upstreamBoundary,
ResourceWater.DEFAULT_NAME_HYDR_RADIUS
);
// Get bed slope and Chezey coefficient from this boundary
// if available, otherwise get them from the upstream boundary
try
{
bedSlope = (ValueDouble)createDependencyOnValue(
ResourceWater.DEFAULT_NAME_BED_SLOPE
);
}
catch (Exception e)
{
bedSlope = (ValueDouble)createDependencyOnValue(
upstreamBoundary,
ResourceWater.DEFAULT_NAME_BED_SLOPE
);
}
try
{
chezey = (ValueDouble)createDependencyOnValue(
ResourceWater.DEFAULT_NAME_CHEZEY
);
}
catch (Exception e)
{
chezey = (ValueDouble)createDependencyOnValue(
upstreamBoundary,
ResourceWater.DEFAULT_NAME_CHEZEY
);
}
// Check if exponents for Chezey equation are available in
// this boundary or the next boundary upstream. They will
// have null values if not available in either
ValueDouble[] exponents = ResourceWater.getChezeyExponentValues(
state.getParentHolon(), this);
if (exponents[0] == null)
{
exponents = ResourceWater.getChezeyExponentValues(
upstreamBoundary, this);
}
if (exponents[0] == null)
{
velocityExponent = 2.0;
radiusExponent = 4.0 / 3.0;
}
else
{
velocityExponent = exponents[0].n;
radiusExponent = exponents[1].n;
}
}
@Override
public void updateDelta() throws Exception
{
double gradient;
if (bedSlope.n < 0.01)
{
gradient = bedSlope.n;
}
else
{
gradient = hydraulicGradient.n;
}
value.n = 0.0;
if (gradient > 0.0)
{
value.n = -xSectionArea.n
* Math.pow(
(Math.pow(hydraulicRadius.n, radiusExponent) * gradient / chezey.n),
(1.0 / velocityExponent)
);
}
}
}
| gpl-3.0 |
timfeu/berkeleycoref-bansalklein | code/fig/basic/FullStatFig.java | 1731 | package fig.basic;
import java.util.ArrayList;
import java.util.List;
/**
* For keeping track of statistics.
* Keeps all the data around (can be memory expensive).
*/
public class FullStatFig extends BigStatFig {
public FullStatFig() { }
public FullStatFig(Iterable<Double> c) {
for(double x : c) add(x);
}
public FullStatFig(double[] m)
{
for (int i = 0; i < m.length; i++)
add(m[i]);
}
@Override
public void add(double x) {
super.add(x);
data.add(x);
}
public double entropy() {
double e = 0;
for(double x : data) {
x /= sum;
if(x > 0)
e += -x * Math.log(x);
}
return e;
}
public double variance() {
double v = 0;
double m = mean();
for(double x : data)
v += (x-m)*(x-m);
return v/n;
}
public double stddev() { return Math.sqrt(variance()); }
public List<Double> getData() { return data; }
// Return for each lag, the correlation
public double[] computeAutocorrelation(int maxLag) {
double mean = mean();
double stddev = stddev();
double[] normData = new double[n];
for(int i = 0; i < n; i++)
normData[i] = (data.get(i) - mean) / stddev;
double[] autocorrelations = new double[maxLag+1];
for(int lag = 0; lag <= maxLag; lag++) {
double sum = 0;
int count = 0;
for(int i = 0; i+lag < n; i++) {
sum += normData[i] * normData[i+lag];
count++;
}
autocorrelations[lag] = sum / count;
}
return autocorrelations;
}
@Override
public String toString() {
return Fmt.D(min) + "/ << " + Fmt.D(mean()) + "~" + Fmt.D(stddev()) + " >> /" + Fmt.D(max) + " (" + n + ")";
}
private ArrayList<Double> data = new ArrayList<Double>();
}
| gpl-3.0 |
ddRPB/rpb | radplanbio-core/src/main/java/de/dktk/dd/rpb/core/domain/ctms/CurriculumVitaeItemType_.java | 1804 | /*
* This file is part of RadPlanBio
*
* Copyright (C) 2013-2016 Tomas Skripcak
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.dktk.dd.rpb.core.domain.ctms;
import javax.persistence.metamodel.ListAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
import java.util.Date;
/**
* CurriculumVitaeItemType entity meta model which is used for JPA
* This allows to use type save criteria API while constructing queries
*
* @author tomas@skripcak.net
* @since 24 Jun 2015
*/
@SuppressWarnings("unused")
@StaticMetamodel(CurriculumVitaeItemType.class)
public class CurriculumVitaeItemType_ {
// Raw attributes
public static volatile SingularAttribute<CurriculumVitaeItemType, Integer> id;
public static volatile SingularAttribute<CurriculumVitaeItemType, String> name;
public static volatile SingularAttribute<CurriculumVitaeItemType, String> description;
// Many-to-One
public static volatile SingularAttribute<CurriculumVitaeItemType, CurriculumVitaeItemType> parent;
// One-to-Many
public static volatile ListAttribute<CurriculumVitaeItemType, CurriculumVitaeItemType> children;
} | gpl-3.0 |
OmicronProject/BakeoutController-Basic | src/test/java/unit/kernel/models/kernel/GetSerialPortNames.java | 899 | package unit.kernel.models.kernel;
import kernel.models.Kernel;
import kernel.views.CommPortReporter;
import org.jmock.Expectations;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
/**
* Contains unit tests for {@link Kernel#getSerialPortNames()}
*/
public final class GetSerialPortNames extends KernelTestCase {
private CommPortReporter reporter;
@Before
public void setReporter(){
reporter = kernel.getCommPortReporter();
}
@Before
public void setContext(){
context.checking(new ExpectationsForReporter());
}
@Test
public void getSerialPortNames(){
assertNotNull(reporter.getSerialPortNames());
}
private class ExpectationsForReporter extends Expectations {
public ExpectationsForReporter(){
oneOf(mockPortDriver).getSerialPortNames();
}
}
}
| gpl-3.0 |
iazarny/gitember | src/main/java/com/az/gitember/controller/handlers/IndexEventHandler.java | 3508 | package com.az.gitember.controller.handlers;
import com.az.gitember.controller.DefaultProgressMonitor;
import com.az.gitember.controller.IntegerlDialog;
import com.az.gitember.data.ScmItemDocument;
import com.az.gitember.data.ScmRevisionInformation;
import com.az.gitember.service.Context;
import com.az.gitember.service.SearchService;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.text.MessageFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class IndexEventHandler extends AbstractLongTaskEventHandler implements EventHandler<ActionEvent> {
private final static Logger log = Logger.getLogger(IndexEventHandler.class.getName());
Integer docQty = 0 ;
@Override
public void handle(ActionEvent event) {
IntegerlDialog integerlDialog = new IntegerlDialog("Index repository history " , "Limit revisions to reindex", "Quantiy", 100);
integerlDialog.showAndWait().ifPresent( r -> {
Task<Void> longTask = new Task<Void>() {
@Override
protected Void call() throws Exception {
DefaultProgressMonitor progressMonitor = new DefaultProgressMonitor((t, d) -> {
updateTitle(t);
updateProgress(d, 1.0);
});
List<ScmRevisionInformation> sriList = Context.getGitRepoService().getItemsToIndex(null, r, progressMonitor);
SearchService service = new SearchService( Context.getProjectFolder() );
progressMonitor.beginTask("Indexing ", sriList.size());
int idx = 0;
for (ScmRevisionInformation sri : sriList) {
sri.getAffectedItems().forEach(
i -> {
service.submitItemToReindex(new ScmItemDocument(i));
}
);
idx++;
progressMonitor.update(idx);
docQty = docQty + sri.getAffectedItems().size();
}
service.close();
return null;
}
};
launchLongTask(
longTask,
o -> {
Context.getCurrentProject().setIndexed(true);
Context.saveSettings();
Context.getMain().showResult(
"Indexing", "Was indexed " + docQty + " documents",
Alert.AlertType.INFORMATION);
},
o -> {
log.log(Level.WARNING,
MessageFormat.format("Indexing error", o.getSource().getException()));
Context.getMain().showResult("Indexing", "Cannot index history of changess\n" +
ExceptionUtils.getStackTrace(o.getSource().getException()), Alert.AlertType.ERROR);
o.getSource().getException().printStackTrace();
}
);
} );
}
}
| gpl-3.0 |
timfeu/berkeleycoref-thesaurus | src/main/java/org/jobimtext/api/configuration/DatabaseThesaurusConfiguration.java | 9826 | /*******************************************************************************
* Copyright 2012
* FG Language Technologie
* Technische Universitaet Darmstadt
*
* 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 org.jobimtext.api.configuration;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* Configuration class for the database connection
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class DatabaseThesaurusConfiguration {
public DatabaseTableConfiguration tables = new DatabaseTableConfiguration();
public String dbUser;
public String dbUrl;
public String dbPassword;
public String jdbcString;
public String similarTermsQuery;
public String similarTermsTopQuery;
public String similarTermsGtScoreQuery;
public String similarTermScoreQuery;
public String similarContextsQuery;
public String similarContextsTopQuery;
public String similarContextsGtScoreQuery;
public String contextTermsScoresQuery;
public String termsCountQuery;
public String contextsCountQuery;
public String termContextsCountQuery;
public String termContextsScoreQuery;
public String batchTermContextsScoreQuery;
public String termContextsScoresQuery;
public String termContextsScoresTopQuery;
public String termContextsScoresGtScoreQuery;
public String sensesQuery;
public String senseCUIsQuery;
public String isasQuery;
@XmlTransient
private HashMap<String, String> tableStringMapping = null;
@XmlTransient
private List<String> tableValuesSorted = null;
public String getSimilarTermsTopQuery(int top) {
return replaceTables(similarTermsTopQuery, "$numberOfEntries",
Integer.toString(top));
}
public String getSimilarTermsGtScoreQuery() {
return replaceTables(similarTermsGtScoreQuery);
}
public String getSimilarContextsQuery() {
return replaceTables(similarContextsQuery);
}
public String getSimilarContextsTopQuery(int top) {
return replaceTables(similarContextsTopQuery, "$numberOfEntries",
Integer.toString(top));
}
public String getSimilarContextsGtScoreQuery() {
return replaceTables(similarContextsGtScoreQuery);
}
public HashMap<String, String> getTableStringMapping() {
return tableStringMapping;
}
public List<String> getTableValuesSorted() {
return tableValuesSorted;
}
public DatabaseTableConfiguration getTables() {
return tables;
}
public void setTables(DatabaseTableConfiguration tables) {
this.tables = tables;
}
public String getDbUser() {
return dbUser;
}
public void setDbUser(String dbUser) {
this.dbUser = dbUser;
}
public String getDbUrl() {
return dbUrl;
}
public void setDbUrl(String dbUrl) {
this.dbUrl = dbUrl;
}
public String getDbPassword() {
return dbPassword;
}
public void setDbPassword(String dbPassword) {
this.dbPassword = dbPassword;
}
public String getJdbcString() {
return jdbcString;
}
public void setJdbcString(String jdbcString) {
this.jdbcString = jdbcString;
}
public void saveAsXml(PrintStream ps) throws JAXBException {
JAXBContext context = JAXBContext
.newInstance(DatabaseThesaurusConfiguration.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(this, ps);
}
public void saveAsXml(File file) throws JAXBException,
FileNotFoundException {
saveAsXml(new PrintStream(file));
}
public static DatabaseThesaurusConfiguration getFromXmlDataReader(Reader reader) throws JAXBException,
InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException,
SecurityException, ClassNotFoundException {
JAXBContext jaxbContext = JAXBContext
.newInstance(DatabaseThesaurusConfiguration.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (DatabaseThesaurusConfiguration) jaxbUnmarshaller
.unmarshal(reader);
}
public static DatabaseThesaurusConfiguration getFromXmlFile(File name) throws IOException, IllegalAccessException,
InstantiationException, JAXBException, NoSuchMethodException, InvocationTargetException,
ClassNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(name));
try {
return getFromXmlDataReader(reader);
} finally {
reader.close();
}
}
public static DatabaseThesaurusConfiguration getFromXmlFile(String name)
throws JAXBException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException,
SecurityException, ClassNotFoundException, IOException {
return getFromXmlFile(new File(name));
}
private String replaceTables(String query, String... replacements) {
if (tableStringMapping == null) {
tableStringMapping = new HashMap<String, String>();
tableValuesSorted = new ArrayList<String>();
for (Field f : tables.getClass().getDeclaredFields()) {
String name = f.getName();
try {
String value = f.get(this.tables).toString();
tableStringMapping.put(name, value);
tableValuesSorted.add(name);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NullPointerException e) {
System.err.println("The table parameter: " + f.toString() + " does not has a value assigned");
}
}
// sort the table names according to their length (longest is first
// element) to avoid replacing parts of table names
Collections.sort(tableValuesSorted, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.length() - o1.length();
}
});
}
String sb = query;
for (String key : tableValuesSorted) {
sb = sb.replace("$" + key, tableStringMapping.get(key));
}
if (replacements.length % 2 != 0) {
throw new IllegalArgumentException(
"the arguemnts should also be modulo two==0: Key1 Value1 Key2 Value2");
}
for (int i = 0; i < replacements.length; i += 2) {
sb = sb.replace(replacements[i], replacements[i + 1]);
}
return sb.toString();
}
public String getSimilarTermsQuery() {
return replaceTables(similarTermsQuery);
}
public String getTermsCountQuery() {
return replaceTables(termsCountQuery);
}
public String getContextsCountQuery() {
return replaceTables(contextsCountQuery);
}
public String getTermContextsCountQuery() {
return replaceTables(termContextsCountQuery);
}
public String getTermContextsScoreQuery() {
return replaceTables(termContextsScoreQuery);
}
/*public String getBatchTermContextsScoreQuery(String inClause) {
return replaceTables(batchTermContextsScoreQuery).replace("[IN-CLAUSE]", inClause);
}*/
public String getBatchTermContextsScoreQuery() {
return replaceTables(batchTermContextsScoreQuery);
}
public String getTermContextsScoresQuery() {
return replaceTables(termContextsScoresQuery);
}
public String getTermContextsScoresTopQuery(int numberOfEntries) {
return replaceTables(termContextsScoresTopQuery, "$numberOfEntries",
Integer.toString(numberOfEntries));
}
public String getTermContextsScoresGtScore() {
return replaceTables(termContextsScoresGtScoreQuery);
}
public String getSensesCUIsQuery() {
return replaceTables(senseCUIsQuery);
}
public String getIsasQuery() {
return replaceTables(isasQuery);
}
public String getSensesQuery() {
return replaceTables(sensesQuery);
}
public String getSimilarTermScoreQuery() {
return replaceTables(similarTermScoreQuery);
}
public String getContextTermsScoresQuery() { return replaceTables(contextTermsScoresQuery); }
}
| gpl-3.0 |
idega/platform2 | src/is/idega/idegaweb/member/isi/block/reports/business/WorkReportBusinessHome.java | 691 | /*
* $Id: WorkReportBusinessHome.java,v 1.5 2004/12/07 15:58:30 eiki Exp $
* Created on Dec 3, 2004
*
* Copyright (C) 2004 Idega Software hf. All Rights Reserved.
*
* This software is the proprietary information of Idega hf.
* Use is subject to license terms.
*/
package is.idega.idegaweb.member.isi.block.reports.business;
import com.idega.business.IBOHome;
/**
*
* Last modified: $Date: 2004/12/07 15:58:30 $ by $Author: eiki $
*
* @author <a href="mailto:eiki@idega.com">eiki</a>
* @version $Revision: 1.5 $
*/
public interface WorkReportBusinessHome extends IBOHome {
public WorkReportBusiness create() throws javax.ejb.CreateException, java.rmi.RemoteException;
}
| gpl-3.0 |
Thierry36tribus/Jeko | app/models/UserEvent.java | 916 | package models;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import play.data.validation.Required;
import play.db.jpa.Model;
@Entity
public class UserEvent extends Model {
public static final int TYPE_LOGIN = 1;
public static final int TYPE_LOGOUT = 2;
@Required
public Date eventDate;
@Required
@ManyToOne
public User user;
@Required
public int eventType;
public UserEvent(final Date eventDate, final User user, final int eventType) {
super();
this.eventDate = eventDate;
this.user = user;
this.eventType = eventType;
}
public static List<UserEvent> findByUser(final long userId) {
return find("user =? order by eventDate desc", User.findById(userId)).fetch(100);
}
@Override
public String toString() {
return "UserEvent [eventDate=" + eventDate + ", user=" + user + ", eventType=" + eventType + "]";
}
}
| gpl-3.0 |
WorldGrower/WorldGrower | test/org/worldgrower/goal/UTestCocoonOutsidersGoal.java | 3579 | /*******************************************************************************
* 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.worldgrower.goal;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.worldgrower.Constants;
import org.worldgrower.TestUtils;
import org.worldgrower.World;
import org.worldgrower.WorldImpl;
import org.worldgrower.WorldObject;
import org.worldgrower.actions.Actions;
import org.worldgrower.condition.Condition;
import org.worldgrower.condition.Conditions;
public class UTestCocoonOutsidersGoal {
private CocoonOutsidersGoal goal = Goals.COCOON_OUTSIDERS_GOAL;
@Test
public void testCalculateGoalNull() {
World world = new WorldImpl(1, 1, null, null);
WorldObject performer = createPerformer(2);
assertEquals(null, goal.calculateGoal(performer, world));
}
@Test
public void testCalculateGoalCocoonOutsider() {
World world = new WorldImpl(10, 10, null, null);
WorldObject performer = createPerformer(2);
WorldObject target = createPerformer(3);
world.addWorldObject(performer);
world.addWorldObject(target);
target.getProperty(Constants.GROUP).removeAll();
Conditions.add(target, Condition.PARALYZED_CONDITION, 8, world);
assertEquals(Actions.COCOON_ACTION, goal.calculateGoal(performer, world).getManagedOperation());
}
@Test
public void testCalculateGoalAlreadyCocooned() {
World world = new WorldImpl(10, 10, null, null);
WorldObject performer = createPerformer(2);
WorldObject target = createPerformer(3);
world.addWorldObject(performer);
world.addWorldObject(target);
target.getProperty(Constants.GROUP).removeAll();
Conditions.add(target, Condition.COCOONED_CONDITION, 8, world);
assertEquals(null, goal.calculateGoal(performer, world));
}
@Test
public void testIsGoalMet() {
World world = new WorldImpl(10, 10, null, null);
WorldObject performer = createPerformer(2);
world.addWorldObject(performer);
assertEquals(true, goal.isGoalMet(performer, world));
WorldObject target = createPerformer(3);
world.addWorldObject(target);
target.getProperty(Constants.GROUP).removeAll();
Conditions.add(target, Condition.PARALYZED_CONDITION, 8, world);
assertEquals(false, goal.isGoalMet(performer, world));
}
private WorldObject createPerformer(int id) {
WorldObject performer = TestUtils.createIntelligentWorldObject(id, "person");
performer.setProperty(Constants.X, 0);
performer.setProperty(Constants.Y, 0);
performer.setProperty(Constants.WIDTH, 1);
performer.setProperty(Constants.HEIGHT, 1);
performer.setProperty(Constants.ARMOR, 1);
performer.setProperty(Constants.HIT_POINTS, 1);
performer.setProperty(Constants.CONDITIONS, new Conditions());
return performer;
}
} | gpl-3.0 |
fauconnier/LaToe | src/de/tudarmstadt/ukp/wikipedia/api/TitleIterator.java | 4695 | /*******************************************************************************
* Copyright (c) 2010 Torsten Zesch.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* Contributors:
* Torsten Zesch - initial API and implementation
******************************************************************************/
package de.tudarmstadt.ukp.wikipedia.api;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import de.tudarmstadt.ukp.wikipedia.api.exception.WikiTitleParsingException;
/**
* An iterator over category objects.
* @author zesch
*
*/
public class TitleIterator implements Iterator<Title> {
// private final static Logger logger = Logger.getLogger(TitleIterator.class);
private TitleBuffer buffer;
public TitleIterator(Wikipedia wiki, int bufferSize) {
buffer = new TitleBuffer(bufferSize, wiki);
}
public boolean hasNext(){
return buffer.hasNext();
}
public Title next(){
return buffer.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Buffers titles in a list.
*
* @author zesch
*
*/
class TitleBuffer {
private Wikipedia wiki;
private List<String> titleStringBuffer;
private int maxBufferSize; // the number of pages to be buffered after a query to the database.
private int bufferFillSize; // even a 500 slot buffer can be filled with only 5 elements
private int bufferOffset; // the offset in the buffer
private int dataOffset; // the overall offset in the data
public TitleBuffer(int bufferSize, Wikipedia wiki){
this.maxBufferSize = bufferSize;
this.wiki = wiki;
this.titleStringBuffer = new ArrayList<String>();
this.bufferFillSize = 0;
this.bufferOffset = 0;
this.dataOffset = 0;
}
/**
* If there are elements in the buffer left, then return true.
* If the end of the filled buffer is reached, then try to load new buffer.
* @return True, if there are pages left. False otherwise.
*/
public boolean hasNext(){
if (bufferOffset < bufferFillSize) {
return true;
}
else {
return this.fillBuffer();
}
}
/**
*
* @return The next Title or null if no more categories are available.
*/
public Title next(){
// if there are still elements in the buffer, just retrieve the next one
if (bufferOffset < bufferFillSize) {
return this.getBufferElement();
}
// if there are no more elements => try to fill a new buffer
else if (this.fillBuffer()) {
return this.getBufferElement();
}
else {
// if it cannot be filled => return null
return null;
}
}
private Title getBufferElement() {
String titleString = titleStringBuffer.get(bufferOffset);
Title title = null;
try {
title = new Title(titleString);
} catch (WikiTitleParsingException e) {
e.printStackTrace();
}
bufferOffset++;
dataOffset++;
return title;
}
private boolean fillBuffer() {
Session session = this.wiki.__getHibernateSession();
session.beginTransaction();
List returnList = session.createSQLQuery(
"select p.name from PageMapLine as p")
.setFirstResult(dataOffset)
.setMaxResults(maxBufferSize)
.setFetchSize(maxBufferSize)
.list();
session.getTransaction().commit();
// clear the old buffer and all variables regarding the state of the buffer
titleStringBuffer.clear();
bufferOffset = 0;
bufferFillSize = 0;
titleStringBuffer.addAll(returnList);
if (titleStringBuffer.size() > 0) {
bufferFillSize = titleStringBuffer.size();
return true;
}
else {
return false;
}
}
}
}
| gpl-3.0 |
hyperbox/server | src/main/java/io/kamax/hboxd/factory/ModelFactory.java | 1201 | /*
* Hyperbox - Virtual Infrastructure Manager
* Copyright (C) 2013 Max Dor
*
* https://apps.kamax.io/hyperbox
*
* 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 io.kamax.hboxd.factory;
import io.kamax.hboxd.core.SingleHostServer;
import io.kamax.hboxd.core._Hyperbox;
public class ModelFactory {
private static _Hyperbox hyperbox;
private ModelFactory() {
throw new RuntimeException("Not allowed");
}
public static _Hyperbox get() {
if (hyperbox == null) {
hyperbox = new SingleHostServer();
}
return hyperbox;
}
}
| gpl-3.0 |
theone1984/parroteer | drone-api/src/main/java/com/dronecontrol/droneapi/ConfigurationDataRetriever.java | 5909 | package com.dronecontrol.droneapi;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.dronecontrol.droneapi.components.AddressComponent;
import com.dronecontrol.droneapi.components.ErrorListenerComponent;
import com.dronecontrol.droneapi.components.ReadyStateListenerComponent;
import com.dronecontrol.droneapi.components.TcpComponent;
import com.dronecontrol.droneapi.components.ThreadComponent;
import com.dronecontrol.droneapi.data.DroneConfiguration;
import com.dronecontrol.droneapi.listeners.DroneConfigurationListener;
import com.dronecontrol.droneapi.listeners.ReadyStateChangeListener;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
public class ConfigurationDataRetriever implements Runnable
{
public static final String SEPARATOR = " = ";
private final Logger logger = Logger.getLogger(ConfigurationDataRetriever.class);
private final ThreadComponent threadComponent;
private final AddressComponent addressComponent;
private final TcpComponent tcpComponent;
private final ReadyStateListenerComponent readyStateListenerComponent;
private final ErrorListenerComponent errorListenerComponent;
private final Set<DroneConfigurationListener> droneConfigurationListeners;
private String droneIpAddress;
private int configDataPort;
@Inject
public ConfigurationDataRetriever(ThreadComponent threadComponent, AddressComponent addressComponent, TcpComponent tcpComponent,
ReadyStateListenerComponent readyStateListenerComponent, ErrorListenerComponent errorListenerComponent)
{
this.threadComponent = threadComponent;
this.addressComponent = addressComponent;
this.tcpComponent = tcpComponent;
this.readyStateListenerComponent = readyStateListenerComponent;
this.errorListenerComponent = errorListenerComponent;
droneConfigurationListeners = Sets.newHashSet();
}
public void start(String droneIpAddress, int configDataPort)
{
this.droneIpAddress = droneIpAddress;
this.configDataPort = configDataPort;
logger.info("Starting config data thread");
threadComponent.start(this);
}
public void stop()
{
logger.info("Stopping config data thread");
threadComponent.stopAndWait();
}
public void addReadyStateChangeListener(ReadyStateChangeListener readyStateChangeListener)
{
readyStateListenerComponent.addReadyStateChangeListener(readyStateChangeListener);
}
public void removeReadyStateChangeListener(ReadyStateChangeListener readyStateChangeListener)
{
readyStateListenerComponent.addReadyStateChangeListener(readyStateChangeListener);
}
public void addDroneConfigurationListener(DroneConfigurationListener droneConfigurationListener)
{
if (!droneConfigurationListeners.contains(droneConfigurationListener))
{
droneConfigurationListeners.add(droneConfigurationListener);
}
}
public void removeDroneConfigurationListener(DroneConfigurationListener droneConfigurationListener)
{
if (droneConfigurationListeners.contains(droneConfigurationListener))
{
droneConfigurationListeners.remove(droneConfigurationListener);
}
}
@Override
public void run()
{
try
{
doRun();
} catch (Throwable e)
{
errorListenerComponent.emitError(e);
}
}
private void doRun()
{
connectToConfigDataPort();
readyStateListenerComponent.emitReadyStateChange(ReadyStateChangeListener.ReadyState.READY);
while (!threadComponent.isStopped())
{
try
{
processData(readLines());
} catch (Throwable e)
{
logger.error("Error processing the config control data", e);
}
}
disconnectFromConfigDataPort();
}
private void connectToConfigDataPort()
{
logger.info(String.format("Connecting to config data port %d", configDataPort));
tcpComponent.connect(addressComponent.getInetAddress(droneIpAddress), configDataPort, 1000);
}
public Collection<String> readLines()
{
try
{
return doReadLines();
} catch (IOException | ClassNotFoundException e)
{
throw new IllegalStateException("Error receiving current lines", e);
}
}
private Collection<String> doReadLines() throws IOException, ClassNotFoundException
{
Collection<String> receivedLines = Lists.newArrayList();
try
{
String line = tcpComponent.getReader().readLine();
while (line != null)
{
receivedLines.add(line);
line = tcpComponent.getReader().readLine();
}
} catch (SocketTimeoutException e)
{
// EOF is reached (this is a dirty workaround, but there is no indicator telling us when to stop)
}
return receivedLines;
}
private void processData(Collection<String> lines)
{
if (lines.size() == 0)
{
return;
}
logger.debug("Drone configuration data received");
DroneConfiguration droneConfiguration = getDroneConfiguration(lines);
for (DroneConfigurationListener listener : droneConfigurationListeners)
{
listener.onDroneConfiguration(droneConfiguration);
}
}
private DroneConfiguration getDroneConfiguration(Collection<String> lines)
{
Map<String, String> configMap = Maps.newHashMap();
for (String line : lines)
{
String[] configOption = line.split(SEPARATOR);
if (configOption.length != 2)
{
continue;
}
configMap.put(configOption[0], configOption[1]);
}
return new DroneConfiguration(configMap);
}
private void disconnectFromConfigDataPort()
{
logger.info(String.format("Disconnecting from config data port %d", configDataPort));
tcpComponent.disconnect();
}
} | gpl-3.0 |
M4thG33k/LittleInsignificantThings_1.9 | src/main/java/com/m4thg33k/lit/lib/EnumBetterFurnaceType.java | 1983 | package com.m4thg33k.lit.lib;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
public enum EnumBetterFurnaceType implements IStringSerializable {
IRON("Iron",0.5,1,1.25,30000, new ItemStack(Items.iron_ingot,1)),
GOLD("Gold",0.25,1,1.25,40000,new ItemStack(Items.gold_ingot,1)),
DIAMOND("Diamond",0.25,2,1.5,80000, new ItemStack(Items.diamond,1)),
REDSTONE("Redstone",0.125,0,1.25,30000,new ItemStack(Blocks.redstone_block,1)),
LAPIS("Lapis",0.25,3,1.0,20000,new ItemStack(Blocks.lapis_block,1));
protected final String name;
protected final double speedMult;
protected final int numUpgrades;
protected final double fuelEfficiencyMult;
protected final int fuelCap;
protected final ItemStack ingredient;
EnumBetterFurnaceType(String name,double speedMult,int numUpgrades,double fuelEfficiencyMult,int fuelCap,ItemStack ingredient)
{
this.name = name;
this.speedMult = speedMult;
this.numUpgrades = numUpgrades;
this.fuelEfficiencyMult = fuelEfficiencyMult;
this.fuelCap = fuelCap;
this.ingredient = ingredient.copy();
}
@Override
public String getName() {
return this.name.toLowerCase();
}
public String getTypeName()
{
return this.name;
}
public double getSpeedMult() {
return speedMult;
}
public int getNumUpgrades() {
return numUpgrades;
}
public double getFuelEfficiencyMult() {
return fuelEfficiencyMult;
}
public int getFuelCap() {
return fuelCap;
}
public ItemStack getIngredient() {
return ingredient.copy();
}
public String[] getDisplayInfo()
{
return new String[]{""+getSpeedMult(),""+getFuelEfficiencyMult(),""+getNumUpgrades(),""+(Math.floor(100*((0.0+getFuelCap())/(1600*64*getFuelEfficiencyMult())))/100)};
}
}
| gpl-3.0 |
abeifuss/simgui | src/evaluation/loadGenerator/applicationLevelTraffic/requestReply/ALRR_BasicWriter.java | 2609 | /*
* gMix open source project - https://svs.informatik.uni-hamburg.de/gmix/
* Copyright (C) 2012 Karl-Peter Fuchs
*
* 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 evaluation.loadGenerator.applicationLevelTraffic.requestReply;
import java.io.IOException;
import evaluation.loadGenerator.ClientTrafficScheduleWriter;
import evaluation.loadGenerator.LoadGenerator;
import evaluation.loadGenerator.scheduler.ScheduleTarget;
import framework.core.util.IOTester;
import framework.core.util.Util;
public class ALRR_BasicWriter implements ScheduleTarget<ApplicationLevelMessage> {
private final boolean IS_DUPLEX;
private ClientTrafficScheduleWriter<ApplicationLevelMessage> owner;
public ALRR_BasicWriter(ClientTrafficScheduleWriter<ApplicationLevelMessage> owner, boolean isDuplex) {
this.owner = owner;
this.IS_DUPLEX = isDuplex;
}
@Override
public void execute(ApplicationLevelMessage message) {
ALRR_ClientWrapper cw = (ALRR_ClientWrapper)owner.getClientWrapper(message.getClientId());
synchronized (cw.outputStream) {
try {
message.setAbsoluteSendTime(System.currentTimeMillis());
byte[] payload = message.createPayloadForRequest();
String stats = "LOAD_GENERATOR: sending request ("
+"client:" +message.getClientId()
+"; transactionId:" +message.getTransactionId()
+"; requestSize: " +message.getRequestSize() +"bytes";
if (message.getReplySize() != Util.NOT_SET)
stats += "; replySize: " +message.getReplySize() +"bytes";
stats += ")";
System.out.println(stats);
if (LoadGenerator.VALIDATE_IO)
IOTester.findInstance(""+message.getClientId()).addSendRecord(payload);
//System.out.println("" +this +": sending (client): " +Util.toHex(payload)); // TODO: remove
cw.outputStream.write(payload);
cw.outputStream.flush();
if (IS_DUPLEX)
ALRR_ClientWrapper.activeTransactions.put(message.getTransactionId(), message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| gpl-3.0 |
SafePodOrg/SafePodAndroid | app/src/main/java/org/safepod/app/android/exceptions/AppSignatureNotGeneratedException.java | 818 | package org.safepod.app.android.exceptions;
/**
* Created by Prajit on 3/7/2016.
*/
public class AppSignatureNotGeneratedException extends Exception {
public AppSignatureNotGeneratedException() {
}
public AppSignatureNotGeneratedException(String detailMessage) {
super(detailMessage);
}
public AppSignatureNotGeneratedException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public AppSignatureNotGeneratedException(Throwable throwable) {
super(throwable);
}
@Override
public String getMessage() {
return super.getMessage();
}
@Override
public String toString() {
return super.toString();
}
@Override
public Throwable getCause() {
return super.getCause();
}
}
| gpl-3.0 |
tritania/Unicus | src/main/java/org/tritania/unicus/command/CResource.java | 3241 | /*
* Copyright 2014-2015 Erik Wilson <erikwilson@magnorum.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.tritania.unicus.command;
/*Start Imports*/
import java.util.Random;
import org.bukkit.permissions.PermissibleBase;
import org.bukkit.entity.Player;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.Location;
import org.tritania.unicus.Unicus;
import org.tritania.unicus.utils.Message;
import org.tritania.unicus.utils.Log;
/*End Imports*/
public class CResource implements CommandExecutor
{
public Unicus un;
private int highest;
public CResource(Unicus un)
{
this.un = un;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
Player player = (Player) sender;
if (player.getWorld().getName().equals("Resource"))
{
Message.info(sender, "You're already in the resource world");
return true;
}
else if (un.land.wipeWorld())
{
Message.info(sender, "Please wait a few moments, the resource world is resetting");
un.land.unloadWorld(un.datalocal);
return true;
}
else if (args.length > 0 && args[0].equals("spawn"))
{
Random rand = new Random();
World world = Bukkit.getWorld("Resource");
Location location = new Location(world, 0, 64.0, 0);
if (world.getHighestBlockYAt(location) > 5)
{
highest = 64;
}
else
{
highest = world.getHighestBlockYAt(location);
}
Location prime = new Location(world, 0, highest, 0);
player.teleport(prime);
}
else
{
Random rand = new Random();
World world = Bukkit.getWorld("Resource");
double x = 40000 * rand.nextDouble();
double z = 40000 * rand.nextDouble();
Location location = new Location(world, x, 64.0, z);
if (world.getHighestBlockYAt(location) > 5)
{
highest = 64;
}
else
{
highest = world.getHighestBlockYAt(location);
}
Location prime = new Location(world, x, highest, z);
player.teleport(prime);
}
Message.info(sender, un.land.timeLeft());
return true;
}
}
| gpl-3.0 |
Guerra24/NanoUI | nanoui-core/src/main/java/net/luxvacuos/nanoui/rendering/glfw/Icon.java | 936 | /*
* This file is part of NanoUI
*
* Copyright (C) 2016-2018 Guerra24
*
* 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 net.luxvacuos.nanoui.rendering.glfw;
import java.nio.ByteBuffer;
public class Icon {
protected String path;
protected ByteBuffer image;
public Icon(String path) {
this.path = path;
}
}
| gpl-3.0 |
BSG-Africa/bbb | src/main/java/za/co/bsg/services/api/BigBlueButtonImp.java | 17687 | package za.co.bsg.services.api;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import za.co.bsg.config.AppPropertiesConfiguration;
import za.co.bsg.model.Meeting;
import za.co.bsg.model.User;
import za.co.bsg.services.api.exception.BigBlueButtonException;
import za.co.bsg.services.api.response.BigBlueButtonResponse;
import za.co.bsg.services.api.response.CreateMeeting;
import za.co.bsg.services.api.response.MeetingRunning;
import za.co.bsg.services.api.xml.BigBlueButtonXMLHandler;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Random;
@Service
public class BigBlueButtonImp implements BigBlueButtonAPI {
@Autowired
AppPropertiesConfiguration appPropertiesConfiguration;
@Autowired
BigBlueButtonXMLHandler bigBlueButtonXMLHandler;
// BBB API Keys
protected final static String API_SERVER_PATH = "api/";
protected final static String API_CREATE = "create";
protected final static String API_JOIN = "join";
protected final static String API_SUCCESS = "SUCCESS";
protected final static String API_MEETING_RUNNING = "isMeetingRunning";
protected final static String API_FAILED = "FAILED";
protected final static String API_END_MEETING = "end";
@Override
public String getUrl() {
return appPropertiesConfiguration.getBbbURL();
}
@Override
public String getSalt() {
return appPropertiesConfiguration.getBbbSalt();
}
@Override
public String getPublicAttendeePW() {
return appPropertiesConfiguration.getAttendeePW();
}
@Override
public String getPublicModeratorPW() {
return appPropertiesConfiguration.getModeratorPW();
}
@Override
public String getLogoutURL() {
return appPropertiesConfiguration.getLogoutURL();
}
/**
* This method creates a public bbb meeting that can be joined by external users.
* First the base url is retrieved, the a meeting query is constructed.
* If a defaultPresentationURL is not empty or null, set uploadPresentation to true
* and append the presentation link to the meeting query.
* A checksumParameter is then appended to the meeting.
* The bbb create api call is invoked to create a bbb meeting and the a
* response is build based on whether or not a presentation is uploaded
*
* @param meeting a Meeting data type - details of meeting to be created
* @param user User data type - user creating a bbb meeting
* @return a String object
*/
@Override
public String createPublicMeeting(Meeting meeting, User user) {
String base_url_join = getBaseURL(API_SERVER_PATH, API_JOIN);
boolean uploadPresentation = false;
// build query
StringBuilder query = new StringBuilder();
Random random = new Random();
String voiceBridge_param = "&voiceBridge=" + (70000 + random.nextInt(9999));
query.append("&name=");
query.append(urlEncode(meeting.getName()));
query.append("&meetingID=");
query.append(urlEncode(meeting.getMeetingId()));
query.append(voiceBridge_param);
query.append("&attendeePW=");
query.append(getPublicAttendeePW());
query.append("&moderatorPW=");
query.append(getPublicModeratorPW());
query.append("&isBreakoutRoom=false");
query.append("&record=");
query.append("false");
query.append("&logoutURL=");
query.append(urlEncode(getLogoutURL()));
query.append(getMetaData( meeting.getMeta() ));
query.append("&welcome=");
query.append(urlEncode("<br>" + meeting.getWelcomeMessage() + "<br>"));
if (meeting.getDefaultPresentationURL() != "" && meeting.getDefaultPresentationURL() != null) {
uploadPresentation = true;
query.append(urlEncode("<br><br><br>" + "The presentation will appear in a moment. To download click <a href=\"event:" + meeting.getDefaultPresentationURL() + "\"><u>" + meeting.getDefaultPresentationURL() + "</u></a>.<br>" + "<br>"));
}
query.append(getCheckSumParameter(API_CREATE, query.toString()));
//Make API call
CreateMeeting response = null;
String responseCode = "";
try {
//pre-upload presentation
if (uploadPresentation) {
String xml_presentation = "<modules> <module name=\"presentation\"> <document url=\"" + meeting.getDefaultPresentationURL() + "\" /> </module> </modules>";
response = makeAPICall(API_CREATE, query.toString(), xml_presentation, CreateMeeting.class);
} else {
response = makeAPICall(API_CREATE, query.toString(), CreateMeeting.class);
}
responseCode = response.getReturncode();
} catch (BigBlueButtonException e) {
e.printStackTrace();
}
if (API_SUCCESS.equals(responseCode)) {
// Looks good, now return a URL to join that meeting
String join_parameters = "meetingID=" + urlEncode(meeting.getMeetingId())
+ "&fullName=" + urlEncode(user.getName()) + "&password="+getPublicModeratorPW();
return base_url_join + join_parameters + "&checksum="
+ getCheckSumParameter(API_JOIN + join_parameters + getSalt());
}
return ""+response;
}
/**
* This method check whether or not meeting is running using meeting id
*
* @param meeting a Meeting object data type - which is used to get meeting id
* @return boolean value indicating whether or not meeting is running
*/
@Override
public boolean isMeetingRunning(Meeting meeting) {
try {
return isMeetingRunning(meeting.getMeetingId());
} catch (BigBlueButtonException e) {
e.printStackTrace();
}
return false;
}
/**
* This method ends a bbb meeting if the user ending the meeting is a moderator,
* by building a query containing meetingId and moderator password.
* This query is then used to make an API call to end the bbb meeting,
* if meeting has ended successfully or meeting does not exists return true boolean value
*
* @param meetingID a String data type - is used to query a meeting to be ended
* @param moderatorPassword a String data type - a moderator password used to end a meeting
* @return boolean value indicating whether meeting has ended
*/
@Override
public boolean endMeeting(String meetingID, String moderatorPassword) {
StringBuilder query = new StringBuilder();
query.append("meetingID=");
query.append(meetingID);
query.append("&password=");
query.append(moderatorPassword);
query.append(getCheckSumParameter(API_END_MEETING, query.toString()));
try {
makeAPICall(API_END_MEETING, query.toString(), BigBlueButtonResponse.class);
} catch (BigBlueButtonException e) {
if(BigBlueButtonException.MESSAGEKEY_NOTFOUND.equals(e.getMessageKey())) {
// we can safely ignore this one: the meeting is not running
return true;
}else{
System.out.println("Error: "+e);
}
}
return true;
}
/**
* This method gets public meeting url, which an external user can use to join meeting
* The url is generated by, getting the base url and join parameters, which are
* combined together with the checksum
*
* @param name a String data type - name of the meeting to be joined
* @param meetingID a String data type - meetingId of the bbb meeting to be joined
* @return a String object
*/
@Override
public String getPublicJoinURL(String name, String meetingID) {
String base_url_join = getUrl() + "api/join?";
String join_parameters = "meetingID=" + urlEncode(meetingID)
+ "&fullName=" + urlEncode(name) + "&password="+getPublicAttendeePW();
return base_url_join + join_parameters + "&checksum="
+ getCheckSumParameter(API_JOIN + join_parameters + getSalt());
}
/**
* This method builds the base url by combining the bbb url with provided path and api call
*
* @param path - a String data type - a server path
* @param api_call a String data type - name of api call
* @return a String object
*/
private String getBaseURL(String path, String api_call) {
StringBuilder url = new StringBuilder(getUrl());
if (url.toString().endsWith("/bigbluebutton")){
url.append("/");
}
url.append(path);
url.append(api_call);
url.append("?");
return url.toString();
}
/**
* This method converts string to UTF-8 type
*
* @param s a String data type - url to encoded
* @return a String object
*/
private String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* This method generates a metadata parameter name
* @param metadata Map of String type object - containing metadata keys user to generate parameter name
*
* @return a String object
*/
private String getMetaData( Map<String, String> metadata ) {
String metadata_params = "";
if ( metadata!=null ){
for(String key : metadata.keySet()){
metadata_params = metadata_params + "&meta_" + urlEncode(key) + "=" + urlEncode(metadata.get(key));
}
}
return metadata_params;
}
/**
* This method check whether a bbb meeting is running
* by building a query containing meetingId to get meeting by.
* This query is then used to make an API call to check whether
* the bbb meeting is running.
*
* @param meetingID a String data type - is used to query a meeting that is running
* @return boolean value
* @throws BigBlueButtonException
*/
public boolean isMeetingRunning(String meetingID)
throws BigBlueButtonException {
try {
StringBuilder query = new StringBuilder();
query.append("meetingID=");
query.append(meetingID);
query.append(getCheckSumParameter(API_MEETING_RUNNING, query.toString()));
MeetingRunning bigBlueButtonResponse = makeAPICall(API_MEETING_RUNNING, query.toString(), MeetingRunning.class);
return Boolean.parseBoolean(bigBlueButtonResponse.getRunning());
} catch (Exception e) {
throw new BigBlueButtonException(BigBlueButtonException.MESSAGEKEY_INTERNALERROR, e.getMessage(), e);
}
}
/**
* This method gets check sum for a api call
*
* @param apiCall a String type - a api call name used as part of generation a checksum
* @param queryString a String type - query string used as part of generating a checksum
* @return a String object
*/
private String getCheckSumParameter(String apiCall, String queryString) {
if (getSalt() != null){
return "&checksum=" + DigestUtils.sha1Hex(apiCall + queryString + getSalt());
} else{
return "";
}
}
/**
* This method generates a checksum which must be included in all api calls
*
* @param s a String data type - which is a SHA-1 hash of callName + queryString + securitySalt
* @return a String object
*/
private String getCheckSumParameter(String s) {
String checksum = "";
try {
checksum = DigestUtils.sha1Hex(s);
} catch (Exception e) {
e.printStackTrace();
}
return checksum;
}
/**
* This method returns a bbb response, by making an api call taking api call type,
* query and response type as parameters.
*
* @param apiCall a String data type - type of api call being made
* @param query a String data type - query to query bbb data
* @param responseType - a generic Class type - used to determine response type
* @return a generic object
* @throws BigBlueButtonException
*/
protected <T extends BigBlueButtonResponse> T makeAPICall(String apiCall, String query, Class<T> responseType)
throws BigBlueButtonException {
return makeAPICall(apiCall, query, "", responseType);
}
/**
* This method returns a bbb response, by making an api call taking api call type,
* query, a presentation and response type as parameters.
* The api call is used to generate a base url that is used to open a connection.
* Once there a connection an XML response to be returned to a api call is processed
* Else a BigBlueButtonException is thrown
*
* @param apiCall a String data type - used to get the base url
* @param query a String data type - used to query bbb data
* @param presentation a String type - presentation
* @param responseType a generic class type - response type
* @return a BigBlueButtonResponse
* @throws BigBlueButtonException
*/
protected <T extends BigBlueButtonResponse> T makeAPICall(String apiCall, String query, String presentation, Class<T> responseType)
throws BigBlueButtonException {
StringBuilder urlStr = new StringBuilder(getBaseURL(API_SERVER_PATH, apiCall));
if (query != null) {
urlStr.append(query);
}
try {
// open connection
URL url = new URL(urlStr.toString());
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setUseCaches(false);
httpConnection.setDoOutput(true);
if(!presentation.equals("")){
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "text/xml");
httpConnection.setRequestProperty("Content-Length", "" + Integer.toString(presentation.getBytes().length));
httpConnection.setRequestProperty("Content-Language", "en-US");
httpConnection.setDoInput(true);
DataOutputStream wr = new DataOutputStream( httpConnection.getOutputStream() );
wr.writeBytes (presentation);
wr.flush();
wr.close();
} else {
httpConnection.setRequestMethod("GET");
}
httpConnection.connect();
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// read response
InputStreamReader isr = null;
BufferedReader reader = null;
StringBuilder xml = new StringBuilder();
try {
isr = new InputStreamReader(httpConnection.getInputStream(), "UTF-8");
reader = new BufferedReader(isr);
String line = reader.readLine();
while (line != null) {
if( !line.startsWith("<?xml version=\"1.0\"?>"))
xml.append(line.trim());
line = reader.readLine();
}
} finally {
if (reader != null)
reader.close();
if (isr != null)
isr.close();
}
httpConnection.disconnect();
String stringXml = xml.toString();
BigBlueButtonResponse bigBlueButtonResponse = bigBlueButtonXMLHandler.processXMLResponse(responseType, stringXml);
String returnCode = bigBlueButtonResponse.getReturncode();
if (API_FAILED.equals(returnCode)) {
throw new BigBlueButtonException(bigBlueButtonResponse.getMessageKey(), bigBlueButtonResponse.getMessage());
}
return responseType.cast(bigBlueButtonResponse);
} else {
throw new BigBlueButtonException(BigBlueButtonException.MESSAGEKEY_HTTPERROR, "BBB server responded with HTTP status code " + responseCode);
}
} catch(BigBlueButtonException e) {
if( !e.getMessageKey().equals("notFound") )
System.out.println("BBBException: MessageKey=" + e.getMessageKey() + ", Message=" + e.getMessage());
throw new BigBlueButtonException( e.getMessageKey(), e.getMessage(), e);
} catch(IOException e) {
System.out.println("BBB IOException: Message=" + e.getMessage());
throw new BigBlueButtonException(BigBlueButtonException.MESSAGEKEY_UNREACHABLE, e.getMessage(), e);
} catch(IllegalArgumentException e) {
System.out.printf("BBB IllegalArgumentException: Message=" + e.getMessage());
throw new BigBlueButtonException(BigBlueButtonException.MESSAGEKEY_INVALIDRESPONSE, e.getMessage(), e);
} catch(Exception e) {
System.out.println("BBB Exception: Message=" + e.getMessage());
throw new BigBlueButtonException(BigBlueButtonException.MESSAGEKEY_UNREACHABLE, e.getMessage(), e);
}
}
}
| gpl-3.0 |
axkr/symja_android_library | symja_android_library/matheclipse-core/src/main/java/org/matheclipse/core/interfaces/INumber.java | 6182 | package org.matheclipse.core.interfaces;
import org.apfloat.Apcomplex;
import org.hipparchus.complex.Complex;
import org.matheclipse.core.eval.EvalEngine;
import org.matheclipse.core.eval.exception.ArgumentTypeException;
import org.matheclipse.core.expression.ApcomplexNum;
import org.matheclipse.core.expression.ComplexNum;
import org.matheclipse.core.expression.F;
/** Implemented by all number interfaces */
public interface INumber extends IExpr {
/**
* Get the absolute value for a given number
*
* @return
*/
@Override
public IExpr abs();
/**
* Get a {@link Apcomplex} number wrapped into an <code>ApcomplexNum</code> object.
*
* @return this number represented as an ApcomplexNum
*/
public ApcomplexNum apcomplexNumValue();
/**
* Get a {@link Apcomplex} object.
*
* @return this number represented as an Apcomplex
*/
public Apcomplex apcomplexValue();
/**
* Returns the smallest (closest to negative infinity) <code>IInteger</code> value that is not
* less than <code>this</code> and is equal to a mathematical integer. This method raises
* {@link ArithmeticException} if a numeric value cannot be represented by an <code>long</code>
* type.
*
* @return the smallest (closest to negative infinity) <code>IInteger</code> value that is not
* less than <code>this</code> and is equal to a mathematical integer.
*/
public INumber ceilFraction() throws ArithmeticException;
/**
* Compare the absolute value of this number with <code>1</code> and return
*
* <ul>
* <li><code>1</code>, if the absolute value is greater than 1
* <li><code>0</code>, if the absolute value equals 1
* <li><code>-1</code>, if the absolute value is less than 1
* </ul>
*
* @return
*/
public int compareAbsValueToOne();
/**
* Get the argument of the complex number
*
* @return
*/
@Override
public IExpr complexArg();
/**
* Get a <code>ComplexNum</code> number bject.
*
* @return
*/
public ComplexNum complexNumValue();
/**
* Gets the signum value of a complex number
*
* @return 0 for <code>this == 0</code>; +1 for <code>real(this) > 0</code> or
* <code>( real(this)==0 && imaginary(this) > 0 )</code>; -1 for
* <code>real(this) < 0 || ( real(this) == 0 && imaginary(this) < 0 )
*/
public int complexSign();
@Override
public INumber conjugate();
/**
* Get the absolute value for a given number
*
* @return
* @deprecated use abs()
*/
@Deprecated
default IExpr eabs() {
return abs();
}
/**
* Check if this number equals the given <code>int</code> number?
*
* @param i the integer number
* @return
*/
public boolean equalsInt(int i);
default INumber evaluatePrecision(EvalEngine engine) {
return this;
}
/**
* Returns the largest (closest to positive infinity) <code>IInteger</code> value that is not
* greater than <code>this</code> and is equal to a mathematical integer. <br>
* This method raises {@link ArithmeticException} if a numeric value cannot be represented by an
* <code>long</code> type.
*
* @return the largest (closest to positive infinity) <code>IInteger</code> value that is not
* greater than <code>this</code> and is equal to a mathematical integer.
*/
public INumber floorFraction() throws ArithmeticException;
/**
* Return the fractional part of this number
*
* @return
*/
public INumber fractionalPart();
/**
* Return the integer (real and imaginary) part of this number
*
* @return
*/
public INumber integerPart();
/**
* Returns the imaginary part of a complex number
*
* @return real part
* @deprecated use {@link #imDoubleValue()}
*/
@Deprecated
default double getImaginary() {
return imDoubleValue();
}
/**
* Returns the real part of a complex number
*
* @return real part
* @deprecated use {@link #reDoubleValue()}
*/
@Override
@Deprecated
default double getReal() {
return reDoubleValue();
}
@Override
default boolean isNumber() {
return true;
}
@Override
default boolean isNumericFunction(boolean allowList) {
return true;
}
/**
* Returns the imaginary part of a complex number
*
* @return real part
*/
@Override
public ISignedNumber im();
/**
* Returns the imaginary part of a complex number
*
* @return real part
*/
public double imDoubleValue();
@Override
public default IExpr[] linear(IExpr variable) {
return new IExpr[] {this, F.C0};
}
@Override
public default IExpr[] linearPower(IExpr variable) {
return new IExpr[] {this, F.C0, F.C1};
}
@Override
public INumber opposite();
/**
* Return the rational Factor of this number. For IComplex numbers check if real and imaginary
* parts are equal or real part or imaginary part is zero.
*
* @return <code>null</code> if no factor could be extracted
*/
default IRational rationalFactor() {
if (this instanceof IRational) {
return (IRational) this;
}
return null;
}
/**
* Returns the real part of a complex number
*
* @return real part
*/
@Override
public ISignedNumber re();
/**
* Returns the real part of a complex number
*
* @return real part
*/
public double reDoubleValue();
/**
* Returns the closest <code>IInteger</code> real and imaginary part to the argument. The result
* is rounded to an integer by adding 1/2 and taking the floor of the result by applying round
* separately to the real and imaginary part . <br>
* This method raises {@link ArithmeticException} if a numeric value cannot be represented by an
* <code>long</code> type.
*
* @return the closest integer to the argument.
*/
public IExpr roundExpr();
/**
* Return the list <code>{r, theta}</code> of the polar coordinates of this number
*
* @return
*/
public IAST toPolarCoordinates();
@Override
default Complex evalComplex() throws ArgumentTypeException {
return new Complex(reDoubleValue(), imDoubleValue());
}
}
| gpl-3.0 |
asarkar/spring | travel-app/src/main/java/name/abhijitsarkar/javaee/travel/repository/N1qlQueryRowToAirportMapper.java | 2021 | package name.abhijitsarkar.javaee.travel.repository;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.query.N1qlQueryRow;
import name.abhijitsarkar.javaee.travel.domain.Airport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.function.Function;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_CITY;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_COUNTRY;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_FAA;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_ICAO;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_NAME;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_TIMEZONE;
/**
* @author Abhijit Sarkar
*/
public class N1qlQueryRowToAirportMapper implements Function<N1qlQueryRow, Airport> {
private static final Logger LOGGER = LoggerFactory.getLogger(N1qlQueryRowToAirportMapper.class);
@Override
public Airport apply(N1qlQueryRow row) {
JsonObject value = row.value();
try {
/* Get current time at airport timezone */
ZonedDateTime now = Instant.now().atZone(ZoneId.of(value.getString(FIELD_TIMEZONE)));
return Airport.builder()
.name(value.getString(FIELD_NAME))
.faaCode(value.getString(FIELD_FAA))
.icaoCode(value.getString(FIELD_ICAO))
.city(value.getString(FIELD_CITY))
.country(value.getString(FIELD_COUNTRY))
.timeZoneOffset(now.getOffset())
.build();
} catch (Exception e) {
LOGGER.error("Failed to convert result row: {} to airport object.", row, e);
return null;
}
}
}
| gpl-3.0 |
ewized/CommonUtils | src/main/java/com/archeinteractive/dev/commonutils/command/CommandHandler.java | 955 | package com.archeinteractive.dev.commonutils.command;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation interface that may be attached to
* a method to designate it as a command handler.
* When registering a handler with this class, only
* methods marked with this annotation will be
* considered for command registration.
*
* @originalauthor AmoebaMan
*/
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CommandHandler {
String name();
String[] aliases() default {""};
String description() default "";
String usage() default "";
String permission() default "";
String permissionMessage() default "You do not have permission to use that command";
}
| gpl-3.0 |
minborg/javapot | src/main/java/com/blogspot/minborgsjavapot/escape_analysis/Main.java | 1138 | package com.blogspot.minborgsjavapot.escape_analysis;
import java.io.IOException;
public class Main {
/*
-server
-XX:BCEATraceLevel=3
-XX:+PrintCompilation
-XX:+UnlockDiagnosticVMOptions
-XX:+PrintInlining
-verbose:gc
-XX:MaxInlineSize=256
-XX:FreqInlineSize=1024
-XX:MaxBCEAEstimateSize=1024
-XX:MaxInlineLevel=22
-XX:CompileThreshold=10
-Xmx4g
-Xms4g
*/
public static void main(String[] args) throws IOException, InterruptedException {
Point p = new Point(100, 200);
sum(p);
System.gc();
System.out.println("Press any key to continue");
System.in.read();
//Thread.sleep(1_000);
long sum = sum(p);
System.out.println(sum);
System.out.println("Press any key to continue2");
System.in.read();
sum = sum(p);
System.out.println(sum);
System.out.println("Press any key to exit");
System.in.read();
}
private static long sum(Point p) {
long sumLen = 0;
for (int i = 0; i < 1_000_000; i++) {
sumLen += p.toString().length();
}
return sumLen;
}
}
| gpl-3.0 |
desces/Essentials | EssentialsUpdate/src/com/earth2me/essentials/update/EssentialsHelp.java | 4454 | package com.earth2me.essentials.update;
import com.earth2me.essentials.update.chat.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
public class EssentialsHelp implements Listener
{
private transient Player chatUser;
private final transient Server server;
private final transient Plugin plugin;
private transient IrcBot ircBot;
private final transient Map<String, Command> commands = new HashMap<String, Command>();
public EssentialsHelp(final Plugin plugin)
{
super();
this.plugin = plugin;
this.server = plugin.getServer();
commands.put("!help", new HelpCommand());
commands.put("!list", new ListCommand());
commands.put("!startup", new StartupCommand(plugin));
commands.put("!errors", new ErrorsCommand(plugin));
commands.put("!config", new ConfigCommand(plugin));
}
public void registerEvents()
{
final PluginManager pluginManager = server.getPluginManager();
pluginManager.registerEvents(this, plugin);
}
public void onCommand(final CommandSender sender)
{
if (sender instanceof Player && sender.hasPermission("essentials.helpchat"))
{
if (chatUser == null)
{
chatUser = (Player)sender;
ircBot = null;
sender.sendMessage("You will be connected to the Essentials Help Chat.");
sender.sendMessage("All your chat messages will be forwarded to the channel. You can't chat with other players on your server while in help chat, but you can use commands.");
sender.sendMessage("Please be patient, if noone is available, check back later.");
sender.sendMessage("Type !help to get a list of all commands.");
sender.sendMessage("Type !quit to leave the channel.");
sender.sendMessage("Do you want to join the channel now? (yes/no)");
}
if (!chatUser.equals(sender))
{
sender.sendMessage("The player " + chatUser.getDisplayName() + " is already using the essentialshelp.");
}
}
else
{
sender.sendMessage("Please run the command as op from in game.");
}
}
public void onDisable()
{
closeConnection();
}
private boolean sendChatMessage(final Player player, final String message)
{
final String messageCleaned = message.trim();
if (messageCleaned.isEmpty())
{
return false;
}
if (ircBot == null)
{
return handleAnswer(messageCleaned, player);
}
else
{
if (ircBot.isKicked())
{
closeConnection();
return false;
}
final String lowMessage = messageCleaned.toLowerCase(Locale.ENGLISH);
if (lowMessage.startsWith("!quit"))
{
closeConnection();
player.sendMessage("Connection closed.");
return true;
}
if (!ircBot.isConnected() || ircBot.getChannels().length == 0)
{
return false;
}
if (handleCommands(lowMessage, player))
{
return true;
}
ircBot.sendMessage(messageCleaned);
chatUser.sendMessage("§6" + ircBot.getNick() + ": §7" + messageCleaned);
return true;
}
}
private void closeConnection()
{
chatUser = null;
if (ircBot != null)
{
ircBot.quit();
ircBot = null;
}
}
private boolean handleAnswer(final String message, final Player player)
{
if (message.equalsIgnoreCase("yes"))
{
player.sendMessage("Connecting...");
connectToIRC(player);
return true;
}
if (message.equalsIgnoreCase("no") || message.equalsIgnoreCase("!quit"))
{
chatUser = null;
return true;
}
return false;
}
private boolean handleCommands(final String lowMessage, final Player player)
{
final String[] parts = lowMessage.split(" ");
if (commands.containsKey(parts[0]))
{
commands.get(parts[0]).run(ircBot, player);
return true;
}
return false;
}
private void connectToIRC(final Player player)
{
ircBot = new IrcBot(player, "Ess_" + player.getName(), UsernameUtil.createUsername(player));
}
@EventHandler
public void onPlayerChat(final PlayerChatEvent event)
{
if (event.getPlayer() == chatUser)
{
final boolean success = sendChatMessage(event.getPlayer(), event.getMessage());
event.setCancelled(success);
}
}
@EventHandler
public void onPlayerQuit(final PlayerQuitEvent event)
{
closeConnection();
}
}
| gpl-3.0 |
danielhuson/megan-ce | src/megan/commands/format/DrawCirclesCommand.java | 3073 | /*
* DrawCirclesCommand.java Copyright (C) 2021. Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 megan.commands.format;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* draw selected nodes as circles
* Daniel Huson, 3.2013
*/
public class DrawCirclesCommand extends CommandBase implements ICommand {
/**
* apply
*
* @param np
* @throws Exception
*/
public void apply(NexusStreamParser np) throws Exception {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ((Director) getDir()).getDocument().getSampleSelection().size() > 0;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Circle";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Circle node shape";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("BlueCircle16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* action to be performed
*
* @param ev
*/
public void actionPerformed(ActionEvent ev) {
execute("set nodeShape=circle;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | packages/apps/Launcher3/src/com/android/launcher3/InfoDropTarget.java | 4717 | /*
* Copyright (C) 2011 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.launcher3;
import android.content.ComponentName;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.TransitionDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.android.launcher3.compat.UserHandleCompat;
public class InfoDropTarget extends ButtonDropTarget {
private ColorStateList mOriginalTextColor;
private TransitionDrawable mDrawable;
public InfoDropTarget(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public InfoDropTarget(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mOriginalTextColor = getTextColors();
// Get the hover color
Resources r = getResources();
mHoverColor = r.getColor(R.color.info_target_hover_tint);
mDrawable = (TransitionDrawable) getCurrentDrawable();
if (mDrawable == null) {
// TODO: investigate why this is ever happening. Presently only on one known device.
mDrawable = (TransitionDrawable) r.getDrawable(R.drawable.info_target_selector);
setCompoundDrawablesRelativeWithIntrinsicBounds(mDrawable, null, null, null);
}
if (null != mDrawable) {
mDrawable.setCrossFadeEnabled(true);
}
// Remove the text in the Phone UI in landscape
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (!LauncherAppState.getInstance().isScreenLarge()) {
setText("");
}
}
}
@Override
public boolean acceptDrop(DragObject d) {
// acceptDrop is called just before onDrop. We do the work here, rather than
// in onDrop, because it allows us to reject the drop (by returning false)
// so that the object being dragged isn't removed from the drag source.
ComponentName componentName = null;
if (d.dragInfo instanceof AppInfo) {
componentName = ((AppInfo) d.dragInfo).componentName;
} else if (d.dragInfo instanceof ShortcutInfo) {
componentName = ((ShortcutInfo) d.dragInfo).intent.getComponent();
} else if (d.dragInfo instanceof PendingAddItemInfo) {
componentName = ((PendingAddItemInfo) d.dragInfo).componentName;
}
final UserHandleCompat user;
if (d.dragInfo instanceof ItemInfo) {
user = ((ItemInfo) d.dragInfo).user;
} else {
user = UserHandleCompat.myUserHandle();
}
if (componentName != null) {
mLauncher.startApplicationDetailsActivity(componentName, user);
}
// There is no post-drop animation, so clean up the DragView now
d.deferDragViewCleanupPostAnimation = false;
return false;
}
@Override
public void onDragStart(DragSource source, Object info, int dragAction) {
boolean isVisible = true;
// Hide this button unless we are dragging something from AllApps
if (!source.supportsAppInfoDropTarget()) {
isVisible = false;
}
mActive = isVisible;
mDrawable.resetTransition();
setTextColor(mOriginalTextColor);
((ViewGroup) getParent()).setVisibility(isVisible ? View.VISIBLE : View.GONE);
}
@Override
public void onDragEnd() {
super.onDragEnd();
mActive = false;
}
public void onDragEnter(DragObject d) {
super.onDragEnter(d);
mDrawable.startTransition(mTransitionDuration);
setTextColor(mHoverColor);
}
public void onDragExit(DragObject d) {
super.onDragExit(d);
if (!d.dragComplete) {
mDrawable.resetTransition();
setTextColor(mOriginalTextColor);
}
}
}
| gpl-3.0 |
afodor/clusterstuff | src/kw_jobinMiRNA/BowtieToPiRBase.java | 1812 | /*
* use bowtie2 to align all samples to piRBase
*/
package kw_jobinMiRNA;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class BowtieToPiRBase {
public static String DIR = "/nobackup/afodor_research/kwinglee/jobin/microRNA/";
public static String FQDIR = DIR + "adapterFiltered/";
public static String OUTDIR = DIR + "piRBaseBowtie/";
public static String SCRIPTDIR = "/projects/afodor_research/kwinglee/scripts/jobin/microRNA/piRNA/";
public static String REF = "/nobackup/afodor_research/kwinglee/piRBase_v1.0/piRbaseMouseBowtie";
public static void main(String[] args) throws IOException {
File odir = new File(OUTDIR);
if(!odir.exists()) {
odir.mkdirs();
}
File[] files = new File(FQDIR).listFiles();
BufferedWriter all = new BufferedWriter(new FileWriter(new File(
SCRIPTDIR + "bowtieAlignAll.sh")));
for(File fq : files) {
if(fq.getName().endsWith(".fastq")) {
String id = fq.getName().replace(".fastq", "");
String scriptName = "bowtieAlignPiR_" + id;
String name = id + ".piR.bowtie";
//add to run all script
all.write("qsub -q \"copperhead\" " + scriptName + "\n");
//write script
BufferedWriter script = new BufferedWriter(new FileWriter(new File(
SCRIPTDIR + scriptName)));
script.write("#PBS -l procs=1,mem=20GB,walltime=12:00:00\n");
script.write("module load bowtie2\n");
script.write("module load samtools\n");
//align
script.write("bowtie2 -x " + REF + " -U " + fq.getAbsolutePath()
+ " -S " + OUTDIR + name + ".sam\n");
script.write("samtools flagstat " + OUTDIR + name + ".sam > "
+ OUTDIR + name + ".flagstat\n");
script.close();
}
}
all.close();
}
}
| gpl-3.0 |
EmilyBjoerk/lsml | src/main/java/org/lisoft/lsml/math/probability/BinomialDistribution.java | 2791 | /*
* @formatter:off
* Li Song Mechlab - A 'mech building tool for PGI's MechWarrior: Online.
* Copyright (C) 2013 Li Song
*
* 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/>.
*/
//@formatter:on
package org.lisoft.lsml.math.probability;
import org.lisoft.lsml.math.FastFactorial;
import java.math.BigDecimal;
import java.math.BigInteger;
import static org.lisoft.lsml.math.FastFactorial.*;
/**
* This class models a binomial distribution
*
* @author Li Song
*/
public class BinomialDistribution implements Distribution {
private final double p;
private final int n;
public static long nChooseK(int n, long aK) {
if(n-aK < aK){
return nChooseK(n, n-aK);
}
long ans = 1;
for (int kk = 0; kk < aK; ++kk) {
ans = ans * (n - kk) / (kk + 1);
}
return ans;
}
public static BigInteger nChooseKLargeNumbers(int n, int aK) {
if(n-aK < aK){
return nChooseKLargeNumbers(n, n-aK);
}
return factorial(n).divide(factorial(aK).multiply(factorial(n-aK)));
/*
BigInteger ans = BigInteger.valueOf(1);
for (int kk = 0; kk < aK; ++kk) {
ans = ans.multiply(BigInteger.valueOf(n - kk)).divide(BigInteger.valueOf(kk + 1));
}
return ans;*/
}
public BinomialDistribution(double aP, int aN) {
p = aP;
n = aN;
}
@Override
public double pdf(double aX) {
long k = Math.round(aX);
return nChooseK(n, k) * Math.pow(p, k) * Math.pow(1.0 - p, n - k);
}
public static double pdf(int aK, int aN, double aP){
BigDecimal Pk = BigDecimal.valueOf(aP).pow(aK);
BigDecimal PnotK = BigDecimal.valueOf(1.0-aP).pow(aN-aK);
BigDecimal permutations = new BigDecimal(nChooseKLargeNumbers(aN, aK));
return permutations.multiply(Pk).multiply(PnotK).doubleValue();
}
@Override
public double cdf(double aX) {
double ans = 0;
final long k = (long) (aX + Math.ulp(aX)); // Accept anything within truncation error of k as k.
for (int i = 0; i <= k; ++i) {
ans += pdf(i);
}
return ans;
}
}
| gpl-3.0 |
shuqin/ALLIN | src/main/java/zzz/study/utils/RemoveJavadocComments.java | 1951 | package zzz.study.utils;
import cc.lovesq.service.CreativeService;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static zzz.study.utils.BaseTool.*;
/**
* 移除指定类的 Javadoc 注释 Created by shuqin on 16/5/4.
*/
public class RemoveJavadocComments {
private static final String javadocRegexStr = "(\\/\\*.*?\\*\\/)";
private static final Pattern javadocPattern =
Pattern.compile(javadocRegexStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
public static void main(String[] args) {
// 移除指定包下面的类 Javadoc 注释
String tradeDALPackage = ALLIN_PROJ_PATH_SRC + "/cc/lovesq/controller";
List<Class> classes = getClasses(tradeDALPackage);
for (Class c : classes) {
if (c.getSimpleName().endsWith("Controller")) {
removeJavadoc(c);
}
}
// 移除单个类的 Javadoc 注释
removeJavadoc(CreativeService.class);
}
public static void removeJavadoc(Class<?> coreServiceCls) {
String coreServiceName = coreServiceCls.getSimpleName();
String packageName = coreServiceCls.getPackage().getName();
String packagePath = "/" + packageName.replaceAll("\\.", "/");
String coreServiceClsRelativePath = packagePath + "/" + coreServiceName + ".java";
String coreServiceClsPath = ALLIN_PROJ_PATH_SRC + coreServiceClsRelativePath;
String coreServiceContent = readFile(coreServiceClsPath);
Matcher m = javadocPattern.matcher(coreServiceContent);
String newContent = coreServiceContent;
while (m.find()) {
String matchedJavadoc = coreServiceContent.substring(m.start(), m.end());
newContent = newContent.replace(matchedJavadoc, "");
}
newContent = newContent.replaceAll("\n\\s*\n", "\n\n");
writeFile(coreServiceClsPath, newContent);
}
}
| gpl-3.0 |
kevdez/abstract-syntax-tree | src/crux/Symbol.java | 601 | package crux;
/**
* studentName = "XXXXXXXX XXXXXXXX";
* studentID = "XXXXXXXX";
* uciNetID = "XXXXXXXX";
*/
public class Symbol {
private String name;
public Symbol(String name) {
this.name = name;
}
public String name()
{
return this.name;
}
public String toString()
{
return "Symbol(" + name + ")";
}
public static Symbol newError(String message) {
return new ErrorSymbol(message);
}
}
class ErrorSymbol extends Symbol
{
public ErrorSymbol(String message)
{
super(message);
}
}
| gpl-3.0 |
Gab0rB/weplantaforest | user/src/main/java/org/dicadeveloper/weplantaforest/trees/UserRepository.java | 358 | package org.dicadeveloper.weplantaforest.trees;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface UserRepository extends CrudRepository<User, Long> {
@Query
public User findByName(@Param("name") String name);
}
| gpl-3.0 |
wizjany/craftbook | src/main/java/com/sk89q/craftbook/circuits/gates/logic/Dispatcher.java | 1687 | package com.sk89q.craftbook.circuits.gates.logic;
import org.bukkit.Server;
import com.sk89q.craftbook.ChangedSign;
import com.sk89q.craftbook.circuits.ic.AbstractIC;
import com.sk89q.craftbook.circuits.ic.AbstractICFactory;
import com.sk89q.craftbook.circuits.ic.ChipState;
import com.sk89q.craftbook.circuits.ic.IC;
import com.sk89q.craftbook.circuits.ic.ICFactory;
public class Dispatcher extends AbstractIC {
public Dispatcher(Server server, ChangedSign block, ICFactory factory) {
super(server, block, factory);
}
@Override
public String getTitle() {
return "Dispatcher";
}
@Override
public String getSignTitle() {
return "DISPATCHER";
}
@Override
public void trigger(ChipState chip) {
boolean value = chip.getInput(0);
boolean targetB = chip.getInput(1);
boolean targetC = chip.getInput(2);
if (targetB) {
chip.setOutput(1, value);
}
if (targetC) {
chip.setOutput(2, value);
}
}
public static class Factory extends AbstractICFactory {
public Factory(Server server) {
super(server);
}
@Override
public IC create(ChangedSign sign) {
return new Dispatcher(getServer(), sign, this);
}
@Override
public String getShortDescription() {
return "Send middle signal out high sides.";
}
@Override
public String[] getLineHelp() {
String[] lines = new String[] {null, null};
return lines;
}
}
}
| gpl-3.0 |
bd2kccd/tetradR | java/edu/cmu/tetrad/annotation/AlgorithmAnnotations.java | 2669 | /*
* Copyright (C) 2017 University of Pittsburgh.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package edu.cmu.tetrad.annotation;
import edu.cmu.tetrad.algcomparison.algorithm.MultiDataSetAlgorithm;
import edu.cmu.tetrad.algcomparison.utils.HasKnowledge;
import edu.cmu.tetrad.algcomparison.utils.TakesIndependenceWrapper;
import edu.cmu.tetrad.algcomparison.utils.UsesScoreWrapper;
import java.util.List;
/**
*
* Sep 26, 2017 12:19:41 AM
*
* @author Kevin V. Bui (kvb2@pitt.edu)
*/
public class AlgorithmAnnotations extends AbstractAnnotations<Algorithm> {
private static final AlgorithmAnnotations INSTANCE = new AlgorithmAnnotations();
private AlgorithmAnnotations() {
super("edu.cmu.tetrad.algcomparison.algorithm", Algorithm.class);
}
public static AlgorithmAnnotations getInstance() {
return INSTANCE;
}
public List<AnnotatedClass<Algorithm>> filterOutExperimental(List<AnnotatedClass<Algorithm>> list) {
return filterOutByAnnotation(list, Experimental.class);
}
public boolean acceptMultipleDataset(Class clazz) {
return (clazz == null)
? false
: MultiDataSetAlgorithm.class.isAssignableFrom(clazz);
}
public boolean acceptKnowledge(Class clazz) {
return (clazz == null)
? false
: HasKnowledge.class.isAssignableFrom(clazz);
}
public boolean requireIndependenceTest(Class clazz) {
return (clazz == null)
? false
: TakesIndependenceWrapper.class.isAssignableFrom(clazz);
}
public boolean requireScore(Class clazz) {
return (clazz == null)
? false
: UsesScoreWrapper.class.isAssignableFrom(clazz);
}
public boolean handleUnmeasuredConfounder(Class clazz) {
return (clazz == null)
? false
: clazz.isAnnotationPresent(UnmeasuredConfounder.class);
}
}
| gpl-3.0 |
ckaestne/LEADT | workspace/argouml_diagrams/argouml-app/src/org/argouml/uml/ui/behavior/common_behavior/UMLReceptionSignalComboBoxModel.java | 4665 | // $Id: UMLReceptionSignalComboBoxModel.java 15837 2008-09-30 23:53:25Z bobtarling $
// Copyright (c) 1996-2006 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui.behavior.common_behavior;
import java.util.Collection;
import org.argouml.kernel.Project;
import org.argouml.kernel.ProjectManager;
import org.argouml.model.Model;
import org.argouml.model.RemoveAssociationEvent;
import org.argouml.model.UmlChangeEvent;
import org.argouml.uml.ui.UMLComboBoxModel2;
/**
* The model for the signal combobox on the reception proppanel.
*/
public class UMLReceptionSignalComboBoxModel extends UMLComboBoxModel2 {
/**
* Constructor for UMLReceptionSignalComboBoxModel.
*/
public UMLReceptionSignalComboBoxModel() {
super("signal", false);
Model.getPump().addClassModelEventListener(this,
Model.getMetaTypes().getNamespace(), "ownedElement");
}
/*
* @see org.argouml.uml.ui.UMLComboBoxModel2#buildModelList()
*/
protected void buildModelList() {
Object target = getTarget();
if (Model.getFacade().isAReception(target)) {
Object rec = /*(MReception)*/ target;
removeAllElements();
Project p = ProjectManager.getManager().getCurrentProject();
Object model = p.getRoot();
setElements(Model.getModelManagementHelper()
.getAllModelElementsOfKindWithModel(
model,
Model.getMetaTypes().getSignal()));
setSelectedItem(Model.getFacade().getSignal(rec));
}
}
/*
* @see org.argouml.uml.ui.UMLComboBoxModel2#isValidElement(Object)
*/
protected boolean isValidElement(Object m) {
return Model.getFacade().isASignal(m);
}
/*
* @see org.argouml.uml.ui.UMLComboBoxModel2#getSelectedModelElement()
*/
protected Object getSelectedModelElement() {
if (getTarget() != null) {
return Model.getFacade().getSignal(getTarget());
}
return null;
}
/**
* Override UMLComboBoxModel2's default handling of RemoveAssociation. We
* get this from MDR for the previous signal when a different signal is
* selected. Don't let that remove it from the combo box. Only remove it if
* the signal was removed from the namespace.
* <p>
* @param evt the event describing the property change
*/
public void modelChanged(UmlChangeEvent evt) {
if (evt instanceof RemoveAssociationEvent) {
if ("ownedElement".equals(evt.getPropertyName())) {
Object o = getChangedElement(evt);
if (contains(o)) {
buildingModel = true;
if (o instanceof Collection) {
removeAll((Collection) o);
} else {
removeElement(o);
}
buildingModel = false;
}
}
} else {
super.propertyChange(evt);
}
}
}
| gpl-3.0 |
treblereel/Opensheet | src/main/java/org/opensheet/client/mvc/views/ProjectView.java | 2557 | /*******************************************************************************
* Copyright (c) 2012 Dmitry Tikhomirov.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Dmitry Tikhomirov - initial API and implementation
******************************************************************************/
package org.opensheet.client.mvc.views;
import org.opensheet.client.mvc.events.AppEvents;
import org.opensheet.client.widges.SheetToolBar;
import org.opensheet.client.widges.project.ProjectPanel;
import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
public class ProjectView extends View{
private LayoutContainer container;
Dispatcher dispatcher = Dispatcher.get();
public ProjectView(Controller controller) {
super(controller);
}
@Override
protected void handleEvent(AppEvent event) {
if (event.getType() == AppEvents.Project) {
LayoutContainer toolbar = (LayoutContainer) Registry.get(AppView.NORTH_PANEL);
if(toolbar.getItems().isEmpty() != true && !toolbar.getItem(0).getItemId().equalsIgnoreCase("sheetToolBarId")){
SheetToolBar sheetToolBar = new SheetToolBar();
toolbar.removeAll();
toolbar.add(sheetToolBar);
toolbar.layout();
}else if(toolbar.getItems().isEmpty()){
SheetToolBar sheetToolBar = new SheetToolBar();
toolbar.add(sheetToolBar);
toolbar.layout();
}
LayoutContainer wrapper = (LayoutContainer) Registry.get(AppView.CENTER_PANEL);
wrapper.removeAll();
wrapper.add(container);
wrapper.layout();
return;
}
}
@Override
protected void initialize() {
container = new LayoutContainer();
BorderLayout layout = new BorderLayout();
layout.setEnableState(false);
container.setLayout(layout);
ProjectPanel pp = new ProjectPanel();
// pp.doLoad();
container.add(pp, new BorderLayoutData(LayoutRegion.CENTER));
}
}
| gpl-3.0 |
vonwenm/EDIReader | src/com/berryworks/edireader/plugin/PluginPreparation.java | 2574 | /*
* Copyright 2005-2011 by BerryWorks Software, LLC. All rights reserved.
*
* This file is part of EDIReader. You may obtain a license for its use directly from
* BerryWorks Software, and you may also choose to use this software under the terms of the
* GPL version 3. Other products in the EDIReader software suite are available only by licensing
* with BerryWorks. Only those files bearing the GPL statement below are available under the GPL.
*
* EDIReader 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.
*
* EDIReader 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 EDIReader. If not,
* see <http://www.gnu.org/licenses/>.
*/
package com.berryworks.edireader.plugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A runtime data structure that optimizes the LoopDescriptors of a plugin
* for access by an EDI parser.
*
* @see com.berryworks.edireader.Plugin
*/
public class PluginPreparation
{
protected final Map<String, List<LoopDescriptor>> segmentMap = new HashMap<String, List<LoopDescriptor>>();
/**
* Constructs an instance given an array of LoopDescriptors.
* <p/>
* The LoopDescriptors typically are taken directly from the EDIPlugin for a given type of document.
*
* @param loops
*/
public PluginPreparation(LoopDescriptor[] loops)
{
if (loops == null)
return;
for (LoopDescriptor loop : loops)
{
String segmentName = loop.getFirstSegment();
List<LoopDescriptor> descriptorList = segmentMap.get(segmentName);
if (descriptorList == null)
{
descriptorList = new ArrayList<LoopDescriptor>();
segmentMap.put(segmentName, descriptorList);
}
descriptorList.add(loop);
}
}
/**
* Returns an ordered list of LoopDescriptors corresponding to loops that start with a
* given segment name.
* <p/>
* The LoopDescriptors appear in the same order as they were mentioned in the plugin.
*
* @param segment
* @return
*/
public List<LoopDescriptor> getList(String segment)
{
return segmentMap.get(segment);
}
}
| gpl-3.0 |
JennyLeeP/AlphaCentauri | src/main/java/com/cyborgJenn/alphaCentauri/utils/AlphaCentauriTab.java | 566 | package com.cyborgJenn.alphaCentauri.utils;
import com.cyborgJenn.alphaCentauri.item.ModItems;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
public class AlphaCentauriTab extends CreativeTabs
{
public AlphaCentauriTab(int id, String name)
{
super(id, name);
this.setNoTitle();
this.setBackgroundImageName("cyborgutils.png");
}
@Override
public ItemStack getTabIconItem()
{
return new ItemStack(ModItems.Sword4);
}
@Override
public boolean hasSearchBar()
{
return false;
}
}
| gpl-3.0 |
theresacsar/BigVoting | MR_SchwartzSet/src/SchwartzSet/IntArrayWritable.java | 2708 | package SchwartzSet;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.WritableComparable;
/**
* Datatype containing an array of {@link IntWritable IntWritables}.
*
* @author -----
*
*/
public class IntArrayWritable implements WritableComparable<Object> {
/**
* Array of {@link IntWritable IntWritables}.
*/
public IntWritable[] values;
/**
* Constructs an {@link IntArrayWritable} with an array of length N.
* @param N number of {@link IntWritable IntWritables} in the object
*/
public IntArrayWritable(int N) {
values = new IntWritable[N];
}
/**
* Constructs an {@link IntArrayWritable} with an array of length 0.
*/
public IntArrayWritable() {
values = new IntWritable[0];
}
/**
* Constructs an {@link IntArrayWritable} containing the input array values.
* @param values array of {@link IntWritable IntWritables}
*/
public IntArrayWritable(IntWritable[] values) {
this.values = values;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(values.length);
for(int i=0; i<values.length; i++){
values[i].write(out);
}
}
@Override
public void readFields(DataInput in) throws IOException {
values = new IntWritable[in.readInt()];
for (int i=0; i<values.length; i++){
IntWritable value = new IntWritable();
value.readFields(in);
values[i]=value;
}
}
@Override
public int compareTo(Object o) {
IntArrayWritable other = (IntArrayWritable) o;
return(this.values[1].compareTo(other.values[1]));
}
public void setValues(int[] values) {
this.values = new IntWritable[values.length];
for(int i=0; i<values.length; i++){
this.values[i].set(values[i]);
}
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
IntArrayWritable other = (IntArrayWritable) obj;
if(values.length != other.values.length){
return false;
}
for (int i=0; i<values.length; i++){
if(values[i].get()!=other.values[i].get()){
return false;
}
}
return true;
}
@Override
public int hashCode() {
if (values == null) {
return 0;
}
if(values.length==0){
return 0;
}
return values[0].hashCode()+values.length*13;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.valueOf(values.length));
if(values.length>0) {
sb.append(",");
for (int i = 0; i < values.length; i++) {
sb.append(values[i].toString());
if (i != values.length - 1) {
sb.append(",");
}
}
}
return sb.toString();
}
} | gpl-3.0 |
kodokojo/kodokojo | src/main/java/io/kodokojo/commons/service/repository/search/ProjectConfigurationSearchDto.java | 1605 | package io.kodokojo.commons.service.repository.search;
import io.kodokojo.commons.model.ProjectConfiguration;
import io.kodokojo.commons.service.elasticsearch.DataIdProvider;
import java.util.function.Function;
import static java.util.Objects.requireNonNull;
public class ProjectConfigurationSearchDto implements DataIdProvider {
private static final String PROJECT = "project";
private String identifier;
private String name;
public ProjectConfigurationSearchDto() {
super();
}
public static ProjectConfigurationSearchDto convert(ProjectConfiguration projectConfiguration) {
requireNonNull(projectConfiguration, "projectConfiguration must be defined.");
return converter().apply(projectConfiguration);
}
public static Function<ProjectConfiguration, ProjectConfigurationSearchDto> converter() {
return projectConfiguration -> {
ProjectConfigurationSearchDto res = new ProjectConfigurationSearchDto();
res.setIdentifier(projectConfiguration.getIdentifier());
res.setName(projectConfiguration.getName());
return res;
};
}
@Override
public String getId() {
return identifier;
}
@Override
public String getType() {
return PROJECT;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/vavr/src/main/java/com/baeldung/samples/java/vavr/VavrSampler.java | 4000 | package com.baeldung.samples.java.vavr;
import java.util.ArrayList;
import java.util.List;
import io.vavr.collection.Stream;
/**
*
* @author baeldung
*/
public class VavrSampler {
static int[] intArray = new int[] { 1, 2, 4 };
static List<Integer> intList = new ArrayList<>();
static int[][] intOfInts = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
public static void main(String[] args) {
vavrStreamElementAccess();
System.out.println("====================================");
vavrParallelStreamAccess();
System.out.println("====================================");
vavrFlatMapping();
System.out.println("====================================");
vavrStreamManipulation();
System.out.println("====================================");
vavrStreamDistinct();
}
public static void vavrStreamElementAccess() {
System.out.println("Vavr Element Access");
System.out.println("====================================");
Stream<Integer> vavredStream = Stream.ofAll(intArray);
System.out.println("Vavr index access: " + vavredStream.get(2));
System.out.println("Vavr head element access: " + vavredStream.get());
Stream<String> vavredStringStream = Stream.of("foo", "bar", "baz");
System.out.println("Find foo " + vavredStringStream.indexOf("foo"));
}
public static void vavrParallelStreamAccess() {
System.out.println("Vavr Stream Concurrent Modification");
System.out.println("====================================");
Stream<Integer> vavrStream = Stream.ofAll(intList);
// intList.add(5);
vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i));
// Stream<Integer> wrapped = Stream.ofAll(intArray);
// intArray[2] = 5;
// wrapped.forEach(i -> System.out.println("Vavr looped " + i));
}
public static void jdkFlatMapping() {
System.out.println("Java flatMapping");
System.out.println("====================================");
java.util.stream.Stream.of(42).flatMap(i -> java.util.stream.Stream.generate(() -> {
System.out.println("nested call");
return 42;
})).findAny();
}
public static void vavrFlatMapping() {
System.out.println("Vavr flatMapping");
System.out.println("====================================");
Stream.of(42)
.flatMap(i -> Stream.continually(() -> {
System.out.println("nested call");
return 42;
}))
.get(0);
}
public static void vavrStreamManipulation() {
System.out.println("Vavr Stream Manipulation");
System.out.println("====================================");
List<String> stringList = new ArrayList<>();
stringList.add("foo");
stringList.add("bar");
stringList.add("baz");
Stream<String> vavredStream = Stream.ofAll(stringList);
vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
Stream<String> vavredStream2 = vavredStream.insert(2, "buzz");
vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
Stream<String> deletionStream = vavredStream.remove("bar");
deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));
}
public static void vavrStreamDistinct() {
Stream<String> vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo");
Stream<String> distinctVavrStream = vavredStream.distinctBy((y, z) -> {
return y.compareTo(z);
});
distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item));
}
}
| gpl-3.0 |
sdp0et/barsuift-simlife | simLifeDisplayAPI/src/test/java/barsuift/simLife/j3d/tree/MockTreeBranch3D.java | 3316 | /**
* barsuift-simlife is a life simulator program
*
* Copyright (C) 2010 Cyrille GACHOT
*
* This file is part of barsuift-simlife.
*
* barsuift-simlife 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.
*
* barsuift-simlife 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 barsuift-simlife. If not, see
* <http://www.gnu.org/licenses/>.
*/
package barsuift.simLife.j3d.tree;
import java.util.ArrayList;
import java.util.List;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Transform3D;
public class MockTreeBranch3D implements TreeBranch3D {
private List<TreeLeaf3D> leaves;
private float length;
private float radius;
private BranchGroup branchGroup;
private TreeBranch3DState state;
private int synchronizedCalled;
private int increaseOneLeafSizeCalled;
private Transform3D transform;
public MockTreeBranch3D() {
super();
reset();
}
public void reset() {
leaves = new ArrayList<TreeLeaf3D>();
length = 0;
radius = 0;
branchGroup = new BranchGroup();
state = new TreeBranch3DState();
synchronizedCalled = 0;
increaseOneLeafSizeCalled = 0;
transform = new Transform3D();
}
@Override
public List<TreeLeaf3D> getLeaves() {
return leaves;
}
@Override
public void addLeaf(TreeLeaf3D leaf3D) {
leaves.add(leaf3D);
}
public void removeLeaf(TreeLeaf3D leaf3D) {
leaves.remove(leaf3D);
}
@Override
public float getLength() {
return length;
}
public void setLength(float length) {
this.length = length;
}
@Override
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
this.radius = radius;
}
@Override
public BranchGroup getBranchGroup() {
return branchGroup;
}
public void setGroup(BranchGroup branchGroup) {
this.branchGroup = branchGroup;
}
@Override
public TreeBranch3DState getState() {
return state;
}
public void setState(TreeBranch3DState state) {
this.state = state;
}
@Override
public void synchronize() {
this.synchronizedCalled++;
}
public int getNbSynchronize() {
return synchronizedCalled;
}
@Override
public void increaseOneLeafSize() {
this.increaseOneLeafSizeCalled++;
}
public int getNbIncreaseOneLeafSizeCalled() {
return increaseOneLeafSizeCalled;
}
@Override
public Transform3D getTransform() {
return transform;
}
public void setTransform(Transform3D transform) {
this.transform = transform;
}
}
| gpl-3.0 |
sgs-us/microtrafficsim | microtrafficsim-core/src/main/java/microtrafficsim/core/vis/glui/Component.java | 5134 | package microtrafficsim.core.vis.glui;
import com.jogamp.newt.event.KeyListener;
import microtrafficsim.core.vis.glui.events.MouseListener;
import microtrafficsim.core.vis.glui.renderer.ComponentRenderPass;
import microtrafficsim.math.Mat3d;
import microtrafficsim.math.Rect2d;
import microtrafficsim.math.Vec2d;
import java.util.ArrayList;
public abstract class Component {
protected UIManager manager = null;
protected ComponentRenderPass[] renderer = null;
protected Mat3d transform = Mat3d.identity();
protected Mat3d invtransform = Mat3d.identity();
protected Rect2d aabb = null;
protected Component parent = null;
protected ArrayList<Component> children = new ArrayList<>();
protected boolean focusable = true;
protected boolean focused = false;
protected boolean mouseover = false;
protected boolean active = true;
protected boolean visible = true;
private ArrayList<MouseListener> mouseListeners = new ArrayList<>();
private ArrayList<KeyListener> keyListeners = new ArrayList<>();
protected Component(ComponentRenderPass... renderer) {
this.renderer = renderer;
}
protected void setUIManager(UIManager manager) {
this.manager = manager;
for (Component c : children)
c.setUIManager(manager);
if (manager != null)
manager.redraw(this);
}
public UIManager getUIManager() {
return manager;
}
protected ComponentRenderPass[] getRenderPasses() {
return renderer;
}
public void setTransform(Mat3d transform) {
this.transform = transform;
this.invtransform = Mat3d.invert(transform);
redraw();
}
public Mat3d getTransform() {
return transform;
}
public Mat3d getInverseTransform() {
return invtransform;
}
protected void setBounds(Rect2d aabb) {
this.aabb = aabb;
redraw();
}
protected Rect2d getBounds() {
return aabb;
}
protected abstract boolean contains(Vec2d p);
public Component getParent() {
return parent;
}
protected void add(Component child) {
if (child.parent != null)
child.parent.remove(child);
children.add(child);
child.parent = this;
child.setUIManager(manager);
updateBounds();
redraw();
}
protected boolean remove(Component child) {
if (children.remove(child)) {
child.parent = null;
child.setUIManager(null);
updateBounds();
redraw();
return true;
}
return false;
}
protected ArrayList<Component> getComponents() {
return children;
}
protected void updateBounds() {
Rect2d aabb = new Rect2d(Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE);
for (Component c : children) {
Rect2d cbb = Rect2d.transform(c.transform, c.getBounds());
if (aabb.xmin > cbb.xmin) aabb.xmin = cbb.xmin;
if (aabb.xmax < cbb.xmax) aabb.xmax = cbb.xmax;
if (aabb.ymin > cbb.ymin) aabb.ymin = cbb.ymin;
if (aabb.ymax < cbb.ymax) aabb.ymax = cbb.ymax;
}
this.aabb = aabb;
}
public void redraw(boolean recursive) {
if (manager != null) {
if (recursive)
for (Component c : children)
c.redraw(true);
manager.redraw(this);
}
}
public void redraw() {
redraw(false);
}
public void setFocusable(boolean focusable) {
this.focusable = focusable;
if (manager != null)
manager.redraw(this);
}
public boolean isFocusable() {
return focusable;
}
public void setFocused(boolean focused) {
if (!focusable) return;
if (this.manager != null)
this.manager.setFocus(this);
}
public boolean isFocused() {
return focused;
}
public boolean isMouseOver() {
return mouseover;
}
public void setActive(boolean active) {
this.active = active;
if (manager != null)
manager.redraw(this);
}
public boolean isActive() {
return active;
}
public void setVisible(boolean visible) {
this.visible = visible;
if (manager != null)
manager.redraw(this);
}
public boolean isVisible() {
return visible;
}
public void addMouseListener(MouseListener listener) {
mouseListeners.add(listener);
}
public void removeMouseListener(MouseListener listener) {
mouseListeners.remove(listener);
}
public ArrayList<MouseListener> getMouseListeners() {
return mouseListeners;
}
public void addKeyListener(KeyListener listener) {
keyListeners.add(listener);
}
public void removeKeyListener(KeyListener listener) {
keyListeners.remove(listener);
}
public ArrayList<KeyListener> getKeyListeners() {
return keyListeners;
}
}
| gpl-3.0 |
HeadInBush/Skywars | src/main/java/mq/xivklott/main/Title.java | 1945 | package mq.xivklott.main;
import net.minecraft.server.v1_8_R3.EntityPlayer;
import net.minecraft.server.v1_8_R3.IChatBaseComponent;
import net.minecraft.server.v1_8_R3.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_8_R3.PacketPlayOutTitle;
import net.minecraft.server.v1_8_R3.PacketPlayOutTitle.EnumTitleAction;
import net.minecraft.server.v1_8_R3.PlayerConnection;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
public class Title {
public static void sendTitle(Player player, String title, String subTitle, int ticks) {
IChatBaseComponent chatTitle = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + title + "\"}");
IChatBaseComponent chatsubTitle = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + subTitle + "\"}");
PacketPlayOutTitle titre = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, chatTitle);
PacketPlayOutTitle soustitre = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.SUBTITLE,
chatsubTitle);
((CraftPlayer) player).getHandle().playerConnection.sendPacket(titre);
((CraftPlayer) player).getHandle().playerConnection.sendPacket(soustitre);
sendTime(player, ticks);
}
private static void sendTime(Player player, int ticks) {
PacketPlayOutTitle p = new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TIMES, null, 20, ticks, 20);
((CraftPlayer) player).getHandle().playerConnection.sendPacket(p);
}
public static void sendActionBar(Player player, String message) {
IChatBaseComponent actionBar = IChatBaseComponent.ChatSerializer.a("{\"text\": \"" + message + "\"}");
net.minecraft.server.v1_8_R3.PacketPlayOutChat ab = new net.minecraft.server.v1_8_R3.PacketPlayOutChat(
actionBar, (byte) 2);
((CraftPlayer) player).getHandle().playerConnection.sendPacket(ab);
}
} | gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/spring-boot-ops/src/main/java/org/baeldung/boot/domain/AbstractEntity.java | 159 | package org.baeldung.boot.domain;
public abstract class AbstractEntity {
long id;
public AbstractEntity(long id){
this.id = id;
}
}
| gpl-3.0 |
drugis/addis-core | src/main/java/org/drugis/addis/subProblems/repository/impl/SubProblemRepositoryImpl.java | 2713 | package org.drugis.addis.subProblems.repository.impl;
import org.drugis.addis.exception.ResourceDoesNotExistException;
import org.drugis.addis.subProblems.SubProblem;
import org.drugis.addis.subProblems.repository.SubProblemRepository;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.Collection;
/**
* Created by joris on 8-5-17.
*/
@Repository
public class SubProblemRepositoryImpl implements SubProblemRepository {
@Qualifier("emAddisCore")
@PersistenceContext(unitName = "addisCore")
private EntityManager em;
@Override
public SubProblem create(Integer workspaceId, String definition, String title) {
SubProblem newSubProblem = new SubProblem(workspaceId, definition, title);
em.persist(newSubProblem);
return newSubProblem;
}
@Override
public Collection<SubProblem> queryByProject(Integer projectId) {
TypedQuery<SubProblem> query = em.createQuery(
"SELECT DISTINCT sp FROM SubProblem sp\n" +
" WHERE sp.workspaceId in(\n " +
" SELECT id FROM AbstractAnalysis where projectid = :projectId\n" +
" )", SubProblem.class);
query.setParameter("projectId", projectId);
return query.getResultList();
}
@Override
public Collection<SubProblem> queryByProjectAndAnalysis(Integer projectId, Integer workspaceId) {
TypedQuery<SubProblem> query = em.createQuery(
"SELECT DISTINCT sp FROM SubProblem sp\n" +
" WHERE sp.workspaceId = :workspaceId \n" +
" AND sp.workspaceId in(\n " +
" SELECT id FROM AbstractAnalysis where id = :workspaceId and projectid = :projectId\n" +
" )", SubProblem.class);
query.setParameter("workspaceId", workspaceId);
query.setParameter("projectId", projectId);
return query.getResultList();
}
@Override
public SubProblem get(Integer subProblemId) throws ResourceDoesNotExistException {
SubProblem subProblem = em.find(SubProblem.class, subProblemId);
if (subProblem == null) {
throw new ResourceDoesNotExistException();
}
return subProblem;
}
@Override
public void update(Integer analysisId, Integer subProblemId, String definition, String title) throws ResourceDoesNotExistException {
SubProblem subProblem = get(subProblemId);
if (definition != null) {
subProblem.setDefinition(definition);
}
if (title != null) {
subProblem.setTitle(title);
}
em.merge(subProblem);
}
}
| gpl-3.0 |
daftano/dl-learner | components-core/src/main/java/org/dllearner/kb/extraction/ClassNode.java | 7843 | /**
* Copyright (C) 2007-2011, Jens Lehmann
*
* This file is part of DL-Learner.
*
* DL-Learner 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.
*
* DL-Learner 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.dllearner.kb.extraction;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.log4j.Logger;
import org.dllearner.kb.aquisitors.RDFBlankNode;
import org.dllearner.kb.aquisitors.TupleAquisitor;
import org.dllearner.kb.manipulator.Manipulator;
import org.dllearner.utilities.datastructures.RDFNodeTuple;
import org.dllearner.utilities.owl.OWLVocabulary;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDataFactory;
/**
* Is a node in the graph, that is a class.
*
* @author Sebastian Hellmann
*/
public class ClassNode extends Node {
private static Logger logger = Logger
.getLogger(ClassNode.class);
List<ObjectPropertyNode> classProperties = new ArrayList<ObjectPropertyNode>();
List<DatatypePropertyNode> datatypeProperties = new ArrayList<DatatypePropertyNode>();
List<BlankNode> blankNodes = new ArrayList<BlankNode>();
public ClassNode(String uri) {
super(uri);
}
// expands all directly connected nodes
@Override
public List<Node> expand(TupleAquisitor tupelAquisitor, Manipulator manipulator) {
SortedSet<RDFNodeTuple> newTuples = tupelAquisitor.getTupelForResource(this.uri);
// see manipulator
newTuples = manipulator.manipulate(this, newTuples);
List<Node> newNodes = new ArrayList<Node>();
Node tmp;
for (RDFNodeTuple tuple : newTuples) {
if((tmp = processTuple(tuple,tupelAquisitor.isDissolveBlankNodes()))!= null) {
newNodes.add(tmp);
}
}
return newNodes;
}
private Node processTuple( RDFNodeTuple tuple, boolean dissolveBlankNodes) {
try {
String property = tuple.a.toString();
if(tuple.b.isLiteral()) {
datatypeProperties.add(new DatatypePropertyNode(tuple.a.toString(), this, new LiteralNode(tuple.b) ));
return null;
}else if(tuple.b.isAnon()){
if(dissolveBlankNodes){
RDFBlankNode n = (RDFBlankNode) tuple.b;
BlankNode tmp = new BlankNode( n, tuple.a.toString());
//add it to the graph
blankNodes.add(tmp);
//return tmp;
return tmp;
}else{
//do nothing
return null;
}
// substitute rdf:type with owl:subclassof
}else if (property.equals(OWLVocabulary.RDF_TYPE) ||
OWLVocabulary.isStringSubClassVocab(property)) {
ClassNode tmp = new ClassNode(tuple.b.toString());
classProperties.add(new ObjectPropertyNode( OWLVocabulary.RDFS_SUBCLASS_OF, this, tmp));
return tmp;
} else {
// further expansion stops here
ClassNode tmp = new ClassNode(tuple.b.toString());
classProperties.add(new ObjectPropertyNode(tuple.a.toString(), this, tmp));
return tmp; //is missing on purpose
}
} catch (Exception e) {
logger.warn("Problem with: " + this + " in tuple " + tuple);
e.printStackTrace();
}
return null;
}
// gets the types for properties recursively
@Override
public List<BlankNode> expandProperties(TupleAquisitor tupelAquisitor, Manipulator manipulator, boolean dissolveBlankNodes) {
return new ArrayList<BlankNode>();
}
/*
* (non-Javadoc)
*
* @see org.dllearner.kb.sparql.datastructure.Node#toNTriple()
*/
@Override
public SortedSet<String> toNTriple() {
SortedSet<String> returnSet = new TreeSet<String>();
String subject = getNTripleForm();
returnSet.add(subject+"<" + OWLVocabulary.RDF_TYPE + "><" + OWLVocabulary.OWL_CLASS + ">.");
for (ObjectPropertyNode one : classProperties) {
returnSet.add(subject + one.getNTripleForm() +
one.getBPart().getNTripleForm()+" .");
returnSet.addAll(one.getBPart().toNTriple());
}
for (DatatypePropertyNode one : datatypeProperties) {
returnSet.add(subject+ one.getNTripleForm() + one.getNTripleFormOfB()
+ " .");
}
return returnSet;
}
@Override
public void toOWLOntology( OWLAPIOntologyCollector owlAPIOntologyCollector){
try{
OWLDataFactory factory = owlAPIOntologyCollector.getFactory();
OWLClass me =factory.getOWLClass(getIRI());
for (ObjectPropertyNode one : classProperties) {
OWLClass c = factory.getOWLClass(one.getBPart().getIRI());
if(OWLVocabulary.isStringSubClassVocab(one.getURIString())){
owlAPIOntologyCollector.addAxiom(factory.getOWLSubClassOfAxiom(me, c));
}else if(one.getURIString().equals(OWLVocabulary.OWL_DISJOINT_WITH)){
owlAPIOntologyCollector.addAxiom(factory.getOWLDisjointClassesAxiom(me, c));
}else if(one.getURIString().equals(OWLVocabulary.OWL_EQUIVALENT_CLASS)){
owlAPIOntologyCollector.addAxiom(factory.getOWLEquivalentClassesAxiom(me, c));
}else if(one.getURIString().equals(OWLVocabulary.RDFS_IS_DEFINED_BY)){
logger.warn("IGNORING: "+OWLVocabulary.RDFS_IS_DEFINED_BY);
continue;
}else {
tail(true, "in ontology conversion"+" object property is: "+one.getURIString()+" connected with: "+one.getBPart().getURIString());
continue;
}
one.getBPart().toOWLOntology(owlAPIOntologyCollector);
}
for (DatatypePropertyNode one : datatypeProperties) {
//FIXME add languages
// watch for tail
if(one.getURIString().equals(OWLVocabulary.RDFS_COMMENT)){
OWLAnnotation annoComment = factory.getOWLAnnotation(factory.getRDFSComment(), factory.getOWLStringLiteral(one.getBPart().getLiteral().getString()));
OWLAxiom ax = factory.getOWLAnnotationAssertionAxiom(me.getIRI(), annoComment);
owlAPIOntologyCollector.addAxiom(ax);
}else if(one.getURIString().equals(OWLVocabulary.RDFS_LABEL)) {
OWLAnnotation annoLabel = factory.getOWLAnnotation(factory.getRDFSLabel(), factory.getOWLStringLiteral(one.getBPart().getLiteral().getString()));
OWLAxiom ax = factory.getOWLAnnotationAssertionAxiom(me.getIRI(), annoLabel);
owlAPIOntologyCollector.addAxiom(ax);
}else {
tail(true, "in ontology conversion: no other datatypes, but annotation is allowed for classes."+" data property is: "+one.getURIString()+" connected with: "+one.getBPart().getNTripleForm());
}
}
for (BlankNode bn : blankNodes) {
OWLClassExpression target = bn.getAnonymousClass(owlAPIOntologyCollector);
if(OWLVocabulary.isStringSubClassVocab(bn.getInBoundEdge())){
owlAPIOntologyCollector.addAxiom(factory.getOWLSubClassOfAxiom(me, target));
}else if(bn.getInBoundEdge().equals(OWLVocabulary.OWL_DISJOINT_WITH)){
owlAPIOntologyCollector.addAxiom(factory.getOWLDisjointClassesAxiom(me, target));
}else if(bn.getInBoundEdge().equals(OWLVocabulary.OWL_EQUIVALENT_CLASS)){
owlAPIOntologyCollector.addAxiom(factory.getOWLEquivalentClassesAxiom(me, target));
}else {
tail( "in ontology conversion"+" bnode is: "+bn.getInBoundEdge()+"||"+ bn );
}
}
}catch (Exception e) {
System.out.println("aaa"+getURIString());
e.printStackTrace();
}
}
}
| gpl-3.0 |
marvisan/HadesFIX | Model/src/main/java/net/hades/fix/message/type/QuoteResponseLevel.java | 1649 | /*
* Copyright (c) 2006-2016 Marvisan Pty. Ltd. All rights reserved.
* Use is subject to license terms.
*/
/*
* QuoteResponseLevel.java
*
* $Id: QuoteResponseLevel.java,v 1.3 2010-01-14 09:06:48 vrotaru Exp $
*/
package net.hades.fix.message.type;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* Level of Response requested from receiver of quote messages.
*
* @author <a href="mailto:support@marvisan.com">Support Team</a>
* @version $Revision: 1.3 $
* @created 21/04/2009, 9:51:34 AM
*/
@XmlType
@XmlEnum(Integer.class)
public enum QuoteResponseLevel {
@XmlEnumValue("0") NoAck (0),
@XmlEnumValue("1") AckOnlyNegativeOrErroneous (1),
@XmlEnumValue("2") AckEachQuote (2),
@XmlEnumValue("3") SummaryAck (3);
private static final long serialVersionUID = -8326896911735835286L;
private int value;
private static final Map<String, QuoteResponseLevel> stringToEnum = new HashMap<String, QuoteResponseLevel>();
static {
for (QuoteResponseLevel tag : values()) {
stringToEnum.put(String.valueOf(tag.getValue()), tag);
}
}
/** Creates a new instance of QuoteResponseLevel */
QuoteResponseLevel(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static QuoteResponseLevel valueFor(int value) {
return stringToEnum.get(String.valueOf(value));
}
}
| gpl-3.0 |
antaljanosbenjamin/DVDComposer | src/main/java/hu/smiths/dvdcomposer/model/algorithm/OuterAlgorithm.java | 2346 | package hu.smiths.dvdcomposer.model.algorithm;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Set;
import hu.smiths.dvdcomposer.model.Disc;
import hu.smiths.dvdcomposer.model.exceptions.CannotFindValidAssignmentException;
import hu.smiths.dvdcomposer.model.exceptions.CannotLoadAlgorithmClass;
public class OuterAlgorithm implements Algorithm {
private Algorithm algorithm;
private OuterAlgorithm(Algorithm algorithm) {
this.algorithm = algorithm;
}
public static OuterAlgorithm createFromJarAndClassFQN(File jar, String classFQN) throws CannotLoadAlgorithmClass {
return new OuterAlgorithm(load(jar, classFQN));
}
private static Algorithm load(File jar, String classFQN) throws CannotLoadAlgorithmClass {
try {
Class<?> loadedClass = getClassFromJar(jar, classFQN);
return getNewAlgorithmInstance(loadedClass);
} catch (IOException | IllegalArgumentException | SecurityException | IllegalAccessException
| ClassNotFoundException | InstantiationException e) {
throw new CannotLoadAlgorithmClass("Cannot load " + classFQN + " from " + jar.getAbsolutePath(), e);
}
}
private static Class<?> getClassFromJar(File jar, String classFQN)
throws MalformedURLException, ClassNotFoundException {
URL url = jar.toURI().toURL();
URLClassLoader loader = new URLClassLoader(new URL[] { url }, OuterAlgorithm.class.getClassLoader());
return Class.forName(classFQN, true, loader);
}
private static Algorithm getNewAlgorithmInstance(Class<?> clazz)
throws CannotLoadAlgorithmClass, InstantiationException, IllegalAccessException {
if (Algorithm.class.isAssignableFrom(clazz)) {
return (Algorithm) clazz.newInstance();
} else {
throw new CannotLoadAlgorithmClass(
clazz.toGenericString() + " doesn't implements " + Algorithm.class.toGenericString() + "!");
}
}
@Override
public Set<Disc> generate(Input input) throws CannotFindValidAssignmentException {
try {
return algorithm.generate(input);
} catch (Throwable t) {
throw new CannotFindValidAssignmentException("The outer algorithm could not find a valid assigment!", t);
}
}
public void changeAlgorithm(File jar, String classFQN) throws CannotLoadAlgorithmClass{
algorithm = load(jar, classFQN);
}
}
| gpl-3.0 |
GeorgH93/Bukkit_Bungee_PluginLib | pcgf_pluginlib-common/src/at/pcgamingfreaks/Message/MessageClickEvent.java | 2531 | /*
* Copyright (C) 2020 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Message;
import com.google.gson.annotations.SerializedName;
import org.jetbrains.annotations.NotNull;
import lombok.Getter;
import lombok.Setter;
/**
* The click event is used for the JSON messages when the part of the message using it is clicked.
*/
public class MessageClickEvent
{
/**
* The action that should be executed when the click event is triggered.
*/
@Getter @Setter private @NotNull ClickEventAction action;
/**
* The value to be used when the click action is triggered.
*/
@Getter @Setter private @NotNull String value;
/**
* Creates a new click event for a JSON message component.
*
* @param action The action that should be executed on click.
* @param value The value used for the action of the event.
*/
public MessageClickEvent(final @NotNull ClickEventAction action, final @NotNull String value)
{
this.action = action;
this.value = value;
}
/**
* Enum with all possible actions for a click event.
*/
public enum ClickEventAction
{
/**
* Runs a command as the clicking player.
*/
@SerializedName("run_command") RUN_COMMAND,
/**
* Suggests a command in the chat bar of the clicking player.
*/
@SerializedName("suggest_command") SUGGEST_COMMAND,
/**
* Opens a url in the browser of the clicking player.
*/
@SerializedName("open_url") OPEN_URL,
/**
* Changes the page of the book the clicking player is currently reading. <b>Only works in books!!!</b>
*/
@SerializedName("change_page") CHANGE_PAGE,
/**
* Opens a file on the clicking players hard drive. Used from minecraft for the clickable screenshot link.
* The chance that we know the path to a file on the clients hard disk is pretty low, so the usage of this is pretty limited.
*/
@SerializedName("open_file") OPEN_FILE
}
} | gpl-3.0 |
SMXCore/SMXCore_NG | src/modules/MeterKamstrup.java | 7242 | /*
* 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 modules;
import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Enumeration;
/**
*
* @author cristi
*/
public class MeterKamstrup extends Module {
@Override
public void Initialize() {
pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
// PropUtil.LoadFromFile(pAssociation, PropUtil.GetString(pAttributes, "pAssociation", ""));
sPrefix = PropUtil.GetString(pAttributes, "sPrefix", "");
// lPeriod = PropUtil.GetInt(pAttributes, "lPeriod", 1000);
sCmdLine = PropUtil.GetString(pAttributes, "sCmdLine", "");
sStartPath = PropUtil.GetString(pAttributes, "sStartPath", "");
iTimeOut = PropUtil.GetInt(pAttributes, "iTimeOut", 30000);
iPause = PropUtil.GetInt(pAttributes, "iPause", 30000);
iDebug = PropUtil.GetInt(pAttributes, "iDebug", 0);
lPeriod = PropUtil.GetLong(pAttributes, "lPeriod", 5000);
}
// Properties pAssociation = new Properties();
//
Properties pDataSet = null;
String sPrefix = "";
Thread tLoop = null;
Thread tWachDog = null;
int iTimeOut = 30000;
int iPause = 30000;
long lLastRead = 0;
int iDebug = 0;
long lPeriod = 0;
@Override
public void Start() {
try {
sdfDate.setTimeZone(TimeZone.getDefault());
tLoop = new Thread(new Runnable() {
@Override
public void run() {
Loop();
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
tLoop.start();
if (tWachDog == null) {
tWachDog = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
if (System.currentTimeMillis() - lLastRead > iTimeOut) {
ReStartProc();
}
} catch (Exception e) {
}
}
}
});
tWachDog.start();
}
} catch (Exception e) {
// Log(Name + "-Open-" + e.getMessage() + "-" + e.getCause());
}
}
BufferedReader br = null;
String sLine = "";
String[] ssLineVars = null;
String sDate = "";
String sTime = "";
private final SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
public void Loop() {
while (bStop == 0) {
try {
Thread.sleep(10);
try {
sLine = br.readLine();
} catch (Exception ex) {
ReStartProc();
continue;
}
if ((iDebug == 1) && (sLine!=null)) {
System.out.println(sLine);
}
lLastRead = System.currentTimeMillis();
if ((sLine == null) || (sLine.length() < 1)) {
ReStartProc();
continue;
}
while (sLine.contains(" ")) {
sLine = sLine.replaceAll(" ", " ");
}
sLine = sLine.replaceAll(" ", "\t");
ssLineVars = sLine.split("\t");
if (ssLineVars.length < 2) {
continue;
}
if ((ssLineVars[0].length() < 1) || (ssLineVars[1].length() < 1) || ("None".equals(ssLineVars[1]))) {
continue;
}
if ("Date".equals(ssLineVars[0])) {
sDate = ssLineVars[1];
if (sTime.length() > 0) {
pDataSet.put(sPrefix + "Date", sDate + " " + sTime);
pDataSet.put(sPrefix + "Date" + "-ts", sdfDate.format(new Date()));
}
} else if ("Time".equals(ssLineVars[0])) {
sTime = ssLineVars[1];
} else {
pDataSet.put(sPrefix + ssLineVars[0], ssLineVars[1]);
pDataSet.put(sPrefix + ssLineVars[0] + "-ts",
sdfDate.format(new Date()));
}
} catch (Exception e) {
if (iDebug == 1) {
System.out.println(e.getMessage());
}
}
}
}
public int Pause = 0;
public int memPause = 0;
public int bStop = 0;
public int Debug = 0;
public long lIniSysTimeMs = 0;
public long lMemSysTimeMs = 0;
public long ldt = 0;
public double ddt = 0.0;
public long lDelay = 0;
private String[] ssCmdLines;
private String sCmdLine;
private String sStartPath;
private Process proc = null;
ProcessBuilder pb = null;
public void ReStartProc() {
try {
if (lPeriod > 0) {
lDelay = lPeriod - (System.currentTimeMillis() % lPeriod);
Thread.sleep(lDelay);
} else {
Thread.sleep(10);
}
if (proc != null) {
if (isRunning(proc)) {
try {
br.close();
} catch (Exception ex2) {
System.out.println(ex2.getMessage());
}
proc.destroy();
Thread.sleep(iPause);
}
}
ssCmdLines = sCmdLine.split(" ");
pb = new ProcessBuilder(ssCmdLines);
if (sStartPath.length() > 1) {
pb.directory(new File(sStartPath));
}
pb.redirectErrorStream(true);
proc = pb.start();
br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public static boolean isRunning(Process process) {
try {
if (process == null) {
return false;
}
process.exitValue();
return false;
} catch (Exception e) {
return true;
}
}
}
| gpl-3.0 |
slub/urnlib | src/main/java/de/slub/urn/NamespaceIdentifier.java | 4394 | /*
* Copyright (C) 2017 Saxon State and University Library Dresden (SLUB)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.slub.urn;
import static de.slub.urn.URN.SCHEME;
import static de.slub.urn.URNSyntaxError.syntaxError;
import static de.slub.urn.URNSyntaxError.lengthError;
import static de.slub.urn.URNSyntaxError.reservedIdentifier;
/**
* Represents a Namespace Identifier (NID) part of a Uniform Resource Identifier (URN).
*
* @author Ralf Claussnitzer
* @see <a href="https://tools.ietf.org/html/rfc1737">Functional Requirements for Uniform Resource Names</a>
* @see <a href="http://www.iana.org/assignments/urn-namespaces/urn-namespaces.xhtml">Official IANA Registry of URN Namespaces</a>
*/
abstract public class NamespaceIdentifier implements RFCSupport {
private final String nid;
/**
* Creates a new {@code NamespaceIdentifier} instance.
*
* @param nid The Namespace Identifier literal
* @throws URNSyntaxError if the given value is <pre>null</pre>, empty or invalid according to the
* {@code isValidNamespaceIdentifier()} method.
* @throws IllegalArgumentException if the parameter is null or empty
*/
public NamespaceIdentifier(String nid) throws URNSyntaxError {
if ((nid == null) || (nid.isEmpty())) {
throw new IllegalArgumentException("Namespace identifier part cannot be null or empty");
}
if (SCHEME.equalsIgnoreCase(nid)) {
throw reservedIdentifier(supportedRFC(), nid);
}
if (nid.length() > 32) {
throw lengthError(supportedRFC(), nid);
}
final String validationError = validateNamespaceIdentifier(nid);
if (validationError != null) {
throw syntaxError(supportedRFC(), validationError);
}
this.nid = nid;
}
/**
* Check if a given literal is a valid namespace identifier and return an error message if not.
*
* @param nid Namespace identifier literal
* @return Error message, if the given string violates the rules for valid namespace identifiers. Null, if not.
*/
abstract protected String validateNamespaceIdentifier(String nid);
/**
* Create a new {@code NamespaceIdentifier} instance that is an exact copy of the given instance.
*
* @param instanceForCopying Base instance for copying
* @throws IllegalArgumentException if parameter is null or empty
*/
public NamespaceIdentifier(NamespaceIdentifier instanceForCopying) {
if (instanceForCopying == null) {
throw new IllegalArgumentException("Namespace identifier cannot be null");
}
nid = instanceForCopying.nid;
}
/**
* Calculates hash code based on the string representation of this namespace identifier.
*
* @return The hash code for this namespace identifier instance.
*/
@Override
public int hashCode() {
return nid.hashCode();
}
/**
* Checks for equality with a given object.
*
* @param obj Object to check equality with
* @return True, if the given object is a {@code NamespaceIdentifier} instance and is lexically equivalent to this instance.
*/
@Override
public boolean equals(Object obj) {
return (obj instanceof NamespaceIdentifier)
&& this.nid.equalsIgnoreCase(((NamespaceIdentifier) obj).nid);
}
/**
* Returns the Namespace Identifier literal
*
* @return Namespace Identifier literal
*/
@Override
public String toString() {
return nid;
}
/**
* @see RFCSupport#supports(RFC)
*/
@Override
public boolean supports(RFC rfc) {
return supportedRFC().equals(rfc);
}
}
| gpl-3.0 |
yongfenghuang/cjegsim | src/input/EventQueueBus.java | 1561 | package input;
/**
**@author yfhuang
**created at 2014-2-26
*/
import java.util.ArrayList;
import java.util.List;
public class EventQueueBus {
private List<EventQueue> queues;
//private long earliest;
private CjEventListener cjeventlistener;
private long eventstime=Long.MAX_VALUE;
public EventQueueBus() {
queues=new ArrayList<EventQueue>();
}
/**
* Returns all the loaded event queues
*
* @return all the loaded event queues
*/
public List<EventQueue> getEventQueues() {
return this.queues;
}
public void addQueue(EventQueue eventqueue){
queues.add(eventqueue);
}
public List<CjEvent> nextEvents(){
//Log.write("excute EventQueueBus nextevent");
long earliest=Long.MAX_VALUE;
EventQueue nextqueue=queues.get(0);
//Log.write("next event queue:"+nextqueue.toString());
/* find the queue that has the next event */
for (EventQueue eq : queues) {
//Log.write("nextqueue:"+eq.toString()+" "+eq.nextEventsTime());
if (eq.nextEventsTime() < earliest){
nextqueue = eq;
earliest = eq.nextEventsTime();
}
}
cjeventlistener=nextqueue.getEventListener();
eventstime=earliest;
List<CjEvent> eventslist=nextqueue.nextEvents();
return eventslist;
}
public long getNextEventsTime(){
long earliest=Long.MAX_VALUE;
for (EventQueue eq : queues) {
if (eq.nextEventsTime() < earliest){
earliest = eq.nextEventsTime();
}
}
return earliest;
}
public long getEventsTime(){
return eventstime;
}
public CjEventListener getEventListener(){
return cjeventlistener;
}
}
| gpl-3.0 |
Tmin10/EVE-Security-Service | server-api/src/main/java/ru/tmin10/EVESecurityService/serverApi/model/GetUniversePlanetsPlanetIdNotFound.java | 2163 | /*
* EVE Swagger Interface
* An OpenAPI for EVE Online
*
* OpenAPI spec version: 0.4.9.dev1
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package ru.tmin10.EVESecurityService.serverApi.model;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Not found
*/
@ApiModel(description = "Not found")
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-06-11T18:18:08.749+04:00")
public class GetUniversePlanetsPlanetIdNotFound {
@SerializedName("error")
private String error = null;
public GetUniversePlanetsPlanetIdNotFound error(String error) {
this.error = error;
return this;
}
/**
* Not found message
* @return error
**/
@ApiModelProperty(example = "null", value = "Not found message")
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GetUniversePlanetsPlanetIdNotFound getUniversePlanetsPlanetIdNotFound = (GetUniversePlanetsPlanetIdNotFound) o;
return Objects.equals(this.error, getUniversePlanetsPlanetIdNotFound.error);
}
@Override
public int hashCode() {
return Objects.hash(error);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class GetUniversePlanetsPlanetIdNotFound {\n");
sb.append(" error: ").append(toIndentedString(error)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| gpl-3.0 |
CCAFS/MARLO | marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/json/project/GeopositionByLocElementAction.java | 3067 | /*****************************************************************
* This file is part of Managing Agricultural Research for Learning &
* Outcomes Platform (MARLO).
* MARLO is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
* MARLO is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with MARLO. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************/
package org.cgiar.ccafs.marlo.action.json.project;
import org.cgiar.ccafs.marlo.action.BaseAction;
import org.cgiar.ccafs.marlo.config.APConstants;
import org.cgiar.ccafs.marlo.data.manager.LocElementManager;
import org.cgiar.ccafs.marlo.data.model.LocElement;
import org.cgiar.ccafs.marlo.utils.APConfig;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.dispatcher.Parameter;
/**
* @author Hermes Jiménez - CIAT/CCAFS
*/
public class GeopositionByLocElementAction extends BaseAction {
private static final long serialVersionUID = -3927332195536071744L;
private LocElementManager locElementManager;
private long locElementID;
private List<Map<String, Object>> geopositions;
@Inject
public GeopositionByLocElementAction(APConfig config, LocElementManager locElementManager) {
super(config);
this.locElementManager = locElementManager;
}
@Override
public String execute() throws Exception {
geopositions = new ArrayList<>();
LocElement element = locElementManager.getLocElementById(locElementID);
Map<String, Object> geoposition = new HashMap<>();
if (element.getLocGeoposition() != null) {
geoposition.put("id", element.getLocGeoposition().getId());
geoposition.put("latitude", element.getLocGeoposition().getLatitude());
geoposition.put("longitude", element.getLocGeoposition().getLongitude());
geopositions.add(geoposition);
}
return SUCCESS;
}
public List<Map<String, Object>> getGeopositions() {
return geopositions;
}
@Override
public void prepare() throws Exception {
// Map<String, Object> parameters = this.getParameters();
// locElementID = Long.parseLong(StringUtils.trim(((String[]) parameters.get(APConstants.LOC_ELEMENT_ID))[0]));
Map<String, Parameter> parameters = this.getParameters();
locElementID = Long.parseLong(StringUtils.trim(parameters.get(APConstants.LOC_ELEMENT_ID).getMultipleValues()[0]));
}
public void setGeopositions(List<Map<String, Object>> geopositions) {
this.geopositions = geopositions;
}
}
| gpl-3.0 |
basicer/parchment | src/main/java/com/basicer/parchment/parameters/ItemParameter.java | 671 | package com.basicer.parchment.parameters;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.basicer.parchment.Context;
public class ItemParameter extends Parameter {
private ItemStack self;
public ItemParameter(ItemStack self) {
this.self = self;
}
@Override
public Class<ItemStack> getUnderlyingType() { return ItemStack.class; }
public ItemStack asItemStack(Context ctx) { return self; }
public String asString(Context ctx) {
ItemMeta m = self.getItemMeta();
if ( m != null && m.getDisplayName() != null ) return m.getDisplayName();
return self.getType().name();
}
}
| gpl-3.0 |
Ficcadenti/java-example | Pattern/pattern/src/pattern/creazione/abstractfactory/ex1/AstrattaA.java | 114 | package pattern.creazione.abstractfactory.ex1;
public abstract class AstrattaA
{
public abstract void info();
}
| gpl-3.0 |
tomas-pluskal/masscascadeknime | src/uk/ac/ebi/masscascade/knime/featurebuilding/tracejoiner/MassTraceCompilerNodeFactory.java | 2404 | /*
* Copyright (C) 2013 EMBL - European Bioinformatics Institute
*
* All rights reserved. This file is part of the MassCascade feature for KNIME.
*
* The feature 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.
*
* The feature 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 the feature. If not, see
* <http://www.gnu.org/licenses/>.
*
* Contributors: Stephan Beisken - initial API and implementation
*/
package uk.ac.ebi.masscascade.knime.featurebuilding.tracejoiner;
import org.knime.core.node.NodeDialogPane;
import org.knime.core.node.NodeFactory;
import org.knime.core.node.NodeView;
import uk.ac.ebi.masscascade.knime.datatypes.featurecell.FeatureValue;
import uk.ac.ebi.masscascade.knime.defaults.DefaultDialog;
import uk.ac.ebi.masscascade.parameters.Parameter;
/**
* <code>NodeFactory</code> for the "MassTraceCompiler" Node. Compiles whole chromatogram mass traces from a given set
* of peaks. Identical masses within a predefined tolerance range are merged into one extracted ion chromatogram.
*
* @author Stephan Beisken
*/
@Deprecated
public class MassTraceCompilerNodeFactory extends NodeFactory<MassTraceCompilerNodeModel> {
/**
* {@inheritDoc}
*/
@Override
public MassTraceCompilerNodeModel createNodeModel() {
return new MassTraceCompilerNodeModel();
}
/**
* {@inheritDoc}
*/
@Override
public int getNrNodeViews() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public NodeView<MassTraceCompilerNodeModel> createNodeView(final int viewIndex,
final MassTraceCompilerNodeModel nodeModel) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasDialog() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public NodeDialogPane createNodeDialogPane() {
DefaultDialog dialog = new DefaultDialog();
dialog.addColumnSelection(Parameter.FEATURE_COLUMN, FeatureValue.class);
dialog.addTextOption(Parameter.MZ_WINDOW_PPM, 5);
return dialog.build();
}
}
| gpl-3.0 |
ENGYS/HELYX-OS | src/eu/engys/core/project/geometry/surface/Cylinder.java | 6610 | /*******************************************************************************
* | o |
* | o o | HELYX-OS: The Open Source GUI for OpenFOAM |
* | o O o | Copyright (C) 2012-2016 ENGYS |
* | o o | http://www.engys.com |
* | o | |
* |---------------------------------------------------------------------------|
* | License |
* | This file is part of HELYX-OS. |
* | |
* | HELYX-OS 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. |
* | |
* | HELYX-OS 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 HELYX-OS; if not, write to the Free Software Foundation, |
* | Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA |
*******************************************************************************/
package eu.engys.core.project.geometry.surface;
import static eu.engys.core.dictionary.Dictionary.TYPE;
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;
import eu.engys.core.dictionary.Dictionary;
import eu.engys.core.project.geometry.Surface;
import eu.engys.core.project.geometry.Type;
import vtk.vtkLineSource;
import vtk.vtkPolyData;
import vtk.vtkTubeFilter;
public class Cylinder extends BaseSurface {
public static final double[] DEFAULT_P1 = {0,0,0};
public static final double[] DEFAULT_P2 = {1,0,0};
public static final double DEFAULT_RADIUS = 1.0;
private double[] point1 = DEFAULT_P1;
private double[] point2 = DEFAULT_P2;
private double radius = DEFAULT_RADIUS;
public static final Dictionary cylinder = new Dictionary("cylinder") {
{
add(TYPE, Surface.SEARCHABLE_CYLINDER_KEY);
add(Surface.POINT1_KEY, "(0 0 0)");
add(Surface.POINT2_KEY, "(1 0 0)");
add(Surface.RADIUS_KEY, "1.0");
}
};
/**
* @deprecated Use GeometryFactory!!
*/
@Deprecated
public Cylinder(String name) {
super(name);
}
@Override
public Type getType() {
return Type.CYLINDER;
}
public double[] getPoint1() {
return point1;
}
public void setPoint1(double[] point1) {
firePropertyChange("point1", this.point1, this.point1 = point1);
}
public void setPoint1(double d1, double d2, double d3) {
setPoint1(new double[]{d1,d2,d3});
}
public double[] getPoint2() {
return point2;
}
public void setPoint2(double[] point2) {
firePropertyChange("point2", this.point2, this.point2 = point2);
}
public void setPoint2(double d1, double d2, double d3) {
setPoint2(new double[]{d1,d2,d3});
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
firePropertyChange("radius", this.radius, this.radius = radius);
}
@Override
public Surface cloneSurface() {
Cylinder cyl = new Cylinder(name);
cyl.point1 = ArrayUtils.clone(point1);
cyl.point2 = ArrayUtils.clone(point2);
cyl.radius = radius;
cloneSurface(cyl);
return cyl;
}
@Override
public void copyFrom(Surface delegate, boolean changeGeometry, boolean changeSurface, boolean changeVolume, boolean changeLayer, boolean changeZone) {
if (delegate instanceof Cylinder) {
Cylinder cyl = (Cylinder) delegate;
if (changeGeometry) {
setPoint1(cyl.getPoint1());
setPoint2(cyl.getPoint2());
setRadius(cyl.getRadius());
}
super.copyFrom(delegate, changeGeometry, changeSurface, changeVolume, changeLayer, changeZone);
}
}
@Override
public vtkPolyData getDataSet() {
double[] point1 = getPoint1();
double[] point2 = getPoint2();
double radius = getRadius();
vtkLineSource lineSource = new vtkLineSource();
lineSource.SetPoint1(point1);
lineSource.SetPoint2(point2);
// Create a tube (cylinder) around the line
vtkTubeFilter tubeFilter = new vtkTubeFilter();
tubeFilter.SetInputConnection(lineSource.GetOutputPort());
tubeFilter.SetCapping(1);
tubeFilter.SetRadius(radius);
tubeFilter.SetNumberOfSides(50);
tubeFilter.Update();
return tubeFilter.GetOutput();
}
@Override
public Dictionary toGeometryDictionary() {
Dictionary d = new Dictionary(name, cylinder);
d.add(POINT1_KEY, point1);
d.add(POINT2_KEY, point2);
d.add(RADIUS_KEY, radius);
return d;
}
@Override
public void fromGeometryDictionary(Dictionary g) {
if (g != null && g.found(TYPE) && g.lookup(TYPE).equals(SEARCHABLE_CYLINDER_KEY) ) {
if (g.found(POINT1_KEY))
setPoint1(g.lookupDoubleArray(POINT1_KEY));
else
setPoint1(DEFAULT_P1);
if (g.found(POINT2_KEY))
setPoint2(g.lookupDoubleArray(POINT2_KEY));
else
setPoint2(DEFAULT_P2);
if (g.found(RADIUS_KEY))
setRadius(g.lookupDouble(RADIUS_KEY));
else
setRadius(DEFAULT_RADIUS);
}
}
@Override
public String toString() {
String string = super.toString();
return string + String.format("[ p1: %s, p2: %s, radius: %s] ", Arrays.toString(point1), Arrays.toString(point2), radius);
}
}
| gpl-3.0 |
mectest1/HelloEE | HelloJS/src/com/mec/servlet/ES6PromiseServlet.java | 3026 | package com.mec.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author MEC
*/
@WebServlet(name = "ES6PromiseServlet", urlPatterns = {"/ES6Promise"})
//@WebInitParam(name = "url", value = "ES6Promise")
public class ES6PromiseServlet extends HttpServlet {
private static final String INIT_PARA_URL = "url";
private static final String REQUEST_TYPE = "type";
private static final String TYPE_VALUE = "url";
private static final String SERVLET_URL = "ES6Promise";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String requestType = request.getParameter(REQUEST_TYPE);
if(TYPE_VALUE.equalsIgnoreCase(requestType)){
//out.print(getInitParameter(INIT_PARA_URL));
out.print(SERVLET_URL);
}else{
out.print(rand.nextInt());
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "ES6 Promise";
}// </editor-fold>
private static final Random rand = new Random(System.currentTimeMillis());
}
| gpl-3.0 |
TheJulianJES/UtilsPlus | src/main/java/de/TheJulianJES/UtilsPlus/Blocks/ItemBlockDeco.java | 615 | package de.TheJulianJES.UtilsPlus.Blocks;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import de.TheJulianJES.UtilsPlus.lib.StringNames;
public class ItemBlockDeco extends ItemBlock {
public ItemBlockDeco(Block block) {
super(block);
this.setHasSubtypes(true);
}
@Override
public int getMetadata(int meta) {
return meta;
}
@Override
public String getUnlocalizedName(ItemStack itemStack) {
int metaData = itemStack.getItemDamage();
return String.format("tile.%s%s", StringNames.MODID.toLowerCase() + ":", "deco." + metaData);
}
} | gpl-3.0 |
greenaddress/GreenBits | app/src/main/java/com/greenaddress/greenbits/spv/PeerFilterProvider.java | 994 | package com.greenaddress.greenbits.spv;
import org.bitcoinj.core.BloomFilter;
class PeerFilterProvider implements org.bitcoinj.core.PeerFilterProvider {
private final SPV mSPV;
public PeerFilterProvider(final SPV spv) { mSPV = spv; }
@Override
public long getEarliestKeyCreationTime() {
final Integer n = mSPV.getService().getLoginData().get("earliest_key_creation_time");
return n.longValue();
}
@Override
public int getBloomFilterElementCount() {
return mSPV.getBloomFilterElementCount();
}
@Override
public BloomFilter getBloomFilter(final int size, final double falsePositiveRate, final long nTweak) {
return mSPV.getBloomFilter(size, falsePositiveRate, nTweak);
}
@Override
public boolean isRequiringUpdateAllBloomFilter() {
return false;
}
public void beginBloomFilterCalculation(){
//TODO: ??
}
public void endBloomFilterCalculation(){
//TODO: ??
}
}
| gpl-3.0 |
statalign/statalign | src/statalign/base/hmm/Hmm.java | 2170 | package statalign.base.hmm;
/**
* The abstract class of Hidden Markov Models.
*
* @author novak
*
*/
public abstract class Hmm {
/**
* HMM model parameters. Implementing classes can use their own assignment and
* any number of parameters.
* In the case of the TKF92 model (HmmTkf92), values are: r, lambda and mu.
*/
public double[] params;
/**
* Abstract function that specifies the emission of each state in the HMM in the form
* of an array A: A[s][i]=1 iff state i emits into sequence s (s=0 is the parent sequence;
* for pair-HMMs s=1 is the child sequence, for 3-seq HMMs s=1 is left and s=2 is right
* child).
* HMM implementations must override this and return their own emission patterns.
* @return array specifying emission patterns as described above
*/
public abstract int[][] getStateEmit();
/**
* Abstract function returning an array A that helps identify the state with some
* emission pattern. The emission pattern is coded as a single integer: e.g. for a 3-seq
* HMM, emission into the parent sequence and right child only is coded as 101 binary,
* i.e. 4+1=5. Then, A[5] gives the index of the state with the above emission pattern.
* HMM implementations must override this and return an array corresponding to their own
* state - emission pattern assignment.
* @return array describing the emission pattern to state conversion
*/
public abstract int[] getEmitPatt2State();
/**
* Returns the index of the start state.
*
* @return The index of the start state;
*/
public abstract int getStart();
/**
* Returns the index of the end state.
*
* @return The index of the end state;
*/
public abstract int getEnd();
/**
* Returns the logarithm of the stationary probability of generating
* a sequence of <code>length</code> characters under the HMM.
* @param length The length of the sequence whose stationary
* probability is to be computed.
* @return The logarithm of the stationary probability under the HMM.
*/
public double getLogStationaryProb(int length) { return 0.0; }
}
| gpl-3.0 |
Captain-Chaos/WorldPainter | WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/selection/SelectionBlock.java | 821 | package org.pepsoft.worldpainter.selection;
import org.pepsoft.worldpainter.layers.Layer;
import org.pepsoft.worldpainter.layers.renderers.LayerRenderer;
import org.pepsoft.worldpainter.layers.renderers.TransparentColourRenderer;
/**
* A block-level layer which indicates that a block belongs to the selection.
*
* <p>Created by Pepijn Schmitz on 03-11-16.
*/
public class SelectionBlock extends Layer {
public SelectionBlock() {
super(SelectionBlock.class.getName(), "SelectionBlock", "Selected area with block resolution", DataSize.BIT, 85);
}
@Override
public LayerRenderer getRenderer() {
return RENDERER;
}
public static final SelectionBlock INSTANCE = new SelectionBlock();
private static final LayerRenderer RENDERER = new TransparentColourRenderer(0xffff00);
} | gpl-3.0 |
a-v-k/astrid | src/main/java/com/todoroo/astrid/data/Metadata.java | 3924 | /**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.data;
import android.content.ContentValues;
import android.net.Uri;
import com.todoroo.andlib.data.AbstractModel;
import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.data.Property.StringProperty;
import com.todoroo.andlib.data.Table;
import org.tasks.BuildConfig;
/**
* Data Model which represents a piece of metadata associated with a task
*
* @author Tim Su <tim@todoroo.com>
*
*/
public class Metadata extends AbstractModel {
// --- table
/** table for this model */
public static final Table TABLE = new Table("metadata", Metadata.class);
/** content uri for this model */
public static final Uri CONTENT_URI = Uri.parse("content://" + BuildConfig.APPLICATION_ID + "/" +
TABLE.name);
// --- properties
/** ID */
public static final LongProperty ID = new LongProperty(
TABLE, ID_PROPERTY_NAME);
/** Associated Task */
public static final LongProperty TASK = new LongProperty(
TABLE, "task");
/** Metadata Key */
public static final StringProperty KEY = new StringProperty(
TABLE, "key");
/** Metadata Text Value Column 1 */
public static final StringProperty VALUE1 = new StringProperty(
TABLE, "value");
/** Metadata Text Value Column 2 */
public static final StringProperty VALUE2 = new StringProperty(
TABLE, "value2");
/** Metadata Text Value Column 3 */
public static final StringProperty VALUE3 = new StringProperty(
TABLE, "value3");
/** Metadata Text Value Column 4 */
public static final StringProperty VALUE4 = new StringProperty(
TABLE, "value4");
/** Metadata Text Value Column 5 */
public static final StringProperty VALUE5 = new StringProperty(
TABLE, "value5");
public static final StringProperty VALUE6 = new StringProperty(
TABLE, "value6");
public static final StringProperty VALUE7 = new StringProperty(
TABLE, "value7");
/** Unixtime Metadata was created */
public static final LongProperty CREATION_DATE = new LongProperty(
TABLE, "created");
/** Unixtime metadata was deleted/tombstoned */
public static final LongProperty DELETION_DATE = new LongProperty(
TABLE, "deleted");
/** List of all properties for this model */
public static final Property<?>[] PROPERTIES = generateProperties(Metadata.class);
// --- defaults
/** Default values container */
private static final ContentValues defaultValues = new ContentValues();
static {
defaultValues.put(DELETION_DATE.name, 0L);
}
public Metadata() {
super();
}
public Metadata(Metadata metadata) {
super(metadata);
}
@Override
public ContentValues getDefaultValues() {
return defaultValues;
}
@Override
public long getId() {
return getIdHelper(ID);
}
// --- parcelable helpers
private static final Creator<Metadata> CREATOR = new ModelCreator<>(Metadata.class);
public Long getDeletionDate() {
return getValue(DELETION_DATE);
}
public void setDeletionDate(Long deletionDate) {
setValue(DELETION_DATE, deletionDate);
}
public Long getTask() {
return getValue(TASK);
}
public void setTask(Long task) {
setValue(TASK, task);
}
public Long getCreationDate() {
return getValue(CREATION_DATE);
}
public void setCreationDate(Long creationDate) {
setValue(CREATION_DATE, creationDate);
}
public String getKey() {
return getValue(KEY);
}
public void setKey(String key) {
setValue(KEY, key);
}
}
| gpl-3.0 |
jipjan/ProjectFestival | src/NewAI/MyNpc.java | 4812 | package NewAI;
import Events.Event;
import GUI.CurrentSetup;
import Mapviewer.TiledMapReader.JsonClasses.TileObject;
import NewAI.AILogic.AILogicRunner;
import NewAI.BaseClasses.MyBody;
import NewAI.NewPathfinding.Grid2d;
import Sprites.Sprites;
import org.dyn4j.geometry.Geometry;
import org.dyn4j.geometry.MassType;
import org.dyn4j.geometry.Vector2;
import java.time.LocalTime;
import java.util.List;
import java.util.Random;
public class MyNpc extends MyBody {
private volatile List<Grid2d.MapNode> _path;
private Grid2d.MapNode _cDestination;
private Grid2d _pathfinder;
private Thread _pathGen = new Thread();
private final boolean _debugOn = false;
private int _peedomiter;//pee meter peeDomiter aka how much does the npc want to pee
private static int _peedomiterMax = CurrentSetup.maxPee;
private Random rand = new Random();
private LocalTime _timeStayingAtEvent;
private TileObject _objectToGoTo;
public boolean reconciderEvents;
public MyNpc(double x, double y, Grid2d pathfinder) {
super(x, y);
Sprite = Sprites.Bezoekers[new Random().nextInt(Sprites.Bezoekers.length)];
_pathfinder = pathfinder;
reconciderEvents = false;
_timeStayingAtEvent = LocalTime.of(0,0,0);
_peedomiter = (int) (Math.random() * _peedomiterMax);
addFixture(Geometry.createCircle(Sprite.getWidth()));
setMass(MassType.FIXED_ANGULAR_VELOCITY);
setAutoSleepingEnabled(false);
translate(x, y);
}
public void setDestination(double x, double y) {
setDestination(new Vector2(x, y));
}
public void setDestination(Vector2 destination)
{
Vector2 vector = new Vector2(getWorldCenter(), destination);
transform.setRotation(vector.getDirection() + Math.PI);
setLinearVelocity(vector.multiply(25));
}
private MyPoint whereDoIWantToGo() {
if (_debugOn) System.out.println("updating whereDoIWantToGo");
AILogicRunner aiLogicRunner = CurrentSetup.aiLogicRunner;
if (_peedomiter > _peedomiterMax)
{
_objectToGoTo = aiLogicRunner.returnRandomToilet();
_peedomiter = 0;
} else {
boolean switchToNewEventChance = CurrentSetup.eventSwitchChance > Math.random();
if (CurrentSetup.aiLogicRunner._time.isAfter(_timeStayingAtEvent)||switchToNewEventChance||reconciderEvents) {
reconciderEvents = false;
Event eventToGoTo = aiLogicRunner.giveActualEventDestination();
if (eventToGoTo!=null){
_timeStayingAtEvent = CurrentSetup.aiLogicRunner.jaredDateToLocalTime( eventToGoTo.getTime().getEndDate());
_objectToGoTo = CurrentSetup.aiLogicRunner.get_podia().get(eventToGoTo.getPodium() - 1);
}
}
}
if (_objectToGoTo == null) return null;
return new MyPoint((_objectToGoTo.getX() + rand.nextInt(_objectToGoTo.getWidth()))/32, (_objectToGoTo.getY() - rand.nextInt(_objectToGoTo.getHeight()))/32);
}
private void generatePath() {
MyPoint togoto = whereDoIWantToGo();
if (togoto == null)
return;
if (inArea(togoto.x, togoto.y)) return;
if (!_pathGen.isAlive()) {
_pathGen = new Thread(() -> {
int xStart = (int) getWorldCenter().x / 32;
int yStart = (int) getWorldCenter().y / 32;
_path = _pathfinder.findPath(xStart, yStart, togoto.x, togoto.y);
if (_path == null && _debugOn)
System.out.println("No path found");
});
_pathGen.start();
}
}
public void AddPee()
{
_peedomiter++;
}
public void update() {
if (_path == null|| _peedomiter > _peedomiterMax)//todo kijken of hier bugs ontstaan
generatePath();
else {
if (_cDestination == null)
_cDestination = _path.get(0);
if (inArea(_cDestination.getX(), _cDestination.getY())) {
setLinearVelocity(0, 0);
_path.remove(0);
if (_path.size() > 0)
_cDestination = _path.get(0);
else
_path = null;
}
}
if (_cDestination != null)
setDestination(_cDestination.getX() * 32, _cDestination.getY() * 32);
}
private boolean inArea(int x, int y) {
Vector2 center = getWorldCenter();
double mX = Math.round(center.x / 32);
double mY = Math.round(center.y / 32);
return mX == x && mY == y;
}
class MyPoint {
int x, y;
MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
}
}
| gpl-3.0 |
jitlogic/zorka | zorka-core/src/main/java/com/jitlogic/zorka/core/spy/ltracer/TraceHandler.java | 6847 | /*
* Copyright 2012-2020 Rafal Lewczuk <rafal.lewczuk@jitlogic.com>
* <p/>
* This 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.
* <p/>
* This software is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jitlogic.zorka.core.spy.ltracer;
import com.jitlogic.zorka.common.tracedata.DTraceContext;
import com.jitlogic.zorka.core.spy.tuner.TraceTuningStats;
import com.jitlogic.zorka.core.spy.tuner.TracerTuner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class TraceHandler {
protected final Logger log = LoggerFactory.getLogger(this.getClass());
/** Default long call threshold for automated tracer tuning: 10ms */
public static final long TUNING_DEFAULT_LCALL_THRESHOLD = 10000000L;
/** Default handler-tuner exchange interval. */
public static final long TUNING_DEFAULT_EXCH_INTERVAL = 30 * 1000000000L;
/** */
public static final long TUNING_EXCHANGE_CALLS_DEFV = 1048576;
protected static boolean tuningEnabled = false;
/** Threshold above which method call will be considered long-duration. */
protected static long tuningLongThreshold = TUNING_DEFAULT_LCALL_THRESHOLD;
/** Interval between handler-tuner exchanges. */
protected static long tuningExchInterval = TUNING_DEFAULT_EXCH_INTERVAL;
/** Minimum number of calls required to initiate tuning stats exchange */
private static long tuningExchangeMinCalls = TUNING_EXCHANGE_CALLS_DEFV;
/** Default: ~0.25ms */
public final static long DEFAULT_MIN_METHOD_TIME = 262144;
/** Minimum default method execution time required to attach method to trace. */
protected static long minMethodTime = DEFAULT_MIN_METHOD_TIME;
protected static int maxAttrLen = 8192;
/** Maximum number of records inside trace */
protected static int maxTraceRecords = 4096;
/** Number of registered trace calls that will force trace submission regardless of execution time. */
protected static int minTraceCalls = 262144;
protected boolean disabled;
protected long tunCalls = 0;
protected TracerTuner tuner;
protected TraceTuningStats tunStats = null;
protected long tunLastExchange = 0;
public static final int LONG_PENALTY = -1024;
public static final int ERROR_PENALTY = -256;
public abstract void traceBegin(int traceId, long clock, int flags);
/**
* Attaches attribute to current trace record (or any other record up the call stack).
*
* @param traceId positive number (trace id) if attribute has to be attached to a top record of specific
* trace, 0 if attribute has to be attached to a top record of any trace, -1 if attribute
* has to be attached to current method;
* @param attrId attribute ID
* @param attrVal attribute value
*/
public abstract void newAttr(int traceId, int attrId, Object attrVal);
public void disable() {
disabled = true;
}
public void enable() {
disabled = false;
}
protected void tuningProbe(int mid, long tstamp, long ttime) {
if (tunStats == null ||
(tstamp > tunLastExchange + tuningExchInterval && tunCalls > tuningExchangeMinCalls)) {
tuningExchange(tstamp);
}
tunCalls++;
if (tuningEnabled) {
if (ttime < minMethodTime) {
if (!tunStats.markRank(mid, 1)) {
tuningExchange(tstamp);
}
} else if (ttime > tuningLongThreshold) {
tunStats.markRank(mid, -1 * (int)(ttime >>> 18));
}
}
}
private void tuningExchange(long tstamp) {
if (tunStats != null) {
tunStats.setThreadId(Thread.currentThread().getId());
tunStats.setCalls(tunCalls);
tunStats.setTstamp(tstamp);
tunCalls = 0;
}
tunStats = tuner.exchange(tunStats);
tunLastExchange = tstamp;
}
/**
* Sets minimum trace execution time for currently recorded trace.
* If there is no trace being recorded just yet, this method will
* have no effect.
*
* @param minimumTraceTime (in nanoseconds)
*/
public abstract void setMinimumTraceTime(long minimumTraceTime);
public abstract void markTraceFlags(int traceId, int flag);
public abstract void markRecordFlags(int flag);
public abstract boolean isInTrace(int traceId);
public abstract void traceReturn(long tstamp);
public abstract void traceEnter(int mid, long tstamp);
public abstract void traceError(Object e, long tstamp);
public abstract DTraceContext getDTraceState();
public abstract DTraceContext parentDTraceState();
public abstract void setDTraceState(DTraceContext state);
public static long getTuningExchangeMinCalls() {
return tuningExchangeMinCalls;
}
public static void setTuningExchangeMinCalls(long tuningExchangeMinCalls) {
TraceHandler.tuningExchangeMinCalls = tuningExchangeMinCalls;
}
public static boolean isTuningEnabled() {
return tuningEnabled;
}
public static void setTuningEnabled(boolean tuningEnabled) {
TraceHandler.tuningEnabled = tuningEnabled;
}
public static long getTuningLongThreshold() {
return tuningLongThreshold;
}
public static void setTuningLongThreshold(long tuningLongThreshold) {
TraceHandler.tuningLongThreshold = tuningLongThreshold;
}
public static long getTuningDefaultExchInterval() {
return tuningExchInterval;
}
public static void setTuningDefaultExchInterval(long tuningDefaultExchInterval) {
TraceHandler.tuningExchInterval = tuningDefaultExchInterval;
}
public static long getMinMethodTime() {
return minMethodTime;
}
public static void setMinMethodTime(long methodTime) {
minMethodTime = methodTime;
}
public static int getMaxTraceRecords() {
return maxTraceRecords;
}
public static void setMaxTraceRecords(int traceSize) {
maxTraceRecords = traceSize;
}
public static int getMinTraceCalls() {
return minTraceCalls;
}
public static void setMinTraceCalls(int traceCalls) {
minTraceCalls = traceCalls;
}
}
| gpl-3.0 |
idega/is.idega.idegaweb.egov.bpm | src/java/com/idega/idegaweb/egov/bpm/data/AppProcBindDefinition.java | 617 | package com.idega.idegaweb.egov.bpm.data;
import org.jbpm.module.def.ModuleDefinition;
import org.jbpm.module.exe.ModuleInstance;
/**
* @deprecated this is held here only to support older processes, that contains this definition
* @author <a href="mailto:civilis@idega.com">Vytautas Čivilis</a>
* @version $Revision: 1.4 $ Last modified: $Date: 2009/04/29 13:38:11 $ by $Author: civilis $
*/
@Deprecated
public class AppProcBindDefinition extends ModuleDefinition {
private static final long serialVersionUID = 6504030191381296426L;
@Override
public ModuleInstance createInstance() {
return null;
}
} | gpl-3.0 |
dforce2055/ReservaHotel | src/sistemaReserva/Persona.java | 2110 | package sistemaReserva;
public class Persona
{
protected String nombre;
protected String apellido;
protected String tipoDocumento;
protected String numeroDocumento;
protected String direccion;
protected String telefono;
protected String email;
protected String estado;//ACTIVA | INACTIVA
public Persona(String nom, String ape, String tDoc, String nDoc, String dir,
String tel, String eMail)
{
nombre = nom;
apellido = ape;
tipoDocumento = tDoc;
numeroDocumento = nDoc;
direccion = dir;
telefono = tel;
email = eMail;
estado = "ACTIVO";
}
public String getNombre()
{
return nombre;
}
public void setNombre(String nombre)
{
this.nombre = nombre;
}
public String getApellido()
{
return apellido;
}
public void setApellido(String apellido)
{
this.apellido = apellido;
}
public String getTipoDocumento()
{
return tipoDocumento;
}
public void setTipoDocumento(String tipoDocumento)
{
this.tipoDocumento = tipoDocumento;
}
public String getNumeroDocumento()
{
return numeroDocumento;
}
public void setNumeroDocumento(String numeroDocumento)
{
this.numeroDocumento = numeroDocumento;
}
public String getDireccion()
{
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono)
{
this.telefono = telefono;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getEstado()
{
return estado;
}
public void setEstado(String estado)
{
this.estado = estado;
}
//negocio
public boolean esTuDocumento(String tipoDoc, String numDoc)
{
return (tipoDocumento.equals(tipoDoc) && numeroDocumento.equals(numDoc));
}
public void darBaja()
{
estado = "INACTIVO";
}
}
| gpl-3.0 |
YannRobert/GazePlay | gazeplay-games/src/main/java/net/gazeplay/games/memory/Memory.java | 7082 | package net.gazeplay.games.memory;
import javafx.geometry.Dimension2D;
import javafx.scene.image.Image;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.gazeplay.GameLifeCycle;
import net.gazeplay.IGameContext;
import net.gazeplay.commons.configuration.Configuration;
import net.gazeplay.commons.utils.games.ImageLibrary;
import net.gazeplay.commons.utils.games.ImageUtils;
import net.gazeplay.commons.utils.games.Utils;
import net.gazeplay.commons.utils.stats.Stats;
import java.util.*;
@Slf4j
public class Memory implements GameLifeCycle {
private static final float cardRatio = 0.75f;
private static final int minHeight = 30;
public enum MemoryGameType {
LETTERS, NUMBERS, DEFAULT
}
@Data
@AllArgsConstructor
public static class RoundDetails {
public final List<MemoryCard> cardList;
}
private int nbRemainingPeers;
private final IGameContext gameContext;
private final int nbLines;
private final int nbColumns;
private final Stats stats;
private ImageLibrary imageLibrary;
/*
* HashMap of images selected for this game and their associated id The id is the same for the 2 same images
*/
public HashMap<Integer, Image> images;
public RoundDetails currentRoundDetails;
public int nbTurnedCards;
private final boolean isOpen;
public Memory(final MemoryGameType gameType, final IGameContext gameContext, final int nbLines, final int nbColumns, final Stats stats,
final boolean isOpen) {
super();
this.isOpen = isOpen;
final int cardsCount = nbLines * nbColumns;
if ((cardsCount & 1) != 0) {
// nbLines * nbColumns must be a multiple of 2
throw new IllegalArgumentException("Cards count must be an even number in this game");
}
this.nbRemainingPeers = (nbLines * nbColumns) / 2;
this.gameContext = gameContext;
this.nbLines = nbLines;
this.nbColumns = nbColumns;
this.stats = stats;
if (gameType == MemoryGameType.LETTERS) {
this.imageLibrary = ImageUtils.createCustomizedImageLibrary(null, "common/letters");
} else if (gameType == MemoryGameType.NUMBERS) {
this.imageLibrary = ImageUtils.createCustomizedImageLibrary(null, "common/numbers");
} else {
this.imageLibrary = ImageUtils.createImageLibrary(Utils.getImagesSubDirectory("magiccards"),
Utils.getImagesSubDirectory("default"));
}
}
HashMap<Integer, Image> pickRandomImages() {
final int cardsCount = nbColumns * nbLines;
final HashMap<Integer, Image> res = new HashMap<>();
final Set<Image> images = imageLibrary.pickMultipleRandomDistinctImages(cardsCount / 2);
int i = 0;
for (final Image image : images) {
res.put(i, image);
i++;
}
return res;
}
@Override
public void launch() {
final Configuration config = gameContext.getConfiguration();
final int cardsCount = nbColumns * nbLines;
images = pickRandomImages();
final List<MemoryCard> cardList = createCards(images, config);
nbRemainingPeers = cardsCount / 2;
currentRoundDetails = new RoundDetails(cardList);
gameContext.getChildren().addAll(cardList);
stats.notifyNewRoundReady();
}
@Override
public void dispose() {
if (currentRoundDetails != null) {
if (currentRoundDetails.cardList != null) {
gameContext.getChildren().removeAll(currentRoundDetails.cardList);
}
currentRoundDetails = null;
}
}
public void removeSelectedCards() {
if (this.currentRoundDetails == null) {
return;
}
final List<MemoryCard> cardsToHide = new ArrayList<>();
for (final MemoryCard pictureCard : this.currentRoundDetails.cardList) {
if (pictureCard.isTurned()) {
cardsToHide.add(pictureCard);
}
}
nbRemainingPeers = nbRemainingPeers - 1;
// remove all turned cards
gameContext.getChildren().removeAll(cardsToHide);
}
private List<MemoryCard> createCards(final HashMap<Integer, Image> im, final Configuration config) {
final javafx.geometry.Dimension2D gameDimension2D = gameContext.getGamePanelDimensionProvider().getDimension2D();
log.debug("Width {} ; height {}", gameDimension2D.getWidth(), gameDimension2D.getHeight());
final double cardHeight = computeCardHeight(gameDimension2D, nbLines);
final double cardWidth = cardHeight * cardRatio;
log.debug("cardWidth {} ; cardHeight {}", cardWidth, cardHeight);
final double width = computeCardWidth(gameDimension2D, nbColumns) - cardWidth;
log.debug("width {} ", width);
final List<MemoryCard> result = new ArrayList<>();
// HashMap <index, number of times the index was used >
final HashMap<Integer, Integer> indUsed = new HashMap<>();
indUsed.clear();
final int fixationlength = config.getFixationLength();
for (int currentLineIndex = 0; currentLineIndex < nbLines; currentLineIndex++) {
for (int currentColumnIndex = 0; currentColumnIndex < nbColumns; currentColumnIndex++) {
final double positionX = width / 2d + (width + cardWidth) * currentColumnIndex;
final double positionY = minHeight / 2d + (minHeight + cardHeight) * currentLineIndex;
log.debug("positionX : {} ; positionY : {}", positionX, positionY);
final int id = getRandomValue(indUsed);
if (indUsed.containsKey(id)) {
indUsed.replace(id, 1, 2);
} else {
indUsed.put(id, 1);
}
final Image image = images.get(id);
final MemoryCard card = new MemoryCard(positionX, positionY, cardWidth, cardHeight, image, id, gameContext,
stats, this, fixationlength, isOpen);
result.add(card);
}
}
return result;
}
private static double computeCardHeight(final Dimension2D gameDimension2D, final int nbLines) {
return gameDimension2D.getHeight() * 0.9 / nbLines;
}
private static double computeCardWidth(final Dimension2D gameDimension2D, final int nbColumns) {
return gameDimension2D.getWidth() / nbColumns;
}
private int getRandomValue(final HashMap<Integer, Integer> indUsed) {
int value;
final Random rdm = new Random();
do {
value = rdm.nextInt(images.size());
} while ((!images.containsKey(value)) || (indUsed.containsKey(value) && (indUsed.get(value) == 2)));
// While selected image is already used 2 times (if it appears )
return value;
}
public int getnbRemainingPeers() {
return nbRemainingPeers;
}
}
| gpl-3.0 |
MHTaleb/Encologim | lib/JasperReport/src/net/sf/jasperreports/engine/ElementsVisitor.java | 1422 | /*
* 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.engine;
/**
* Report elements visitor extended interface that is able to visit deep/nested elements.
*
* @author Lucian Chirita (lucianc@users.sourceforge.net)
*/
public interface ElementsVisitor extends JRVisitor
{
/**
* Decides whether this visitor is to visit deep/nested elements.
*
* @return whether this visitor is to visit deep/nested elements
*/
boolean visitDeepElements();
}
| gpl-3.0 |
BennoGAP/notification-forwarder | SMS/src/main/java/org/groebl/sms/ui/popup/QKComposeActivity.java | 3554 | package org.groebl.sms.ui.popup;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.view.View;
import android.widget.AdapterView;
import com.android.ex.chips.recipientchip.DrawableRecipientChip;
import org.groebl.sms.R;
import org.groebl.sms.common.utils.KeyboardUtils;
import org.groebl.sms.interfaces.ActivityLauncher;
import org.groebl.sms.interfaces.RecipientProvider;
import org.groebl.sms.ui.base.QKPopupActivity;
import org.groebl.sms.ui.view.AutoCompleteContactView;
import org.groebl.sms.ui.view.ComposeView;
import org.groebl.sms.ui.view.StarredContactsView;
public class QKComposeActivity extends QKPopupActivity implements ComposeView.OnSendListener, RecipientProvider,
ActivityLauncher, AdapterView.OnItemClickListener {
private final String TAG = "QKComposeActivity";
private Context mContext = this;
private AutoCompleteContactView mRecipients;
private StarredContactsView mStarredContactsView;
private ComposeView mCompose;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.title_compose);
mRecipients = (AutoCompleteContactView) findViewById(R.id.compose_recipients);
mRecipients.setOnItemClickListener(this);
// Get the compose view, and set it up with all the listeners.
findViewById(R.id.compose_view_stub).setVisibility(View.VISIBLE);
mCompose = (ComposeView) findViewById(R.id.compose_view);
mCompose.setActivityLauncher(this);
mCompose.setOnSendListener(this);
mCompose.setRecipientProvider(this);
mStarredContactsView = (StarredContactsView) findViewById(R.id.starred_contacts);
mStarredContactsView.setComposeScreenViews(mRecipients, mCompose);
// Apply different attachments based on the type.
mCompose.loadMessageFromIntent(getIntent());
}
@Override
protected int getLayoutResource() {
return R.layout.activity_qkcompose;
}
@Override
protected void onPause() {
super.onPause();
KeyboardUtils.hide(mContext, mCompose);
}
@Override
public void finish() {
// Override pending transitions so that we don't see black for a second when QuickReply closes
super.finish();
overridePendingTransition(0, 0);
}
@Override
public String[] getRecipientAddresses() {
DrawableRecipientChip[] chips = mRecipients.getRecipients();
String[] addresses = new String[chips.length];
for (int i = 0; i < chips.length; i++) {
addresses[i] = PhoneNumberUtils.stripSeparators(chips[i].getEntry().getDestination());
}
return addresses;
}
@Override
public void onSend(String[] recipients, String body) {
// When the SMS is sent, close this activity.
finish();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (!mCompose.onActivityResult(requestCode, resultCode, data)) {
// Handle other results here, since the ComposeView didn't handle them.
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mRecipients.onItemClick(parent, view, position, id);
mStarredContactsView.collapse();
mCompose.requestReplyTextFocus();
}
}
| gpl-3.0 |
ignesco/teb | src/main/java/uk/co/ignesco/teb/api/TebProject.java | 1055 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package uk.co.ignesco.teb.api;
/**
*
* @author craig
*/
public class TebProject {
public String repoLocation;
public String branch;
public String workingDirectory;
public String authGroup;
public ProjectStatus status;
public String id;
public TebProject() {
}
public TebProject(String id, String repoLocation, String branch, String workingDirectory, String authGroup, ProjectStatus status) {
this.id = id;
this.repoLocation = repoLocation;
this.branch = branch;
this.workingDirectory = workingDirectory;
this.authGroup = authGroup;
this.status = status;
}
public String getStatusString() {
switch(status) {
case active: {
return "active";
}
case inactive: {
return "inactive";
}
default: {
return "";
}
}
}
} | gpl-3.0 |
mikusher/JavaBasico | src/cv/designpatterns/factory/AbstractFactory.java | 544 | /*
* Copyright (C) 2019 Miky Mikusher
* 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.
*/
package cv.designpatterns.factory;
/**
* @author Miky Mikusher
*
*/
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Shape getShape(String shape);
}
| gpl-3.0 |
filipemb/siesp | app/br/com/core/conversor/FichaDeInscricaoConversor.java | 9669 | /*******************************************************************************
* 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.conversor;
import java.util.ArrayList;
import java.util.List;
import br.com.core.conversor.utils.ConversorUtils;
import br.com.core.jdbc.dao.evento.FichaDeInscricaoTable;
import br.com.core.modelo.curso.Turma;
import br.com.core.modelo.evento.Evento;
import br.com.core.modelo.evento.FichaDeInscricao;
import br.com.core.modelo.evento.enumerator.StatusFichaInscricao;
import br.com.core.modelo.pessoa.Pessoa;
import br.com.core.modelo.publico.Aeroporto;
import br.com.core.modelo.publico.Arquivo;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
public class FichaDeInscricaoConversor {
public static FichaDeInscricaoTable converterModeloParaTabela(FichaDeInscricao modelo){
FichaDeInscricaoTable fichaDeInscricaoTable = new FichaDeInscricaoTable();
fichaDeInscricaoTable.setId(modelo.getId());
Evento evento = modelo.getEvento();
if(evento!=null && evento.getId()!=null){
fichaDeInscricaoTable.setEvento(evento.getId());
}
Turma turma = modelo.getTurma();
if(turma!=null && turma.getId()!=null){
fichaDeInscricaoTable.setTurma(turma.getId());
}
Pessoa pessoa = modelo.getPessoa();
if(pessoa!=null && pessoa.getId()!=null){
fichaDeInscricaoTable.setPessoa(pessoa.getId());
}
Aeroporto aeroportoEmbarque = modelo.getAeroportoEmbarque();
if(aeroportoEmbarque!=null && aeroportoEmbarque.getId()!=null){
fichaDeInscricaoTable.setAeroportoEmbarque(aeroportoEmbarque.getId());
}
Aeroporto aeroportoEvento = modelo.getAeroportoEvento();
if(aeroportoEvento!=null && aeroportoEvento.getId()!=null){
fichaDeInscricaoTable.setAeroportoEvento(aeroportoEvento.getId());
}
Aeroporto aeroportoRetorno = modelo.getAeroportoRetorno();
if(aeroportoRetorno!=null && aeroportoRetorno.getId()!=null){
fichaDeInscricaoTable.setAeroportoRetorno(aeroportoRetorno.getId());
}
Arquivo oficioResposta = modelo.getOficioResposta();
if(oficioResposta!=null && oficioResposta.getId()!=null){
fichaDeInscricaoTable.setOficioResposta(oficioResposta.getId());
}
fichaDeInscricaoTable.setObservacao(modelo.getObservacao());
fichaDeInscricaoTable.setTematica(modelo.getTematica());
fichaDeInscricaoTable.setLocal(modelo.getLocal());
fichaDeInscricaoTable.setPeriodo(modelo.getPeriodo());
fichaDeInscricaoTable.setNome(modelo.getNome());
fichaDeInscricaoTable.setIdentidade(modelo.getIdentidade());
fichaDeInscricaoTable.setCpf(modelo.getCpf());
fichaDeInscricaoTable.setMatricula(modelo.getMatricula());
fichaDeInscricaoTable.setSiape(modelo.getSiape());
fichaDeInscricaoTable.setMae(modelo.getMae());
fichaDeInscricaoTable.setDataNascimento(modelo.getDataNascimento());
fichaDeInscricaoTable.setNaturalidade(modelo.getNaturalidade());
fichaDeInscricaoTable.setOrgaoDeLotacao(modelo.getOrgaoDeLotacao());
fichaDeInscricaoTable.setPosto(modelo.getPosto());
fichaDeInscricaoTable.setEmail(modelo.getEmail());
fichaDeInscricaoTable.setEndereco(modelo.getEndereco());
fichaDeInscricaoTable.setBairro(modelo.getBairro());
fichaDeInscricaoTable.setCidadeUf(modelo.getCidadeUf());
fichaDeInscricaoTable.setCep(modelo.getCep());
fichaDeInscricaoTable.setTelefoneContato(modelo.getTelefoneContato());
fichaDeInscricaoTable.setTelefoneFax(modelo.getTelefoneFax());
fichaDeInscricaoTable.setTelefoneCelular(modelo.getTelefoneCelular());
fichaDeInscricaoTable.setValorAlimentacao(modelo.getValorAlimentacao());
fichaDeInscricaoTable.setValorTransporte(modelo.getValorTransporte());
fichaDeInscricaoTable.setBancoNumeroNome(modelo.getBancoNumeroNome());
fichaDeInscricaoTable.setAgencia(modelo.getAgencia());
fichaDeInscricaoTable.setContaCorrente(modelo.getContaCorrente());
fichaDeInscricaoTable.setAeroportoDeEmbarque(modelo.getAeroportoDeEmbarque());
fichaDeInscricaoTable.setAeroportoDeRetorno(modelo.getAeroportoDeRetorno());
fichaDeInscricaoTable.setAeroportoDoEvento(modelo.getAeroportoDoEvento());
fichaDeInscricaoTable.setOutroAeroportoEmbarque(modelo.getOutroAeroportoEmbarque());
fichaDeInscricaoTable.setOutroAeroportoRetorno(modelo.getOutroAeroportoRetorno());
fichaDeInscricaoTable.setNisPisPasep(modelo.getNisPisPasep());
StatusFichaInscricao status = modelo.getStatus();
if(status!=null ){
fichaDeInscricaoTable.setStatus(status.name());
}
fichaDeInscricaoTable.setVersion(modelo.getVersion());
return fichaDeInscricaoTable;
}
public static FichaDeInscricao converterTabelaParaModelo(FichaDeInscricaoTable tabela){
FichaDeInscricao fichaDeInscricao = new FichaDeInscricao();
Evento evento = new Evento();
evento.setId(tabela.getEvento());
fichaDeInscricao.setEvento(evento);
Turma turma = new Turma();
turma.setId(tabela.getTurma());
fichaDeInscricao.setTurma(turma);
Pessoa pessoa = new Pessoa();
pessoa.setId(tabela.getPessoa());
fichaDeInscricao.setPessoa(pessoa);
Aeroporto aeroportoEmbarque = new Aeroporto();
aeroportoEmbarque.setId(tabela.getAeroportoEmbarque());
fichaDeInscricao.setAeroportoEmbarque(aeroportoEmbarque);
Aeroporto aeroportoEvento = new Aeroporto();
aeroportoEvento.setId(tabela.getAeroportoEvento());
fichaDeInscricao.setAeroportoEvento(aeroportoEvento);
Aeroporto aeroportoRetorno = new Aeroporto();
aeroportoRetorno.setId(tabela.getAeroportoRetorno());
fichaDeInscricao.setAeroportoRetorno(aeroportoRetorno);
Arquivo oficioResposta = new Arquivo();
oficioResposta.setId(tabela.getOficioResposta());
fichaDeInscricao.setOficioResposta(oficioResposta);
fichaDeInscricao.setId(tabela.getId());
fichaDeInscricao.setVersion(tabela.getVersion());
fichaDeInscricao.setTematica(tabela.getTematica());
fichaDeInscricao.setLocal(tabela.getLocal());
fichaDeInscricao.setPeriodo(tabela.getPeriodo());
fichaDeInscricao.setNome(tabela.getNome());
fichaDeInscricao.setIdentidade(tabela.getIdentidade());
fichaDeInscricao.setCpf(tabela.getCpf());
fichaDeInscricao.setMatricula(tabela.getMatricula());
fichaDeInscricao.setSiape(tabela.getSiape());
fichaDeInscricao.setMae(tabela.getMae());
fichaDeInscricao.setDataNascimento(tabela.getDataNascimento());
fichaDeInscricao.setNaturalidade(tabela.getNaturalidade());
fichaDeInscricao.setOrgaoDeLotacao(tabela.getOrgaoDeLotacao());
fichaDeInscricao.setPosto(tabela.getPosto());
fichaDeInscricao.setEmail(tabela.getEmail());
fichaDeInscricao.setEndereco(tabela.getEndereco());
fichaDeInscricao.setBairro(tabela.getBairro());
fichaDeInscricao.setCidadeUf(tabela.getCidadeUf());
fichaDeInscricao.setCep(tabela.getCep());
fichaDeInscricao.setTelefoneContato(tabela.getTelefoneContato());
fichaDeInscricao.setTelefoneFax(tabela.getTelefoneFax());
fichaDeInscricao.setTelefoneCelular(tabela.getTelefoneCelular());
fichaDeInscricao.setValorAlimentacao(tabela.getValorAlimentacao());
fichaDeInscricao.setValorTransporte(tabela.getValorTransporte());
fichaDeInscricao.setBancoNumeroNome(tabela.getBancoNumeroNome());
fichaDeInscricao.setAgencia(tabela.getAgencia());
fichaDeInscricao.setContaCorrente(tabela.getContaCorrente());
fichaDeInscricao.setAeroportoDeEmbarque(tabela.getAeroportoDeEmbarque());
fichaDeInscricao.setAeroportoDeRetorno(tabela.getAeroportoDeRetorno());
fichaDeInscricao.setAeroportoDoEvento(tabela.getAeroportoDoEvento());
fichaDeInscricao.setOutroAeroportoEmbarque(tabela.getOutroAeroportoEmbarque());
fichaDeInscricao.setOutroAeroportoRetorno(tabela.getOutroAeroportoRetorno());
fichaDeInscricao.setNisPisPasep(tabela.getNisPisPasep());
fichaDeInscricao.setObservacao(tabela.getObservacao());
if(tabela.getStatus() !=null && !tabela.getStatus().isEmpty() ){
StatusFichaInscricao status = StatusFichaInscricao.valueOf(tabela.getStatus());
fichaDeInscricao.setStatus(status);
}
return fichaDeInscricao;
}
public static String converterModeloParaJson(FichaDeInscricao fichaDeInscricao){
JSONSerializer serializer = ConversorUtils.getJsonSerializer();
String json = serializer.serialize(fichaDeInscricao);
return json;
}
@SuppressWarnings("rawtypes")
public static FichaDeInscricao converterJsonParaModelo(String json){
JSONDeserializer deserializer = ConversorUtils.getJsonDeserializer();
Object objeto = deserializer.use(null, FichaDeInscricao.class).deserialize(json);
FichaDeInscricao fichaDeInscricao = (FichaDeInscricao) objeto;
return fichaDeInscricao;
}
public static List<FichaDeInscricao> converterJsonParaList(String json){
List<FichaDeInscricao> lista = new JSONDeserializer<List<FichaDeInscricao>>().use(null, ArrayList.class).use("values", FichaDeInscricao.class).deserialize(json);
return lista;
}
}
| gpl-3.0 |
MNLBC/Group2Projects | 7. Group Project/W6D5_Project/W6D5_Project/Spring Hibernate/src/com/oocl/mnlbc/svc/impl/UserSVCImpl.java | 1512 | package com.oocl.mnlbc.svc.impl;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.oocl.mnlbc.dao.inf.UserDAO;
import com.oocl.mnlbc.model.User;
import com.oocl.mnlbc.svc.inf.UserSVC;
/**
*
* @author Lance Jasper Lopez
* @desc DAO Implementation for USER TABLE
* @date 07-15-2016
*/
public class UserSVCImpl implements UserSVC {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
@Override
@Transactional
public boolean validateUser(String email, String password) {
return this.userDAO.validateUser(email, password);
}
@Override
@Transactional
public User getUser(String email, String password) {
return this.userDAO.getUser(email, password);
}
@Override
@Transactional
public List<User> getUserByEmail(String email) {
return this.userDAO.getUserByEmail(email);
}
@Override
@Transactional
public int createUser(User user) {
return this.userDAO.createUser(user);
}
@Override
@Transactional
public List<User> getBlackList() {
return this.userDAO.getUserBlackList();
}
@Override
@Transactional
public int deleteUser(long id) {
return this.userDAO.deleteUser(id);
}
@Override
public int updateUser(User user) {
return this.userDAO.updateUser(user);
}
@Override
public List<User> getAllUsers() {
return this.userDAO.getAllUser();
}
@Override
@Transactional
public int updateToPremium(String email) {
return this.userDAO.updateToPremium(email);
}
} | gpl-3.0 |
MooseTheBrown/scriba-android | src/org/scribacrm/scriba/EditEntryFragment.java | 21596 | /*
* Copyright (C) 2015 Mikhail Sapozhnikov
*
* This file is part of scriba-android.
*
* scriba-android 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.
*
* scriba-android 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 scriba-android. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.scribacrm.scriba;
import org.scribacrm.libscriba.*;
import android.app.Activity;
import android.util.Log;
import android.app.Fragment;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ArrayAdapter;
import android.content.Loader;
import android.app.LoaderManager;
import android.widget.AdapterView;
import android.widget.Spinner;
import java.util.Date;
import java.text.DateFormat;
import java.util.UUID;
import java.util.Set;
import java.util.HashSet;
import android.widget.LinearLayout;
public class EditEntryFragment extends Fragment
implements CompanySpinnerHandler.OnSelectedListener,
DateTimeHandler.OnDateChangedListener,
ReminderDialog.ReminderSetListener {
private class ReminderListClickListener implements View.OnClickListener {
private EventAlarm _alarm = null;
public ReminderListClickListener(EventAlarm alarm) {
_alarm = alarm;
}
@Override
public void onClick(View v) {
// remove alarm from adapter and its view from reminder list
_eventAlarmAdapter.remove(_alarm);
LinearLayout reminderList = (LinearLayout)getActivity().
findViewById(R.id.event_reminder_list);
reminderList.removeView(v);
}
}
// entry data for each entry type
private Company _company = null;
private Event _event = null;
private Project _project = null;
private POC _poc = null;
// company spinner handler instance
private CompanySpinnerHandler _companySpinnerHandler = null;
// project state spinner handler instance
private ProjectStateSpinnerHandler _projectStateSpinnerHandler = null;
// POC spinner handler instance
private POCSpinnerHandler _pocSpinnerHandler = null;
// project spinner handler instance
private ProjectSpinnerHandler _projectSpinnerHandler = null;
// currency spinner handler instance
private CurrencySpinnerHandler _currencySpinnerHandler = null;
// event type spinner handler instance
private EventTypeSpinnerHandler _eventTypeSpinnerHandler = null;
// event state spinner handler instance
private EventStateSpinnerHandler _eventStateSpinnerHandler = null;
// event date
private Date _eventDate = null;
// date/time handler instance
private DateTimeHandler _dateTimeHandler = null;
// event reminder adapter
private ArrayAdapter<EventAlarm> _eventAlarmAdapter = null;
public EditEntryFragment(Company company) {
_company = company;
}
public EditEntryFragment(Event event) {
_event = event;
}
public EditEntryFragment(Project project) {
_project = project;
}
public EditEntryFragment(POC poc) {
_poc = poc;
}
// save changes made by user
public void save() {
if (_company != null) {
saveCompanyData();
}
else if (_event != null) {
saveEventData();
}
else if (_project != null) {
saveProjectData();
}
else if (_poc != null) {
savePOCData();
}
else {
Log.e("[Scriba]", "EditEntryFragment.save() called, but there's no entry data");
}
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = null;
if (_company != null) {
view = inflater.inflate(R.layout.add_company, container, false);
}
else if (_event != null) {
view = inflater.inflate(R.layout.add_event, container, false);
}
else if (_project != null) {
view = inflater.inflate(R.layout.add_project, container, false);
}
else if (_poc != null) {
view = inflater.inflate(R.layout.add_poc, container, false);
}
else {
Log.e("[Scriba]", "Cannot create EditEntryFragment view, no data passed to fragment");
}
return view;
}
@Override
public void onStart() {
if (_company != null) {
populateCompanyView();
}
else if (_event != null) {
populateEventView();
}
else if (_project != null) {
populateProjectView();
}
else if (_poc != null) {
populatePOCView();
}
getActivity().invalidateOptionsMenu();
super.onStart();
}
// CompanySpinnerHandler.OnSelectedListener implementation
@Override
public void onCompanySelected(UUID companyId) {
// only for event editor
if (_event != null) {
// populate poc spinner with people for currently selected company
Spinner pocSpinner = (Spinner)getActivity().findViewById(R.id.event_poc_spinner);
_pocSpinnerHandler.load(pocSpinner, companyId, _event.poc_id);
// populate project spinner with projects for currently selected company
Spinner projectSpinner = (Spinner)getActivity().findViewById(R.id.event_project_spinner);
_projectSpinnerHandler.load(projectSpinner, companyId, _event.project_id);
}
}
// DateTimeHandler.OnDateChangedListener implementation
@Override
public void onDateChanged(Date newDate) {
_eventDate = newDate;
TextView dateText = (TextView)getActivity().findViewById(R.id.event_date_text);
TextView timeText = (TextView)getActivity().findViewById(R.id.event_time_text);
DateFormat dateFormat = DateFormat.getDateInstance();
DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
dateText.setText(dateFormat.format(_eventDate));
timeText.setText(timeFormat.format(_eventDate));
}
// ReminderDialog.ReminderSetListener implementation
@Override
public void onReminderSet(byte type, long value) {
if (_eventAlarmAdapter == null) {
// this is the first one, create adapter
_eventAlarmAdapter = new ArrayAdapter<EventAlarm>(getActivity(),
R.layout.reminder_item, R.id.event_reminder_text);
}
EventAlarm alarm = new EventAlarm(getActivity(), value, type, _eventDate.getTime());
_eventAlarmAdapter.add(alarm);
// get view and add it to the reminder list
int pos = _eventAlarmAdapter.getPosition(alarm);
LinearLayout reminderList = (LinearLayout)getActivity().
findViewById(R.id.event_reminder_list);
View alarmView = _eventAlarmAdapter.getView(pos, null, (ViewGroup)reminderList);
ViewGroup.LayoutParams params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
reminderList.addView(alarmView, params);
alarmView.setOnClickListener(new ReminderListClickListener(alarm));
}
// populate view with company data
private void populateCompanyView() {
EditText txt = (EditText)getActivity().findViewById(R.id.company_name_text);
txt.setText(_company.name);
txt = (EditText)getActivity().findViewById(R.id.company_jur_name_text);
txt.setText(_company.jur_name);
txt = (EditText)getActivity().findViewById(R.id.company_address_text);
txt.setText(_company.address);
txt = (EditText)getActivity().findViewById(R.id.company_inn_text);
txt.setText(_company.inn);
txt = (EditText)getActivity().findViewById(R.id.company_phonenum_text);
txt.setText(_company.phonenum);
txt = (EditText)getActivity().findViewById(R.id.company_email_text);
txt.setText(_company.email);
}
// populate view with event data
private void populateEventView() {
EditText txt = (EditText)getActivity().findViewById(R.id.event_descr_text);
txt.setText(_event.descr);
// setup company spinner
_companySpinnerHandler = new CompanySpinnerHandler(getActivity(),
getLoaderManager(),
this);
Spinner companySpinner = (Spinner)getActivity().findViewById(R.id.event_company_spinner);
_companySpinnerHandler.load(companySpinner, _event.company_id);
// setup poc spinner
_pocSpinnerHandler = new POCSpinnerHandler(getActivity(), getLoaderManager());
// load() for poc spinner is called when company spinner reports selection
// setup project spinner
_projectSpinnerHandler = new ProjectSpinnerHandler(getActivity(),
getLoaderManager());
// load() for project spinner is called when company spinner reports selection
// setup event type spinner
_eventTypeSpinnerHandler = new EventTypeSpinnerHandler(getActivity());
Spinner eventTypeSpinner = (Spinner)getActivity().findViewById(R.id.event_type_spinner);
_eventTypeSpinnerHandler.populateSpinner(eventTypeSpinner, _event.type);
// setup event state spinner
_eventStateSpinnerHandler = new EventStateSpinnerHandler(getActivity());
Spinner eventStateSpinner = (Spinner)getActivity().findViewById(R.id.event_state_spinner);
_eventStateSpinnerHandler.populateSpinner(eventStateSpinner, _event.state);
// event outcome
txt = (EditText)getActivity().findViewById(R.id.event_outcome_text);
txt.setText(_event.outcome);
// setup event date and time
_eventDate = new Date(_event.timestamp * 1000);
_dateTimeHandler = new DateTimeHandler(_eventDate,
getActivity(),
getActivity().getFragmentManager(),
this);
View dateView = getActivity().findViewById(R.id.event_date);
View timeView = getActivity().findViewById(R.id.event_time);
dateView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_dateTimeHandler.showDatePicker();
}
});
timeView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_dateTimeHandler.showTimePicker();
}
});
// populate date and time text fields - onDateChanged() will do the job
onDateChanged(_eventDate);
// setup "add reminder" button
View reminderView = getActivity().findViewById(R.id.event_add_reminder);
reminderView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ReminderDialog dialog = new ReminderDialog(EditEntryFragment.this,
getActivity());
dialog.show(getActivity().getFragmentManager(), "ReminderDialog");
}
});
// create views for already existing reminders
EventAlarmMgr eventAlarmMgr = new EventAlarmMgr(getActivity());
Set<Long> existingAlarms = eventAlarmMgr.getAlarms(_event.id);
if (existingAlarms != null) {
for (Long ts : existingAlarms) {
EventAlarm eventAlarm = new EventAlarm(getActivity(), ts.longValue(),
_event.timestamp);
// onReminderSet will create the view for each reminder
onReminderSet(eventAlarm.getIntervalType(), eventAlarm.getInterval());
}
}
}
// populate view with project data
private void populateProjectView() {
EditText txt = (EditText)getActivity().findViewById(R.id.project_title_text);
txt.setText(_project.title);
txt = (EditText)getActivity().findViewById(R.id.project_descr_text);
txt.setText(_project.descr);
// setup company spinner
_companySpinnerHandler = new CompanySpinnerHandler(getActivity(),
getLoaderManager(),
this);
Spinner companySpinner = (Spinner)getActivity().findViewById(R.id.project_company_spinner);
_companySpinnerHandler.load(companySpinner, _project.company_id);
// setup project state spinner
Spinner projStateSpinner = (Spinner)getActivity().findViewById(R.id.project_state_spinner);
_projectStateSpinnerHandler = new ProjectStateSpinnerHandler(getActivity());
_projectStateSpinnerHandler.populateSpinner(projStateSpinner, _project.state);
// setup currency spinner
Spinner currencySpinner = (Spinner)getActivity().findViewById(R.id.project_currency_spinner);
_currencySpinnerHandler = new CurrencySpinnerHandler(getActivity());
_currencySpinnerHandler.populateSpinner(currencySpinner, _project.currency);
txt = (EditText)getActivity().findViewById(R.id.project_cost_text);
txt.setText((new Long(_project.cost)).toString());
}
// populate view with poc data
private void populatePOCView() {
EditText txt = (EditText)getActivity().findViewById(R.id.poc_firstname_text);
txt.setText(_poc.firstname);
txt = (EditText)getActivity().findViewById(R.id.poc_secondname_text);
txt.setText(_poc.secondname);
txt = (EditText)getActivity().findViewById(R.id.poc_lastname_text);
txt.setText(_poc.lastname);
txt = (EditText)getActivity().findViewById(R.id.poc_mobilenum_text);
txt.setText(_poc.mobilenum);
txt = (EditText)getActivity().findViewById(R.id.poc_phonenum_text);
txt.setText(_poc.phonenum);
txt = (EditText)getActivity().findViewById(R.id.poc_email_text);
txt.setText(_poc.email);
txt = (EditText)getActivity().findViewById(R.id.poc_position_text);
txt.setText(_poc.position);
// setup company spinner
_companySpinnerHandler = new CompanySpinnerHandler(getActivity(),
getLoaderManager(),
this);
Spinner companySpinner = (Spinner)getActivity().findViewById(R.id.poc_company_spinner);
_companySpinnerHandler.load(companySpinner, _poc.company_id);
}
// save company modifications
private void saveCompanyData() {
EditText txt = (EditText)getActivity().findViewById(R.id.company_name_text);
String companyName = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.company_jur_name_text);
String companyJurName = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.company_address_text);
String companyAddress = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.company_inn_text);
String companyInn = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.company_phonenum_text);
String companyPhonenum = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.company_email_text);
String companyEmail = txt.getText().toString();
Company company = new Company(_company.id, companyName, companyJurName,
companyAddress, companyInn, companyPhonenum,
companyEmail);
// update company data
ScribaDBManager.useDB(getActivity());
ScribaDB.updateCompany(company);
ScribaDBManager.releaseDB();
}
// save event modifications
private void saveEventData() {
EditText txt = (EditText)getActivity().findViewById(R.id.event_descr_text);
String descr = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.event_outcome_text);
String outcome = txt.getText().toString();
UUID companyId = _companySpinnerHandler.getSelectedCompanyId();
UUID pocId = _pocSpinnerHandler.getSelectedPOCId();
UUID projectId = _projectSpinnerHandler.getSelectedProjectId();
byte type = _eventTypeSpinnerHandler.getSelectedType();
byte state = _eventStateSpinnerHandler.getSelectedState();
// libscriba expects timestamp in seconds
long timestamp = _eventDate.getTime() / 1000;
Event event = new Event(_event.id, descr, companyId, pocId, projectId,
type, outcome, timestamp, state);
ScribaDBManager.useDB(getActivity());
ScribaDB.updateEvent(event);
ScribaDBManager.releaseDB();
saveEventReminders(event);
}
// save event reminder modifications
private void saveEventReminders(Event event) {
EventAlarmMgr evtAlarmMgr = new EventAlarmMgr(getActivity());
if (_eventAlarmAdapter != null) {
// remove all alarms and add only those that are present
// in the alarm adapter
evtAlarmMgr.removeAlarms(event.id);
for (int i = 0; i < _eventAlarmAdapter.getCount(); i++) {
EventAlarm alarm = _eventAlarmAdapter.getItem(i);
// event timestamp may have changed since EventAlarm object
// creation, so make new object with updated event time
EventAlarm updAlarm = new EventAlarm(getActivity(),
alarm.getInterval(), alarm.getIntervalType(), event.timestamp);
evtAlarmMgr.addAlarm(event.id, updAlarm.getAlarmTimestamp());
}
}
// if the alarm adapter is not instantiated at this moment, it
// means there were no reminders set for this event, so do nothing
}
// save project modifications
private void saveProjectData() {
EditText txt = (EditText)getActivity().findViewById(R.id.project_title_text);
String title = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.project_descr_text);
String descr = txt.getText().toString();
UUID selectedCompanyId = _companySpinnerHandler.getSelectedCompanyId();
byte selectedState = _projectStateSpinnerHandler.getSelectedState();
byte selectedCurrency = _currencySpinnerHandler.getSelectedCurrency();
txt = (EditText)getActivity().findViewById(R.id.project_cost_text);
long cost = Long.parseLong(txt.getText().toString(), 10);
long mod_time = _project.mod_time;
// if project state has changed, update mod_time
if (_projectStateSpinnerHandler.hasChanged()) {
mod_time = (new Date()).getTime() / 1000; // convert to seconds
}
Project project = new Project(_project.id, title, descr,
selectedCompanyId, selectedState,
selectedCurrency, cost,
_project.start_time, mod_time);
ScribaDBManager.useDB(getActivity());
ScribaDB.updateProject(project);
ScribaDBManager.releaseDB();
}
// save poc modifications
private void savePOCData() {
EditText txt = (EditText)getActivity().findViewById(R.id.poc_firstname_text);
String firstname = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.poc_secondname_text);
String secondname = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.poc_lastname_text);
String lastname = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.poc_mobilenum_text);
String mobilenum = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.poc_phonenum_text);
String phonenum = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.poc_email_text);
String email = txt.getText().toString();
txt = (EditText)getActivity().findViewById(R.id.poc_position_text);
String position = txt.getText().toString();
UUID selectedCompanyId = _companySpinnerHandler.getSelectedCompanyId();
POC poc = new POC(_poc.id, firstname, secondname, lastname, mobilenum,
phonenum, email, position, selectedCompanyId);
ScribaDBManager.useDB(getActivity());
ScribaDB.updatePOC(poc);
ScribaDBManager.releaseDB();
}
}
| gpl-3.0 |
zeatul/poc | e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/domain/AlipaySecurityProdFingerprintDeleteModel.java | 958 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 指纹解注册
*
* @author auto create
* @since 1.0, 2017-01-12 17:27:09
*/
public class AlipaySecurityProdFingerprintDeleteModel extends AlipayObject {
private static final long serialVersionUID = 8631337432346717531L;
/**
* IFAA协议的版本,目前为2.0
*/
@ApiField("ifaa_version")
private String ifaaVersion;
/**
* IFAA标准中用于关联IFAA Server和业务方Server开通状态的token,此token为注册时保存的token,传入此token,用于生成服务端去注册信息。
*/
@ApiField("token")
private String token;
public String getIfaaVersion() {
return this.ifaaVersion;
}
public void setIfaaVersion(String ifaaVersion) {
this.ifaaVersion = ifaaVersion;
}
public String getToken() {
return this.token;
}
public void setToken(String token) {
this.token = token;
}
}
| gpl-3.0 |
tferr/ASA | src/main/java/sholl/UPoint.java | 5219 | /*
* #%L
* Sholl Analysis plugin for ImageJ.
* %%
* Copyright (C) 2005 - 2020 Tiago Ferreira.
* %%
* 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%
*/
package sholl;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import ij.measure.Calibration;
/**
* 'Universal Point' Class to access Cartesian coordinates of 2D and 3D points.
* Designed to accommodate points from several sources such SWC nodes, pixels,
* voxels, and ROIs.
*
* @author Tiago Ferreira
*/
public class UPoint {
/** The x-coordinate */
public double x;
/** The y-coordinate */
public double y;
/** The z-coordinate */
public double z;
public int flag = NONE;
public final static int NONE = -1;
public final static int VISITED = -2;
public final static int DELETE = -4;
public final static int KEEP = -8;
public UPoint() {
}
public UPoint(final double x, final double y, final double z) {
this.x = x;
this.y = y;
this.z = z;
}
public UPoint(final double x, final double y) {
this.x = x;
this.y = y;
this.z = 0;
}
public UPoint(final int x, final int y, final int z, final Calibration cal) {
this.x = cal.getX(x);
this.y = cal.getY(y);
this.z = cal.getZ(z);
}
public UPoint(final int x, final int y, final Calibration cal) {
this.x = cal.getX(x);
this.y = cal.getY(y);
this.z = cal.getZ(0);
}
public UPoint(final int x, final int y, final int z, final int flag) {
this.x = x;
this.y = y;
this.z = z;
this.flag = flag;
}
public void scale(final double xScale, final double yScale, final double zScale) {
this.x *= xScale;
this.y *= yScale;
this.z *= zScale;
}
public void applyOffset(final double xOffset, final double yOffset, final double zOffset) {
this.x += xOffset;
this.y += yOffset;
this.z += zOffset;
}
public UPoint minus(final UPoint point) {
return new UPoint(x - point.x, y - point.y, z - point.z);
}
public UPoint plus(final UPoint point) {
return new UPoint(x + point.x, y + point.y, z + point.z);
}
public double scalar(final UPoint point) {
return x * point.x + y * point.y + z * point.z;
}
public UPoint times(final double factor) {
return new UPoint(x * factor, y * factor, z * factor);
}
public double length() {
return Math.sqrt(scalar(this));
}
public double distanceSquared(final UPoint point) {
final double x1 = x - point.x;
final double y1 = y - point.y;
final double z1 = z - point.z;
return x1 * x1 + y1 * y1 + z1 * z1;
}
public double euclideanDxTo(final UPoint point) {
return Math.sqrt(distanceSquared(point));
}
public double chebyshevXYdxTo(final UPoint point) {
return Math.max(Math.abs(x - point.x), Math.abs(y - point.y));
}
public double chebyshevZdxTo(final UPoint point) {
return Math.abs(z - point.z);
}
public double chebyshevDxTo(final UPoint point) {
return Math.max(chebyshevXYdxTo(point), chebyshevZdxTo(point));
}
public static UPoint average(final List<UPoint> points) {
UPoint result = points.get(0);
for(int i = 1; i < points.size(); i++)
result = result.plus(points.get(i));
return result.times(1.0 / points.size());
}
public static void scale(final Set<UPoint> set, final Calibration cal) {
for (final Iterator<UPoint> it = set.iterator(); it.hasNext();) {
final UPoint point = it.next();
point.x = cal.getX(point.x);
point.y = cal.getY(point.y);
point.z = cal.getZ(point.z);
}
}
protected static UPoint fromString(final String string) {
if (string == null || string.isEmpty())
return null;
final String[] ccs = string.trim().split(",");
if (ccs.length == 3) {
return new UPoint(Double.valueOf(ccs[0]), Double.valueOf(ccs[1]), Double.valueOf(ccs[2]));
}
return null;
}
public double rawX(final Calibration cal) {
return cal.getRawX(x);
}
public double rawY(final Calibration cal) {
return cal.getRawY(y);
}
public double rawZ(final Calibration cal) {
return z / cal.pixelDepth + cal.zOrigin;
}
public void setFlag(final int flag) {
this.flag = flag;
}
public int intX() {
return (int) x;
}
public int intY() {
return (int) y;
}
public int intZ() {
return (int) z;
}
@Override
public String toString() {
return ShollUtils.d2s(x) + ", " + ShollUtils.d2s(y) + ", " + ShollUtils.d2s(z);
}
@Override
public boolean equals(final Object object) {
if (this == object)
return true;
if (!(object instanceof UPoint))
return false;
final UPoint point = (UPoint) object;
return (this.x == point.x && this.y == point.y && this.z == point.z);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
| gpl-3.0 |
hlfernandez/GC4S | gc4s/src/main/java/org/sing_group/gc4s/input/tree/JTreeSelectionPanel.java | 10120 | /*
* #%L
* GC4S components
* %%
* Copyright (C) 2014 - 2019 Hugo López-Fernández, Daniel Glez-Peña, Miguel Reboiro-Jato,
* Florentino Fdez-Riverola, Rosalía Laza-Fidalgo, Reyes Pavón-Rial
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
package org.sing_group.gc4s.input.tree;
import static javax.swing.BorderFactory.createEmptyBorder;
import static org.sing_group.gc4s.utilities.builder.JButtonBuilder.newJButtonBuilder;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import org.sing_group.gc4s.utilities.JTreeUtils;
/**
* A component to select an element from a {@code JTree}. The tree is displayed in a popup menu when user clicks the
* button and the selected element in the tree is displayed in the component.
*
* @author hlfernandez
*
*/
public class JTreeSelectionPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final String DEFAULT_CHOOSE_BUTTON_LABEL = "Choose";
private static final boolean DEFAULT_CLOSE_POPUP_TREE_SELECTION = false;
private static final boolean DEFAULT_BUTTON_CLOSE_VISIBLE = true;
private static final boolean DEFAULT_BUTTON_EXPAND_ALL_VISIBLE = true;
private static final boolean DEFAULT_BUTTON_COLLAPSE_ALL_VISIBLE = true;
private JTree tree;
private JLabel selectionLabel;
private JTreePopupMenu popupMenu;
private String chooseButtonLabel;
private JButton chooseButton;
private boolean closePopupOnTreeSelection;
private boolean closeButtonVisible;
private boolean expandAllButtonVisible;
private boolean collapseAllButtonVisible;
/**
* Constructs a new {@code JTreeSelectionPanel} with the specified tree and default values for the rest of the
* parameters.
*
* @param tree the {@code JTree} for the user selection
*/
public JTreeSelectionPanel(
JTree tree
) {
this(
tree, DEFAULT_CHOOSE_BUTTON_LABEL, DEFAULT_CLOSE_POPUP_TREE_SELECTION, DEFAULT_BUTTON_CLOSE_VISIBLE,
DEFAULT_BUTTON_EXPAND_ALL_VISIBLE, DEFAULT_BUTTON_COLLAPSE_ALL_VISIBLE
);
}
/**
* Constructs a new {@code JTreeSelectionPanel} with the specified tree. This constructor also allows to specify:
*
* <ul>
* <li>The label for the choose button.</li>
* <li>Whether the popup must be closed when an item is selected.</li>
* <li>The visibility of the close, expand all and collapse all buttons.</li>
* </ul>
*
* @param tree the {@code JTree} for the user selection
* @param chooseButtonLabel the label for the choose button
* @param closePopupOnTreeSelection whether the popup must be closed when an item is selected
*/
public JTreeSelectionPanel(
JTree tree, String chooseButtonLabel, boolean closePopupOnTreeSelection,
boolean closeButtonVisible, boolean expandAllButtonVisible, boolean collapseAllButtonVisible
) {
this.tree = tree;
this.chooseButtonLabel = chooseButtonLabel;
this.closePopupOnTreeSelection = closePopupOnTreeSelection;
this.closeButtonVisible = closeButtonVisible;
this.expandAllButtonVisible = expandAllButtonVisible;
this.collapseAllButtonVisible = collapseAllButtonVisible;
this.init();
this.tree.getSelectionModel().addTreeSelectionListener(this::treeValueChanged);
}
private void init() {
this.popupMenu =
new JTreePopupMenu(this.tree, this.closeButtonVisible, this.expandAllButtonVisible, this.collapseAllButtonVisible);
this.setLayout(new BorderLayout());
this.add(getChooseButton(), BorderLayout.WEST);
this.add(getSelectionLabel(), BorderLayout.CENTER);
}
private Component getChooseButton() {
if (this.chooseButton == null) {
this.chooseButton =
newJButtonBuilder().withText(this.chooseButtonLabel).thatDoes(getChooseButtonAction()).build();
}
return this.chooseButton;
}
private Action getChooseButtonAction() {
return new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
chooseButtonAction();
}
};
}
private void chooseButtonAction() {
popupMenu.show(
this.chooseButton, this.chooseButton.getX(), this.chooseButton.getY()
);
popupMenu.pack();
}
/**
* Returns the selection label component.
*
* @return the {@code JLabel} used to display the current selection
*/
public JLabel getSelectionLabel() {
if (this.selectionLabel == null) {
this.selectionLabel = new JLabel(getCurrentSelection());
this.selectionLabel.setMinimumSize(getSelectionLabelMinimumSize());
this.selectionLabel.setPreferredSize(getSelectionLabelMinimumSize());
this.selectionLabel.setBorder(createEmptyBorder(0, 10, 0, 5));
this.selectionLabel.setFont(getSelectionLabelFont());
}
return this.selectionLabel;
}
/**
* Returns the font of the selected item text label.
*
* @return the {@code Font} of the selected item text label
*/
protected Font getSelectionLabelFont() {
return new JLabel().getFont();
}
/**
* Returns the minimum size of the selected item text label.
*
* @return the minimum size of the selected item text label
*/
protected Dimension getSelectionLabelMinimumSize() {
return new Dimension(150, 30);
}
private String getCurrentSelection() {
if (this.tree.getSelectionModel().isSelectionEmpty()) {
return "";
} else {
return this.tree.getSelectionModel().getSelectionPath()
.getLastPathComponent().toString();
}
}
private void treeValueChanged(TreeSelectionEvent e) {
this.selectionLabel.setText(getCurrentSelection());
if (this.closePopupOnTreeSelection) {
this.popupMenu.setVisible(false);
}
}
/**
*
* An extension of {@code JPopupMenu} that show a {@code JTree} when it becomes visible. It has also some buttons to
* control the tree (expand/collapse nodes) and to close the menu.
*
* @author hlfernandez
*
*/
public static class JTreePopupMenu extends JPopupMenu {
private static final long serialVersionUID = 1L;
private JTree tree;
private JScrollPane scrollPane;
private JPanel buttonsPanel;
private boolean closeButtonVisible;
private boolean expandAllButtonVisible;
private boolean collapseAllButtonVisible;
/**
* Constructs a new {@code JTreePopupMenu} with the specified tree.
*
* @param tree the {@code JTree} to be displayed
*/
public JTreePopupMenu(JTree tree) {
this(tree, true, true, true);
}
public JTreePopupMenu(
JTree tree, boolean closeButtonVisible, boolean expandAllButtonVisible, boolean collapseAllButtonVisible
) {
this.tree = tree;
this.closeButtonVisible = closeButtonVisible;
this.expandAllButtonVisible = expandAllButtonVisible;
this.collapseAllButtonVisible = collapseAllButtonVisible;
this.setLayout(new BorderLayout());
this.add(getTreeViewScrollPane(), BorderLayout.CENTER);
this.add(getButtonsPanel(), BorderLayout.SOUTH);
}
private Component getTreeViewScrollPane() {
if (scrollPane == null) {
JPanel treePanel = new JPanel();
treePanel.setLayout(new BorderLayout());
treePanel.add(this.tree, BorderLayout.NORTH);
treePanel.setBackground(tree.getBackground());
scrollPane = new JScrollPane(treePanel);
scrollPane.setPreferredSize(new Dimension(400, 400));
scrollPane.getVerticalScrollBar().setUnitIncrement(15);
}
return scrollPane;
}
private Component getButtonsPanel() {
if (this.buttonsPanel == null) {
buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JButton closeButton = new JButton("Close");
closeButton.setVisible(closeButtonVisible);
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == closeButton) {
setVisible(false);
}
}
});
JButton collapseAllButton = new JButton("Collapse all");
collapseAllButton.setVisible(collapseAllButtonVisible);
collapseAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == collapseAllButton) {
JTreeUtils.collapseAll(tree);
}
}
});
JButton expandAllButton = new JButton("Expand all");
expandAllButton.setVisible(expandAllButtonVisible);
expandAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == expandAllButton) {
JTreeUtils.expandAll(tree);
}
}
});
buttonsPanel.add(closeButton);
buttonsPanel.add(collapseAllButton);
buttonsPanel.add(expandAllButton);
}
return this.buttonsPanel;
}
}
}
| gpl-3.0 |
hmueller80/VCF.Filter | VCFFilter/src/at/ac/oeaw/cemm/bsf/vcffilter/filter/QualFilter.java | 3595 | /*
* This file is part of the VCF.Filter project (https://biomedical-sequencing.at/VCFFilter/).
* VCF.Filter permits graphical filtering of VCF files on cutom annotations and standard VCF fields, pedigree analysis, and cohort searches.
* %%
* Copyright © 2016, 2017 Heiko Müller (hmueller@cemm.oeaw.ac.at)
* %%
*
* VCF.Filter 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 VCF.Filter. If not, see <http://www.gnu.org/licenses/>.
*
* VCF.Filter Copyright © 2016, 2017 Heiko Müller (hmueller@cemm.oeaw.ac.at)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it
* under certain conditions;
* For details interrogate the About section in the File menu.
*/
package at.ac.oeaw.cemm.bsf.vcffilter.filter;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.vcf.VCFCompoundHeaderLine;
/**
* Filters for default QUAL field (Phred scaled quality).
* QualFilter.java 04 OCT 2016
*
* @author Heiko Müller
* @version 1.0
* @since 1.0
*/
public class QualFilter extends DoubleNumberFilter{
/**
* The version number of this class.
*/
static final long serialVersionUID = 1L;
/**
* Creates new QualFilter.
*
* @param header VCF header line object
* @author Heiko Müller
* @since 1.0
*/
public QualFilter(VCFCompoundHeaderLine header){
super(header);
criterion1.setToolTipText(">1000");
criterion2.setToolTipText("=1000");
criterion3.setToolTipText("");
}
public boolean passesFilter(VariantContext vc) {
Object o = vc.getPhredScaledQual();
if (o == null) {
//System.out.println(ID + " not found");
return false;
}
String attstring = o.toString();
//System.out.println("attribute string: " + attstring);
Double attribute = parseNumber(attstring);
if(testPredicate(attribute, operator1, predicate1) || testPredicate(attribute, operator2, predicate2) || testPredicate(attribute, operator3, predicate3)){
return true;
}else{
return false;
}
}
private boolean testPredicate(Double attribute, String operator, Double predicate){
if(operator.equals("<")){
if(attribute.doubleValue() < predicate.doubleValue()){
return true;
}else{
return false;
}
}
if(operator.equals("=")){
if(attribute.doubleValue() == predicate.doubleValue()){
return true;
}else{
return false;
}
}
if(operator.equals(">")){
if(attribute.doubleValue() > predicate.doubleValue()){
return true;
}else{
return false;
}
}
return false;
}
}
| gpl-3.0 |
TLQPQPQ/tlq_git_study | src/com/sun/corba/se/PortableActivationIDL/Locator.java | 492 | package com.sun.corba.se.PortableActivationIDL;
/**
* com/sun/corba/se/PortableActivationIDL/Locator.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /HUDSON/workspace/8-2-build-linux-amd64/jdk8u77/6540/corba/src/share/classes/com/sun/corba/se/PortableActivationIDL/activation.idl
* Sunday, March 20, 2016 10:01:25 PM PDT
*/
public interface Locator extends LocatorOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity
{
} // interface Locator
| gpl-3.0 |
zeatul/poc | e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/domain/BPOpenApiInstance.java | 4773 | package com.alipay.api.domain;
import java.util.Date;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* 流程实例
*
* @author auto create
* @since 1.0, 2017-03-03 11:29:15
*/
public class BPOpenApiInstance extends AlipayObject {
private static final long serialVersionUID = 5581722165768253843L;
/**
* 业务上下文,JSON格式
*/
@ApiField("biz_context")
private String bizContext;
/**
* 业务ID
*/
@ApiField("biz_id")
private String bizId;
/**
* 创建人域账号
*/
@ApiField("create_user")
private String createUser;
/**
* 流程实例描述
*/
@ApiField("description")
private String description;
/**
* 创建到完成的毫秒数,未完结为0
*/
@ApiField("duration")
private Long duration;
/**
* 创建时间
*/
@ApiField("gmt_create")
private Date gmtCreate;
/**
* 完结时间,未完结时为空
*/
@ApiField("gmt_end")
private Date gmtEnd;
/**
* 最后更新时间
*/
@ApiField("gmt_modified")
private Date gmtModified;
/**
* 2088账号
*/
@ApiField("ip_role_id")
private String ipRoleId;
/**
* 最后更新人域账号
*/
@ApiField("modify_user")
private String modifyUser;
/**
* 流程配置名称
*/
@ApiField("name")
private String name;
/**
* 父流程实例ID。用于描述父子流程
*/
@ApiField("parent_id")
private String parentId;
/**
* 父流程实例所处的节点
*/
@ApiField("parent_node")
private String parentNode;
/**
* 优先级
*/
@ApiField("priority")
private Long priority;
/**
* 全局唯一ID
*/
@ApiField("puid")
private String puid;
/**
* 前置流程ID。用于描述流程串联
*/
@ApiField("source_id")
private String sourceId;
/**
* 前置流程从哪个节点发起的本流程
*/
@ApiField("source_node_name")
private String sourceNodeName;
/**
* 流程实例状态:CREATED,PROCESSING,COMPLETED,CANCELED
*/
@ApiField("state")
private String state;
/**
* 包含的任务列表
*/
@ApiListField("tasks")
@ApiField("b_p_open_api_task")
private List<BPOpenApiTask> tasks;
public String getBizContext() {
return this.bizContext;
}
public void setBizContext(String bizContext) {
this.bizContext = bizContext;
}
public String getBizId() {
return this.bizId;
}
public void setBizId(String bizId) {
this.bizId = bizId;
}
public String getCreateUser() {
return this.createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getDuration() {
return this.duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public Date getGmtCreate() {
return this.gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtEnd() {
return this.gmtEnd;
}
public void setGmtEnd(Date gmtEnd) {
this.gmtEnd = gmtEnd;
}
public Date getGmtModified() {
return this.gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
public String getIpRoleId() {
return this.ipRoleId;
}
public void setIpRoleId(String ipRoleId) {
this.ipRoleId = ipRoleId;
}
public String getModifyUser() {
return this.modifyUser;
}
public void setModifyUser(String modifyUser) {
this.modifyUser = modifyUser;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getParentId() {
return this.parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getParentNode() {
return this.parentNode;
}
public void setParentNode(String parentNode) {
this.parentNode = parentNode;
}
public Long getPriority() {
return this.priority;
}
public void setPriority(Long priority) {
this.priority = priority;
}
public String getPuid() {
return this.puid;
}
public void setPuid(String puid) {
this.puid = puid;
}
public String getSourceId() {
return this.sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
public String getSourceNodeName() {
return this.sourceNodeName;
}
public void setSourceNodeName(String sourceNodeName) {
this.sourceNodeName = sourceNodeName;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public List<BPOpenApiTask> getTasks() {
return this.tasks;
}
public void setTasks(List<BPOpenApiTask> tasks) {
this.tasks = tasks;
}
}
| gpl-3.0 |
Nick2324/tesis_red_social | Prototipo/Construccion/SNADeportivo/app/src/main/java/sportsallaround/utils/generales/ConstructorArrObjSNS.java | 2607 | package sportsallaround.utils.generales;
import com.sna_deportivo.utils.gr.FactoryObjectSNSDeportivo;
import com.sna_deportivo.utils.gr.ObjectSNSDeportivo;
import com.sna_deportivo.utils.json.JsonUtils;
import com.sna_deportivo.utils.json.excepciones.ExcepcionJsonDeserializacion;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import sportsallaround.utils.gui.KeyValueItem;
/**
* Created by nicolas on 30/08/15.
*/
public final class ConstructorArrObjSNS {
private ConstructorArrObjSNS(){}
public static ArrayList<ObjectSNSDeportivo> producirArrayObjetoSNS(FactoryObjectSNSDeportivo fabrica,
JSONArray arrayJson){
if(fabrica != null && arrayJson != null) {
ArrayList<ObjectSNSDeportivo> retorno = new ArrayList<ObjectSNSDeportivo>();
try {
for(int i = 0;i < arrayJson.length(); i++){
retorno.add(i,fabrica.getObjetoSNS());
retorno.get(i).deserializarJson(JsonUtils.JsonStringToObject(arrayJson.getString(i)));
}
} catch (ExcepcionJsonDeserializacion excepcionJsonDeserializacion) {
excepcionJsonDeserializacion.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return retorno;
}
return null;
}
public static ArrayList<KeyValueItem> producirArrayAdapterObjSNS(ArrayList<ObjectSNSDeportivo> objetos,
String[] atributoAMostrarAdapter){
ArrayList<KeyValueItem> adapter = new ArrayList<KeyValueItem>();
Integer i = 0;
for(ObjectSNSDeportivo obj:objetos){
obj.retornoToString(atributoAMostrarAdapter);
adapter.add(new KeyValueItem(i++,obj));
}
return adapter;
}
public static ArrayList<KeyValueItem> producirArrayAdapterObjSNS(ArrayList<ObjectSNSDeportivo> objetos,
String[] atributoAMostrarAdapter,
String[] separadoresAtributos) throws Exception{
ArrayList<KeyValueItem> adapter = new ArrayList<KeyValueItem>();
Integer i = 0;
for(ObjectSNSDeportivo obj:objetos){
obj.retornoToStringSeparadores(atributoAMostrarAdapter,separadoresAtributos);
adapter.add(new KeyValueItem(i++,obj));
}
return adapter;
}
}
| gpl-3.0 |