repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
pantelis60/L2Scripts_Underground | gameserver/src/main/java/l2s/gameserver/network/l2/c2s/RequestAutoSoulShot.java | 1741 | package l2s.gameserver.network.l2.c2s;
import l2s.gameserver.handler.items.IItemHandler;
import l2s.gameserver.model.Player;
import l2s.gameserver.model.items.ItemInstance;
import l2s.gameserver.network.l2.s2c.ExAutoSoulShot;
import l2s.gameserver.network.l2.s2c.SystemMessage;
public class RequestAutoSoulShot extends L2GameClientPacket {
private int itemId;
private int type; // look at ExAutoSoulShot.Type
private boolean enabled;
@Override
protected void readImpl() {
this.itemId = readD();
this.enabled = readD() == 1;
this.type = readD();
}
@Override
protected void runImpl() {
Player activeChar = getClient().getActiveChar();
if (activeChar == null) {
return;
}
if (activeChar.getPrivateStoreType() != Player.STORE_PRIVATE_NONE || activeChar.isDead()) {
return;
}
ItemInstance item = activeChar.getInventory().getItemByItemId(itemId);
if (item == null) {
return;
}
if (enabled) {
activeChar.addAutoSoulShot(itemId);
activeChar.sendPacket(new ExAutoSoulShot(itemId, type, enabled));
activeChar.sendPacket(new SystemMessage(SystemMessage.THE_USE_OF_S1_WILL_NOW_BE_AUTOMATED).addItemName(item.getItemId()));
IItemHandler handler = item.getTemplate().getHandler();
handler.useItem(activeChar, item, false);
return;
}
activeChar.removeAutoSoulShot(itemId);
activeChar.sendPacket(new ExAutoSoulShot(itemId, type, enabled));
activeChar.sendPacket(new SystemMessage(SystemMessage.THE_AUTOMATIC_USE_OF_S1_WILL_NOW_BE_CANCELLED).addItemName(item.getItemId()));
}
} | gpl-3.0 |
optimizationBenchmarking/utils-base | src/test/java/shared/junit/org/optimizationBenchmarking/utils/graphics/style/StylePaletteTest.java | 1983 | package shared.junit.org.optimizationBenchmarking.utils.graphics.style;
import java.util.HashSet;
import org.junit.Assert;
import org.junit.Ignore;
import org.optimizationBenchmarking.utils.graphics.style.spec.IStyle;
import org.optimizationBenchmarking.utils.graphics.style.spec.IStylePalette;
import org.optimizationBenchmarking.utils.text.TextUtils;
import shared.junit.org.optimizationBenchmarking.utils.collections.ListTest;
/**
* A basic test for style palettes.
*
* @param <PT>
* the palette type
* @param <ET>
* the palette element type
*/
@Ignore
public class StylePaletteTest<ET extends IStyle, PT extends IStylePalette<ET>>
extends ListTest<ET, PT> {
/** create */
public StylePaletteTest() {
this(null, true);
}
/**
* create
*
* @param isSingleton
* is this a singleton-based tests?
* @param instance
* the instance, or {@code null} if unspecified
*/
public StylePaletteTest(final PT instance, final boolean isSingleton) {
super(null, instance, isSingleton, false);
}
/** {@inheritDoc} */
@Override
protected Object testEachElement_createContext() {
return new HashSet<>();
}
/** {@inheritDoc} */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected void testEachElement_testElement(final ET element,
final Object context) {
final String id;
super.testEachElement_testElement(element, context);
Assert.assertNotNull(element);
id = element.getID();
Assert.assertNotNull(id);
Assert.assertTrue(id.length() > 0);
Assert.assertTrue(((HashSet) context).add(//
TextUtils.toComparisonCase(id)));
Assert.assertTrue(((HashSet) context).add(element));
Assert.assertFalse(((HashSet) context).add(element));
}
/** not applicable */
@Ignore
@Override
public void testSubList() {
//
}
/** not applicable */
@Ignore
@Override
public void testEqualsToArrayList() {
//
}
}
| gpl-3.0 |
gaborfeher/grantmaster | grantmaster/src/main/java/com/github/gaborfeher/grantmaster/logic/entities/ProjectReport.java | 2666 | /*
* This file is a part of GrantMaster.
* Copyright (C) 2015 Gábor Fehér <feherga@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.gaborfeher.grantmaster.logic.entities;
import com.github.gaborfeher.grantmaster.framework.base.EntityBase;
import java.io.Serializable;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
@Entity
@Table(
uniqueConstraints=
@UniqueConstraint(columnNames={"reportDate", "project_id"}))
public class ProjectReport extends EntityBase implements Serializable {
@Id
@GeneratedValue
private long id;
@NotNull(message="%ValidationErrorReportDateNotEmpty")
@Column(nullable = false)
@Temporal(TemporalType.DATE)
private LocalDate reportDate;
@ManyToOne(optional = false)
@JoinColumn(nullable = false)
private Project project;
@Column(nullable = true)
private String note;
public static enum Status {
OPEN,
CLOSED;
}
@Column(nullable = false)
private Status status = Status.OPEN;
@Override
public Long getId() {
return id;
}
@Override
public String toString() {
return "R" + reportDate.toString();
}
public LocalDate getReportDate() {
return reportDate;
}
public void setReportDate(LocalDate reportDate) {
this.reportDate = reportDate;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
| gpl-3.0 |
jawb/ElevatorSystem | features/DoorControl/Elevator.java | 1529 | import java.util.ArrayList;
import java.lang.Runnable;
public class Elevator {
public volatile int leftDoorPos;
public volatile int rightDoorPos;
public volatile int doorStep = 0;
public final static int OPENED = 0;
public final static int OPENING = 1;
public final static int CLOSING = 2;
public final static int CLOSED = 3;
public int doorStatus = CLOSED;
public final static int NUM_STEP = 16;
public final static int STEP = Main.ELEVATOR_WIDTH/(2*NUM_STEP);
Thread doorThread;
public Elevator(Environment env) {
doorThread = new Thread(new Runnable() {
@Override
public void run() {
while (notPaused) {
while (running) {
if (doorStatus == CLOSING) {
if (doorStep>0) {
leftDoorPos += STEP;
rightDoorPos -= STEP;
--doorStep;
}
else {
doorStatus = CLOSED;
synchronized (d2eLock) { d2eLock.notify(); }
}
}
if (doorStatus == OPENING) {
if (doorStep<NUM_STEP) {
leftDoorPos -= STEP;
rightDoorPos += STEP;
++doorStep;
}
else {
doorStatus = CLOSED;
synchronized (d2eLock) { d2eLock.notify(); }
}
}
try { Thread.sleep(100); } catch(Exception ex) {ex.printStackTrace();}
}
}
}
});
doorThread.start();
}
public void closeDoor() {
doorStatus = CLOSING;
}
public void openDoor() {
doorStatus = OPENING;
}
} | gpl-3.0 |
xiaotiantiantian/IS2560-Questionnaire-System | INFSCI2560-Questionnaire-System/src/java/controller/changeuserinfo.java | 3795 | /*
* 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 controller;
import dataAccessObject.userDao;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author qssheep
*/
//@WebServlet(name = "changeuserinfo", urlPatterns = {"/changeuserinfo"})
public class changeuserinfo extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession();
int userid = (int)session.getAttribute("userID");
String username = request.getParameter("username");
String sex = request.getParameter("gender");
userDao ud = new userDao();
int err = 0;
if(!username.equals(""))
err += ud.changeusername(userid, username);
if(!sex.equals(""))
err += ud.changeusersex(userid, sex);
if(err < 0){
session.setAttribute("err", "Failed to change user information!");
response.sendRedirect("fail.jsp");
}
else{
response.sendRedirect("success.jsp");
}
return;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(changeuserinfo.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(changeuserinfo.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| gpl-3.0 |
Pentico/StudioTAM | data/src/main/java/com/pencorp/data/repository/datasource/SongData/CloudSongDataStore.java | 135 | package com.pencorp.data.repository.datasource.SongData;
/**
* Created by Tuane on 3/02/17.
*/
public class CloudSongDataStore {
}
| gpl-3.0 |
CatCoderr/CustomBans | custombans-api/src/main/java/me/catcoder/custombans/database/ResponseHandler.java | 180 | package me.catcoder.custombans.database;
/**
* Created by Ruslan on 12.03.2017.
*/
public interface ResponseHandler<H, R> {
R handleResponse(H handle) throws Exception;
}
| gpl-3.0 |
bengtmartensson/IrpTransmogrifier | src/test/java/org/harctoolbox/ircore/ModulatedIrSequenceNGTest.java | 2785 | package org.harctoolbox.ircore;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class ModulatedIrSequenceNGTest {
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
public ModulatedIrSequenceNGTest() {
}
@BeforeMethod
public void setUpMethod() throws Exception {
}
@AfterMethod
public void tearDownMethod() throws Exception {
}
/**
* Test of clone method, of class ModulatedIrSequence.
*/
@Test
public void testClone() {
System.out.println("clone");
try {
ModulatedIrSequence instance = new ModulatedIrSequence(new double[]{1, 3, 4, 5}, 12345d, 0.45);
ModulatedIrSequence result = instance.clone();
assertTrue(result.approximatelyEquals(instance));
} catch (OddSequenceLengthException ex) {
fail();
}
}
/**
* Test of modulate method, of class ModulatedIrSequence.
* @throws org.harctoolbox.ircore.OddSequenceLengthException
*/
@Test
public void testModulate() throws OddSequenceLengthException {
System.out.println("modulate");
double[] data = new double[] {100, 100, 105, 100, 92, 100};
ModulatedIrSequence instance = new ModulatedIrSequence(data, 100000.0);
IrSequence expResult = new IrSequence(new double[]{4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,106,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,101,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,2,100});
IrSequence result = instance.modulate();
assertTrue(expResult.approximatelyEquals(result));
}
/**
* Test of demodulate method, of class ModulatedIrSequence.
* @throws org.harctoolbox.ircore.OddSequenceLengthException
*/
@Test
public void testDemodulate_IrSequence_double() throws OddSequenceLengthException {
System.out.println("demodulate");
IrSequence irSequence = new IrSequence(new double[]{4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,106,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,101,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,4,6,2,100});
double threshold = 20.0;
ModulatedIrSequence expResult = new ModulatedIrSequence(new double[]{94, 106, 104, 101, 92, 100}, 100000.0, 0.4);
ModulatedIrSequence result = ModulatedIrSequence.demodulate(irSequence, threshold);
assertTrue(expResult.approximatelyEquals(result, 0, 0.001, 0.001, 0.001));
}
}
| gpl-3.0 |
EyeSeeTea/dhis2 | dhis-2/dhis-api/src/main/java/org/hisp/dhis/datastatistics/DataStatisticsEventType.java | 1912 | package org.hisp.dhis.datastatistics;
/*
* Copyright (c) 2004-2016, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*/
/**
* Enum of EventTypes to be used as identifiers in DataStatisticsEvent
*
* @author Yrjan A. F. Fraschetti
* @author Julie Hill Roa
*/
public enum DataStatisticsEventType
{
CHART_VIEW,
MAP_VIEW,
DASHBOARD_VIEW,
REPORT_TABLE_VIEW,
EVENT_REPORT_VIEW,
EVENT_CHART_VIEW,
TOTAL_VIEW
}
| gpl-3.0 |
Teeyenoh/zephis | src/uk/co/quarklike/zephis/src/map/item/Inventory.java | 2225 | package uk.co.quarklike.zephis.src.map.item;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
public class Inventory {
private HashMap<Integer, Integer> _items;
public static final int SORT_QUANTITY = 0;
public static final int SORT_ALPHABETICAL = 1;
public static final int SORT_ID = 2;
private int _sorting = SORT_QUANTITY;
public Inventory() {
_items = new HashMap<Integer, Integer>();
}
public void addItem(int itemID, int quantity) {
if (_items.containsKey(itemID)) {
_items.put(itemID, _items.get(itemID) + quantity);
} else {
_items.put(itemID, quantity);
}
}
public void removeItem(int itemID, int quantity) {
_items.put(itemID, _items.get(itemID) - quantity);
}
public int getItemCount(int itemID) {
return _items.get(itemID);
}
public boolean containsItem(int itemID, int quantity) {
return _items.get(itemID) >= quantity;
}
private Comparator<Integer> _sortQuantity = new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return getItemCount(b) - getItemCount(a);
}
};
private Comparator<Integer> _sortAlphabet = new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
int i = 0;
String nameA = Item.getItem(a).getTranslatedName();
String nameB = Item.getItem(b).getTranslatedName();
while (nameB.charAt(i) - nameA.charAt(i) == 0) {
if (i == nameA.length() || i == nameB.length()) {
return (nameA.length() - nameB.length()) / (Math.abs(nameA.length() - nameB.length()));
}
i++;
}
return nameA.charAt(i) - nameB.charAt(i);
}
};
public int[] getItems() {
ArrayList<Integer> list = new ArrayList<Integer>(_items.keySet());
switch (_sorting) {
case SORT_QUANTITY:
list.sort(_sortQuantity);
break;
case SORT_ALPHABETICAL:
list.sort(_sortAlphabet);
break;
case SORT_ID:
list.sort(null);
break;
}
return list.stream().mapToInt(i -> i).toArray();
}
public void sortByQuantity() {
_sorting = SORT_QUANTITY;
}
public void sortByAlphabet() {
_sorting = SORT_ALPHABETICAL;
}
public void sortByID() {
_sorting = SORT_ID;
}
} | gpl-3.0 |
Deletescape-Media/Lawnchair | src/com/android/launcher3/util/LogConfig.java | 1144 | package com.android.launcher3.util;
/**
* This is a utility class that keeps track of all the tag that can be enabled to debug
* a behavior in runtime.
*
* To use any of the strings defined in this class, execute the following command.
*
* $ adb shell setprop log.tag.TAGNAME VERBOSE
*/
public class LogConfig {
// These are list of strings that can be used to replace TAGNAME.
public static final String STATSLOG = "StatsLog";
/**
* After this tag is turned on, whenever there is n user event, debug information is
* printed out to logcat.
*/
public static final String USEREVENT = "UserEvent";
/**
* When turned on, all icons are kept on the home screen, even if they don't have an active
* session.
*/
public static final String KEEP_ALL_ICONS = "KeepAllIcons";
/**
* When turned on, icon cache is only fetched from memory and not disk.
*/
public static final String MEMORY_ONLY_ICON_CACHE = "MemoryOnlyIconCache";
/**
* When turned on, we enable doodle related logging.
*/
public static final String DOODLE_LOGGING = "DoodleLogging";
}
| gpl-3.0 |
danielhams/mad-java | 2COMMONPROJECTS/audio-services/src/uk/co/modularaudio/service/gui/impl/racktable/dndpolicy/rackdrag/DndRackDragTargetLookupException.java | 1036 | /**
*
* Copyright (C) 2015 - Daniel Hams, Modular Audio Limited
* daniel.hams@gmail.com
*
* Mad 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.
*
* Mad 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 Mad. If not, see <http://www.gnu.org/licenses/>.
*
*/
package uk.co.modularaudio.service.gui.impl.racktable.dndpolicy.rackdrag;
public class DndRackDragTargetLookupException extends Exception
{
private static final long serialVersionUID = -1425833655072214560L;
public DndRackDragTargetLookupException(final String msg)
{
super( msg );
}
}
| gpl-3.0 |
AHXR/Clockwerk | java/GlobalThemeControl.java | 3761 | /*
* Clockwerk: Dota 2 Rune and Camp Stacking Timer.
* Copyright (C) 2017 AR.
*
* 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/>.
*/
// Imports.
import java.io.File;
import java.io.IOException;
import org.ini4j.Wini;
import clockwerk.global.GlobalSettingsSound;
/*
* ThemeControl is a class that controls anything related to the program
* and user changing the theme. Themes are stored in INI files and can easily
* be modified. This will allow the user to change the wallpaper and sounds of this program.
*
* By default, the file format is saved in ini. The library used is ini4j, which is also
* used in the settings system in Clockwerk.
*
* ini4j - The Java .ini library - http://ini4j.sourceforge.net
*
* @author AR
* @version 1.0
*
* public static void loadTheme( String ThemeName ) throws IOException
*/
public class GlobalThemeControl {
/*
* The theme settings are located in this enumeration here. Considering enumerations
* are predefined constants, I wanted to avoid using the simple variable statement
* methods I used in previous versions.
*/
public enum ThemeSettings {
FOLDER ( "/themes/" ),
EXTENSION ( "ini" ),
SECTION ( "theme" ),
WALLPAPER ( "background" ),
CLOCK ( "clock" ),
GAMECLOCK ( "gameclock" ),
SOUNDS ( "sounds" );
private String
setting;
ThemeSettings( String setting ) { this.setting = setting; }
public final String setting( ) { return setting; }
}
/*
* Static Variables:
*
* @s_wallpaper_path - Retrieved wallpaper path from INI.
*
* @s_clock_code - Retrieved clock color code from INI.
*
* @s_game_clock_code - Retrieved game clock color code from INI
*
* @s_custom_sounds - Retrieved sounds path from INI
*
* @b_theme_reset - Does the theme need to be reset?
*/
public static String
s_wallpaper_path,
s_clock_code,
s_game_clock_code,
s_custom_sounds,
s_run_path,
s_theme_name = "default.ini";
public static boolean
b_theme_reset;
/*
* Load theme will fetch the values from the INI file and store it inside of the static
* variables. Once that is processed, it will then set the b_theme_reset value to true.
* This change will trigger an event found on the timer in ClockwerkGUI.
*/
public static void loadTheme( String ThemeName ) throws IOException {
Wini
f_ini;
f_ini = new Wini( new File( GlobalThemeControl.s_run_path + GlobalThemeControl.ThemeSettings.FOLDER.setting() + ThemeName ) );
String
s_section = ThemeSettings.SECTION.setting();
// Loading values.
s_wallpaper_path = f_ini.get( s_section, ThemeSettings.WALLPAPER.setting(), String.class );
s_clock_code = f_ini.get( s_section, ThemeSettings.CLOCK.setting(), String.class );
s_game_clock_code = f_ini.get( s_section, ThemeSettings.GAMECLOCK.setting(), String.class );
// Changing the audio directory.
GlobalSettingsSound.DIR.changeValue( f_ini.get( s_section, ThemeSettings.SOUNDS.setting(), String.class ) );
// Setting theme result switch.
b_theme_reset = true;
// Assigning the s_theme_name variable just so the user can save their settings.
s_theme_name = ThemeName;
}
}
| gpl-3.0 |
Samjackrep/CakeStuff | mods/TeamL33T/CakeStuff/CakeStuffID.java | 1529 | package mods.TeamL33T.CakeStuff;
public class CakeStuffID {
// IDs are 4020-4099
// Cake Ore, Cake Tools and Armor
public static final int CakeOre = 4020;
public static final int CakeSword = 4021;
public static final int CakePick = 4022;
public static final int CakeAxe = 4023;
public static final int CakeShovel = 4024;
public static final int CakeHoe = 4025;
public static final int CakeBow = 4026;
public static final int CakeArrow = 4027;
public static final int CakeHelm = 4028;
public static final int CakeChest = 4029;
public static final int CakeLegs = 4030;
public static final int CakeBoots = 4031;
// Sugar Dimension Blocks
public static final int StrawberryCream = 4032;
public static final int ChocoCream = 4033;
public static final int VanillaCream = 4044;
public static final int MapleCream = 4045;
public static final int HoneyCream = 4046;
public static final int OrangeCream = 4047;
public static final int GrapeCream = 4048;
public static final int CherryCream = 4049;
// Cakes
public static final int DarkCake = 4050;
public static final int StrawberryCake = 4051;
public static final int ChocoCake = 4052;
public static final int VanillaCake = 4053;
public static final int MapleCake = 4054;
public static final int HoneyCake = 4055;
public static final int OrangeCake = 4056;
public static final int GrapeCake = 4057;
public static final int CherryCake = 4058;
public static final int OverbakedCake = 4059;
// Stuff
public static final int DarkSugar = 4060;
}
| gpl-3.0 |
4lberto/soapUiJunit | src/test/java/com/alberto/soapUiJunit/SoapUIEasyTest.java | 1611 | package com.alberto.soapUiJunit;
import static org.junit.Assert.*;
import java.io.IOException;
import org.apache.xmlbeans.XmlException;
import org.junit.Test;
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.model.support.PropertiesMap;
import com.eviware.soapui.model.testsuite.TestCase;
import com.eviware.soapui.model.testsuite.TestRunner;
import com.eviware.soapui.model.testsuite.TestRunner.Status;
import com.eviware.soapui.model.testsuite.TestSuite;
import com.eviware.soapui.support.SoapUIException;
import com.eviware.soapui.tools.SoapUITestCaseRunner;
public class SoapUIEasyTest {
private static final String TEST_FILE = "src/test/resources/REST-Project-1-soapui-project.xml";
@Test
public void shouldExecuteSpecificTestCase() throws XmlException, IOException, SoapUIException {
// given
WsdlProject project = new WsdlProject(TEST_FILE);
TestSuite testSuite = project.getTestSuiteByName("TestSuite");
TestCase testCase = testSuite.getTestCaseByName("TestCase");
for (int i = 0; i < 10; i++) {
PropertiesMap propertiesMap = new PropertiesMap();
//Sets parameter defined in Soap UI teste case
testCase.setPropertyValue("name", "aName_" + i);
TestRunner runner = testCase.run(propertiesMap, false);
assertEquals(Status.FINISHED, runner.getStatus());
}
}
@Test
public void shouldExecuteAllTestCases() throws Exception{
SoapUITestCaseRunner soapUITestCaseRunner = new SoapUITestCaseRunner();
soapUITestCaseRunner.setProjectFile(TEST_FILE);
boolean run = soapUITestCaseRunner.run();
//No asserts in this mode
}
}
| gpl-3.0 |
cpinan/AlgorithmTraining | DataStructureAndAlgos/src/arrays/DynamicArray.java | 88 | package arrays;
/**
* Created by cpinan on 8/11/17.
*/
public class DynamicArray {
}
| gpl-3.0 |
janosgyerik/ecocitizenapp | src/com/ecocitizen/service/BluetoothSensorManager.java | 8746 | /*
* Copyright (C) 2010-2012 Eco Mobile Citizen
*
* This file is part of EcoCitizen.
*
* EcoCitizen 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.
*
* EcoCitizen 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 EcoCitizen. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ecocitizen.service;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import android.os.Handler;
import android.util.Log;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import com.ecocitizen.common.DeviceHandlerFactory;
import com.ecocitizen.common.reader.DeviceReader;
/**
* This class does all the work for setting up and managing Bluetooth
* connections with other devices. It has a thread for connecting with
* a device, and a thread for performing data transmissions when connected.
*/
public class BluetoothSensorManager extends SensorManager {
// Debugging
private static final String TAG = "BluetoothSensorManager";
private static final boolean D = false;
// Unique UUID for this application generated by uuidgen
private static final UUID MY_UUID = UUID.fromString("0E8783DA-BB85-4225-948F-F0EAB948C5FF");
private static final long IS_ALIVE_TEST_SECONDS = 30;
// Member fields
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
/**
* The class is for one-time use only.
*/
private final BluetoothDevice mDevice;
/**
* Constructor. Prepares a new session.
* @param handler A Handler to send messages back to the UI Activity
*/
public BluetoothSensorManager(Handler handler, GpsLocationListener gpsLocationListener,
BluetoothDevice device) {
super(getDeviceId(device), device.getName(), handler, gpsLocationListener);
mDevice = device;
}
protected static String getDeviceId(BluetoothDevice device) {
return device.getAddress().replaceAll(":", "_");
}
public synchronized void connect() throws Exception {
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
try {
mConnectThread = new ConnectThread();
mConnectThread.start();
}
catch (Exception e) {
this.sendConnectFailedMsg();
throw e; // propagate to caller
}
}
private synchronized void connected(BluetoothSocket socket) {
// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
try {
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
}
catch (Exception e) {
this.sendConnectFailedMsg();
}
}
@Override
public void shutdown() {
if (D) Log.d(TAG, "stop");
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
}
/**
* This thread runs while creating a connection with a remote device.
* It shuts itself down after successful connection.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
public ConnectThread() throws Exception {
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
Method m = mDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(mDevice, 1);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
throw new Exception("failed to create bluetooth socket");
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
Log.e(TAG, "mmSocket.connect() failed", e);
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothSensorManager.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean stop;
public ConnectedThread(BluetoothSocket socket) throws Exception {
if (D) Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}
catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
throw new Exception("failed to setup input/output streams");
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
final DeviceReader deviceReader = DeviceHandlerFactory.getInstance().getReader(getDeviceName(), getDeviceId());
deviceReader.setInputStream(mmInStream);
deviceReader.setOutputStream(mmOutStream);
deviceReader.initialize();
boolean isBinary = deviceReader.isBinary();
Log.i(TAG, "Sanity check if sensor is alive: " + getDeviceName());
ExecutorService executor = Executors.newFixedThreadPool(1);
Callable<Boolean> isAliveTest = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return deviceReader.readNextData() != null;
}
};
Future<Boolean> future = executor.submit(isAliveTest);
boolean isAlive = false;
try {
isAlive = future.get(IS_ALIVE_TEST_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e2) {
} catch (ExecutionException e2) {
} catch (TimeoutException e2) {
isAlive = false;
}
if (! isAlive) {
Log.w(TAG, "Device appears to be DEAD: " + getDeviceName());
BluetoothSensorManager.this.sendConnectFailedMsg();
closeFileHandles();
return;
}
BluetoothSensorManager.this.sendConnectedMsg();
stop = false;
long sequenceNumber = 0;
while (! stop) {
try {
byte[] data = deviceReader.readNextData();
if (data != null) {
sendSensorDataMsg(++sequenceNumber, data, isBinary);
}
} catch (Exception e) {
Log.e(TAG, "disconnected", e);
break;
}
}
closeFileHandles();
if (stop) {
// clean disconnect
BluetoothSensorManager.this.sendConnectionClosedMsg();
}
else {
// interrupt, abrupt disconnect, connection lost
BluetoothSensorManager.this.sendConnectionLostMsg();
}
}
private void closeFileHandles() {
try {
mmInStream.close();
}
catch (IOException e) {
Log.e(TAG, "close() of InputStream failed.");
}
try {
mmOutStream.close();
}
catch (IOException e) {
Log.e(TAG, "close() of OutputStream failed.");
}
try {
mmSocket.close();
}
catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
public void cancel() {
stop = true;
}
}
}
| gpl-3.0 |
drbizzaro/diggime | base/main/src/com/diggime/modules/contact_person/model/ContactStatus.java | 543 | package com.diggime.modules.contact_person.model;
public enum ContactStatus {
ACTIVE(1), DELETED(9);
private final int id;
ContactStatus(int id) {
this.id = id;
}
public int getId() {
return id;
}
public static ContactStatus getById(int id) {
for(ContactStatus status: ContactStatus.values()) {
if(status.getId()==id) {
return status;
}
}
throw new IllegalArgumentException("No contact status exists with id "+id);
}
}
| gpl-3.0 |
rakeshyeka/PDFprocessor | src/main/java/htmlParser/TextPropertyVault.java | 3514 | package htmlParser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TextPropertyVault {
private static TextPropertyVault vault = new TextPropertyVault();
private static Map<String, String> hindiFontClasses;
private static List<String> boldFontClasses;
private static Map<String, Boolean> colouredClasses;
private static Map<String, Float> xPositions;
private static Map<String, Float> yPositions;
private static Map<String, Float> fontSizes;
private static final String DEFAULT_FEATURE_LIST_FORMAT = "x y fs l fc fb";
private static final String DEFAULT_DELIMITER = " ";
private static String featureListFormat;
private static String delimiter;
private TextPropertyVault() {
clearVault(true);
}
public static void clearVault(Boolean clearFeatureFormat) {
TextPropertyVault.setHindiFontClasses(new HashMap<String, String>());
TextPropertyVault.setBoldFontClasses(new ArrayList<String>());
TextPropertyVault.setColouredClasses(new HashMap<String, Boolean>());
TextPropertyVault.setXPositions(new HashMap<String, Float>());
TextPropertyVault.setYPositions(new HashMap<String, Float>());
TextPropertyVault.setFontSizes(new HashMap<String, Float>());
if (clearFeatureFormat) {
TextPropertyVault.featureListFormat = null;
}
}
public static TextPropertyVault getVault() {
return vault;
}
public static void setVault(TextPropertyVault vault) {
TextPropertyVault.vault = vault;
}
public static Map<String, Float> getXPositions() {
return xPositions;
}
public static void setXPositions(Map<String, Float> xPositions) {
TextPropertyVault.xPositions = xPositions;
}
public static Map<String, Float> getYPositions() {
return yPositions;
}
public static void setYPositions(Map<String, Float> yPositions) {
TextPropertyVault.yPositions = yPositions;
}
public static Map<String, Float> getFontSizes() {
return fontSizes;
}
public static void setFontSizes(Map<String, Float> fontSizes) {
TextPropertyVault.fontSizes = fontSizes;
}
public static String getFeatureListFormat() {
String outputFeatureListFormat =
featureListFormat == null ? DEFAULT_FEATURE_LIST_FORMAT : featureListFormat;
return correctDelimiter(outputFeatureListFormat);
}
public static String getDefaultFeatureListFormat() {
return DEFAULT_FEATURE_LIST_FORMAT;
}
public static void setFeatureListFormat(String featureListFormat) {
TextPropertyVault.featureListFormat = featureListFormat;
}
public static String getDelimiter() {
return delimiter == null ? DEFAULT_DELIMITER : delimiter;
}
public static void setDelimiter(String delimiter) {
TextPropertyVault.delimiter = delimiter;
}
public Map<String, String> getHindiFontClasses() {
return hindiFontClasses;
}
public static void setHindiFontClasses(Map<String, String> hindiFontClasses) {
TextPropertyVault.hindiFontClasses = hindiFontClasses;
}
public List<String> getBoldFontClasses() {
return boldFontClasses;
}
public static void setBoldFontClasses(List<String> boldFontClasses) {
TextPropertyVault.boldFontClasses = boldFontClasses;
}
public Map<String, Boolean> getColouredClasses() {
return colouredClasses;
}
public static void setColouredClasses(Map<String, Boolean> colouredClasses) {
TextPropertyVault.colouredClasses = colouredClasses;
}
private static String correctDelimiter(String outputFeatureListFormat) {
return outputFeatureListFormat.replace(DEFAULT_DELIMITER, getDelimiter());
}
}
| gpl-3.0 |
jmeetsma/Iglu-Util | src/main/java/org/ijsberg/iglu/util/io/FileSupport.java | 29671 | /*
* Copyright 2011-2014 Jeroen Meetsma - IJsberg Automatisering BV
*
* This file is part of Iglu.
*
* Iglu 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.
*
* Iglu 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 Iglu. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ijsberg.iglu.util.io;
import org.ijsberg.iglu.util.collection.CollectionSupport;
import org.ijsberg.iglu.util.formatting.PatternMatchingSupport;
import org.ijsberg.iglu.util.misc.Line;
import org.ijsberg.iglu.util.misc.StringSupport;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Supports retrieval and deletion of particular files in a directory structure
* as well as other file system manipulation.
*/
public abstract class FileSupport {
private static final int COPY_BUFFER = 100000;
/**
* Retrieves all files from a directory and its subdirectories.
*
* @param path path to directory
* @return A list containing the found files
*/
public static ArrayList<File> getFilesInDirectoryTree(String path) {
File directory = new File(path);
return getContentsInDirectoryTree(directory, "*", true, false);
}
/**
* Retrieves all files from a directory and its subdirectories.
*
* @param directory directory
* @return a list containing the found files
*/
public static ArrayList<File> getFilesInDirectoryTree(File directory) {
return getContentsInDirectoryTree(directory, "*", true, false);
}
/**
* Retrieves files for a given mask from a directory and its subdirectories.
*
* @param path root of directory tree
* @param includeMask exact filename, or mask containing wildcards
* @return A list containing the found files
*/
public static List<File> getFilesInDirectoryTree(String path, String includeMask) {
File file = new File(path);
return getContentsInDirectoryTree(file, includeMask, true, false);
}
/**
* Retrieves files for a given mask from a directory and its subdirectories.
*
* @param path root of directory tree
* @param includeRuleSet rule set defining precisely which files to include
* @return A list containing the found files
*/
public static ArrayList<File> getFilesInDirectoryTree(String path, FileFilterRuleSet includeRuleSet) {
File file = new File(path);
return getContentsInDirectoryTree(file, includeRuleSet, true, false);
}
/**
*/
public static List<File> replaceStringsInFilesInDirectoryTree (
String path, FileFilterRuleSet includeRuleSet,
String searchString, String replaceString) throws IOException {
File directory = new File(path);
List<File> files = getContentsInDirectoryTree(directory, includeRuleSet, true, false);
for(File file : files) {
String text = getTextFileFromFS(file);
String modifiedText = StringSupport.replaceAll(text, searchString, replaceString);
saveTextFile(modifiedText, file);
}
return files;
}
/**
* Retrieves all files from a directory and its subdirectories
* matching the given mask.
*
* @param file directory
* @param includeMask mask to match
* @return a list containing the found files
*/
public static ArrayList<File> getFilesInDirectoryTree(File file, String includeMask) {
return getContentsInDirectoryTree(file, includeMask, true, false);
}
/**
* Retrieves contents from a directory and its subdirectories matching a given mask.
*
* @param directory directory
* @param includeMask file name to match
* @param returnFiles return files
* @param returnDirs return directories
* @return a list containing the found contents
*/
private static ArrayList<File> getContentsInDirectoryTree(File directory, String includeMask, boolean returnFiles, boolean returnDirs) {
return getContentsInDirectoryTree(directory, new FileFilterRuleSet(directory.getPath()).setIncludeFilesWithNameMask(includeMask), returnFiles, returnDirs);
}
/**
* Retrieves contents from a directory and its subdirectories matching a given rule set.
*
* @param directory directory
* @param ruleSet file name to match
* @param returnFiles return files
* @param returnDirs return directories
* @return a list containing the found contents
*/
private static ArrayList<File> getContentsInDirectoryTree(File directory, FileFilterRuleSet ruleSet, boolean returnFiles, boolean returnDirs) {
ArrayList<File> result = new ArrayList<File>();
if (directory != null && directory.exists() && directory.isDirectory()) {
File[] files = directory.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
if (returnDirs && ruleSet.fileMatchesRules(files[i])) {
result.add(files[i]);
}
result.addAll(getContentsInDirectoryTree(files[i], ruleSet, returnFiles, returnDirs));
}
else if (returnFiles && ruleSet.fileMatchesRules(files[i])) {
result.add(files[i]);
}
}
}
}
return result;
}
/**
* Retrieves all directories from a directory and its subdirectories.
*
* @param path path to directory
* @return A list containing the found directories
*/
public static ArrayList<File> getDirectoriesInDirectoryTree(String path) {
File file = new File(path);
return getContentsInDirectoryTree(file, "*", false, true);
}
/**
* Retrieves all directories from a directory and its subdirectories.
*
* @param path path to directory
* @param includeMask file name to match
* @return A list containing the found directories
*/
public static ArrayList<File> getDirectoriesInDirectoryTree(String path, String includeMask) {
File file = new File(path);
return getContentsInDirectoryTree(file, includeMask, false, true);
}
/**
* Retrieves all files from a directory and its subdirectories.
*
* @param path path to directory
* @param includeMask file name to match
* @return a list containing the found files
*/
public static ArrayList<File> getFilesAndDirectoriesInDirectoryTree(String path, String includeMask) {
File file = new File(path);
return getContentsInDirectoryTree(file, includeMask, true, true);
}
/**
* Tries to retrieve a class as File from all directories mentioned in system property java.class.path
*
* @param className class name as retrieved in myObject.getClass().getName()
* @return a File if the class file was found or null otherwise
*/
public static File getClassFileFromDirectoryInClassPath(String className) {
String fileName = StringSupport.replaceAll(className, ".", "/");
fileName += ".class";
return getFileFromDirectoryInClassPath(fileName, System.getProperty("java.class.path"));
}
/**
* Locates a file in the classpath.
*
* @param fileName
* @param classPath
* @return the found file or null if the file can not be located
*/
public static File getFileFromDirectoryInClassPath(String fileName, String classPath) {
Collection<String> paths = StringSupport.split(classPath, ";:", false);
for(String singlePath : paths) {
File dir = new File(singlePath);
if (dir.isDirectory()) {
File file = new File(singlePath + '/' + fileName);
if (file.exists()) {
return file;
}
}
}
return null;
}
/**
* @param fileName
* @return
* @throws IOException
*/
public static byte[] getBinaryFromFS(String fileName) throws IOException {
File file = new File(fileName);
if (file.exists()) {
return getBinaryFromFS(file);
}
throw new FileNotFoundException("file '" + fileName + "' does not exist");
}
/**
* @param existingTextFile
* @return
* @throws IOException
*/
public static String getTextFileFromFS(File existingTextFile) throws IOException {
return new String(getBinaryFromFS(existingTextFile));
}
/**
* @return
* @throws IOException
*/
public static byte[] getBinaryFromFS(File existingFile) throws IOException {
FileInputStream in = new FileInputStream(existingFile);
try {
return StreamSupport.absorbInputStream(in);
}
finally {
in.close();
}
}
/**
* Tries to retrieve a class as ZipEntry from all jars mentioned in system property java.class.path
*
* @param className class name as retrieved in myObject.getClass().getName()
* @return a ZipEntry if the class file was found or null otherwise
*/
public static ZipEntry getClassZipEntryFromZipInClassPath(String className) throws IOException {
String fileName = StringSupport.replaceAll(className, ".", "/");
fileName += ".class";
Collection<String> jars = StringSupport.split(System.getProperty("java.class.path"), ";:", false);
for(String jarFileName : jars) {
if (jarFileName.endsWith(".jar") || jarFileName.endsWith(".zip")) {
ZipEntry entry = getZipEntryFromZip(fileName, jarFileName);
if (entry != null) {
return entry;
}
}
}
return null;
}
public static void zip(String path, String zipFileName, String includeMask) throws IOException {
String zipFilePath = convertToUnixStylePath(path);
List<File> files = getFilesInDirectoryTree(path, includeMask);
FileStreamProvider output = new ZipFileStreamProvider(zipFileName);
for (File file : files) {
String fullFileName = convertToUnixStylePath(file.getPath());
String fileName = fullFileName.substring(zipFilePath.length() + (zipFilePath.endsWith("/") ? 0 : 1));
OutputStream outputStream = output.createOutputStream(fileName);
copyFileResource(fullFileName, outputStream);
output.closeCurrentStream();
}
output.close();
}
public static void unzip(String path, ZipFile zipFile) throws IOException {
ArrayList<ZipEntry> entries = getContentsFromZipFile(zipFile, new FileFilterRuleSet().setIncludeFilesWithNameMask("*.*"));
for(ZipEntry entry : entries) {
InputStream in = zipFile.getInputStream(entry);
if(!entry.isDirectory()) {
File file = new File(path + "/" + entry.getName());
file.mkdirs();
OutputStream out = new FileOutputStream(file);
try {
StreamSupport.absorbInputStream(in, out);
}
finally {
in.close();
}
}
}
}
public static byte[] getBinaryFromZip(String fileName, ZipFile zipFile) throws IOException {
ZipEntry entry = zipFile.getEntry(FileSupport.convertToUnixStylePath(fileName));
if (entry == null) {
entry = zipFile.getEntry("/" + FileSupport.convertToUnixStylePath(fileName));
/* System.out.println("entry " + fileName + " not found in jar " + zipFile.getName());
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()) {
ZipEntry entry2 = entries.nextElement();
System.out.println(entry2.getName());
} */
if (entry == null) {
throw new IOException("entry " + fileName + " not found in jar " + zipFile.getName());
}
}
InputStream in = zipFile.getInputStream(entry);
try {
return StreamSupport.absorbInputStream(in);
}
finally {
in.close();
}
}
public static byte[] getBinaryFromJar(String fileName, String jarFileName) throws IOException {
//zipfile is opened for READ on instantiation
ZipFile zipfile = new ZipFile(jarFileName);
try {
return getBinaryFromZip(fileName, zipfile);
}
finally {
zipfile.close();
}
}
public static String getTextFileFromZip(String fileName, ZipFile zipFile) throws IOException {
return new String(getBinaryFromZip(fileName, zipFile));
}
public static byte[] getBinaryFromClassPath(String fileName, String classPath) throws IOException {
byte[] retval = null;
Collection<String> paths = StringSupport.split(classPath, ";:", false);
for(String path : paths) {
if (path.endsWith(".zip") || path.endsWith(".jar")) {
retval = getBinaryFromJar(fileName, path);
}
else {
retval = getBinaryFromFS(path + '/' + fileName);
}
if (retval == null) {
File dir = new File(path);
if (dir.exists() && dir.isDirectory()) {
Collection<File> jars = FileSupport.getFilesInDirectoryTree(dir, "*.jar");
for(File jar : jars) {
try {
retval = getBinaryFromJar(fileName, jar.getPath());
}
catch (IOException ioe) {
//FIXME
}
if (retval != null) {
return retval;
}
}
}
}
if (retval != null) {
return retval;
}
}
return null;
}
public static byte[] getBinaryFromClassLoader(String path) throws IOException {
return StreamSupport.absorbInputStream(getInputStreamFromClassLoader(path));
}
/**
*
* @param path path with regular path separators ('/')
* @return
* @throws IOException
*/
public static InputStream getInputStreamFromClassLoader(String path) throws IOException {
ClassLoader classLoader = FileSupport.class.getClassLoader();
InputStream retval = classLoader.getResourceAsStream(path);
if(retval == null) {
throw new IOException("class loader can not load resource '" + path + "'");
}
return retval;
}
/**
* @param pathToResource
* @param outputPath
* @throws IOException
*/
public static void copyClassLoadableResourceToFileSystem(String pathToResource, String outputPath) throws IOException{
//TODO make sure that files exist
File outputFile = createFile(outputPath);
if(outputFile.isDirectory()) {
outputFile = new File(outputFile.getPath() + '/' + getFileNameFromPath(pathToResource));
}
OutputStream output = new FileOutputStream(outputFile);
copyClassLoadableResource(pathToResource, output);
output.close();
}
/**
* @param pathToResource
* @param output
* @throws IOException
*/
public static void copyClassLoadableResource(String pathToResource, OutputStream output) throws IOException{
//TODO make sure that files exist
InputStream input = getInputStreamFromClassLoader(pathToResource);
try {
StreamSupport.absorbInputStream(input, output);
} finally {
input.close();
}
}
public static void copyFileResource(String pathToResource, OutputStream output) throws IOException{
InputStream input = new FileInputStream(pathToResource);
try {
StreamSupport.absorbInputStream(input, output);
} finally {
input.close();
}
}
public static boolean containsFileInZip(String fileName, ZipFile zipFile) {
return zipFile.getEntry(fileName) != null;
}
public static ZipEntry getZipEntryFromZip(String fileName, String zipFileName) throws IOException {
//zipfile is opened for READ on instantiation
ZipFile zipfile = new ZipFile(zipFileName);
return zipfile.getEntry(fileName);
}
public static ArrayList<ZipEntry> getContentsFromZipFile(ZipFile zipFile, FileFilterRuleSet ruleSet) {
ArrayList<ZipEntry> result = new ArrayList<ZipEntry>();
Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
while(zipEntries.hasMoreElements()) {
ZipEntry zipEntry = zipEntries.nextElement();
if(ruleSet.fileMatchesRules(zipEntry, zipFile)) {
result.add(zipEntry);
}
}
return result;
}
/**
* Creates a file.
* The file, and the directory structure is created physically,
* if it does not exist already.
*
* @param filename
* @return
*/
public static File createFile(String filename) throws IOException {
File file = new File(filename);
if (!file.exists()) {
if(file.getParent() != null) {
File path = new File(file.getParent());
path.mkdirs();
}
file.createNewFile();
}
return file;
}
public static File createDirectory(String directoryname) throws IOException {
File file = new File(directoryname);
if (!file.exists()) {
if(!file.mkdirs()) {
throw new IOException("unable to create missing directory '" + directoryname + "'");
}
}
return file;
}
public static File writeTextFile(String filename, String text) throws IOException {
File file = createFile(filename);
BufferedReader reader = new BufferedReader(new StringReader(text));
PrintStream out = new PrintStream(file);
String line = null;
while((line = reader.readLine()) != null) {
out.println(line);
}
out.close();
return file;
}
/**
* Deletes all files and subdirectories from a directory.
*
* @param path
*/
public static void emptyDirectory(String path) {
deleteContentsInDirectoryTree(path, null);
}
/**
* Deletes all files and subdirectories from a directory.
*
* @param file
*/
public static void emptyDirectory(File file) {
deleteContentsInDirectoryTree(file, null);
}
/**
* Deletes a file or a directory including its contents;
*
* @param file
*/
public static boolean deleteFile(File file) {
deleteContentsInDirectoryTree(file, null);
return file.delete();
}
/**
* Copies a file.
*
* @param fileName
* @param newFileName
* @param overwriteExisting
* @throws IOException
*/
public static void copyFile(String fileName, String newFileName, boolean overwriteExisting) throws IOException {
copyFile(new File(fileName), newFileName, overwriteExisting);
}
public static void copyFile(File file, String newFileName, boolean overwriteExisting) throws IOException {
if (!file.exists()) {
throw new IOException("file '" + file.getName() + "' does not exist");
}
if (file.isDirectory()) {
throw new IOException('\'' + file.getName() + "' is a directory");
}
File newFile = new File(newFileName);
if(newFile.isDirectory()) {
newFile = new File(newFileName + '/' + file.getName());
}
if (!overwriteExisting && newFile.exists()) {
throw new IOException("file '" + newFile.getName() + "' already exists");
} else {
//newFile.mkdirs();
newFile.getParentFile().mkdirs();
newFile.createNewFile();
}
byte[] buffer = new byte[COPY_BUFFER];
int read = 0;
FileInputStream in = new FileInputStream(file);
FileOutputStream out = new FileOutputStream(newFile);
while ((read = in.read(buffer)) > 0) {
out.write(buffer, 0, read);
}
out.close();
in.close();
}
public static void copyDirectory(String fileName, String newFileName, boolean overwriteExisting) throws IOException {
List<File> files = getFilesInDirectoryTree(fileName);
for(File file : files) {
copyFile(file, newFileName, overwriteExisting);
}
}
/**
* Deletes from a directory all files and subdirectories targeted by a given mask.
* The method will recurse into subdirectories.
*
* @param path
* @param includeMask
*/
public static void deleteContentsInDirectoryTree(String path, String includeMask) {
deleteContentsInDirectoryTree(new File(path), includeMask);
}
/**
* Deletes from a directory all files and subdirectories targeted by a given mask.
* The method will recurse into subdirectories.
*
* @param root
* @param includeMask
*/
public static void deleteContentsInDirectoryTree(File root, String includeMask) {
Collection<File> files = getContentsInDirectoryTree(root, includeMask, true, true);
for(File file : files) {
if (file.exists()) {//file may meanwhile have been deleted
if (file.isDirectory()) {
//empty directory
emptyDirectory(file.getAbsolutePath());
}
file.delete();
}
}
}
/**
* @param file
* @param searchString
* @return a map containing the number of occurrences of the search string in lines, if 1 or more, keyed and sorted by line number
* @throws IOException if the file could not be found or is a directory or locked
*/
public static Map<Integer, Integer> countOccurencesInTextFile(File file, String searchString) throws IOException {
TreeMap<Integer, Integer> retval = new TreeMap<Integer, Integer>();
InputStream input;
input = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
int lineCount = 1;
while (line != null) {
int occCount = -1;
while ((occCount = line.indexOf(searchString, occCount + 1)) != -1) {
Integer lineNo = new Integer(lineCount);
Integer nrofOccurrencesInLine = (Integer) retval.get(lineNo);
if (nrofOccurrencesInLine == null) {
nrofOccurrencesInLine = new Integer(1);
}
else {
nrofOccurrencesInLine = new Integer(nrofOccurrencesInLine.intValue() + 1);
}
retval.put(lineNo, nrofOccurrencesInLine);
System.out.println(">" + line + "<");
}
lineCount++;
line = reader.readLine();
}
return retval;
}
/**
* Prints a message to a user that invokes FileSupport commandline.
*/
private static void printUsage() {
System.out.println("Commandline use of FileSupport only supports recursive investigation of directories");
System.out.println("Usage: java FileSupport -{d(elete)|s(how)} <path> [<mask>] [-f(ind) <word>]");
}
/**
* @param files
* @param searchString
*/
public static void printOccurringString(List<File> files, String searchString) {
//TODO use unix conventions for arguments
//TODO print message if no files found
for (File file : files) {
try {
Map<Integer, Integer> occurrences = countOccurencesInTextFile(file, searchString);
if (occurrences.size() > 0) {
int total = 0;
StringBuffer message = new StringBuffer();
for (Integer lineNo : occurrences.keySet()) {
Integer no = (Integer) occurrences.get(lineNo);
total += no.intValue();
message.append("line " + lineNo + ": " + no + "\n");
}
System.out.println(total + " occurrence" +
(total > 1 ? "s" : "") + " found in file '" +
file.getAbsolutePath() + "'\n" + message);
}
}
catch (IOException e) {
System.out.println("error while trying to read file " + file.getAbsolutePath() + " with message: " + e.getMessage());
}
}
}
/**
* Converts backslashes into forward slashes.
*
* @param path
* @return
*/
public static String convertToUnixStylePath(String path) {
String retval = StringSupport.replaceAll(path, "\\", "/");
retval = StringSupport.replaceAll(retval, new String[]{"///", "//"}, new String[]{"/", "/"});
return retval;
}
public static String getFileNameFromPath(String path) {
String unixStylePath = convertToUnixStylePath(path);
if(unixStylePath.endsWith("/")) {
throw new IllegalArgumentException("path '" + path + "' points to a directory");
}
return unixStylePath.substring(unixStylePath.lastIndexOf('/') + 1);
}
public static String getDirNameFromPath(String path) {
String unixStylePath = convertToUnixStylePath(path);
return unixStylePath.substring(0, unixStylePath.lastIndexOf('/') + 1);
}
public static File createTmpDir() throws IOException {
File file = File.createTempFile("iglu_util_test_", null);
file.delete();
file.mkdirs();
return file;
}
public static File createTmpDir(String prefix) throws IOException {
File file = File.createTempFile(prefix, null);
file.delete();
file.mkdirs();
return file;
}
public static List<Line> convertToTextFile(String input) throws IOException {
return convertToTextFile(input, false);
}
public static List<Line> convertToTextFile(String input, boolean skipEmpty) throws IOException {
return convertToTextFile(null, input, skipEmpty);
}
public static List<Line> convertToTextFile(String fileName, String input, boolean skipEmpty) throws IOException {
BufferedReader reader = new BufferedReader(new StringReader(input));
List<Line> lines = new ArrayList<Line>();
String line; int count = 0;
while ((line = reader.readLine()) != null) {
count++;
if(!skipEmpty || !line.trim().isEmpty()) {
lines.add(new Line(fileName, count, line));
}
}
return lines;
}
public static List<Line> loadTextFile(String encoding, File file) throws IOException {
return findLinesInTextFile(encoding, file, null);
}
public static void saveTextFile(List<Line> lines, File file) throws IOException {
FileOutputStream outputStream = new FileOutputStream(file);
PrintStream printStream = new PrintStream(outputStream);
for(Line line : lines) {
printStream.println(line.getLine());
}
outputStream.close();
}
public static void saveTextFile(String text, File file) throws IOException {
FileOutputStream outputStream = new FileOutputStream(file);
PrintStream printStream = new PrintStream(outputStream);
printStream.println(text);
outputStream.close();
}
public static ArrayList<Line> getLinesInTextFile(File file) throws IOException {
return getLinesInTextFile(file);
}
//TODO read text file from zip
public static ArrayList<Line> getLinesInTextFile(String encoding, File file) throws IOException {
ArrayList<Line> lines = new ArrayList<Line>();
FileInputStream inputStream = new FileInputStream(file);
InputStreamReader inputReader = null;
if(encoding != null) {
inputReader = new InputStreamReader(inputStream, encoding);
} else {
inputReader = new InputStreamReader(inputStream);
}
//FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(inputReader);
String line; int count = 0;
while ((line = reader.readLine()) != null) {
count++;
lines.add(new Line(file.getName(), count, line));
}
reader.close();
return lines;
}
public static ArrayList<Line> findLinesInTextFile(String encoding, File file, String regexp) throws IOException {
ArrayList<Line> lines = new ArrayList<Line>();
ArrayList<Line> linesInFile = getLinesInTextFile(encoding, file);
lines.addAll(findLinesInTextFile(regexp, linesInFile));
return lines;
}
public static ArrayList<Line> findLinesInTextFile(String fileName, String fileData, String regexp) throws IOException {
ArrayList<Line> lines = new ArrayList<Line>();
List<Line> linesInFile = convertToTextFile(fileName, fileData, false);
lines.addAll(findLinesInTextFile(regexp, linesInFile));
return lines;
}
private static ArrayList<Line> findLinesInTextFile(String regexp, List<Line> linesInFile) {
ArrayList<Line> lines = new ArrayList<Line>();
for(Line line : linesInFile) {
if(regexp == null || PatternMatchingSupport.valueMatchesRegularExpression(line.getLine(), regexp)) {
lines.add(line);
}
}
return lines;
}
public static ArrayList<Line> findLinesInTextFile(File file, String regexp) throws IOException {
return findLinesInTextFile(null, file, regexp);
}
public static ArrayList<Line> findLinesInFileCollection(FileCollection files, String regexp) throws IOException {
ArrayList<Line> lines = new ArrayList<Line>();
for(String fileName : files.getFileNames()) {
String fileData = files.getFileContentsByName(fileName);
lines.addAll(findLinesInTextFile(fileName, fileData, regexp));
}
return lines;
}
public static void saveSerializable(Serializable serializable, String fileName) throws IOException {
FileOutputStream fStream = new FileOutputStream(fileName);
ObjectOutputStream oOutput = new ObjectOutputStream(fStream);
try {
oOutput.writeObject(serializable);
} finally {
oOutput.close();
fStream.close();
}
}
public static Serializable readSerializable(String fileName) throws IOException, ClassNotFoundException {
FileInputStream fStream = new FileInputStream(fileName);
ObjectInputStream oInput = new ObjectInputStream(fStream);
Serializable retval = null;
try {
retval = (Serializable)oInput.readObject();
} finally {
oInput.close();
fStream.close();
}
return retval;
}
public static void saveProperties(Properties properties, String fileName) throws IOException {
FileOutputStream outputStream = new FileOutputStream(fileName);
PrintStream printStream = new PrintStream(outputStream);
for(String propertyName : properties.stringPropertyNames()) {
printStream.println(propertyName + "=" + properties.getProperty(propertyName));
}
printStream.close();
outputStream.close();
}
/**
* Commandline use of FileSupport only supports recursive investigation of directories.
* Usage: java FileSupport -<d(elete)|s(how)> [<path>] [<filename>]
*
* @param args
*/
public static void main(String[] args) throws Exception {
//TODO error message if root dir does not exist
zip("C:\\util\\keys\\", "C:\\util\\keys.zip", "*.*");
System.exit(0);
if (args.length >= 2) {
if (args[0].startsWith("-d")) {
if (args.length == 3) {
deleteContentsInDirectoryTree(args[1], args[2]);
return;
}
if (args.length == 2) {
emptyDirectory(args[1]);
return;
}
}
if (args[0].startsWith("-s")) {
if (args.length == 2) {
CollectionSupport.print(getFilesAndDirectoriesInDirectoryTree(args[1], null));
return;
}
if (args.length == 3) {
CollectionSupport.print(getFilesAndDirectoriesInDirectoryTree(args[1], args[2]));
return;
}
if (args.length > 3) {
if (args.length == 4 && args[2].startsWith("-f")) {
List files = getFilesInDirectoryTree(args[1]);
printOccurringString(files, args[3]);
return;
}
if (args.length == 5 && args[3].startsWith("-f")) {
List files = getFilesInDirectoryTree(args[1], args[2]);
printOccurringString(files, args[4]);
return;
}
}
}
}
printUsage();
}
}
| gpl-3.0 |
jacekwasilewski/RankSys | RankSys-core/src/main/java/org/ranksys/core/index/MutableItemIndex.java | 868 | /*
* Copyright (C) 2015 RankSys http://ranksys.org
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.ranksys.core.index;
import es.uam.eps.ir.ranksys.core.index.ItemIndex;
/**
* Mutable item index.
*
* @author Saúl Vargas (Saul.Vargas@mendeley.com)
* @param <I> item type
*/
public interface MutableItemIndex<I> extends ItemIndex<I> {
/**
* Add item with specified id.
*
* @param i id of the item
* @return true if new item was added, false otherwise
*/
public boolean addItem(I i);
/**
* Removes item
*
* @param i id of the item
* @return true if item was removed, false otherwise
*/
public boolean removeItem(I i);
}
| gpl-3.0 |
tweea/matrixjavalib-main-common | src/main/java/net/matrix/util/package-info.java | 148 | /*
* 版权所有 2020 Matrix。
* 保留所有权利。
*/
/**
* 类似 {@link java.util} 包的工具。
*/
package net.matrix.util;
| gpl-3.0 |
PhoenixDevTeam/Phoenix-for-VK | app/src/main/java/biz/dealnote/messenger/view/mozaik/MatrixCalculator.java | 6646 | package biz.dealnote.messenger.view.mozaik;
/**
* Created by admin on 16.01.2017.
* JavaRushHomeWork
*/
public class MatrixCalculator {
private final Libra libra;
private final int count;
public interface Libra {
float getWeight(int index);
}
public MatrixCalculator(int count, Libra libra){
this.count = count;
this.libra = libra;
}
private static class Result {
float minDiff = Float.MAX_VALUE;
int[][] matrix;
}
private void analize(int[][] matrix, Result target){
float maxDiff = getMaxDiff(libra, matrix);
if(maxDiff < target.minDiff || target.matrix == null){
target.minDiff = maxDiff;
target.matrix = cloneArray(matrix);
}
}
public int[][] calculate(int rows) {
Result result = checkAllVariants(rows);
return result.matrix;
}
private static float getMaxDiff(Libra libra, int[][] variant) {
//float[][] realRows = new float[variant.length][variant[0].length];
//for (int i = 0; i < variant.length; i++) {
// for (int a = 0; a < variant[i].length; a++) {
// int v = variant[i][a];
//
// if (v == -1) {
// realRows[i][a] = 0;
// } else {
// realRows[i][a] = libra.getWeight(v);
// }
// }
//}
float[] sums = new float[variant.length];
for(int i = 0; i < variant.length; i++){
sums[i] = getWeightSumm(libra, variant[i]);
}
//for (int i = 0; i < realRows.length; i++) {
// float[] rowArray = realRows[i];
// float sum = getSum(rowArray);
// sums[i] = sum;
//}
float average = getAverage(sums);
float maxDiff = 0;
for (float sum : sums) {
float diff = Math.abs(sum - average);
if (diff > maxDiff) {
maxDiff = diff;
}
}
return maxDiff;
}
private static float getWeightSumm(Libra libra, int ... positions){
float s = 0;
for (int position : positions) {
if(position == -1){
continue;
}
s = s + libra.getWeight(position);
}
return s;
}
/*private static float getSum(float... values) {
float s = 0;
for (float f : values) {
s = s + f;
}
return s;
}*/
private static float getAverage(float... values) {
float sum = 0;
int nonZeroValuesCount = 0;
for (float value : values) {
sum = sum + value;
if (value != 0) {
nonZeroValuesCount++;
}
}
return sum / (float) nonZeroValuesCount;
}
private Result checkAllVariants(int rowsCount) {
Result result = new Result();
int[][] rows = new int[rowsCount][count];
for (int i = rowsCount - 1; i >= 0; i--) {
int[] array = new int[count];
for (int a = 0; a < count; a++) {
array[a] = -1;
}
rows[i] = array;
}
int forFirst = count - rowsCount;
for (int i = 0; i < count; i++) {
boolean toFirst = i < forFirst + 1;
rows[toFirst ? 0 : i - forFirst][toFirst ? i : 0] = i;
}
doShuffle(rows, result);
return result;
}
private void doShuffle(int[][] data, Result result) {
analize(data, result);
moveAll(data, 0, result);
}
/**
* Clones the provided array
*
* @param src
* @return a new clone of the provided array
*/
private static int[][] cloneArray(int[][] src) {
int length = src.length;
int[][] target = new int[length][src[0].length];
for (int i = 0; i < length; i++) {
System.arraycopy(src[i], 0, target[i], 0, src[i].length);
}
return target;
}
private void moveAll(int[][] data, int startFromIndex, Result result) {
while (canMoveToNext(startFromIndex, data)) {
move(startFromIndex, data);
analize(data, result);
if (startFromIndex + 1 < data.length - 1) {
moveAll(cloneArray(data), startFromIndex + 1, result);
}
}
}
/**
* Можно ли переместить последний елемент субмассива data по индексу row на следующую строку
* @param row
* @param data
* @return
*/
private static boolean canMoveToNext(int row, int[][] data) {
// можно только в том случае, если в строке есть хотябы 2 валидных значения
// и с главном массиве есть следующая строка после row
return data[row][1] != -1 && data.length > row + 1;
}
/**
* Переместить последний елемент из строки с индексом row на следующую
*/
private static void move(int row, int[][] data) {
//if(data.length < row){
// throw new IllegalArgumentException();
//}
int[] rowArray = data[row];
int[] nextRowArray = data[row + 1];
if (nextRowArray[nextRowArray.length - 1] != -1) {
move(row + 1, data);
}
int moveIndex = getLastNoNegativeIndex(rowArray);
//if(moveIndex == -1){
// throw new IllegalStateException();
//}
int value = rowArray[moveIndex];
shiftByOneToRight(nextRowArray);
nextRowArray[0] = value;
rowArray[moveIndex] = -1;
}
/**
* Сдвинуть все значение на 1 вправо, значение первого елемента будет заменено на -1
* @param array
*/
private static void shiftByOneToRight(int[] array) {
for (int i = array.length - 1; i >= 0; i--) {
if (i == 0) {
array[i] = -1;
} else {
array[i] = array[i - 1];
}
}
}
/**
* Получить индекс последнего елемента, чье значение не равно -1
* @param array
* @return
*/
private static int getLastNoNegativeIndex(int[] array) {
for (int i = array.length - 1; i >= 0; i--) {
if (array[i] != -1) {
return i;
}
}
return -1;
}
}
| gpl-3.0 |
Jeffconexion/Android | Android - Do básico ao Avançado(Livro)/Cap26/EngHaw/app/src/androidTest/java/dominando/android/enghaw/DiscoUITest.java | 2289 | package dominando.android.enghaw;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.Espresso.pressBack;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.swipeLeft;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.contrib.RecyclerViewActions.actionOnItem;
import static android.support.test.espresso.contrib.RecyclerViewActions.scrollTo;
import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withTagValue;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.is;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class DiscoUITest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule(MainActivity.class);
@Before
public void setUp(){
mActivityRule.getActivity().deleteDatabase(DiscoDbHelper.DB_NAME);
}
@Test
public void testAdicionarFavorito() {
final String RECYCLER_WEB = "web";
final String RECYCLER_FAVORITO = "fav";
final String DISCO_CLICADO = "Minuano";
onView(withTagValue(is((Object) RECYCLER_WEB)))
.perform(scrollTo(hasDescendant(withText(DISCO_CLICADO))));
onView(withTagValue(is((Object) RECYCLER_WEB)))
.perform(actionOnItem(hasDescendant(withText(DISCO_CLICADO)), click()));
onView(withId(R.id.txtTitulo)).check(matches(withText(DISCO_CLICADO)));
onView(withId(R.id.fabFavorito)).perform(click());
pressBack();
onView(withId(R.id.viewPager)).perform(swipeLeft());
onView(withTagValue(is((Object) RECYCLER_FAVORITO)))
.check(matches(hasDescendant(withText(DISCO_CLICADO))));
}
}
| gpl-3.0 |
Lanchon/DexPatcher-tool | tool/src/main/java/lanchon/dexpatcher/transform/codec/BinaryClassNameRewriter.java | 1276 | /*
* DexPatcher - Copyright 2015-2020 Rodrigo Balerdi
* (GNU General Public License version 3 or later)
*
* DexPatcher is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*/
package lanchon.dexpatcher.transform.codec;
import org.jf.dexlib2.rewriter.Rewriter;
// Binary class name '<name>' (eg: 'java/lang/String') corresponds to type descriptor 'L<name>;'.
public abstract class BinaryClassNameRewriter implements Rewriter<String> {
@Override
public String rewrite(String value) {
int end = value.length() - 1;
if (end < 0 || value.charAt(end) != ';') return value;
int start = 0;
char c;
while ((c = value.charAt(start)) == '[') start++;
if (c != 'L') return value;
start++;
String name = value.substring(start, end);
String rewrittenName = rewriteBinaryClassName(name);
if (rewrittenName.equals(name)) return value;
StringBuilder sb = new StringBuilder(start + rewrittenName.length() + 1);
sb.append(value, 0, start).append(rewrittenName).append(';');
return sb.toString();
}
public abstract String rewriteBinaryClassName(String binaryClassName);
}
| gpl-3.0 |
vjdv/deltas_intelidomoserver | server/src-gen/intelidomo/plus/modelos/Luz.java | 492 | package intelidomo.plus.modelos;
import intelidomo.estatico.Constantes;
import intelidomo.plus.modelos.commands.EncenderLuz;
import intelidomo.plus.modelos.commands.ApagarLuz;
/*** added by dLuces
*/
public abstract class Luz extends Dispositivo {
public Luz() {
setCategoria(Constantes.LUZ);
setTipoEstado(Constantes.ON_OFF);
addFuncion(new EncenderLuz(this));
addFuncion(new ApagarLuz(this));
}
public abstract void encender();
public abstract void apagar();
} | gpl-3.0 |
ScaryBlock/Test | Test/src/lu/scary_block/blocks/test/Main.java | 201 | package lu.scary_block.blocks.test;
public class Main {
public static void main(String[] args)
{
System.out.println("HALLO");
System.out.println(SmallKlass.getString());
}
}
| gpl-3.0 |
kd0kfo/javalib | src/main/java/com/davecoss/java/BuildInfo.java | 1047 | package com.davecoss.java;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class BuildInfo {
private Properties info_data = null;
public BuildInfo(@SuppressWarnings("rawtypes") Class c) {
Package pack = c.getPackage();
if(pack == null) {
info_data = null;
return;
}
String packageName = pack.getName();
info_data = new Properties();
InputStream info_file = get_info_file("/" + packageName + ".build_info.properties", c);
if (info_file == null) {
info_data = null;
} else {
try {
info_data.load(info_file);
} catch (IOException e) {
info_data = null;
}
}
}
public Properties get_build_properties() {
return info_data;
}
public String get_version() {
return info_data.getProperty("version");
}
public InputStream get_info_file(String filename) {
return get_info_file(filename, this.getClass());
}
public InputStream get_info_file(String filename, @SuppressWarnings("rawtypes") Class c) {
return c.getResourceAsStream(filename);
}
}
| gpl-3.0 |
flashpixx/MecSim | src/test/java/de/tu_clausthal/in/mec/common/Test_CTreeNode.java | 4480 | /**
* @cond LICENSE
* ######################################################################################
* # GPL License #
* # #
* # This file is part of the micro agent-based traffic simulation MecSim of #
* # Clausthal University of Technology - Mobile and Enterprise Computing #
* # Copyright (c) 2014-15, Philipp Kraus (philipp.kraus@tu-clausthal.de) #
* # This program is free software: you can redistribute it and/or modify #
* # it under the terms of the GNU General Public License as #
* # published by the Free Software Foundation, either version 3 of the #
* # License, or (at your option) any later version. #
* # #
* # This program is distributed in the hope that it will be useful, #
* # but WITHOUT ANY WARRANTY; without even the implied warranty of #
* # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
* # GNU General Public License for more details. #
* # #
* # You should have received a copy of the GNU General Public License #
* # along with this program. If not, see http://www.gnu.org/licenses/ #
* ######################################################################################
* @endcond
*/
package de.tu_clausthal.in.mec.common;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.Test;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* test for CTreeNode class
*/
public class Test_CTreeNode
{
/**
* test-case for path-data store
*/
@Test
public void testDataStore()
{
final List<Pair<CPath, Double>> l_treedata = new LinkedList()
{{
add( new ImmutablePair<>( new CPath( "sub1" ), new Double( 1 ) ) );
add( new ImmutablePair<>( new CPath( "sub1/subsub1.1" ), new Double( 1.1 ) ) );
add( new ImmutablePair<>( new CPath( "sub1/subsub1.2" ), new Double( 1.2 ) ) );
add( new ImmutablePair<>( new CPath( "sub2" ), new Double( 2 ) ) );
add( new ImmutablePair<>( new CPath( "sub2/subsub2.1" ), new Double( 2.1 ) ) );
add( new ImmutablePair<>( new CPath( "sub3" ), new Double( 3 ) ) );
add( new ImmutablePair<>( new CPath( "sub3/subsub3.1" ), new Double( 3.1 ) ) );
add( new ImmutablePair<>( new CPath( "sub3/subsub3.2" ), new Double( 3.2 ) ) );
add( new ImmutablePair<>( new CPath( "sub3/subsub3.3" ), new Double( 3.3 ) ) );
}};
final List<Double> l_data = new LinkedList()
{{
add( new Double( 0 ) );
}};
for ( final Pair<CPath, Double> l_item : l_treedata )
l_data.add( l_item.getValue() );
final CTreeNode<Double> l_root = new CTreeNode<>( "root" );
l_root.setData( new Double( 0 ) );
l_root.setData( l_treedata );
assertEquals( l_root.getNode( "sub3/subsub3.1" ).getData(), new Double( 3.1 ) );
for ( final Double l_item : l_root.getTreeData( true ) )
{
assertTrue( l_data.contains( l_item ) );
l_data.remove( l_item );
}
assertTrue( l_data.isEmpty() );
}
/**
* test-case for root node
*/
@Test
public void testEmpty()
{
final CTreeNode<String> l_node = new CTreeNode<>( "root" );
assertTrue( l_node.isDataNull() );
assertFalse( l_node.hasParent() );
}
/**
* test-case for path-node traversing
*/
@Test
public void testPathNodeTraversing()
{
final CTreeNode<String> l_root = new CTreeNode<>( "root" );
l_root.getNode( "sub/subsub" );
assertTrue( l_root.pathExist( "sub/subsub" ) );
assertNotNull( l_root.getNode( "sub/subsub" ) );
}
}
| gpl-3.0 |
jorenham/fingerblox | FingerBlox/app/src/main/java/org/fingerblox/fingerblox/ImageDisplayActivity.java | 10748 | package org.fingerblox.fingerblox;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.github.clans.fab.FloatingActionButton;
import org.opencv.core.KeyPoint;
import org.opencv.core.Mat;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.core.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
public class ImageDisplayActivity extends AppCompatActivity {
public static final String TAG = "ImageDisplayActivity";
public File fileDir;
public final String kpFileSuffix = "_keypoints.json";
public final String descFileSuffix = "_descriptors.json";
/*
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Zebra");
setContentView(R.layout.activity_image_display);
ImageView mImageView = (ImageView) findViewById(R.id.image_view);
mImageView.setImageBitmap(ImageSingleton.image);
Context context = getApplicationContext();
fileDir = context.getFilesDir();
FloatingActionButton saveFeaturesButton = (FloatingActionButton) findViewById(R.id.btn_save_feat);
assert saveFeaturesButton != null;
saveFeaturesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openSaveDialog();
}
});
FloatingActionButton matchFeaturesButton = (FloatingActionButton) findViewById(R.id.btn_match_feat);
assert matchFeaturesButton != null;
matchFeaturesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
findMatch();
}
});
}
public void openSaveDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this, R.style.DialogTheme);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.save_dialog, null);
dialogBuilder.setView(dialogView);
final EditText fileNameEditText = (EditText) dialogView.findViewById(R.id.filename_edit_text);
dialogBuilder.setMessage("Enter a name");
dialogBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
saveFeatures(fileNameEditText.getText().toString());
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//do nothing
}
});
AlertDialog saveDialog = dialogBuilder.create();
saveDialog.show();
}
protected void saveFeatures(String fileName){
boolean saveSuccess = true;
MatOfKeyPoint keypoints = ImageProcessing.getKeypoints();
Mat descriptors = ImageProcessing.getDescriptors();
String keypointsJSON = keypointsToJSON(keypoints);
String descriptorsJSON = matToJSON(descriptors);
try{
FileWriter fw;
File keypointsFile = new File(fileDir, fileName+kpFileSuffix);
fw = new FileWriter(keypointsFile);
fw.write(keypointsJSON);
fw.flush();
fw.close();
File descriptorsFile = new File(fileDir, fileName+descFileSuffix);
fw = new FileWriter(descriptorsFile);
fw.write(descriptorsJSON);
fw.flush();
fw.close();
} catch (Exception e){
saveSuccess = false;
e.printStackTrace();
}
if(saveSuccess) {
makeToast("Save success!");
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
String fileNameList = preferences.getString("fileNameList", "");
if (fileNameList.equals("")) {
fileNameList = fileName;
} else {
fileNameList += " " + fileName;
}
SharedPreferences.Editor editor = preferences.edit();
editor.putString("fileNameList", fileNameList);
editor.apply();
}
else{
makeToast("Save failed!");
}
}
public void findMatch() {
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
String[] fileNameList = preferences.getString("fileNameList", "").split(" ");
double maxRatio = 0;
String bestFileName = null;
for (String fileName : fileNameList) {
double ratio = matchFeaturesFile(fileName);
if (ratio > maxRatio) {
maxRatio = ratio;
bestFileName = fileName;
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Match found");
builder.setMessage(String.format("%s: %s%%", bestFileName, (int) (maxRatio * 100)));
builder.setPositiveButton("OK", null);
AlertDialog dialog = builder.show();
// Must call show() prior to fetching text view
TextView messageView = (TextView)dialog.findViewById(android.R.id.message);
messageView.setGravity(Gravity.CENTER);
}
private double matchFeaturesFile(String fileName){
String[] loadedFeatures = loadFiles(fileName);
Log.d(TAG, "Features loaded from file");
Log.d(TAG, "Keypoints: "+loadedFeatures[0]);
Log.d(TAG, "Descriptors: "+loadedFeatures[1]);
MatOfKeyPoint keypointsToMatch = jsonToKeypoints(loadedFeatures[0]);
Mat descriptorsToMatch = jsonToMat(loadedFeatures[1]);
return ImageProcessing.matchFeatures(keypointsToMatch, descriptorsToMatch);
}
private String[] loadFiles(String fileName){
String[] res = new String[2];
try {
File kpFile = new File(fileDir, fileName + kpFileSuffix);
FileInputStream is = new FileInputStream(kpFile);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String kpJson = new String(buffer);
res[0] = kpJson;
} catch(Exception e){
e.printStackTrace();
}
try {
File descFile = new File(fileDir, fileName + descFileSuffix);
FileInputStream is = new FileInputStream(descFile);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String descJson = new String(buffer);
res[1] = descJson;
} catch(Exception e){
e.printStackTrace();
}
return res;
}
public String keypointsToJSON(MatOfKeyPoint kps){
Gson gson = new Gson();
JsonArray jsonArr = new JsonArray();
KeyPoint[] kpsArray = kps.toArray();
for(KeyPoint kp : kpsArray){
JsonObject obj = new JsonObject();
obj.addProperty("class_id", kp.class_id);
obj.addProperty("x", kp.pt.x);
obj.addProperty("y", kp.pt.y);
obj.addProperty("size", kp.size);
obj.addProperty("angle", kp.angle);
obj.addProperty("octave", kp.octave);
obj.addProperty("response", kp.response);
jsonArr.add(obj);
}
return gson.toJson(jsonArr);
}
public static MatOfKeyPoint jsonToKeypoints(String json){
MatOfKeyPoint result = new MatOfKeyPoint();
JsonParser parser = new JsonParser();
JsonArray jsonArr = parser.parse(json).getAsJsonArray();
int size = jsonArr.size();
KeyPoint[] kpArray = new KeyPoint[size];
for(int i=0; i<size; i++){
KeyPoint kp = new KeyPoint();
JsonObject obj = (JsonObject) jsonArr.get(i);
kp.pt = new Point(
obj.get("x").getAsDouble(),
obj.get("y").getAsDouble()
);
kp.class_id = obj.get("class_id").getAsInt();
kp.size = obj.get("size").getAsFloat();
kp.angle = obj.get("angle").getAsFloat();
kp.octave = obj.get("octave").getAsInt();
kp.response = obj.get("response").getAsFloat();
kpArray[i] = kp;
}
result.fromArray(kpArray);
return result;
}
public static String matToJSON(Mat mat){
JsonObject obj = new JsonObject();
int cols = mat.cols();
int rows = mat.rows();
int elemSize = (int) mat.elemSize();
byte[] data = new byte[cols * rows * elemSize];
mat.get(0, 0, data);
obj.addProperty("rows", mat.rows());
obj.addProperty("cols", mat.cols());
obj.addProperty("type", mat.type());
String dataString = new String(Base64.encode(data, Base64.DEFAULT));
obj.addProperty("data", dataString);
Gson gson = new Gson();
return gson.toJson(obj);
}
public static Mat jsonToMat(String json){
JsonParser parser = new JsonParser();
JsonObject JsonObject = parser.parse(json).getAsJsonObject();
int rows = JsonObject.get("rows").getAsInt();
int cols = JsonObject.get("cols").getAsInt();
int type = JsonObject.get("type").getAsInt();
String dataString = JsonObject.get("data").getAsString();
byte[] data = Base64.decode(dataString.getBytes(), Base64.DEFAULT);
Mat mat = new Mat(rows, cols, type);
mat.put(0, 0, data);
return mat;
}
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
public void makeToast(String toShow){
Toast toast = Toast.makeText(getApplicationContext(), toShow, Toast.LENGTH_SHORT);
toast.show();
}
}
| gpl-3.0 |
andersrosbaek/pixel-dungeon | src/com/watabou/noosa/tweeners/CameraScrollTweener.java | 1205 | /*
* Copyright (C) 2012-2014 Oleg Dolya
*
* 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.watabou.noosa.tweeners;
import com.watabou.noosa.Camera;
import com.watabou.utils.PointF;
public class CameraScrollTweener extends Tweener {
public Camera camera;
public PointF start;
public PointF end;
public CameraScrollTweener( Camera camera, PointF pos, float time ) {
super( camera, time );
this.camera = camera;
start = camera.scroll;
end = pos;
}
@Override
protected void updateValues( float progress ) {
camera.scroll = PointF.inter( start, end, progress );
}
}
| gpl-3.0 |
MisterKozo/SudokuSama | app/src/main/java/xyz/cornhub/sudoku/GameView.java | 11550 | package xyz.cornhub.sudoku;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.v4.internal.view.SupportMenu;
import android.support.v4.view.InputDeviceCompat;
import android.support.v4.view.ViewCompat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import java.lang.reflect.Array;
import xyz.cornhub.sudoku.Sudoku.Game;
public class GameView extends View {
private int Ax;
private int Ay;
private int Bx;
private int By;
private Canvas canvas;
public SudokuCell[][] cells = ((SudokuCell[][]) Array.newInstance(SudokuCell.class, new int[]{9, 9}));
private int height;
private int pX = -1;
private int pY = -1;
private ProgressDialog progress = new ProgressDialog(getContext());
private Paint recPaint;
public Game sudoku = new Game();
private Paint thick;
private Paint thin;
private Paint txtPaint;
private int width;
public GameView(Context context) {
super(context);
this.progress.setIcon(R.drawable.icon);
this.progress.setTitle("Please Wait");
this.progress.setMessage("Loading...");
this.progress.show();
this.sudoku.newGame();
this.progress.dismiss();
for (int y = 0; y < 9; y++) {
for (int x = 0; x < 9; x++) {
if (this.sudoku.getNumber(x, y) == 0) {
this.cells[x][y] = new SudokuCell(this.sudoku.getNumber(x, y), x, y, false);
} else {
this.cells[x][y] = new SudokuCell(this.sudoku.getNumber(x, y), x, y, true);
}
}
}
invalidate();
}
protected void onDraw(Canvas canvas) {
int x;
super.onDraw(canvas);
canvas.save();
this.canvas = canvas;
this.width = canvas.getWidth();
this.height = canvas.getHeight();
this.recPaint = new Paint();
this.txtPaint = new Paint();
this.thick = new Paint();
this.thin = new Paint();
for (int y = 0; y < 9; y++) {
for (x = 0; x < 9; x++) {
this.cells[x][y].Redraw(canvas, this.width);
}
}
this.recPaint.setColor(-1);
this.txtPaint.setColor(ViewCompat.MEASURED_STATE_MASK);
this.txtPaint.setTextSize(70.0f);
this.thick.setColor(ViewCompat.MEASURED_STATE_MASK);
this.thin.setColor(ViewCompat.MEASURED_STATE_MASK);
this.thick.setStrokeWidth(10.0f);
this.thin.setStrokeWidth(5.0f);
this.Ax = 45;
this.Ay = 45;
this.Bx = (((this.width - 90) / 9) * 9) + 45;
this.By = (((this.width - 90) / 9) * 9) + 45;
for (x = 0; x < 9; x++) {
int startVer = this.By + 45;
int endVer = (this.By + 45) + ((this.width - 90) / 9);
int startHor = (((this.width - 90) / 9) * x) + 45;
int endHor = (((this.width - 90) / 9) * (x + 1)) + 45;
int textY = (startVer + 45) + ((endVer - startVer) / 4);
int textX = startHor + ((endHor - startHor) / 4);
canvas.drawRect((float) startHor, (float) startVer, (float) endHor, (float) endVer, this.recPaint);
canvas.drawText(String.valueOf(x + 1), (float) textX, (float) textY, this.txtPaint);
canvas.drawLine(45.0f, (float) ((((this.width - 90) / 9) * x) + 45), (float) (this.width - 45), (float) ((((this.width - 90) / 9) * x) + 45), this.thin);
canvas.drawLine((float) ((((this.width - 90) / 9) * x) + 45), 45.0f, (float) ((((this.width - 90) / 9) * x) + 45), (float) ((((this.width - 90) / 9) * 9) + 45), this.thin);
}
canvas.drawLine((float) ((((this.width - 90) / 9) * 3) + 45), 45.0f, (float) ((((this.width - 90) / 9) * 3) + 45), (float) ((((this.width - 90) / 9) * 9) + 45), this.thick);
canvas.drawLine((float) ((((this.width - 90) / 9) * 6) + 45), 45.0f, (float) ((((this.width - 90) / 9) * 6) + 45), (float) ((((this.width - 90) / 9) * 9) + 45), this.thick);
canvas.drawLine(45.0f, (float) ((((this.width - 90) / 9) * 3) + 45), (float) ((((this.width - 90) / 9) * 9) + 45), (float) ((((this.width - 90) / 9) * 3) + 45), this.thick);
canvas.drawLine(45.0f, (float) ((((this.width - 90) / 9) * 6) + 45), (float) ((((this.width - 90) / 9) * 9) + 45), (float) ((((this.width - 90) / 9) * 6) + 45), this.thick);
Drawable back = getResources().getDrawable(R.drawable.back);
Drawable help = getResources().getDrawable(R.drawable.help);
Drawable solve = getResources().getDrawable(R.drawable.solve);
back.setBounds(45, this.height - 245, 245, this.height - 45);
help.setBounds((this.width / 2) - 100, this.height - 245, (this.width / 2) + 100, this.height - 45);
solve.setBounds(this.width - 245, this.height - 245, this.width - 45, this.height - 45);
back.draw(canvas);
help.draw(canvas);
solve.draw(canvas);
}
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case 0:
AnalTouch(x, y);
break;
}
return true;
}
public void RedrawBoard() {
invalidate();
}
public void AnalTouch(float touchX, float touchY) {
int ly;
int lx;
boolean freezone = true;
if (touchX >= ((float) this.Ax) && touchX <= ((float) this.Bx) && touchY >= ((float) this.Ay) && touchY <= ((float) this.By)) {
int intX = (int) ((touchX - 45.0f) / ((float) ((this.width - 90) / 9)));
int intY = (int) ((touchY - 45.0f) / ((float) ((this.width - 90) / 9)));
Log.i("tripaloski", "TOUCH: " + String.valueOf(intX) + "," + String.valueOf(intY));
this.cells[intX][intY].Press(this.cells);
RedrawBoard();
this.pX = intX;
this.pY = intY;
freezone = false;
}
if (touchX >= ((float) this.Ax) && touchX <= ((float) this.Bx) && touchY >= ((float) (this.By + 45)) && touchY <= ((float) (this.By + 155))) {
freezone = false;
int intX = (int) ((touchX - 45.0f) / ((float) ((this.width - 90) / 9)));
Log.i("tripaloski", "NUMROW: " + String.valueOf(intX + 1));
for (ly = 0; ly < 9; ly++) {
for (lx = 0; lx < 9; lx++) {
if (this.cells[lx][ly].IsPressed()) {
this.cells[lx][ly].SetNumber(intX + 1);
this.cells[lx][ly].Paint(-16711681);
Log.i("tripaloski", "Detected: " + String.valueOf(lx) + "," + String.valueOf(ly));
}
}
}
if (!(this.pX == -1 || this.pY == -1 || this.cells[this.pX][this.pY].IsHard() || !BoardFull())) {
if (IsValidBoard()) {
for (ly = 0; ly < 9; ly++) {
for (lx = 0; lx < 9; lx++) {
this.cells[lx][ly].Paint(-65281);
}
}
Toast.makeText(getContext(), "Congratulations!", 1).show();
} else {
Toast.makeText(getContext(), "Please check the board! Something is wrong with your solution.", 1).show();
}
}
invalidate();
}
if (touchY >= ((float) (this.height - 245)) && touchY <= ((float) (this.height - 45))) {
if (touchX >= 45.0f && touchX <= 245.0f) {
Log.i("tripaloski", "BACK");
freezone = false;
ly = 0;
while (ly < 9) {
lx = 0;
while (lx < 9) {
if (!this.cells[lx][ly].IsHard() && this.cells[lx][ly].IsPressed()) {
this.cells[lx][ly].SetNumber(0);
this.cells[lx][ly].Paint(-16711681);
}
lx++;
}
ly++;
}
invalidate();
}
if (touchX >= ((float) ((this.width / 2) - 100)) && touchX <= ((float) ((this.width / 2) + 100))) {
Log.i("tripaloski", "HELP");
freezone = false;
for (ly = 0; ly < 9; ly++) {
for (lx = 0; lx < 9; lx++) {
if (this.cells[lx][ly].IsPressed()) {
if (this.cells[lx][ly].GetNumber() == 0) {
this.cells[lx][ly].Paint(InputDeviceCompat.SOURCE_ANY);
} else if (IsPossible(lx, ly)) {
this.cells[lx][ly].Paint(-16711936);
} else {
this.cells[lx][ly].Paint(SupportMenu.CATEGORY_MASK);
}
}
}
}
invalidate();
}
if (touchX >= ((float) (this.width - 245)) && touchX <= ((float) (this.width - 45))) {
Log.i("tripaloski", "CLEAN");
freezone = false;
for (ly = 0; ly < 9; ly++) {
for (lx = 0; lx < 9; lx++) {
if (!this.cells[lx][ly].IsHard()) {
this.cells[lx][ly].SetNumber(0);
}
if (this.cells[lx][ly].IsPressed()) {
this.cells[lx][ly].Depress();
}
}
}
invalidate();
}
}
if (freezone) {
Log.i("tripaloski", "free");
if (this.pX != -1 && this.pY != -1) {
this.cells[this.pX][this.pY].Depress();
invalidate();
}
}
}
public boolean IsPossible(int cx, int cy) {
Log.i("tripaloski", "Checking if possible");
int y = 0;
while (y < 9) {
if (y != cy && this.cells[cx][y].GetNumber() == this.cells[cx][cy].GetNumber()) {
return false;
}
y++;
}
int x = 0;
while (x < 9) {
if (x != cx && this.cells[x][cy].GetNumber() == this.cells[cx][cy].GetNumber()) {
return false;
}
x++;
}
y = (cy / 3) * 3;
while (y < ((cy / 3) + 1) * 3) {
x = (cx / 3) * 3;
while (x < ((cx / 3) + 1) * 3) {
if ((cx != x || cy != y) && this.cells[x][y].GetNumber() == this.cells[cx][cy].GetNumber()) {
return false;
}
x++;
}
y++;
}
return true;
}
public boolean BoardFull() {
for (int y = 0; y < 9; y++) {
for (int x = 0; x < 9; x++) {
if (this.cells[x][y].GetNumber() == 0) {
return false;
}
}
}
return true;
}
public boolean IsValidBoard() {
for (int y = 0; y < 9; y++) {
for (int x = 0; x < 9; x++) {
if (!IsPossible(x, y)) {
return false;
}
}
}
return true;
}
}
| gpl-3.0 |
xabgesagtx/mensa-api | mensa-indexer/src/main/java/com/github/xabgesagtx/mensa/scrape/MensaDetailsScraper.java | 2094 | package com.github.xabgesagtx.mensa.scrape;
import com.github.xabgesagtx.mensa.scrape.model.MensaDetails;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Scrapes mensa details as the address, zipcode or the name of the city
*/
@Component
@Slf4j
public class MensaDetailsScraper extends AbstractSimpleScraper<Optional<MensaDetails>> {
private static final Pattern ZIPCODE_PATTERN = Pattern.compile("(\\d\\d\\d\\d\\d)\\s+([^\\s]+)");
@AllArgsConstructor
private class CityDetails {
private String zipcode;
private String city;
}
@Override
Optional<MensaDetails> scrapeFromDocument(Document document) {
return document.select("#cafeteria p").stream().flatMap(this::getFromCafeteriaElem).findFirst();
}
@Override
Optional<MensaDetails> getDefault() {
return Optional.empty();
}
private Stream<MensaDetails> getFromCafeteriaElem(Element elem) {
Stream<MensaDetails> result = Stream.empty();
elem.select("br").append("\\n");
List<String> lines = Stream.of(StringUtils.split(elem.text().replaceAll("\\\\n", "\n"), "\n"))
.flatMap(line -> Stream.of(StringUtils.split(line, ",")))
.map(StringUtils::trim)
.filter(StringUtils::isNotBlank)
.collect(Collectors.toList());
if (lines.size() >= 2) {
String address = lines.get(0);
result = getCityInfo(lines.get(1)).map(details -> MensaDetails.builder().address(address).city(details.city).zipcode(details.zipcode).build());
}
return result;
}
private Stream<CityDetails> getCityInfo(String line) {
Stream<CityDetails> result = Stream.empty();
Matcher matcher = ZIPCODE_PATTERN.matcher(line);
if (matcher.matches()) {
result = Stream.of(new CityDetails(matcher.group(1), matcher.group(2)));
}
return result;
}
}
| gpl-3.0 |
transwarpio/rapidminer | rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/repository/RepositoryLocation.java | 13468 | /**
* 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.repository;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.UserError;
/**
* A location in a repository. Format:
*
* //Repository/path/to/object
*
* All constructors throw IllegalArugmentExceptions if names are malformed, contain illegal
* characters etc.
*
* @author Simon Fischer, Adrian Wilke
*
*/
public class RepositoryLocation {
public static final char SEPARATOR = '/';
public static final String REPOSITORY_PREFIX = "//";
public static final String[] BLACKLISTED_STRINGS = new String[] { "/", "\\", ":", "<", ">", "*", "?", "\"", "|" };
private String repositoryName;
private String[] path;
private RepositoryAccessor accessor;
/**
* Constructs a RepositoryLocation from a string of the form //Repository/path/to/object.
*/
public RepositoryLocation(String absoluteLocation) throws MalformedRepositoryLocationException {
if (isAbsolute(absoluteLocation)) {
initializeFromAbsoluteLocation(absoluteLocation);
} else {
repositoryName = null;
initializeAbsolutePath(absoluteLocation);
}
}
/**
* Creates a RepositoryLocation for a given repository and a set of path components which will
* be concatenated by a /.
*
* @throws MalformedRepositoryLocationException
*/
public RepositoryLocation(String repositoryName, String[] pathComponents) throws MalformedRepositoryLocationException {
// actually check submitted parameters
if (repositoryName == null || repositoryName.isEmpty()) {
throw new MalformedRepositoryLocationException("repositoryName must not contain null or empty!");
}
if (pathComponents == null) {
throw new MalformedRepositoryLocationException("pathComponents must not be null!");
}
for (String pathComp : pathComponents) {
if (pathComp == null || pathComp.isEmpty()) {
throw new MalformedRepositoryLocationException("path must not contain null or empty strings!");
}
}
this.repositoryName = repositoryName;
this.path = pathComponents;
}
/**
* Appends a child entry to a given parent location. Child can be composed of subcomponents
* separated by /. Dots ("..") will resolve to the parent folder.
*
* @throws MalformedRepositoryLocationException
*/
public RepositoryLocation(RepositoryLocation parent, String childName) throws MalformedRepositoryLocationException {
this.accessor = parent.accessor;
if (isAbsolute(childName)) {
initializeFromAbsoluteLocation(childName);
} else if (childName.startsWith("" + SEPARATOR)) {
this.repositoryName = parent.repositoryName;
initializeAbsolutePath(childName);
} else {
this.repositoryName = parent.repositoryName;
String[] components = childName.split("" + SEPARATOR);
// skip empty path components
LinkedList<String> newComponents = new LinkedList<>();
for (String pathComp : parent.path) {
if (pathComp != null && !pathComp.isEmpty()) {
newComponents.add(pathComp);
}
}
for (String component : components) {
if (".".equals(component)) {
// do nothing
} else if ("..".equals(component)) {
if (!newComponents.isEmpty()) {
newComponents.removeLast();
} else {
throw new IllegalArgumentException("Cannot resolve relative location '" + childName
+ "' with respect to '" + parent + "': Too many '..'");
}
} else {
newComponents.add(component);
}
}
this.path = newComponents.toArray(new String[newComponents.size()]);
}
}
private void initializeFromAbsoluteLocation(String absoluteLocation) throws MalformedRepositoryLocationException {
if (!isAbsolute(absoluteLocation)) {
throw new MalformedRepositoryLocationException(
"Repository location '"
+ absoluteLocation
+ "' is not absolute! Absolute repository locations look for example like this: '//Repository/path/to/object'.");
}
String tmp = absoluteLocation.substring(2);
int nextSlash = tmp.indexOf(RepositoryLocation.SEPARATOR);
if (nextSlash != -1) {
repositoryName = tmp.substring(0, nextSlash);
} else {
throw new MalformedRepositoryLocationException("Malformed repositoy location '" + absoluteLocation
+ "': path component missing.");
}
initializeAbsolutePath(tmp.substring(nextSlash));
}
private void initializeAbsolutePath(String path) throws MalformedRepositoryLocationException {
if (!path.startsWith("" + SEPARATOR)) {
throw new MalformedRepositoryLocationException("No absolute path: '" + path
+ "'. Absolute paths look e.g. like this: '/path/to/object'.");
}
path = path.substring(1);
this.path = path.split("" + SEPARATOR);
}
/** Returns the absolute location of this RepoositoryLocation. */
public String getAbsoluteLocation() {
StringBuilder b = new StringBuilder();
b.append(REPOSITORY_PREFIX);
b.append(repositoryName);
for (String component : path) {
b.append(SEPARATOR);
b.append(component);
}
return b.toString();
}
/**
* Returns the repository associated with this location.
*
* @throws RepositoryException
*/
public Repository getRepository() throws RepositoryException {
return RepositoryManager.getInstance(getAccessor()).getRepository(repositoryName);
}
/** Returns the name of the repository associated with this location. */
public String getRepositoryName() {
return repositoryName;
}
/** Returns the path within the repository. */
public String getPath() {
StringBuilder b = new StringBuilder();
for (String component : path) {
b.append(SEPARATOR);
b.append(component);
}
return b.toString();
}
/**
* Locates the corresponding entry in the repository. It returns null if it doesn't exist yet.
* An exception is thrown if this location is invalid.
*
* @throws RepositoryException
* If repository can not be found or entry can not be located.
* */
public Entry locateEntry() throws RepositoryException {
Repository repos = getRepository();
if (repos != null) {
Entry entry = repos.locate(getPath());
return entry;
} else {
return null;
}
}
/** Returns the last path component. */
public String getName() {
if (path.length > 0) {
return path[path.length - 1];
} else {
return null;
}
}
public RepositoryLocation parent() {
if (path.length == 0) {
// we are at a root
return null;
} else {
String[] pathCopy = new String[path.length - 1];
System.arraycopy(path, 0, pathCopy, 0, path.length - 1);
RepositoryLocation parent;
try {
parent = new RepositoryLocation(this.repositoryName, pathCopy);
} catch (MalformedRepositoryLocationException e) {
throw new RuntimeException(e);
}
parent.setAccessor(accessor);
return parent;
}
}
@Override
public String toString() {
return getAbsoluteLocation();
}
/**
* Assume absoluteLocation == "//MyRepos/foo/bar/object" and
* relativeToFolder=//MyRepos/foo/baz/, then this method will return ../bar/object.
*/
public String makeRelative(RepositoryLocation relativeToFolder) {
// can only do something if repositories match.
if (!this.repositoryName.equals(relativeToFolder.repositoryName)) {
return getAbsoluteLocation();
}
int min = Math.min(this.path.length, relativeToFolder.path.length);
// find common prefix
int i = 0;
while (i < min && this.path[i].equals(relativeToFolder.path[i])) {
i++;
}
StringBuilder result = new StringBuilder();
// add one ../ for each excess component in relativeComponent which we have to leave
for (int j = i; j < relativeToFolder.path.length; j++) {
result.append("..");
result.append(RepositoryLocation.SEPARATOR);
}
// add components from each excess absoluteComponent
for (int j = i; j < this.path.length; j++) {
result.append(this.path[j]);
if (j < this.path.length - 1) {
result.append(RepositoryLocation.SEPARATOR);
}
}
return result.toString();
}
public static boolean isAbsolute(String loc) {
return loc.startsWith(RepositoryLocation.REPOSITORY_PREFIX);
}
/**
* Creates this folder and its parents.
*
* @throws RepositoryException
*/
public Folder createFoldersRecursively() throws RepositoryException {
Entry entry = locateEntry();
if (entry == null) {
Folder folder = parent().createFoldersRecursively();
Folder child = folder.createFolder(getName());
return child;
} else {
if (entry instanceof Folder) {
return (Folder) entry;
} else {
throw new RepositoryException(toString() + " is not a folder.");
}
}
}
@Override
public boolean equals(Object obj) {
return obj != null && this.toString().equals(obj.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
public void setAccessor(RepositoryAccessor accessor) {
this.accessor = accessor;
}
public RepositoryAccessor getAccessor() {
return accessor;
}
/**
* Checks if the given name is valid as a repository entry. Checks against a blacklist of
* characters.
*
* @param name
* @return
*/
public static boolean isNameValid(String name) {
if (name == null) {
throw new IllegalArgumentException("name must not be null!");
}
if ("".equals(name.trim())) {
return false;
}
for (String forbiddenString : BLACKLISTED_STRINGS) {
if (name.contains(forbiddenString)) {
return false;
}
}
return true;
}
/**
* Returns the sub{@link String} in the given name which is invalid or <code>null</code> if
* there are no illegal characters.
*
* @return
*/
public static String getIllegalCharacterInName(String name) {
if (name == null || "".equals(name.trim())) {
return null;
}
for (String forbiddenString : BLACKLISTED_STRINGS) {
if (name.contains(forbiddenString)) {
return forbiddenString;
}
}
return null;
}
/**
* Removes locations from list, which are already included in others.
*
* If there are any problems requesting a repository, the input is returned.
*
* Example: [/1/2/3, /1, /1/2] becomes [/1]
*/
public static List<RepositoryLocation> removeIntersectedLocations(List<RepositoryLocation> repositoryLocations) {
List<RepositoryLocation> locations = new LinkedList<>(repositoryLocations);
try {
Set<RepositoryLocation> removeSet = new HashSet<>();
for (RepositoryLocation locationA : locations) {
for (RepositoryLocation locationB : locations) {
if (!locationA.equals(locationB) && locationA.getRepository().equals(locationB.getRepository())) {
String pathA = locationA.getPath();
String pathB = locationB.getPath();
if (pathA.startsWith(pathB)
&& pathA.substring(pathB.length(), pathB.length() + 1).equals(String.valueOf(SEPARATOR))) {
removeSet.add(locationA);
}
}
}
}
locations.removeAll(removeSet);
} catch (RepositoryException e) {
return repositoryLocations;
}
return locations;
}
/**
* Returns the repository location for the provided path and operator. In case it is relative
* the operators process is used base path.
*
* @param loc
* the relative or absolute repository location path as String
* @param op
* the operator for which should be used as base path in case the location is
* relative
* @return the repository location for the specified path
* @throws UserError
* in case the location is malformed
*/
public static RepositoryLocation getRepositoryLocation(String loc, Operator op) throws UserError {
com.rapidminer.Process process = op.getProcess();
if (process != null) {
RepositoryLocation result;
try {
result = process.resolveRepositoryLocation(loc);
} catch (MalformedRepositoryLocationException e) {
throw new UserError(op, e, 319, e.getMessage());
}
result.setAccessor(process.getRepositoryAccessor());
return result;
} else {
if (RepositoryLocation.isAbsolute(loc)) {
RepositoryLocation result;
try {
result = new RepositoryLocation(loc);
} catch (MalformedRepositoryLocationException e) {
throw new UserError(op, e, 319, e.getMessage());
}
return result;
} else {
throw new UserError(op, 320, loc);
}
}
}
}
| gpl-3.0 |
GitPS/PiCasino | src/com/piindustries/picasino/blackjack/client/GuiData.java | 2459 | /*
* [Class]
* [Current Version]
* [Date last modified]
*
* Copyright 2013 - Michael Hoyt, Aaron Jensen, Andrew Reis, and Phillip Sime.
*
* This file is part of PiCasino.
*
* PiCasino 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.
*
* PiCasino 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 PiCasino. If not, see <http://www.gnu.org/licenses/>.
*/
package com.piindustries.picasino.blackjack.client;
import com.piindustries.picasino.blackjack.domain.Phase;
public class GuiData {
private Player player1;
private Player player2;
private Player player3;
private Player player4;
private Player player5;
private Player player6;
private Player player7;
private Player player8;
private Player dealer;
private Phase phase;
public Player getPlayer(int index){
switch(index){
case 1: return player1;
case 2: return player2;
case 3: return player3;
case 4: return player4;
case 5: return player5;
case 6: return player6;
case 7: return player7;
case 8: return player8;
case 0: return dealer;
default: throw new IllegalArgumentException("Player not defined at index "+index+ '.');
}
}
public void setPlayer(int index, Player toSet){
switch(index){
case 1: player1 = toSet; break;
case 2: player2 = toSet; break;
case 3: player3 = toSet; break;
case 4: player4 = toSet; break;
case 5: player5 = toSet; break;
case 6: player6 = toSet; break;
case 7: player7 = toSet; break;
case 8: player8 = toSet; break;
case 0: dealer = toSet; break;
default: throw new IllegalArgumentException("Player not defined at index "+index+ '.');
}
}
public Phase getPhase(){
return this.phase;
}
public void setPhase(Phase phase){
this.phase = phase;
}
}
| gpl-3.0 |
kamisakihideyoshi/TaipeiTechRefined | app/src/main/java/owo/npc/taipeitechrefined/course/CourseDetailActivity.java | 7564 | package owo.npc.taipeitechrefined.course;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import owo.npc.taipeitechrefined.runnable.ClassmateRunnable;
import owo.npc.taipeitechrefined.runnable.CourseDetailRunnable;
import owo.npc.taipeitechrefined.R;
import owo.npc.taipeitechrefined.utility.Utility;
import java.util.ArrayList;
public class CourseDetailActivity extends AppCompatActivity {
Toolbar mToolbar;
ProgressDialog mProgressDialog;
String courseNo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.course_detail);
Intent i = getIntent();
courseNo = i.getStringExtra("CourseNo");
if (courseNo == null) {
finish();
return;
}
mToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(mToolbar);
setActionBar();
mProgressDialog = ProgressDialog.show(this, null, getString(R.string.course_loading), true);
Thread t = new Thread(new CourseDetailRunnable(courseDetailHandler,
courseNo));
t.start();
}
public void setActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
actionBar.setTitle(R.string.course_detail_title);
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.dark_green)));
}
setStatusBarColor(getResources().getColor(R.color.dark_green));
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setStatusBarColor(int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
if (color == Color.BLACK
&& window.getNavigationBarColor() == Color.BLACK) {
window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
}
window.setStatusBarColor(color);
}
}
private void showCourseDetail(ArrayList<String> courseDetail) {
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout courseInfo = (LinearLayout) findViewById(R.id.courseInfo);
for (int i = 0; i < courseDetail.size(); i++) {
if (i == 1 || i == 2 || i == 4 || i == 6 || i == 13 || i == 14
|| i == 15 || i == 16 || i == 17) {
} else {
LinearLayout item = (LinearLayout) li.inflate(
R.layout.course_item, courseInfo, false);
TextView text = (TextView) item.findViewById(R.id.text);
text.setTextColor(getResources().getColor(R.color.darken));
text.setText(courseDetail.get(i));
courseInfo.addView(item);
}
}
}
private void showClassmates(ArrayList<String> classmateList) {
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout classmates = (LinearLayout) findViewById(R.id.classmates);
for (int i = 0; i < classmateList.size(); i++) {
LinearLayout classmate = (LinearLayout) li.inflate(
R.layout.classmate_item, classmates, false);
LinearLayout item = (LinearLayout) classmate
.findViewById(R.id.classmate_item);
if (i % 2 == 1) {
item.setBackgroundResource(R.color.cloud);
} else {
item.setBackgroundResource(R.color.white);
}
String[] temp = classmateList.get(i).split(",");
TextView text = (TextView) classmate.findViewById(R.id.sclass);
text.setText(temp[0]);
text = (TextView) classmate.findViewById(R.id.sid);
text.setText(temp[1]);
text = (TextView) classmate.findViewById(R.id.sname);
text.setText(temp[2]);
Button submit = (Button) classmate.findViewById(R.id.submit);
submit.setTag(temp[1]);
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String sid = (String) v.getTag();
Intent intent = new Intent();
intent.putExtra("sid", sid);
setResult(RESULT_OK, intent);
finish();
}
});
classmates.addView(classmate);
}
}
private Handler courseDetailHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case CourseDetailRunnable.REFRESH:
ArrayList<String> result = Utility.castListObject(msg.obj,
String.class);
if (result != null) {
showCourseDetail(result);
Thread t = new Thread(new ClassmateRunnable(
classmateHandler, courseNo));
t.start();
}
break;
case CourseDetailRunnable.ERROR:
dismissProgressDialog();
Utility.showDialog("提示", "查詢課程詳細資料時發生錯誤,請重新查詢!",
CourseDetailActivity.this);
break;
}
}
};
private Handler classmateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
dismissProgressDialog();
switch (msg.what) {
case ClassmateRunnable.REFRESH:
ArrayList<String> result = Utility.castListObject(msg.obj,
String.class);
if (result != null) {
showClassmates(result);
}
break;
case ClassmateRunnable.ERROR:
Utility.showDialog("提示", "查詢課程修課學生清單時發生錯誤,請重新查詢!",
CourseDetailActivity.this);
break;
}
}
};
private void dismissProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
if (!isFinishing()) {
mProgressDialog.dismiss();
}
}
}
}
| gpl-3.0 |
sklarman/grakn | grakn-engine/src/main/java/ai/grakn/engine/controller/TasksController.java | 11734 | /*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Grakn is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package ai.grakn.engine.controller;
import ai.grakn.engine.TaskStatus;
import ai.grakn.engine.tasks.BackgroundTask;
import ai.grakn.engine.TaskId;
import ai.grakn.engine.tasks.TaskManager;
import ai.grakn.engine.tasks.TaskSchedule;
import ai.grakn.engine.tasks.TaskState;
import ai.grakn.exception.EngineStorageException;
import ai.grakn.exception.GraknEngineServerException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import mjson.Json;
import spark.Request;
import spark.Response;
import spark.Service;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import static ai.grakn.engine.tasks.TaskSchedule.recurring;
import static ai.grakn.util.ErrorMessage.MISSING_MANDATORY_PARAMETERS;
import static ai.grakn.util.ErrorMessage.UNAVAILABLE_TASK_CLASS;
import static ai.grakn.util.REST.Request.ID_PARAMETER;
import static ai.grakn.util.REST.Request.LIMIT_PARAM;
import static ai.grakn.util.REST.Request.OFFSET_PARAM;
import static ai.grakn.util.REST.Request.TASK_CLASS_NAME_PARAMETER;
import static ai.grakn.util.REST.Request.TASK_CREATOR_PARAMETER;
import static ai.grakn.util.REST.Request.TASK_RUN_AT_PARAMETER;
import static ai.grakn.util.REST.Request.TASK_RUN_INTERVAL_PARAMETER;
import static ai.grakn.util.REST.Request.TASK_STATUS_PARAMETER;
import static ai.grakn.util.REST.WebPath.Tasks.GET;
import static ai.grakn.util.REST.WebPath.Tasks.STOP;
import static ai.grakn.util.REST.WebPath.Tasks.TASKS;
import static java.lang.Long.parseLong;
import static java.time.Instant.ofEpochMilli;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;
/**
* <p>
* Endpoints used to query and control queued background tasks.
* </p>
*
* @author Denis Lobanov, alexandraorth
*/
@Path("/tasks")
@Api(value = "/tasks", description = "Endpoints used to query and control queued background tasks.", produces = "application/json")
public class TasksController {
private final TaskManager manager;
public TasksController(Service spark, TaskManager manager) {
if (manager==null) {
throw new GraknEngineServerException(500,"Task manager has not been instantiated.");
}
this.manager = manager;
spark.get(TASKS, this::getTasks);
spark.get(GET, this::getTask);
spark.put(STOP, this::stopTask);
spark.post(TASKS, this::createTask);
spark.exception(EngineStorageException.class, (e, req, res) -> handleNotFoundInStorage(e, res));
}
@GET
@Path("/")
@ApiOperation(value = "Get tasks matching a specific TaskStatus.")
@ApiImplicitParams({
@ApiImplicitParam(name = "status", value = "TaskStatus as string.", dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "className", value = "Class name of BackgroundTask Object.", dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "creator", value = "Who instantiated these tasks.", dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "limit", value = "Limit the number of entries in the returned result.", dataType = "integer", paramType = "query"),
@ApiImplicitParam(name = "offset", value = "Use in conjunction with limit for pagination.", dataType = "integer", paramType = "query")
})
private Json getTasks(Request request, Response response) {
TaskStatus status = null;
String className = request.queryParams(TASK_CLASS_NAME_PARAMETER);
String creator = request.queryParams(TASK_CREATOR_PARAMETER);
int limit = 0;
int offset = 0;
if(request.queryParams(LIMIT_PARAM) != null) {
limit = Integer.parseInt(request.queryParams(LIMIT_PARAM));
}
if(request.queryParams(OFFSET_PARAM) != null) {
offset = Integer.parseInt(request.queryParams(OFFSET_PARAM));
}
if(request.queryParams(TASK_STATUS_PARAMETER) != null) {
status = TaskStatus.valueOf(request.queryParams(TASK_STATUS_PARAMETER));
}
Json result = Json.array();
manager.storage()
.getTasks(status, className, creator, null, limit, offset).stream()
.map(this::serialiseStateSubset)
.forEach(result::add);
response.status(200);
response.type(APPLICATION_JSON.getMimeType());
return result;
}
@GET
@Path("/{id}")
@ApiOperation(value = "Get the state of a specific task by its ID.", produces = "application/json")
@ApiImplicitParam(name = "uuid", value = "ID of task.", required = true, dataType = "string", paramType = "path")
private Json getTask(Request request, Response response) {
String id = request.params("id");
response.status(200);
response.type("application/json");
return serialiseStateFull(manager.storage().getState(TaskId.of(id)));
}
@PUT
@Path("/{id}/stop")
@ApiOperation(value = "Stop a running or paused task.")
@ApiImplicitParam(name = "uuid", value = "ID of task.", required = true, dataType = "string", paramType = "path")
private Json stopTask(Request request, Response response) {
String id = request.params(ID_PARAMETER);
manager.stopTask(TaskId.of(id));
return Json.object();
}
@POST
@Path("/")
@ApiOperation(value = "Schedule a task.")
@ApiImplicitParams({
@ApiImplicitParam(name = "className", value = "Class name of object implementing the BackgroundTask interface", required = true, dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "createdBy", value = "String representing the user scheduling this task", required = true, dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "runAt", value = "Time to run at as milliseconds since the UNIX epoch", required = true, dataType = "long", paramType = "query"),
@ApiImplicitParam(name = "interval",value = "If set the task will be marked as recurring and the value will be the time in milliseconds between repeated executions of this task. Value should be as Long.",
dataType = "long", paramType = "query"),
@ApiImplicitParam(name = "configuration", value = "JSON Object that will be given to the task as configuration.", dataType = "String", paramType = "body")
})
private Json createTask(Request request, Response response) {
String className = getMandatoryParameter(request, TASK_CLASS_NAME_PARAMETER);
String createdBy = getMandatoryParameter(request, TASK_CREATOR_PARAMETER);
String runAtTime = getMandatoryParameter(request, TASK_RUN_AT_PARAMETER);
String intervalParam = request.queryParams(TASK_RUN_INTERVAL_PARAMETER);
TaskSchedule schedule;
Json configuration;
try {
// Get the schedule of the task
Optional<Duration> optionalInterval = Optional.ofNullable(intervalParam).map(Long::valueOf).map(Duration::ofMillis);
Instant time = ofEpochMilli(parseLong(runAtTime));
schedule = optionalInterval
.map(interval -> recurring(time, interval))
.orElse(TaskSchedule.at(time));
// Get the configuration of the task
configuration = request.body().isEmpty() ? Json.object() : Json.read(request.body());
} catch (Exception e){
throw new GraknEngineServerException(400, e);
}
// Get the class of this background task
Class<?> clazz = getClass(className);
// Create and schedule the task
TaskState taskState = TaskState.of(clazz, createdBy, schedule, configuration);
manager.addTask(taskState);
// Configure the response
response.type(APPLICATION_JSON.getMimeType());
response.status(200);
return Json.object("id", taskState.getId().getValue());
}
/**
* Use reflection to get a reference to the given class. Returns a 500 to the client if the class is
* unavailable.
*
* @param className class to retrieve
* @return reference to the given class
*/
private Class<?> getClass(String className){
try {
Class<?> clazz = Class.forName(className);
if (!BackgroundTask.class.isAssignableFrom(clazz)) {
throw new GraknEngineServerException(400, UNAVAILABLE_TASK_CLASS, className);
}
return clazz;
} catch (ClassNotFoundException e) {
throw new GraknEngineServerException(400, UNAVAILABLE_TASK_CLASS, className);
}
}
/**
* Given a {@link Request} object retrieve the value of the {@param parameter} argument. If it is not present
* in the request, return a 404 to the client.
*
* @param request information about the HTTP request
* @param parameter value to retrieve from the HTTP request
* @return value of the given parameter
*/
private String getMandatoryParameter(Request request, String parameter){
return Optional.ofNullable(request.queryParams(parameter)).orElseThrow(() ->
new GraknEngineServerException(400, MISSING_MANDATORY_PARAMETERS, parameter));
}
/**
* Error accessing or retrieving a task from storage. This throws a 404 Task Not Found to the user.
* @param exception {@link EngineStorageException} thrown by the server
* @param response The response object providing functionality for modifying the response
*/
private void handleNotFoundInStorage(Exception exception, Response response){
response.status(404);
response.body(Json.object("exception", exception.getMessage()).toString());
}
// TODO: Return 'schedule' object as its own object
private Json serialiseStateSubset(TaskState state) {
return Json.object()
.set("id", state.getId().getValue())
.set("status", state.status().name())
.set("creator", state.creator())
.set("className", state.taskClass().getName())
.set("runAt", state.schedule().runAt().toEpochMilli())
.set("recurring", state.schedule().isRecurring());
}
private Json serialiseStateFull(TaskState state) {
return serialiseStateSubset(state)
.set("interval", state.schedule().interval().map(Duration::toMillis).orElse(null))
.set("recurring", state.schedule().isRecurring())
.set("exception", state.exception())
.set("stackTrace", state.stackTrace())
.set("engineID", state.engineID() != null ? state.engineID().value() : null)
.set("configuration", state.configuration());
}
}
| gpl-3.0 |
TheTransitClock/transitime | transitclockQuickStart/src/test/java/org/transitclock/testapp/AppTest.java | 2100 | /*
* This file is part of Transitime.org
*
* Transitime.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Transitime.org 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 Transitime.org . If not, see <http://www.gnu.org/licenses/>.
*/
package org.transitclock.testapp;
import org.hsqldb.server.Server;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public void testApp()
{
String dbPath = "mem:test;sql.enforce_strict_size=true";
String serverProps;
String url;
String user = "sa";
String password = "";
Server server;
boolean isNetwork = true;
boolean isHTTP = false; // Set false to test HSQL protocol, true to test HTTP, in which case you can use isUseTestServlet to target either HSQL's webserver, or the Servlet server-mode
boolean isServlet = false;
server=new Server();
server.setPort(8085);
server.setDatabaseName(0, "test");
server.setDatabasePath(0, dbPath);
server.setLogWriter(null);
server.setErrWriter(null);
server.start();
assertTrue( true );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
}
| gpl-3.0 |
kuiwang/my-dev | src/main/java/com/taobao/api/request/WaimaiOrderSingleGetRequest.java | 2079 | package com.taobao.api.request;
import java.util.Map;
import com.taobao.api.ApiRuleException;
import com.taobao.api.TaobaoRequest;
import com.taobao.api.internal.util.RequestCheckUtils;
import com.taobao.api.internal.util.TaobaoHashMap;
import com.taobao.api.response.WaimaiOrderSingleGetResponse;
/**
* TOP API: taobao.waimai.order.single.get request
*
* @author auto create
* @since 1.0, 2014-11-02 16:51:28
*/
public class WaimaiOrderSingleGetRequest implements TaobaoRequest<WaimaiOrderSingleGetResponse> {
private Map<String, String> headerMap = new TaobaoHashMap();
/**
* 订单ID
*/
private Long orderId;
private Long timestamp;
private TaobaoHashMap udfParams; // add user-defined text parameters
@Override
public void check() throws ApiRuleException {
RequestCheckUtils.checkNotEmpty(orderId, "orderId");
}
@Override
public String getApiMethodName() {
return "taobao.waimai.order.single.get";
}
@Override
public Map<String, String> getHeaderMap() {
return headerMap;
}
public Long getOrderId() {
return this.orderId;
}
@Override
public Class<WaimaiOrderSingleGetResponse> getResponseClass() {
return WaimaiOrderSingleGetResponse.class;
}
@Override
public Map<String, String> getTextParams() {
TaobaoHashMap txtParams = new TaobaoHashMap();
txtParams.put("order_id", this.orderId);
if (this.udfParams != null) {
txtParams.putAll(this.udfParams);
}
return txtParams;
}
@Override
public Long getTimestamp() {
return this.timestamp;
}
@Override
public void putOtherTextParam(String key, String value) {
if (this.udfParams == null) {
this.udfParams = new TaobaoHashMap();
}
this.udfParams.put(key, value);
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
@Override
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}
| gpl-3.0 |
sketchpunk/jniunrar | src/com/sketchpunk/jniunrar/MainActivity.java | 2828 | package com.sketchpunk.jniunrar;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.widget.ImageView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//TEST: Just simple IO between Java and C++ with JNI
//System.out.println(unrar.getVersion());
/*TEST : Get list of filtered files from the rar based on the list of EXT.
String[] ary = unrar.getEntries("/sdcard/test.rar",".JPG,.PNG,.jpeg,.gif");
if(ary != null){
System.out.println(ary.length);
for(int i=0; i < ary.length; i++){
System.out.println(ary[i]);
}//for
}//if
*/
/*TEST: Reading image out of rar, get its width+height then scale it down and display it in an image view.*/
byte[] bAry = unrar.extractEntryToArray("/sdcard/test.rar","Highschool_of_the_Dead_c29-IRF\\48.jpg");
if(bAry != null){
System.out.println(bAry.length);
ByteArrayInputStream iStream = new ByteArrayInputStream(bAry);
Bitmap bmp = null;
BitmapFactory.Options bmpOption = new BitmapFactory.Options();
bmpOption.inJustDecodeBounds = true; //we only want header info, not pixel
BitmapFactory.decodeStream(iStream,null,bmpOption);
System.out.println(bmpOption.outHeight);
System.out.println(bmpOption.outWidth);
int maxSize = 900;
int scale = 0;
if(Math.max(bmpOption.outHeight,bmpOption.outWidth) > maxSize){
if(bmpOption.outHeight > bmpOption.outWidth) scale = Math.round((float)bmpOption.outHeight / maxSize);
else scale = Math.round((float)bmpOption.outWidth / maxSize);
}//if
bmpOption.inSampleSize = scale;
bmpOption.inJustDecodeBounds = false;
bmpOption.inScaled = false;
iStream.reset();
bmp = BitmapFactory.decodeStream(iStream,null,bmpOption);
ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageBitmap(bmp);
try{
iStream.close();
}catch(Exception e){}
}else System.out.println("no data");
}//func
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| gpl-3.0 |
kiawin/bayar | src/main/java/com/senang/bayar/core/provider/GenericCreditCardPaymentProvider.java | 551 | package com.senang.bayar.core.provider;
import com.neovisionaries.i18n.CountryCode;
import java.util.Map;
import com.senang.bayar.core.invoice.Invoice.Type;
/**
* Credit card payment provider - Generic
*/
public class GenericCreditCardPaymentProvider extends CreditCardPaymentProvider {
public static final String NAME = "Generic";
public GenericCreditCardPaymentProvider(Type type, CountryCode country, Map<String, Float> fees) {
setName(NAME);
setType(type);
setCountry(country);
setFees(fees);
}
}
| gpl-3.0 |
isc-konstanz/OpenMUC | projects/driver/mbus/src/test/java/org/openmuc/framework/driver/mbus/DriverTest.java | 13450 | /*
* Copyright 2011-2021 Fraunhofer ISE
*
* This file is part of OpenMUC.
* For more information visit http://www.openmuc.org
*
* OpenMUC 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.
*
* OpenMUC 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 OpenMUC. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openmuc.framework.driver.mbus;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.powermock.api.mockito.PowerMockito.doAnswer;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.doThrow;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import java.io.IOException;
import java.io.InterruptedIOException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.openmuc.framework.config.ArgumentSyntaxException;
import org.openmuc.framework.config.DeviceScanInfo;
import org.openmuc.framework.config.ScanException;
import org.openmuc.framework.config.ScanInterruptedException;
import org.openmuc.framework.driver.spi.ConnectionException;
import org.openmuc.framework.driver.spi.DriverDeviceScanListener;
import org.openmuc.jmbus.MBusConnection;
import org.openmuc.jmbus.MBusConnection.MBusSerialBuilder;
import org.openmuc.jmbus.VariableDataStructure;
import org.openmuc.jrxtx.Parity;
import org.openmuc.jrxtx.SerialPortTimeoutException;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Driver.class, MBusConnection.class })
@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*" })
public class DriverTest {
@Test
public void testGetDriverInfo() {
assertEquals("mbus", new Driver().getInfo().getId());
}
/*
* Test the connect Method of MBusDriver without the functionality of jMBus Called the {@link #connect(String
* channelAdress, String bautrate) connect} Method
*/
@Test
public void testConnectSucceed() throws Exception {
String channelAdress = "/dev/ttyS100:5";
String bautrate = "2400";
connect(channelAdress, bautrate);
}
@Test
public void testConnectSucceedWithSecondary() throws Exception {
String channelAdress = "/dev/ttyS100:74973267a7320404";
String bautrate = "2400";
connect(channelAdress, bautrate);
}
@Test
public void testConnectionBautrateIsEmpty() throws Exception {
String channelAdress = "/dev/ttyS100:5";
String bautrate = "";
connect(channelAdress, bautrate);
}
@Test
public void TestConnectTwoTimes() throws Exception {
String channelAdress = "/dev/ttyS100:5";
String bautrate = "2400";
Driver mdriver = new Driver();
MBusConnection mockedMBusSap = PowerMockito.mock(MBusConnection.class);
PowerMockito.whenNew(MBusConnection.class).withAnyArguments().thenReturn(mockedMBusSap);
PowerMockito.doNothing().when(mockedMBusSap).linkReset(ArgumentMatchers.anyInt());
PowerMockito.when(mockedMBusSap.read(ArgumentMatchers.anyInt())).thenReturn(null);
Assert.assertNotNull(mdriver.connect(channelAdress, bautrate));
Assert.assertNotNull(mdriver.connect(channelAdress, bautrate));
}
/*
* This Testmethod will test the connect Method of MBus Driver, without testing jMBus Library functions. With
* Mockito and PowerMockito its possible to do this. At first it will create an MBusDriver Objekt. Then we mocking
* an MBusSap Objects without functionality. If new MBusSap will created, it will return the mocked Object
* "mockedMBusSap". If the linkReset Method will called, it will do nothing. If the read Method will call, we return
* null.
*/
private void connect(String deviceAddress, String bautrate) throws Exception {
Driver driver = new Driver();
MBusConnection con = mock(MBusConnection.class);
MBusSerialBuilder builder = mock(MBusSerialBuilder.class);
whenNew(MBusSerialBuilder.class).withAnyArguments().thenReturn(builder);
when(builder.setBaudrate(anyInt())).thenReturn(builder);
when(builder.setTimeout(anyInt())).thenReturn(builder);
when(builder.setParity(any(Parity.class))).thenReturn(builder);
when(builder.build()).thenReturn(con);
doNothing().when(con).linkReset(anyInt());
when(con.read(anyInt())).thenReturn(null);
assertNotNull(driver.connect(deviceAddress, bautrate));
}
@Test(expected = ArgumentSyntaxException.class)
public void testConnectionArgumentSyntaxExceptionNoPortSet() throws Exception {
String channelAdress = "/dev/ttyS100:";
String bautrate = "2400";
connect(channelAdress, bautrate);
}
@Test(expected = ArgumentSyntaxException.class)
public void testConnectWithWrongSecondary() throws Exception {
String channelAdress = "/dev/ttyS100:74973267a20404";
String bautrate = "2400";
connect(channelAdress, bautrate);
}
@Test(expected = ArgumentSyntaxException.class)
public void testConnectionChannelAddressEmpty() throws Exception {
String channelAdress = "";
String bautrate = "2400";
connect(channelAdress, bautrate);
}
@Test(expected = ArgumentSyntaxException.class)
public void testConnectionArgumentSyntaxExceptionChannelAddressWrongSyntax() throws Exception {
String channelAdress = "/dev/ttyS100:a";
String bautrate = "2400";
connect(channelAdress, bautrate);
}
@Test(expected = ArgumentSyntaxException.class)
public void testConnectionArgumentSyntaxExceptionToManyArguments() throws Exception {
String channelAdress = "/dev/ttyS100:5:1";
String bautrate = "2400";
connect(channelAdress, bautrate);
}
@Test(expected = ArgumentSyntaxException.class)
public void testConnectionArgumentSyntaxExceptionBautIsNotANumber() throws Exception {
String channelAdress = "/dev/ttyS100:5";
String bautrate = "asd";
connect(channelAdress, bautrate);
}
@Test(expected = ConnectionException.class)
public void testMBusSapLinkResetThrowsIOException() throws Exception {
Driver mdriver = new Driver();
MBusConnection mockedMBusSap = PowerMockito.mock(MBusConnection.class);
PowerMockito.whenNew(MBusConnection.class).withAnyArguments().thenReturn(mockedMBusSap);
PowerMockito.doThrow(new IOException()).when(mockedMBusSap).linkReset(ArgumentMatchers.anyInt());
PowerMockito.when(mockedMBusSap.read(ArgumentMatchers.anyInt())).thenReturn(null);
mdriver.connect("/dev/ttyS100:5", "2400:lr:sc");
}
@Test(expected = ConnectionException.class)
public void testMBusSapReadThrowsTimeoutException() throws Exception {
Driver mdriver = new Driver();
MBusConnection mockedMBusSap = PowerMockito.mock(MBusConnection.class);
PowerMockito.whenNew(MBusConnection.class).withAnyArguments().thenReturn(mockedMBusSap);
PowerMockito.doThrow(new SerialPortTimeoutException()).when(mockedMBusSap).linkReset(ArgumentMatchers.anyInt());
mdriver.connect("/dev/ttyS100:5", "2400:sc");
}
@Test(expected = ConnectionException.class)
public void testMBusSapReadThrowsTimeoutExceptionAtSecondRun() throws Exception {
MBusConnection con = mock(MBusConnection.class);
whenNew(MBusConnection.class).withAnyArguments().thenReturn(con);
doNothing().when(con).linkReset(anyInt());
when(con.read(anyInt())).thenReturn(null);
Driver mdriver = new Driver();
assertNotNull(mdriver.connect("/dev/ttyS100:5", "2400"));
doThrow(new IOException()).when(con).linkReset(anyInt());
mdriver.connect("/dev/ttyS100:5", "2400:sc");
}
// ******************* SCAN TESTS ********************//
private static void scan(String settings) throws Exception {
MBusConnection con = mock(MBusConnection.class);
PowerMockito.whenNew(MBusConnection.class).withAnyArguments().thenReturn(con);
PowerMockito.when(con.read(1)).thenReturn(new VariableDataStructure(null, 0, 0, null, null));
PowerMockito.when(con.read(250)).thenThrow(new SerialPortTimeoutException());
PowerMockito.when(con.read(anyInt())).thenThrow(new SerialPortTimeoutException());
Driver mdriver = new Driver();
mdriver.interruptDeviceScan();
mdriver.scanForDevices(settings, mock(DriverDeviceScanListener.class));
}
@Test
public void testScanForDevices() throws Exception {
scan("/dev/ttyS100:2400");
}
@Test
public void testScanForDevicesWithOutBautRate() throws Exception {
scan("/dev/ttyS100");
}
@Test(expected = ArgumentSyntaxException.class)
public void scanEmptySettings() throws Exception {
scan("");
}
@Test(expected = ArgumentSyntaxException.class)
public void testScanForDevicesBautrateIsNotANumber() throws Exception {
scan("/dev/ttyS100:aaa");
}
@Test(expected = ArgumentSyntaxException.class)
public void scanToManyArgs() throws Exception {
scan("/dev/ttyS100:2400:assda");
}
@Test(expected = ScanInterruptedException.class)
public void testInterrupedException() throws Exception {
final Driver mdriver = new Driver();
DriverDeviceScanListener ddsl = mock(DriverDeviceScanListener.class);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
mdriver.interruptDeviceScan();
return null;
}
}).when(ddsl).deviceFound(any(DeviceScanInfo.class));
MBusConnection con = mock(MBusConnection.class);
when(con.read(anyInt())).thenReturn(new VariableDataStructure(null, 0, 0, null, null));
whenNew(MBusConnection.class).withAnyArguments().thenReturn(con);
doNothing().when(con).linkReset(ArgumentMatchers.anyInt());
PowerMockito.when(con.read(ArgumentMatchers.anyInt())).thenReturn(null);
mdriver.scanForDevices("/dev/ttyS100:2400", ddsl);
}
private static MBusConnection mockNewBuilderCon() throws IOException, InterruptedIOException, Exception {
MBusSerialBuilder builder = mock(MBusSerialBuilder.class);
MBusConnection con = mock(MBusConnection.class);
doNothing().when(con).linkReset(ArgumentMatchers.anyInt());
when(con.read(ArgumentMatchers.anyInt())).thenReturn(null);
whenNew(MBusSerialBuilder.class).withAnyArguments().thenReturn(builder);
when(builder.setBaudrate(anyInt())).thenReturn(builder);
when(builder.setTimeout(anyInt())).thenReturn(builder);
when(builder.setParity(any(Parity.class))).thenReturn(builder);
when(builder.build()).thenReturn(con);
return con;
}
@Test(expected = ScanException.class)
public void scanConOpenIOException() throws Exception {
MBusSerialBuilder builder = mock(MBusSerialBuilder.class);
whenNew(MBusSerialBuilder.class).withAnyArguments().thenReturn(builder);
when(builder.setBaudrate(anyInt())).thenReturn(builder);
when(builder.setTimeout(anyInt())).thenReturn(builder);
when(builder.build()).thenThrow(new IOException());
new Driver().scanForDevices("/dev/ttyS100:2400", mock(DriverDeviceScanListener.class));
}
@Test(expected = ScanException.class)
public void testScanMBusSapReadThrowsIOException() throws Exception {
MBusConnection con = mockNewBuilderCon();
when(con.read(1)).thenReturn(new VariableDataStructure(null, 0, 0, null, null));
when(con.read(250)).thenThrow(new SerialPortTimeoutException());
when(con.read(anyInt())).thenThrow(new IOException());
final Driver mdriver = new Driver();
class InterruptScanThread implements Runnable {
@Override
public void run() {
try {
Thread.sleep(100);
mdriver.interruptDeviceScan();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
new InterruptScanThread().run();
mdriver.scanForDevices("/dev/ttyS100:2400", mock(DriverDeviceScanListener.class));
}
}
| gpl-3.0 |
FthrNature/unleashed-pixel-dungeon | src/main/java/com/shatteredpixel/pixeldungeonunleashed/actors/Char.java | 11136 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2015 Evan Debenham
*
* 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.shatteredpixel.pixeldungeonunleashed.actors;
import com.shatteredpixel.pixeldungeonunleashed.Assets;
import com.shatteredpixel.pixeldungeonunleashed.Dungeon;
import com.shatteredpixel.pixeldungeonunleashed.ResultDescriptions;
import com.shatteredpixel.pixeldungeonunleashed.actors.buffs.*;
import com.shatteredpixel.pixeldungeonunleashed.actors.hero.Hero;
import com.shatteredpixel.pixeldungeonunleashed.actors.hero.HeroSubClass;
import com.shatteredpixel.pixeldungeonunleashed.actors.mobs.Bestiary;
import com.shatteredpixel.pixeldungeonunleashed.actors.mobs.Yog;
import com.shatteredpixel.pixeldungeonunleashed.levels.Level;
import com.shatteredpixel.pixeldungeonunleashed.levels.Terrain;
import com.shatteredpixel.pixeldungeonunleashed.levels.features.Door;
import com.shatteredpixel.pixeldungeonunleashed.sprites.CharSprite;
import com.shatteredpixel.pixeldungeonunleashed.utils.GLog;
import com.shatteredpixel.pixeldungeonunleashed.utils.Utils;
import com.watabou.noosa.audio.Sample;
import com.watabou.noosa.Camera;
import com.watabou.utils.Bundlable;
import com.watabou.utils.Bundle;
import com.watabou.utils.GameMath;
import com.watabou.utils.Random;
import java.util.HashSet;
public abstract class Char extends Actor {
protected static final String TXT_HIT = "%s hit %s";
protected static final String TXT_KILL = "%s killed you...";
protected static final String TXT_DEFEAT = "%s defeated %s";
private static final String TXT_YOU_MISSED = "%s %s your attack";
private static final String TXT_SMB_MISSED = "%s %s %s's attack";
private static final String TXT_OUT_OF_PARALYSIS = "The pain snapped %s out of paralysis";
public int pos = 0;
public CharSprite sprite;
public String name = "mob";
public int HT;
public int HP;
protected float baseSpeed = 1;
public boolean paralysed = false;
public boolean rooted = false;
public boolean flying = false;
public int invisible = 0;
public int viewDistance = 8;
public boolean TYPE_ANIMAL = false;
public boolean TYPE_EVIL = false;
public boolean TYPE_UNDEAD = false;
public boolean TYPE_MINDLESS = false;
private HashSet<Buff> buffs = new HashSet<Buff>();
@Override
protected boolean act() {
Dungeon.level.updateFieldOfView( this );
return false;
}
private static final String POS = "pos";
private static final String TAG_HP = "HP";
private static final String TAG_HT = "HT";
private static final String BUFFS = "buffs";
@Override
public void storeInBundle( Bundle bundle ) {
super.storeInBundle( bundle );
bundle.put(POS, pos);
bundle.put( TAG_HP, HP );
bundle.put( TAG_HT, HT );
bundle.put( BUFFS, buffs );
}
@Override
public void restoreFromBundle( Bundle bundle ) {
super.restoreFromBundle( bundle );
pos = bundle.getInt( POS );
HP = bundle.getInt( TAG_HP );
HT = bundle.getInt( TAG_HT );
for (Bundlable b : bundle.getCollection( BUFFS )) {
if (b != null) {
((Buff)b).attachTo( this );
}
}
}
public boolean attack( Char enemy ) {
boolean visibleFight = Dungeon.visible[pos] || Dungeon.visible[enemy.pos];
if (hit( this, enemy, false )) {
if (visibleFight) {
GLog.i( TXT_HIT, name, enemy.name );
}
// FIXME
int dr = this instanceof Hero && ((Hero)this).rangedWeapon != null && ((Hero)this).subClass ==
HeroSubClass.SNIPER ? 0 : Random.IntRange( 0, enemy.dr() );
int dmg = damageRoll();
int effectiveDamage = Math.max( dmg - dr, 0 );
effectiveDamage = attackProc( enemy, effectiveDamage );
effectiveDamage = enemy.defenseProc( this, effectiveDamage );
if (visibleFight) {
Sample.INSTANCE.play( Assets.SND_HIT, 1, 1, Random.Float( 0.8f, 1.25f ) );
}
// If the enemy is already dead, interrupt the attack.
// This matters as defence procs can sometimes inflict self-damage, such as armor glyphs.
if (!enemy.isAlive()){
return true;
}
//TODO: consider revisiting this and shaking in more cases.
float shake = 0f;
if (enemy == Dungeon.hero)
shake = effectiveDamage / (enemy.HT / 4);
if (shake > 1f)
Camera.main.shake( GameMath.gate( 1, shake, 5), 0.3f );
enemy.damage( effectiveDamage, this );
if (buff(FireImbue.class) != null)
buff(FireImbue.class).proc(enemy);
if (buff(EarthImbue.class) != null)
buff(EarthImbue.class).proc(enemy);
if (enemy.sprite != null) {
enemy.sprite.bloodBurstA(sprite.center(), effectiveDamage);
enemy.sprite.flash();
}
if (!enemy.isAlive() && visibleFight) {
if (enemy == Dungeon.hero) {
if ( this instanceof Yog ) {
Dungeon.fail( Utils.format( ResultDescriptions.NAMED, name) );
} if (Bestiary.isUnique( this )) {
Dungeon.fail( Utils.format( ResultDescriptions.UNIQUE, name) );
} else {
Dungeon.fail( Utils.format( ResultDescriptions.MOB, Utils.indefinite( name )) );
}
GLog.n( TXT_KILL, name );
} else {
GLog.i( TXT_DEFEAT, name, enemy.name );
}
}
return true;
} else {
if (visibleFight) {
String defense = enemy.defenseVerb();
enemy.sprite.showStatus( CharSprite.NEUTRAL, defense );
if (this == Dungeon.hero) {
GLog.i( TXT_YOU_MISSED, enemy.name, defense );
} else {
GLog.i( TXT_SMB_MISSED, enemy.name, defense, name );
}
Sample.INSTANCE.play(Assets.SND_MISS);
}
return false;
}
}
public static boolean hit( Char attacker, Char defender, boolean magic ) {
float acuRoll = Random.Float( attacker.attackSkill( defender ) );
float defRoll = Random.Float( defender.defenseSkill( attacker ) );
if (attacker.buff(Bless.class) != null) acuRoll *= 1.20f;
if (defender.buff(Bless.class) != null) defRoll *= 1.20f;
return (magic ? acuRoll * 2 : acuRoll) >= defRoll;
}
public int attackSkill( Char target ) {
return 0;
}
public int defenseSkill( Char enemy ) {
return 0;
}
public String defenseVerb() {
return "dodged";
}
public int dr() {
return 0;
}
public int damageRoll() {
return 1;
}
public int attackProc( Char enemy, int damage ) {
return damage;
}
public int defenseProc( Char enemy, int damage ) {
return damage;
}
public float speed() {
return buff( Cripple.class ) == null ? baseSpeed : baseSpeed * 0.5f;
}
public void damage( int dmg, Object src ) {
if (HP <= 0 || dmg < 0) {
return;
}
if (this.buff(Frost.class) != null){
Buff.detach( this, Frost.class );
}
if (this.buff(MagicalSleep.class) != null){
Buff.detach(this, MagicalSleep.class);
}
Class<?> srcClass = src.getClass();
if (immunities().contains( srcClass )) {
dmg = 0;
} else if (resistances().contains( srcClass )) {
dmg = Random.IntRange( 0, dmg );
}
if (buff( Paralysis.class ) != null) {
if (Random.Int( dmg ) >= Random.Int( HP )) {
Buff.detach( this, Paralysis.class );
if (Dungeon.visible[pos]) {
GLog.i( TXT_OUT_OF_PARALYSIS, name );
}
}
}
HP -= dmg;
if (dmg > 0 || src instanceof Char) {
if (sprite != null) {
sprite.showStatus(HP > HT / 2 ?
CharSprite.WARNING :
CharSprite.NEGATIVE,
Integer.toString(dmg));
}
}
if (HP <= 0) {
die( src );
}
}
public void destroy() {
HP = 0;
Actor.remove(this);
}
public void die( Object src ) {
destroy();
if (sprite != null) {
sprite.die();
}
}
public boolean isAlive() {
return HP > 0;
}
@Override
protected void spend( float time ) {
float timeScale = 1f;
if (buff( Slow.class ) != null) {
timeScale *= 0.5f;
//slowed and chilled do not stack
} else if (buff( Chill.class ) != null) {
timeScale *= buff( Chill.class ).speedFactor();
}
if (buff( Speed.class ) != null) {
timeScale *= 2.0f;
}
super.spend( time / timeScale );
}
public HashSet<Buff> buffs() {
return buffs;
}
@SuppressWarnings("unchecked")
public <T extends Buff> HashSet<T> buffs( Class<T> c ) {
HashSet<T> filtered = new HashSet<T>();
for (Buff b : buffs) {
if (c.isInstance( b )) {
filtered.add( (T)b );
}
}
return filtered;
}
@SuppressWarnings("unchecked")
public <T extends Buff> T buff( Class<T> c ) {
for (Buff b : buffs) {
if (c.isInstance( b )) {
return (T)b;
}
}
return null;
}
public boolean isCharmedBy( Char ch ) {
int chID = ch.id();
for (Buff b : buffs) {
if (b instanceof Charm && ((Charm)b).object == chID) {
return true;
}
}
return false;
}
public void add( Buff buff ) {
buffs.add( buff );
Actor.add( buff );
if (sprite != null)
switch(buff.type){
case POSITIVE:
sprite.showStatus(CharSprite.POSITIVE, buff.toString()); break;
case NEGATIVE:
sprite.showStatus(CharSprite.NEGATIVE, buff.toString());break;
case NEUTRAL:
sprite.showStatus(CharSprite.NEUTRAL, buff.toString()); break;
case SILENT: default:
break; //show nothing
}
}
public void remove( Buff buff ) {
buffs.remove( buff );
Actor.remove( buff );
}
public void remove( Class<? extends Buff> buffClass ) {
for (Buff buff : buffs( buffClass )) {
remove( buff );
}
}
@Override
protected void onRemove() {
for (Buff buff : buffs.toArray( new Buff[0] )) {
buff.detach();
}
}
public void updateSpriteState() {
for (Buff buff:buffs) {
buff.fx( true );
}
}
public int stealth() {
return 0;
}
public void move( int step ) {
if (Level.adjacent( step, pos ) && buff( Vertigo.class ) != null) {
step = pos + Level.NEIGHBOURS8[Random.Int( 8 )];
if (!(Level.passable[step] || Level.avoid[step]) || Actor.findChar( step ) != null)
return;
}
if (Dungeon.level.map[pos] == Terrain.OPEN_DOOR) {
Door.leave( pos );
}
pos = step;
if (flying && Dungeon.level.map[pos] == Terrain.DOOR) {
Door.enter( pos );
}
if (this != Dungeon.hero) {
sprite.visible = Dungeon.visible[pos];
}
}
public int distance( Char other ) {
return Level.distance( pos, other.pos );
}
public void onMotionComplete() {
next();
}
public void onAttackComplete() {
next();
}
public void onOperateComplete() {
next();
}
private static final HashSet<Class<?>> EMPTY = new HashSet<Class<?>>();
public HashSet<Class<?>> resistances() {
return EMPTY;
}
public HashSet<Class<?>> immunities() {
return EMPTY;
}
}
| gpl-3.0 |
MHTaleb/Encologim | lib/JasperReport/src/net/sf/jasperreports/crosstabs/base/BaseCrosstabColumnCell.java | 2743 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2016 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.crosstabs.base;
import java.io.Serializable;
import net.sf.jasperreports.crosstabs.CrosstabColumnCell;
import net.sf.jasperreports.crosstabs.JRCellContents;
import net.sf.jasperreports.crosstabs.type.CrosstabColumnPositionEnum;
import net.sf.jasperreports.engine.JRConstants;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.base.JRBaseObjectFactory;
import net.sf.jasperreports.engine.util.JRCloneUtils;
/**
* @author Lucian Chirita (lucianc@users.sourceforge.net)
*/
public class BaseCrosstabColumnCell implements CrosstabColumnCell, Serializable
{
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
protected int height;
protected CrosstabColumnPositionEnum contentsPosition = CrosstabColumnPositionEnum.LEFT;
protected JRCellContents cellContents;
// used by the design implementation
protected BaseCrosstabColumnCell()
{
}
public BaseCrosstabColumnCell(CrosstabColumnCell cell, JRBaseObjectFactory factory)
{
factory.put(cell, this);
height = cell.getHeight();
contentsPosition = cell.getContentsPosition();
cellContents = factory.getCell(cell.getCellContents());
}
@Override
public int getHeight()
{
return height;
}
@Override
public CrosstabColumnPositionEnum getContentsPosition()
{
return contentsPosition;
}
@Override
public JRCellContents getCellContents()
{
return cellContents;
}
@Override
public Object clone()
{
try
{
BaseCrosstabColumnCell clone = (BaseCrosstabColumnCell) super.clone();
clone.cellContents = JRCloneUtils.nullSafeClone(cellContents);
return clone;
}
catch (CloneNotSupportedException e)
{
// never
throw new JRRuntimeException(e);
}
}
}
| gpl-3.0 |
ceskaexpedice/kramerius | search/src/java/cz/incad/Kramerius/PrintQueue.java | 6517 | /*
* Copyright (C) 2010 Pavel Stastny
*
* 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 cz.incad.Kramerius;
import java.awt.print.PrinterException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.util.List;
import java.util.logging.Level;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import cz.incad.Kramerius.backend.guice.GuiceServlet;
import cz.incad.kramerius.FedoraAccess;
import cz.incad.kramerius.ProcessSubtreeException;
import cz.incad.kramerius.SolrAccess;
import cz.incad.kramerius.printing.PrintingService;
import cz.incad.kramerius.utils.ApplicationURL;
import cz.incad.kramerius.utils.conf.KConfiguration;
import cz.incad.kramerius.utils.params.ParamsLexer;
import cz.incad.kramerius.utils.params.ParamsParser;
public class PrintQueue extends GuiceServlet {
public static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(PrintQueue.class.getName());
public static final String PID_FROM="pidFrom";
public static final String HOW_MANY="howMany";
public static final String PATH="path";
@Inject
protected PrintingService printService;
@Inject
@Named("securedFedoraAccess")
protected FedoraAccess fedoraAccess;
@Inject
protected KConfiguration configuration;
// @Inject
// @Named("new-index")
// protected SolrAccess solrAccess;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
this.print(req, resp);
} catch (ProcessSubtreeException e) {
resp.setContentType("text/plain");
resp.getWriter().println("{status:'failed'}");
LOGGER.log(Level.SEVERE,e.getMessage(),e);
} catch (NumberFormatException e) {
resp.setContentType("text/plain");
resp.getWriter().println("{status:'failed'}");
LOGGER.log(Level.SEVERE,e.getMessage(),e);
} catch (PrinterException e) {
resp.setContentType("text/plain");
resp.getWriter().println("{status:'failed'}");
LOGGER.log(Level.SEVERE,e.getMessage(),e);
} catch (PrintException e) {
resp.setContentType("text/plain");
resp.getWriter().println("{status:'failed'}");
LOGGER.log(Level.SEVERE,e.getMessage(),e);
}
}
public void print(HttpServletRequest req, HttpServletResponse resp) throws MalformedURLException, IOException, ProcessSubtreeException, NumberFormatException, PrinterException, PrintException {
String imgServletUrl = ApplicationURL.applicationURL(req)+"/img";
if ((configuration.getApplicationURL() != null) && (!configuration.getApplicationURL().equals(""))){
imgServletUrl = configuration.getApplicationURL()+"img";
}
String i18nUrl = ApplicationURL.applicationURL(req)+"/i18n";
if ((configuration.getApplicationURL() != null) && (!configuration.getApplicationURL().equals(""))){
i18nUrl = configuration.getApplicationURL()+"i18n";
}
String action = req.getParameter("action");
Action.valueOf(action).print(req,resp, this.printService,imgServletUrl, i18nUrl);
}
static enum Action {
PARENT {
@Override
protected void print(HttpServletRequest request, HttpServletResponse response, PrintingService service, String imgServlet, String i18nservlet) throws IOException, ProcessSubtreeException, PrinterException, PrintException {
String from = request.getParameter(PID_FROM);
service.printMaster(from, imgServlet, i18nservlet);
response.setContentType("text/plain");
response.getWriter().println("{status:'printing'}");
}
}, SELECTION {
@Override
protected void print(HttpServletRequest request, HttpServletResponse response, PrintingService service, String imgServlet, String i18nservlet) throws IOException, ProcessSubtreeException, PrinterException, PrintException {
try {
String par = request.getParameter("pids");
ParamsParser parser = new ParamsParser(new ParamsLexer(new StringReader(par)));
List params = parser.params();
service.printSelection((String[])params.toArray(new String[params.size()]), imgServlet, i18nservlet);
response.setContentType("text/plain");
response.getWriter().println("{status:'printing'}");
} catch (RecognitionException e) {
response.setContentType("text/plain");
response.getWriter().println("{status:'failed'}");
throw new IOException(e);
} catch (TokenStreamException e) {
response.setContentType("text/plain");
response.getWriter().println("{status:'failed'}");
throw new IOException(e);
}
}
};
protected abstract void print(HttpServletRequest request, HttpServletResponse response,PrintingService service, String imgServlet, String i18nservlet) throws IOException, ProcessSubtreeException, PrinterException, PrintException;
}
}
| gpl-3.0 |
aopi1125/OrmTest | OrmDemo/ormlite/src/main/java/com/harbor/ormlite/hello/DatabaseConfigUtil.java | 690 | package com.harbor.ormlite.hello;
import com.j256.ormlite.android.apptools.OrmLiteConfigUtil;
import java.io.IOException;
import java.sql.SQLException;
/**
* Created by Harbor on 2017/7/6.
* DatabaseConfigUtl writes a configuration file to avoid using annotation processing in runtime which is very slow
* under Android. This gains a noticeable performance improvement.
*
* The configuration file is written to /res/raw/ by default. More info at: http://ormlite.com/docs/table-config
*/
public class DatabaseConfigUtil extends OrmLiteConfigUtil {
public static void main(String[] args) throws SQLException, IOException {
writeConfigFile("ormlite_config.txt");
}
} | gpl-3.0 |
pokebyte/Spark360 | app/src/main/java/com/akop/bach/util/rss/RssChannel.java | 2004 | /*
* RssChannel.java
* Copyright (C) 2010-2014 Akop Karapetyan
*
* This file is part of Spark 360, the online gaming service client.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*
*/
package com.akop.bach.util.rss;
import java.util.ArrayList;
import android.os.Parcel;
import android.os.Parcelable;
public class RssChannel implements Parcelable
{
public String title;
public String description;
public String link;
public ArrayList<RssItem> items;
public static final Parcelable.Creator<RssChannel> CREATOR = new Parcelable.Creator<RssChannel>()
{
public RssChannel createFromParcel(Parcel in)
{
return new RssChannel(in);
}
public RssChannel[] newArray(int size)
{
return new RssChannel[size];
}
};
public RssChannel()
{
this.items = new ArrayList<RssItem>();
}
private RssChannel(Parcel in)
{
this.items = new ArrayList<RssItem>();
this.title = in.readString();
this.description = in.readString();
this.link = in.readString();
in.readTypedList(this.items, RssItem.CREATOR);
}
@Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeString(this.title);
dest.writeString(this.description);
dest.writeString(this.link);
dest.writeTypedList(this.items);
}
@Override
public int describeContents()
{
return 0;
}
} | gpl-3.0 |
dennmar/Rotated | app/src/androidTest/java/com/extracliff/rotated/ExampleInstrumentedTest.java | 712 | package com.extracliff.rotated;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.extracliff.rotated", appContext.getPackageName());
}
}
| gpl-3.0 |
YAMJ/yamj-v2 | yamj/src/main/java/com/moviejukebox/plugin/trailer/TrailersLandPlugin.java | 18535 | /*
* Copyright (c) 2004-2016 YAMJ Members
* https://github.com/orgs/YAMJ/people
*
* This file is part of the Yet Another Movie Jukebox (YAMJ) project.
*
* YAMJ 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.
*
* YAMJ 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 YAMJ. If not, see <http://www.gnu.org/licenses/>.
*
* Web: https://github.com/YAMJ/yamj-v2
*
*/
package com.moviejukebox.plugin.trailer;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.moviejukebox.model.ExtraFile;
import com.moviejukebox.model.Movie;
import com.moviejukebox.tools.PropertiesUtil;
import com.moviejukebox.tools.StringTools;
import com.moviejukebox.tools.SystemTools;
/**
* @author iuk
*/
public class TrailersLandPlugin extends TrailerPlugin {
private static final Logger LOG = LoggerFactory.getLogger(TrailersLandPlugin.class);
private static final String TL_BASE_URL = "http://www.trailersland.com/";
private static final String TL_SEARCH_URL = "cerca?ricerca=";
private static final String TL_MOVIE_URL = "film/";
private static final String TL_TRAILER_URL = "trailer/";
private static final String TL_TRAILER_FILE_URL = "wrapping/tls.php?";
private final int trailerMaxCount;
private final String trailerMaxResolution;
private final String trailerAllowedFormats;
private final String trailerPreferredLanguages;
private final String trailerPreferredTypes;
public TrailersLandPlugin() {
super();
trailersPluginName = "TrailersLand";
trailerMaxCount = PropertiesUtil.getIntProperty("trailersland.max", 3);
trailerMaxResolution = PropertiesUtil.getProperty("trailersland.maxResolution", RESOLUTION_1080P);
trailerAllowedFormats = PropertiesUtil.getProperty("trailersland.allowedFormats", "wmv,mov,mp4,avi,mkv,mpg");
trailerPreferredLanguages = PropertiesUtil.getProperty("trailersland.preferredLanguages", "ita,sub-ita,en");
trailerPreferredTypes = PropertiesUtil.getProperty("trailersland.preferredTypes", "trailer,teaser");
}
@Override
public final boolean generate(Movie movie) {
if (trailerMaxResolution.length() == 0) {
LOG.trace("No resolution provided, skipping");
return false;
}
// Set the last scan to now
movie.setTrailerLastScan(new Date().getTime());
List<TrailersLandTrailer> trailerList = getTrailerUrls(movie);
if (trailerList == null) {
LOG.error("Error while scraping");
return false;
} else if (trailerList.isEmpty()) {
LOG.debug("No trailer found");
return false;
} else {
LOG.debug("Found {} trailers", trailerList.size());
}
for (int i = trailerList.size() - 1; i >= 0; i--) {
TrailersLandTrailer tr = trailerList.get(i);
String trailerUrl = tr.getUrl();
LOG.info("Found trailer at URL {}", trailerUrl);
String trailerLabel = Integer.toString(trailerList.size() - i) + "-" + tr.getLang() + "-" + tr.getType();
ExtraFile extra = new ExtraFile();
extra.setTitle("TRAILER-" + trailerLabel);
if (isDownload()) {
if (!downloadTrailer(movie, trailerUrl, trailerLabel, extra)) {
return false;
}
} else {
extra.setFilename(trailerUrl);
movie.addExtraFile(extra);
}
}
return true;
}
@Override
public String getName() {
return "trailersland";
}
protected String getTrailersLandIdFromTitle(String title) {
String trailersLandId = Movie.UNKNOWN;
String searchUrl;
try {
searchUrl = TL_BASE_URL + TL_SEARCH_URL + URLEncoder.encode(title, "iso-8859-1");
} catch (UnsupportedEncodingException ex) {
LOG.error("Unsupported encoding, cannot build search URL", ex);
return Movie.UNKNOWN;
}
LOG.debug("Searching for movie at URL {}", searchUrl);
String xml;
try {
xml = httpClient.request(searchUrl);
} catch (IOException error) {
LOG.error("Failed retreiving TrailersLand Id for movie: {}", title);
LOG.error(SystemTools.getStackTrace(error));
return Movie.UNKNOWN;
}
int indexRes = xml.indexOf("<span class=\"info\"");
if (indexRes >= 0) {
int indexMovieUrl = xml.indexOf(TL_BASE_URL + TL_MOVIE_URL, indexRes + 1);
if (indexMovieUrl >= 0) {
int endMovieUrl = xml.indexOf('"', indexMovieUrl + 1);
if (endMovieUrl >= 0) {
trailersLandId = xml.substring(indexMovieUrl + TL_BASE_URL.length() + TL_MOVIE_URL.length(), endMovieUrl);
LOG.debug("Found Trailers Land Id '{}'", trailersLandId);
}
} else {
LOG.error("Got search result but no movie. Layout has changed?");
}
} else {
LOG.debug("No movie found with title '{}'.", title);
}
return trailersLandId;
}
protected String getTrailersLandId(Movie movie) {
String title = movie.getTitle();
String origTitle = movie.getOriginalTitle();
String trailersLandId = getTrailersLandIdFromTitle(title);
if (StringTools.isNotValidString(trailersLandId) && StringTools.isValidString(origTitle) && !title.equalsIgnoreCase(origTitle)) {
trailersLandId = getTrailersLandIdFromTitle(origTitle);
}
return trailersLandId;
}
/**
* Scrape the web page for trailer URLs
*
* @param movie
* @return
*/
protected List<TrailersLandTrailer> getTrailerUrls(Movie movie) {
List<TrailersLandTrailer> trailerList = new ArrayList<>();
String trailersLandId = movie.getId(getName());
if (StringTools.isNotValidString(trailersLandId)) {
trailersLandId = getTrailersLandId(movie);
if (StringTools.isNotValidString(trailersLandId)) {
LOG.debug("No ID found for movie {}", movie.getBaseName());
return trailerList;
}
movie.setId(getName(), trailersLandId);
}
String xml;
try {
xml = httpClient.request(TL_BASE_URL + TL_MOVIE_URL + trailersLandId);
} catch (IOException error) {
LOG.error("Failed retreiving movie details for movie: {}", movie.getTitle());
LOG.error(SystemTools.getStackTrace(error));
return trailerList;
}
int indexVideo = xml.indexOf("<div class=\"trailer_container\">");
int indexEndVideo = xml.indexOf("<div id=\"sidebar\">", indexVideo + 1);
if (indexVideo >= 0 && indexVideo < indexEndVideo) {
int nextIndex = xml.indexOf(TL_BASE_URL + TL_TRAILER_URL, indexVideo);
while (nextIndex >= 0 && nextIndex < indexEndVideo) {
int endIndex = xml.indexOf('"', nextIndex + 1);
String trailerPageUrl = xml.substring(nextIndex, endIndex);
TrailersLandTrailer tr = new TrailersLandTrailer(trailerPageUrl);
tr.parseName();
tr.setFoundOrder(nextIndex);
if (tr.validateLang() && tr.validateType()) {
if (trailerList.contains(tr)) {
LOG.debug("Duplicate trailer page (Ignoring) - URL {}", trailerPageUrl);
} else {
LOG.debug("Found trailer page - URL {}", trailerPageUrl);
trailerList.add(tr);
}
} else {
LOG.trace("Discarding page - URL {}", trailerPageUrl);
}
nextIndex = xml.indexOf(TL_BASE_URL + TL_TRAILER_URL, endIndex + 1);
}
} else {
LOG.error("Video section not found. Layout changed?");
}
Collections.sort(trailerList);
LOG.debug("Found {} trailers, maximum required is {}", trailerList.size(), trailerMaxCount);
int remaining = trailerMaxCount;
for (int i = trailerList.size() - 1; i >= 0; i--) {
if (remaining == 0) {
LOG.trace("Discarding trailer (not required): {}", trailerList.get(i));
trailerList.remove(i);
} else {
TrailersLandTrailer tr = trailerList.get(i);
String trailerXml;
String trailerPageUrl = tr.getPageUrl();
LOG.trace("Evaluating page {}", trailerPageUrl);
try {
trailerXml = httpClient.request(trailerPageUrl);
} catch (IOException error) {
LOG.error("Failed retreiving trailer details for movie: {}", movie.getTitle());
LOG.error(SystemTools.getStackTrace(error));
return null;
}
int nextIndex = trailerXml.indexOf(TL_BASE_URL + TL_TRAILER_FILE_URL);
if (nextIndex < 0) {
LOG.error("No downloadable files found. Layout changed?");
trailerList.remove(i);
} else {
boolean found = false;
while (nextIndex >= 0) {
int endIndex = trailerXml.indexOf('"', nextIndex);
String url = trailerXml.substring(nextIndex, endIndex);
LOG.trace("Evaluating url {}", url);
if (tr.candidateUrl(url) && !found) {
found = true;
remaining--;
LOG.trace("Current best url is {}", url);
}
nextIndex = trailerXml.indexOf(TL_BASE_URL + TL_TRAILER_FILE_URL, endIndex + 1);
}
if (!found) {
trailerList.remove(i);
LOG.debug("No valid url found at trailer page {}", trailerPageUrl);
}
}
}
}
return trailerList;
}
public class TrailersLandTrailer implements Comparable<TrailersLandTrailer> {
private String pageUrl;
private String url;
private String res;
private String type;
private String lang;
private int foundOrder = 0;
public TrailersLandTrailer(String pageUrl) {
this.pageUrl = pageUrl;
this.lang = Movie.UNKNOWN;
this.res = Movie.UNKNOWN;
this.type = Movie.UNKNOWN;
this.url = Movie.UNKNOWN;
}
public String getPageUrl() {
return pageUrl;
}
public void setPageUrl(String pageUrl) {
this.pageUrl = pageUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public int getFoundOrder() {
return foundOrder;
}
public void setFoundOrder(int foundOrder) {
this.foundOrder = foundOrder;
}
public void parseName() {
String trailerPageUrl = getPageUrl();
int nameIndex = TL_BASE_URL.length() + TL_TRAILER_URL.length();
// Some typo are present...
if (trailerPageUrl.indexOf("teaser", nameIndex) >= 0 || trailerPageUrl.indexOf("tesaer", nameIndex) >= 0) {
setType("teaser");
} else if (trailerPageUrl.indexOf("trailer", nameIndex) >= 0) {
setType("trailer");
}
if (trailerPageUrl.indexOf("sottotitolato", nameIndex) >= 0) {
setLang("sub-ita");
} else if (trailerPageUrl.indexOf("italiano", nameIndex) >= 0) {
setLang("ita");
} else if (trailerPageUrl.indexOf("francese", nameIndex) >= 0) {
setLang("fr");
} else {
setLang("en");
}
}
private boolean isResValid(String res) {
if (res.equals(RESOLUTION_SD)) {
return true;
}
if (res.equals(RESOLUTION_720P) && (trailerMaxResolution.equals(RESOLUTION_1080P) || trailerMaxResolution.equals(RESOLUTION_720P))) {
return true;
}
return res.equals(RESOLUTION_1080P) && trailerMaxResolution.equals(RESOLUTION_1080P);
}
private boolean isResBetter(String res) {
String thisRes = getRes();
if (StringTools.isNotValidString(res)) {
return false;
}
if (StringTools.isNotValidString(getRes())) {
return true;
}
if (thisRes.equals(RESOLUTION_1080P)) {
return false;
}
if (thisRes.equals(RESOLUTION_720P) && res.equals(RESOLUTION_1080P)) {
return true;
}
return thisRes.equals(RESOLUTION_SD) && (res.equals(RESOLUTION_1080P) || res.equals(RESOLUTION_720P));
}
public boolean candidateUrl(String url) {
int startIndex = url.indexOf("url=");
if (startIndex >= 0) {
String fileUrl = url.substring(startIndex + 4);
LOG.trace("Evaulating candidate URL {}", fileUrl);
String ext = fileUrl.substring(fileUrl.lastIndexOf('.') + 1);
if (this.evaluateAgainstList(ext, trailerAllowedFormats) < 0) {
LOG.trace("Discarding '{}' due to invalid extension.", fileUrl);
return false;
}
String params = url.substring(0, startIndex - 1);
String resolution;
if (params.contains("sd_file")) {
resolution = RESOLUTION_SD;
} else if (params.contains("480")) {
resolution = RESOLUTION_SD;
} else if (params.contains("720")) {
resolution = RESOLUTION_720P;
} else if (params.contains("1080")) {
resolution = RESOLUTION_1080P;
} else {
LOG.error("Cannot guess trailer resolution for params '{}'. Layout changed?", params);
return false;
}
LOG.trace("Resolution is {}", resolution);
if (!isResValid(resolution)) {
LOG.trace("Discarding '{}' due to resolution.", fileUrl);
return false;
}
if (!this.isResBetter(resolution)) {
LOG.trace("Discarding '{}' as it's not better than actual resolution.", fileUrl);
return false;
}
setUrl(fileUrl);
setRes(resolution);
return true;
}
LOG.error("Couldn't find trailer url. Layout changed?");
return false;
}
private int evaluateAgainstList(String what, String list) {
if (list.indexOf(',') < 0) {
return what.equalsIgnoreCase(list) ? 1 : -1;
}
StringTokenizer st = new StringTokenizer(list, ",");
int w = 1;
while (st.hasMoreTokens()) {
if (what.equalsIgnoreCase(st.nextToken())) {
return w;
}
w++;
}
return -1;
}
public boolean validateLang() {
return evaluateAgainstList(getLang(), trailerPreferredLanguages) > 0;
}
public boolean validateType() {
return evaluateAgainstList(getType(), trailerPreferredTypes) > 0;
}
@Override
public boolean equals(final Object obj) {
if (obj instanceof TrailersLandTrailer) {
final TrailersLandTrailer other = (TrailersLandTrailer) obj;
return new EqualsBuilder()
.append(res, other.res)
.append(type, other.type)
.append(lang, other.lang)
.isEquals();
}
return false;
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(res)
.append(type)
.append(lang)
.toHashCode();
}
@Override
public int compareTo(TrailersLandTrailer o) {
int diff = evaluateAgainstList(o.getLang(), trailerPreferredLanguages) - evaluateAgainstList(this.getLang(), trailerPreferredLanguages);
if (diff == 0) {
diff = evaluateAgainstList(o.getType(), trailerPreferredTypes) - evaluateAgainstList(this.getType(), trailerPreferredTypes);
if (diff == 0) {
diff = o.getFoundOrder() - this.getFoundOrder();
}
}
return diff;
}
}
}
| gpl-3.0 |
Teacher-of-Things/RPG1 | ClickListener.java | 791 | /*
* ClickListener.java
*
* Copyright 2017 Noah Dunbar
*
* This file is part of RPG1.
*
* RPG1 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.
*
* RPG1 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 RPG1. If not, see <http://www.gnu.org/licenses/>.
*
*/
public interface ClickListener{
public void onClick();
}
| gpl-3.0 |
Sarius997/shattered-ice-dungeon | src/com/shatteredicedungeon/sprites/GuardSprite.java | 1741 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2015 Evan Debenham
*
* 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.shatteredicedungeon.sprites;
import com.shatteredicedungeon.Assets;
import com.shatteredicedungeon.effects.particles.ShadowParticle;
import com.watabou.noosa.MovieClip;
import com.watabou.noosa.TextureFilm;
public class GuardSprite extends MobSprite {
public GuardSprite() {
super();
texture( Assets.GUARD );
TextureFilm frames = new TextureFilm( texture, 12, 16 );
idle = new Animation( 2, true );
idle.frames( frames, 0, 0, 0, 1, 0, 0, 1, 1 );
run = new MovieClip.Animation( 15, true );
run.frames( frames, 2, 3, 4, 5, 6, 7 );
attack = new MovieClip.Animation( 12, false );
attack.frames( frames, 8, 9, 10 );
die = new MovieClip.Animation( 8, false );
die.frames( frames, 11, 12, 13, 14 );
play( idle );
}
@Override
public void play( Animation anim ) {
if (anim == die) {
emitter().burst( ShadowParticle.UP, 4 );
}
super.play( anim );
}
} | gpl-3.0 |
isnuryusuf/ingress-indonesia-dev | apk/classes-ekstartk/com/google/a/i/a/i.java | 310 | package com.google.a.i.a;
import com.google.a.a.aa;
final class i
implements d<I, O>
{
i(aa paramaa)
{
}
public final p<O> a(I paramI)
{
return h.a(this.a.a(paramI));
}
}
/* Location: classes_dex2jar.jar
* Qualified Name: com.google.a.i.a.i
* JD-Core Version: 0.6.2
*/ | gpl-3.0 |
cvette/intellij-neos | src/main/java/de/vette/idea/neos/lang/eel/formatter/EelCodeStyleSettings.java | 1108 | /*
* IntelliJ IDEA plugin to support the Neos CMS.
* Copyright (C) 2016 Christian Vette
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vette.idea.neos.lang.eel.formatter;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CustomCodeStyleSettings;
public class EelCodeStyleSettings extends CustomCodeStyleSettings {
public EelCodeStyleSettings(CodeStyleSettings container) {
super("EelCodeStyleSettings", container);
}
}
| gpl-3.0 |
axkr/symja_android_library | symja_android_library/matheclipse-io/src/main/java/tech/tablesaw/columns/numbers/Stats.java | 4608 | /*
* 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 tech.tablesaw.columns.numbers;
import org.hipparchus.stat.descriptive.StreamingStatistics;
import tech.tablesaw.api.DoubleColumn;
import tech.tablesaw.api.NumericColumn;
import tech.tablesaw.api.StringColumn;
import tech.tablesaw.api.Table;
public class Stats {
private long n;
private double sum;
private double mean;
private double min;
private double max;
private double variance;
private double standardDeviation;
private double geometricMean;
private double quadraticMean;
private double secondMoment;
private double populationVariance;
private double sumOfLogs;
private double sumOfSquares;
private final String name;
private Stats(String name) {
this.name = name;
}
public static Stats create(final NumericColumn<?> values) {
StreamingStatistics summaryStatistics = new StreamingStatistics();
for (int i = 0; i < values.size(); i++) {
summaryStatistics.addValue(values.getDouble(i));
}
return getStats(values, summaryStatistics);
}
private static Stats getStats(NumericColumn<?> values, StreamingStatistics summaryStatistics) {
Stats stats = new Stats("Column: " + values.name());
stats.min = summaryStatistics.getMin();
stats.max = summaryStatistics.getMax();
stats.n = summaryStatistics.getN();
stats.sum = summaryStatistics.getSum();
stats.variance = summaryStatistics.getVariance();
stats.populationVariance = summaryStatistics.getPopulationVariance();
stats.quadraticMean = summaryStatistics.getQuadraticMean();
stats.geometricMean = summaryStatistics.getGeometricMean();
stats.mean = summaryStatistics.getMean();
stats.standardDeviation = summaryStatistics.getStandardDeviation();
stats.sumOfLogs = summaryStatistics.getSumOfLogs();
stats.sumOfSquares = summaryStatistics.getSumOfSquares();
stats.secondMoment = summaryStatistics.getSecondMoment();
return stats;
}
public double range() {
return (max - min);
}
public double standardDeviation() {
return standardDeviation;
}
public long n() {
return n;
}
public double mean() {
return mean;
}
public double min() {
return min;
}
public double max() {
return max;
}
public double sum() {
return sum;
}
public double variance() {
return variance;
}
public double sumOfSquares() {
return sumOfSquares;
}
public double populationVariance() {
return populationVariance;
}
public double sumOfLogs() {
return sumOfLogs;
}
public double geometricMean() {
return geometricMean;
}
public double quadraticMean() {
return quadraticMean;
}
public double secondMoment() {
return secondMoment;
}
public Table asTable() {
Table t = Table.create(name);
StringColumn measure = StringColumn.create("Measure");
DoubleColumn value = DoubleColumn.create("Value");
t.addColumns(measure);
t.addColumns(value);
measure.append("Count");
value.append(n);
measure.append("sum");
value.append(sum());
measure.append("Mean");
value.append(mean());
measure.append("Min");
value.append(min());
measure.append("Max");
value.append(max());
measure.append("Range");
value.append(range());
measure.append("Variance");
value.append(variance());
measure.append("Std. Dev");
value.append(standardDeviation());
return t;
}
public Table asTableComplete() {
Table t = asTable();
StringColumn measure = t.stringColumn("Measure");
DoubleColumn value = t.doubleColumn("Value");
measure.append("Sum of Squares");
value.append(sumOfSquares());
measure.append("Sum of Logs");
value.append(sumOfLogs());
measure.append("Population Variance");
value.append(populationVariance());
measure.append("Geometric Mean");
value.append(geometricMean());
measure.append("Quadratic Mean");
value.append(quadraticMean());
measure.append("Second Moment");
value.append(secondMoment());
return t;
}
}
| gpl-3.0 |
0x277F/Rangers | src/main/java/net/coasterman10/rangers/game/GameStateTasks.java | 120 | package net.coasterman10.rangers.game;
public interface GameStateTasks {
void start();
void onSecond();
}
| gpl-3.0 |
weibingithub/BreathApp | social_sdk_library_project/src/androidTest/java/com/hhd/social/umeng/ApplicationTest.java | 351 | package com.hhd.social.umeng;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | gpl-3.0 |
magdaaproject/magdaa-library | src/org/zeroturnaround/zip/ByteSource.java | 1771 | /**
* Copyright (C) 2012 ZeroTurnaround LLC <support@zeroturnaround.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zeroturnaround.zip;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
public class ByteSource implements ZipEntrySource {
private final String path;
private final byte[] bytes;
private final long time;
public ByteSource(String path, byte[] bytes) {
this(path, bytes, System.currentTimeMillis());
}
public ByteSource(String path, byte[] bytes, long time) {
this.path = path;
this.bytes = (byte[])bytes.clone();
this.time = time;
}
public String getPath() {
return path;
}
public ZipEntry getEntry() {
ZipEntry entry = new ZipEntry(path);
if (bytes != null) {
entry.setSize(bytes.length);
}
entry.setTime(time);
return entry;
}
public InputStream getInputStream() throws IOException {
if (bytes == null) {
return null;
}
else {
return new ByteArrayInputStream(bytes);
}
}
public String toString() {
return "ByteSource[" + path + "]";
}
}
| gpl-3.0 |
joydeepsaha05/android | src/main/java/org/amahi/anywhere/util/MediaNotificationManager.java | 12918 | /*
* Copyright (c) 2014 Amahi
*
* This file is part of Amahi.
*
* Amahi 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.
*
* Amahi 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 Amahi. If not, see <http ://www.gnu.org/licenses/>.
*/
package org.amahi.anywhere.util;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import org.amahi.anywhere.R;
import org.amahi.anywhere.service.AudioService;
/**
* Keeps track of a notification and updates it automatically for a given
* MediaSession. Maintaining a visible notification (usually) guarantees that the music service
* won't be killed during playback.
*/
public class MediaNotificationManager extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 412;
private static final int REQUEST_CODE = 100;
public static final String ACTION_PAUSE = "org.amahi.anywhere.pause";
public static final String ACTION_PLAY = "org.amahi.anywhere.play";
public static final String ACTION_PREV = "org.amahi.anywhere.prev";
public static final String ACTION_NEXT = "org.amahi.anywhere.next";
private static final String TAG = "notification_manager";
private final AudioService mService;
private MediaSessionCompat.Token mSessionToken;
private MediaControllerCompat mController;
private MediaControllerCompat.TransportControls mTransportControls;
private PlaybackStateCompat mPlaybackState;
private MediaMetadataCompat mMetadata;
private final NotificationManagerCompat mNotificationManager;
private final PendingIntent mPauseIntent;
private final PendingIntent mPlayIntent;
private final PendingIntent mPreviousIntent;
private final PendingIntent mNextIntent;
private boolean mStarted = false;
public MediaNotificationManager(AudioService service) throws RemoteException {
mService = service;
updateSessionToken();
mNotificationManager = NotificationManagerCompat.from(service);
String pkg = mService.getPackageName();
mPauseIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
new Intent(ACTION_PAUSE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
mPlayIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
new Intent(ACTION_PLAY).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
mPreviousIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
mNextIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
new Intent(ACTION_NEXT).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
// Cancel all notifications to handle the case where the Service was killed and
// restarted by the system.
mNotificationManager.cancelAll();
}
/**
* Posts the notification and starts tracking the session to keep it
* updated. The notification will automatically be removed if the session is
* destroyed before {@link #stopNotification} is called.
*/
public void startNotification() {
if (!mStarted) {
mMetadata = mController.getMetadata();
mPlaybackState = mController.getPlaybackState();
// The notification must be updated after setting started to true
Notification notification = createNotification();
if (notification != null) {
mController.registerCallback(mCb);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_NEXT);
filter.addAction(ACTION_PAUSE);
filter.addAction(ACTION_PLAY);
filter.addAction(ACTION_PREV);
mService.registerReceiver(this, filter);
mService.startForeground(NOTIFICATION_ID, notification);
mStarted = true;
}
}
}
/**
* Removes the notification and stops tracking the session. If the session
* was destroyed this has no effect.
*/
public void stopNotification() {
if (mStarted) {
mStarted = false;
mController.unregisterCallback(mCb);
try {
mNotificationManager.cancel(NOTIFICATION_ID);
mService.unregisterReceiver(this);
} catch (IllegalArgumentException ex) {
// ignore if the receiver is not registered.
}
mService.stopForeground(true);
}
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
switch (action) {
case ACTION_PAUSE:
mTransportControls.pause();
break;
case ACTION_PLAY:
mTransportControls.play();
break;
case ACTION_NEXT:
mTransportControls.skipToNext();
break;
case ACTION_PREV:
mTransportControls.skipToPrevious();
break;
default:
Log.w(TAG, "Unknown intent ignored. Action=" + action);
}
}
/**
* Update the state based on a change on the session token. Called either when
* we are running for the first time or when the media session owner has destroyed the session
* (see {@link android.media.session.MediaController.Callback#onSessionDestroyed()})
*/
private void updateSessionToken() throws RemoteException {
MediaSessionCompat.Token freshToken = mService.getSessionToken();
if (mSessionToken == null && freshToken != null ||
mSessionToken != null && !mSessionToken.equals(freshToken)) {
if (mController != null) {
mController.unregisterCallback(mCb);
}
mSessionToken = freshToken;
if (mSessionToken != null) {
mController = new MediaControllerCompat(mService, mSessionToken);
mTransportControls = mController.getTransportControls();
if (mStarted) {
mController.registerCallback(mCb);
}
}
}
}
private final MediaControllerCompat.Callback mCb = new MediaControllerCompat.Callback() {
@Override
public void onPlaybackStateChanged(@NonNull PlaybackStateCompat state) {
mPlaybackState = state;
Log.d(TAG, "Received new playback state");
if (state.getState() == PlaybackStateCompat.STATE_STOPPED ||
state.getState() == PlaybackStateCompat.STATE_NONE) {
stopNotification();
} else {
Notification notification = createNotification();
if (notification != null) {
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
}
}
@Override
public void onMetadataChanged(MediaMetadataCompat metadata) {
mMetadata = metadata;
Log.d(TAG, "Received new metadata");
Notification notification = createNotification();
if (notification != null) {
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
}
@Override
public void onSessionDestroyed() {
super.onSessionDestroyed();
Log.d(TAG, "Session was destroyed, resetting to the new session token");
try {
updateSessionToken();
} catch (RemoteException e) {
Log.e(TAG, "could not connect media controller", e);
}
}
};
private Notification createNotification() {
Log.d(TAG, "updateNotificationMetadata. mMetadata=" + mMetadata);
if (mMetadata == null || mPlaybackState == null) {
return null;
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mService);
notificationBuilder.addAction(android.R.drawable.ic_media_previous,
mService.getString(R.string.label_previous), mPreviousIntent);
addPlayPauseAction(notificationBuilder);
notificationBuilder.addAction(android.R.drawable.ic_media_next,
mService.getString(R.string.label_next), mNextIntent);
MediaDescriptionCompat description = mMetadata.getDescription();
Bitmap audioAlbumArt = mMetadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART);
if (audioAlbumArt == null) {
// use a placeholder art while the remote art is being downloaded
audioAlbumArt = BitmapFactory.decodeResource(mService.getResources(), R.drawable.default_audiotrack);
}
notificationBuilder
.setStyle(new NotificationCompat.MediaStyle()
.setShowActionsInCompactView(1) // show only play/pause in compact view
.setMediaSession(mSessionToken))
.setSmallIcon(getAudioPlayerNotificationIcon())
.setLargeIcon(getAudioPlayerNotificationArtwork(audioAlbumArt))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setUsesChronometer(true)
.setContentIntent(mService.createContentIntent())
.setContentTitle(description.getTitle())
.setContentText(description.getSubtitle());
setNotificationPlaybackState(notificationBuilder);
return notificationBuilder.build();
}
private int getAudioPlayerNotificationIcon() {
return R.drawable.ic_notification_audio;
}
private Bitmap getAudioPlayerNotificationArtwork(Bitmap audioAlbumArt) {
int iconHeight = (int) mService.getResources().getDimension(android.R.dimen.notification_large_icon_height);
int iconWidth = (int) mService.getResources().getDimension(android.R.dimen.notification_large_icon_width);
if (audioAlbumArt == null) {
return null;
}
return Bitmap.createScaledBitmap(audioAlbumArt, iconWidth, iconHeight, false);
}
private void addPlayPauseAction(NotificationCompat.Builder builder) {
Log.d(TAG, "updatePlayPauseAction");
String label;
int icon;
PendingIntent intent;
if (mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
label = mService.getString(R.string.label_pause);
icon = android.R.drawable.ic_media_pause;
intent = mPauseIntent;
} else {
label = mService.getString(R.string.label_play);
icon = android.R.drawable.ic_media_play;
intent = mPlayIntent;
}
builder.addAction(new NotificationCompat.Action(icon, label, intent));
}
private void setNotificationPlaybackState(NotificationCompat.Builder builder) {
if (mPlaybackState == null || !mStarted) {
mService.stopForeground(true);
return;
}
if (mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING
&& mPlaybackState.getPosition() >= 0) {
builder
.setWhen(System.currentTimeMillis() - mPlaybackState.getPosition())
.setShowWhen(true)
.setUsesChronometer(true);
} else {
builder
.setWhen(0)
.setShowWhen(false)
.setUsesChronometer(false);
}
// Make sure that the notification can be dismissed by the user when we are not playing:
builder.setOngoing(mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING);
}
}
| gpl-3.0 |
McoreD/TreeGUI | Android/treegui1/app/src/androidTest/java/delpach/com/treegui/ApplicationTest.java | 350 | package delpach.com.treegui;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | gpl-3.0 |
halvors/Quantum | src/main/java/org/halvors/nuclearphysics/common/grid/thermal/ThermalPhysics.java | 2236 | package org.halvors.nuclearphysics.common.grid.thermal;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
public class ThermalPhysics {
public static final int roomTemperature = 295;
public static final int iceMeltTemperature = 273;
public static final int waterBoilTemperature = 373;
/** Temperature: 0.5f = 22C
*
* @return The temperature of the coordinate in the world in kelvin.
*/
public static float getTemperatureForCoordinate(final World world, final BlockPos pos) {
final int averageTemperature = 273 + (int) ((world.getBiome(pos).getTemperature(pos) - 0.4) * 50);
final double dayNightVariance = averageTemperature * 0.05;
return (float) (averageTemperature + (world.isDaytime() ? dayNightVariance : -dayNightVariance));
}
public static double getEnergyForTemperatureChange(final float mass, final double specificHeatCapacity, final float temperature) {
return mass * specificHeatCapacity * temperature;
}
public static float getTemperatureForEnergy(final float mass, final long specificHeatCapacity, final long energy) {
return energy / (mass * specificHeatCapacity);
}
public static double getRequiredBoilWaterEnergy(final World world, final BlockPos pos) {
return getRequiredBoilWaterEnergy(world, pos, 1000);
}
public static double getRequiredBoilWaterEnergy(final World world, final BlockPos pos, final int volume) {
final float temperatureChange = waterBoilTemperature - getTemperatureForCoordinate(world, pos);
final float mass = getMass(volume, 1);
return getEnergyForTemperatureChange(mass, 4200, temperatureChange) + getEnergyForStateChange(mass, 2257000);
}
public static double getEnergyForStateChange(final float mass, final double latentHeatCapacity) {
return mass * latentHeatCapacity;
}
public static float getMass(final float volume, final float density) {
return (volume / 1000 * density);
}
public static int getMass(final FluidStack fluidStack) {
return (fluidStack.amount / 1000) * fluidStack.getFluid().getDensity(fluidStack);
}
}
| gpl-3.0 |
theHilikus/JRoboCom | jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/Player.java | 7927 | /**
*
*/
package com.github.thehilikus.jrobocom;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.thehilikus.jrobocom.exceptions.PlayerException;
import com.github.thehilikus.jrobocom.player.Bank;
import com.github.thehilikus.jrobocom.robot.Robot;
/**
* Encapsulates each team in the game
*
* @author hilikus
*/
public class Player {
static final int DEFAULT_START_STATE = 1;
private static final String PLAYER_PROPERTIES_FILE = System.getProperty("jrobocom.player-properties",
"player.properties");
private final String teamName;
private final String author;
private final Bank[] banks;
private static final Logger log = LoggerFactory.getLogger(Player.class);
private static final int ROBOTS_MAX_PRIORITY = 3;
private final ThreadGroup robotsThreads;
private final int teamId;
private static Set<Integer> teamIds = new HashSet<>();
private boolean leader = false;
/**
* The common parent of all player thread-groups
*/
public final static ThreadGroup PLAYERS_GROUP = new ThreadGroup("Players' common ancestor");
private URLClassLoader loader;
/**
* Internal constructor
*
* @param pLoader the loader used to import the code into the game
* @param codePath file system path of the location to load from
* @throws PlayerException if there's an exception loading the player's code
*/
Player(URLClassLoader pLoader, String codePath) throws PlayerException {
loader = pLoader;
if (Thread.currentThread().getPriority() < ROBOTS_MAX_PRIORITY) {
throw new PlayerException("Robot priority cannot be greater than game's");
}
try {
InputStream stream = loader.getResourceAsStream(PLAYER_PROPERTIES_FILE);
if (stream == null) {
throw new PlayerException("Player Specification File not found: " + codePath + "!"
+ PLAYER_PROPERTIES_FILE);
} else {
Properties playerInfo = new Properties();
playerInfo.load(stream);
// read parameters
author = playerInfo.getProperty("Author", "Unknown developer");
teamName = playerInfo.getProperty("Team", "Unknown team");
robotsThreads = new ThreadGroup(PLAYERS_GROUP, teamName + " Threads");
robotsThreads.setMaxPriority(ROBOTS_MAX_PRIORITY);
String banksList = playerInfo.getProperty("Banks");
if (banksList == null || banksList.isEmpty()) {
throw new PlayerException("Error loading configuration property: No banks definition found");
}
String[] banksClasses = banksList.split(",");
teamId = getNextTeamId();
teamIds.add(teamId);
banks = loadBanks(loader, banksClasses);
log.info("[Player] Successfully loaded Player: {}. Banks found = {}", this, banksClasses.length);
}
} catch (ClassCastException | IOException | ClassNotFoundException | InstantiationException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException exc) {
closeClassLoader();
throw new PlayerException("Error loading player's code", exc);
} catch (PlayerException exc) {
closeClassLoader();
throw exc;
}
}
/**
* Main constructor
*
* @param codePath path to player's code. If ends in '/' it assumes the code is in .class'es in
* a directory; otherwise assumes a jar
* @throws PlayerException if there is a problem loading the code
*/
public Player(File codePath) throws PlayerException {
this(classLoaderCreator(codePath), codePath.getAbsolutePath());
}
private static URLClassLoader classLoaderCreator(File codePath) throws PlayerException {
if (!codePath.exists() || !codePath.canRead()) {
throw new IllegalArgumentException("Path is invalid: " + codePath
+ ". It can't be read or it doesn't exist");
}
try {
return new URLClassLoader(new URL[] { codePath.toURI().toURL() });
} catch (MalformedURLException exc) {
throw new PlayerException("Error loading player's code", exc);
}
}
private static int getNextTeamId() {
int potentialTeamId;
do {
Random generator = new Random();
potentialTeamId = generator.nextInt(1000);
} while (teamIds.contains(potentialTeamId));
// found good one
return potentialTeamId;
}
private Bank[] loadBanks(SecureClassLoader pLoader, String[] banksClasses) throws ClassNotFoundException,
InstantiationException, IllegalAccessException, ClassCastException, PlayerException,
IllegalArgumentException, InvocationTargetException, SecurityException {
log.debug("[loadCode] Attempting to load code for {}", teamName);
if (banksClasses.length == 0) {
throw new PlayerException("Error loading configuration property: No banks found");
}
Bank[] playerBanks = new Bank[banksClasses.length];
for (int pos = 0; pos < playerBanks.length; pos++) {
String className = banksClasses[pos].trim();
Class<? extends Bank> bankClass = (Class<? extends Bank>) pLoader.loadClass(className);
try {
playerBanks[pos] = bankClass.getDeclaredConstructor().newInstance();
playerBanks[pos].setTeamId(teamId);
} catch (NoSuchMethodException exc) {
throw new PlayerException("Player banks need a no-arg constructor", exc);
}
}
return playerBanks;
}
/**
* @return all the banks in the player's code
*/
public Bank[] getCode() {
return banks;
}
/**
* @return the name of the player's team
*/
public String getTeamName() {
return teamName;
}
@Override
public String toString() {
return author + " (" + teamName + ")";
}
/**
* Starts the thread of a robot in the player's thread group
*
* @param newRobot the robot to start
*/
public void startRobot(Robot newRobot) {
newRobot.getData().setActiveState(DEFAULT_START_STATE);
Thread newThread = new Thread(robotsThreads, newRobot, "Bot-" + newRobot.getSerialNumber());
newThread.start(); // jumpstarts the robot
}
/**
* Creates a list of players using the paths provided
*
* @param playersFiles list of paths (jars or dirs) to the players code
* @return list of all created players
* @throws PlayerException if there was a problem loading one of the players
*/
public static List<Player> loadPlayers(List<String> playersFiles) throws PlayerException {
log.info("[loadPlayers] Loading all players");
List<Player> players = new ArrayList<>();
if (playersFiles.size() < 1) {
log.warn("[loadPlayers] No players to load");
}
for (String singlePath : playersFiles) {
Player single = new Player(new File(singlePath));
players.add(single);
}
return players;
}
/**
* @return the robot's creator
*/
public String getAuthor() {
return author;
}
/**
* @return the unique team identification for this player
*/
public int getTeamId() {
return teamId;
}
/**
* Releases the player resources
*/
public void clean() {
log.info("[clean] Cleaning player {}", this);
closeClassLoader();
}
private void closeClassLoader() {
if (loader != null) {
try {
loader.close();
} catch (IOException exc) {
log.error("[clean] Problem closing class loader of " + this, exc);
}
}
}
/**
* @return the leader
*/
public boolean isLeader() {
return leader;
}
/**
* @param leader true if the player is one of the leaders now
*/
public void setLeader(boolean leader) {
this.leader = leader;
}
}
| gpl-3.0 |
turnus/turnus | turnus.model/src/turnus/model/analysis/buffers/OptimalBufferData.java | 4167 | /*
* TURNUS - www.turnus.co
*
* Copyright (C) 2010-2016 EPFL SCI STI MM
*
* This file is part of TURNUS.
*
* TURNUS 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.
*
* TURNUS 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 TURNUS. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining it
* with Eclipse (or a modified version of Eclipse or an Eclipse plugin or
* an Eclipse library), containing parts covered by the terms of the
* Eclipse Public License (EPL), the licensors of this Program grant you
* additional permission to convey the resulting work. Corresponding Source
* for a non-source form of such a combination shall include the source code
* for the parts of Eclipse libraries used as well as that of the covered work.
*
*/
package turnus.model.analysis.buffers;
import org.eclipse.emf.ecore.EObject;
import turnus.model.analysis.bottlenecks.BottlenecksWithSchedulingReport;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Optimal Buffer Data</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link turnus.model.analysis.buffers.OptimalBufferData#getBufferData <em>Buffer Data</em>}</li>
* <li>{@link turnus.model.analysis.buffers.OptimalBufferData#getBottlenecksData <em>Bottlenecks Data</em>}</li>
* </ul>
*
* @see turnus.model.analysis.buffers.BuffersPackage#getOptimalBufferData()
* @model
* @generated
*/
public interface OptimalBufferData extends EObject {
/**
* Returns the value of the '<em><b>Buffer Data</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Buffer Data</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Buffer Data</em>' containment reference.
* @see #setBufferData(BoundedBuffersReport)
* @see turnus.model.analysis.buffers.BuffersPackage#getOptimalBufferData_BufferData()
* @model containment="true"
* @generated
*/
BoundedBuffersReport getBufferData();
/**
* Sets the value of the '{@link turnus.model.analysis.buffers.OptimalBufferData#getBufferData <em>Buffer Data</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Buffer Data</em>' containment reference.
* @see #getBufferData()
* @generated
*/
void setBufferData(BoundedBuffersReport value);
/**
* Returns the value of the '<em><b>Bottlenecks Data</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Bottlenecks Data</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Bottlenecks Data</em>' containment reference.
* @see #setBottlenecksData(BottlenecksWithSchedulingReport)
* @see turnus.model.analysis.buffers.BuffersPackage#getOptimalBufferData_BottlenecksData()
* @model containment="true"
* @generated
*/
BottlenecksWithSchedulingReport getBottlenecksData();
/**
* Sets the value of the '{@link turnus.model.analysis.buffers.OptimalBufferData#getBottlenecksData <em>Bottlenecks Data</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Bottlenecks Data</em>' containment reference.
* @see #getBottlenecksData()
* @generated
*/
void setBottlenecksData(BottlenecksWithSchedulingReport value);
} // OptimalBufferData
| gpl-3.0 |
MoreThanHidden/BluePower | src/main/java/com/bluepowermod/helper/ItemStackHelper.java | 2780 | /*
* This file is part of Blue Power. Blue Power 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. Blue Power 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 Blue Power. If not, see <http://www.gnu.org/licenses/>
*/
package com.bluepowermod.helper;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import com.bluepowermod.util.ItemStackUtils;
public class ItemStackHelper {
/**
* compares ItemStack argument to the instance ItemStack; returns true if both ItemStacks are equal
*/
public static boolean areItemStacksEqual(ItemStack itemStack1, ItemStack itemStack2) {
return itemStack1.isEmpty() && itemStack2.isEmpty() || !(itemStack1.isEmpty() || itemStack2.isEmpty())
&& itemStack1.getItem() == itemStack2.getItem() && itemStack1.getItemDamage() == itemStack2.getItemDamage()
&& !(itemStack1.getTagCompound() == null && itemStack2.getTagCompound() != null)
&& (itemStack1.getTagCompound() == null || itemStack1.getTagCompound().equals(itemStack2.getTagCompound()));
}
/**
* Mode is a WidgetFuzzySetting mode.
*
* @param stack1
* @param stack2
* @param mode
* @return
*/
public static boolean areStacksEqual(ItemStack stack1, ItemStack stack2, int mode) {
if (stack1.isEmpty() && !stack2.isEmpty())
return false;
if (!stack1.isEmpty() && stack2.isEmpty())
return false;
if (stack1.isEmpty() && stack2.isEmpty())
return true;
if (mode == 0) {
return OreDictionary.itemMatches(stack1, stack2, false);
} else if (mode == 1) {
return ItemStackUtils.isItemFuzzyEqual(stack1, stack2);
} else {
return OreDictionary.itemMatches(stack1, stack2, false) && ItemStack.areItemStackTagsEqual(stack1, stack2);
}
}
public static boolean canStack(ItemStack stack1, ItemStack stack2) {
return stack1 == ItemStack.EMPTY || stack2 == ItemStack.EMPTY ||
(stack1.getItem() == stack2.getItem() &&
(!stack2.getHasSubtypes() || stack2.getItemDamage() == stack1.getItemDamage()) &&
ItemStack.areItemStackTagsEqual(stack2, stack1)) &&
stack1.isStackable();
}
}
| gpl-3.0 |
wesklei/BAN2 | src/main/java/com/br/me/trabalho_ban2/controller/CursoController.java | 5373 | package com.br.me.trabalho_ban2.controller;
import com.br.me.trabalho_ban2.model.Curso;
import com.br.me.trabalho_ban2.controller.util.JsfUtil;
import com.br.me.trabalho_ban2.controller.util.JsfUtil.PersistAction;
import com.br.me.trabalho_ban2.controller.session.CursoFacade;
import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
@Named("cursoController")
@SessionScoped
public class CursoController implements Serializable {
@EJB
private com.br.me.trabalho_ban2.controller.session.CursoFacade ejbFacade;
private List<Curso> items = null;
private Curso selected;
public CursoController() {
}
public Curso getSelected() {
return selected;
}
public void setSelected(Curso selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
private CursoFacade getFacade() {
return ejbFacade;
}
public Curso prepareCreate() {
selected = new Curso();
initializeEmbeddableKey();
return selected;
}
public void create() {
persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("CursoCreated"));
if (!JsfUtil.isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
}
}
public void update() {
persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("CursoUpdated"));
}
public void destroy() {
persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("CursoDeleted"));
if (!JsfUtil.isValidationFailed()) {
selected = null; // Remove selection
items = null; // Invalidate list of items to trigger re-query.
}
}
public List<Curso> getItems() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
getFacade().edit(selected);
} else {
getFacade().remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = ex.getCause();
if (cause != null) {
msg = cause.getLocalizedMessage();
}
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
public Curso getCurso(java.lang.Integer id) {
return getFacade().find(id);
}
public List<Curso> getItemsAvailableSelectMany() {
return getFacade().findAll();
}
public List<Curso> getItemsAvailableSelectOne() {
return getFacade().findAll();
}
@FacesConverter(forClass = Curso.class)
public static class CursoControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
CursoController controller = (CursoController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "cursoController");
return controller.getCurso(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Curso) {
Curso o = (Curso) object;
return getStringKey(o.getIdCurso());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Curso.class.getName()});
return null;
}
}
}
}
| gpl-3.0 |
exteso/alf.io | src/main/java/alfio/controller/api/admin/LocationApiController.java | 3593 | /**
* 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.controller.api.admin;
import alfio.manager.system.ConfigurationLevel;
import alfio.manager.system.ConfigurationManager;
import alfio.model.modification.support.LocationDescriptor;
import alfio.model.system.ConfigurationKeys;
import com.moodysalem.TimezoneMapper;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.time.ZoneId;
import java.util.*;
import static alfio.model.system.ConfigurationKeys.*;
@RestController
@RequestMapping("/admin/api")
@Log4j2
public class LocationApiController {
private final ConfigurationManager configurationManager;
@Autowired
public LocationApiController(ConfigurationManager configurationManager) {
this.configurationManager = configurationManager;
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String unhandledException(Exception e) {
log.error("Exception in location api", e);
return e.getMessage();
}
@GetMapping("/location/timezones")
public List<String> getTimezones() {
List<String> s = new ArrayList<>(ZoneId.getAvailableZoneIds());
s.sort(String::compareTo);
return s;
}
@GetMapping("/location/timezone")
public String getTimezone(@RequestParam("lat") double lat, @RequestParam("lng") double lng) {
String tzId = TimezoneMapper.tzNameAt(lat, lng);
return getTimezones().contains(tzId) ? tzId : null;
}
@GetMapping("/location/static-map-image")
public String getMapImage(
@RequestParam(name = "lat", required = false) String lat,
@RequestParam(name = "lng", required = false) String lng) {
return LocationDescriptor.getMapUrl(lat, lng, getGeoConf());
}
private Map<ConfigurationKeys, ConfigurationManager.MaybeConfiguration> getGeoConf() {
var keys = Set.of(MAPS_PROVIDER, MAPS_CLIENT_API_KEY, MAPS_HERE_API_KEY);
return configurationManager.getFor(keys, ConfigurationLevel.system());
}
@GetMapping("/location/map-provider-client-api-key")
public ProviderAndKeys getGeoInfoProviderAndKeys() {
var geoInfoConfiguration = getGeoConf();
ConfigurationKeys.GeoInfoProvider provider = LocationDescriptor.getProvider(geoInfoConfiguration);
Map<ConfigurationKeys, String> apiKeys = new EnumMap<>(ConfigurationKeys.class);
geoInfoConfiguration.forEach((k,v) -> v.getValue().ifPresent(value -> apiKeys.put(k, value)));
return new ProviderAndKeys(provider, apiKeys);
}
@AllArgsConstructor
@Getter
public static class ProviderAndKeys {
private final ConfigurationKeys.GeoInfoProvider provider;
private Map<ConfigurationKeys, String> keys;
}
}
| gpl-3.0 |
StarTux/Home | src/main/java/com/cavetale/home/HomeCommand.java | 494 | package com.cavetale.home;
import com.cavetale.core.command.AbstractCommand;
public final class HomeCommand extends AbstractCommand<HomePlugin> {
protected HomeCommand(final HomePlugin plugin) {
super(plugin, "home");
}
@Override
protected void onEnable() {
rootNode.arguments("[home]")
.description("Visit your home")
.completers(plugin.homesCommand::completeUsableHomes)
.playerCaller(plugin.homesCommand::home);
}
}
| gpl-3.0 |
dested/Spoke-in-Craftbook | src/circuits/com/sk89q/craftbook/Spoke/BuildExpressions.java | 65948 | package com.sk89q.craftbook.Spoke;
import org.bukkit.material.Button;
import org.bukkit.craftbukkit.block.CraftSign;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.print.attribute.standard.MediaSize.Other;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.*;
import com.sk89q.craftbook.Spoke.ALH.Aggregator;
import com.sk89q.craftbook.Spoke.ALH.Finder;
import com.sk89q.craftbook.Spoke.ClassInfo.ClassWithLines;
import com.sk89q.craftbook.Spoke.ClassInfo.EnumWithLines;
import com.sk89q.craftbook.Spoke.ClassInfo.GlobalsWithLines;
import com.sk89q.craftbook.Spoke.ClassInfo.MethodWithLines;
import com.sk89q.craftbook.Spoke.SpokeExpressions.*;
import com.sk89q.craftbook.Spoke.SpokeInstructions.ParamEter;
import com.sk89q.craftbook.Spoke.SpokeInstructions.SpokeObject;
import com.sk89q.craftbook.Spoke.Tokens.*;
import com.sk89q.craftbook.bukkit.AsyncBlockChange;
import com.sk89q.craftbook.bukkit.CircuitsPlugin;
import com.sun.net.ssl.internal.ssl.Debug;
import com.sun.org.apache.bcel.internal.generic.GETSTATIC;
public class BuildExpressions {
private String CurMethodName;
public Tuple3<ArrayList<SpokeClass>, ArrayList<SpokeEnum>, SpokeGlobal> build(
Server server,
final CircuitsPlugin plugin,
String worldName,
Tuple5<ArrayList<ClassWithLines>, ArrayList<EnumWithLines>, ArrayList<GlobalsWithLines>, ArrayList<TokenMacroPiece>, IToken[]> classes2)
throws SpokeException {
allMacros_ = classes2.Item4;
if (allMacros_ == null) {
allMacros_ = new ArrayList<TokenMacroPiece>();
}
final World world = server.getWorld(worldName);
ArrayList<SpokeClass> classes = new ArrayList<SpokeClass>();
ArrayList<SpokeGlobal> globs = new ArrayList<SpokeGlobal>();
SpokeClass cl = new SpokeClass();
classes.add(cl);
cl.Name = "Array";
cl.Methods = new ArrayList<SpokeMethod>(
Arrays.asList(new SpokeMethod[] {
new SpokeMethod(
".ctor",
cl,
new SpokeType(ObjectType.Object),
new SpokeMethodParameter[] { new SpokeMethodParameter(
"this",
new SpokeType(ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
return parameters[0];
}
@Override
public String getMethodName() {
return ".ctor";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Object);
}
@Override
public Integer getMethodIndex() {
return 0;
}
}),
new SpokeMethod("add", cl, new SpokeType(
ObjectType.Void), new SpokeMethodParameter[] {
new SpokeMethodParameter("this", new SpokeType(
ObjectType.Array)),
new SpokeMethodParameter("v", new SpokeType(
ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
parameters[0].ArrayItems
.add(parameters[1]);
return null;
}
@Override
public String getMethodName() {
return "add";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Void);
}
@Override
public Integer getMethodIndex() {
return 1;
}
})
,
new SpokeMethod(
"clear",
cl,
new SpokeType(ObjectType.Void),
new SpokeMethodParameter[] { new SpokeMethodParameter(
"this", new SpokeType(ObjectType.Array)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
parameters[0].ArrayItems.clear();
return null;
}
@Override
public String getMethodName() {
return "clear";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Void);
}
@Override
public Integer getMethodIndex() {
return 2;
}
})
,
new SpokeMethod(
"length",
cl,
new SpokeType(ObjectType.Int),
new SpokeMethodParameter[] { new SpokeMethodParameter(
"this", new SpokeType(ObjectType.Array)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
return new SpokeObject(
parameters[0].ArrayItems.size());
}
@Override
public String getMethodName() {
return "length";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Int);
}
@Override
public Integer getMethodIndex() {
return 3;
}
})
,
new SpokeMethod("remove", cl, new SpokeType(
ObjectType.Void), new SpokeMethodParameter[] {
new SpokeMethodParameter("this", new SpokeType(
ObjectType.Array)),
new SpokeMethodParameter("v", new SpokeType(
ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
// TODO: a[0].ArrayItems.RemoveAll(b =>
// SpokeObject.Compare(b,a[1]));
;
return null;
}
@Override
public String getMethodName() {
return "remove";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Void);
}
@Override
public Integer getMethodIndex() {
return 4;
}
})
,
new SpokeMethod(
"last",
cl,
new SpokeType(ObjectType.Object),
new SpokeMethodParameter[] { new SpokeMethodParameter(
"this", new SpokeType(ObjectType.Array)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
return parameters[0].ArrayItems
.get(parameters[0].ArrayItems
.size() - 1);
}
@Override
public String getMethodName() {
return "last";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Object);
}
@Override
public Integer getMethodIndex() {
return 5;
}
})
,
new SpokeMethod(
"first",
cl,
new SpokeType(ObjectType.Object),
new SpokeMethodParameter[] { new SpokeMethodParameter(
"this", new SpokeType(ObjectType.Array)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
return (parameters[0].ArrayItems.get(0));
}
@Override
public String getMethodName() {
return "first";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Object);
}
@Override
public Integer getMethodIndex() {
return 6;
}
})
,
new SpokeMethod("insert", cl, new SpokeType(
ObjectType.Void), new SpokeMethodParameter[] {
new SpokeMethodParameter("this", new SpokeType(
ObjectType.Array)),
new SpokeMethodParameter("v", new SpokeType(
ObjectType.Int)),
new SpokeMethodParameter("v2", new SpokeType(
ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
parameters[0].ArrayItems.add(
parameters[1].IntVal,
parameters[2]);
return null;
}
@Override
public String getMethodName() {
return "insert";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Void);
}
@Override
public Integer getMethodIndex() {
return 7;
}
}),
new SpokeMethod("contains", cl, new SpokeType(
ObjectType.Bool), new SpokeMethodParameter[] {
new SpokeMethodParameter("this", new SpokeType(
ObjectType.Array)),
new SpokeMethodParameter("v", new SpokeType(
ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
for (SpokeObject s : parameters[0].ArrayItems) {
if (s.Compare(parameters[1])) {
return new SpokeObject(true);
}
}
return new SpokeObject(false);
}
@Override
public String getMethodName() {
return "contains";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Bool);
}
@Override
public Integer getMethodIndex() {
return 8;
}
}),
new SpokeMethod("indexOf", cl, new SpokeType(
ObjectType.Int), new SpokeMethodParameter[] {
new SpokeMethodParameter("this", new SpokeType(
ObjectType.Array)),
new SpokeMethodParameter("v", new SpokeType(
ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
int index = 0;
for (SpokeObject s : parameters[0].ArrayItems) {
if (s.Compare(parameters[1])) {
return new SpokeObject(index);
}
index++;
}
return new SpokeObject(-1);
}
@Override
public String getMethodName() {
return "indexOf";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Int);
}
@Override
public Integer getMethodIndex() {
return 9;
}
})
}));
cl = new SpokeClass();
classes.add(cl);
cl.Name = "Sign";
cl.Variables = new String[1];
cl.Variables[0] = "signData";
cl.Methods = new ArrayList<SpokeMethod>(
Arrays.asList(new SpokeMethod[] {
new SpokeMethod(
".ctor",
cl,
new SpokeType(ObjectType.Object),
new SpokeMethodParameter[] { new SpokeMethodParameter(
"this",
new SpokeType(ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
return parameters[0];
}
@Override
public String getMethodName() {
return ".ctor";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Object);
}
@Override
public Integer getMethodIndex() {
return 0;
}
}),
new SpokeMethod(
"turnIntoIC",
cl,
new SpokeType(ObjectType.Object),
new SpokeMethodParameter[] { new SpokeMethodParameter(
"this",
new SpokeType(ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
return parameters[0];
}
@Override
public String getMethodName() {
return "turnIntoIC";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Object);
}
@Override
public Integer getMethodIndex() {
return 1;
}
}), }));
cl = new SpokeClass();
classes.add(cl);
cl.Name = "Block";
cl.Variables = new String[1];
cl.Variables[0] = "blockData";
cl.Methods = new ArrayList<SpokeMethod>(
Arrays.asList(new SpokeMethod[] {
new SpokeMethod(
".ctor",
cl,
new SpokeType(ObjectType.Object),
new SpokeMethodParameter[] { new SpokeMethodParameter(
"this",
new SpokeType(ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
return parameters[0];
}
@Override
public String getMethodName() {
return ".ctor";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Object);
}
@Override
public Integer getMethodIndex() {
return 0;
}
}),
new SpokeMethod(
"getType",
cl,
new SpokeType(ObjectType.Int),
new SpokeMethodParameter[] { new SpokeMethodParameter(
"this",
new SpokeType(ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
return new SpokeObject(
((Block) parameters[0].Variables[0].javaObject)
.getType().getId());
}
@Override
public String getMethodName() {
return "getType";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Int);
}
@Override
public Integer getMethodIndex() {
return 1;
}
}),
new SpokeMethod("setType", cl, new SpokeType(
ObjectType.Void), new SpokeMethodParameter[] {
new SpokeMethodParameter("this", new SpokeType(
ObjectType.Object)),
new SpokeMethodParameter("v", new SpokeType(
ObjectType.Int)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
plugin.getScheduler()
.push(((Block) parameters[0].Variables[0].javaObject)
.getLocation(),
parameters[1].IntVal);
return null;
}
@Override
public String getMethodName() {
return "setType";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Void);
}
@Override
public Integer getMethodIndex() {
return 2;
}
}),
new SpokeMethod("makeSign", cl, new SpokeType(
ObjectType.Void), new SpokeMethodParameter[] {
new SpokeMethodParameter("this", new SpokeType(
ObjectType.Object)),
new SpokeMethodParameter("v", new SpokeType(
ObjectType.Array, new SpokeType(
ObjectType.String))) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
String[] lines = new String[4];
for (int i = 0; i < parameters[1].ArrayItems
.size(); i++) {
SpokeObject line = parameters[1].ArrayItems
.get(i);
lines[i] = line.StringVal;
}
plugin.getScheduler()
.pushAsyncChange(
new AsyncBlockChange(
((Block) parameters[0].Variables[0].javaObject)
.getLocation(),
68, (byte) 0x3,
(byte) 1, lines));
SpokeObject so = new SpokeObject(
ObjectType.Object,
((Block) parameters[0].Variables[0].javaObject));
so.ClassName = "Sign";
return so;
}
@Override
public String getMethodName() {
return "makeSign";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Object,
"Sign");
}
@Override
public Integer getMethodIndex() {
return 3;
}
}),
new SpokeMethod("makeStoneButton", cl, new SpokeType(
ObjectType.Void), new SpokeMethodParameter[] {
new SpokeMethodParameter("this", new SpokeType(
ObjectType.Object)),
new SpokeMethodParameter("v", new SpokeType(
ObjectType.Int)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
BlockFace f = null;
switch (parameters[1].IntVal) {
case 0:
f = BlockFace.NORTH;
break;
case 1:
f = BlockFace.WEST;
break;
case 2:
f = BlockFace.SOUTH;
break;
case 3:
f = BlockFace.EAST;
break;
}
plugin.getScheduler()
.pushAsyncChange(
new AsyncBlockChange(
((Block) parameters[0].Variables[0].javaObject)
.getLocation(),
org.bukkit.Material.STONE_BUTTON,
f));
return null;
}
@Override
public String getMethodName() {
return "makeSign";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Object,
"Sign");
}
@Override
public Integer getMethodIndex() {
return 3;
}
}),
new SpokeMethod("setTypeAndData", cl, new SpokeType(
ObjectType.Void), new SpokeMethodParameter[] {
new SpokeMethodParameter("this", new SpokeType(
ObjectType.Object)),
new SpokeMethodParameter("v", new SpokeType(
ObjectType.Int)),
new SpokeMethodParameter("v2", new SpokeType(
ObjectType.Int)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
plugin.getScheduler()
.push(((Block) parameters[0].Variables[0].javaObject)
.getLocation(),
parameters[1].IntVal,
(byte) parameters[2].IntVal);
return null;
}
@Override
public String getMethodName() {
return "setTypeAndData";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Void);
}
@Override
public Integer getMethodIndex() {
return 3;
}
})
}));
cl = new SpokeClass();
classes.add(cl);
cl.Name = "World";
cl.Methods = new ArrayList<SpokeMethod>(
Arrays.asList(new SpokeMethod[] {
new SpokeMethod(
".ctor",
cl,
new SpokeType(ObjectType.Object),
new SpokeMethodParameter[] { new SpokeMethodParameter(
"this",
new SpokeType(ObjectType.Object)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
return parameters[0];
}
@Override
public String getMethodName() {
return ".ctor";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Object);
}
@Override
public Integer getMethodIndex() {
return 0;
}
}),
new SpokeMethod(
"getBlockAt",
cl,
new SpokeType(ObjectType.Object, "Block"),
new SpokeMethodParameter[] {
new SpokeMethodParameter("this",
new SpokeType(ObjectType.Array)),
new SpokeMethodParameter("v1",
new SpokeType(ObjectType.Int)),
new SpokeMethodParameter("v2",
new SpokeType(ObjectType.Int)),
new SpokeMethodParameter("v3",
new SpokeType(ObjectType.Int)) },
new SpokeInternalMethod() {
@Override
public SpokeObject Evaluate(
SpokeObject[] parameters) {
SpokeObject jc = new SpokeObject(
new SpokeObject[] { new SpokeObject(
ObjectType.Object,
world.getBlockAt(
parameters[1].IntVal,
parameters[2].IntVal,
parameters[3].IntVal)) });
jc.ClassName = "Block";
return jc;
}
@Override
public String getMethodName() {
return "getBlockAt";
}
@Override
public SpokeType getMethodType() {
return new SpokeType(ObjectType.Object,
"Block");
}
@Override
public Integer getMethodIndex() {
return 1;
}
})
}));
ArrayList<SpokeEnum> enums = new ArrayList<SpokeEnum>();
for (Iterator<EnumWithLines> i = classes2.Item2.iterator(); i.hasNext();) {
EnumWithLines enumWithLines = (EnumWithLines) i.next();
ObjectType ot = null;
switch (enumWithLines.Variables.get(0).Tokens.get(3).getType()) {
case Int:
ot = ObjectType.Int;
break;
case String:
ot = ObjectType.String;
break;
case Float:
ot = ObjectType.Float;
break;
}
SpokeEnum se = new SpokeEnum(enumWithLines.Name, ot);
enums.add(se);
for (LineToken variable : enumWithLines.Variables) {
switch (variable.Tokens.get(3).getType()) {
case Int:
se.addVariable(((TokenWord) variable.Tokens.get(1)).Word,
((TokenInt) variable.Tokens.get(3))._value);
break;
case String:
se.addVariable(((TokenWord) variable.Tokens.get(1)).Word,
((TokenString) variable.Tokens.get(3))._value);
break;
case Float:
se.addVariable(((TokenWord) variable.Tokens.get(1)).Word,
((TokenFloat) variable.Tokens.get(3))._value);
break;
}
}
}
for (Iterator<ClassWithLines> i = classes2.Item1.iterator(); i
.hasNext();) {
ClassWithLines classWithLines = (ClassWithLines) i.next();
classes.add(cl = new SpokeClass());
cl.Variables = classWithLines.VariableNames
.toArray(new String[classWithLines.VariableNames.size()]);
cl.Name = classWithLines.Name;
for (Iterator<MethodWithLines> ic = classWithLines.Methods
.iterator(); ic.hasNext();) {
MethodWithLines method = (MethodWithLines) ic.next();
SpokeMethod me;
cl.Methods.add(me = new SpokeMethod(method.Name));
me.Static = method.Static;
CurMethodName = method.Name;
if (!method.Static) {
me.Parameters = new SpokeMethodParameter[method.paramNames
.size() + 1];
me.Parameters[0] = new SpokeMethodParameter(new SpokeType(
ObjectType.Object, cl.Name), "this");
for (int index = 0; index < method.paramNames.size(); index++) {
me.Parameters[index + 1] = new SpokeMethodParameter(
method.paramNames.get(index).Type,
method.paramNames.get(index).Name);
}
} else {
me.Parameters = new SpokeMethodParameter[method.paramNames
.size()];
for (int index = 0; index < method.paramNames.size(); index++) {
me.Parameters[index] = new SpokeMethodParameter(
method.paramNames.get(index).Type,
method.paramNames.get(index).Name);
}
}
me.Class = cl;
TokenEnumerator enumerator = new TokenEnumerator(
method.Lines.toArray(new LineToken[method.Lines.size()]));
ArrayList<SpokeLine> gc = null;
try {
gc = getLines(enumerator, 2, new evalInformation());
} catch (SpokeException ec) {
ec.printStackTrace();
throw ec;
}
me.Lines = gc.toArray(new SpokeLine[gc.size()]);
me.HasYieldReturn = linesHave(me.Lines, ISpokeLine.YieldReturn);
me.HasYield = linesHave(me.Lines, ISpokeLine.Yield);
me.HasReturn = linesHave(me.Lines, ISpokeLine.Return);
}
}
int ind = 0;
for (Iterator<GlobalsWithLines> i = classes2.Item3.iterator(); i
.hasNext();) {
GlobalsWithLines globalWithLines = (GlobalsWithLines) i.next();
SpokeGlobal gl;
globs.add(gl = new SpokeGlobal());
for (Iterator<LineToken> ic = globalWithLines.Variables.iterator(); ic
.hasNext();) {
LineToken method = (LineToken) ic.next();
String varName;
Spoke val;
method.Tokens.add(new TokenNewLine(-1));
TokenEnumerator enumerator = new TokenEnumerator(
new LineToken[] { method });
SpokeCommon.Assert(
enumerator.getCurrent().getType() == Token.Tab,
"bad global", enumerator);
enumerator.MoveNext();
varName = ((TokenWord) enumerator.getCurrent()).Word;
enumerator.MoveNext();
SpokeCommon.Assert(
enumerator.getCurrent().getType() == Token.Equal,
"bad global equal: " + varName, enumerator);
enumerator.MoveNext();
try {
val = eval(enumerator, 2, new evalInformation());
} catch (Exception ec) {
ec.printStackTrace();
continue;
}
SpokeGlobalVariable gv;
gl.Variables.add(gv = new SpokeGlobalVariable());
gv.Name = varName;
gv.SpokeItem = val;
gv.Index = ind++;
}
}
return new Tuple3<ArrayList<SpokeClass>, ArrayList<SpokeEnum>, SpokeGlobal>(
classes, enums, ALH.Aggregate(globs, new SpokeGlobal(),
new Aggregator<SpokeGlobal, SpokeGlobal>() {
@Override
public SpokeGlobal Accumulate(
SpokeGlobal accumulate, SpokeGlobal source) {
accumulate.Variables.addAll(source.Variables);
return accumulate;
}
}));
}
private boolean linesHave(SpokeLine[] lines, ISpokeLine r) {
for (int index = 0; index < lines.length; index++) {
SpokeLine e = lines[index];
if (e.getLType() == r) {
return true;
}
if (e instanceof SpokeLines
&& (!(e instanceof SpokeAnonMethod) || (r == ISpokeLine.Return))) {
if (e instanceof SpokeAnonMethod) {
if (linesHave(((SpokeLines) e).getLines(),
ISpokeLine.Return)
|| linesHave(((SpokeLines) e).getLines(),
ISpokeLine.Yield)
|| linesHave(((SpokeLines) e).getLines(),
ISpokeLine.YieldReturn)) {
return true;
}
} else if (linesHave(((SpokeLines) e).getLines(), r)) {
return true;
}
}
}
return false;
}
private SpokeItem CurrentItem;
public ArrayList<SpokeLine> getLines(TokenEnumerator enumerator,
int tabIndex, evalInformation inf) throws SpokeException {
int lineIndex = 0;
ArrayList<SpokeLine> lines = new ArrayList<SpokeLine>();
while (true) {
IToken token = enumerator.getCurrent();
if (token == null || token.getType() == Token.EndOfCodez) {
return lines;
}
if (token.getType() == Token.NewLine) {
enumerator.MoveNext();
continue;
}
if (token.getType() == Token.Tab
&& enumerator.PeakNext().getType() == Token.NewLine) {
enumerator.MoveNext();
enumerator.MoveNext();
continue;
}
if (!(token instanceof TokenTab)) {
throw new SpokeException(token);
}
if (((TokenTab) token).TabIndex < tabIndex) {
enumerator.PutBack();
return lines;
}
SpokeCommon.Assert(((TokenTab) token).TabIndex == tabIndex,
"Bad Tab", enumerator);
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.NewLine) {
enumerator.MoveNext();
continue;
}
CurrentItem = null;
Spoke s;
try {
s = eval(
enumerator,
tabIndex,
new evalInformation(inf).EatTab(false).ResetCurrentVal(
true));
} catch (SpokeException e) {
throw e;
} catch (Exception e) {
throw new SpokeException(e, enumerator.getCurrent());
}
if (s instanceof SpokeLine) {
lines.add((SpokeLine) s);
} else {
throw new SpokeException(enumerator.getCurrent());/*
* SpokeException(
* "Build",
* "problem on line "
* +
* lines.size()
* +
* " line is"
* +
* s.getClass()
* .getName() +
* " Method name="
* +
* CurMethodName
* +
* " tab index="
* + tabIndex);
*/
}
}
}
public Spoke eval(TokenEnumerator enumerator, int tabIndex,
evalInformation inf) throws Exception {
if (inf.ResetCurrentVal) {
CurrentItem = null;
}
if (inf.CheckMacs < 2) {
SpokeItem df = CurrentItem;
CurrentItem = null;
SpokeItem rm = checkRunMacro(enumerator, tabIndex, inf);
if (rm != null) {
CurrentItem = rm;
} else
CurrentItem = df;
}
if (enumerator.getCurrent().getType() == Token.Not) {
enumerator.MoveNext();
Spoke gc = eval(enumerator.IncreaseDebugLevel(), tabIndex,
new evalInformation(inf).BreakBeforeEvaler(true));
CurrentItem = (SpokeItem) new SpokeEquality((SpokeItem) gc,
new SpokeBool(false));
((SpokeEquality) CurrentItem).setTokens(enumerator
.DecreaseDebugLevel());
}
if (!inf.SkipStart) {
switch (enumerator.getCurrent().getType()) {
case Word:
if (((TokenWord) enumerator.IncreaseDebugLevel().getCurrent()).Word
.toLowerCase() == "null") {
CurrentItem = (SpokeItem) new SpokeNull()
.setTokens(enumerator.DecreaseDebugLevel());
} else {
CurrentItem = (SpokeItem) new SpokeVariable(
(((TokenWord) enumerator.getCurrent()).Word),
CurrentItem).setTokens(enumerator
.DecreaseDebugLevel());
}
enumerator.MoveNext();
break;
case Int:
CurrentItem = (SpokeItem) new SpokeInt(((TokenInt) enumerator
.IncreaseDebugLevel().getCurrent())._value)
.setTokens(enumerator.DecreaseDebugLevel());
enumerator.MoveNext();
break;
case Float:
CurrentItem = (SpokeItem) new SpokeFloat(
((TokenFloat) enumerator.IncreaseDebugLevel()
.getCurrent())._value).setTokens(enumerator
.DecreaseDebugLevel());
enumerator.MoveNext();
break;
case String:
CurrentItem = (SpokeItem) new SpokeString(
((TokenString) enumerator.IncreaseDebugLevel()
.getCurrent())._value).setTokens(enumerator
.DecreaseDebugLevel());
enumerator.MoveNext();
break;
case False:
CurrentItem = (SpokeItem) new SpokeBool(false)
.setTokens(enumerator.DecreaseDebugLevel());
enumerator.MoveNext();
break;
case True:
CurrentItem = (SpokeItem) new SpokeBool(true)
.setTokens(enumerator.DecreaseDebugLevel());
enumerator.MoveNext();
break;
case OpenParen:
enumerator.MoveNext();
CurrentItem = (SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf));
if (enumerator.getCurrent().getType() == Token.Tab) {
enumerator.MoveNext();
}
if (enumerator.getCurrent().getType() != Token.CloseParen) {
throw new Exception("Bad");
}
enumerator.MoveNext();
break;
case If:
return (SpokeLine) evaluateIf(enumerator, tabIndex, inf);
case Switch:
return (SpokeLine) evaluateSwitch(enumerator, tabIndex, inf);
case Bar:
SpokeAnonMethod an = new SpokeAnonMethod(
(SpokeParent) CurrentItem);
enumerator.IncreaseDebugLevel().MoveNext();
SpokeCommon.Assert(
enumerator.getCurrent().getType() == Token.OpenParen,
enumerator.getCurrent().getType() + " Isnt OpenParen",
enumerator);
ArrayList<ParamEter> parameters_ = new ArrayList<ParamEter>();
enumerator.MoveNext();
if (enumerator.getCurrent().getType() != Token.CloseParen) {
while (true) {
boolean byRe_f = false;
if (((TokenWord) enumerator.getCurrent()).Word
.toLowerCase().equals("ref")) {
byRe_f = true;
enumerator.MoveNext();
}
parameters_.add(new ParamEter(((TokenWord) enumerator
.getCurrent()).Word, 0, byRe_f));
enumerator.MoveNext();
switch (enumerator.getCurrent().getType()) {
case CloseParen:
enumerator.MoveNext();
break;
case Comma:
enumerator.MoveNext();
continue;
}
break;
}
}
an.Parameters = parameters_.toArray(new ParamEter[parameters_
.size()]);
SpokeCommon
.Assert(enumerator.getCurrent().getType() == Token.AnonMethodStart,
enumerator.getCurrent().getType()
+ " Isnt anonmethodstart", enumerator);
enumerator.MoveNext();
SpokeCommon.Assert(
enumerator.getCurrent().getType() == Token.NewLine,
enumerator.getCurrent().getType() + " Isnt Newline",
enumerator);
enumerator.MoveNext();
ArrayList<SpokeLine> dc = getLines(enumerator, tabIndex + 1,
new evalInformation(inf));
an.lines = dc.toArray(new SpokeLine[dc.size()]);
SpokeCommon
.Assert(enumerator.getCurrent().getType() == Token.NewLine
|| enumerator.getCurrent().getType() == Token.EndOfCodez,
enumerator.getCurrent().getType()
+ " Isnt Newline", enumerator);
enumerator.MoveNext();
an.HasYield = linesHave(an.lines, ISpokeLine.Yield);
an.HasReturn = linesHave(an.lines, ISpokeLine.Return);
an.HasYieldReturn = linesHave(an.lines, ISpokeLine.YieldReturn);
SpokeCommon
.Assert(enumerator.getCurrent().getType() == Token.Tab
&& ((TokenTab) enumerator.getCurrent()).TabIndex == tabIndex,
"Bad tabindex", enumerator);
if (enumerator.getCurrent().getType() == Token.Tab
&& inf.EatTab)
enumerator.MoveNext();
if (enumerator.PeakNext().getType() != Token.CloseParen) {
return an;
} else {
enumerator.MoveNext();
CurrentItem = an;
}
((SpokeBasic) CurrentItem).setTokens(enumerator
.DecreaseDebugLevel());
break;
case OpenSquare:
CurrentItem = (SpokeItem) dyanmicArray(
enumerator.IncreaseDebugLevel(), tabIndex, inf)
.setTokens(enumerator.DecreaseDebugLevel());
break;
case OpenCurly:
CurrentItem = new SpokeConstruct();
CurrentItem = (SpokeItem) dynamicObject(
enumerator.IncreaseDebugLevel(), tabIndex, inf)
.setTokens(enumerator.DecreaseDebugLevel());
break;
case Create:
return (SpokeItem) createObject(enumerator, tabIndex, inf);
case Return:
enumerator.IncreaseDebugLevel().MoveNext();
SpokeReturn r = (SpokeReturn) new SpokeReturn((SpokeItem) eval(
enumerator, tabIndex, new evalInformation(inf)))
.setTokens(enumerator.DecreaseDebugLevel());
enumerator.MoveNext();
return r;
case Yield:
enumerator.IncreaseDebugLevel().MoveNext();
if (enumerator.getCurrent().getType() == Token.Return) {
enumerator.MoveNext();
SpokeYieldReturn y = (SpokeYieldReturn) new SpokeYieldReturn(
(SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf)))
.setTokens(enumerator.DecreaseDebugLevel());
;
enumerator.MoveNext();
return y;
} else {
SpokeYield y = (SpokeYield) new SpokeYield(
(SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf)))
.setTokens(enumerator.DecreaseDebugLevel());
;
enumerator.MoveNext();
return y;
}
}
}
switch (enumerator.getCurrent().getType()) {
case OpenSquare:
SpokeArrayIndex ar = new SpokeArrayIndex();
ar.setParent(CurrentItem);
enumerator.IncreaseDebugLevel().MoveNext();
ar.Index = (SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).BreakBeforeEqual(false)
.ResetCurrentVal(true));
SpokeCommon.Assert(
enumerator.getCurrent().getType() == Token.CloseSquare,
enumerator.getCurrent().getType() + " Isnt closesquare",
enumerator);
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.OpenSquare) {
CurrentItem = ar;
return eval(enumerator, tabIndex, new evalInformation(inf)
.ResetCurrentVal(false).SkipStart(true));
}
CurrentItem = ar;
((SpokeBasic) CurrentItem).setTokens(enumerator
.DecreaseDebugLevel());
break;
case OpenParen:
if (enumerator.GetLast(1) instanceof TokenWord) {
((TokenWord) enumerator.GetLast(1))
.SetTokenType(SpokeTokenType.Method);
}
SpokeMethodCall meth = new SpokeMethodCall(CurrentItem);
meth.setTokens(((TokenWord) enumerator.GetLast(1)));
enumerator.MoveNext();
ArrayList<SpokeItem> param_ = new ArrayList<SpokeItem>();
param_.add(new SpokeCurrent());
CurrentItem = null;
if (enumerator.getCurrent().getType() != Token.CloseParen) {
while (true) {
param_.add((SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true)));
if (enumerator.getCurrent().getType() == Token.Comma) {
enumerator.MoveNext();
continue;
}
break;
}
}
enumerator.MoveNext();// closeparen
meth.Parameters = param_.toArray(new SpokeItem[param_.size()]);
CurrentItem = meth;
// loop params
break;
case Period:
SpokeItem t = CurrentItem;
enumerator.IncreaseDebugLevel().MoveNext();
SpokeParent g;
Spoke c;
CurrentItem = g = (SpokeParent) (c = eval(enumerator, tabIndex,
new evalInformation(inf).BreakBeforeEqual(true).BreakBeforeEvaler(true)));
// g.Parent = t;
// enumerator.MoveNext();
((SpokeBasic) CurrentItem).setTokens(enumerator
.DecreaseDebugLevel());
break;
}
switch (enumerator.getCurrent().getType()) {
case Period:
enumerator.MoveNext();
SpokeItem t = CurrentItem;
SpokeParent g;
Spoke c;
CurrentItem = g = (SpokeParent) (c = eval(enumerator, tabIndex,
new evalInformation(inf).BreakBeforeEqual(true).BreakBeforeEvaler(true)));
// g.Parent = t;
((SpokeBasic) CurrentItem).setTokens(((SpokeBasic) t).getTokens());
// enumerator.MoveNext();
break;
}
while (true) {
switch (enumerator.getCurrent().getType()) {
case OpenParen:
SpokeMethodCall meth = new SpokeMethodCall(CurrentItem);
enumerator.IncreaseDebugLevel().MoveNext();
ArrayList<SpokeItem> param_ = new ArrayList<SpokeItem>();
param_.add(new SpokeCurrent());
while (true) {
param_.add((SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true)));
if (enumerator.getCurrent().getType() == Token.Comma) {
enumerator.MoveNext();
continue;
}
break;
}
enumerator.MoveNext();// closeparen
meth.Parameters = param_.toArray(new SpokeItem[param_.size()]);
CurrentItem = meth;
((SpokeBasic) CurrentItem).setTokens(enumerator
.DecreaseDebugLevel());
continue;
}
break;
}
if (inf.BreakBeforeEvaler) {
return CurrentItem;
}
if (!inf.DontEvalEquals) {
if (enumerator.IncreaseDebugLevel().getCurrent().getType() == Token.Equal) {
SpokeEqual equ = new SpokeEqual(CurrentItem);
enumerator.MoveNext();
equ.RightSide = (SpokeItem) eval(
enumerator,
tabIndex,
new evalInformation(inf).EatTab(false).ResetCurrentVal(
true));
if (enumerator.getCurrent().getType() == Token.NewLine) {
// enumerator.MoveNext(); //newline
}
equ.setTokens(enumerator.DecreaseDebugLevel());
return equ;
}
}
switch (enumerator.getCurrent().getType()) {
case AnonMethodStart:
// checkparamsgetlines
SpokeAnonMethod an = new SpokeAnonMethod(CurrentItem);
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.Bar) {
enumerator.MoveNext();
SpokeCommon.Assert(
enumerator.getCurrent().getType() == Token.OpenParen,
enumerator.getCurrent().getType() + " Isnt openparen",
enumerator);
ArrayList<ParamEter> parameters_ = new ArrayList<ParamEter>();
enumerator.MoveNext();
while (true) {
boolean byRe_f = false;
if (((TokenWord) enumerator.getCurrent()).Word
.toLowerCase() == "ref") {
byRe_f = true;
enumerator.MoveNext();
}
parameters_.add(new ParamEter(((TokenWord) enumerator
.getCurrent()).Word, 0, byRe_f));
((SpokeBasic) CurrentItem).setTokens((TokenWord) enumerator
.getCurrent());
enumerator.MoveNext();
switch (enumerator.getCurrent().getType()) {
case CloseParen:
enumerator.MoveNext();
break;
case Comma:
enumerator.MoveNext();
continue;
}
break;
}
an.Parameters = parameters_.toArray(new ParamEter[parameters_
.size()]);
} else {
an.RunOnVar = (SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true)
.BreakBeforeEqual(false)
.BreakBeforeEvaler(true));
}
SpokeCommon.Assert(
enumerator.getCurrent().getType() == Token.NewLine,
enumerator.getCurrent().getType() + " Isnt Newline",
enumerator);
enumerator.MoveNext();
CurrentItem = null;
ArrayList<SpokeLine> dc = getLines(enumerator, tabIndex + 1,
new evalInformation(inf));
an.lines = dc.toArray(new SpokeLine[dc.size()]);
an.HasYield = linesHave(an.lines, ISpokeLine.Yield);
an.HasReturn = linesHave(an.lines, ISpokeLine.Return);
an.HasYieldReturn = linesHave(an.lines, ISpokeLine.YieldReturn);
SpokeCommon
.Assert(enumerator.getCurrent().getType() == Token.NewLine
|| enumerator.getCurrent().getType() == Token.EndOfCodez,
enumerator.getCurrent().getType() + " Isnt Newline",
enumerator);
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.Tab && inf.EatTab)
enumerator.MoveNext();
CurrentItem = an;
break;
}
if (inf.BreakBeforeMath) {
return CurrentItem;
}
IToken dm;
IToken cm;
SpokeBasic ccm;
// 5*6-7+8/9+10 does not evaluate properly
switch (enumerator.getCurrent().getType()) {
case Percent:
dm = enumerator.getCurrent();
enumerator.MoveNext();
int me = 0;
if (currentMathItem.size() == 0) {
SpokeMod j;
currentMathItem.add(j = new SpokeMod());
j.PushItem(CurrentItem);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() > me) {
SpokeMod j;
SpokeMathItem c = currentMathItem
.get(currentMathItem.size() - 1);
c.PushItem(CurrentItem);
currentMathItem.remove(currentMathItem.size() - 1);
currentMathItem.add(j = new SpokeMod());
j.PushItem((SpokeItem) c);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() < me) {
SpokeMod j;
currentMathItem.add(j = new SpokeMod());
j.PushItem(CurrentItem);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() == me) {
SpokeMod j = (SpokeMod) currentMathItem.get(currentMathItem
.size() - 1);
if (!CurrentItem.equals(j))
j.PushItem(CurrentItem);
}
ccm = ((SpokeBasic) eval(enumerator, tabIndex, new evalInformation(
inf).BreakBeforeEqual(true).ResetCurrentVal(true)
.DoingMath(true)));
if (currentMathItem.size() > 0) {
CurrentItem = (SpokeItem) currentMathItem.get(currentMathItem
.size() - 1);
((SpokeMathItem) CurrentItem).PushItem((SpokeItem) ccm);
((SpokeBasic) CurrentItem).setTokens(dm);
} else
CurrentItem = (SpokeItem) ccm.setTokens(dm);
break;
case Plus:
dm = enumerator.getCurrent();
enumerator.MoveNext();
me = 0;
if (currentMathItem.size() == 0) {
SpokeAddition j;
currentMathItem.add(j = new SpokeAddition());
j.PushItem(CurrentItem);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() > me) {
SpokeAddition j;
currentMathItem.add(j = new SpokeAddition());
j.PushItem(((SpokeItem) currentMathItem.get(currentMathItem
.size() - 1)));
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() < me) {
SpokeAddition j;
currentMathItem.add(j = new SpokeAddition());
j.PushItem(CurrentItem);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() == me) {
SpokeAddition j = (SpokeAddition) currentMathItem
.get(currentMathItem.size() - 1);
if (!CurrentItem.equals(j))
j.PushItem(CurrentItem);
}
ccm = ((SpokeBasic) eval(enumerator, tabIndex, new evalInformation(
inf).BreakBeforeEqual(true).ResetCurrentVal(true)
.DoingMath(true)));
if (currentMathItem.size() > 0) {
CurrentItem = (SpokeItem) currentMathItem.get(currentMathItem
.size() - 1);
((SpokeMathItem) CurrentItem).PushItem((SpokeItem) ccm);
((SpokeBasic) CurrentItem).setTokens(dm);
} else
CurrentItem = (SpokeItem) ccm.setTokens(dm);
break;
case Minus:
dm = enumerator.getCurrent();
enumerator.MoveNext();
me = 1;
if (currentMathItem.size() == 0) {
SpokeSubtraction j;
currentMathItem.add(j = new SpokeSubtraction());
j.PushItem(CurrentItem);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() > me) {
SpokeSubtraction j;
SpokeMathItem c = currentMathItem
.get(currentMathItem.size() - 1);
c.PushItem(CurrentItem);
currentMathItem.remove(currentMathItem.size() - 1);
currentMathItem.add(j = new SpokeSubtraction());
j.PushItem((SpokeItem) c);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() < me) {
SpokeSubtraction j;
currentMathItem.add(j = new SpokeSubtraction());
j.PushItem(CurrentItem);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() == me) {
SpokeSubtraction j = (SpokeSubtraction) currentMathItem
.get(currentMathItem.size() - 1);
if (!CurrentItem.equals(j))
j.PushItem(CurrentItem);
}
ccm = ((SpokeBasic) eval(enumerator, tabIndex, new evalInformation(
inf).BreakBeforeEqual(true).ResetCurrentVal(true)
.DoingMath(true)));
if (currentMathItem.size() > 0) {
CurrentItem = (SpokeItem) currentMathItem.get(currentMathItem
.size() - 1);
((SpokeMathItem) CurrentItem).PushItem((SpokeItem) ccm);
((SpokeBasic) CurrentItem).setTokens(dm);
} else
CurrentItem = (SpokeItem) ccm.setTokens(dm);
break;
case Divide:
dm = enumerator.getCurrent();
enumerator.MoveNext();
me = 3;
if (currentMathItem.size() == 0) {
SpokeDivision j;
currentMathItem.add(j = new SpokeDivision());
j.PushItem(CurrentItem);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() > me) {
SpokeDivision j;
SpokeMathItem c = currentMathItem
.get(currentMathItem.size() - 1);
c.PushItem(CurrentItem);
currentMathItem.remove(currentMathItem.size() - 1);
currentMathItem.add(j = new SpokeDivision());
j.PushItem((SpokeItem) c);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() < me) {
SpokeDivision j;
currentMathItem.add(j = new SpokeDivision());
j.PushItem(CurrentItem);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() == me) {
SpokeDivision j = (SpokeDivision) currentMathItem
.get(currentMathItem.size() - 1);
if (!CurrentItem.equals(j))
j.PushItem(CurrentItem);
}
ccm = ((SpokeBasic) eval(enumerator, tabIndex, new evalInformation(
inf).BreakBeforeEqual(true).ResetCurrentVal(true)
.DoingMath(true)));
if (currentMathItem.size() > 0) {
CurrentItem = (SpokeItem) currentMathItem.get(currentMathItem
.size() - 1);
((SpokeMathItem) CurrentItem).PushItem((SpokeItem) ccm);
((SpokeBasic) CurrentItem).setTokens(dm);
} else
CurrentItem = (SpokeItem) ccm.setTokens(dm);
break;
case Mulitply:
dm = enumerator.getCurrent();
enumerator.MoveNext();
me = 2;
if (currentMathItem.size() == 0) {
SpokeMultiplication j;
currentMathItem.add(j = new SpokeMultiplication());
j.PushItem(CurrentItem);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() > me) {
SpokeMultiplication j;
SpokeMathItem c = currentMathItem
.get(currentMathItem.size() - 1);
c.PushItem(CurrentItem);
currentMathItem.remove(currentMathItem.size() - 1);
currentMathItem.add(j = new SpokeMultiplication());
j.PushItem((SpokeItem) c);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() < me) {
SpokeMultiplication j;
currentMathItem.add(j = new SpokeMultiplication());
j.PushItem(CurrentItem);
} else if (currentMathItem.get(currentMathItem.size() - 1)
.getWeight() == me) {
SpokeMultiplication j = (SpokeMultiplication) currentMathItem
.get(currentMathItem.size() - 1);
if (!CurrentItem.equals(j))
j.PushItem(CurrentItem);
}
ccm = ((SpokeBasic) eval(enumerator, tabIndex, new evalInformation(
inf).BreakBeforeEqual(true).ResetCurrentVal(true)
.DoingMath(true)));
if (currentMathItem.size() > 0) {
CurrentItem = (SpokeItem) currentMathItem.get(currentMathItem
.size() - 1);
((SpokeMathItem) CurrentItem).PushItem((SpokeItem) ccm);
((SpokeBasic) CurrentItem).setTokens(dm);
} else
CurrentItem = (SpokeItem) ccm.setTokens(dm);
break;
}
if (inf.BreakBeforeEqual) {
if (currentMathItem.size() > 0 && inf.DoingMath) {
SpokeMathItem a = (currentMathItem
.get(currentMathItem.size() - 1));
if (!CurrentItem.equals(a))
a.PushItem(CurrentItem);
currentMathItem.remove(a);
return (Spoke) a;
}
return CurrentItem;
}
switch (enumerator.getCurrent().getType()) {
case DoubleOr:
dm = enumerator.getCurrent();
enumerator.MoveNext();
CurrentItem = (SpokeItem) new SpokeOr(CurrentItem,
(SpokeItem) eval(enumerator, tabIndex, new evalInformation(
inf).ResetCurrentVal(true))).setTokens(dm);
break;
case DoubleAnd:
dm = enumerator.getCurrent();
enumerator.MoveNext();
CurrentItem = (SpokeItem) new SpokeAnd(CurrentItem,
(SpokeItem) eval(enumerator, tabIndex, new evalInformation(
inf).ResetCurrentVal(true))).setTokens(dm);
;
break;
}
SpokeItem e;
switch (enumerator.getCurrent().getType()) {
case DoubleEqual:
dm = enumerator.getCurrent();
enumerator.MoveNext();
e = (SpokeItem) new SpokeEquality(CurrentItem, (SpokeItem) eval(
enumerator, tabIndex, new evalInformation(inf)
.BreakBeforeEqual(true).ResetCurrentVal(true)))
.setTokens(dm);
;
CurrentItem = e;
break;
case NotEqual:
dm = enumerator.getCurrent();
enumerator.MoveNext();
e = (SpokeItem) new SpokeNotEqual(CurrentItem, (SpokeItem) eval(
enumerator, tabIndex, new evalInformation(inf)
.BreakBeforeEqual(true).ResetCurrentVal(true)))
.setTokens(dm);
CurrentItem = e;
break;
case Less:
dm = enumerator.getCurrent();
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.Equal) {
cm = enumerator.getCurrent();
enumerator.MoveNext();
e = (SpokeItem) new SpokeLessThanOrEqual(CurrentItem,
(SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).BreakBeforeEqual(true)
.ResetCurrentVal(true))).setTokens(dm,
cm);
CurrentItem = e;
break;
}
e = (SpokeItem) new SpokeLessThan(CurrentItem, (SpokeItem) eval(
enumerator, tabIndex, new evalInformation(inf)
.BreakBeforeEqual(true).ResetCurrentVal(true)))
.setTokens(dm);
CurrentItem = e;
break;
case Greater:
dm = enumerator.getCurrent();
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.Equal) {
cm = enumerator.getCurrent();
enumerator.MoveNext();
e = (SpokeItem) new SpokeGreaterThanOrEqual(CurrentItem,
(SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).BreakBeforeEqual(true)
.ResetCurrentVal(true))).setTokens(dm,
cm);
CurrentItem = e;
break;
}
e = (SpokeItem) new SpokeGreaterThan(CurrentItem, (SpokeItem) eval(
enumerator, tabIndex, new evalInformation(inf)
.BreakBeforeEqual(true).ResetCurrentVal(true)))
.setTokens(dm);
CurrentItem = e;
break;
}
switch (enumerator.getCurrent().getType()) {
case DoubleOr:
dm = enumerator.getCurrent();
enumerator.MoveNext();
CurrentItem = (SpokeItem) new SpokeOr(CurrentItem,
(SpokeItem) eval(enumerator, tabIndex, new evalInformation(
inf).ResetCurrentVal(true))).setTokens(dm);
break;
case DoubleAnd:
dm = enumerator.getCurrent();
enumerator.MoveNext();
CurrentItem = (SpokeItem) new SpokeAnd(CurrentItem,
(SpokeItem) eval(enumerator, tabIndex, new evalInformation(
inf).ResetCurrentVal(true))).setTokens(dm);
break;
}
switch (enumerator.getCurrent().getType()) {
case QuestionMark:
dm = enumerator.getCurrent();
enumerator.MoveNext();
SpokeItem bas = CurrentItem;
SpokeItem left = (SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true));
if (!(enumerator.getCurrent() instanceof TokenColon))
throw new SpokeException("bad ternary", enumerator.getCurrent());
enumerator.MoveNext();
SpokeItem right = (SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true));
CurrentItem = (SpokeItem) new SpokeTernary(bas, left, right)
.setTokens(dm);
break;
}
return CurrentItem;
}
ArrayList<SpokeMathItem> currentMathItem = new ArrayList<SpokeMathItem>();
private SpokeIf evaluateIf(TokenEnumerator enumerator, int tabIndex,
evalInformation inf) throws Exception {
enumerator.MoveNext();
SpokeIf i_f = new SpokeIf((SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true)));
enumerator.MoveNext();
ArrayList<SpokeLine> gc = getLines(enumerator, tabIndex + 1,
new evalInformation(inf));
i_f.IfLines = gc.toArray(new SpokeLine[gc.size()]);
SpokeCommon
.Assert(enumerator.getCurrent().getType() == Token.NewLine
|| enumerator.getCurrent().getType() == Token.EndOfCodez,
enumerator.getCurrent().getType() + " Isnt Newline",
enumerator);
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.Tab
&& enumerator.PeakNext().getType() == Token.Else) {
if (((TokenTab) enumerator.getCurrent()).TabIndex < tabIndex) {
return i_f;
}
enumerator.MoveNext();
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.If) {
i_f.ElseIf = evaluateIf(enumerator, tabIndex,
inf.ResetCurrentVal(true));
} else {
gc = getLines(enumerator, tabIndex + 1,
new evalInformation(inf));
SpokeLine[] fc = new SpokeLine[gc.size()];
gc.toArray(fc);
i_f.ElseLines = fc;
SpokeCommon
.Assert(enumerator.getCurrent().getType() == Token.NewLine
|| enumerator.getCurrent().getType() == Token.EndOfCodez,
enumerator.getCurrent().getType()
+ " Isnt Newline", enumerator);
enumerator.MoveNext();
}
}
if (enumerator.getCurrent().getType() == Token.Tab && inf.EatTab)
enumerator.MoveNext();
return i_f;
}
private SpokeSwitch evaluateSwitch(TokenEnumerator enumerator,
int tabIndex, evalInformation inf) throws Exception {
enumerator.MoveNext();
SpokeSwitch sw = new SpokeSwitch((SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true)));
ArrayList<SpokeSwitch.Case> als = new ArrayList<SpokeSwitch.Case>();
while (true) {
if (enumerator.PeakNext() instanceof TokenTab) {
enumerator.MoveNext();
if (((TokenTab) enumerator.getCurrent()).TabIndex == tabIndex + 1) {
enumerator.MoveNext();
SpokeItem jf = (SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true));
SpokeCommon.Assert(
enumerator.getCurrent() instanceof TokenColon,
"case bad", enumerator);
enumerator.MoveNext();
enumerator.MoveNext();
ArrayList<SpokeLine> gc = getLines(enumerator,
tabIndex + 2, new evalInformation(inf));
als.add(sw.new Case(jf,
gc.toArray(new SpokeLine[gc.size()])));
SpokeCommon
.Assert(enumerator.getCurrent().getType() == Token.NewLine
|| enumerator.getCurrent().getType() == Token.EndOfCodez,
enumerator.getCurrent().getType()
+ " Isnt Newline", enumerator);
}
continue;
}
break;
}
sw.Cases = als.toArray(new SpokeSwitch.Case[als.size()]);
if (enumerator.getCurrent().getType() == Token.Tab && inf.EatTab)
enumerator.MoveNext();
return sw;
}
private ArrayList<TokenMacroPiece> allMacros_;
private SpokeMethodCall checkRunMacro(TokenEnumerator enumerator,
int tabIndex, evalInformation inf) throws Exception { // tm.
for (int index = 0;; index++) {
TokenMacroPiece tokenMacroPiece = null;
ArrayList<SpokeItem> parameters = null;
TokenEnumerator tm = null;
boolean bad = false;
boolean continueBack = false;
boolean breakFor = false;
while (true) {
bad = false;
continueBack = false;
if (index >= allMacros_.size()) {
breakFor = true;
break;
}
tokenMacroPiece = allMacros_.get(index);
parameters = new ArrayList<SpokeItem>();
tm = enumerator.Clone();
ArrayList<IToken> outs = tm.getOutstandingLine();
for (int i = 0; i < tokenMacroPiece.Macro.length; i++) {
IToken mp = tokenMacroPiece.Macro[i];
if (mp.getType() == Token.Ampersand) {
for (int j = i + 1; j < tokenMacroPiece.Macro.length; j++) {
final IToken r = tokenMacroPiece.Macro[j];
if (!ALH.Any(outs, new Finder<IToken>() {
@Override
public boolean Find(IToken a) {
return (r.getType() == Token.Ampersand || (a
.getType() == r.getType() && (a
.getType() == Token.Word
&& r.getType() == Token.Word ? ((TokenWord) a).Word == ((TokenWord) r).Word
: true)));
}
})) {
bad = true;
break;
}
}
if (bad) {
break;
}
IToken frf = tokenMacroPiece.Macro.length == i + 1 ? new TokenNewLine(
-1) : tokenMacroPiece.Macro[i + 1];
int selectedLine = 0;
IToken tp = null;
int selectedToken = tm.tokenIndex;
List<LineToken> gm = tm.getCurrentLines();
if (frf.getType() != Token.NewLine) {
for (int j = 0; j < gm.size(); j++) {
for (int ic = selectedToken; ic < gm.get(j).Tokens
.size(); ic++) {
IToken a = gm.get(j).Tokens.get(ic);
if (gm.get(j).Tokens.get(ic).getType() == frf
.getType()
&& (a.getType() == frf.getType() && (a
.getType() == Token.Word
&& frf.getType() == Token.Word ? ((TokenWord) a).Word == ((TokenWord) frf).Word
: true))) {
tp = gm.get(j).Tokens.get(ic);
break;
}
}
if (tp != null) {
selectedLine = j;
break;
} else {
selectedToken = 0;
}
}
TokenAmpersand bf = new TokenAmpersand(-1);
gm.get(selectedLine).Tokens
.add(gm.get(selectedLine).Tokens
.indexOf(tp), bf);
try {
CurrentItem = null;
Spoke d = eval(
tm,
tabIndex,
new evalInformation(inf)
.CheckMacs(inf.CheckMacs + 1)
.DontEvalEquals(true)
.BreakBeforeEqual(true));
parameters.add((SpokeItem) d);
if (d == null
|| (!(tm.getCurrent().getType() == Token.Ampersand || tokenMacroPiece.Macro.length == i + 1))) {
index++;
continueBack = true;
tm.getCurrentLine().Tokens.remove(bf);
break;
}
} catch (Exception e) {
index++;
continueBack = true;
tm.getCurrentLine().Tokens.remove(bf);
break;
}
tm.getCurrentLine().Tokens.remove(bf);
} else {
try {
CurrentItem = null;
Spoke d = eval(
tm,
tabIndex,
new evalInformation(inf)
.CheckMacs(inf.CheckMacs + 1)
.DontEvalEquals(true)
.BreakBeforeEqual(true));
parameters.add((SpokeItem) d);
if (d == null) {
index++;
continueBack = true;
break;
}
} catch (Exception e) {
index++;
continueBack = true;
break;
}
}
} else {
if (mp.getType() == tm.getCurrent().getType()
&& (mp.getType() == Token.Word
&& tm.getCurrent().getType() == Token.Word ? ((TokenWord) mp).Word == ((TokenWord) tm
.getCurrent()).Word : true)) {
tm.MoveNext();
} else {
bad = true;
break;
}
}
}
if (continueBack) {
continue;
}
break;
}
if (breakFor) {
break;
}
if (!bad) {
SpokeMethodCall ambe = new SpokeMethodCall();
SpokeAnonMethod me = new SpokeAnonMethod();
me.SpecAnon = true;
me.Parameters = tokenMacroPiece.Parameters;
ArrayList<SpokeLine> gc = getLines(
new TokenEnumerator(
tokenMacroPiece.Lines
.toArray(new LineToken[tokenMacroPiece.Lines
.size()])), 1, inf);
me.lines = gc.toArray(new SpokeLine[gc.size()]);
me.HasYieldReturn = linesHave(me.lines, ISpokeLine.YieldReturn);
me.HasYield = linesHave(me.lines, ISpokeLine.Yield);
me.HasReturn = linesHave(me.lines, ISpokeLine.Return);
ambe.setParent(me);
parameters.add(0, new SpokeCurrent());
ambe.Parameters = parameters.toArray(new SpokeItem[parameters
.size()]);
enumerator.Set(tm);
return ambe;
}
}
return null;
}
private SpokeType NameToType(String word) {
word = word.toLowerCase();
if (word.equals("unset")) {
return new SpokeType(ObjectType.Unset);
} else if (word.equals("null")) {
return new SpokeType(ObjectType.Null);
} else if (word.equals("int")) {
return new SpokeType(ObjectType.Int);
} else if (word.equals("float")) {
return new SpokeType(ObjectType.Float);
} else if (word.equals("string")) {
return new SpokeType(ObjectType.String);
} else if (word.equals("bool")) {
return new SpokeType(ObjectType.Bool);
} else if (word.equals("array")) {
return new SpokeType(ObjectType.Array);
} else if (word.equals("object")) {
return new SpokeType(ObjectType.Object);
} else if (word.equals("method")) {
return new SpokeType(ObjectType.Method);
} else if (word.equals("void")) {
return new SpokeType(ObjectType.Void);
}
return new SpokeType(ObjectType.Object, word);
}
private SpokeBasic createObject(TokenEnumerator enumerator, int tabIndex,
evalInformation inf) throws Exception {
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.OpenCurly) {
return dynamicObject(enumerator, tabIndex, inf);
}
SpokeConstruct sp = new SpokeConstruct();
SpokeCommon.Assert(enumerator.getCurrent().getType() == Token.Word,
enumerator.getCurrent().getType() + " Isnt word", enumerator);
sp.setTokens(((TokenWord) enumerator.getCurrent()));
sp.ClassName = ((TokenWord) enumerator.getCurrent()).Word;
((TokenWord) enumerator.getCurrent())
.SetTokenType(SpokeTokenType.Object);
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.OpenSquare) {
enumerator.MoveNext();// closequare
enumerator.MoveNext();
return new SpokeArray(NameToType(sp.ClassName));
}
enumerator.MoveNext();// openeparam
ArrayList<SpokeItem> param_ = new ArrayList<SpokeItem>();
if (enumerator.getCurrent().getType() != Token.CloseParen) {
CurrentItem = null;
while (true) {
param_.add((SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true)));
if (enumerator.getCurrent().getType() == Token.Comma) {
enumerator.MoveNext();
continue;
}
break;
}
}
sp.Parameters = param_.toArray(new SpokeItem[param_.size()]);
enumerator.MoveNext();// closeparam
CurrentItem = sp;
return (SpokeConstruct) CurrentItem;
}
private SpokeBasic dynamicObject(TokenEnumerator enumerator, int tabIndex,
evalInformation inf) throws Exception {
enumerator.MoveNext(); // openesquigly
SpokeConstruct cons = (SpokeConstruct) CurrentItem;
ArrayList<SpokeEqual> param_ = new ArrayList<SpokeEqual>();
if (enumerator.getCurrent().getType() != Token.CloseCurly) {
CurrentItem = null;
while (true) {
((TokenWord) enumerator.getCurrent())
.SetTokenType(SpokeTokenType.Param);
param_.add((SpokeEqual) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true)));
if (enumerator.getCurrent().getType() == Token.Comma) {
enumerator.MoveNext();
continue;
}
break;
}
}
enumerator.MoveNext();// closesquigly
cons.SetVars = ALH.Select(param_,
new ALH.Selector<SpokeEqual, SVarItems>() {
@Override
public SVarItems Select(SpokeEqual item) {
return new SVarItems(
((SpokeVariable) item.LeftSide).VariableName,
0, item.RightSide);
}
}).toArray(new SVarItems[param_.size()]);
return cons;
}
private SpokeBasic dyanmicArray(TokenEnumerator enumerator, int tabIndex,
evalInformation inf) throws Exception {
SpokeArray ars = new SpokeArray(new SpokeItem[0]);
ArrayList<SpokeItem> parameters = new ArrayList<SpokeItem>();
enumerator.MoveNext();
if (enumerator.getCurrent().getType() == Token.CloseSquare) {
enumerator.MoveNext();
ars.Parameters = parameters
.toArray(new SpokeItem[parameters.size()]);
return (ars);
}
while (true) {
parameters.add((SpokeItem) eval(enumerator, tabIndex,
new evalInformation(inf).ResetCurrentVal(true)));
switch (enumerator.getCurrent().getType()) {
case CloseSquare:
enumerator.MoveNext();
break;
case Comma:
enumerator.MoveNext();
continue;
default:
throw new Exception("Bad");
}
break;
}
ars.Parameters = parameters.toArray(new SpokeItem[parameters.size()]);
return (ars);
}
}
| gpl-3.0 |
angecab10/travelport-uapi-tutorial | src/com/travelport/schema/cruise_v29_0/Balance.java | 6510 |
package com.travelport.schema.cruise_v29_0;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
import com.sun.xml.bind.Locatable;
import com.sun.xml.bind.annotation.XmlLocation;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.cxf.xjc.runtime.JAXBToStringStyle;
import org.xml.sax.Locator;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attGroup ref="{http://www.travelport.com/schema/cruise_v29_0}attrDueReceivedDates"/>
* <attribute name="CreditCardDueAmount" type="{http://www.travelport.com/schema/common_v29_0}typeMoney" />
* <attribute name="CheckDueAmount" type="{http://www.travelport.com/schema/common_v29_0}typeMoney" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "Balance")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public class Balance
implements Locatable
{
@XmlAttribute(name = "CreditCardDueAmount")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
protected String creditCardDueAmount;
@XmlAttribute(name = "CheckDueAmount")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
protected String checkDueAmount;
@XmlAttribute(name = "DueDate")
@XmlSchemaType(name = "date")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
protected XMLGregorianCalendar dueDate;
@XmlAttribute(name = "ReceivedDate")
@XmlSchemaType(name = "date")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
protected XMLGregorianCalendar receivedDate;
@XmlLocation
@XmlTransient
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
protected Locator locator;
/**
* Gets the value of the creditCardDueAmount property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public String getCreditCardDueAmount() {
return creditCardDueAmount;
}
/**
* Sets the value of the creditCardDueAmount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public void setCreditCardDueAmount(String value) {
this.creditCardDueAmount = value;
}
/**
* Gets the value of the checkDueAmount property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public String getCheckDueAmount() {
return checkDueAmount;
}
/**
* Sets the value of the checkDueAmount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public void setCheckDueAmount(String value) {
this.checkDueAmount = value;
}
/**
* Gets the value of the dueDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public XMLGregorianCalendar getDueDate() {
return dueDate;
}
/**
* Sets the value of the dueDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public void setDueDate(XMLGregorianCalendar value) {
this.dueDate = value;
}
/**
* Gets the value of the receivedDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public XMLGregorianCalendar getReceivedDate() {
return receivedDate;
}
/**
* Sets the value of the receivedDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public void setReceivedDate(XMLGregorianCalendar value) {
this.receivedDate = value;
}
/**
* Generates a String representation of the contents of this type.
* This is an extension method, produced by the 'ts' xjc plugin
*
*/
@Override
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public String toString() {
return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.MULTI_LINE_STYLE);
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public Locator sourceLocation() {
return locator;
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:08:06-06:00", comment = "JAXB RI v2.2.6")
public void setSourceLocation(Locator newLocator) {
locator = newLocator;
}
}
| gpl-3.0 |
epam/Wilma | wilma-application/modules/wilma-route-engine/src/main/java/com/epam/wilma/router/helper/WilmaHttpRequestCloner.java | 2249 | package com.epam.wilma.router.helper;
/*==========================================================================
Copyright since 2013, EPAM Systems
This file is part of Wilma.
Wilma 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.
Wilma 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 Wilma. If not, see <http://www.gnu.org/licenses/>.
===========================================================================*/
import com.epam.wilma.domain.http.WilmaHttpRequest;
import com.epam.wilma.domain.http.header.HttpHeaderChange;
import org.springframework.stereotype.Component;
import java.util.Map.Entry;
/**
* Copies a {@link WilmaHttpRequest}.
* @author Tunde_Kovacs
*
*/
@Component
public class WilmaHttpRequestCloner {
/**
* Copies a {@link WilmaHttpRequest}'s headers and body to new instance.
* @param request the original request
* @return the new instance
*/
public WilmaHttpRequest cloneRequest(final WilmaHttpRequest request) {
WilmaHttpRequest result = new WilmaHttpRequest();
result.setRequestLine(request.getRequestLine());
result.setUri(request.getUri());
result.setBody(request.getBody());
result.setWilmaMessageId(request.getWilmaMessageId());
copyHeaders(request, result);
return result;
}
private void copyHeaders(final WilmaHttpRequest request, final WilmaHttpRequest result) {
for (Entry<String, String> header : request.getHeaders().entrySet()) {
result.addHeader(header.getKey(), header.getValue());
}
for (Entry<String, HttpHeaderChange> headerChanges : request.getHeaderChanges().entrySet()) {
result.addHeaderChange(headerChanges.getKey(), headerChanges.getValue());
}
}
}
| gpl-3.0 |
MrGenga/ServerCobweb | src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_A.java | 519 | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_A extends DataPacket {
public static byte ID = (byte) 0x8a;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_A();
}
}
}
| gpl-3.0 |
pippokill/tri | src/main/java/di/uniba/it/tri/script/gbooks/v2/GBooksMergeFreqV2.java | 4933 | /**
* Copyright (c) 2014, the Temporal Random Indexing AUTHORS.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the University of Bari nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*
* GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007
*
*/
package di.uniba.it.tri.script.gbooks.v2;
import di.uniba.it.tri.data.DictionaryEntry;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
/**
*
* @author pierpaolo
*/
public class GBooksMergeFreqV2 {
static Options options;
static CommandLineParser cmdParser = new BasicParser();
static {
options = new Options();
options.addOption("in", true, "Freq dir").
addOption("out", true, "Output file");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
CommandLine cmd = cmdParser.parse(options, args);
if (cmd.hasOption("in") && cmd.hasOption("out")) {
File corpusDir = new File(cmd.getOptionValue("in"));
File[] files = corpusDir.listFiles();
Map<String, Integer> dict = new HashMap<>();
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".freq")) {
Logger.getLogger(GBooksMergeFreqV2.class.getName()).log(Level.INFO, "Open file {0}", file.getName());
BufferedReader reader = new BufferedReader(new FileReader(file));
while (reader.ready()) {
String[] values = reader.readLine().split("\t");
Integer c = dict.get(values[0]);
if (c == null) {
dict.put(values[0], Integer.parseInt(values[1]));
} else {
dict.put(values[0], c + Integer.parseInt(values[1]));
}
}
reader.close();
}
}
List<DictionaryEntry> list = new ArrayList();
for (Map.Entry<String, Integer> e : dict.entrySet()) {
list.add(new DictionaryEntry(e.getKey(), e.getValue()));
}
Collections.sort(list, Collections.reverseOrder());
BufferedWriter writer = new BufferedWriter(new FileWriter(cmd.getOptionValue("out")));
for (DictionaryEntry e : list) {
writer.append(e.getWord()).append("\t").append(String.valueOf(e.getCounter()));
writer.newLine();
}
writer.close();
} else {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp("Build token frequencies file given ngram files", options, true);
}
} catch (Exception ex) {
Logger.getLogger(GBooksMergeFreqV2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| gpl-3.0 |
potty-dzmeia/db4o | src/db4ounit/src/db4ounit/ArrayAssert.java | 5298 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o 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 db4ounit;
import com.db4o.foundation.*;
/**
* @sharpen.partial
*/
public class ArrayAssert {
public static void contains(long[] array, long expected) {
if (-1 != indexOf(array, expected)) {
return;
}
Assert.fail("Expecting '" + expected + "'.");
}
public static void containsByIdentity(Object[] array, Object[] expected){
for (int i = 0; i < expected.length; i++) {
if (-1 == Arrays4.indexOfIdentity(array, expected[i])) {
Assert.fail("Expecting contains '" + expected[i] + "'.");
}
}
}
public static void containsByEquality(Object[] array, Object[] expected){
for (int i = 0; i < expected.length; i++) {
if (-1 == Arrays4.indexOfEquals(array, expected[i])) {
Assert.fail("Expecting contains '" + expected[i] + "'.");
}
}
}
public static void areEqual(Object[] expected, Object[] actual) {
areEqualImpl(expected, actual);
}
public static void areEqual(String[] expected, String[] actual) {
// JDK 1.1 needs the conversion
areEqualImpl(stringArrayToObjectArray(expected), stringArrayToObjectArray(actual));
}
private static Object[] stringArrayToObjectArray(String[] expected) {
Object[] expectedAsObject = new Object[expected.length];
System.arraycopy(expected, 0, expectedAsObject, 0, expected.length);
return expectedAsObject;
}
/**
* @sharpen.ignore
*/
private static void areEqualImpl(Object[] expected, Object[] actual) {
if (expected == actual) return;
if (expected == null || actual == null) Assert.areSame(expected, actual);
Assert.areEqual(expected.length, actual.length);
Assert.areSame(expected.getClass(), actual.getClass());
for (int i = 0; i < expected.length; i++) {
Assert.areEqual(expected[i], actual[i], indexMessage(i));
}
}
private static String indexMessage(int i) {
return "expected[" + i + "]";
}
public static void areEqual(byte[] expected, byte[] actual) {
if (expected == actual) return;
if (expected == null || actual == null) Assert.areSame(expected, actual);
Assert.areEqual(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
Assert.areEqual(expected[i], actual[i], indexMessage(i));
}
}
public static void areNotEqual(byte[] expected, byte[] actual) {
Assert.areNotSame(expected, actual);
for (int i = 0; i < expected.length; i++) {
if (expected[i] != actual[i]) return;
}
Assert.isTrue(false);
}
public static void areEqual(int[] expected, int[] actual) {
if (expected == actual) return;
if (expected == null || actual == null) Assert.areSame(expected, actual);
Assert.areEqual(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
Assert.areEqual(expected[i], actual[i], indexMessage(i));
}
}
public static void areEqual(long[] expected, long[] actual) {
if (expected == actual) return;
if (expected == null || actual == null) Assert.areSame(expected, actual);
Assert.areEqual(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
Assert.areEqual(expected[i], actual[i], indexMessage(i));
}
}
public static void areEqual(float[] expected, float[] actual) {
if (expected == actual) return;
if (expected == null || actual == null) Assert.areSame(expected, actual);
Assert.areEqual(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
Assert.areEqual(expected[i], actual[i], indexMessage(i));
}
}
public static void areEqual(double[] expected, double[] actual) {
if (expected == actual) return;
if (expected == null || actual == null) Assert.areSame(expected, actual);
Assert.areEqual(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
Assert.areEqual(expected[i], actual[i], indexMessage(i));
}
}
public static void areEqual(char[] expected, char[] actual) {
if (expected == actual) return;
if (expected == null || actual == null) Assert.areSame(expected, actual);
Assert.areEqual(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
Assert.areEqual(expected[i], actual[i], indexMessage(i));
}
}
private static int indexOf(long[] array, long expected) {
for (int i = 0; i < array.length; ++i) {
if (expected == array[i]) {
return i;
}
}
return -1;
}
}
| gpl-3.0 |
nairs77/GB-Android-SDK | GeBros/geBrosSDK/src/main/java/com/gebros/platform/net/okhttp/internal/okio/RealBufferedSink.java | 5044 | /*
* Copyright (C) 2014 Square, Inc.
*
* 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.gebros.platform.net.okhttp.internal.okio;
import java.io.IOException;
import java.io.OutputStream;
final class RealBufferedSink implements BufferedSink {
public final OkBuffer buffer;
public final Sink sink;
private boolean closed;
public RealBufferedSink(Sink sink, OkBuffer buffer) {
if (sink == null) throw new IllegalArgumentException("sink == null");
this.buffer = buffer;
this.sink = sink;
}
public RealBufferedSink(Sink sink) {
this(sink, new OkBuffer());
}
@Override
public OkBuffer buffer() {
return buffer;
}
@Override
public void write(OkBuffer source, long byteCount)
throws IOException {
checkNotClosed();
buffer.write(source, byteCount);
emitCompleteSegments();
}
@Override
public BufferedSink write(ByteString byteString) throws IOException {
checkNotClosed();
buffer.write(byteString);
return emitCompleteSegments();
}
@Override
public BufferedSink writeUtf8(String string) throws IOException {
checkNotClosed();
buffer.writeUtf8(string);
return emitCompleteSegments();
}
@Override
public BufferedSink write(byte[] source) throws IOException {
checkNotClosed();
buffer.write(source);
return emitCompleteSegments();
}
@Override
public BufferedSink write(byte[] source, int offset, int byteCount) throws IOException {
checkNotClosed();
buffer.write(source, offset, byteCount);
return emitCompleteSegments();
}
@Override
public BufferedSink writeByte(int b) throws IOException {
checkNotClosed();
buffer.writeByte(b);
return emitCompleteSegments();
}
@Override
public BufferedSink writeShort(int s) throws IOException {
checkNotClosed();
buffer.writeShort(s);
return emitCompleteSegments();
}
@Override
public BufferedSink writeInt(int i) throws IOException {
checkNotClosed();
buffer.writeInt(i);
return emitCompleteSegments();
}
@Override
public BufferedSink emitCompleteSegments() throws IOException {
checkNotClosed();
long byteCount = buffer.completeSegmentByteCount();
if (byteCount > 0) sink.write(buffer, byteCount);
return this;
}
@Override
public OutputStream outputStream() {
return new OutputStream() {
@Override
public void write(int b) throws IOException {
checkNotClosed();
buffer.writeByte((byte) b);
emitCompleteSegments();
}
@Override
public void write(byte[] data, int offset, int byteCount) throws IOException {
checkNotClosed();
buffer.write(data, offset, byteCount);
emitCompleteSegments();
}
@Override
public void flush() throws IOException {
// For backwards compatibility, a flush() on a closed stream is a no-op.
if (!RealBufferedSink.this.closed) {
RealBufferedSink.this.flush();
}
}
@Override
public void close() throws IOException {
RealBufferedSink.this.close();
}
@Override
public String toString() {
return RealBufferedSink.this + ".outputStream()";
}
private void checkNotClosed() throws IOException {
// By convention in java.io, IOException and not IllegalStateException is used.
if (RealBufferedSink.this.closed) {
throw new IOException("closed");
}
}
};
}
@Override
public void flush() throws IOException {
checkNotClosed();
if (buffer.size > 0) {
sink.write(buffer, buffer.size);
}
sink.flush();
}
@Override
public void close() throws IOException {
if (closed) return;
// Emit buffered data to the underlying sink. If this fails, we still need
// to close the sink; otherwise we risk leaking resources.
Throwable thrown = null;
try {
if (buffer.size > 0) {
sink.write(buffer, buffer.size);
}
} catch (Throwable e) {
thrown = e;
}
try {
sink.close();
} catch (Throwable e) {
if (thrown == null) thrown = e;
}
closed = true;
if (thrown != null) Util.sneakyRethrow(thrown);
}
@Override
public Sink deadline(Deadline deadline) {
sink.deadline(deadline);
return this;
}
@Override
public String toString() {
return "buffer(" + sink + ")";
}
private void checkNotClosed() {
if (closed) {
throw new IllegalStateException("closed");
}
}
}
| gpl-3.0 |
hneemann/Digital | src/test/java/de/neemann/digital/hdl/vhdl2/VHDLRenamingTest.java | 1158 | /*
* Copyright (c) 2018 Helmut Neemann.
* Use of this source code is governed by the GPL v3 license
* that can be found in the LICENSE file.
*/
package de.neemann.digital.hdl.vhdl2;
import junit.framework.TestCase;
public class VHDLRenamingTest extends TestCase {
public void testCheckName() {
VHDLRenaming r = new VHDLRenaming();
assertEquals("a", r.checkName("a"));
assertEquals("n0a", r.checkName("0a"));
assertEquals("p_in", r.checkName("in"));
assertEquals("a_u_in", r.checkName("a&u(in"));
assertEquals("a_in", r.checkName("a&ü(in"));
assertEquals("a_o_o", r.checkName("a\"o\"o"));
assertEquals("o", r.checkName("\"o\""));
assertEquals("o", r.checkName("_o_"));
assertEquals("notQ", r.checkName("/Q"));
assertEquals("notQ", r.checkName("!Q"));
assertEquals("notQ", r.checkName("~Q"));
assertEquals("aleb", r.checkName("a<b"));
assertEquals("agrb", r.checkName("a>b"));
assertEquals("aeqb", r.checkName("a=b"));
assertEquals("a_b", r.checkName("a\\_b"));
assertEquals("a_b", r.checkName("a\\^b"));
}
} | gpl-3.0 |
grtlinux/KIEA_JAVA7 | KIEA_JAVA7/src/tain/kr/com/test/sigar/v01/MemWatch.java | 4479 | /**
* Copyright 2014, 2015, 2016, 2017 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, 2017 TAIN, Inc.
*
*/
package tain.kr.com.test.sigar.v01;
import org.apache.log4j.Logger;
import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.Sigar;
/**
* Code Templates > Comments > Types
*
* <PRE>
* -. FileName : MemWatch.java
* -. Package : tain.kr.com.test.sigar.v01
* -. Comment :
* -. Author : taincokr
* -. First Date : 2017. 3. 17. {time}
* </PRE>
*
* @author taincokr
*
*/
public final class MemWatch {
private static boolean flag = true;
private static final Logger log = Logger.getLogger(MemWatch.class);
///////////////////////////////////////////////////////////////////////////////////////////////
private static final int SLEEP_TIME = 1000 * 10;
///////////////////////////////////////////////////////////////////////////////////////////////
/*
* constructor
*/
public MemWatch() {
if (flag)
log.debug(">>>>> in class " + this.getClass().getSimpleName());
}
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
private static StringBuffer diff(ProcMem last, ProcMem cur) {
StringBuffer sb = new StringBuffer();
long diff;
diff = cur.getSize() - last.getSize();
if (diff != 0) {
sb.append("size=" + diff);
}
diff = cur.getResident() - last.getResident();
if (diff != 0) {
sb.append(", resident=" + diff);
}
diff = cur.getShare() - last.getShare();
if (diff != 0) {
sb.append(", share=" + diff);
}
return sb;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/*
* static test method
*/
private static void test01(String[] args) throws Exception {
if (flag)
new MemWatch();
if (flag) {
Sigar sigar = new Sigar();
if (args.length != 1) {
throw new Exception("Usage: MemWatch pid");
}
long pid = Long.parseLong(args[0]);
long lastTime = System.currentTimeMillis();
ProcMem last = sigar.getProcMem(pid);
while (true) {
ProcMem cur = sigar.getProcMem(pid);
StringBuffer diff = diff(last, cur);
if (diff.length() == 0) {
System.out.println("no change " + "(size=" + Sigar.formatSize(cur.getSize()) + ")");
} else {
long curTime = System.currentTimeMillis();
long timeDiff = curTime - lastTime;
lastTime = curTime;
diff.append(" after " + timeDiff + "ms");
System.out.println(diff);
}
last = cur;
Thread.sleep(SLEEP_TIME);
}
}
}
/*
* main method
*/
public static void main(String[] args) throws Exception {
if (flag)
log.debug(">>>>> " + new Object() {
}.getClass().getEnclosingClass().getName());
if (flag) {
/*
* begin
*/
// test01(args);
test01(new String[] { "2648" });
}
}
}
| gpl-3.0 |
CMPUT301F13T08/CMPUT301F13T08 | Team08StoryApp/src/com/team08storyapp/PicAdapter.java | 7987 | /*
AUTHORS
========
Alice Wu, Ana Marcu, Michele Paulichuk, Jarrett Toll, Jiawei Shen.
LICENSE
=======
Copyright ��� 2013 Alice Wu, Ana Marcu, Michele Paulichuk, Jarrett Toll, Jiawei Shen,
Free Software Foundation, Inc., Marky Mark License GPLv3+: GNU
GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
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/>.
3rd Party Libraries
=============
Retrieved Oct. 27, 2013 - https://github.com/rayzhangcl/ESDemo
-This demo was used to help with JSON and ESHelper which is under the CC0 licenses
Retrieved Oct. 29, 2013 - http://hc.apache.org/downloads.cgi
-This is for the fluent library which is licensed under apache V2
Retrieved Oct. 29, 2013
- https://code.google.com/p/google-gson/downloads/detail?name=google-gson-2.2.4-release.zip&can=2&q=
-This is for JSON which is licensed under apache V2
*/
package com.team08storyapp;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
/**
* PicAdapter is a customized Adapter based on BaseAdapter
*
* @author Sue Smith
* @author Michele Paulichuk
* @author Alice Wu
* @author Ana Marcu
* @author Jarrett Toll
* @author Jiawei Shen
* @version 1.0 November 8, 2013
* @since 1.0
*
*/
@SuppressWarnings("deprecation")
public class PicAdapter extends BaseAdapter {
/* use the default gallery background image */
int defaultItemBackground;
/* gallery context */
private Context galleryContext;
/* array to store bitmaps to display */
private Bitmap[] imageBitmaps;
/* placeholder bitmap for empty spaces in gallery */
Bitmap placeholder;
@SuppressWarnings("unused")
private ArrayList<Photo> pList;
/**
* This constructor of PicAdapter will populate all images from photoList
* into a gallery with customized getView function.
*
*
* @param context
* a context object
* @param photoList
* a list of photo objects
* @param currentStoryId
* the id of current story object
* @param currentStoryFragmentId
* the id of the current story fragment object
*/
public PicAdapter(Context context, ArrayList<Photo> photoList,
int currentStoryId, int currentStoryFragmentId) {
pList = photoList;
/* instantiate context */
galleryContext = context;
/* create bitmap array */
imageBitmaps = new Bitmap[5];
/* decode the placeholder image */
placeholder = BitmapFactory.decodeResource(
galleryContext.getResources(), R.drawable.ic_launcher);
/* decode the placeholder image */
placeholder = BitmapFactory.decodeResource(
galleryContext.getResources(), R.drawable.ic_launcher);
/* set placeholder as all thumbnail images in the gallery initially */
for (int i = 0; i < imageBitmaps.length; i++)
imageBitmaps[i] = placeholder;
if (photoList.size() > 0) {
File file = galleryContext.getFilesDir();
File[] fileList = file.listFiles();
ArrayList<File> prefixFileList = new ArrayList<File>();
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].getName().startsWith(
"Image" + Integer.toString(currentStoryId) + "Fragment"
+ Integer.toString(currentStoryFragmentId)
+ "Photo")) {
prefixFileList.add(fileList[i]);
}
}
for (int i = 0; i < Math.min(imageBitmaps.length,
prefixFileList.size()); i++) {
String path = prefixFileList.get(i).getAbsolutePath();
placeholder = BitmapFactory.decodeFile(path);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
placeholder.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytePicture = stream.toByteArray();
imageBitmaps[i] = BitmapFactory.decodeByteArray(bytePicture, 0,
bytePicture.length);
}
}
/* get the styling attributes - use default Android system resources */
TypedArray styleAttrs = galleryContext
.obtainStyledAttributes(R.styleable.PicGallery);
/* get the background resource */
defaultItemBackground = styleAttrs.getResourceId(
R.styleable.PicGallery_android_galleryItemBackground, 0);
/* recycle attributes */
styleAttrs.recycle();
}
/**
* This function gives the number of bitmap images to be displayed in the
* adapter
*
* @return The length of the current Bitmaps array
*/
public int getCount() {
return imageBitmaps.length;
}
/**
* This function returns the photo in the adapter at the given index
*
* @param position
* the index of the selected photo in the adapter
*
* @return The photo at the given adapter index
*/
public Object getItem(int position) {
return position;
}
/**
* This function retrieves the id of the photo at the given adapter index
*
* @param position
* the index of the selected photo in the adapter
*
* @return The id of the photo at the given adapter index
*/
public long getItemId(int position) {
return position;
}
/**
* get view specifies layout and display options for each thumbnail in the
* gallery
*
* @param position
* the index of the selected photo in the adapter
* @param convertView
* the view that is going to be converted to user's desire
* @param parent
* a ViewGroup object
* @return the converted view for the Photo
*/
public View getView(int position, View convertView, ViewGroup parent) {
/* create the view */
ImageView imageView = new ImageView(galleryContext);
/* specify the bitmap at this position in the array */
imageView.setImageBitmap(imageBitmaps[position]);
/* set layout options */
imageView.setLayoutParams(new Gallery.LayoutParams(300, 200));
/* scale type within view area */
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
/* set default gallery item background */
imageView.setBackgroundResource(defaultItemBackground);
/* return the view */
return imageView;
}
/**
* addPic method is a helper method to add a bitmap to the gallery when the
* user chooses one
*
* @param currentPic
* the index in the imageBitmaps
* @param newPic
* new bitmap object that will be added to the currentPic
* position in the imageBitmaps
*/
public void addPic(int currentPic, Bitmap newPic) {
/* set at currently selected index */
imageBitmaps[currentPic] = newPic;
}
/**
* getPic returns bitmap at specified position for larger display
*
* @param position
* the index of the desired picture in the imageBitmaps
* @return the bitmap at the given position
*/
public Bitmap getPic(int position) {
/* return bitmap at position index */
return imageBitmaps[position];
}
} | gpl-3.0 |
ricecakesoftware/CommunityMedicalLink | ricecakesoftware.communitymedicallink.documentconsumer/src/main/java/ricecakesoftware/communitymedicallink/documentconsumer/index/MainAction.java | 852 | package ricecakesoftware.communitymedicallink.documentconsumer.index;
import ricecakesoftware.common.web.action.BaseAction;
import ricecakesoftware.communitymedicallink.documentconsumer.index.process.InitializeProcess;
import ricecakesoftware.communitymedicallink.documentconsumer.index.process.StartProcess;
/**
* メインアクション
* @author RCSW)Y.Omoya
*/
public class MainAction extends BaseAction<MainForm> {
/**
* コンストラクター
*/
public MainAction() {
super();
}
/**
* 初期化
*/
@Override
protected void initialize() {
InitializeProcess process = new InitializeProcess();
process.perform(this.form);
}
/**
* 開始
* @return 処理結果
*/
public String start() {
StartProcess process = new StartProcess();
return process.perform(this.form);
}
}
| gpl-3.0 |
gitools/gitools | org.gitools.ui.core/src/main/java/org/gitools/ui/core/actions/HeatmapAction.java | 1834 | /*
* #%L
* gitools-ui-app
* %%
* Copyright (C) 2013 Universitat Pompeu Fabra - Biomedical Genomics group
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package org.gitools.ui.core.actions;
import org.gitools.api.components.IEditor;
import org.gitools.heatmap.Heatmap;
import org.gitools.ui.core.Application;
import org.gitools.ui.core.components.editor.EditorsPanel;
public abstract class HeatmapAction extends AbstractAction {
public HeatmapAction(String name) {
super(name);
setDesc(name);
}
@Override
public boolean isEnabledByModel(Object model) {
return model instanceof Heatmap;
}
protected IEditor getSelectedEditor() {
return getEditorsPanel().getSelectedEditor();
}
protected EditorsPanel getEditorsPanel() {
return Application.get().getEditorsPanel();
}
protected Heatmap getHeatmap() {
IEditor editor = getSelectedEditor();
Object model = editor != null ? editor.getModel() : null;
if (!(model instanceof Heatmap)) {
throw new UnsupportedOperationException("This action is only valid on a heatmap editor");
}
return (Heatmap) model;
}
}
| gpl-3.0 |
srnsw/xena | plugins/pdf/ext/src/jpedal_lgpl-3.83b38/src/org/jpedal/utils/repositories/Vector_Short.java | 5979 | /**
* ===========================================
* Java Pdf Extraction Decoding Access Library
* ===========================================
*
* Project Info: http://www.jpedal.org
* (C) Copyright 1997-2008, IDRsolutions and Contributors.
*
* This file is part of JPedal
*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* ---------------
* Vector_Short.java
* ---------------
*/
package org.jpedal.utils.repositories;
import java.io.Serializable;
/**
* Provides the functionality/convenience of a Vector for shorts
*
* Much faster because not synchronized and no cast
* Does not double in size each time
*/
public class Vector_Short implements Serializable
{
//how much we resize each time - will be doubled up to 160
int increment_size = 1000;
protected int current_item = 0;
//current max size
int max_size = 250;
//holds the data
private short[] items = new short[max_size];
//default size
public Vector_Short()
{
}
protected static int incrementSize(int increment_size){
if(increment_size<8000)
increment_size=increment_size*4;
else if(increment_size<16000)
increment_size=increment_size*2;
else
increment_size=increment_size+2000;
return increment_size;
}
//set size
public Vector_Short( int number )
{
max_size = number;
items = new short[max_size];
}
///////////////////////////////////
/**
* get element at
*/
final public short elementAt( int id )
{
if( id >= max_size )
return (short)0;
else
return items[id];
}
///////////////////////////////////
/**
* extract underlying data
*/
final public short[] get()
{
return items;
}
///////////////////////////////////
/**
* set an element
*/
final public void setElementAt( short new_name, int id )
{
if( id >= max_size )
checkSize( id );
items[id] = new_name;
}
///////////////////////////////////
/**
* replace underlying data
*/
final public void set( short[] new_items )
{
items = new_items;
}
////////////////////////////////////
//merge together using larger as new value
final public void keep_larger( short master, short child )
{
if( items[master] < items[child] )
items[master] = items[child];
}
////////////////////////////////////
//merge to keep smaller
final public void keep_smaller( short master, short child )
{
if( items[master] > items[child] )
items[master] = items[child];
}
///////////////////////////////////
/**
* clear the array
*/
final public void clear()
{
//items = null;
//holds the data
//items = new short[max_size];
if(current_item>0){
for(int i=0;i<current_item;i++)
items[i]=0;
}else{
for(int i=0;i<max_size;i++)
items[i]=0;
}
current_item = 0;
}
///////////////////////////////////
/**
* return the size
*/
final public int size()
{
return current_item + 1;
}
///////////////////////////////////
/**
* remove element at
*/
final public void removeElementAt( int id )
{
if( id >= 0 )
{
//copy all items back one to over-write
System.arraycopy(items, id + 1, items, id, current_item - 1 - id);
//flush last item
items[current_item - 1] = 0;
}
else
items[0] = 0;
//reduce counter
current_item--;
}
////////////////////////////////////
/**
* see if value present
*/
final public boolean contains( short value )
{
boolean flag = false;
for( int i = 0;i < current_item;i++ )
{
if( items[i] == value )
{
i = current_item + 1;
flag = true;
}
}
return flag;
}
/////////////////////////////////////
/**
* pull item from top as in LIFO stack
*/
final public short pull()
{
if(current_item>0)
current_item--;
return ( items[current_item] );
}
/////////////////////////////////////
/**
* put item at top as in LIFO stack
*/
final public void push( short value )
{
checkSize( current_item );
items[current_item] = value;
current_item++;
}
///////////////////////////////////
/**
* add an item
*/
final public void addElement( short value )
{
checkSize( current_item );
items[current_item] = value;
current_item++;
}
////////////////////////////////////
//merge together using larger as new value
final public void add_together( short master, short child )
{
items[master] = (short)(items[master] + items[child]);
}
////////////////////////////////////
/**
* check the size of the array and increase if needed
*/
final private void checkSize( int i )
{
if( i >= max_size )
{
int old_size = max_size;
max_size = max_size + increment_size;
//allow for it not creating space
if( max_size <= i )
max_size = i +increment_size+ 2;
short[] temp = items;
items = new short[max_size];
System.arraycopy( temp, 0, items, 0, old_size );
//increase size increase for next time
increment_size=incrementSize(increment_size);
}
}
public void trim(){
short[] newItems = new short[current_item];
System.arraycopy(items,0,newItems,0,current_item);
items=newItems;
max_size=current_item;
}
/**reset pointer used in add to remove items above*/
public void setSize(int currentItem) {
current_item=currentItem;
}
}
| gpl-3.0 |
ymachkivskiy/hage | platform/platform-components/simulation-config/simulation-config-load/load-adapter/src/main/java/org/hage/platform/component/simulationconfig/load/definition/agent/AgentCountData.java | 1855 | package org.hage.platform.component.simulationconfig.load.definition.agent;
import lombok.Getter;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Optional.ofNullable;
public final class AgentCountData {
private static final AgentCountData RANDOM = new AgentCountData(AgentCountMode.RANDOM, 1);
@Getter
private final AgentCountMode agentCountMode;
@Getter
private final Optional<Integer> value;
@Getter
private final Optional<Integer> secondaryValue;
private AgentCountData(AgentCountMode agentCountMode, Integer value, Integer secondaryValue) {
checkArgument(value == null || value > 0, "Primary value should be greater than zero but is " + value);
checkArgument(secondaryValue == null || secondaryValue > 0, "Secondary value should be greater than zero but is " + secondaryValue);
this.agentCountMode = agentCountMode;
this.value = ofNullable(value);
this.secondaryValue = ofNullable(secondaryValue);
}
private AgentCountData(AgentCountMode agentCountMode, Integer value) {
this(agentCountMode, value, null);
}
public static AgentCountData fixed(int number) {
return new AgentCountData(AgentCountMode.FIXED, number);
}
public static AgentCountData atLeast(int number) {
return new AgentCountData(AgentCountMode.AT_LEAST, number);
}
public static AgentCountData atMost(int number) {
return new AgentCountData(AgentCountMode.AT_MOST, number);
}
public static AgentCountData between(int lowerBound, int upperBound) {
checkArgument(lowerBound <= upperBound);
return new AgentCountData(AgentCountMode.BETWEEN, lowerBound, upperBound);
}
public static AgentCountData random() {
return RANDOM;
}
}
| gpl-3.0 |
daboross/OutputTablesClient | src/main/java/net/daboross/outputtablesclient/gui/StaleInterface.java | 6879 | package net.daboross.outputtablesclient.gui;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import net.daboross.outputtablesclient.main.Application;
import net.daboross.outputtablesclient.util.GBC;
import org.ingrahamrobotics.robottables.api.RobotTable;
import org.ingrahamrobotics.robottables.api.RobotTablesClient;
import org.ingrahamrobotics.robottables.api.TableType;
import org.ingrahamrobotics.robottables.api.listeners.ClientUpdateListener;
public class StaleInterface implements ClientUpdateListener {
private final RobotTablesClient tablesClient;
private final AtomicInteger nextStaleY = new AtomicInteger();
private final AtomicInteger nextSubscriberStaleY = new AtomicInteger();
private final Map<String, JLabel> subscriberStaleTableLabels = new HashMap<>();
private final Map<String, JLabel> staleTableLabels = new HashMap<>();
private final Map<String, JLabel> staleStateLabels = new HashMap<>();
private final Map<String, JLabel> subscriberStaleStateLabels = new HashMap<>();
private final JPanel stalePanel;
private final JLabel mainStatusLabel;
private final JPanel subscriberStalePanel;
public StaleInterface(final Application application) {
this.tablesClient = application.getTables();
// mainTabPanel
JPanel mainTabPanel = new JPanel(new GridBagLayout());
mainTabPanel.setBorder(new TitledBorder("status"));
application.getRoot().getTabbedPane().add(mainTabPanel, "Status", 3);
stalePanel = new JPanel(new GridBagLayout());
mainTabPanel.add(stalePanel, new GBC().weightx(1).fill(GridBagConstraints.BOTH).gridy(0).anchor(GridBagConstraints.EAST));
subscriberStalePanel = new JPanel(new GridBagLayout());
mainTabPanel.add(subscriberStalePanel, new GBC().weightx(1).fill(GridBagConstraints.BOTH).gridy(1).anchor(GridBagConstraints.EAST));
mainStatusLabel = new JLabel("DISCONNECTED - NO INITIAL CONNECTION RECEIVED");
mainStatusLabel.setFont(mainStatusLabel.getFont().deriveFont(20f));
mainStatusLabel.setBorder(new EmptyBorder(5, 5, 5, 5));
application.getRoot().getMainPanel().add(mainStatusLabel,
new GBC().weightx(1).gridx(0).gridy(0).anchor(GridBagConstraints.NORTH).gridwidth(2));
// stalePanel refresh
stalePanel.revalidate();
}
@Override
public void onTableChangeType(final RobotTable table, final TableType oldType, final TableType newType) {
JLabel tableLabel;
JLabel stateLabel;
JPanel panel;
switch (table.getType()) {
case LOCAL:
tableLabel = subscriberStaleTableLabels.remove(table.getName());
stateLabel = subscriberStaleStateLabels.remove(table.getName());
panel = subscriberStalePanel;
break;
case REMOTE:
tableLabel = staleTableLabels.remove(table.getName());
stateLabel = staleStateLabels.remove(table.getName());
panel = stalePanel;
break;
default:
return;
}
// minimum code duplication
panel.remove(tableLabel);
panel.remove(stateLabel);
panel.revalidate();
updateMainStatusLabel();
}
@Override
public void onTableStaleChange(final RobotTable table, final boolean nowStale) {
staleStateLabels.get(table.getName()).setText(nowStale ? "stale" : "fresh");
stalePanel.revalidate();
updateMainStatusLabel();
}
@Override
public void onAllSubscribersStaleChange(final RobotTable table, final boolean nowStale) {
subscriberStaleStateLabels.get(table.getName()).setText(nowStale ? "robot stale" : "robot fresh");
subscriberStalePanel.revalidate();
updateMainStatusLabel();
}
@Override
public void onNewTable(final RobotTable table) {
switch (table.getType()) {
case LOCAL:
addLocalTable(table.getName());
break;
case REMOTE:
addRemoteTable(table.getName());
break;
}
updateMainStatusLabel();
}
private void addLocalTable(String tableName) {
int gridY = nextSubscriberStaleY.getAndAdd(1);
JLabel tableLabel = new JLabel(tableName);
tableLabel.setBorder(new EmptyBorder(5, 5, 5, 5));
subscriberStaleTableLabels.put(tableName, tableLabel);
subscriberStalePanel.add(tableLabel, new GBC().gridx(0).gridy(gridY).anchor(GridBagConstraints.WEST));
JLabel stateLabel = new JLabel("robot stale");
stateLabel.setBorder(new EmptyBorder(5, 5, 5, 5));
subscriberStaleStateLabels.put(tableName, stateLabel);
subscriberStalePanel.add(stateLabel, new GBC().gridx(1).gridy(gridY).anchor(GridBagConstraints.EAST));
subscriberStalePanel.revalidate();
}
private void addRemoteTable(String tableName) {
int gridY = nextStaleY.getAndAdd(1);
JLabel tableLabel = new JLabel(tableName);
tableLabel.setBorder(new EmptyBorder(5, 5, 5, 5));
staleTableLabels.put(tableName, tableLabel);
stalePanel.add(tableLabel, new GBC().gridx(0).gridy(gridY).anchor(GridBagConstraints.WEST));
JLabel stateLabel = new JLabel("stale");
stateLabel.setBorder(new EmptyBorder(5, 5, 5, 5));
staleStateLabels.put(tableName, stateLabel);
stalePanel.add(stateLabel, new GBC().gridx(1).gridy(gridY).anchor(GridBagConstraints.EAST));
stalePanel.revalidate();
}
private void updateMainStatusLabel() {
boolean localStale = false;
boolean remoteStale = false;
for (RobotTable table : tablesClient.getTableSet()) {
if (table.getType() == TableType.LOCAL) {
if (table.isSubcriberStale()) {
localStale = true;
}
} else {
if (table.isStale()) {
remoteStale = true;
}
}
}
if (localStale) {
if (remoteStale) {
mainStatusLabel.setText("DISCONNECTED - NOT ALL ROBOT SETTINGS ARE ACTIVE, NOT ALL DATA IS UP TO DATE");
} else {
mainStatusLabel.setText("DISCONNECTED - NOT ALL ROBOT SETTINGS ARE ACTIVE");
}
} else {
if (remoteStale) {
mainStatusLabel.setText("DISCONNECTED - NOT ALL DATA IS UP TO DATE");
} else {
mainStatusLabel.setText("CONNECTED - ALL UP TO DATE");
}
}
}
}
| gpl-3.0 |
zer0square/SoftArch-DesignECE437Assignment1 | src-assignment2/TALessThan.java | 1772 | import java.util.ArrayList;
/*
Type Abstraction for less than operation
*/
public class TALessThan extends TABool implements TAFormula {
private Boolean value_lessthan;
private TANumber operand1, operand2;
private String name = null;
TALessThan(TAInt a, TAInt b){
operand1 = a;
operand2 = b;
}
TALessThan(String s, TAInt a, TAInt b) throws Exception {
NamesChecker.check(s);
name = s;
operand1 = a;
operand2 = b;
}
TALessThan(TADouble a , TADouble b){
operand1 = a;
operand2 = b;
}
TALessThan(String s,TADouble a , TADouble b) throws Exception {
NamesChecker.check(s);
name = s;
operand1 = a;
operand2 = b;
}
public Boolean getValue() {
return value_lessthan;
}
public void evaluate(){
if(operand1.getValue().doubleValue() < operand2.getValue().doubleValue())
value_lessthan = true;
else
value_lessthan = false;
}
@Override
public TAPrimitive getValueTA() {
return new TABool(value_lessthan);
}
public void list(){
if(name == null) {
System.out.print("(< ");
operand1.list();
System.out.print(" ");
operand2.list();
System.out.print(" )");
}
else
System.out.print(name);
}
public ArrayList getOperands(){
ArrayList opList = new ArrayList();
// opList.addAll(operand1.getOperands());
// opList.addAll(operand2.getOperands());
opList.add(operand1);
opList.add(operand2);
return opList;
}
public void printState(){
System.out.println(value_lessthan);
}
} | gpl-3.0 |
jbundle/jbundle | thin/main/src/main/java/org/jbundle/thin/main/db/DatabaseInfo.java | 2827 | /**
* @(#)DatabaseInfo.
* Copyright © 2013 jbundle.org. All rights reserved.
* GPL3 Open Source Software License.
*/
package org.jbundle.thin.main.db;
import java.util.*;
import org.jbundle.thin.base.util.*;
import org.jbundle.thin.base.db.*;
import org.jbundle.model.main.db.*;
public class DatabaseInfo extends FieldList
implements DatabaseInfoModel
{
private static final long serialVersionUID = 1L;
public DatabaseInfo()
{
super();
}
public DatabaseInfo(Object recordOwner)
{
this();
this.init(recordOwner);
}
public static final String DATABASE_INFO_FILE = "DatabaseInfo";
/**
* Get the table name.
*/
public String getTableNames(boolean bAddQuotes)
{
return (m_tableName == null) ? DatabaseInfo.DATABASE_INFO_FILE : super.getTableNames(bAddQuotes);
}
/**
* Get the Database Name.
*/
public String getDatabaseName()
{
return "DatabaseInfo";
}
/**
* Is this a local (vs remote) file?.
*/
public int getDatabaseType()
{
return Constants.REMOTE | Constants.SHARED_DATA;
}
/**
* Set up the screen input fields.
*/
public void setupFields()
{
FieldInfo field = null;
field = new FieldInfo(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null);
field.setDataClass(Integer.class);
field.setHidden(true);
field = new FieldInfo(this, LAST_CHANGED, Constants.DEFAULT_FIELD_LENGTH, null, null);
field.setDataClass(Date.class);
field.setHidden(true);
field = new FieldInfo(this, DELETED, 10, null, new Boolean(false));
field.setDataClass(Boolean.class);
field.setHidden(true);
field = new FieldInfo(this, NAME, 30, null, null);
field = new FieldInfo(this, DESCRIPTION, 30, null, null);
field = new FieldInfo(this, VERSION, 20, null, null);
field = new FieldInfo(this, START_ID, 10, null, null);
field.setDataClass(Integer.class);
field = new FieldInfo(this, END_ID, 10, null, null);
field.setDataClass(Integer.class);
field = new FieldInfo(this, BASE_DATABASE, 30, null, null);
field = new FieldInfo(this, PROPERTIES, Constants.DEFAULT_FIELD_LENGTH, null, null);
}
/**
* Set up the key areas.
*/
public void setupKeys()
{
KeyAreaInfo keyArea = null;
keyArea = new KeyAreaInfo(this, Constants.UNIQUE, ID_KEY);
keyArea.addKeyField(ID, Constants.ASCENDING);
keyArea = new KeyAreaInfo(this, Constants.NOT_UNIQUE, NAME_KEY);
keyArea.addKeyField(NAME, Constants.ASCENDING);
}
/**
* SetDatabaseName Method.
*/
public void setDatabaseName(String databaseName)
{
// Not used in thin impl
}
}
| gpl-3.0 |
metalx1000/MyBin | android/apks/hello_world/src/com/filmsbykris/tester/MainActivity.java | 351 | package com.filmsbykris.tester;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
| gpl-3.0 |
EBINEUTRINO/EBINeutrino | src/org/sdk/utils/EBIReportFilter.java | 437 | package org.sdk.utils;
import java.io.File;
/** Filter to work with JFileChooser to select jasper file types. **/
public class EBIReportFilter extends javax.swing.filechooser.FileFilter {
@Override
public boolean accept (final File f) {
return f.getName ().toLowerCase ().endsWith (".jasper") || f.isDirectory();
}
@Override
public String getDescription () {
return "Reportdatei (*.jasper)";
}
} // class JavaFilter | gpl-3.0 |
Sandman671/VideoRent | src/conexion/CajaClienteBD.java | 492 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package conexion;
import java.sql.ResultSet;
/**
*
* @author Marcelo Cazon <sandman.net@gmail.com>
*/
public class CajaClienteBD {
private int datos;
conexionBD conecta = new conexionBD();
private ResultSet rs;
public ResultSet clientescombobox(){
rs = this.conecta.Consulta("SELECT dni FROM cliente");
return rs;
}
}
| gpl-3.0 |
icgc-dcc/dcc-downloader | dcc-downloader-client/src/main/java/org/icgc/dcc/downloader/client/ArchiveOutputStream.java | 9046 | /*
* 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.downloader.client;
import static com.google.common.collect.Lists.newArrayList;
import static org.icgc.dcc.downloader.core.ArchiverConstant.END_OF_LINE;
import static org.icgc.dcc.downloader.core.ArchiverConstant.TSV_DELIMITER;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;
import lombok.AllArgsConstructor;
import lombok.Cleanup;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.hbase.util.Bytes;
import org.icgc.dcc.downloader.core.DataType;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
@Slf4j
@RequiredArgsConstructor
class ArchiveOutputStream {
@NonNull
private final Path dynamicDownloadPath;
@NonNull
private final Configuration conf;
private static final String EXTENSION = ".tsv.gz";
private final static long MAX_BUCKET_SIZE = 4294967296L; // 4 GB per tar
public boolean streamArchiveInGzTar(OutputStream out, String downloadId,
List<DataType> downloadedDataTypes, Map<DataType, List<String>> headersLookupMap) throws IOException {
try {
FileSystem fs = FileSystem.get(dynamicDownloadPath.toUri(), conf);
Path downloadPath = new Path(dynamicDownloadPath, downloadId);
FileStatus[] files = fs.listStatus(downloadPath);
if (files == null) return false;
ImmutableList.Builder<List<PathBucket>> builder = ImmutableList.builder();
for (val dataType : downloadedDataTypes) {
Path downloadTypePath = new Path(downloadPath, dataType.indexName);
if (fs.exists(downloadTypePath)) {
// the directory name is the data type index name
log.info("Trying to download data for download id : "
+ downloadId + ", Data Type: " + dataType);
builder.add(bucketize(fs, downloadTypePath,
dataType, headersLookupMap.get(dataType)));
}
}
@Cleanup
TarArchiveOutputStream tarOut = new TarArchiveOutputStream(
new BufferedOutputStream(out));
List<List<PathBucket>> entryDataTypes = builder.build();
for (val tarEntryInputs : entryDataTypes) {
boolean isMultiPart = (tarEntryInputs.size() > 1) ? true : false;
for (val bucket : tarEntryInputs) {
byte[] header = gzipHeader(Bytes.toBytes(bucket.getHeader()));
String extension = (isMultiPart) ? ".part-" + bucket.getBucketNumber() + EXTENSION : EXTENSION;
addArchiveEntry(tarOut, bucket.getBucketName() + extension,
bucket.getSize() + header.length);
concatGZipFiles(fs, tarOut, bucket.getPaths(), header);
closeArchiveEntry(tarOut);
}
}
return true;
} catch (Exception e) {
log.error("Fail to produce an archive for download id: "
+ downloadId + ", download data Types: " + downloadedDataTypes, e);
}
return false;
}
private byte[] gzipHeader(byte[] header) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gout = new GZIPOutputStream(bos) {
{
def.setLevel(Deflater.BEST_SPEED);
}
};
gout.write(header);
gout.write(END_OF_LINE);
gout.close();
return bos.toByteArray();
}
public boolean streamArchiveInGz(OutputStream out, String downloadId,
DataType dataType, Map<DataType, List<String>> headerLookupMap) throws IOException {
try {
FileSystem fs = FileSystem.get(dynamicDownloadPath.toUri(), conf);
Path dataTypePath = new Path(dynamicDownloadPath, new Path(
downloadId, dataType.indexName));
RemoteIterator<LocatedFileStatus> files = fs.listFiles(
dataTypePath, false);
List<Path> paths = newArrayList();
while (files.hasNext()) {
paths.add(files.next().getPath());
}
@Cleanup
OutputStream managedOut = out;
concatGZipFiles(
fs,
managedOut,
paths,
gzipHeader(Bytes.toBytes(formatHeader(headerLookupMap.get(dataType)))));
return true;
} catch (Exception e) {
log.error("Fail to stream archive. DownloadID: " + downloadId, e);
}
return false;
}
private String formatHeader(List<String> headers) {
return Joiner.on(Bytes.toString(TSV_DELIMITER)).join(headers);
}
private List<PathBucket> bucketize(FileSystem fs, Path dataTypePath,
DataType allowedType, List<String> headers) throws IOException {
// First-Fit Algorithm
String header = formatHeader(headers);
List<PathBucket> buckets = newArrayList();
RemoteIterator<LocatedFileStatus> files = fs.listFiles(dataTypePath,
false);
int bucketNum = 1;
while (files.hasNext()) {
LocatedFileStatus file = files.next();
boolean isFound = false;
if (file.getLen() > MAX_BUCKET_SIZE) {
log.error("File size too big to fit into a single bucket (Tar Entry Limitation): "
+ file.getPath());
throw new RuntimeException(
"Cannot tar the entry with file size exceeding the limit :"
+ file.getPath());
} else {
for (val bucket : buckets) {
if ((bucket.getSize() + file.getLen()) < MAX_BUCKET_SIZE) {
bucket.add(file.getLen(), file.getPath());
isFound = true;
continue;
}
}
if (!isFound) {
PathBucket newBucket = new PathBucket(
dataTypePath.getName(), bucketNum,
header, file.getLen(), newArrayList(file.getPath()));
buckets.add(newBucket);
bucketNum++;
}
}
}
return buckets;
}
private void concatGZipFiles(FileSystem fs, OutputStream out,
List<Path> files, byte[] header) throws IOException {
IOUtils.write(header, out);
for (val file : files) {
FSDataInputStream is = fs.open(file);
try {
IOUtils.copy(is, out);
} finally {
is.close();
}
}
}
@SneakyThrows
private static void addArchiveEntry(TarArchiveOutputStream os,
String filename, long fileSize) {
TarArchiveEntry entry = new TarArchiveEntry(filename);
entry.setSize(fileSize);
os.putArchiveEntry(entry);
}
@SneakyThrows
private static void closeArchiveEntry(TarArchiveOutputStream os) {
os.closeArchiveEntry();
}
@Data
@AllArgsConstructor
private static class PathBucket {
String bucketName;
int bucketNumber;
String header;
long size;
List<Path> paths;
public void add(long size, Path path) {
this.size = this.size + size;
paths.add(path);
}
}
}
| gpl-3.0 |
DRE2N/FactionsXL | src/main/java/de/erethon/factionsxl/player/AsyncPowerTask.java | 2543 | /*
* Copyright (c) 2017-2019 Daniel Saukel
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.erethon.factionsxl.player;
import de.erethon.factionsxl.FactionsXL;
import de.erethon.factionsxl.config.FData;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
/**
* @author Daniel Saukel
*/
public class AsyncPowerTask extends BukkitRunnable {
FData data = FactionsXL.getInstance().getFData();
private double increaseRate;
private double decreaseRate;
private int maxPower;
public AsyncPowerTask(double increaseRate, double decreaseRate, int maxPower) {
this.increaseRate = increaseRate;
this.decreaseRate = decreaseRate;
this.maxPower = maxPower;
}
@Override
public void run() {
Map<UUID, Double> updatedPower = new HashMap<>();
for (Entry<UUID, Double> entry : data.power.entrySet()) {
UUID uuid = entry.getKey();
double power = entry.getValue();
if (Bukkit.getOnlinePlayers().contains(Bukkit.getPlayer(uuid))) {
continue;
}
if (power > 0) {
power -= decreaseRate;
}
if (power < 0 || power > 1) {
updatedPower.put(uuid, power);
}
}
for (Player player : Bukkit.getOnlinePlayers()) {
UUID uuid = player.getUniqueId();
double power = data.power.get(uuid) != null ? data.power.get(uuid) : 0;
power += increaseRate;
if (power > maxPower) {
power = maxPower;
}
updatedPower.put(uuid, power);
}
data.power = updatedPower;
data.lastPowerUpdate = System.currentTimeMillis();
FactionsXL.debug("Updated power values");
}
}
| gpl-3.0 |
unclesado/DecentHome | app/src/main/java/com/android/launcher3/FolderInfo.java | 5080 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3;
import android.content.ContentValues;
import android.content.Context;
import com.android.launcher3.compat.UserHandleCompat;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Represents a folder containing shortcuts or apps.
*/
public class FolderInfo extends ItemInfo {
public static final int REMOTE_SUBTYPE = 1;
/**
* Whether this folder has been opened
*/
boolean opened;
int subType;
/**
* The apps and shortcuts and hidden status
*/
public ArrayList<ShortcutInfo> contents = new ArrayList<ShortcutInfo>();
Boolean hidden = false;
ArrayList<FolderListener> listeners = new ArrayList<FolderListener>();
FolderInfo() {
itemType = LauncherSettings.Favorites.ITEM_TYPE_FOLDER;
user = UserHandleCompat.myUserHandle();
}
/**
* Add an app or shortcut
*
* @param item
*/
public void add(ShortcutInfo item) {
contents.add(item);
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onAdd(item);
}
itemsChanged();
}
/**
* Remove an app or shortcut. Does not change the DB.
*
* @param item
*/
public void remove(ShortcutInfo item) {
contents.remove(item);
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onRemove(item);
}
itemsChanged();
}
/**
* Remove all apps and shortcuts. Does not change the DB unless
* LauncherModel.deleteFolderContentsFromDatabase(Context, FolderInfo) is called first.
*/
public void removeAll() {
contents.clear();
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onRemoveAll();
}
itemsChanged();
}
/**
* Remove all supplied shortcuts. Does not change the DB unless
* LauncherModel.deleteFolderContentsFromDatabase(Context, FolderInfo) is called first.
* @param items the shortcuts to remove.
*/
public void removeAll(ArrayList<ShortcutInfo> items) {
contents.removeAll(items);
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onRemoveAll(items);
}
itemsChanged();
}
/**
* @return true if this info represents a remote folder, false otherwise
*/
public boolean isRemote() {
return (subType & REMOTE_SUBTYPE) != 0;
}
/**
* Set flag indicating whether this folder is remote
* @param remote true if folder is remote, false otherwise
*/
public void setRemote(final boolean remote) {
if (remote) {
subType |= REMOTE_SUBTYPE;
} else {
subType &= ~REMOTE_SUBTYPE;
}
}
public void setTitle(CharSequence title) {
this.title = title;
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onTitleChanged(title);
}
}
@Override
void onAddToDatabase(Context context, ContentValues values) {
super.onAddToDatabase(context, values);
values.put(LauncherSettings.Favorites.TITLE, title.toString());
values.put(LauncherSettings.Favorites.HIDDEN, hidden ? 1 : 0);
values.put(LauncherSettings.BaseLauncherColumns.SUBTYPE, subType);
}
void addListener(FolderListener listener) {
listeners.add(listener);
}
void removeListener(FolderListener listener) {
if (listeners.contains(listener)) {
listeners.remove(listener);
}
}
void itemsChanged() {
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onItemsChanged();
}
}
@Override
void unbind() {
super.unbind();
listeners.clear();
}
interface FolderListener {
void onAdd(ShortcutInfo item);
void onRemove(ShortcutInfo item);
void onRemoveAll();
void onRemoveAll(ArrayList<ShortcutInfo> items);
void onTitleChanged(CharSequence title);
void onItemsChanged();
}
@Override
public String toString() {
return "FolderInfo(id=" + this.id + " type=" + this.itemType + " subtype=" + this.subType
+ " container=" + this.container + " screen=" + screenId
+ " cellX=" + cellX + " cellY=" + cellY + " spanX=" + spanX
+ " spanY=" + spanY + " dropPos=" + Arrays.toString(dropPos) + ")";
}
}
| gpl-3.0 |
GoSuji/Suji | src/main/java/logic/gametree/ComplexTreeIterator.java | 2992 | package logic.gametree;
import logic.board.Board;
import util.Coords;
import util.Move;
import util.StoneColour;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.util.function.Consumer;
public class ComplexTreeIterator implements GameTreeIterator {
private TreeNode node;
protected ComplexTreeIterator(TreeNode treeNode) {
node = treeNode;
}
@Override
public boolean isRoot() {
return node.isRoot();
}
@Override
public int getNumChildren() {
return node.getChildren().size();
}
@Override
public void stepForward() {
node = new TreeNode(node);
}
@Override
public void addProperty(GameTreeBuilder.GameTreeProperty property) {
String identifier = property.getIdentifier();
if ( identifier.equals("B") || identifier.equals("W") ) {
StoneColour colour = StoneColour.fromString(identifier);
if ( property.getValues().isEmpty() || property.getValues().firstElement().equals("") )
node.setMove(Move.pass(colour));
else {
Coords coords = Coords.fromSGFString(property.getValues().firstElement());
node.setMove(Move.play(coords, colour));
}
}
}
@Override
public void preorder(Consumer<TreeNode> enterNode, Consumer<TreeNode> exitNode) {
node.preorder(enterNode, exitNode);
}
@Override
public void stepForward(int child) {
Vector<TreeNode> children = node.getChildren();
if ( child < children.size() )
node = children.get(child);
}
@Override
public void stepForward(Move move) {
TreeNode child = node.getChildMatching(treeNode -> treeNode.hasMove() && treeNode.getMove().equals(move));
if ( child == null ) {
child = new TreeNode(node);
child.setMove(move);
}
node = child;
}
@Override
public void stepBack() {
if ( node.isRoot() )
return;
node = node.getParent();
}
@Override
public Move getLastMove() {
TreeNode search = node;
while (!search.hasMove() && search.getParent() != null) {
search = search.getParent();
}
return search.getMove();
}
@Override
public int getNumMoves() {
TreeNode search = node;
int count = 0;
while (search != null) {
if ( search.hasMove() )
count++;
search = search.getParent();
}
return count;
}
@Override
public List<Move> getSequence() {
return getSequenceAt(node);
}
private List<Move> getSequenceAt(TreeNode point) {
LinkedList<Move> result = new LinkedList<>();
point.backtrack(treeNode -> {
if ( treeNode.hasMove() )
result.addFirst(treeNode.getMove());
});
return result;
}
private Board getPositionFromSequence(List<Move> sequence) {
Board position = new Board();
for (Move m : sequence)
if ( m.getType() == Move.Type.PLAY )
position.playStone(m);
return position;
}
@Override
public Board getPosition() {
return getPositionFromSequence(getSequence());
}
@Override
public Board getLastPosition() {
if ( isRoot() )
return new Board();
return getPositionFromSequence(getSequenceAt(node.getParent()));
}
}
| gpl-3.0 |
mrlolethan/Buttered-Pixel-Dungeon | src/com/mrlolethan/butteredpd/levels/painters/PitPainter.java | 3140 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2015 Evan Debenham
*
* 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.mrlolethan.butteredpd.levels.painters;
import com.mrlolethan.butteredpd.Dungeon;
import com.mrlolethan.butteredpd.items.Generator;
import com.mrlolethan.butteredpd.items.Heap.Type;
import com.mrlolethan.butteredpd.items.Item;
import com.mrlolethan.butteredpd.items.keys.IronKey;
import com.mrlolethan.butteredpd.levels.Level;
import com.mrlolethan.butteredpd.levels.Room;
import com.mrlolethan.butteredpd.levels.Terrain;
import com.watabou.utils.Point;
import com.watabou.utils.Random;
public class PitPainter extends Painter {
public static void paint( Level level, Room room ) {
fill( level, room, Terrain.WALL );
fill( level, room, 1, Terrain.EMPTY );
Room.Door entrance = room.entrance();
entrance.set( Room.Door.Type.LOCKED );
Point well = null;
if (entrance.x == room.left) {
well = new Point( room.right-1, Random.Int( 2 ) == 0 ? room.top + 1 : room.bottom - 1 );
} else if (entrance.x == room.right) {
well = new Point( room.left+1, Random.Int( 2 ) == 0 ? room.top + 1 : room.bottom - 1 );
} else if (entrance.y == room.top) {
well = new Point( Random.Int( 2 ) == 0 ? room.left + 1 : room.right - 1, room.bottom-1 );
} else if (entrance.y == room.bottom) {
well = new Point( Random.Int( 2 ) == 0 ? room.left + 1 : room.right - 1, room.top+1 );
}
set( level, well, Terrain.EMPTY_WELL );
int remains = room.random();
while (level.map[remains] == Terrain.EMPTY_WELL) {
remains = room.random();
}
level.drop( new IronKey( Dungeon.depth ), remains ).type = Type.SKELETON;
int loot = Random.Int( 3 );
if (loot == 0) {
level.drop( Generator.random( Generator.Category.RING ), remains );
} else if (loot == 1) {
level.drop( Generator.random( Generator.Category.ARTIFACT ), remains );
} else {
level.drop( Generator.random( Random.oneOf(
Generator.Category.WEAPON,
Generator.Category.ARMOR
) ), remains );
}
int n = Random.IntRange( 1, 2 );
for (int i=0; i < n; i++) {
level.drop( prize( level ), remains );
}
}
private static Item prize( Level level ) {
if (Random.Int(2) != 0){
Item prize = level.findPrizeItem();
if (prize != null)
return prize;
}
return Generator.random( Random.oneOf(
Generator.Category.POTION,
Generator.Category.SCROLL,
Generator.Category.FOOD,
Generator.Category.GOLD
) );
}
}
| gpl-3.0 |
redsoftbiz/executequery | src/org/executequery/gui/browser/BrowserNodeBasePanel.java | 5612 | /*
* BrowserNodeBasePanel.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.gui.browser;
import org.executequery.gui.SortableColumnsTable;
import org.executequery.gui.forms.AbstractFormObjectViewPanel;
import org.executequery.print.TablePrinter;
import org.underworldlabs.swing.DisabledField;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.print.Printable;
/**
* @author Takis Diakoumis
*/
abstract class BrowserNodeBasePanel extends AbstractFormObjectViewPanel {
private DisabledField typeField;
private JPanel tablePanel;
private JScrollPane scroller;
private JTable table;
private DisabledField rowCountField;
BrowserNodeBasePanel(String labelText) {
super();
try {
init(labelText);
} catch (Exception e) {
e.printStackTrace();
}
}
private void init(String labelText) throws Exception {
JPanel base = new JPanel(new GridBagLayout());
typeField = new DisabledField();
GridBagConstraints gbc = new GridBagConstraints();
Insets ins = new Insets(10, 5, 5, 5);
gbc.insets = ins;
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
base.add(new JLabel(labelText), gbc);
gbc.insets.top = 8;
gbc.insets.left = 5;
gbc.insets.right = 5;
gbc.gridx = 1;
gbc.weightx = 1.0;
base.add(typeField, gbc);
table = createTable();
tablePanel = new JPanel(new GridBagLayout());
scroller = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tablePanel.add(scroller, getPanelConstraints());
rowCountField = new DisabledField();
// add to the panel
gbc.insets.top = 10;
gbc.weighty = 1.0;
gbc.gridy = 1;
gbc.gridx = 0;
gbc.insets.left = 5;
gbc.gridwidth = GridBagConstraints.REMAINDER;
base.add(tablePanel, gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.weighty = 0;
gbc.weightx = 1.0;
gbc.insets.top = 0;
gbc.insets.bottom = 5;
gbc.insets.right = 5;
gbc.insets.left = 5;
gbc.ipady = 5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.SOUTHWEST;
base.add(creatCountPanel(), gbc);
setContentPanel(base);
}
private JPanel creatCountPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.gridx = 0;
gbc.weighty = 1.0;
gbc.weightx = 0;
gbc.insets.top = 1;
gbc.insets.left = 1;
gbc.insets.right = 2;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
panel.add(new JLabel("Object Count:"), gbc);
gbc.gridx = 1;
gbc.insets.top = 0;
gbc.insets.left = 5;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
panel.add(rowCountField, gbc);
return panel;
}
private JTable createTable() {
final JTable table = new SortableColumnsTable() {
@Override
public void setModel(final TableModel dataModel) {
dataModel.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
rowCountField.setText(String.valueOf(dataModel.getRowCount()));
}
});
super.setModel(dataModel);
}
};
table.getTableHeader().setReorderingAllowed(false);
table.setColumnSelectionAllowed(false);
return table;
}
protected final DisabledField typeField() {
return typeField;
}
protected final JPanel tablePanel() {
return tablePanel;
}
protected final JScrollPane scroller() {
return scroller;
}
protected final JTable table() {
return table;
}
public JTable getTable() {
return table();
}
public final Printable getPrintable() {
return new TablePrinter(
table(), getPrintablePrefixLabel() + typeField().getText());
}
protected abstract String getPrintablePrefixLabel();
/**
* Performs some cleanup and releases resources before being closed.
*/
public abstract void cleanup();
/**
* Refreshes the data and clears the cache
*/
public abstract void refresh();
/**
* Returns the name of this panel
*/
public abstract String getLayoutName();
}
| gpl-3.0 |
cascheberg/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/megaphone/Megaphones.java | 21271 | package org.thoughtcrime.securesms.megaphone;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.annimon.stream.Stream;
import org.signal.core.util.TranslationDetection;
import org.signal.core.util.logging.Log;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.settings.app.AppSettingsActivity;
import org.thoughtcrime.securesms.conversationlist.ConversationListFragment;
import org.thoughtcrime.securesms.database.model.MegaphoneRecord;
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies;
import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint;
import org.thoughtcrime.securesms.keyvalue.SignalStore;
import org.thoughtcrime.securesms.lock.SignalPinReminderDialog;
import org.thoughtcrime.securesms.lock.SignalPinReminders;
import org.thoughtcrime.securesms.lock.v2.CreateKbsPinActivity;
import org.thoughtcrime.securesms.lock.v2.KbsMigrationActivity;
import org.thoughtcrime.securesms.messagerequests.MessageRequestMegaphoneActivity;
import org.thoughtcrime.securesms.notifications.NotificationChannels;
import org.thoughtcrime.securesms.profiles.ProfileName;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.util.CommunicationActions;
import org.thoughtcrime.securesms.util.FeatureFlags;
import org.thoughtcrime.securesms.util.LocaleFeatureFlags;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.VersionTracker;
import org.thoughtcrime.securesms.util.dynamiclanguage.DynamicLanguageContextWrapper;
import org.thoughtcrime.securesms.wallpaper.ChatWallpaperActivity;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* Creating a new megaphone:
* - Add an enum to {@link Event}
* - Return a megaphone in {@link #forRecord(Context, MegaphoneRecord)}
* - Include the event in {@link #buildDisplayOrder(Context)}
*
* Common patterns:
* - For events that have a snooze-able recurring display schedule, use a {@link RecurringSchedule}.
* - For events guarded by feature flags, set a {@link ForeverSchedule} with false in
* {@link #buildDisplayOrder(Context)}.
* - For events that change, return different megaphones in {@link #forRecord(Context, MegaphoneRecord)}
* based on whatever properties you're interested in.
*/
public final class Megaphones {
private static final String TAG = Log.tag(Megaphones.class);
private static final MegaphoneSchedule ALWAYS = new ForeverSchedule(true);
private static final MegaphoneSchedule NEVER = new ForeverSchedule(false);
private Megaphones() {}
static @Nullable Megaphone getNextMegaphone(@NonNull Context context, @NonNull Map<Event, MegaphoneRecord> records) {
long currentTime = System.currentTimeMillis();
List<Megaphone> megaphones = Stream.of(buildDisplayOrder(context))
.filter(e -> {
MegaphoneRecord record = Objects.requireNonNull(records.get(e.getKey()));
MegaphoneSchedule schedule = e.getValue();
return !record.isFinished() && schedule.shouldDisplay(record.getSeenCount(), record.getLastSeen(), record.getFirstVisible(), currentTime);
})
.map(Map.Entry::getKey)
.map(records::get)
.map(record -> Megaphones.forRecord(context, record))
.sortBy(m -> -m.getPriority().getPriorityValue())
.toList();
if (megaphones.size() > 0) {
return megaphones.get(0);
} else {
return null;
}
}
/**
* This is when you would hide certain megaphones based on {@link FeatureFlags}. You could
* conditionally set a {@link ForeverSchedule} set to false for disabled features.
*/
private static Map<Event, MegaphoneSchedule> buildDisplayOrder(@NonNull Context context) {
return new LinkedHashMap<Event, MegaphoneSchedule>() {{
put(Event.REACTIONS, ALWAYS);
put(Event.PINS_FOR_ALL, new PinsForAllSchedule());
put(Event.PIN_REMINDER, new SignalPinReminderSchedule());
put(Event.MESSAGE_REQUESTS, shouldShowMessageRequestsMegaphone() ? ALWAYS : NEVER);
put(Event.LINK_PREVIEWS, shouldShowLinkPreviewsMegaphone(context) ? ALWAYS : NEVER);
put(Event.CLIENT_DEPRECATED, SignalStore.misc().isClientDeprecated() ? ALWAYS : NEVER);
put(Event.RESEARCH, shouldShowResearchMegaphone(context) ? ShowForDurationSchedule.showForDays(7) : NEVER);
put(Event.DONATE, shouldShowDonateMegaphone(context) ? ShowForDurationSchedule.showForDays(7) : NEVER);
put(Event.GROUP_CALLING, shouldShowGroupCallingMegaphone() ? ALWAYS : NEVER);
put(Event.ONBOARDING, shouldShowOnboardingMegaphone(context) ? ALWAYS : NEVER);
put(Event.NOTIFICATIONS, shouldShowNotificationsMegaphone(context) ? RecurringSchedule.every(TimeUnit.DAYS.toMillis(30)) : NEVER);
put(Event.CHAT_COLORS, ALWAYS);
}};
}
private static @NonNull Megaphone forRecord(@NonNull Context context, @NonNull MegaphoneRecord record) {
switch (record.getEvent()) {
case REACTIONS:
return buildReactionsMegaphone();
case PINS_FOR_ALL:
return buildPinsForAllMegaphone(record);
case PIN_REMINDER:
return buildPinReminderMegaphone(context);
case MESSAGE_REQUESTS:
return buildMessageRequestsMegaphone(context);
case LINK_PREVIEWS:
return buildLinkPreviewsMegaphone();
case CLIENT_DEPRECATED:
return buildClientDeprecatedMegaphone(context);
case RESEARCH:
return buildResearchMegaphone(context);
case DONATE:
return buildDonateMegaphone(context);
case GROUP_CALLING:
return buildGroupCallingMegaphone(context);
case ONBOARDING:
return buildOnboardingMegaphone();
case NOTIFICATIONS:
return buildNotificationsMegaphone(context);
case CHAT_COLORS:
return buildChatColorsMegaphone(context);
default:
throw new IllegalArgumentException("Event not handled!");
}
}
private static @NonNull Megaphone buildReactionsMegaphone() {
return new Megaphone.Builder(Event.REACTIONS, Megaphone.Style.REACTIONS)
.setPriority(Megaphone.Priority.DEFAULT)
.build();
}
private static @NonNull Megaphone buildPinsForAllMegaphone(@NonNull MegaphoneRecord record) {
if (PinsForAllSchedule.shouldDisplayFullScreen(record.getFirstVisible(), System.currentTimeMillis())) {
return new Megaphone.Builder(Event.PINS_FOR_ALL, Megaphone.Style.FULLSCREEN)
.setPriority(Megaphone.Priority.HIGH)
.enableSnooze(null)
.setOnVisibleListener((megaphone, listener) -> {
if (new NetworkConstraint.Factory(ApplicationDependencies.getApplication()).create().isMet()) {
listener.onMegaphoneNavigationRequested(KbsMigrationActivity.createIntent(), KbsMigrationActivity.REQUEST_NEW_PIN);
}
})
.build();
} else {
return new Megaphone.Builder(Event.PINS_FOR_ALL, Megaphone.Style.BASIC)
.setPriority(Megaphone.Priority.HIGH)
.setImage(R.drawable.kbs_pin_megaphone)
.setTitle(R.string.KbsMegaphone__create_a_pin)
.setBody(R.string.KbsMegaphone__pins_keep_information_thats_stored_with_signal_encrytped)
.setActionButton(R.string.KbsMegaphone__create_pin, (megaphone, listener) -> {
Intent intent = CreateKbsPinActivity.getIntentForPinCreate(ApplicationDependencies.getApplication());
listener.onMegaphoneNavigationRequested(intent, CreateKbsPinActivity.REQUEST_NEW_PIN);
})
.build();
}
}
@SuppressWarnings("CodeBlock2Expr")
private static @NonNull Megaphone buildPinReminderMegaphone(@NonNull Context context) {
return new Megaphone.Builder(Event.PIN_REMINDER, Megaphone.Style.BASIC)
.setTitle(R.string.Megaphones_verify_your_signal_pin)
.setBody(R.string.Megaphones_well_occasionally_ask_you_to_verify_your_pin)
.setImage(R.drawable.kbs_pin_megaphone)
.setActionButton(R.string.Megaphones_verify_pin, (megaphone, controller) -> {
SignalPinReminderDialog.show(controller.getMegaphoneActivity(), controller::onMegaphoneNavigationRequested, new SignalPinReminderDialog.Callback() {
@Override
public void onReminderDismissed(boolean includedFailure) {
Log.i(TAG, "[PinReminder] onReminderDismissed(" + includedFailure + ")");
if (includedFailure) {
SignalStore.pinValues().onEntrySkipWithWrongGuess();
}
}
@Override
public void onReminderCompleted(@NonNull String pin, boolean includedFailure) {
Log.i(TAG, "[PinReminder] onReminderCompleted(" + includedFailure + ")");
if (includedFailure) {
SignalStore.pinValues().onEntrySuccessWithWrongGuess(pin);
} else {
SignalStore.pinValues().onEntrySuccess(pin);
}
controller.onMegaphoneSnooze(Event.PIN_REMINDER);
controller.onMegaphoneToastRequested(context.getString(SignalPinReminders.getReminderString(SignalStore.pinValues().getCurrentInterval())));
}
});
})
.build();
}
@SuppressWarnings("CodeBlock2Expr")
private static @NonNull Megaphone buildMessageRequestsMegaphone(@NonNull Context context) {
return new Megaphone.Builder(Event.MESSAGE_REQUESTS, Megaphone.Style.FULLSCREEN)
.disableSnooze()
.setPriority(Megaphone.Priority.HIGH)
.setOnVisibleListener(((megaphone, listener) -> {
listener.onMegaphoneNavigationRequested(new Intent(context, MessageRequestMegaphoneActivity.class),
ConversationListFragment.MESSAGE_REQUESTS_REQUEST_CODE_CREATE_NAME);
}))
.build();
}
private static @NonNull Megaphone buildLinkPreviewsMegaphone() {
return new Megaphone.Builder(Event.LINK_PREVIEWS, Megaphone.Style.LINK_PREVIEWS)
.setPriority(Megaphone.Priority.HIGH)
.build();
}
private static @NonNull Megaphone buildClientDeprecatedMegaphone(@NonNull Context context) {
return new Megaphone.Builder(Event.CLIENT_DEPRECATED, Megaphone.Style.FULLSCREEN)
.disableSnooze()
.setPriority(Megaphone.Priority.HIGH)
.setOnVisibleListener((megaphone, listener) -> listener.onMegaphoneNavigationRequested(new Intent(context, ClientDeprecatedActivity.class)))
.build();
}
private static @NonNull Megaphone buildResearchMegaphone(@NonNull Context context) {
return new Megaphone.Builder(Event.RESEARCH, Megaphone.Style.BASIC)
.disableSnooze()
.setTitle(R.string.ResearchMegaphone_tell_signal_what_you_think)
.setBody(R.string.ResearchMegaphone_to_make_signal_the_best_messaging_app_on_the_planet)
.setImage(R.drawable.ic_research_megaphone)
.setActionButton(R.string.ResearchMegaphone_learn_more, (megaphone, controller) -> {
controller.onMegaphoneCompleted(megaphone.getEvent());
controller.onMegaphoneDialogFragmentRequested(new ResearchMegaphoneDialog());
})
.setSecondaryButton(R.string.ResearchMegaphone_dismiss, (megaphone, controller) -> controller.onMegaphoneCompleted(megaphone.getEvent()))
.setPriority(Megaphone.Priority.DEFAULT)
.build();
}
private static @NonNull Megaphone buildDonateMegaphone(@NonNull Context context) {
return new Megaphone.Builder(Event.DONATE, Megaphone.Style.BASIC)
.disableSnooze()
.setTitle(R.string.DonateMegaphone_donate_to_signal)
.setBody(R.string.DonateMegaphone_Signal_is_powered_by_people_like_you_show_your_support_today)
.setImage(R.drawable.ic_donate_megaphone)
.setActionButton(R.string.DonateMegaphone_donate, (megaphone, controller) -> {
controller.onMegaphoneCompleted(megaphone.getEvent());
CommunicationActions.openBrowserLink(controller.getMegaphoneActivity(), context.getString(R.string.donate_url));
})
.setSecondaryButton(R.string.DonateMegaphone_no_thanks, (megaphone, controller) -> controller.onMegaphoneCompleted(megaphone.getEvent()))
.setPriority(Megaphone.Priority.DEFAULT)
.build();
}
private static @NonNull Megaphone buildGroupCallingMegaphone(@NonNull Context context) {
return new Megaphone.Builder(Event.GROUP_CALLING, Megaphone.Style.BASIC)
.disableSnooze()
.setTitle(R.string.GroupCallingMegaphone__introducing_group_calls)
.setBody(R.string.GroupCallingMegaphone__open_a_new_group_to_start)
.setImage(R.drawable.ic_group_calls_megaphone)
.setActionButton(android.R.string.ok, (megaphone, controller) -> {
controller.onMegaphoneCompleted(megaphone.getEvent());
})
.setPriority(Megaphone.Priority.DEFAULT)
.build();
}
private static @NonNull Megaphone buildOnboardingMegaphone() {
return new Megaphone.Builder(Event.ONBOARDING, Megaphone.Style.ONBOARDING)
.setPriority(Megaphone.Priority.DEFAULT)
.build();
}
private static @NonNull Megaphone buildNotificationsMegaphone(@NonNull Context context) {
return new Megaphone.Builder(Event.NOTIFICATIONS, Megaphone.Style.BASIC)
.setTitle(R.string.NotificationsMegaphone_turn_on_notifications)
.setBody(R.string.NotificationsMegaphone_never_miss_a_message)
.setImage(R.drawable.megaphone_notifications_64)
.setActionButton(R.string.NotificationsMegaphone_turn_on, (megaphone, controller) -> {
if (Build.VERSION.SDK_INT >= 26 && !NotificationChannels.isMessageChannelEnabled(context)) {
Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_CHANNEL_ID, NotificationChannels.getMessagesChannel(context));
intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
controller.onMegaphoneNavigationRequested(intent);
} else if (Build.VERSION.SDK_INT >= 26 &&
(!NotificationChannels.areNotificationsEnabled(context) || !NotificationChannels.isMessagesChannelGroupEnabled(context)))
{
Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
controller.onMegaphoneNavigationRequested(intent);
} else {
controller.onMegaphoneNavigationRequested(AppSettingsActivity.notifications(context));
}
})
.setSecondaryButton(R.string.NotificationsMegaphone_not_now, (megaphone, controller) -> controller.onMegaphoneSnooze(Event.NOTIFICATIONS))
.setPriority(Megaphone.Priority.DEFAULT)
.build();
}
private static @NonNull Megaphone buildChatColorsMegaphone(@NonNull Context context) {
return new Megaphone.Builder(Event.CHAT_COLORS, Megaphone.Style.BASIC)
.setTitle(R.string.ChatColorsMegaphone__new_chat_colors)
.setBody(R.string.ChatColorsMegaphone__we_switched_up_chat_colors)
.setLottie(R.raw.color_bubble_64)
.setActionButton(R.string.ChatColorsMegaphone__appearance, (megaphone, listener) -> {
listener.onMegaphoneNavigationRequested(ChatWallpaperActivity.createIntent(context));
listener.onMegaphoneCompleted(Event.CHAT_COLORS);
})
.setSecondaryButton(R.string.ChatColorsMegaphone__not_now, (megaphone, listener) -> {
listener.onMegaphoneCompleted(Event.CHAT_COLORS);
})
.build();
}
private static boolean shouldShowMessageRequestsMegaphone() {
return Recipient.self().getProfileName() == ProfileName.EMPTY;
}
private static boolean shouldShowResearchMegaphone(@NonNull Context context) {
return VersionTracker.getDaysSinceFirstInstalled(context) > 7 && LocaleFeatureFlags.isInResearchMegaphone();
}
private static boolean shouldShowDonateMegaphone(@NonNull Context context) {
return VersionTracker.getDaysSinceFirstInstalled(context) > 7 && LocaleFeatureFlags.isInDonateMegaphone();
}
private static boolean shouldShowLinkPreviewsMegaphone(@NonNull Context context) {
return TextSecurePreferences.wereLinkPreviewsEnabled(context) && !SignalStore.settings().isLinkPreviewsEnabled();
}
private static boolean shouldShowGroupCallingMegaphone() {
return Build.VERSION.SDK_INT > 19;
}
private static boolean shouldShowOnboardingMegaphone(@NonNull Context context) {
return SignalStore.onboarding().hasOnboarding(context);
}
private static boolean shouldShowNotificationsMegaphone(@NonNull Context context) {
boolean shouldShow = !SignalStore.settings().isMessageNotificationsEnabled() ||
!NotificationChannels.isMessageChannelEnabled(context) ||
!NotificationChannels.isMessagesChannelGroupEnabled(context) ||
!NotificationChannels.areNotificationsEnabled(context);
if (shouldShow) {
Locale locale = DynamicLanguageContextWrapper.getUsersSelectedLocale(context);
if (!new TranslationDetection(context, locale)
.textExistsInUsersLanguage(R.string.NotificationsMegaphone_turn_on_notifications,
R.string.NotificationsMegaphone_never_miss_a_message,
R.string.NotificationsMegaphone_turn_on,
R.string.NotificationsMegaphone_not_now)) {
Log.i(TAG, "Would show NotificationsMegaphone but is not yet translated in " + locale);
return false;
}
}
return shouldShow;
}
public enum Event {
REACTIONS("reactions"),
PINS_FOR_ALL("pins_for_all"),
PIN_REMINDER("pin_reminder"),
MESSAGE_REQUESTS("message_requests"),
LINK_PREVIEWS("link_previews"),
CLIENT_DEPRECATED("client_deprecated"),
RESEARCH("research"),
DONATE("donate"),
GROUP_CALLING("group_calling"),
ONBOARDING("onboarding"),
NOTIFICATIONS("notifications"),
CHAT_COLORS("chat_colors");
private final String key;
Event(@NonNull String key) {
this.key = key;
}
public @NonNull String getKey() {
return key;
}
public static Event fromKey(@NonNull String key) {
for (Event event : values()) {
if (event.getKey().equals(key)) {
return event;
}
}
throw new IllegalArgumentException("No event for key: " + key);
}
public static boolean hasKey(@NonNull String key) {
for (Event event : values()) {
if (event.getKey().equals(key)) {
return true;
}
}
return false;
}
}
}
| gpl-3.0 |
pkiraly/metadata-qa-marc | src/main/java/de/gwdg/metadataqa/marc/definition/controlpositions/tag007/Tag007motionPicture15.java | 1586 | package de.gwdg.metadataqa.marc.definition.controlpositions.tag007;
import de.gwdg.metadataqa.marc.Utils;
import de.gwdg.metadataqa.marc.definition.structure.ControlfieldPositionDefinition;
import static de.gwdg.metadataqa.marc.definition.FRBRFunction.*;
import java.util.Arrays;
/**
* Deterioration stage
* https://www.loc.gov/marc/bibliographic/bd007m.html
*/
public class Tag007motionPicture15 extends ControlfieldPositionDefinition {
private static Tag007motionPicture15 uniqueInstance;
private Tag007motionPicture15() {
initialize();
extractValidCodes();
}
public static Tag007motionPicture15 getInstance() {
if (uniqueInstance == null)
uniqueInstance = new Tag007motionPicture15();
return uniqueInstance;
}
private void initialize() {
label = "Deterioration stage";
id = "007motionPicture15";
mqTag = "deteriorationStage";
positionStart = 15;
positionEnd = 16;
descriptionUrl = "https://www.loc.gov/marc/bibliographic/bd007m.html";
codes = Utils.generateCodes(
"a", "None apparent",
"b", "Nitrate: suspicious odor",
"c", "Nitrate: pungent odor",
"d", "Nitrate: brownish, discoloration, fading, dusty",
"e", "Nitrate: sticky",
"f", "Nitrate: frothy, bubbles, blisters",
"g", "Nitrate: congealed",
"h", "Nitrate: powder",
"k", "Non-nitrate: detectable deterioration",
"l", "Non-nitrate: advanced deterioration",
"m", "Non-nitrate: disaster",
"|", "No attempt to code"
);
functions = Arrays.asList(DiscoverySelect, UseManage);
}
} | gpl-3.0 |
Neogs12/GVue | Libraries/src/org/lwjgl/opengl/EXTTransformFeedback.java | 18783 | /*
* Copyright LWJGL. All rights reserved.
* License terms: http://lwjgl.org/license.php
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opengl;
import org.lwjgl.*;
import org.lwjgl.system.*;
import java.nio.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.Pointer.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.APIUtil.*;
/**
* Native bindings to the <a href="http://www.opengl.org/registry/specs/EXT/transform_feedback.txt">EXT_transform_feedback</a> extension.
*
* <p>This extension provides a new mode to the GL, called transform feedback, which records selected vertex attributes for each primitive processed by the
* GL. The selected attributes are written into buffer objects, and can be written with each attribute in a separate buffer object or with all attributes
* interleaved into a single buffer object. If a geometry shader is active, the primitives recorded are those emitted by the geometry shader. Otherwise,
* transform feedback captures primitives whose vertices are transformed by a vertex shader. In either case, the primitives captured are those generated
* prior to clipping. Transform feedback mode captures the values of specified varying variables emitted from GLSL vertex or geometry shaders.</p>
*
* <p>The vertex data recorded in transform feedback mode is stored into buffer objects as an array of vertex attributes. The regular representation and the
* use of buffer objects allows the recorded data to be processed directly by the GL without requiring CPU intervention to copy data. In particular,
* transform feedback data can be used for vertex arrays (via vertex buffer objects), as the source for pixel data (via pixel buffer objects), as shader
* constant data (via the <a href="http://www.opengl.org/registry/specs/NV/parameter_buffer_object.txt">NV_parameter_buffer_object</a> or {@link EXTBindableUniform EXT_bindable_uniform} extensions), or via any other extension that
* makes use of buffer objects.</p>
*
* <p>This extension introduces new query object support to allow transform feedback mode to operate asynchronously. Query objects allow applications to
* determine when transform feedback results are complete, as well as the number of primitives processed and written back to buffer objects while in
* transform feedback mode. This extension also provides a new rasterizer discard enable, which allows applications to use transform feedback to capture
* vertex attributes without rendering anything.</p>
*
* <p>Requires {@link GL20 OpenGL 2.0} or {@link ARBShaderObjects ARB_shader_objects}. Promoted to core in {@link GL30 OpenGL 3.0}.</p>
*/
public final class EXTTransformFeedback {
/**
* Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, GetBufferPointerv,
* BindBufferRangeEXT, BindBufferOffsetEXT and BindBufferBaseEXT.
*/
public static final int GL_TRANSFORM_FEEDBACK_BUFFER_EXT = 0x8C8E;
/** Accepted by the {@code param} parameter of GetIntegerIndexedvEXT and GetBooleanIndexedvEXT. */
public static final int
GL_TRANSFORM_FEEDBACK_BUFFER_START_EXT = 0x8C84,
GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_EXT = 0x8C85;
/**
* Accepted by the {@code param} parameter of GetIntegerIndexedvEXT and GetBooleanIndexedvEXT, and by the {@code pname} parameter of GetBooleanv,
* GetDoublev, GetIntegerv, and GetFloatv.
*/
public static final int GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_EXT = 0x8C8F;
/** Accepted by the {@code bufferMode} parameter of TransformFeedbackVaryingsEXT. */
public static final int
GL_INTERLEAVED_ATTRIBS_EXT = 0x8C8C,
GL_SEPARATE_ATTRIBS_EXT = 0x8C8D;
/** Accepted by the {@code target} parameter of BeginQuery, EndQuery, and GetQueryiv. */
public static final int
GL_PRIMITIVES_GENERATED_EXT = 0x8C87,
GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_EXT = 0x8C88;
/**
* Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
* GetDoublev.
*/
public static final int GL_RASTERIZER_DISCARD_EXT = 0x8C89;
/** Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv. */
public static final int
GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT = 0x8C8A,
GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_EXT = 0x8C8B,
GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT = 0x8C80;
/** Accepted by the {@code pname} parameter of GetProgramiv. */
public static final int
GL_TRANSFORM_FEEDBACK_VARYINGS_EXT = 0x8C83,
GL_TRANSFORM_FEEDBACK_BUFFER_MODE_EXT = 0x8C7F,
GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH_EXT = 0x8C76;
/** Function address. */
@JavadocExclude
public final long
BindBufferRangeEXT,
BindBufferOffsetEXT,
BindBufferBaseEXT,
BeginTransformFeedbackEXT,
EndTransformFeedbackEXT,
TransformFeedbackVaryingsEXT,
GetTransformFeedbackVaryingEXT,
GetIntegerIndexedvEXT,
GetBooleanIndexedvEXT;
@JavadocExclude
public EXTTransformFeedback(FunctionProvider provider) {
BindBufferRangeEXT = provider.getFunctionAddress("glBindBufferRangeEXT");
BindBufferOffsetEXT = provider.getFunctionAddress("glBindBufferOffsetEXT");
BindBufferBaseEXT = provider.getFunctionAddress("glBindBufferBaseEXT");
BeginTransformFeedbackEXT = provider.getFunctionAddress("glBeginTransformFeedbackEXT");
EndTransformFeedbackEXT = provider.getFunctionAddress("glEndTransformFeedbackEXT");
TransformFeedbackVaryingsEXT = provider.getFunctionAddress("glTransformFeedbackVaryingsEXT");
GetTransformFeedbackVaryingEXT = provider.getFunctionAddress("glGetTransformFeedbackVaryingEXT");
GetIntegerIndexedvEXT = provider.getFunctionAddress("glGetIntegerIndexedvEXT");
GetBooleanIndexedvEXT = provider.getFunctionAddress("glGetBooleanIndexedvEXT");
}
// --- [ Function Addresses ] ---
/** Returns the {@link EXTTransformFeedback} instance for the current context. */
public static EXTTransformFeedback getInstance() {
return GL.getCapabilities().__EXTTransformFeedback;
}
static EXTTransformFeedback create(java.util.Set<String> ext, FunctionProvider provider) {
if ( !ext.contains("GL_EXT_transform_feedback") ) return null;
EXTTransformFeedback funcs = new EXTTransformFeedback(provider);
boolean supported = checkFunctions(
funcs.BindBufferRangeEXT, funcs.BindBufferOffsetEXT, funcs.BindBufferBaseEXT, funcs.BeginTransformFeedbackEXT, funcs.EndTransformFeedbackEXT,
funcs.TransformFeedbackVaryingsEXT, funcs.GetTransformFeedbackVaryingEXT, funcs.GetIntegerIndexedvEXT, funcs.GetBooleanIndexedvEXT
);
return GL.checkExtension("GL_EXT_transform_feedback", funcs, supported);
}
// --- [ glBindBufferRangeEXT ] ---
/** JNI method for {@link #glBindBufferRangeEXT BindBufferRangeEXT} */
@JavadocExclude
public static native void nglBindBufferRangeEXT(int target, int index, int buffer, long offset, long size, long __functionAddress);
/**
*
*
* @param target
* @param index
* @param buffer
* @param offset
* @param size
*/
public static void glBindBufferRangeEXT(int target, int index, int buffer, long offset, long size) {
long __functionAddress = getInstance().BindBufferRangeEXT;
if ( LWJGLUtil.CHECKS )
checkFunctionAddress(__functionAddress);
nglBindBufferRangeEXT(target, index, buffer, offset, size, __functionAddress);
}
// --- [ glBindBufferOffsetEXT ] ---
/** JNI method for {@link #glBindBufferOffsetEXT BindBufferOffsetEXT} */
@JavadocExclude
public static native void nglBindBufferOffsetEXT(int target, int index, int buffer, long offset, long __functionAddress);
/**
*
*
* @param target
* @param index
* @param buffer
* @param offset
*/
public static void glBindBufferOffsetEXT(int target, int index, int buffer, long offset) {
long __functionAddress = getInstance().BindBufferOffsetEXT;
if ( LWJGLUtil.CHECKS )
checkFunctionAddress(__functionAddress);
nglBindBufferOffsetEXT(target, index, buffer, offset, __functionAddress);
}
// --- [ glBindBufferBaseEXT ] ---
/** JNI method for {@link #glBindBufferBaseEXT BindBufferBaseEXT} */
@JavadocExclude
public static native void nglBindBufferBaseEXT(int target, int index, int buffer, long __functionAddress);
/**
*
*
* @param target
* @param index
* @param buffer
*/
public static void glBindBufferBaseEXT(int target, int index, int buffer) {
long __functionAddress = getInstance().BindBufferBaseEXT;
if ( LWJGLUtil.CHECKS )
checkFunctionAddress(__functionAddress);
nglBindBufferBaseEXT(target, index, buffer, __functionAddress);
}
// --- [ glBeginTransformFeedbackEXT ] ---
/** JNI method for {@link #glBeginTransformFeedbackEXT BeginTransformFeedbackEXT} */
@JavadocExclude
public static native void nglBeginTransformFeedbackEXT(int primitiveMode, long __functionAddress);
/**
*
*
* @param primitiveMode
*/
public static void glBeginTransformFeedbackEXT(int primitiveMode) {
long __functionAddress = getInstance().BeginTransformFeedbackEXT;
if ( LWJGLUtil.CHECKS )
checkFunctionAddress(__functionAddress);
nglBeginTransformFeedbackEXT(primitiveMode, __functionAddress);
}
// --- [ glEndTransformFeedbackEXT ] ---
/** JNI method for {@link #glEndTransformFeedbackEXT EndTransformFeedbackEXT} */
@JavadocExclude
public static native void nglEndTransformFeedbackEXT(long __functionAddress);
/** */
public static void glEndTransformFeedbackEXT() {
long __functionAddress = getInstance().EndTransformFeedbackEXT;
if ( LWJGLUtil.CHECKS )
checkFunctionAddress(__functionAddress);
nglEndTransformFeedbackEXT(__functionAddress);
}
// --- [ glTransformFeedbackVaryingsEXT ] ---
/** JNI method for {@link #glTransformFeedbackVaryingsEXT TransformFeedbackVaryingsEXT} */
@JavadocExclude
public static native void nglTransformFeedbackVaryingsEXT(int program, int count, long varyings, int bufferMode, long __functionAddress);
/** Unsafe version of {@link #glTransformFeedbackVaryingsEXT TransformFeedbackVaryingsEXT} */
@JavadocExclude
public static void nglTransformFeedbackVaryingsEXT(int program, int count, long varyings, int bufferMode) {
long __functionAddress = getInstance().TransformFeedbackVaryingsEXT;
if ( LWJGLUtil.CHECKS )
checkFunctionAddress(__functionAddress);
nglTransformFeedbackVaryingsEXT(program, count, varyings, bufferMode, __functionAddress);
}
/**
*
*
* @param program
* @param count
* @param varyings
* @param bufferMode
*/
public static void glTransformFeedbackVaryingsEXT(int program, int count, ByteBuffer varyings, int bufferMode) {
if ( LWJGLUtil.CHECKS )
checkBuffer(varyings, count << POINTER_SHIFT);
nglTransformFeedbackVaryingsEXT(program, count, memAddress(varyings), bufferMode);
}
/** Alternative version of: {@link #glTransformFeedbackVaryingsEXT TransformFeedbackVaryingsEXT} */
public static void glTransformFeedbackVaryingsEXT(int program, PointerBuffer varyings, int bufferMode) {
nglTransformFeedbackVaryingsEXT(program, varyings.remaining(), memAddress(varyings), bufferMode);
}
/** Array version of: {@link #glTransformFeedbackVaryingsEXT TransformFeedbackVaryingsEXT} */
public static void glTransformFeedbackVaryingsEXT(int program, CharSequence[] varyings, int bufferMode) {
APIBuffer __buffer = apiBuffer();
int varyingsAddress = __buffer.bufferParam(varyings.length << POINTER_SHIFT);
ByteBuffer[] varyingsBuffers = new ByteBuffer[varyings.length];
for ( int i = 0; i < varyings.length; i++ )
__buffer.pointerParam(varyingsAddress, i, memAddress(varyingsBuffers[i] = memEncodeASCII(varyings[i], true)));
nglTransformFeedbackVaryingsEXT(program, varyings.length, __buffer.address(varyingsAddress), bufferMode);
}
/** Single varying version of: {@link #glTransformFeedbackVaryingsEXT TransformFeedbackVaryingsEXT} */
public static void glTransformFeedbackVaryingsEXT(int program, CharSequence varying, int bufferMode) {
APIBuffer __buffer = apiBuffer();
ByteBuffer varyingBuffers = memEncodeASCII(varying, true);
int varyingsAddress = __buffer.pointerParam(memAddress(varyingBuffers));
nglTransformFeedbackVaryingsEXT(program, 1, __buffer.address(varyingsAddress), bufferMode);
}
// --- [ glGetTransformFeedbackVaryingEXT ] ---
/** JNI method for {@link #glGetTransformFeedbackVaryingEXT GetTransformFeedbackVaryingEXT} */
@JavadocExclude
public static native void nglGetTransformFeedbackVaryingEXT(int program, int index, int bufSize, long length, long size, long type, long name, long __functionAddress);
/** Unsafe version of {@link #glGetTransformFeedbackVaryingEXT GetTransformFeedbackVaryingEXT} */
@JavadocExclude
public static void nglGetTransformFeedbackVaryingEXT(int program, int index, int bufSize, long length, long size, long type, long name) {
long __functionAddress = getInstance().GetTransformFeedbackVaryingEXT;
if ( LWJGLUtil.CHECKS )
checkFunctionAddress(__functionAddress);
nglGetTransformFeedbackVaryingEXT(program, index, bufSize, length, size, type, name, __functionAddress);
}
/**
*
*
* @param program
* @param index
* @param bufSize
* @param length
* @param size
* @param type
* @param name
*/
public static void glGetTransformFeedbackVaryingEXT(int program, int index, int bufSize, ByteBuffer length, ByteBuffer size, ByteBuffer type, ByteBuffer name) {
if ( LWJGLUtil.CHECKS ) {
checkBuffer(name, bufSize);
if ( length != null ) checkBuffer(length, 1 << 2);
checkBuffer(size, 1 << 2);
checkBuffer(type, 1 << 2);
}
nglGetTransformFeedbackVaryingEXT(program, index, bufSize, memAddressSafe(length), memAddress(size), memAddress(type), memAddress(name));
}
/** Alternative version of: {@link #glGetTransformFeedbackVaryingEXT GetTransformFeedbackVaryingEXT} */
public static void glGetTransformFeedbackVaryingEXT(int program, int index, IntBuffer length, IntBuffer size, IntBuffer type, ByteBuffer name) {
if ( LWJGLUtil.CHECKS ) {
if ( length != null ) checkBuffer(length, 1);
checkBuffer(size, 1);
checkBuffer(type, 1);
}
nglGetTransformFeedbackVaryingEXT(program, index, name.remaining(), memAddressSafe(length), memAddress(size), memAddress(type), memAddress(name));
}
/** String return version of: {@link #glGetTransformFeedbackVaryingEXT GetTransformFeedbackVaryingEXT} */
public static String glGetTransformFeedbackVaryingEXT(int program, int index, int bufSize, IntBuffer size, IntBuffer type) {
if ( LWJGLUtil.CHECKS ) {
checkBuffer(size, 1);
checkBuffer(type, 1);
}
APIBuffer __buffer = apiBuffer();
int length = __buffer.intParam();
int name = __buffer.bufferParam(bufSize);
nglGetTransformFeedbackVaryingEXT(program, index, bufSize, __buffer.address(length), memAddress(size), memAddress(type), __buffer.address(name));
return memDecodeASCII(memByteBuffer(__buffer.address(name), __buffer.intValue(length)));
}
/** String return (w/ implicit max length) version of: {@link #glGetTransformFeedbackVaryingEXT GetTransformFeedbackVaryingEXT} */
public static String glGetTransformFeedbackVaryingEXT(int program, int index, IntBuffer size, IntBuffer type) {
if ( LWJGLUtil.CHECKS ) {
checkBuffer(size, 1);
checkBuffer(type, 1);
}
int bufSize = GL.getCapabilities().OpenGL20
? GL20.glGetProgrami(program, GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH_EXT)
: ARBShaderObjects.glGetObjectParameteriARB(program, GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH_EXT);
APIBuffer __buffer = apiBuffer();
int length = __buffer.intParam();
int name = __buffer.bufferParam(bufSize);
nglGetTransformFeedbackVaryingEXT(program, index, bufSize, __buffer.address(length), memAddress(size), memAddress(type), __buffer.address(name));
return memDecodeASCII(memByteBuffer(__buffer.address(name), __buffer.intValue(length)));
}
// --- [ glGetIntegerIndexedvEXT ] ---
/** JNI method for {@link #glGetIntegerIndexedvEXT GetIntegerIndexedvEXT} */
@JavadocExclude
public static native void nglGetIntegerIndexedvEXT(int param, int index, long values, long __functionAddress);
/** Unsafe version of {@link #glGetIntegerIndexedvEXT GetIntegerIndexedvEXT} */
@JavadocExclude
public static void nglGetIntegerIndexedvEXT(int param, int index, long values) {
long __functionAddress = getInstance().GetIntegerIndexedvEXT;
if ( LWJGLUtil.CHECKS )
checkFunctionAddress(__functionAddress);
nglGetIntegerIndexedvEXT(param, index, values, __functionAddress);
}
/**
*
*
* @param param
* @param index
* @param values
*/
public static void glGetIntegerIndexedvEXT(int param, int index, ByteBuffer values) {
if ( LWJGLUtil.CHECKS )
checkBuffer(values, 1 << 2);
nglGetIntegerIndexedvEXT(param, index, memAddress(values));
}
/** Alternative version of: {@link #glGetIntegerIndexedvEXT GetIntegerIndexedvEXT} */
public static void glGetIntegerIndexedvEXT(int param, int index, IntBuffer values) {
if ( LWJGLUtil.CHECKS )
checkBuffer(values, 1);
nglGetIntegerIndexedvEXT(param, index, memAddress(values));
}
/** Single return value version of: {@link #glGetIntegerIndexedvEXT GetIntegerIndexedvEXT} */
public static int glGetIntegerIndexedEXT(int param, int index) {
APIBuffer __buffer = apiBuffer();
int values = __buffer.intParam();
nglGetIntegerIndexedvEXT(param, index, __buffer.address(values));
return __buffer.intValue(values);
}
// --- [ glGetBooleanIndexedvEXT ] ---
/** JNI method for {@link #glGetBooleanIndexedvEXT GetBooleanIndexedvEXT} */
@JavadocExclude
public static native void nglGetBooleanIndexedvEXT(int param, int index, long values, long __functionAddress);
/** Unsafe version of {@link #glGetBooleanIndexedvEXT GetBooleanIndexedvEXT} */
@JavadocExclude
public static void nglGetBooleanIndexedvEXT(int param, int index, long values) {
long __functionAddress = getInstance().GetBooleanIndexedvEXT;
if ( LWJGLUtil.CHECKS )
checkFunctionAddress(__functionAddress);
nglGetBooleanIndexedvEXT(param, index, values, __functionAddress);
}
/**
*
*
* @param param
* @param index
* @param values
*/
public static void glGetBooleanIndexedvEXT(int param, int index, ByteBuffer values) {
if ( LWJGLUtil.CHECKS )
checkBuffer(values, 1);
nglGetBooleanIndexedvEXT(param, index, memAddress(values));
}
/** Single return value version of: {@link #glGetBooleanIndexedvEXT GetBooleanIndexedvEXT} */
public static boolean glGetBooleanIndexedEXT(int param, int index) {
APIBuffer __buffer = apiBuffer();
int values = __buffer.booleanParam();
nglGetBooleanIndexedvEXT(param, index, __buffer.address(values));
return __buffer.booleanValue(values);
}
} | gpl-3.0 |
vaishakhnair1/commoncode | cache/src/main/java/com/nair/cache/common/App.java | 1571 | /*
* This File is the sole property of Paytm(One97 Communications Limited)
*/
package com.nair.cache.common;
import java.util.concurrent.TimeUnit;
import javax.management.InstanceAlreadyExistsException;
import com.nair.cache.expirable.IExpirableCache;
/**
* Hello world! This class is the testing class to test the functionality.
*/
public class App {
public static void main(final String[] args) throws InstanceAlreadyExistsException {
final CacheManager cacheManager = CacheManager.getCacheManager();
final IExpirableCache<String, String> testString = new TestStringImplementation<String, String>();
final IExpirableCache<Integer, Integer> testInteger = new TestIntegerImplementation<Integer, Integer>();
cacheManager.registerExpirableCache("testStringCache", String.class, String.class, 5, TimeUnit.SECONDS, testString);
cacheManager.registerExpirableCache("testIntegerCache", Integer.class, Integer.class, 5, TimeUnit.SECONDS, testInteger);
cacheManager.putValueToExpirableCache("key1", "value1", "testStringCache");
cacheManager.putValueToExpirableCache("key2", "value2", 1, TimeUnit.SECONDS, "testStringCache");
final String value = cacheManager.getValueFromExpirableCache("key1", String.class, "testStringCache");
System.out.println(value);
cacheManager.putValueToExpirableCache(1, 1, "testIntegerCache");
cacheManager.putValueToExpirableCache(2, 2, 1, TimeUnit.SECONDS, "testIntegerCache");
final Integer value1 = cacheManager.getValueFromExpirableCache(1, Integer.class, "testIntegerCache");
System.out.println(value1);
}
}
| gpl-3.0 |
anna-kislovskaia/bullet-balance | bullet-balance-analytics/src/test/java/com/bulletbalance/random/RandomWeightsTest.java | 1669 | package com.bulletbalance.random;
import com.bulletbalance.utils.PortfolioUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Checks consistency of weights allocation
*/
public class RandomWeightsTest {
private RandomWeightsGenerator weightsGenerator;
@Before
public void init() {
weightsGenerator = new NoShortSellWeightsGenerator();
}
@Test
public void testConsistency() {
for (int i = 1; i < 1_000_000; i = i*10) {
BigDecimal[] weights = weightsGenerator.generateWeights(i);
PortfolioUtils.checkWeightsTotal(weights);
}
}
@Test
public void testDistribution() {
Set<BigDecimal[]> probes = new HashSet<>();
for (int i = 0; i < 10000; i++) {
BigDecimal[] weights = weightsGenerator.generateWeights(2);
Assert.assertTrue(probes.add(weights));
}
System.out.println("");
}
@Test
public void testAssignmentCount() {
// check whether each asset will participate in at least one calculation
for(int i = 1; i < 100; i+=5) {
testAssignmentCount(i);
}
}
private void testAssignmentCount(int assetCount) {
int[] assignments = new int[assetCount];
for (int i = 1; i < assetCount * 1_000; i++) {
BigDecimal[] weights = weightsGenerator.generateWeights(assetCount);
PortfolioUtils.checkWeightsTotal(weights);
for (int k = 0; k < assetCount; k++) {
if (weights[k].doubleValue() != 0) {
assignments[k]++;
}
}
}
System.out.println(Arrays.toString(assignments));
for (int k = 0; k < assetCount; k++) {
Assert.assertTrue(assignments[k] > 0);
}
}
}
| gpl-3.0 |
Phonemetra/TurboStore | app/src/com/phonemetra/turbo/store/net/ApkDownloader.java | 9544 | /*
* Copyright (C) 2010-2012 Ciaran Gultnieks <ciaran@ciarang.com>
* Copyright (C) 2011 Henrik Tunedal <tunedal@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.phonemetra.turbo.store.net;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import com.phonemetra.turbo.store.Hasher;
import com.phonemetra.turbo.store.Preferences;
import com.phonemetra.turbo.store.ProgressListener;
import com.phonemetra.turbo.store.Utils;
import com.phonemetra.turbo.store.compat.FileCompat;
import com.phonemetra.turbo.store.data.Apk;
import com.phonemetra.turbo.store.data.SanitizedFile;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
/**
* Downloads and verifies (against the Apk.hash) the apk file.
* If the file has previously been downloaded, it will make use of that
* instead, without going to the network to download a new one.
*/
public class ApkDownloader implements AsyncDownloadWrapper.Listener {
private static final String TAG = "ApkDownloader";
public static final String EVENT_APK_DOWNLOAD_COMPLETE = "apkDownloadComplete";
public static final String EVENT_APK_DOWNLOAD_CANCELLED = "apkDownloadCancelled";
public static final String EVENT_ERROR = "apkDownloadError";
public static final int ERROR_HASH_MISMATCH = 101;
public static final int ERROR_DOWNLOAD_FAILED = 102;
private static final String EVENT_SOURCE_ID = "sourceId";
private static long downloadIdCounter = 0;
/**
* Used as a key to pass data through with an error event, explaining the type of event.
*/
public static final String EVENT_DATA_ERROR_TYPE = "apkDownloadErrorType";
@NonNull private final Apk curApk;
@NonNull private final Context context;
@NonNull private final String repoAddress;
@NonNull private final SanitizedFile localFile;
@NonNull private final SanitizedFile potentiallyCachedFile;
private ProgressListener listener;
private AsyncDownloadWrapper dlWrapper = null;
private boolean isComplete = false;
private final long id = ++downloadIdCounter;
public void setProgressListener(ProgressListener listener) {
this.listener = listener;
}
public void removeProgressListener() {
setProgressListener(null);
}
public ApkDownloader(@NonNull final Context context, @NonNull final Apk apk, @NonNull final String repoAddress) {
this.context = context;
curApk = apk;
this.repoAddress = repoAddress;
localFile = new SanitizedFile(Utils.getApkDownloadDir(context), apk.apkName);
potentiallyCachedFile = new SanitizedFile(Utils.getApkCacheDir(context), apk.apkName);
}
/**
* The downloaded APK. Valid only when getStatus() has returned STATUS.DONE.
*/
public SanitizedFile localFile() {
return localFile;
}
/**
* When stopping/starting downloaders multiple times (on different threads), it can
* get weird whereby different threads are sending progress events. It is important
* to be able to see which downloader these progress events are coming from.
*/
public boolean isEventFromThis(Event event) {
return event.getData().containsKey(EVENT_SOURCE_ID) && event.getData().getLong(EVENT_SOURCE_ID) == id;
}
public String getRemoteAddress() {
return repoAddress + "/" + curApk.apkName.replace(" ", "%20");
}
private Hasher createHasher(File apkFile) {
Hasher hasher;
try {
hasher = new Hasher(curApk.hashType, apkFile);
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "Error verifying hash of cached apk at " + apkFile + ". " +
"I don't understand what the " + curApk.hashType + " hash algorithm is :(");
hasher = null;
}
return hasher;
}
private boolean hashMatches(@NonNull final File apkFile) {
if (!apkFile.exists()) {
return false;
}
Hasher hasher = createHasher(apkFile);
return hasher != null && hasher.match(curApk.hash);
}
/**
* If an existing cached version exists, and matches the hash of the apk we
* want to download, then we will return true. Otherwise, we return false
* (and remove the cached file - if it exists and didn't match the correct hash).
*/
private boolean verifyOrDelete(@NonNull final File apkFile) {
if (apkFile.exists()) {
if (hashMatches(apkFile)) {
Utils.DebugLog(TAG, "Using cached apk at " + apkFile);
return true;
}
Utils.DebugLog(TAG, "Not using cached apk at " + apkFile + "(hash doesn't match, will delete file)");
delete(apkFile);
}
return false;
}
private void delete(@NonNull final File file) {
if (file.exists()) {
if (!file.delete()) {
Log.w(TAG, "Could not delete file " + file);
}
}
}
private void prepareApkFileAndSendCompleteMessage() {
// Need the apk to be world readable, so that the installer is able to read it.
// Note that saving it into external storage for the purpose of letting the installer
// have access is insecure, because apps with permission to write to the external
// storage can overwrite the app between Turbo Store asking for it to be installed and
// the installer actually installing it.
FileCompat.setReadable(localFile, true, false);
isComplete = true;
sendMessage(EVENT_APK_DOWNLOAD_COMPLETE);
}
public boolean isComplete() {
return this.isComplete;
}
/**
* If the download successfully spins up a new thread to start downloading, then we return
* true, otherwise false. This is useful, e.g. when we use a cached version, and so don't
* want to bother with progress dialogs et al.
*/
public boolean download() {
// Can we use the cached version?
if (verifyOrDelete(potentiallyCachedFile)) {
delete(localFile);
Utils.copy(potentiallyCachedFile, localFile);
prepareApkFileAndSendCompleteMessage();
return false;
}
String remoteAddress = getRemoteAddress();
Utils.DebugLog(TAG, "Downloading apk from " + remoteAddress + " to " + localFile);
try {
Downloader downloader = DownloaderFactory.create(context, remoteAddress, localFile);
dlWrapper = new AsyncDownloadWrapper(downloader, this);
dlWrapper.download();
return true;
} catch (IOException e) {
onErrorDownloading(e.getLocalizedMessage());
}
return false;
}
private void sendMessage(String type) {
sendProgressEvent(new ProgressListener.Event(type));
}
private void sendError(int errorType) {
Bundle data = new Bundle(1);
data.putInt(EVENT_DATA_ERROR_TYPE, errorType);
sendProgressEvent(new Event(EVENT_ERROR, data));
}
private void sendProgressEvent(Event event) {
event.getData().putLong(EVENT_SOURCE_ID, id);
if (listener != null) {
listener.onProgress(event);
}
}
@Override
public void onErrorDownloading(String localisedExceptionDetails) {
Log.e(TAG, "Download failed: " + localisedExceptionDetails);
sendError(ERROR_DOWNLOAD_FAILED);
delete(localFile);
}
private void cacheIfRequired() {
if (Preferences.get().shouldCacheApks()) {
Utils.DebugLog(TAG, "Copying .apk file to cache at " + potentiallyCachedFile.getAbsolutePath());
Utils.copy(localFile, potentiallyCachedFile);
}
}
@Override
public void onDownloadComplete() {
if (!verifyOrDelete(localFile)) {
sendError(ERROR_HASH_MISMATCH);
return;
}
cacheIfRequired();
Utils.DebugLog(TAG, "Download finished: " + localFile);
prepareApkFileAndSendCompleteMessage();
}
@Override
public void onDownloadCancelled() {
sendMessage(EVENT_APK_DOWNLOAD_CANCELLED);
}
@Override
public void onProgress(Event event) {
sendProgressEvent(event);
}
/**
* Attempts to cancel the download (if in progress) and also removes the progress
* listener (to prevent
*/
public void cancel() {
if (dlWrapper != null) {
dlWrapper.attemptCancel();
}
}
public Apk getApk() { return curApk; }
public int getBytesRead() { return dlWrapper != null ? dlWrapper.getBytesRead() : 0; }
public int getTotalBytes() { return dlWrapper != null ? dlWrapper.getTotalBytes() : 0; }
}
| gpl-3.0 |
Vult-R/Astraeus-Java-Framework | src/main/java/com/astraeus/game/world/entity/mob/combat/def/AttackType.java | 8782 | package com.astraeus.game.world.entity.mob.combat.def;
import com.astraeus.game.world.entity.mob.combat.Combat;
/**
* The enumerated type whose elements represent the fighting types.
*
* @author lare96 <http://github.com/lare96>
*/
public enum AttackType {
STAFF_BASH(406, 43, 0, Combat.ATTACK_CRUSH, AttackStyle.ACCURATE),
STAFF_POUND(406, 43, 1, Combat.ATTACK_CRUSH, AttackStyle.AGGRESSIVE),
STAFF_FOCUS(406, 43, 2, Combat.ATTACK_CRUSH, AttackStyle.DEFENSIVE),
WARHAMMER_POUND(401, 43, 0, Combat.ATTACK_CRUSH, AttackStyle.ACCURATE),
WARHAMMER_PUMMEL(401, 43, 1, Combat.ATTACK_CRUSH, AttackStyle.AGGRESSIVE),
WARHAMMER_BLOCK(401, 43, 2, Combat.ATTACK_CRUSH, AttackStyle.DEFENSIVE),
SCYTHE_REAP(408, 43, 0, Combat.ATTACK_SLASH, AttackStyle.ACCURATE),
SCYTHE_CHOP(451, 43, 1, Combat.ATTACK_STAB, AttackStyle.AGGRESSIVE),
SCYTHE_JAB(412, 43, 2, Combat.ATTACK_CRUSH, AttackStyle.AGGRESSIVE),
SCYTHE_BLOCK(408, 43, 3, Combat.ATTACK_SLASH, AttackStyle.DEFENSIVE),
BATTLEAXE_CHOP(1833, 43, 0, Combat.ATTACK_SLASH, AttackStyle.ACCURATE),
BATTLEAXE_HACK(1833, 43, 1, Combat.ATTACK_SLASH, AttackStyle.AGGRESSIVE),
BATTLEAXE_SMASH(401, 43, 2, Combat.ATTACK_CRUSH, AttackStyle.AGGRESSIVE),
BATTLEAXE_BLOCK(1833, 43, 3, Combat.ATTACK_SLASH, AttackStyle.DEFENSIVE),
CROSSBOW_ACCURATE(427, 43, 0, Combat.ATTACK_RANGED, AttackStyle.ACCURATE),
CROSSBOW_RAPID(427, 43, 1, Combat.ATTACK_RANGED, AttackStyle.AGGRESSIVE),
CROSSBOW_LONGRANGE(427, 43, 2, Combat.ATTACK_RANGED, AttackStyle.DEFENSIVE),
SHORTBOW_ACCURATE(426, 43, 0, Combat.ATTACK_RANGED, AttackStyle.ACCURATE),
SHORTBOW_RAPID(426, 43, 1, Combat.ATTACK_RANGED, AttackStyle.AGGRESSIVE),
SHORTBOW_LONGRANGE(426, 43, 2, Combat.ATTACK_RANGED, AttackStyle.DEFENSIVE),
LONGBOW_ACCURATE(426, 43, 0, Combat.ATTACK_RANGED, AttackStyle.ACCURATE),
LONGBOW_RAPID(426, 43, 1, Combat.ATTACK_RANGED, AttackStyle.AGGRESSIVE),
LONGBOW_LONGRANGE(426, 43, 2, Combat.ATTACK_RANGED, AttackStyle.DEFENSIVE),
DAGGER_STAB(400, 43, 0, Combat.ATTACK_STAB, AttackStyle.ACCURATE),
DAGGER_LUNGE(400, 43, 1, Combat.ATTACK_STAB, AttackStyle.AGGRESSIVE),
DAGGER_SLASH(451, 43, 2, Combat.ATTACK_STAB, AttackStyle.AGGRESSIVE),
DAGGER_BLOCK(400, 43, 3, Combat.ATTACK_STAB, AttackStyle.DEFENSIVE),
SWORD_STAB(412, 43, 0, Combat.ATTACK_STAB, AttackStyle.ACCURATE),
SWORD_LUNGE(412, 43, 1, Combat.ATTACK_STAB, AttackStyle.AGGRESSIVE),
SWORD_SLASH(451, 43, 2, Combat.ATTACK_SLASH, AttackStyle.AGGRESSIVE),
SWORD_BLOCK(412, 43, 3, Combat.ATTACK_STAB, AttackStyle.DEFENSIVE),
SCIMITAR_CHOP(451, 43, 0, Combat.ATTACK_SLASH, AttackStyle.ACCURATE),
SCIMITAR_SLASH(451, 43, 1, Combat.ATTACK_SLASH, AttackStyle.AGGRESSIVE),
SCIMITAR_LUNGE(412, 43, 2, Combat.ATTACK_STAB, AttackStyle.CONTROLLED),
SCIMITAR_BLOCK(451, 43, 3, Combat.ATTACK_SLASH, AttackStyle.DEFENSIVE),
LONGSWORD_CHOP(451, 43, 0, Combat.ATTACK_SLASH, AttackStyle.ACCURATE),
LONGSWORD_SLASH(451, 43, 1, Combat.ATTACK_SLASH, AttackStyle.AGGRESSIVE),
LONGSWORD_LUNGE(412, 43, 2, Combat.ATTACK_STAB, AttackStyle.CONTROLLED),
LONGSWORD_BLOCK(451, 43, 3, Combat.ATTACK_SLASH, AttackStyle.DEFENSIVE),
MACE_POUND(1833, 43, 0, Combat.ATTACK_CRUSH, AttackStyle.ACCURATE),
MACE_PUMMEL(401, 43, 1, Combat.ATTACK_CRUSH, AttackStyle.AGGRESSIVE),
MACE_SPIKE(412, 43, 2, Combat.ATTACK_STAB, AttackStyle.CONTROLLED),
MACE_BLOCK(401, 43, 3, Combat.ATTACK_CRUSH, AttackStyle.DEFENSIVE),
KNIFE_ACCURATE(806, 43, 0, Combat.ATTACK_RANGED, AttackStyle.ACCURATE),
KNIFE_RAPID(806, 43, 1, Combat.ATTACK_RANGED, AttackStyle.AGGRESSIVE),
KNIFE_LONGRANGE(806, 43, 2, Combat.ATTACK_RANGED, AttackStyle.DEFENSIVE),
SPEAR_LUNGE(2080, 43, 0, Combat.ATTACK_STAB, AttackStyle.CONTROLLED),
SPEAR_SWIPE(2081, 43, 1, Combat.ATTACK_SLASH, AttackStyle.CONTROLLED),
SPEAR_POUND(2082, 43, 2, Combat.ATTACK_CRUSH, AttackStyle.CONTROLLED),
SPEAR_BLOCK(2080, 43, 3, Combat.ATTACK_STAB, AttackStyle.DEFENSIVE),
TWOHANDEDSWORD_CHOP(407, 43, 0, Combat.ATTACK_SLASH, AttackStyle.ACCURATE),
TWOHANDEDSWORD_SLASH(407, 43, 1, Combat.ATTACK_SLASH, AttackStyle.AGGRESSIVE),
TWOHANDEDSWORD_SMASH(406, 43, 2, Combat.ATTACK_CRUSH, AttackStyle.AGGRESSIVE),
TWOHANDEDSWORD_BLOCK(407, 43, 3, Combat.ATTACK_SLASH, AttackStyle.DEFENSIVE),
PICKAXE_SPIKE(412, 43, 0, Combat.ATTACK_STAB, AttackStyle.ACCURATE),
PICKAXE_IMPALE(412, 43, 1, Combat.ATTACK_STAB, AttackStyle.AGGRESSIVE),
PICKAXE_SMASH(401, 43, 2, Combat.ATTACK_CRUSH, AttackStyle.AGGRESSIVE),
PICKAXE_BLOCK(412, 43, 3, Combat.ATTACK_STAB, AttackStyle.DEFENSIVE),
CLAWS_CHOP(451, 43, 0, Combat.ATTACK_SLASH, AttackStyle.ACCURATE),
CLAWS_SLASH(451, 43, 1, Combat.ATTACK_SLASH, AttackStyle.AGGRESSIVE),
CLAWS_LUNGE(412, 43, 2, Combat.ATTACK_STAB, AttackStyle.CONTROLLED),
CLAWS_BLOCK(451, 43, 3, Combat.ATTACK_SLASH, AttackStyle.DEFENSIVE),
HALBERD_JAB(412, 43, 0, Combat.ATTACK_STAB, AttackStyle.CONTROLLED),
HALBERD_SWIPE(440, 43, 1, Combat.ATTACK_SLASH, AttackStyle.AGGRESSIVE),
HALBERD_FEND(412, 43, 2, Combat.ATTACK_STAB, AttackStyle.DEFENSIVE),
UNARMED_PUNCH(422, 43, 0, Combat.ATTACK_CRUSH, AttackStyle.ACCURATE),
UNARMED_KICK(423, 43, 1, Combat.ATTACK_CRUSH, AttackStyle.AGGRESSIVE),
UNARMED_BLOCK(422, 43, 2, Combat.ATTACK_CRUSH, AttackStyle.DEFENSIVE),
WHIP_FLICK(1658, 43, 0, Combat.ATTACK_SLASH, AttackStyle.ACCURATE),
WHIP_LASH(1658, 43, 1, Combat.ATTACK_SLASH, AttackStyle.CONTROLLED),
WHIP_DEFLECT(1658, 43, 2, Combat.ATTACK_SLASH, AttackStyle.DEFENSIVE),
THROWNAXE_ACCURATE(806, 43, 0, Combat.ATTACK_RANGED, AttackStyle.ACCURATE),
THROWNAXE_RAPID(806, 43, 1, Combat.ATTACK_RANGED, AttackStyle.AGGRESSIVE),
THROWNAXE_LONGRANGE(806, 43, 2, Combat.ATTACK_RANGED, AttackStyle.DEFENSIVE),
DART_ACCURATE(806, 43, 0, Combat.ATTACK_RANGED, AttackStyle.ACCURATE),
DART_RAPID(806, 43, 1, Combat.ATTACK_RANGED, AttackStyle.AGGRESSIVE),
DART_LONGRANGE(806, 43, 2, Combat.ATTACK_RANGED, AttackStyle.DEFENSIVE),
JAVELIN_ACCURATE(806, 43, 0, Combat.ATTACK_RANGED, AttackStyle.ACCURATE),
JAVELIN_RAPID(806, 43, 2, Combat.ATTACK_RANGED, AttackStyle.AGGRESSIVE),
JAVELIN_LONGRANGE(806, 43, 3, Combat.ATTACK_RANGED, AttackStyle.DEFENSIVE);
/**
* The animation executed when this type is active.
*/
private final int attackAnimation;
/**
* The parent config identification.
*/
private final int parent;
/**
* The child config identification.
*/
private final int child;
/**
* The type of bonus this type will apply.
*/
private final int bonus;
/**
* The style active when this type is active.
*/
private final AttackStyle style;
/**
* Creates a new {@link AttackType}.
*
* @param animation the animation executed when this type is active.
* @param parent the parent config identification.
* @param child the child config identification.
* @param bonus the type of bonus this type will apply.
* @param style the style active when this type is active.
*/
private AttackType(int attackAnimation, int parent, int child, int bonus, AttackStyle style) {
this.attackAnimation = attackAnimation;
this.parent = parent;
this.child = child;
this.bonus = bonus;
this.style = style;
}
/**
* Determines the corresponding bonus for this fight type.
*
* @return the corresponding.
*/
public final int getCorrespondingBonus() {
switch (bonus) {
case Combat.ATTACK_CRUSH:
return Combat.DEFENCE_CRUSH;
case Combat.ATTACK_MAGIC:
return Combat.DEFENCE_MAGIC;
case Combat.ATTACK_RANGED:
return Combat.DEFENCE_RANGED;
case Combat.ATTACK_SLASH:
return Combat.DEFENCE_SLASH;
case Combat.ATTACK_STAB:
return Combat.DEFENCE_STAB;
default:
return Combat.DEFENCE_CRUSH;
}
}
/**
* Gets the animation executed when this type is active.
*
* @return the animation executed.
*/
public final int getAttackAnimation() {
return attackAnimation;
}
/**
* Gets the parent config identification.
*
* @return the parent config.
*/
public final int getParent() {
return parent;
}
/**
* Gets the child config identification.
*
* @return the child config.
*/
public final int getChild() {
return child;
}
/**
* Gets the type of bonus this type will apply
*
* @return the bonus type.
*/
public final int getBonus() {
return bonus;
}
/**
* Gets the style active when this type is active.
*
* @return the fighting style.
*/
public final AttackStyle getStyle() {
return style;
}
}
| gpl-3.0 |
jtux270/translate | ovirt/3.6_source/backend/manager/modules/restapi/types/src/main/java/org/ovirt/engine/api/restapi/types/QosMapper.java | 9079 | package org.ovirt.engine.api.restapi.types;
import org.ovirt.engine.api.model.DataCenter;
import org.ovirt.engine.api.model.QoS;
import org.ovirt.engine.api.model.QosType;
import org.ovirt.engine.api.restapi.utils.GuidUtils;
import org.ovirt.engine.core.common.businessentities.network.HostNetworkQos;
import org.ovirt.engine.core.common.businessentities.network.NetworkQoS;
import org.ovirt.engine.core.common.businessentities.qos.CpuQos;
import org.ovirt.engine.core.common.businessentities.qos.QosBase;
import org.ovirt.engine.core.common.businessentities.qos.StorageQos;
import org.ovirt.engine.core.compat.Guid;
public class QosMapper {
@Mapping(from = QosBase.class, to = QoS.class)
public static QoS map(QosBase entity, QoS template) {
QoS model = template != null ? template : new QoS();
model.setId(entity.getId().toString());
model.setName(entity.getName());
model.setType(QosTypeMapper.qosTypeToString(entity.getQosType()));
Guid storagePoolId = entity.getStoragePoolId();
if (storagePoolId != null) {
DataCenter dataCenter = new DataCenter();
dataCenter.setId(storagePoolId.toString());
model.setDataCenter(dataCenter);
}
model.setDescription(entity.getDescription());
mapQosTypeToModel(entity, model);
return model;
}
private static void mapQosTypeToModel(QosBase entity, QoS model) {
switch (entity.getQosType()) {
case STORAGE:
mapStorageQosToModel(entity, model);
break;
case CPU:
mapCpuQosToModel(entity, model);
break;
case NETWORK:
mapNetworkQosToModel(entity, model);
break;
case HOSTNETWORK:
mapHostNetworkQosToModel(entity, model);
break;
default:
throw new IllegalArgumentException("Unsupported QoS type");
}
}
private static void mapHostNetworkQosToModel(QosBase entity, QoS model) {
HostNetworkQos hostNetworkQos = verifyAndCast(entity, HostNetworkQos.class);
if (hostNetworkQos != null) {
model.setOutboundAverageLinkshare(hostNetworkQos.getOutAverageLinkshare());
model.setOutboundAverageUpperlimit(hostNetworkQos.getOutAverageUpperlimit());
model.setOutboundAverageRealtime(hostNetworkQos.getOutAverageRealtime());
}
}
private static void mapNetworkQosToModel(QosBase entity, QoS model) {
NetworkQoS networkQos = verifyAndCast(entity, NetworkQoS.class);
if (networkQos != null) {
model.setInboundAverage(networkQos.getInboundAverage());
model.setInboundPeak(networkQos.getInboundPeak());
model.setInboundBurst(networkQos.getInboundBurst());
model.setOutboundAverage(networkQos.getOutboundAverage());
model.setOutboundPeak(networkQos.getOutboundPeak());
model.setOutboundBurst(networkQos.getOutboundBurst());
}
}
private static void mapCpuQosToModel(QosBase entity, QoS model) {
CpuQos cpuQos = verifyAndCast(entity, CpuQos.class);
if (cpuQos != null) {
model.setCpuLimit(cpuQos.getCpuLimit());
}
}
private static void mapStorageQosToModel(QosBase entity, QoS model) {
StorageQos storageQos = verifyAndCast(entity, StorageQos.class);
if (storageQos != null) {
model.setMaxThroughput(storageQos.getMaxThroughput());
model.setMaxReadThroughput(storageQos.getMaxReadThroughput());
model.setMaxWriteThroughput(storageQos.getMaxWriteThroughput());
model.setMaxIops(storageQos.getMaxIops());
model.setMaxReadIops(storageQos.getMaxReadIops());
model.setMaxWriteIops(storageQos.getMaxWriteIops());
}
}
private static <T> T verifyAndCast(Object toCast, Class<T> castTo) {
if (toCast == null) {
return null;
}
if (castTo.isAssignableFrom(toCast.getClass())) {
return castTo.cast(toCast);
} else {
throw new IllegalArgumentException("Cannot cast \"" +
toCast +
"\" to \"" +
castTo +
"\", however given object should be capable of that.");
}
}
private static QosBase createNewQosEntityForQosType(QosType qosType) {
switch (qosType) {
case STORAGE:
return new StorageQos();
case CPU:
return new CpuQos();
case NETWORK:
return new NetworkQoS();
case HOSTNETWORK:
return new HostNetworkQos();
default:
throw new IllegalArgumentException("Unsupported QoS type");
}
}
@Mapping(from = QoS.class, to = QosBase.class)
public static QosBase map(QoS model, QosBase template) {
QosBase entity = template == null ? null : template;
QosType qosType = QosTypeMapper.map (model.getType().toLowerCase(), entity == null ? null : entity.getQosType());
if (entity == null) {
entity = createNewQosEntityForQosType(qosType);
}
if (model.isSetId()) {
entity.setId(GuidUtils.asGuid(model.getId()));
}
if (model.isSetName()) {
entity.setName(model.getName());
}
if (model.isSetDataCenter() && model.getDataCenter().isSetId()) {
entity.setStoragePoolId(GuidUtils.asGuid(model.getDataCenter()
.getId()));
}
if (model.isSetDescription()) {
entity.setDescription(model.getDescription());
}
mapQosToEntity(model, entity, qosType);
return entity;
}
private static void mapQosToEntity(QoS model, QosBase entity, QosType qosType) {
switch (qosType) {
case STORAGE:
mapStorageQosToEntity(model, (StorageQos) entity);
break;
case CPU:
mapCpuQosToEntity(model, (CpuQos) entity);
break;
case NETWORK:
mapNetworkQosToEntity(model, (NetworkQoS) entity);
break;
case HOSTNETWORK:
mapHostNetworkQosToEntity(model, (HostNetworkQos) entity);
break;
default:
break;
}
}
private static void mapHostNetworkQosToEntity(QoS model, HostNetworkQos entity) {
if (model.isSetOutboundAverageLinkshare()) {
entity.setOutAverageLinkshare(model.getOutboundAverageLinkshare());
}
if (model.isSetOutboundAverageUpperlimit()) {
entity.setOutAverageUpperlimit(model.getOutboundAverageUpperlimit());
}
if (model.isSetOutboundAverageRealtime()) {
entity.setOutAverageRealtime(model.getOutboundAverageRealtime());
}
}
private static QosBase mapNetworkQosToEntity(QoS model, NetworkQoS entity) {
if (model.isSetInboundAverage()) {
entity.setInboundAverage(IntegerMapper.mapMinusOneToNull(model.getInboundAverage()));
}
if (model.isSetInboundPeak()) {
entity.setInboundPeak(IntegerMapper.mapMinusOneToNull(model.getInboundPeak()));
}
if (model.isSetInboundBurst()) {
entity.setInboundBurst(IntegerMapper.mapMinusOneToNull(model.getInboundBurst()));
}
if (model.isSetOutboundAverage()) {
entity.setOutboundAverage(IntegerMapper.mapMinusOneToNull(model.getOutboundAverage()));
}
if (model.isSetOutboundPeak()) {
entity.setOutboundPeak(IntegerMapper.mapMinusOneToNull(model.getOutboundPeak()));
}
if (model.isSetOutboundBurst()) {
entity.setOutboundBurst(IntegerMapper.mapMinusOneToNull(model.getOutboundBurst()));
}
return entity;
}
private static QosBase mapCpuQosToEntity(QoS model, CpuQos entity) {
if (model.isSetCpuLimit()) {
entity.setCpuLimit(IntegerMapper.mapMinusOneToNull(model.getCpuLimit()));
}
return entity;
}
private static void mapStorageQosToEntity(QoS model, StorageQos entity) {
if (model.isSetMaxThroughput()) {
entity.setMaxThroughput(IntegerMapper.mapMinusOneToNull(model.getMaxThroughput()));
}
if (model.isSetMaxReadThroughput()) {
entity.setMaxReadThroughput(IntegerMapper.mapMinusOneToNull(model.getMaxReadThroughput()));
}
if (model.isSetMaxWriteThroughput()) {
entity.setMaxWriteThroughput(IntegerMapper.mapMinusOneToNull(model.getMaxWriteThroughput()));
}
if (model.isSetMaxIops()) {
entity.setMaxIops(IntegerMapper.mapMinusOneToNull(model.getMaxIops()));
}
if (model.isSetMaxReadIops()) {
entity.setMaxReadIops(IntegerMapper.mapMinusOneToNull(model.getMaxReadIops()));
}
if (model.isSetMaxWriteIops()) {
entity.setMaxWriteIops(IntegerMapper.mapMinusOneToNull(model.getMaxWriteIops()));
}
}
}
| gpl-3.0 |