repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
portguas/androidsc | Demons/allutil/src/main/java/com/personal/allutil/ZApplication.java | 1215 | package com.personal.allutil;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import android.app.Application;
import android.content.Context;
/**
* Created by zzz on 8/18/2016.
*/
public class ZApplication extends Application {
private static final String TAG = "ZApp";
private static ZApplication instance;
private static Context context;
/**
* Called when the application is starting, before any activity, service,
* or receiver objects (excluding content providers) have been created.
* Implementations should be as quick as possible (for example using
* lazy initialization of state) since the time spent in this function
* directly impacts the performance of starting the first activity,
* service, or receiver in a process.
* If you override this method, be sure to call super.onCreate().
*/
@Override
public void onCreate() {
super.onCreate();
instance = this;
context = getApplicationContext();
Logger.init(TAG);
}
public static ZApplication getInstance() {
return instance;
}
public static Context getContext() {
return context;
}
}
| gpl-3.0 |
iCarto/siga | libGPE-GML/src/org/gvsig/gpe/gml/parser/sfp0/geometries/GeometryBinding.java | 3114 | package org.gvsig.gpe.gml.parser.sfp0.geometries;
import java.io.IOException;
import javax.xml.namespace.QName;
import org.gvsig.gpe.gml.parser.GPEDefaultGmlParser;
import org.gvsig.gpe.gml.utils.GMLTags;
import org.gvsig.gpe.xml.stream.IXmlStreamReader;
import org.gvsig.gpe.xml.stream.XmlStreamException;
import org.gvsig.gpe.xml.utils.CompareUtils;
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibáñez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* gvsig@gva.es
* www.gvsig.gva.es
*
* or
*
* IVER T.I. S.A
* Salamanca 50
* 46005 Valencia
* Spain
*
* +34 963163400
* dac@iver.es
*/
/* CVS MESSAGES:
*
* $Id$
* $Log$
*
*/
/**
* @author Jorge Piera LLodrá (jorge.piera@iver.es)
*/
public class GeometryBinding extends org.gvsig.gpe.gml.parser.v2.geometries.GeometryBinding{
/*
* (non-Javadoc)
* @see org.gvsig.gpe.gml.bindings.v2.geometries.GeometryBinding#parseTag(org.xmlpull.v1.XmlPullParser, org.gvsig.gpe.gml.GPEDefaultGmlParser, java.lang.String)
*/
protected Object parseTag(IXmlStreamReader parser,GPEDefaultGmlParser handler, QName tag) throws XmlStreamException, IOException{
Object geometry = super.parseTag(parser, handler, tag);
if (geometry != null){
return geometry;
}
if (CompareUtils.compareWithNamespace(tag,GMLTags.GML_MULTICURVEPROPERTY)){
geometry = handler.getProfile().getCurvePropertyTypeBinding().
parse(parser, handler);
}else if (CompareUtils.compareWithNamespace(tag,GMLTags.GML_CURVEPROPERTY)){
geometry = handler.getProfile().getCurvePropertyTypeBinding().
parse(parser, handler);
}else if (CompareUtils.compareWithNamespace(tag,GMLTags.GML_MULTICURVE)){
geometry = handler.getProfile().getMultiCurveTypeBinding().
parse(parser, handler);
}
//MULTIPOLYGON PROPERTY ALIASES
else if (CompareUtils.compareWithNamespace(tag,GMLTags.GML_MULTISURFACE)){
geometry = handler.getProfile().getMultiPolygonTypeBinding().
parse(parser, handler);
}else if (CompareUtils.compareWithNamespace(tag,GMLTags.GML_SURFACE)){
geometry = handler.getProfile().getPolygonTypeBinding().
parse(parser, handler);
}
return geometry;
}
}
| gpl-3.0 |
pcimcioch/scraper | src/main/java/scraper/environment/StatusMessage.java | 464 | package scraper.environment;
/**
* Simple status message class wrapping messages.
*/
public class StatusMessage {
private String message;
protected StatusMessage() {
}
public StatusMessage(String message) {
this.message = message;
}
public StatusMessage(String messageFormat, Object... args) {
this.message = String.format(messageFormat, args);
}
public String getMessage() {
return message;
}
}
| gpl-3.0 |
Waoss/Enesys | enesys/src/main/java/com/waoss/enesys/cpu/instructions/Instruction.java | 11105 | /*
* Enesys : An NES Emulator
* Copyright (C) 2017 Rahul Chhabra and Waoss
*
* 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.waoss.enesys.cpu.instructions;
import com.waoss.enesys.cpu.CentralProcessor;
import com.waoss.enesys.mem.Addressing;
import javafx.beans.property.*;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
/**
* Represents an instruction of the NES processor.<br>
* <p>An instruction object contains all the data : the name of the instruction,the opcode,the addressing mode,the
* arguments required for the instruction (a jump instruction takes in the new value of the program counter along)</p>
* For example,
* {@code
* Instruction instruction = new Instruction(InstructionName.ADC, Addressing.ABSOLUTE);
* instruction.getOpCode(); // works fine
* instruction.setArguments(5); // the arguments
* }
* <p>Addressing is also handled because every time there is a change in the arguments;their is an update according to
* the addressing mode</p>
*/
public final class Instruction {
/**
* This property holds the instruction name
*/
private final AtomicReference<SimpleObjectProperty<InstructionName>> instructionName = new AtomicReference<>(
new SimpleObjectProperty<>(this, "instructionName"));
/**
* This property holds the opcode
*/
private final AtomicReference<SimpleObjectProperty<Integer>> opCode = new AtomicReference<>(
new SimpleObjectProperty<>(this, "opCode"));
/**
* This property holds the addressing mode
*/
private final AtomicReference<SimpleObjectProperty<Addressing>> addressing = new AtomicReference<>(new SimpleObjectProperty<>(this, "addressing"));
/**
* This property stores the arguments<br>
* For example, a branching instruction would have one argument: where to go if condition is true
*/
private final AtomicReference<SimpleObjectProperty<Integer[]>> arguments = new AtomicReference<>(
new SimpleObjectProperty<>(this, "arguments"));
private final AtomicReference<IntegerProperty> size = new AtomicReference<>(
new SimpleIntegerProperty(this, "size", 0));
private final AtomicReference<SimpleObjectProperty<CentralProcessor>> centralProcessor = new AtomicReference<>(
new SimpleObjectProperty<>(this, "centralProcessor"));
{
/*
This ensures that if arguments change the size also changes because size is actually the length of the arguments
and the addressing mode is recognised an the arguments
are parsed accordingly.
*/
arguments.get().addListener((observable, oldValue, newValue) -> size.get().set(newValue.length));
}
/**
* Creates a new Instruction when given the name and addressing
*
* @param instructionName
* The name
* @param addressing
* The Addressing mode
*/
public Instruction(InstructionName instructionName, Addressing addressing) {
this.instructionName.get().set(instructionName);
this.addressing.get().set(addressing);
}
/**
* Creates a new Instruction given the opcode and addressing
*
* @param opcode
* The opcode
* @param addressing
* The addressing mode
*/
public Instruction(Integer opcode, Addressing addressing) {
this.opCode.get().set(opcode);
this.addressing.get().set(addressing);
this.instructionName.get().set(InstructionName.getByOpCode(opcode));
}
public InstructionName getInstructionName() {
return instructionName.get().get();
}
public void setInstructionName(InstructionName instructionName) {
this.instructionName.get().set(instructionName);
}
public final ObjectProperty<InstructionName> instructionNameProperty() {
return instructionName.get();
}
public Integer getOpCode() {
return opCode.get().get();
}
public void setOpCode(Integer opCode) {
this.opCode.get().set(opCode);
}
public final ObjectProperty<Integer> opCodeProperty() {
return opCode.get();
}
public Addressing getAddressing() {
return addressing.get().get();
}
public void setAddressing(Addressing addressing) {
this.addressing.get().set(addressing);
}
public final ObjectProperty<Addressing> addressingProperty() {
return addressing.get();
}
public Integer[] getArguments() {
return arguments.get().get();
}
public void setArguments(Integer... arguments) {
this.arguments.get().set(arguments);
}
public ObjectProperty<Integer[]> argumentsProperty() {
return arguments.get();
}
public int getSize() {
return size.get().get();
}
public void setSize(int size) {
this.size.get().set(size);
}
public final IntegerProperty sizeProperty() {
return size.get();
}
public CentralProcessor getCentralProcessor() {
return centralProcessor.get().get();
}
public void setCentralProcessor(final CentralProcessor centralProcessor) {
this.centralProcessor.get().set(centralProcessor);
}
public final ObjectProperty<CentralProcessor> centralProcessorProperty() {
return centralProcessor.get();
}
/**
* Parses itself according to the arguments and addressing
*/
public void parseArgumentsAccordingToAddressing() {
final Addressing addressing = getAddressing();
final Integer[] givenArguments = argumentsProperty().get();
/*
If there are no arguments it is safe to assume that the instruction does not require any results from us.
This type of addressing is handled but not inferring nullity is shitty af.Wish I was using Kotlin
*/
final Integer[] resultArguments = givenArguments != null ? Arrays.copyOf(givenArguments, givenArguments.length) : null;
final CentralProcessor centralProcessor = getCentralProcessor();
switch (addressing) {
case ABSOLUTE:
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(givenArguments[0]);
}
break;
case ABSOLUTE_X:
if (resultArguments != null) {
resultArguments[0] = givenArguments[0] + centralProcessor.getXRegister().getValue();
}
break;
case ABSOLUTE_Y:
if (resultArguments != null) {
resultArguments[0] = givenArguments[0] + centralProcessor.getYRegister().getValue();
}
break;
case ACCUMULATOR:
break;
case IMMEDIATE:
if (resultArguments != null) {
resultArguments[0] = givenArguments[0];
}
break;
case IMPLIED:
break;
case INDEXED_INDIRECT:
Integer postXAddress = null;
if (givenArguments != null) {
postXAddress = givenArguments[0] + centralProcessor.getXRegister().getValue();
}
Integer mostSignificantByte = centralProcessor.getCompleteMemory().read(postXAddress + 1);
Integer leastSignificantByte = centralProcessor.getCompleteMemory().read(postXAddress);
Integer finalAddress = (mostSignificantByte * 0x0100) + leastSignificantByte;
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(finalAddress);
}
break;
case INDIRECT:
mostSignificantByte = givenArguments != null ? givenArguments[1] : null;
leastSignificantByte = givenArguments != null ? givenArguments[0] : null;
finalAddress = (mostSignificantByte * 0x0100) + leastSignificantByte;
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(finalAddress);
}
break;
case INDIRECT_INDEXED:
Integer addressToLookup = givenArguments != null ? givenArguments[0] : null;
mostSignificantByte = centralProcessor.getCompleteMemory().read(addressToLookup + 1);
leastSignificantByte = centralProcessor.getCompleteMemory().read(addressToLookup);
finalAddress = (mostSignificantByte * 0x0100) + leastSignificantByte;
finalAddress += centralProcessor.getYRegister().getValue();
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(finalAddress);
}
break;
case RELATIVE:
Byte rawAddress = givenArguments != null ? givenArguments[0].byteValue() : 0;
if (resultArguments != null) {
resultArguments[0] = rawAddress.intValue();
}
break;
case ZERO_PAGE:
addressToLookup = givenArguments != null ? givenArguments[0] : null;
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(addressToLookup);
}
break;
case ZERO_PAGE_X:
Integer zeroPageAddressToLookup = givenArguments != null ? givenArguments[0] : 0;
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(zeroPageAddressToLookup);
}
if (resultArguments != null) {
resultArguments[0] += centralProcessor.getXRegister().getValue();
}
break;
case ZERO_PAGE_Y:
zeroPageAddressToLookup = givenArguments != null ? givenArguments[0] : 0;
if (resultArguments != null) {
resultArguments[0] = centralProcessor.getCompleteMemory().read(zeroPageAddressToLookup);
}
if (resultArguments != null) {
resultArguments[0] += centralProcessor.getYRegister().getValue();
}
break;
}
setArguments(resultArguments);
}
}
| gpl-3.0 |
smolvo/OpenBundestagswahl | Implementierung/Mandatsrechner/src/main/java/model/Gebiet.java | 2449 | package main.java.model;
import java.io.Serializable;
/**
* Abstrakte Oberklasse die den Namen und die Anzahl der Wahlberechtigten eines
* Gebiets haltet.
*/
public abstract class Gebiet implements Serializable {
/**
* Automatisch generierte serialVersionUID die fuer das De-/Serialisieren
* verwendet wird.
*/
private static final long serialVersionUID = -5067472345236494574L;
/** Der Name des Gebiets. */
private String name;
/** Zweitstimmenanzahl in ganz Deutschland. */
protected int zweitstimmeGesamt;
/**
* Gibt die Erststimmenanzahl aller Kandidaten im Gebiet.
*
* @return die Erststimmenanzahl aller Kandidaten.
*/
public abstract int getAnzahlErststimmen();
/**
* Gibt die anzahl der Zweitstimmen einer bestimmten Partei zur�ck.
*
* @param partei
* Die Partei zu der die Stimmen gegeben werden sollen.
* @return Die anzahl der Zweitstimmen einer bestimmten Partei.
*/
abstract public int getAnzahlErststimmen(Partei partei);
/**
* Gibt die Zweitstimmenanzahl aller Parteien im Gebiet.
*
* @return die Zweistimmenanzahl aller Partein.
*/
public abstract int getAnzahlZweitstimmen();
/**
* Gibt die anzahl der Zweitstimmen einer bestimmten Partei zur�ck.
*
* @param partei
* Die Partei zu der die Stimmen gegeben werden sollen.
* @return Die anzahl der Zweitstimmen einer bestimmten Partei.
*/
abstract public int getAnzahlZweitstimmen(Partei partei);
/**
* Gibt den Namen des Gebietes zurueck.
*
* @return der Name des Gebiets.
*/
public String getName() {
return this.name;
}
/**
* Gibt die Anzahl der Wahlberechtigten zurueck.
*
* @return die Anzahl der Wahlberechtigten.
*/
abstract public int getWahlberechtigte();
/**
* Setzt einen Namen fuer das Gebiet.
*
* @param name
* der Name des Gebiets.
* @throws IllegalArgumentException
* wenn der Name leer ist.
*/
public void setName(String name) throws IllegalArgumentException {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException(
"Der Parameter \"name\" ist null oder ein leerer String!");
}
this.name = name;
}
/**
* Beschreibt dieses Gebiet.
*
* @return einen String der dieses Gebiet beschreibt.
*/
@Override
public String toString() {
return this.name;
}
}
| gpl-3.0 |
r-k-/MarketAnalysis | src/marketanalysis/package-info.java | 316 | /**
* The <b>MarketAnalysis</b> is a gui application using a database for data storage.
*
* The main purpose of this application is to provide indication on rewarding investments.
* Additionally once the investment strategy is selected allows the monitoring of the performance.
*
*/
package marketanalysis;
| gpl-3.0 |
Sohalt/malp | app/src/main/java/org/gateshipone/malp/application/background/NotificationManager.java | 20104 | /*
* Copyright (C) 2017 Team Gateship-One
* (Hendrik Borghorst & Frederik Luetkes)
*
* The AUTHORS.md file contains a detailed contributors list:
* <https://github.com/gateship-one/malp/blob/master/AUTHORS.md>
*
* 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.gateshipone.malp.application.background;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.DrawFilter;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.VolumeProviderCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.support.v7.app.NotificationCompat;
import org.gateshipone.malp.R;
import org.gateshipone.malp.application.activities.MainActivity;
import org.gateshipone.malp.application.artworkdatabase.ArtworkManager;
import org.gateshipone.malp.application.utils.CoverBitmapLoader;
import org.gateshipone.malp.application.utils.FormatHelper;
import org.gateshipone.malp.mpdservice.handlers.serverhandler.MPDCommandHandler;
import org.gateshipone.malp.mpdservice.mpdprotocol.mpdobjects.MPDAlbum;
import org.gateshipone.malp.mpdservice.mpdprotocol.mpdobjects.MPDCurrentStatus;
import org.gateshipone.malp.mpdservice.mpdprotocol.mpdobjects.MPDTrack;
public class NotificationManager implements CoverBitmapLoader.CoverBitmapListener, ArtworkManager.onNewAlbumImageListener {
private static final String TAG = NotificationManager.class.getSimpleName();
private static final int NOTIFICATION_ID = 0;
private BackgroundService mService;
/**
* Intent IDs used for controlling action.
*/
private final static int INTENT_OPENGUI = 0;
private final static int INTENT_PREVIOUS = 1;
private final static int INTENT_PLAYPAUSE = 2;
private final static int INTENT_STOP = 3;
private final static int INTENT_NEXT = 4;
private final static int INTENT_QUIT = 5;
// Notification objects
private final android.app.NotificationManager mNotificationManager;
private NotificationCompat.Builder mNotificationBuilder = null;
// Notification itself
private Notification mNotification;
// Save last track and last image
private Bitmap mLastBitmap = null;
/**
* Last state of the MPD server
*/
private MPDCurrentStatus mLastStatus = null;
/**
* Last played track of the MPD server. Used to check if track changed and a new cover is necessary.
*/
private MPDTrack mLastTrack = null;
/**
* State of the notification and the media session.
*/
private boolean mSessionActive;
/**
* Loader to asynchronously load cover images.
*/
private CoverBitmapLoader mCoverLoader;
/**
* Mediasession to set the lockscreen picture as well
*/
private MediaSessionCompat mMediaSession;
/**
* {@link VolumeProviderCompat} to react to volume changes over the hardware keys by the user.
* Only active as long as the notification is active.
*/
private MALPVolumeControlProvider mVolumeControlProvider;
public NotificationManager(BackgroundService service) {
mService = service;
mNotificationManager = (android.app.NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);
mLastStatus = new MPDCurrentStatus();
mLastTrack = new MPDTrack("");
/**
* Create loader to asynchronously load cover images. This class is the callback (s. receiveBitmap)
*/
mCoverLoader = new CoverBitmapLoader(mService, this);
ArtworkManager.getInstance(service).registerOnNewAlbumImageListener(this);
}
/**
* Shows the notification
*/
public void showNotification() {
if (mMediaSession == null) {
mMediaSession = new MediaSessionCompat(mService, mService.getString(R.string.app_name));
mMediaSession.setCallback(new MALPMediaSessionCallback());
mVolumeControlProvider = new MALPVolumeControlProvider();
mMediaSession.setPlaybackToRemote(mVolumeControlProvider);
mMediaSession.setActive(true);
}
mService.startForeground(NOTIFICATION_ID, mNotification);
updateNotification(mLastTrack, mLastStatus.getPlaybackState());
mSessionActive = true;
}
/**
* Hides the notification (if shown) and resets state variables.
*/
public void hideNotification() {
if (mMediaSession != null) {
mMediaSession.setActive(false);
mMediaSession.release();
mMediaSession = null;
}
mNotificationManager.cancel(NOTIFICATION_ID);
if (mNotification != null) {
mService.stopForeground(true);
mNotification = null;
mNotificationBuilder = null;
}
mSessionActive = false;
}
/*
* Creates a android system notification with two different remoteViews. One
* for the normal layout and one for the big one. Sets the different
* attributes of the remoteViews and starts a thread for Cover generation.
*/
public synchronized void updateNotification(MPDTrack track, MPDCurrentStatus.MPD_PLAYBACK_STATE state) {
if (track != null) {
mNotificationBuilder = new NotificationCompat.Builder(mService);
// Open application intent
Intent contentIntent = new Intent(mService, MainActivity.class);
contentIntent.putExtra(MainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW, MainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW_NOWPLAYINGVIEW);
contentIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NO_HISTORY);
PendingIntent contentPendingIntent = PendingIntent.getActivity(mService, INTENT_OPENGUI, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationBuilder.setContentIntent(contentPendingIntent);
// Set pendingintents
// Previous song action
Intent prevIntent = new Intent(BackgroundService.ACTION_PREVIOUS);
PendingIntent prevPendingIntent = PendingIntent.getBroadcast(mService, INTENT_PREVIOUS, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action prevAction = new NotificationCompat.Action.Builder(R.drawable.ic_skip_previous_48dp, "Previous", prevPendingIntent).build();
// Pause/Play action
PendingIntent playPauseIntent;
int playPauseIcon;
if (state == MPDCurrentStatus.MPD_PLAYBACK_STATE.MPD_PLAYING) {
Intent pauseIntent = new Intent(BackgroundService.ACTION_PAUSE);
playPauseIntent = PendingIntent.getBroadcast(mService, INTENT_PLAYPAUSE, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
playPauseIcon = R.drawable.ic_pause_48dp;
} else {
Intent playIntent = new Intent(BackgroundService.ACTION_PLAY);
playPauseIntent = PendingIntent.getBroadcast(mService, INTENT_PLAYPAUSE, playIntent, PendingIntent.FLAG_UPDATE_CURRENT);
playPauseIcon = R.drawable.ic_play_arrow_48dp;
}
NotificationCompat.Action playPauseAction = new NotificationCompat.Action.Builder(playPauseIcon, "PlayPause", playPauseIntent).build();
// Stop action
Intent stopIntent = new Intent(BackgroundService.ACTION_STOP);
PendingIntent stopPendingIntent = PendingIntent.getBroadcast(mService, INTENT_STOP, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action stopActon = new NotificationCompat.Action.Builder(R.drawable.ic_stop_black_48dp, "Stop", stopPendingIntent).build();
// Next song action
Intent nextIntent = new Intent(BackgroundService.ACTION_NEXT);
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(mService, INTENT_NEXT, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action nextAction = new NotificationCompat.Action.Builder(R.drawable.ic_skip_next_48dp, "Next", nextPendingIntent).build();
// Quit action
Intent quitIntent = new Intent(BackgroundService.ACTION_QUIT_BACKGROUND_SERVICE);
PendingIntent quitPendingIntent = PendingIntent.getBroadcast(mService, INTENT_QUIT, quitIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mNotificationBuilder.setDeleteIntent(quitPendingIntent);
mNotificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
mNotificationBuilder.setSmallIcon(R.drawable.ic_notification_24dp);
mNotificationBuilder.addAction(prevAction);
mNotificationBuilder.addAction(playPauseAction);
mNotificationBuilder.addAction(stopActon);
mNotificationBuilder.addAction(nextAction);
NotificationCompat.MediaStyle notificationStyle = new NotificationCompat.MediaStyle();
notificationStyle.setShowActionsInCompactView(1, 2);
mNotificationBuilder.setStyle(notificationStyle);
String title;
if (track.getTrackTitle().isEmpty()) {
title = FormatHelper.getFilenameFromPath(track.getPath());
} else {
title = track.getTrackTitle();
}
mNotificationBuilder.setContentTitle(title);
String secondRow;
if (!track.getTrackArtist().isEmpty() && !track.getTrackAlbum().isEmpty()) {
secondRow = track.getTrackArtist() + mService.getString(R.string.track_item_separator) + track.getTrackAlbum();
} else if (track.getTrackArtist().isEmpty() && !track.getTrackAlbum().isEmpty()) {
secondRow = track.getTrackAlbum();
} else if (track.getTrackAlbum().isEmpty() && !track.getTrackArtist().isEmpty()) {
secondRow = track.getTrackArtist();
} else {
secondRow = track.getPath();
}
// Set the media session metadata
updateMetadata(track, state);
mNotificationBuilder.setContentText(secondRow);
// Remove unnecessary time info
mNotificationBuilder.setWhen(0);
// Cover but only if changed
if (mNotification == null || !track.getTrackAlbum().equals(mLastTrack.getTrackAlbum())) {
mLastTrack = track;
mLastBitmap = null;
mCoverLoader.getImage(mLastTrack, true);
}
// Only set image if an saved one is available
if (mLastBitmap != null) {
mNotificationBuilder.setLargeIcon(mLastBitmap);
} else {
/**
* Create a dummy placeholder image for versions greater android 7 because it
* does not automatically show the application icon anymore in mediastyle notifications.
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Drawable icon = mService.getDrawable(R.drawable.notification_placeholder_256dp);
Bitmap iconBitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(iconBitmap);
DrawFilter filter = new PaintFlagsDrawFilter(Paint.ANTI_ALIAS_FLAG, 1);
canvas.setDrawFilter(filter);
icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
icon.setFilterBitmap(true);
icon.draw(canvas);
mNotificationBuilder.setLargeIcon(iconBitmap);
} else {
/**
* For older android versions set the null icon which will result in a dummy icon
* generated from the application icon.
*/
mNotificationBuilder.setLargeIcon(null);
}
}
// Build the notification
mNotification = mNotificationBuilder.build();
// Send the notification away
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
}
/**
* Updates the Metadata from Androids MediaSession. This sets track/album and stuff
* for a lockscreen image for example.
*
* @param track Current track.
* @param playbackState State of the PlaybackService.
*/
private void updateMetadata(MPDTrack track, MPDCurrentStatus.MPD_PLAYBACK_STATE playbackState) {
if (track != null) {
if (playbackState == MPDCurrentStatus.MPD_PLAYBACK_STATE.MPD_PLAYING) {
mMediaSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_PLAYING, 0, 1.0f)
.setActions(PlaybackStateCompat.ACTION_SKIP_TO_NEXT + PlaybackStateCompat.ACTION_PAUSE +
PlaybackStateCompat.ACTION_PLAY + PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS +
PlaybackStateCompat.ACTION_STOP + PlaybackStateCompat.ACTION_SEEK_TO).build());
} else {
mMediaSession.setPlaybackState(new PlaybackStateCompat.Builder().
setState(PlaybackStateCompat.STATE_PAUSED, 0, 1.0f).setActions(PlaybackStateCompat.ACTION_SKIP_TO_NEXT +
PlaybackStateCompat.ACTION_PAUSE + PlaybackStateCompat.ACTION_PLAY +
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS + PlaybackStateCompat.ACTION_STOP +
PlaybackStateCompat.ACTION_SEEK_TO).build());
}
// Try to get old metadata to save image retrieval.
MediaMetadataCompat oldData = mMediaSession.getController().getMetadata();
MediaMetadataCompat.Builder metaDataBuilder;
if (oldData == null) {
metaDataBuilder = new MediaMetadataCompat.Builder();
} else {
metaDataBuilder = new MediaMetadataCompat.Builder(mMediaSession.getController().getMetadata());
}
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, track.getTrackTitle());
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, track.getTrackAlbum());
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, track.getTrackArtist());
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, track.getTrackArtist());
metaDataBuilder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, track.getTrackTitle());
metaDataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, track.getTrackNumber());
metaDataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, track.getLength());
mMediaSession.setMetadata(metaDataBuilder.build());
}
}
/**
* Notifies about a change in MPDs status. If not shown this may be used later.
*
* @param status New MPD status
*/
public void setMPDStatus(MPDCurrentStatus status) {
if (mSessionActive) {
updateNotification(mLastTrack, status.getPlaybackState());
// Notify the mediasession about the new volume
mVolumeControlProvider.setCurrentVolume(status.getVolume());
}
// Save for later usage
mLastStatus = status;
}
/**
* Notifies about a change in MPDs track. If not shown this may be used later.
*
* @param track New MPD track
*/
public void setMPDFile(MPDTrack track) {
if (mSessionActive) {
updateNotification(track, mLastStatus.getPlaybackState());
}
// Save for later usage
mLastTrack = track;
}
/*
* Receives the generated album picture from the main status helper for the
* notification controls. Sets it and notifies the system that the
* notification has changed
*/
@Override
public synchronized void receiveBitmap(Bitmap bm, final CoverBitmapLoader.IMAGE_TYPE type) {
// Check if notification exists and set picture
mLastBitmap = bm;
if (type == CoverBitmapLoader.IMAGE_TYPE.ALBUM_IMAGE && mNotification != null && bm != null) {
mNotificationBuilder.setLargeIcon(bm);
mNotification = mNotificationBuilder.build();
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
/* Set lockscreen picture and stuff */
if (mMediaSession != null) {
MediaMetadataCompat.Builder metaDataBuilder;
metaDataBuilder = new MediaMetadataCompat.Builder(mMediaSession.getController().getMetadata());
metaDataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bm);
mMediaSession.setMetadata(metaDataBuilder.build());
}
}
}
@Override
public void newAlbumImage(MPDAlbum album) {
if (mLastTrack.getTrackAlbum().equals(album.getName())) {
mCoverLoader.getImage(mLastTrack, true);
}
}
/**
* Callback class for MediaControls controlled by android system like BT remotes, etc and
* Volume keys on some android versions.
*/
private class MALPMediaSessionCallback extends MediaSessionCompat.Callback {
@Override
public void onPlay() {
super.onPlay();
MPDCommandHandler.togglePause();
}
@Override
public void onPause() {
super.onPause();
MPDCommandHandler.togglePause();
}
@Override
public void onSkipToNext() {
super.onSkipToNext();
MPDCommandHandler.nextSong();
}
@Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
MPDCommandHandler.previousSong();
}
@Override
public void onStop() {
super.onStop();
MPDCommandHandler.stop();
}
@Override
public void onSeekTo(long pos) {
super.onSeekTo(pos);
MPDCommandHandler.seekSeconds((int) pos);
}
}
/**
* Handles volume changes from mediasession callbacks. Will send user requested changes
* in volume back to the MPD server.
*/
private class MALPVolumeControlProvider extends VolumeProviderCompat {
public MALPVolumeControlProvider() {
super(VOLUME_CONTROL_ABSOLUTE, 100, mLastStatus.getVolume());
}
@Override
public void onSetVolumeTo(int volume) {
MPDCommandHandler.setVolume(volume);
setCurrentVolume(volume);
}
@Override
public void onAdjustVolume(int direction) {
if (direction == 1) {
MPDCommandHandler.increaseVolume();
} else if (direction == -1) {
MPDCommandHandler.decreaseVolume();
}
}
}
}
| gpl-3.0 |
idega/com.idega.builder | src/java/com/idega/builder/presentation/AddModuleBlock.java | 8828 | package com.idega.builder.presentation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ejb.FinderException;
import com.idega.builder.business.BuilderConstants;
import com.idega.builder.business.ICObjectComparator;
import com.idega.core.accesscontrol.business.StandardRoles;
import com.idega.core.component.data.ICObject;
import com.idega.core.component.data.ICObjectBMPBean;
import com.idega.core.component.data.ICObjectHome;
import com.idega.data.IDOLookup;
import com.idega.data.IDOLookupException;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.Image;
import com.idega.presentation.Layer;
import com.idega.presentation.Span;
import com.idega.presentation.text.Heading3;
import com.idega.presentation.text.ListItem;
import com.idega.presentation.text.Lists;
import com.idega.presentation.text.Text;
public class AddModuleBlock extends Block {
private Map<String, List<ICObject>> addedTabs = new HashMap<String, List<ICObject>>();
private String localizedText = "Sorry, there are no components available.";
private boolean isBuilderUser(IWContext iwc) {
if (iwc.hasRole(StandardRoles.ROLE_KEY_BUILDER)) {
return true;
}
if (iwc.hasRole(StandardRoles.ROLE_KEY_EDITOR)) {
return true;
}
return iwc.hasRole(StandardRoles.ROLE_KEY_AUTHOR);
}
@Override
public String getBundleIdentifier() {
return BuilderConstants.IW_BUNDLE_IDENTIFIER;
}
@Override
public void main(IWContext iwc) throws Exception {
IWResourceBundle iwrb = getResourceBundle(iwc);
boolean isBuilderUser = isBuilderUser(iwc);
localizedText = iwrb.getLocalizedString("no_components_available", localizedText);
Collection<ICObject> allComoponents = getAllComponents();
Layer container = new Layer();
container.setStyleClass("addModuleContainer");
add(container);
// Header
/*Layer header = new Layer();
String regionName = iwc.getParameter(BuilderConstants.REGION_NAME);
StringBuffer label = new StringBuffer(iwrb.getLocalizedString(BuilderConstants.ADD_MODULE_TO_REGION_LOCALIZATION_KEY,
BuilderConstants.ADD_MODULE_TO_REGION_LOCALIZATION_VALUE));
if (regionName != null && !(CoreConstants.EMPTY.equals(regionName))) {
label.append(CoreConstants.SPACE).append(iwrb.getLocalizedString("to", "to")).append(CoreConstants.SPACE).append(iwrb.getLocalizedString("region", "region"));
label.append(CoreConstants.SPACE).append(regionName);
}
header.add(new Heading1(label.toString()));
header.setStyleClass("addModuleToBuilderPage");
container.add(header);*/
Lists titles = new Lists();
titles.setStyleClass("mootabs_title");
List<ICObject> widgets = getConcreteComponents(iwc, allComoponents, true, false, false);
if (widgets != null && widgets.size() > 0) {
addComponentsTitles(titles, widgets, "widgetsTab", iwrb.getLocalizedString("widget_modules", "Widgets"));
}
List<ICObject> blocks = getConcreteComponents(iwc, allComoponents, false, true, false);
if (blocks != null && blocks.size() > 0) {
addComponentsTitles(titles, blocks, "blocksTab", iwrb.getLocalizedString("blocks_header", "Blocks"));
}
List<ICObject> builderComponents = null;
if (isBuilderUser) {
builderComponents = getConcreteComponents(iwc, allComoponents, false, false, true);
if (builderComponents != null && builderComponents.size() > 0) {
addComponentsTitles(titles, builderComponents, "builderTab", iwrb.getLocalizedString("builder_modules", "Builder"));
}
}
if (addedTabs.size() == 0) {
container.add(new Heading3(localizedText));
return;
}
container.add(titles);
String key = null;
for (Iterator<String> keys = addedTabs.keySet().iterator(); keys.hasNext();) {
key = keys.next();
Layer componentsListContainer = new Layer();
componentsListContainer.setStyleClass("mootabs_panel");
componentsListContainer.setId(key);
addListToWindow(iwc, addedTabs.get(key), componentsListContainer);
container.add(componentsListContainer);
}
Layer script = new Layer();
script.add(new StringBuffer("<script type=\"text/javascript\">createTabsWithMootabs('").append(container.getId()).append("'); closeAllLoadingMessages();</script>").toString());
container.add(script);
}
private void addComponentsTitles(Lists titles, List<ICObject> components, String tabText, String text) {
ListItem tab = new ListItem();
tab.setMarkupAttribute("title", tabText);
tab.addText(text);
titles.add(tab);
addedTabs.put(tabText, components);
}
private void addListToWindow(IWContext iwc, List<ICObject> objects, Layer container) {
if (objects == null || objects.size() == 0) {
container.add(localizedText);
return;
}
Lists items = new Lists();
String itemStyleClass = "modulesListItemStyle";
ListItem item = new ListItem();
String actionDefinition = "onclick";
ICObject object = null;
for (int i = 0; i < objects.size(); i++) {
object = objects.get(i);
String iconURI = object.getIconURI();
//IWBundle iwb = object.getBundle(iwc.getIWMainApplication());
//IWResourceBundle iwrb = iwb.getResourceBundle(iwc);
item = new ListItem();
item.setStyleClass(itemStyleClass);
item.attributes.put(actionDefinition, new StringBuffer("addSelectedModule(").append(object.getID()).append(", '").append(object.getClassName()).append("');").toString());
items.add(item);
if (iconURI != null) {
Image image = new Image(iconURI);
image.setAlt(object.getName());
item.add(image);
}
Span span = new Span();
span.setStyleClass("objectName");
//span.add(new Text(iwrb.getLocalizedString("iw.component." + object.getClassName(), object.getName())));
span.add(new Text(object.getName()));
item.add(span);
span = new Span();
span.setStyleClass("objectDescription");
//span.add(new Text(iwrb.getLocalizedString("iw.component.description." + object.getName(), "Descripition for item " + object.getName())));
span.add(new Text("Descripition for item " + object.getName()));
item.add(span);
}
container.add(items);
}
private List<ICObject> getConcreteComponents(IWContext iwc, Collection<ICObject> allComponents, boolean findWidgets, boolean findBlocks, boolean findBuilder) {
List<ICObject> components = new ArrayList<ICObject>();
List<String> namesList = new ArrayList<String>();
if (allComponents == null) {
return components;
}
ICObject object = null;
// Find "widget" type modules
if (findWidgets) {
for (Iterator<ICObject> it = allComponents.iterator(); it.hasNext(); ) {
object = it.next();
if (object.isWidget()) {
addComponent(components, object, namesList);
}
}
return getSortedComponents(components);
}
// Find "block" type modules
if (findBlocks) {
for (Iterator<ICObject> it = allComponents.iterator(); it.hasNext(); ) {
object = it.next();
if (object.isBlock()) {
if (!components.contains(object)) {
addComponent(components, object, namesList);
}
}
}
return getSortedComponents(components);
}
// Find all other Builder/Development modules
List<String> componentTypes = Arrays.asList(new String[] {ICObjectBMPBean.COMPONENT_TYPE_ELEMENT, ICObjectBMPBean.COMPONENT_TYPE_BLOCK,
ICObjectBMPBean.COMPONENT_TYPE_JSFUICOMPONENT});
for (Iterator<ICObject> it = allComponents.iterator(); it.hasNext(); ) {
object = it.next();
if (!object.isBlock() && !object.isWidget()) {
if (componentTypes.contains(object.getObjectType())) {
addComponent(components, object, namesList);
}
}
}
return getSortedComponents(components);
}
private List<ICObject> getSortedComponents(List<ICObject> components) {
if (components == null) {
return null;
}
ICObjectComparator comparator = new ICObjectComparator();
Collections.sort(components, comparator);
return components;
}
private void addComponent(List<ICObject> components, ICObject component, List<String> namesList) {
if (component == null || components == null || namesList == null) {
return;
}
if (namesList.contains(component.getClassName())) {
return;
}
namesList.add(component.getClassName());
components.add(component);
}
private Collection<ICObject> getAllComponents() {
ICObjectHome icoHome = null;
try {
icoHome = (ICObjectHome) IDOLookup.getHome(ICObject.class);
} catch (IDOLookupException e) {
e.printStackTrace();
}
if (icoHome == null) {
return null;
}
try {
return icoHome.findAll();
} catch (FinderException e) {
e.printStackTrace();
}
return null;
}
}
| gpl-3.0 |
blinkdog/xcom | src/main/java/com/rpgsheet/xcom/io/ScrInputStream.java | 1727 | /*
* ScrInputStream.java
* Copyright 2012 Patrick Meade
*
* 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.rpgsheet.xcom.io;
import com.rpgsheet.xcom.slick.Palette;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.newdawn.slick.Color;
import org.newdawn.slick.Image;
import org.newdawn.slick.ImageBuffer;
public class ScrInputStream
{
public ScrInputStream(InputStream inputStream)
{
this.dataInputStream = new DataInputStream(inputStream);
}
public Image readImage(Palette palette) throws IOException
{
ImageBuffer imageBuffer = new ImageBuffer(320, 200);
for(int y=0; y<200; y++) {
for(int x=0; x<320; x++) {
int color = dataInputStream.readUnsignedByte();
Color c = palette.getColor(color & (palette.getNumColors()-1));
imageBuffer.setRGBA(x, y, c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
}
}
return imageBuffer.getImage(Image.FILTER_NEAREST);
}
private DataInputStream dataInputStream;
}
| gpl-3.0 |
stinsonga/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/util/BitmapUtil.java | 18105 | package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;
import androidx.exifinterface.media.ExifInterface;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import org.signal.core.util.ThreadUtil;
import org.signal.core.util.logging.Log;
import org.thoughtcrime.securesms.mms.GlideApp;
import org.thoughtcrime.securesms.mms.MediaConstraints;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
public class BitmapUtil {
private static final String TAG = BitmapUtil.class.getSimpleName();
private static final int MAX_COMPRESSION_QUALITY = 90;
private static final int MIN_COMPRESSION_QUALITY = 45;
private static final int MAX_COMPRESSION_ATTEMPTS = 5;
private static final int MIN_COMPRESSION_QUALITY_DECREASE = 5;
private static final int MAX_IMAGE_HALF_SCALES = 3;
/**
* @deprecated You probably want to use {@link ImageCompressionUtil} instead, which has a clearer
* contract and handles mimetypes properly.
*/
@Deprecated
@WorkerThread
public static <T> ScaleResult createScaledBytes(@NonNull Context context, @NonNull T model, @NonNull MediaConstraints constraints)
throws BitmapDecodingException
{
return createScaledBytes(context, model,
constraints.getImageMaxWidth(context),
constraints.getImageMaxHeight(context),
constraints.getImageMaxSize(context));
}
/**
* @deprecated You probably want to use {@link ImageCompressionUtil} instead, which has a clearer
* contract and handles mimetypes properly.
*/
@WorkerThread
public static <T> ScaleResult createScaledBytes(@NonNull Context context,
@NonNull T model,
final int maxImageWidth,
final int maxImageHeight,
final int maxImageSize)
throws BitmapDecodingException
{
return createScaledBytes(context, model, maxImageWidth, maxImageHeight, maxImageSize, CompressFormat.JPEG);
}
/**
* @deprecated You probably want to use {@link ImageCompressionUtil} instead, which has a clearer
* contract and handles mimetypes properly.
*/
@WorkerThread
public static <T> ScaleResult createScaledBytes(Context context,
T model,
int maxImageWidth,
int maxImageHeight,
int maxImageSize,
@NonNull CompressFormat format)
throws BitmapDecodingException
{
return createScaledBytes(context, model, maxImageWidth, maxImageHeight, maxImageSize, format, 1, 0);
}
@WorkerThread
private static <T> ScaleResult createScaledBytes(@NonNull Context context,
@NonNull T model,
final int maxImageWidth,
final int maxImageHeight,
final int maxImageSize,
@NonNull CompressFormat format,
final int sizeAttempt,
int totalAttempts)
throws BitmapDecodingException
{
try {
int quality = MAX_COMPRESSION_QUALITY;
int attempts = 0;
byte[] bytes;
Bitmap scaledBitmap = GlideApp.with(context.getApplicationContext())
.asBitmap()
.load(model)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.centerInside()
.submit(maxImageWidth, maxImageHeight)
.get();
if (scaledBitmap == null) {
throw new BitmapDecodingException("Unable to decode image");
}
Log.i(TAG, String.format(Locale.US,"Initial scaled bitmap has size of %d bytes.", scaledBitmap.getByteCount()));
Log.i(TAG, String.format(Locale.US, "Max dimensions %d x %d, %d bytes", maxImageWidth, maxImageHeight, maxImageSize));
try {
do {
totalAttempts++;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
scaledBitmap.compress(format, quality, baos);
bytes = baos.toByteArray();
Log.d(TAG, "iteration with quality " + quality + " size " + bytes.length + " bytes.");
if (quality == MIN_COMPRESSION_QUALITY) break;
int nextQuality = (int)Math.floor(quality * Math.sqrt((double)maxImageSize / bytes.length));
if (quality - nextQuality < MIN_COMPRESSION_QUALITY_DECREASE) {
nextQuality = quality - MIN_COMPRESSION_QUALITY_DECREASE;
}
quality = Math.max(nextQuality, MIN_COMPRESSION_QUALITY);
}
while (bytes.length > maxImageSize && attempts++ < MAX_COMPRESSION_ATTEMPTS);
if (bytes.length > maxImageSize) {
if (sizeAttempt <= MAX_IMAGE_HALF_SCALES) {
scaledBitmap.recycle();
scaledBitmap = null;
Log.i(TAG, "Halving dimensions and retrying.");
return createScaledBytes(context, model, maxImageWidth / 2, maxImageHeight / 2, maxImageSize, format, sizeAttempt + 1, totalAttempts);
} else {
throw new BitmapDecodingException("Unable to scale image below " + bytes.length + " bytes.");
}
}
if (bytes.length <= 0) {
throw new BitmapDecodingException("Decoding failed. Bitmap has a length of " + bytes.length + " bytes.");
}
Log.i(TAG, String.format(Locale.US, "createScaledBytes(%s) -> quality %d, %d attempt(s) over %d sizes.", model.getClass().getName(), quality, totalAttempts, sizeAttempt));
return new ScaleResult(bytes, scaledBitmap.getWidth(), scaledBitmap.getHeight());
} finally {
if (scaledBitmap != null) scaledBitmap.recycle();
}
} catch (InterruptedException | ExecutionException e) {
throw new BitmapDecodingException(e);
}
}
@WorkerThread
public static <T> Bitmap createScaledBitmap(Context context, T model, int maxWidth, int maxHeight)
throws BitmapDecodingException
{
try {
return GlideApp.with(context.getApplicationContext())
.asBitmap()
.load(model)
.centerInside()
.submit(maxWidth, maxHeight)
.get();
} catch (InterruptedException | ExecutionException e) {
throw new BitmapDecodingException(e);
}
}
@WorkerThread
public static Bitmap createScaledBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
if (bitmap.getWidth() <= maxWidth && bitmap.getHeight() <= maxHeight) {
return bitmap;
}
if (maxWidth <= 0 || maxHeight <= 0) {
return bitmap;
}
int newWidth = maxWidth;
int newHeight = maxHeight;
float widthRatio = bitmap.getWidth() / (float) maxWidth;
float heightRatio = bitmap.getHeight() / (float) maxHeight;
if (widthRatio > heightRatio) {
newHeight = (int) (bitmap.getHeight() / widthRatio);
} else {
newWidth = (int) (bitmap.getWidth() / heightRatio);
}
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
public static @NonNull CompressFormat getCompressFormatForContentType(@Nullable String contentType) {
if (contentType == null) return CompressFormat.JPEG;
switch (contentType) {
case MediaUtil.IMAGE_JPEG: return CompressFormat.JPEG;
case MediaUtil.IMAGE_PNG: return CompressFormat.PNG;
case MediaUtil.IMAGE_WEBP: return CompressFormat.WEBP;
default: return CompressFormat.JPEG;
}
}
private static BitmapFactory.Options getImageDimensions(InputStream inputStream)
throws BitmapDecodingException
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BufferedInputStream fis = new BufferedInputStream(inputStream);
BitmapFactory.decodeStream(fis, null, options);
try {
fis.close();
} catch (IOException ioe) {
Log.w(TAG, "failed to close the InputStream after reading image dimensions");
}
if (options.outWidth == -1 || options.outHeight == -1) {
throw new BitmapDecodingException("Failed to decode image dimensions: " + options.outWidth + ", " + options.outHeight);
}
return options;
}
@Nullable
public static Pair<Integer, Integer> getExifDimensions(InputStream inputStream) throws IOException {
ExifInterface exif = new ExifInterface(inputStream);
int width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0);
int height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0);
if (width == 0 || height == 0) {
return null;
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
if (orientation == ExifInterface.ORIENTATION_ROTATE_90 ||
orientation == ExifInterface.ORIENTATION_ROTATE_270 ||
orientation == ExifInterface.ORIENTATION_TRANSVERSE ||
orientation == ExifInterface.ORIENTATION_TRANSPOSE)
{
return new Pair<>(height, width);
}
return new Pair<>(width, height);
}
public static Pair<Integer, Integer> getDimensions(InputStream inputStream) throws BitmapDecodingException {
BitmapFactory.Options options = getImageDimensions(inputStream);
return new Pair<>(options.outWidth, options.outHeight);
}
public static InputStream toCompressedJpeg(Bitmap bitmap) {
ByteArrayOutputStream thumbnailBytes = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 85, thumbnailBytes);
return new ByteArrayInputStream(thumbnailBytes.toByteArray());
}
public static @Nullable byte[] toByteArray(@Nullable Bitmap bitmap) {
if (bitmap == null) return null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
public static @Nullable byte[] toWebPByteArray(@Nullable Bitmap bitmap) {
if (bitmap == null) return null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if (Build.VERSION.SDK_INT >= 30) {
bitmap.compress(CompressFormat.WEBP_LOSSLESS, 100, stream);
} else {
bitmap.compress(CompressFormat.WEBP, 100, stream);
}
return stream.toByteArray();
}
public static @Nullable Bitmap fromByteArray(@Nullable byte[] bytes) {
if (bytes == null) return null;
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
public static byte[] createFromNV21(@NonNull final byte[] data,
final int width,
final int height,
int rotation,
final Rect croppingRect,
final boolean flipHorizontal)
throws IOException
{
byte[] rotated = rotateNV21(data, width, height, rotation, flipHorizontal);
final int rotatedWidth = rotation % 180 > 0 ? height : width;
final int rotatedHeight = rotation % 180 > 0 ? width : height;
YuvImage previewImage = new YuvImage(rotated, ImageFormat.NV21,
rotatedWidth, rotatedHeight, null);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
previewImage.compressToJpeg(croppingRect, 80, outputStream);
byte[] bytes = outputStream.toByteArray();
outputStream.close();
return bytes;
}
/*
* NV21 a.k.a. YUV420sp
* YUV 4:2:0 planar image, with 8 bit Y samples, followed by interleaved V/U plane with 8bit 2x2
* subsampled chroma samples.
*
* http://www.fourcc.org/yuv.php#NV21
*/
public static byte[] rotateNV21(@NonNull final byte[] yuv,
final int width,
final int height,
final int rotation,
final boolean flipHorizontal)
throws IOException
{
if (rotation == 0) return yuv;
if (rotation % 90 != 0 || rotation < 0 || rotation > 270) {
throw new IllegalArgumentException("0 <= rotation < 360, rotation % 90 == 0");
} else if ((width * height * 3) / 2 != yuv.length) {
throw new IOException("provided width and height don't jive with the data length (" +
yuv.length + "). Width: " + width + " height: " + height +
" = data length: " + (width * height * 3) / 2);
}
final byte[] output = new byte[yuv.length];
final int frameSize = width * height;
final boolean swap = rotation % 180 != 0;
final boolean xflip = flipHorizontal ? rotation % 270 == 0 : rotation % 270 != 0;
final boolean yflip = rotation >= 180;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
final int yIn = j * width + i;
final int uIn = frameSize + (j >> 1) * width + (i & ~1);
final int vIn = uIn + 1;
final int wOut = swap ? height : width;
final int hOut = swap ? width : height;
final int iSwapped = swap ? j : i;
final int jSwapped = swap ? i : j;
final int iOut = xflip ? wOut - iSwapped - 1 : iSwapped;
final int jOut = yflip ? hOut - jSwapped - 1 : jSwapped;
final int yOut = jOut * wOut + iOut;
final int uOut = frameSize + (jOut >> 1) * wOut + (iOut & ~1);
final int vOut = uOut + 1;
output[yOut] = (byte)(0xff & yuv[yIn]);
output[uOut] = (byte)(0xff & yuv[uIn]);
output[vOut] = (byte)(0xff & yuv[vIn]);
}
}
return output;
}
public static Bitmap createFromDrawable(final Drawable drawable, final int width, final int height) {
final AtomicBoolean created = new AtomicBoolean(false);
final Bitmap[] result = new Bitmap[1];
Runnable runnable = new Runnable() {
@Override
public void run() {
if (drawable instanceof BitmapDrawable) {
result[0] = ((BitmapDrawable) drawable).getBitmap();
} else {
int canvasWidth = drawable.getIntrinsicWidth();
if (canvasWidth <= 0) canvasWidth = width;
int canvasHeight = drawable.getIntrinsicHeight();
if (canvasHeight <= 0) canvasHeight = height;
Bitmap bitmap;
try {
bitmap = Bitmap.createBitmap(canvasWidth, canvasHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
} catch (Exception e) {
Log.w(TAG, e);
bitmap = null;
}
result[0] = bitmap;
}
synchronized (result) {
created.set(true);
result.notifyAll();
}
}
};
ThreadUtil.runOnMain(runnable);
synchronized (result) {
while (!created.get()) Util.wait(result, 0);
return result[0];
}
}
public static int getMaxTextureSize() {
final int MAX_ALLOWED_TEXTURE_SIZE = 2048;
EGL10 egl = (EGL10) EGLContext.getEGL();
EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(display, version);
int[] totalConfigurations = new int[1];
egl.eglGetConfigs(display, null, 0, totalConfigurations);
EGLConfig[] configurationsList = new EGLConfig[totalConfigurations[0]];
egl.eglGetConfigs(display, configurationsList, totalConfigurations[0], totalConfigurations);
int[] textureSize = new int[1];
int maximumTextureSize = 0;
for (int i = 0; i < totalConfigurations[0]; i++) {
egl.eglGetConfigAttrib(display, configurationsList[i], EGL10.EGL_MAX_PBUFFER_WIDTH, textureSize);
if (maximumTextureSize < textureSize[0])
maximumTextureSize = textureSize[0];
}
egl.eglTerminate(display);
return Math.min(maximumTextureSize, MAX_ALLOWED_TEXTURE_SIZE);
}
public static class ScaleResult {
private final byte[] bitmap;
private final int width;
private final int height;
public ScaleResult(byte[] bitmap, int width, int height) {
this.bitmap = bitmap;
this.width = width;
this.height = height;
}
public byte[] getBitmap() {
return bitmap;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
}
| gpl-3.0 |
NoCheatPlus/NoCheatPlus | NCPCore/src/main/java/fr/neatmonster/nocheatplus/components/registry/event/IUnregisterGenericInstanceRegistryListener.java | 1108 | /*
* 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 fr.neatmonster.nocheatplus.components.registry.event;
/**
* Allow to unregister listeners, should also disable internally created handles
* if they are this listener. Rather an internal interface.
*
* @author asofold
*
*/
public interface IUnregisterGenericInstanceRegistryListener {
public <T> void unregisterGenericInstanceRegistryListener(Class<T> registeredFor, IGenericInstanceRegistryListener<T> listener);
}
| gpl-3.0 |
kostovhg/SoftUni | Java Fundamentals-Sep17/Java_OOP_Advanced/t01_InterfacesAndAbstraction_E/src/p09_CollectionHierarchy/Main.java | 1874 | package p09_CollectionHierarchy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<String> collection = Arrays.stream(reader.readLine().split("\\s+"))
.collect(Collectors.toList());
AddRemoveCollection<String> addRemoveCollection = new AddRemoveCollectionImpl<>();
AddCollection<String> addCollection = new AddCollectionImpl<>();
MyList<String> myList = new MyListImpl<>();
int count = Integer.parseInt(reader.readLine());
StringBuilder addToAddCollection = new StringBuilder();
StringBuilder addToAddRemoveCollection = new StringBuilder();
StringBuilder addToMyList = new StringBuilder();
StringBuilder removeFromAddRemoveCollection = new StringBuilder();
StringBuilder removeFromMyList = new StringBuilder();
for (String element : collection) {
addToAddCollection.append(addCollection.add(element)).append(" ");
addToAddRemoveCollection.append(addRemoveCollection.add(element)).append(" ");
addToMyList.append(myList.add(element)).append(" ");
}
for (int i = 0; i < count; i++) {
removeFromAddRemoveCollection.append(addRemoveCollection.remove()).append(" ");
removeFromMyList.append(myList.remove()).append(" ");
}
System.out.println(addToAddCollection);
System.out.println(addToAddRemoveCollection);
System.out.println(addToMyList);
System.out.println(removeFromAddRemoveCollection);
System.out.println(removeFromMyList);
}
}
| gpl-3.0 |
adityayadav76/internet_of_things_simulator | AutoSIM-Environments/src/com/automatski/autosim/environments/utils/GsonUtils.java | 1519 | /*
* AutoSIM - Internet of Things Simulator
* Copyright (C) 2014, Aditya Yadav <aditya@automatski.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.automatski.autosim.environments.utils;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonUtils {
private static GsonBuilder builder = null;
static {
builder = new GsonBuilder();
builder.setPrettyPrinting().serializeNulls();
}
public static String objectToJson(Object obj) throws Exception {
Gson gson = builder.create();
return gson.toJson(obj);
}
public static Object jsonToObject(String path, Class clas) throws Exception {
Gson gson = builder.create();
String json = new String(Files.readAllBytes(Paths.get(path)));//"./albums.json")));
return gson.fromJson(json, clas);
}
}
| gpl-3.0 |
investovator/investovator-core | src/main/java/org/investovator/core/commons/events/GameEvent.java | 925 | /*
* investovator, Stock Market Gaming framework
* Copyright (C) 2013 investovator
*
* 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.investovator.core.commons.events;
import java.io.Serializable;
/**
* @author Amila Surendra
* @version $Revision
*/
public class GameEvent implements Serializable {
}
| gpl-3.0 |
sanger-pathogens/Artemis | src/test/evosuite/org/gmod/schema/general/Tableinfo_ESTest.java | 686 | /*
* This file was automatically generated by EvoSuite
* Thu Sep 20 14:03:48 GMT 2018
*/
package org.gmod.schema.general;
import org.junit.Test;
import static org.junit.Assert.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.gmod.schema.general.Tableinfo;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true)
public class Tableinfo_ESTest extends Tableinfo_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
Tableinfo tableinfo0 = new Tableinfo();
}
}
| gpl-3.0 |
LokeshSreekanta/TurtleGraphicsDesignPatterns | src/coordinateSystem/Point.java | 318 | package coordinateSystem;
public class Point {
private double x;
private double y;
public Point() {
this.setX(0);
this.setY(0);
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
| gpl-3.0 |
chvink/kilomek | megamek/src/megamek/common/weapons/battlearmor/ISBAERSmallLaser.java | 1993 | /**
* MegaMek - Copyright (C) 2004,2005 Ben Mazur (bmazur@sev.org)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 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.
*/
/*
* Created on Sep 12, 2004
*
*/
package megamek.common.weapons.battlearmor;
import megamek.common.EquipmentType;
import megamek.common.TechConstants;
import megamek.common.weapons.LaserWeapon;
/**
* @author Andrew Hunter
*/
public class ISBAERSmallLaser extends LaserWeapon {
/**
*
*/
private static final long serialVersionUID = -4997798107691083605L;
/**
*
*/
public ISBAERSmallLaser() {
super();
techLevel.put(3071, TechConstants.T_IS_TW_NON_BOX);
name = "ER Small Laser";
setInternalName("ISBAERSmallLaser");
addLookupName("IS BA ER Small Laser");
damage = 3;
shortRange = 2;
mediumRange = 4;
longRange = 5;
extremeRange = 8;
waterShortRange = 1;
waterMediumRange = 2;
waterLongRange = 3;
waterExtremeRange = 4;
tonnage = 0.35f;
criticals = 2;
flags = flags.or(F_NO_FIRES).or(F_BA_WEAPON).andNot(F_MECH_WEAPON).andNot(F_TANK_WEAPON).andNot(F_AERO_WEAPON).andNot(F_PROTO_WEAPON);
bv = 17;
cost = 11250;
shortAV = 3;
maxRange = RANGE_SHORT;
availRating = new int[] { EquipmentType.RATING_X,
EquipmentType.RATING_X, EquipmentType.RATING_D };
introDate = 3058;
techRating = EquipmentType.RATING_E;
techLevel.put(3058, techLevel.get(3071));
}
}
| gpl-3.0 |
NevEagleson/EcoCraft | ecocraft/main/java/com/neveagleson/ecocraft/core/utility/PlayerEntityFilter.java | 436 | package com.neveagleson.ecocraft.core.utility;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
/**
* Created by NevEagleson on 4/03/2015
*/
public class PlayerEntityFilter extends EntityFilter
{
@Override
public boolean isEntityValid(EntityLivingBase entity)
{
return entity instanceof EntityPlayer != negate;
}
}
| gpl-3.0 |
Wehavecookies56/Kingdom-Keys | kk_common/wehavecookies56/kk/item/recipes/ItemSweetMemoriesRecipe.java | 1149 | package wehavecookies56.kk.item.recipes;
import java.util.List;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import wehavecookies56.kk.item.ItemKingdomKeys;
import wehavecookies56.kk.lib.LocalStrings;
import wehavecookies56.kk.lib.Reference;
import wehavecookies56.kk.lib.Strings;
public class ItemSweetMemoriesRecipe extends ItemKingdomKeys{
public ItemSweetMemoriesRecipe(int par1) {
super(par1);
}
public void registerIcons(IconRegister par1IconRegister) {
itemIcon = par1IconRegister.registerIcon(Reference.MOD_ID + ":" + this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".")+1));
}
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack itemStack, EntityPlayer player, List dataList, boolean bool){
dataList.add(LocalStrings.Sweetmemories);
}
public static final ResourceLocation texture = new ResourceLocation("kk", "textures/items/" + Strings.Sweetmemories + ".png");
}
| gpl-3.0 |
ferenc-hechler/RollenspielAlexaSkill | RoleplayMaster/RoleplayEngine/src/main/java/de/hechler/soloroleplay/data/Opponent.java | 4316 | /**
* Diese Datei ist Teil des Alexa Skills Rollenspiel Soloabenteuer.
* Copyright (C) 2016-2017 Ferenc Hechler (github@fh.anderemails.de)
*
* Der Alexa Skills Rollenspiel Soloabenteuer ist Freie Software:
* Sie koennen es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder spaeteren
* veroeffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Der Alexa Skills Rollenspiel Soloabenteuer wird in der Hoffnung,
* dass es nuetzlich sein wird, aber
* OHNE JEDE GEWAEHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewaehrleistung der MARKTFAEHIGKEIT oder EIGNUNG FUER EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License fuer weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*/
package de.hechler.soloroleplay.data;
import java.util.ArrayList;
import java.util.List;
import de.hechler.soloroleplay.util.TextUtil;
public class Opponent {
public enum OpponentType {
FRIEND, FOE
}
private RestrictedParameterMap parameters = new RestrictedParameterMap(new String[]
{"WAFFE", "AT", "PA", "TP", "DK", "LEP", "AP", "RS", "AUP", "GS", "MR", "MU", "KK", "GE", "CH", "IN", "WS", "KO"}
);
private List<String> additions = new ArrayList<String>();
private OpponentType type;
private String name;
private String gegnerText;
public Opponent(OpponentType type, String name, String gegnerText) {
this.type = type;
this.name = name;
this.gegnerText = gegnerText;
}
public String getName() {
return name;
}
public OpponentType getType() {
return type;
}
public String getTypeName() {
return type == OpponentType.FRIEND ? "Freund" : "Gegner";
}
public boolean knowsParameter(String name) {
return parameters.isAllowed(name);
}
public void addParameter(String name, String value) {
parameters.addParameter(name, value);
}
public String getParameter(String paramName) {
return parameters.getValue(paramName);
}
public void addAddition(String addition) {
additions.add(addition);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(getTypeName().toUpperCase()).append(": ").append(name).append(TextUtil.endl);
if (gegnerText != null) {
result.append("TEXT: ").append(gegnerText).append(TextUtil.endl);
}
result.append(parameters);
for (String addition:additions) {
result.append("ZUSATZ: ").append(addition).append(TextUtil.endl);
}
return result.toString();
}
public void describe(Response response) {
if (gegnerText != null) {
response.addDescription(gegnerText);
}
else {
response.addDescription(getTypeName()).addDescription(getName()+":");
describeParameter(response, "MU", "Mut");
describeParameter(response, "WAFFE", "Waffe");
describeParameter(response, "DK", "Distanzklasse");
describeParameter(response, "TP", "Trefferpunkte");
describeParameter(response, "AT", "Attacke");
describeParameter(response, "PA", "Parade");
describeParameter(response, "RS", "R"+TextUtil.UML_ue+"stungsschutz");
describeParameter(response, "LEP", "Lebenspunkte");
describeParameter(response, "AP", "Astralpunkte");
describeParameter(response, "AUP", "Ausdauerpunkte");
describeParameter(response, "GS", "Geschwindigkeit");
describeParameter(response, "MR", "Magieresistenz");
describeParameter(response, "KK", "K"+TextUtil.UML_oe+"rperkraft");
describeParameter(response, "GE", "Geschicklichkeit");
describeParameter(response, "CH", "Charisma");
describeParameter(response, "IN", "Intelligenz");
describeParameter(response, "WS", "Weisheit");
describeParameter(response, "KO", "Konstitution");
for (String addition:additions) {
response.addDescription(";").addDescription(TextUtil.handleMinus(addition));
}
}
response.addDescription(";");
}
private void describeParameter(Response response, String paramName, String plaintextName) {
String value = getParameter(paramName);
if ((value != null) && !value.trim().isEmpty()) {
response.addDescription(";").addDescription(plaintextName).addDescription(TextUtil.handleMinus(value));
}
}
}
| gpl-3.0 |
clementvillanueva/SimpleHDR | src/com/jidesoft/grouper/date/package-info.java | 123 | /**
* The package contains all kinds of date object groupers for JIDE Common Layer.
*/
package com.jidesoft.grouper.date; | gpl-3.0 |
defascat/presentation-tool | demo/src/main/java/org/defascat/presentation/basic/IntCache.java | 332 | package org.defascat.presentation.basic;
import java.util.Arrays;
import java.util.List;
/*
javap -c ../demo/target/classes/org/defascat/presentation/unsorted/IntCache.class
*/
public class IntCache {
public static void main(String[] args) {
List<Integer> a = Arrays.asList(22);
System.out.println(a);
}
}
| gpl-3.0 |
Foghrye4/ihl | src/main/java/ihl/processing/metallurgy/DetonationSprayingMachineContainer.java | 1679 | package ihl.processing.metallurgy;
import ic2.core.ContainerBase;
import ic2.core.slot.SlotInvSlot;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
public class DetonationSprayingMachineContainer extends ContainerBase<DetonationSprayingMachineTileEntity> {
protected DetonationSprayingMachineTileEntity tileEntity;
public int lastFluidAmount = -1;
public short lastProgress = -1;
private final static int height=166;
public DetonationSprayingMachineContainer(EntityPlayer entityPlayer, DetonationSprayingMachineTileEntity detonationSprayingMachineTileEntity){
super(detonationSprayingMachineTileEntity);
this.tileEntity = detonationSprayingMachineTileEntity;
int col;
for (col = 0; col < 3; ++col)
{
for (int col1 = 0; col1 < 9; ++col1)
{
this.addSlotToContainer(new Slot(entityPlayer.inventory, col1 + col * 9 + 9, 8 + col1 * 18, height + -82 + col * 18));
}
}
for (col = 0; col < 9; ++col)
{
this.addSlotToContainer(new Slot(entityPlayer.inventory, col, 8 + col * 18, height + -24));
}
this.addSlotToContainer(new SlotInvSlot(detonationSprayingMachineTileEntity.input, 0, 10, 17));
this.addSlotToContainer(new SlotInvSlot(detonationSprayingMachineTileEntity.input, 1, 98, 17));
this.addSlotToContainer(new SlotInvSlot(detonationSprayingMachineTileEntity.input, 2, 117, 17));
}
@Override
public boolean canInteractWith(EntityPlayer var1) {
return tileEntity.isUseableByPlayer(var1);
}
}
| gpl-3.0 |
kperisetla/YODA | yoda/src/test/java/edu/cmu/sv/TestRegexPlusKeywordUnderstander.java | 7088 | package edu.cmu.sv;
import edu.cmu.sv.database.Ontology;
import edu.cmu.sv.dialog_management.DialogRegistry;
import edu.cmu.sv.domain.DatabaseRegistry;
import edu.cmu.sv.domain.DomainSpec;
import edu.cmu.sv.domain.NonDialogTaskRegistry;
import edu.cmu.sv.domain.smart_house.SmartHouseDatabaseRegistry;
import edu.cmu.sv.domain.smart_house.SmartHouseLexicon;
import edu.cmu.sv.domain.smart_house.SmartHouseNonDialogTaskRegistry;
import edu.cmu.sv.domain.smart_house.SmartHouseOntologyRegistry;
import edu.cmu.sv.domain.smart_house.data.SmartHouseSLUDataset;
import edu.cmu.sv.domain.yoda_skeleton.YodaSkeletonLexicon;
import edu.cmu.sv.domain.yoda_skeleton.YodaSkeletonOntologyRegistry;
import edu.cmu.sv.domain.yoda_skeleton.data.YodaSkeletonSLUDataset;
import edu.cmu.sv.spoken_language_understanding.SLUDataset;
import edu.cmu.sv.spoken_language_understanding.regex_plus_keyword_understander.RegexPlusKeywordUnderstander;
import edu.cmu.sv.yoda_environment.YodaEnvironment;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;
/**
* Created by David Cohen on 10/29/14.
*
* Generate an artificial corpus and use it to train language components (SLU / LM)
*/
public class TestRegexPlusKeywordUnderstander {
/*
* Can only create one yoda environment per program, since it relies on static classes
* */
@Test
public void Test() throws FileNotFoundException, UnsupportedEncodingException {
// testYodaSkeletonSLU();
testSmartHouseSLU();
// runUnderstander();
}
public void testYodaSkeletonSLU() throws FileNotFoundException, UnsupportedEncodingException {
YodaEnvironment yodaEnvironment = YodaEnvironment.dialogTestingEnvironment();
List<DomainSpec> domainSpecs = new LinkedList<>();
domainSpecs.add(new DomainSpec(
"YODA skeleton domain",
new YodaSkeletonLexicon(),
new YodaSkeletonOntologyRegistry(),
new NonDialogTaskRegistry(),
new DatabaseRegistry()));
for (DomainSpec spec : domainSpecs) {
System.err.println("loading domain spec ..." + spec.getDomainName());
yodaEnvironment.loadDomain(spec);
}
Ontology.finalizeOntology();
DialogRegistry.finalizeDialogRegistry();
((RegexPlusKeywordUnderstander) yodaEnvironment.slu).constructTemplates();
System.err.println("done loading domain");
SLUDataset tmp = new YodaSkeletonSLUDataset();
yodaEnvironment.slu.evaluate(yodaEnvironment, tmp);
}
//
// public void testYelpPhoenixSLU() throws FileNotFoundException, UnsupportedEncodingException {
// YodaEnvironment yodaEnvironment = YodaEnvironment.dialogTestingEnvironment();
//
// List<DomainSpec> domainSpecs = new LinkedList<>();
// domainSpecs.add(new DomainSpec(
// "YODA skeleton domain",
// new YodaSkeletonLexicon(),
// new YodaSkeletonOntologyRegistry(),
// new NonDialogTaskRegistry(),
// new DatabaseRegistry()));
// // yelp phoenix domain
// domainSpecs.add(new DomainSpec(
// "Yelp Phoenix domain",
// new YelpPhoenixLexicon(),
// new YelpPhoenixOntologyRegistry(),
// new YelpPhoenixNonDialogTaskRegistry(),
// new YelpPhoenixDatabaseRegistry()));
//
// for (DomainSpec spec : domainSpecs) {
// System.err.println("loading domain spec ..." + spec.getDomainName());
// yodaEnvironment.loadDomain(spec);
// }
// Ontology.finalizeOntology();
// DialogRegistry.finalizeDialogRegistry();
// ((RegexPlusKeywordUnderstander) yodaEnvironment.slu).constructTemplates();
// System.err.println("done loading domain");
//
// SLUDataset tmp = new YelpPhoenixSLUDataset();
// yodaEnvironment.slu.evaluate(yodaEnvironment, tmp);
// }
public void testSmartHouseSLU() throws FileNotFoundException, UnsupportedEncodingException{
YodaEnvironment yodaEnvironment = YodaEnvironment.dialogTestingEnvironment();
List<DomainSpec> domainSpecs = new LinkedList<>();
domainSpecs.add(new DomainSpec(
"YODA skeleton domain",
new YodaSkeletonLexicon(),
new YodaSkeletonOntologyRegistry(),
new NonDialogTaskRegistry(),
new DatabaseRegistry()));
// smart house domain
domainSpecs.add(new DomainSpec(
"Smart house domain",
new SmartHouseLexicon(),
new SmartHouseOntologyRegistry(),
new SmartHouseNonDialogTaskRegistry(),
new SmartHouseDatabaseRegistry()));
for (DomainSpec spec : domainSpecs) {
System.err.println("loading domain spec ..." + spec.getDomainName());
yodaEnvironment.loadDomain(spec);
}
Ontology.finalizeOntology();
DialogRegistry.finalizeDialogRegistry();
((RegexPlusKeywordUnderstander) yodaEnvironment.slu).constructTemplates();
System.err.println("done loading domain");
SLUDataset tmp = new SmartHouseSLUDataset();
yodaEnvironment.slu.evaluate(yodaEnvironment, tmp);
}
public void runUnderstander(){
YodaEnvironment yodaEnvironment = YodaEnvironment.dialogTestingEnvironment();
List<DomainSpec> domainSpecs = new LinkedList<>();
domainSpecs.add(new DomainSpec(
"YODA skeleton domain",
new YodaSkeletonLexicon(),
new YodaSkeletonOntologyRegistry(),
new NonDialogTaskRegistry(),
new DatabaseRegistry()));
// smart house domain
domainSpecs.add(new DomainSpec(
"Smart house domain",
new SmartHouseLexicon(),
new SmartHouseOntologyRegistry(),
new SmartHouseNonDialogTaskRegistry(),
new SmartHouseDatabaseRegistry()));
for (DomainSpec spec : domainSpecs) {
System.err.println("loading domain spec ..." + spec.getDomainName());
yodaEnvironment.loadDomain(spec);
}
Ontology.finalizeOntology();
DialogRegistry.finalizeDialogRegistry();
((RegexPlusKeywordUnderstander) yodaEnvironment.slu).constructTemplates();
System.err.println("done loading domain");
List<String> testUtterances = new LinkedList<>();
testUtterances.add("turn on the air conditioner");
testUtterances.add("turn it on");
testUtterances.add("turn on it");
testUtterances.add("is the air conditioner on");
testUtterances.add("is the air security system on");
for (String testUtterance : testUtterances){
System.out.println("understanding utterance: " + testUtterance);
yodaEnvironment.slu.process1BestAsr(testUtterance);
}
}
} | gpl-3.0 |
brk3/finch | src/com/bourke/finch/fragments/ConnectionsTimelineFragment.java | 467 | package com.bourke.finch;
import com.bourke.finch.common.TwitterTask;
public class ConnectionsTimelineFragment extends BaseTimelineFragment {
private static final String TAG = "Finch/ConnectionsTimelineFragment";
public ConnectionsTimelineFragment() {
super(TwitterTask.GET_MENTIONS);
}
@Override
public void onResume() {
super.onResume();
refresh();
}
public void setupActionMode() {
// TODO
}
}
| gpl-3.0 |
awol2010ex/metl | metl-patch-db2-97/src/main/java/org/jumpmind/metl/core/ui/views/custom/CustomDbTreeNode.java | 6297 | package org.jumpmind.metl.core.ui.views.custom;
import com.vaadin.server.Resource;
import org.jumpmind.db.model.Table;
import org.jumpmind.db.platform.IDatabasePlatform;
import org.jumpmind.properties.TypedProperties;
import org.jumpmind.vaadin.ui.sqlexplorer.DbTree;
import org.jumpmind.vaadin.ui.sqlexplorer.IDb;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CustomDbTreeNode implements Serializable {
private static final long serialVersionUID = 1L;
protected String name;
protected String description;
protected String type;
protected Resource icon;
protected TypedProperties properties = new TypedProperties();
protected CustomDbTreeNode parent;
protected List<CustomDbTreeNode> children = new ArrayList<CustomDbTreeNode>();
protected CustomDbTree dbTree;
public CustomDbTreeNode(CustomDbTree dbTree, String name, String type, Resource icon,
CustomDbTreeNode parent) {
this.name = name;
this.type = type;
this.parent = parent;
this.icon = icon;
this.dbTree = dbTree;
}
public CustomDbTreeNode() {
}
public void setParent(CustomDbTreeNode parent) {
this.parent = parent;
}
public CustomDbTreeNode getParent() {
return parent;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return name;
}
public boolean hasChildren() {
return children.size() > 0;
}
public List<CustomDbTreeNode> getChildren() {
return children;
}
public void setChildren(List<CustomDbTreeNode> children) {
this.children = children;
}
public CustomDbTreeNode find(CustomDbTreeNode node) {
if (this.equals(node)) {
return this;
} else if (children != null && children.size() > 0) {
Iterator<CustomDbTreeNode> it = children.iterator();
while (it.hasNext()) {
CustomDbTreeNode child = (CustomDbTreeNode) it.next();
if (child.equals(node)) {
return child;
}
}
for (CustomDbTreeNode child : children) {
CustomDbTreeNode target = child.find(node);
if (target != null) {
return target;
}
}
}
return null;
}
protected Table getTableFor() {
IDb db = dbTree.getDbForNode(this);
IDatabasePlatform platform = db.getPlatform();
TypedProperties nodeProperties = getProperties();
return platform.getTableFromCache(
nodeProperties.get(DbTree.PROPERTY_CATALOG_NAME),
nodeProperties.get(DbTree.PROPERTY_SCHEMA_NAME), name, false);
}
public boolean delete(CustomDbTreeNode node) {
if (children != null && children.size() > 0) {
Iterator<CustomDbTreeNode> it = children.iterator();
while (it.hasNext()) {
CustomDbTreeNode child = (CustomDbTreeNode) it.next();
if (child.equals(node)) {
it.remove();
return true;
}
}
for (CustomDbTreeNode child : children) {
if (child.delete(node)) {
return true;
}
}
}
return false;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setIcon(Resource icon) {
this.icon = icon;
}
public Resource getIcon() {
return icon;
}
public List<String> findTreeNodeNamesOfType(String type) {
List<String> names = new ArrayList<String>();
if (this.getType().equals(type)) {
names.add(getName());
}
findTreeNodeNamesOfType(type, getChildren(), names);
return names;
}
public void findTreeNodeNamesOfType(String type,
List<CustomDbTreeNode> treeNodes, List<String> names) {
for (CustomDbTreeNode treeNode : treeNodes) {
if (treeNode.getType().equals(type)) {
names.add(treeNode.getName());
}
findTreeNodeNamesOfType(type, treeNode.getChildren(), names);
}
}
public void setProperties(TypedProperties properties) {
this.properties = properties;
}
public TypedProperties getProperties() {
return properties;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((parent == null) ? 0 : parent.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomDbTreeNode other = (CustomDbTreeNode) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (parent == null) {
if (other.parent != null) {
return false;
}
} else if (!parent.equals(other.parent)) {
return false;
}
return true;
}
} | gpl-3.0 |
transwarpio/rapidminer | rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/operator/preprocessing/filter/AbsoluteValueFilter.java | 2782 | /**
* Copyright (C) 2001-2016 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.preprocessing.filter;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.ports.metadata.AttributeMetaData;
import com.rapidminer.operator.ports.metadata.ExampleSetMetaData;
import com.rapidminer.operator.preprocessing.AbstractValueProcessing;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.math.container.Range;
/**
* This operator simply replaces all values by their absolute respective value.
*
* @author Ingo Mierswa, Sebastian Land, Tobias Malbrecht
*/
public class AbsoluteValueFilter extends AbstractValueProcessing {
public AbsoluteValueFilter(OperatorDescription description) {
super(description);
}
@Override
public ExampleSetMetaData applyOnFilteredMetaData(ExampleSetMetaData metaData) {
for (AttributeMetaData amd : metaData.getAllAttributes()) {
if (amd.isNumerical() && !amd.isSpecial()) {
Range range = amd.getValueRange();
amd.setValueRange(new Range(0, Math.max(Math.abs(range.getLower()), Math.abs(range.getUpper()))),
amd.getValueSetRelation());
amd.getMean().setUnkown();
}
}
return metaData;
}
@Override
public ExampleSet applyOnFiltered(ExampleSet exampleSet) throws OperatorException {
for (Example example : exampleSet) {
for (Attribute attribute : exampleSet.getAttributes()) {
if (attribute.isNumerical()) {
double value = example.getValue(attribute);
value = Math.abs(value);
example.setValue(attribute, value);
}
}
}
return exampleSet;
}
@Override
protected int[] getFilterValueTypes() {
return new int[] { Ontology.NUMERICAL };
}
@Override
public boolean writesIntoExistingData() {
return true;
}
}
| gpl-3.0 |
tiborgo/MiniJCompiler | src/test/java/minij/MiniJCompilerTest.java | 3277 | /*
* MiniJCompiler: Compiler for a subset of the Java(R) language
*
* (C) Copyright 2014-2015 Tibor Goldschwendt <goldschwendt@cip.ifi.lmu.de>,
* Michael Seifert <mseifert@error-reports.org>
*
* This file is part of MiniJCompiler.
*
* MiniJCompiler 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.
*
* MiniJCompiler 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 MiniJCompiler. If not, see <http://www.gnu.org/licenses/>.
*/
package minij;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collection;
import minij.Configuration;
import minij.MiniJCompiler;
import minij.backend.i386.I386MachineSpecifics;
import org.apache.commons.io.FilenameUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class MiniJCompilerTest {
@Parameterized.Parameters
public static Collection<Object[]> files() throws IOException {
return TestFiles.getFiles();
}
private File file;
private Class<? extends Exception> exceptionClass;
private MiniJCompiler compiler;
public MiniJCompilerTest(File file, Class<? extends Exception> exceptionClass) {
this.file = file;
this.exceptionClass = exceptionClass;
}
@Before
public void setUp() {
compiler = new MiniJCompiler(new I386MachineSpecifics());
}
@Test
public void testCompileExamples() throws IOException {
System.out.println("Testing compiler input from file \"" + file.toString() + "\"");
Configuration config = new Configuration(new String[]{file.toString()});
config.outputFile = "out" + File.separator + config.outputFile;
try {
compiler.compile(config);
String output = compiler.runExecutable(config, 15);
if (exceptionClass != null) {
fail("The example " + file.toString() + " should have failed with exception " + exceptionClass + ", but was accepted by the compiler.");
}
byte[] content = Files.readAllBytes(new File("src/test/resources/minij-examples-outputs/working/" + FilenameUtils.getBaseName(file.toString()) + ".txt").toPath());
String expectedOutput = new String(content);
if (!output.equals(expectedOutput)) {
fail("The example " + file.toString() + " should have printed '" + expectedOutput + "' but printed '" + output + "'");
}
}
catch (Exception e) {
if (exceptionClass == null) {
e.printStackTrace();
fail("The example " + file.toString() + " should have been accepted by the compiler but failed: " + e.getMessage());
}
if (!exceptionClass.isInstance(e)) {
fail("The example " + file.toString() + " should have failed with exception " + exceptionClass + " but with failed with exception " + e.getClass() + ", " + e.getMessage());
}
}
}
}
| gpl-3.0 |
epam/Gepard | gepard-gherkin-jbehave/src/main/java/com/epam/gepard/gherkin/jbehave/helper/IOUtils.java | 1559 | package com.epam.gepard.gherkin.jbehave.helper;
/*==========================================================================
Copyright 2004-2015 EPAM Systems
This file is part of Gepard.
Gepard 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.
Gepard 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 Gepard. If not, see <http://www.gnu.org/licenses/>.
===========================================================================*/
import java.io.IOException;
import java.io.InputStream;
/**
* Wrapper for org.apache.commons.io.IOUtils.
* @author Adam_Csaba_Kiraly
*/
public class IOUtils {
/**
* Get the contents of an InputStream as a String using the default character encoding of the platform.
* This method buffers the input internally, so there is no need to use a BufferedInputStream.
* @param inputStream the InputStream to read from
* @return the contents of the inputStream
* @throws IOException - if an I/O error occurs
*/
public String toString(final InputStream inputStream) throws IOException {
return org.apache.commons.io.IOUtils.toString(inputStream);
}
}
| gpl-3.0 |
risingshivansh/robotics | portlet/Robotics-Portlet-portlet/docroot/WEB-INF/src/com/xebia/assesment/dto/impl/Robot.java | 4881 | package com.xebia.assesment.dto.impl;
import com.xebia.assesment.dto.Observer;
import com.xebia.assesment.dto.Subject;
import com.xebia.assesment.utils.RobotConstants;
import java.util.ArrayList;
/**
* @author Shivansh Sharma
* This class is responsible for managing the operation/events performed by robots
*/
public class Robot implements Subject
{
// Predefined max strength of robot
private static final Double MAX_ROBOT_STRENGTH = 5.0;
// Predefined max load threshold attain by robot
private static final Double MAX_ROBOT_LOAD_THRESHOLD = 10.0;
private static boolean OVERWEIGHT_INDICATOR = false;
private static boolean LOW_BATTERY = false;
private ArrayList<Observer> observers = new ArrayList<Observer>();
private Double strength;
private Double load;
String consumptionMsg;
public Robot(Double aStrength, Double aLoad, String aConsumptionMsg)
{
super();
strength = aStrength;
load = aLoad;
consumptionMsg = aConsumptionMsg;
}
/**
* Calculate the Capacity & efficiency of the robot based on the activity performed by it.
*/
public void consumption()
{
try
{
double unitPercentileStrength = strength / MAX_ROBOT_STRENGTH;
for (Observer ob : observers)
{
// System.out.println("Distance " + ob.getDistanceInput());
// System.out.println("Weight " + ob.getWeightInput());
double distance = ob.getDistanceInput();
double weight = ob.getWeightInput();
if (null != ob.getDistanceInput() && null != ob.getWeightInput())
{
if (distance != 0.0)
{
double result = unitPercentileStrength * distance;
strength = strength - result;
if (strength <= 15.0)
{
LOW_BATTERY = true;
}
}
if (weight > 10.0 && !LOW_BATTERY)
{
OVERWEIGHT_INDICATOR = true;
}
else
{
strength = strength - (2 * weight);
}
notifyObservers(ob, strength.toString(), LOW_BATTERY, OVERWEIGHT_INDICATOR);
// System.out.println("Result" + strength);
}
// ob.getMessages(this.consumptionMsg);
strength = 100.0;
LOW_BATTERY = false;
OVERWEIGHT_INDICATOR = false;
}
}
catch (Exception e)
{
System.out.println(RobotConstants.INPUT_NAN_KEY);
}
}
/**
* @return the observers
*/
public ArrayList<Observer> getObservers()
{
return observers;
}
/**
* @param aObservers the observers to set
*/
public void setObservers(ArrayList<Observer> aObservers)
{
observers = aObservers;
}
/**
* @return the strength
*/
public Double getStrength()
{
return strength;
}
/**
* @param aStrength the strength to set
*/
public void setStrength(Double aStrength)
{
strength = aStrength;
}
/**
* @return the load
*/
public Double getLoad()
{
return load;
}
/**
* @param aLoad the load to set
*/
public void setLoad(Double aLoad)
{
load = aLoad;
}
/**
* @return the consumptionMsg
*/
public String getConsumptionMsg()
{
return consumptionMsg;
}
/**
* @param aConsumptionMsg the consumptionMsg to set
*/
public void setConsumptionMsg(String aConsumptionMsg)
{
consumptionMsg = aConsumptionMsg;
// notifyObservers();
}
@Override
public void registerObserver(Observer aObserver)
{
observers.add(aObserver);
}
@Override
public void removeObserver(Observer aObserver)
{
observers.remove(aObserver);
}
/**
* Notifying to all the subscribers and publish the messages
*/
@Override
public String notifyObservers(Observer ob, String msg, boolean lb, boolean ow)
{
if (lb)
{
ob.getMessages(RobotConstants.LOW_BATTERY);
}
if (ow)
{
ob.getMessages(RobotConstants.OVER_WEIGHT);
}
if (!lb && !ow)
{
ob.getMessages(msg);
}
return msg;
}
}
| gpl-3.0 |
darrivau/GOOL | src/main/java/gool/generator/objc/ObjcPlatform.java | 2582 | /*
* Copyright 2010 Pablo Arrighi, Alex Concha, Miguel Lezama for version 1.
* Copyright 2013 Pablo Arrighi, Miguel Lezama, Kevin Mazet for version 2.
*
* This file is part of GOOL.
*
* GOOL 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.
*
* GOOL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License version 3 for more details.
*
* You should have received a copy of the GNU General Public License along with GOOL,
* in the file COPYING.txt. If not, see <http://www.gnu.org/licenses/>.
*/
package gool.generator.objc;
import gool.executor.common.SpecificCompiler;
import gool.executor.objc.ObjcCompiler;
import gool.generator.common.CodePrinter;
import gool.generator.common.Platform;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
public class ObjcPlatform extends Platform {
/**
* Name of the directory where the ouput files will be written in.
*/
protected static String outputDir;
public String getOutputDir() {
return outputDir;
}
protected ObjcPlatform(Collection<File> myFile, String outDir) {
super("OBJC", myFile);
if (outDir == null)
outputDir = "";
else
outputDir = outDir;
}
@Override
protected CodePrinter initializeCodeWriter() {
return new ObjcCodePrinter(new File(outputDir), myFileToCopy);
}
@Override
protected SpecificCompiler initializeCompiler() {
return new ObjcCompiler(new File(outputDir), new ArrayList<File>());
}
private static ObjcPlatform instance = new ObjcPlatform(myFileToCopy, outputDir);
public static ObjcPlatform getInstance(Collection<File> myF, String outDir) {
if (myF == null) {
myFileToCopy = new ArrayList<File>();
}
else{
myFileToCopy = myF;
}
if (outDir == null){
outputDir = "";
}
else{
outputDir = outDir;
}
return instance;
}
public static ObjcPlatform getInstance(Collection<File> myF) {
return getInstance(myF, outputDir);
}
public static ObjcPlatform getInstance(String outDir) {
return getInstance(myFileToCopy, outDir);
}
public static ObjcPlatform getInstance() {
if (myFileToCopy == null) {
myFileToCopy = new ArrayList<File>();
}
if (outputDir == null){
outputDir = "";
}
return instance;
}
public static void newInstance() {
instance = new ObjcPlatform(myFileToCopy, outputDir);
}
} | gpl-3.0 |
Wizzercn/NutzShop | src/main/java/cn/wizzer/app/shop/modules/services/impl/ShopOrderPayPaymentServiceImpl.java | 603 | package cn.wizzer.app.shop.modules.services.impl;
import cn.wizzer.app.shop.modules.models.Shop_order_pay_payment;
import cn.wizzer.app.shop.modules.services.ShopOrderPayPaymentService;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
/**
* Created by wizzer on 2019/6/14
*/
@IocBean(args = {"refer:dao"})
public class ShopOrderPayPaymentServiceImpl extends BaseServiceImpl<Shop_order_pay_payment> implements ShopOrderPayPaymentService {
public ShopOrderPayPaymentServiceImpl(Dao dao) {
super(dao);
}
}
| gpl-3.0 |
Creeperface01/RedstoneLamp | src/redstonelamp/entity/Villager.java | 908 | /*
Copyright (C) 2015 RedstoneLamp Project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package redstonelamp.entity;
/**
* A Villager
*/
public class Villager extends Entity{
public final static short NETWORK_ID = 15;
public Villager(int id) {
super(id);
}
}
| gpl-3.0 |
waikato-datamining/adams-base | adams-spreadsheet/src/test/java/adams/data/spreadsheet/cellfinder/SingleCellTest.java | 2090 | /*
* 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/>.
*/
/**
* SingleCellTest.java
* Copyright (C) 2013 University of Waikato, Hamilton, New Zealand
*/
package adams.data.spreadsheet.cellfinder;
import adams.core.Index;
import adams.data.spreadsheet.SpreadSheetColumnIndex;
/**
* Tests the SingleCell cell locator.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class SingleCellTest
extends AbstractCellFinderTestCase {
/**
* Initializes the test.
*
* @param name the name of the test
*/
public SingleCellTest(String name) {
super(name);
}
/**
* Returns the filenames (without path) of the input data files to use
* in the regression test.
*
* @return the filenames
*/
@Override
protected String[] getRegressionInputFiles() {
return new String[]{
"bolts.csv",
"bolts.csv",
"bolts.csv",
};
}
/**
* Returns the setups to use in the regression test.
*
* @return the setups
*/
@Override
protected CellFinder[] getRegressionSetups() {
SingleCell[] result;
result = new SingleCell[3];
result[0] = new SingleCell();
result[1] = new SingleCell();
result[1].setColumn(new SpreadSheetColumnIndex(Index.LAST));
result[1].setRow(new Index(Index.LAST));
result[2] = new SingleCell();
result[2].setColumn(new SpreadSheetColumnIndex("2"));
result[2].setRow(new Index("10"));
return result;
}
}
| gpl-3.0 |
wayerr/ivasu | src/main/java/wayerr/reflect/ParametrizedTypeImpl.java | 3188 | package wayerr.reflect;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
final class ParameterizedTypeImpl implements ParameterizedType {
private final Class rawType;
private final Type[] actualTypeArguments;
private final Type ownerType;
public ParameterizedTypeImpl(Class rawType, Type[] actualTypeArguments, Type ownerType) {
this.rawType = rawType;
this.actualTypeArguments = actualTypeArguments;
if(ownerType != null) {
this.ownerType = ownerType;
} else {
this.ownerType = this.rawType.getDeclaringClass();
}
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public Type[] getActualTypeArguments() {
return actualTypeArguments.clone();
}
@Override
public Type getOwnerType() {
return ownerType;
}
@Override
public boolean equals(Object o) {
if(!(o instanceof ParameterizedType)) {
return false;
} else {
// Check that information is equivalent
ParameterizedType that = (ParameterizedType)o;
if(this == that) {
return true;
}
Type thatOwner = that.getOwnerType();
Type thatRawType = that.getRawType();
return (ownerType == null ? thatOwner == null : ownerType.equals(thatOwner)) && (rawType == null ? thatRawType == null : rawType.equals(thatRawType)) && Arrays.equals(actualTypeArguments, that.getActualTypeArguments());
}
}
@Override
public int hashCode() {
return Arrays.hashCode(actualTypeArguments) ^ (ownerType == null ? 0 : ownerType.hashCode()) ^ (rawType == null ? 0 : rawType.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if(ownerType != null) {
if(ownerType instanceof Class) {
sb.append(((Class)ownerType).getName());
} else {
sb.append(ownerType.toString());
}
sb.append(".");
if(ownerType instanceof ParameterizedTypeImpl) {
// Find simple name of nested type by removing the
// shared prefix with owner.
sb.append(rawType.getName().replace(((ParameterizedTypeImpl)ownerType).rawType.getName() + "$",
""));
} else {
sb.append(rawType.getName());
}
} else {
sb.append(rawType.getName());
}
if(actualTypeArguments != null
&& actualTypeArguments.length > 0) {
sb.append("<");
boolean first = true;
for(Type t : actualTypeArguments) {
if(!first) {
sb.append(", ");
}
if(t instanceof Class) {
sb.append(((Class)t).getName());
} else {
sb.append(t.toString());
}
first = false;
}
sb.append(">");
}
return sb.toString();
}
}
| gpl-3.0 |
JangwonYie/LeetCodeChallenge | src/main/java/com/jyie/leet/BTLOT.java | 1668 | package com.jyie.leet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
*
* Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
*
*
* Created by Jangwon Yie on 2018. 4. 2..
*/
public class BTLOT {
private static class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new LinkedList<List<Integer>>();
Queue<TreeNode> init = new LinkedList<TreeNode> ();
init.offer(root);
addLevel(list, init);
return list;
}
private void addLevel(List<List<Integer>> list, Queue<TreeNode> queue){
if(queue.isEmpty())
return;
Queue<TreeNode> next = new LinkedList<TreeNode> ();
List<Integer> levelList = null;
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(null != node){
if(null == levelList)
levelList = new LinkedList<Integer> ();
levelList.add(node.val);
if(null != node.left)
next.offer(node.left);
if(null != node.right)
next.offer(node.right);
}
}
if(null != levelList)
list.add(levelList);
if(!next.isEmpty())
addLevel(list, next);
}
}
| gpl-3.0 |
takisd123/executequery | src/org/executequery/event/QueryBookmarkEvent.java | 1019 | /*
* QueryBookmarkEvent.java
*
* Copyright (C) 2002-2017 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.executequery.event;
public interface QueryBookmarkEvent extends ApplicationEvent {
/** Method name for bookmark added */
String BOOKMARK_ADDED = "queryBookmarkAdded";
/** Method name for bookmark added */
String BOOKMARK_REMOVED = "queryBookmarkRemoved";
}
| gpl-3.0 |
TinyGroup/tiny | db/org.tinygroup.tinydb/src/test/java/org/tinygroup/tinydb/test/List2ArrayTest.java | 1949 | /**
* Copyright (c) 1997-2013, www.tinygroup.org (luo_guo@icloud.com).
*
* Licensed under the GPL, Version 3.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.gnu.org/licenses/gpl.html
*
* 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.tinygroup.tinydb.test;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class List2ArrayTest {
@SuppressWarnings("unchecked")
public static <T> T[] collectionToArray(List<?> collection) {
if (collection == null || collection.size() == 0) {
throw new RuntimeException("集合为空或没有元素!");
}
T[] array = (T[]) Array.newInstance(collection.get(0).getClass(),
collection.size());
for (int i = 0; i < collection.size(); i++) {
array[i] = (T) collection.get(i);
}
return array;
}
@SuppressWarnings("unchecked")
public static <T> T[] collectionToArray(Collection<?> collection) {
if (collection == null || collection.size() == 0) {
throw new RuntimeException("集合为空或没有元素!");
}
T[] array = (T[]) Array.newInstance(collection.iterator().next().getClass(),
collection.size());
int i = 0;
for (Object obj : collection) {
array[i++] = (T) obj;
}
return array;
}
/**
* @param args
*/
public static void main(String[] args) {
Collection<User> userList = new ArrayList<User>();
userList.add(new User());
userList.add(new User());
User[] array = collectionToArray(userList);
System.out.println(array.getClass().getName());
}
}
class User {
} | gpl-3.0 |
wiki2014/Learning-Summary | alps/cts/tests/tests/preference2/src/android/preference2/cts/CustomPreference.java | 4826 | /*
* Copyright (C) 2012 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 android.preference2.cts;
import android.preference2.cts.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
public class CustomPreference extends Preference {
protected boolean mOnPrepareCalled;
public CustomPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public CustomPreference(Context context) {
this(context, null, 0);
}
public CustomPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
private void init(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.CustPref);
setTitle(a.getString(R.styleable.CustPref_title));
setIcon(a.getDrawable(R.styleable.CustPref_icon));
}
@Override
protected boolean callChangeListener(Object newValue) {
return super.callChangeListener(newValue);
}
@Override
protected Preference findPreferenceInHierarchy(String key) {
return super.findPreferenceInHierarchy(key);
}
@Override
protected boolean getPersistedBoolean(boolean defaultReturnValue) {
return super.getPersistedBoolean(defaultReturnValue);
}
@Override
protected float getPersistedFloat(float defaultReturnValue) {
return super.getPersistedFloat(defaultReturnValue);
}
@Override
protected int getPersistedInt(int defaultReturnValue) {
return super.getPersistedInt(defaultReturnValue);
}
@Override
protected long getPersistedLong(long defaultReturnValue) {
return super.getPersistedLong(defaultReturnValue);
}
@Override
protected String getPersistedString(String defaultReturnValue) {
return super.getPersistedString(defaultReturnValue);
}
@Override
protected void notifyChanged() {
super.notifyChanged();
}
@Override
protected void notifyHierarchyChanged() {
super.notifyHierarchyChanged();
}
@Override
protected void onAttachedToActivity() {
super.onAttachedToActivity();
}
@Override
protected void onAttachedToHierarchy(PreferenceManager preferenceManager) {
super.onAttachedToHierarchy(preferenceManager);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
}
@Override
protected void onClick() {
super.onClick();
}
@Override
protected View onCreateView(ViewGroup parent) {
return super.onCreateView(parent);
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return super.onGetDefaultValue(a, index);
}
@Override
protected void onPrepareForRemoval() {
super.onPrepareForRemoval();
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(state);
}
@Override
protected Parcelable onSaveInstanceState() {
return super.onSaveInstanceState();
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue,
Object defaultValue) {
super.onSetInitialValue(restorePersistedValue, defaultValue);
}
@Override
protected boolean persistBoolean(boolean value) {
return super.persistBoolean(value);
}
@Override
protected boolean persistFloat(float value) {
return super.persistFloat(value);
}
@Override
protected boolean persistInt(int value) {
return super.persistInt(value);
}
@Override
protected boolean persistLong(long value) {
return super.persistLong(value);
}
@Override
protected boolean persistString(String value) {
return super.persistString(value);
}
@Override
protected boolean shouldPersist() {
return super.shouldPersist();
}
}
| gpl-3.0 |
idega/com.idega.core | src/java/com/idega/core/user/data/GenderBMPBean.java | 2124 | package com.idega.core.user.data;
import java.sql.SQLException;
import com.idega.data.GenericEntity;
/**
* Title: User
* Description:
* Copyright: Copyright (c) 2001
* Company: idega.is
* @author 2000 - idega team - <a href="mailto:gummi@idega.is">Guðmundur Ágúst Sæmundsson</a>
* @version 1.0
*/
public class GenderBMPBean extends com.idega.data.GenericEntity implements com.idega.core.user.data.Gender {
public static final String NAME_MALE="male";
public static final String NAME_FEMALE="female";
public GenderBMPBean() {
super();
}
public GenderBMPBean(int id) throws SQLException {
super(id);
}
public void initializeAttributes() {
this.addAttribute(this.getIDColumnName());
this.addAttribute(getNameColumnName(),"Nafn",true,true,"java.lang.String");
this.addAttribute(getDescriptionColumnName(),"Description",true,true,"java.lang.String",1000);
getEntityDefinition().setBeanCachingActiveByDefault(true);
}
public String getEntityName() {
return "ic_gender";
}
public void insertStartData() throws SQLException {
Gender male = ((com.idega.core.user.data.GenderHome)com.idega.data.IDOLookup.getHomeLegacy(Gender.class)).createLegacy();
male.setName(NAME_MALE);
male.insert();
Gender female = ((com.idega.core.user.data.GenderHome)com.idega.data.IDOLookup.getHomeLegacy(Gender.class)).createLegacy();
female.setName(NAME_FEMALE);
female.insert();
}
public static String getNameColumnName(){
return "name";
}
public static String getDescriptionColumnName(){
return "description";
}
public void setName(String name){
this.setColumn(getNameColumnName(),name);
}
public void setDescription(String description){
this.setColumn(getDescriptionColumnName(),description);
}
public String getName(){
return this.getStringColumnValue(getNameColumnName());
}
public String getDescription(){
return this.getStringColumnValue(getDescriptionColumnName());
}
public Gender getStaticInstance(){
return (Gender)GenericEntity.getStaticInstance(Gender.class);
}
}
| gpl-3.0 |
ThihaZaw-MM/librarysystem | libraryservices/src/main/java/com/thiha/libraryservices/controllers/AppController.java | 586 | package com.thiha.libraryservices.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AppController {
@RequestMapping("/")
String home(ModelMap modal) {
modal.addAttribute("title","Library Services");
return "index";
}
@RequestMapping("/partials/{page}")
String partialHandler(@PathVariable("page") final String page) {
return page;
}
}
| gpl-3.0 |
jukiewiczm/renjin | core/src/main/java/org/renjin/primitives/combine/Combine.java | 3051 | /*
* R : A Computer Language for Statistical Data Analysis
* Copyright (C) 1995, 1996 Robert Gentleman and Ross Ihaka
* Copyright (C) 1997--2008 The R Development Core Team
* Copyright (C) 2003, 2004 The R Foundation
* Copyright (C) 2010 bedatadriven
*
* 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.renjin.primitives.combine;
import org.renjin.invoke.annotations.*;
import org.renjin.repackaged.guava.base.Function;
import org.renjin.repackaged.guava.collect.Iterables;
import org.renjin.sexp.ListVector;
import org.renjin.sexp.NamedValue;
import org.renjin.sexp.Null;
import org.renjin.sexp.SEXP;
/**
* Implementation of the combine-related functions, including c(), list(), unlist(),
* cbind(), rbind(), matrix(), and aperm()
*/
public class Combine {
/**
* combines its arguments to form a vector. All arguments are coerced to a common type which is the
* type of the returned value, and all attributes except names are removed.
*/
@Generic
@Builtin
public static SEXP c(@ArgumentList ListVector arguments,
@NamedFlag("recursive") boolean recursive) {
// Iterate over all the vectors in the argument
// list to determine which vector type to use
Inspector inspector = new Inspector(recursive);
inspector.acceptAll(Iterables.transform(arguments.namedValues(), VALUE_OF));
CombinedBuilder builder = inspector.newBuilder().useNames(true);
// Allocate a new vector with all the elements
return new Combiner(recursive, builder)
.add(arguments)
.build();
}
@Generic
@Internal
public static SEXP unlist(SEXP sexp, boolean recursive, boolean useNames) {
if(!(sexp instanceof ListVector)) {
return sexp;
}
ListVector vector = (ListVector) sexp;
// Iterate over all the vectors in the argument
// list to determine which vector type to use
Inspector inspector = new Inspector(recursive);
inspector.acceptAll(vector);
if(inspector.getResult() == Null.VECTOR_TYPE) {
return Null.INSTANCE;
}
CombinedBuilder builder = inspector.newBuilder().useNames(useNames);
return new Combiner(recursive, builder)
.add(vector)
.build();
}
private static final Function<NamedValue,SEXP> VALUE_OF =
new Function<NamedValue, SEXP>() {
@Override
public SEXP apply(NamedValue input) {
return input.getValue();
}
};
}
| gpl-3.0 |
greenkeeper/ArduinoLight | ArduinoLight/src/arduinoLight/framework/ShutdownListener.java | 436 | package arduinoLight.framework;
/**
* Classes that need to act upon shutdown, for example to close connections or clean up resources
* should implement this interface and add themselves to the ShutdownHandler.
*/
public interface ShutdownListener
{
/**
* Gets called if the application is shutting down.
* Obviously, should not be called of the application is not shutting down.
*/
public void onShutdown();
}
| gpl-3.0 |
KingOThePig/TutorialMod | src/main/java/com/kingothepig/tutorialmod/creativetab/CreativeTabMod.java | 477 | package com.kingothepig.tutorialmod.creativetab;
import com.kingothepig.tutorialmod.init.ModItems;
import com.kingothepig.tutorialmod.reference.Reference;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class CreativeTabMod {
public static final CreativeTabs MOD_TAB = new CreativeTabs(Reference.MOD_ID.toLowerCase()){
@Override
public Item getTabIconItem(){
return ModItems.mapleLeaf;
}
};
}
| gpl-3.0 |
repoxIST/repoxLight | repox-gui/src/main/java/harvesterUI/client/servlets/transformations/TransformationsServiceAsync.java | 2405 | /*
* Ext GWT 2.2.1 - Ext for GWT
* Copyright(c) 2007-2010, Ext JS, LLC.
* licensing@extjs.com
*
* http://extjs.com/license
*/
package harvesterUI.client.servlets.transformations;
import com.extjs.gxt.ui.client.data.FilterPagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.google.gwt.user.client.rpc.AsyncCallback;
import harvesterUI.shared.mdr.SchemaTreeUI;
import harvesterUI.shared.mdr.SchemaUI;
import harvesterUI.shared.mdr.TransformationUI;
import harvesterUI.shared.servletResponseStates.ResponseState;
import java.util.List;
//import harvesterUI.client.models.FilterAttributes;
//import harvesterUI.client.models.MailItem;
public interface TransformationsServiceAsync {
public void getFullTransformationsList(AsyncCallback<List<TransformationUI>> callback);
public void saveTransformation(TransformationUI transformationUI, String oldTransId, AsyncCallback<ResponseState> callback);
public void deleteTransformation(List<String> transfomationIDs, AsyncCallback<String> callback);
public void getPagedTransformations(FilterPagingLoadConfig config, AsyncCallback<PagingLoadResult<TransformationUI>> callback);
public void validateTransformation(String id, String xslFilePath, String oldTransId, AsyncCallback<ResponseState> callback);
// public void getMdrMappings(String schema, String metadataNamespace,AsyncCallback<List<TransformationUI>> callback);
// public void getAllMdrMappings(AsyncCallback<List<TransformationUI>> callback);
// public void importMdrTransformation(List<TransformationUI> transformationUIs,AsyncCallback<BaseModel> callback);
// public void updateMdrTransformations(List<TransformationUI> transformationUIs,AsyncCallback<BaseModel> callback);
public void getPagedSchemas(PagingLoadConfig config, AsyncCallback<List<SchemaTreeUI>> callback);
public void getPagingData(PagingLoadConfig config, AsyncCallback<PagingLoadResult<SchemaTreeUI>> callback);
public void getSchemasTree(AsyncCallback<List<SchemaTreeUI>> callback);
public void deleteMetadataSchema(List<String> schemaIds, AsyncCallback<ResponseState> callback);
public void saveMetadataSchema(SchemaUI schemaUI, String oldSchemaUIId, AsyncCallback<ResponseState> callback);
public void getAllMetadataSchemas(AsyncCallback<List<SchemaUI>> callback);
}
| gpl-3.0 |
rpmulligan/V2V | src/model/ReportConfig.java | 621 | package model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class ReportConfig {
@Id
private String reportType;
private String fieldNames;
public ReportConfig(String reportType, String fieldNames) {
this.reportType = reportType;
this.fieldNames = fieldNames;
}
public ReportConfig() {
}
public String getReportType() {
return reportType;
}
public String getFieldNames() {
return fieldNames;
}
public void setReportType(String reportType) {
this.reportType = reportType;
}
public void setFieldNames(String fieldNames) {
this.fieldNames = fieldNames;
}
}
| gpl-3.0 |
arie-benichou/zero-sum-game-engine | src/test/java/concretisations/checkers/CheckerPotentialMutationsTest.java | 8540 |
package concretisations.checkers;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import abstractions.cell.CellManager;
import abstractions.cell.CellManagerInterface;
import abstractions.cell.ManagedCellInterface;
import abstractions.dimension.DimensionFactory;
import abstractions.direction.Direction;
import abstractions.direction.DirectionManager;
import abstractions.direction.DirectionManager.NamedDirection;
import abstractions.mutation.MutationInterface;
import abstractions.piece.PieceManager;
import abstractions.piece.PieceManagerInterface;
import abstractions.position.PositionManager;
import abstractions.position.PositionManagerInterface;
import abstractions.side.SideInterface;
import abstractions.side.Sides;
import concretisations.checkers.mutations.CheckersMutationFactory;
import concretisations.checkers.pieces.CheckersPieceSet;
// TODO à compléter
public final class CheckerPotentialMutationsTest {
private CellManagerInterface cellManager;
@Before
public void setUp() throws Exception {
final PositionManagerInterface positionManager = new PositionManager(new DirectionManager(DimensionFactory.dimension(5, 5)));
final PieceManagerInterface pieceManager = new PieceManager(CheckersPieceSet.class);
this.cellManager = new CellManager(positionManager, pieceManager);
}
/*
---------------------
| | | | | |
---------------------
| | | | | |
---------------------
| | | o | | |
---------------------
| x | | | x | |
---------------------
| | | | | |
---------------------
*/
@Test
public void testGetPotentialMutations1() {
final SideInterface side = Sides.FIRST;
this.cellManager.getCell(4, 1).setPiece(side, CheckersPieceSet.MAN);
this.cellManager.getCell(4, 4).setPiece(side, CheckersPieceSet.MAN);
this.cellManager.getCell(3, 3).setPiece(side.getNextSide(), CheckersPieceSet.MAN);
final Set<MutationInterface> expectedPotentialMutations = new HashSet<MutationInterface>();
expectedPotentialMutations.add(CheckersMutationFactory.newWalkMutation(this.cellManager.getCell(4, 4), new Direction(-1, 1)));
expectedPotentialMutations.add(CheckersMutationFactory.newJumpMutation(this.cellManager.getCell(4, 4), new Direction(-1, -1)));
expectedPotentialMutations.add(CheckersMutationFactory.newWalkMutation(this.cellManager.getCell(4, 1), new Direction(-1, 1)));
final Map<ManagedCellInterface, Set<? extends MutationInterface>> potentialMutations = this.cellManager.getPotentialMutations(Sides.FIRST);
//System.out.println(this.cellManager);
// TODO ! classer par type de mutations dans CellManager
final Set<MutationInterface> result = new HashSet<MutationInterface>();
for (final Set<? extends MutationInterface> cellPotentialMutations : potentialMutations.values()) {
result.addAll(cellPotentialMutations);
}
Assert.assertTrue(expectedPotentialMutations.equals(result));
}
/*
---------------------
| | | | | |
---------------------
| | | | | |
---------------------
| | | o | | |
---------------------
| x | | | x | |
---------------------
| | | | | |
---------------------
*/
@Test
public void testGetPotentialMutations2() {
final SideInterface side = Sides.FIRST;
this.cellManager.getCell(4, 1).setPiece(side, CheckersPieceSet.MAN);
this.cellManager.getCell(4, 4).setPiece(side, CheckersPieceSet.MAN);
this.cellManager.getCell(3, 3).setPiece(side.getNextSide(), CheckersPieceSet.MAN);
final Set<MutationInterface> expectedPotentialMutations = new HashSet<MutationInterface>();
expectedPotentialMutations.add(CheckersMutationFactory.newWalkMutation(this.cellManager.getCell(4, 4), NamedDirection.TOP_RIGHT.value()));
expectedPotentialMutations.add(CheckersMutationFactory.newJumpMutation(this.cellManager.getCell(4, 4), NamedDirection.TOP_LEFT.value()));
expectedPotentialMutations.add(CheckersMutationFactory.newWalkMutation(this.cellManager.getCell(4, 1), NamedDirection.TOP_RIGHT.value()));
final Map<ManagedCellInterface, Set<? extends MutationInterface>> potentialMutations = this.cellManager.getPotentialMutations(Sides.FIRST);
//System.out.println(this.cellManager);
// TODO ! classer par type de mutations dans CellManager
final Set<MutationInterface> result = new HashSet<MutationInterface>();
for (final Set<? extends MutationInterface> cellPotentialMutations : potentialMutations.values()) {
result.addAll(cellPotentialMutations);
}
Assert.assertTrue(expectedPotentialMutations.equals(result));
// TODO à tester unitairement
for (final Entry<ManagedCellInterface, Set<? extends MutationInterface>> mutations : potentialMutations.entrySet()) {
for (final MutationInterface mutation : mutations.getValue()) {
mutation.process();
//System.out.println(this.cellManager);
mutation.cancel();
//System.out.println(this.cellManager);
}
}
}
/*
---------------------
| | | | | |
---------------------
| | | | | |
---------------------
| | | | | |
---------------------
| x | | | x | |
---------------------
| | | | | |
---------------------
*/
@Test
public void testGetPotentialMutations3() {
final SideInterface side = Sides.FIRST;
this.cellManager.getCell(4, 1).setPiece(side, CheckersPieceSet.MAN);
this.cellManager.getCell(4, 4).setPiece(side, CheckersPieceSet.MAN);
final Set<MutationInterface> expectedPotentialMutations = new HashSet<MutationInterface>();
expectedPotentialMutations.add(CheckersMutationFactory.newWalkMutation(this.cellManager.getCell(4, 4), NamedDirection.TOP_LEFT.value()));
expectedPotentialMutations.add(CheckersMutationFactory.newWalkMutation(this.cellManager.getCell(4, 4), NamedDirection.TOP_RIGHT.value()));
expectedPotentialMutations.add(CheckersMutationFactory.newWalkMutation(this.cellManager.getCell(4, 1), NamedDirection.TOP_RIGHT.value()));
final Map<ManagedCellInterface, Set<? extends MutationInterface>> potentialMutations = this.cellManager.getPotentialMutations(Sides.FIRST);
//System.out.println(this.cellManager);
// TODO ! classer par type de mutations dans CellManager
final Set<MutationInterface> result = new HashSet<MutationInterface>();
for (final Set<? extends MutationInterface> cellPotentialMutations : potentialMutations.values()) {
result.addAll(cellPotentialMutations);
}
Assert.assertTrue(expectedPotentialMutations.equals(result));
// TODO à tester unitairement
for (final Entry<ManagedCellInterface, Set<? extends MutationInterface>> mutations : potentialMutations.entrySet()) {
for (final MutationInterface mutation : mutations.getValue()) {
mutation.process();
//System.out.println(this.cellManager);
mutation.cancel();
//System.out.println(this.cellManager);
}
}
}
/*
---------------------
| | | | | |
---------------------
| | | | o | |
---------------------
| | | o | | |
---------------------
| | | | | |
---------------------
| | | | | |
---------------------
*/
@Test
public void testGetPotentialMutations4() {
final SideInterface side = Sides.SECOND;
this.cellManager.getCell(2, 4).setPiece(side, CheckersPieceSet.MAN);
this.cellManager.getCell(3, 3).setPiece(side, CheckersPieceSet.MAN);
final Map<ManagedCellInterface, Set<? extends MutationInterface>> potentialMutations = this.cellManager.getPotentialMutations(Sides.FIRST);
Assert.assertTrue(potentialMutations.isEmpty());
}
@After
public void tearDown() throws Exception {
this.cellManager = null; // NOPMD
}
}
| gpl-3.0 |
Silverpeas/silverpeas-jupload | src/test/java/wjhk/jupload2/upload/AbstractJUploadTestHelper.java | 16517 | //
// $Id$
//
// jupload - A file upload applet.
//
// Copyright 2010 The JUpload Team
//
// Created: 27 janv. 2010
// Creator: etienne_sf
// Last modified: $Date$
//
// 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., 675 Mass Ave, Cambridge, MA 02139, USA.
package wjhk.jupload2.upload;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import wjhk.jupload2.JUploadDaemon;
import wjhk.jupload2.context.JUploadContext;
import wjhk.jupload2.exception.JUploadException;
import wjhk.jupload2.filedata.FileData;
import wjhk.jupload2.gui.JUploadPanel;
import wjhk.jupload2.gui.filepanel.FilePanel;
import wjhk.jupload2.policies.UploadPolicy;
import wjhk.jupload2.testhelpers.FileDataTestHelper;
import wjhk.jupload2.testhelpers.FilePanelTestHelper;
import wjhk.jupload2.testhelpers.FileUploadManagerThreadTestHelper;
import wjhk.jupload2.testhelpers.FileUploadThreadTestHelper;
import wjhk.jupload2.testhelpers.JUploadContextTestHelper;
import wjhk.jupload2.testhelpers.JUploadPanelTestHelper;
import wjhk.jupload2.testhelpers.UploadPolicyTestHelper;
/**
* This class is the superclass of all test classes in this package. It creates
* all common objects (upload policy, queues...)
*
* @author etienne_sf
*/
public class AbstractJUploadTestHelper {
/** Logger for this class */
protected final Logger logger = Logger
.getLogger(AbstractJUploadTestHelper.class);
final static String DEFAULT_LOCAL_POST_URL = "http://localhost/index.html";
final static String DEFAULT_POST_URL = "http://jupload.sourceforge.net/upload_dummy.html";
/** Maximum time to wait for a thread to finish its work, in milliseconds */
final static int MAX_WAIT_FOR_THREAD = 10000;
/**
* Indicates whether the postURL system property has been set for the
* current unit test execution.
*/
public static boolean postURLHasBeenSet = false;
/** Interval of time, before checking if a thread has finished its work */
final static int INTERVAL_BEFORE_CHECKING_THREAD = 1000;
/** A default {@link JUploadDaemon} */
public JUploadDaemon juploadDaemon;
/** A default {@link JUploadContext} */
public JUploadContext juploadContext = null;
/** A default {@link FilePanel} */
public FilePanel filePanel;
/** A default {@link JUploadPanel} */
public JUploadPanel juploadPanel;
/** A default {@link UploadPolicy} */
public UploadPolicy uploadPolicy = null;
/** The root for the file to upload */
public File fileroot = null;
/**
* The list of files that will be loaded. Initialized in
* {@link #setupFileList(int)}.
*/
public List<FileData> filesToUpload = null;
/** A default {@link FilePreparationThread} */
public FilePreparationThread filePreparationThread = null;
/** A default {@link PacketConstructionThread} */
public PacketConstructionThread packetConstructionThread = null;
/** A default {@link FileUploadThread} */
public FileUploadThread fileUploadThread = null;
/** A default {@link FileUploadManagerThread} */
public FileUploadManagerThread fileUploadManagerThread = null;
/** The actual start of this test */
public long uploadStartTime = -1;
/** A default queue, for the prepared files */
public BlockingQueue<UploadFileData> preparedFileQueue = new ArrayBlockingQueue<UploadFileData>(
100);
/** A default queue, for the packets to upload */
public BlockingQueue<UploadFilePacket> packetQueue = new ArrayBlockingQueue<UploadFilePacket>(
100);
/**
* Constructs the UploadPolicy, and all threads to simulate a real upload.
* Maybe too long for real unit testing.
*
* @throws Exception
*/
@Before
public void setupFullUploadEnvironment() throws Exception {
// Set the postURL for the current unit test, according to the local
// network access.
setPostURL();
this.juploadDaemon = new JUploadDaemon();
this.filePanel = new FilePanelTestHelper(this.filesToUpload);
this.juploadPanel = new JUploadPanelTestHelper(this.filePanel);
this.uploadPolicy = new UploadPolicyTestHelper(this.juploadPanel);
this.juploadContext = this.uploadPolicy.getContext();
this.fileUploadThread = new FileUploadThreadTestHelper(this.packetQueue);
this.fileUploadManagerThread = new FileUploadManagerThreadTestHelper();
((JUploadPanelTestHelper) this.juploadPanel).fileUploadManagerThread = this.fileUploadManagerThread;
// Set up the file data, for the simulated upload.
this.fileroot = new File(JUploadContextTestHelper.TEST_FILES_FOLDER);
setupFileList(1);
// Let's note the current system time. It should be almost the upload
// start time.
this.uploadStartTime = System.currentTimeMillis();
}
/**
* This method tries to determine if the current computer can access to
* jupload.sourceforge.net. If yes, the
* http://jupload.sourceforge.net/upload_dummy.html URL is used. <BR>
* If no, the http://localhost/index.html URL is used for test postURL.<BR>
* <BR>
* The reason for this test, is that I often work unconnected, in the train.
* And I still want the unit tests to work properly.
*/
private void setPostURL() {
// If the system property has not been set yet, let's determine if
// we're connected to the network.
if (!postURLHasBeenSet) {
String postURL;
try {
URL url = new URL(DEFAULT_POST_URL);
new Socket(url.getHost(), url.getPort());
// The given host is valid. We use this URL.
postURL = DEFAULT_POST_URL;
} catch (Exception e) {
logger.warn(e.getClass().getName() + " when creating URL from "
+ DEFAULT_POST_URL + " (will use "
+ DEFAULT_LOCAL_POST_URL + " instead");
//
postURL = DEFAULT_LOCAL_POST_URL;
}
System.setProperty(UploadPolicy.PROP_POST_URL, postURL);
postURLHasBeenSet = true;
}
}
/**
* @param nbFiles
*/
public void setupFileList(int nbFiles) {
this.filesToUpload = new ArrayList<FileData>(nbFiles);
File[] fArray = new File[nbFiles];
for (int i = 0; i < nbFiles; i += 1) {
FileData fileData = new FileDataTestHelper(i);
// We must be able to load the file. Otherwise, it's useless to
// start. And there seems to be problem with user dir, depending on
// the java tool used.
Assert.assertTrue(fileData.getFileName() + " must be readable !",
fileData.canRead());
this.filesToUpload.add(fileData);
}
// Let's add these files to the FilePanel
if (this.filePanel instanceof FilePanelTestHelper) {
((FilePanelTestHelper) this.filePanel).filesToUpload = this.filesToUpload;
} else {
// We first clear the list, to be sure of the final content.
this.filePanel.removeAll();
this.filePanel.addFiles(fArray, null);
}
}
/**
* Call the beforeUpload method for all files.
*
* @throws JUploadException
*/
void prepareFileList() throws JUploadException {
for (FileData fileData : this.filesToUpload) {
fileData.beforeUpload();
}
}
/**
* Wait for a queue to be emptied by a consuming thread. This will wait
* {@link #MAX_WAIT_FOR_THREAD} at most, and check this every
* {@link INTERVAL_BEFORE_CHECKING_THREAD} ms.
*/
void waitForQueueToBeEmpty(Queue<UploadFileData> queue, String queueName) {
int nbLoop = MAX_WAIT_FOR_THREAD / INTERVAL_BEFORE_CHECKING_THREAD;
try {
for (int i = 0; i < nbLoop; i += 1) {
if (queue.isEmpty()) {
logger.info("The queue " + queueName + " has been emptied");
return;
}
Thread.sleep(10);
}
} catch (InterruptedException e) {
logger.warn("waitForQueueToBeEmpty got interrupted");
}
logger.warn("The queue " + queueName + " was not emptied");
}
/**
* Wait for a thread to finish normally. This will wait
* {@link #MAX_WAIT_FOR_THREAD} at most, and check this every
* {@link INTERVAL_BEFORE_CHECKING_THREAD} ms.
*/
void waitForThreadToFinish(Thread thread, String threadName) {
if (thread.isAlive()) {
// Let's wait a little for this thread to finish...
try {
(thread).join(MAX_WAIT_FOR_THREAD);
} catch (InterruptedException e) {
Assert.fail("Was interrupted during the join: the thread "
+ threadName + " did not finish on time ");
}
}
// Is the thread finished now ?
if (thread.isAlive()) {
logger.warn("The thread " + threadName
+ " did not finished alone: let's interrupt it");
thread.interrupt();
} else {
logger.info("The thread " + threadName
+ " finished alone (no interruption needed)");
}
}
/** */
@After
public void cleanQueues() {
logger.debug("Finishing the test: interrupting the threads, and cleaning the queues");
if (this.fileUploadThread != null) {
if (this.fileUploadThread.isAlive()) {
this.fileUploadThread.interrupt();
this.fileUploadThread = null;
}
}
if (this.fileUploadManagerThread != null) {
if (this.fileUploadManagerThread.isAlive()) {
this.fileUploadManagerThread.interrupt();
this.fileUploadManagerThread = null;
}
}
if (this.packetConstructionThread != null) {
if (this.packetConstructionThread.isAlive()) {
this.packetConstructionThread.interrupt();
this.packetConstructionThread = null;
}
}
if (this.preparedFileQueue != null) {
while (!this.preparedFileQueue.isEmpty()) {
this.preparedFileQueue.poll();
}
this.preparedFileQueue = null;
}
if (this.packetQueue != null) {
while (!this.packetQueue.isEmpty()) {
this.packetQueue.poll();
}
this.packetQueue = null;
}
}
/**
* This method calls a given method onto a given object. It is used to
* execute the call of the callback registered by the last call to
* juploadContext.registerUnload.<BR>
* This works only if juploadContext is an instance of
* {@link JUploadContextTestHelper}
*
* @param expectedClass Contains the class to which the
* lastRegisterUnloadObject should belong to.
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws NoSuchMethodException
* @throws SecurityException
*/
@SuppressWarnings("rawtypes")
public void testLastRegisteredUnload(Class expectedClass)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SecurityException, NoSuchMethodException {
Assert.assertTrue(
"juploadContext must be an instance of JUploadContextTestHelper",
this.juploadContext instanceof JUploadContextTestHelper);
Assert.assertTrue(
"The lastRegisterUnloadObject should be an instance of "
+ expectedClass,
expectedClass
.isInstance(((JUploadContextTestHelper) this.juploadContext).lastRegisterUnloadObject));
testUnload(
((JUploadContextTestHelper) this.juploadContext).lastRegisterUnloadObject,
((JUploadContextTestHelper) this.juploadContext).lastRegisterUnloadMethod);
}
/**
* This method calls a given method onto a given object.
*
* @param object
* @param methodName
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws NoSuchMethodException
* @throws SecurityException
*/
public void testUnload(Object object, String methodName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SecurityException, NoSuchMethodException {
// Let's find and call this method. This method must have no argument.
Method method = object.getClass().getMethod(methodName);
Assert.assertNotNull("The method '" + methodName
+ "' must exist (and have no argument)", method);
method.invoke(object);
}
/**
* This static class computes create a file instance for the given relative
* path.<BR>
* This method is taken from <A HREF=
* "http://kozelka.net/blog/generating-temporary-files-in-junit-tests">Petr
* Kozelka's blog</A>
*
* @param relativeFilePath The path of the file, starting from
* src/test/resources.
* @return The File for the file, whose relative path to tests folder is
* given in argument. This method is compatible with whatever tool
* is used to execute the tests: it can be from maven, from eclipse,
* or from any other tool.
*/
public static File getTestFile(String relativeFilePath) {
final String clsUri = AbstractJUploadTestHelper.class.getName()
.replace('.', File.separatorChar) + ".class";
final URL url = AbstractJUploadTestHelper.class.getClassLoader()
.getResource(clsUri);
final String clsPath = url.getPath().replaceAll("%20", " ")
.replaceAll("%5c", ".");
final File root = new File(clsPath.substring(0, clsPath.length()
- clsUri.length()));
return new File(root, relativeFilePath);
}
/**
* This method returns the absolute path for the given file. It is based on
* the {@link #getTestFile(String)} method.
*
* @param relativeFilePath The path of the file, starting from
* src/test/resources.
* @return The absolute path for the given file.
*/
public static String getTestFilePath(String relativeFilePath) {
return getTestFile(relativeFilePath).getAbsolutePath();
}
/**
* Get the root for the tests files, whatever is the current tool used to
* run JUnit test: maven, eclipse, any IDE...
*
* @return The absolute path for the test files root, ending with the file
* separator character.
*/
public static String getTestFilesRootPath() {
return getTestFilePath("files") + File.separator;
}
}
| gpl-3.0 |
gittozji/FundTrade | src/main/java/me/zji/dao/AdminInfoDao.java | 591 | package me.zji.dao;
import me.zji.entity.AdminInfo;
/**
* 管理员信息 Dao
* Created by imyu on 2017/2/23.
*/
public interface AdminInfoDao {
/**
* 创建一条记录
* @param adminInfo
*/
void create(AdminInfo adminInfo);
/**
* 通过用户名删除
* @param username
*/
void deleteByUsername(String username);
/**
* 更新一条记录
* @param adminInfo
*/
void update(AdminInfo adminInfo);
/**
* 通过用户名查找
* @param username
*/
AdminInfo queryByUsername(String username);
}
| gpl-3.0 |
eric-lemesre/OpenConcerto | OpenConcerto/src/org/openconcerto/task/TodoListElementEditorPanel.java | 4376 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.task;
import org.openconcerto.sql.users.UserManager;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TodoListElementEditorPanel extends JPanel {
private transient TodoListElement element;
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy à HH:mm");
TodoListElementEditorPanel(TodoListElement e) {
this.element = e;
System.out.println(e);
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(2, 2, 2, 2);
c.fill = GridBagConstraints.HORIZONTAL;
// Ligne 1 =====================================
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
JLabel l = new JLabel("Résumé:");
this.add(l, c);
//
c.gridx++;
c.weightx = 1;
final JTextField f = new JTextField();
f.setText(e.getName());
this.add(f, c);
// Ligne 1 bis =====================================
c.gridwidth = 2;
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
c.insets = new Insets(0, 0, 0, 0);
this.add(new JSeparator(JSeparator.HORIZONTAL), c);
// Ligne 2 =====================================
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
final JTextArea fComment = new JTextArea();
fComment.setFont(f.getFont());
fComment.setText(e.getComment());
this.add(fComment, c);
// Ligne 2 bis =====================================
c.gridwidth = 2;
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
c.weighty = 0;
this.add(new JSeparator(JSeparator.HORIZONTAL), c);
// Ligne 3 =====================================
c.gridx = 0;
c.gridy++;
c.weighty = 0;
c.gridwidth = 2;
c.insets = new Insets(2, 2, 2, 2);
c.fill = GridBagConstraints.HORIZONTAL;
JLabel label = new JLabel("A réaliser pour le " + simpleDateFormat.format(e.getExpectedDate()) + " par " + UserManager.getInstance().getUser(e.getUserId()).getFullName());
this.add(label, c);
// Ligne 4 =====================================
JButton bOk = new JButton("Ok");
bOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
element.setName(f.getText());
element.setComment(fComment.getText());
element.commitChanges();
SwingUtilities.getWindowAncestor(TodoListElementEditorPanel.this).dispose();
}
});
JButton bAnnuler = new JButton("Annuler");
bAnnuler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
SwingUtilities.getWindowAncestor(TodoListElementEditorPanel.this).dispose();
}
});
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
p.add(bOk);
p.add(bAnnuler);
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.EAST;
this.add(p, c);
}
}
| gpl-3.0 |
andrasfuchs/BioBalanceDetector | Tools/KiCad_FreeRouting/FreeRouting-miho-master/freerouting-master/src/main/java/eu/mihosoft/freerouting/autoroute/LocateFoundConnectionAlgo.java | 22361 | /*
* Copyright (C) 2014 Alfons Wirtz
* website www.freerouting.net
*
* Copyright (C) 2017 Michael Hoffer <info@michaelhoffer.de>
* Website www.freerouting.mihosoft.eu
*
* 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 at <http://www.gnu.org/licenses/>
* for more details.
*
* LocateFoundConnectionAlgo.java
*
* Created on 31. Januar 2006, 08:20
*
*/
package eu.mihosoft.freerouting.autoroute;
import java.util.Collection;
import java.util.SortedSet;
import java.util.LinkedList;
import java.util.Iterator;
import eu.mihosoft.freerouting.geometry.planar.IntPoint;
import eu.mihosoft.freerouting.geometry.planar.FloatPoint;
import eu.mihosoft.freerouting.geometry.planar.TileShape;
import eu.mihosoft.freerouting.board.Connectable;
import eu.mihosoft.freerouting.board.Item;
import eu.mihosoft.freerouting.board.AngleRestriction;
import eu.mihosoft.freerouting.board.ShapeSearchTree;
import eu.mihosoft.freerouting.board.TestLevel;
/**
*
* @author Alfons Wirtz
*/
public abstract class LocateFoundConnectionAlgo
{
/**
* Returns a new Instance of LocateFoundConnectionAlgo or null,
* if p_destination_door is null.
*/
public static LocateFoundConnectionAlgo get_instance(MazeSearchAlgo.Result p_maze_search_result, AutorouteControl p_ctrl,
ShapeSearchTree p_search_tree, AngleRestriction p_angle_restriction, SortedSet<Item> p_ripped_item_list, TestLevel p_test_level)
{
if (p_maze_search_result == null)
{
return null;
}
LocateFoundConnectionAlgo result;
if (p_angle_restriction == AngleRestriction.NINETY_DEGREE || p_angle_restriction == AngleRestriction.FORTYFIVE_DEGREE)
{
result = new LocateFoundConnectionAlgo45Degree(p_maze_search_result, p_ctrl, p_search_tree, p_angle_restriction,
p_ripped_item_list, p_test_level);
}
else
{
result = new LocateFoundConnectionAlgoAnyAngle(p_maze_search_result, p_ctrl, p_search_tree, p_angle_restriction,
p_ripped_item_list, p_test_level);
}
return result;
}
/** Creates a new instance of LocateFoundConnectionAlgo */
protected LocateFoundConnectionAlgo(MazeSearchAlgo.Result p_maze_search_result, AutorouteControl p_ctrl,
ShapeSearchTree p_search_tree, AngleRestriction p_angle_restriction, SortedSet<Item> p_ripped_item_list, TestLevel p_test_level)
{
this.ctrl = p_ctrl;
this.angle_restriction = p_angle_restriction;
this.test_level = p_test_level;
Collection<BacktrackElement> backtrack_list = backtrack(p_maze_search_result, p_ripped_item_list);
this.backtrack_array = new BacktrackElement[backtrack_list.size()];
Iterator<BacktrackElement> it = backtrack_list.iterator();
for (int i = 0; i < backtrack_array.length; ++i)
{
this.backtrack_array[i] = it.next();
}
this.connection_items = new LinkedList<ResultItem>();
BacktrackElement start_info = this.backtrack_array[backtrack_array.length - 1];
if (!(start_info.door instanceof TargetItemExpansionDoor))
{
System.out.println("LocateFoundConnectionAlgo: ItemExpansionDoor expected for start_info.door");
this.start_item = null;
this.start_layer = 0;
this.target_item = null;
this.target_layer = 0;
this.start_door = null;
return;
}
this.start_door = (TargetItemExpansionDoor) start_info.door;
this.start_item = start_door.item;
this.start_layer = start_door.room.get_layer();
this.current_from_door_index = 0;
boolean at_fanout_end = false;
if (p_maze_search_result.destination_door instanceof TargetItemExpansionDoor)
{
TargetItemExpansionDoor curr_destination_door = (TargetItemExpansionDoor) p_maze_search_result.destination_door;
this.target_item = curr_destination_door.item;
this.target_layer = curr_destination_door.room.get_layer();
this.current_from_point = calculate_starting_point(curr_destination_door, p_search_tree);
}
else if (p_maze_search_result.destination_door instanceof ExpansionDrill)
{
// may happen only in case of fanout
this.target_item = null;
ExpansionDrill curr_drill = (ExpansionDrill) p_maze_search_result.destination_door;
this.current_from_point = curr_drill.location.to_float();
this.target_layer = curr_drill.first_layer + p_maze_search_result.section_no_of_door;
at_fanout_end = true;
}
else
{
System.out.println("LocateFoundConnectionAlgo: unexpected type of destination_door");
this.target_item = null;
this.target_layer = 0;
return;
}
this.current_trace_layer = this.target_layer;
this.previous_from_point = this.current_from_point;
boolean connection_done = false;
while (!connection_done)
{
boolean layer_changed = false;
if (at_fanout_end)
{
// do not increase this.current_target_door_index
layer_changed = true;
}
else
{
this.current_target_door_index = this.current_from_door_index + 1;
while (current_target_door_index < this.backtrack_array.length && !layer_changed)
{
if (this.backtrack_array[this.current_target_door_index].door instanceof ExpansionDrill)
{
layer_changed = true;
}
else
{
++this.current_target_door_index;
}
}
}
if (layer_changed)
{
// the next trace leads to a via
ExpansionDrill current_target_drill = (ExpansionDrill) this.backtrack_array[this.current_target_door_index].door;
this.current_target_shape = TileShape.get_instance(current_target_drill.location);
}
else
{
// the next trace leads to the final target
connection_done = true;
this.current_target_door_index = this.backtrack_array.length - 1;
TileShape target_shape = ((Connectable) start_item).get_trace_connection_shape(p_search_tree, start_door.tree_entry_no);
this.current_target_shape = target_shape.intersection(start_door.room.get_shape());
if (this.current_target_shape.dimension() >= 2)
{
// the target is a conduction area, make a save connection
// by shrinking the shape by the trace halfwidth.
double trace_half_width = this.ctrl.compensated_trace_half_width[start_door.room.get_layer()];
TileShape shrinked_shape = (TileShape) this.current_target_shape.offset(-trace_half_width);
if (!shrinked_shape.is_empty())
{
this.current_target_shape = shrinked_shape;
}
}
}
this.current_to_door_index = this.current_from_door_index + 1;
ResultItem next_trace = this.calculate_next_trace(layer_changed, at_fanout_end);
at_fanout_end = false;
this.connection_items.add(next_trace);
}
}
/**
* Calclates the next trace trace of the connection under construction.
* Returns null, if all traces are returned.
*/
private ResultItem calculate_next_trace(boolean p_layer_changed, boolean p_at_fanout_end)
{
Collection<FloatPoint> corner_list = new LinkedList<FloatPoint>();
corner_list.add(this.current_from_point);
if (!p_at_fanout_end)
{
FloatPoint adjusted_start_corner = this.adjust_start_corner();
if (adjusted_start_corner != this.current_from_point)
{
FloatPoint add_corner = calculate_additional_corner(this.current_from_point, adjusted_start_corner,
true, this.angle_restriction);
corner_list.add(add_corner);
corner_list.add(adjusted_start_corner);
this.previous_from_point = this.current_from_point;
this.current_from_point = adjusted_start_corner;
}
}
FloatPoint prev_corner = this.current_from_point;
for (;;)
{
Collection<FloatPoint> next_corners = calculate_next_trace_corners();
if (next_corners.isEmpty())
{
break;
}
Iterator<FloatPoint> it = next_corners.iterator();
while (it.hasNext())
{
FloatPoint curr_next_corner = it.next();
if (curr_next_corner != prev_corner)
{
corner_list.add(curr_next_corner);
this.previous_from_point = this.current_from_point;
this.current_from_point = curr_next_corner;
prev_corner = curr_next_corner;
}
}
}
int next_layer = this.current_trace_layer;
if (p_layer_changed)
{
this.current_from_door_index = this.current_target_door_index + 1;
CompleteExpansionRoom next_room = this.backtrack_array[this.current_from_door_index].next_room;
if (next_room != null)
{
next_layer = next_room.get_layer();
}
}
// Round the new trace corners to Integer.
Collection<IntPoint> rounded_corner_list = new LinkedList<IntPoint>();
Iterator<FloatPoint> it = corner_list.iterator();
IntPoint prev_point = null;
while (it.hasNext())
{
IntPoint curr_point = (it.next()).round();
if (!curr_point.equals(prev_point))
{
rounded_corner_list.add(curr_point);
prev_point = curr_point;
}
}
// Construct the result item
IntPoint[] corner_arr = new IntPoint[rounded_corner_list.size()];
Iterator<IntPoint> it2 = rounded_corner_list.iterator();
for (int i = 0; i < corner_arr.length; ++i)
{
corner_arr[i] = it2.next();
}
ResultItem result = new ResultItem(corner_arr, this.current_trace_layer);
this.current_trace_layer = next_layer;
return result;
}
/**
* Returns the next list of corners for the construction of the trace
* in calculate_next_trace. If the result is emppty, the trace is already completed.
*/
protected abstract Collection<FloatPoint> calculate_next_trace_corners();
/** Test display of the baktrack rooms. */
public void draw(java.awt.Graphics p_graphics, eu.mihosoft.freerouting.boardgraphics.GraphicsContext p_graphics_context)
{
for (int i = 0; i < backtrack_array.length; ++i)
{
CompleteExpansionRoom next_room = backtrack_array[i].next_room;
if (next_room != null)
{
next_room.draw(p_graphics, p_graphics_context, 0.2);
}
ExpandableObject next_door = backtrack_array[i].door;
if (next_door instanceof ExpansionDrill)
{
((ExpansionDrill) next_door).draw(p_graphics, p_graphics_context, 0.2);
}
}
}
/**
* Calculates the starting point of the next trace on p_from_door.item.
* The implementation is not yet optimal for starting points on traces
* or areas.
*/
private static FloatPoint calculate_starting_point(TargetItemExpansionDoor p_from_door, ShapeSearchTree p_search_tree)
{
TileShape connection_shape =
((Connectable) p_from_door.item).get_trace_connection_shape(p_search_tree, p_from_door.tree_entry_no);
connection_shape = connection_shape.intersection(p_from_door.room.get_shape());
return connection_shape.centre_of_gravity().round().to_float();
}
/**
* Creates a list of doors by backtracking from p_destination_door to
* the start door.
* Returns null, if p_destination_door is null.
*/
private static Collection<BacktrackElement> backtrack(MazeSearchAlgo.Result p_maze_search_result, SortedSet<Item> p_ripped_item_list)
{
if (p_maze_search_result == null)
{
return null;
}
Collection<BacktrackElement> result = new LinkedList<BacktrackElement>();
CompleteExpansionRoom curr_next_room = null;
ExpandableObject curr_backtrack_door = p_maze_search_result.destination_door;
MazeSearchElement curr_maze_search_element = curr_backtrack_door.get_maze_search_element(p_maze_search_result.section_no_of_door);
if (curr_backtrack_door instanceof TargetItemExpansionDoor)
{
curr_next_room = ((TargetItemExpansionDoor) curr_backtrack_door).room;
}
else if (curr_backtrack_door instanceof ExpansionDrill)
{
ExpansionDrill curr_drill = (ExpansionDrill) curr_backtrack_door;
curr_next_room = curr_drill.room_arr[curr_drill.first_layer + p_maze_search_result.section_no_of_door];
if (curr_maze_search_element.room_ripped)
{
for (CompleteExpansionRoom tmp_room : curr_drill.room_arr)
{
if (tmp_room instanceof ObstacleExpansionRoom)
{
p_ripped_item_list.add(((ObstacleExpansionRoom) tmp_room).get_item());
}
}
}
}
BacktrackElement curr_backtrack_element = new BacktrackElement(curr_backtrack_door, p_maze_search_result.section_no_of_door, curr_next_room);
for (;;)
{
result.add(curr_backtrack_element);
curr_backtrack_door = curr_maze_search_element.backtrack_door;
if (curr_backtrack_door == null)
{
break;
}
int curr_section_no = curr_maze_search_element.section_no_of_backtrack_door;
if (curr_section_no >= curr_backtrack_door.maze_search_element_count())
{
System.out.println("LocateFoundConnectionAlgo: curr_section_no to big");
curr_section_no = curr_backtrack_door.maze_search_element_count() - 1;
}
if (curr_backtrack_door instanceof ExpansionDrill)
{
ExpansionDrill curr_drill = (ExpansionDrill) curr_backtrack_door;
curr_next_room = curr_drill.room_arr[curr_section_no];
}
else
{
curr_next_room = curr_backtrack_door.other_room(curr_next_room);
}
curr_maze_search_element = curr_backtrack_door.get_maze_search_element(curr_section_no);
curr_backtrack_element = new BacktrackElement(curr_backtrack_door, curr_section_no, curr_next_room);
if (curr_maze_search_element.room_ripped)
{
if (curr_next_room instanceof ObstacleExpansionRoom)
{
p_ripped_item_list.add(((ObstacleExpansionRoom) curr_next_room).get_item());
}
}
}
return result;
}
/**
* Adjusts the start corner, so that a trace starting at this corner is completely
* contained in the start room.
*/
private FloatPoint adjust_start_corner()
{
if (this.current_from_door_index < 0)
{
return this.current_from_point;
}
BacktrackElement curr_from_info = this.backtrack_array[this.current_from_door_index];
if (curr_from_info.next_room == null)
{
return this.current_from_point;
}
double trace_half_width = this.ctrl.compensated_trace_half_width[this.current_trace_layer];
TileShape shrinked_room_shape = (TileShape) curr_from_info.next_room.get_shape().offset(-trace_half_width);
if (shrinked_room_shape.is_empty() || shrinked_room_shape.contains(this.current_from_point))
{
return this.current_from_point;
}
return shrinked_room_shape.nearest_point_approx(this.current_from_point).round().to_float();
}
private static FloatPoint ninety_degree_corner(FloatPoint p_from_point, FloatPoint p_to_point,
boolean p_horizontal_first)
{
double x;
double y;
if (p_horizontal_first)
{
x = p_to_point.x;
y = p_from_point.y;
}
else
{
x = p_from_point.x;
y = p_to_point.y;
}
return new FloatPoint(x, y);
}
private static FloatPoint fortyfive_degree_corner(FloatPoint p_from_point, FloatPoint p_to_point,
boolean p_horizontal_first)
{
double abs_dx = Math.abs(p_to_point.x - p_from_point.x);
double abs_dy = Math.abs(p_to_point.y - p_from_point.y);
double x;
double y;
if (abs_dx <= abs_dy)
{
if (p_horizontal_first)
{
x = p_to_point.x;
if (p_to_point.y >= p_from_point.y)
{
y = p_from_point.y + abs_dx;
}
else
{
y = p_from_point.y - abs_dx;
}
}
else
{
x = p_from_point.x;
if (p_to_point.y > p_from_point.y)
{
y = p_to_point.y - abs_dx;
}
else
{
y = p_to_point.y + abs_dx;
}
}
}
else
{
if (p_horizontal_first)
{
y = p_from_point.y;
if (p_to_point.x > p_from_point.x)
{
x = p_to_point.x - abs_dy;
}
else
{
x = p_to_point.x + abs_dy;
}
}
else
{
y = p_to_point.y;
if (p_to_point.x > p_from_point.x)
{
x = p_from_point.x + abs_dy;
}
else
{
x = p_from_point.x - abs_dy;
}
}
}
return new FloatPoint(x, y);
}
/**
* Calculates an additional corner, so that for the lines from p_from_point to the result corner
* and from the result corner to p_to_point p_angle_restriction is fulfilled.
*/
static FloatPoint calculate_additional_corner(FloatPoint p_from_point, FloatPoint p_to_point,
boolean p_horizontal_first, AngleRestriction p_angle_restriction)
{
FloatPoint result;
if (p_angle_restriction == AngleRestriction.NINETY_DEGREE)
{
result = ninety_degree_corner(p_from_point, p_to_point, p_horizontal_first);
}
else if (p_angle_restriction == AngleRestriction.FORTYFIVE_DEGREE)
{
result = fortyfive_degree_corner(p_from_point, p_to_point, p_horizontal_first);
}
else
{
result = p_to_point;
}
return result;
}
/** The new items implementing the found connection */
public final Collection<ResultItem> connection_items;
/** The start item of the new routed connection */
public final Item start_item;
/** The layer of the connection to the start item */
public final int start_layer;
/** The destination item of the new routed connection */
public final Item target_item;
/** The layer of the connection to the target item */
public final int target_layer;
/**
* The array of backtrack doors from the destination to the start of a found
* connection of the maze search algorithm.
*/
protected final BacktrackElement[] backtrack_array;
protected final AutorouteControl ctrl;
protected final AngleRestriction angle_restriction;
protected final TestLevel test_level;
protected final TargetItemExpansionDoor start_door;
protected FloatPoint current_from_point;
protected FloatPoint previous_from_point;
protected int current_trace_layer;
protected int current_from_door_index;
protected int current_to_door_index;
protected int current_target_door_index;
protected TileShape current_target_shape;
/**
* Type of a single item in the result list connection_items.
* Used to create a new PolylineTrace.
*/
protected static class ResultItem
{
public ResultItem(IntPoint[] p_corners, int p_layer)
{
corners = p_corners;
layer = p_layer;
}
public final IntPoint[] corners;
public final int layer;
}
/**
* Type of the elements of the list returned by this.backtrack().
* Next_room is the common room of the current door and the next
* door in the backtrack list.
*/
protected static class BacktrackElement
{
private BacktrackElement(ExpandableObject p_door, int p_section_no_of_door, CompleteExpansionRoom p_room)
{
door = p_door;
section_no_of_door = p_section_no_of_door;
next_room = p_room;
}
public final ExpandableObject door;
public final int section_no_of_door;
public final CompleteExpansionRoom next_room;
}
}
| gpl-3.0 |
Belobobr/Eventsource | todoTxtBackend/src/main/java/com/google/todotxt/backend/RegistrationRecord.java | 572 | package com.google.todotxt.backend;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
/** The Objectify object model for device registrations we are persisting */
@Entity
public class RegistrationRecord {
@Id
Long id;
@Index
private String regId;
// you can add more fields...
public RegistrationRecord() {}
public String getRegId() {
return regId;
}
public void setRegId(String regId) {
this.regId = regId;
}
} | gpl-3.0 |
MIND-Tools/mind-compiler | adl-frontend/src/main/java/org/ow2/mind/adl/imports/ImportDefinitionReferenceResolver.java | 4188 | /**
* Copyright (C) 2009 STMicroelectronics
*
* This file is part of "Mind Compiler" is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: mind@ow2.org
*
* Authors: Matthieu Leclercq
* Contributors:
*/
package org.ow2.mind.adl.imports;
import static org.ow2.mind.NameHelper.getPackageName;
import static org.ow2.mind.adl.imports.ast.ImportASTHelper.isOnDemandImport;
import static org.ow2.mind.adl.imports.ast.ImportASTHelper.setUsedImport;
import java.util.Map;
import org.objectweb.fractal.adl.ADLException;
import org.objectweb.fractal.adl.Definition;
import org.ow2.mind.adl.ADLLocator;
import org.ow2.mind.adl.DefinitionReferenceResolver;
import org.ow2.mind.adl.DefinitionReferenceResolver.AbstractDelegatingDefinitionReferenceResolver;
import org.ow2.mind.adl.ast.DefinitionReference;
import org.ow2.mind.adl.imports.ast.Import;
import org.ow2.mind.adl.imports.ast.ImportContainer;
import com.google.inject.Inject;
/**
* Delegating {@link DefinitionReferenceResolver} that uses {@link Import} nodes
* of the <code>encapsulatingDefinition</code> to complete the name contained in
* the definition reference to resolve.
*/
public class ImportDefinitionReferenceResolver
extends
AbstractDelegatingDefinitionReferenceResolver {
@Inject
protected ADLLocator adlLocatorItf;
// ---------------------------------------------------------------------------
// Implementation of the DefinitionReferenceResolver interface
// ---------------------------------------------------------------------------
public Definition resolve(final DefinitionReference reference,
final Definition encapsulatingDefinition,
final Map<Object, Object> context) throws ADLException {
reference.setName(resolveName(reference.getName(), encapsulatingDefinition,
context));
return clientResolverItf.resolve(reference, encapsulatingDefinition,
context);
}
protected String resolveName(final String name,
final Definition encapsilatingDefinition,
final Map<Object, Object> context) {
if (name.contains(".")) {
return name;
}
final Import[] imports = (encapsilatingDefinition instanceof ImportContainer)
? ((ImportContainer) encapsilatingDefinition).getImports()
: null;
if (imports != null) {
for (final Import imp : imports) {
if (isOnDemandImport(imp)) {
// on-demand import.
final String fullyQualifiedName = imp.getPackageName() + '.' + name;
if (adlLocatorItf.findBinaryADL(fullyQualifiedName, context) != null
|| adlLocatorItf.findSourceADL(fullyQualifiedName, context) != null) {
return fullyQualifiedName;
}
} else {
if (imp.getSimpleName().equals(name)) {
// import simple name matches
setUsedImport(imp);
return imp.getPackageName() + '.' + name;
}
}
}
}
if (encapsilatingDefinition != null) {
final String packageName = getPackageName(encapsilatingDefinition
.getName());
// try in current package.
if (packageName != null) {
final String fullyQualifiedName = packageName + '.' + name;
if (adlLocatorItf.findBinaryADL(fullyQualifiedName, context) != null
|| adlLocatorItf.findSourceADL(fullyQualifiedName, context) != null) {
return fullyQualifiedName;
}
}
}
// no import match, return the name as it is (i.e. assume that it refers to
// an ADL in the 'default package').
return name;
}
}
| gpl-3.0 |
grtlinux/KIEA_JAVA7 | KIEA_JAVA7/src/tain/kr/com/test/file/v02/FileInfoBean.java | 2390 | /**
* Copyright 2014, 2015, 2016 TAIN, Inc. all rights reserved.
*
* Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007 (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.gnu.org/licenses/
*
* 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.
*
* -----------------------------------------------------------------
* Copyright 2014, 2015, 2016 TAIN, Inc.
*
*/
package tain.kr.com.test.file.v02;
/**
*
* Code Templates > Comments > Types
*
* <PRE>
* -. FileName : FileInfoBean.java
* -. Package : tain.kr.com.test.file.v02
* -. Comment :
* -. Author : taincokr
* -. First Date : 2016. 2. 2. {time}
* </PRE>
*
* @author taincokr
*
*/
public class FileInfoBean {
private static boolean flag = true;
private String type; // file type : RF(Remote File), LF(Local File), RD(Remote File Download), LU(Local File Upload)
private String base; // base path name
private String name; // file name except base path name
private long time; // last modified time by millisecond
private long length; // file size
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
///////////////////////////////////////////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
if (flag) {
sb.append(this.type).append("||");
sb.append(this.base).append("||");
sb.append(this.name).append("||");
sb.append(this.time).append("||");
sb.append(this.length);
}
return sb.toString();
}
}
| gpl-3.0 |
robward-scisys/sldeditor | modules/application/src/main/java/com/sldeditor/filter/v2/function/temporal/MetBy.java | 4262 | /*
* SLD Editor - The Open Source Java SLD Editor
*
* Copyright (C) 2018, SCISYS UK Limited
*
* 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.sldeditor.filter.v2.function.temporal;
import com.sldeditor.filter.v2.expression.ExpressionTypeEnum;
import com.sldeditor.filter.v2.function.FilterBase;
import com.sldeditor.filter.v2.function.FilterConfigInterface;
import com.sldeditor.filter.v2.function.FilterExtendedInterface;
import com.sldeditor.filter.v2.function.FilterName;
import com.sldeditor.filter.v2.function.FilterNameParameter;
import java.util.Date;
import java.util.List;
import org.geotools.filter.temporal.MetByImpl;
import org.opengis.filter.Filter;
import org.opengis.filter.expression.Expression;
/**
* The Class MetBy.
*
* @author Robert Ward (SCISYS)
*/
public class MetBy extends FilterBase implements FilterConfigInterface {
/** The Class MetByExtended. */
public class MetByExtended extends MetByImpl implements FilterExtendedInterface {
/** Instantiates a new after extended. */
public MetByExtended() {
super(null, null);
}
/**
* Instantiates a new after extended.
*
* @param expression1 the expression 1
* @param expression2 the expression 2
*/
public MetByExtended(Expression expression1, Expression expression2) {
super(expression1, expression2);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "[ " + getExpression1() + " MetBy " + getExpression2() + " ]";
}
/*
* (non-Javadoc)
*
* @see com.sldeditor.filter.v2.function.FilterExtendedInterface#getOriginalFilter()
*/
@Override
public Class<?> getOriginalFilter() {
return MetByImpl.class;
}
}
/** Default constructor. */
public MetBy(String category) {
super(category);
}
/**
* Gets the filter configuration.
*
* @return the filter configuration
*/
@Override
public FilterName getFilterConfiguration() {
FilterName filterName = new FilterName("MetBy", Boolean.class);
filterName.addParameter(
new FilterNameParameter("property", ExpressionTypeEnum.PROPERTY, Date.class));
filterName.addParameter(
new FilterNameParameter("datetime", ExpressionTypeEnum.LITERAL, Date.class));
return filterName;
}
/**
* Gets the filter class.
*
* @return the filter class
*/
@Override
public Class<?> getFilterClass() {
return MetByImpl.class;
}
/**
* Creates the filter.
*
* @return the filter
*/
@Override
public Filter createFilter() {
return new MetByExtended();
}
/**
* Creates the filter.
*
* @param parameterList the parameter list
* @return the filter
*/
@Override
public Filter createFilter(List<Expression> parameterList) {
MetByImpl filter = null;
if ((parameterList == null) || (parameterList.size() != 2)) {
filter = new MetByExtended();
} else {
filter = new MetByExtended(parameterList.get(0), parameterList.get(1));
}
return filter;
}
/**
* Creates the logic filter.
*
* @param filterList the filter list
* @return the filter
*/
@Override
public Filter createLogicFilter(List<Filter> filterList) {
// Not supported
return null;
}
}
| gpl-3.0 |
cams7/erp | freedom/src/main/java/org/freedom/modulos/fnc/business/component/cnab/RegTrailer.java | 4314 | package org.freedom.modulos.fnc.business.component.cnab;
import org.freedom.infra.functions.StringFunctions;
import org.freedom.library.business.component.Banco;
import org.freedom.library.business.exceptions.ExceptionCnab;
import org.freedom.modulos.fnc.library.business.compoent.FbnUtil.ETipo;
public class RegTrailer extends Reg {
private String codBanco;
private String loteServico;
private String registroTrailer;
private String conta;
private int qtdLotes;
private int qtdRegistros;
private int qtdConsilacoes;
private int seqregistro;
public RegTrailer() {
setLoteServico( "9999" );
setRegistroTrailer( "9" );
}
public int getSeqregistro() {
return seqregistro;
}
public void setSeqregistro( int seqregistro ) {
this.seqregistro = seqregistro;
}
public String getCodBanco() {
return codBanco;
}
public void setCodBanco( final String codBanco ) {
this.codBanco = codBanco;
}
public String getLoteServico() {
return loteServico;
}
private void setLoteServico( final String loteServico ) {
this.loteServico = loteServico;
}
public int getQtdConsilacoes() {
return qtdConsilacoes;
}
public void setQtdConsilacoes( final int qtdConsilacoes ) {
this.qtdConsilacoes = qtdConsilacoes;
}
public int getQtdLotes() {
return qtdLotes;
}
public void setQtdLotes( final int qtdLotes ) {
this.qtdLotes = qtdLotes;
}
public int getQtdRegistros() {
return qtdRegistros;
}
public void setQtdRegistros( final int qtdRegistros ) {
this.qtdRegistros = qtdRegistros;
}
public String getRegistroTrailer() {
return registroTrailer;
}
private void setRegistroTrailer( final String regTrailer ) {
this.registroTrailer = regTrailer;
}
public String getConta() {
return conta;
}
public void setConta( String codConta ) {
this.conta = codConta;
}
@ Override
public String getLine( String padraocnab ) throws ExceptionCnab {
StringBuilder line = new StringBuilder();
try {
if ( padraocnab.equals( CNAB_240 ) ) {
line.append( format( getCodBanco(), ETipo.$9, 3, 0 ) );
line.append( format( getLoteServico(), ETipo.$9, 4, 0 ) );
line.append( format( getRegistroTrailer(), ETipo.$9, 1, 0 ) );
line.append( StringFunctions.replicate( " ", 9 ) );
line.append( format( getQtdLotes(), ETipo.$9, 6, 0 ) );
line.append( format( getQtdRegistros(), ETipo.$9, 6, 0 ) );
line.append( format( getQtdConsilacoes(), ETipo.$9, 6, 0 ) );
line.append( StringFunctions.replicate( " ", 205 ) );
}
else if ( padraocnab.equals( CNAB_400 ) ) {
line.append( StringFunctions.replicate( "9", 1 ) ); // Posição 001 a 001 - Identificação do registro
if( getCodBanco().equals( Banco.SICRED )){
line.append( "1" );
line.append( getCodBanco() );
line.append( format( getConta(), ETipo.$9, 5, 0 ) );
line.append( StringFunctions.replicate( " ", 384 ) );
} else {
line.append( StringFunctions.replicate( " ", 393 ) ); // Posição 002 a 394 - Branco
}
line.append( format( seqregistro, ETipo.$9, 6, 0 ) ); // Posição 395 a 400 - Nro Sequancial do ultimo registro
}
} catch ( Exception e ) {
throw new ExceptionCnab( "CNAB registro trailer.\nErro ao escrever registro.\n" + e.getMessage() );
}
line.append( (char) 13 );
line.append( (char) 10 );
return line.toString();
}
/*
* (non-Javadoc)
*
* @see org.freedom.modulos.fnc.CnabUtil.Reg#parseLine(java.lang.String)
*/
@ Override
public void parseLine( String line ) throws ExceptionCnab {
try {
if ( line == null ) {
throw new ExceptionCnab( "Linha nula." );
}
else {
setCodBanco( line.substring( 0, 3 ) );
setLoteServico( line.substring( 3, 7 ) );
setRegistroTrailer( line.substring( 7, 8 ) );
setQtdRegistros( line.substring( 17, 23 ).trim().length() > 0 ? Integer.parseInt( line.substring( 17, 23 ).trim() ) : 0 );
setQtdLotes( line.substring( 23, 29 ).trim().length() > 0 ? Integer.parseInt( line.substring( 23, 29 ).trim() ) : 0 );
setQtdRegistros( line.substring( 29, 35 ).trim().length() > 0 ? Integer.parseInt( line.substring( 29, 35 ).trim() ) : 0 );
}
} catch ( Exception e ) {
throw new ExceptionCnab( "CNAB registro trailer.\nErro ao ler registro.\n" + e.getMessage() );
}
}
}
| gpl-3.0 |
mustafaberkaymutlu/ytu-homeworks | Introduction to Mobile Programming -- 2015-2016/Phone State/PhoneState/app/src/main/java/berkay/ders/mobilprogramlama/phonestate/MainActivity.java | 4066 | package berkay.ders.mobilprogramlama.phonestate;
import android.content.Intent;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private ImageView imageView_statusIcon;
private TextView textView_activeTime;
private TextView textView_passiveTime;
private SensorResultReceiver mSensorResultReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorResultReceiver = new SensorResultReceiver(null);
imageView_statusIcon = (ImageView) findViewById(R.id.imageView_mainActivity_statusIcon);
textView_activeTime = (TextView) findViewById(R.id.textView_mainActivity_activeTime);
textView_passiveTime = (TextView) findViewById(R.id.textView_mainActivity_passiveTime);
justUpdateUI();
}
public void button_mainActivity_start_onClick(View view){
Intent mainServiceIntent = new Intent(this, MainService.class);
mainServiceIntent.setAction(Config.ACTION_SERVICE_START_LISTENING);
mainServiceIntent.putExtra(Config.TAG_SENSOR_RESULT_RECEIVER, mSensorResultReceiver);
startService(mainServiceIntent);
}
public void button_mainActivity_stop_onClick(View view){
Intent mainServiceIntent = new Intent(this, MainService.class);
mainServiceIntent.setAction(Config.ACTION_SERVICE_STOP_LISTENING);
mainServiceIntent.putExtra(Config.TAG_SENSOR_RESULT_RECEIVER, mSensorResultReceiver);
startService(mainServiceIntent);
}
public void justUpdateUI(){
Intent mainServiceIntent = new Intent(this, MainService.class);
mainServiceIntent.setAction(Config.ACTION_SERVICE_JUST_UPDATE_UI);
mainServiceIntent.putExtra(Config.TAG_SENSOR_RESULT_RECEIVER, mSensorResultReceiver);
startService(mainServiceIntent);
}
public class SensorResultReceiver extends ResultReceiver{
public SensorResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if(resultCode == Config.RESULT_CODE_OK){
long activeTime = resultData.getLong(Config.TAG_ACTIVE_TIME);
long passiveTime = resultData.getLong(Config.TAG_PASSIVE_TIME);
float accelerometerValue = resultData.getFloat(Config.TAG_ACCELEROMETER_VALUE);
runOnUiThread(new UpdateUI(activeTime, passiveTime, accelerometerValue));
}
}
}
private class UpdateUI implements Runnable{
long activeTime, passiveTime;
float accelerometerValue;
SimpleDateFormat dateFormat = new SimpleDateFormat("s", Locale.ENGLISH);
public UpdateUI(long activeTime, long passiveTime, float accelerometerValue) {
this.activeTime = activeTime;
this.passiveTime = passiveTime;
this.accelerometerValue = accelerometerValue;
}
public void run() {
textView_activeTime.setText(String.format("%d " + getString(R.string.seconds_short), Integer.parseInt(dateFormat.format(activeTime))));
textView_passiveTime.setText(String.format("%d " + getString(R.string.seconds_short), Integer.parseInt(dateFormat.format(passiveTime))));
if(accelerometerValue < Config.ACTIVE_THRESHOLD ){
imageView_statusIcon.setBackgroundResource(R.drawable.standing);
} else if(accelerometerValue < Config.VERY_ACTIVE_THRESHOLD ){
imageView_statusIcon.setBackgroundResource(R.drawable.moving);
} else{
imageView_statusIcon.setBackgroundResource(R.drawable.dancing);
}
}
}
}
| gpl-3.0 |
anvarzkr/symphony | src/main/java/org/b3log/symphony/processor/CommentProcessor.java | 15876 | /*
* Symphony - A modern community (forum/SNS/blog) platform written in Java.
* Copyright (C) 2012-2017, b3log.org & hacpai.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.b3log.symphony.processor;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.User;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.Before;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.util.Requests;
import org.b3log.symphony.model.*;
import org.b3log.symphony.processor.advice.CSRFCheck;
import org.b3log.symphony.processor.advice.LoginCheck;
import org.b3log.symphony.processor.advice.PermissionCheck;
import org.b3log.symphony.processor.advice.validate.ClientCommentAddValidation;
import org.b3log.symphony.processor.advice.validate.CommentAddValidation;
import org.b3log.symphony.service.*;
import org.json.JSONObject;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* Comment processor.
* <p>
* <ul>
* <li>Adds a comment (/comment) <em>locally</em>, POST</li>
* <li>Adds a comment (/solo/comment) <em>remotely</em>, POST</li>
* <li>Thanks a comment (/comment/thank), POST</li>
* <li>Gets a comment's replies (/comment/replies), GET </li>
* </ul>
* </p>
* <p>
* The '<em>locally</em>' means user post a comment on Symphony directly rather than receiving a comment from externally
* (for example Solo).
* </p>
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.5.1.13, Jan 21, 2017
* @since 0.2.0
*/
@RequestProcessor
public class CommentProcessor {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(CommentProcessor.class.getName());
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* Comment management service.
*/
@Inject
private CommentMgmtService commentMgmtService;
/**
* Comment query service.
*/
@Inject
private CommentQueryService commentQueryService;
/**
* Client management service.
*/
@Inject
private ClientMgmtService clientMgmtService;
/**
* Client query service.
*/
@Inject
private ClientQueryService clientQueryService;
/**
* Article query service.
*/
@Inject
private ArticleQueryService articleQueryService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Reward query service.
*/
@Inject
private RewardQueryService rewardQueryService;
/**
* Gets a comment's original comment.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/comment/original", method = HTTPRequestMethod.POST)
public void getOriginalComment(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, context.getResponse());
final String commentId = requestJSONObject.optString(Comment.COMMENT_T_ID);
int commentViewMode = requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE);
int avatarViewMode = UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL;
final JSONObject currentUser = userQueryService.getCurrentUser(request);
if (null != currentUser) {
avatarViewMode = currentUser.optInt(UserExt.USER_AVATAR_VIEW_MODE);
}
final JSONObject originalCmt = commentQueryService.getOriginalComment(avatarViewMode, commentViewMode, commentId);
// Fill thank
final String originalCmtId = originalCmt.optString(Keys.OBJECT_ID);
if (null != currentUser) {
originalCmt.put(Common.REWARDED,
rewardQueryService.isRewarded(currentUser.optString(Keys.OBJECT_ID),
originalCmtId, Reward.TYPE_C_COMMENT));
}
originalCmt.put(Common.REWARED_COUNT, rewardQueryService.rewardedCount(originalCmtId, Reward.TYPE_C_COMMENT));
context.renderJSON(true).renderJSONValue(Comment.COMMENT_T_REPLIES, (Object) originalCmt);
}
/**
* Gets a comment's replies.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/comment/replies", method = HTTPRequestMethod.POST)
public void getReplies(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, context.getResponse());
final String commentId = requestJSONObject.optString(Comment.COMMENT_T_ID);
int commentViewMode = requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE);
int avatarViewMode = UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL;
final JSONObject currentUser = userQueryService.getCurrentUser(request);
if (null != currentUser) {
avatarViewMode = currentUser.optInt(UserExt.USER_AVATAR_VIEW_MODE);
}
final List<JSONObject> replies = commentQueryService.getReplies(avatarViewMode, commentViewMode, commentId);
// Fill reply thank
for (final JSONObject reply : replies) {
final String replyId = reply.optString(Keys.OBJECT_ID);
if (null != currentUser) {
reply.put(Common.REWARDED,
rewardQueryService.isRewarded(currentUser.optString(Keys.OBJECT_ID),
replyId, Reward.TYPE_C_COMMENT));
}
reply.put(Common.REWARED_COUNT, rewardQueryService.rewardedCount(replyId, Reward.TYPE_C_COMMENT));
}
context.renderJSON(true).renderJSONValue(Comment.COMMENT_T_REPLIES, (Object) replies);
}
/**
* Adds a comment locally.
* <p>
* The request json object (a comment):
* <pre>
* {
* "articleId": "",
* "commentContent": "",
* "commentAnonymous": boolean,
* "commentOriginalCommentId": "", // optional
* "userCommentViewMode": int
* }
* </pre>
* </p>
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws IOException io exception
* @throws ServletException servlet exception
*/
@RequestProcessing(value = "/comment", method = HTTPRequestMethod.POST)
@Before(adviceClass = {CSRFCheck.class, CommentAddValidation.class, PermissionCheck.class})
public void addComment(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws IOException, ServletException {
context.renderJSON();
final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
final String articleId = requestJSONObject.optString(Article.ARTICLE_T_ID);
final String commentContent = requestJSONObject.optString(Comment.COMMENT_CONTENT);
final String commentOriginalCommentId = requestJSONObject.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID);
final int commentViewMode = requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE);
final String ip = Requests.getRemoteAddr(request);
final String ua = request.getHeader("User-Agent");
final boolean isAnonymous = requestJSONObject.optBoolean(Comment.COMMENT_ANONYMOUS, false);
final JSONObject comment = new JSONObject();
comment.put(Comment.COMMENT_CONTENT, commentContent);
comment.put(Comment.COMMENT_ON_ARTICLE_ID, articleId);
comment.put(UserExt.USER_COMMENT_VIEW_MODE, commentViewMode);
comment.put(Comment.COMMENT_IP, "");
if (StringUtils.isNotBlank(ip)) {
comment.put(Comment.COMMENT_IP, ip);
}
comment.put(Comment.COMMENT_UA, "");
if (StringUtils.isNotBlank(ua)) {
comment.put(Comment.COMMENT_UA, ua);
}
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, commentOriginalCommentId);
try {
final JSONObject currentUser = userQueryService.getCurrentUser(request);
if (null == currentUser) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
final String currentUserName = currentUser.optString(User.USER_NAME);
final JSONObject article = articleQueryService.getArticle(articleId);
final String articleContent = article.optString(Article.ARTICLE_CONTENT);
final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject articleAuthor = userQueryService.getUser(articleAuthorId);
final String articleAuthorName = articleAuthor.optString(User.USER_NAME);
final Set<String> userNames = userQueryService.getUserNames(articleContent);
if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)
&& !articleAuthorName.equals(currentUserName)) {
boolean invited = false;
for (final String userName : userNames) {
if (userName.equals(currentUserName)) {
invited = true;
break;
}
}
if (!invited) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
comment.put(Comment.COMMENT_AUTHOR_ID, currentUser.optString(Keys.OBJECT_ID));
comment.put(Comment.COMMENT_T_COMMENTER, currentUser);
comment.put(Comment.COMMENT_ANONYMOUS, isAnonymous
? Comment.COMMENT_ANONYMOUS_C_ANONYMOUS : Comment.COMMENT_ANONYMOUS_C_PUBLIC);
commentMgmtService.addComment(comment);
context.renderTrueResult();
} catch (final ServiceException e) {
context.renderMsg(e.getMessage());
}
}
/**
* Adds a comment remotely.
* <p>
* The request json object (a comment):
* <pre>
* {
* "comment": {
* "commentId": "", // client comment id
* "articleId": "",
* "commentContent": "",
* "commentAuthorName": "", // optional, 'default commenter'
* "commentAuthorEmail": "" // optional, 'default commenter'
* },
* "clientName": "",
* "clientVersion": "",
* "clientHost": "",
* "clientRuntimeEnv": "" // LOCAL
* "clientAdminEmail": "",
* "userB3Key": ""
* }
* </pre>
* </p>
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/solo/comment", method = HTTPRequestMethod.POST)
@Before(adviceClass = ClientCommentAddValidation.class)
public void addCommentFromSolo(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
LOGGER.log(Level.DEBUG, "Adds a comment from solo");
final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
final JSONObject originalCmt = requestJSONObject.optJSONObject(Comment.COMMENT);
final JSONObject article = (JSONObject) request.getAttribute(Article.ARTICLE);
final String ip = Requests.getRemoteAddr(request);
final String ua = request.getHeader("User-Agent");
final JSONObject defaultCommenter = userQueryService.getDefaultCommenter();
final JSONObject comment = new JSONObject();
comment.put(Comment.COMMENT_AUTHOR_ID, defaultCommenter.optString(Keys.OBJECT_ID));
comment.put(Comment.COMMENT_CLIENT_COMMENT_ID, originalCmt.optString(Comment.COMMENT_T_ID));
comment.put(Comment.COMMENT_CONTENT, originalCmt.optString(Comment.COMMENT_CONTENT));
comment.put(Comment.COMMENT_ON_ARTICLE_ID, article.optString(Keys.OBJECT_ID));
comment.put(Comment.COMMENT_T_COMMENTER, defaultCommenter);
comment.put(Comment.COMMENT_IP, "");
if (StringUtils.isNotBlank(ip)) {
comment.put(Comment.COMMENT_IP, ip);
}
comment.put(Comment.COMMENT_UA, "");
if (StringUtils.isNotBlank(ua)) {
comment.put(Comment.COMMENT_UA, ua);
}
comment.put(Comment.COMMENT_T_AUTHOR_NAME, originalCmt.optString(Comment.COMMENT_T_AUTHOR_NAME));
commentMgmtService.addComment(comment);
// Updates client record
final String clientAdminEmail = requestJSONObject.optString(Client.CLIENT_ADMIN_EMAIL);
final String clientName = requestJSONObject.optString(Client.CLIENT_NAME);
final String clientVersion = requestJSONObject.optString(Client.CLIENT_VERSION);
final String clientHost = requestJSONObject.optString(Client.CLIENT_HOST);
final String clientRuntimeEnv = requestJSONObject.optString(Client.CLIENT_RUNTIME_ENV);
JSONObject client = clientQueryService.getClientByAdminEmail(clientAdminEmail);
if (null == client) {
client = new JSONObject();
client.put(Client.CLIENT_ADMIN_EMAIL, clientAdminEmail);
client.put(Client.CLIENT_HOST, clientHost);
client.put(Client.CLIENT_NAME, clientName);
client.put(Client.CLIENT_RUNTIME_ENV, clientRuntimeEnv);
client.put(Client.CLIENT_VERSION, clientVersion);
client.put(Client.CLIENT_LATEST_ADD_COMMENT_TIME, System.currentTimeMillis());
client.put(Client.CLIENT_LATEST_ADD_ARTICLE_TIME, 0L);
clientMgmtService.addClient(client);
} else {
client.put(Client.CLIENT_ADMIN_EMAIL, clientAdminEmail);
client.put(Client.CLIENT_HOST, clientHost);
client.put(Client.CLIENT_NAME, clientName);
client.put(Client.CLIENT_RUNTIME_ENV, clientRuntimeEnv);
client.put(Client.CLIENT_VERSION, clientVersion);
client.put(Client.CLIENT_LATEST_ADD_COMMENT_TIME, System.currentTimeMillis());
clientMgmtService.updateClient(client);
}
LOGGER.log(Level.DEBUG, "Added a comment from solo");
}
}
| gpl-3.0 |
tvesalainen/util | util/src/test/java/org/vesalainen/time/MutableInstantTest.java | 2464 | /*
* Copyright (C) 2019 Timo Vesalainen <timo.vesalainen@iki.fi>
*
* 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.vesalainen.time;
import java.time.Instant;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Timo Vesalainen <timo.vesalainen@iki.fi>
*/
public class MutableInstantTest
{
public MutableInstantTest()
{
}
@Test
public void test1()
{
MutableInstant mi = new MutableInstant(10, -1);
assertEquals(9, mi.second());
assertEquals(999999999L, mi.nano());
}
@Test
public void test2()
{
MutableInstant mi = new MutableInstant(10, 1000000000);
assertEquals(11, mi.second());
assertEquals(0L, mi.nano());
}
@Test
public void testPlus()
{
MutableInstant mi = MutableInstant.now();
Instant exp = mi.instant();
assertEquals(exp.toEpochMilli(), mi.millis());
assertTrue(mi.isEqual(exp));
long v = 12345678912345L;
mi.plus(v);
assertTrue(mi.isEqual(exp.plusNanos(v)));
}
@Test
public void testUntil()
{
long v = 12345678912345L;
MutableInstant mi1 = MutableInstant.now();
MutableInstant mi2 = new MutableInstant(mi1);
assertTrue(mi1.compareTo(mi2)==0);
mi2.plus(v);
assertTrue(mi1.compareTo(mi2)<0);
assertTrue(mi2.compareTo(mi1)>0);
assertEquals(v, mi1.until(mi2));
mi2.plus(-v);
assertEquals(mi1, mi2);
}
@Test
public void testNanoTime()
{
MutableInstant mi1 = MutableInstant.now();
MutableInstant mi2 = new MutableInstant(0, System.nanoTime());
long d = mi1.until(mi2);
mi2.plus(-d);
assertEquals(mi1, mi2);
}
}
| gpl-3.0 |
SiLeBAT/BfROpenLab | de.bund.bfr.knime.pmmlite.views/src/de/bund/bfr/knime/pmmlite/views/SingleSelectionViewSettings.java | 2555 | /*******************************************************************************
* Copyright (c) 2019 German Federal Institute for Risk Assessment (BfR)
*
* 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/>.
*
* Contributors:
* Department Biological Safety - BfR
*******************************************************************************/
package de.bund.bfr.knime.pmmlite.views;
import java.util.Arrays;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NodeSettingsRO;
import org.knime.core.node.NodeSettingsWO;
import de.bund.bfr.knime.pmmlite.views.chart.ChartSelectionPanel;
public class SingleSelectionViewSettings extends SingleDimensionViewSettings {
private static final String CFG_SELECTED_ID = "SelectedID";
protected String selectedID;
public SingleSelectionViewSettings() {
selectedID = null;
}
@Override
public void load(NodeSettingsRO settings) {
super.load(settings);
try {
selectedID = settings.getString(CFG_SELECTED_ID);
} catch (InvalidSettingsException e) {
}
}
@Override
public void save(NodeSettingsWO settings) throws InvalidSettingsException {
super.save(settings);
settings.addString(CFG_SELECTED_ID, selectedID);
}
@Override
public void setFromSelectionPanel(ChartSelectionPanel selectionPanel) {
super.setFromSelectionPanel(selectionPanel);
if (!selectionPanel.getSelectedIDs().isEmpty()) {
selectedID = selectionPanel.getSelectedIDs().get(0);
} else {
selectedID = null;
}
}
@Override
public void setToSelectionPanel(ChartSelectionPanel selectionPanel) {
super.setToSelectionPanel(selectionPanel);
if (getSelectedID() != null) {
selectionPanel.setSelectedIDs(Arrays.asList(selectedID));
}
}
public String getSelectedID() {
return selectedID;
}
public void setSelectedID(String selectedID) {
this.selectedID = selectedID;
}
}
| gpl-3.0 |
Banana4Life/Exmatrikulation | core/src/de/cubeisland/games/dhbw/entity/action/MathReward.java | 532 | package de.cubeisland.games.dhbw.entity.action;
import de.cubeisland.games.dhbw.character.PlayerCharacter;
import de.cubeisland.games.dhbw.entity.CardAction;
/**
* This class represents the action that only increases the Math skill by a given value.
*
* @author Andreas Geis
*/
public class MathReward implements CardAction {
public void apply(PlayerCharacter character, int value) {
character.setMath(character.getMath() + value);
}
public void unapply(PlayerCharacter character, int value) {
}
}
| gpl-3.0 |
CCAFS/MARLO | marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/ReportSynthesisKeyPartnershipCollaborationPmuManagerImpl.java | 3312 | /*****************************************************************
* 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.data.manager.impl;
import org.cgiar.ccafs.marlo.data.dao.ReportSynthesisKeyPartnershipCollaborationPmuDAO;
import org.cgiar.ccafs.marlo.data.manager.ReportSynthesisKeyPartnershipCollaborationPmuManager;
import org.cgiar.ccafs.marlo.data.model.ReportSynthesisKeyPartnershipCollaborationPmu;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
/**
* @author CCAFS
*/
@Named
public class ReportSynthesisKeyPartnershipCollaborationPmuManagerImpl implements ReportSynthesisKeyPartnershipCollaborationPmuManager {
private ReportSynthesisKeyPartnershipCollaborationPmuDAO reportSynthesisKeyPartnershipCollaborationPmuDAO;
// Managers
@Inject
public ReportSynthesisKeyPartnershipCollaborationPmuManagerImpl(ReportSynthesisKeyPartnershipCollaborationPmuDAO reportSynthesisKeyPartnershipCollaborationPmuDAO) {
this.reportSynthesisKeyPartnershipCollaborationPmuDAO = reportSynthesisKeyPartnershipCollaborationPmuDAO;
}
@Override
public void deleteReportSynthesisKeyPartnershipCollaborationPmu(long reportSynthesisKeyPartnershipCollaborationPmuId) {
reportSynthesisKeyPartnershipCollaborationPmuDAO.deleteReportSynthesisKeyPartnershipCollaborationPmu(reportSynthesisKeyPartnershipCollaborationPmuId);
}
@Override
public boolean existReportSynthesisKeyPartnershipCollaborationPmu(long reportSynthesisKeyPartnershipCollaborationPmuID) {
return reportSynthesisKeyPartnershipCollaborationPmuDAO.existReportSynthesisKeyPartnershipCollaborationPmu(reportSynthesisKeyPartnershipCollaborationPmuID);
}
@Override
public List<ReportSynthesisKeyPartnershipCollaborationPmu> findAll() {
return reportSynthesisKeyPartnershipCollaborationPmuDAO.findAll();
}
@Override
public ReportSynthesisKeyPartnershipCollaborationPmu getReportSynthesisKeyPartnershipCollaborationPmuById(long reportSynthesisKeyPartnershipCollaborationPmuID) {
return reportSynthesisKeyPartnershipCollaborationPmuDAO.find(reportSynthesisKeyPartnershipCollaborationPmuID);
}
@Override
public ReportSynthesisKeyPartnershipCollaborationPmu saveReportSynthesisKeyPartnershipCollaborationPmu(ReportSynthesisKeyPartnershipCollaborationPmu reportSynthesisKeyPartnershipCollaborationPmu) {
return reportSynthesisKeyPartnershipCollaborationPmuDAO.save(reportSynthesisKeyPartnershipCollaborationPmu);
}
}
| gpl-3.0 |
DrPrykhodko/Marro | src/com/weffle/table/payment/Payment.java | 305 | package com.weffle.table.payment;
import com.weffle.object.BaseObject;
public class Payment extends BaseObject<PaymentData> {
public Payment() {
super(PaymentData.id);
setAutoKey();
}
public Payment(int id) {
super(PaymentData.id, id);
setAutoKey();
}
}
| gpl-3.0 |
papamas/DMS-KANGREG-XI-MANADO | src/main/java/com/openkm/frontend/client/extension/event/HasNavigatorEvent.java | 1665 | /**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* 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 com.openkm.frontend.client.extension.event;
/**
* HasNavigatorEvent
*
*
* @author jllort
*
*/
public interface HasNavigatorEvent {
/**
* NavigatorEventConstant
*
* @author jllort
*
*/
public static class NavigatorEventConstant {
static final int EVENT_STACK_CHANGED = 1;
private int type = 0;
/**
* ToolBarEventConstant
*
* @param type
*/
private NavigatorEventConstant(int type) {
this.type = type;
}
public int getType(){
return type;
}
}
NavigatorEventConstant STACK_CHANGED = new NavigatorEventConstant(NavigatorEventConstant.EVENT_STACK_CHANGED);
/**
* @param event
*/
void fireEvent(NavigatorEventConstant event);
} | gpl-3.0 |
wattdepot/wattdepot | src/main/java/org/wattdepot/client/http/api/performance/GetIntervalValueThroughput.java | 10140 | /**
* GetIntervalValueThroughput.java This file is part of WattDepot.
*
* Copyright (C) 2014 Cam Moore
*
* 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.wattdepot.client.http.api.performance;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.wattdepot.common.exception.BadCredentialException;
import org.wattdepot.common.exception.BadSensorUriException;
import org.wattdepot.common.exception.IdNotFoundException;
/**
* GetIntervalValueThroughput - Attempts to determine the maximum rate of
* getting the value for an interval for a Sensor in a WattDepot installation.
*
* @author Cam Moore
*
*/
public class GetIntervalValueThroughput extends TimerTask {
/** Manages the GetIntervalValueTasks. */
private Timer timer;
/** The GetIntervalValueTask we will sample. */
private GetIntervalValueTask sampleTask;
/** The WattDepot server's URI. */
private String serverUri;
/** The WattDepot User. */
private String username;
/** The WattDepot User's organization. */
private String orgId;
/** The WattDepot User's password. */
private String password;
/** Flag for debugging. */
private boolean debug;
/** The number of times we've checked the stats. */
private Integer numChecks;
private DescriptiveStatistics averageGetTime;
private DescriptiveStatistics averageMinGetTime;
private DescriptiveStatistics averageMaxGetTime;
private Long getsPerSec;
private Long calculatedGetsPerSec;
/**
* Initializes the GetIntervalValueThroughput instance.
*
* @param serverUri The URI for the WattDepot server.
* @param username The name of a user defined in the WattDepot server.
* @param orgId the id of the organization the user is in.
* @param password The password for the user.
* @param debug flag for debugging messages.
* @throws BadCredentialException if the user or password don't match the
* credentials in WattDepot.
* @throws IdNotFoundException if the processId is not defined.
* @throws BadSensorUriException if the Sensor's URI isn't valid.
*/
public GetIntervalValueThroughput(String serverUri, String username, String orgId,
String password, boolean debug) throws BadCredentialException, IdNotFoundException,
BadSensorUriException {
this.serverUri = serverUri;
this.username = username;
this.orgId = orgId;
this.password = password;
this.debug = debug;
this.numChecks = 0;
this.getsPerSec = 1l;
this.calculatedGetsPerSec = 1l;
this.averageMaxGetTime = new DescriptiveStatistics();
this.averageMinGetTime = new DescriptiveStatistics();
this.averageGetTime = new DescriptiveStatistics();
this.timer = new Timer("throughput");
this.sampleTask = new GetIntervalValueTask(serverUri, username, orgId, password, debug);
// Starting at 1 get/second
this.timer.schedule(sampleTask, 0, 1000);
}
/**
* @param args command line arguments -s <server uri> -u <username> -p
* <password> -o <orgId> -n <numSamples> [-d].
* @throws BadSensorUriException if there is a problem with the WattDepot
* sensor definition.
* @throws IdNotFoundException if there is a problem with the organization id.
* @throws BadCredentialException if the credentials are not valid.
*/
public static void main(String[] args) throws BadCredentialException, IdNotFoundException,
BadSensorUriException {
Options options = new Options();
CommandLine cmd = null;
String serverUri = null;
String username = null;
String organizationId = null;
String password = null;
Integer numSamples = null;
boolean debug = false;
options.addOption("h", false, "Usage: GetIntervalValueThroughput -s <server uri> -u <username>"
+ " -p <password> -o <orgId> [-d]");
options.addOption("s", "server", true, "WattDepot Server URI. (http://server.wattdepot.org)");
options.addOption("u", "username", true, "Username");
options.addOption("o", "organizationId", true, "User's Organization id.");
options.addOption("p", "password", true, "Password");
options.addOption("n", "numSamples", true, "Number of puts to sample.");
options.addOption("d", "debug", false, "Displays statistics as the Gets are made.");
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.err.println("Command line parsing failed. Reason: " + e.getMessage() + ". Exiting.");
System.exit(1);
}
if (cmd.hasOption("h")) {
formatter.printHelp("GetIntervalValueThroughput", options);
System.exit(0);
}
if (cmd.hasOption("s")) {
serverUri = cmd.getOptionValue("s");
}
else {
serverUri = "http://server.wattdepot.org/";
}
if (cmd.hasOption("u")) {
username = cmd.getOptionValue("u");
}
else {
username = "user";
}
if (cmd.hasOption("p")) {
password = cmd.getOptionValue("p");
}
else {
password = "default";
}
if (cmd.hasOption("o")) {
organizationId = cmd.getOptionValue("o");
}
else {
organizationId = "organization";
}
if (cmd.hasOption("n")) {
numSamples = Integer.parseInt(cmd.getOptionValue("n"));
}
else {
numSamples = 13;
}
debug = cmd.hasOption("d");
if (debug) {
System.out.println("GetLatestValue Throughput:");
System.out.println(" WattDepotServer: " + serverUri);
System.out.println(" Username: " + username);
System.out.println(" OrganizationId: " + organizationId);
System.out.println(" Password: ********");
System.out.println(" Samples: " + numSamples);
}
Timer t = new Timer("monitoring");
t.schedule(
new GetIntervalValueThroughput(serverUri, username, organizationId, password, debug), 0,
numSamples * 1000);
}
/*
* (non-Javadoc)
*
* @see java.util.TimerTask#run()
*/
@Override
public void run() {
// wake up to check the stats.
if (this.numChecks == 0) {
// haven't actually run so do nothing.
this.numChecks++;
// should I put a bogus first rate so we don't start too fast?
this.averageGetTime.addValue(1.0); // took 1 second per so we start with a
// low average.
}
else {
this.timer.cancel();
this.numChecks++;
Double aveTime = sampleTask.getAverageTime();
this.averageGetTime.addValue(aveTime / 1E9);
this.averageMinGetTime.addValue(sampleTask.getMinTime() / 1E9);
this.averageMaxGetTime.addValue(sampleTask.getMaxTime() / 1E9);
this.calculatedGetsPerSec = calculateGetRate(averageGetTime);
this.getsPerSec = calculatedGetsPerSec;
// System.out.println("Min put time = " + (sampleTask.getMinGetTime() /
// 1E9));
System.out.println("Ave get value (date, date) time = " + (aveTime / 1E9) + " => "
+ Math.round(1.0 / (aveTime / 1E9)) + " gets/sec.");
// System.out.println("Max put time = " + (sampleTask.getMaxGetTime() /
// 1E9));
// System.out.println("Max put rate = " +
// calculateGetRate(averageMinGetTime));
System.out.println("Setting rate to " + this.calculatedGetsPerSec);
// System.out.println("Min put rate = " +
// calculateGetRate(averageMaxGetTime));
this.timer = new Timer("throughput");
this.sampleTask = null;
// if (debug) {
// System.out.println("Starting " + this.measPerSec +
// " threads @ 1 meas/s");
// }
for (int i = 0; i < getsPerSec; i++) {
try {
if (sampleTask == null) {
this.sampleTask = new GetIntervalValueTask(serverUri, username, orgId, password, debug);
timer.schedule(sampleTask, 0, 1000);
if (debug) {
System.out.println("Starting task " + i);
}
}
else {
timer.schedule(new GetIntervalValueTask(serverUri, username, orgId, password, debug),
0, 1000);
if (debug) {
System.out.println("Starting task " + i);
}
}
Thread.sleep(10);
}
catch (BadCredentialException e) { // NOPMD
// should not happen.
e.printStackTrace();
}
catch (IdNotFoundException e) { // NOPMD
// should not happen.
e.printStackTrace();
}
catch (BadSensorUriException e) { // NOPMD
// should not happen
e.printStackTrace();
}
catch (InterruptedException e) { // NOPMD
// should not happen
e.printStackTrace();
}
}
}
}
/**
* @param stats the DescriptiveStatistics to calculate the mean put time.
* @return The estimated put rate based upon the time it takes to put a single
* measurement.
*/
private Long calculateGetRate(DescriptiveStatistics stats) {
double putTime = stats.getMean();
Long ret = null;
double numPuts = 1.0 / putTime;
ret = Math.round(numPuts);
return ret;
}
}
| gpl-3.0 |
NIASC/PROM_PREM_Collector | src/main/java/se/nordicehealth/servlet/impl/request/user/LoadQuestions.java | 2088 | package se.nordicehealth.servlet.impl.request.user;
import java.util.Map;
import java.util.Map.Entry;
import se.nordicehealth.common.impl.Packet;
import se.nordicehealth.servlet.core.PPCDatabase;
import se.nordicehealth.servlet.core.PPCLogger;
import se.nordicehealth.servlet.impl.QuestionData;
import se.nordicehealth.servlet.impl.io.IPacketData;
import se.nordicehealth.servlet.impl.io.ListData;
import se.nordicehealth.servlet.impl.io.MapData;
import se.nordicehealth.servlet.impl.request.RequestProcesser;
public class LoadQuestions extends RequestProcesser {
private PPCDatabase db;
public LoadQuestions(IPacketData packetData, PPCLogger logger, PPCDatabase db) {
super(packetData, logger);
this.db = db;
}
public MapData processRequest(MapData in) {
MapData out = packetData.getMapData();
out.put(Packet.TYPE, Packet.LOAD_Q);
MapData data = packetData.getMapData();
String result = packetData.getMapData().toString();
try {
result = retrieveQuestions().toString();
} catch (Exception e) { }
data.put(Packet.QUESTIONS, result);
out.put(Packet.DATA, data.toString());
return out;
}
private MapData retrieveQuestions() throws Exception {
Map<Integer, QuestionData> questions = db.loadQuestions();
MapData _questions = packetData.getMapData();
for (Entry<Integer, QuestionData> _e : questions.entrySet()) {
QuestionData _q = _e.getValue();
MapData _question = packetData.getMapData();
ListData options = packetData.getListData();
for (String str : _q.options) {
options.add(str);
}
_question.put(Packet.OPTIONS, options.toString());
_question.put(Packet.TYPE, _q.type);
_question.put(Packet.ID, Integer.toString(_q.id));
_question.put(Packet.QUESTION, _q.question);
_question.put(Packet.DESCRIPTION, _q.description);
_question.put(Packet.OPTIONAL, _q.optional ? Packet.YES : Packet.NO);
_question.put(Packet.MAX_VAL, Integer.toString(_q.max_val));
_question.put(Packet.MIN_VAL, Integer.toString(_q.min_val));
_questions.put(_e.getKey(), _question.toString());
}
return _questions;
}
} | gpl-3.0 |
Snickersnack/TelegramBotAPI | src/org/wilson/telegram/BotConfig.java | 585 | package org.wilson.telegram;
public class BotConfig {
public static final String TOKENNEWBOT = "99536655:AAG_uycvQeXgm-1Cdpk-zvBRUu2w_nz5p1Y";
public static final String USERNAMENEWBOT = "newbot";
public static final String CONSUMERKEY = "jb5Y4AYcwMgrTMCpBWC8JQ";
public static final String CONSUMERSECRET = "Gt8Yb4yXUIDo5nZh15ZIzOgmKBQ";
public static final String YELPTOKEN = "MLHPqPG7-pWg4VjmXTK-fDnAcb9lP5rt";
public static final String YELPTOKENSECRET = "yM4OG1_fewCqwmLyAszme59asx4";
public static final String SENDMESSAGEMARKDOWN = "HTML";
}
| gpl-3.0 |
forgodsake/TowerPlus | Android/src/com/fuav/android/data/provider/FileProvider.java | 33666 | package com.fuav.android.data.provider;
import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.START_TAG;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing
* of files associated with an app by creating a <code>content://</code> {@link Uri} for a file
* instead of a <code>file:///</code> {@link Uri}.
* <p>
* A content URI allows you to grant read and write access using
* temporary access permissions. When you create an {@link Intent} containing
* a content URI, in order to send the content URI
* to a client app, you can also call {@link Intent#setFlags(int) Intent.setFlags()} to add
* permissions. These permissions are available to the client app for as long as the stack for
* a receiving {@link android.app.Activity} is active. For an {@link Intent} going to a
* {@link android.app.Service}, the permissions are available as long as the
* {@link android.app.Service} is running.
* <p>
* In comparison, to control access to a <code>file:///</code> {@link Uri} you have to modify the
* file system permissions of the underlying file. The permissions you provide become available to
* <em>any</em> app, and remain in effect until you change them. This level of access is
* fundamentally insecure.
* <p>
* The increased level of file access security offered by a content URI
* makes FileProvider a key part of Android's security infrastructure.
* <p>
* This overview of FileProvider includes the following topics:
* </p>
* <ol>
* <li><a href="#ProviderDefinition">Defining a FileProvider</a></li>
* <li><a href="#SpecifyFiles">Specifying Available Files</a></li>
* <li><a href="#GetUri">Retrieving the Content URI for a File</li>
* <li><a href="#Permissions">Granting Temporary Permissions to a URI</a></li>
* <li><a href="#ServeUri">Serving a Content URI to Another App</a></li>
* </ol>
* <h3 id="ProviderDefinition">Defining a FileProvider</h3>
* <p>
* Since the default functionality of FileProvider includes content URI generation for files, you
* don't need to define a subclass in code. Instead, you can include a FileProvider in your app
* by specifying it entirely in XML. To specify the FileProvider component itself, add a
* <code><a href="{@docRoot}guide/topics/manifest/provider-element.html"><provider></a></code>
* element to your app manifest. Set the <code>android:name</code> attribute to
* <code>android.support.v4.content.FileProvider</code>. Set the <code>android:authorities</code>
* attribute to a URI authority based on a domain you control; for example, if you control the
* domain <code>mydomain.com</code> you should use the authority
* <code>com.mydomain.fileprovider</code>. Set the <code>android:exported</code> attribute to
* <code>false</code>; the FileProvider does not need to be public. Set the
* <a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"
* >android:grantUriPermissions</a> attribute to <code>true</code>, to allow you
* to grant temporary access to files. For example:
* <pre class="prettyprint">
*<manifest>
* ...
* <application>
* ...
* <provider
* android:name="android.support.v4.content.FileProvider"
* android:authorities="com.mydomain.fileprovider"
* android:exported="false"
* android:grantUriPermissions="true">
* ...
* </provider>
* ...
* </application>
*</manifest></pre>
* <p>
* If you want to override any of the default behavior of FileProvider methods, extend
* the FileProvider class and use the fully-qualified class name in the <code>android:name</code>
* attribute of the <code><provider></code> element.
* <h3 id="SpecifyFiles">Specifying Available Files</h3>
* A FileProvider can only generate a content URI for files in directories that you specify
* beforehand. To specify a directory, specify the its storage area and path in XML, using child
* elements of the <code><paths></code> element.
* For example, the following <code>paths</code> element tells FileProvider that you intend to
* request content URIs for the <code>images/</code> subdirectory of your private file area.
* <pre class="prettyprint">
*<paths xmlns:android="http://schemas.android.com/apk/res/android">
* <files-path name="my_images" path="images/"/>
* ...
*</paths>
*</pre>
* <p>
* The <code><paths></code> element must contain one or more of the following child elements:
* </p>
* <dl>
* <dt>
* <pre class="prettyprint">
*<files-path name="<i>name</i>" path="<i>path</i>" />
*</pre>
* </dt>
* <dd>
* Represents files in the <code>files/</code> subdirectory of your app's internal storage
* area. This subdirectory is the same as the value returned by {@link Context#getFilesDir()
* Context.getFilesDir()}.
* <dt>
* <pre class="prettyprint">
*<external-path name="<i>name</i>" path="<i>path</i>" />
*</pre>
* </dt>
* <dd>
* Represents files in the root of your app's external storage area. The path
* {@link Context#getExternalFilesDir(String) Context.getExternalFilesDir()} returns the
* <code>files/</code> subdirectory of this this root.
* </dd>
* <dt>
* <pre>
*<cache-path name="<i>name</i>" path="<i>path</i>" />
*</pre>
* <dt>
* <dd>
* Represents files in the cache subdirectory of your app's internal storage area. The root path
* of this subdirectory is the same as the value returned by {@link Context#getCacheDir()
* getCacheDir()}.
* </dd>
* </dl>
* <p>
* These child elements all use the same attributes:
* </p>
* <dl>
* <dt>
* <code>name="<i>name</i>"</code>
* </dt>
* <dd>
* A URI path segment. To enforce security, this value hides the name of the subdirectory
* you're sharing. The subdirectory name for this value is contained in the
* <code>path</code> attribute.
* </dd>
* <dt>
* <code>path="<i>path</i>"</code>
* </dt>
* <dd>
* The subdirectory you're sharing. While the <code>name</code> attribute is a URI path
* segment, the <code>path</code> value is an actual subdirectory name. Notice that the
* value refers to a <b>subdirectory</b>, not an individual file or files. You can't
* share a single file by its file name, nor can you specify a subset of files using
* wildcards.
* </dd>
* </dl>
* <p>
* You must specify a child element of <code><paths></code> for each directory that contains
* files for which you want content URIs. For example, these XML elements specify two directories:
* <pre class="prettyprint">
*<paths xmlns:android="http://schemas.android.com/apk/res/android">
* <files-path name="my_images" path="images/"/>
* <files-path name="my_docs" path="docs/"/>
*</paths>
*</pre>
* <p>
* Put the <code><paths></code> element and its children in an XML file in your project.
* For example, you can add them to a new file called <code>res/xml/file_paths.xml</code>.
* To link this file to the FileProvider, add a
* <a href="{@docRoot}guide/topics/manifest/meta-data-element.html"><meta-data></a> element
* as a child of the <code><provider></code> element that defines the FileProvider. Set the
* <code><meta-data></code> element's "android:name" attribute to
* <code>android.support.FILE_PROVIDER_PATHS</code>. Set the element's "android:resource" attribute
* to <code>@xml/file_paths</code> (notice that you don't specify the <code>.xml</code>
* extension). For example:
* <pre class="prettyprint">
*<provider
* android:name="android.support.v4.content.FileProvider"
* android:authorities="com.mydomain.fileprovider"
* android:exported="false"
* android:grantUriPermissions="true">
* <meta-data
* android:name="android.support.FILE_PROVIDER_PATHS"
* android:resource="@xml/file_paths" />
*</provider>
*</pre>
* <h3 id="GetUri">Generating the Content URI for a File</h3>
* <p>
* To share a file with another app using a content URI, your app has to generate the content URI.
* To generate the content URI, create a new {@link File} for the file, then pass the {@link File}
* to {@link #getUriForFile(Context, String, File) getUriForFile()}. You can send the content URI
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()} to another app in an
* {@link android.content.Intent}. The client app that receives the content URI can open the file
* and access its contents by calling
* {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
* ContentResolver.openFileDescriptor} to get a {@link ParcelFileDescriptor}.
* <p>
* For example, suppose your app is offering files to other apps with a FileProvider that has the
* authority <code>com.mydomain.fileprovider</code>. To get a content URI for the file
* <code>default_image.jpg</code> in the <code>images/</code> subdirectory of your internal storage
* add the following code:
* <pre class="prettyprint">
*File imagePath = new File(Context.getFilesDir(), "images");
*File newFile = new File(imagePath, "default_image.jpg");
*Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
*</pre>
* As a result of the previous snippet,
* {@link #getUriForFile(Context, String, File) getUriForFile()} returns the content URI
* <code>content://com.mydomain.fileprovider/my_images/default_image.jpg</code>.
* <h3 id="Permissions">Granting Temporary Permissions to a URI</h3>
* To grant an access permission to a content URI returned from
* {@link #getUriForFile(Context, String, File) getUriForFile()}, do one of the following:
* <ul>
* <li>
* Call the method
* {@link Context#grantUriPermission(String, Uri, int)
* Context.grantUriPermission(package, Uri, mode_flags)} for the <code>content://</code>
* {@link Uri}, using the desired mode flags. This grants temporary access permission for the
* content URI to the specified package, according to the value of the
* the <code>mode_flags</code> parameter, which you can set to
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}, {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}
* or both. The permission remains in effect until you revoke it by calling
* {@link Context#revokeUriPermission(Uri, int) revokeUriPermission()} or until the device
* reboots.
* </li>
* <li>
* Put the content URI in an {@link Intent} by calling {@link Intent#setData(Uri) setData()}.
* </li>
* <li>
* Next, call the method {@link Intent#setFlags(int) Intent.setFlags()} with either
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} or
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} or both.
* </li>
* <li>
* Finally, send the {@link Intent} to
* another app. Most often, you do this by calling
* {@link android.app.Activity#setResult(int, android.content.Intent) setResult()}.
* <p>
* Permissions granted in an {@link Intent} remain in effect while the stack of the receiving
* {@link android.app.Activity} is active. When the stack finishes, the permissions are
* automatically removed. Permissions granted to one {@link android.app.Activity} in a client
* app are automatically extended to other components of that app.
* </p>
* </li>
* </ul>
* <h3 id="ServeUri">Serving a Content URI to Another App</h3>
* <p>
* There are a variety of ways to serve the content URI for a file to a client app. One common way
* is for the client app to start your app by calling
* {@link android.app.Activity#startActivityForResult(Intent, int, Bundle) startActivityResult()},
* which sends an {@link Intent} to your app to start an {@link android.app.Activity} in your app.
* In response, your app can immediately return a content URI to the client app or present a user
* interface that allows the user to pick a file. In the latter case, once the user picks the file
* your app can return its content URI. In both cases, your app returns the content URI in an
* {@link Intent} sent via {@link android.app.Activity#setResult(int, Intent) setResult()}.
* </p>
* <p>
* You can also put the content URI in a {@link android.content.ClipData} object and then add the
* object to an {@link Intent} you send to a client app. To do this, call
* {@link Intent#setClipData(ClipData) Intent.setClipData()}. When you use this approach, you can
* add multiple {@link android.content.ClipData} objects to the {@link Intent}, each with its own
* content URI. When you call {@link Intent#setFlags(int) Intent.setFlags()} on the {@link Intent}
* to set temporary access permissions, the same permissions are applied to all of the content
* URIs.
* </p>
* <p class="note">
* <strong>Note:</strong> The {@link Intent#setClipData(ClipData) Intent.setClipData()} method is
* only available in platform version 16 (Android 4.1) and later. If you want to maintain
* compatibility with previous versions, you should send one content URI at a time in the
* {@link Intent}. Set the action to {@link Intent#ACTION_SEND} and put the URI in data by calling
* {@link Intent#setData setData()}.
* </p>
* <h3 id="">More Information</h3>
* <p>
* To learn more about FileProvider, see the Android training class
* <a href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files Securely with URIs</a>.
* </p>
*/
public class FileProvider extends ContentProvider {
private static final String[] COLUMNS = {
OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE };
private static final String
META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS";
private static final String TAG_ROOT_PATH = "root-path";
private static final String TAG_FILES_PATH = "files-path";
private static final String TAG_CACHE_PATH = "cache-path";
private static final String TAG_EXTERNAL = "external-path";
private static final String ATTR_NAME = "name";
private static final String ATTR_PATH = "path";
private static final File DEVICE_ROOT = new File("/");
// @GuardedBy("sCache")
private static HashMap<String, PathStrategy> sCache = new HashMap<String, PathStrategy>();
private PathStrategy mStrategy;
/**
* The default FileProvider implementation does not need to be initialized. If you want to
* override this method, you must provide your own subclass of FileProvider.
*/
@Override
public boolean onCreate() {
return true;
}
/**
* After the FileProvider is instantiated, this method is called to provide the system with
* information about the provider.
*
* @param context A {@link Context} for the current component.
* @param info A {@link ProviderInfo} for the new provider.
*/
@Override
public void attachInfo(Context context, ProviderInfo info) {
super.attachInfo(context, info);
// Sanity check our security
if (info.exported) {
throw new SecurityException("Provider must not be exported");
}
if (!info.grantUriPermissions) {
throw new SecurityException("Provider must grant uri permissions");
}
mStrategy = getPathStrategy(context, info.authority);
}
/**
* Return a content URI for a given {@link File}. Specific temporary
* permissions for the content URI can be set with
* {@link Context#grantUriPermission(String, Uri, int)}, or added
* to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then
* {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a
* <code>content</code> {@link Uri} for file paths defined in their <code><paths></code>
* meta-data element. See the Class Overview for more information.
*
* @param context A {@link Context} for the current component.
* @param authority The authority of a {@link FileProvider} defined in a
* {@code <provider>} element in your app's manifest.
* @param file A {@link File} pointing to the filename for which you want a
* <code>content</code> {@link Uri}.
* @return A content URI for the file.
* @throws IllegalArgumentException When the given {@link File} is outside
* the paths supported by the provider.
*/
public static Uri getUriForFile(Context context, String authority, File file) {
final PathStrategy strategy = getPathStrategy(context, authority);
return strategy.getUriForFile(file);
}
/**
* Use a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
* managed by the FileProvider.
* FileProvider reports the column names defined in {@link android.provider.OpenableColumns}:
* <ul>
* <li>{@link android.provider.OpenableColumns#DISPLAY_NAME}</li>
* <li>{@link android.provider.OpenableColumns#SIZE}</li>
* </ul>
* For more information, see
* {@link ContentProvider#query(Uri, String[], String, String[], String)
* ContentProvider.query()}.
*
* @param uri A content URI returned by {@link #getUriForFile}.
* @param projection The list of columns to put into the {@link Cursor}. If null all columns are
* included.
* @param selection Selection criteria to apply. If null then all data that matches the content
* URI is returned.
* @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
* the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
* right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
* <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
* values are bound to <i>selection</i> as {@link java.lang.String} values.
* @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
* the resulting {@link Cursor}.
* @return A {@link Cursor} containing the results of the query.
*
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
if (projection == null) {
projection = COLUMNS;
}
String[] cols = new String[projection.length];
Object[] values = new Object[projection.length];
int i = 0;
for (String col : projection) {
if (OpenableColumns.DISPLAY_NAME.equals(col)) {
cols[i] = OpenableColumns.DISPLAY_NAME;
values[i++] = file.getName();
} else if (OpenableColumns.SIZE.equals(col)) {
cols[i] = OpenableColumns.SIZE;
values[i++] = file.length();
}
}
cols = copyOf(cols, i);
values = copyOf(values, i);
final MatrixCursor cursor = new MatrixCursor(cols, 1);
cursor.addRow(values);
return cursor;
}
/**
* Returns the MIME type of a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
*
* @param uri A content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @return If the associated file has an extension, the MIME type associated with that
* extension; otherwise <code>application/octet-stream</code>.
*/
@Override
public String getType(Uri uri) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
final int lastDot = file.getName().lastIndexOf('.');
if (lastDot >= 0) {
final String extension = file.getName().substring(lastDot + 1);
final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (mime != null) {
return mime;
}
}
return "application/octet-stream";
}
/**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality.
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException("No external inserts");
}
/**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality.
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException("No external updates");
}
/**
* Deletes the file associated with the specified content URI, as
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this
* method does <b>not</b> throw an {@link java.io.IOException}; you must check its return value.
*
* @param uri A content URI for a file, as returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @param selection Ignored. Set to {@code null}.
* @param selectionArgs Ignored. Set to {@code null}.
* @return 1 if the delete succeeds; otherwise, 0.
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
return file.delete() ? 1 : 0;
}
/**
* By default, FileProvider automatically returns the
* {@link ParcelFileDescriptor} for a file associated with a <code>content://</code>
* {@link Uri}. To get the {@link ParcelFileDescriptor}, call
* {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
* ContentResolver.openFileDescriptor}.
*
* To override this method, you must provide your own subclass of FileProvider.
*
* @param uri A content URI associated with a file, as returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @param mode Access mode for the file. May be "r" for read-only access, "rw" for read and
* write access, or "rwt" for read and write access that truncates any existing file.
* @return A new {@link ParcelFileDescriptor} with which you can access the file.
*/
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
final int fileMode = modeToMode(mode);
return ParcelFileDescriptor.open(file, fileMode);
}
/**
* Return {@link PathStrategy} for given authority, either by parsing or
* returning from cache.
*/
private static PathStrategy getPathStrategy(Context context, String authority) {
PathStrategy strat;
synchronized (sCache) {
strat = sCache.get(authority);
if (strat == null) {
try {
strat = parsePathStrategy(context, authority);
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
} catch (XmlPullParserException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
}
sCache.put(authority, strat);
}
}
return strat;
}
/**
* Parse and return {@link PathStrategy} for given authority as defined in
* {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
*
* @see #getPathStrategy(Context, String)
*/
private static PathStrategy parsePathStrategy(Context context, String authority)
throws IOException, XmlPullParserException {
final SimplePathStrategy strat = new SimplePathStrategy(authority);
final ProviderInfo info = context.getPackageManager()
.resolveContentProvider(authority, PackageManager.GET_META_DATA);
final XmlResourceParser in = info.loadXmlMetaData(
context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
if (in == null) {
throw new IllegalArgumentException(
"Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
}
int type;
while ((type = in.next()) != END_DOCUMENT) {
if (type == START_TAG) {
final String tag = in.getName();
final String name = in.getAttributeValue(null, ATTR_NAME);
String path = in.getAttributeValue(null, ATTR_PATH);
File target = null;
if (TAG_ROOT_PATH.equals(tag)) {
target = buildPath(DEVICE_ROOT, path);
} else if (TAG_FILES_PATH.equals(tag)) {
target = buildPath(context.getFilesDir(), path);
} else if (TAG_CACHE_PATH.equals(tag)) {
target = buildPath(context.getCacheDir(), path);
} else if (TAG_EXTERNAL.equals(tag)) {
target = buildPath(context.getExternalFilesDir(null), path);
}
if (target != null) {
strat.addRoot(name, target);
}
}
}
return strat;
}
/**
* Strategy for mapping between {@link File} and {@link Uri}.
* <p>
* Strategies must be symmetric so that mapping a {@link File} to a
* {@link Uri} and then back to a {@link File} points at the original
* target.
* <p>
* Strategies must remain consistent across app launches, and not rely on
* dynamic state. This ensures that any generated {@link Uri} can still be
* resolved if your process is killed and later restarted.
*
* @see SimplePathStrategy
*/
interface PathStrategy {
/**
* Return a {@link Uri} that represents the given {@link File}.
*/
Uri getUriForFile(File file);
/**
* Return a {@link File} that represents the given {@link Uri}.
*/
File getFileForUri(Uri uri);
}
/**
* Strategy that provides access to files living under a narrow whitelist of
* filesystem roots. It will throw {@link SecurityException} if callers try
* accessing files outside the configured roots.
* <p>
* For example, if configured with
* {@code addRoot("myfiles", context.getFilesDir())}, then
* {@code context.getFileStreamPath("foo.txt")} would map to
* {@code content://myauthority/myfiles/foo.txt}.
*/
static class SimplePathStrategy implements PathStrategy {
private final String mAuthority;
private final HashMap<String, File> mRoots = new HashMap<String, File>();
public SimplePathStrategy(String authority) {
mAuthority = authority;
}
/**
* Add a mapping from a name to a filesystem root. The provider only offers
* access to files that live under configured roots.
*/
public void addRoot(String name, File root) {
if (TextUtils.isEmpty(name)) {
throw new IllegalArgumentException("Name must not be empty");
}
try {
// Resolve to canonical path to keep path checking fast
root = root.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to resolve canonical path for " + root, e);
}
mRoots.put(name, root);
}
@Override
public Uri getUriForFile(File file) {
String path;
try {
path = file.getCanonicalPath();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
// Find the most-specific root path
Map.Entry<String, File> mostSpecific = null;
for (Map.Entry<String, File> root : mRoots.entrySet()) {
final String rootPath = root.getValue().getPath();
if (path.startsWith(rootPath) && (mostSpecific == null
|| rootPath.length() > mostSpecific.getValue().getPath().length())) {
mostSpecific = root;
}
}
if (mostSpecific == null) {
throw new IllegalArgumentException(
"Failed to find configured root that contains " + path);
}
// Start at first char of path under root
final String rootPath = mostSpecific.getValue().getPath();
if (rootPath.endsWith("/")) {
path = path.substring(rootPath.length());
} else {
path = path.substring(rootPath.length() + 1);
}
// Encode the tag and path separately
path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/");
return new Uri.Builder().scheme("content")
.authority(mAuthority).encodedPath(path).build();
}
@Override
public File getFileForUri(Uri uri) {
String path = uri.getEncodedPath();
final int splitIndex = path.indexOf('/', 1);
final String tag = Uri.decode(path.substring(1, splitIndex));
path = Uri.decode(path.substring(splitIndex + 1));
final File root = mRoots.get(tag);
if (root == null) {
throw new IllegalArgumentException("Unable to find configured root for " + uri);
}
File file = new File(root, path);
try {
file = file.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
if (!file.getPath().startsWith(root.getPath())) {
throw new SecurityException("Resolved path jumped beyond configured root");
}
return file;
}
}
/**
* Copied from ContentResolver.java
*/
private static int modeToMode(String mode) {
int modeBits;
if ("r".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_ONLY;
} else if ("w".equals(mode) || "wt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else if ("wa".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_APPEND;
} else if ("rw".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE;
} else if ("rwt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else {
throw new IllegalArgumentException("Invalid mode: " + mode);
}
return modeBits;
}
private static File buildPath(File base, String... segments) {
File cur = base;
for (String segment : segments) {
if (segment != null) {
cur = new File(cur, segment);
}
}
return cur;
}
private static String[] copyOf(String[] original, int newLength) {
final String[] result = new String[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
private static Object[] copyOf(Object[] original, int newLength) {
final Object[] result = new Object[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
}
| gpl-3.0 |
Graylog2/graylog2-server | graylog2-server/src/main/java/org/graylog/schema/SessionFields.java | 763 | /*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
package org.graylog.schema;
public class SessionFields {
public static final String SESSION_ID = "session_id";
}
| gpl-3.0 |
Nirei/Tobacco | tobacco-game-test/src/tobacco/game/test/collisions/BulletRemovalCollisionHandler.java | 2033 | /*******************************************************************************
* Tobacco - A portable and reusable game engine written in Java.
* Copyright © 2016 Nirei
*
* This file is part of Tobacco
*
* Tobacco 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 tobacco.game.test.collisions;
import tobacco.core.collision.Collision;
import tobacco.core.collision.CollisionHandler;
import tobacco.core.components.RemoveComponent;
import tobacco.core.entities.Entity;
import tobacco.game.test.components.GameComponent;
import tobacco.game.test.components.TeamComponent;
/**
* This handler removes bullets after they've hit something unless
* both entities are on the same team.
* @author nirei
*
*/
public class BulletRemovalCollisionHandler implements CollisionHandler {
@Override
public void handle(Collision col) {
Entity e1 = col.getE1();
Entity e2 = col.getE2();
TeamComponent teamE1, teamE2;
if(e1.has(GameComponent.TEAM_C) && e2.has(GameComponent.TEAM_C)) {
teamE1 = ((TeamComponent) e1.get(GameComponent.TEAM_C));
teamE2 = ((TeamComponent) e2.get(GameComponent.TEAM_C));
if(teamE1.equals(teamE2)) return;
}
remove(e1, e2);
remove(e2, e1);
}
private void remove(Entity e1, Entity e2) {
if(e1.has(GameComponent.BULLET_C) && !e2.has(GameComponent.BULLET_C)) {
e1.add(new RemoveComponent());
}
}
}
| gpl-3.0 |
jukiewiczm/renjin | tools/gcc-bridge/compiler/src/main/java/org/renjin/gcc/codegen/expr/ExprFactory.java | 20321 | package org.renjin.gcc.codegen.expr;
import org.renjin.gcc.InternalCompilerException;
import org.renjin.gcc.codegen.MethodGenerator;
import org.renjin.gcc.codegen.array.ArrayExpr;
import org.renjin.gcc.codegen.array.ArrayTypeStrategy;
import org.renjin.gcc.codegen.call.CallGenerator;
import org.renjin.gcc.codegen.call.FunPtrCallGenerator;
import org.renjin.gcc.codegen.condition.ConditionGenerator;
import org.renjin.gcc.codegen.condition.ConstConditionGenerator;
import org.renjin.gcc.codegen.condition.NullCheckGenerator;
import org.renjin.gcc.codegen.fatptr.FatPtrPair;
import org.renjin.gcc.codegen.type.PointerTypeStrategy;
import org.renjin.gcc.codegen.type.TypeOracle;
import org.renjin.gcc.codegen.type.TypeStrategy;
import org.renjin.gcc.codegen.type.UnsupportedCastException;
import org.renjin.gcc.codegen.type.complex.ComplexCmpGenerator;
import org.renjin.gcc.codegen.type.complex.ComplexValue;
import org.renjin.gcc.codegen.type.complex.ComplexValues;
import org.renjin.gcc.codegen.type.fun.FunPtr;
import org.renjin.gcc.codegen.type.primitive.*;
import org.renjin.gcc.codegen.type.primitive.op.*;
import org.renjin.gcc.codegen.type.record.RecordTypeStrategy;
import org.renjin.gcc.gimple.GimpleOp;
import org.renjin.gcc.gimple.expr.*;
import org.renjin.gcc.gimple.type.*;
import org.renjin.gcc.symbols.SymbolTable;
import org.renjin.repackaged.asm.Type;
import java.util.List;
/**
* Creates code-generating {@link GExpr}s from {@code GimpleExpr}s
*/
public class ExprFactory {
private final TypeOracle typeOracle;
private final SymbolTable symbolTable;
private MethodGenerator mv;
public ExprFactory(TypeOracle typeOracle, SymbolTable symbolTable, MethodGenerator mv) {
this.typeOracle = typeOracle;
this.symbolTable = symbolTable;
this.mv = mv;
}
public GExpr findGenerator(GimpleExpr expr, GimpleType expectedType) {
return maybeCast(findGenerator(expr), expectedType, expr.getType());
}
public GExpr maybeCast(GExpr rhs, GimpleType lhsType, GimpleType rhsType) {
if(lhsType.equals(rhsType)) {
return rhs;
}
TypeStrategy leftStrategy = typeOracle.forType(lhsType);
TypeStrategy rightStrategy = typeOracle.forType(rhsType);
if(ConstantValue.isZero(rhs) && leftStrategy instanceof PointerTypeStrategy) {
return ((PointerTypeStrategy) leftStrategy).nullPointer();
}
try {
return leftStrategy.cast(mv, rhs, rightStrategy);
} catch (UnsupportedCastException e) {
throw new InternalCompilerException(String.format("Unsupported cast to %s [%s] from %s [%s]",
lhsType, leftStrategy.getClass().getSimpleName(),
rhsType, rightStrategy.getClass().getSimpleName()), e);
}
}
public GExpr findGenerator(GimpleExpr expr) {
if(expr instanceof GimpleSymbolRef) {
GExpr variable = symbolTable.getVariable((GimpleSymbolRef) expr);
if(variable == null) {
throw new InternalCompilerException("No such variable: " + expr);
}
return variable;
} else if(expr instanceof GimpleConstant) {
return forConstant((GimpleConstant) expr);
} else if(expr instanceof GimpleConstructor) {
return forConstructor((GimpleConstructor) expr);
} else if(expr instanceof GimpleNopExpr) {
return findGenerator(((GimpleNopExpr) expr).getValue(), expr.getType());
} else if(expr instanceof GimpleAddressOf) {
GimpleAddressOf addressOf = (GimpleAddressOf) expr;
if (addressOf.getValue() instanceof GimpleFunctionRef) {
GimpleFunctionRef functionRef = (GimpleFunctionRef) addressOf.getValue();
return new FunPtr(symbolTable.findHandle(functionRef));
} else if(addressOf.getValue() instanceof GimplePrimitiveConstant) {
// Exceptionally, gimple often contains to address of constants when
// passing them to functions
JExpr value = findPrimitiveGenerator(addressOf.getValue());
return new FatPtrPair(new PrimitiveValueFunction(value.getType()), Expressions.newArray(value));
} else {
GExpr value = findGenerator(addressOf.getValue());
try {
return value.addressOf();
} catch (ClassCastException | UnsupportedOperationException ignored) {
throw new InternalCompilerException(addressOf.getValue() + " [" + value.getClass().getName() + "] is not addressable");
}
}
} else if(expr instanceof GimpleMemRef) {
GimpleMemRef memRefExpr = (GimpleMemRef) expr;
return memRef(memRefExpr, memRefExpr.getType());
} else if(expr instanceof GimpleArrayRef) {
GimpleArrayRef arrayRef = (GimpleArrayRef) expr;
ArrayTypeStrategy arrayStrategy = typeOracle.forArrayType(arrayRef.getArray().getType());
GExpr array = findGenerator(arrayRef.getArray());
GExpr index = findGenerator(arrayRef.getIndex());
return arrayStrategy.elementAt(array, index);
} else if(expr instanceof GimpleConstantRef) {
GimpleConstant constant = ((GimpleConstantRef) expr).getValue();
JExpr constantValue = findPrimitiveGenerator(constant);
FatPtrPair address = new FatPtrPair(
new PrimitiveValueFunction(constantValue.getType()),
Expressions.newArray(constantValue));
return new PrimitiveValue(constantValue, address);
} else if(expr instanceof GimpleComplexPartExpr) {
GimpleExpr complexExpr = ((GimpleComplexPartExpr) expr).getComplexValue();
ComplexValue complexGenerator = (ComplexValue) findGenerator(complexExpr);
if (expr instanceof GimpleRealPartExpr) {
return complexGenerator.getRealGExpr();
} else {
return complexGenerator.getImaginaryGExpr();
}
} else if (expr instanceof GimpleComponentRef) {
GimpleComponentRef ref = (GimpleComponentRef) expr;
GExpr instance = findGenerator(((GimpleComponentRef) expr).getValue());
RecordTypeStrategy typeStrategy = (RecordTypeStrategy) typeOracle.forType(ref.getValue().getType());
TypeStrategy fieldTypeStrategy = typeOracle.forType(ref.getType());
return typeStrategy.memberOf(mv, instance,
ref.getMember().getOffset(),
ref.getMember().getSize(),
fieldTypeStrategy);
} else if (expr instanceof GimpleBitFieldRefExpr) {
GimpleBitFieldRefExpr ref = (GimpleBitFieldRefExpr) expr;
GExpr instance = findGenerator(ref.getValue());
RecordTypeStrategy recordTypeStrategy = (RecordTypeStrategy) typeOracle.forType(ref.getValue().getType());
TypeStrategy memberTypeStrategy = typeOracle.forType(expr.getType());
return recordTypeStrategy.memberOf(mv, instance, ref.getOffset(), ref.getSize(), memberTypeStrategy);
} else if(expr instanceof GimpleCompoundLiteral) {
return findGenerator(((GimpleCompoundLiteral) expr).getDecl());
} else if(expr instanceof GimpleObjectTypeRef) {
GimpleObjectTypeRef typeRef = (GimpleObjectTypeRef) expr;
return findGenerator(typeRef.getExpr());
} else if(expr instanceof GimplePointerPlus) {
GimplePointerPlus pointerPlus = (GimplePointerPlus) expr;
return pointerPlus(pointerPlus.getPointer(), pointerPlus.getOffset(), pointerPlus.getType());
}
throw new UnsupportedOperationException(expr + " [" + expr.getClass().getSimpleName() + "]");
}
private GExpr forConstructor(GimpleConstructor expr) {
return typeOracle.forType(expr.getType()).constructorExpr(this, mv, expr);
}
public CallGenerator findCallGenerator(GimpleExpr functionExpr) {
if(functionExpr instanceof GimpleAddressOf) {
GimpleAddressOf addressOf = (GimpleAddressOf) functionExpr;
if (addressOf.getValue() instanceof GimpleFunctionRef) {
GimpleFunctionRef ref = (GimpleFunctionRef) addressOf.getValue();
return symbolTable.findCallGenerator(ref);
}
GimpleAddressOf address = (GimpleAddressOf) functionExpr;
throw new UnsupportedOperationException("function ref: " + address.getValue() +
" [" + address.getValue().getClass().getSimpleName() + "]");
}
// Assume this is a function pointer ptr expression
FunPtr expr = (FunPtr) findGenerator(functionExpr);
return new FunPtrCallGenerator(typeOracle, (GimpleFunctionType) functionExpr.getType().getBaseType(), expr.unwrap());
}
public ConditionGenerator findConditionGenerator(GimpleOp op, List<GimpleExpr> operands) {
if(operands.size() == 2) {
return findComparisonGenerator(op, operands.get(0), operands.get(1));
} else {
throw new UnsupportedOperationException();
}
}
private ConditionGenerator findComparisonGenerator(GimpleOp op, GimpleExpr x, GimpleExpr y) {
if(x.getType() instanceof org.renjin.gcc.gimple.type.GimpleComplexType) {
return new ComplexCmpGenerator(op, findComplexGenerator(x), findComplexGenerator(y));
} else if(x.getType() instanceof GimplePrimitiveType) {
if(x.getType() instanceof GimpleIntegerType && ((GimpleIntegerType) x.getType()).isUnsigned()) {
return PrimitiveCmpGenerator.unsigned(op, findPrimitiveGenerator(x), findPrimitiveGenerator(y));
} else {
return new PrimitiveCmpGenerator(op, findPrimitiveGenerator(x), findPrimitiveGenerator(y));
}
} else if(x.getType() instanceof GimpleIndirectType) {
return comparePointers(op, x, y);
} else {
throw new UnsupportedOperationException("Unsupported comparison " + op + " between types " +
x.getType() + " and " + y.getType());
}
}
private ConditionGenerator comparePointers(GimpleOp op, GimpleExpr x, GimpleExpr y) {
// First see if this is a null check
if(isNull(x) && isNull(y)) {
switch (op) {
case EQ_EXPR:
case GE_EXPR:
case LE_EXPR:
return new ConstConditionGenerator(true);
case NE_EXPR:
case LT_EXPR:
case GT_EXPR:
return new ConstConditionGenerator(false);
default:
throw new UnsupportedOperationException("op: " + op);
}
} else if(isNull(x)) {
return new NullCheckGenerator(op, (PtrExpr) findGenerator(y));
} else if(isNull(y)) {
return new NullCheckGenerator(op, (PtrExpr) findGenerator(x));
}
// Shouldn't matter which we pointer we cast to the other, but if we have a choice,
// cast away from a void* to a concrete pointer type
GimpleType commonType;
if(x.getType().isPointerTo(GimpleVoidType.class)) {
commonType = y.getType();
} else {
commonType = x.getType();
}
PointerTypeStrategy typeStrategy = typeOracle.forPointerType(commonType);
GExpr ptrX = findGenerator(x, commonType);
GExpr ptrY = findGenerator(y, commonType);
return typeStrategy.comparePointers(mv, op, ptrX, ptrY);
}
private boolean isNull(GimpleExpr expr) {
return expr instanceof GimpleConstant && ((GimpleConstant) expr).isNull();
}
public GExpr findGenerator(GimpleOp op, List<GimpleExpr> operands, GimpleType expectedType) {
switch (op) {
case PLUS_EXPR:
case MINUS_EXPR:
case MULT_EXPR:
case RDIV_EXPR:
case TRUNC_DIV_EXPR:
case EXACT_DIV_EXPR:
case TRUNC_MOD_EXPR:
case BIT_IOR_EXPR:
case BIT_XOR_EXPR:
case BIT_AND_EXPR:
return findBinOpGenerator(op, operands);
case POINTER_PLUS_EXPR:
return pointerPlus(operands.get(0), operands.get(1), expectedType);
case BIT_NOT_EXPR:
return primitive(new BitwiseNot(findPrimitiveGenerator(operands.get(0))));
case LSHIFT_EXPR:
case RSHIFT_EXPR:
return primitive(new BitwiseShift(
op,
operands.get(0).getType(),
findPrimitiveGenerator(operands.get(0)),
findPrimitiveGenerator(operands.get(1))));
case MEM_REF:
// Cast the pointer type first, then dereference
return memRef((GimpleMemRef) operands.get(0), expectedType);
case CONVERT_EXPR:
case FIX_TRUNC_EXPR:
case FLOAT_EXPR:
case PAREN_EXPR:
case VAR_DECL:
case PARM_DECL:
case NOP_EXPR:
case INTEGER_CST:
case REAL_CST:
case STRING_CST:
case COMPLEX_CST:
case ADDR_EXPR:
case ARRAY_REF:
case COMPONENT_REF:
case BIT_FIELD_REF:
case REALPART_EXPR:
case IMAGPART_EXPR:
return maybeCast(findGenerator(operands.get(0)), expectedType, operands.get(0).getType());
case COMPLEX_EXPR:
return new ComplexValue(findPrimitiveGenerator(operands.get(0)));
case NEGATE_EXPR:
return primitive(new NegativeValue(findPrimitiveGenerator(operands.get(0))));
case TRUTH_NOT_EXPR:
return primitive(new LogicalNot(findPrimitiveGenerator(operands.get(0))));
case TRUTH_AND_EXPR:
return primitive(new LogicalAnd(
findPrimitiveGenerator(operands.get(0)),
findPrimitiveGenerator(operands.get(1))));
case TRUTH_OR_EXPR:
return primitive(new LogicalOr(
findPrimitiveGenerator(operands.get(0)),
findPrimitiveGenerator(operands.get(1))));
case TRUTH_XOR_EXPR:
return primitive(new LogicalXor(
findPrimitiveGenerator(operands.get(0)),
findPrimitiveGenerator(operands.get(1))));
case EQ_EXPR:
case LT_EXPR:
case LE_EXPR:
case NE_EXPR:
case GT_EXPR:
case GE_EXPR:
return primitive(new ConditionExpr(
findComparisonGenerator(op,operands.get(0), operands.get(1))));
case MAX_EXPR:
case MIN_EXPR:
return primitive(new MinMaxValue(op,
findPrimitiveGenerator(operands.get(0)),
findPrimitiveGenerator(operands.get(1))));
case ABS_EXPR:
return primitive(new AbsValue(
findPrimitiveGenerator(operands.get(0))));
case UNORDERED_EXPR:
return primitive(new UnorderedExpr(
findPrimitiveGenerator(operands.get(0)),
findPrimitiveGenerator(operands.get(1))));
case CONJ_EXPR:
return findComplexGenerator(operands.get(0)).conjugate();
default:
throw new UnsupportedOperationException("op: " + op);
}
}
private PrimitiveValue primitive(JExpr expr) {
return new PrimitiveValue(expr);
}
private GExpr memRef(GimpleMemRef gimpleExpr, GimpleType expectedType) {
GimpleExpr pointer = gimpleExpr.getPointer();
// Case of *&x, which can be simplified to x
if(pointer instanceof GimpleAddressOf) {
GimpleAddressOf addressOf = (GimpleAddressOf) pointer;
return findGenerator(addressOf.getValue(), expectedType);
}
GimpleIndirectType pointerType = (GimpleIndirectType) pointer.getType();
if(pointerType.getBaseType() instanceof GimpleVoidType) {
// We can't dereference a null pointer, so cast the pointer first, THEN dereference
return castThenDereference(gimpleExpr, expectedType);
} else {
return dereferenceThenCast(gimpleExpr, expectedType);
}
}
private GExpr castThenDereference(GimpleMemRef gimpleExpr, GimpleType expectedType) {
GimpleExpr pointer = gimpleExpr.getPointer();
GimpleIndirectType pointerType = (GimpleIndirectType) pointer.getType();
GimpleIndirectType expectedPointerType = expectedType.pointerTo();
// Cast from the void pointer type to the "expected" pointer type
GExpr ptrExpr = maybeCast(findGenerator(pointer), expectedPointerType, pointerType);
PointerTypeStrategy pointerStrategy = typeOracle.forPointerType(expectedPointerType);
if(!gimpleExpr.isOffsetZero()) {
JExpr offsetInBytes = findPrimitiveGenerator(gimpleExpr.getOffset());
ptrExpr = pointerStrategy.pointerPlus(mv, ptrExpr, offsetInBytes);
}
return ((PtrExpr) ptrExpr).valueOf();
}
private GExpr dereferenceThenCast(GimpleMemRef gimpleExpr, GimpleType expectedType) {
GimpleExpr pointer = gimpleExpr.getPointer();
GimpleIndirectType pointerType = (GimpleIndirectType) pointer.getType();
PointerTypeStrategy pointerStrategy = typeOracle.forPointerType(pointerType);
GExpr ptrExpr = findGenerator(pointer);
if(!gimpleExpr.isOffsetZero()) {
JExpr offsetInBytes = findPrimitiveGenerator(gimpleExpr.getOffset());
ptrExpr = pointerStrategy.pointerPlus(mv, ptrExpr, offsetInBytes);
}
GExpr valueExpr = ((PtrExpr) ptrExpr).valueOf();
return maybeCast(valueExpr, pointerType.getBaseType(), expectedType);
}
private GExpr pointerPlus(GimpleExpr pointerExpr, GimpleExpr offsetExpr, GimpleType expectedType) {
GExpr pointer = findGenerator(pointerExpr);
JExpr offsetInBytes = findPrimitiveGenerator(offsetExpr);
GimpleType pointerType = pointerExpr.getType();
GExpr result = typeOracle.forPointerType(pointerType).pointerPlus(mv, pointer, offsetInBytes);
return maybeCast(result, expectedType, pointerType);
}
private <T extends GExpr> T findGenerator(GimpleExpr gimpleExpr, Class<T> exprClass) {
GExpr expr = findGenerator(gimpleExpr);
if(exprClass.isAssignableFrom(expr.getClass())) {
return exprClass.cast(expr);
} else {
throw new InternalCompilerException(String.format("Expected %s for expr %s, found: %s",
exprClass.getSimpleName(),
gimpleExpr,
expr.getClass().getName()));
}
}
public JExpr findPrimitiveGenerator(GimpleExpr gimpleExpr) {
// When looking specifically for a value generator, treat a null pointer as zero integer
if(gimpleExpr instanceof GimplePrimitiveConstant && gimpleExpr.getType() instanceof GimpleIndirectType) {
return Expressions.constantInt(((GimplePrimitiveConstant) gimpleExpr).getValue().intValue());
}
PrimitiveValue primitive = findGenerator(gimpleExpr, PrimitiveValue.class);
return primitive.getExpr();
}
private ComplexValue findComplexGenerator(GimpleExpr gimpleExpr) {
return findGenerator(gimpleExpr, ComplexValue.class);
}
private GExpr findBinOpGenerator(GimpleOp op, List<GimpleExpr> operands) {
GimpleExpr x = operands.get(0);
GimpleExpr y = operands.get(1);
if( x.getType() instanceof GimpleComplexType &&
y.getType() instanceof GimpleComplexType) {
return complexBinOp(op, findComplexGenerator(x), findComplexGenerator(y));
} else if(
x.getType() instanceof GimplePrimitiveType &&
y.getType() instanceof GimplePrimitiveType) {
return primitive(new PrimitiveBinOpGenerator(op, findPrimitiveGenerator(x), findPrimitiveGenerator(y)));
}
throw new UnsupportedOperationException(op.name() + ": " + x.getType() + ", " + y.getType());
}
private GExpr complexBinOp(GimpleOp op, ComplexValue cx, ComplexValue cy) {
switch (op) {
case PLUS_EXPR:
return ComplexValues.add(cx, cy);
case MINUS_EXPR:
return ComplexValues.subtract(cx, cy);
case MULT_EXPR:
return ComplexValues.multiply(cx, cy);
default:
throw new UnsupportedOperationException("complex operation: " + op);
}
}
public GExpr forConstant(GimpleConstant constant) {
if (constant.getType() instanceof GimpleIndirectType) {
// TODO: Treat all pointer constants as null
return typeOracle.forPointerType(constant.getType()).nullPointer();
} else if (constant instanceof GimplePrimitiveConstant) {
return primitive(new ConstantValue((GimplePrimitiveConstant) constant));
} else if (constant instanceof GimpleComplexConstant) {
GimpleComplexConstant complexConstant = (GimpleComplexConstant) constant;
return new ComplexValue(
forConstant(complexConstant.getReal()),
forConstant(complexConstant.getIm()));
} else if (constant instanceof GimpleStringConstant) {
StringConstant array = new StringConstant(((GimpleStringConstant) constant).getValue());
ArrayExpr arrayExpr = new ArrayExpr(new PrimitiveValueFunction(Type.BYTE_TYPE), array.getLength(), array);
return arrayExpr;
} else {
throw new UnsupportedOperationException("constant: " + constant);
}
}
public TypeStrategy strategyFor(GimpleType type) {
return typeOracle.forType(type);
}
}
| gpl-3.0 |
marpet/seadas | seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/general/CallL3BinDumpAction.java | 7144 | package gov.nasa.gsfc.seadas.processing.general;
import com.bc.ceres.swing.TableLayout;
import gov.nasa.gsfc.seadas.processing.core.ProcessorModel;
import gov.nasa.gsfc.seadas.processing.utilities.SheetCell;
import gov.nasa.gsfc.seadas.processing.utilities.SpreadSheet;
import org.esa.beam.framework.ui.ModalDialog;
import org.esa.beam.visat.VisatApp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 4/29/14
* Time: 1:22 PM
* To change this template use File | Settings | File Templates.
*/
public class CallL3BinDumpAction extends CallCloProgramAction {
@Override
void displayOutput(final ProcessorModel processorModel) {
String output = processorModel.getExecutionLogMessage();
StringTokenizer st = new StringTokenizer(output, "\n");
int numRows = st.countTokens();
String line = st.nextToken();
StringTokenizer stLine = new StringTokenizer(line, " ");
String prodName = null;
boolean skipFirstLine = false;
if (stLine.countTokens() < 14) {
prodName = stLine.nextToken();
numRows--;
skipFirstLine = true;
}
if (!skipFirstLine) {
st = new StringTokenizer(output, "\n");
}
final SheetCell[][] cells = new SheetCell[numRows][14];
int i = 0;
while (st.hasMoreElements()) {
line = st.nextToken();
stLine = new StringTokenizer(line, " ");
int j = 0;
while (stLine.hasMoreElements()) {
cells[i][j] = new SheetCell(i, j, stLine.nextToken(), null);
j++;
}
i++;
}
if (skipFirstLine) {
cells[0][10] = new SheetCell(0, 10, prodName + " " + cells[0][10].getValue(), null);
cells[0][11] = new SheetCell(0, 11, prodName + " " + cells[0][11].getValue(), null);
}
SpreadSheet sp = new SpreadSheet(cells);
final JFrame frame = new JFrame("l3bindump Output");
JPanel content = new JPanel(new BorderLayout());
JButton save = new JButton("Save");
JButton cancel = new JButton("Cancel");
TableLayout buttonPanelLayout = new TableLayout(2);
JPanel buttonPanel = new JPanel(buttonPanelLayout);
/*
* Allows the user to exit the application
* from the window manager's dressing.
*/
frame.addWindowListener(new WindowAdapter() {
// public void windowClosing(WindowEvent e) {
// System.exit(0);
// }
});
sp.getScrollPane().getVerticalScrollBar().setAutoscrolls(true);
content.add(sp.getScrollPane(), BorderLayout.NORTH);
buttonPanel.add(save);
buttonPanel.add(cancel);
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
//To change body of implemented methods use File | Settings | File Templates.
String outputFileName = processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName()) + "_l3bindump_output.txt";
saveForSpreadsheet(outputFileName, cells);
String message = "l3bindump output is saved in file \n"
+ outputFileName +"\n"
+ " in spreadsheet format.";
final ModalDialog modalDialog = new ModalDialog(VisatApp.getApp().getApplicationWindow(), "", message, ModalDialog.ID_OK, "test");
final int dialogResult = modalDialog.show();
if (dialogResult != ModalDialog.ID_OK) {
}
frame.setVisible(false);
}
});
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
//To change body of implemented methods use File | Settings | File Templates.
frame.setVisible(false);
}
});
content.add(buttonPanel, BorderLayout.SOUTH);
//frame.getContentPane().add(sp.getScrollPane());
frame.getContentPane().add(content);
frame.pack();
frame.setVisible(true);
}
private void saveForSpreadsheet(String outputFileName, SheetCell[][] cells) {
String cell, all = new String();
for (int i = 0; i < cells.length; i++) {
cell = new String();
for (int j = 0; j < cells[i].length; j++) {
cell = cell + cells[i][j].getValue() + "\t";
}
all = all + cell + "\n";
}
try {
final File excelFile = new File(outputFileName);
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(excelFile);
fileWriter.write(all);
} finally {
if (fileWriter != null) {
fileWriter.close();
}
}
} catch (IOException e) {
SeadasLogger.getLogger().warning(outputFileName + " is not created. " + e.getMessage());
}
}
// public void createSpreadsheet(SheetCell[][] cells) {//throws BiffException, IOException, WriteException {
// WritableWorkbook wworkbook;
// try {
// wworkbook = Workbook.createWorkbook(new File("output.xls"));
// WritableSheet wsheet = wworkbook.createSheet("l3bindump output", 0);
// jxl.write.Label label;
// jxl.write.Number number;
//
// /**
// * Create labels for the worksheet
// */
// for (int j = 0; j < cells[0].length; j++) {
// label = new jxl.write.Label(0, j, (String) cells[0][j].getValue());
// wsheet.addCell(label);
// }
// /**
// * Create cell values for the worksheet
// */
// for (int i = 1; i < cells.length; i++) {
// for (int j = 0; j < cells[i].length; j++) {
// number = new jxl.write.Number(i, j, new Double((String) cells[i][j].getValue()).doubleValue());
// wsheet.addCell(number);
// }
// }
// wworkbook.write();
// wworkbook.close();
// } catch (Exception ioe) {
// //System.out.println(ioe.getMessage());
//
// }
//
//// Workbook workbook = Workbook.getWorkbook(new File("output.xls"));
////
//// Sheet sheet = workbook.getSheet(0);
//// Cell cell1 = sheet.getCell(0, 2);
//// System.out.println(cell1.getContents());
//// Cell cell2 = sheet.getCell(3, 4);
//// System.out.println(cell2.getContents());
//// workbook.close();
// }
}
| gpl-3.0 |
Dechcaudron/xtreaming-app-android | Xtreaming/app/src/main/java/com/dechcaudron/xtreaming/model/Repository.java | 1615 | package com.dechcaudron.xtreaming.model;
import com.dechcaudron.xtreaming.repositoryInterface.IRepositoryAuthToken;
public class Repository
{
private final int repoLocalId;
private final int repoTypeCode;
private final String domainURL;
private final int port;
private final boolean requireSSL;
private final String username;
private final IRepositoryAuthToken authenticationToken;
public Repository(int repoLocalId, int repoTypeCode, String domainURL, int port, boolean requireSSL, String username, IRepositoryAuthToken authenticationToken)
{
this.repoLocalId = repoLocalId;
this.repoTypeCode = repoTypeCode;
this.domainURL = domainURL;
this.port = port;
this.requireSSL = requireSSL;
this.username = username;
this.authenticationToken = authenticationToken;
}
public int getRepoLocalId()
{
return repoLocalId;
}
public int getRepoTypeCode()
{
return repoTypeCode;
}
public String getDomainURL()
{
return domainURL;
}
public int getPort()
{
return port;
}
public boolean requiresSSL()
{
return requireSSL;
}
public String getUsername()
{
return username;
}
public IRepositoryAuthToken getAuthenticationToken()
{
return authenticationToken;
}
@Override
public String toString()
{
return "[LocalId " + repoLocalId + "] [RepoType " + repoTypeCode + "] " + domainURL + ":" + port +" "+ (requireSSL ? "" : "NO ") + "SSL Username: " + username;
}
}
| gpl-3.0 |
isnuryusuf/ingress-indonesia-dev | apk/classes-ekstartk/com/badlogic/gdx/math/Interpolation$BounceOut.java | 2430 | package com.badlogic.gdx.math;
public class Interpolation$BounceOut extends Interpolation
{
final float[] heights;
final float[] widths;
public Interpolation$BounceOut(int paramInt)
{
if ((paramInt < 2) || (paramInt > 5))
throw new IllegalArgumentException("bounces cannot be < 2 or > 5: " + paramInt);
this.widths = new float[paramInt];
this.heights = new float[paramInt];
this.heights[0] = 1.0F;
switch (paramInt)
{
default:
case 2:
case 3:
case 4:
case 5:
}
while (true)
{
float[] arrayOfFloat = this.widths;
arrayOfFloat[0] = (2.0F * arrayOfFloat[0]);
return;
this.widths[0] = 0.6F;
this.widths[1] = 0.4F;
this.heights[1] = 0.33F;
continue;
this.widths[0] = 0.4F;
this.widths[1] = 0.4F;
this.widths[2] = 0.2F;
this.heights[1] = 0.33F;
this.heights[2] = 0.1F;
continue;
this.widths[0] = 0.34F;
this.widths[1] = 0.34F;
this.widths[2] = 0.2F;
this.widths[3] = 0.15F;
this.heights[1] = 0.26F;
this.heights[2] = 0.11F;
this.heights[3] = 0.03F;
continue;
this.widths[0] = 0.3F;
this.widths[1] = 0.3F;
this.widths[2] = 0.2F;
this.widths[3] = 0.1F;
this.widths[4] = 0.1F;
this.heights[1] = 0.45F;
this.heights[2] = 0.3F;
this.heights[3] = 0.15F;
this.heights[4] = 0.06F;
}
}
public Interpolation$BounceOut(float[] paramArrayOfFloat1, float[] paramArrayOfFloat2)
{
if (paramArrayOfFloat1.length != paramArrayOfFloat2.length)
throw new IllegalArgumentException("Must be the same number of widths and heights.");
this.widths = paramArrayOfFloat1;
this.heights = paramArrayOfFloat2;
}
public float apply(float paramFloat)
{
float f1 = paramFloat + this.widths[0] / 2.0F;
int i = this.widths.length;
float f2 = f1;
int j = 0;
float f3 = 0.0F;
while (true)
{
float f4 = 0.0F;
if (j < i)
{
f3 = this.widths[j];
if (f2 <= f3)
f4 = this.heights[j];
}
else
{
float f5 = f2 / f3;
float f6 = f5 * (f4 * (4.0F / f3));
return 1.0F - f3 * (f6 - f5 * f6);
}
f2 -= f3;
j++;
}
}
}
/* Location: classes_dex2jar.jar
* Qualified Name: com.badlogic.gdx.math.Interpolation.BounceOut
* JD-Core Version: 0.6.2
*/ | gpl-3.0 |
tarcisiodpl/ssdp | SSDP/src/dp2/RSS.java | 2406 | /*
* 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 dp2;
/**
*
* @author Marianna
*/
public class RSS {
public static Pattern[] run(Pattern[] p, int k){
//Pesos dos exemplos positivos
int[] pesos = new int[D.numeroExemplosPositivo];
//Atribuindo pesos iniciais
for(int i = 0; i < pesos.length; i++){
pesos[i] = 1;
}
//PA: revisão!
Pattern[] S = p.clone();
Pattern[] SS = new Pattern[k];//Inicializando array com os melhores patterns
for(int i = 0; i < SS.length; i++){
//Identificando o maior pontuador
int indiceMaximoPontuador = RSS.indiceMaiorPontuador(S, pesos);
//Atribuindo maior pontuador ao array com os k melhores
SS[i] = p[indiceMaximoPontuador];
//Atualizando vetor de pesos com base no maior pontuador
RSS.atualizaPesos(p[indiceMaximoPontuador].getVrP(), pesos);
//Excluir exemplo com maior pontuação
S[indiceMaximoPontuador] = null;
}
return SS;
}
private static double pontuacao(boolean[] vetorResultantePattern, int[] pesos){
double pontuacao = 0.0;
for(int i = 0; i < vetorResultantePattern.length; i++){
if(vetorResultantePattern[i]){
pontuacao += 1.0/(double)pesos[i];
}
}
return pontuacao;
}
private static int indiceMaiorPontuador(Pattern[] S, int[] pesos){
double pontuacaoMaxima = 0.0;
int indiceMaiorPontuador = 0;
for(int i = 0; i < S.length; i++){
if(S[i] != null){
double pontuacao = RSS.pontuacao(S[i].getVrP(), pesos);
if(pontuacao > pontuacaoMaxima){
pontuacaoMaxima = pontuacao;
indiceMaiorPontuador = i;
}
}
}
return indiceMaiorPontuador;
}
private static void atualizaPesos(boolean[] vetorResultantePositivo, int[] vetorPesosPositivo){
for(int i = 0; i < vetorPesosPositivo.length; i++){
if(vetorResultantePositivo[i]){
vetorPesosPositivo[i]++;
}
}
}
}
| gpl-3.0 |
trackplus/Genji | src/main/java/com/aurel/track/admin/customize/category/filter/FieldExpressionBL.java | 40054 | /**
* Genji Scrum Tool and Issue Tracker
* Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions
* <a href="http://www.trackplus.com">Genji Scrum Tool</a>
*
* 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/>.
*/
/* $Id:$ */
package com.aurel.track.admin.customize.category.filter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.aurel.track.admin.customize.category.filter.tree.design.FieldExpressionInTreeTO;
import com.aurel.track.admin.customize.category.filter.tree.design.FieldExpressionSimpleTO;
import com.aurel.track.admin.customize.category.filter.tree.design.FilterSelectsListsLoader;
import com.aurel.track.admin.customize.role.FieldsRestrictionsToRoleBL;
import com.aurel.track.admin.project.ProjectBL;
import com.aurel.track.beans.ILabelBean;
import com.aurel.track.beans.TFieldConfigBean;
import com.aurel.track.beans.TPersonBean;
import com.aurel.track.beans.TProjectBean;
import com.aurel.track.beans.TQueryRepositoryBean;
import com.aurel.track.beans.TReportLayoutBean;
import com.aurel.track.fieldType.constants.SystemFields;
import com.aurel.track.fieldType.runtime.base.IFieldTypeRT;
import com.aurel.track.fieldType.runtime.bl.FieldRuntimeBL;
import com.aurel.track.fieldType.runtime.custom.text.CustomDoubleRT;
import com.aurel.track.fieldType.runtime.matchers.MatchRelations;
import com.aurel.track.fieldType.runtime.matchers.converter.AccountingTimeMatcherConverter;
import com.aurel.track.fieldType.runtime.matchers.converter.DoubleMatcherConverter;
import com.aurel.track.fieldType.runtime.matchers.converter.MatcherConverter;
import com.aurel.track.fieldType.runtime.matchers.converter.SelectMatcherConverter;
import com.aurel.track.fieldType.runtime.matchers.design.AccountingTimeMatcherDT;
import com.aurel.track.fieldType.runtime.matchers.design.DoubleMatcherDT;
import com.aurel.track.fieldType.runtime.matchers.design.IMatcherDT;
import com.aurel.track.fieldType.runtime.matchers.design.IMatcherValue;
import com.aurel.track.fieldType.runtime.matchers.design.MatcherDatasourceContext;
import com.aurel.track.fieldType.runtime.matchers.design.SelectMatcherDT;
import com.aurel.track.fieldType.runtime.matchers.run.MatcherContext;
import com.aurel.track.fieldType.runtime.system.select.SystemManagerRT;
import com.aurel.track.fieldType.types.FieldTypeManager;
import com.aurel.track.item.consInf.RaciRole;
import com.aurel.track.itemNavigator.layout.column.ColumnFieldsBL;
import com.aurel.track.resources.LocalizeUtil;
import com.aurel.track.util.GeneralUtils;
import com.aurel.track.util.IntegerStringBean;
public class FieldExpressionBL {
//the following names should comply with the setter field names
//in the filter actions which will be set as a result of a form submit
public static String MATCHER_RELATION_BASE_NAME = "MatcherRelationMap";
public static String VALUE_BASE_NAME = "DisplayValueMap";
public static String VALUE_BASE_ITEM_ID = "DisplayValue";
public static String SIMPLE = "simple";
public static String IN_TREE = "inTree";
public static String CASCADING_PART = "CascadingPart";
public static String FIELD_NAME = "fieldMap";
public static String FIELD_MOMENT_NAME = "fieldMomentMap";
public static String OPERATION_NAME = "operationMap";
public static String PARENTHESIS_OPEN_NAME = "parenthesisOpenedMap";
public static String PARENTHESIS_CLOSED_NAME = "parenthesisClosedMap";
public static String NEGATION_NAME = "negationMap";
public static String MATCH_RELATION_PREFIX = "admin.customize.queryFilter.opt.relation.";
/**
* Prepares a JSON string after matcher relation change
* @param baseName
* @param stringValue
* @param fieldID
* @param matcherID
* @param modifiable
* @param personID
* @param locale
* @return
*/
static String selectMatcher(Integer[] projectIDs, Integer[] itemTypeIDs, String baseName, String baseItemId, Integer index, String stringValue,
Integer fieldID, Integer matcherID, boolean modifiable, TPersonBean personBean, Locale locale) {
FieldExpressionInTreeTO fieldExpressionInTreeTO =
configureValueDetails(projectIDs, itemTypeIDs, baseName, baseItemId, index, stringValue, fieldID, matcherID, modifiable, personBean, locale);
return FilterJSON.getFieldExpressionValueJSON(fieldExpressionInTreeTO.getValueItemId(), fieldExpressionInTreeTO.isNeedMatcherValue(),
fieldExpressionInTreeTO.getValueRenderer(), fieldExpressionInTreeTO.getJsonConfig());
}
/**
* Reload part of the filter expression after a field change: possible matchers and the value part
* @param baseName
* @param stringValue
* @param index
* @param fieldID
* @param matcherID
* @param personID
* @param locale
* @param withParameter
* @return
*/
static String selectField(Integer[] projectIDs, Integer[] itemTypeIDs, String baseName, String baseItemId, Integer index, String stringValue, Integer fieldID, Integer matcherID,
boolean modifiable, TPersonBean personBean, Locale locale, boolean withParameter) {
List<IntegerStringBean> matcherRelations = getMatchers(fieldID, withParameter, true, locale);
if (matcherID == null) {
//set the matcher relation to the first when not yet selected
matcherID = matcherRelations.get(0).getValue();
} else {
Iterator<IntegerStringBean> iterator = matcherRelations.iterator();
boolean found = false;
while (iterator.hasNext()) {
IntegerStringBean integerStringBean = iterator.next();
if (matcherID.equals(integerStringBean.getValue())) {
found = true;
break;
}
}
if (!found) {
//change the matcher relation to the first
//only if the old one is not found among the new matcherRelations list
matcherID = matcherRelations.get(0).getValue();
}
}
FieldExpressionInTreeTO fieldExpressionInTreeTO =
configureValueDetails(projectIDs, itemTypeIDs, baseName, baseItemId, index, stringValue, fieldID, matcherID, modifiable, personBean, locale);
String valueJSON = FilterJSON.getFieldExpressionValueBaseJSON(fieldExpressionInTreeTO.getValueItemId(), fieldExpressionInTreeTO.isNeedMatcherValue(),
fieldExpressionInTreeTO.getValueRenderer(), fieldExpressionInTreeTO.getJsonConfig(), true);
return FilterJSON.getFieldExpressionMatcherAndValueValueJSON(matcherRelations, matcherID, valueJSON);
}
/**
* Prepares a JSON string after matcher relation or field change
* @param name
* @param stringValue
* @param fieldID
* @param matcherID
* @param modifiable
* @param personID
* @param locale
* @return
*/
private static FieldExpressionInTreeTO configureValueDetails(Integer[] projectIDs, Integer[] itemTypeIDs, String baseName, String baseItemId, Integer index, String stringValue,
Integer fieldID, Integer matcherID, boolean modifiable, TPersonBean personBean, Locale locale) {
FieldExpressionInTreeTO fieldExpressionInTreeTO = new FieldExpressionInTreeTO();
fieldExpressionInTreeTO.setField(fieldID);
fieldExpressionInTreeTO.setSelectedMatcher(matcherID);
MatcherConverter matcherConverter = null;
if (fieldID>0) {
//system or custom field
IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID);
if (fieldTypeRT!=null) {
matcherConverter = fieldTypeRT.getMatcherConverter();
}
} else {
//pseudo field
matcherConverter = getPseudoFieldMatcherConverter(fieldID);
}
Object value = null;
if (matcherConverter!=null) {
value = matcherConverter.fromValueString(stringValue, locale, matcherID);
}
fieldExpressionInTreeTO.setValue(value);
Integer[] ancestorProjectIDs = null;
if (projectIDs==null || projectIDs.length==0) {
//none of the projects is selected -> get the other lists datasource as all available projects would be selected
List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID());
if (projectBeans!=null && !projectBeans.isEmpty()) {
projectIDs = GeneralUtils.createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans));
ancestorProjectIDs = projectIDs;
}
} else {
ancestorProjectIDs = ProjectBL.getAncestorProjects(projectIDs);
}
setExpressionValue(fieldExpressionInTreeTO, projectIDs, ancestorProjectIDs, itemTypeIDs, baseName, baseItemId, index, modifiable, personBean, locale);
return fieldExpressionInTreeTO;
}
/**
* Prepares a FieldExpressionSimpleTO for rendering:
* Only the matcher and the value controls are "active",
* field is fixed (only label is rendered for field)
* @param fieldID
* @param matcherID
* @param modifiable
* @param withParameter
* @param personID
* @param locale
* @param value
* @return
*/
public static FieldExpressionSimpleTO loadFilterExpressionSimple(Integer fieldID, Integer[] projectIDs, Integer[] itemTypeIDs,
Integer matcherID, boolean modifiable, boolean withParameter, TPersonBean personBean,
Locale locale, Map<Integer, String> fieldLabelsMap, Object value) {
FieldExpressionSimpleTO fieldExpressionSimpleTO = new FieldExpressionSimpleTO();
fieldExpressionSimpleTO.setField(fieldID);
fieldExpressionSimpleTO.setSelectedMatcher(matcherID);
fieldExpressionSimpleTO.setValue(value);
fieldExpressionSimpleTO.setFieldLabel(fieldLabelsMap.get(fieldID));
fieldExpressionSimpleTO.setMatcherName(getName(SIMPLE + MATCHER_RELATION_BASE_NAME, fieldID));
fieldExpressionSimpleTO.setMatcherItemId(getItemId(SIMPLE + MATCHER_RELATION_BASE_NAME, fieldID));
List<IntegerStringBean> matchers = getMatchers(fieldID, withParameter, false, locale);
//add empty matcher for FieldExpressionSimpleTO to give the possibility to not filter by this field
matchers.add(0, new IntegerStringBean("-", MatchRelations.NO_MATCHER));
fieldExpressionSimpleTO.setMatchersList(matchers);
Integer[] ancestorProjectIDs = null;
if (projectIDs==null || projectIDs.length==0) {
//none of the projects is selected -> get the other lists datasource as all available projects would be selected
List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID());
if (projectBeans!=null && !projectBeans.isEmpty()) {
projectIDs = GeneralUtils.createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans));
ancestorProjectIDs = projectIDs;
}
} else {
ancestorProjectIDs = ProjectBL.getAncestorProjects(projectIDs);
}
setExpressionValue(fieldExpressionSimpleTO, projectIDs, ancestorProjectIDs, itemTypeIDs,
SIMPLE + VALUE_BASE_NAME, SIMPLE + VALUE_BASE_ITEM_ID, fieldID, modifiable, personBean, locale);
return fieldExpressionSimpleTO;
}
/**
* Prepares a FieldExpressionSimpleTO created from a parameterized FieldExpressionInTreeTO for rendering:
* @param fieldExpressionSimpleTO
* @param projectIDs
* @param showClosed
* @param personID
* @param locale
* @param index
* @return
*/
public static FieldExpressionSimpleTO loadFieldExpressionSimpleForInTreeParameter(
FieldExpressionSimpleTO fieldExpressionSimpleTO, Integer[] projectIDs, Integer[] itemTypeIDs,
TPersonBean personBean, Locale locale, Map<Integer, String> fieldLabelsMap, int index) {
Integer fieldID = fieldExpressionSimpleTO.getField();
fieldExpressionSimpleTO.setIndex(index);
fieldExpressionSimpleTO.setFieldLabel(fieldLabelsMap.get(fieldID));
setMatchers(fieldExpressionSimpleTO, true, locale);
fieldExpressionSimpleTO.setMatcherName(getName(IN_TREE + MATCHER_RELATION_BASE_NAME, index));
fieldExpressionSimpleTO.setMatcherItemId(getItemId(IN_TREE + MATCHER_RELATION_BASE_NAME, index));
Integer[] ancestorProjectIDs = null;
if (projectIDs==null || projectIDs.length==0) {
//none of the projects is selected -> get the other lists datasource as all available projects would be selected
List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID());
if (projectBeans!=null && !projectBeans.isEmpty()) {
projectIDs = GeneralUtils.createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans));
ancestorProjectIDs = projectIDs;
}
} else {
ancestorProjectIDs = ProjectBL.getAncestorProjects(projectIDs);
}
setExpressionValue(fieldExpressionSimpleTO, projectIDs, ancestorProjectIDs, itemTypeIDs,
IN_TREE + VALUE_BASE_NAME, IN_TREE + VALUE_BASE_ITEM_ID, index, true, personBean, locale);
return fieldExpressionSimpleTO;
}
/**
* Set the matchers for parameter fields
* @param fieldExpressionSimpleTO
* @param locale
* @return
*/
public static FieldExpressionSimpleTO setMatchers(FieldExpressionSimpleTO fieldExpressionSimpleTO, boolean isTree, Locale locale) {
List<IntegerStringBean> matcherRelations = getMatchers(fieldExpressionSimpleTO.getField(), false, isTree, locale);
//add empty matcher for FieldExpressionSimpleTO to give the possibility to
//not to set parameter for this field consequently do not filter by this field
//TODO do we need this empty matcher for parameters or not?
matcherRelations.add(0, new IntegerStringBean("", MatchRelations.NO_MATCHER));
fieldExpressionSimpleTO.setMatchersList(matcherRelations);
Integer matcherID = fieldExpressionSimpleTO.getSelectedMatcher();
if (matcherID==null || matcherID.equals(MatcherContext.PARAMETER)) {
//matcher was parameter, now set it to the first
matcherID = matcherRelations.get(0).getValue();
fieldExpressionSimpleTO.setSelectedMatcher(matcherID);
}
return fieldExpressionSimpleTO;
}
/**
* Prepares the "in tree" filter expressions for rendering
* @param fieldExpressionInTreeList
* @param modifiable
* @param personID
* @param locale
* @param instant
* @param withFieldMoment
*/
public static void loadFilterExpressionInTreeList(List<FieldExpressionInTreeTO> fieldExpressionInTreeList, Integer[] projectIDs,
Integer[] itemTypeIDs, boolean modifiable, TPersonBean personBean, Locale locale, boolean withParameter, boolean withFieldMoment) {
if (fieldExpressionInTreeList!=null && !fieldExpressionInTreeList.isEmpty()) {
List<IntegerStringBean> fieldsWithMatcher = getAllMatcherColumns(projectIDs, personBean.getObjectID(), locale);
List<IntegerStringBean> localizedOperationList = getLocalizedOperationList(locale);
List<IntegerStringBean> parenthesisOpenList = createParenthesisOpenList();
List<IntegerStringBean> parenthesisClosedList = createParenthesisClosedList();
List<IntegerStringBean> fieldMoments = null;
if (withFieldMoment) {
fieldMoments = prepareFieldMomentList(locale);
}
Integer[] ancestorProjects = null;
if (projectIDs==null || projectIDs.length==0) {
//none of the projects is selected -> get the other lists datasource as all available projects would be selected
List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID());
if (projectBeans!=null && !projectBeans.isEmpty()) {
projectIDs = GeneralUtils.createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans));
ancestorProjects = projectIDs;
}
} else {
ancestorProjects = ProjectBL.getAncestorProjects(projectIDs);
}
int i=0;
for (FieldExpressionInTreeTO fieldExpressionInTreeTO : fieldExpressionInTreeList) {
fieldExpressionInTreeTO.setOperationsList(localizedOperationList);
fieldExpressionInTreeTO.setParenthesisOpenList(parenthesisOpenList);
fieldExpressionInTreeTO.setParenthesisClosedList(parenthesisClosedList);
if (withFieldMoment) {
fieldExpressionInTreeTO.setFieldMomentsList(fieldMoments);
}
loadFieldExpressionInTree(fieldExpressionInTreeTO, projectIDs, ancestorProjects, itemTypeIDs, fieldsWithMatcher,
modifiable, personBean, locale, withParameter, withFieldMoment, i++);
}
}
}
/**
* Prepares the "in tree" filter expressions for rendering
* @param index
* @param operation the default operation
* @param modifiable
* @param personID
* @param locale
* @param instant
* @param withFieldMoment
* @return
*/
static FieldExpressionInTreeTO loadFilterExpressionInTree(Integer[] projectIDs, Integer[] itemTypeIDs, Integer fieldID, Integer index,
boolean modifiable, TPersonBean personBean, Locale locale, boolean withParameter, boolean withFieldMoment) {
List<IntegerStringBean> fieldsWithMatcher = getAllMatcherColumns(projectIDs, personBean.getObjectID(), locale);
FieldExpressionInTreeTO fieldExpressionInTreeTO = new FieldExpressionInTreeTO();
List<IntegerStringBean> operationList = getLocalizedOperationList(locale);
fieldExpressionInTreeTO.setOperationsList(operationList);
//if added from the first add (For adds from a filter expression
//it takes the operation from the actual filter expression as default on the client side)
fieldExpressionInTreeTO.setSelectedOperation(QNode.OR);
fieldExpressionInTreeTO.setField(fieldID);
fieldExpressionInTreeTO.setParenthesisOpenList(createParenthesisOpenList());
fieldExpressionInTreeTO.setParenthesisClosedList(createParenthesisClosedList());
if (withFieldMoment) {
List<IntegerStringBean> fieldMoments = prepareFieldMomentList(locale);
fieldExpressionInTreeTO.setFieldMomentsList(fieldMoments);
fieldExpressionInTreeTO.setFieldMoment(fieldMoments.get(0).getValue());
}
Integer[] ancestorProjects = null;
if (projectIDs==null || projectIDs.length==0) {
//none of the projects is selected -> get the other lists datasource as all available projects would be selected
List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID());
if (projectBeans!=null && !projectBeans.isEmpty()) {
projectIDs = GeneralUtils.createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans));
ancestorProjects = projectIDs;
}
} else {
ancestorProjects = ProjectBL.getAncestorProjects(projectIDs);
}
loadFieldExpressionInTree(fieldExpressionInTreeTO, projectIDs, ancestorProjects, itemTypeIDs, fieldsWithMatcher,
modifiable, personBean, locale, withParameter, withFieldMoment, index);
return fieldExpressionInTreeTO;
}
/**
* Get all matcher columns
* @param projectIDs
* @param personID
* @param locale
* @return
*/
private static List<IntegerStringBean> getAllMatcherColumns(Integer[] projectIDs, Integer personID, Locale locale) {
List<TFieldConfigBean> fieldConfigsWithMatcher =
FieldRuntimeBL.getDefaultFieldConfigsWithMatcher(locale);
List<IntegerStringBean> fieldsWithMatcher = new LinkedList<IntegerStringBean>();
for (TFieldConfigBean fieldConfigBean : fieldConfigsWithMatcher) {
fieldsWithMatcher.add(new IntegerStringBean(fieldConfigBean.getLabel(), fieldConfigBean.getField()));
}
fieldsWithMatcher.addAll(getPseudoColumns(personID, locale));
Collections.sort(fieldsWithMatcher);
return fieldsWithMatcher;
}
/**
* Gets the pseudo columns allowed to see
* @param projectIDs
* @param locale
* @return
*/
private static List<IntegerStringBean> getPseudoColumns(Integer personID, Locale locale) {
boolean hasAccounting = ColumnFieldsBL.hasAccounting(personID);
Map<Integer, Boolean> pseudoFieldsVisible = ColumnFieldsBL.getVisisblePseudoFields(personID, hasAccounting);
List<IntegerStringBean> fieldsWithMatcher = new LinkedList<IntegerStringBean>();
Boolean watcherFieldsAllowed = pseudoFieldsVisible.get(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.WATCHERS);
if (watcherFieldsAllowed!=null && watcherFieldsAllowed.booleanValue()) {
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.CONSULTANT_LIST, locale), TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST));
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.INFORMANT_LIST, locale), TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST));
}
Boolean ownExpense = pseudoFieldsVisible.get(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.MY_EXPENSES);
if (ownExpense!=null && ownExpense.booleanValue()) {
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.MY_EXPENSE_TIME, locale), TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME));
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.MY_EXPENSE_COST, locale), TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST));
}
Boolean viewAllExpenses = pseudoFieldsVisible.get(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.ALL_EXPENSES);
if (viewAllExpenses!=null && viewAllExpenses.booleanValue()) {
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.TOTAL_EXPENSE_TIME, locale), TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME));
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.TOTAL_EXPENSE_COST, locale), TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST));
}
Boolean planVisible = pseudoFieldsVisible.get(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.PLAN);
if (planVisible!=null && planVisible.booleanValue()) {
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.TOTAL_PLANNED_TIME, locale), TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME));
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.TOTAL_PLANNED_COST, locale), TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST));
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.REMAINING_PLANNED_TIME, locale), TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME));
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.REMAINING_PLANNED_COST, locale), TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST));
}
Boolean budgetVisible = pseudoFieldsVisible.get(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.BUDGET);
if (budgetVisible!=null && budgetVisible) {
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.BUDGET_TIME, locale), TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME));
fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.BUDGET_COST, locale), TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST));
}
return fieldsWithMatcher;
}
/**
* Populates an "in tree" filter expression
* @param fieldExpressionInTreeTO
* @param fieldsWithMatcher
* @param modifiable
* @param personID
* @param locale
* @param instant
* @param withFieldMoment
* @param index
*/
private static void loadFieldExpressionInTree(FieldExpressionInTreeTO fieldExpressionInTreeTO, Integer[] projectIDs,
Integer[] ancestorProjectIDs, Integer[] itemTypeIDs, List<IntegerStringBean> fieldsWithMatcher, boolean modifiable, TPersonBean personBean,
Locale locale, boolean withParameter, boolean withFieldMoment, int index) {
fieldExpressionInTreeTO.setIndex(index);
//field moment
if (withFieldMoment) {
Integer selectedFieldMoment = fieldExpressionInTreeTO.getFieldMoment();
if (selectedFieldMoment==null) {
fieldExpressionInTreeTO.setFieldMoment(Integer.valueOf(TQueryRepositoryBean.FIELD_MOMENT.NEW));
}
fieldExpressionInTreeTO.setFieldMomentName(getName(FIELD_MOMENT_NAME, index));
fieldExpressionInTreeTO.setWithFieldMoment(withFieldMoment);
}
//field
Integer fieldID = fieldExpressionInTreeTO.getField();
if (fieldID==null &&
fieldsWithMatcher!=null && !fieldsWithMatcher.isEmpty()) {
//new field expression: preselect the first available field
fieldID = fieldsWithMatcher.get(0).getValue();
fieldExpressionInTreeTO.setField(fieldID);
}
fieldExpressionInTreeTO.setFieldsList(fieldsWithMatcher);
fieldExpressionInTreeTO.setFieldName(getName(FIELD_NAME, index));
fieldExpressionInTreeTO.setFieldItemId(getItemId(FIELD_NAME, index));
//matcher
List<IntegerStringBean> matcherList = getMatchers(fieldID, withParameter, true, locale);
fieldExpressionInTreeTO.setMatchersList(matcherList);
Integer matcherID = fieldExpressionInTreeTO.getSelectedMatcher();
if (matcherID==null) {
//new field expression: preselect the first available matcher:
//in FieldExpressionInTreeTO no empty matcher is available (like in FieldExpressionSimpleTO)
if (matcherList!=null && !matcherList.isEmpty()) {
matcherID = matcherList.get(0).getValue();
fieldExpressionInTreeTO.setSelectedMatcher(matcherID);
}
}
fieldExpressionInTreeTO.setMatcherName(getName(IN_TREE + MATCHER_RELATION_BASE_NAME, index));
fieldExpressionInTreeTO.setMatcherItemId(getItemId(IN_TREE + MATCHER_RELATION_BASE_NAME, index));
//value
setExpressionValue(fieldExpressionInTreeTO, projectIDs, ancestorProjectIDs, itemTypeIDs, IN_TREE + VALUE_BASE_NAME, IN_TREE + VALUE_BASE_ITEM_ID, index, modifiable, personBean, locale);
fieldExpressionInTreeTO.setOperationName(getName(OPERATION_NAME, index));
fieldExpressionInTreeTO.setOperationItemId(getItemId(OPERATION_NAME, index));
fieldExpressionInTreeTO.setParenthesisOpenName(getName(PARENTHESIS_OPEN_NAME, index));
fieldExpressionInTreeTO.setParenthesisClosedName(getName(PARENTHESIS_CLOSED_NAME, index));
}
/**
* Set expression value attributes: needMatcherValue, matcherID, valueRenderer and JsonConfig string
* The field, the matcher (if it is the case) and the value object should be already set for FieldExpressionSimpleTO
* @param fieldExpressionSimpleTreeTO
* @param projectIDs
* @param ancestorProjectIDs
* @param itemTypeIDs
* @param baseName
* @param baseItemId
* @param index
* @param modifiable
* @param personID
* @param locale
*/
private static void setExpressionValue(FieldExpressionSimpleTO fieldExpressionSimpleTreeTO,
Integer[] projectIDs, Integer[] ancestorProjectIDs, Integer[] itemTypeIDs, String baseName, String baseItemId, Integer index,
boolean modifiable, TPersonBean personBean, Locale locale) {
Integer personID = personBean.getObjectID();
Integer matcherID = fieldExpressionSimpleTreeTO.getSelectedMatcher();
fieldExpressionSimpleTreeTO.setValueItemId(getItemId(baseItemId, index));
if (matcherID!=null) {
//do not force the matcher to a value if not specified because no matcher means no filtering by that field
//even if the field is always present (it is set as upper filter field)
//(it was set already to a value if if was the case)
boolean needMatcherValue = getNeedMatcherValue(matcherID);
fieldExpressionSimpleTreeTO.setNeedMatcherValue(needMatcherValue);
if (needMatcherValue) {
Integer fieldID = fieldExpressionSimpleTreeTO.getField();
IMatcherDT matcherDT = null;
Object possibleValues = null;
//for field expressions the "withParameter" is false for getting the datasoucre,
//because only the matcher is parameterized not the value
//but "initValueIfNull" is true to preselect the first entry if nothing selected
//do not show the closed entities in field expressions (typically used for release but it can be
//interpreted also for person (deactivated), deleted custom entries etc.)
MatcherDatasourceContext matcherDatasourceContext = new MatcherDatasourceContext(projectIDs, ancestorProjectIDs, itemTypeIDs, personBean, locale, false, true, false, false);
if (fieldID.intValue()>0) {
IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID);
if (fieldTypeRT!=null) {
matcherDT = fieldTypeRT.processLoadMatcherDT(fieldID);
possibleValues = fieldTypeRT.getMatcherDataSource(fieldExpressionSimpleTreeTO, matcherDatasourceContext, null);
}
} else {
matcherDT = getPseudoMatcherDT(fieldID);
possibleValues = getPseudoFieldMatcherDataSource(fieldExpressionSimpleTreeTO, matcherDatasourceContext);
}
if (matcherDT!=null) {
matcherDT.setRelation(matcherID);
fieldExpressionSimpleTreeTO.setValueRenderer(matcherDT.getMatchValueControlClass());
fieldExpressionSimpleTreeTO.setJsonConfig(matcherDT.getMatchValueJsonConfig(fieldID,
baseName, index, fieldExpressionSimpleTreeTO.getValue(), !modifiable, possibleValues, projectIDs, matcherID, locale, personID));
}
}
}
}
/**
* Gets the datasource for pseudo fields (only for lists)
* @param matcherValue
* @param matcherDatasourceContext
* @param parameterCode
* @return
*/
private static Object getPseudoFieldMatcherDataSource(IMatcherValue matcherValue, MatcherDatasourceContext matcherDatasourceContext) {
Integer fieldID = matcherValue.getField();
if (fieldID!=null) {
String raciRole;
switch (fieldID.intValue()) {
case TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST:
raciRole = RaciRole.CONSULTANT;
break;
case TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST:
raciRole = RaciRole.INFORMANT;
break;
default:
//expense/budget/plan
return null;
}
Integer[] projects = matcherDatasourceContext.getProjectIDs();
Integer[] ancestorProjects = matcherDatasourceContext.getAncestorProjectIDs();
if (projects!=null && projects.length>0) {
List<ILabelBean> watcherList = FilterSelectsListsLoader.getConsultantsInformants(projects, ancestorProjects,
matcherDatasourceContext.getPersonBean().getObjectID(), false, raciRole, matcherDatasourceContext.getLocale());
if (matcherDatasourceContext.isInitValueIfNull() && matcherValue!=null && watcherList!=null && !watcherList.isEmpty()) {
Object value = matcherValue.getValue();
if (value==null) {
matcherValue.setValue(new Integer[] {watcherList.get(0).getObjectID()});
}
}
return watcherList;
}
}
return null;
}
/**
* Whether do we need a matcherValue field: for matcherRelations
* IS_NULL NOT_IS_NULL and LATER_AS_LASTLOGIN we do not need it
* @param matcherRelation
* @return
*/
public static boolean getNeedMatcherValue(Integer matcherRelation) {
if (matcherRelation==null) {
return false;
}
if (matcherRelation.equals(MatcherContext.PARAMETER)) {
return false;
}
switch(matcherRelation.intValue()) {
case MatchRelations.IS_NULL:
case MatchRelations.NOT_IS_NULL:
case MatchRelations.LATER_AS_LASTLOGIN:
case MatchRelations.SET:
case MatchRelations.RESET:
return false;
default:
return true;
}
}
/**
* Builds the name of the client side controls for submit
* @param name
* @param suffix
* @return
*/
private static String getName(String name, Integer suffix) {
StringBuilder stringBuilder = new StringBuilder();
return stringBuilder.append(name).append("[").append(suffix).append("]").toString();
}
/**
* Builds the name of the client side controls for submit
* @param name
* @param suffix
* @return
*/
private static String getItemId(String name, Integer suffix) {
StringBuilder stringBuilder = new StringBuilder();
return stringBuilder.append(name).append(suffix).toString();
}
/**
* Gets the localized operations
* @param locale
* @return
*/
private static List<IntegerStringBean> getLocalizedOperationList(Locale locale) {
List<IntegerStringBean> operationList = new ArrayList<IntegerStringBean>();
operationList.add(new IntegerStringBean(
LocalizeUtil.getLocalizedTextFromApplicationResources(
"admin.customize.queryFilter.opt.operation.and", locale), QNode.AND));
operationList.add(new IntegerStringBean(
LocalizeUtil.getLocalizedTextFromApplicationResources(
"admin.customize.queryFilter.opt.operation.or", locale), QNode.OR));
operationList.add(new IntegerStringBean(
LocalizeUtil.getLocalizedTextFromApplicationResources(
"admin.customize.queryFilter.opt.operation.notAnd", locale), QNode.NOT_AND));
operationList.add(new IntegerStringBean(
LocalizeUtil.getLocalizedTextFromApplicationResources(
"admin.customize.queryFilter.opt.operation.notOr", locale), QNode.NOT_OR));
return operationList;
}
//max number of parenthesis
private static final int MAX_PARENTHESIS_DEEP = 6;
/**
* Generate the parenthesisOpenList
* @return
*/
private static List<IntegerStringBean> createParenthesisOpenList() {
return getParenthesisList('(', MAX_PARENTHESIS_DEEP);
}
/**
* Generate the parenthesisClosedList
* @return
*/
private static List<IntegerStringBean> createParenthesisClosedList() {
return getParenthesisList(')', MAX_PARENTHESIS_DEEP);
}
/**
* Generate the parenthesis list
* @param parenthesis
* @param maxDeep
* @return
*/
private static List<IntegerStringBean> getParenthesisList(char parenthesis, int maxDeep) {
List<IntegerStringBean> parenthesisList = new ArrayList<IntegerStringBean>();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < maxDeep; i++) {
parenthesisList.add(new IntegerStringBean(stringBuffer.toString(), Integer.valueOf(i)));
stringBuffer.append(parenthesis);
}
return parenthesisList;
}
/**
* Prepares the field moment list for notification filters
* @param locale
* @return
*/
private static List<IntegerStringBean> prepareFieldMomentList(Locale locale) {
List<IntegerStringBean> fieldMomentList = new ArrayList<IntegerStringBean>();
fieldMomentList.add
(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(
"common.opt.fieldMoment.new", locale),
Integer.valueOf(TQueryRepositoryBean.FIELD_MOMENT.NEW)));
fieldMomentList.add
(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(
"common.opt.fieldMoment.old", locale),
Integer.valueOf(TQueryRepositoryBean.FIELD_MOMENT.OLD)));
return fieldMomentList;
}
/**
* Get the matchers corresponding to the field
* @param fieldID
* @param withParameter
* @param inTree
* @param locale
* @return
*/
public static List<IntegerStringBean> getMatchers(Integer fieldID, boolean withParameter, boolean inTree, Locale locale) {
List<IntegerStringBean> localizedRelations = new ArrayList<IntegerStringBean>();
if (fieldID==null) {
return localizedRelations;
} else {
IMatcherDT matcherDT = null;
if (fieldID>0) {
IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID);
if (fieldTypeRT==null) {
//for example the Keyword pseudo field
return localizedRelations;
}
matcherDT = fieldTypeRT.processLoadMatcherDT(fieldID);
} else {
matcherDT = getPseudoMatcherDT(fieldID);
}
if (matcherDT!=null) {
List<Integer> possibleRelations = matcherDT.getPossibleRelations(withParameter, inTree);
if (possibleRelations!=null) {
localizedRelations = LocalizeUtil.getLocalizedList(
MATCH_RELATION_PREFIX, possibleRelations, locale);
}
}
}
return localizedRelations;
}
/**
* Gets the pseudo field matcherDTs
* @param fieldID
* @return
*/
private static IMatcherDT getPseudoMatcherDT(Integer fieldID) {
if (fieldID!=null) {
switch (fieldID.intValue()) {
case TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST:
case TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST:
return new SelectMatcherDT(fieldID);
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME:
return new AccountingTimeMatcherDT(fieldID);
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST:
return new DoubleMatcherDT(fieldID);
}
}
return null;
}
/**
* Gets the pseudo fields matcher converter
* @param fieldID
* @return
*/
public static MatcherConverter getPseudoFieldMatcherConverter(Integer fieldID) {
if (fieldID!=null) {
switch (fieldID.intValue()) {
case TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST:
case TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST:
return new SelectMatcherConverter();
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME:
return new AccountingTimeMatcherConverter();
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST:
return new DoubleMatcherConverter();
}
}
return null;
}
/**
* Gets the pseudo field matcherDTs
* @param fieldID
* @return
*/
public static IFieldTypeRT getPseudoFieldFieldTypeRT(Integer fieldID) {
if (fieldID!=null) {
switch (fieldID.intValue()) {
case TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST:
case TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST:
return new SystemManagerRT();
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST:
return new CustomDoubleRT();
}
}
return null;
}
/**
* Gets the pseudo field matcherDTs
* @param fieldID
* @return
*/
public static Integer getPseudoFieldSystemOption(Integer fieldID) {
if (fieldID!=null) {
switch (fieldID.intValue()) {
case TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST:
case TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST:
return SystemFields.INTEGER_PERSON;
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST:
case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME:
case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST:
return fieldID;
}
}
return null;
}
}
| gpl-3.0 |
jdmonin/JSettlers2 | src/test/java/soctest/message/TestTemplatesAbstracts.java | 4601 | /**
* Java Settlers - An online multiplayer version of the game Settlers of Catan
* This file Copyright (C) 2020-2021 Jeremy D Monin <jeremy@nand.net>
*
* 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/>.
*
* The maintainer of this program can be reached at jsettlers@nand.net
**/
package soctest.message;
import java.util.ArrayList;
import java.util.List;
import soc.message.SOCMessage;
import soc.message.SOCMessageTemplateMs;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* A few tests for template/abstract message types like {@link SOCMessageTemplateMs}
* which aren't part of the main list tested in {@link TestToCmdToStringParse}.
* @since 2.5.00
*/
public class TestTemplatesAbstracts
{
/** Test {@link SOCMessageTemplateMs#toString()} and {@link SOCMessageTemplateMs#toString(List, String[])}. */
@Test
public void testSOCMessageTemplateMsToString()
{
final String[] NAMES_1 = {"a"}, NAMES_3 = {"a", "b", "c"};
MessageMs msg = new MessageMs(null);
assertEquals("MessageMs:(pa null)", msg.toString());
assertEquals("MessageMs:(pa null)", msg.toString(null, null));
List<String> pa = new ArrayList<>();
msg = new MessageMs(pa);
assertEquals("MessageMs:(pa empty)", msg.toString());
assertEquals("MessageMs:(pa empty)", msg.toString(pa, null));
assertEquals("MessageMs:(pa empty)", msg.toString(pa, NAMES_3));
pa.add("xy");
msg = new MessageMs(pa);
assertEquals("MessageMs:p=xy", msg.toString());
assertEquals("MessageMs:p=xy", msg.toString(pa, null));
assertEquals("MessageMs:a=xy", msg.toString(pa, NAMES_1));
assertEquals("MessageMs:a=xy", msg.toString(pa, NAMES_3));
pa.add("z");
msg = new MessageMs(pa);
assertEquals("MessageMs:p=xy|p=z", msg.toString());
assertEquals("MessageMs:p=xy|p=z", msg.toString(pa, null));
assertEquals("MessageMs:a=xy|p=z", msg.toString(pa, NAMES_1));
assertEquals("MessageMs:a=xy|b=z", msg.toString(pa, NAMES_3));
pa.add(null);
pa.add("w");
msg = new MessageMs(pa);
assertEquals("MessageMs:p=xy|p=z|(p null)|p=w", msg.toString());
assertEquals("MessageMs:p=xy|p=z|(p null)|p=w", msg.toString(pa, null));
assertEquals("MessageMs:a=xy|p=z|(p null)|p=w", msg.toString(pa, NAMES_1));
assertEquals("MessageMs:a=xy|b=z|(c null)|p=w", msg.toString(pa, NAMES_3));
pa.clear();
pa.add(null);
msg = new MessageMs(pa);
assertEquals("MessageMs:(p null)", msg.toString());
assertEquals("MessageMs:(p null)", msg.toString(pa, null));
assertEquals("MessageMs:(a null)", msg.toString(pa, NAMES_3));
pa.add("zw");
msg = new MessageMs(pa);
assertEquals("MessageMs:(p null)|p=zw", msg.toString());
assertEquals("MessageMs:(p null)|p=zw", msg.toString(pa, null));
assertEquals("MessageMs:(a null)|p=zw", msg.toString(pa, NAMES_1));
assertEquals("MessageMs:(a null)|b=zw", msg.toString(pa, NAMES_3));
}
// TODO test SOCMessageTemplateMs.parseData_FindEmptyStrs
/** Non-abstract subclass for tests. */
@SuppressWarnings("serial")
private static class MessageMs extends SOCMessageTemplateMs
{
/**
* Constructor for tests.
* @param pal List of parameters, or null if none.
* Sets {@link #pa} field to {@code pal}: Afterwards method calls on {@code pa} or {@code pal}
* will affect the same List object.
* <P>
* Does not convert {@link SOCMessage#EMPTYSTR} field values to "";
* see {@link SOCMessageTemplateMs#parseData_FindEmptyStrs(List)}.
*/
public MessageMs(List<String> pal)
{
super(0, pal);
}
public String toString(List<String> params, String[] fieldNames)
{
return super.toString(params, fieldNames);
}
}
}
| gpl-3.0 |
AminLiu/Test | queencastle-all/queencastle-service/src/main/java/com/queencastle/service/interf/SysResourceInfoService.java | 182 | package com.queencastle.service.interf;
import com.queencastle.dao.model.SysResourceInfo;
public interface SysResourceInfoService {
int insert(SysResourceInfo resourceInfo);
}
| gpl-3.0 |
icgc-dcc/dcc-common | dcc-common-test/src/main/java/org/icgc/dcc/common/test/mongodb/MongoExporter.java | 3427 | /*
* Copyright (c) 2016 The Ontario Institute for Cancer Research. 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/>.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.icgc.dcc.common.test.mongodb;
import static com.google.common.base.Preconditions.checkState;
import java.io.File;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.mongodb.DB;
@Slf4j
public class MongoExporter extends BaseMongoImportExport {
public MongoExporter(File targetDirectory, DB targetDatabase) {
super(targetDirectory, new Jongo(targetDatabase));
}
@Override
@SneakyThrows
public void execute() {
for(String collectionName : jongo.getDatabase().getCollectionNames()) {
MongoCollection collection = jongo.getCollection(collectionName);
String fileName = getFileName(collectionName);
File collectionFile = new File(directory, fileName);
log.info("Exporting to '{}' from '{}'...", collectionFile, collection);
exportCollection(collectionFile, collection);
}
}
@SneakyThrows
private void exportCollection(File collectionFile, MongoCollection collection) {
Files.createParentDirs(collectionFile);
if(collectionFile.exists()) {
checkState(collectionFile.delete(), "Collection file not deleted: %s", collectionFile);
}
checkState(collectionFile.createNewFile(), "Collection file not created: %s", collectionFile);
ObjectMapper mapper = new ObjectMapper();
for(JsonNode jsonNode : collection.find().as(JsonNode.class)) {
String json = mapper.writeValueAsString(jsonNode) + System.getProperty("line.separator");
Files.append(json, collectionFile, Charsets.UTF_8);
}
}
}
| gpl-3.0 |
sethten/MoDesserts | mcp50/src/minecraft/net/minecraft/src/EntityExplodeFX.java | 1510 | package net.minecraft.src;
import java.util.Random;
public class EntityExplodeFX extends EntityFX
{
public EntityExplodeFX(World par1World, double par2, double par4, double par6, double par8, double par10, double par12)
{
super(par1World, par2, par4, par6, par8, par10, par12);
motionX = par8 + (double)((float)(Math.random() * 2D - 1.0D) * 0.05F);
motionY = par10 + (double)((float)(Math.random() * 2D - 1.0D) * 0.05F);
motionZ = par12 + (double)((float)(Math.random() * 2D - 1.0D) * 0.05F);
particleRed = particleGreen = particleBlue = rand.nextFloat() * 0.3F + 0.7F;
particleScale = rand.nextFloat() * rand.nextFloat() * 6F + 1.0F;
particleMaxAge = (int)(16D / ((double)rand.nextFloat() * 0.80000000000000004D + 0.20000000000000001D)) + 2;
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate()
{
prevPosX = posX;
prevPosY = posY;
prevPosZ = posZ;
if (particleAge++ >= particleMaxAge)
{
setDead();
}
setParticleTextureIndex(7 - (particleAge * 8) / particleMaxAge);
motionY += 0.0040000000000000001D;
moveEntity(motionX, motionY, motionZ);
motionX *= 0.89999997615814209D;
motionY *= 0.89999997615814209D;
motionZ *= 0.89999997615814209D;
if (onGround)
{
motionX *= 0.69999998807907104D;
motionZ *= 0.69999998807907104D;
}
}
}
| gpl-3.0 |
mg-1999/alf.io | src/main/java/alfio/manager/EventStatisticsManager.java | 8171 | /**
* This file is part of alf.io.
*
* alf.io 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.
*
* alf.io 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 alf.io. If not, see <http://www.gnu.org/licenses/>.
*/
package alfio.manager;
import alfio.manager.system.ConfigurationManager;
import alfio.manager.user.UserManager;
import alfio.model.*;
import alfio.model.modification.TicketWithStatistic;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import alfio.model.user.Organization;
import alfio.repository.*;
import alfio.util.EventUtil;
import alfio.util.MonetaryUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
@Component
@AllArgsConstructor
public class EventStatisticsManager {
private final EventRepository eventRepository;
private final EventDescriptionRepository eventDescriptionRepository;
private final TicketRepository ticketRepository;
private final TicketCategoryRepository ticketCategoryRepository;
private final TicketCategoryDescriptionRepository ticketCategoryDescriptionRepository;
private final TicketReservationRepository ticketReservationRepository;
private final SpecialPriceRepository specialPriceRepository;
private final ConfigurationManager configurationManager;
private final UserManager userManager;
private List<Event> getAllEvents(String username) {
List<Integer> orgIds = userManager.findUserOrganizations(username).stream().map(Organization::getId).collect(toList());
return orgIds.isEmpty() ? Collections.emptyList() : eventRepository.findByOrganizationIds(orgIds);
}
public List<EventStatistic> getAllEventsWithStatisticsFilteredBy(String username, Predicate<Event> predicate) {
List<Event> events = getAllEvents(username).stream().filter(predicate).collect(toList());
Map<Integer, Event> mappedEvent = events.stream().collect(Collectors.toMap(Event::getId, Function.identity()));
if(!mappedEvent.isEmpty()) {
boolean isOwner = userManager.isOwner(userManager.findUserByUsername(username));
Set<Integer> ids = mappedEvent.keySet();
Stream<EventStatisticView> stats = isOwner ? eventRepository.findStatisticsFor(ids).stream() : ids.stream().map(EventStatisticView::empty);
return stats.map(stat -> {
Event event = mappedEvent.get(stat.getEventId());
return new EventStatistic(event, stat, displayStatisticsForEvent(event));
}).sorted().collect(Collectors.toList());
} else {
return Collections.emptyList();
}
}
private boolean displayStatisticsForEvent(Event event) {
return configurationManager.getBooleanConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.DISPLAY_STATS_IN_EVENT_DETAIL), true);
}
@Cacheable
public List<EventStatistic> getAllEventsWithStatistics(String username) {
return getAllEventsWithStatisticsFilteredBy(username, (e) -> true);
}
public EventWithAdditionalInfo getEventWithAdditionalInfo(String eventName, String username) {
Event event = getEventAndCheckOwnership(eventName, username);
Map<String, String> description = eventDescriptionRepository.findByEventIdAsMap(event.getId());
boolean owner = userManager.isOwner(userManager.findUserByUsername(username));
EventStatisticView statistics = owner ? eventRepository.findStatisticsFor(event.getId()) : EventStatisticView.empty(event.getId());
EventStatistic eventStatistic = new EventStatistic(event, statistics, displayStatisticsForEvent(event));
BigDecimal grossIncome = owner ? MonetaryUtil.centsToUnit(eventRepository.getGrossIncome(event.getId())) : BigDecimal.ZERO;
List<TicketCategory> ticketCategories = loadTicketCategories(event);
List<Integer> ticketCategoriesIds = ticketCategories.stream().map(TicketCategory::getId).collect(Collectors.toList());
Map<Integer, Map<String, String>> descriptions = ticketCategoryDescriptionRepository.descriptionsByTicketCategory(ticketCategoriesIds);
Map<Integer, TicketCategoryStatisticView> ticketCategoriesStatistics = owner ? ticketCategoryRepository.findStatisticsForEventIdByCategoryId(event.getId()) : ticketCategoriesIds.stream().collect(toMap(Function.identity(), id -> TicketCategoryStatisticView.empty(id, event.getId())));
Map<Integer, List<SpecialPrice>> specialPrices = ticketCategoriesIds.isEmpty() ? Collections.emptyMap() : specialPriceRepository.findAllByCategoriesIdsMapped(ticketCategoriesIds);
List<TicketCategoryWithAdditionalInfo> tWithInfo = ticketCategories.stream()
.map(t -> new TicketCategoryWithAdditionalInfo(event, t, ticketCategoriesStatistics.get(t.getId()), descriptions.get(t.getId()), specialPrices.get(t.getId())))
.collect(Collectors.toList());
return new EventWithAdditionalInfo(event, tWithInfo, eventStatistic, description, grossIncome);
}
private List<TicketCategory> loadTicketCategories(Event event) {
return ticketCategoryRepository.findByEventId(event.getId());
}
private Event getEventAndCheckOwnership(String eventName, String username) {
Event event = eventRepository.findByShortName(eventName);
userManager.findOrganizationById(event.getOrganizationId(), username);
return event;
}
private static String prepareSearchTerm(String search) {
String toSearch = StringUtils.trimToNull(search);
return toSearch == null ? null : ("%" + toSearch + "%");
}
public List<TicketWithStatistic> loadModifiedTickets(int eventId, int categoryId, int page, String search) {
Event event = eventRepository.findById(eventId);
String toSearch = prepareSearchTerm(search);
final int pageSize = 30;
return ticketRepository.findAllModifiedTicketsWithReservationAndTransaction(eventId, categoryId, page * pageSize, pageSize, toSearch).stream()
.map(t -> new TicketWithStatistic(t.getTicket(), event, t.getTicketReservation(), event.getZoneId(), t.getTransaction()))
.sorted()
.collect(Collectors.toList());
}
public Integer countModifiedTicket(int eventId, int categoryId, String search) {
String toSearch = prepareSearchTerm(search);
return ticketRepository.countAllModifiedTicketsWithReservationAndTransaction(eventId, categoryId, toSearch);
}
public Predicate<Event> noSeatsAvailable() {
return event -> {
Map<Integer, TicketCategoryStatisticView> stats = ticketCategoryRepository.findStatisticsForEventIdByCategoryId(event.getId());
EventStatisticView eventStatisticView = eventRepository.findStatisticsFor(event.getId());
return ticketCategoryRepository.findAllTicketCategories(event.getId())
.stream()
.filter(tc -> !tc.isAccessRestricted())
.allMatch(tc -> EventUtil.determineAvailableSeats(stats.get(tc.getId()), eventStatisticView) == 0);
};
}
public List<TicketSoldStatistic> getTicketSoldStatistics(int eventId, Date from, Date to) {
return ticketReservationRepository.getSoldStatistic(eventId, from, to);
}
}
| gpl-3.0 |
emrah-it/Softuni | Level 1/Java Basics/Loops Methods Classes/Loops Methods Classes/src/_5_AngleUnitConverterDegreesRadians.java | 1330 | //Problem 5. Angle Unit Converter (Degrees ↔ Radians)
//Write a method to convert from degrees to radians. Write a method to convert from radians to degrees.
// You are given a number n and n queries for conversion. Each conversion query will consist of a
// number + space + measure. Measures are "deg" and "rad". Convert all radians to degrees and all
// degrees to radians. Print the results as n lines, each holding a number + space + measure. Format
// all numbers with 6 digit after the decimal point.
import java.util.ArrayList;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Scanner;
public class _5_AngleUnitConverterDegreesRadians {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter how many calculation you want to make");
int n = Integer.parseInt(input.nextLine());
List<String> result = new ArrayList<String>();
for (int i = 0; i < n; i++) {
String[] cmd = input.nextLine().split(" ");
String currentResult;
if (cmd[1].equals("rad")) {
currentResult = Math.toDegrees(Double.parseDouble(cmd[0]))
+ " deg";
} else {
currentResult = Math.toDegrees(Double.parseDouble(cmd[0]))
+ " rad";
}
result.add(currentResult);
}
System.out.println(String.join("\n", result));
}
}
| gpl-3.0 |
ksmonkey123/ModellbahnCore | src/ch/awae/moba/core/operators/Enabled.java | 608 | package ch.awae.moba.core.operators;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Indicates whether an operator is enabled or not.
*
* Enabled operators are activated by default during startup.
*
* <p>
* This annotation defaults to {@code enabled}; therefore {@code @Enabled} is
* equivalent to {@code @Enabled(true)}. To disable an operator annotate it with
* {@code @Enabled(false)}.
* </p>
*
* @author Andreas Wälchli
* @see IOperation
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Enabled {
boolean value() default true;
}
| gpl-3.0 |
wanleung/Stroke5Keyboard-android | src/com/linkomnia/android/Stroke5/IMEKeyboard.java | 1979 | /*
Stroke5 Chinese Input Method for Android
Copyright (C) 2012 LinkOmnia Ltd.
Author: Wan Leung Wong (wanleung@linkomnia.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.linkomnia.android.Stroke5;
import android.content.Context;
import android.inputmethodservice.Keyboard;
public class IMEKeyboard extends Keyboard {
static final int KEYCODE_ENTER = 10;
static final int KEYCODE_CAPLOCK = -200;
static final int KEYCODE_MODE_CHANGE_CHAR = -300;
static final int KEYCODE_MODE_CHANGE_SIMLEY = -400;
static final int KEYCODE_MODE_CHANGE_CHSYMBOL = -500;
static final int KEYCODE_MODE_CHANGE_LANG = -600;
private boolean isCapLock;
public IMEKeyboard(Context context, int xmlLayoutResId) {
super(context, xmlLayoutResId);
this.isCapLock = false;
this.setShifted(false);
}
public IMEKeyboard(Context context, int layoutTemplateResId,
CharSequence characters, int columns, int horizontalPadding) {
super(context, layoutTemplateResId, characters, columns,
horizontalPadding);
this.isCapLock = false;
this.setShifted(false);
}
public boolean isCapLock() {
return this.isCapLock;
}
public void setCapLock(boolean b) {
this.isCapLock = b;
this.setShifted(b);
}
}
| gpl-3.0 |
ckaestne/CIDE | CIDE_Language_CS/src/tmp/generated_cs/field_declarators.java | 1120 | package tmp.generated_cs;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class field_declarators extends GenASTNode {
public field_declarators(field_declarator field_declarator, ArrayList<field_declarator> field_declarator1, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyOne<field_declarator>("field_declarator", field_declarator),
new PropertyZeroOrMore<field_declarator>("field_declarator1", field_declarator1)
}, firstToken, lastToken);
}
public field_declarators(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public IASTNode deepCopy() {
return new field_declarators(cloneProperties(),firstToken,lastToken);
}
public field_declarator getField_declarator() {
return ((PropertyOne<field_declarator>)getProperty("field_declarator")).getValue();
}
public ArrayList<field_declarator> getField_declarator1() {
return ((PropertyZeroOrMore<field_declarator>)getProperty("field_declarator1")).getValue();
}
}
| gpl-3.0 |
rferreira/uva-core | src/com/uvasoftware/core/data/student/StudentSchoolEnrollment.java | 447 | package com.uvasoftware.core.data.student;
import com.uvasoftware.core.ISIFObject;
import com.uvasoftware.core.data.common.BaseSIFObject;
public class StudentSchoolEnrollment extends BaseSIFObject implements
ISIFObject {
@Override
public Object getPrimitive() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setPrimitive(Object primitive) {
// TODO Auto-generated method stub
}
}
| gpl-3.0 |
Securecom/Securecom-Voice | src/com/securecomcode/voice/call/CallLogDatabase.java | 6364 | /*
* Copyright (C) 2015 Securecom
* 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.securecomcode.voice.call;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.securecomcode.voice.ui.RecentCallListActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CallLogDatabase {
private static final String DATABASE_NAME = "securecom_calllog.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "call_log";
private static final String ID = "_id";
public static final String NUMBER = "number";
public static final String CONTACT_NAME = "contactName";
public static final String DATE = "date";
public static final String TYPE = "type";
public static final String NUMBER_LABEL = "numberLabel";
private RecentCallListActivity recentCallListActivity = null;
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY, " +
NUMBER + " TEXT," +
CONTACT_NAME + " TEXT," +
DATE + " TEXT," +
TYPE + " TEXT," +
NUMBER_LABEL + " TEXT );";
private static final Object instanceLock = new Object();
private static volatile CallLogDatabase instance;
public static CallLogDatabase getInstance(Context context) {
if (instance == null) {
synchronized (instanceLock) {
if (instance == null) {
instance = new CallLogDatabase(context);
}
}
}
return instance;
}
private final DatabaseHelper databaseHelper;
private final Context context;
private CallLogDatabase(Context context) {
this.context = context;
this.databaseHelper = new DatabaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void setCallLogEntryValues(ContentValues values) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
if(cursor.getCount() == 200){
deleteFirstRow(db, cursor);
}
db.beginTransaction();
try {
db.insert(TABLE_NAME, null, values);
db.setTransactionSuccessful();
}finally {
db.endTransaction();
}
if(recentCallListActivity != null){
recentCallListActivity.databaseContentUpdated();
}
}
public void deleteFirstRow(SQLiteDatabase db, Cursor cursor){
db.beginTransaction();
try {
if (cursor.moveToFirst()) {
String rowId = cursor.getString(cursor.getColumnIndex(ID));
db.delete(TABLE_NAME, ID + "=?", new String[]{rowId});
db.setTransactionSuccessful();
}
}finally {
db.endTransaction();
}
}
public void doDatabaseReset(Context context) {
context.deleteDatabase(DATABASE_NAME);
instance = null;
}
public int getDatabaseTableRowCount(){
int count = 0;
try {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
count = cursor.getCount();
}catch (Exception e){
}
return count;
}
public ArrayList<CallDetail> getActiveCallLog(RecentCallListActivity recentCallListActivity) {
this.recentCallListActivity = recentCallListActivity;
final ArrayList<CallDetail> results = new ArrayList<CallDetail>();
Cursor cursor = null;
try {
cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, new String[]{NUMBER, CONTACT_NAME, DATE, TYPE, NUMBER_LABEL}, null, null, null, null, null);
while (cursor != null && cursor.moveToNext()) {
results.add(cursorToCallDetail(cursor));
}
Collections.sort(results, new Comparator<CallDetail>() {
@Override
public int compare(CallDetail lhs, CallDetail rhs) {
long date1 = Long.parseLong(lhs.getDate());
long date2 = Long.parseLong(rhs.getDate());
return (date1>date2 ? -1 : (date1 == date2 ? 0 : 1));
}
});
return results;
} finally {
if (cursor != null)
cursor.close();
}
}
private CallDetail cursorToCallDetail(Cursor cursor) {
CallDetail callDetail = new CallDetail();
callDetail.setNumber(cursor.getString(0));
callDetail.setContactName(cursor.getString(1));
callDetail.setDate(cursor.getString(2));
callDetail.setType(cursor.getString(3));
callDetail.setNumberLabel(cursor.getString(4));
return callDetail;
}
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS call_log;");
onCreate(db);
}
}
}
| gpl-3.0 |
nikiroo/fanfix | src/be/nikiroo/utils/test_code/StringUtilsTest.java | 10509 | package be.nikiroo.utils.test_code;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import be.nikiroo.utils.StringUtils;
import be.nikiroo.utils.StringUtils.Alignment;
import be.nikiroo.utils.test.TestCase;
import be.nikiroo.utils.test.TestLauncher;
class StringUtilsTest extends TestLauncher {
public StringUtilsTest(String[] args) {
super("StringUtils test", args);
addTest(new TestCase("Time serialisation") {
@Override
public void test() throws Exception {
for (long fullTime : new Long[] { 0l, 123456l, 123456000l,
new Date().getTime() }) {
// precise to the second, no more
long time = (fullTime / 1000) * 1000;
String displayTime = StringUtils.fromTime(time);
assertNotNull("The stringified time for " + time
+ " should not be null", displayTime);
assertEquals("The stringified time for " + time
+ " should not be empty", false, displayTime.trim()
.isEmpty());
assertEquals("The time " + time
+ " should be loop-convertable", time,
StringUtils.toTime(displayTime));
assertEquals("The time " + displayTime
+ " should be loop-convertable", displayTime,
StringUtils.fromTime(StringUtils
.toTime(displayTime)));
}
}
});
addTest(new TestCase("MD5") {
@Override
public void test() throws Exception {
String mess = "The String we got is not what 'md5sum' said it should heve been";
assertEquals(mess, "34ded48fcff4221d644be9a37e1cb1d9",
StringUtils.getMd5Hash("fanfan la tulipe"));
assertEquals(mess, "7691b0cb74ed0f94b4d8cd858abe1165",
StringUtils.getMd5Hash("je te do-o-o-o-o-o-nne"));
}
});
addTest(new TestCase("Padding") {
@Override
public void test() throws Exception {
for (String data : new String[] { "fanfan", "la tulipe",
"1234567890", "12345678901234567890", "1", "" }) {
String result = StringUtils.padString(data, -1);
assertEquals("A size of -1 is expected to produce a noop",
true, data.equals(result));
for (int size : new Integer[] { 0, 1, 5, 10, 40 }) {
result = StringUtils.padString(data, size);
assertEquals(
"Padding a String at a certain size should give a String of the given size",
size, result.length());
assertEquals(
"Padding a String should not change the content",
true, data.trim().startsWith(result.trim()));
result = StringUtils.padString(data, size, false, null);
assertEquals(
"Padding a String without cutting should not shorten the String",
true, data.length() <= result.length());
assertEquals(
"Padding a String without cutting should keep the whole content",
true, data.trim().equals(result.trim()));
result = StringUtils.padString(data, size, false,
Alignment.RIGHT);
if (size > data.length()) {
assertEquals(
"Padding a String to the end should work as expected",
true, result.endsWith(data));
}
result = StringUtils.padString(data, size, false,
Alignment.JUSTIFY);
if (size > data.length()) {
String unspacedData = data.trim();
String unspacedResult = result.trim();
for (int i = 0; i < size; i++) {
unspacedData = unspacedData.replace(" ", " ");
unspacedResult = unspacedResult.replace(" ",
" ");
}
assertEquals(
"Justified text trimmed with all spaces collapsed "
+ "sould be identical to original text "
+ "trimmed with all spaces collapsed",
unspacedData, unspacedResult);
}
result = StringUtils.padString(data, size, false,
Alignment.CENTER);
if (size > data.length()) {
int before = 0;
for (int i = 0; i < result.length()
&& result.charAt(i) == ' '; i++) {
before++;
}
int after = 0;
for (int i = result.length() - 1; i >= 0
&& result.charAt(i) == ' '; i--) {
after++;
}
if (result.trim().isEmpty()) {
after = before / 2;
if (before > (2 * after)) {
before = after + 1;
} else {
before = after;
}
}
assertEquals(
"Padding a String on center should work as expected",
result.length(), before + data.length()
+ after);
assertEquals(
"Padding a String on center should not uncenter the content",
true, Math.abs(before - after) <= 1);
}
}
}
}
});
addTest(new TestCase("Justifying") {
@Override
public void test() throws Exception {
Map<String, Map<Integer, Entry<Alignment, List<String>>>> source = new HashMap<String, Map<Integer, Entry<Alignment, List<String>>>>();
addValue(source, Alignment.LEFT, "testy", -1, "testy");
addValue(source, Alignment.RIGHT, "testy", -1, "testy");
addValue(source, Alignment.CENTER, "testy", -1, "testy");
addValue(source, Alignment.JUSTIFY, "testy", -1, "testy");
addValue(source, Alignment.LEFT, "testy", 5, "testy");
addValue(source, Alignment.LEFT, "testy", 3, "te-", "sty");
addValue(source, Alignment.LEFT,
"Un petit texte qui se mettra sur plusieurs lignes",
10, "Un petit", "texte qui", "se mettra", "sur",
"plusieurs", "lignes");
addValue(source, Alignment.LEFT,
"Un petit texte qui se mettra sur plusieurs lignes", 7,
"Un", "petit", "texte", "qui se", "mettra", "sur",
"plusie-", "urs", "lignes");
addValue(source, Alignment.RIGHT,
"Un petit texte qui se mettra sur plusieurs lignes", 7,
" Un", " petit", " texte", " qui se", " mettra",
" sur", "plusie-", " urs", " lignes");
addValue(source, Alignment.CENTER,
"Un petit texte qui se mettra sur plusieurs lignes", 7,
" Un ", " petit ", " texte ", "qui se ", "mettra ",
" sur ", "plusie-", " urs ", "lignes ");
addValue(source, Alignment.JUSTIFY,
"Un petit texte qui se mettra sur plusieurs lignes", 7,
"Un pet-", "it tex-", "te qui", "se met-", "tra sur",
"plusie-", "urs li-", "gnes");
addValue(source, Alignment.JUSTIFY,
"Un petit texte qui se mettra sur plusieurs lignes",
14, "Un petit", "texte qui se",
"mettra sur", "plusieurs lig-", "nes");
addValue(source, Alignment.JUSTIFY, "le dash-test", 9,
"le dash-", "test");
for (String data : source.keySet()) {
for (int size : source.get(data).keySet()) {
Alignment align = source.get(data).get(size).getKey();
List<String> values = source.get(data).get(size)
.getValue();
List<String> result = StringUtils.justifyText(data,
size, align);
// System.out.println("[" + data + " (" + size + ")" +
// "] -> [");
// for (int i = 0; i < result.size(); i++) {
// String resultLine = result.get(i);
// System.out.println(i + ": " + resultLine);
// }
// System.out.println("]");
assertEquals(values, result);
}
}
}
});
addTest(new TestCase("unhtml") {
@Override
public void test() throws Exception {
Map<String, String> data = new HashMap<String, String>();
data.put("aa", "aa");
data.put("test with spaces ", "test with spaces ");
data.put("<a href='truc://target/'>link</a>", "link");
data.put("<html>Digimon</html>", "Digimon");
data.put("", "");
data.put(" ", " ");
for (Entry<String, String> entry : data.entrySet()) {
String result = StringUtils.unhtml(entry.getKey());
assertEquals("Result is not what we expected",
entry.getValue(), result);
}
}
});
addTest(new TestCase("zip64") {
@Override
public void test() throws Exception {
String orig = "test";
String zipped = StringUtils.zip64(orig);
String unzipped = StringUtils.unzip64s(zipped);
assertEquals(orig, unzipped);
}
});
addTest(new TestCase("format/toNumber simple") {
@Override
public void test() throws Exception {
assertEquals(263l, StringUtils.toNumber("263"));
assertEquals(21200l, StringUtils.toNumber("21200"));
assertEquals(0l, StringUtils.toNumber("0"));
assertEquals("263", StringUtils.formatNumber(263l));
assertEquals("21 k", StringUtils.formatNumber(21000l));
assertEquals("0", StringUtils.formatNumber(0l));
}
});
addTest(new TestCase("format/toNumber not 000") {
@Override
public void test() throws Exception {
assertEquals(263200l, StringUtils.toNumber("263.2 k"));
assertEquals(42000l, StringUtils.toNumber("42.0 k"));
assertEquals(12000000l, StringUtils.toNumber("12 M"));
assertEquals(2000000000l, StringUtils.toNumber("2 G"));
assertEquals("263 k", StringUtils.formatNumber(263012l));
assertEquals("42 k", StringUtils.formatNumber(42012l));
assertEquals("12 M", StringUtils.formatNumber(12012121l));
assertEquals("7 G", StringUtils.formatNumber(7364635928l));
}
});
addTest(new TestCase("format/toNumber decimals") {
@Override
public void test() throws Exception {
assertEquals(263200l, StringUtils.toNumber("263.2 k"));
assertEquals(1200l, StringUtils.toNumber("1.2 k"));
assertEquals(42700000l, StringUtils.toNumber("42.7 M"));
assertEquals(1220l, StringUtils.toNumber("1.22 k"));
assertEquals(1432l, StringUtils.toNumber("1.432 k"));
assertEquals(6938l, StringUtils.toNumber("6.938 k"));
assertEquals("1.3 k", StringUtils.formatNumber(1300l, 1));
assertEquals("263.2020 k", StringUtils.formatNumber(263202l, 4));
assertEquals("1.26 k", StringUtils.formatNumber(1267l, 2));
assertEquals("42.7 M", StringUtils.formatNumber(42712121l, 1));
assertEquals("5.09 G", StringUtils.formatNumber(5094837485l, 2));
}
});
}
static private void addValue(
Map<String, Map<Integer, Entry<Alignment, List<String>>>> source,
final Alignment align, String input, int size,
final String... result) {
if (!source.containsKey(input)) {
source.put(input,
new HashMap<Integer, Entry<Alignment, List<String>>>());
}
source.get(input).put(size, new Entry<Alignment, List<String>>() {
@Override
public Alignment getKey() {
return align;
}
@Override
public List<String> getValue() {
return Arrays.asList(result);
}
@Override
public List<String> setValue(List<String> value) {
return null;
}
});
}
}
| gpl-3.0 |
austindlawless/dotCMS | src/com/liferay/util/dao/hibernate/DSConnectionProvider.java | 2530 | /**
* Copyright (c) 2000-2005 Liferay, LLC. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.liferay.util.dao.hibernate;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import com.dotcms.repackage.hibernate2.net.sf.hibernate.HibernateException;
import com.dotcms.repackage.hibernate2.net.sf.hibernate.connection.ConnectionProvider;
import com.dotmarketing.db.DbConnectionFactory;
/**
* <a href="DSConnectionProvider.java.html"><b><i>View Source</i></b></a>
*
* @author Brian Wing Shun Chan
* @version $Revision: 1.5 $
*
*/
public class DSConnectionProvider implements ConnectionProvider {
public void configure(Properties props) throws HibernateException {
try {
_ds = DbConnectionFactory.getDataSource();
}
catch (Exception e) {
throw new HibernateException(e.getMessage());
}
}
public Connection getConnection() throws SQLException {
//This forces liferay to use our connection manager
return DbConnectionFactory.getConnection();
}
public void closeConnection(Connection con) throws SQLException {
//This condition is set to avoid closing connection when in middle of a transaction
if(con != null && con.getAutoCommit())
DbConnectionFactory.closeConnection();
}
public boolean isStatementCache() {
return false;
}
public void close() {
}
private DataSource _ds;
} | gpl-3.0 |
nikiroo/fanfix | src/be/nikiroo/utils/streams/NextableInputStream.java | 7444 | package be.nikiroo.utils.streams;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
/**
* This {@link InputStream} can be separated into sub-streams (you can process
* it as a normal {@link InputStream} but, when it is spent, you can call
* {@link NextableInputStream#next()} on it to unlock new data).
* <p>
* The separation in sub-streams is done via {@link NextableInputStreamStep}.
*
* @author niki
*/
public class NextableInputStream extends BufferedInputStream {
private NextableInputStreamStep step;
private boolean started;
private boolean stopped;
/**
* Create a new {@link NextableInputStream} that wraps the given
* {@link InputStream}.
*
* @param in
* the {@link InputStream} to wrap
* @param step
* how to separate it into sub-streams (can be NULL, but in that
* case it will behave as a normal {@link InputStream})
*/
public NextableInputStream(InputStream in, NextableInputStreamStep step) {
super(in);
this.step = step;
}
/**
* Create a new {@link NextableInputStream} that wraps the given bytes array
* as a data source.
*
* @param in
* the array to wrap, cannot be NULL
* @param step
* how to separate it into sub-streams (can be NULL, but in that
* case it will behave as a normal {@link InputStream})
*/
public NextableInputStream(byte[] in, NextableInputStreamStep step) {
this(in, step, 0, in.length);
}
/**
* Create a new {@link NextableInputStream} that wraps the given bytes array
* as a data source.
*
* @param in
* the array to wrap, cannot be NULL
* @param step
* how to separate it into sub-streams (can be NULL, but in that
* case it will behave as a normal {@link InputStream})
* @param offset
* the offset to start the reading at
* @param length
* the number of bytes to take into account in the array,
* starting from the offset
*
* @throws NullPointerException
* if the array is NULL
* @throws IndexOutOfBoundsException
* if the offset and length do not correspond to the given array
*/
public NextableInputStream(byte[] in, NextableInputStreamStep step,
int offset, int length) {
super(in, offset, length);
this.step = step;
checkBuffer(true);
}
/**
* Unblock the processing of the next sub-stream.
* <p>
* It can only be called when the "current" stream is spent (i.e., you must
* first process the stream until it is spent).
* <p>
* {@link IOException}s can happen when we have no data available in the
* buffer; in that case, we fetch more data to know if we can have a next
* sub-stream or not.
* <p>
* This is can be a blocking call when data need to be fetched.
*
* @return TRUE if we unblocked the next sub-stream, FALSE if not (i.e.,
* FALSE when there are no more sub-streams to fetch)
*
* @throws IOException
* in case of I/O error or if the stream is closed
*/
public boolean next() throws IOException {
return next(false);
}
/**
* Unblock the next sub-stream as would have done
* {@link NextableInputStream#next()}, but disable the sub-stream systems.
* <p>
* That is, the next stream, if any, will be the last one and will not be
* subject to the {@link NextableInputStreamStep}.
* <p>
* This is can be a blocking call when data need to be fetched.
*
* @return TRUE if we unblocked the next sub-stream, FALSE if not
*
* @throws IOException
* in case of I/O error or if the stream is closed
*/
public boolean nextAll() throws IOException {
return next(true);
}
/**
* Check if this stream is totally spent (no more data to read or to
* process).
* <p>
* Note: when the stream is divided into sub-streams, each sub-stream will
* report its own eof when spent.
*
* @return TRUE if it is
*
* @throws IOException
* in case of I/O error
*/
@Override
public boolean eof() throws IOException {
return super.eof();
}
/**
* Check if we still have some data in the buffer and, if not, fetch some.
*
* @return TRUE if we fetched some data, FALSE if there are still some in
* the buffer
*
* @throws IOException
* in case of I/O error
*/
@Override
protected boolean preRead() throws IOException {
if (!stopped) {
boolean bufferChanged = super.preRead();
checkBuffer(bufferChanged);
return bufferChanged;
}
if (start >= stop) {
eof = true;
}
return false;
}
@Override
protected boolean hasMoreData() {
return started && super.hasMoreData();
}
/**
* Check that the buffer didn't overshot to the next item, and fix
* {@link NextableInputStream#stop} if needed.
* <p>
* If {@link NextableInputStream#stop} is fixed,
* {@link NextableInputStream#eof} and {@link NextableInputStream#stopped}
* are set to TRUE.
*
* @param newBuffer
* we changed the buffer, we need to clear some information in
* the {@link NextableInputStreamStep}
*/
private void checkBuffer(boolean newBuffer) {
if (step != null && stop >= 0) {
if (newBuffer) {
step.clearBuffer();
}
int stopAt = step.stop(buffer, start, stop, eof);
if (stopAt >= 0) {
stop = stopAt;
eof = true;
stopped = true;
}
}
}
/**
* The implementation of {@link NextableInputStream#next()} and
* {@link NextableInputStream#nextAll()}.
* <p>
* This is can be a blocking call when data need to be fetched.
*
* @param all
* TRUE for {@link NextableInputStream#nextAll()}, FALSE for
* {@link NextableInputStream#next()}
*
* @return TRUE if we unblocked the next sub-stream, FALSE if not (i.e.,
* FALSE when there are no more sub-streams to fetch)
*
* @throws IOException
* in case of I/O error or if the stream is closed
*/
private boolean next(boolean all) throws IOException {
checkClose();
if (!started) {
// First call before being allowed to read
started = true;
if (all) {
step = null;
}
return true;
}
// If started, must be stopped and no more data to continue
// i.e., sub-stream must be spent
if (!stopped || hasMoreData()) {
return false;
}
if (step != null) {
stop = step.getResumeLen();
start += step.getResumeSkip();
eof = step.getResumeEof();
stopped = false;
if (all) {
step = null;
}
checkBuffer(false);
return true;
}
return false;
// // consider that if EOF, there is no next
// if (start >= stop) {
// // Make sure, block if necessary
// preRead();
//
// return hasMoreData();
// }
//
// return true;
}
/**
* Display a DEBUG {@link String} representation of this object.
* <p>
* Do <b>not</b> use for release code.
*/
@Override
public String toString() {
String data = "";
if (stop > 0) {
try {
data = new String(Arrays.copyOfRange(buffer, 0, stop), "UTF-8");
} catch (UnsupportedEncodingException e) {
}
if (data.length() > 200) {
data = data.substring(0, 197) + "...";
}
}
String rep = String.format(
"Nextable %s: %d -> %d [eof: %s] [more data: %s]: %s",
(stopped ? "stopped" : "running"), start, stop, "" + eof, ""
+ hasMoreData(), data);
return rep;
}
}
| gpl-3.0 |
danielyc/MoleculeCraft-1.7.10 | src/main/java/com/daniel_yc/moleculecraft/blocks/tileentity/TileEntityCompressor.java | 8818 | package com.daniel_yc.moleculecraft.blocks.tileentity;
import com.daniel_yc.moleculecraft.blocks.Compressor;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
public class TileEntityCompressor extends TileEntity implements ISidedInventory{
private static final int[] slotsTop = new int[] { 0 };
private static final int[] slotsBottom = new int[] { 2, 1 };
private static final int[] slotsSides = new int[] { 1 };
private ItemStack[] compressorItemStacks = new ItemStack[3];
public int compressorBurnTime;
public int currentBurnTime;
public int compressorCookTime;
private String compressorName;
public void compressorName(String string){
this.compressorName = string;
}
@Override
public int getSizeInventory() {
return this.compressorItemStacks.length;
}
@Override
public ItemStack getStackInSlot(int slot) {
return this.compressorItemStacks[slot];
}
@Override
public ItemStack decrStackSize(int par1, int par2) {
if(this.compressorItemStacks[par1] != null){
ItemStack itemstack;
if(this.compressorItemStacks[par1].stackSize <= par2){
itemstack = this.compressorItemStacks[par1];
this.compressorItemStacks[par1] = null;
return itemstack;
}else{
itemstack = this.compressorItemStacks[par1].splitStack(par2);
if(this.compressorItemStacks[par1].stackSize == 0){
this.compressorItemStacks[par1] = null;
}
return itemstack;
}
}else{
return null;
}
}
@Override
public ItemStack getStackInSlotOnClosing(int slot) {
if(this.compressorItemStacks[slot] != null){
ItemStack itemstack = this.compressorItemStacks[slot];
this.compressorItemStacks[slot] = null;
return itemstack;
}else{
return null;
}
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemstack) {
this.compressorItemStacks[slot] = itemstack;
if(itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()){
itemstack.stackSize = this.getInventoryStackLimit();
}
}
@Override
public String getInventoryName() {
return this.hasCustomInventoryName() ? this.compressorName : "Compressor";
}
@Override
public boolean hasCustomInventoryName() {
return this.compressorName != null && this.compressorName.length() > 0;
}
@Override
public int getInventoryStackLimit() {
return 64;
}
public void readFromNBT(NBTTagCompound tagCompound){
super.readFromNBT(tagCompound);
NBTTagList tagList = tagCompound.getTagList("Items", 10);
this.compressorItemStacks = new ItemStack[this.getSizeInventory()];
for (int i = 0; i < tagList.tagCount(); ++i){
NBTTagCompound tabCompound1 = tagList.getCompoundTagAt(i);
byte byte0 = tabCompound1.getByte("slot");
if(byte0 >= 0 && byte0 < this.compressorItemStacks.length){
this.compressorItemStacks[byte0] = ItemStack.loadItemStackFromNBT(tabCompound1);
}
}
this.compressorBurnTime = tagCompound.getShort("BurnTime");
this.compressorCookTime = tagCompound.getShort("CookTime");
this.currentBurnTime = getItemBurnTime(this.compressorItemStacks[1]);
if(tagCompound.hasKey("CustumName", 8)){
this.compressorName = tagCompound.getString("CustomName");
}
}
public void writeToNBT(NBTTagCompound tagCompound){
super.writeToNBT(tagCompound);
tagCompound.setShort("BurnTime", (short) this.compressorBurnTime);
tagCompound.setShort("CookTime", (short) this.compressorBurnTime);
NBTTagList tagList = new NBTTagList();
for(int i = 0; i < this.compressorItemStacks.length; ++i){
if(this.compressorItemStacks[1] != null){
NBTTagCompound tagCompound1 = new NBTTagCompound();
tagCompound1.setByte("slot", (byte) i);
this.compressorItemStacks[1].writeToNBT(tagCompound1);
tagList.appendTag(tagCompound1);
}
}
tagCompound.setTag("Items", tagList);
if(this.hasCustomInventoryName()){
tagCompound.setString("CustomName", this.compressorName);
}
}
@SideOnly(Side.CLIENT)
public int getCookProgressScaled(int par1){
return this.compressorCookTime * par1 / 200;
}
@SideOnly(Side.CLIENT)
public int getBurnTimeRemainingScaled(int par1){
if(this.currentBurnTime == 0){
this.currentBurnTime = 200;
}
return this.compressorBurnTime * par1 / this.currentBurnTime;
}
public boolean isWorking(){
return this.compressorBurnTime > 0;
}
public void updateEntity(){
boolean flag = this.compressorBurnTime > 0;
boolean flag1 = false;
if(this.compressorBurnTime > 0){
--this.compressorBurnTime;
}
if(!this.worldObj.isRemote){
if(this.compressorBurnTime == 0 && this.canSmelt()){
this.currentBurnTime = this.compressorBurnTime = getItemBurnTime(this.compressorItemStacks[1]);
if(this.compressorBurnTime > 0){
flag1 = true;
if(this.compressorItemStacks[1] != null){
--this.compressorItemStacks[1].stackSize;
if(this.compressorItemStacks[1].stackSize == 0){
this.compressorItemStacks[1] = compressorItemStacks[1].getItem().getContainerItem(this.compressorItemStacks[1]);
}
}
}
}
if(this.isWorking() && this.canSmelt()){
++this.compressorCookTime;
if(this.compressorCookTime == 200){
this.compressorCookTime = 0;
this.smeltItem();
flag1 = true;
}
}else{
this.compressorCookTime = 0;
}
}
if(flag1 != this.compressorBurnTime > 0){
flag1 = true;
Compressor.updateBlockState(this.compressorBurnTime > 0, this.worldObj, this.xCoord, this.yCoord, this.zCoord);
}
if (flag1){
this.markDirty();
}
}
private boolean canSmelt(){
if(this.compressorItemStacks[0] == null){
return false;
}else{
ItemStack itemstack = FurnaceRecipes.smelting().getSmeltingResult(this.compressorItemStacks[0]);
if(itemstack == null) return false;
if(this.compressorItemStacks[2] == null) return true;
if(!this.compressorItemStacks[2].isItemEqual(itemstack)) return false;
int result = compressorItemStacks[2].stackSize + itemstack.stackSize;
return result <= getInventoryStackLimit() && result <= this.compressorItemStacks[2].getMaxStackSize();
}
}
public void smeltItem(){
if(this.canSmelt()){
ItemStack itemstack = FurnaceRecipes.smelting().getSmeltingResult(this.compressorItemStacks[0]);
if(this.compressorItemStacks[2] == null){
this.compressorItemStacks[2].copy();
}else if(this.compressorItemStacks[2].getItem() == itemstack.getItem()){
this.compressorItemStacks[2].stackSize += itemstack.stackSize;
}
}
}
public static int getItemBurnTime(ItemStack itemstack){
if(itemstack == null){
return 0;
}else{
Item item = itemstack.getItem();
if(item instanceof ItemBlock && Block.getBlockFromItem(item) != Blocks.air){
Block block = Block.getBlockFromItem(item);
if(block == Blocks.coal_block){
return 1600;
}
if(block.getMaterial() == Material.wood){
return 300;
}
}
if(item == Items.coal) return 600;
if(item instanceof ItemTool && ((ItemTool) item).getToolMaterialName().equals("WOOD")) return 300;
return GameRegistry.getFuelValue(itemstack);
}
}
public static boolean isItemFuel(ItemStack itemstack){
return getItemBurnTime(itemstack) > 0;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord) != this ? false : player.getDistanceSq((double) this.xCoord + 0.5D, (double) this.yCoord + 0.5D, (double) this.zCoord + 0.5D) <= 64.0D;
}
@Override
public void openInventory() {
}
@Override
public void closeInventory() {
}
@Override
public boolean isItemValidForSlot(int par1, ItemStack itemstack) {
return par1 == 2 ? false : (par1 == 1 ? isItemFuel(itemstack) : true);
}
@Override
public int[] getAccessibleSlotsFromSide(int par1) {
return par1 == 0 ? slotsBottom : (par1 == 1 ? slotsTop : slotsSides);
}
@Override
public boolean canInsertItem(int par1, ItemStack itemstack, int par3) {
return this.isItemValidForSlot(par1, itemstack);
}
@Override
public boolean canExtractItem(int par1, ItemStack itemstack, int par3) {
return par3 != 0 || par1 != 1 || itemstack.getItem() == Items.bucket;
}
}
| gpl-3.0 |
fabiopetroni/CrawlFacebookPostTrees | src/facebook/Autenticate.java | 1986 | // Copyright (C) 2015 Fabio Petroni
// Contact: http://www.fabiopetroni.com
//
// This file is part of CrawlFacebookPostTrees application.
//
// CrawlFacebookPostTrees 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.
//
// CrawlFacebookPostTrees 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 CrawlFacebookPostTrees. If not, see <http://www.gnu.org/licenses/>.
//
// If you use CrawlFacebookPostTrees please cite the following paper:
// - Alessandro Bessi, Fabio Petroni, Michela Del Vicario, Fabiana Zollo,
// Aris Anagnostopoulos, Antonio Scala, Guido Caldarelli, Walter Quattrociocchi:
// Viral Misinformation: The Role of Homophily and Polarization. In Proceedings
// of the 24th International Conference on World Wide Web Companion (WWW), 2015.
package facebook;
import application.Globals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class Autenticate {
public static void perform(WebDriver driver, String email, String password){
driver.get(Globals.START_PAGE);
WebElement email_element = driver.findElement(By.xpath("//*[@id='email']"));
email_element.sendKeys(email);
WebElement password_element = driver.findElement(By.xpath("//*[@id='pass']"));
password_element.sendKeys(password);
WebElement click_element = driver.findElement(By.xpath("//*[@type='submit']"));
click_element.click();
return;
}
}
| gpl-3.0 |
iCarto/siga | extGeoreferencing/src/org/gvsig/georeferencing/process/GeoreferencingProcess.java | 13937 | /* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2006 Instituto de Desarrollo Regional and Generalitat Valenciana.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibañez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* gvsig@gva.es
* www.gvsig.gva.es
*
* or
*
* Instituto de Desarrollo Regional (Universidad de Castilla La-Mancha)
* Campus Universitario s/n
* 02071 Alabacete
* Spain
*
* +34 967 599 200
*/
package org.gvsig.georeferencing.process;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
import org.gvsig.georeferencing.process.geotransform.GeoTransformProcess;
import org.gvsig.raster.IProcessActions;
import org.gvsig.raster.RasterProcess;
import org.gvsig.raster.buffer.BufferFactory;
import org.gvsig.raster.buffer.RasterBuffer;
import org.gvsig.raster.buffer.RasterBufferInvalidAccessException;
import org.gvsig.raster.buffer.RasterBufferInvalidException;
import org.gvsig.raster.buffer.WriterBufferServer;
import org.gvsig.raster.dataset.GeoRasterWriter;
import org.gvsig.raster.dataset.IBuffer;
import org.gvsig.raster.dataset.IRasterDataSource;
import org.gvsig.raster.dataset.NotSupportedExtensionException;
import org.gvsig.raster.dataset.io.RasterDriverException;
import org.gvsig.raster.datastruct.GeoPointList;
import org.gvsig.raster.grid.Grid;
import org.gvsig.raster.grid.GridExtent;
import org.gvsig.raster.grid.GridInterpolated;
import org.gvsig.raster.grid.OutOfGridException;
import org.gvsig.raster.process.RasterTask;
import org.gvsig.raster.process.RasterTaskQueue;
import org.gvsig.raster.util.RasterToolsUtil;
import com.iver.andami.PluginServices;
/**
* Clase que representa una proceso de georreferenciacion de un raster.
*
* @author Alejandro Muñoz Sanchez (alejandro.munoz@uclm.es)
* @version 10/2/2008
**/
public class GeoreferencingProcess extends RasterProcess implements IProcessActions{
//Capa a georreferenciar
private FLyrRasterSE rasterSE = null;
//Grid resultante de georreferenciacion
private Grid imageGrid = null;
//Fichero de salida
private String filename = null;
// Lista puntos de control
private GeoPointList gpcs = null;
//Extend de imagen corregida
GridExtent newExtend = null;
// Metodo de resampleado utilizado
private int rMethod = 0;
//Indicador de progreso
private int percent = 0;
// Grid resultado
private Grid gridResult = null;
WriterBufferServer writerBufferServer = null;
private int orden = 0;
private int[] bands = null;
//Tamaño de celda en X si es pasada por el usuario
private double xCellSize = 0;
//Tamaño de celda en Y si es pasada por el usuario
private double yCellSize = 0;
/** Metodo que recoge los parametros del proceso georreferenciacion de un raster
* <LI>rasterSE: capa a georeferenciar</LI>
* <LI>filename: path con el fichero de salida</LI>
* <LI>method: metodo de resampleo </LI>
*/
public void init() {
rasterSE = (FLyrRasterSE)getParam("fLayer");
filename = (String)getParam("filename");
rMethod = (int)getIntParam("method");
gpcs = (GeoPointList) getParam("gpcs");
orden= (int)getIntParam("orden");
bands = new int[rasterSE.getBandCount()];
xCellSize = (double)getDoubleParam("xCellSize");
yCellSize = (double)getDoubleParam("yCellSize");
for(int i=0; i<rasterSE.getBandCount(); i++)
bands[i]= i;
// Inicializacion del grid correspondiente a la imagen a corregir
IRasterDataSource dsetCopy = null;
dsetCopy = rasterSE.getDataSource().newDataset();
BufferFactory bufferFactory = new BufferFactory(dsetCopy);
bufferFactory.setReadOnly(true);
try {
imageGrid = new Grid(bufferFactory);
}catch (RasterBufferInvalidException e) {
e.printStackTrace();
}
}
public void process() throws InterruptedException {
RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
GeoTransformProcess transform = new GeoTransformProcess();
transform.setActions(this);
transform.addParam("gpcs", gpcs);
transform.addParam("orden",new Integer(orden));
transform.run();
// Obtenida la transformacion la aplicamos a los puntos extremos de la imagen
double p1[]=transform.getCoordMap(0,0);
double p2[]=transform.getCoordMap(rasterSE.getPxWidth(),0);
double p3[]=transform.getCoordMap(0,rasterSE.getPxHeight());
double p4[]=transform.getCoordMap(rasterSE.getPxWidth(),rasterSE.getPxHeight());
double xmin=Math.min(p1[0],p3[0]);
double ymin=Math.min(p3[1],p4[1]);
double xmax=Math.max(p2[0],p4[0]);
double ymax=Math.max(p1[1],p2[1]);
if(xCellSize <= 1)
xCellSize = (xmax - xmin) / (double)rasterSE.getPxWidth();
if(yCellSize <= 1)
yCellSize = (ymax - ymin) / (double)rasterSE.getPxHeight();
newExtend= new GridExtent(xmin, ymin, xmax, ymax, xCellSize);
int datatype= rasterSE.getBufferFactory().getRasterBuf().getDataType();
try {
gridResult = new Grid(newExtend, newExtend, datatype, bands);
} catch (RasterBufferInvalidException e) {
RasterToolsUtil.messageBoxError("error_grid", this, e);
}
double minPointX=gridResult.getGridExtent().getMin().getX();
double maxPointY=gridResult.getGridExtent().getMax().getY();
double cellsize=gridResult.getCellSize();
GridInterpolated gridInterpolated=null;
gridInterpolated = new GridInterpolated((RasterBuffer)imageGrid.getRasterBuf(),imageGrid.getGridExtent(),imageGrid.getGridExtent(),bands);
// SE ESTABLECE EL METODO DE INTERPOLACION (por defecto vecino mas proximo)
if(rMethod==GridInterpolated.INTERPOLATION_BicubicSpline)
gridInterpolated.setInterpolationMethod(GridInterpolated.INTERPOLATION_BicubicSpline);
else if(rMethod==GridInterpolated.INTERPOLATION_Bilinear)
gridInterpolated.setInterpolationMethod(GridInterpolated.INTERPOLATION_Bilinear);
else
gridInterpolated.setInterpolationMethod(GridInterpolated.INTERPOLATION_NearestNeighbour);
double coord[] = null;
try {
if(datatype==IBuffer.TYPE_BYTE) {
byte values[]=new byte[bands.length];
int progress=0;
// OPTIMIZACION. Se esta recorriendo secuencialmente cada banda.
for(int band = 0; band < bands.length; band++) {
gridResult.setBandToOperate(band);
gridInterpolated.setBandToOperate(band);
for(int row = 0; row < gridResult.getLayerNY(); row++) {
progress++;
for(int col = 0; col < gridResult.getLayerNX(); col++) {
coord = transform.getCoordPixel(col * cellsize+minPointX, maxPointY - row * cellsize);
values[band] = (byte)gridInterpolated._getValueAt(coord[0], coord[1]);
gridResult.setCellValue(col,row,(byte)values[band]);
}
percent=(int)(progress * 100 / (gridResult.getLayerNY() * bands.length));
if(task.getEvent() != null)
task.manageEvent(task.getEvent());
}
}
}
if(datatype==IBuffer.TYPE_SHORT) {
short values[] = new short[bands.length];
int progress = 0;
// OPTIMIZACION. Se esta recorriendo secuencialmente cada banda.
for(int band = 0; band < bands.length; band++) {
gridResult.setBandToOperate(band);
gridInterpolated.setBandToOperate(band);
for(int row = 0; row < gridResult.getLayerNY(); row++) {
progress++;
for(int col = 0; col < gridResult.getLayerNX(); col++) {
coord=transform.getCoordPixel(col * cellsize+minPointX, maxPointY - row * cellsize);
values[band] = (short)gridInterpolated._getValueAt(coord[0], coord[1]);
gridResult.setCellValue(col, row, (short)values[band]);
}
percent=(int)(progress * 100 / (gridResult.getLayerNY() * bands.length));
if(task.getEvent() != null)
task.manageEvent(task.getEvent());
}
}
}
if(datatype == IBuffer.TYPE_INT)
{
int values[] = new int[bands.length];
int progress = 0;
// OPTIMIZACION. Se esta recorriendo secuencialmente cada banda.
for(int band = 0; band < bands.length; band++) {
gridResult.setBandToOperate(band);
gridInterpolated.setBandToOperate(band);
for(int row = 0; row < gridResult.getLayerNY(); row++){
progress++;
for(int col = 0; col < gridResult.getLayerNX(); col++) {
coord = transform.getCoordPixel(col * cellsize + minPointX, maxPointY - row * cellsize);
values[band] = (int)gridInterpolated._getValueAt(coord[0], coord[1]);
gridResult.setCellValue(col, row, (int)values[band]);
}
percent=(int)( progress*100/(gridResult.getLayerNY()*bands.length));
if(task.getEvent() != null)
task.manageEvent(task.getEvent());
}
}
}
if(datatype == IBuffer.TYPE_FLOAT) {
float values[] = new float[bands.length];
int progress = 0;
// OPTIMIZACION. Se esta recorriendo secuencialmente cada banda.
for(int band = 0; band < bands.length; band++) {
gridResult.setBandToOperate(band);
gridInterpolated.setBandToOperate(band);
for(int row = 0; row < gridResult.getLayerNY(); row++) {
progress++;
for(int col = 0; col < gridResult.getLayerNX(); col++) {
coord = transform.getCoordPixel(col * cellsize + minPointX, maxPointY - row * cellsize);
values[band] = (float)gridInterpolated._getValueAt(coord[0], coord[1]);
gridResult.setCellValue(col, row, (float)values[band]);
}
percent=(int)(progress * 100 / (gridResult.getLayerNY() * bands.length));
if(task.getEvent() != null)
task.manageEvent(task.getEvent());
}
}
}
if(datatype == IBuffer.TYPE_DOUBLE) {
double values[] = new double[bands.length];
int progress = 0;
// OPTIMIZACION. Se esta recorriendo secuencialmente cada banda.
for(int band = 0; band < bands.length; band++) {
gridResult.setBandToOperate(band);
gridInterpolated.setBandToOperate(band);
for(int row = 0; row < gridResult.getLayerNY(); row++) {
progress++;
for(int col = 0; col < gridResult.getLayerNX(); col++) {
coord = transform.getCoordPixel(col * cellsize + minPointX, maxPointY - row * cellsize);
values[band] = (double)gridInterpolated._getValueAt(coord[0], coord[1]);
gridResult.setCellValue(col, row, (double)values[band]);
}
percent=(int)( progress * 100 / (gridResult.getLayerNY() * bands.length));
if(task.getEvent() != null)
task.manageEvent(task.getEvent());
}
}
}
} catch (OutOfGridException e) {
e.printStackTrace();
} catch (RasterBufferInvalidAccessException e) {
e.printStackTrace();
} catch (RasterBufferInvalidException e) {
e.printStackTrace();
}
generateLayer();
if(externalActions!=null)
externalActions.end(filename);
}
private void generateLayer(){
GeoRasterWriter grw = null;
IBuffer buffer= gridResult.getRasterBuf();
writerBufferServer = new WriterBufferServer(buffer);
AffineTransform aTransform = new AffineTransform(newExtend.getCellSize(),0.0,0.0,-newExtend.getCellSize(),newExtend.getMin().getX(),newExtend.getMax().getY());
int endIndex =filename.lastIndexOf(".");
if (endIndex < 0)
endIndex = filename.length();
try {
grw = GeoRasterWriter.getWriter(writerBufferServer, filename,gridResult.getRasterBuf().getBandCount(),aTransform, gridResult.getRasterBuf().getWidth(),gridResult.getRasterBuf().getHeight(), gridResult.getRasterBuf().getDataType(), GeoRasterWriter.getWriter(filename).getParams(),null);
grw.dataWrite();
grw.setWkt(rasterSE.getWktProjection());
grw.writeClose();
} catch (NotSupportedExtensionException e1) {
RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer_notsupportedextension"), this, e1);
} catch (RasterDriverException e1) {
RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e1);
} catch (IOException e) {
RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/*
* (non-Javadoc)
* @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
*/
public String getTitle() {
return PluginServices.getText(this,"georreferenciacion_process");
}
/*
* (non-Javadoc)
* @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLabel()
*/
public int getPercent() {
if(writerBufferServer==null)
return percent;
else
return writerBufferServer.getPercent();
}
/*
* (non-Javadoc)
* @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLabel()
*/
public String getLog() {
return PluginServices.getText(this,"georreferencing_log_message");
}
public void interrupted() {
// TODO Auto-generated method stub
}
public void end(Object param) {
}
}
| gpl-3.0 |
zuonima/sql-utils | src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/expr/OracleSizeExpr.java | 1888 | /*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* 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.alibaba.druid.sql.dialect.oracle.ast.expr;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.dialect.oracle.ast.OracleSQLObjectImpl;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleASTVisitor;
public class OracleSizeExpr extends OracleSQLObjectImpl implements OracleExpr {
private SQLExpr value;
private Unit unit;
public OracleSizeExpr(){
}
public OracleSizeExpr(SQLExpr value, Unit unit){
super();
this.value = value;
this.unit = unit;
}
@Override
public void accept0(OracleASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, value);
}
visitor.endVisit(this);
}
public SQLExpr getValue() {
return value;
}
public void setValue(SQLExpr value) {
this.value = value;
}
public Unit getUnit() {
return unit;
}
public void setUnit(Unit unit) {
this.unit = unit;
}
public static enum Unit {
K, M, G, T, P, E
}
public OracleSizeExpr clone() {
OracleSizeExpr x = new OracleSizeExpr();
if (value != null) {
x.setValue(value.clone());
}
x.unit = unit;
return x;
}
}
| gpl-3.0 |
icgc-dcc/dcc-storage | score-client/src/main/java/bio/overture/score/client/util/CsvParser.java | 700 | package bio.overture.score.client.util;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.val;
import java.io.File;
import java.util.List;
@RequiredArgsConstructor
public class CsvParser<T> {
private final Class<T> type;
private final Character columnSep;
@SneakyThrows
public List<T> parseFile(File file){
val mapper = new CsvMapper();
mapper.addMixIn(type, type);
val schema = mapper.schemaFor(type)
.withHeader()
.withColumnSeparator(columnSep);
return mapper
.readerFor(type)
.with(schema)
.<T>readValues(file)
.readAll();
}
}
| gpl-3.0 |
DivineCooperation/bco.registry | unit-registry/core/src/main/java/org/openbase/bco/registry/unit/core/dbconvert/ServiceTemplateToServiceDescriptionDbConverter.java | 2625 | package org.openbase.bco.registry.unit.core.dbconvert;
/*-
* #%L
* BCO Registry Unit Core
* %%
* Copyright (C) 2014 - 2020 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.File;
import java.util.Map;
import org.openbase.jul.exception.CouldNotPerformException;
import org.openbase.jul.storage.registry.version.AbstractGlobalDBVersionConverter;
import org.openbase.jul.storage.registry.version.DBVersionControl;
import org.openbase.jul.storage.registry.version.DatabaseEntryDescriptor;
/**
*
* @author <a href="mailto:pleminoq@openbase.org">Tamino Huxohl</a>
*/
public class ServiceTemplateToServiceDescriptionDbConverter extends AbstractGlobalDBVersionConverter {
protected static final String SERVICE_CONFIG_FIELD = "service_config";
protected static final String SERVICE_TEMPLATE_FIELD = "service_template";
protected static final String SERVICE_DESCRIPTION_FIELD = "service_description";
public ServiceTemplateToServiceDescriptionDbConverter(DBVersionControl versionControl) {
super(versionControl);
}
@Override
public JsonObject upgrade(JsonObject outdatedDBEntry, Map<File, JsonObject> dbSnapshot, Map<String, Map<File, DatabaseEntryDescriptor>> globalDbSnapshots) throws CouldNotPerformException {
if (outdatedDBEntry.has(SERVICE_CONFIG_FIELD)) {
for (JsonElement serviceConfigElem : outdatedDBEntry.getAsJsonArray(SERVICE_CONFIG_FIELD)) {
JsonObject serviceConfig = serviceConfigElem.getAsJsonObject();
if (serviceConfig.has(SERVICE_TEMPLATE_FIELD)) {
JsonObject serviceTemplate = serviceConfig.getAsJsonObject(SERVICE_TEMPLATE_FIELD);
serviceConfig.remove(SERVICE_TEMPLATE_FIELD);
serviceConfig.add(SERVICE_DESCRIPTION_FIELD, serviceTemplate);
}
}
}
return outdatedDBEntry;
}
}
| gpl-3.0 |
jitlogic/zorka | zorka-core/src/test/java/com/jitlogic/zorka/core/test/spy/support/TestAsyncQueueCollector.java | 1106 | /*
* 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.test.spy.support;
import com.jitlogic.zorka.core.spy.plugins.AsyncQueueCollector;
import java.util.Map;
public class TestAsyncQueueCollector extends AsyncQueueCollector {
public Map<String, Object> process(int stage, Map<String, Object> record) {
doProcess(record);
return record;
}
public void start() {
}
}
| gpl-3.0 |
fschwab/maz-db | database/src/main/java/de/spiritaner/maz/controller/approval/ApprovalEditorController.java | 3009 | package de.spiritaner.maz.controller.approval;
import de.spiritaner.maz.controller.meta.ApprovalTypeOverviewController;
import de.spiritaner.maz.model.Approval;
import de.spiritaner.maz.model.meta.ApprovalType;
import de.spiritaner.maz.util.database.CoreDatabase;
import de.spiritaner.maz.util.validator.ComboBoxValidator;
import de.spiritaner.maz.view.renderer.MetaClassListCell;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import org.apache.log4j.Logger;
import org.controlsfx.control.ToggleSwitch;
import javax.persistence.EntityManager;
import java.net.URL;
import java.util.Collection;
import java.util.ResourceBundle;
public class ApprovalEditorController implements Initializable {
final static Logger logger = Logger.getLogger(ApprovalEditorController.class);
@FXML
private Button addNewApprovalTypeButton;
@FXML
private ToggleSwitch approvedToggleSwitch;
@FXML
private ComboBox<ApprovalType> approvalTypeComboBox;
private boolean readOnly = false;
private ComboBoxValidator<ApprovalType> approvalTypeValidator;
public void initialize(URL location, ResourceBundle resources) {
approvalTypeValidator = new ComboBoxValidator<>(approvalTypeComboBox).fieldName("Einwilligungsart").isSelected(true).validateOnChange();
approvalTypeComboBox.setCellFactory(column -> new MetaClassListCell<>());
approvalTypeComboBox.setButtonCell(new MetaClassListCell<>());
loadApprovalType();
}
public void setAll(Approval approval) {
approvedToggleSwitch.setSelected(approval.isApproved());
approvalTypeComboBox.setValue(approval.getApprovalType());
}
public Approval getAll(Approval approval) {
if (approval == null) approval = new Approval();
approval.setApproved(approvedToggleSwitch.isSelected());
approval.setApprovalType(approvalTypeComboBox.getValue());
return approval;
}
public void setReadonly(boolean readonly) {
this.readOnly = readonly;
approvedToggleSwitch.setDisable(readonly);
approvalTypeComboBox.setDisable(readonly);
addNewApprovalTypeButton.setDisable(readonly);
}
public void loadApprovalType() {
EntityManager em = CoreDatabase.getFactory().createEntityManager();
Collection<ApprovalType> result = em.createNamedQuery("ApprovalType.findAllWithIdGreaterThanThree", ApprovalType.class).getResultList();
ApprovalType selectedBefore = approvalTypeComboBox.getValue();
approvalTypeComboBox.getItems().clear();
approvalTypeComboBox.getItems().addAll(FXCollections.observableArrayList(result));
approvalTypeComboBox.setValue(selectedBefore);
}
public boolean isValid() {
boolean approvalTypeValid = approvalTypeValidator.validate();
return approvalTypeValid;
}
public void addNewApprovalType(ActionEvent actionEvent) {
new ApprovalTypeOverviewController().create(actionEvent);
loadApprovalType();
}
public boolean isReadOnly() {
return readOnly;
}
}
| gpl-3.0 |
aaitor/flink-charts | src/main/java/com/foreach/poc/charts/core/SimpleChartsPipeline.java | 3254 | package com.foreach.poc.charts.core;
import com.foreach.poc.charts.model.ChartsResult;
import com.foreach.poc.charts.model.TagEvent;
import org.apache.flink.api.common.operators.Order;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.tuple.Tuple3;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
/**
* SimpleChartsPipeline specialization. Extends Charts pipeline
* and implements a custom cleansing and transformation logic.
*/
public class SimpleChartsPipeline extends ChartsPipeline implements DataPipeline<TagEvent>, Serializable {
public SimpleChartsPipeline(PipelineConf conf) {
super(conf);
env.registerType(ChartsResult.class);
}
/**
* Filtering invalid input data.
* Initially removing TagEvents without trackId
* The cleansing logic can be encapsulated here
* @param input
* @return
*/
@Override
public DataSet<Tuple3<Long, Integer, TagEvent>> cleansing(DataSet<?> input) {
log.info("Cleansing Phase. Removing invalid TagEvent's");
return ((DataSet<TagEvent>) input)
.filter(t -> t.trackId > 0) // Removing all the events with invalid trackids
.map( t -> new Tuple3<>(t.trackId, 1, t)) // getting tuples
.returns(new TypeHint<Tuple3<Long, Integer, TagEvent>>(){});
}
/**
* Data transformation.
* The method group by trackId, sum the number of occurrences, sort the output
* and get the top elements defined by the user.
* @param input
* @return
*/
@Override
public DataSet<ChartsResult> transformation(DataSet<?> input) {
log.info("Transformation Phase. Computing the tags");
return input
.groupBy(0) // Grouping by trackId
.sum(1) // Sum the occurrences of each grouped item
.sortPartition(1, Order.DESCENDING).setParallelism(1) // Sort by count
.first(pipelineConf.args.getLimit())
.map( t -> {
Tuple3<Long, Integer, TagEvent> tuple= (Tuple3<Long, Integer, TagEvent>) t;
return new ChartsResult(tuple.f0, tuple.f1, tuple.f2);
})
.returns(new TypeHint<ChartsResult>(){});
}
@Override
public boolean persistence(DataSet<?> input) {
return false;
}
/**
* Pipeline runner. This static method orchestrates the pipeline execution stages.
* @param conf
* @throws Exception
*/
public static void run(PipelineConf conf) throws Exception {
SimpleChartsPipeline pipeline= new SimpleChartsPipeline(conf);
DataSet<TagEvent> inputTags= pipeline.ingestion();
DataSet<Tuple3<Long, Integer, TagEvent>> cleanTags = pipeline.cleansing(inputTags);
DataSet<ChartsResult> topTags= pipeline.transformation(cleanTags);
System.out.println("CHART POSITION , TRACK TITLE , ARTIST NAME , COUNT");
AtomicInteger position= new AtomicInteger(0);
topTags.collect().forEach( t ->
System.out.println("#" + position.incrementAndGet() + ", " + t.toString())
);
}
}
| gpl-3.0 |
tmhorne/storybook | src/ch/intertec/storybook/playground/swing/undo/PgUndo.java | 2224 | /*
Storybook: Scene-based software for novelists and authors.
Copyright (C) 2008 - 2011 Martin Mustun
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 ch.intertec.storybook.playground.swing.undo;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
import ch.intertec.storybook.toolkit.swing.undo.UndoableTextArea;
import ch.intertec.storybook.toolkit.swing.undo.UndoableTextField;
@SuppressWarnings("serial")
public class PgUndo extends JFrame {
private UndoableTextArea taTest;
private UndoableTextField tfTest;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PgUndo();
}
});
}
public PgUndo() {
super("undo / redo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initGUI();
setVisible(true);
}
private void initGUI() {
setLayout(new MigLayout("fill,wrap"));
tfTest = new UndoableTextField();
tfTest.setDragEnabled(true);
taTest = new UndoableTextArea();
taTest.setLineWrap(true);
taTest.setDragEnabled(true);
taTest.setText("press Ctrl-Z to undo, Ctrl-Y to redo");
taTest.getUndoManager().discardAllEdits();
JScrollPane scroller = new JScrollPane(taTest);
JButton btUndo = new JButton();
btUndo.setAction(taTest.getUndoAction());
JButton btRedo = new JButton();
btRedo.setAction(taTest.getRedoAction());
add(tfTest, "growx");
add(scroller, "gapy 10,grow");
add(btUndo, "split 2");
add(btRedo);
}
}
| gpl-3.0 |