repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
lincolnthree/windup
rules-base/tests/src/test/java/org/jboss/windup/rules/apps/condition/FileTest.java
6551
package org.jboss.windup.rules.apps.condition; import org.apache.commons.io.FileUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.forge.arquillian.AddonDependencies; import org.jboss.forge.arquillian.AddonDependency; import org.jboss.forge.arquillian.archive.AddonArchive; import org.jboss.forge.furnace.util.Predicate; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.windup.config.AbstractRuleProvider; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.RuleProvider; import org.jboss.windup.config.metadata.MetadataBuilder; import org.jboss.windup.config.parameters.ParameterizedIterationOperation; import org.jboss.windup.config.phase.InitialAnalysisPhase; import org.jboss.windup.config.phase.MigrationRulesPhase; import org.jboss.windup.config.phase.ReportGenerationPhase; import org.jboss.windup.exec.WindupProcessor; import org.jboss.windup.exec.configuration.WindupConfiguration; import org.jboss.windup.exec.rulefilters.NotPredicate; import org.jboss.windup.exec.rulefilters.RuleProviderPhasePredicate; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.graph.GraphContextFactory; import org.jboss.windup.reporting.model.ClassificationModel; import org.jboss.windup.reporting.service.ClassificationService; import org.jboss.windup.rules.files.condition.File; import org.jboss.windup.rules.files.model.FileReferenceModel; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.ocpsoft.rewrite.config.Configuration; import org.ocpsoft.rewrite.config.ConfigurationBuilder; import org.ocpsoft.rewrite.context.EvaluationContext; import org.ocpsoft.rewrite.param.ParameterStore; import org.ocpsoft.rewrite.param.RegexParameterizedPatternParser; import javax.inject.Inject; import javax.inject.Singleton; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; @RunWith(Arquillian.class) public class FileTest { @Deployment @AddonDependencies({ @AddonDependency(name = "org.jboss.windup.config:windup-config"), @AddonDependency(name = "org.jboss.windup.config:windup-config-xml"), @AddonDependency(name = "org.jboss.windup.reporting:windup-reporting"), @AddonDependency(name = "org.jboss.windup.exec:windup-exec"), @AddonDependency(name = "org.jboss.windup.rules.apps:windup-rules-base"), @AddonDependency(name = "org.jboss.windup.rules.apps:windup-rules-java"), @AddonDependency(name = "org.jboss.forge.furnace.container:cdi") }) public static AddonArchive getDeployment() { final AddonArchive archive = ShrinkWrap.create(AddonArchive.class) .addBeansXML() .addAsResource("xml/FileXmlExample.windup.xml"); return archive; } @Inject private WindupProcessor processor; @Inject private GraphContextFactory factory; @Inject private FileContentTestRuleProvider provider; @Test public void testFileScan() throws Exception { try (GraphContext context = factory.create()) { Path inputPath = Paths.get("src/test/resources/"); Path outputPath = Paths.get(FileUtils.getTempDirectory().toString(), "windup_" + UUID.randomUUID().toString()); FileUtils.deleteDirectory(outputPath.toFile()); Files.createDirectories(outputPath); Predicate<RuleProvider> predicate = new NotPredicate(new RuleProviderPhasePredicate(ReportGenerationPhase.class, MigrationRulesPhase.class)); WindupConfiguration windupConfiguration = new WindupConfiguration() .setRuleProviderFilter(predicate) .setGraphContext(context); windupConfiguration.setInputPath(inputPath); windupConfiguration.setOutputDirectory(outputPath); processor.execute(windupConfiguration); ClassificationService classificationService = new ClassificationService(context); Iterable<ClassificationModel> classifications = classificationService.findAll(); int count=0; for (ClassificationModel classification : classifications) { count++; } //test the classifications xml windup.xml rules Assert.assertEquals(3,count); //test the matches from the java rules Assert.assertTrue(provider.rule1ResultStrings.contains("file1")); Assert.assertTrue(provider.rule1ResultStrings.contains("file2")); Assert.assertTrue(provider.rule1ResultStrings.contains("file3")); } } @Singleton public static class FileContentTestRuleProvider extends AbstractRuleProvider { private List<String> rule1ResultStrings = new ArrayList<>(); private List<FileReferenceModel> rule1ResultModels = new ArrayList<>(); public FileContentTestRuleProvider() { super(MetadataBuilder.forProvider(FileContentTestRuleProvider.class) .setPhase(InitialAnalysisPhase.class).setExecuteAfterIDs(Collections.singletonList("AnalyzeJavaFilesRuleProvider"))); } // @formatter:off @Override public Configuration getConfiguration(GraphContext context) { return ConfigurationBuilder.begin() .addRule() .when(File.inFileNamed("{text}.txt")) .perform(new ParameterizedIterationOperation<FileReferenceModel>() { private RegexParameterizedPatternParser textPattern = new RegexParameterizedPatternParser("{text}"); @Override public void performParameterized(GraphRewrite event, EvaluationContext context, FileReferenceModel payload) { rule1ResultStrings.add(textPattern.getBuilder().build(event, context)); rule1ResultModels.add(payload); } @Override public Set<String> getRequiredParameterNames() { return textPattern.getRequiredParameterNames(); } @Override public void setParameterStore(ParameterStore store) { textPattern.setParameterStore(store); } }); } // @formatter:on } }
epl-1.0
BOTlibre/BOTlibre
botlibre-web/source/org/botlibre/web/servlet/IRCServlet.java
2926
/****************************************************************************** * * Copyright 2013-2019 Paphus Solutions Inc. * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.botlibre.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.botlibre.util.Utils; import org.botlibre.web.bean.IRCBean; import org.botlibre.web.bean.LoginBean; import org.botlibre.web.bean.BotBean; import org.botlibre.web.service.PageStats; @javax.servlet.annotation.WebServlet("/irc") @SuppressWarnings("serial") public class IRCServlet extends BeanServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PageStats.page(request); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); LoginBean loginBean = (LoginBean)request.getSession().getAttribute("loginBean"); if (loginBean == null) { response.sendRedirect("index.jsp"); return; } BotBean botBean = loginBean.getBotBean(); IRCBean bean = loginBean.getBean(IRCBean.class); try { String postToken = (String)request.getParameter("postToken"); loginBean.verifyPostToken(postToken); String instance = (String)request.getParameter("instance"); if (instance != null) { if (botBean.getInstance() == null || !String.valueOf(botBean.getInstanceId()).equals(instance)) { botBean.validateInstance(instance); } } if (!botBean.isConnected()) { response.sendRedirect("irc.jsp"); return; } botBean.checkAdmin(); String server = Utils.sanitize((String)request.getParameter("server")); String channel = Utils.sanitize((String)request.getParameter("channel")); String listen = Utils.sanitize((String)request.getParameter("listen")); String nick = Utils.sanitize((String)request.getParameter("nick")); String submit = (String)request.getParameter("connect"); if (submit != null) { bean.connect(server, channel, nick, "on".equals(listen)); } submit = (String)request.getParameter("disconnect"); if (submit != null) { bean.disconnectChat(); } } catch (Throwable failed) { loginBean.error(failed); } response.sendRedirect("irc.jsp"); } }
epl-1.0
StBurcher/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupBeanQuery.java
8020
/** * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.hawkbit.ui.rollout.rolloutgroup; import static org.apache.commons.lang3.ArrayUtils.isEmpty; import static org.springframework.data.domain.Sort.Direction.ASC; import static org.springframework.data.domain.Sort.Direction.DESC; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.hawkbit.repository.RolloutGroupManagement; import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; import org.eclipse.hawkbit.ui.rollout.state.RolloutUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SpringContextHelper; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.vaadin.addons.lazyquerycontainer.AbstractBeanQuery; import org.vaadin.addons.lazyquerycontainer.QueryDefinition; /** * Simple implementation of generics bean query which dynamically loads a batch * of {@link ProxyRolloutGroup} beans. * */ public class RolloutGroupBeanQuery extends AbstractBeanQuery<ProxyRolloutGroup> { private static final long serialVersionUID = 5342450502894318589L; private Sort sort = new Sort(Direction.ASC, "createdAt"); private transient Page<RolloutGroup> firstPageRolloutGroupSets = null; private transient RolloutManagement rolloutManagement; private transient RolloutGroupManagement rolloutGroupManagement; private transient RolloutUIState rolloutUIState; private final Long rolloutId; /** * Parametric Constructor. * * @param definition * as QueryDefinition * @param queryConfig * as Config * @param sortPropertyIds * as sort * @param sortStates * as Sort status */ public RolloutGroupBeanQuery(final QueryDefinition definition, final Map<String, Object> queryConfig, final Object[] sortPropertyIds, final boolean[] sortStates) { super(definition, queryConfig, sortPropertyIds, sortStates); rolloutId = getRolloutId(); if (!isEmpty(sortStates)) { sort = new Sort(sortStates[0] ? ASC : DESC, (String) sortPropertyIds[0]); for (int targetId = 1; targetId < sortPropertyIds.length; targetId++) { sort.and(new Sort(sortStates[targetId] ? ASC : DESC, (String) sortPropertyIds[targetId])); } } } private Long getRolloutId() { return getRolloutUIState().getRolloutId().isPresent() ? getRolloutUIState().getRolloutId().get() : null; } @Override protected ProxyRolloutGroup constructBean() { return new ProxyRolloutGroup(); } @Override protected List<ProxyRolloutGroup> loadBeans(final int startIndex, final int count) { List<RolloutGroup> proxyRolloutGroupsList = new ArrayList<>(); if (startIndex == 0 && firstPageRolloutGroupSets != null) { proxyRolloutGroupsList = firstPageRolloutGroupSets.getContent(); } else if (null != rolloutId) { proxyRolloutGroupsList = getRolloutGroupManagement() .findAllRolloutGroupsWithDetailedStatus(rolloutId, new PageRequest(startIndex / count, count)) .getContent(); } return getProxyRolloutGroupList(proxyRolloutGroupsList); } private List<ProxyRolloutGroup> getProxyRolloutGroupList(final List<RolloutGroup> rolloutGroupBeans) { final List<ProxyRolloutGroup> proxyRolloutGroupsList = new ArrayList<>(); for (final RolloutGroup rolloutGroup : rolloutGroupBeans) { final ProxyRolloutGroup proxyRolloutGroup = new ProxyRolloutGroup(); proxyRolloutGroup.setName(rolloutGroup.getName()); proxyRolloutGroup.setDescription(rolloutGroup.getDescription()); proxyRolloutGroup.setCreatedDate(SPDateTimeUtil.getFormattedDate(rolloutGroup.getCreatedAt())); proxyRolloutGroup.setModifiedDate(SPDateTimeUtil.getFormattedDate(rolloutGroup.getLastModifiedAt())); proxyRolloutGroup.setCreatedBy(UserDetailsFormatter.loadAndFormatCreatedBy(rolloutGroup)); proxyRolloutGroup.setLastModifiedBy(UserDetailsFormatter.loadAndFormatLastModifiedBy(rolloutGroup)); proxyRolloutGroup.setId(rolloutGroup.getId()); proxyRolloutGroup.setStatus(rolloutGroup.getStatus()); proxyRolloutGroup.setErrorAction(rolloutGroup.getErrorAction()); proxyRolloutGroup.setErrorActionExp(rolloutGroup.getErrorActionExp()); proxyRolloutGroup.setErrorCondition(rolloutGroup.getErrorCondition()); proxyRolloutGroup.setErrorConditionExp(rolloutGroup.getErrorConditionExp()); proxyRolloutGroup.setSuccessCondition(rolloutGroup.getSuccessCondition()); proxyRolloutGroup.setSuccessConditionExp(rolloutGroup.getSuccessConditionExp()); proxyRolloutGroup.setFinishedPercentage(calculateFinishedPercentage(rolloutGroup)); proxyRolloutGroup.setRolloutRendererData(new RolloutRendererData(rolloutGroup.getName(), null)); proxyRolloutGroup.setTotalTargetsCount(String.valueOf(rolloutGroup.getTotalTargets())); proxyRolloutGroup.setTotalTargetCountStatus(rolloutGroup.getTotalTargetCountStatus()); proxyRolloutGroupsList.add(proxyRolloutGroup); } return proxyRolloutGroupsList; } private String calculateFinishedPercentage(final RolloutGroup rolloutGroup) { return HawkbitCommonUtil.formattingFinishedPercentage(rolloutGroup, getRolloutManagement() .getFinishedPercentForRunningGroup(rolloutGroup.getRollout().getId(), rolloutGroup)); } @Override protected void saveBeans(final List<ProxyRolloutGroup> arg0, final List<ProxyRolloutGroup> arg1, final List<ProxyRolloutGroup> arg2) { /** * CRUD operations be done through repository methods. */ } @Override public int size() { long size = 0; if (null != rolloutId) { firstPageRolloutGroupSets = getRolloutGroupManagement().findAllRolloutGroupsWithDetailedStatus(rolloutId, new PageRequest(0, SPUIDefinitions.PAGE_SIZE, sort)); size = firstPageRolloutGroupSets.getTotalElements(); } if (size > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } return (int) size; } /** * @return the rolloutManagement */ public RolloutManagement getRolloutManagement() { if (null == rolloutManagement) { rolloutManagement = SpringContextHelper.getBean(RolloutManagement.class); } return rolloutManagement; } /** * @return the rolloutManagement */ public RolloutGroupManagement getRolloutGroupManagement() { if (null == rolloutGroupManagement) { rolloutGroupManagement = SpringContextHelper.getBean(RolloutGroupManagement.class); } return rolloutGroupManagement; } /** * @return the rolloutUIState */ public RolloutUIState getRolloutUIState() { if (null == rolloutUIState) { rolloutUIState = SpringContextHelper.getBean(RolloutUIState.class); } return rolloutUIState; } }
epl-1.0
mutandon/ExecutionUtilities
src/main/java/eu/unitn/disi/db/command/ConfigurableParam.java
923
/* * Copyright (C) 2012 Davide Mottin <mottin@disi.unitn.eu> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 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 eu.unitn.disi.db.command; /** * * @author Davide Mottin <mottin@disi.unitn.eu> */ public @interface ConfigurableParam { }
gpl-2.0
noegonmar/udimapatterns
noegonmar/src/com/noegonmar/patter/abstractfactory/FabricaMultasSinPuntos.java
495
package com.noegonmar.patter.abstractfactory; /** * Clase que implementa las operaciones de creación de productos concretos * * @author noegonmar * */ public class FabricaMultasSinPuntos implements FabricaMultas { MultaGraveSinPuntos mgsp = new MultaGraveSinPuntos(); @Override public MultaGrave crearMultaGrave() { return new MultaGraveSinPuntos(); } @Override public MultaMuyGrave crearMultaMuyGrave() { // No existen las multas muy graves sin puntos return null; } }
gpl-2.0
jensnerche/plantuml
src/net/sourceforge/plantuml/skin/rose/ComponentRoseGroupingSpace.java
2327
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2014, Arnaud Roques * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML 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. * * PlantUML 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * Original Author: Arnaud Roques * * Revision $Revision: 7891 $ * */ package net.sourceforge.plantuml.skin.rose; import java.awt.geom.Dimension2D; import net.sourceforge.plantuml.Dimension2DDouble; import net.sourceforge.plantuml.graphic.StringBounder; import net.sourceforge.plantuml.skin.Area; import net.sourceforge.plantuml.skin.Component; import net.sourceforge.plantuml.skin.Context2D; import net.sourceforge.plantuml.ugraphic.UGraphic; public class ComponentRoseGroupingSpace implements Component { private final double space; public ComponentRoseGroupingSpace(double space) { this.space = space; } public double getPreferredWidth(StringBounder stringBounder) { return 0; } public double getPreferredHeight(StringBounder stringBounder) { return space; } public void drawU(UGraphic ug, Area area, Context2D context) { } public final Dimension2D getPreferredDimension(StringBounder stringBounder) { final double w = getPreferredWidth(stringBounder); final double h = getPreferredHeight(stringBounder); return new Dimension2DDouble(w, h); } }
gpl-2.0
FernandoUnix/MeusArquivos
ComprarJsfHibernate/src/controller/CarrinhoComprasController.java
1269
package controller; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import entities.Comprar; import entities.Item; import model.ComprasModel; @ManagedBean(name = "carrinhoComprasController") @SessionScoped public class CarrinhoComprasController { private ComprasModel cm = new ComprasModel(); private List<Item> carrinho = new ArrayList<Item>(); public List<Item> getCarrinho() { return carrinho; } public void setCarrinho(List<Item> carrinho) { this.carrinho = carrinho; } public double soma() { double s = 0; for (Item it : this.carrinho) s += it.getQuantidade() * it.getComprar().getPreco(); return s; } public void delete(Item it) { this.carrinho.remove(it); } private int isExisting(Comprar p) { for (int i = 0; i < this.carrinho.size(); i++) if (this.carrinho.get(i).getComprar().getId() == p.getId()) return i; return -1; } public String compras(Comprar p) { int index = isExisting(p); if (index == -1) this.carrinho.add(new Item(p, 1)); else { int quantidade = this.carrinho.get(index).getQuantidade() + 1; this.carrinho.get(index).setQuantidade(quantidade); } return "carrinho?face-redirect=true"; } }
gpl-2.0
JohnTodd78/Emojis
app/src/main/java/com/example/todd/connector/EmojisConnector.java
2882
package com.example.todd.connector; import android.app.Activity; import android.os.AsyncTask; import android.util.JsonReader; import android.util.Log; import android.widget.ListView; import com.example.todd.adapter.EmojisAdapter; import com.example.todd.emojis.R; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; /** * Created by john on 11/11/15. * Simple AsyncTask to load emojis names and image url's into a hashmap */ public class EmojisConnector extends AsyncTask<String, Void, HashMap<String,String>> { // Set up our simple objects and variables private final String LOG = this.getClass().getName(); final String EMO_URL = "https://api.github.com/emojis"; URL emoURL; Activity activity; EmojisAdapter emojisAdapter; public EmojisConnector(Activity activity){ this.activity = activity; } // doInBackground makes the https call, loads the hashmap and passes off to onPostExecute @Override protected HashMap<String,String> doInBackground(String... params) { HttpURLConnection urlConnection = null; InputStream inputStream; try { emoURL = new URL(EMO_URL); urlConnection = (HttpURLConnection) emoURL.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); inputStream = urlConnection.getInputStream(); JsonReader reader; if(inputStream == null){ return null; } reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8")); return getEmojis(reader); }catch (IOException e){ Log.e(LOG, e.getMessage()); return null; } finally { if(urlConnection != null){ urlConnection.disconnect(); } } } // onPostExecute sets up the listview, creates the emojisAdapter and sets the adapter to the listview @Override protected void onPostExecute(HashMap<String,String> hashMap) { super.onPostExecute(hashMap); ListView listView = (ListView) activity.findViewById(R.id.list_view); emojisAdapter = new EmojisAdapter(activity,hashMap); listView.setAdapter(emojisAdapter); } // getEmojis takes the returned json and makes a hashmap from it public HashMap<String, String> getEmojis(JsonReader jsonReader) throws IOException { HashMap<String,String> emoMap = new HashMap<>(); String name = ""; String url = null; jsonReader.beginObject(); while (jsonReader.hasNext()) { name = jsonReader.nextName(); url = jsonReader.nextString(); emoMap.put(name,url); } return emoMap; } }
gpl-2.0
CodeFromJordan/Gloggr
src/com/JordHan/Gloggr/Services/AbstractService.java
1329
package com.JordHan.Gloggr.Services; import java.io.Serializable; import java.util.ArrayList; import android.os.Bundle; import android.os.Handler; import android.os.Message; public abstract class AbstractService implements Serializable, Runnable { private ArrayList<IServiceListener> listeners; private boolean error; public AbstractService() { listeners = new ArrayList<IServiceListener>(); } public void addListener(IServiceListener listener) { listeners.add(listener); } public void removeListener(IServiceListener listener) { listeners.remove(listener); } public boolean hasError() { return error; } public void serviceComplete(boolean error) { this.error = error; Message m = _handler.obtainMessage(); Bundle b = new Bundle(); b.putSerializable("service", this); m.setData(b); _handler.sendMessage(m); } final Handler _handler = new Handler() { @Override public void handleMessage(Message msg) { AbstractService service = (AbstractService) msg.getData().getSerializable("service"); for (IServiceListener listener : service.listeners) { listener.ServiceComplete(service); } } }; }
gpl-2.0
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/reader/services/ServiceCompletionListener.java
138
package org.wordpress.android.ui.reader.services; public interface ServiceCompletionListener { void onCompleted(Object companion); }
gpl-2.0
Baaleos/nwnx2-linux
plugins/jvm/java/src/org/nwnx/nwnx2/jvm/constants/CreaturePart.java
2380
package org.nwnx.nwnx2.jvm.constants; /** * This class contains all unique constants beginning with "CREATURE_PART". * Non-distinct keys are filtered; only the LAST appearing was * kept. */ public final class CreaturePart { private CreaturePart() {} public final static int BELT = 8; public final static int HEAD = 20; public final static int LEFT_BICEP = 13; public final static int LEFT_FOOT = 1; public final static int LEFT_FOREARM = 11; public final static int LEFT_HAND = 17; public final static int LEFT_SHIN = 3; public final static int LEFT_SHOULDER = 15; public final static int LEFT_THIGH = 4; public final static int NECK = 9; public final static int PELVIS = 6; public final static int RIGHT_BICEP = 12; public final static int RIGHT_FOOT = 0; public final static int RIGHT_FOREARM = 10; public final static int RIGHT_HAND = 16; public final static int RIGHT_SHIN = 2; public final static int RIGHT_SHOULDER = 14; public final static int RIGHT_THIGH = 5; public final static int TORSO = 7; public static String nameOf(int value) { if (value == 8) return "CreaturePart.BELT"; if (value == 20) return "CreaturePart.HEAD"; if (value == 13) return "CreaturePart.LEFT_BICEP"; if (value == 1) return "CreaturePart.LEFT_FOOT"; if (value == 11) return "CreaturePart.LEFT_FOREARM"; if (value == 17) return "CreaturePart.LEFT_HAND"; if (value == 3) return "CreaturePart.LEFT_SHIN"; if (value == 15) return "CreaturePart.LEFT_SHOULDER"; if (value == 4) return "CreaturePart.LEFT_THIGH"; if (value == 9) return "CreaturePart.NECK"; if (value == 6) return "CreaturePart.PELVIS"; if (value == 12) return "CreaturePart.RIGHT_BICEP"; if (value == 0) return "CreaturePart.RIGHT_FOOT"; if (value == 10) return "CreaturePart.RIGHT_FOREARM"; if (value == 16) return "CreaturePart.RIGHT_HAND"; if (value == 2) return "CreaturePart.RIGHT_SHIN"; if (value == 14) return "CreaturePart.RIGHT_SHOULDER"; if (value == 5) return "CreaturePart.RIGHT_THIGH"; if (value == 7) return "CreaturePart.TORSO"; return "CreaturePart.(not found: " + value + ")"; } public static String nameOf(float value) { return "CreaturePart.(not found: " + value + ")"; } public static String nameOf(String value) { return "CreaturePart.(not found: " + value + ")"; } }
gpl-2.0
Tamfoolery/Woodcraft
src/main/java/com/giftedpineapples/wood/client/renderer/tileentity/TileEntityRendererWindTurbine.java
1351
package com.giftedpineapples.wood.client.renderer.tileentity; import com.giftedpineapples.wood.client.renderer.model.ModelWindTurbine; import com.giftedpineapples.wood.reference.MiscVariables; import com.giftedpineapples.wood.reference.Textures; import com.giftedpineapples.wood.tileentity.TileEntityWindTurbine; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import org.lwjgl.opengl.GL11; @SideOnly(Side.CLIENT) public class TileEntityRendererWindTurbine extends TileEntitySpecialRenderer { private final ModelWindTurbine modelWindTurbine = new ModelWindTurbine(); @Override public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float tick) { if (tileEntity instanceof TileEntityWindTurbine) { // TileEntityWindTurbine tileEntityWindTurbine = (TileEntityWindTurbine) tileEntity; GL11.glPushMatrix(); // Scale, Translate, Rotate GL11.glScalef(1.0F, 1.0F, 1.0F); GL11.glTranslatef((float) x + 0.5F, (float) y + 0.0F, (float) z + 0.5F); GL11.glRotatef(MiscVariables.shaftRotation, 0F, 1F, 0F); // Bind Texture this.bindTexture(Textures.Model.WIND_TURBINE); // Render modelWindTurbine.render(); GL11.glPopMatrix(); } } }
gpl-2.0
csimplestring/xsd-2-go
src/test/java/main/TestStart.java
364
package main; import org.junit.Test; public class TestStart { @Test public void testStart() { String pkg = "generated"; String folder = "/Users/yiwang/Desktop/marble-2404/generated"; Start s = new Start(); try { s.run(folder, pkg); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
gpl-2.0
shiyqw/wyvern
tools/src/wyvern/tools/tests/RossettaCodeTests.java
3372
package wyvern.tools.tests; import static java.util.Optional.empty; import static wyvern.stdlib.Globals.getStandardEnv; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Optional; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import edu.umn.cs.melt.copper.runtime.logging.CopperParserException; import wyvern.stdlib.Globals; import wyvern.tools.imports.extensions.WyvernResolver; import wyvern.tools.parsing.coreparser.ParseException; import wyvern.tools.parsing.coreparser.TokenManager; import wyvern.tools.parsing.coreparser.WyvernParser; import wyvern.tools.parsing.coreparser.WyvernTokenManager; import wyvern.tools.tests.suites.RegressionTests; import wyvern.tools.tests.tagTests.TestUtil; import wyvern.tools.typedAST.core.values.IntegerConstant; import wyvern.tools.typedAST.interfaces.TypedAST; import wyvern.tools.typedAST.interfaces.Value; import wyvern.tools.types.Type; import wyvern.tools.types.extensions.Int; @Category(RegressionTests.class) public class RossettaCodeTests { @BeforeClass public static void setupResolver() { TestUtil.setPaths(); WyvernResolver.getInstance().addPath(PATH); } @Test public void testHello() throws ParseException { String program = TestUtil.readFile(PATH + "hello.wyv"); /* String input = "requires stdout\n\n" // or stdio, or io, or stdres, but these are not least privilege + "stdout.print(\"Hello, World\")\n"; String altInput = "requires ffi\n" // more explicit version; but resources can be available w/o explicit ffi + "instantiate stdout(ffi)\n\n" + "stdout.print(\"Hello, World\")\n"; // a standard bag of resources is a map from type to resource module impl String stdoutInput = "module stdout.java : stdout\n\n" // the java version + "requires ffi.java as ffi\n\n" // this is the version for the Java platform; others linked in transparently + "instantiate java(ffi)\n\n" // a particular FFI that needs the FFI meta-permission + "import java:java.lang.System\n\n" + "java.lang.System.out\n"; // result of the stdout module - of course could also be wrapped String stdoutSig = "type stdout\n" // type sig for stdout; part of std prelude, so this is always in scope + " def print(String text):void"; */ TypedAST ast = TestUtil.getNewAST(program); //Type resultType = ast.typecheck(Globals.getStandardEnv(), Optional.<Type>empty()); TestUtil.evaluateNew(ast); //Assert.assertEquals(resultType, new Int()); //Value out = testAST.evaluate(Globals.getStandardEvalEnv()); //int finalRes = ((IntegerConstant)out).getValue(); //Assert.assertEquals(3, finalRes); } private static final String BASE_PATH = TestUtil.BASE_PATH; private static final String PATH = BASE_PATH + "rosetta/"; private static final String OLD_PATH = BASE_PATH + "rosetta-old/"; @Test /** * This test ensures that hello world works with the old parser */ public void testOldHello() throws CopperParserException, IOException { String program = TestUtil.readFile(OLD_PATH + "helloOld.wyv"); TypedAST ast = TestUtil.getAST(program); TestUtil.evaluate(ast); } }
gpl-2.0
biblelamp/JavaExercises
GamesOldVersion/GameSnake.java
5987
/** * Java. Classic Game Snake * * @author Sergey Iryupin * @version 0.1 dated Aug 20, 2016 * * See webinar: * https://www.youtube.com/watch?v=Zsthou6Ttyc */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; public class GameSnake { final String TITLE_OF_PROGRAM = "Classic Game Snake"; final String GAME_OVER_MSG = "GAME OVER"; final int POINT_RADIUS = 20; // in pix final int FIELD_WIDTH = 30; // in point final int FIELD_HEIGHT = 20; final int FIELD_DX = 6; final int FIELD_DY = 28; final int START_LOCATION = 200; final int START_SNAKE_SIZE = 6; final int START_SNAKE_X = 10; final int START_SNAKE_Y = 10; final int SHOW_DELAY = 150; final int LEFT = 37; final int UP = 38; final int RIGHT = 39; final int DOWN = 40; final int START_DIRECTION = RIGHT; final Color DEFAULT_COLOR = Color.black; final Color FOOD_COLOR = Color.green; //final Color POISON_COLOR = Color.red; Snake snake; Food food; //Poison poison; JFrame frame; Canvas canvasPanel; Random random = new Random(); boolean gameOver = false; public static void main(String[] args) { new GameSnake().go(); } void go() { frame = new JFrame(TITLE_OF_PROGRAM + " : " + START_SNAKE_SIZE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(FIELD_WIDTH * POINT_RADIUS + FIELD_DX, FIELD_HEIGHT * POINT_RADIUS + FIELD_DY); frame.setLocation(START_LOCATION, START_LOCATION); frame.setResizable(false); canvasPanel = new Canvas(); canvasPanel.setBackground(Color.white); frame.getContentPane().add(BorderLayout.CENTER, canvasPanel); frame.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { snake.setDirection(e.getKeyCode()); } }); frame.setVisible(true); snake = new Snake(START_SNAKE_X, START_SNAKE_Y, START_SNAKE_SIZE, START_DIRECTION); food = new Food(); while (!gameOver) { snake.move(); if (food.isEaten()) { food.next(); } canvasPanel.repaint(); try { Thread.sleep(SHOW_DELAY); } catch (InterruptedException e) { e.printStackTrace(); } } } class Snake { ArrayList<Point> snake = new ArrayList<Point>(); int direction; public Snake(int x, int y, int length, int direction) { for (int i = 0; i < length; i++) { Point point = new Point(x-i, y); snake.add(point); } this.direction = direction; } boolean isInsideSnake(int x, int y) { for (Point point : snake) { if ((point.getX() == x) && (point.getY() == y)) { return true; } } return false; } boolean isFood(Point food) { return ((snake.get(0).getX() == food.getX()) && (snake.get(0).getY() == food.getY())); } void move() { int x = snake.get(0).getX(); int y = snake.get(0).getY(); if (direction == LEFT) { x--; } if (direction == RIGHT) { x++; } if (direction == UP) { y--; } if (direction == DOWN) { y++; } if (x > FIELD_WIDTH - 1) { x = 0; } if (x < 0) { x = FIELD_WIDTH - 1; } if (y > FIELD_HEIGHT - 1) { y = 0; } if (y < 0) { y = FIELD_HEIGHT - 1; } gameOver = isInsideSnake(x, y); // check for acrooss itselves snake.add(0, new Point(x, y)); if (isFood(food)) { food.eat(); frame.setTitle(TITLE_OF_PROGRAM + " : " + snake.size()); } else { snake.remove(snake.size() - 1); } } void setDirection(int direction) { if ((direction >= LEFT) && (direction <= DOWN)) { if (Math.abs(this.direction - direction) != 2) { this.direction = direction; } } } void paint(Graphics g) { for (Point point : snake) { point.paint(g); } } } class Food extends Point { public Food() { super(-1, -1); this.color = FOOD_COLOR; } void eat() { this.setXY(-1, -1); } boolean isEaten() { return this.getX() == -1; } void next() { int x, y; do { x = random.nextInt(FIELD_WIDTH); y = random.nextInt(FIELD_HEIGHT); } while (snake.isInsideSnake(x, y)); this.setXY(x, y); } } class Point { int x, y; Color color = DEFAULT_COLOR; public Point(int x, int y) { this.setXY(x, y); } void paint(Graphics g) { g.setColor(color); g.fillOval(x * POINT_RADIUS, y * POINT_RADIUS, POINT_RADIUS, POINT_RADIUS); } int getX() { return x; } int getY() { return y; } void setXY(int x, int y) { this.x = x; this.y = y; } } public class Canvas extends JPanel { @Override public void paint(Graphics g) { super.paint(g); snake.paint(g); food.paint(g); if (gameOver) { g.setColor(Color.red); g.setFont(new Font("Arial", Font.BOLD, 40)); FontMetrics fm = g.getFontMetrics(); g.drawString(GAME_OVER_MSG, (FIELD_WIDTH * POINT_RADIUS + FIELD_DX - fm.stringWidth(GAME_OVER_MSG))/2, (FIELD_HEIGHT * POINT_RADIUS + FIELD_DY)/2); } } } }
gpl-2.0
saces/fred
src/freenet/node/fcp/PersistentPutDir.java
6678
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package freenet.node.fcp; import java.util.HashMap; import com.db4o.ObjectContainer; import freenet.client.async.ManifestElement; import freenet.client.async.SimpleManifestPutter; import freenet.keys.FreenetURI; import freenet.node.Node; import freenet.support.HexUtil; import freenet.support.Logger; import freenet.support.SimpleFieldSet; import freenet.support.api.Bucket; import freenet.support.io.DelayedFreeBucket; import freenet.support.io.FileBucket; import freenet.support.io.NullBucket; import freenet.support.io.PaddedEphemerallyEncryptedBucket; import freenet.support.io.PersistentTempFileBucket; import freenet.support.io.TempBucketFactory; public class PersistentPutDir extends FCPMessage { static final String name = "PersistentPutDir"; final String identifier; final FreenetURI uri; final int verbosity; final short priorityClass; final short persistenceType; final boolean global; private final HashMap<String, Object> manifestElements; final String defaultName; final String token; final boolean started; final int maxRetries; final boolean wasDiskPut; private final SimpleFieldSet cached; final boolean dontCompress; final String compressorDescriptor; final boolean realTime; final byte[] splitfileCryptoKey; public PersistentPutDir(String identifier, FreenetURI uri, int verbosity, short priorityClass, short persistenceType, boolean global, String defaultName, HashMap<String, Object> manifestElements, String token, boolean started, int maxRetries, boolean dontCompress, String compressorDescriptor, boolean wasDiskPut, boolean realTime, byte[] splitfileCryptoKey, ObjectContainer container) { this.identifier = identifier; this.uri = uri; this.verbosity = verbosity; this.priorityClass = priorityClass; this.persistenceType = persistenceType; this.global = global; this.defaultName = defaultName; this.manifestElements = manifestElements; this.token = token; this.started = started; this.maxRetries = maxRetries; this.wasDiskPut = wasDiskPut; this.dontCompress = dontCompress; this.compressorDescriptor = compressorDescriptor; this.realTime = realTime; this.splitfileCryptoKey = splitfileCryptoKey; cached = generateFieldSet(container); } private SimpleFieldSet generateFieldSet(ObjectContainer container) { SimpleFieldSet fs = new SimpleFieldSet(false); // false because this can get HUGE fs.putSingle("Identifier", identifier); fs.putSingle("URI", uri.toString(false, false)); fs.put("Verbosity", verbosity); fs.putSingle("Persistence", ClientRequest.persistenceTypeString(persistenceType)); fs.put("PriorityClass", priorityClass); fs.put("Global", global); fs.putSingle("PutDirType", wasDiskPut ? "disk" : "complex"); SimpleFieldSet files = new SimpleFieldSet(false); // Flatten the hierarchy, it can be reconstructed on restarting. // Storing it directly would be a PITA. // FIXME/RESOLVE: The new BaseManifestPutter's container mode does not hold the origin data, // after composing the PutHandlers (done in BaseManifestPutter), they are 'lost': // A resumed half done container put can not get the complete file list from BaseManifestPutter. // Is it really necessary to include the file list here? ManifestElement[] elements = SimpleManifestPutter.flatten(manifestElements); fs.putSingle("DefaultName", defaultName); for(int i=0;i<elements.length;i++) { String num = Integer.toString(i); ManifestElement e = elements[i]; String mimeOverride = e.getMimeTypeOverride(); SimpleFieldSet subset = new SimpleFieldSet(false); FreenetURI tempURI = e.getTargetURI(); subset.putSingle("Name", e.getName()); if(tempURI != null) { subset.putSingle("UploadFrom", "redirect"); subset.putSingle("TargetURI", tempURI.toString()); } else { // Deactivate the top, not the middle. // Deactivating the middle can cause big problems. Bucket origData = e.getData(); Bucket data = origData; boolean deactivate = false; if(persistenceType == ClientRequest.PERSIST_FOREVER) deactivate = !container.ext().isActive(data); if(deactivate) container.activate(data, 1); if(data instanceof DelayedFreeBucket) { data = ((DelayedFreeBucket)data).getUnderlying(); } subset.put("DataLength", e.getSize()); if(mimeOverride != null) subset.putSingle("Metadata.ContentType", mimeOverride); // What to do with the bucket? // It is either a persistent encrypted bucket or a file bucket ... if(data == null) { Logger.error(this, "Bucket already freed: "+e.getData()+" for "+e+" for "+e.getName()+" for "+identifier); } else if(data instanceof FileBucket) { subset.putSingle("UploadFrom", "disk"); subset.putSingle("Filename", ((FileBucket)data).getFile().getPath()); } else if (data instanceof PaddedEphemerallyEncryptedBucket || data instanceof NullBucket || data instanceof PersistentTempFileBucket || data instanceof TempBucketFactory.TempBucket) { subset.putSingle("UploadFrom", "direct"); } else { throw new IllegalStateException("Don't know what to do with bucket: "+data); } if(deactivate) container.deactivate(origData, 1); } files.put(num, subset); } files.put("Count", elements.length); fs.put("Files", files); if(token != null) fs.putSingle("ClientToken", token); fs.put("Started", started); fs.put("MaxRetries", maxRetries); fs.put("DontCompress", dontCompress); if(compressorDescriptor != null) fs.putSingle("Codecs", compressorDescriptor); fs.put("RealTime", realTime); if(splitfileCryptoKey != null) fs.putSingle("SplitfileCryptoKey", HexUtil.bytesToHex(splitfileCryptoKey)); return fs; } @Override public SimpleFieldSet getFieldSet() { return cached; } @Override public String getName() { return name; } @Override public void run(FCPConnectionHandler handler, Node node) throws MessageInvalidException { throw new MessageInvalidException(ProtocolErrorMessage.INVALID_MESSAGE, "PersistentPut goes from server to client not the other way around", identifier, global); } @Override public void removeFrom(ObjectContainer container) { container.activate(uri, 5); uri.removeFrom(container); // manifestElements will be removed by ClientPutDir.freeData, not our problem. container.activate(cached, Integer.MAX_VALUE); cached.removeFrom(container); container.delete(this); } }
gpl-2.0
tn5250j/tn5250j
src/org/tn5250j/tools/logging/ConsoleLogger.java
4270
/* * @(#)ConsoleLogger.java * @author Kenneth J. Pouncey * * Copyright: Copyright (c) 2001, 2002, 2003 * * 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, 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 software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * */ package org.tn5250j.tools.logging; /** * An implementation of the TN5250jLogger to provide logger instances to the * console - System.out or System.err. */ public final class ConsoleLogger implements TN5250jLogger { private int logLevel = TN5250jLogger.WARN; private String clazz = null; /* * Package level access only */ ConsoleLogger() { } public void initialize(final String clazz) { this.clazz = clazz; } public void debug(Object message) { if (isDebugEnabled()) System.out.println("DEBUG [" + clazz + "] " + ((message != null) ? message.toString() : "")); } public void debug(Object message, Throwable throwable) { if (isDebugEnabled()) System.out.println("DEBUG [" + clazz + "] " + ((message != null) ? message.toString() : "") + ((throwable != null) ? throwable.getMessage() : "")); } public void info(Object message) { if (isInfoEnabled()) System.out.println("INFO [" + clazz + "] " + ((message != null) ? message.toString() : "")); } public void info(Object message, Throwable throwable) { if (isInfoEnabled()) System.out.println("INFO [" + clazz + "] " + ((message != null) ? message.toString() : "") + ((throwable != null) ? throwable.getMessage() : "")); } public void warn(Object message) { if (isWarnEnabled()) System.err.println("WARN [" + clazz + "] " + ((message != null) ? message.toString() : "")); } public void warn(Object message, Throwable throwable) { if (isWarnEnabled()) System.err.println("WARN [" + clazz + "] " + ((message != null) ? message.toString() : "") + ((throwable != null) ? throwable.getMessage() : "")); } public void error(Object message) { if (isErrorEnabled()) System.err.println("ERROR [" + clazz + "] " + ((message != null) ? message.toString() : "")); } public void error(Object message, Throwable throwable) { if (isErrorEnabled()) System.err.println("ERROR [" + clazz + "] " + ((message != null) ? message.toString() : "") + ((throwable != null) ? throwable.getMessage() : "")); } public void fatal(Object message) { if (isFatalEnabled()) System.err.println("FATAL [" + clazz + "] " + ((message != null) ? message.toString() : "")); } public void fatal(Object message, Throwable throwable) { if (isFatalEnabled()) System.err.println("FATAL [" + clazz + "] " + ((message != null) ? message.toString() : "") + ((throwable != null) ? throwable.getMessage() : "")); } public boolean isDebugEnabled() { return (logLevel <= DEBUG); // 1 } public boolean isInfoEnabled() { return (logLevel <= INFO); // 2 } public boolean isWarnEnabled() { return (logLevel <= WARN); // 4 } public boolean isErrorEnabled() { return (logLevel <= ERROR); // 8 } public boolean isFatalEnabled() { return (logLevel <= FATAL); // 16 } public int getLevel() { return logLevel; } public void setLevel(int newLevel) { logLevel = newLevel; } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/src/share/classes/com/sun/jdi/VMMismatchException.java
1641
/* * Copyright 1999-2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.jdi; /** * Thrown to indicate that the requested operation cannot be * completed because the a mirror from one target VM is being * combined with a mirror from another target VM. * * @author Gordon Hirsch * @since 1.3 */ public class VMMismatchException extends RuntimeException { public VMMismatchException() { super(); } public VMMismatchException(String s) { super(s); } }
gpl-2.0
dsp/projectsonar
src/edu/kit/ipd/sonar/client/rpc/RPCHandler.java
16059
/** * This file is part of Sonar. * * Sonar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2 of the License. * * Sonar 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 Sonar. If not, see <http://www.gnu.org/licenses/>. */ package edu.kit.ipd.sonar.client.rpc; import edu.kit.ipd.sonar.client.SonarMessages; import edu.kit.ipd.sonar.client.event.AttemptAuthenticationEvent; import edu.kit.ipd.sonar.client.event.AttemptAuthenticationEventHandler; import edu.kit.ipd.sonar.client.event.AttemptLogoutEvent; import edu.kit.ipd.sonar.client.event.AttemptLogoutEventHandler; import edu.kit.ipd.sonar.client.event.AvailableCentralitiesArrivedEvent; import edu.kit.ipd.sonar.client.event.AvailableCentralitiesRequestEvent; import edu.kit.ipd.sonar.client.event.AvailableCentralitiesRequestEventHandler; import edu.kit.ipd.sonar.client.event.AvailableTimeBoundaryArrivedEvent; import edu.kit.ipd.sonar.client.event.AvailableTimeBoundaryRequestEvent; import edu.kit.ipd.sonar.client.event.AvailableTimeBoundaryRequestEventHandler; import edu.kit.ipd.sonar.client.event.DatabaseChangedEvent; import edu.kit.ipd.sonar.client.event.ErrorOccuredEvent; import edu.kit.ipd.sonar.client.event.FailedAuthenticationEvent; import edu.kit.ipd.sonar.client.event.GraphArrivedEvent; import edu.kit.ipd.sonar.client.event.GraphRequestEvent; import edu.kit.ipd.sonar.client.event.GraphRequestEventHandler; import edu.kit.ipd.sonar.client.event.SuccessfulAuthenticationEvent; import edu.kit.ipd.sonar.client.event.SuccessfulLogoutEvent; import edu.kit.ipd.sonar.client.event.UserlistArrivedEvent; import edu.kit.ipd.sonar.client.event.UserlistRequestEvent; import edu.kit.ipd.sonar.client.event.UserlistRequestEventHandler; import edu.kit.ipd.sonar.server.AuthenticationResult; import edu.kit.ipd.sonar.server.Graph; import edu.kit.ipd.sonar.server.TimeBoundary; import edu.kit.ipd.sonar.server.User; import edu.kit.ipd.sonar.server.CalculationFailedException; import edu.kit.ipd.sonar.server.centralities.Centrality; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.Timer; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.user.client.rpc.AsyncCallback; import java.util.ArrayList; /** * The task of this class is to catch all events related to client-server * communication, talk to the server, and send events depending * on the answer. * * @author Kevin-Simon Kohlmeyer */ public class RPCHandler { // Checkstyle: This is no utility class /** Contains localized Strings. */ private SonarMessages messages = (SonarMessages) GWT.create(SonarMessages.class); /** The service through which we can communicate with the server. */ private final RPCServiceAsync service; /** The HandlerManager through which our events are sent. */ private final HandlerManager handlerManager; /** The last retrieved hash of the database state. */ private int lastHash = 0; /** The time in milli-secounds between checks for database changes. */ private static final int UPDATE_INTERVAL = 240 * 1000; /** * Create an RPCHandler object. * * The rpc handler registers itself with the event manager. * * @param handlerManager The handlerManager used to communicate with other * parts of the client. * @param service The RPCServiceAsync used to communicate with the * server. */ public RPCHandler(final HandlerManager handlerManager, final RPCServiceAsync service) { this.handlerManager = handlerManager; this.service = service; setUpHandlers(); } /** Sets up the event Handlers. */ private void setUpHandlers() { this.handlerManager.addHandler(AttemptAuthenticationEvent.TYPE, new AttemptAuthenticationEventHandler() { public void onAttemptAuthentication( final AttemptAuthenticationEvent e) { if (e.isAdmin()) { service.authenticateAdmin(e.getPassword(), authenticateAdminCallback); } else { service.authenticateUser(e.getUsername(), e.getPassword(), authenticateUserCallback); } } }); this.handlerManager.addHandler(AttemptLogoutEvent.TYPE, new AttemptLogoutEventHandler() { public void onAttemptLogout( final AttemptLogoutEvent e) { service.logout(logoutCallback); } }); this.handlerManager.addHandler(AvailableCentralitiesRequestEvent.TYPE, new AvailableCentralitiesRequestEventHandler() { public void onAvailableCentralitiesRequest( final AvailableCentralitiesRequestEvent e) { service.getAvailableCentralities( getAvailableCentralitiesCallback); } }); this.handlerManager.addHandler(AvailableTimeBoundaryRequestEvent.TYPE, new AvailableTimeBoundaryRequestEventHandler() { public void onAvailableTimeBoundaryRequest( final AvailableTimeBoundaryRequestEvent e) { service.getTimeBoundary(getTimeBoundaryCallback); } }); this.handlerManager.addHandler(GraphRequestEvent.TYPE, new GraphRequestEventHandler() { public void onGraphRequest(final GraphRequestEvent e) { GraphSpecification spec = e.getGraphSpecification(); ArrayList<Centrality> cents = new ArrayList<Centrality>( spec.getCentralities()); if (spec.getRequestType() == GraphType.GLOBAL_GRAPH) { service.getGlobalGraph(spec.getTimeBoundary(), cents, spec.getCutoff(), new GlobalGraphCallback(spec)); } else if (spec.getRequestType() == GraphType.PEER_GRAPH) { service.getPeerGraph(spec.getUser(), spec.getTimeBoundary(), cents, spec.getCutoff(), new PeerGraphCallback(spec)); } else { throw new IllegalArgumentException( "Neither peer nor global graph"); } } }); this.handlerManager.addHandler(UserlistRequestEvent.TYPE, new UserlistRequestEventHandler() { public void onUserlistRequest( final UserlistRequestEvent e) { service.getUserList(getUserListCallback); } }); /* Regularily check for updates. */ Timer t = new Timer() { @Override public void run() { service.getStateHash(getStateHashCallback); } }; t.scheduleRepeating(UPDATE_INTERVAL); } /** Callback for authenticateAdmin calls. */ private AsyncCallback<Boolean> authenticateAdminCallback = new AsyncCallback<Boolean>() { public void onSuccess(final Boolean successful) { GWT.log("RPCHandler: authenticateAdmin called back, got " + successful, null); if (successful) { fireEvent(new SuccessfulAuthenticationEvent(null, true)); } else { fireEvent(new FailedAuthenticationEvent()); } } public void onFailure(final Throwable caught) { GWT.log("RPCHandler: authenticateAdmin call failed", caught); fireEvent(new ErrorOccuredEvent( messages.rpcAuthenticationFailed())); } }; /** Callback for authenticateUser calls. */ private AsyncCallback<AuthenticationResult> authenticateUserCallback = new AsyncCallback<AuthenticationResult>() { public void onSuccess(final AuthenticationResult result) { GWT.log("RPCHandler: authenticateUser called back, got " + result.toString(), null); if (result.isSuccessful()) { fireEvent(new SuccessfulAuthenticationEvent( result.getUser(), false)); } else { fireEvent(new FailedAuthenticationEvent()); } } public void onFailure(final Throwable caught) { GWT.log("RPCHandler: authenticateUser call failed", caught); fireEvent(new ErrorOccuredEvent( messages.rpcAuthenticationFailed())); } }; /** Callback for getAvailableCentralities calls. */ private AsyncCallback<ArrayList<Centrality>> getAvailableCentralitiesCallback = new AsyncCallback<ArrayList<Centrality>>() { public void onSuccess(final ArrayList<Centrality> centralities) { GWT.log("RPCHandler: getAvailableCentralities called back, got " + centralities.toString(), null); fireEvent(new AvailableCentralitiesArrivedEvent(centralities)); } public void onFailure(final Throwable caught) { GWT.log("RPCHandler: getAvailableCentralities call failed" , caught); fireEvent(new ErrorOccuredEvent( messages.rpcGetCentralitiesFailed())); } }; /** Callback for getTimeBoundary calls. */ private AsyncCallback<TimeBoundary> getTimeBoundaryCallback = new AsyncCallback<TimeBoundary>() { public void onSuccess(final TimeBoundary tb) { GWT.log("RPCHandler: getTimeBoundard called back, got " + tb.toString(), null); fireEvent(new AvailableTimeBoundaryArrivedEvent(tb)); } public void onFailure(final Throwable caught) { GWT.log("RPCHandler: getTimeBoundary call failed", caught); fireEvent(new ErrorOccuredEvent( messages.rpcGetTimeBoundaryFailed())); } }; /** Callback for getUserList calls. */ private AsyncCallback<ArrayList<User>> getUserListCallback = new AsyncCallback<ArrayList<User>>() { public void onSuccess(final ArrayList<User> users) { GWT.log("RPCHandler: getUserList called back, got " + users.toString(), null); fireEvent(new UserlistArrivedEvent(users)); } public void onFailure(final Throwable caught) { GWT.log("RPCHandler: getUserList call failed", caught); fireEvent(new ErrorOccuredEvent( messages.rpcGetUserListFailed())); } }; /** Callback for getGlobalGraph calls. */ private class GlobalGraphCallback implements AsyncCallback<Graph> { /** The spec for the graph we're waiting for. */ private GraphSpecification spec; /** * Constructor. * * @param spec The spec for the graph to come. */ public GlobalGraphCallback(final GraphSpecification spec) { this.spec = spec; } /** * Implements func in AsyncCallback. * * @param g The requested Graph. */ public void onSuccess(final Graph g) { fireEvent(new GraphArrivedEvent(g, spec)); } /** * Implements func in AsyncCallback. * * @param caught The throwable that occured. */ public void onFailure(final Throwable caught) { GWT.log("RPCHandler: getGlobalGraph call failed", caught); try { throw caught; } catch (CalculationFailedException e) { fireEvent(new ErrorOccuredEvent( messages.rpcGetGlobalGraphFailedWithCalcException())); } catch (Throwable e) { fireEvent(new ErrorOccuredEvent( messages.rpcGetGlobalGraphFailed())); } } } /** Callback for getPeerGraph calls. */ private class PeerGraphCallback implements AsyncCallback<Graph> { /** The spec for the graph we're waiting for. */ private GraphSpecification spec; /** * Constructor. * * @param spec The spec for the graph to come. */ public PeerGraphCallback(final GraphSpecification spec) { this.spec = spec; } /** * Implements func in AsyncCallback. * * @param g The graph. */ public void onSuccess(final Graph g) { GWT.log("RPCHandler: getPeerGraph called back, got " + g, null); fireEvent(new GraphArrivedEvent(g, spec)); } /** * Implements func in AsyncCallback. * * @param caught The throwable that occured. */ public void onFailure(final Throwable caught) { GWT.log("RPCHandler: getPeerGraph call failed", caught); try { throw caught; } catch (CalculationFailedException e) { fireEvent(new ErrorOccuredEvent( messages.rpcGetPeerGraphFailedWithCalcException())); } catch (Throwable e) { fireEvent(new ErrorOccuredEvent( messages.rpcGetPeerGraphFailed())); } } } /** Callback for getStateHash calls. */ private AsyncCallback<Integer> getStateHashCallback = new AsyncCallback<Integer>() { public void onSuccess(final Integer hash) { GWT.log("RPCHandler: getStateHash called back, got " + hash, null); if (lastHash != hash) { lastHash = hash; fireEvent(new DatabaseChangedEvent()); } } public void onFailure(final Throwable caught) { GWT.log("RPCHandler: getStateHash call failed", caught); fireEvent(new ErrorOccuredEvent(messages.rpcGetStateHashFailed())); } }; /** Callback for logout calls. */ private AsyncCallback<Void> logoutCallback = new AsyncCallback<Void>() { public void onSuccess(final Void v) { GWT.log("RPCHandler: logout called back", null); fireEvent(new SuccessfulLogoutEvent()); } public void onFailure(final Throwable caught) { GWT.log("RPCHandler: logout call failed", caught); fireEvent(new ErrorOccuredEvent(messages.rpcLogoutFailed())); } }; /** * Helper method, delegates the event to the event bus. * * @param e The event to be fired. */ private void fireEvent(final GwtEvent e) { this.handlerManager.fireEvent(e); } }
gpl-2.0
antivo/Parallel-Machine-Simulator
src/main/java/hr/fer/zemris/parallelmachinesimulator/memory/MemoryFactory.java
545
package hr.fer.zemris.parallelmachinesimulator.memory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; /** * Created by antivo */ @Component public class MemoryFactory { @Autowired private ApplicationContext applicationContext; public Memory createMemory(String location) { Memory memory = applicationContext.getBean(Memory.class); memory.setLocation(location); return memory; } }
gpl-2.0
pspala/mpeg7
MPEG7Annotation/src/org/exist/xquery/modules/mpeg7/x3d/geometries/ILSDetector.java
7823
package org.exist.xquery.modules.mpeg7.x3d.geometries; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * * @author Patti Spala <pd.spala@gmail.com> */ public class ILSDetector extends GeometryDetector { private static final Logger logger = Logger.getLogger(ILSDetector.class); public ILSDetector(Document doc) throws IOException, XPathExpressionException { super(doc); processShapes(); } @Override public void processShapes() throws IOException, XPathExpressionException { String[] coordIndexArray = null; List totalPointParts = null; ArrayList<String> resultedIFSExtractionList = new ArrayList<String>(); ArrayList<String> resultedSGDExtractionList = new ArrayList<String>(); StringBuilder IFSStringBuilder = new StringBuilder(); StringBuilder SGDStringBuilder = new StringBuilder(); XPath xPath = XPathFactory.newInstance().newXPath(); this.getDoc().getDocumentElement().normalize(); NodeList ifsSet = (NodeList) xPath.evaluate("//Shape/IndexedLineSet", this.getDoc().getDocumentElement(), XPathConstants.NODESET); for (int p = 0; p < ifsSet.getLength(); p++) { HashMap<String, String[]> coordDictParams = new HashMap<String, String[]>(); HashMap<String, String[]> pointDictParams = new HashMap<String, String[]>(); Element elem = (Element) ifsSet.item(p); // case: <IndexedFaceSet USE='SardineIndex'/> boolean isUseIFS = elem.hasAttribute("USE"); if (isUseIFS) { String def = elem.getAttribute("USE"); elem = (Element) xPath.compile("//Shape/IndexedLineSet[@DEF='" + def + "']").evaluate(this.getDoc().getDocumentElement(), XPathConstants.NODE); } String coordIndex = null; if (elem.hasAttribute("coordIndex")) { coordIndex = elem.getAttribute("coordIndex"); } Element coordinate = (Element) elem.getElementsByTagName("Coordinate").item(0); // case: // <IndexedFaceSet coordIndex='3 2 5 4 -1 12 13 14 15 -1 21 3 4 22 -1 13 26 27 14 -1 31 21 22 32 -1 26 36 37 27 -1 41 31 32 42 -1 36 46 47 37 -1'> // <Coordinate USE='WindowCoordinates'/> // </IndexedFaceSet> boolean isUseCoordinate = coordinate.hasAttribute("USE"); if (isUseCoordinate) { String defCoord = coordinate.getAttribute("USE"); //case: // <IndexedFaceSet> // <Coordinate USE='WallCoordinates'/> // </IndexedFaceSet> if (coordIndex == null) { elem = (Element) xPath.compile("//Shape/IndexedLineSet[Coordinate[@DEF='" + defCoord + "']]").evaluate(this.getDoc().getDocumentElement(), XPathConstants.NODE); coordIndex = elem.getAttribute("coordIndex"); } else { coordinate = (Element) xPath.compile("//IndexedLineSet/Coordinate[@DEF='" + defCoord + "']").evaluate(this.getDoc().getDocumentElement(), XPathConstants.NODE); } } String points = coordinate.getAttribute("point").replaceAll("\\r|\\n", " ").trim().replaceAll(" +", " ").replaceAll(",", ""); coordIndex = coordIndex.replaceAll("\\r|\\n", " ").trim().replaceAll(" +", " ").replaceAll(",", ""); Scanner sc = new Scanner(coordIndex).useDelimiter(" "); int maxCoordIndex = 0; while (sc.hasNextInt()) { int thisVal = sc.nextInt(); if (thisVal > maxCoordIndex) { maxCoordIndex = thisVal; } } totalPointParts = new ArrayList(); totalPointParts = getPointParts(points, maxCoordIndex); coordIndex = coordIndex.replaceAll(",", ""); if (coordIndex.contains("-1")) { coordIndex = coordIndex.substring(0, coordIndex.lastIndexOf("-1")); coordIndexArray = coordIndex.split(" -1 "); } else { coordIndexArray = new String[1]; coordIndexArray[0] = coordIndex; } coordDictParams.put("coordIndex", coordIndexArray); pointDictParams.put("points", (String[]) totalPointParts.toArray(new String[0])); String coordTempFile = writeParamsToFile(coordDictParams, new File("coordIndex.txt"), this.getWriter()); String pointTempFile = writeParamsToFile(pointDictParams, new File("point.txt"), this.getWriter()); String[] tempFiles = {coordTempFile, pointTempFile}; String resultedExtraction = ShapeIndexExtraction.shapeIndexEctraction(tempFiles); resultedIFSExtractionList.add(resultedExtraction); //ShapeGoogleExtraction int vocabularySize = 32; ShapeGoogleExtraction shExtraction = new ShapeGoogleExtraction(points, coordIndex, vocabularySize); resultedSGDExtractionList.add(shExtraction.getStringRepresentation()); } for (int i = 0; i < resultedIFSExtractionList.size(); i++) { IFSStringBuilder.append(resultedIFSExtractionList.get(i)); IFSStringBuilder.append("#"); } if (IFSStringBuilder.length() > 0) { this.getParamMap().put("ILSPointsExtraction", IFSStringBuilder.toString()); } for (int i = 0; i < resultedSGDExtractionList.size(); i++) { SGDStringBuilder.append(resultedSGDExtractionList.get(i)); SGDStringBuilder.append("#"); } if (SGDStringBuilder.length() > 0) { this.getParamMap().put("SGD", SGDStringBuilder.toString()); } } @Override public String writeParamsToFile(HashMap<String, String[]> dictMap, File file, BufferedWriter writer) throws IOException { // if file doesnt exists, then create it if (file.exists()) { file.delete(); } file.createNewFile(); this.setWriter(new BufferedWriter(new FileWriter(file))); Set set = dictMap.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry me = (Map.Entry) i.next(); for (String data : (String[]) me.getValue()) { this.getWriter().write(data); this.getWriter().newLine(); } } this.getWriter().close(); return file.getAbsolutePath(); } private List getPointParts(String points, int indexSize) { List pointParts = new ArrayList(); Scanner scannedPoints = new Scanner(points).useDelimiter(" "); int totalPointIndex = 3 * (indexSize + 1); int index = 0; double[] floats = new double[totalPointIndex]; while ((scannedPoints.hasNextDouble()) && (index < floats.length)) { double fl = scannedPoints.nextDouble(); floats[index] = fl; index++; } for (int i = 0; i < floats.length; i += 3) { String nextPart = String.valueOf(floats[i]) + " " + String.valueOf(floats[i + 1]) + " " + String.valueOf(floats[i + 2]); pointParts.add(nextPart); } return pointParts; } }
gpl-2.0
caipiao/Lottery
src/com/jeecms/cms/action/admin/ImageCutAct.java
5061
package com.jeecms.cms.action.admin; import java.io.File; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.jeecms.cms.entity.main.CmsSite; import com.jeecms.cms.web.CmsUtils; import com.jeecms.common.image.ImageScale; import com.jeecms.common.upload.FileRepository; import com.jeecms.core.entity.Ftp; import com.jeecms.core.manager.DbFileMng; @Controller public class ImageCutAct { private static final Logger log = LoggerFactory .getLogger(ImageCutAct.class); /** * 图片选择页面 */ public static final String IMAGE_SELECT_RESULT = "/common/image_area_select"; /** * 图片裁剪完成页面 */ public static final String IMAGE_CUTED = "/common/image_cuted"; /** * 错误信息参数 */ public static final String ERROR = "error"; @RequestMapping("/common/v_image_area_select.do") public String imageAreaSelect(String uploadBase, String imgSrcPath, Integer zoomWidth, Integer zoomHeight, Integer uploadNum, HttpServletRequest request, ModelMap model) { model.addAttribute("uploadBase", uploadBase); model.addAttribute("imgSrcPath", imgSrcPath); model.addAttribute("zoomWidth", zoomWidth); model.addAttribute("zoomHeight", zoomHeight); model.addAttribute("uploadNum", uploadNum); return IMAGE_SELECT_RESULT; } @RequestMapping("/common/o_image_cut.do") public String imageCut(String imgSrcPath, Integer imgTop, Integer imgLeft, Integer imgWidth, Integer imgHeight, Integer reMinWidth, Integer reMinHeight, Float imgScale, Integer uploadNum, HttpServletRequest request, ModelMap model) { CmsSite site = CmsUtils.getSite(request); try { if (imgWidth > 0) { if (site.getConfig().getUploadToDb()) { String dbFilePath = site.getConfig().getDbFileUri(); imgSrcPath = imgSrcPath.substring(dbFilePath.length()); File file = dbFileMng.retrieve(imgSrcPath); imageScale.resizeFix(file, file, reMinWidth, reMinHeight, getLen(imgTop, imgScale), getLen(imgLeft, imgScale), getLen(imgWidth, imgScale), getLen(imgHeight, imgScale)); dbFileMng.restore(imgSrcPath, file); } else if (site.getUploadFtp() != null) { Ftp ftp = site.getUploadFtp(); String ftpUrl = ftp.getUrl(); imgSrcPath = imgSrcPath.substring(ftpUrl.length()); String fileName=imgSrcPath.substring(imgSrcPath.lastIndexOf("/")); File file = ftp.retrieve(imgSrcPath,fileName); imageScale.resizeFix(file, file, reMinWidth, reMinHeight, getLen(imgTop, imgScale), getLen(imgLeft, imgScale), getLen(imgWidth, imgScale), getLen(imgHeight, imgScale)); ftp.restore(imgSrcPath, file); } else { String ctx = request.getContextPath(); imgSrcPath = imgSrcPath.substring(ctx.length()); File file = fileRepository.retrieve(imgSrcPath); imageScale.resizeFix(file, file, reMinWidth, reMinHeight, getLen(imgTop, imgScale), getLen(imgLeft, imgScale), getLen(imgWidth, imgScale), getLen(imgHeight, imgScale)); } } else { if (site.getConfig().getUploadToDb()) { String dbFilePath = site.getConfig().getDbFileUri(); imgSrcPath = imgSrcPath.substring(dbFilePath.length()); File file = dbFileMng.retrieve(imgSrcPath); imageScale.resizeFix(file, file, reMinWidth, reMinHeight); dbFileMng.restore(imgSrcPath, file); } else if (site.getUploadFtp() != null) { Ftp ftp = site.getUploadFtp(); String ftpUrl = ftp.getUrl(); imgSrcPath = imgSrcPath.substring(ftpUrl.length()); String fileName=imgSrcPath.substring(imgSrcPath.lastIndexOf("/")); File file = ftp.retrieve(imgSrcPath,fileName); imageScale.resizeFix(file, file, reMinWidth, reMinHeight); ftp.restore(imgSrcPath, file); } else { String ctx = request.getContextPath(); imgSrcPath = imgSrcPath.substring(ctx.length()); File file = fileRepository.retrieve(imgSrcPath); imageScale.resizeFix(file, file, reMinWidth, reMinHeight); } } model.addAttribute("uploadNum", uploadNum); } catch (Exception e) { log.error("cut image error", e); model.addAttribute(ERROR, e.getMessage()); } return IMAGE_CUTED; } private int getLen(int len, float imgScale) { return Math.round(len / imgScale); } private ImageScale imageScale; private FileRepository fileRepository; private DbFileMng dbFileMng; @Autowired public void setImageScale(ImageScale imageScale) { this.imageScale = imageScale; } @Autowired public void setFileRepository(FileRepository fileRepository) { this.fileRepository = fileRepository; } @Autowired public void setDbFileMng(DbFileMng dbFileMng) { this.dbFileMng = dbFileMng; } }
gpl-2.0
hackathon-3d/ecpi-repo
SurviveThis/src/edu/ecpi/survivethis/WoodsActivity.java
2659
package edu.ecpi.survivethis; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnAttachStateChangeListener; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; public class WoodsActivity extends Activity { private int pageID = 0; private TextView view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_woods); Button next = (Button) findViewById(R.id.btnWoodsNext); next.setOnClickListener(onClickListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.woods, menu); return true; } private OnClickListener onClickListener = new OnClickListener() { public void onClick(View v) { switch(pageID) { case 0: view = (TextView) findViewById(R.id.woods_hydrationHeader); view.setVisibility(4); view = (TextView) findViewById(R.id.woods_hydrationDetail); view.setVisibility(4); view = (TextView) findViewById(R.id.woods_foodHeader); view.setVisibility(0); view = (TextView) findViewById(R.id.woods_foodDetail); view.setVisibility(0); pageID = 1; break; case 1: view = (TextView) findViewById(R.id.woods_foodHeader); view.setVisibility(4); view = (TextView) findViewById(R.id.woods_foodDetail); view.setVisibility(4); view = (TextView) findViewById(R.id.woods_animalsHeader); view.setVisibility(0); view = (TextView) findViewById(R.id.woods_animalsDetail); view.setVisibility(0); pageID = 2; break; case 2: view = (TextView) findViewById(R.id.woods_animalsHeader); view.setVisibility(4); view = (TextView) findViewById(R.id.woods_animalsDetail); view.setVisibility(4); view = (TextView) findViewById(R.id.woods_plantsHeader); view.setVisibility(0); view = (TextView) findViewById(R.id.woods_plantsDetail); view.setVisibility(0); pageID = 3; break; case 3: view = (TextView) findViewById(R.id.woods_plantsHeader); view.setVisibility(4); view = (TextView) findViewById(R.id.woods_plantsDetail); view.setVisibility(4); view = (TextView) findViewById(R.id.woods_hydrationHeader); view.setVisibility(0); view = (TextView) findViewById(R.id.woods_hydrationDetail); view.setVisibility(0); pageID = 0; break; default: break; } } }; }
gpl-2.0
Furt/JMaNGOS
Realm/src/main/java/org/jmangos/world/entities/ItemPrototype.java
56020
/******************************************************************************* * Copyright (C) 2012 JMaNGOS <http://jmangos.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * 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.jmangos.world.entities; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import org.jmangos.commons.enums.InventoryType; import org.jmangos.commons.model.NamedObject; import org.jmangos.realm.model.base.item._Damage; import org.jmangos.realm.model.base.item._ItemStat; import org.jmangos.realm.model.base.item._Socket; /** * The Class ItemPrototype. * * @author minimajack */ @Entity @Table(name = "item_template") public class ItemPrototype extends NamedObject { /** The Constant MAX_ITEM_PROTO_STATS. */ final public static int MAX_ITEM_PROTO_STATS = 10; /** The Constant MAX_ITEM_PROTO_DAMAGES. */ final public static int MAX_ITEM_PROTO_DAMAGES = 2; /** The Constant MAX_ITEM_PROTO_SOCKETS. */ final public static int MAX_ITEM_PROTO_SOCKETS = 3; /** The Constant MAX_ITEM_PROTO_SPELLS. */ final public static int MAX_ITEM_PROTO_SPELLS = 5; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "entry", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private Integer entry; /** The Class. */ @Basic @Column(name = "class", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private int Class; /** The Sub class. */ @Basic @Column(name = "subclass", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private int SubClass; // id from // ItemSubClass.dbc /** The Unk0. */ @Basic @Column(name = "unk0", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) private int Unk0; @Basic @Column(name = "name", nullable = false, insertable = true, updatable = true, length = 100, precision = 0) private String itemName; /** The Display info id. */ @Basic @Column(name = "displayid", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int displayId; // id from // ItemDisplayInfo.dbc /** The Quality. */ @Basic @Column(name = "Quality", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private int Quality; /** The Flags. */ @Basic @Column(name = "Flags", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) private long Flags; /** The Flags2. */ @Basic @Column(name = "Flags2", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) private int Flags2; /** The Buy count. */ @Basic @Column(name = "BuyCount", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private int BuyCount; /** The Buy price. */ @Basic @Column(name = "BuyPrice", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) private int BuyPrice; /** The Sell price. */ @Basic @Column(name = "SellPrice", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) private int SellPrice; /** The inventory type. */ @Basic @Column(name = "InventoryType", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private InventoryType inventoryType; /** The Allowable class. */ @Column(name = "AllowableClass", nullable = false, insertable = true, updatable = true, length = 7, precision = 0) private int AllowableClass; /** The Allowable race. */ @Basic @Column(name = "AllowableRace", nullable = false, insertable = true, updatable = true, length = 7, precision = 0) private int AllowableRace; /** The Item level. */ @Basic @Column(name = "ItemLevel", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int ItemLevel; /** The Required level. */ @Basic @Column(name = "RequiredLevel", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte RequiredLevel; /** The Required skill. */ @Basic @Column(name = "RequiredSkill", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int RequiredSkill; // id from // SkillLine.dbc /** The Required skill rank. */ @Basic @Column(name = "RequiredSkillRank", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int RequiredSkillRank; /** The Required spell. */ @Basic @Column(name = "requiredspell", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int RequiredSpell; // id from // Spell.dbc /** The Required honor rank. */ @Basic @Column(name = "requiredhonorrank", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int RequiredHonorRank; /** The Required city rank. */ @Basic @Column(name = "RequiredCityRank", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int RequiredCityRank; /** The Required reputation faction. */ @Basic @Column(name = "RequiredReputationFaction", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int RequiredReputationFaction; // id from // Faction.dbc /** The Required reputation rank. */ @Basic @Column(name = "RequiredReputationRank", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int RequiredReputationRank; /** The Max count. */ @Basic @Column(name = "maxcount", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int MaxCount; // <=0: no // limit /** The Stackable. */ @Basic @Column(name = "stackable", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int Stackable; // 0: not // allowed, // -1: put // in // player // coin // info // tab // and don't limit stacking (so 1 slot) /** The Container slots. */ @Basic @Column(name = "ContainerSlots", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte ContainerSlots; /** The Stats count. */ @Basic @Column(name = "StatsCount", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private int statsCount; // TODO: item bytes implement // @Basic // @Column(name = "stat_type1", nullable = false, insertable = true, updatable = true, length = // 3, precision = 0) /** item stats. */ @Transient private _ItemStat[] itemStat; /** The Scaling stat distribution. */ @Basic @Column(name = "scalingStatDistribution", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int ScalingStatDistribution; // id from // ScalingStatDistribution.dbc /** The Scaling stat value. */ @Basic @Column(name = "scalingStatValue", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) private int ScalingStatValue; // mask // for // selecting // column // in // ScalingStatValues.dbc /** damages. */ /* * @Columns(columns = { * * @Column(name = "dmg_min1", nullable = false, insertable = true, updatable = true, length = * 12, precision = 0), * * @Column(name = "dmg_max1", nullable = false, insertable = true, updatable = true, length = * 12, precision = 0), * * @Column(name = "dmg_type1", nullable = false, insertable = true, updatable = true, length = * 3, precision = 0), * * @Column(name = "dmg_min2", nullable = false, insertable = true, updatable = true, length = * 12, precision = 0), * * @Column(name = "dmg_max2", nullable = false, insertable = true, updatable = true, length = * 12, precision = 0), * * @Column(name = "dmg_type2", nullable = false, insertable = true, updatable = true, length = * 3, precision = 0), }) */ @Transient private final _Damage[] Damage = new _Damage[MAX_ITEM_PROTO_DAMAGES]; /** The Armor. */ @Basic @Column(name = "armor", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int Armor; /** The Holy res. */ @Basic @Column(name = "holy_res", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte HolyRes; /** The Fire res. */ @Basic @Column(name = "fire_res", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte FireRes; /** The Nature res. */ @Basic @Column(name = "nature_res", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte NatureRes; /** The Frost res. */ @Basic @Column(name = "frost_res", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte FrostRes; /** The Shadow res. */ @Basic @Column(name = "shadow_res", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte ShadowRes; /** The Arcane res. */ @Basic @Column(name = "arcane_res", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte ArcaneRes; /** The Delay. */ @Basic @Column(name = "delay", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int Delay; /** The Ammo type. */ @Basic @Column(name = "ammo_type", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private int AmmoType; /** The Ranged mod range. */ @Column(name = "RangedModRange", nullable = false, insertable = true, updatable = true, length = 12, precision = 0) float RangedModRange; /* * private int[] SpellId = new int[MAX_ITEM_PROTO_SPELLS]; private byte[] SpellTrigger = new * byte[MAX_ITEM_PROTO_SPELLS]; private int[] SpellCharges = new int[MAX_ITEM_PROTO_SPELLS]; * private float[] SpellPPMRate = new float[MAX_ITEM_PROTO_SPELLS]; private int[] SpellCooldown * = new int[MAX_ITEM_PROTO_SPELLS]; private int[] SpellCategory = new * int[MAX_ITEM_PROTO_SPELLS]; private int[] SpellCategoryCooldown = new * int[MAX_ITEM_PROTO_SPELLS]; */ /** The Bonding. */ @Basic @Column(name = "bonding", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte Bonding; /** The Description. */ @Basic @Column(name = "description", nullable = false, insertable = true, updatable = true, length = 255, precision = 0) private String Description; /** The Page text. */ @Basic @Column(name = "PageText", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int PageText; /** The Language id. */ @Basic @Column(name = "LanguageID", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte LanguageID; /** The Page material. */ @Basic @Column(name = "PageMaterial", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte PageMaterial; /** The Start quest. */ @Basic @Column(name = "startquest", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int StartQuest; // id from // QuestCache.wdb /** The Lock id. */ @Basic @Column(name = "lockid", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int LockID; /** The Material. */ @Basic @Column(name = "Material", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private int Material; // id from // Material.dbc /** The Sheath. */ @Basic @Column(name = "sheath", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte Sheath; /** The Random property. */ @Basic @Column(name = "RandomProperty", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int RandomProperty; // id from // ItemRandomProperties.dbc /** The Random suffix. */ @Basic @Column(name = "RandomSuffix", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int RandomSuffix; // id from // ItemRandomSuffix.dbc /** The Block. */ @Basic @Column(name = "block", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int Block; /** The Item set. */ @Basic @Column(name = "itemset", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int ItemSet; // id from // ItemSet.dbc /** The Max durability. */ @Basic @Column(name = "MaxDurability", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int MaxDurability; /** The Area. */ @Basic @Column(name = "area", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) private int Area; // id from // AreaTable.dbc /** The Map. */ @Basic @Column(name = "Map", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int Map; // id from // Map.dbc /** The Bag family. */ @Basic @Column(name = "BagFamily", nullable = false, insertable = true, updatable = true, length = 7, precision = 0) private int BagFamily; // bit // mask (1 // << id // from // ItemBagFamily.dbc) /** The Totem category. */ @Basic @Column(name = "TotemCategory", nullable = false, insertable = true, updatable = true, length = 7, precision = 0) private int TotemCategory; // id from // TotemCategory.dbc /** socket data. */ // TODO: implement socket // @Column(name = "socketColor_1", nullable = false, insertable = true, updatable = true, length // = 3, precision = 0) // @Column(name = "socketContent_1", nullable = false, insertable = true, updatable = true, // length = 7, precision = 0) @Transient private _Socket[] Socket; /** The socket bonus. */ @Basic @Column(name = "socketBonus", nullable = false, insertable = true, updatable = true, length = 7, precision = 0) private int socketBonus; // id from // SpellItemEnchantment.dbc /** The Gem properties. */ @Basic @Column(name = "GemProperties", nullable = false, insertable = true, updatable = true, length = 7, precision = 0) private int GemProperties; // id from // GemProperties.dbc /** The Required disenchant skill. */ @Basic @Column(name = "RequiredDisenchantSkill", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int RequiredDisenchantSkill; /** The Armor damage modifier. */ @Basic @Column(name = "ArmorDamageModifier", nullable = false, insertable = true, updatable = true, length = 12, precision = 0) private float ArmorDamageModifier; /** The Duration. */ @Basic @Column(name = "Duration", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) private int Duration; // negative // = // realtime, // positive // = // ingame // time /** The Item limit category. */ @Basic @Column(name = "ItemLimitCategory", nullable = false, insertable = true, updatable = true, length = 5, precision = 0) private int ItemLimitCategory; // id from // ItemLimitCategory.dbc /** The Holiday id. */ @Basic @Column(name = "HolidayId", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) private int HolidayId; // id from // Holidays.dbc /** The Script name. */ @Basic @Column(name = "ScriptName", nullable = false, insertable = true, updatable = true, length = 64, precision = 0) private String ScriptName; /** The Disenchant id. */ @Basic @Column(name = "DisenchantID", nullable = false, insertable = true, updatable = true, length = 8, precision = 0) int DisenchantID; /** The Food type. */ @Basic @Column(name = "FoodType", nullable = false, insertable = true, updatable = true, length = 3, precision = 0) private byte FoodType; /** The Min money loot. */ @Basic @Column(name = "minMoneyLoot", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) private int MinMoneyLoot; /** The Max money loot. */ @Basic @Column(name = "maxMoneyLoot", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) private int MaxMoneyLoot; /** The Extra flags. */ @Basic @Column(name = "ExtraFlags", nullable = false, insertable = true, updatable = true, length = 0, precision = 0) private byte ExtraFlags; public ItemPrototype() { } /** * Gets the clazz. * * @return the class of Item from ItemClass.dbc */ public int getClazz() { return this.Class; } /** * Sets the clazz. * * @param clazz * set Class Item */ public void setClazz(final int clazz) { this.Class = clazz; } /** * Gets the sub class. * * @return the subClass */ public int getSubClass() { return this.SubClass; } /** * Sets the sub class. * * @param subClass * the subClass to set */ public void setSubClass(final int subClass) { this.SubClass = subClass; } /** * Gets the unk0. * * @return the unk0 */ public int getUnk0() { return this.Unk0; } /** * Sets the unk0. * * @param unk0 * the unk0 to set */ public void setUnk0(final int unk0) { this.Unk0 = unk0; } /** * Gets the display info id. * * @return the displayInfoID */ public int getDisplayInfoID() { return this.displayId; } /** * Sets the display info id. * * @param displayInfoID * the displayInfoID to set */ public void setDisplayInfoID(final int displayInfoID) { this.displayId = displayInfoID; } /** * Gets the quality. * * @return the quality */ public int getQuality() { return this.Quality; } /** * Sets the quality. * * @param quality * the quality to set */ public void setQuality(final int quality) { this.Quality = quality; } /** * Gets the flags. * * @return the flags */ public long getFlags() { return this.Flags; } /** * Sets the flags. * * @param flags * the flags to set */ public void setFlags(final int flags) { this.Flags = flags; } /** * Gets the buy count. * * @return the buyCount */ public int getBuyCount() { return this.BuyCount; } /** * Sets the buy count. * * @param buyCount * the buyCount to set */ public void setBuyCount(final int buyCount) { this.BuyCount = buyCount; } /** * Gets the buy price. * * @return the buyPrice */ public int getBuyPrice() { return this.BuyPrice; } /** * Sets the buy price. * * @param buyPrice * the buyPrice to set */ public void setBuyPrice(final int buyPrice) { this.BuyPrice = buyPrice; } /** * Gets the sell price. * * @return the sellPrice */ public int getSellPrice() { return this.SellPrice; } /** * Sets the sell price. * * @param sellPrice * the sellPrice to set */ public void setSellPrice(final int sellPrice) { this.SellPrice = sellPrice; } /** * Gets the inventory type. * * @return the inventoryType */ public InventoryType getInventoryType() { return this.inventoryType; } /** * Sets the inventory type. * * @param inventoryType * the inventoryType to set */ public void setInventoryType(final InventoryType inventoryType) { this.inventoryType = inventoryType; } /** * Gets the allowable class. * * @return the allowableClass */ public int getAllowableClass() { return this.AllowableClass; } /** * Sets the allowable class. * * @param allowableClass * the allowableClass to set */ public void setAllowableClass(final int allowableClass) { this.AllowableClass = allowableClass; } /** * Gets the allowable race. * * @return the allowableRace */ public int getAllowableRace() { return this.AllowableRace; } /** * Sets the allowable race. * * @param allowableRace * the allowableRace to set */ public void setAllowableRace(final int allowableRace) { this.AllowableRace = allowableRace; } /** * Gets the item level. * * @return the itemLevel */ public int getItemLevel() { return this.ItemLevel; } /** * Sets the item level. * * @param itemLevel * the itemLevel to set */ public void setItemLevel(final int itemLevel) { this.ItemLevel = itemLevel; } /** * Gets the required level. * * @return the requiredLevel */ public int getRequiredLevel() { return this.RequiredLevel; } /** * Sets the required level. * * @param requiredLevel * the requiredLevel to set */ public void setRequiredLevel(final byte requiredLevel) { this.RequiredLevel = requiredLevel; } /** * Gets the required skill. * * @return the requiredSkill */ public int getRequiredSkill() { return this.RequiredSkill; } /** * Sets the required skill. * * @param requiredSkill * the requiredSkill to set */ public void setRequiredSkill(final int requiredSkill) { this.RequiredSkill = requiredSkill; } /** * Gets the required skill rank. * * @return the requiredSkillRank */ public int getRequiredSkillRank() { return this.RequiredSkillRank; } /** * Sets the required skill rank. * * @param requiredSkillRank * the requiredSkillRank to set */ public void setRequiredSkillRank(final int requiredSkillRank) { this.RequiredSkillRank = requiredSkillRank; } /** * Gets the required spell. * * @return the requiredSpell */ public int getRequiredSpell() { return this.RequiredSpell; } /** * Sets the required spell. * * @param requiredSpell * the requiredSpell to set */ public void setRequiredSpell(final int requiredSpell) { this.RequiredSpell = requiredSpell; } /** * Gets the required honor rank. * * @return the requiredHonorRank */ public int getRequiredHonorRank() { return this.RequiredHonorRank; } /** * Sets the required honor rank. * * @param requiredHonorRank * the requiredHonorRank to set */ public void setRequiredHonorRank(final int requiredHonorRank) { this.RequiredHonorRank = requiredHonorRank; } /** * Gets the required city rank. * * @return the requiredCityRank */ public int getRequiredCityRank() { return this.RequiredCityRank; } /** * Sets the required city rank. * * @param requiredCityRank * the requiredCityRank to set */ public void setRequiredCityRank(final int requiredCityRank) { this.RequiredCityRank = requiredCityRank; } /** * Gets the required reputation faction. * * @return the requiredReputationFaction */ public int getRequiredReputationFaction() { return this.RequiredReputationFaction; } /** * Sets the required reputation faction. * * @param requiredReputationFaction * the requiredReputationFaction to set */ public void setRequiredReputationFaction(final int requiredReputationFaction) { this.RequiredReputationFaction = requiredReputationFaction; } /** * Gets the required reputation rank. * * @return the requiredReputationRank */ public int getRequiredReputationRank() { return this.RequiredReputationRank; } /** * Sets the required reputation rank. * * @param requiredReputationRank * the requiredReputationRank to set */ public void setRequiredReputationRank(final int requiredReputationRank) { this.RequiredReputationRank = requiredReputationRank; } /** * Gets the max count. * * @return the maxCount */ public int getMaxCount() { return this.MaxCount; } /** * Sets the max count. * * @param maxCount * the maxCount to set */ public void setMaxCount(final int maxCount) { this.MaxCount = maxCount; } /** * Gets the stackable. * * @return the stackable */ public int getStackable() { return this.Stackable; } /** * Sets the stackable. * * @param stackable * the stackable to set */ public void setStackable(final int stackable) { this.Stackable = stackable; } /** * Gets the container slots. * * @return the containerSlots */ public int getContainerSlots() { return this.ContainerSlots; } /** * Sets the container slots. * * @param containerSlots * the containerSlots to set */ public void setContainerSlots(final byte containerSlots) { this.ContainerSlots = containerSlots; } /** * Gets the stats count. * * @return the statsCount */ public int getStatsCount() { return this.statsCount; } /** * Sets the stats count. * * @param statsCount * the statsCount to set */ public void setStatsCount(final int statsCount) { this.statsCount = statsCount; } /** * Gets the item stat. * * @param i * the i * @return the _ItemStat */ public _ItemStat getItemStat(final int i) { return this.itemStat[i]; } /** * Sets the item stat. * * @param is * the new item stat */ public void setItemStat(final _ItemStat[] is) { this.itemStat = is; } /** * Gets the scaling stat distribution. * * @return the scalingStatDistribution */ public int getScalingStatDistribution() { return this.ScalingStatDistribution; } /** * Sets the scaling stat distribution. * * @param scalingStatDistribution * the scalingStatDistribution to set */ public void setScalingStatDistribution(final int scalingStatDistribution) { this.ScalingStatDistribution = scalingStatDistribution; } /** * Gets the scaling stat value. * * @return the scalingStatValue */ public int getScalingStatValue() { return this.ScalingStatValue; } /** * Sets the scaling stat value. * * @param scalingStatValue * the scalingStatValue to set */ public void setScalingStatValue(final int scalingStatValue) { this.ScalingStatValue = scalingStatValue; } /** * Gets the damage. * * @param i * the i * @return the damage */ public _Damage getDamage(final int i) { return this.Damage[i]; } /** * Sets the damage. * * @param _damage * the _damage * @param pos * the pos */ public void setDamage(final _Damage _damage, final byte pos) { this.Damage[pos] = _damage; } /** * Sets the damage. * * @param damageMin * the damage min * @param damageMax * the damage max * @param damageType * the damage type * @param pos * the pos */ public void setDamage(final float damageMin, final float damageMax, final byte damageType, final byte pos) { this.Damage[pos] = new _Damage(damageMin, damageMax, damageType); } /** * Gets the armor. * * @return the armor */ public int getArmor() { return this.Armor; } /** * Sets the armor. * * @param armor * the armor to set */ public void setArmor(final int armor) { this.Armor = armor; } /** * Gets the holy res. * * @return the holy Resistance */ public byte getHolyRes() { return this.HolyRes; } /** * Sets the holy res. * * @param holyRes * the holyRes to set */ public void setHolyRes(final byte holyRes) { this.HolyRes = holyRes; } /** * Gets the fire res. * * @return the fire Resistance */ public byte getFireRes() { return this.FireRes; } /** * Sets the fire res. * * @param fireRes * the fireRes to set */ public void setFireRes(final byte fireRes) { this.FireRes = fireRes; } /** * Gets the nature res. * * @return the nature Resistance */ public byte getNatureRes() { return this.NatureRes; } /** * Sets the nature res. * * @param natureRes * the natureRes to set */ public void setNatureRes(final byte natureRes) { this.NatureRes = natureRes; } /** * Gets the frost res. * * @return the frostRes */ public byte getFrostRes() { return this.FrostRes; } /** * Sets the frost res. * * @param frostRes * the frostRes to set */ public void setFrostRes(final byte frostRes) { this.FrostRes = frostRes; } /** * Gets the shadow res. * * @return the shadowRes */ public byte getShadowRes() { return this.ShadowRes; } /** * Sets the shadow res. * * @param shadowRes * the shadowRes to set */ public void setShadowRes(final byte shadowRes) { this.ShadowRes = shadowRes; } /** * Gets the arcane res. * * @return the arcaneRes */ public byte getArcaneRes() { return this.ArcaneRes; } /** * Sets the arcane res. * * @param arcaneRes * the arcaneRes to set */ public void setArcaneRes(final byte arcaneRes) { this.ArcaneRes = arcaneRes; } /** * Gets the delay. * * @return the delay */ public int getDelay() { return this.Delay; } /** * Sets the delay. * * @param delay * the delay to set */ public void setDelay(final int delay) { this.Delay = delay; } /** * Gets the ammo type. * * @return the ammoType */ public int getAmmoType() { return this.AmmoType; } /** * Sets the ammo type. * * @param ammoType * the ammoType to set */ public void setAmmoType(final int ammoType) { this.AmmoType = ammoType; } /** * Gets the ranged mod range. * * @return the rangedModRange */ public float getRangedModRange() { return this.RangedModRange; } /** * Sets the ranged mod range. * * @param rangedModRange * the rangedModRange to set */ public void setRangedModRange(final float rangedModRange) { this.RangedModRange = rangedModRange; } /** * Gets the bonding. * * @return the bonding */ /* * public void setSpells(int _SpellId, byte _SpellTrigger, int _SpellCharges, float * _SpellPPMRate, int _SpellCooldown, int _SpellCategory, int _SpellCategoryCooldown, byte pos) * { SpellId[pos] = _SpellId; SpellTrigger[pos] = _SpellTrigger; SpellCharges[pos] = * _SpellCharges; SpellPPMRate[pos] = _SpellPPMRate; SpellCooldown[pos] = _SpellCooldown; * SpellCategory[pos] = _SpellCategory; SpellCategoryCooldown[pos] = _SpellCategoryCooldown; } */ /** * @return the bonding */ public int getBonding() { return this.Bonding; } /** * Sets the bonding. * * @param bonding * the bonding to set */ public void setBonding(final byte bonding) { this.Bonding = bonding; } /** * Gets the description. * * @return the description */ public String getDescription() { return this.Description; } /** * Sets the description. * * @param description * the description to set */ public void setDescription(final String description) { this.Description = description; } /** * Gets the page text. * * @return the pageText */ public int getPageText() { return this.PageText; } /** * Sets the page text. * * @param pageText * the pageText to set */ public void setPageText(final int pageText) { this.PageText = pageText; } /** * Gets the language id. * * @return the languageID */ public byte getLanguageID() { return this.LanguageID; } /** * Sets the language id. * * @param languageID * the languageID to set */ public void setLanguageID(final byte languageID) { this.LanguageID = languageID; } /** * Gets the page material. * * @return the pageMaterial */ public byte getPageMaterial() { return this.PageMaterial; } /** * Sets the page material. * * @param pageMaterial * the pageMaterial to set */ public void setPageMaterial(final byte pageMaterial) { this.PageMaterial = pageMaterial; } /** * Gets the start quest. * * @return the startQuest */ public int getStartQuest() { return this.StartQuest; } /** * Sets the start quest. * * @param startQuest * the startQuest to set */ public void setStartQuest(final int startQuest) { this.StartQuest = startQuest; } /** * Gets the lock id. * * @return the lockID */ public int getLockID() { return this.LockID; } /** * Sets the lock id. * * @param lockID * the lockID to set */ public void setLockID(final int lockID) { this.LockID = lockID; } /** * Gets the material. * * @return the material */ public int getMaterial() { return this.Material; } /** * Sets the material. * * @param material * the material to set */ public void setMaterial(final int material) { this.Material = material; } /** * Gets the sheath. * * @return the sheath */ public byte getSheath() { return this.Sheath; } /** * Sets the sheath. * * @param sheath * the sheath to set */ public void setSheath(final byte sheath) { this.Sheath = sheath; } /** * Gets the random property. * * @return the randomProperty */ public int getRandomProperty() { return this.RandomProperty; } /** * Sets the random property. * * @param randomProperty * the randomProperty to set */ public void setRandomProperty(final int randomProperty) { this.RandomProperty = randomProperty; } /** * Gets the random suffix. * * @return the randomSuffix */ public int getRandomSuffix() { return this.RandomSuffix; } /** * Sets the random suffix. * * @param randomSuffix * the randomSuffix to set */ public void setRandomSuffix(final int randomSuffix) { this.RandomSuffix = randomSuffix; } /** * Gets the block. * * @return the block */ public int getBlock() { return this.Block; } /** * Sets the block. * * @param block * the block to set */ public void setBlock(final int block) { this.Block = block; } /** * Gets the item set. * * @return the itemSet */ public int getItemSet() { return this.ItemSet; } /** * Sets the item set. * * @param itemSet * the itemSet to set */ public void setItemSet(final int itemSet) { this.ItemSet = itemSet; } /** * Gets the max durability. * * @return the maxDurability */ public int getMaxDurability() { return this.MaxDurability; } /** * Sets the max durability. * * @param maxDurability * the maxDurability to set */ public void setMaxDurability(final int maxDurability) { this.MaxDurability = maxDurability; } /** * Gets the area. * * @return the area */ public int getArea() { return this.Area; } /** * Sets the area. * * @param area * the area to set */ public void setArea(final int area) { this.Area = area; } /** * Gets the map. * * @return the map */ public int getMap() { return this.Map; } /** * Sets the map. * * @param map * the map to set */ public void setMap(final int map) { this.Map = map; } /** * Gets the bag family. * * @return the bagFamily */ public int getBagFamily() { return this.BagFamily; } /** * Sets the bag family. * * @param bagFamily * the bagFamily to set */ public void setBagFamily(final int bagFamily) { this.BagFamily = bagFamily; } /** * Gets the totem category. * * @return the totemCategory */ public int getTotemCategory() { return this.TotemCategory; } /** * Sets the totem category. * * @param totemCategory * the totemCategory to set */ public void setTotemCategory(final int totemCategory) { this.TotemCategory = totemCategory; } /** * Gets the socket. * * @param i * the i * @return the socket */ public _Socket getSocket(final int i) { // TODO implement socket return new _Socket((byte) 0, 0); } /** * Sets the socket. * * @param ob * the new socket */ public void setSocket(final _Socket[] ob) { this.Socket = ob; } /** * Gets the socket bonus. * * @return the socketBonus */ public int getSocketBonus() { return this.socketBonus; } /** * Sets the socket bonus. * * @param socketBonus * the socketBonus to set */ public void setSocketBonus(final int socketBonus) { this.socketBonus = socketBonus; } /** * Gets the gem properties. * * @return the gemProperties */ public int getGemProperties() { return this.GemProperties; } /** * Sets the gem properties. * * @param gemProperties * the gemProperties to set */ public void setGemProperties(final int gemProperties) { this.GemProperties = gemProperties; } /** * Gets the required disenchant skill. * * @return the requiredDisenchantSkill */ public int getRequiredDisenchantSkill() { return this.RequiredDisenchantSkill; } /** * Sets the required disenchant skill. * * @param requiredDisenchantSkill * the requiredDisenchantSkill to set */ public void setRequiredDisenchantSkill(final int requiredDisenchantSkill) { this.RequiredDisenchantSkill = requiredDisenchantSkill; } /** * Gets the armor damage modifier. * * @return the armorDamageModifier */ public float getArmorDamageModifier() { return this.ArmorDamageModifier; } /** * Sets the armor damage modifier. * * @param armorDamageModifier * the armorDamageModifier to set */ public void setArmorDamageModifier(final float armorDamageModifier) { this.ArmorDamageModifier = armorDamageModifier; } /** * Gets the duration. * * @return the duration */ public int getDuration() { return this.Duration; } /** * Sets the duration. * * @param duration * the duration to set */ public void setDuration(final int duration) { this.Duration = duration; } /** * Gets the item limit category. * * @return the itemLimitCategory */ public int getItemLimitCategory() { return this.ItemLimitCategory; } /** * Sets the item limit category. * * @param itemLimitCategory * the itemLimitCategory to set */ public void setItemLimitCategory(final int itemLimitCategory) { this.ItemLimitCategory = itemLimitCategory; } /** * Gets the holiday id. * * @return the holidayId */ public int getHolidayId() { return this.HolidayId; } /** * Sets the holiday id. * * @param holidayId * the holidayId to set */ public void setHolidayId(final int holidayId) { this.HolidayId = holidayId; } /** * Gets the script id. * * @return the scriptId */ public String getScriptId() { return this.ScriptName; } /** * Sets the script id. * * @param scriptName * the scriptId to set */ public void setScriptId(final String scriptName) { this.ScriptName = scriptName; } /** * Gets the disenchant id. * * @return the disenchantID */ public int getDisenchantID() { return this.DisenchantID; } /** * Sets the disenchant id. * * @param disenchantID * the disenchantID to set */ public void setDisenchantID(final int disenchantID) { this.DisenchantID = disenchantID; } /** * Gets the food type. * * @return the foodType */ public byte getFoodType() { return this.FoodType; } /** * Sets the food type. * * @param foodType * the foodType to set */ public void setFoodType(final byte foodType) { this.FoodType = foodType; } /** * Gets the min money loot. * * @return the minMoneyLoot */ public int getMinMoneyLoot() { return this.MinMoneyLoot; } /** * Sets the min money loot. * * @param minMoneyLoot * the minMoneyLoot to set */ public void setMinMoneyLoot(final int minMoneyLoot) { this.MinMoneyLoot = minMoneyLoot; } /** * Gets the max money loot. * * @return the maxMoneyLoot */ public int getMaxMoneyLoot() { return this.MaxMoneyLoot; } /** * Sets the max money loot. * * @param maxMoneyLoot * the maxMoneyLoot to set */ public void setMaxMoneyLoot(final int maxMoneyLoot) { this.MaxMoneyLoot = maxMoneyLoot; } /** * Gets the extra flags. * * @return the extraFlags */ public byte getExtraFlags() { return this.ExtraFlags; } /** * Sets the extra flags. * * @param extraFlags * the extraFlags to set */ public void setExtraFlags(final byte extraFlags) { this.ExtraFlags = extraFlags; } /** * Gets the flags2. * * @return the flags2 */ public int getFlags2() { return this.Flags2; } /** * Sets the flags2. * * @param flags2 * the new flags2 */ public void setFlags2(final int flags2) { this.Flags2 = flags2; } public Integer getEntry() { return this.entry; } public void setEntry(final Integer entry) { this.entry = entry; } public String getItemName() { return this.itemName; } public void setItemName(final String itemName) { this.itemName = itemName; } }
gpl-2.0
HoratiusTang/EsperDist
EsperDist2/core/dist/esper/event/EventRegistry.java
853
package dist.esper.event; import java.io.Serializable; import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; public class EventRegistry implements Serializable{ private static final long serialVersionUID = 6685488304512558784L; Map<String,Event> eventMap=new ConcurrentSkipListMap<String,Event>(); public void registEvent(Event event){ //System.out.format("** regist Event: %s\n", event.toString()); eventMap.put(event.getName(),event); } public Event resolveEvent(String eventTypeName){ Event event=eventMap.get(eventTypeName); return event; } public Collection<Event> getRegistedEvents(){ return eventMap.values(); } public Map<String, Event> getEventMap() { return eventMap; } public void setEventMap(Map<String, Event> eventMap) { this.eventMap = eventMap; } }
gpl-2.0
kompics/kompics-scala
docs/src/main/java/jexamples/virtualnetworking/pingpongselectors/Ping.java
187
package jexamples.virtualnetworking.pingpongselectors; import se.sics.kompics.KompicsEvent; public class Ping implements KompicsEvent { public static final Ping EVENT = new Ping(); }
gpl-2.0
supermerill/DistributedFs
src/remi/distributedFS/gui/install/PanelCreateNewCluster.java
3257
package remi.distributedFS.gui.install; import javafx.geometry.Insets; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; /** * id du cluster (generateur aleat) * passcode du cluster * protection aes? * * bouton next -> create data pour creation + ask cluster parameters * * @author centai * */ public class PanelCreateNewCluster extends InstallPanel { Label lblClusterId = new Label(); Label lblClusterPwd = new Label(); TextField txtClusterId = new TextField(); TextField txtClusterPwd = new TextField(); Button btNext = new Button(); public PanelCreateNewCluster() { super(new GridPane()); GridPane grid = (GridPane) rootProperty().get(); lblClusterId.setText("Cluster name"); lblClusterPwd.setText("Cluster password"); txtClusterId.setTooltip(new Tooltip("Your cluster name, It's what it's used to identify this new drive")); txtClusterPwd.setTooltip(new Tooltip("The passcode that is used to see who is authorized to connect.")); txtClusterId.setText("My 1st cluster drive"); txtClusterPwd.setText("nøtQWERTYplz"); btNext.setText("Next"); btNext.setTooltip(new Tooltip("Ask peer paremeters")); btNext.setOnAction((ActionEvent)->{ //check data System.out.println(txtClusterId.getText().length()); if(txtClusterId.getText().length()<6 || txtClusterId.getText().length()>32) { Alert alert = new Alert(Alert.AlertType.WARNING);alert.setTitle("Error");alert.setHeaderText("Error:"); alert.setContentText("you must have a cluster name with at least 6 characaters and maximum 32"); alert.showAndWait(); return; } if(txtClusterPwd.getText().length()<6 || txtClusterPwd.getText().length()>32) { Alert alert = new Alert(Alert.AlertType.WARNING);alert.setTitle("Error");alert.setHeaderText("Error:"); alert.setContentText("you must have a cluster password with at least 6 characaters and maximum 32"); alert.showAndWait(); return; } manager.goToPanel(new PanelParameterPeer()); }); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(3, 10, 2, 10)); // Setting columns size ColumnConstraints column = new ColumnConstraints(); grid.getColumnConstraints().add(column); column = new ColumnConstraints(); column.setFillWidth(true); column.setHgrow(Priority.ALWAYS); grid.getColumnConstraints().add(column); grid.setMaxSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE); grid.add(lblClusterId, 0, 0, 1, 1); grid.add(txtClusterId, 1, 0, 1, 1); grid.add(lblClusterPwd, 0, 1, 1, 1); grid.add(txtClusterPwd, 1, 1, 1, 1); grid.add(btNext, 2, 2, 1, 1); } @Override public void construct() { } @Override public void destroy() { System.out.println("destroy"); manager.savedData.put("CreateNewKey", true); manager.savedData.put("CreateEmptyDrive", true); manager.savedData.put("ClusterId", txtClusterId.getText()); manager.savedData.put("ClusterPwd", txtClusterPwd.getText()); } }
gpl-2.0
jedwards1211/breakout
andork-plot/src/com/andork/plot/AxisLinkButton.java
2142
/******************************************************************************* * Breakout Cave Survey Visualizer * * Copyright (C) 2014 James Edwards * * jedwards8 at fastmail dot fm * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *******************************************************************************/ package com.andork.plot; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.ImageIcon; import javax.swing.JToggleButton; @SuppressWarnings("serial") public class AxisLinkButton extends JToggleButton { /** * */ private static final long serialVersionUID = 8709240190885186201L; PlotAxisController[] axisControllers; PlotAxis[] axes; public AxisLinkButton(PlotAxisController... axisControllers) { this.axisControllers = axisControllers; axes = new PlotAxis[axisControllers.length]; for (int i = 0; i < axisControllers.length; i++) { axes[i] = axisControllers[i].getView(); } setIcon(new ImageIcon(getClass().getResource("unlink.png"))); setSelectedIcon(new ImageIcon(getClass().getResource("link.png"))); addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (isSelected()) { PlotAxis.equalizeScale(axes); } for (PlotAxisController axisController : AxisLinkButton.this.axisControllers) { axisController.setEnableZoom(!isSelected()); } } }); } }
gpl-2.0
ttwd80archive/hemlock
src/main/java/com/twistlet/hemlock/security/service/SecurityContextService.java
426
package com.twistlet.hemlock.security.service; import java.util.List; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; public interface SecurityContextService { SecurityContext getContext(); Authentication getAuthentication(); List<GrantedAuthority> getAuthorities(); }
gpl-2.0
ZhangBohan/jiajiaohello
src/main/java/com/jiajiaohello/core/account/service/AccountService.java
229
package com.jiajiaohello.core.account.service; import com.jiajiaohello.core.account.model.Account; /** * User: bohan * Date: 11/14/14 * Time: 6:25 PM */ public interface AccountService { Account get(String username); }
gpl-2.0
delta534/Chisel
src/main/java/info/jbcs/minecraft/chisel/handlers/TinyChiselPacketHandler.java
1341
package info.jbcs.minecraft.chisel.handlers; import cpw.mods.fml.common.network.FMLNetworkHandler; import cpw.mods.fml.common.network.ITinyPacketHandler; import cpw.mods.fml.common.network.NetworkModHandler; import info.jbcs.minecraft.chisel.Chisel; import net.minecraft.client.Minecraft; import net.minecraft.network.NetServerHandler; import net.minecraft.network.packet.NetHandler; import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.Packet131MapData; public class TinyChiselPacketHandler implements ITinyPacketHandler { // This is going to be a pain to update; @Override public void handle(NetHandler handler, Packet131MapData mapData) { if (handler instanceof NetServerHandler) ChiselEventHandler.place(handler.getPlayer(), handler.getPlayer().worldObj); } static Packet packet = null; public TinyChiselPacketHandler() { } public static void signalServer() { if (packet == null) { NetworkModHandler handler = FMLNetworkHandler.instance() .findNetworkModHandler(Chisel.instance); packet = new Packet131MapData((short) handler.getNetworkId(), (short) 0, new byte[]{1}); } Minecraft.getMinecraft().getNetHandler().addToSendQueue(packet); } }
gpl-2.0
zhangweiheu/exams-system-core
src/main/java/com/online/exams/system/core/bean/Page.java
4776
package com.online.exams.system.core.bean; import com.alibaba.fastjson.annotation.JSONField; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * 分页通用类 * 本类实现了Iterable接口,可以用foreach来遍历 * * @author * @param <T> * 分页列表项类型 */ public class Page<T> implements Iterable<T>, Serializable { public static final int MAX_PAGE_SIZE = 1000; private static final long serialVersionUID = 8102012822572335930L; protected int page = 1; protected int pageSize = 10; // protected String sort; protected int totalCount = 0; protected List<T> data; public static <V> Page<V> create() { return new Page<V>(); } public static <V> Page<V> create(int page, int pageSize) { return (new Page<V>()).setPage(page).setPageSize(pageSize); } public static <V> Page<V> create(int page, int pageSize, int totalCount) { return (new Page<V>()).setPage(page).setPageSize(pageSize). setTotalCount(totalCount); } public static <V> Page<V> create(int page, int pageSize, int totalCount, List<V> data) { return (new Page<V>()).setPage(page).setPageSize(pageSize). setTotalCount(totalCount).setData(data); } /** * 将当前分页对象转成另一个分页对象,例如把Company的Page对象转成CompanyVO的Page对象 * * @param data * @return */ public <VO> Page<VO> cast(List<VO> data) { return (new Page<VO>()).setPage(page).setPageSize(pageSize). setTotalCount(totalCount).setData(data); } /** * * eg: * * <pre> * <code> * Page&lt;Long&gt; p = findPage(1, 20); * Page&lt;Integer&gt; voPage = p.cast(); * if (p.hasData()) { * List&lt;Integer&gt; voList = new ArrayList&lt;Integer&gt;(p.size()); * for (Long item : p.getData()) { * Integer vo = convert(item); * voList.add(vo); * } * voPage.setData(voList); * //或者voPage = p.cast(voList); * } * return voPage; * </code> * </pre> * * @return */ public <VO> Page<VO> cast() { return (new Page<VO>()).setPage(page).setPageSize(pageSize). setTotalCount(totalCount); } /** * @return 返回值永远>=1 */ public int getPageSize() { return pageSize; } /** * @return 返回值永远>=0 */ @JSONField(serialize=false) public int getOffset() { return (page - 1) * pageSize; } /** * 是否有上一页 * * @return */ public boolean hasPrevious() { return page > 1; } /** * 获取总页数 * * @return */ public int getTotalPages() { return (int) Math.ceil((double) totalCount / (double) pageSize); } /** * 获取总记录数 * * @return */ public int getTotalCount() { return totalCount; } /** * 判断是否有内容 * * @return */ public boolean hasData() { return null != data && !data.isEmpty(); } @JSONField(serialize=false) public boolean isFirst() { return !hasPrevious(); } @JSONField(serialize=false) public boolean isLast() { return !hasNext(); } public boolean hasNext() { return page + 1 < getTotalPages(); } public int getPage() { return page; } public List<T> getData() { if (null == data) { return Collections.emptyList(); } return data; } public int size() { if (null == data) { return 0; } return data.size(); } public Page<T> setPage(int page) { this.page = page < 1 ? 1 : page; return this; } public Page<T> setTotalCount(int totalCount) { this.totalCount = totalCount > 0 ? totalCount : 0; return this; } public Page<T> setPageSize(int pageSize) { if (pageSize < 1) { this.pageSize = 1; } else if (pageSize > MAX_PAGE_SIZE) {// 防止拖死数据库 this.pageSize = MAX_PAGE_SIZE; } else { this.pageSize = pageSize; } return this; } public Page<T> setData(List<T> data) { this.data = data; return this; } @Override public Iterator<T> iterator() { if (null == data) { return Collections.emptyIterator(); } return data.iterator(); } }
gpl-2.0
Keripo/BulletsForever
src/com/bulletsforever/bullets/ToolsTracker.java
233
package com.bulletsforever.bullets; /** * This is for user data tracking * This should be set up by MenuHome * This will probably not be implemented * See Localytics http://www.localytics.com/ */ public class ToolsTracker { }
gpl-2.0
guillep19/grails-responsys-ws-integration
ResponsysClientLib/src/com/rsys/ws/DeleteLinkTable.java
19151
/** * DeleteLinkTable.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST) */ package com.rsys.ws; /** * DeleteLinkTable bean class */ @SuppressWarnings({"unchecked","unused"}) public class DeleteLinkTable implements org.apache.axis2.databinding.ADBBean{ public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName( "urn:ws.rsys.com", "deleteLinkTable", ""); /** * field for LinkTable */ protected com.rsys.ws.InteractObject localLinkTable ; /** * Auto generated getter method * @return com.rsys.ws.InteractObject */ public com.rsys.ws.InteractObject getLinkTable(){ return localLinkTable; } /** * Auto generated setter method * @param param LinkTable */ public void setLinkTable(com.rsys.ws.InteractObject param){ this.localLinkTable=param; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,MY_QNAME); return factory.createOMElement(dataSource,MY_QNAME); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter); if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"urn:ws.rsys.com"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":deleteLinkTable", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "deleteLinkTable", xmlWriter); } } if (localLinkTable==null){ writeStartElement(null, "urn:ws.rsys.com", "linkTable", xmlWriter); // write the nil attribute writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","nil","1",xmlWriter); xmlWriter.writeEndElement(); }else{ localLinkTable.serialize(new javax.xml.namespace.QName("urn:ws.rsys.com","linkTable"), xmlWriter); } xmlWriter.writeEndElement(); } private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("urn:ws.rsys.com")){ return ""; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * Utility method to write an element start tag. */ private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, localPart); } else { if (namespace.length() == 0) { prefix = ""; } else if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, localPart, namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext(); while (true) { java.lang.String uri = nsContext.getNamespaceURI(prefix); if (uri == null || uri.length() == 0) { break; } prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); elementList.add(new javax.xml.namespace.QName("urn:ws.rsys.com", "linkTable")); elementList.add(localLinkTable==null?null: localLinkTable); return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static DeleteLinkTable parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ DeleteLinkTable object = new DeleteLinkTable(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"deleteLinkTable".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (DeleteLinkTable)com.rsys.ws.fault.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("urn:ws.rsys.com","linkTable").equals(reader.getName())){ nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","nil"); if ("true".equals(nillableValue) || "1".equals(nillableValue)){ object.setLinkTable(null); reader.next(); reader.next(); }else{ object.setLinkTable(com.rsys.ws.InteractObject.Factory.parse(reader)); reader.next(); } } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
gpl-2.0
smarr/Truffle
sulong/projects/com.oracle.truffle.llvm.runtime/src/com/oracle/truffle/llvm/runtime/interop/access/LLVMSelfArgumentPackNode.java
2350
/* * Copyright (c) 2020, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.oracle.truffle.llvm.runtime.interop.access; import com.oracle.truffle.api.dsl.GenerateUncached; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.llvm.runtime.nodes.api.LLVMNode; import com.oracle.truffle.llvm.runtime.pointer.LLVMPointer; @GenerateUncached public abstract class LLVMSelfArgumentPackNode extends LLVMNode { public abstract Object[] execute(LLVMPointer receiver, Object[] arguments); @Specialization public Object[] doPack(LLVMPointer receiver, Object[] arguments) { Object[] newArgs = new Object[arguments.length + 1]; newArgs[0] = receiver; for (int i = 0; i < arguments.length; i++) { newArgs[i + 1] = arguments[i]; } return newArgs; } }
gpl-2.0
robertquitt/iaroc2015-option16b
ch/aplu/bluetooth/BtListener.java
707
// BtListener.java /* This software is part of the NxtJLib library. It is Open Source Free Software, so you may - run the code for any purpose - study how the code works and adapt it to your needs - integrate all or parts of the code in your own programs - redistribute copies of the code - improve the code and release your improvements to the public However the use of the code is entirely your responsibility. */ package ch.aplu.bluetooth; import java.io.*; /** * Declaration of a notification method called from the class BluetoothServer. */ public interface BtListener { /** * Called when a connection is established. */ public void notifyConnection(InputStream is, OutputStream os); }
gpl-2.0
TweakCraft/TweakCart2
src/net/tweakcraft/tweakcart/util/InventoryManager.java
9327
/* * Copyright (c) 2012. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.tweakcraft.tweakcart.util; import net.tweakcraft.tweakcart.model.IntMap; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; /** * @author Edoxile * Here comes the black magic */ public class InventoryManager { public static int[] moveContainerContents(Inventory cart, Inventory chest, IntMap[] maps) { if (maps == null) return null; if (cart == null) { System.out.println("Cart was null!"); return null; } if (chest == null) { System.out.println("Chest was null!"); return null; } if (maps.length == 2) { int data[] = moveContainerContents(cart, chest, maps[0]); if (data[2] == 64) { return data; } else { return moveContainerContents(chest, cart, maps[1]); } } else { return null; } } //returns state of containers[from {empty slots}][to {full slots}][non matching stacks?] public static int[] moveContainerContents(Inventory iFrom, Inventory iTo, IntMap map) { ItemStack[] from = iFrom.getContents(); ItemStack[] to = iTo.getContents(); //Compile the return data from these three bytes int[] returnData = new int[3]; for (int fromIndex = 0; fromIndex < from.length; fromIndex++) { ItemStack fStack = from[fromIndex]; if (fStack == null) continue; int maxAmountToMove = map.getInt(fStack.getType(), fStack.getDurability()); if (fStack == null || maxAmountToMove == 0) { returnData[0]++; continue; } for (int toIndex = 0; toIndex < to.length; toIndex++) { ItemStack tStack = to[toIndex]; /* Extra check op maxAmountToMove */ if(maxAmountToMove == 0) { break; } if (tStack == null) { if (fStack.getAmount() <= maxAmountToMove) { to[toIndex] = fStack; fStack = null; returnData[0]++; map.setInt( to[toIndex].getType(), to[toIndex].getDurability(), maxAmountToMove - to[toIndex].getAmount() ); break; } else { //TODO: check if durability & data is the same in this case to[toIndex] = new ItemStack( fStack.getType(), maxAmountToMove, fStack.getDurability() ); fStack.setAmount(fStack.getAmount() - maxAmountToMove); map.setInt( fStack.getType(), fStack.getDurability(), 0 ); break; } } else if (tStack.getAmount() == 64) { returnData[1]++; continue; } else if (fStack.getTypeId() == tStack.getTypeId() && fStack.getDurability() == tStack.getDurability() && tStack.getEnchantments().equals(fStack.getEnchantments())) { //And now the magic begins //First check if the stackAmount is smaller then the max amount to move if (fStack.getAmount() <= maxAmountToMove) { int total = fStack.getAmount() + tStack.getAmount(); if (total > 64) { map.setInt( tStack.getType(), tStack.getDurability(), map.getInt(tStack.getType(), tStack.getDurability()) - (64 - tStack.getAmount()) ); tStack.setAmount(64); fStack.setAmount(total - 64); returnData[1]++; } else { map.setInt( tStack.getType(), tStack.getDurability(), map.getInt(tStack.getType(), tStack.getDurability()) - fStack.getAmount() ); tStack.setAmount(total); fStack = null; returnData[0]++; break; } } else { //Otherwise, run some other code int total = maxAmountToMove + tStack.getAmount(); int stableAmount = fStack.getAmount() - maxAmountToMove; if (total > 64) { map.setInt( tStack.getType(), tStack.getDurability(), map.getInt(tStack.getType(), tStack.getDurability()) - (64 - tStack.getAmount()) ); maxAmountToMove -= 64 - tStack.getAmount(); tStack.setAmount(64); fStack.setAmount(total - 64 + stableAmount); returnData[1]++; } else { map.setInt( tStack.getType(), tStack.getDurability(), map.getInt(tStack.getType(), tStack.getDurability()) - maxAmountToMove ); tStack.setAmount(total); fStack.setAmount(stableAmount); break; } } } else { returnData[2]++; continue; } to[toIndex] = tStack; } from[fromIndex] = fStack; } iFrom.setContents(from); iTo.setContents(to); return returnData; } public static ItemStack[] putContents(Inventory iTo, ItemStack... stackFrom) { ItemStack[] stackTo = iTo.getContents(); fromLoop: for (int fromIndex = 0; fromIndex < stackFrom.length; fromIndex++) { ItemStack fromStack = stackFrom[fromIndex]; if (fromStack == null) { continue; } else { for (int toIndex = 0; toIndex < stackTo.length; toIndex++) { ItemStack toStack = stackTo[toIndex]; if (toStack == null) { stackTo[toIndex] = fromStack; stackFrom[fromIndex] = null; continue fromLoop; } else if (fromStack.getTypeId() == toStack.getTypeId() && fromStack.getDurability() == toStack.getDurability() && toStack.getEnchantments().isEmpty()) { int total = fromStack.getAmount() + toStack.getAmount(); if (total > 64) { toStack.setAmount(64); fromStack.setAmount(total - 64); } else { toStack.setAmount(total); int remainder = total - 64; if (remainder <= 0) { stackFrom[fromIndex] = null; stackTo[toIndex] = toStack; continue fromLoop; } else { fromStack.setAmount(remainder); } } } else { continue; } stackTo[toIndex] = toStack; } } stackFrom[fromIndex] = fromStack; } iTo.setContents(stackTo); return stackFrom; } public static boolean isEmpty(ItemStack... stacks) { for (ItemStack stack : stacks) { if (stack != null && stack.getAmount() != 0) { return false; } } return true; } }
gpl-2.0
heartsome/tmxeditor8
ts/net.heartsome.cat.ts.ui.qa/src/net/heartsome/cat/ts/ui/qa/views/QAResultViewPart.java
25097
package net.heartsome.cat.ts.ui.qa.views; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import net.heartsome.cat.ts.core.qa.QAConstant; import net.heartsome.cat.ts.ui.editors.IXliffEditor; import net.heartsome.cat.ts.ui.qa.Activator; import net.heartsome.cat.ts.ui.qa.model.QAResult; import net.heartsome.cat.ts.ui.qa.model.QAResultBean; import net.heartsome.cat.ts.ui.qa.resource.Messages; import net.heartsome.cat.ts.ui.util.MultiFilesOper; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.ViewPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 品质检查结果视图 * @author robert 2011-11-12 */ public class QAResultViewPart extends ViewPart implements PropertyChangeListener { /** 常量,视图ID。 */ public static final String ID = "net.heartsome.cat.ts.ui.qa.views.QAResultViewPart"; private Composite parent; private TableViewer tableViewer; private Table table; private QAResult qaResult; private IWorkspaceRoot root; private IWorkbenchWindow window; /** 列表中所显示的数据,这个是用来排序的,其值随列表数据删除时删除 */ private List<QAResultBean> inputData = new ArrayList<QAResultBean>(); private Image errorImg; private Image warningImg; private boolean isMultiFile; private MultiFilesOper oper; private final static String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor"; public final static Logger logger = LoggerFactory.getLogger(QAResultViewPart.class.getName()); /** 标识当前品质检查结果视图所处理的文件路径的集合 */ private List<String> filePathList = null; private Image deleteImage = Activator.getImageDescriptor("images/delete.png").createImage(); public QAResultViewPart() { errorImg = Activator.getImageDescriptor("icons/error.png").createImage(); warningImg = Activator.getImageDescriptor("icons/warning.png").createImage(); } @Override public void createPartControl(Composite parent) { this.parent = parent; root = ResourcesPlugin.getWorkspace().getRoot(); window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); createTable(); } @Override public void setFocus() { // TODO Auto-generated method stub } @Override public void dispose() { if (qaResult != null) { qaResult.listeners.removePropertyChangeListener(this); } if(errorImg != null && !errorImg.isDisposed()){ errorImg.dispose(); } if(warningImg != null && !warningImg.isDisposed()){ warningImg.dispose(); } if (deleteImage != null && !deleteImage.isDisposed()) { deleteImage.dispose(); } super.dispose(); } /** labelProvider. */ private ITableLabelProvider labelProvider = new ITableLabelProvider() { public Image getColumnImage(Object element, int columnIndex) { if (columnIndex == 0) { if (element instanceof QAResultBean) { QAResultBean bean = (QAResultBean) element; if (0 == bean.getTipLevel()) { return errorImg; } else if (1 == bean.getTipLevel()) { return warningImg; } } } return null; } public String getColumnText(Object element, int columnIndex) { if (element instanceof QAResultBean) { QAResultBean bean = (QAResultBean) element; switch (columnIndex) { case 0: return ""; case 1: return bean.getLineNumber(); case 2: return bean.getQaType(); case 3: return bean.getErrorTip(); case 4: return bean.getResource(); case 5: return bean.getLangPair(); default: return ""; } } return null; } public void addListener(ILabelProviderListener listener) { } public void dispose() { } public boolean isLabelProperty(Object element, String property) { return false; } public void removeListener(ILabelProviderListener listener) { } }; public void createTable() { tableViewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); table = tableViewer.getTable(); GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, true); table.setLayoutData(tableData); table.setHeaderVisible(true); table.setLinesVisible(true); tableViewer.setLabelProvider(labelProvider); tableViewer.setContentProvider(new ArrayContentProvider()); tableViewer.setInput(inputData); // tableViewer.setSorter(new QASorter()); String[] columnNames = new String[] { Messages.getString("qa.views.QAResultViewPart.columnTipLevel"), Messages.getString("qa.views.QAResultViewPart.columnErrorLine"), Messages.getString("qa.views.QAResultViewPart.columnQAType"), Messages.getString("qa.views.QAResultViewPart.columnErrorTip"), Messages.getString("qa.views.QAResultViewPart.columnFilePath"), Messages.getString("qa.views.QAResultViewPart.columnLangPair") }; // 第0列为错误级别 TableColumn tipLevelColumn = new TableColumn(table, SWT.BOTTOM | SWT.CENTER); tipLevelColumn.setText(columnNames[0]); // tipLevelColumn.setAlignment(SWT.RIGHT_TO_LEFT); tipLevelColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? QASorter.tipLevel_ASC : QASorter.tipLevel_DESC); asc = !asc; } }); // 第一列为行号 TableColumn lineNumberColumn = new TableColumn(table, SWT.LEFT); lineNumberColumn.setText(columnNames[1]); lineNumberColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? QASorter.lineNumber_ASC : QASorter.lineNumber_DESC); asc = !asc; } }); // 第二列为检查类型 TableColumn qaTypeColumn = new TableColumn(table, SWT.LEFT); qaTypeColumn.setText(columnNames[2]); qaTypeColumn.addSelectionListener(new SelectionAdapter() { boolean asc = true; @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? QASorter.qaType_ASC : QASorter.qaType_DESC); asc = !asc; } }); // 第三行为错误描述,不添加排序功能 TableColumn qaTipColumn = new TableColumn(table, SWT.LEFT); qaTipColumn.setText(columnNames[3]); // 第四行为资源(路径) TableColumn resourceCln = new TableColumn(table, SWT.LEFT); resourceCln.setText(columnNames[4]); resourceCln.addSelectionListener(new SelectionAdapter() { boolean asc = true; @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? QASorter.resource_ASC : QASorter.resource_DESC); asc = !asc; } }); // 第五列,语言对 TableColumn langPairCln = new TableColumn(table, SWT.LEFT); langPairCln.setText(columnNames[5]); langPairCln.addSelectionListener(new SelectionAdapter() { boolean asc = true; @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(asc ? QASorter.langPair_ASC : QASorter.langPair_DESC); asc = !asc; } }); // 初始化时默认以行号进行排序 tableViewer.setSorter(QASorter.lineNumber_ASC); // 让列表列宽动态变化 table.addListener(SWT.Resize, new Listener() { public void handleEvent(Event event) { final Table table = ((Table) event.widget); final TableColumn[] columns = table.getColumns(); event.widget.getDisplay().syncExec(new Runnable() { public void run() { double[] columnWidths = new double[] { 0.08, 0.08, 0.14, 0.36, 0.2, 0.13 }; for (int i = 0; i < columns.length; i++) columns[i].setWidth((int) (table.getBounds().width * columnWidths[i])); } }); } }); table.addMouseListener(new MouseAdapter() { public void mouseDoubleClick(MouseEvent e) { locationRow(); } }); table.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.keyCode == QAConstant.QA_CENTERKEY_1 || e.keyCode == QAConstant.QA_CENTERKEY_2) { locationRow(); } } }); createPropMenu(); } /** * 创建右键参数 */ private void createPropMenu() { Menu propMenu = new Menu(table); table.setMenu(propMenu); MenuItem deletWarnItem = new MenuItem(propMenu, SWT.NONE); deletWarnItem.setText(Messages.getString("views.QAResultViewPart.deletWarnItem")); deletWarnItem.setImage(deleteImage); deletWarnItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { QAResultBean bean; for (int i = 0; i < inputData.size(); i++) { bean = inputData.get(i); // 0为错误,1为警告 if (1 == bean.getTipLevel()) { inputData.remove(bean); i--; } } tableViewer.refresh(); } }); MenuItem deleteAllItem = new MenuItem(propMenu, SWT.NONE); deleteAllItem.setText(Messages.getString("views.QAResultViewPart.deleteAllItem")); deleteAllItem.setImage(deleteImage); deleteAllItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { inputData.clear(); tableViewer.refresh(); } }); propMenu.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if(deleteImage!= null && !deleteImage.isDisposed()){ deleteImage.dispose(); } } }); // MenuItem ignoreSpellItem = new MenuItem(propMenu, SWT.NONE); // ignoreSpellItem.setText(Messages.getString("views.QAResultViewPart.ignoreSpellItem")); } /** * 将品质检查的结果传到这里来 */ public void setTableData(final String[] qaResultData) { try { Display.getCurrent().asyncExec(new Runnable() { public void run() { TableItem ti = new TableItem(table, 0); ti.setText(qaResultData); // ti.setImage(index, image); table.update(); // tableViewer.setInput(qaResultData); } }); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.views.QAResultViewPart.log1"), e); } } public void propertyChange(final PropertyChangeEvent evt) { /* * 备注,传过来的数据是一个 ArrayList<QAResultBean>, 每组数据都是相同的 rowId */ if ("printData".equals(evt.getPropertyName())) { try { Display.getDefault().syncExec(new Runnable() { @SuppressWarnings("unchecked") public void run() { Object obj = evt.getNewValue(); if (obj instanceof List) { List<QAResultBean> objList = (List<QAResultBean>) obj; if (objList.size() <= 0) { return; } // StringBuffer sb = new StringBuffer(); // sb.append("是否是自动检查 = " + qaResult.isAutoQA()); // sb.append("\n"); // sb.append("是否处理同一对象 = " + qaResult.isSameOperObjForAuto()); // MessageDialog.openInformation(getSite().getShell(), "用于测试", sb.toString()); String rowId = objList.get(0).getRowId(); // 如果是自动检查。那么要删除之前的记录 if (qaResult.isAutoQA()) { if (qaResult.isSameOperObjForAuto()) { for(int i = 0; i < inputData.size(); i ++){ QAResultBean bean = inputData.get(i); if (rowId.equals(bean.getRowId())) { inputData.remove(bean); i --; } } }else { // MessageDialog.openInformation(getSite().getShell(), "通知", "这里要清空数据 + filePathList.length = " + filePathList.size()); inputData.clear(); tableViewer.refresh(); filePathList = qaResult.getFilePathList(); qaResult.setSameOperObjForAuto(true); } } inputData.addAll(objList); tableViewer.refresh(); if (qaResult.isAutoQA()) { tableViewer.setSelection(new StructuredSelection(objList)); } }else if (obj instanceof String) { // 这是针对自动品质检查,若一个文本段没有错误,那么就将这个文本段之前的提示进行清除 if (qaResult.isAutoQA()) { if (qaResult.isSameOperObjForAuto()) { String rowId = (String) obj; for(int i = 0; i < inputData.size(); i ++){ QAResultBean bean = inputData.get(i); if (rowId.equals(bean.getRowId())) { inputData.remove(bean); i --; } } }else { inputData.clear(); tableViewer.refresh(); filePathList = qaResult.getFilePathList(); qaResult.setSameOperObjForAuto(true); } } tableViewer.refresh(); } } }); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.views.QAResultViewPart.log1"), e); } } else if ("isMultiFiles".equals(evt.getPropertyName())) { try { Display.getCurrent().syncExec(new Runnable() { public void run() { isMultiFile = (Boolean) ((Object[]) evt.getNewValue())[0]; if (isMultiFile) { oper = (MultiFilesOper) ((Object[]) evt.getNewValue())[1]; }else { oper = null; } } }); } catch (Exception e) { e.printStackTrace(); logger.error(Messages.getString("qa.views.QAResultViewPart.log1"), e); } } } public void registLister(QAResult qaResult) { this.qaResult = qaResult; this.qaResult.listeners.addPropertyChangeListener(this); if (filePathList != null && filePathList.size() > 0) { // 自动品质检查这里是不能保存相关信息的 if (!qaResult.isAutoQA()) { filePathList = this.qaResult.getFilePathList(); }else { boolean isSameOperObj = true; List<String> curFilePathList = this.qaResult.getFilePathList(); if (curFilePathList.size() == filePathList.size()) { for(String filePath : filePathList){ if (curFilePathList.contains(filePath)) { curFilePathList.remove(filePath); }else { isSameOperObj = false; break; } } }else { isSameOperObj = false; } this.qaResult.setSameOperObjForAuto(isSameOperObj); } }else { filePathList = this.qaResult.getFilePathList(); } } /** * 双击或按回车键,将品质检查结果中的数据定位到翻译界面上去。 */ public void locationRow() { TableItem[] items = table.getSelection(); if (items.length <= 0) { return; } // 获取第一行选择的值 TableItem item = items[0]; String fileFullPath = item.getText(4); // 如果是合并打开的文件 if (isMultiFile) { IXliffEditor xliffEditor = openMultiFilesEditor(); if (xliffEditor == null) { return; } String lineNumber = item.getText(1); // 跳转到错误行 xliffEditor.setFocus(); xliffEditor.jumpToRow(Integer.parseInt(lineNumber) - 1, true); return; } else { // 检查该文件是否已经打开,如果没有打开,就在界面上打开,再返回这个 IXliffEditor xliffEditor = openEditor(fileFullPath); if (xliffEditor == null) { return; } String lineNumber = item.getText(1); // 跳转到错误行 xliffEditor.setFocus(); xliffEditor.jumpToRow(Integer.parseInt(lineNumber) - 1, false); } } public IXliffEditor openEditor(String fileFullPath) { IFile ifile = root.getFileForLocation(root.getLocation().append(fileFullPath)); FileEditorInput fileInput = new FileEditorInput(ifile); IEditorReference[] editorRefer = window.getActivePage().findEditors(fileInput, XLIFF_EDITOR_ID, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); IEditorPart editorPart = null; IXliffEditor xliffEditor = null; if (editorRefer.length >= 1) { editorPart = editorRefer[0].getEditor(true); xliffEditor = (IXliffEditor) editorPart; // 若该文件未激活,激活此文件 if (window.getActivePage().getActiveEditor() != editorPart) { window.getActivePage().activate(editorPart); } // 对于已经打开过的文件,进行重排序 xliffEditor.resetOrder(); } else { // 如果文件没有打开,那么先打开文件 try { if(!validateXliffCanOpen(ifile)){ return null; } xliffEditor = (IXliffEditor) window.getActivePage().openEditor(fileInput, XLIFF_EDITOR_ID, true, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); } catch (PartInitException e) { e.printStackTrace(); logger.error(Messages.getString("qa.views.QAResultViewPart.log2"), e); } } return xliffEditor; } /** * 处理合并打开文件 nattable editor的相关问题 * @return ; */ public IXliffEditor openMultiFilesEditor() { IXliffEditor xliffEditor = null; FileEditorInput fileInput = new FileEditorInput(oper.getCurMultiTempFile()); IEditorReference[] editorRefer = window.getActivePage().findEditors(fileInput, XLIFF_EDITOR_ID, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); IEditorPart editorPart = null; if (editorRefer.length >= 1) { editorPart = editorRefer[0].getEditor(true); xliffEditor = (IXliffEditor) editorPart; // 若该文件未激活,激活此文件 if (window.getActivePage().getActiveEditor() != editorPart) { window.getActivePage().activate(editorPart); } // 对于已经打开过的文件,进行重排序 xliffEditor.resetOrder(); } else { // 如果文件没有打开,那么先打开文件 try { // 如果保存合并打开所有信息的临时文件已经被删除,那么,重新生成临时文件 if (!oper.getCurMultiTempFile().getLocation().toFile().exists()) { // 检查这两个文件是否重新进行合并打开了的。 IFile findMultiTempIfile = oper.getMultiFilesTempIFile(true); if (findMultiTempIfile != null) { fileInput = new FileEditorInput(findMultiTempIfile); oper.setCurMultiTempFile(findMultiTempIfile); } else { //先验证这些所处理的文件是否有已经被打开的 List<IFile> openedFileList = oper.getOpenedIfile(); if (openedFileList.size() > 0) { String openFileStr = ""; for(IFile ifile : openedFileList){ openFileStr += "\t" + ifile.getFullPath().toOSString() + "\n"; } MessageDialog.openInformation(getSite().getShell(), Messages.getString("views.QAResultViewPart.msgTitle"), MessageFormat.format(Messages.getString("qa.views.QAResultViewPart.addTip1"), openFileStr)); return null; } // 如果选中的文件没有合并打开,那么就重新打开它们 IFile multiIFile = oper.createMultiTempFile(); if (multiIFile != null && multiIFile.exists()) { fileInput = new FileEditorInput(multiIFile); oper.setCurMultiTempFile(multiIFile); } else { MessageDialog.openInformation(getSite().getShell(), Messages.getString("views.QAResultViewPart.msgTitle"), Messages.getString("views.QAResultViewPart.msg1")); return null; } xliffEditor = (IXliffEditor) window.getActivePage().openEditor(fileInput, XLIFF_EDITOR_ID, true, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID); } } } catch (PartInitException e) { e.printStackTrace(); logger.error(Messages.getString("qa.views.QAResultViewPart.log2"), e); } } return xliffEditor; } /** * 验证当前要单个打开的文件是否已经被合并打开,针对单个文件的品质检查点击结果进行定位 * @return */ public boolean validateXliffCanOpen(IFile iFile){ IEditorReference[] editorRes = window.getActivePage().getEditorReferences(); for (int i = 0; i < editorRes.length; i++) { IXliffEditor editor = (IXliffEditor) editorRes[i].getEditor(true); if (editor.isMultiFile()) { if (editor.getMultiFileList().indexOf(iFile.getLocation().toFile()) != -1) { MessageDialog.openInformation(getSite().getShell(), Messages.getString("views.QAResultViewPart.msgTitle"), MessageFormat.format(Messages.getString("qa.views.QAResultViewPart.addTip2"), iFile.getFullPath().toOSString())); return false; } } } return true; } /** * 品质检查显示数据的列表排序类 * @author robert * @version * @since JDK1.6 */ static class QASorter extends ViewerSorter { private static final int tipLevel_ID = 1; private static final int lineNumber_ID = 2; // 错语行号 private static final int qaType_ID = 3; // 检查类型 private static final int resource_ID = 5; // 第四列错语描述不技持排序,这是第五列,路径 private static final int langPair_ID = 6; // 第六列,语言对 public static final QASorter tipLevel_ASC = new QASorter(tipLevel_ID); public static final QASorter tipLevel_DESC = new QASorter(-tipLevel_ID); public static final QASorter lineNumber_ASC = new QASorter(lineNumber_ID); public static final QASorter lineNumber_DESC = new QASorter(-lineNumber_ID); public static final QASorter qaType_ASC = new QASorter(qaType_ID); public static final QASorter qaType_DESC = new QASorter(-qaType_ID); public static final QASorter resource_ASC = new QASorter(resource_ID); public static final QASorter resource_DESC = new QASorter(-resource_ID); public static final QASorter langPair_ASC = new QASorter(langPair_ID); public static final QASorter langPair_DESC = new QASorter(-langPair_ID); private int sortType; private QASorter(int sortType) { this.sortType = sortType; } @Override public int compare(Viewer viewer, Object e1, Object e2) { QAResultBean bean1 = (QAResultBean) e1; QAResultBean bean2 = (QAResultBean) e2; switch (sortType) { case tipLevel_ID: { int lineNumber1 = bean1.getTipLevel(); int lineNumber2 = bean2.getTipLevel(); return lineNumber1 > lineNumber2 ? 1 : -1; } case -tipLevel_ID: { int lineNumber1 = bean1.getTipLevel(); int lineNumber2 = bean2.getTipLevel(); return lineNumber1 > lineNumber2 ? -1 : 1; } case lineNumber_ID: { int lineNumber1 = Integer.parseInt(bean1.getLineNumber()); int lineNumber2 = Integer.parseInt(bean2.getLineNumber()); return lineNumber1 > lineNumber2 ? 1 : -1; } case -lineNumber_ID: { int lineNumber1 = Integer.parseInt(bean1.getLineNumber()); int lineNumber2 = Integer.parseInt(bean2.getLineNumber()); return lineNumber1 > lineNumber2 ? -1 : 1; } case qaType_ID: { String qaType1 = bean1.getQaType(); String qaType2 = bean2.getQaType(); return qaType1.compareToIgnoreCase(qaType2); } case -qaType_ID: { String qaType1 = bean1.getQaType(); String qaType2 = bean2.getQaType(); return qaType2.compareToIgnoreCase(qaType1); } case resource_ID: { String resource1 = bean1.getResource(); String resource2 = bean2.getResource(); return resource1.compareToIgnoreCase(resource2); } case -resource_ID: { String resource1 = bean1.getResource(); String resource2 = bean2.getResource(); return resource2.compareToIgnoreCase(resource1); } case langPair_ID: { String langPair1 = bean1.getLangPair(); String langPair2 = bean2.getLangPair(); return langPair1.compareToIgnoreCase(langPair2); } case -langPair_ID: { String langPair1 = bean1.getLangPair(); String langPair2 = bean2.getLangPair(); return langPair2.compareToIgnoreCase(langPair1); } } return 0; } } /** * 清除结果显示视图的列表中的数据 */ public void clearTableData() { inputData.clear(); table.removeAll(); } }
gpl-2.0
hvoss/logistik
src/main/java/de/hsbremen/kss/configuration/ComplexOrder.java
3679
package de.hsbremen.kss.configuration; import org.apache.commons.lang3.Validate; /** * a complex order is a combination of two {@link Order}s. * * @author henrik * */ public final class ComplexOrder { /** the id */ private final Integer id; /** order which must be performed first */ private final Order firstOrder; /** order which must be performed after the first order */ private final Order secondOrder; /** max duration between both orders */ private final Double maxDuration; /** * ctor. * * @param id * the id * @param firstOrder * order which must be performed first * @param secondOrder * order which must be performed after the first order * @param maxDuration * max duration between both orders */ public ComplexOrder(final Integer id, final Order firstOrder, final Order secondOrder, final Double maxDuration) { Validate.notNull(id, "id is null"); Validate.notNull(firstOrder, "firstOrder is null"); Validate.notNull(secondOrder, "secondOrder is null"); Validate.notNull(maxDuration, "maxDuration is null"); Validate.isTrue(firstOrder.getDestinationStation().equals(secondOrder.getDestinationStation()), "destination stations must be the same"); Validate.isTrue(!firstOrder.getProduct().equals(secondOrder.getProduct()), "products must be different"); final Double start = firstOrder.getDestination().getTimeWindow().getStart() + firstOrder.getDestination().getServiceTime(); final Double end = firstOrder.getDestination().getTimeWindow().getEnd() + firstOrder.getDestination().getServiceTime(); final boolean betweenStart = secondOrder.getDestination().getTimeWindow().between(start); final boolean betweenEnd = secondOrder.getDestination().getTimeWindow().between(end); Validate.isTrue(betweenStart && betweenEnd); this.id = id; this.firstOrder = firstOrder; this.secondOrder = secondOrder; this.maxDuration = maxDuration; } /** * Gets the id. * * @return the id */ public Integer getId() { return this.id; } /** * Gets the order which must be performed first. * * @return the order which must be performed first */ public Order getFirstOrder() { return this.firstOrder; } /** * Gets the order which must be performed after the first order. * * @return the order which must be performed after the first order */ public Order getSecondOrder() { return this.secondOrder; } /** * Gets the max duration between both orders. * * @return the max duration between both orders */ public Double getMaxDuration() { return this.maxDuration; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.getId() == null) ? 0 : this.getId().hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ComplexOrder other = (ComplexOrder) obj; if (this.getId() == null) { if (other.getId() != null) { return false; } } else if (!this.getId().equals(other.getId())) { return false; } return true; } }
gpl-2.0
lukaville/http-server
src/main/java/com/lukaville/server/http/ErrorGenerator.java
829
package com.lukaville.server.http; /** * Created by nickolay on 21.10.15. */ public class ErrorGenerator { public static final String TEMPLATE = "<!DOCTYPE html><html><head> <title>{description}</title> <link href='https://fonts.googleapis.com/css?family=Ropa+Sans' rel='stylesheet' type='text/css'> <style type=\"text/css\"> html{padding: 0; margin: 0;}body{padding: 0; margin: 0; background: #2196F3; color: white; font-family: 'Ropa Sans', sans-serif;}h1{text-align: center; font-size: 12em; margin-bottom: 0.2em;}h2{text-align: center; font-size: 2.4em;}</style></head><body> <h1>{code}</h1> <h2>{description}</h2></body></html>"; public static String generateErrorPage(int code, String description) { return TEMPLATE.replace("{description}", description).replace("{code}", String.valueOf(code)); } }
gpl-2.0
Kloen/citra-android
app/src/androidTest/java/org/citraemu/citra/ApplicationTest.java
349
package org.citraemu.citra; 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-2.0
Corvu/dbeaver
plugins/org.jkiss.dbeaver.ext.db2/src/org/jkiss/dbeaver/ext/db2/model/dict/DB2RoutineType.java
2055
/* * DBeaver - Universal Database Manager * Copyright (C) 2013-2015 Denis Forveille (titou10.titou10@gmail.com) * Copyright (C) 2010-2016 Serge Rieder (serge@jkiss.org) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2) * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jkiss.dbeaver.ext.db2.model.dict; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.model.DBPNamedObject; import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureType; /** * DB2 Routine Type * * @author Denis Forveille */ public enum DB2RoutineType implements DBPNamedObject { F("Function", DBSProcedureType.FUNCTION), M("Method", DBSProcedureType.PROCEDURE), P("Procedure", DBSProcedureType.PROCEDURE); private String name; private DBSProcedureType procedureType; // ----------- // Constructor // ----------- private DB2RoutineType(String name, DBSProcedureType procedureType) { this.name = name; this.procedureType = procedureType; } // ----------------------- // Display @Property Value // ----------------------- @Override public String toString() { return name; } // ---------------- // Standard Getters // ---------------- @NotNull @Override public String getName() { return name; } public DBSProcedureType getProcedureType() { return procedureType; } }
gpl-2.0
epicprojects/learnerslib
Learners/src/learners/classifiers/neural/Neuron.java
2023
package learners.classifiers.neural; import java.util.ArrayList; import learners.functions.*; public class Neuron { private double output; private double error = 0.0; private boolean useBias = true; private double biasWeight = 0.0; private ArrayList<Synapse> inputSynapses = new ArrayList<Synapse>(); private ActivationFunction activationFunction; public Neuron() { setActivationFunction(new LinearFunction()); } public Neuron(ActivationFunction f) { setActivationFunction(f); } public void addSynapse(Synapse s) { if (s != null) { inputSynapses.add(s); } } public void setActivationFunction(ActivationFunction activationFunction) { this.activationFunction = activationFunction; } public ArrayList<Synapse> getInputSynapses() { return inputSynapses; } public double getOutput() { return output; } public void setOutput(double output) { this.output = output; } public void compute() { output = 0.0; for (Synapse s: inputSynapses) { output += s.getNeuron().getOutput() * s.getWeight(); } if (useBias) { output += biasWeight * 1.0; } output = activationFunction.compute(output); } public double getError() { return error; } public void setError(double error) { this.error = error; } public ActivationFunction getActivationFunction() { return activationFunction; } public double getBiasWeight() { return biasWeight; } public void setBiasWeight(double biasWeight) { this.biasWeight = biasWeight; } public boolean isUseBias() { return useBias; } public void setUseBias(boolean useBias) { this.useBias = useBias; } }
gpl-2.0
andresriancho/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest02188.java
2135
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest02188") public class BenchmarkTest02188 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = request.getParameter("vector"); if (param == null) param = ""; String bar = doSomething(param); Object[] obj = { bar, "b"}; response.getWriter().printf("Formatted like: %1$s and %2$s.",obj); } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar = param; if (param != null && param.length() > 1) { StringBuilder sbxyz88468 = new StringBuilder(param); bar = sbxyz88468.replace(param.length()-"Z".length(), param.length(),"Z").toString(); } return bar; } }
gpl-2.0
delMar43/wcworkshop
wcworkshop/wcworkshop-core/src/main/java/wcworkshop/core/data/Wc1Ship.java
711
package wcworkshop.core.data; public class Wc1Ship { public static final Wc1Ship EMPTY = new Wc1Ship(); private byte value; private String name; private boolean flyable; public Wc1Ship() { } public Wc1Ship(byte value, String name, boolean flyable) { this.value = value; this.name = name; this.flyable = flyable; } public byte getValue() { return value; } public void setValue(byte value) { this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setFlyable(boolean flyable) { this.flyable = flyable; } public boolean isFlyable() { return flyable; } }
gpl-2.0
Lythimus/lptv
apache-solr-3.6.0/solr/core/src/java/org/apache/solr/response/QueryResponseWriter.java
3489
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.solr.response; import java.io.Writer; import java.io.IOException; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.util.plugin.NamedListInitializedPlugin; /** * Implementations of <code>QueryResponseWriter</code> are used to format responses to query requests. * * Different <code>QueryResponseWriter</code>s are registered with the <code>SolrCore</code>. * One way to register a QueryResponseWriter with the core is through the <code>solrconfig.xml</code> file. * <p> * Example <code>solrconfig.xml</code> entry to register a <code>QueryResponseWriter</code> implementation to * handle all queries with a writer type of "simple": * <p> * <code> * &lt;queryResponseWriter name="simple" class="foo.SimpleResponseWriter" /&gt; * </code> * <p> * A single instance of any registered QueryResponseWriter is created * via the default constructor and is reused for all relevant queries. * * @version $Id: QueryResponseWriter.java 1075192 2011-02-28 00:50:09Z uschindler $ */ public interface QueryResponseWriter extends NamedListInitializedPlugin { public static String CONTENT_TYPE_XML_UTF8="application/xml; charset=UTF-8"; public static String CONTENT_TYPE_TEXT_UTF8="text/plain; charset=UTF-8"; public static String CONTENT_TYPE_TEXT_ASCII="text/plain; charset=US-ASCII"; /** * Write a SolrQueryResponse, this method must be thread save. * * <p> * Information about the request (in particular: formating options) may be * obtained from <code>req</code> but the dominant source of information * should be <code>rsp</code>. * <p> * There are no mandatory actions that write must perform. * An empty write implementation would fulfill * all interface obligations. * </p> */ public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException; /** * Return the applicable Content Type for a request, this method * must be thread safe. * * <p> * QueryResponseWriter's must implement this method to return a valid * HTTP Content-Type header for the request, that will logically * correspond with the output produced by the write method. * </p> * @return a Content-Type string, which may not be null. */ public String getContentType(SolrQueryRequest request, SolrQueryResponse response); /** <code>init</code> will be called just once, immediately after creation. * <p>The args are user-level initialization parameters that * may be specified when declaring a response writer in * solrconfig.xml */ public void init(NamedList args); }
gpl-2.0
mmpedraza/camel-netty
src/main/java/mx/redhat/com/coppel/netty/codecs/Encoder.java
2289
package mx.redhat.com.coppel.netty.codecs; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; import mx.redhat.com.coppel.netty.*; /** * OneToOneEncoder implementation that converts an Envelope instance into a ChannelBuffer. * * Since the encoder is stateless, a single instance can be shared among all pipelines, hence the @Sharable annotation * and the singleton instantiation. */ @ChannelHandler.Sharable public class Encoder extends OneToOneEncoder { private Encoder() { } // public static methods ------------------------------------------------------------------------------------------ public static Encoder getInstance() { return InstanceHolder.INSTANCE; } public static ChannelBuffer encodeMessage(byte[] message) throws IllegalArgumentException { // you can move these verifications "upper" (before writing to the channel) in order not to cause a // channel shutdown. if ((message == null) ) { throw new IllegalArgumentException("Message payload cannot be null or empty"); } // payload length(4b) + payload(nb) int size = 4 + message.length; ChannelBuffer buffer = ChannelBuffers.buffer(size); buffer.writeInt(message.length); buffer.writeBytes(message); System.out.println("Mensajes --> "+java.util.Arrays.toString(message)); System.out.println("Capacidad en el encoder "+ buffer.capacity()); return buffer; } // OneToOneEncoder ------------------------------------------------------------------------------------------------ @Override protected Object encode(ChannelHandlerContext channelHandlerContext, Channel channel, Object msg) throws Exception { return encodeMessage((byte[]) msg); } // private classes ------------------------------------------------------------------------------------------------ private static final class InstanceHolder { private static final Encoder INSTANCE = new Encoder(); } }
gpl-2.0
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/trees/international/pennchinese/ChineseHeadFinder.java
6623
package edu.stanford.nlp.trees.international.pennchinese; import edu.stanford.nlp.trees.AbstractCollinsHeadFinder; import edu.stanford.nlp.trees.TreebankLanguagePack; import java.util.HashMap; /** * HeadFinder for the Penn Chinese Treebank. Adapted from * CollinsHeadFinder. This is the version used in Levy and Manning (2003). * * @author Roger Levy */ public class ChineseHeadFinder extends AbstractCollinsHeadFinder { /** * If true, reverses the direction of search in VP and IP coordinations. * Works terribly . */ private static final boolean coordSwitch = false; static String[] leftExceptPunct = {"leftexcept", "PU"}; static String[] rightExceptPunct = {"rightexcept", "PU"}; public ChineseHeadFinder() { this(new ChineseTreebankLanguagePack()); } public ChineseHeadFinder(TreebankLanguagePack tlp) { super(tlp); nonTerminalInfo = new HashMap<String,String[][]>(); // these are first-cut rules String left = (coordSwitch ? "right" : "left"); String right = (coordSwitch ? "left" : "right"); String rightdis = "rightdis"; defaultRule = new String[]{right}; // ROOT is not always unary for chinese -- PAIR is a special notation // that the Irish people use for non-unary ones.... nonTerminalInfo.put("ROOT", new String[][]{{left, "IP"}}); nonTerminalInfo.put("PAIR", new String[][]{{left, "IP"}}); // Major syntactic categories nonTerminalInfo.put("ADJP", new String[][]{{left, "JJ", "ADJP"}}); // there is one ADJP unary rewrite to AD but otherwise all have JJ or ADJP nonTerminalInfo.put("ADVP", new String[][]{{left, "AD", "CS", "ADVP", "JJ"}}); // CS is a subordinating conjunctor, and there are a couple of ADVP->JJ unary rewrites nonTerminalInfo.put("CLP", new String[][]{{right, "M", "CLP"}}); //nonTerminalInfo.put("CP", new String[][] {{left, "WHNP","IP","CP","VP"}}); // this is complicated; see bracketing guide p. 34. Actually, all WHNP are empty. IP/CP seems to be the best semantic head; syntax would dictate DEC/ADVP. Using IP/CP/VP/M is INCREDIBLY bad for Dep parser - lose 3% absolute. nonTerminalInfo.put("CP", new String[][]{{right, "DEC", "WHNP", "WHPP"}, rightExceptPunct}); // the (syntax-oriented) right-first head rule // nonTerminalInfo.put("CP", new String[][]{{right, "DEC", "ADVP", "CP", "IP", "VP", "M"}}); // the (syntax-oriented) right-first head rule nonTerminalInfo.put("DNP", new String[][]{{right, "DEG", "DEC"}, rightExceptPunct}); // according to tgrep2, first preparation, all DNPs have a DEG daughter nonTerminalInfo.put("DP", new String[][]{{left, "DT", "DP"}}); // there's one instance of DP adjunction nonTerminalInfo.put("DVP", new String[][]{{right, "DEV", "DEC"}}); // DVP always has DEV under it nonTerminalInfo.put("FRAG", new String[][]{{right, "VV", "NN"}, rightExceptPunct}); //FRAG seems only to be used for bits at the beginnings of articles: "Xinwenshe<DATE>" and "(wan)" nonTerminalInfo.put("INTJ", new String[][]{{right, "INTJ", "IJ", "SP"}}); nonTerminalInfo.put("IP", new String[][]{{left, "VP", "IP"}, rightExceptPunct}); // CDM July 2010 following email from Pi-Chuan changed preference to VP over IP: IP can be -SBJ, -OBJ, or -ADV, and shouldn't be head nonTerminalInfo.put("LCP", new String[][]{{right, "LC", "LCP"}}); // there's a bit of LCP adjunction nonTerminalInfo.put("LST", new String[][]{{right, "CD", "PU"}}); // covers all examples nonTerminalInfo.put("NP", new String[][]{{right, "NN", "NR", "NT", "NP", "PN", "CP"}}); // Basic heads are NN/NR/NT/NP; PN is pronoun. Some NPs are nominalized relative clauses without overt nominal material; these are NP->CP unary rewrites. Finally, note that this doesn't give any special treatment of coordination. nonTerminalInfo.put("PP", new String[][]{{left, "P", "PP"}}); // in the manual there's an example of VV heading PP but I couldn't find such an example with tgrep2 // cdm 2006: PRN changed to not choose punctuation. Helped parsing (if not significantly) // nonTerminalInfo.put("PRN", new String[][]{{left, "PU"}}); //presumably left/right doesn't matter nonTerminalInfo.put("PRN", new String[][]{{left, "NP", "VP", "IP", "QP", "PP", "ADJP", "CLP", "LCP"}, {rightdis, "NN", "NR", "NT", "FW"}}); // cdm 2006: QP: add OD -- occurs some; occasionally NP, NT, M; parsing performance no-op nonTerminalInfo.put("QP", new String[][]{{right, "QP", "CLP", "CD", "OD", "NP", "NT", "M"}}); // there's some QP adjunction // add OD? nonTerminalInfo.put("UCP", new String[][]{{left, }}); //an alternative would be "PU","CC" nonTerminalInfo.put("VP", new String[][]{{left, "VP", "VCD", "VPT", "VV", "VCP", "VA", "VC", "VE", "IP", "VSB", "VCP", "VRD", "VNV"}, leftExceptPunct}); //note that ba and long bei introduce IP-OBJ small clauses; short bei introduces VP // add BA, LB, as needed // verb compounds nonTerminalInfo.put("VCD", new String[][]{{left, "VCD", "VV", "VA", "VC", "VE"}}); // could easily be right instead nonTerminalInfo.put("VCP", new String[][]{{left, "VCD", "VV", "VA", "VC", "VE"}}); // not much info from documentation nonTerminalInfo.put("VRD", new String[][]{{left, "VCD", "VRD", "VV", "VA", "VC", "VE"}}); // definitely left nonTerminalInfo.put("VSB", new String[][]{{right, "VCD", "VSB", "VV", "VA", "VC", "VE"}}); // definitely right, though some examples look questionably classified (na2lai2 zhi1fu4) nonTerminalInfo.put("VNV", new String[][]{{left, "VV", "VA", "VC", "VE"}}); // left/right doesn't matter nonTerminalInfo.put("VPT", new String[][]{{left, "VV", "VA", "VC", "VE"}}); // activity verb is to the left // some POS tags apparently sit where phrases are supposed to be nonTerminalInfo.put("CD", new String[][]{{right, "CD"}}); nonTerminalInfo.put("NN", new String[][]{{right, "NN"}}); nonTerminalInfo.put("NR", new String[][]{{right, "NR"}}); // I'm adding these POS tags to do primitive morphology for character-level // parsing. It shouldn't affect anything else because heads of preterminals are not // generally queried - GMA nonTerminalInfo.put("VV", new String[][]{{left}}); nonTerminalInfo.put("VA", new String[][]{{left}}); nonTerminalInfo.put("VC", new String[][]{{left}}); nonTerminalInfo.put("VE", new String[][]{{left}}); // new for ctb6. nonTerminalInfo.put("FLR", new String[][]{rightExceptPunct}); } private static final long serialVersionUID = 6143632784691159283L; }
gpl-2.0
ntj/ComplexRapidMiner
src/com/rapidminer/tools/WekaInstancesAdaptor.java
10025
/* * RapidMiner * * Copyright (C) 2001-2008 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.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.tools; import java.util.Enumeration; import java.util.Iterator; import weka.core.FastVector; import weka.core.Instance; import weka.core.Instances; import com.rapidminer.example.Attribute; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.example.FastExample2SparseTransform; import com.rapidminer.example.Statistics; import com.rapidminer.operator.OperatorException; /** * This class extends the Weka class Instances and overrides all methods needed * to directly use a RapidMiner {@link ExampleSet} as source for Weka instead of * copying the complete data. * * @author Ingo Mierswa * @version $Id: WekaInstancesAdaptor.java,v 2.13 2006/04/06 15:23:38 * ingomierswa Exp $ */ public class WekaInstancesAdaptor extends Instances { private static final long serialVersionUID = 99943154106235423L; public static final int LEARNING = 0; public static final int PREDICTING = 1; public static final int CLUSTERING = 2; public static final int ASSOCIATION_RULE_MINING = 3; public static final int WEIGHTING = 4; /** * This enumeration implementation uses an ExampleReader (Iterator) to enumerate the * instances. */ private class InstanceEnumeration implements Enumeration { private Iterator<Example> reader; public InstanceEnumeration(Iterator<Example> reader) { this.reader = reader; } public Object nextElement() { return toWekaInstance(reader.next()); } public boolean hasMoreElements() { return reader.hasNext(); } } /** The example set which backs up the Instances object. */ private ExampleSet exampleSet; /** This transformation might help to speed up the creation of sparse examples. */ private transient FastExample2SparseTransform exampleTransform; /** The most frequent nominal values (only used for association rule mining, null otherwise). * -1 if attribute is numerical. */ private int[] mostFrequent = null; /** * The task type for which this instances object is used. Must be one out of * LEARNING, PREDICTING, CLUSTERING, ASSOCIATION_RULE_MINING, or WEIGHTING. For the * latter cases the original label attribute will be omitted. */ private int taskType = LEARNING; /** The label attribute or null if not desired (depending on task). */ private Attribute labelAttribute = null; /** The weight attribute or null if not available. */ private Attribute weightAttribute = null; /** Creates a new Instances object based on the given example set. */ public WekaInstancesAdaptor(String name, ExampleSet exampleSet, int taskType) throws OperatorException { super(name, getAttributeVector(exampleSet, taskType), 0); this.exampleSet = exampleSet; this.taskType = taskType; this.weightAttribute = exampleSet.getAttributes().getWeight(); this.exampleTransform = new FastExample2SparseTransform(exampleSet); switch (taskType) { case LEARNING: labelAttribute = exampleSet.getAttributes().getLabel(); setClassIndex(exampleSet.getAttributes().size()); break; case PREDICTING: labelAttribute = exampleSet.getAttributes().getPredictedLabel(); setClassIndex(exampleSet.getAttributes().size()); break; case CLUSTERING: labelAttribute = null; setClassIndex(-1); break; case ASSOCIATION_RULE_MINING: // in case of association learning the most frequent attribute // is needed to set to "unknown" exampleSet.recalculateAllAttributeStatistics(); this.mostFrequent = new int[exampleSet.getAttributes().size()]; int i = 0; for (Attribute attribute : exampleSet.getAttributes()) { if (attribute.isNominal()) { this.mostFrequent[i] = (int)exampleSet.getStatistics(attribute, Statistics.MODE); } else { this.mostFrequent[i] = -1; } i++; } labelAttribute = null; setClassIndex(-1); break; case WEIGHTING: labelAttribute = exampleSet.getAttributes().getLabel(); if (labelAttribute != null) setClassIndex(exampleSet.getAttributes().size()); break; } } protected Object readResolve() { try { this.exampleTransform = new FastExample2SparseTransform(this.exampleSet); } catch (OperatorException e) { // do nothing } return this; } // ================================================================================ // Overriding some Weka methods // ================================================================================ /** Returns an instance enumeration based on an ExampleReader. */ public Enumeration enumerateInstances() { return new InstanceEnumeration(exampleSet.iterator()); } /** Returns the i-th instance. */ public Instance instance(int i) { return toWekaInstance(exampleSet.getExample(i)); } /** Returns the number of instances. */ public int numInstances() { return exampleSet.size(); } // ================================================================================ // Transforming examples into Weka instances // ================================================================================ /** Gets an example and creates a Weka instance. */ private Instance toWekaInstance(Example example) { int numberOfRegularValues = example.getAttributes().size(); int numberOfValues = numberOfRegularValues + (labelAttribute != null ? 1 : 0); double[] values = new double[numberOfValues]; // set regular attribute values if (taskType == ASSOCIATION_RULE_MINING) { int a = 0; for (Attribute attribute : exampleSet.getAttributes()) { double value = example.getValue(attribute); if (attribute.isNominal()) { if (value == mostFrequent[a]) value = Double.NaN; // sets the most frequent value to missing // for association learning } values[a] = value; a++; } } else { int[] nonDefaultIndices = exampleTransform.getNonDefaultAttributeIndices(example); double[] nonDefaultValues = exampleTransform.getNonDefaultAttributeValues(example, nonDefaultIndices); for (int a = 0; a < nonDefaultIndices.length; a++) { values[nonDefaultIndices[a]] = nonDefaultValues[a]; } } // set label value if necessary switch (taskType) { case LEARNING: values[values.length - 1] = example.getValue(labelAttribute); break; case PREDICTING: values[values.length - 1] = Double.NaN; break; case WEIGHTING: if (labelAttribute != null) values[values.length - 1] = example.getValue(labelAttribute); break; default: break; } // get instance weight double weight = 1.0d; if (this.weightAttribute != null) weight = example.getValue(this.weightAttribute); // create new instance Instance instance = new Instance(weight, values); instance.setDataset(this); return instance; } // ================================================================================ private static FastVector getAttributeVector(ExampleSet exampleSet, int taskType) { // determine label Attribute label = null; switch (taskType) { case LEARNING: case WEIGHTING: label = exampleSet.getAttributes().getLabel(); break; case PREDICTING: label = exampleSet.getAttributes().getPredictedLabel(); break; default: break; } // add regular attributes FastVector attributeVector = new FastVector(exampleSet.getAttributes().size() + (label != null ? 1 : 0)); for (Attribute attribute : exampleSet.getAttributes()) { attributeVector.addElement(toWekaAttribute(attribute)); } // add label if (label != null) attributeVector.addElement(toWekaAttribute(label)); return attributeVector; } /** Converts an {@link Attribute} to a Weka attribute. */ private static weka.core.Attribute toWekaAttribute(Attribute attribute) { if (attribute == null) return null; weka.core.Attribute result = null; if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.NOMINAL)) { FastVector nominalValues = new FastVector(attribute.getMapping().getValues().size()); for (int i = 0; i < attribute.getMapping().getValues().size(); i++) { nominalValues.addElement(attribute.getMapping().mapIndex(i)); } result = new weka.core.Attribute(attribute.getName(), nominalValues); } else { result = new weka.core.Attribute(attribute.getName()); } return result; } }
gpl-2.0
sigeu-deseg/sigeu-deseg
sigeu/src/br/edu/utfpr/dv/sigeu/dao/UriPermissaoDAO.java
1774
package br.edu.utfpr.dv.sigeu.dao; import java.util.List; import org.hibernate.Query; import br.edu.utfpr.dv.sigeu.entities.Campus; import br.edu.utfpr.dv.sigeu.entities.UriPermissao; import br.edu.utfpr.dv.sigeu.persistence.HibernateDAO; import br.edu.utfpr.dv.sigeu.persistence.Transaction; public class UriPermissaoDAO extends HibernateDAO<UriPermissao> { public UriPermissaoDAO(Transaction transaction) { super(transaction); } @Override public UriPermissao encontrePorId(Integer id) { String hql = "from UriPermissao o where o.idPermissao = :id"; Query q = session.createQuery(hql); q.setInteger("id", id); return (UriPermissao) q.uniqueResult(); } @Override public String getNomeSequencia() { return "instituicao"; } @Override public void preCriacao(UriPermissao o) { // Automatic } public UriPermissao pesquisaUriPorNomeGrupoPessoa(Campus campus, String nomeGrupo, String uri) { String hql = "SELECT o FROM UriPermissao o JOIN GrupoPessoa g WHERE o.uri = :uri AND g.nome = :nome AND g.idCampus.idCampus = :idCampus AND o.idCampus.idCampus = :idCampus"; Query q = session.createQuery(hql); q.setInteger("idCampus", campus.getIdCampus()); q.setString("nome", nomeGrupo.trim().toUpperCase()); q.setString("uri", uri); UriPermissao p = (UriPermissao) q.uniqueResult(); return p; } public List<UriPermissao> pesquisaPermissoesPorUri(Campus campus, String uri) { String hql = "SELECT o FROM UriPermissao o WHERE o.uri = :uri AND o.idCampus.idCampus = :idCampus"; Query q = session.createQuery(hql); q.setInteger("idCampus", campus.getIdCampus()); q.setString("uri", uri); return this.pesquisaObjetos(q, 0); } @Override public void preAlteracao(UriPermissao o) { // TODO Auto-generated method stub } }
gpl-2.0
tkdiooo/framework
QI-Common/QI-Common-Model/src/main/java/com/qi/common/model/vo/tree/ZTreeVO.java
1161
package com.qi.common.model.vo.tree; /** * Class ZTreeVO * * @author 张麒 2016/7/18. * @version Description: */ public class ZTreeVO { private String id; private String pId; private String name; private boolean open = false; private boolean isParent; public ZTreeVO() { } public ZTreeVO(String id, String pId, String name, boolean isParent) { this.id = id; this.pId = pId; this.name = name; this.isParent = isParent; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPId() { return pId; } public void setPId(String pId) { this.pId = pId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean getOpen() { return open; } public void setOpen(boolean open) { this.open = open; } public boolean getIsParent() { return isParent; } public void setIsParent(boolean isParent) { this.isParent = isParent; } }
gpl-2.0
activityworkshop/GpsPrune
src/tim/prune/save/BaseImageConfigDialog.java
18124
package tim.prune.save; import java.awt.BorderLayout; import java.awt.Component; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import tim.prune.I18nManager; import tim.prune.config.Config; import tim.prune.data.Track; import tim.prune.gui.map.MapSource; import tim.prune.gui.map.MapSourceLibrary; import tim.prune.threedee.ImageDefinition; /** * Dialog to let you choose the parameters for a base image * (source and zoom) including preview */ public class BaseImageConfigDialog implements Runnable { /** Parent to notify */ private BaseImageConsumer _parent = null; /** Parent dialog for position */ private JDialog _parentDialog = null; /** Track to use for preview image */ private Track _track = null; /** Dialog to show */ private JDialog _dialog = null; /** Checkbox for using an image or not */ private JCheckBox _useImageCheckbox = null; /** Panel to hold the other controls */ private JPanel _mainPanel = null; /** Dropdown for map source */ private JComboBox<String> _mapSourceDropdown = null; /** Dropdown for zoom levels */ private JComboBox<String> _zoomDropdown = null; /** Button to trigger a download of the missing map tiles */ private JButton _downloadTilesButton = null; /** Progress bar for downloading additional tiles */ private JProgressBar _progressBar = null; /** Label for number of tiles found */ private JLabel _tilesFoundLabel = null; /** Label for image size in pixels */ private JLabel _imageSizeLabel = null; /** Image preview panel */ private ImagePreviewPanel _previewPanel = null; /** Grouter, used to avoid regenerating images */ private MapGrouter _grouter = new MapGrouter(); /** OK button, needs to be enabled/disabled */ private JButton _okButton = null; /** Flag for rebuilding dialog, don't bother refreshing and recalculating */ private boolean _rebuilding = false; /** Cached values to allow cancellation of dialog */ private ImageDefinition _imageDef = new ImageDefinition(); /** * Constructor * @param inParent parent object to notify on completion of dialog * @param inParentDialog parent dialog * @param inTrack track object */ public BaseImageConfigDialog(BaseImageConsumer inParent, JDialog inParentDialog, Track inTrack) { _parent = inParent; _parentDialog = inParentDialog; _dialog = new JDialog(inParentDialog, I18nManager.getText("dialog.baseimage.title"), true); _dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); _dialog.getContentPane().add(makeDialogComponents()); _dialog.pack(); _track = inTrack; } /** * @param inDefinition image definition object from previous dialog */ public void setImageDefinition(ImageDefinition inDefinition) { _imageDef = inDefinition; if (_imageDef == null) { _imageDef = new ImageDefinition(); } } /** * Begin the function */ public void begin() { initDialog(); _dialog.setLocationRelativeTo(_parentDialog); _dialog.setVisible(true); } /** * Begin the function with a default of using an image */ public void beginWithImageYes() { initDialog(); _useImageCheckbox.setSelected(true); refreshDialog(); _dialog.setVisible(true); } /** * Initialise the dialog from the cached values */ private void initDialog() { _rebuilding = true; _useImageCheckbox.setSelected(_imageDef.getUseImage()); // Populate the dropdown of map sources from the library in case it has changed _mapSourceDropdown.removeAllItems(); for (int i=0; i<MapSourceLibrary.getNumSources(); i++) { _mapSourceDropdown.addItem(MapSourceLibrary.getSource(i).getName()); } int sourceIndex = _imageDef.getSourceIndex(); if (sourceIndex < 0 || sourceIndex >= _mapSourceDropdown.getItemCount()) { sourceIndex = 0; } _mapSourceDropdown.setSelectedIndex(sourceIndex); // Zoom level int zoomLevel = _imageDef.getZoom(); if (_imageDef.getUseImage()) { for (int i=0; i<_zoomDropdown.getItemCount(); i++) { String item = _zoomDropdown.getItemAt(i); try { if (Integer.parseInt(item) == zoomLevel) { _zoomDropdown.setSelectedIndex(i); break; } } catch (NumberFormatException nfe) {} } } _rebuilding = false; refreshDialog(); } /** * Update the visibility of the controls, and update the zoom dropdown based on the selected map source */ private void refreshDialog() { _mainPanel.setVisible(_useImageCheckbox.isSelected()); // Exit if we're in the middle of something if (_rebuilding) {return;} int currentZoom = 0; try { currentZoom = Integer.parseInt(_zoomDropdown.getSelectedItem().toString()); } catch (Exception nfe) {} // First time in, the dropdown might be empty but we still might have a zoom in the definition if (_zoomDropdown.getItemCount() == 0) { currentZoom = _imageDef.getZoom(); } // Get the extent of the track so we can work out how big the images are going to be for each zoom level final double xyExtent = Math.max(_track.getXRange().getRange(), _track.getYRange().getRange()); int zoomToSelect = -1; _rebuilding = true; _zoomDropdown.removeAllItems(); if (_useImageCheckbox.isSelected() && _mapSourceDropdown.getItemCount() > 0) { int currentSource = _mapSourceDropdown.getSelectedIndex(); for (int i=5; i<18; i++) { // How many pixels does this give? final int zoomFactor = 1 << i; final int pixCount = (int) (xyExtent * zoomFactor * 256); if (pixCount > 100 // less than this isn't worth it && pixCount < 4000 // don't want to run out of memory && isZoomAvailable(i, MapSourceLibrary.getSource(currentSource))) { _zoomDropdown.addItem("" + i); if (i == currentZoom) { zoomToSelect = _zoomDropdown.getItemCount() - 1; } } // else System.out.println("Not using zoom " + i + " because pixCount=" + pixCount + " and xyExtent=" + xyExtent); } } _zoomDropdown.setSelectedIndex(zoomToSelect); _rebuilding = false; _okButton.setEnabled(!_useImageCheckbox.isSelected() || (_zoomDropdown.getItemCount() > 0 && _zoomDropdown.getSelectedIndex() >= 0)); updateImagePreview(); } /** * @return true if it should be possible to use an image, false if no disk cache or cache empty */ public static boolean isImagePossible() { String path = Config.getConfigString(Config.KEY_DISK_CACHE); if (path != null && !path.equals("")) { File cacheDir = new File(path); if (cacheDir.exists() && cacheDir.isDirectory()) { // Check if there are any directories in the cache for (File subdir : cacheDir.listFiles()) { if (subdir.exists() && subdir.isDirectory()) { return true; } } } } return false; } /** * See if the requested zoom level is available * @param inZoom zoom level * @param inSource selected map source * @return true if there is a zoom directory for each of the source's layers */ private static boolean isZoomAvailable(int inZoom, MapSource inSource) { if (inSource == null) {return false;} String path = Config.getConfigString(Config.KEY_DISK_CACHE); if (path == null || path.equals("")) { return false; } File cacheDir = new File(path); if (!cacheDir.exists() || !cacheDir.isDirectory()) { return false; } // First layer File layer0 = new File(cacheDir, inSource.getSiteName(0) + inZoom); if (!layer0.exists() || !layer0.isDirectory() || !layer0.canRead()) { return false; } // Second layer, if any if (inSource.getNumLayers() > 1) { File layer1 = new File(cacheDir, inSource.getSiteName(1) + inZoom); if (!layer1.exists() || !layer1.isDirectory() || !layer1.canRead()) { return false; } } // must be ok return true; } /** * @return image definition object */ public ImageDefinition getImageDefinition() { return _imageDef; } /** * Make the dialog components to select the options * @return Component holding gui elements */ private Component makeDialogComponents() { JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); _useImageCheckbox = new JCheckBox(I18nManager.getText("dialog.baseimage.useimage")); _useImageCheckbox.setBorder(BorderFactory.createEmptyBorder(4, 4, 6, 4)); _useImageCheckbox.setHorizontalAlignment(JLabel.CENTER); _useImageCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { refreshDialog(); } }); panel.add(_useImageCheckbox, BorderLayout.NORTH); // Outer panel with the grid and the map preview _mainPanel = new JPanel(); _mainPanel.setLayout(new BorderLayout(1, 10)); // Central stuff with labels and dropdowns JPanel controlsPanel = new JPanel(); controlsPanel.setLayout(new GridLayout(0, 2, 10, 4)); // map source JLabel sourceLabel = new JLabel(I18nManager.getText("dialog.baseimage.mapsource") + ": "); sourceLabel.setHorizontalAlignment(JLabel.RIGHT); controlsPanel.add(sourceLabel); _mapSourceDropdown = new JComboBox<String>(); _mapSourceDropdown.addItem("name of map source"); // Add listener to dropdown to change zoom levels _mapSourceDropdown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { refreshDialog(); } }); controlsPanel.add(_mapSourceDropdown); // zoom level JLabel zoomLabel = new JLabel(I18nManager.getText("dialog.baseimage.zoom") + ": "); zoomLabel.setHorizontalAlignment(JLabel.RIGHT); controlsPanel.add(zoomLabel); _zoomDropdown = new JComboBox<String>(); // Add action listener to enable ok button when zoom changed _zoomDropdown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (_zoomDropdown.getSelectedIndex() >= 0) { _okButton.setEnabled(true); updateImagePreview(); } } }); controlsPanel.add(_zoomDropdown); _mainPanel.add(controlsPanel, BorderLayout.NORTH); JPanel imagePanel = new JPanel(); imagePanel.setLayout(new BorderLayout(10, 1)); // image preview _previewPanel = new ImagePreviewPanel(); imagePanel.add(_previewPanel, BorderLayout.CENTER); // Label panel on right JPanel labelPanel = new JPanel(); labelPanel.setLayout(new BorderLayout()); JPanel downloadPanel = new JPanel(); downloadPanel.setLayout(new BorderLayout(4, 4)); _downloadTilesButton = new JButton(I18nManager.getText("button.load")); _downloadTilesButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { downloadRemainingTiles(); } }); _downloadTilesButton.setVisible(false); downloadPanel.add(_downloadTilesButton, BorderLayout.NORTH); _progressBar = new JProgressBar(); _progressBar.setIndeterminate(true); _progressBar.setVisible(false); downloadPanel.add(_progressBar, BorderLayout.SOUTH); labelPanel.add(downloadPanel, BorderLayout.NORTH); JPanel labelGridPanel = new JPanel(); labelGridPanel.setLayout(new GridLayout(0, 2, 10, 4)); labelGridPanel.add(new JLabel(I18nManager.getText("dialog.baseimage.tiles") + ": ")); _tilesFoundLabel = new JLabel("11 / 11"); labelGridPanel.add(_tilesFoundLabel); labelGridPanel.add(new JLabel(I18nManager.getText("dialog.baseimage.size") + ": ")); _imageSizeLabel = new JLabel("1430"); labelGridPanel.add(_imageSizeLabel); labelGridPanel.add(new JLabel(" ")); // just for spacing labelPanel.add(labelGridPanel, BorderLayout.SOUTH); imagePanel.add(labelPanel, BorderLayout.EAST); _mainPanel.add(imagePanel, BorderLayout.CENTER); panel.add(_mainPanel, BorderLayout.CENTER); // OK, Cancel buttons JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); _okButton = new JButton(I18nManager.getText("button.ok")); _okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Check values, maybe don't want to exit if (!_useImageCheckbox.isSelected() || (_mapSourceDropdown.getSelectedIndex() >= 0 && _zoomDropdown.getSelectedIndex() >= 0)) { storeValues(); _dialog.dispose(); } } }); buttonPanel.add(_okButton); JButton cancelButton = new JButton(I18nManager.getText("button.cancel")); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _dialog.dispose(); } }); buttonPanel.add(cancelButton); panel.add(buttonPanel, BorderLayout.SOUTH); // Listener to close dialog if escape pressed KeyAdapter closer = new KeyAdapter() { public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { _dialog.dispose(); } } }; _useImageCheckbox.addKeyListener(closer); _mapSourceDropdown.addKeyListener(closer); _zoomDropdown.addKeyListener(closer); _okButton.addKeyListener(closer); cancelButton.addKeyListener(closer); return panel; } /** * Use the selected settings to make a preview image and (asynchronously) update the preview panel */ private void updateImagePreview() { // Clear labels _downloadTilesButton.setVisible(false); _tilesFoundLabel.setText(""); _imageSizeLabel.setText(""); if (_useImageCheckbox.isSelected() && _mapSourceDropdown.getSelectedIndex() >= 0 && _zoomDropdown.getItemCount() > 0 && _zoomDropdown.getSelectedIndex() >= 0) { _previewPanel.startLoading(); // Launch a separate thread to create an image and pass it to the preview panel new Thread(this).start(); } else { // clear preview _previewPanel.setImage(null); } } /** * Store the selected details in the variables */ private void storeValues() { // Store values of controls in variables _imageDef.setUseImage(_useImageCheckbox.isSelected(), _mapSourceDropdown.getSelectedIndex(), getSelectedZoomLevel()); // Inform parent that details have changed _parent.baseImageChanged(); } /** * Run method for separate thread. Uses the current dialog parameters * to trigger a call to the Grouter, and pass the image to the preview panel */ public void run() { // Remember the current dropdown indices, so we know whether they've changed or not final int mapIndex = _mapSourceDropdown.getSelectedIndex(); final int zoomIndex = _zoomDropdown.getSelectedIndex(); if (!_useImageCheckbox.isSelected() || mapIndex < 0 || zoomIndex < 0) {return;} // Get the map source from the index MapSource mapSource = MapSourceLibrary.getSource(mapIndex); // Use the Grouter to create an image (slow, blocks thread) GroutedImage groutedImage = _grouter.createMapImage(_track, mapSource, getSelectedZoomLevel()); // If the dialog hasn't changed, pass the generated image to the preview panel if (_useImageCheckbox.isSelected() && _mapSourceDropdown.getSelectedIndex() == mapIndex && _zoomDropdown.getSelectedIndex() == zoomIndex && groutedImage != null) { _previewPanel.setImage(groutedImage); final int numTilesRemaining = groutedImage.getNumTilesTotal() - groutedImage.getNumTilesUsed(); final boolean offerDownload = numTilesRemaining > 0 && numTilesRemaining < 50 && Config.getConfigBoolean(Config.KEY_ONLINE_MODE); // Set values of labels _downloadTilesButton.setVisible(offerDownload); _downloadTilesButton.setEnabled(offerDownload); _tilesFoundLabel.setText(groutedImage.getNumTilesUsed() + " / " + groutedImage.getNumTilesTotal()); if (groutedImage.getImageSize() > 0) { _imageSizeLabel.setText("" + groutedImage.getImageSize()); } else { _imageSizeLabel.setText(""); } } else { _previewPanel.setImage(null); // Clear labels _downloadTilesButton.setVisible(false); _tilesFoundLabel.setText(""); _imageSizeLabel.setText(""); } } /** * @return zoom level selected in the dropdown */ private int getSelectedZoomLevel() { int zoomLevel = 0; try { zoomLevel = Integer.parseInt(_zoomDropdown.getSelectedItem().toString()); } catch (NullPointerException npe) {} catch (Exception e) { System.err.println("Exception: " + e.getClass().getName() + " : " + e.getMessage()); } return zoomLevel; } /** * @return true if any map data has been found for the image */ public boolean getFoundData() { return _imageDef.getUseImage() && _imageDef.getZoom() > 0 && _previewPanel != null && _previewPanel.getTilesFound(); } /** * @return true if selected zoom is valid for the current track (based only on pixel size) */ public boolean isSelectedZoomValid() { final double xyExtent = Math.max(_track.getXRange().getRange(), _track.getYRange().getRange()); // How many pixels does this give? final int zoomFactor = 1 << _imageDef.getZoom(); final int pixCount = (int) (xyExtent * zoomFactor * 256); return (pixCount > 100 // less than this isn't worth it && pixCount < 4000); // don't want to run out of memory } /** * @return the map grouter for retrieval of generated image */ public MapGrouter getGrouter() { return _grouter; } /** * method triggered by "download" button, to asynchronously download the missing tiles */ private void downloadRemainingTiles() { _downloadTilesButton.setEnabled(false); new Thread(new Runnable() { public void run() { _progressBar.setVisible(true); // Use a grouter to get all tiles from the TileManager, including downloading MapGrouter grouter = new MapGrouter(); final int mapIndex = _mapSourceDropdown.getSelectedIndex(); if (!_useImageCheckbox.isSelected() || mapIndex < 0) {return;} MapSource mapSource = MapSourceLibrary.getSource(mapIndex); grouter.createMapImage(_track, mapSource, getSelectedZoomLevel(), true); _progressBar.setVisible(false); // And then refresh the dialog _grouter.clearMapImage(); updateImagePreview(); } }).start(); } }
gpl-2.0
thaidn/securegram
android/src/main/java/org/telegram/android/query/BotQuery.java
9675
/* * This is the source code of Telegram for Android v. 2.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2015. */ package org.telegram.android.query; import org.telegram.android.AndroidUtilities; import org.telegram.android.MessagesStorage; import org.telegram.android.NotificationCenter; import org.telegram.messenger.ByteBufferDesc; import org.telegram.messenger.FileLog; import org.telegram.messenger.TLRPC; import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLitePreparedStatement; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; public class BotQuery { private static HashMap<Integer, TLRPC.BotInfo> botInfos = new HashMap<>(); private static HashMap<Long, TLRPC.Message> botKeyboards = new HashMap<>(); private static HashMap<Integer, Long> botKeyboardsByMids = new HashMap<>(); public static void cleanup() { botInfos.clear(); } public static void clearBotKeyboard(final long did, final ArrayList<Integer> messages) { AndroidUtilities.runOnUIThread( new Runnable() { @Override public void run() { if (messages != null) { for (int a = 0; a < messages.size(); a++) { Long did = botKeyboardsByMids.get(messages.get(a)); if (did != null) { botKeyboards.remove(did); botKeyboardsByMids.remove(messages.get(a)); NotificationCenter.getInstance() .postNotificationName(NotificationCenter.botKeyboardDidLoaded, null, did); } } } else { botKeyboards.remove(did); NotificationCenter.getInstance() .postNotificationName(NotificationCenter.botKeyboardDidLoaded, null, did); } } }); } public static void loadBotKeyboard(final long did) { TLRPC.Message keyboard = botKeyboards.get(did); if (keyboard != null) { NotificationCenter.getInstance() .postNotificationName(NotificationCenter.botKeyboardDidLoaded, keyboard, did); return; } MessagesStorage.getInstance() .getStorageQueue() .postRunnable( new Runnable() { @Override public void run() { try { TLRPC.Message botKeyboard = null; SQLiteCursor cursor = MessagesStorage.getInstance() .getDatabase() .queryFinalized( String.format( Locale.US, "SELECT info FROM bot_keyboard WHERE uid = %d", did)); if (cursor.next()) { ByteBufferDesc data; if (!cursor.isNull(0)) { data = MessagesStorage.getInstance() .getBuffersStorage() .getFreeBuffer(cursor.byteArrayLength(0)); if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) { botKeyboard = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); } MessagesStorage.getInstance().getBuffersStorage().reuseFreeBuffer(data); } } cursor.dispose(); if (botKeyboard != null) { final TLRPC.Message botKeyboardFinal = botKeyboard; AndroidUtilities.runOnUIThread( new Runnable() { @Override public void run() { NotificationCenter.getInstance() .postNotificationName( NotificationCenter.botKeyboardDidLoaded, botKeyboardFinal, did); } }); } } catch (Exception e) { FileLog.e("tmessages", e); } } }); } public static void loadBotInfo(final int uid, boolean cache, final int classGuid) { if (cache) { TLRPC.BotInfo botInfo = botInfos.get(uid); if (botInfo != null) { NotificationCenter.getInstance() .postNotificationName(NotificationCenter.botInfoDidLoaded, botInfo, classGuid); return; } } MessagesStorage.getInstance() .getStorageQueue() .postRunnable( new Runnable() { @Override public void run() { try { TLRPC.BotInfo botInfo = null; SQLiteCursor cursor = MessagesStorage.getInstance() .getDatabase() .queryFinalized( String.format( Locale.US, "SELECT info FROM bot_info WHERE uid = %d", uid)); if (cursor.next()) { ByteBufferDesc data; if (!cursor.isNull(0)) { data = MessagesStorage.getInstance() .getBuffersStorage() .getFreeBuffer(cursor.byteArrayLength(0)); if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) { botInfo = TLRPC.BotInfo.TLdeserialize(data, data.readInt32(false), false); } MessagesStorage.getInstance().getBuffersStorage().reuseFreeBuffer(data); } } cursor.dispose(); if (botInfo != null) { final TLRPC.BotInfo botInfoFinal = botInfo; AndroidUtilities.runOnUIThread( new Runnable() { @Override public void run() { NotificationCenter.getInstance() .postNotificationName( NotificationCenter.botInfoDidLoaded, botInfoFinal, classGuid); } }); } } catch (Exception e) { FileLog.e("tmessages", e); } } }); } public static void putBotKeyboard(final long did, final TLRPC.Message message) { if (message == null) { return; } try { int mid = 0; SQLiteCursor cursor = MessagesStorage.getInstance() .getDatabase() .queryFinalized( String.format(Locale.US, "SELECT mid FROM bot_keyboard WHERE uid = %d", did)); if (cursor.next()) { mid = cursor.intValue(0); } cursor.dispose(); if (mid >= message.id) { return; } SQLitePreparedStatement state = MessagesStorage.getInstance() .getDatabase() .executeFast("REPLACE INTO bot_keyboard VALUES(?, ?, ?)"); state.requery(); ByteBufferDesc data = MessagesStorage.getInstance().getBuffersStorage().getFreeBuffer(message.getObjectSize()); message.serializeToStream(data); state.bindLong(1, did); state.bindInteger(2, message.id); state.bindByteBuffer(3, data.buffer); state.step(); MessagesStorage.getInstance().getBuffersStorage().reuseFreeBuffer(data); state.dispose(); AndroidUtilities.runOnUIThread( new Runnable() { @Override public void run() { TLRPC.Message old = botKeyboards.put(did, message); if (old != null) { botKeyboardsByMids.remove(old.id); } botKeyboardsByMids.put(message.id, did); NotificationCenter.getInstance() .postNotificationName(NotificationCenter.botKeyboardDidLoaded, message, did); } }); } catch (Exception e) { FileLog.e("tmessages", e); } } public static void putBotInfo(final TLRPC.BotInfo botInfo) { if (botInfo == null || botInfo instanceof TLRPC.TL_botInfoEmpty) { return; } botInfos.put(botInfo.user_id, botInfo); MessagesStorage.getInstance() .getStorageQueue() .postRunnable( new Runnable() { @Override public void run() { try { SQLitePreparedStatement state = MessagesStorage.getInstance() .getDatabase() .executeFast("REPLACE INTO bot_info(uid, info) VALUES(?, ?)"); state.requery(); ByteBufferDesc data = MessagesStorage.getInstance() .getBuffersStorage() .getFreeBuffer(botInfo.getObjectSize()); botInfo.serializeToStream(data); state.bindInteger(1, botInfo.user_id); state.bindByteBuffer(2, data.buffer); state.step(); MessagesStorage.getInstance().getBuffersStorage().reuseFreeBuffer(data); state.dispose(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); } }
gpl-2.0
Googlelover1234/mStats
src/mstats/cmds/Stats.java
1411
package mstats.cmds; import mstats.managers.ConfigManager; import mstats.managers.Manager; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Stats implements CommandExecutor { @SuppressWarnings("deprecation") @Override public boolean onCommand(CommandSender sender, Command cmd, String arg2, String[] args) { if (!(sender instanceof Player)) { return true; } Player p = (Player) sender; if (cmd.getName().equalsIgnoreCase("stats")) { if (args.length < 1) { Manager.getInstance().messageStats(p, p); return true; } else if (args.length == 1) { Player target = Bukkit.getPlayer(args[0]); if (target == null) { if (ConfigManager.getInstance().getConfig() .get("users." + args[0]) == null) { p.sendMessage(ChatColor.RED + "Sorry, that player doesn't seem to exist."); p.sendMessage(ChatColor.RED + "*NOTE* CaSe SeNsItIvE"); return true; } else { OfflinePlayer op = Bukkit.getOfflinePlayer(args[0]); Manager.getInstance().messageStats(op, p); return true; } } else { Manager.getInstance().messageStats(target, p); return true; } } else return false; } return true; } }
gpl-2.0
evgs/Bombus
src/login/SASLAuth.java
13092
/* * SASLAuth.java * * Created on 8.06.2006, 23:34 * * Copyright (c) 2005-2007, Eugene Stahov (evgs), http://bombus-im.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * You can also redistribute and/or modify this program under the * terms of the Psi License, specified in the accompanied COPYING * file, as published by the Psi Project; either dated January 1st, * 2005, 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 library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package login; import Client.Account; import Client.Config; import com.alsutton.jabber.JabberBlockListener; import com.alsutton.jabber.JabberDataBlock; import com.alsutton.jabber.JabberStream; import com.alsutton.jabber.datablocks.Iq; import com.ssttr.crypto.MD5; import java.io.IOException; import locale.SR; import util.strconv; import xmpp.XmppError; //#if SASL_XGOOGLETOKEN import java.io.InputStream; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; //#endif /** * * @author evgs */ public class SASLAuth implements JabberBlockListener{ private LoginListener listener; private Account account; private JabberStream stream; /** Creates a new instance of SASLAuth */ public SASLAuth(Account account, LoginListener listener, JabberStream stream) { this.listener=listener; this.account=account; this.stream=stream; if (stream!=null) stream.addBlockListener(this); //listener.loginMessage(SR.MS_SASL_STREAM); } //#if SASL_XGOOGLETOKEN private String token; public void setToken(String token) { this.token=token; } //#endif public int blockArrived(JabberDataBlock data) { //System.out.println(data.toString()); if (data.getTagName().equals("stream:features")) { //#if ZLIB JabberDataBlock compr=data.getChildBlock("compression"); if (compr!=null && account.useCompression()) { if (compr.getChildBlockByText("zlib")!=null) { // negotiating compression JabberDataBlock askCompr=new JabberDataBlock("compress", null, null); askCompr.setNameSpace("http://jabber.org/protocol/compress"); askCompr.addChild("method", "zlib"); stream.send(askCompr); listener.loginMessage(SR.MS_ZLIB); return JabberBlockListener.BLOCK_PROCESSED; } } //#endif JabberDataBlock mech=data.getChildBlock("mechanisms"); if (mech!=null) { // first stream - step 1. selecting authentication mechanism //common body JabberDataBlock auth=new JabberDataBlock("auth", null,null); auth.setNameSpace("urn:ietf:params:xml:ns:xmpp-sasl"); // DIGEST-MD5 mechanism if (mech.getChildBlockByText("DIGEST-MD5")!=null) { auth.setAttribute("mechanism", "DIGEST-MD5"); //System.out.println(auth.toString()); stream.send(auth); listener.loginMessage(SR.MS_AUTH); return JabberBlockListener.BLOCK_PROCESSED; } //#if SASL_XGOOGLETOKEN // X-GOOGLE-TOKEN mechanism if (mech.getChildBlockByText("X-GOOGLE-TOKEN")!=null && token!=null) { auth.setAttribute("mechanism", "X-GOOGLE-TOKEN"); auth.setText(token); //System.out.println(auth.toString()); stream.send(auth); listener.loginMessage(SR.MS_AUTH); return JabberBlockListener.BLOCK_PROCESSED; } //#endif if (mech.getChildBlockByText("PLAIN")!=null) { if (!account.getPlainAuth()) { listener.loginFailed("SASL: Plain auth required"); return JabberBlockListener.NO_MORE_BLOCKS; } auth.setAttribute("mechanism", "PLAIN"); String plain= strconv.unicodeToUTF(account.getBareJid()) +(char)0x00 +strconv.unicodeToUTF(account.getUserName()) +(char)0x00 +strconv.unicodeToUTF(account.getPassword()); auth.setText(strconv.toBase64(plain)); stream.send(auth); listener.loginMessage(SR.MS_AUTH); return JabberBlockListener.BLOCK_PROCESSED; } // no more method found listener.loginFailed("SASL: Unknown mechanisms"); return JabberBlockListener.NO_MORE_BLOCKS; } //SASL mechanisms // second stream - step 1. binding resource else if (data.getChildBlock("bind")!=null) { JabberDataBlock bindIq=new Iq(null, Iq.TYPE_SET, "bind"); JabberDataBlock bind=bindIq.addChildNs("bind", "urn:ietf:params:xml:ns:xmpp-bind"); bind.addChild("resource", account.getResource()); stream.send(bindIq); listener.loginMessage(SR.MS_RESOURCE_BINDING); return JabberBlockListener.BLOCK_PROCESSED; } //#ifdef NON_SASL_AUTH if (data.findNamespace("auth", "http://jabber.org/features/iq-auth")!=null) { new NonSASLAuth(account, listener, stream); return JabberBlockListener.NO_MORE_BLOCKS; } //#endif //fallback if no known authentication methods were found listener.loginFailed("No known authentication methods"); return JabberBlockListener.NO_MORE_BLOCKS; } else if (data.getTagName().equals("challenge")) { // first stream - step 2,3. reaction to challenges String challenge=decodeBase64(data.getText()); //System.out.println(challenge); JabberDataBlock resp=new JabberDataBlock("response", null, null); resp.setNameSpace("urn:ietf:params:xml:ns:xmpp-sasl"); int nonceIndex=challenge.indexOf("nonce="); // first stream - step 2. generating DIGEST-MD5 response due to challenge if (nonceIndex>=0) { nonceIndex+=7; String nonce=challenge.substring(nonceIndex, challenge.indexOf('\"', nonceIndex)); String cnonce=Config.getInstance().getStringProperty("Bombus-CNonce", "123456789abcd"); resp.setText(responseMd5Digest( strconv.unicodeToUTF(account.getUserName()), strconv.unicodeToUTF(account.getPassword()), account.getServer(), "xmpp/"+account.getServer(), nonce, cnonce )); //System.out.println(resp.toString()); } // first stream - step 3. sending second empty response due to second challenge //if (challenge.startsWith("rspauth")) {} stream.send(resp); return JabberBlockListener.BLOCK_PROCESSED; } //#if ZLIB else if ( data.getTagName().equals("compressed")) { stream.setZlibCompression(); try { stream.initiateStream(); } catch (IOException ex) { } return JabberBlockListener.NO_MORE_BLOCKS; } //#endif else if ( data.getTagName().equals("failure")) { // first stream - step 4a. not authorized listener.loginFailed( XmppError.decodeSaslError(data).toString() ); } else if ( data.getTagName().equals("success")) { // first stream - step 4b. success. try { stream.initiateStream(); } catch (IOException ex) { } return JabberBlockListener.NO_MORE_BLOCKS; // at first stream } if (data instanceof Iq) { if (data.getTypeAttribute().equals("result")) { // second stream - step 2. resource binded - opening session if (data.getAttribute("id").equals("bind")) { String myJid=data.getChildBlock("bind").getChildBlockText("jid"); listener.bindResource(myJid); JabberDataBlock session=new Iq(null, Iq.TYPE_SET, "sess"); session.addChildNs("session", "urn:ietf:params:xml:ns:xmpp-session"); stream.send(session); listener.loginMessage(SR.MS_SESSION); return JabberBlockListener.BLOCK_PROCESSED; // second stream - step 3. session opened - reporting success login } else if (data.getAttribute("id").equals("sess")) { listener.loginSuccess(); return JabberBlockListener.NO_MORE_BLOCKS; //return JabberBlockListener.BLOCK_PROCESSED; } } } return JabberBlockListener.BLOCK_REJECTED; } private String decodeBase64(String src) { int len=0; int ibuf=1; StringBuffer out=new StringBuffer(); for (int i=0; i<src.length(); i++) { int nextChar = src.charAt(i); int base64=-1; if (nextChar>'A'-1 && nextChar<'Z'+1) base64=nextChar-'A'; else if (nextChar>'a'-1 && nextChar<'z'+1) base64=nextChar+26-'a'; else if (nextChar>'0'-1 && nextChar<'9'+1) base64=nextChar+52-'0'; else if (nextChar=='+') base64=62; else if (nextChar=='/') base64=63; else if (nextChar=='=') {base64=0; len++;} else if (nextChar=='<') break; if (base64>=0) ibuf=(ibuf<<6)+base64; if (ibuf>=0x01000000){ out.append( (char)((ibuf>>16) &0xff) ); if (len<2) out.append( (char)((ibuf>>8) &0xff) ); if (len==0) out.append( (char)(ibuf &0xff) ); //len+=3; ibuf=1; } } return out.toString(); } /** * This routine generates MD5-DIGEST response via SASL specification * @param user * @param pass * @param realm * @param digest_uri * @param nonce * @param cnonce * @return */ private String responseMd5Digest(String user, String pass, String realm, String digestUri, String nonce, String cnonce) { MD5 hUserRealmPass=new MD5(); hUserRealmPass.init(); hUserRealmPass.updateASCII(user); hUserRealmPass.update((byte)':'); hUserRealmPass.updateASCII(realm); hUserRealmPass.update((byte)':'); hUserRealmPass.updateASCII(pass); hUserRealmPass.finish(); MD5 hA1=new MD5(); hA1.init(); hA1.update(hUserRealmPass.getDigestBits()); hA1.update((byte)':'); hA1.updateASCII(nonce); hA1.update((byte)':'); hA1.updateASCII(cnonce); hA1.finish(); MD5 hA2=new MD5(); hA2.init(); hA2.updateASCII("AUTHENTICATE:"); hA2.updateASCII(digestUri); hA2.finish(); MD5 hResp=new MD5(); hResp.init(); hResp.updateASCII(hA1.getDigestHex()); hResp.update((byte)':'); hResp.updateASCII(nonce); hResp.updateASCII(":00000001:"); hResp.updateASCII(cnonce); hResp.updateASCII(":auth:"); hResp.updateASCII(hA2.getDigestHex()); hResp.finish(); String out = "username=\""+user+"\",realm=\""+realm+"\"," + "nonce=\""+nonce+"\",nc=00000001,cnonce=\""+cnonce+"\"," + "qop=auth,digest-uri=\""+digestUri+"\"," + "response=\""+hResp.getDigestHex()+"\",charset=utf-8"; String resp = strconv.toBase64(out); //System.out.println(decodeBase64(resp)); return resp; } }
gpl-2.0
meier/opensm-client-server
src/main/java/gov/llnl/lc/infiniband/opensm/plugin/data/OMS_CollectionChangeListener.java
2994
/************************************************************ * Copyright (c) 2015, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Timothy Meier, meier3@llnl.gov, All rights reserved. * LLNL-CODE-673346 * * This file is part of the OpenSM Monitoring Service (OMS) package. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (as published by * the Free Software Foundation) version 2.1 dated February 1999. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * OUR NOTICE AND TERMS AND CONDITIONS OF THE GNU GENERAL PUBLIC LICENSE * * Our Preamble Notice * * A. This notice is required to be provided under our contract with the U.S. * Department of Energy (DOE). This work was produced at the Lawrence Livermore * National Laboratory under Contract No. DE-AC52-07NA27344 with the DOE. * * B. Neither the United States Government nor Lawrence Livermore National * Security, LLC nor any of their employees, makes any warranty, express or * implied, or assumes any liability or responsibility for the accuracy, * completeness, or usefulness of any information, apparatus, product, or * process disclosed, or represents that its use would not infringe privately- * owned rights. * * C. Also, reference herein to any specific commercial products, process, or * services by trade name, trademark, manufacturer or otherwise does not * necessarily constitute or imply its endorsement, recommendation, or favoring * by the United States Government or Lawrence Livermore National Security, * LLC. The views and opinions of authors expressed herein do not necessarily * state or reflect those of the United States Government or Lawrence Livermore * National Security, LLC, and shall not be used for advertising or product * endorsement purposes. * * file: OMS_CollectionChangeListener.java * * Created on: Nov 19, 2014 * Author: meier3 ********************************************************************/ package gov.llnl.lc.infiniband.opensm.plugin.data; public interface OMS_CollectionChangeListener { public void osmCollectionUpdate(OMS_Collection omsHistory, OpenSmMonitorService oms, boolean recordingNow) throws Exception; }
gpl-2.0
AlexFinney/IslandSurvival
src/main/java/com/skeeter144/blocks/BlockMithrilOre.java
258
package com.skeeter144.blocks; import net.minecraft.block.Block; import net.minecraft.block.material.Material; public class BlockMithrilOre extends Block{ protected BlockMithrilOre(Material material) { super(material); this.setHardness(50.0f); } }
gpl-2.0
itplanter/itpManager2
src/Selecters.java
4738
import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.util.Observable; import java.util.Observer; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.SwingConstants; import javax.swing.WindowConstants; public class Selecters extends JPanel { private static final long serialVersionUID = 1L; /** * @param args */ public static void main(String[] args) { JFrame frame = new JFrame(); Selecters gjp=new Selecters(); frame.getContentPane().add(gjp); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); } private Object selectButton; // Observer‚ð’ljÁ‚·‚é void addObserver(Observer o) { //observableMan.deleteObserver(defaultO);// ‘O‚ɐݒ肳‚ꂽObserver‚ðíœ‚·‚éB //observableMan.deleteObservers(); observableMan.addObserver(o); } // Observer‚ðÝ’è‚·‚é // ˆÈ‘O‚ɒljÁ‚³‚ꂽObserver‚Í‘S‚Ä”jŠü‚³‚ê‚é void setObserver(Observer o) { observableMan.deleteObservers(); observableMan.addObserver(o); } public void reListPlanter() { ps.reListPlanter(); } // Observer‚ðíœ void deleteObserver(Observer o) { observableMan.deleteObserver(o); } public void actionPerformed(ActionEvent arg0) { if(arg0.equals(selectButton)==false) return; JButton btn = (JButton)arg0.getSource(); if(btn.equals(selectButton)){ // System.out.println("addTimeButton"); } message ="Ž„‚ÍSelectors class‚Å‚·B"+btn.getText()+"‚ª‰Ÿ‚³‚ê‚Ü‚µ‚½B!!!!!!"+"btn.getName():"+btn.getName()+" +btn.getText():"+btn.getText(); if(btn.getText().contains("‚±‚̃vƒ‰ƒ“ƒ^[‚ð‘I‘ð‚·‚é")==true){ int pno=Integer.parseInt(btn.getText().replaceAll("[^0-9]",""));// //int pno=Integer.valueOf(btn.getText()); ITPlanterClass.setCurrentPlanterNo(pno);// Œ»Ý‚̃vƒ‰ƒ“ƒ^[‚̔ԍ† ITPlanterClass.setCurrentPlanterClass(ITPlanterClass.getPlanterList().get(pno));// Œ»Ý‚̃vƒ‰ƒ“ƒ^[‚̃Nƒ‰ƒX // save cam no int camno=cs.getCamNo(); Files.setCamNo(camno); } // observableMan.setMessage(message); // ŠÏŽ@ŽÒ‘Sˆõ‚É’Ê’m observableMan.notifyObservers(); } private ObservableMan observableMan=null; private String message=""; //private Observer defaultO=null; /** * ŠÏŽ@ŽÒ‚ðŠÏŽ@‚·‚élAB * */ static class ObserverA implements Observer { /* (”ñ Javadoc) * @see java.util.Observer#update(java.util.Observable, java.lang.Object) */ @Override public void update(Observable o, Object arg) { String str = (String) arg; System.out.println("Ž„‚ÍSelectors class‚Å‚·BŠÏŽ@‘Ώۂ̒ʒm‚ðŒŸ’m‚µ‚½‚æB" + str); } } CameraSelecter cs=null; /** * This is the default constructor */ public Selecters() { super(); initialize(); } private PlanterSelecter ps=null; private JPanel base=null; /** * This method initializes this * * @return void */ private void initialize() { GridBagLayout gridbag = new GridBagLayout(); base=new JPanel(gridbag); //base.setPreferredSize(new Dimension(640,400)); base.setBackground(new Color(250,251,245)); // ƒJƒƒ‰‘I‘ð cs=new CameraSelecter(); cs.setPreferredSize(new Dimension(640,120)); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth= 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 0, 0, 0); gridbag.setConstraints(cs, constraints); base.add(cs); // separator JSeparator vspr=new JSeparator(SwingConstants.HORIZONTAL); vspr.setPreferredSize(new Dimension(640,10)); GridBagConstraints constraints2 = new GridBagConstraints(); constraints2.gridx = 0; constraints2.gridy = 1; constraints2.gridwidth= 1; constraints2.gridheight = 1; constraints2.insets = new Insets(0, 0, 0, 0); gridbag.setConstraints(vspr, constraints2); base.add(vspr); // ƒvƒ‰ƒ“ƒ^[‘I‘ð ps=new PlanterSelecter(); ps.setPreferredSize(new Dimension(640,180)); GridBagConstraints constraints3 = new GridBagConstraints(); constraints3.gridx = 0; constraints3.gridy = 2; constraints3.gridwidth= 1; constraints3.gridheight = 1; constraints3.insets = new Insets(0, 0, 0, 0); gridbag.setConstraints(ps, constraints3); base.add(ps); this.add(base); this.setBackground(new Color(250,251,245)); // ŠÏŽ@‚³‚ê‚él‚𐶐¬ observableMan = new ObservableMan(); // ƒfƒtƒHƒ‹ƒg‚ÌŠÏŽ@ŽÒ‚ð’ljÁ Observer defaultO=new PlanterSetting.ObserverA(); observableMan.addObserver(defaultO); } }
gpl-2.0
TechMiX/DANTE-simulator
src/es/ladyr/dante/node/deactivationAndReactivation/NodesDeactivator.java
6017
/* * Copyright 2007 Luis Rodero Merino. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Luis Rodero Merino if you need additional information or * have any questions. Contact information: * Email: lrodero AT gsyc.es * Webpage: http://gsyc.es/~lrodero * Phone: +34 91 488 8107; Fax: +34 91 +34 91 664 7494 * Postal address: Desp. 121, Departamental II, * Universidad Rey Juan Carlos * C/Tulipán s/n, 28933, Móstoles, Spain * */ package es.ladyr.dante.node.deactivationAndReactivation; import java.util.HashMap; import es.ladyr.dante.node.DanteNode; import es.ladyr.dante.run.DanteConf; import es.ladyr.simulator.Event; import es.ladyr.simulator.EventHandler; import es.ladyr.simulator.SimulationComponent; import es.ladyr.simulator.Simulator; import es.ladyr.util.math.ExponentialDistribution; public class NodesDeactivator implements EventHandler, SimulationComponent { private ExponentialDistribution activeTimeDistrb = null; private boolean simulationOver = false; private boolean mustWork = true; private HashMap nodesEvents = new HashMap(); private static NodesDeactivator _instance = new NodesDeactivator(); public static NodesDeactivator getInstance(){ return _instance; } public void processEvent(Event event) { if(!mustWork) throw new Error("Should not receive events in Nodes Deactivator, no distributions for times were set"); if(simulationOver) return; if(!(event instanceof DeactivateNodeEvent)) // Unknown event type throw new Error("Unknown event in NodesDeactivator???"); DanteNode nodeToDeactivate = ((DeactivateNodeEvent)event).getNode(); nodesEvents.remove(nodeToDeactivate); if(!nodeToDeactivate.nodeIsActive()) throw new Error("Trying to deactivate a not active node"); nodeToDeactivate.deactiveNode(); NodesReactivator.getInstance().scheduleNodeReactivation(nodeToDeactivate); return; } public void beforeStart() { simulationOver = false; nodesEvents.clear(); double actMeanTime = DanteConf.getPresentSimConf().actMeanTime(); activeTimeDistrb = (actMeanTime > 0) ? new ExponentialDistribution(actMeanTime) : null; mustWork = (activeTimeDistrb != null); if(!mustWork) return; // Programming deactivation or activation time for all nodes DanteNode[] allNodes = (DanteNode[])DanteNode.allNodesInSystem().toArray(new DanteNode[0]); for(int nodeIndex = 0; nodeIndex < allNodes.length; nodeIndex++){ DanteNode node = allNodes[nodeIndex]; if(node.nodeIsActive()) scheduleNodeDeactivation(node); } } public void scheduleNodeDeactivation(DanteNode node){ if(!node.nodeIsActive()) throw new Error("Node is not active"); if(simulationOver) return; if(!mustWork) return; long activeTime = activeTimeDistrb.nextLong(); long timeToNextEvent = Simulator.simulator().getSimulationTime() + activeTime; DeactivateNodeEvent deactivateNodeEvent = new DeactivateNodeEvent(timeToNextEvent, this, node); nodesEvents.put(node, deactivateNodeEvent); Simulator.simulator().registerEvent(deactivateNodeEvent); } public void afterStop() { simulationOver = true; } // If some node has been attacked, its corresponding deactivation event (if any) must be suspended public void nodeWasAttacked(DanteNode node){ if(!mustWork) return; if(simulationOver) return; Event event = (Event)nodesEvents.remove(node); if(event == null) return; Simulator.simulator().suspendEvent((DeactivateNodeEvent)event); } // After some node recovers from an attack, it must be planned again its deactivation public void nodeWasRecovered(DanteNode node){ if(!mustWork) return; if(!simulationOver) return; Event event = (Event)nodesEvents.remove(node); if(event != null) throw new Error("There was a pending event of a recovered node"); scheduleNodeDeactivation(node); } } class DeactivateNodeEvent extends Event { public final static int DEACTIVATION_EVENT_PRIORITY = Event.MINIMUM_EVENT_PRIORITY; protected DanteNode node = null; public DeactivateNodeEvent(long time, EventHandler eventHandler,DanteNode node) { super(time, eventHandler, DEACTIVATION_EVENT_PRIORITY); this.node = node; } public DanteNode getNode(){ return node; } }
gpl-2.0
NSIS-Dev/nsl-assembler
src/nsl/instruction/ReadRegDWORDInstruction.java
1922
/* * ReadRegDWORDInstruction.java */ package nsl.instruction; import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; import nsl.*; import nsl.expression.*; /** * @author Stuart */ public class ReadRegDWORDInstruction extends AssembleExpression { public static final String name = "ReadRegDWORD"; private final Expression rootKey; private final Expression subKey; private final Expression keyName; /** * Class constructor. * @param returns the number of values to return */ public ReadRegDWORDInstruction(int returns) { if (PageExInfo.in()) throw new NslContextException(EnumSet.of(NslContext.Section, NslContext.Function, NslContext.Global), name); if (returns != 1) throw new NslReturnValueException(name, 1); ArrayList<Expression> paramsList = Expression.matchList(); if (paramsList.size() != 3) throw new NslArgumentException(name, 3); this.rootKey = paramsList.get(0); if (!ExpressionType.isString(this.rootKey)) throw new NslArgumentException(name, 1, ExpressionType.String); this.subKey = paramsList.get(1); this.keyName = paramsList.get(2); } /** * Assembles the source code. */ @Override public void assemble() throws IOException { throw new UnsupportedOperationException("Not supported."); } /** * Assembles the source code. * @param var the variable to assign the value to */ @Override public void assemble(Register var) throws IOException { AssembleExpression.assembleIfRequired(this.rootKey); Expression varOrSubKey = AssembleExpression.getRegisterOrExpression(this.subKey); Expression varOrKeyName = AssembleExpression.getRegisterOrExpression(this.keyName); ScriptParser.writeLine(name + " " + var + " " + this.rootKey + " " + varOrSubKey + " " + varOrKeyName); varOrSubKey.setInUse(false); varOrKeyName.setInUse(false); } }
gpl-2.0
hflynn/openmicroscopy
components/insight/SRC/org/openmicroscopy/shoola/agents/fsimporter/chooser/FileSelectionTable.java
20808
/* * org.openmicroscopy.shoola.fsimporter.chooser.FileSelectionTable * *------------------------------------------------------------------------------ * Copyright (C) 2006-2007 University of Dundee. All rights reserved. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * *------------------------------------------------------------------------------ */ package org.openmicroscopy.shoola.agents.fsimporter.chooser; //Java imports import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; //Third-party libraries import info.clearthought.layout.TableLayout; //Application-internal dependencies import org.openmicroscopy.shoola.agents.fsimporter.view.Importer; import org.openmicroscopy.shoola.agents.util.browser.DataNode; import org.openmicroscopy.shoola.env.data.model.ImportableFile; import org.openmicroscopy.shoola.util.ui.IconManager; import org.openmicroscopy.shoola.util.ui.MultilineHeaderSelectionRenderer; import org.openmicroscopy.shoola.util.ui.TooltipTableHeader; import pojos.DatasetData; import pojos.GroupData; /** * Component displaying the files to import. * * @author Jean-Marie Burel &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a> * @author Donald MacDonald &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:donald@lifesci.dundee.ac.uk">donald@lifesci.dundee.ac.uk</a> * @version 3.0 * <small> * (<b>Internal version:</b> $Revision: $Date: $) * </small> * @since 3.0-Beta4 */ class FileSelectionTable extends JPanel implements ActionListener { /** Bound property indicating to add files to the queue. */ static final String ADD_PROPERTY = "add"; /** Bound property indicating to remove files to the queue. */ static final String REMOVE_PROPERTY = "remove"; /** Action command ID to add a field to the result table. */ private static final int ADD = 0; /** Action command ID to remove a field from the result table. */ private static final int REMOVE = 1; /** Action command ID to remove all fields from the result table. */ private static final int REMOVE_ALL = 2; /** The index of the file's name column. */ static final int FILE_INDEX = 0; /** The index of the file's length column. */ static final int SIZE_INDEX = 1; /** * The index of the column indicating the container where files will * be imported */ static final int CONTAINER_INDEX = 2; /** * The index of the column indicating the group where to import data. */ static final int GROUP_INDEX = 3; /** * The index of the column indicating to use the folder * as a dataset. */ static final int FOLDER_AS_CONTAINER_INDEX = 4; /** The columns of the table. */ private static final Vector<String> COLUMNS; /** The columns of the table w/o group information */ private static final Vector<String> COLUMNS_NO_GROUP; /** The tool-tip of the columns. */ private static final String[] COLUMNS_TOOLTIP; /** The tool-tip of the columns. */ private static final String[] COLUMNS_NO_GROUP_TOOLTIP; /** The text displayed to use the folder as container. */ private static final String FAD_TEXT = "Folder as\nDataset"; /** Indicate to select the files. */ private static final String FILE_TEXT = "File or\nFolder"; /** The text indicating the size of the file or folder. */ private static final String SIZE_TEXT = "Size"; /** * The text displaying where to import the data to if importing * to Project/Dataset or Screen. */ private static final String CONTAINER_PROJECT_TEXT = "Project/Dataset\nor Screen"; /** The group where the files will be imported.*/ private static final String GROUP_TEXT = "Group"; static { int n = 5; COLUMNS = new Vector<String>(n); COLUMNS.add(FILE_TEXT); COLUMNS.add(SIZE_TEXT); COLUMNS.add(CONTAINER_PROJECT_TEXT); COLUMNS.add(GROUP_TEXT); COLUMNS.add(FAD_TEXT); COLUMNS_TOOLTIP = new String[n]; COLUMNS_TOOLTIP[FILE_INDEX] = "File or Folder to import."; COLUMNS_TOOLTIP[SIZE_INDEX] = "Size of File or Folder."; COLUMNS_TOOLTIP[CONTAINER_INDEX] = "The container where to import the data."; COLUMNS_TOOLTIP[GROUP_INDEX] = "The group where to import data."; COLUMNS_TOOLTIP[FOLDER_AS_CONTAINER_INDEX] = "Convert the folder as dataset."; COLUMNS_NO_GROUP = new Vector<String>(n-1); COLUMNS_NO_GROUP.add(FILE_TEXT); COLUMNS_NO_GROUP.add(SIZE_TEXT); COLUMNS_NO_GROUP.add(CONTAINER_PROJECT_TEXT); COLUMNS_NO_GROUP.add(FAD_TEXT); COLUMNS_NO_GROUP_TOOLTIP = new String[n-1]; COLUMNS_NO_GROUP_TOOLTIP[FILE_INDEX] = COLUMNS_TOOLTIP[FILE_INDEX]; COLUMNS_NO_GROUP_TOOLTIP[SIZE_INDEX] = COLUMNS_TOOLTIP[SIZE_INDEX]; COLUMNS_NO_GROUP_TOOLTIP[CONTAINER_INDEX] = COLUMNS_TOOLTIP[CONTAINER_INDEX]; COLUMNS_NO_GROUP_TOOLTIP[FOLDER_AS_CONTAINER_INDEX-1] = COLUMNS_TOOLTIP[FOLDER_AS_CONTAINER_INDEX]; } /** The button to move an item from the remaining items to current items. */ private JButton addButton; /** The button to move an item from the current items to remaining items. */ private JButton removeButton; /** The button to move all items to the remaining items. */ private JButton removeAllButton; /** The table displaying the collection to files to import. */ private JTable table; /** Reference to the model. */ private ImportDialog model; /** The key listener added to the queue. */ private KeyAdapter keyListener; /** The columns selected for the display.*/ private Vector<String> selectedColumns; /** Formats the table model. */ private void formatTableModel() { TableColumnModel tcm = table.getColumnModel(); TableColumn tc = tcm.getColumn(FILE_INDEX); tc.setCellRenderer(new FileTableRenderer()); tc = tcm.getColumn(CONTAINER_INDEX); tc.setCellRenderer(new FileTableRenderer()); String[] tips; boolean single = model.isSingleGroup(); if (!single) { tc = tcm.getColumn(GROUP_INDEX); tc.setCellRenderer(new FileTableRenderer()); tc = tcm.getColumn(FOLDER_AS_CONTAINER_INDEX); tc.setCellEditor(table.getDefaultEditor(Boolean.class)); tc.setCellRenderer(table.getDefaultRenderer(Boolean.class)); tc.setResizable(false); tips = COLUMNS_TOOLTIP; } else { tc = tcm.getColumn(FOLDER_AS_CONTAINER_INDEX-1); tc.setCellEditor(table.getDefaultEditor(Boolean.class)); tc.setCellRenderer(table.getDefaultRenderer(Boolean.class)); tc.setResizable(false); tips = COLUMNS_NO_GROUP_TOOLTIP; } TooltipTableHeader header = new TooltipTableHeader(tcm, tips); table.setTableHeader(header); tcm.getColumn(SIZE_INDEX).setHeaderRenderer( new MultilineHeaderSelectionRenderer()); tc = tcm.getColumn(FILE_INDEX); tc.setHeaderRenderer(new MultilineHeaderSelectionRenderer()); tc = tcm.getColumn(CONTAINER_INDEX); tc.setHeaderRenderer(new MultilineHeaderSelectionRenderer()); if (!single) { tc = tcm.getColumn(GROUP_INDEX); tc.setHeaderRenderer(new MultilineHeaderSelectionRenderer()); tc = tcm.getColumn(FOLDER_AS_CONTAINER_INDEX); tc.setHeaderRenderer(new MultilineHeaderSelectionRenderer()); } else { tc = tcm.getColumn(FOLDER_AS_CONTAINER_INDEX-1); tc.setHeaderRenderer(new MultilineHeaderSelectionRenderer()); } table.getTableHeader().resizeAndRepaint(); table.getTableHeader().setReorderingAllowed(false); } /** Initializes the components composing the display. */ private void initComponents() { IconManager icons = IconManager.getInstance(); addButton = new JButton(icons.getIcon(IconManager.RIGHT_ARROW)); addButton.setToolTipText("Add the selected files to the queue."); addButton.setEnabled(false); removeButton = new JButton(icons.getIcon(IconManager.LEFT_ARROW)); removeButton.setToolTipText("Remove the selected files " + "from the queue."); removeButton.setEnabled(false); removeAllButton = new JButton( icons.getIcon(IconManager.DOUBLE_LEFT_ARROW)); removeAllButton.setToolTipText("Remove all files from the queue."); removeAllButton.setEnabled(false); addButton.setActionCommand(""+ADD); addButton.addActionListener(this); removeButton.setActionCommand(""+REMOVE); removeButton.addActionListener(this); removeAllButton.setActionCommand(""+REMOVE_ALL); removeAllButton.addActionListener(this); if (model.isSingleGroup()) selectedColumns = COLUMNS_NO_GROUP; else selectedColumns = COLUMNS; table = new JTable(new FileTableModel(selectedColumns)); table.getTableHeader().setReorderingAllowed(false); keyListener = new KeyAdapter() { /** * Adds the files to the import queue. * @see KeyListener#keyPressed(KeyEvent) */ public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (table.isFocusOwner()) removeSelectedFiles(); } } }; table.addKeyListener(keyListener); formatTableModel(); } /** * Returns the component hosting the collection of files to import. * * @return See above. */ private JPanel buildTablePane() { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS)); p.add(Box.createVerticalStrut(5)); p.add(new JScrollPane(table)); return p; } /** Builds and lays out the UI. */ private void builGUI() { double[][] size = {{TableLayout.FILL}, {TableLayout.FILL}}; setLayout(new TableLayout(size)); add(buildTablePane(), "0, 0"); } /** Removes the selected files from the queue. */ private void removeSelectedFiles() { table.removeKeyListener(keyListener); int[] rows = table.getSelectedRows(); if (rows == null || rows.length == 0) return; DefaultTableModel dtm = (DefaultTableModel) table.getModel(); Vector v = dtm.getDataVector(); List<Object> indexes = new ArrayList<Object>(); for (int i = 0; i < table.getRowCount(); i++) { if (table.isRowSelected(i)) indexes.add(v.get(i)); } v.removeAll(indexes); dtm.setDataVector(v, selectedColumns); table.clearSelection(); formatTableModel(); table.repaint(); table.addKeyListener(keyListener); int n = table.getRowCount(); firePropertyChange(REMOVE_PROPERTY, n-1, n); enabledControl(table.getRowCount() > 0); model.onSelectionChanged(); } /** * Returns <code>true</code> if the file can be added to the queue again, * <code>false</code> otherwise. * * @param queue The list of files already in the queue. * @param f The file to check. * @param gID The id of the group to import the image into. * @return See above. */ private boolean allowAddToQueue(List<FileElement> queue, File f, long gID) { if (f == null) return false; if (queue == null) return true; Iterator<FileElement> i = queue.iterator(); FileElement fe; String name = f.getAbsolutePath(); while (i.hasNext()) { fe = i.next(); if (fe.getFile().getAbsolutePath().equals(name) && fe.getGroup().getId() == gID) return false; } return true; } /** * Sets the enabled flag of the buttons. * * @param value The value to set. */ private void enabledControl(boolean value) { removeButton.setEnabled(value); removeAllButton.setEnabled(value); } /** * Creates a new instance. * * @param model The model. */ FileSelectionTable(ImportDialog model) { if (model == null) throw new IllegalArgumentException("No model."); this.model = model; initComponents(); builGUI(); } /** * Builds and lays out the controls. * * @return See above. */ JPanel buildControls() { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); p.add(addButton); p.add(Box.createVerticalStrut(5)); p.add(removeButton); p.add(Box.createVerticalStrut(5)); p.add(removeAllButton); return p; } /** * Returns <code>true</code> if there are files to import, * <code>false</code> otherwise. * * @return See above. */ boolean hasFilesToImport() { return table.getRowCount() > 0; } /** * Returns the collection of files to import. * * @return See above. */ List<ImportableFile> getFilesToImport() { List<ImportableFile> files = new ArrayList<ImportableFile>(); int n = table.getRowCount(); DefaultTableModel dtm = (DefaultTableModel) table.getModel(); FileElement element; File file; ImportableFile importable; boolean single = model.isSingleGroup(); boolean b; DataNodeElement dne; DatasetData dataset; for (int i = 0; i < n; i++) { element = (FileElement) dtm.getValueAt(i, FILE_INDEX); dne = (DataNodeElement) dtm.getValueAt(i, CONTAINER_INDEX); file = element.getFile(); dataset = dne.getLocation(); if (single) { b = Boolean.valueOf((Boolean) dtm.getValueAt(i, FOLDER_AS_CONTAINER_INDEX-1)); importable = new ImportableFile(file, b); } else { b = Boolean.valueOf((Boolean) dtm.getValueAt(i, FOLDER_AS_CONTAINER_INDEX)); importable = new ImportableFile(file, b); } if (b) dataset = null; importable.setLocation(dne.getParent(), dataset); importable.setRefNode(dne.getRefNode()); importable.setGroup(element.getGroup()); files.add(importable); } return files; } /** * Resets the components. * * @param value The value to set. */ void reset(boolean value) { allowAddition(value); if (model.isSingleGroup()) selectedColumns = COLUMNS_NO_GROUP; else selectedColumns = COLUMNS; table.setModel(new FileTableModel(selectedColumns)); formatTableModel(); } /** * Sets the enable flag of the {@link #addButton}. * * @param value The value to set. */ void allowAddition(boolean value) { addButton.setEnabled(value); } /** Removes all the files from the queue. */ void removeAllFiles() { int n = table.getRowCount(); if (n == 0) return; DefaultTableModel dtm = (DefaultTableModel) table.getModel(); dtm.getDataVector().clear(); table.clearSelection(); formatTableModel(); table.repaint(); firePropertyChange(REMOVE_PROPERTY, -1, 0); enabledControl(false); model.onSelectionChanged(); } /** * Adds the collection of files to the queue. * * @param files The files to add. * @param fad Pass <code>true</code> to indicate to mark the folder as * a dataset, <code>false</code> otherwise. * @param group The group where to import the file. */ void addFiles(List<File> files, boolean fad, GroupData group) { if (files == null || files.size() == 0) return; enabledControl(true); File f; DefaultTableModel dtm = (DefaultTableModel) table.getModel(); //Check if the file has already List<FileElement> inQueue = new ArrayList<FileElement>(); FileElement element; for (int i = 0; i < table.getRowCount(); i++) { element = (FileElement) dtm.getValueAt(i, FILE_INDEX); inQueue.add(element); } Iterator<File> i = files.iterator(); boolean multi = !model.isSingleGroup(); DataNode node = model.getImportLocation(); if (node.isDefaultNode() && model.getType() != Importer.SCREEN_TYPE) node.setParent(model.getParentImportLocation()); String value = null; boolean v = false; long gID = group.getId(); while (i.hasNext()) { f = i.next(); if (allowAddToQueue(inQueue, f, gID)) { element = new FileElement(f, model.getType(), group); element.setName(f.getName()); value = null; v = false; if (f.isDirectory()) { value = f.getName(); v = fad; if (model.getType() == Importer.SCREEN_TYPE) { value = null; } } else { if (model.isParentFolderAsDataset()) { value = f.getParentFile().getName(); v = true; element.setToggleContainer(v); } } if (multi) { dtm.addRow(new Object[] {element, element.getFileLengthAsString(), new DataNodeElement(node, value), group.getName(), Boolean.valueOf(v)}); } else { dtm.addRow(new Object[] {element, element.getFileLengthAsString(), new DataNodeElement(node, value), Boolean.valueOf(v)}); } } } model.onSelectionChanged(); } /** * Returns the size of the files to import. * * @return See above. */ long getSizeFilesInQueue() { DefaultTableModel dtm = (DefaultTableModel) table.getModel(); FileElement element; long size = 0; for (int i = 0; i < table.getRowCount(); i++) { element = (FileElement) dtm.getValueAt(i, FILE_INDEX); size += element.getFileLength(); } return size; } /** * Marks the folder as a dataset. * * @param fad Pass <code>true</code> to mark the folder as a dataset, * <code>false</code> otherwise. */ void markFolderAsDataset(boolean fad) { int n = table.getRowCount(); if (n == 0) return; DefaultTableModel dtm = (DefaultTableModel) table.getModel(); FileElement element; int j = 0; if (model.isSingleGroup()) j = -1; for (int i = 0; i < n; i++) { element = (FileElement) dtm.getValueAt(i, FILE_INDEX); if (element.isDirectory()) dtm.setValueAt(fad, i, FOLDER_AS_CONTAINER_INDEX+j); } } /** Resets the names of all selected files. */ void resetFilesName() { int n = table.getRowCount(); if (n == 0) return; DefaultTableModel model = (DefaultTableModel) table.getModel(); FileElement element; for (int i = 0; i < n; i++) { element = (FileElement) model.getValueAt(i, FILE_INDEX); element.setName(element.getFile().getAbsolutePath()); } table.repaint(); } /** Applies the partial names to all the files. */ void applyToAll() { int n = table.getRowCount(); DefaultTableModel dtm = (DefaultTableModel) table.getModel(); FileElement element; for (int i = 0; i < n; i++) { element = (FileElement) dtm.getValueAt(i, FILE_INDEX); if (!element.isDirectory()) { element.setName(model.getDisplayedFileName( element.getFile().getAbsolutePath())); } } table.repaint(); } /** * Adds or removes files from the import queue. * @see ActionListener#actionPerformed(ActionEvent) */ public void actionPerformed(ActionEvent evt) { int index = Integer.parseInt(evt.getActionCommand()); switch (index) { case ADD: firePropertyChange(ADD_PROPERTY, Boolean.valueOf(false), Boolean.valueOf(true)); break; case REMOVE: removeSelectedFiles(); break; case REMOVE_ALL: removeAllFiles(); } } /** Inner class so that some cells cannot be edited. */ class FileTableModel extends DefaultTableModel { /** * Creates a new instance. * * @param columns The columns to display. */ FileTableModel(Vector<String> columns) { super(null, columns); } /** * Overridden so that some cells cannot be edited. * @see DefaultTableModel#isCellEditable(int, int) */ public boolean isCellEditable(int row, int column) { FileElement f = (FileElement) getValueAt(row, FILE_INDEX); switch (column) { case FILE_INDEX: case CONTAINER_INDEX: case SIZE_INDEX: return false; case FOLDER_AS_CONTAINER_INDEX: return false; } return false; } /** * Overridden to set the name of the image to save. * @see DefaultTableModel#setValueAt(Object, int, int) */ public void setValueAt(Object value, int row, int col) { if (value instanceof Boolean) { if (col == FOLDER_AS_CONTAINER_INDEX) { DataNodeElement element = (DataNodeElement) getValueAt(row, CONTAINER_INDEX); FileElement f = (FileElement) getValueAt(row, FILE_INDEX); if (f.isDirectory() || (!f.isDirectory() && f.isToggleContainer())) { boolean b = ((Boolean) value).booleanValue(); if (b) element.setName(f.getName()); else element.setName(null); } } super.setValueAt(value, row, col); } fireTableCellUpdated(row, col); } } }
gpl-2.0
wmaier/rparse
src/de/tuebingen/rparse/parser/PriorityAgendaFibonacci.java
4573
/******************************************************************************* * File PriorityAgendaFibonacci.java * * Authors: * Wolfgang Maier * * Copyright: * Wolfgang Maier, 2011 * * This file is part of rparse, see <www.wolfgang-maier.net/rparse>. * * rparse 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. * * rparse 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.tuebingen.rparse.parser; import java.util.BitSet; import java.util.HashMap; import java.util.Map; import org.jgrapht.util.FibonacciHeap; import org.jgrapht.util.FibonacciHeapNode; import de.tuebingen.rparse.misc.Numberer; /** * Priority queue (Nederhof 2003) with some extras. Implemented on basis of the fibonacci heap implementation of the * JGraphT library. * * @author wmaier */ public class PriorityAgendaFibonacci extends FibonacciHeap<CYKItem> implements PriorityAgenda { // The node store helps us finding the right heap node private NodeStore chart; // watches the agenda grow private long agendaMaxSize; // checks how often we perform the add operation private long addCount; // A numberer protected Numberer nb; /** * Constructor. * * @param nb * A numberer */ public PriorityAgendaFibonacci(Numberer nb) { agendaMaxSize = 0; addCount = 0; chart = new NodeStore(10000); this.nb = nb; } @Override public void clear() { super.clear(); agendaMaxSize = 0; addCount = 0; } @Override public CYKItem poll() { // get the heap node FibonacciHeapNode<CYKItem> heapNode = super.removeMin(); // get its data field CYKItem it = heapNode.getData(); // remove it from our "chart" chart.get(it.pl).remove(it.rvec); if (chart.get(it.pl).isEmpty()) { chart.remove(it.pl); } return it; } @Override public void push(CYKItem it) { FibonacciHeapNode<CYKItem> onode = chart.getNode(it); if (onode != null) { CYKItem oit = onode.getData(); // update? also update backpointers if (oit.iscore + oit.oscore > it.iscore + it.oscore) { super.decreaseKey(onode, it.iscore + it.oscore); oit.olc = it.olc; oit.orc = it.orc; oit.iscore = it.iscore; oit.oscore = it.oscore; oit.iscf = it.iscf; oit.start = it.start; oit.end = it.end; } } else { // create a new heap node for the item FibonacciHeapNode<CYKItem> heapNode = new FibonacciHeapNode<CYKItem>( it); // make sure we find it later if (!chart.containsKey(it.pl)) chart.put(it.pl, new HashMap<BitSet, FibonacciHeapNode<CYKItem>>()); chart.get(it.pl).put(it.rvec, heapNode); // put it on the heap super.insert(heapNode, it.iscore + it.oscore); ++addCount; } agendaMaxSize = Math.max(super.size(), agendaMaxSize); } @Override public String getStats() { return "Agenda stats: Max size: " + agendaMaxSize + ", adds: " + addCount; } /* * Keeps track of heap nodes */ private class NodeStore extends HashMap<Integer, Map<BitSet, FibonacciHeapNode<CYKItem>>> { private static final long serialVersionUID = 1L; public NodeStore(int capacity) { super(capacity); } public FibonacciHeapNode<CYKItem> getNode(CYKItem it) { if (super.containsKey(it.pl) && super.get(it.pl).containsKey(it.rvec)) return super.get(it.pl).get(it.rvec); return null; } } }
gpl-2.0
masreis/e-commerce-jee
src/main/java/net/marcoreis/ecommerce/webservice/UsuarioServiceREST.java
2775
package net.marcoreis.ecommerce.webservice; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.json.JSONObject; import net.marcoreis.ecommerce.entidades.Usuario; import net.marcoreis.ecommerce.service.UsuarioService; @Path("/usuarios") public class UsuarioServiceREST { protected static final Logger logger = Logger .getLogger(UsuarioServiceREST.class.getCanonicalName()); @Inject private UsuarioService usuarioService; @GET @Produces({ MediaType.APPLICATION_JSON }) @Path("/email/{email}") public Usuario buscarPeloEmail(@PathParam("email") String email) { return usuarioService.buscarPeloEmail(email); } @GET @Produces({ MediaType.APPLICATION_JSON }) @Path("/id/{id}") public Usuario buscarPeloId(@PathParam("id") String id) { return usuarioService.buscarPeloId(new Long(id)); } @GET @Produces(MediaType.APPLICATION_JSON) public Collection<Usuario> consultarTodos() { return usuarioService.consultarTodos(); } @POST @Consumes(MediaType.APPLICATION_JSON) public void inserir(String jsonS) { try { JSONObject json = new JSONObject(jsonS); String nome = json.getString("nome"); String email = json.getString("email"); Usuario usuario = new Usuario(); usuario.setNome(nome); usuario.setEmail(email); usuarioService.inserir(usuario); logger.info("JSON -> Objeto inserido com sucesso"); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage()); } } @PUT @Consumes(MediaType.APPLICATION_JSON) @Path("/{id}") public void atualizar(@PathParam("id") String id, String jsonS) { try { JSONObject json = new JSONObject(jsonS); String nome = json.getString("nome"); String email = json.getString("email"); Usuario usuario = new Usuario(); usuario.setNome(nome); usuario.setEmail(email); usuario.setId(Long.parseLong(id)); usuarioService.atualizar(usuario); logger.info("JSON -> Objeto inserido com sucesso"); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage()); } } @DELETE @Path("/{id}") public void removerPeloId(@PathParam("id") String id) { usuarioService.removerPeloId(id); } }
gpl-2.0
wjnudter/ll100
src/com/cmcc/attendance/exceptions/AfinalException.java
151
package com.cmcc.attendance.exceptions; public class AfinalException extends RuntimeException { private static final long serialVersionUID = 1L; }
gpl-2.0
camposer/curso_in_persistence
Ejercicio5/src/dao/PersonaDao.java
768
package dao; import java.util.List; import javax.persistence.Query; import model.Persona; @SuppressWarnings("unchecked") public class PersonaDao extends GenericDao<Persona, Integer>{ public PersonaDao() { this(true); } public PersonaDao(boolean autoCommit) { super(autoCommit); } public List<Persona> obtenerTodosOrdenadosPorNombreApellido() { return em.createQuery("SELECT p FROM Persona p " + "ORDER BY upper(p.nombre) ASC, upper(p.apellido) ASC") .getResultList(); } public List<Persona> obtenerTodosPorOrdenadorSerial(String serial) { Query q = em.createQuery("SELECT p FROM Persona p " + "JOIN p.ordenadores o WHERE o.serial LIKE :serial"); q.setParameter("serial", "%" + serial + "%"); return q.getResultList(); } }
gpl-2.0
yqoq/JS2013
2013.08.30.DI/src/main/java/my/app/MyApp.java
1493
package my.app; import my.app.db.DB; import sun.misc.Service; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Properties; public class MyApp { public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException { System.out.println("Hello World!!"); Properties properties = new Properties(); InputStream resourceAsStream = MyApp.class.getClassLoader().getResourceAsStream("app.properties"); properties.load(resourceAsStream); String dbName = properties.getProperty("my.app.db", "ERROR"); System.out.println(dbName); Class<DB> clazz = (Class<DB>) Class.forName(dbName); DB db = clazz.newInstance(); System.out.println("DB is: "+db.name()); Iterator<DB> providers = Service.providers(DB.class); while (providers.hasNext()) { DB db2 = providers.next(); System.out.println("Service name:"+db2.name()); } System.out.println(Service.providers(DB.class).next()); System.out.println(Service.providers(DB.class).next()); String myDb = properties.getProperty("my.db"); providers = Service.providers(DB.class); while (providers.hasNext()) { DB db2 = providers.next(); if (myDb.equals(db2.name())) { System.out.println("Use in my app:"+db2.name()); } } } }
gpl-2.0
zning1994/paper
数据库与飞机大战/名片管理系统/Card/src/com/manager/servlet/DepartmentAddServlet.java
3026
package com.manager.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.manager.dao.CompanyDao; import com.manager.dao.DepartmentDao; import com.manager.dao.impl.CompanyDaoImpl; import com.manager.dao.impl.DepartmentDaoImpl; import com.manager.entity.Company; import com.manager.entity.Department; public class DepartmentAddServlet extends HttpServlet { /** * Constructor of the object. */ public DepartmentAddServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8");// ÉèÖÃ×Ö·û¸ñʽ HttpSession session = request.getSession(); String companyName = request.getParameter("companyname"); String departmentName = request.getParameter("departmentname"); String departmentTel = request.getParameter("tel"); DepartmentDao dao = new DepartmentDaoImpl(); Department department = new Department(); CompanyDao cd = new CompanyDaoImpl(); int companyId = cd.findByName(companyName); department.setCompanyId(companyId); department.setDepartmentName(departmentName); department.setDepartmentTel(departmentTel); int i = dao.insert(department); System.out.println(i); String all = (String) session.getAttribute("all"); if(i>0) { if(all.equals("1")) response.sendRedirect("DepartmentSelectServlet.action?all=1"); else if(all.equals("0")) response.sendRedirect("DepartmentSelectServlet.action?all=0"); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
gpl-2.0
dynamo2/tianma
mycrm/src/main/java/org/lsmp/djep/djep/DiffRulesI.java
1413
/* @author rich * Created on 04-Jul-2003 */ package org.lsmp.djep.djep; import org.nfunk.jep.ASTFunNode; import org.nfunk.jep.Node; import org.nfunk.jep.ParseException; /****** Classes to implement the differentation rules **********/ /** * Holds a set of rules describing how to differentiate a function. Each * function to be differentiated should have a object which implements this * interface. * * @author R Morris Created on 18-Jun-2003 */ public interface DiffRulesI { /** * Returns the top node of of the derivative of this function wrt to * variable var. * * @param var * The name of variable to differentiate wrt to. * @param children * the arguments of the function * @param dchildren * the derivatives of each argument of the function. * @return top node of and expression tree for the derivative. * @throws ParseException * if there is some problem in compiling the derivative. */ public Node differentiate(ASTFunNode node, String var, Node[] children, Node[] dchildren, DJep djep) throws ParseException; /** * Returns a string representation of the rule. */ public String toString(); /** * Returns the name of the function. Used as index in hashtable and as way * of linking with standard JEP functions. You probably want to specify the * in the constructors. */ public String getName(); }
gpl-2.0
diegoheusser/cost-estimator
aplicacao/CostEstimator/src/java/br/udesc/ceavi/costestimator/dao/ator/AtorDAO.java
241
package br.udesc.ceavi.costestimator.dao.ator; import br.udesc.ceavi.costestimator.dao.core.DefaultDAO; import br.udesc.ceavi.costestimator.modelo.Ator; /** * * @author diego */ public interface AtorDAO extends DefaultDAO<Ator> { }
gpl-2.0
GenomicParisCentre/corsen
src/main/java/fr/ens/transcriptome/corsen/calc/CorsenResult.java
8774
/* * Corsen development code * * This code may be freely distributed and modified under the * terms of the GNU General Public Licence version 2 or later. This * should be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/licenses/gpl-2.0.txt * * Copyright for this code is held jointly by the microarray platform * of the École Normale Supérieure and the individual authors. * These should be listed in @author doc comments. * * For more information on the Corsen project and its aims, * or to join the Corsen google group, visit the home page * at: * * http://transcriptome.ens.fr/corsen * */ package fr.ens.transcriptome.corsen.calc; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Map; import fr.ens.transcriptome.corsen.Settings; import fr.ens.transcriptome.corsen.UpdateStatus; import fr.ens.transcriptome.corsen.model.Particle3D; import fr.ens.transcriptome.corsen.model.Particles3D; import fr.ens.transcriptome.corsen.model.Particles3DFilter; /** * This class define the result class. * @author Laurent Jourdren */ public class CorsenResult { private UpdateStatus updateStatus; private Settings settings; private File particlesAFile; private File particlesBFile; private File resultPath; private InputStream particlesAStream; private InputStream particlesBStream; private Particles3D particlesA; private Particles3D particlesB; private Particles3D particlesACuboids; private Particles3D particlesBCuboids; private Map<Particle3D, Distance> minDistances; private Map<Particle3D, Distance> maxDistances; private DistanceAnalyser minAnalyser; private DistanceAnalyser maxAnalyser; private Particles3DFilter particlesAFilter; private Particles3DFilter particlesBFilter; // // Getters // /** * Get the particlesA cuboids particles. * @return Returns the particlesACuboids */ public Particles3D getCuboidsParticlesA() { return particlesACuboids; } /** * Get the particlesB cuboids. * @return Returns the particlesBCuboids */ public Particles3D getCuboidsParticlesB() { return particlesBCuboids; } /** * Get the max distances. * @return Returns the maxDistances */ public Map<Particle3D, Distance> getMaxDistances() { return maxDistances; } /** * Get the particlesA particles. * @return Returns the particlesA */ public Particles3D getParticlesA() { return particlesA; } /** * Get the min distances. * @return Returns the minDistances */ public Map<Particle3D, Distance> getMinDistances() { return minDistances; } /** * Get the particles B. * @return Returns the particlesB */ public Particles3D getParticlesB() { return particlesB; } /** * Get the updateStatus. * @return Returns the updateStatus */ UpdateStatus getUpdateStatus() { return updateStatus; } /** * Get the particlesA file. * @return Returns the messengersFile */ public File getMessengersFile() { return particlesAFile; } /** * Get the particlesB file. * @return Returns the mitosFile */ public File getMitosFile() { return particlesBFile; } /** * Get the result path * @return a file object with the path of results */ public File getResultsPath() { return resultPath; } /** * Get the particlesA stream. * @return Returns the messengersFile */ InputStream getMessengersStream() { return particlesAStream; } /** * Get the particlesB file. * @return Returns the mitosFile */ InputStream getMitosStream() { return particlesBStream; } /** * Get the settings. * @return the settings */ Settings getSettings() { return this.settings; } /** * Get the analyser for max distances. * @return Returns the maxAnalyser */ public DistanceAnalyser getMaxAnalyser() { return maxAnalyser; } /** * Get the analyser for min distances. * @return Returns the minAnalyser */ public DistanceAnalyser getMinAnalyser() { return minAnalyser; } /** * Get the Particles3DFilter for particlesA * @return a Particles3DFilter */ public Particles3DFilter getParticlesAFilter() { return particlesAFilter; } /** * Get the Particles3DFilter for particlesB * @return a Particles3DFilter */ public Particles3DFilter getParticlesBFilter() { return particlesBFilter; } // // Setters // /** * Set the DistanceAnalyser for maximal. * @param maxAnalyser The maxAnalyser to set */ public void setMaxAnalyser(final DistanceAnalyser maxAnalyser) { this.maxAnalyser = maxAnalyser; } /** * Set the DistanceAnalyser for minimal. * @param minAnalyser The minAnalyser to set */ public void setMinAnalyser(final DistanceAnalyser minAnalyser) { this.minAnalyser = minAnalyser; } /** * Set the particlesA particles. * @param particlesA The particlesA to set */ void setParticlesA(final Particles3D particlesA) { this.particlesA = particlesA; } /** * Set the particlesB particles. * @param particlesB The particlesB to set */ void setParticlesB(final Particles3D particlesB) { this.particlesB = particlesB; } /** * Set the update status. * @param updateStatus The updateStatus to set */ public void setUpdateStatus(final UpdateStatus updateStatus) { this.updateStatus = updateStatus; } /** * Set the particlesB cuboids particles. * @param particles Particles to Set */ void setCuboidsParticlesB(final Particles3D particles) { this.particlesBCuboids = particles; } /** * Set the particlesA cuboids particles. * @param particles Particles to Set */ void setCuboidsParticlesA(final Particles3D particles) { this.particlesACuboids = particles; } /** * Set the maximal distances. * @param maxDistances The maxDistances to set */ void setMaxDistances(final Map<Particle3D, Distance> maxDistances) { this.maxDistances = maxDistances; } /** * Set the minimal distances. * @param minDistances The minDistances to set */ void setMinDistances(final Map<Particle3D, Distance> minDistances) { this.minDistances = minDistances; } /** * Set the Particles3DFilter for particles A * @param particlesAFilter the filter to set */ public void setParticlesAFilter(final Particles3DFilter particlesAFilter) { this.particlesAFilter = particlesAFilter; } /** * Set the Particles3DFilter for particles B * @param particlesBFilter the filter to set */ public void setParticlesBFilter(final Particles3DFilter particlesBFilter) { this.particlesBFilter = particlesBFilter; } // // Constructor // /** * Public constructor. * @param particlesBFile File of the particlesB particles * @param particlesAFile File of the particlesA particles * @param resultsPath path for results files * @param settings Setting of the computation * @param updateStatus The updateStatus * @throws FileNotFoundException if an error occurs while reading or writing * files */ public CorsenResult(final File particlesAFile, final File particlesBFile, final File resultsPath, final Settings settings, final UpdateStatus updateStatus) throws FileNotFoundException { this(particlesAFile, particlesBFile, new FileInputStream(particlesAFile), new FileInputStream(particlesBFile), resultsPath, settings, updateStatus); } /** * Public constructor. * @param particlesAFile File of the particlesA * @param particlesBFile File of the particlesB * @param particlesAStream Stream of the particlesA * @param particlesBStream Stream of the particlesB * @param resultsPath path for results files * @param settings Setting of the computation * @param updateStatus The updateStatus */ public CorsenResult(final File particlesAFile, final File particlesBFile, final InputStream particlesAStream, final InputStream particlesBStream, final File resultsPath, final Settings settings, final UpdateStatus updateStatus) { if (particlesBStream == null) throw new RuntimeException("Unable to find particles A file"); if (particlesAStream == null) throw new RuntimeException("Unable to find particles B file"); this.particlesBFile = particlesBFile; this.particlesAFile = particlesAFile; this.particlesBStream = particlesBStream; this.particlesAStream = particlesAStream; this.resultPath = resultsPath; this.settings = settings; setUpdateStatus(updateStatus); } }
gpl-2.0
manofsteel76667/Grobots_Java
src/simulation/GBSyphonState.java
1728
/******************************************************************************* * Copyright (c) 2002-2013 (c) Devon and Warren Schudy * Copyright (c) 2014 Devon and Warren Schudy, Mike Anderson *******************************************************************************/ package simulation; import sides.SyphonSpec; import support.GBMath; public class GBSyphonState { SyphonSpec spec; // orders double direction; double distance; double rate; double syphoned; // amount siphoned: for reporting to brains // public: public GBSyphonState(SyphonSpec spc) { spec = spc; } public double getMaxRate() { return spec.getPower(); } public double getMaxRange() { return spec.getRange(); } public double getDirection() { return direction; } public double getDistance() { return distance; } public double getRate() { return rate; } public double getSyphoned() { return syphoned; } public void setDistance(double dist) { distance = Math.max(dist, 0); } public void setDirection(double dir) { direction = dir; } public void setRate(double pwr) { rate = GBMath.clamp(pwr, -getMaxRate(), getMaxRate()); } public void reportUse(double pwr) { syphoned += pwr; } public void act(GBRobot robot, GBWorld world) { if (rate != 0) { double limit = getMaxRate() * robot.getShieldFraction(); // should maybe // diminish with // distance double actual = GBMath.clamp(rate, -limit, limit); GBObject shot = new GBSyphon( robot.getPosition().addPolar( Math.min(distance, robot.getRadius() + getMaxRange()), direction), actual, robot, this, spec.getHitsEnemies()); world.addObjectLater(shot); } syphoned = 0; } }
gpl-2.0
psychint/Gnome-OSRS-Client
src/Shader.java
141
import java.awt.image.DataBufferByte; //For custom shaders public abstract class Shader { public abstract void Apply(DataBufferByte db); }
gpl-2.0
matteomartelli/licknet
src/licknet/lick/LickGraphScoreComparator.java
1306
/* * Copyright (C) 2015 Matteo Martelli matteomartelli3@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 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 licknet.lick; import java.util.Comparator; /** * * @author Matteo Martelli matteomartelli3@gmail.com */ /* Compare the score of the licks in an ArrayList for descending order sorting */ public class LickGraphScoreComparator implements Comparator<LickGraphScore>{ @Override public int compare(LickGraphScore lgs1, LickGraphScore lgs2) { float s1 = lgs1.getScore(); float s2 = lgs2.getScore(); if (s2 > s1) return 1; else if (s2 < s1) return -1; else return 0; } }
gpl-2.0
yhnbgfd/GZB-WapFast
src/util/RandomNumber.java
230
package util; import java.util.Random; public class RandomNumber { public int RandomNumbers(int i){ Random random = new Random(); int x = (int)Math.pow(10,i-1) + random.nextInt(9*(int)Math.pow(10,i-1)-1); return x; } }
gpl-2.0
animesks/projects
Non_Academic/FileTrackingSystem_2012/WebApp/src/in/ac/iiitdmj/fts/core/system/Tracker.java
3727
package in.ac.iiitdmj.fts.core.system; import in.ac.iiitdmj.fts.persistence.UserDAO; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Transient; /** * Class to represent an edge in the file path through which a file travels * @author animeshsi */ @Entity(name="trackers") public class Tracker { private long id; private String fromDesignation; private String toDesignation; /** * the date when the file was sent by fromDesignation to toDesignation */ private Date sentDate; /** * the date when the file was received by toDesignation from fromDesignation */ private Date receiveDate; /** * default constructor - DO NOT USE */ public Tracker() { this(null, null, null, null); } /** * parameterized constructor * @param fromDesignation * @param toDesignation * @param sentDate * @param receiveDate */ public Tracker(String fromDesignation, String toDesignation, Date sentDate, Date receiveDate) { super(); this.id = -1L; this.fromDesignation = fromDesignation; this.toDesignation = toDesignation; this.sentDate = sentDate; this.receiveDate = receiveDate; } /** * @return the id */ @Id @GeneratedValue(strategy=GenerationType.AUTO) public long getId() { return id; } /** * @param id the id to set */ public void setId(long id) { this.id = id; } /** * @return the fromDesignation */ @Column(nullable=false) public String getFromDesignation() { return fromDesignation; } /** * @return */ @Transient public String getFromDesignationName() { return UserDAO.getDesignationNameFromCode(fromDesignation); } /** * @param fromDesignation the fromDesignation to set */ public void setFromDesignation(String fromDesignation) { this.fromDesignation = fromDesignation; } /** * @return the toDesignation */ @Column(nullable=false) public String getToDesignation() { return toDesignation; } /** * @return */ @Transient public String getToDesignationName() { return UserDAO.getDesignationNameFromCode(toDesignation); } /** * @param toUID the toUID to set */ public void setToDesignation(String toDesignation) { this.toDesignation = toDesignation; } /** * @return the sentDate */ @Column(nullable=false) public Date getSentDate() { return sentDate; } /** * @return */ @Transient public String getFormattedSentDate() { return FTSUtil.getFormattedDateAndTime(sentDate); } /** * @param sentDate the sentDate to set */ public void setSentDate(Date sentDate) { this.sentDate = sentDate; } /** * @return the receiveDate */ @Column(nullable=true) public Date getReceiveDate() { return receiveDate; } /** * @return */ @Transient public String getFormattedReceiveDate() { return FTSUtil.getFormattedDateAndTime(receiveDate); } /** * @param receiveDate the receiveDate to set */ public void setReceiveDate(Date receiveDate) { this.receiveDate = receiveDate; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Tracker [id=" + id + ", fromDesignation=" + fromDesignation + ", toDesignation=" + toDesignation + ", sentDate=" + FTSUtil.getFormattedTimeAndDate(sentDate) + ", receiveDate=" + FTSUtil.getFormattedTimeAndDate(receiveDate) + "]"; } // public String getFromUserId() { // return null; // } // // public String getToUserId() { // return null; // } // // public Date getReceiveDate() { // return null; // } // // public File getFile() { // return null; // } }
gpl-2.0
vishwaAbhinav/OpenNMS
opennms-webapp/src/main/java/org/opennms/web/admin/nodeManagement/GetNodesServlet.java
5777
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.web.admin.nodeManagement; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.opennms.core.utils.DBUtils; import org.opennms.netmgt.config.DataSourceFactory; /** * A servlet that handles querying the database for node, interface, service * combinations * * @author <A HREF="mailto:jason@opennms.org">Jason Johns </A> * @author <A HREF="http://www.opennms.org/">OpenNMS </A> */ public class GetNodesServlet extends HttpServlet { private static final long serialVersionUID = 9083494959783285766L; // @ipv6 The regex in this statement is not IPv6-clean private static final String INTERFACE_QUERY = "SELECT nodeid, ipaddr, isManaged FROM ipinterface WHERE ismanaged in ('M','A','U','F') AND ipaddr <> '0.0.0.0' ORDER BY nodeid, case when (ipaddr ~ E'^([0-9]{1,3}\\.){3}[0-9]{1,3}$') then inet(ipaddr) else null end, ipaddr"; private static final String SERVICE_QUERY = "SELECT ifservices.serviceid, servicename, status FROM ifservices, service WHERE nodeid=? AND ipaddr=? AND status in ('A','U','F', 'S', 'R') AND ifservices.serviceid = service.serviceid ORDER BY servicename"; /** * <p>init</p> * * @throws javax.servlet.ServletException if any. */ public void init() throws ServletException { try { DataSourceFactory.init(); } catch (Throwable e) { } } /** {@inheritDoc} */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession user = request.getSession(true); try { user.setAttribute("listAll.manage.jsp", getAllNodes(user)); } catch (SQLException e) { throw new ServletException(e); } // forward the request for proper display RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/admin/manage.jsp"); dispatcher.forward(request, response); } /** */ private List<ManagedInterface> getAllNodes(HttpSession userSession) throws SQLException { Connection connection = null; List<ManagedInterface> allNodes = new ArrayList<ManagedInterface>(); int lineCount = 0; final DBUtils d = new DBUtils(getClass()); try { connection = DataSourceFactory.getInstance().getConnection(); d.watch(connection); PreparedStatement ifaceStmt = connection.prepareStatement(INTERFACE_QUERY); d.watch(ifaceStmt); ResultSet ifaceResults = ifaceStmt.executeQuery(); d.watch(ifaceResults); if (ifaceResults != null) { while (ifaceResults.next()) { lineCount++; ManagedInterface newInterface = new ManagedInterface(); allNodes.add(newInterface); newInterface.setNodeid(ifaceResults.getInt(1)); newInterface.setAddress(ifaceResults.getString(2)); newInterface.setStatus(ifaceResults.getString(3)); PreparedStatement svcStmt = connection.prepareStatement(SERVICE_QUERY); d.watch(svcStmt); svcStmt.setInt(1, newInterface.getNodeid()); svcStmt.setString(2, newInterface.getAddress()); ResultSet svcResults = svcStmt.executeQuery(); d.watch(svcResults); if (svcResults != null) { while (svcResults.next()) { lineCount++; ManagedService newService = new ManagedService(); newService.setId(svcResults.getInt(1)); newService.setName(svcResults.getString(2)); newService.setStatus(svcResults.getString(3)); newInterface.addService(newService); } } } } userSession.setAttribute("lineItems.manage.jsp", new Integer(lineCount)); } finally { d.cleanUp(); } return allNodes; } }
gpl-2.0
iucn-whp/world-heritage-outlook
portlets/iucn-dbservice-portlet/docroot/WEB-INF/service/com/iucn/whp/dbservice/service/assessment_lang_lkpLocalServiceWrapper.java
12790
/** * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. * * 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. */ package com.iucn.whp.dbservice.service; import com.liferay.portal.service.ServiceWrapper; /** * <p> * This class is a wrapper for {@link assessment_lang_lkpLocalService}. * </p> * * @author alok.sen * @see assessment_lang_lkpLocalService * @generated */ public class assessment_lang_lkpLocalServiceWrapper implements assessment_lang_lkpLocalService, ServiceWrapper<assessment_lang_lkpLocalService> { public assessment_lang_lkpLocalServiceWrapper( assessment_lang_lkpLocalService assessment_lang_lkpLocalService) { _assessment_lang_lkpLocalService = assessment_lang_lkpLocalService; } /** * Adds the assessment_lang_lkp to the database. Also notifies the appropriate model listeners. * * @param assessment_lang_lkp the assessment_lang_lkp * @return the assessment_lang_lkp that was added * @throws SystemException if a system exception occurred */ public com.iucn.whp.dbservice.model.assessment_lang_lkp addassessment_lang_lkp( com.iucn.whp.dbservice.model.assessment_lang_lkp assessment_lang_lkp) throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.addassessment_lang_lkp(assessment_lang_lkp); } /** * Creates a new assessment_lang_lkp with the primary key. Does not add the assessment_lang_lkp to the database. * * @param languageid the primary key for the new assessment_lang_lkp * @return the new assessment_lang_lkp */ public com.iucn.whp.dbservice.model.assessment_lang_lkp createassessment_lang_lkp( long languageid) { return _assessment_lang_lkpLocalService.createassessment_lang_lkp(languageid); } /** * Deletes the assessment_lang_lkp with the primary key from the database. Also notifies the appropriate model listeners. * * @param languageid the primary key of the assessment_lang_lkp * @return the assessment_lang_lkp that was removed * @throws PortalException if a assessment_lang_lkp with the primary key could not be found * @throws SystemException if a system exception occurred */ public com.iucn.whp.dbservice.model.assessment_lang_lkp deleteassessment_lang_lkp( long languageid) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.deleteassessment_lang_lkp(languageid); } /** * Deletes the assessment_lang_lkp from the database. Also notifies the appropriate model listeners. * * @param assessment_lang_lkp the assessment_lang_lkp * @return the assessment_lang_lkp that was removed * @throws SystemException if a system exception occurred */ public com.iucn.whp.dbservice.model.assessment_lang_lkp deleteassessment_lang_lkp( com.iucn.whp.dbservice.model.assessment_lang_lkp assessment_lang_lkp) throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.deleteassessment_lang_lkp(assessment_lang_lkp); } public com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery() { return _assessment_lang_lkpLocalService.dynamicQuery(); } /** * Performs a dynamic query on the database and returns the matching rows. * * @param dynamicQuery the dynamic query * @return the matching rows * @throws SystemException if a system exception occurred */ @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.dynamicQuery(dynamicQuery); } /** * Performs a dynamic query on the database and returns a range of the matching rows. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param dynamicQuery the dynamic query * @param start the lower bound of the range of model instances * @param end the upper bound of the range of model instances (not inclusive) * @return the range of matching rows * @throws SystemException if a system exception occurred */ @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end) throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.dynamicQuery(dynamicQuery, start, end); } /** * Performs a dynamic query on the database and returns an ordered range of the matching rows. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param dynamicQuery the dynamic query * @param start the lower bound of the range of model instances * @param end the upper bound of the range of model instances (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching rows * @throws SystemException if a system exception occurred */ @SuppressWarnings("rawtypes") public java.util.List dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end, com.liferay.portal.kernel.util.OrderByComparator orderByComparator) throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.dynamicQuery(dynamicQuery, start, end, orderByComparator); } /** * Returns the number of rows that match the dynamic query. * * @param dynamicQuery the dynamic query * @return the number of rows that match the dynamic query * @throws SystemException if a system exception occurred */ public long dynamicQueryCount( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.dynamicQueryCount(dynamicQuery); } public com.iucn.whp.dbservice.model.assessment_lang_lkp fetchassessment_lang_lkp( long languageid) throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.fetchassessment_lang_lkp(languageid); } /** * Returns the assessment_lang_lkp with the primary key. * * @param languageid the primary key of the assessment_lang_lkp * @return the assessment_lang_lkp * @throws PortalException if a assessment_lang_lkp with the primary key could not be found * @throws SystemException if a system exception occurred */ public com.iucn.whp.dbservice.model.assessment_lang_lkp getassessment_lang_lkp( long languageid) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.getassessment_lang_lkp(languageid); } public com.liferay.portal.model.PersistedModel getPersistedModel( java.io.Serializable primaryKeyObj) throws com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.getPersistedModel(primaryKeyObj); } /** * Returns a range of all the assessment_lang_lkps. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param start the lower bound of the range of assessment_lang_lkps * @param end the upper bound of the range of assessment_lang_lkps (not inclusive) * @return the range of assessment_lang_lkps * @throws SystemException if a system exception occurred */ public java.util.List<com.iucn.whp.dbservice.model.assessment_lang_lkp> getassessment_lang_lkps( int start, int end) throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.getassessment_lang_lkps(start, end); } /** * Returns the number of assessment_lang_lkps. * * @return the number of assessment_lang_lkps * @throws SystemException if a system exception occurred */ public int getassessment_lang_lkpsCount() throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.getassessment_lang_lkpsCount(); } /** * Updates the assessment_lang_lkp in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners. * * @param assessment_lang_lkp the assessment_lang_lkp * @return the assessment_lang_lkp that was updated * @throws SystemException if a system exception occurred */ public com.iucn.whp.dbservice.model.assessment_lang_lkp updateassessment_lang_lkp( com.iucn.whp.dbservice.model.assessment_lang_lkp assessment_lang_lkp) throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.updateassessment_lang_lkp(assessment_lang_lkp); } /** * Updates the assessment_lang_lkp in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners. * * @param assessment_lang_lkp the assessment_lang_lkp * @param merge whether to merge the assessment_lang_lkp with the current session. See {@link com.liferay.portal.service.persistence.BatchSession#update(com.liferay.portal.kernel.dao.orm.Session, com.liferay.portal.model.BaseModel, boolean)} for an explanation. * @return the assessment_lang_lkp that was updated * @throws SystemException if a system exception occurred */ public com.iucn.whp.dbservice.model.assessment_lang_lkp updateassessment_lang_lkp( com.iucn.whp.dbservice.model.assessment_lang_lkp assessment_lang_lkp, boolean merge) throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.updateassessment_lang_lkp(assessment_lang_lkp, merge); } /** * Returns the Spring bean ID for this bean. * * @return the Spring bean ID for this bean */ public java.lang.String getBeanIdentifier() { return _assessment_lang_lkpLocalService.getBeanIdentifier(); } /** * Sets the Spring bean ID for this bean. * * @param beanIdentifier the Spring bean ID for this bean */ public void setBeanIdentifier(java.lang.String beanIdentifier) { _assessment_lang_lkpLocalService.setBeanIdentifier(beanIdentifier); } public java.lang.Object invokeMethod(java.lang.String name, java.lang.String[] parameterTypes, java.lang.Object[] arguments) throws java.lang.Throwable { return _assessment_lang_lkpLocalService.invokeMethod(name, parameterTypes, arguments); } public java.util.List<com.iucn.whp.dbservice.model.assessment_lang_lkp> findAll() throws com.liferay.portal.kernel.exception.SystemException { return _assessment_lang_lkpLocalService.findAll(); } /** * @deprecated Renamed to {@link #getWrappedService} */ public assessment_lang_lkpLocalService getWrappedassessment_lang_lkpLocalService() { return _assessment_lang_lkpLocalService; } /** * @deprecated Renamed to {@link #setWrappedService} */ public void setWrappedassessment_lang_lkpLocalService( assessment_lang_lkpLocalService assessment_lang_lkpLocalService) { _assessment_lang_lkpLocalService = assessment_lang_lkpLocalService; } public assessment_lang_lkpLocalService getWrappedService() { return _assessment_lang_lkpLocalService; } public void setWrappedService( assessment_lang_lkpLocalService assessment_lang_lkpLocalService) { _assessment_lang_lkpLocalService = assessment_lang_lkpLocalService; } private assessment_lang_lkpLocalService _assessment_lang_lkpLocalService; }
gpl-2.0
profosure/porogram
TMessagesProj/src/main/java/com/porogram/profosure1/ui/Cells/HeaderCell.java
1846
/* * This is the source code of Telegram for Android v. 3.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2017. */ package com.porogram.profosure1.ui.Cells; import android.content.Context; import android.util.TypedValue; import android.view.Gravity; import android.widget.FrameLayout; import android.widget.TextView; import com.porogram.profosure1.messenger.AndroidUtilities; import com.porogram.profosure1.messenger.LocaleController; import com.porogram.profosure1.ui.ActionBar.Theme; import com.porogram.profosure1.ui.Components.LayoutHelper; public class HeaderCell extends FrameLayout { private TextView textView; public HeaderCell(Context context) { super(context); textView = new TextView(getContext()); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader)); textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 17, 15, 17, 0)); } public TextView getTextView() { return textView; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(38), MeasureSpec.EXACTLY)); } public void setText(String text) { textView.setText(text); } }
gpl-2.0
cdparra/reminiscens-lifeapi
app/pojos/FuzzyDateBean.java
4158
package pojos; import java.io.Serializable; import java.text.ParseException; import org.joda.time.DateTime; import utils.JodaDateTime; public class FuzzyDateBean implements Serializable { /** * */ private static final long serialVersionUID = 7304578497268955428L; private Long fuzzyDateId; private String textual_date; @JodaDateTime(format = "yyyy-MM-dd HH:mm:ss") private DateTime exactDate; private Long decade; private Long year; private String month; private String day; private Long accuracy; private String locale; // Fields in Database not exposed in this API // private String season; // private String day_name; // private String day_part; // private String hour; // private String minute; // private String second; /** * @return the fuzzyDateId */ public Long getFuzzyDateId() { return fuzzyDateId; } /** * @param fuzzyDateId the fuzzyDateId to set */ public void setFuzzyDateId(Long fuzzyDateId) { this.fuzzyDateId = fuzzyDateId; } /** * @return the textual_date */ public String getTextual_date() { return textual_date; } /** * @param textual_date the textual_date to set */ public void setTextual_date(String textual_date) { this.textual_date = textual_date; } /** * @return the exact_date */ public DateTime getExactDate() { return exactDate; } public String getExactDateAsString () { return exactDate == null ? null : exactDate.toString("yyyy-MM-dd HH:mm:ss"); } /** * @param exact_date the exact_date to set * @throws ParseException */ public void setExactDate(DateTime exact_date) throws ParseException { this.exactDate = exact_date; } /** * @return the decade */ public Long getDecade() { return decade; } /** * @param decade the decade to set */ public void setDecade(Long decade) { this.decade = decade; } /** * @return the year */ public Long getYear() { return year; } /** * @param year the year to set */ public void setYear(Long year) { this.year = year; } // /** // * @return the season // */ // public String getSeason() { // return season; // } // // /** // * @param season the season to set // */ // public void setSeason(String season) { // this.season = season; // } /** * @return the month */ public String getMonth() { return month; } /** * @param month the month to set */ public void setMonth(String month) { this.month = month; } /** * @return the day */ public String getDay() { return day; } /** * @param day the day to set */ public void setDay(String day) { this.day = day; } // /** // * @return the day_name // */ // public String getDay_name() { // return day_name; // } // // /** // * @param day_name the day_name to set // */ // public void setDay_name(String day_name) { // this.day_name = day_name; // } // // /** // * @return the day_part // */ // public String getDay_part() { // return day_part; // } // // /** // * @param day_part the day_part to set // */ // public void setDay_part(String day_part) { // this.day_part = day_part; // } // // /** // * @return the hour // */ // public String getHour() { // return hour; // } // // /** // * @param hour the hour to set // */ // public void setHour(String hour) { // this.hour = hour; // } // // /** // * @return the minute // */ // public String getMinute() { // return minute; // } // // /** // * @param minute the minute to set // */ // public void setMinute(String minute) { // this.minute = minute; // } // // /** // * @return the second // */ // public String getSecond() { // return second; // } // // /** // * @param second the second to set // */ // public void setSecond(String second) { // this.second = second; // } /** * @return the accuracy */ public Long getAccuracy() { return accuracy; } /** * @param accuracy the accuracy to set */ public void setAccuracy(Long accuracy) { this.accuracy = accuracy; } /** * @return the locale */ public String getLocale() { return locale; } /** * @param locale the locale to set */ public void setLocale(String locale) { this.locale = locale; } }
gpl-2.0
vishalmanohar/databene-benerator
src/main/java/org/databene/domain/person/PersonFormatter.java
3473
/* * (c) Copyright 2010 by Volker Bergmann. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, is permitted under the terms of the * GNU General Public License (GPL). * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS, * REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE * HEREBY EXCLUDED. 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. */ package org.databene.domain.person; import java.util.Locale; import java.util.Set; import org.databene.commons.CollectionUtil; import org.databene.commons.ConversionException; import org.databene.commons.LocaleUtil; import org.databene.commons.Locales; import org.databene.commons.StringUtil; import org.databene.commons.converter.ThreadSafeConverter; /** * Formats {@link Person} objects.<br/><br/> * Created: 22.02.2010 12:41:37 * @since 0.6.0 * @author Volker Bergmann */ public abstract class PersonFormatter extends ThreadSafeConverter<Person, String> { private static final Set<Locale> EASTERN_LOCALES = CollectionUtil.toSet( Locales.CHINESE, Locales.JAPANESE, Locales.KOREAN, Locales.THAI, Locales.VIETNAMESE ); public static final PersonFormatter WESTERN = new Western(); public static final PersonFormatter EASTERN = new Eastern(); public PersonFormatter() { super(Person.class, String.class); } public String convert(Person person) throws ConversionException { return format(person); } public abstract String format(Person person); public static PersonFormatter getInstance(Locale locale) { return (EASTERN_LOCALES.contains(LocaleUtil.language(locale)) ? EASTERN : WESTERN); } protected void appendSeparated(String part, StringBuilder builder) { if (!StringUtil.isEmpty(part)) { if (builder.length() > 0) builder.append(' '); builder.append(part); } } static class Western extends PersonFormatter { @Override public String format(Person person) { StringBuilder builder = new StringBuilder(); appendSeparated(person.getSalutation(), builder); appendSeparated(person.getAcademicTitle(), builder); appendSeparated(person.getNobilityTitle(), builder); appendSeparated(person.getGivenName(), builder); appendSeparated(person.getFamilyName(), builder); return builder.toString(); } } static class Eastern extends PersonFormatter { @Override public String format(Person person) { StringBuilder builder = new StringBuilder(); appendSeparated(person.getSalutation(), builder); appendSeparated(person.getAcademicTitle(), builder); appendSeparated(person.getNobilityTitle(), builder); appendSeparated(person.getFamilyName(), builder); appendSeparated(person.getGivenName(), builder); return builder.toString(); } } }
gpl-2.0
nano88/belajarAndroid
src/com/nano88/mylib/scrollview/Scroll_Viw.java
323
package com.nano88.mylib.scrollview; import android.app.Activity; import android.os.Bundle; import com.nano88.mylib.R; public class Scroll_Viw extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scroll__viw); } }
gpl-2.0
jamesbibby/mockito-sample
src/main/java/calculators/WeightBasedShippingCostCalculator.java
767
package calculators; import order.Order; /* * Calculates the cost of shipping based on the weight of the order, collaborates with an OrderWeightCalculator */ public class WeightBasedShippingCostCalculator implements ShippingCostCalculator { private OrderWeightCalculator orderWeightCalculator; public OrderWeightCalculator getOrderWeightCalculator() { return orderWeightCalculator; } public void setOrderWeightCalculator(OrderWeightCalculator orderWeightCalculator) { this.orderWeightCalculator = orderWeightCalculator; } @Override public double calculateShippingCost(Order order) { double totalWeight = orderWeightCalculator.calculateOrderWeight(order); return (totalWeight == 0 ? 0.0 : 12.99); //nice and simple here, 0 or $12.99 :) } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00264.java
2070
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest00264") public class BenchmarkTest00264 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // some code String[] values = request.getParameterValues("foo"); String param; if (values.length != 0) param = request.getParameterValues("foo")[0]; else param = null; try { float rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextFloat(); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing SecureRandom.nextFloat() - TestCase"); throw new ServletException(e); } response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextFloat() executed"); } }
gpl-2.0
laukvik/TimeTravel
src/main/java/org/laukvik/timetravel/UserType.java
857
/* * Copyright (C) 2014 Morten Laukvik <morten@laukvik.no> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.laukvik.timetravel; /** * * @author Morten Laukvik <morten@laukvik.no> */ public enum UserType { NORMAL, AUTHOR, MASTER }
gpl-2.0
anthony-salutari/Java-Pirate-Bay-Api
JavaPirateBayApi/src/main/java/jpa/ImageSearch.java
3987
package jpa; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.*; public class ImageSearch implements Runnable { private final Torrent torrent; private final Pattern pattern; public ImageSearch(Torrent torrent) { this.torrent = torrent; this.pattern = Pattern.compile(Constants.COVER_IMAGE_REGEX); } public void run() { String searchTerm = ""; String[] searchCriteria; URL url = null; if (torrent.Category.equals("TV shows") || torrent.Category.equals("HD - TV shows")) { searchCriteria = parseShow(); searchTerm += searchCriteria[0]; searchTerm += "&type=series"; } else { searchCriteria = parseMovie(); searchTerm += searchCriteria[0]; if (searchCriteria[1] != null) { searchTerm += "&y=" + searchCriteria[1]; } } if (!searchTerm.equals("null")) { try { url = new URL(Constants.OMDB_URL + searchTerm); } catch (MalformedURLException e) { e.printStackTrace(); } // setup HttpURLConnection HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); } try { connection.setRequestMethod("GET"); } catch (ProtocolException e) { e.printStackTrace(); } String response = null; try { // ensure the response code is 200 if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = bufferedReader.readLine(); } } catch (IOException e) { e.printStackTrace(); } if (response != null) { try { JSONObject object = new JSONObject(response); // get the imageurl and imdbid from the request torrent.CoverImage = object.getString("Poster"); torrent.ImdbID = object.getString("imdbID"); } catch (JSONException e) { // either log or ignore any time a cover image isn't found } } } } private String[] parseMovie() { final String regex = "(.*?)\\ \\(?(\\d{4}).*"; Pattern pattern = Pattern.compile(regex); final String torrentName = torrent.Name.replace('.', ' '); String[] results = new String[2]; Matcher matcher = pattern.matcher(torrentName); if (matcher.find()) { try { // title results[0] = matcher.group(1); // year results[1] = matcher.group(2); } catch (Exception e) { e.printStackTrace(); } } // if the search query contains spaces replace the spaces with +'s to provide a proper URL later if (results[0] != null) { results[0] = results[0].replace(' ', '+'); } return results; } private String[] parseShow() { final String regex = "(.*?)\\ S(\\d{2})E?(\\d{2})?.*"; Pattern pattern = Pattern.compile(regex); final String torrentName = torrent.Name.replace('.', ' '); String[] results = new String[3]; Matcher matcher = pattern.matcher(torrentName); if (matcher.find()) { try { // title results[0] = matcher.group(1); // season results[1] = matcher.group(2); // episode results[2] = matcher.group(3); } catch (Exception e) { // handle exception } } else { // handle error } // replace spaces with +'s to provide a proper URL later if (results[0] != null) { results[0] = results[0].replace(' ', '+'); } return results; } private String parseTitle() { String coverString = torrent.Name.replace(" ", "."); Matcher matcher = pattern.matcher(coverString); while (matcher.find()) { coverString = matcher.group(1); } return coverString; } }
gpl-2.0
damarinm26/DocumentalUD
Documental/src/java/com/documental/beans/GestionController.java
632
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.documental.beans; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; /** * * @author DiegoM */ @ManagedBean(name = "beanGestion") @SessionScoped public class GestionController { /** * Creates a new instance of GestionController */ public GestionController() { } public String prepareList() { return "/GUI/Gestion/BandejaEntrada/GUIBandejaEntradaList"; } }
gpl-2.0
ForBetter/doSchool
src/us/dobell/doschool/user/UserDatabase.java
7772
package us.dobell.doschool.user; import java.util.ArrayList; import us.dobell.xtools.XDatabase; import android.content.ContentValues; import android.database.Cursor; import android.util.Log; public class UserDatabase extends XDatabase { public static final String TAG = "Database"; public static void userSet(User user) { ContentValues values = new ContentValues(); values.put("id", user.id); values.put("nick", user.nick); values.put("head", user.head); values.put("card", user.card); values.put("friend", user.friend); if (userGet(user.id) == null) { xInsert("user", null, values); } else { xUpdate("user", values, "id=?", new String[] { "" + user.id }); } } public static User userGet(int objId) { Cursor cursor = xQuery("select * from user where id=?", new String[] { "" + objId }); User user = null; if (cursor.moveToNext()) { user = new User(cursor.getInt(cursor.getColumnIndex("id")), cursor.getString(cursor.getColumnIndex("nick")), cursor.getString(cursor.getColumnIndex("head")), cursor.getInt(cursor.getColumnIndex("card")), cursor.getInt(cursor.getColumnIndex("friend"))); } cursor.close(); return user; } public static ArrayList<User> userSearch(String objNick) { ArrayList<User> searchResult = new ArrayList<User>(); Cursor cursor = xQuery("select * from user where nick like ?", new String[] { objNick }); while (cursor.moveToNext()) { User user = new User(cursor.getInt(cursor.getColumnIndex("id")), cursor.getString(cursor.getColumnIndex("nick")), cursor.getString(cursor.getColumnIndex("head")), cursor.getInt(cursor.getColumnIndex("card")), cursor.getInt(cursor.getColumnIndex("friend"))); searchResult.add(user); } cursor.close(); return searchResult; } public static void userCardSet(Card card) { ContentValues values = new ContentValues(); values.put("id", card.id); values.put("nick", card.nick); values.put("head", card.head); values.put("card", card.card); values.put("friend", card.friend); values.put("fId", card.fId); values.put("name", card.name); values.put("phone", card.phone); values.put("qq", card.qq); values.put("mail", card.mail); values.put("introduce", card.introduce); if (userCardGet(card.id) == null) { xInsert("userCard", null, values); } else { xUpdate("userCard", values, "id=?", new String[] { "" + card.id }); } } public static void userDelete(int usrId) { xDelete("user", "id=?", new String[] { "" + usrId }); } public static Card userCardGet(int usrId) { Cursor cursor = xQuery("select * from userCard where id = ?", new String[] { "" + usrId }); Card card = null; if (cursor.moveToNext()) { card = new Card(cursor.getInt(cursor.getColumnIndex("id")), cursor.getString(cursor.getColumnIndex("nick")), cursor.getString(cursor.getColumnIndex("head")), cursor.getInt(cursor.getColumnIndex("card")), cursor.getInt(cursor.getColumnIndex("friend")), cursor.getString(cursor.getColumnIndex("fId")), cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("phone")), cursor.getString(cursor.getColumnIndex("qq")), cursor.getString(cursor.getColumnIndex("mail")), cursor.getString(cursor.getColumnIndex("introduce"))); } cursor.close(); return card; } public static ArrayList<Card> userCardList(int lastId, int rollType, int objCount) { ArrayList<Card> cardList = new ArrayList<Card>(); Cursor cursor; if (rollType == 0) { cursor = xQuery("select * from userCard order by id desc", null); } else if (rollType == 1) { cursor = xQuery( "select * from userCard where id > ? order by id desc", new String[] { "" + lastId }); int move = cursor.getCount() - objCount; while (cursor.moveToNext() && move-- > 0) ; } else { cursor = xQuery( "select * from userCard where id < ? order by id desc", new String[] { "" + lastId }); } while (cursor.moveToNext() && objCount-- > 0) { Card card = new Card(cursor.getInt(cursor.getColumnIndex("id")), cursor.getString(cursor.getColumnIndex("nick")), cursor.getString(cursor.getColumnIndex("head")), cursor.getInt(cursor.getColumnIndex("card")), cursor.getInt(cursor.getColumnIndex("friend")), cursor.getString(cursor.getColumnIndex("fId")), cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("phone")), cursor.getString(cursor.getColumnIndex("qq")), cursor.getString(cursor.getColumnIndex("mail")), cursor.getString(cursor.getColumnIndex("introduce"))); cardList.add(card); } cursor.close(); return cardList; } public static void userCardDelete(int cardId, int delType) { } public static void userApplySet(Apply apply) { ContentValues values = new ContentValues(); values.put("usrId", apply.usrId); values.put("usrNick", apply.usrNick); values.put("usrHead", apply.usrHead); values.put("id", apply.id); values.put("time", apply.time); values.put("state", apply.state); values.put("reason", apply.reason); if (userApplyGet(apply.id) == null) { xInsert("userApply", null, values); } else { xUpdate("userApply", values, "id=?", new String[] { "" + apply.id }); } } public static Apply userApplyGet(int applyId) { Cursor cursor = xQuery("select * from userApply where id = ?", new String[] { "" + applyId }); Apply apply = null; if (cursor.moveToNext()) { apply = new Apply(cursor.getInt(cursor.getColumnIndex("usrId")), cursor.getString(cursor.getColumnIndex("usrNick")), cursor.getString(cursor.getColumnIndex("usrHead")), cursor.getInt(cursor.getColumnIndex("id")), cursor.getLong(cursor.getColumnIndex("time")), cursor.getInt(cursor.getColumnIndex("state")), cursor.getString(cursor.getColumnIndex("reason"))); } cursor.close(); return apply; } public static ArrayList<Apply> userApplyList(int lastId, int rollType, int objCount) { ArrayList<Apply> applyList = new ArrayList<Apply>(); Cursor cursor; if (rollType == 0) { cursor = xQuery("select * from userApply order by id desc", null); } else if (rollType == 1) { cursor = xQuery( "select * from userApply where id > ? order by id desc", new String[] { "" + lastId }); int move = cursor.getCount() - objCount; while (cursor.moveToNext() && move-- > 0) ; } else { cursor = xQuery( "select * from userApply where id < ? order by id desc", new String[] { "" + lastId }); } while (cursor.moveToNext() && objCount-- > 0) { Apply apply = new Apply(cursor.getInt(cursor .getColumnIndex("usrId")), cursor.getString(cursor .getColumnIndex("usrNick")), cursor.getString(cursor .getColumnIndex("usrHead")), cursor.getInt(cursor .getColumnIndex("id")), cursor.getLong(cursor .getColumnIndex("time")), cursor.getInt(cursor .getColumnIndex("state")), cursor.getString(cursor .getColumnIndex("reason"))); applyList.add(apply); } cursor.close(); return applyList; } public static void userApplyDelete(int applyId, int delType) { } public static ArrayList<User> userFriendList() { ArrayList<User> friends = new ArrayList<User>(); Cursor cursor = xQuery("select * from user where friend = 3", null); Log.d(TAG, "测试好友列表"); while (cursor.moveToNext()) { Log.d(TAG, "test"); User user = new User(cursor.getInt(cursor.getColumnIndex("id")), cursor.getString(cursor.getColumnIndex("nick")), cursor.getString(cursor.getColumnIndex("head")), cursor.getInt(cursor.getColumnIndex("card")), cursor.getInt(cursor.getColumnIndex("friend"))); friends.add(user); } cursor.close(); return friends; } }
gpl-2.0
ykro/androidmooc-clase4
Demo 7 - Esquema de datos de lugares (SQLHelper) e insertar datos/src/com/ug/telescopio/data/DBHelper.java
1257
package com.ug.telescopio.data; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { public final static String KEY_ID = "id"; public final static String KEY_DATE = "date"; public final static String KEY_TIME = "time"; public final static String KEY_AUTHOR = "author"; public final static String KEY_THUMBNAILURL = "thumbnailURL"; public final static String PLACES_TABLE = "places"; private final static String DATABASE_CREATE = "CREATE TABLE " + PLACES_TABLE + "(" + KEY_ID + " integer primary key autoincrement, " + KEY_DATE + " text, " + KEY_TIME + " text," + KEY_AUTHOR + " text, " + KEY_THUMBNAILURL + " text)"; public DBHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + PLACES_TABLE); onCreate(db); } }
gpl-2.0
danaderp/unalcol
projects/self-assembly-replication/src/unalcol/lifesim/layers/SelfReplicationLayer.java
1117
/* * 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 unalcol.lifesim.layers; import unalcol.agents.Action; import unalcol.lifesim.agents.MoleculeAgent; import unalcol.lifesim.agents.MoleculePercept; import unalcol.lifesim.environment.Space; /** * * @author daniel */ public class SelfReplicationLayer extends Layer { public SelfReplicationLayer(Space _space, Layer _nexLayer) { super(_space,_nexLayer); } @Override public boolean add(MoleculeAgent agent) { return true; } @Override public void updateLayer() { } @Override protected boolean change(MoleculeAgent m, Action a) { return true; } @Override public MoleculePercept operates(MoleculeAgent m) { return null; } @Override public void display() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
gpl-2.0
DrewG/mzmine3
src/main/java/io/github/mzmine/parameters/ParameterSheetView.java
2412
/* * Copyright 2006-2016 The MZmine 3 Development Team * * This file is part of MZmine 3. * * MZmine 3 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. * * MZmine 3 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 MZmine 3; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package io.github.mzmine.parameters; import org.controlsfx.control.PropertySheet; import org.controlsfx.property.editor.PropertyEditor; import org.controlsfx.validation.ValidationSupport; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /** * Parameter sheet view */ public class ParameterSheetView extends PropertySheet { private final ParameterSet parameters; private final ParameterEditorFactory editorFactory; @SuppressWarnings({"rawtypes", "unchecked"}) public ParameterSheetView(ParameterSet parameters, ValidationSupport validationSupport) { super((ObservableList) FXCollections.observableList(parameters.getParameters())); this.parameters = parameters; setModeSwitcherVisible(false); setSearchBoxVisible(false); setMode(PropertySheet.Mode.NAME); setPrefSize(600.0, 400.0); // Set editor factory to keep track of which editing component belongs // to which parameter this.editorFactory = new ParameterEditorFactory(validationSupport); setPropertyEditorFactory(editorFactory); } public <ValueType> PropertyEditor<ValueType> getEditorForParameter( Parameter<ValueType> parameter) { // Let's lookup the parameter by name, because the actual instance may // differ due to the cloning of parameter sets Parameter<?> actualParameter = parameters.getParameter(parameter); if (actualParameter == null) throw new IllegalArgumentException( "Parameter " + parameter.getName() + " not found in this component"); return editorFactory.getEditorForItem(actualParameter); } }
gpl-2.0
zhuxiaocqu/UtopiaCommunity
src/com/ilive/response/NewsShowResponse.java
641
package com.ilive.response; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import com.ilive.iLiveResponse; import com.ilive.structs.News; public class NewsShowResponse implements iLiveResponse { private News news = null; private Long code = null; public NewsShowResponse(JSONObject json) throws JSONException { if (json != null) { if (!json.isNull("news")) news = new News(json.getJSONObject("news")); if (!json.isNull("code")) code = json.getLong("code"); } } public News getNews() { return news; } public Long getCode() { return code; } }
gpl-2.0
Esleelkartea/gestion-de-licencias
src/java/com/Negocio/Grupo.java
1348
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.Negocio; /** * * @author Julen */ public class Grupo { //Atributos private int idGrupo; private String letra; private String nombre; private String descripcion; //Constructor public Grupo() { } public Grupo(int pIdGrupo, String pLetra, String pNombre, String pDescripcion) { idGrupo = pIdGrupo; letra = pLetra; nombre = pNombre; descripcion = pDescripcion; } public Grupo(String pLetra, String pNombre, String pDescripcion) { letra = pLetra; nombre = pNombre; descripcion = pDescripcion; } //Metodos Get y Set public int getIdGrupo() { return idGrupo; } public void setIdGrupo(int idGrupo) { this.idGrupo = idGrupo; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getLetra() { return letra; } public void setLetra(String letra) { this.letra = letra; } }
gpl-2.0
PepeLui17/Proyecto_Ingenieria_de_Software
LibreriaDonQuijote/src/main/java/com/donquijote/daointerface/FacturaInterfaceDAO.java
780
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.donquijote.daointerface; import com.donquijote.persistence.Cliente; import com.donquijote.persistence.DetalleFactura; import com.donquijote.persistence.Factura; import java.util.Date; import java.util.List; /** * * @author José Luis */ public interface FacturaInterfaceDAO { void saveFactura(Factura obj); void saveDetalleFactura(DetalleFactura obj); Cliente findClientByCedula(String cedula); Factura obtainLastFactura(); List<Factura> getFacturasByFecha(Date fechaInicio, Date fechaFin); List<DetalleFactura> getDetallesByIdFactura(int idFactura); }
gpl-2.0
iTransformers/netTransformer
iDiscover/netDiscoverer/src/main/java/net/itransformers/idiscover/v2/core/listeners/node/sdnDeviceXmlFileLogDiscoveryListener.java
4409
/* * sdnDeviceXmlFileLogDiscoveryListener.java * * This work 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 work 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 * * Copyright (c) 2010-2016 iTransformers Labs. All rights reserved. */ package net.itransformers.idiscover.v2.core.listeners.node; import net.itransformers.idiscover.api.NodeDiscoveryListener; import net.itransformers.idiscover.api.NodeDiscoveryResult; import net.itransformers.utils.XsltTransformer; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; public class sdnDeviceXmlFileLogDiscoveryListener implements NodeDiscoveryListener { static Logger logger = Logger.getLogger(sdnDeviceXmlFileLogDiscoveryListener.class); String deviceXmlDataDirName; String labelDirName; String deviceXmlXsltTransformator; // walker = (JsonDiscoverer) new DefaultDiscovererFactory().createDiscoverer(resource); @Override public void nodeDiscovered(NodeDiscoveryResult discoveryResult) { File baseDir = new File(labelDirName); if (!baseDir.exists()) baseDir.mkdir(); File deviceXmlXslt = new File(System.getProperty("base.dir"), deviceXmlXsltTransformator); File deviceXmlDataDir = new File(deviceXmlDataDirName); if (!deviceXmlDataDir.exists()) deviceXmlDataDir.mkdir(); String deviceName = discoveryResult.getNodeId(); String rawDataXml = new String((byte[]) discoveryResult.getDiscoveredData("rawData")); try { //Create DeviceXml File ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); ByteArrayInputStream inputStream; XsltTransformer transformer = new XsltTransformer(); inputStream = new ByteArrayInputStream(rawDataXml.getBytes()); transformer.transformXML(inputStream, deviceXmlXslt, outputStream1); logger.info("Transforming raw-data to DeviceXml for "+deviceName); logger.debug("Raw Data \n" + rawDataXml.toString()); File deviceXmlFile = new File(deviceXmlDataDir, "node"+"-"+"floodLight"+"-"+deviceName+".xml"); FileUtils.writeStringToFile(deviceXmlFile, outputStream1.toString()); logger.info("Raw-data transformed to device-xml for "+deviceName); logger.debug("Node Data \n" + outputStream1.toString()); } catch (IOException e) { logger.error(e); } catch (ParserConfigurationException e) { logger.error(e); //To change body of catch statement use File | Settings | File Templates. } catch (SAXException e) { logger.error(e); //To change body of catch statement use File | Settings | File Templates. } catch (TransformerException e) { logger.error(e); //To change body of catch statement use File | Settings | File Templates. } } public String getDeviceXmlDataDirName() { return deviceXmlDataDirName; } public void setDeviceXmlDataDirName(String deviceXmlDataDirName) { this.deviceXmlDataDirName = deviceXmlDataDirName; } public String getLabelDirName() { return labelDirName; } public void setLabelDirName(String labelDirName) { this.labelDirName = labelDirName; } public String getDeviceXmlXsltTransformator() { return deviceXmlXsltTransformator; } public void setDeviceXmlXsltTransformator(String deviceXmlXsltTransformator) { this.deviceXmlXsltTransformator = deviceXmlXsltTransformator; } }
gpl-2.0
kadargergely/kgsoft-wordgame
src/main/java/hu/unideb/kgsoft/scrabble/model/Gameboard.java
25450
package hu.unideb.kgsoft.scrabble.model; /* * #%L * kgsoft-scrabble * %% * Copyright (C) 2015 kgsoft * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.util.ArrayList; import java.util.List; /** * The {@code Gameboard} class represents the board on which the players place * their tiles. An instance of this class stores informations about its fields * in a tow dimensional array of {@link Field} objects and about how many tiles * were placed on it in the current turn. The methods of this class are * essential pieces of the games logic, like testing if the tiles were placed * correctly on the board, spell checking the words, calculating the points * scored in the current turn. * * @author kadar_000 * */ public class Gameboard { /** * The number of fields in a row or column. */ public static final int BOARD_SIZE = 15; /** * Two dimensional array of <code>Field</code> objects, describing the game * board. */ private Field[][] board; /** * The number of tiles that were placed on the board in the current turn. */ private int movableTiles; /** * Constructs a <code>Gameboard</code> object and initializes its two * dimensional array of <code>Field</code> objects. */ public Gameboard() { board = new Field[BOARD_SIZE][BOARD_SIZE]; for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { board[i][j] = new Field(); } } movableTiles = 0; setMultipliers(); } /** * Constructs a new {@code Gameboard} object and initializes it with a two * dimensional array of {@code Field} objects. * * @param fields * the fields of the new {@code Gameboard} object */ public Gameboard(Field[][] fields) { board = fields; movableTiles = 0; for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { if (board[i][j].getStatus() == Field.Status.MOVABLE) { movableTiles++; } } } } /** * If it is possible, places a tile at the given position on the board, with * a given tile code. If the tile is a joker, use the * <code>setJokerTile</code> method instead. * * @param row * the row index where the tile should be placed * @param col * the column index where the tile should be placed * @param code * the code of the tile * @return <code>true</code> if the tile has been successfully placed on the * board, <code>false</code> otherwise */ public boolean setTile(int row, int col, int code) { if (board[row][col].getStatus() == Field.Status.EMPTY) { board[row][col].setTileCode(code); board[row][col].setStatus(Field.Status.MOVABLE); movableTiles++; return true; } else { return false; } } /** * If it is possible, places a joker at the given position, replacing the * given tile code. * * @param row * the row index where the tile should be placed * @param col * the column index where the tile should be placed * @param code * the code of the tile that is replaced by the joker * @return <code>true</code> if the tile has been successfully placed on the * board, <code>false</code> otherwise */ public boolean setJokerTile(int row, int col, int code) { if (board[row][col].getStatus() == Field.Status.EMPTY) { board[row][col].setTileCode(Letters.JOKER_CODE); board[row][col].setJokerTileCode(code); board[row][col].setStatus(Field.Status.MOVABLE); movableTiles++; return true; } else { return false; } } /** * Returns the tile code of the field with the given row and column indices, * if the tile is movable, regarding the rules, and sets its value to * {@code Field.NOTILE}. * * @param row * the row index from where the tile should be removed * @param col * the column index from where the tile should be removed * @return the tile code of the tile picked up, or the * <code>Field.NOTILE</code> constant if there was no tile on the * field */ public int pickUpTile(int row, int col) { if (board[row][col].getStatus() == Field.Status.MOVABLE) { int code = board[row][col].getTileCode(); board[row][col].setTileCode(Field.NOTILE); board[row][col].setJokerTileCode(Field.NOTILE); board[row][col].setStatus(Field.Status.EMPTY); movableTiles--; return code; } else { return Field.NOTILE; } } /** * Checks if the disposal of the tiles on the board allows the player to end * his turn, regarding the rules. The method needs to know that the game is * in the first turn, or not, because that is a special case. * * @param firstTurn * <code>true</code> if the game is in the first turn * @return <code>true</code> if the state of the board matches the above * condition, <code>false</code> otherwise */ public boolean isLegal(boolean firstTurn) { int row = -1, col = -1; boolean found = false; for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { if (board[i][j].getStatus() == Field.Status.MOVABLE) { row = i; col = j; found = true; break; } } if (found) break; } if (found) { boolean connected = false; int tilesInRow = 0; for (int j = col; j < BOARD_SIZE; j++) { if (board[row][j].getStatus() == Field.Status.MOVABLE) { tilesInRow++; } } int tilesInCol = 0; for (int i = row; i < BOARD_SIZE; i++) { if (board[i][col].getStatus() == Field.Status.MOVABLE) { tilesInCol++; } } if (tilesInRow > 1) { if (tilesInRow < movableTiles) { return false; } else { int connectedTiles = 0; for (int j = col; j < BOARD_SIZE; j++) { if (board[row][j].getStatus() == Field.Status.EMPTY) { break; } else if (board[row][j].getStatus() == Field.Status.MOVABLE) { connectedTiles++; } if (!connected && !firstTurn) { if ((row > 0 && board[row - 1][j].getStatus() == Field.Status.FIXED) || (row < BOARD_SIZE - 1 && board[row + 1][j].getStatus() == Field.Status.FIXED) || (j > 0 && board[row][j - 1].getStatus() == Field.Status.FIXED) || (j < BOARD_SIZE - 1 && board[row][j + 1].getStatus() == Field.Status.FIXED)) { connected = true; } } } if (connectedTiles < movableTiles) { return false; } } } else if (tilesInCol > 1) { if (tilesInCol < movableTiles) { return false; } else { int connectedTiles = 0; for (int i = row; i < BOARD_SIZE; i++) { if (board[i][col].getStatus() == Field.Status.EMPTY) { break; } else if (board[i][col].getStatus() == Field.Status.MOVABLE) { connectedTiles++; } if (!connected && !firstTurn) { if ((col > 0 && board[i][col - 1].getStatus() == Field.Status.FIXED) || (col < BOARD_SIZE - 1 && board[i][col + 1].getStatus() == Field.Status.FIXED) || (i > 0 && board[i - 1][col].getStatus() == Field.Status.FIXED) || (i < BOARD_SIZE - 1 && board[i + 1][col].getStatus() == Field.Status.FIXED)) { connected = true; } } } if (connectedTiles < movableTiles) { return false; } } } else if (movableTiles > 1) { return false; } else { if (!connected && !firstTurn) { if ((col > 0 && board[row][col - 1].getStatus() == Field.Status.FIXED) || (col < BOARD_SIZE - 1 && board[row][col + 1].getStatus() == Field.Status.FIXED) || (row > 0 && board[row - 1][col].getStatus() == Field.Status.FIXED) || (row < BOARD_SIZE - 1 && board[row + 1][col].getStatus() == Field.Status.FIXED)) { connected = true; } } } if (!connected && !firstTurn) { return false; } if (firstTurn && board[7][7].getStatus() != Field.Status.MOVABLE) { return false; } } else { return false; } return true; } /** * Sets the multipliers of the fields of the game board. */ public void setMultipliers() { board[0][0].setMultiplier(Field.Multiplier.TWORD); board[0][7].setMultiplier(Field.Multiplier.TWORD); board[0][14].setMultiplier(Field.Multiplier.TWORD); board[7][0].setMultiplier(Field.Multiplier.TWORD); board[14][0].setMultiplier(Field.Multiplier.TWORD); board[7][14].setMultiplier(Field.Multiplier.TWORD); board[14][14].setMultiplier(Field.Multiplier.TWORD); board[14][7].setMultiplier(Field.Multiplier.TWORD); board[1][1].setMultiplier(Field.Multiplier.DWORD); board[2][2].setMultiplier(Field.Multiplier.DWORD); board[3][3].setMultiplier(Field.Multiplier.DWORD); board[4][4].setMultiplier(Field.Multiplier.DWORD); board[1][13].setMultiplier(Field.Multiplier.DWORD); board[2][12].setMultiplier(Field.Multiplier.DWORD); board[3][11].setMultiplier(Field.Multiplier.DWORD); board[4][10].setMultiplier(Field.Multiplier.DWORD); board[13][1].setMultiplier(Field.Multiplier.DWORD); board[12][2].setMultiplier(Field.Multiplier.DWORD); board[11][3].setMultiplier(Field.Multiplier.DWORD); board[10][4].setMultiplier(Field.Multiplier.DWORD); board[10][10].setMultiplier(Field.Multiplier.DWORD); board[11][11].setMultiplier(Field.Multiplier.DWORD); board[12][12].setMultiplier(Field.Multiplier.DWORD); board[13][13].setMultiplier(Field.Multiplier.DWORD); board[7][7].setMultiplier(Field.Multiplier.DWORD); board[1][5].setMultiplier(Field.Multiplier.TLETTER); board[1][9].setMultiplier(Field.Multiplier.TLETTER); board[5][1].setMultiplier(Field.Multiplier.TLETTER); board[5][5].setMultiplier(Field.Multiplier.TLETTER); board[5][9].setMultiplier(Field.Multiplier.TLETTER); board[5][13].setMultiplier(Field.Multiplier.TLETTER); board[9][1].setMultiplier(Field.Multiplier.TLETTER); board[9][5].setMultiplier(Field.Multiplier.TLETTER); board[9][9].setMultiplier(Field.Multiplier.TLETTER); board[9][13].setMultiplier(Field.Multiplier.TLETTER); board[13][5].setMultiplier(Field.Multiplier.TLETTER); board[13][9].setMultiplier(Field.Multiplier.TLETTER); board[0][3].setMultiplier(Field.Multiplier.DLETTER); board[0][11].setMultiplier(Field.Multiplier.DLETTER); board[14][3].setMultiplier(Field.Multiplier.DLETTER); board[14][11].setMultiplier(Field.Multiplier.DLETTER); board[3][0].setMultiplier(Field.Multiplier.DLETTER); board[11][0].setMultiplier(Field.Multiplier.DLETTER); board[3][14].setMultiplier(Field.Multiplier.DLETTER); board[11][14].setMultiplier(Field.Multiplier.DLETTER); board[2][6].setMultiplier(Field.Multiplier.DLETTER); board[2][8].setMultiplier(Field.Multiplier.DLETTER); board[3][7].setMultiplier(Field.Multiplier.DLETTER); board[6][2].setMultiplier(Field.Multiplier.DLETTER); board[8][2].setMultiplier(Field.Multiplier.DLETTER); board[7][3].setMultiplier(Field.Multiplier.DLETTER); board[6][12].setMultiplier(Field.Multiplier.DLETTER); board[8][12].setMultiplier(Field.Multiplier.DLETTER); board[7][11].setMultiplier(Field.Multiplier.DLETTER); board[12][6].setMultiplier(Field.Multiplier.DLETTER); board[12][8].setMultiplier(Field.Multiplier.DLETTER); board[11][7].setMultiplier(Field.Multiplier.DLETTER); board[6][6].setMultiplier(Field.Multiplier.DLETTER); board[8][8].setMultiplier(Field.Multiplier.DLETTER); board[6][8].setMultiplier(Field.Multiplier.DLETTER); board[8][6].setMultiplier(Field.Multiplier.DLETTER); for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { if (board[i][j].getMultiplier() == null) { board[i][j].setMultiplier(Field.Multiplier.NONE); } } } } /** * Reads a word horizontally, starting from the given position. It is called * by the public method <code>getPlayedWords</code>. * * @param row * the row index of the starting position * @param col * the column index of the starting position * @return the word read, or <code>null</code> if there is no tile on the * starting position */ private String readRowWord(int row, int col) { int startCol = 0; StringBuilder word = new StringBuilder(); if (board[row][col].getStatus() == Field.Status.EMPTY) { return null; } for (int j = col; j >= 0; j--) { if (board[row][j].getStatus() == Field.Status.EMPTY) { startCol = j + 1; break; } } for (int j = startCol; j < BOARD_SIZE; j++) { if (board[row][j].getStatus() == Field.Status.EMPTY) { break; } if (board[row][j].getTileCode() != Letters.JOKER_CODE) { word.append(Letters.getL(board[row][j].getTileCode())); } else { word.append(Letters.getL(board[row][j].getJokerTileCode())); } } return word.toString(); } /** * Reads a word vertically, starting from the given position. It is called * by the public method <code>getPlayedWords</code>. * * @param row * the row index of the starting position * @param col * the column index of the starting position * @return the word read, or <code>null</code> if there is no tile on the * starting position */ private String readColWord(int row, int col) { int startRow = 0; StringBuilder word = new StringBuilder(); if (board[row][col].getStatus() == Field.Status.EMPTY) { return null; } for (int i = row; i >= 0; i--) { if (board[i][col].getStatus() == Field.Status.EMPTY) { startRow = i + 1; break; } } for (int i = startRow; i < BOARD_SIZE; i++) { if (board[i][col].getStatus() == Field.Status.EMPTY) { break; } if (board[i][col].getTileCode() != Letters.JOKER_CODE) { word.append(Letters.getL(board[i][col].getTileCode())); } else { word.append(Letters.getL(board[i][col].getJokerTileCode())); } } return word.toString(); } /** * Returns a list of the words played in the current turn. The method * assumes that the state of the board allows the player to end his turn * regarding the rules, i.e. the <code>isLegal</code> method returns * <code>true</code>, otherwise the return value will be undefined. * * @return a list of strings containing the words played in the current * turn, or <code>null</code> if there were no words played in the * current turn */ public List<String> getPlayedWords() { int col = -1, row = -1; List<String> playedWords = new ArrayList<String>(); boolean found = false; for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { if (board[i][j].getStatus() == Field.Status.MOVABLE) { row = i; col = j; found = true; break; } } if (found) { break; } } if (!found) { return null; } boolean tilesInRow = false; for (int j = col + 1; j < BOARD_SIZE; j++) { if (board[row][j].getStatus() == Field.Status.MOVABLE) { tilesInRow = true; break; } } boolean tilesInCol = false; for (int i = row + 1; i < BOARD_SIZE; i++) { if (board[i][col].getStatus() == Field.Status.MOVABLE) { tilesInCol = true; break; } } if (tilesInRow) { playedWords.add(readRowWord(row, col)); for (int j = col; j < BOARD_SIZE; j++) { if (board[row][j].getStatus() == Field.Status.EMPTY) { break; } else if (board[row][j].getStatus() == Field.Status.MOVABLE) { String w = readColWord(row, j); if (w.length() > 1 && !(w.equals("CS") || w.equals("GY") || w.equals("LY") || w.equals("NY") || w.equals("SZ") || w.equals("TY") || w.equals("ZS"))) { playedWords.add(w); } } } } else if (tilesInCol) { playedWords.add(readColWord(row, col)); for (int i = row; i < BOARD_SIZE; i++) { if (board[i][col].getStatus() == Field.Status.EMPTY) { break; } else if (board[i][col].getStatus() == Field.Status.MOVABLE) { String w = readRowWord(i, col); if (w.length() > 1 && !(w.equals("CS") || w.equals("GY") || w.equals("LY") || w.equals("NY") || w.equals("SZ") || w.equals("TY") || w.equals("ZS"))) { playedWords.add(w); } } } } else { String rowWord = readRowWord(row, col); if (rowWord.length() > 1 && !(rowWord.equals("CS") || rowWord.equals("GY") || rowWord.equals("LY") || rowWord.equals("NY") || rowWord.equals("SZ") || rowWord.equals("TY") || rowWord.equals("ZS"))) { playedWords.add(rowWord); } String colWord = readColWord(row, col); if (colWord.length() > 1 && !(colWord.equals("CS") || colWord.equals("GY") || colWord.equals("LY") || colWord.equals("NY") || colWord.equals("SZ") || colWord.equals("TY") || colWord.equals("ZS"))) { playedWords.add(colWord); } } return playedWords; } /** * Calculates the value in points of a word placed horizontally and * including the given position. This method is used by the public * <code>calcPoints()</code> method. * * @param row * the row index of the starting position of the word * @param col * the column index of the starting position of the word * @return the value of the word in points */ private int calcRowWordPts(int row, int col) { int startCol = 0; int pts = 0; int factor = 1; if (board[row][col].getStatus() == Field.Status.EMPTY) { return 0; } // Find factors. for (int j = col; j < BOARD_SIZE; j++) { if (board[row][j].getStatus() == Field.Status.EMPTY) { break; } else if (board[row][j].getStatus() == Field.Status.MOVABLE) { if (board[row][j].getMultiplier() == Field.Multiplier.DWORD) { factor *= 2; } else if (board[row][j].getMultiplier() == Field.Multiplier.TWORD) { factor *= 3; } } } // Find the first tile of the word. for (int j = col; j >= 0; j--) { if (board[row][j].getStatus() == Field.Status.EMPTY) { startCol = j + 1; break; } } // Calculate points. for (int j = startCol; j < BOARD_SIZE; j++) { if (board[row][j].getStatus() == Field.Status.EMPTY) { break; } else if (board[row][j].getStatus() == Field.Status.MOVABLE) { switch (board[row][j].getMultiplier()) { case DLETTER: pts += 2 * factor * Letters.getValue(board[row][j].getTileCode()); break; case TLETTER: pts += 3 * factor * Letters.getValue(board[row][j].getTileCode()); break; default: pts += factor * Letters.getValue(board[row][j].getTileCode()); break; } } else { pts += factor * Letters.getValue(board[row][j].getTileCode()); } } return pts; } /** * Calculates the value in points of a word placed vertically and including * the given position. This method is used by the public * <code>calcPoints()</code> method. * * @param row * the row index of the starting position of the word * @param col * the column index of the starting position of the word * @return the value of the word in points */ private int calcColWordPts(int row, int col) { int startRow = 0; int pts = 0; int factor = 1; if (board[row][col].getStatus() == Field.Status.EMPTY) { return 0; } // Find factors. for (int i = row; i < BOARD_SIZE; i++) { if (board[i][col].getStatus() == Field.Status.EMPTY) { break; } else if (board[i][col].getStatus() == Field.Status.MOVABLE) { if (board[i][col].getMultiplier() == Field.Multiplier.DWORD) { factor *= 2; } else if (board[i][col].getMultiplier() == Field.Multiplier.TWORD) { factor *= 3; } } } // Find the first tile of the word. for (int i = row; i >= 0; i--) { if (board[i][col].getStatus() == Field.Status.EMPTY) { startRow = i + 1; break; } } // Calculate points. for (int i = startRow; i < BOARD_SIZE; i++) { if (board[i][col].getStatus() == Field.Status.EMPTY) { break; } else if (board[i][col].getStatus() == Field.Status.MOVABLE) { switch (board[i][col].getMultiplier()) { case DLETTER: pts += 2 * factor * Letters.getValue(board[i][col].getTileCode()); break; case TLETTER: pts += 3 * factor * Letters.getValue(board[i][col].getTileCode()); break; default: pts += factor * Letters.getValue(board[i][col].getTileCode()); break; } } else { pts += factor * Letters.getValue(board[i][col].getTileCode()); } } return pts; } /** * Returns the number of points the player will get in the current turn, * based on the current state of the board. The method assumes that the * state of the board allows the player to end his turn regarding the rules, * i.e. the <code>isLegal()</code> method returns <code>true</code>, * otherwise the return value will be undefined. * * @return the total number of points gained in the current turn, or * undefined value if the <code>isLegal()</code> method returns * <code>false</code> */ public int calcPoints() { int pts = 0; int col = -1, row = -1; boolean found = false; for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { if (board[i][j].getStatus() == Field.Status.MOVABLE) { row = i; col = j; found = true; break; } } if (found) { break; } } if (!found) { return 0; } boolean tilesInRow = false; for (int j = col + 1; j < BOARD_SIZE; j++) { if (board[row][j].getStatus() == Field.Status.MOVABLE) { tilesInRow = true; break; } } boolean tilesInCol = false; for (int i = row + 1; i < BOARD_SIZE; i++) { if (board[i][col].getStatus() == Field.Status.MOVABLE) { tilesInCol = true; break; } } if (tilesInRow) { pts += calcRowWordPts(row, col); for (int j = col; j < BOARD_SIZE; j++) { if (board[row][j].getStatus() == Field.Status.EMPTY) { break; } else if (board[row][j].getStatus() == Field.Status.MOVABLE) { if ((row != 0 && board[row - 1][j].getStatus() != Field.Status.EMPTY) || (row < BOARD_SIZE - 1 && board[row + 1][j].getStatus() != Field.Status.EMPTY)) { pts += calcColWordPts(row, j); } } } } else if (tilesInCol) { pts += calcColWordPts(row, col); for (int i = row; i < BOARD_SIZE; i++) { if (board[i][col].getStatus() == Field.Status.EMPTY) { break; } else if (board[i][col].getStatus() == Field.Status.MOVABLE) { if ((col != 0 && board[i][col - 1].getStatus() != Field.Status.EMPTY) || (col < BOARD_SIZE - 1 && board[i][col + 1].getStatus() != Field.Status.EMPTY)) { pts += calcRowWordPts(i, col); } } } } else { if (board[row][col].getStatus() == Field.Status.MOVABLE) { if ((row != 0 && board[row - 1][col].getStatus() != Field.Status.EMPTY) || (row < BOARD_SIZE - 1 && board[row + 1][col].getStatus() != Field.Status.EMPTY)) { pts += calcColWordPts(row, col); } if ((col != 0 && board[row][col - 1].getStatus() != Field.Status.EMPTY) || (col < BOARD_SIZE - 1 && board[row][col + 1].getStatus() != Field.Status.EMPTY)) { pts += calcRowWordPts(row, col); } } } return pts; } /** * Returns the two dimensional array representing the fields of the board. * * @return a two dimensional array of <code>Field</code> objects */ public Field[][] getFields() { return board; } /** * Returns the number of tiles placed on the board in the current turn. * * @return the movableTiles the number of tiles placed on the board in the * current turn */ public int getMovableTiles() { return movableTiles; } /** * Checks if the tiles placed on the board in the current turn form * grammatically correct words. If there are no such tiles, the method will * return <code>false</code>. The method receives a {@link Dictionary} * object with the words considered correct. * * @param dict * the <code>Dictionary</code> object * @return <code>true</code> if all the words placed on the board in the * current turn are correct, <code>false</code> if there are no * tiles placed on the board in the current turn, or there is at * least one grammatically incorrect word. */ public boolean wordsAreCorrect(Dictionary dict) { List<String> playedWords = getPlayedWords(); if (playedWords == null) { return false; } boolean areCorrect = true; for (String word : playedWords) { if (!dict.isCorrect(word)) { areCorrect = false; break; } } return areCorrect; } /** * Sets the status of each {@code MOVABLE} field to {@code FIXED} and also * sets the number of movable tiles to 0. Is usually called at the end of a * turn. */ public void finalizeFields() { for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { if (board[i][j].getStatus() == Field.Status.MOVABLE) { board[i][j].setStatus(Field.Status.FIXED); } } } movableTiles = 0; } }
gpl-2.0
kompics/kompics-simulator
core/src/main/java/se/sics/kompics/simulator/core/Simulator.java
1390
/** * This file is part of the Kompics P2P Framework. * * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) Copyright (C) * 2009 Royal Institute of Technology (KTH) * * Kompics 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 se.sics.kompics.simulator.core; /** * The <code>Simulator</code> class. * * @author Cosmin Arad {@literal <cosmin@sics.se>} * @version $Id$ */ public interface Simulator { public boolean advanceSimulation(); public long java_lang_System_currentTimeMillis(); public long java_lang_System_nanoTime(); public void java_lang_Thread_sleep(long millis); public void java_lang_Thread_sleep(long millis, int nanos); public void java_lang_Thread_start(); }
gpl-2.0
favedit/MoPlatform
mo-4-web/src/web-face/org/mo/jfa/face/design/property/IPropertyService.java
494
package org.mo.jfa.face.design.property; import org.mo.web.protocol.context.IWebContext; import org.mo.web.protocol.context.IWebInput; import org.mo.web.protocol.context.IWebOutput; public interface IPropertyService { public void listFields(IWebContext context, IWebInput input, IWebOutput output); public void listForms(IWebContext context, IWebInput input, IWebOutput output); }
gpl-2.0
panhainan/contact
src/com/phn/contact/MainActivity.java
4583
package com.phn.contact; import java.util.List; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.phn.contact.dao.PeopleDao; import com.phn.contact.entity.People; public class MainActivity extends BaseActivity implements OnClickListener, OnItemClickListener { private List<String> listPeopleName; private final int CONTEXT_MENU_EDIT = 0x111; private final int CONTEXT_MENU_DELETE = 0x112; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); setContentViewDate(); setOnClickEvent(); } private void setOnClickEvent() { Button titleEditPeople = (Button) findViewById(R.id.action_add_people); titleEditPeople.setOnClickListener(this); } private void setContentViewDate() { listPeopleName = PeopleDao.getContactsName(getContentResolver()); TextView peopleCount = (TextView) findViewById(R.id.all_count_people); if(listPeopleName!=null&&listPeopleName.size()!=0){ ArrayAdapter<String> peopleNameAdapter = new ArrayAdapter<String>( MainActivity.this, R.layout.main_contact_item, listPeopleName); peopleCount.setText("(" + listPeopleName.size() + "位)"); ListView listView = (ListView) findViewById(R.id.contact_list); listView.setAdapter(peopleNameAdapter); listView.setOnItemClickListener(this); registerForContextMenu(listView); }else{ peopleCount.setText("(0位)"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add(0, CONTEXT_MENU_EDIT, 0, "编辑"); menu.add(0, CONTEXT_MENU_DELETE, 0, "删除"); } public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); String peopleName = listPeopleName.get(info.position); switch (item.getItemId()) { case CONTEXT_MENU_EDIT: PeopleEditActivity.activityStart(this, PeopleDao.getPeopleByName(getContentResolver(), peopleName)); // Toast.makeText(this, "您点击了编辑" + peopleName, Toast.LENGTH_SHORT) // .show(); break; case CONTEXT_MENU_DELETE: deletePeopleOption(peopleName); break; default: break; } return true; } private void deletePeopleOption(final String peopleName) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); dialogBuilder.setTitle("警告"); dialogBuilder.setMessage("您确定要删除联系人“" + peopleName + "”吗?"); dialogBuilder.setCancelable(true); dialogBuilder.setNegativeButton("取消", null); dialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { PeopleDao.deletePeopleByName(getContentResolver(), peopleName); listPeopleName = null; setContentViewDate(); } }); AlertDialog alertDialog = dialogBuilder.create(); // 需要设置AlertDialog的类型,保证在广播接收器中可以正常弹出 alertDialog.getWindow().setType( WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); alertDialog.show(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String peopleName = listPeopleName.get(position); People people = PeopleDao.getPeopleByName(getContentResolver(), peopleName); PeopleDetailsActivity.activityStart(this, people); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.action_add_people: Intent intent = new Intent(this, PeopleAddActivity.class); startActivity(intent); break; default: break; } } @Override public void onBackPressed() { ActivityController.finishAll(); } }
gpl-2.0
jstralko/data-structures-and-algorithms
leetcode/ReverseLinkedList.java
260
public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; }
gpl-2.0
Decentrify/GVoD
simulator/src/main/java/se/sics/gvod/simulator/util/TestStatus.java
1201
/* * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) Copyright (C) * 2009 Royal Institute of Technology (KTH) * * GVoD 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 se.sics.gvod.simulator.util; /** * @author Alex Ormenisan <aaor@kth.se> */ public class TestStatus { public boolean ongoing = true; public boolean success = false; public void fail() { ongoing = false; success = false; } public void success() { ongoing = false; success = true; } }
gpl-2.0