repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
pdepaepe/graylog2-server
graylog2-server/src/test/java/org/graylog2/alerts/types/FieldContentValueAlertConditionTest.java
7289
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog2.alerts.types; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.graylog2.Configuration; import org.graylog2.alerts.AbstractAlertCondition; import org.graylog2.alerts.AlertConditionTest; import org.graylog2.indexer.ranges.IndexRange; import org.graylog2.indexer.ranges.MongoIndexRange; import org.graylog2.indexer.results.SearchResult; import org.graylog2.indexer.searches.Searches; import org.graylog2.indexer.searches.Sorting; import org.graylog2.plugin.Tools; import org.graylog2.plugin.alarms.AlertCondition; import org.graylog2.plugin.indexer.searches.timeranges.RelativeRange; import org.graylog2.plugin.streams.Stream; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; public class FieldContentValueAlertConditionTest extends AlertConditionTest { @Test public void testConstructor() throws Exception { final Map<String, Object> parameters = getParametersMap(0, "field", "value"); final FieldContentValueAlertCondition condition = getCondition(parameters, alertConditionTitle); assertNotNull(condition); assertNotNull(condition.getDescription()); } @Test public void testRunMatchingMessagesInStream() throws Exception { final SearchHits searchHits = mock(SearchHits.class); final SearchHit searchHit = mock(SearchHit.class); final HashMap<String, Object> source = Maps.newHashMap(); source.put("message", "something is in here"); when(searchHit.getId()).thenReturn("some id"); when(searchHit.getSource()).thenReturn(source); when(searchHit.getIndex()).thenReturn("graylog_test"); when(searchHits.iterator()).thenReturn(Iterators.singletonIterator(searchHit)); final DateTime now = DateTime.now(DateTimeZone.UTC); final IndexRange indexRange = MongoIndexRange.create("graylog_test", now.minusDays(1), now, now, 0); final Set<IndexRange> indexRanges = Sets.newHashSet(indexRange); final SearchResult searchResult = spy(new SearchResult(searchHits, indexRanges, "message:something", null, new TimeValue(100, TimeUnit.MILLISECONDS))); when(searchResult.getTotalResults()).thenReturn(1L); when(searches.search( anyString(), anyString(), any(RelativeRange.class), anyInt(), anyInt(), any(Sorting.class))) .thenReturn(searchResult); final FieldContentValueAlertCondition condition = getCondition(getParametersMap(0, "message", "something"), "Alert Condition for testing"); alertLastTriggered(-1); final AlertCondition.CheckResult result = alertService.triggered(condition); assertTriggered(condition, result); } @Test public void testRunNoMatchingMessages() throws Exception { final SearchHits searchHits = mock(SearchHits.class); when(searchHits.iterator()).thenReturn(Collections.<SearchHit>emptyIterator()); final DateTime now = DateTime.now(DateTimeZone.UTC); final IndexRange indexRange = MongoIndexRange.create("graylog_test", now.minusDays(1), now, now, 0); final Set<IndexRange> indexRanges = Sets.newHashSet(indexRange); final SearchResult searchResult = spy(new SearchResult(searchHits, indexRanges, "message:something", null, new TimeValue(100, TimeUnit.MILLISECONDS))); when(searches.search( anyString(), anyString(), any(RelativeRange.class), anyInt(), anyInt(), any(Sorting.class))) .thenReturn(searchResult); final FieldContentValueAlertCondition condition = getCondition(getParametersMap(0, "message", "something"), alertConditionTitle); alertLastTriggered(-1); final AlertCondition.CheckResult result = alertService.triggered(condition); assertNotTriggered(result); } @Test public void testCorrectUsageOfRelativeRange() throws Exception { final Stream stream = mock(Stream.class); final Searches searches = mock(Searches.class); final Configuration configuration = mock(Configuration.class); final SearchResult searchResult = mock(SearchResult.class); final int alertCheckInterval = 42; final RelativeRange relativeRange = RelativeRange.create(alertCheckInterval); when(configuration.getAlertCheckInterval()).thenReturn(alertCheckInterval); when(searches.search(anyString(), anyString(), eq(relativeRange), anyInt(), anyInt(), any(Sorting.class))).thenReturn(searchResult); final FieldContentValueAlertCondition alertCondition = new FieldContentValueAlertCondition(searches, configuration, stream, null, DateTime.now(DateTimeZone.UTC), "mockuser", ImmutableMap.<String,Object>of("field", "test", "value", "test"), "Field Content Value Test COndition"); final AbstractAlertCondition.CheckResult result = alertCondition.runCheck(); } protected FieldContentValueAlertCondition getCondition(Map<String, Object> parameters, String title) { return new FieldContentValueAlertCondition( searches, mock(Configuration.class), stream, CONDITION_ID, Tools.nowUTC(), STREAM_CREATOR, parameters, title); } protected Map<String, Object> getParametersMap(Integer grace, String field, String value) { Map<String, Object> parameters = new HashMap<>(); parameters.put("grace", grace); parameters.put("field", field); parameters.put("value", value); return parameters; } }
gpl-3.0
KarnYong/BPaaS-modeling
platform extensions/bpmn20xmlbasic/src/de/hpi/bpmn2_0/factory/node/DataStoreFactory.java
3603
/******************************************************************************* * Signavio Core Components * Copyright (C) 2012 Signavio GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package de.hpi.bpmn2_0.factory.node; import org.oryxeditor.server.diagram.generic.GenericShape; import de.hpi.bpmn2_0.annotations.StencilId; import de.hpi.bpmn2_0.exceptions.BpmnConverterException; import de.hpi.bpmn2_0.factory.AbstractShapeFactory; import de.hpi.bpmn2_0.model.BaseElement; import de.hpi.bpmn2_0.model.data_object.DataState; import de.hpi.bpmn2_0.model.data_object.DataStore; import de.hpi.bpmn2_0.model.data_object.DataStoreReference; import de.hpi.diagram.SignavioUUID; /** * Factory for DataStores * * @author Philipp Giese * @author Sven Wagner-Boysen * */ @StencilId("DataStore") public class DataStoreFactory extends AbstractShapeFactory { /* (non-Javadoc) * @see de.hpi.bpmn2_0.factory.AbstractBpmnFactory#createProcessElement(org.oryxeditor.server.diagram.Shape) */ // @Override protected BaseElement createProcessElement(GenericShape shape) throws BpmnConverterException { DataStoreReference dataStoreRef = new DataStoreReference(); this.setCommonAttributes(dataStoreRef, shape); dataStoreRef.setDataStoreRef(new DataStore()); this.setDataStoreRefAttributes(dataStoreRef, shape); return dataStoreRef; } /** * Sets the attributes related to a data store element. * * @param dataStoreRef * The @link {@link DataStoreReference}. * @param shape * The data store {@link GenericShape} */ private void setDataStoreRefAttributes(DataStoreReference dataStoreRef, GenericShape shape) { DataStore dataStore = dataStoreRef.getDataStoreRef(); String dataStateName = shape.getProperty("state"); /* Set attributes of the global data store */ if(dataStore != null) { dataStore.setId(SignavioUUID.generate()); dataStore.setName(shape.getProperty("name")); if(shape.getProperty("capacity") != null && !(shape.getProperty("capacity").length() == 0)) dataStore.setCapacity(Integer.valueOf(shape.getProperty("capacity")).intValue()); /* Set isUnlimited attribute */ String isUnlimited = shape.getProperty("isunlimited"); if(isUnlimited != null && isUnlimited.equalsIgnoreCase("true")) dataStore.setUnlimited(true); else dataStore.setUnlimited(false); /* Define DataState element */ if(dataStateName != null && !(dataStateName.length() == 0)) { DataState dataState = new DataState(dataStateName); dataStore.setDataState(dataState); } } /* Set attributes of the data store reference */ dataStoreRef.setName(shape.getProperty("name")); dataStoreRef.setId(shape.getResourceId()); /* Define DataState element */ if(dataStateName != null && !(dataStateName.length() == 0)) { DataState dataState = new DataState(dataStateName); dataStoreRef.setDataState(dataState); } } }
gpl-3.0
leokdawson/di-geva
GEVA/test/Operator/Operations/ContextSensitiveOperations/NodalMutationTest.java
6288
/* Grammatical Evolution in Java Release: GEVA-v2.0.zip Copyright (C) 2008 Michael O'Neill, Erik Hemberg, Anthony Brabazon, Conor Gilligan Contributors Patrick Middleburgh, Eliott Bartley, Jonathan Hugosson, Jeff Wrigh Separate licences for asm, bsf, antlr, groovy, jscheme, commons-logging, jsci is included in the lib folder. Separate licence for rieps is included in src/com folder. This licence refers to GEVA-v2.0. This software is distributed under the terms of the GNU General Public License. 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/>. />. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Operator.Operations.ContextSensitiveOperations; import Helpers.GrammarCreator; import Helpers.IndividualMaker; import Helpers.JUnitHelper; import Individuals.GEChromosome; import Individuals.GEIndividual; import Individuals.GEIndividualTest; import Mapper.ContextualDerivationTree; import Util.Constants; import Util.GenotypeHelper; import Util.Random.MersenneTwisterFast; import java.util.ArrayList; import java.util.Properties; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author jbyrne */ public class NodalMutationTest { Properties p; Properties p2; public NodalMutationTest() { p = GrammarCreator.getProperties(); p2 = GrammarCreator.getProperties(); p.setProperty(Constants.MAX_WRAPS,"0"); p.setProperty(Constants.DERIVATION_TREE,"Mapper.ContextualDerivationTree"); p2.setProperty(Constants.MAX_WRAPS,"0"); p2.setProperty(Constants.DERIVATION_TREE,"Mapper.ContextualDerivationTree"); String grammar_file = GrammarCreator.getGrammarFile("test_gec.bnf"); p2.setProperty("grammar_file", grammar_file); } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of doOperation method, of class NodalMutation. * create an instance, mutate it, see if its okay */ @Test public void testDoOperation_Individual() { System.out.println("Nodal muation doOperation"); //Integer.MAX_VALUE GEIndividual operand = IndividualMaker.makeIndividual(p); int[] chromosome = {0,1,2}; int[] expected = {0,1,111352301}; GEChromosome geChromosome = (GEChromosome)operand.getGenotype().get(0); geChromosome.setAll(chromosome); NodalMutation instance = new NodalMutation(0.5, new MersenneTwisterFast(2)); instance.doOperation(operand); JUnitHelper.checkArrays(expected, geChromosome.data); GEIndividualTest.testInvalidated(operand); //test to make sure its invalidated geChromosome = null; try { instance.doOperation(operand); } catch(NullPointerException e) { assertTrue(true); } GEIndividualTest.testInvalidated(operand); } /** * Test of doOperation method, of class NodalMutation. * create an instance, mutate it, see if its okay */ @Test public void testDoOperation_codonList() { System.out.println("Nodal mutation codonlist"); //Integer.MAX_VALUE GEIndividual operand = IndividualMaker.makeIndividual(p); int[] chromosome = {1,1,2,1,1,2,4,6,7,8,9,9,9,0,5,4,3}; GEChromosome geChromosome = (GEChromosome)operand.getGenotype().get(0); geChromosome.setAll(chromosome); ContextualDerivationTree tree = (ContextualDerivationTree) GenotypeHelper.buildDerivationTree(operand); System.out.println(tree.toString()); ArrayList<Integer> expected = tree.getNodeCodonList(); NodalMutation instance = new NodalMutation(0.5, new MersenneTwisterFast(2)); instance.doOperation(operand); tree = (ContextualDerivationTree) GenotypeHelper.buildDerivationTree(operand); ArrayList<Integer> result = tree.getNodeCodonList();; System.out.println("expected"+expected.toString()); System.out.println("result"+result.toString()); System.out.println(tree.toString()); JUnitHelper.checkArrays(expected, result); GEIndividualTest.testInvalidated(operand); } //this tests that it will mutate gecodonvalues @Test public void testDoOperation_GECodonValue() { GEIndividual operand = IndividualMaker.makeIndividual(p2); int[] chromosome = {1,2,1,1,2,2,0,0}; int[] expected = {1,2,1937831252,1,2,1748719057,0,0,}; GEChromosome geChromosome = (GEChromosome)operand.getGenotype().get(0); geChromosome.setAll(chromosome); System.out.println("Operand:"+operand); ContextualDerivationTree tree = (ContextualDerivationTree) GenotypeHelper.buildDerivationTree(operand); System.out.println("BEFORE "+operand.getGenotype()); //FIXME Erik Commenting out string because it threw null pointer and I did not know why. And it did not seem to matter to the test what was printed?? //System.out.println(tree.toString()); NodalMutation instance = new NodalMutation(1.0, new MersenneTwisterFast(0)); instance.doOperation(operand); tree = (ContextualDerivationTree) GenotypeHelper.buildDerivationTree(operand); System.out.println("AFTER "+operand.getGenotype()); // System.out.println(tree.toString()); //JUnitHelper.checkArrays(expected, geChromosome.data); //GEIndividualTest.testInvalidated(operand); } }
gpl-3.0
bonepeople/SDCardCleaner
app/src/main/java/com/bonepeople/android/sdcardcleaner/basic/BaseAppCompatActivity.java
3515
package com.bonepeople.android.sdcardcleaner.basic; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.os.Message; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.bonepeople.android.sdcardcleaner.R; import java.util.LinkedList; /** * 集成对Handler控制的基类 * <p> * Created by bonepeople on 2017/12/25. */ public abstract class BaseAppCompatActivity extends AppCompatActivity { private LinkedList<BaseHandler> handlers = null; protected final BaseHandler createHandler() { if (handlers == null) handlers = new LinkedList<>(); BaseHandler handler = new BaseHandler(this); handlers.add(handler); return handler; } protected void handleMessage(Message msg) { } @Override public final void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); onRequestPermission(requestCode, grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED); } /** * 权限申请的回调函数 * * @param requestCode 权限申请的请求ID * @param granted 权限请求的结果 true-获得权限,false-拒绝权限 */ protected void onRequestPermission(int requestCode, boolean granted) { } /** * 检查权限是否已被授权 * * @param permission android.Manifest.permission * @return boolean 是否拥有对应权限 */ protected boolean checkPermission(@NonNull String permission) { return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED; } /** * 申请指定权限 * <p> * 申请某一权限,如需提示用户会创建AlertDialog对用户进行提示,权限申请的结果需要重写{@link #onRequestPermission(int, boolean)}接收 * </p> * * @param permission android.Manifest.permission * @param rationale 提示信息 */ protected void requestPermission(@NonNull final String permission, @Nullable String rationale, final int requestCode) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(rationale); builder.setPositiveButton(R.string.caption_button_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(BaseAppCompatActivity.this, new String[]{permission}, requestCode); } }); builder.setNegativeButton(R.string.caption_button_negative, null); builder.create().show(); } else ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode); } @Override protected void onDestroy() { if (handlers != null) { for (BaseHandler handler : handlers) { handler.destroy(); } handlers.clear(); handlers = null; } super.onDestroy(); } }
gpl-3.0
foxerfly/Wabacus4.1src
src/com/wabacus/system/datatype/IntType.java
3450
/* * Copyright (C) 2010---2013 星星(wuweixing)<349446658@qq.com> * * This file is part of Wabacus * * Wabacus is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.wabacus.system.datatype; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.wabacus.config.database.type.AbsDatabaseType; public class IntType extends AbsNumberType { private final static Log log=LogFactory.getLog(IntType.class); private final static Map<String,AbsNumberType> mIntTypeObjects=new HashMap<String,AbsNumberType>(); public Object getColumnValue(ResultSet rs,String column,AbsDatabaseType dbtype) throws SQLException { return Integer.valueOf(rs.getInt(column)); } public Object getColumnValue(ResultSet rs,int iindex,AbsDatabaseType dbtype) throws SQLException { return Integer.valueOf(rs.getInt(iindex)); } public void setPreparedStatementValue(int iindex,String value,PreparedStatement pstmt, AbsDatabaseType dbtype) throws SQLException { log.debug("setInt("+iindex+","+value+")"); Object objTmp=label2value(value); if(objTmp==null) { pstmt.setObject(iindex,null,java.sql.Types.INTEGER); }else { pstmt.setInt(iindex,(Integer)objTmp); } } public Class getJavaTypeClass() { return Integer.class; } public Object label2value(String label) { if(label==null||label.trim().equals("")) return null; if(this.numberformat!=null&&!this.numberformat.trim().equals("")) { return Integer.valueOf(this.getNumber(label.trim()).intValue()); }else { int idxdot=label.indexOf("."); if(idxdot==0) { label="0"; }else if(idxdot>0) { label=label.substring(0,idxdot).trim(); if(label.equals("")) label="0"; } return Integer.valueOf(label.trim()); } } public String value2label(Object value) { if(value==null) return ""; if(!(value instanceof Integer)) return String.valueOf(value); if(this.numberformat!=null&&!this.numberformat.trim().equals("")) { DecimalFormat df=new DecimalFormat(this.numberformat); return df.format((Integer)value); }else { return String.valueOf(value); } } protected Map<String,AbsNumberType> getAllMNumberTypeObjects() { return mIntTypeObjects; } }
gpl-3.0
Piron1991/Builder_tools
src/main/java/com/piron1991/builder_tools/reference/Reference.java
575
package com.piron1991.builder_tools.reference; public class Reference { public static final String MOD_ID = "builder_tools"; public static final String VERSION = "0.1"; public static final String MOD_NAME = "Builder tools"; public static final String CPROXY = "com.piron1991.builder_tools.proxy.clientProxy"; public static final String SPROXY = "com.piron1991.builder_tools.proxy.serverProxy"; public static final String SIZE_CATEGORY="Ranges of block placings for tools: "; public static final String RECIPE_CATEGORY="Recipes for tools: "; }
gpl-3.0
pahans/Kichibichiya
src/com/pahans/kichibichiya/loader/UserSearchLoader.java
1944
/* * Twidere - Twitter client for Android * * Copyright (C) 2012 Mariotaku Lee <mariotaku.lee@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pahans.kichibichiya.loader; import java.util.ArrayList; import java.util.List; import com.pahans.kichibichiya.model.ParcelableUser; import twitter4j.ResponseList; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.User; import android.content.Context; public class UserSearchLoader extends ParcelableUsersLoader { private final String mQuery; private final int mPage; private final long mAccountId; public UserSearchLoader(final Context context, final long account_id, final String query, final int page, final List<ParcelableUser> users_list) { super(context, account_id, users_list); mQuery = query; mPage = page; mAccountId = account_id; } @Override public List<ParcelableUser> getUsers() throws TwitterException { final Twitter twitter = getTwitter(); if (twitter == null) return null; final ResponseList<User> users = twitter.searchUsers(mQuery, mPage); final List<ParcelableUser> result = new ArrayList<ParcelableUser>(); final int size = users.size(); for (int i = 0; i < size; i++) { result.add(new ParcelableUser(users.get(i), mAccountId, (mPage - 1) * 20 + i)); } return result; } }
gpl-3.0
Techwave-dev/OpenGlModernGameEngine
src/com/teckcoder/crashengine/file/FileStream.java
1379
package com.teckcoder.crashengine.file; import com.teckcoder.crashengine.utils.logger.Logger; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class FileStream { File file = null; FileLocationType locationType = null; private FileStream(String path, FileLocationType locationType){ this.locationType = locationType; file = new File(path); } public static FileStream loadInternalFile(String path){ FileStream file = new FileStream(path, FileLocationType.INTERNAL); return file; } public static FileStream loadExternalFile(String path){ FileStream file = new FileStream(path, FileLocationType.EXTERNAL); return file; } public InputStream getInputStream() { if(locationType == FileLocationType.EXTERNAL) try { return new FileInputStream(file.getPath().replace("\\", "/")); } catch (FileNotFoundException e) { e.printStackTrace(); Logger.logError("file missing", "Le fichier n'existe pas!"); } else if(locationType == FileLocationType.INTERNAL) return FileStream.class.getResourceAsStream("/"+file.getPath().replace("\\", "/")); Logger.logError("file location", "FileLocationType erreur"); return null; } public File getFile(){ return file; } public FileLocationType getFileLocationType(){ return locationType; } }
gpl-3.0
xGamers665/tera-emu
com.tera.common.database/src/main/java/com/tera/common/database/dao/ServerPropertiesDAO.java
1348
/** * This file is part of tera-api. * * tera-api 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. * * tera-api 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 tera-api. If not, see <http://www.gnu.org/licenses/>. */ package com.tera.common.database.dao; import java.util.Map; import com.tera.common.model.context.Context; import com.tera.common.model.context.ContextType; /** * @author ATracer */ @Context(type = ContextType.DAO) public interface ServerPropertiesDAO extends ContextDAO { /** * @param name * @return */ String loadProperty(String name); /** * @return */ Map<String, String> loadProperties(); /** * @param name * @return */ boolean hasProperty(String name); /** * @param name * @param value */ void saveProperty(String name, String value, boolean isNew); }
gpl-3.0
NYRDS/pixel-dungeon-remix
RemixedDungeon/src/main/java/com/watabou/pixeldungeon/windows/WndModSelect.java
5619
package com.watabou.pixeldungeon.windows; import com.nyrds.pixeldungeon.game.GameLoop; import com.nyrds.pixeldungeon.game.GamePreferences; import com.nyrds.pixeldungeon.ml.R; import com.nyrds.pixeldungeon.utils.ModDesc; import com.nyrds.pixeldungeon.windows.DownloadProgressWindow; import com.nyrds.pixeldungeon.windows.ScrollableList; import com.nyrds.pixeldungeon.windows.WndHelper; import com.nyrds.platform.game.RemixedDungeon; import com.nyrds.platform.storage.FileSystem; import com.nyrds.platform.util.StringsManager; import com.nyrds.util.DownloadStateListener; import com.nyrds.util.DownloadTask; import com.nyrds.util.GuiProperties; import com.nyrds.util.ModdingMode; import com.nyrds.util.Mods; import com.nyrds.util.UnzipStateListener; import com.nyrds.util.UnzipTask; import com.nyrds.util.Util; import com.watabou.noosa.Text; import com.watabou.noosa.ui.Component; import com.watabou.pixeldungeon.SaveUtils; import com.watabou.pixeldungeon.scenes.PixelScene; import com.watabou.pixeldungeon.ui.Icons; import com.watabou.pixeldungeon.ui.RedButton; import com.watabou.pixeldungeon.ui.SimpleButton; import com.watabou.pixeldungeon.ui.Window; import com.watabou.pixeldungeon.utils.Utils; import java.io.File; import java.util.Map; public class WndModSelect extends Window implements DownloadStateListener.IDownloadComplete, UnzipStateListener { private String selectedMod; private String downloadTo; private final Map<String, ModDesc> modsList; public WndModSelect() { super(); resizeLimited(120); modsList = Mods.buildModsList(); boolean haveInternet = Util.isConnectedToInternet(); Text tfTitle = PixelScene.createMultiline(StringsManager.getVar(R.string.ModsButton_SelectMod), GuiProperties.titleFontSize()); tfTitle.hardlight(TITLE_COLOR); tfTitle.x = tfTitle.y = GAP; tfTitle.maxWidth(width - GAP * 2); add(tfTitle); ScrollableList list = new ScrollableList(new Component()); add(list); float pos = 0; for (Map.Entry<String, ModDesc> entry : modsList.entrySet()) { final ModDesc desc = entry.getValue(); float additionalMargin = Icons.get(Icons.CLOSE).width() + GAP; if (desc.installed && !ModdingMode.REMIXED.equals(desc.name)) { SimpleButton deleteBtn = new SimpleButton(Icons.get(Icons.CLOSE)) { protected void onClick() { onDelete(desc.installDir); } }; deleteBtn.setPos(width - (deleteBtn.width() * 2) - GAP, pos + (BUTTON_HEIGHT - deleteBtn.height())/2); list.content().add(deleteBtn); } String option = desc.name; if (desc.needUpdate && haveInternet) { option = "Update " + option; } if (desc.installed || haveInternet) { RedButton btn = new RedButton(option) { @Override protected void onClick() { hide(); onSelect(desc.installDir); } }; btn.setRect(GAP, pos, width - GAP * 2 - (additionalMargin * 2), BUTTON_HEIGHT); list.content().add(btn); pos += BUTTON_HEIGHT + GAP; } } resize(WndHelper.getLimitedWidth(120), WndHelper.getFullscreenHeight() - WINDOW_MARGIN); list.content().setSize(width, pos); list.setRect(0, tfTitle.bottom() + GAP, width, height - tfTitle.height() - GAP); list.scrollTo(0,0); } private void onDelete(String name) { File modDir = FileSystem.getExternalStorageFile(name); if (modDir.exists() && modDir.isDirectory()) { FileSystem.deleteRecursive(modDir); } if (GamePreferences.activeMod().equals(name)) { SaveUtils.deleteGameAllClasses(); SaveUtils.copyAllClassesFromSlot(ModdingMode.REMIXED); GamePreferences.activeMod(ModdingMode.REMIXED); RemixedDungeon.instance().doRestart(); } if (getParent() != null) { hide(); } GameLoop.addToScene(new WndModSelect()); } protected void onSelect(String option) { ModDesc desc = modsList.get(option); if (!option.equals(ModdingMode.REMIXED) || desc.needUpdate) { if (desc.needUpdate) { FileSystem.deleteRecursive(FileSystem.getExternalStorageFile(desc.installDir)); selectedMod = desc.installDir; downloadTo = FileSystem.getExternalStorageFile(selectedMod+".tmp").getAbsolutePath(); desc.needUpdate = false; GameLoop.execute(new DownloadTask(new DownloadProgressWindow(Utils.format("Downloading %s", selectedMod),this), desc.url, downloadTo)); return; } } String prevMod = GamePreferences.activeMod(); if (option.equals(prevMod)) { return; } if (getParent() != null) { hide(); } GameLoop.addToScene(new WndModDescription(option, prevMod)); } @Override public void DownloadComplete(String url, final Boolean result) { GameLoop.pushUiTask(() -> { if (result) { GameLoop.execute(new UnzipTask(WndModSelect.this, downloadTo, true)); } else { GameLoop.addToScene(new WndError(Utils.format("Downloading %s failed", selectedMod))); } }); } private WndMessage unzipProgress; @Override public void UnzipComplete(final Boolean result) { GameLoop.pushUiTask(() -> { if(unzipProgress!=null) { unzipProgress.hide(); unzipProgress = null; } if (result) { GameLoop.addToScene(new WndModSelect()); } else { GameLoop.addToScene(new WndError(Utils.format("unzipping %s failed", downloadTo))); } }); } @Override public void UnzipProgress(Integer unpacked) { GameLoop.pushUiTask(() -> { if (unzipProgress == null) { unzipProgress = new WndMessage(Utils.EMPTY_STRING); GameLoop.addToScene(unzipProgress); } if (unzipProgress.getParent() == GameLoop.scene()) { unzipProgress.setText(Utils.format("Unpacking: %d", unpacked)); } }); } }
gpl-3.0
mbshopM/openconcerto
OpenConcerto/src/org/openconcerto/sql/element/SQLElementDirectory.java
11868
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. * * The contents of this file are subject to the terms of the GNU General Public License Version 3 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each file. */ package org.openconcerto.sql.element; import org.openconcerto.sql.Log; import org.openconcerto.sql.TM; import org.openconcerto.sql.model.DBStructureItemNotFound; import org.openconcerto.sql.model.SQLName; import org.openconcerto.sql.model.SQLTable; import org.openconcerto.utils.CollectionUtils; import org.openconcerto.utils.SetMap; import org.openconcerto.utils.cc.ITransformer; import org.openconcerto.utils.i18n.LocalizedInstances; import org.openconcerto.utils.i18n.Phrase; import org.openconcerto.utils.i18n.TranslationManager; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.jdom.JDOMException; /** * Directory of SQLElement by table. * * @author Sylvain CUAZ */ public final class SQLElementDirectory { public static final String BASENAME = SQLElementNames.class.getSimpleName(); private static final LocalizedInstances<SQLElementNames> LOCALIZED_INSTANCES = new LocalizedInstances<SQLElementNames>(SQLElementNames.class, TranslationManager.getControl()) { @Override protected SQLElementNames createInstance(String bundleName, Locale candidate, Class<?> cl) throws IOException { final InputStream ins = cl.getResourceAsStream('/' + getControl().toResourceName(bundleName, "xml")); if (ins == null) return null; final SQLElementNamesFromXML res = new SQLElementNamesFromXML(candidate); try { res.load(ins); } catch (JDOMException e) { throw new IOException("Invalid XML", e); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException(e); } finally { ins.close(); } return res; } }; private final Map<SQLTable, SQLElement> elements; private final SetMap<String, SQLTable> tableNames; private final SetMap<String, SQLTable> byCode; private final SetMap<Class<? extends SQLElement>, SQLTable> byClass; private final List<DirectoryListener> listeners; private String phrasesPkgName; private final Map<String, SQLElementNames> elementNames; public SQLElementDirectory() { this.elements = new HashMap<SQLTable, SQLElement>(); // to mimic elements behaviour, if we add twice the same table // the second one should replace the first one this.tableNames = new SetMap<String, SQLTable>(); this.byCode = new SetMap<String, SQLTable>(); this.byClass = new SetMap<Class<? extends SQLElement>, SQLTable>(); this.listeners = new ArrayList<DirectoryListener>(); this.phrasesPkgName = null; this.elementNames = new HashMap<String, SQLElementNames>(); } private static <K> SQLTable getSoleTable(SetMap<K, SQLTable> m, K key) throws IllegalArgumentException { final Collection<SQLTable> res = m.getNonNull(key); if (res.size() > 1) throw new IllegalArgumentException(key + " is not unique: " + CollectionUtils.join(res, ",", new ITransformer<SQLTable, SQLName>() { @Override public SQLName transformChecked(SQLTable input) { return input.getSQLName(); } })); return CollectionUtils.getSole(res); } public synchronized final void putAll(SQLElementDirectory o) { for (final SQLElement elem : o.getElements()) { if (!this.contains(elem.getTable())) this.addSQLElement(elem); } } /** * Add an element by creating it with the no-arg constructor. If the element cannot find its * table and thus raise DBStructureItemNotFound, the exception is logged. * * @param element the element to add. */ public final void addSQLElement(final Class<? extends SQLElement> element) { try { this.addSQLElement(element.getConstructor().newInstance()); } catch (InvocationTargetException e) { if (e.getCause() instanceof DBStructureItemNotFound) { Log.get().config("ignore inexistent tables: " + e.getCause().getLocalizedMessage()); return; } throw new IllegalArgumentException("ctor failed", e); } catch (Exception e) { throw new IllegalArgumentException("no-arg ctor failed", e); } } /** * Adds an already instantiated element. * * @param elem the SQLElement to add. * @return the previously added element. */ public synchronized final SQLElement addSQLElement(SQLElement elem) { final SQLElement res = this.removeSQLElement(elem.getTable()); this.elements.put(elem.getTable(), elem); this.tableNames.add(elem.getTable().getName(), elem.getTable()); this.byCode.add(elem.getCode(), elem.getTable()); this.byClass.add(elem.getClass(), elem.getTable()); for (final DirectoryListener dl : this.listeners) { dl.elementAdded(elem); } elem.setDirectory(this); return res; } public synchronized final boolean contains(SQLTable t) { return this.elements.containsKey(t); } public synchronized final SQLElement getElement(SQLTable t) { return this.elements.get(t); } /** * Search for a table whose name is <code>tableName</code>. * * @param tableName a table name, e.g. "ADRESSE". * @return the corresponding SQLElement, or <code>null</code> if there is no table named * <code>tableName</code>. * @throws IllegalArgumentException if more than one table match. */ public synchronized final SQLElement getElement(String tableName) { return this.getElement(getSoleTable(this.tableNames, tableName)); } /** * Search for an SQLElement whose class is <code>clazz</code>. * * @param <S> type of SQLElement * @param clazz the class. * @return the corresponding SQLElement, or <code>null</code> if none can be found. * @throws IllegalArgumentException if there's more than one match. */ public synchronized final <S extends SQLElement> S getElement(Class<S> clazz) { return clazz.cast(this.getElement(getSoleTable(this.byClass, clazz))); } public synchronized final SQLElement getElementForCode(String code) { return this.getElement(getSoleTable(this.byCode, code)); } public synchronized final Set<SQLTable> getTables() { return this.getElementsMap().keySet(); } public synchronized final Collection<SQLElement> getElements() { return this.getElementsMap().values(); } public final Map<SQLTable, SQLElement> getElementsMap() { return Collections.unmodifiableMap(this.elements); } /** * Remove the passed instance. NOTE: this method only remove the specific instance passed, so * it's a conditional <code>removeSQLElement(elem.getTable())</code>. * * @param elem the instance to remove. * @see #removeSQLElement(SQLTable) */ public synchronized void removeSQLElement(SQLElement elem) { if (this.getElement(elem.getTable()) == elem) this.removeSQLElement(elem.getTable()); } /** * Remove the element for the passed table. * * @param t the table to remove. * @return the removed element, can be <code>null</code>. */ public synchronized SQLElement removeSQLElement(SQLTable t) { final SQLElement elem = this.elements.remove(t); if (elem != null) { this.tableNames.remove(elem.getTable().getName(), elem.getTable()); this.byCode.remove(elem.getCode(), elem.getTable()); this.byClass.remove(elem.getClass(), elem.getTable()); // MAYBE only reset neighbours. for (final SQLElement otherElem : this.elements.values()) otherElem.resetRelationships(); elem.setDirectory(null); for (final DirectoryListener dl : this.listeners) { dl.elementRemoved(elem); } } return elem; } public synchronized final void initL18nPackageName(final String baseName) { if (this.phrasesPkgName != null) throw new IllegalStateException("Already initialized : " + this.getL18nPackageName()); this.phrasesPkgName = baseName; } public synchronized final String getL18nPackageName() { return this.phrasesPkgName; } protected synchronized final SQLElementNames getElementNames(final String pkgName, final Locale locale, final Class<?> cl) { if (pkgName == null) return null; final char sep = ' '; final String key = pkgName + sep + locale.toString(); assert pkgName.indexOf(sep) < 0 : "ambiguous key : " + key; SQLElementNames res = this.elementNames.get(key); if (res == null) { final List<SQLElementNames> l = LOCALIZED_INSTANCES.createInstances(pkgName + "." + BASENAME, locale, cl).get1(); if (!l.isEmpty()) { for (int i = 1; i < l.size(); i++) { l.get(i - 1).setParent(l.get(i)); } res = l.get(0); } this.elementNames.put(key, res); } return res; } /** * Search a name for the passed instance and the {@link TM#getTranslationsLocale() current * locale}. Search for {@link SQLElementNames} using {@link LocalizedInstances} and * {@link SQLElementNamesFromXML} first in {@link SQLElement#getL18nPackageName()} then in * {@link #getL18nPackageName()}. E.g. this could load SQLElementNames_en.class and * SQLElementNames_en_UK.xml. * * @param elem the element. * @return the name if found, <code>null</code> otherwise. */ public final Phrase getName(final SQLElement elem) { final String elemBaseName = elem.getL18nPackageName(); final String pkgName = elemBaseName == null ? getL18nPackageName() : elemBaseName; final SQLElementNames elementNames = getElementNames(pkgName, TM.getInstance().getTranslationsLocale(), elem.getL18nClass()); return elementNames == null ? null : elementNames.getName(elem); } public synchronized final void addListener(DirectoryListener dl) { this.listeners.add(dl); } public synchronized final void removeListener(DirectoryListener dl) { this.listeners.remove(dl); } static public interface DirectoryListener { void elementAdded(SQLElement elem); void elementRemoved(SQLElement elem); } }
gpl-3.0
iCarto/siga
libCorePlugin/src/com/iver/core/ConfigExtension.java
2163
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. * * For more information, contact: * * Generalitat Valenciana * Conselleria d'Infraestructures i Transport * Av. Blasco Ibáñez, 50 * 46010 VALENCIA * SPAIN * * +34 963862235 * gvsig@gva.es * www.gvsig.gva.es * * or * * IVER T.I. S.A * Salamanca 50 * 46005 Valencia * Spain * * +34 963163400 * dac@iver.es */ package com.iver.core; /** */ import com.iver.andami.PluginServices; import com.iver.andami.plugins.Extension; import com.iver.core.configExtensions.ConfigPlugins; /** * Extensión para abrir el diálogo de configuración de ANDAMI. * * @author Vicente Caballero Navarro * @deprecated * */ public class ConfigExtension extends Extension { /* (non-Javadoc) * @see com.iver.andami.plugins.Extension#execute(java.lang.String) */ public void execute(String actionCommand) { ConfigPlugins cp=new ConfigPlugins(); PluginServices.getMDIManager().addWindow(cp); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisible() { return true; } /** * @see com.iver.mdiApp.plugins.IExtension#isEnabled() */ public boolean isEnabled() { return true; } /** * @see com.iver.andami.plugins.IExtension#initialize() */ public void initialize() { } }
gpl-3.0
yangweijun213/Java
J2SE300/28_51OO/src/cn/bjsxt/oop/inherit/Animal2.java
1087
package cn.bjsxt.oop.inherit; /** * 测试组合 * @author dell * */ public class Animal2 { String eye; public void run(){ System.out.println("跑跑!"); } public void eat(){ System.out.println("吃吃!"); } public void sleep(){ System.out.println("zzzzz"); } public Animal2(){ super(); System.out.println("创建一个动物!"); } public static void main(String[] args) { Bird2 b = new Bird2(); b.run(); b.animal2.eat(); } } class Mammal2 { Animal2 animal2=new Animal2(); //所谓组合,就是将父类的animal2作为属性防在这里 public void taisheng(){ System.out.println("我是胎生"); } } class Bird2 { Animal2 animal2=new Animal2(); //所谓组合,就是将父类的animal2作为属性防在这里 public void run(){ animal2.run(); System.out.println("我是一个小小小小鸟,飞呀飞不高"); } public void eggSheng(){ System.out.println("卵生"); } public Bird2(){ super(); System.out.println("建一个鸟对象"); } }
gpl-3.0
00-Evan/shattered-pixel-dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/tiles/DungeonWallsTilemap.java
3780
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2021 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.tiles; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain; public class DungeonWallsTilemap extends DungeonTilemap { public DungeonWallsTilemap(){ super(Dungeon.level.tilesTex()); map( Dungeon.level.map, Dungeon.level.width() ); } @Override protected int getTileVisual(int pos, int tile, boolean flat){ if (flat) return -1; if (DungeonTileSheet.wallStitcheable(tile)) { if (pos + mapWidth < size && !DungeonTileSheet.wallStitcheable(map[pos + mapWidth])){ if (map[pos + mapWidth] == Terrain.DOOR){ return DungeonTileSheet.DOOR_SIDEWAYS; } else if (map[pos + mapWidth] == Terrain.LOCKED_DOOR){ return DungeonTileSheet.DOOR_SIDEWAYS_LOCKED; } else if (map[pos + mapWidth] == Terrain.OPEN_DOOR){ return DungeonTileSheet.NULL_TILE; } } else { return DungeonTileSheet.stitchInternalWallTile( tile, (pos+1) % mapWidth != 0 ? map[pos + 1] : -1, (pos+1) % mapWidth != 0 && pos + mapWidth < size ? map[pos + 1 + mapWidth] : -1, pos + mapWidth < size ? map[pos + mapWidth] : -1, pos % mapWidth != 0 && pos + mapWidth < size ? map[pos - 1 + mapWidth] : -1, pos % mapWidth != 0 ? map[pos - 1] : -1 ); } } if (pos + mapWidth < size && DungeonTileSheet.wallStitcheable(map[pos+mapWidth])) { return DungeonTileSheet.stitchWallOverhangTile( tile, (pos+1) % mapWidth != 0 ? map[pos + 1 + mapWidth] : -1, map[pos + mapWidth], pos % mapWidth != 0 ? map[pos - 1 + mapWidth] : -1 ); } else if (Dungeon.level.insideMap(pos) && (map[pos+mapWidth] == Terrain.DOOR || map[pos+mapWidth] == Terrain.LOCKED_DOOR) ) { return DungeonTileSheet.DOOR_OVERHANG; } else if (Dungeon.level.insideMap(pos) && map[pos+mapWidth] == Terrain.OPEN_DOOR ) { return DungeonTileSheet.DOOR_OVERHANG_OPEN; } else if (pos + mapWidth < size && (map[pos+mapWidth] == Terrain.STATUE || map[pos+mapWidth] == Terrain.STATUE_SP)){ return DungeonTileSheet.STATUE_OVERHANG; } else if (pos + mapWidth < size && map[pos+mapWidth] == Terrain.ALCHEMY){ return DungeonTileSheet.ALCHEMY_POT_OVERHANG; } else if (pos + mapWidth < size && map[pos+mapWidth] == Terrain.BARRICADE){ return DungeonTileSheet.BARRICADE_OVERHANG; } else if (pos + mapWidth < size && map[pos+mapWidth] == Terrain.HIGH_GRASS){ return DungeonTileSheet.getVisualWithAlts(DungeonTileSheet.HIGH_GRASS_OVERHANG, pos + mapWidth); } else if (pos + mapWidth < size && map[pos+mapWidth] == Terrain.FURROWED_GRASS){ return DungeonTileSheet.getVisualWithAlts(DungeonTileSheet.FURROWED_OVERHANG, pos + mapWidth); } return -1; } @Override public boolean overlapsPoint( float x, float y ) { return true; } @Override public boolean overlapsScreenPoint( int x, int y ) { return true; } }
gpl-3.0
BlenderViking/NewPipe
app/src/main/java/org/schabi/newpipe/player/LunchAudioTrack.java
10189
package org.schabi.newpipe.player; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.Log; import android.view.View; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import org.schabi.newpipe.ActivityCommunicator; import org.schabi.newpipe.R; import org.schabi.newpipe.extractor.MediaFormat; import org.schabi.newpipe.extractor.NewPipe; import org.schabi.newpipe.extractor.exceptions.ParsingException; import org.schabi.newpipe.extractor.stream_info.AudioStream; import org.schabi.newpipe.extractor.stream_info.StreamExtractor; import org.schabi.newpipe.extractor.stream_info.StreamPreviewInfo; import org.schabi.newpipe.extractor.stream_info.VideoStream; import org.schabi.newpipe.playList.NewPipeSQLiteHelper; import org.schabi.newpipe.settings.NetworkHelper; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.schabi.newpipe.search_fragment.SearchInfoItemFragment.PLAYLIST_ID; public class LunchAudioTrack { private final static String TAG = LunchAudioTrack.class.getName(); private final Context activity; private StreamPreviewInfo info = null; private Bitmap bitmap = null; private AudioStream audioStream = null; private final int playListId; private boolean hasLoadBitmap = false; private boolean hasAudioStream = false; public LunchAudioTrack(final Context activity, @NonNull final StreamPreviewInfo info, final int playListId) { this.activity = activity; this.info = info; this.playListId = playListId; } public void retrieveBitmap(final Runnable callback) { hasLoadBitmap = true; if (!TextUtils.isEmpty(info.thumbnail_url)) { ImageLoader.getInstance().loadImage(info.thumbnail_url, new ImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { Log.e(TAG, String.format("FAILED to load bitmap at %s", imageUri), failReason.getCause()); } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { Log.d(TAG, String.format("SUCCESS to load bitmap at %s", imageUri)); bitmap = loadedImage; if(callback != null) { callback.run(); } } @Override public void onLoadingCancelled(String imageUri, View view) { } }); } } public void retrieveInfoFromService(final Runnable callback) { hasAudioStream = true; new AsyncTask<Void, Void, AudioStream>() { @Override protected AudioStream doInBackground(Void... voids) { if(info != null) { try { final StreamExtractor extractor = NewPipe.getService(info.service_id) .getExtractorInstance(info.webpage_url); try { final List<AudioStream> audioStreams = extractor.getAudioStreams(); Log.d(TAG, String.format("Found %d audio track for song at %s", audioStreams.size(), info.webpage_url)); final AudioStream audioStream = audioStreams .get(getPreferredAudioStreamId(audioStreams)); Log.d(TAG, String.format("Url for track at %s\r\n%s", info.webpage_url, audioStream)); return audioStream; } catch (ParsingException e) { // fail back convert video to audio final List<VideoStream> videoStreams = extractor.getVideoStreams(); VideoStream selectedVideoStreamsBest = null; VideoStream selectedVideoStreamsSmall = null; int previousResolution = -1; for (final VideoStream videoStream : videoStreams) { if ("360p".equals(videoStream.resolution)) { selectedVideoStreamsBest = videoStream; } final int resolution = extractNumberPositiveInteger(videoStream.resolution); if (previousResolution == -1 || resolution < previousResolution) { previousResolution = resolution; selectedVideoStreamsSmall = videoStream; } } // check if we use wifi or not for avoid big download data on mobile network final boolean isConnectedByWifi = NetworkHelper.isOnlineByWifi(activity); final VideoStream videoStream = isConnectedByWifi && selectedVideoStreamsBest != null ? selectedVideoStreamsBest : selectedVideoStreamsSmall; if(videoStream == null) { return null; } Log.w(TAG, String.format("No audio track found, use fallback process " + "convert to AudioStream the video item (%s - %s)", MediaFormat.getMimeById(videoStream.format), videoStream.resolution)); return new AudioStream(videoStream.url, videoStream.format, -1, -1); } } catch (Exception e) { Log.e(TAG, "FAILED to found a proper audioStream value!", e); return null; } } else { return null; } } private int extractNumberPositiveInteger(final String str) { final Matcher m = Pattern.compile("[0-9]+").matcher(str); return m.find() ? Integer.parseInt(m.group()) : -1; } @Override protected void onPostExecute(AudioStream preferedAudioStream) { super.onPostExecute(preferedAudioStream); audioStream = preferedAudioStream; if(callback != null) { callback.run(); } } }.execute(); } private int getPreferredAudioStreamId(final List<AudioStream> audioStreams) { String preferredFormatString = PreferenceManager.getDefaultSharedPreferences(activity) .getString(activity.getString(R.string.default_audio_format_key), "webm"); int preferredFormat = MediaFormat.WEBMA.id; switch (preferredFormatString) { case "webm": preferredFormat = MediaFormat.WEBMA.id; break; case "m4a": preferredFormat = MediaFormat.M4A.id; break; default: break; } for (int i = 0; i < audioStreams.size(); i++) { if (audioStreams.get(i).format == preferredFormat) { Log.d(TAG, String.format("Preferred audio format found : %s with id : %d", preferredFormatString, preferredFormat)); return i; } } //todo: make this a proper error Log.e(TAG, "FAILED to set audioStream value, use the default value 0 !"); return 0; } public boolean hasLoadBitmap() { return hasLoadBitmap; } public boolean hasAudioStream() { return hasAudioStream; } public Intent retrieveIntent() { if (bitmap != null && audioStream != null) { ActivityCommunicator.getCommunicator().backgroundPlayerThumbnail = bitmap; final String mime = MediaFormat.getMimeById(audioStream.format); final Uri uri = Uri.parse(audioStream.url); final Intent intent = new Intent(activity, BackgroundPlayer.class); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(uri, mime); intent.putExtra(BackgroundPlayer.TITLE, info.title); intent.putExtra(BackgroundPlayer.WEB_URL, info.webpage_url); intent.putExtra(BackgroundPlayer.SERVICE_ID, info.service_id); intent.putExtra(PLAYLIST_ID, playListId); intent.putExtra(NewPipeSQLiteHelper.PLAYLIST_LINK_ENTRIES.POSITION, info.position); intent.putExtra(BackgroundPlayer.CHANNEL_NAME, info.uploader); return intent; } else { return null; } } public void process(final boolean forcePlay) { if (!BackgroundPlayer.isRunning || forcePlay) { if (bitmap != null && audioStream != null) { activity.startService(retrieveIntent()); } else if (!hasLoadBitmap) { retrieveBitmap(new Runnable() { @Override public void run() { process(forcePlay); } }); } else if (!hasAudioStream) { retrieveInfoFromService(new Runnable() { @Override public void run() { process(forcePlay); } }); } } } }
gpl-3.0
fauconnier/LaToe
src/org/melodi/learning/service/Classifier_MaxEnt.java
3139
package org.melodi.learning.service; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.melodi.tools.dataset.DataSet_Corpora; import org.melodi.tools.evaluation.Evaluation_Service; import opennlp.maxent.BasicEventStream; import opennlp.maxent.GIS; import opennlp.maxent.PlainTextByLineDataStream; import opennlp.model.AbstractModel; import opennlp.model.EventStream; public class Classifier_MaxEnt { AbstractModel model; public static double SMOOTHING_OBSERVATION = 0.1; public Classifier_MaxEnt() { } public AbstractModel train(FeatureGenerator_Service featureGen, int iteration, int cutoff, boolean USE_SMOOTHING, double value_smooth) throws IOException{ this.SMOOTHING_OBSERVATION = value_smooth; return this.train(featureGen,iteration,cutoff,USE_SMOOTHING); } public AbstractModel train(FeatureGenerator_Service featureGen, int iteration, int cutoff) throws IOException{ return this.train(featureGen,iteration,cutoff,false); } public AbstractModel train(FeatureGenerator_Service featureGen, int iteration) throws IOException{ return this.train(featureGen,iteration,0,false); } public AbstractModel train(FeatureGenerator_Service featureGen) throws IOException{ return this.train(featureGen,100,0,false); } public AbstractModel train(FeatureGenerator_Service featureGen, int iteration, int cutoff, boolean USE_SMOOTHING) throws IOException { // TODO : Utilisable mais améliorable sans passer par écriture/lecture! // TODO : Ecrire un vrai wrapper. featureGen.writeMaxEnt("dataset_train.txt"); FileReader datafr = new FileReader(new File("dataset_train.txt")); EventStream es = new BasicEventStream(new PlainTextByLineDataStream( datafr)); GIS.SMOOTHING_OBSERVATION = SMOOTHING_OBSERVATION; model = GIS.trainModel(es, iteration, cutoff, USE_SMOOTHING, true ); // Data Structures // datastructure[0] = model parameters // datastructure[1] = java.util.Map (mapping model predicate to unique integers) // datastructure[2] = java.lang.String[] names of outcomes // datastructure[3] = java.lang.integer : value of models correction constante // datastructure[4] = java.lang.Double : value of models correction paramter return model; } public Evaluation_Service predict(AbstractModel model, DataSet_Corpora corpora, FeatureGenerator_Service featureGen) { Evaluation_Service evaluator = new Evaluation_Service(); evaluator.setName("evaluator"); evaluator.setCorpora(corpora); for(PairUnit_Features currPair : featureGen){ predict(model, currPair); } return evaluator; } public void predict(AbstractModel model, PairUnit_Features currPair){ String predicates = ""; for(String currString : currPair.getFeatures()){ predicates += currString + " "; } String[] contexts = predicates.split(" "); double[] ocs = model.eval(contexts); currPair.getUnit().setPredict_y(model.getBestOutcome(ocs)); // System.out.println("For context: " + predicates+ "\n" + model.getAllOutcomes(ocs) + "\n"); } }
gpl-3.0
petebrew/tellervo
src/main/java/org/tellervo/desktop/hardware/device/LintabDevice.java
11073
/******************************************************************************* * Copyright (C) 2010 Lucas Madar and Peter Brewer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * Lucas Madar * Peter Brewer ******************************************************************************/ package org.tellervo.desktop.hardware.device; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tellervo.desktop.admin.model.GroupsWithPermissionsTableModel; import org.tellervo.desktop.hardware.AbstractMeasuringDevice; import org.tellervo.desktop.hardware.AbstractSerialMeasuringDevice; import org.tellervo.desktop.hardware.MeasuringSampleIOEvent; import gnu.io.SerialPortEvent; /** * The LINTAB platform is made by RINNTECH. The original platform uses a protocol * that RINNTECH claim is proprietary. An agreement was made whereby RINNTECH * would produce and supply new boxes that would attach to LINTAB platforms that * communicate with a non-proprietary ASCII-based protocol. Users must purchase * such an adapter to use LINTAB platforms with Tellervo (or any other software * other than TSAP-Win). * * These new boxes include a serial and USB connection. The USB connection is * provided by an internal USB-to-serial adapter (driver from www.ftdichip.com). * * Both serial and virtual-serial connections use the following parameters: * - Baud: 1200 * - Data bits : 8 * - Stop bits : 1 * - Parity : none * - Flow control : none * * There is no way for the user to alter these settings. * * Data is transmitted by LINTAB whenever the platform is moved. The data is * as follows: * [integer position in 1/1000mm];[add button state �0� or �1�][reset button state �0� or �1�][LF] * * LINTAB also accepts commands. To force a manual data record output the ASCII-command * GETDATA should be sent to LINTAB. A reset of the counter is done by sending the * ASCII-command RESET to LINTAB. After a command a linefeed (0x0A) or carriage return * (0x0D) must sent to execute the command. * * @author peterbrewer * */ public class LintabDevice extends AbstractSerialMeasuringDevice{ private static final int EVE_ENQ = 5; private Boolean fireOnNextValue = false; private String previousFireState = "0"; private Boolean resetting = false; private Boolean isInitialized = false; int resetCounter = 0; private final static Logger log = LoggerFactory.getLogger(LintabDevice.class); @Override public void setDefaultPortParams() { baudRate = BaudRate.B_1200; dataBits = DataBits.DATABITS_8; stopBits = StopBits.STOPBITS_1; parity = PortParity.NONE; flowControl = FlowControl.NONE; lineFeed = LineFeed.NONE; unitMultiplier = UnitMultiplier.TIMES_1; this.correctionMultiplier = 1.0; this.measureInReverse = true; this.measureCumulatively = true; } @Override public String toString() { return "LINTAB with ASCII adapter"; } @Override public boolean doesInitialize() { return false; } @Override public void serialEvent(SerialPortEvent e) { if(e.getEventType() == SerialPortEvent.DATA_AVAILABLE) { InputStream input; try { input = getSerialPort().getInputStream(); StringBuffer readBuffer = new StringBuffer(); int intReadFromPort; /* LINTAB data appears in the following format: * [integer position in 1/1000mm];[add button state ‘0’ or ’1’][reset button state ‘0’ or ‘1’][LF] * It should look like "140;10" or "46;10" with a LF. * With every change of the LINTAB table state (move table, button press, button release) a * new data record is sent with a line feed (0x0A) at the end of the line. * This means that a lot of the data needs to be ignored. */ //Read from port into buffer while not LF (10) while ((intReadFromPort=input.read()) != 10){ //System.out.println(intReadFromPort); //If a timeout then show bad sample if(intReadFromPort == -1) { fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.BAD_SAMPLE_EVENT, null); return; } readBuffer.append((char) intReadFromPort); } String strReadBuffer = readBuffer.toString(); fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.RAW_DATA, String.valueOf(strReadBuffer), DataDirection.RECEIVED); // Ignore "0;10" data as this is a side-effect of Lintab's hardware button if (strReadBuffer.equals("0;10")) return; // Ignore repeated 'fire' requests String thisFireState = strReadBuffer.substring(strReadBuffer.indexOf(";")+1, strReadBuffer.indexOf(";")+2); if (previousFireState.equals("1") && thisFireState.equals("1")) return; // Keep track of the state of the 'fire' button previousFireState = thisFireState; //Chop the three characters off the right side of the string to leave the number. String strReadPosition = strReadBuffer.substring(0,(strReadBuffer.length())-3); // Check that Lintab has actually reset when we asked. Sometimes if a hardware // switch is used quickly, it doesn't hear the reset request if(resetting) { if(!strReadPosition.equals("0")) { log.debug("Platform reset request ignored... retrying (attempt "+resetCounter+")"); zeroMeasurement(); return; } else if (resetCounter>10) { log.error("Lintab appears to be continually ignoring reset requests!"); } resetRequestTrack(false); } isInitialized = true; // Round up to integer of 1/1000th mm Float fltValue = new Float(strReadPosition); Integer intValue = Math.round(fltValue); // Inverse if reverse measuring mode is on if(getReverseMeasuring()) { intValue = 0 - intValue; } // Handle any correction factor intValue = getCorrectedValue(intValue); //Only process the data if the add button is set and the reset button is not set. if( strReadBuffer.endsWith(";10") || fireOnNextValue) { // Do calculation if working in cumulative mode if(this.measureCumulatively) { Integer cumValue = intValue; intValue = intValue - getPreviousPosition(); setPreviousPosition(cumValue); } fireOnNextValue = false; fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.NEW_SAMPLE_EVENT, intValue); // Only zero the measurement if we're not measuring cumulatively if(!measureCumulatively) { zeroMeasurement(); } } else if( strReadBuffer.endsWith(";01") || strReadBuffer.endsWith(";11")) { zeroMeasurement(); } else { // Not recording this value just updating current value counter fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.UPDATED_CURRENT_VALUE_EVENT, intValue); } } catch (IOException ioe) { fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.ERROR, "Error reading from serial port"); } } } /** * Lintab boxes sometimes ignore reset requests, so we need to ask several * times to make sure it is accepted. This function keeps track of requests, * to ensure we don't enter an infinite loop. * * @param reset */ private void resetRequestTrack(Boolean reset) { if (reset == true) { resetting = true; resetCounter++; } else { resetting = false; resetCounter = 0; } } /** * Send zero command to LINTAB 6 */ @Override public void zeroMeasurement() { if(isInitialized) { String strCommand = "RESET"; resetRequestTrack(true); this.sendData(strCommand); this.setPreviousPosition(0); } } /** * Send request for data to LINTAB 6 */ @Override public void requestMeasurement() { fireOnNextValue=true; String strCommand = "GETDATA"; this.sendData(strCommand); } /** * Send a command to the LINTAB 6 platform. * * @param strCommand */ private void sendData(String strCommand) { //After a command a linefeed (0x0A) or carriage return (0x0D) must be sent to execute the command. strCommand = strCommand+"\r"; OutputStream output; try { output = getSerialPort().getOutputStream(); OutputStream outToPort=new DataOutputStream(output); byte[] command = strCommand.getBytes(); outToPort.write(command); fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.RAW_DATA, strCommand, DataDirection.SENT); } catch (IOException ioe) { fireMeasuringSampleEvent(this, MeasuringSampleIOEvent.ERROR, "Error writing to serial port", DataDirection.SENT); } } @Override public Boolean isRequestDataCapable() { return true; } @Override public Boolean isCurrentValueCapable() { return true; } @Override public Boolean isBaudEditable() { return false; } @Override public Boolean isDatabitsEditable() { return false; } @Override public Boolean isLineFeedEditable() { return false; } @Override public Boolean isParityEditable() { return false; } @Override public Boolean isStopbitsEditable() { return false; } @Override public Boolean isFlowControlEditable(){ return false; } @Override public Boolean isUnitsEditable() { return false; } @Override public Boolean isMeasureCumulativelyConfigurable() { return true; } @Override public Boolean isReverseMeasureCapable() { return true; } @Override public Boolean isCorrectionFactorEditable() { return true; } }
gpl-3.0
exch-bms2/beatoraja
src/bms/player/beatoraja/result/CourseResult.java
12539
package bms.player.beatoraja.result; import static bms.player.beatoraja.ClearType.*; import static bms.player.beatoraja.skin.SkinProperty.*; import java.util.*; import java.util.logging.Logger; import bms.player.beatoraja.input.KeyCommand; import com.badlogic.gdx.utils.FloatArray; import bms.model.BMSModel; import bms.player.beatoraja.*; import bms.player.beatoraja.MainController.IRStatus; import bms.player.beatoraja.input.BMSPlayerInputProcessor; import bms.player.beatoraja.input.KeyBoardInputProcesseor.ControlKeys; import bms.player.beatoraja.ir.*; import bms.player.beatoraja.select.MusicSelector; import bms.player.beatoraja.skin.SkinType; import bms.player.beatoraja.skin.property.EventFactory.EventType; /** * コースリザルト * * @author exch */ public class CourseResult extends AbstractResult { private List<IRSendStatus> irSendStatus = new ArrayList<IRSendStatus>(); private ResultKeyProperty property; public CourseResult(MainController main) { super(main); } public void create() { final PlayerResource resource = main.getPlayerResource(); for(int i = 0;i < REPLAY_SIZE;i++) { saveReplay[i] = main.getPlayDataAccessor().existsReplayData(resource.getCourseBMSModels(), resource.getPlayerConfig().getLnmode(), i ,resource.getConstraint()) ? ReplayStatus.EXIST : ReplayStatus.NOT_EXIST ; } setSound(SOUND_CLEAR, "course_clear.wav", SoundType.SOUND,false); setSound(SOUND_FAIL, "course_fail.wav", SoundType.SOUND, false); setSound(SOUND_CLOSE, "course_close.wav", SoundType.SOUND, false); loadSkin(SkinType.COURSE_RESULT); for(int i = resource.getCourseGauge().size;i < resource.getCourseBMSModels().length;i++) { FloatArray[] list = new FloatArray[resource.getGrooveGauge().getGaugeTypeLength()]; for(int type = 0; type < list.length; type++) { list[type] = new FloatArray(); for(int l = 0;l < (resource.getCourseBMSModels()[i].getLastNoteTime() + 500) / 500;l++) { list[type].add(0f); } } resource.getCourseGauge().add(list); } property = ResultKeyProperty.get(resource.getBMSModel().getMode()); if(property == null) { property = ResultKeyProperty.BEAT_7K; } updateScoreDatabase(); // リプレイの自動保存 if(resource.getPlayMode().mode == BMSPlayerMode.Mode.PLAY){ for(int i=0;i<REPLAY_SIZE;i++){ if(MusicResult.ReplayAutoSaveConstraint.get(resource.getPlayerConfig().getAutoSaveReplay()[i]).isQualified(oldscore ,getNewScore())) { saveReplayData(i); } } } gaugeType = resource.getGrooveGauge().getType(); } public void prepare() { state = STATE_OFFLINE; final PlayerResource resource = main.getPlayerResource(); final PlayerConfig config = resource.getPlayerConfig(); final ScoreData newscore = getNewScore(); ranking = resource.getRankingData() != null && resource.getCourseBMSModels() != null ? resource.getRankingData() : new RankingData(); rankingOffset = 0; final IRStatus[] ir = main.getIRStatus(); if (ir.length > 0 && resource.getPlayMode().mode == BMSPlayerMode.Mode.PLAY) { state = STATE_IR_PROCESSING; boolean uln = false; for(BMSModel model : resource.getCourseBMSModels()) { if(model.containsUndefinedLongNote()) { uln = true; break; } } final int lnmode = uln ? config.getLnmode() : 0; for(IRStatus irc : ir) { boolean send = resource.isUpdateCourseScore() && resource.getCourseData().isRelease(); switch(irc.config.getIrsend()) { case IRConfig.IR_SEND_ALWAYS: break; case IRConfig.IR_SEND_COMPLETE_SONG: // FloatArray gauge = resource.getGauge()[resource.getGrooveGauge().getType()]; // send &= gauge.get(gauge.size - 1) > 0.0; break; case IRConfig.IR_SEND_UPDATE_SCORE: // send &= (newscore.getExscore() > oldscore.getExscore() || newscore.getClear() > oldscore.getClear() // || newscore.getCombo() > oldscore.getCombo() || newscore.getMinbp() < oldscore.getMinbp()); break; } if(send) { irSendStatus.add(new IRSendStatus(irc.connection, resource.getCourseData(), lnmode, newscore)); } } Thread irprocess = new Thread(() -> { try { int irsend = 0; boolean succeed = true; List<IRSendStatus> removeIrSendStatus = new ArrayList<IRSendStatus>(); for(IRSendStatus irc : irSendStatus) { if(irsend == 0) { main.switchTimer(TIMER_IR_CONNECT_BEGIN, true); } irsend++; succeed &= irc.send(); if(irc.retry < 0 || irc.retry > main.getConfig().getIrSendCount()) { removeIrSendStatus.add(irc); } } irSendStatus.removeAll(removeIrSendStatus); if(irsend > 0) { main.switchTimer(succeed ? TIMER_IR_CONNECT_SUCCESS : TIMER_IR_CONNECT_FAIL, true); IRResponse<bms.player.beatoraja.ir.IRScoreData[]> response = ir[0].connection.getCoursePlayData(null, new IRCourseData(resource.getCourseData(), lnmode)); if(response.isSucceeded()) { ranking.updateScore(response.getData(), newscore.getExscore() > oldscore.getExscore() ? newscore : oldscore); rankingOffset = ranking.getRank() > 10 ? ranking.getRank() - 5 : 0; Logger.getGlobal().warning("IRからのスコア取得成功 : " + response.getMessage()); } else { Logger.getGlobal().warning("IRからのスコア取得失敗 : " + response.getMessage()); } } } catch (Exception e) { Logger.getGlobal().severe(e.getMessage()); } finally { state = STATE_IR_FINISHED; } }); irprocess.start(); } play(newscore.getClear() != Failed.id ? SOUND_CLEAR : SOUND_FAIL); } public void render() { long time = main.getNowTime(); main.switchTimer(TIMER_RESULTGRAPH_BEGIN, true); main.switchTimer(TIMER_RESULTGRAPH_END, true); main.switchTimer(TIMER_RESULT_UPDATESCORE, true); if(time > getSkin().getInput()){ main.switchTimer(TIMER_STARTINPUT, true); } if (main.isTimerOn(TIMER_FADEOUT)) { if (main.getNowTime(TIMER_FADEOUT) > getSkin().getFadeout()) { main.getPlayerResource().getPlayerConfig().setGauge(main.getPlayerResource().getOrgGaugeOption()); stop(SOUND_CLEAR); stop(SOUND_FAIL); stop(SOUND_CLOSE); main.changeState(MainStateType.MUSICSELECT); } } else if (time > getSkin().getScene()) { main.switchTimer(TIMER_FADEOUT, true); if(getSound(SOUND_CLOSE) != null) { stop(SOUND_CLEAR); stop(SOUND_FAIL); play(SOUND_CLOSE); } } } public void input() { super.input(); final PlayerResource resource = main.getPlayerResource(); final BMSPlayerInputProcessor inputProcessor = main.getInputProcessor(); if (!main.isTimerOn(TIMER_FADEOUT) && main.isTimerOn(TIMER_STARTINPUT)) { boolean ok = false; for (int i = 0; i < property.getAssignLength(); i++) { if (property.getAssign(i) == ResultKeyProperty.ResultKey.CHANGE_GRAPH && inputProcessor.getKeyState(i) && inputProcessor.resetKeyChangedTime(i)) { gaugeType = (gaugeType - 5) % 3 + 6; } else if (property.getAssign(i) != null && inputProcessor.getKeyState(i) && inputProcessor.resetKeyChangedTime(i)) { ok = true; } } if (inputProcessor.isControlKeyPressed(ControlKeys.ESCAPE) || inputProcessor.isControlKeyPressed(ControlKeys.ENTER)) { ok = true; } if (resource.getScoreData() == null || ok) { if (((CourseResultSkin) getSkin()).getRankTime() != 0 && !main.isTimerOn(TIMER_RESULT_UPDATESCORE)) { main.switchTimer(TIMER_RESULT_UPDATESCORE, true); } else if (state == STATE_OFFLINE || state == STATE_IR_FINISHED){ main.switchTimer(TIMER_FADEOUT, true); if(getSound(SOUND_CLOSE) != null) { stop(SOUND_CLEAR); stop(SOUND_FAIL); play(SOUND_CLOSE); } } } if(inputProcessor.isControlKeyPressed(ControlKeys.NUM1)) { saveReplayData(0); } else if(inputProcessor.isControlKeyPressed(ControlKeys.NUM2)) { saveReplayData(1); } else if(inputProcessor.isControlKeyPressed(ControlKeys.NUM3)) { saveReplayData(2); } else if(inputProcessor.isControlKeyPressed(ControlKeys.NUM4)) { saveReplayData(3); } if(inputProcessor.isActivated(KeyCommand.OPEN_IR)) { this.executeEvent(EventType.open_ir); } } } public void updateScoreDatabase() { final PlayerResource resource = main.getPlayerResource(); final PlayerConfig config = resource.getPlayerConfig(); BMSModel[] models = resource.getCourseBMSModels(); final ScoreData newscore = getNewScore(); if (newscore == null) { return; } boolean dp = false; for (BMSModel model : models) { dp |= model.getMode().player == 2; } newscore.setCombo(resource.getMaxcombo()); int random = 0; if (config.getRandom() > 0 || (dp && (config.getRandom2() > 0 || config.getDoubleoption() > 0))) { random = 2; } if (config.getRandom() == 1 && (!dp || (config.getRandom2() == 1 && config.getDoubleoption() == 1))) { random = 1; } final ScoreData score = main.getPlayDataAccessor().readScoreData(models, config.getLnmode(), random, resource.getConstraint()); oldscore = score != null ? score : new ScoreData(); getScoreDataProperty().setTargetScore(oldscore.getExscore(), resource.getRivalScoreData() != null ? resource.getRivalScoreData().getExscore() : 0, Arrays.asList(resource.getCourseData().getSong()).stream().mapToInt(sd -> sd.getNotes()).sum()); getScoreDataProperty().update(newscore); main.getPlayDataAccessor().writeScoreDara(newscore, models, config.getLnmode(), random, resource.getConstraint(), resource.isUpdateCourseScore()); Logger.getGlobal().info("スコアデータベース更新完了 "); } public int getJudgeCount(int judge, boolean fast) { final PlayerResource resource = main.getPlayerResource(); ScoreData score = resource.getCourseScoreData(); if (score != null) { switch (judge) { case 0: return fast ? score.getEpg() : score.getLpg(); case 1: return fast ? score.getEgr() : score.getLgr(); case 2: return fast ? score.getEgd() : score.getLgd(); case 3: return fast ? score.getEbd() : score.getLbd(); case 4: return fast ? score.getEpr() : score.getLpr(); case 5: return fast ? score.getEms() : score.getLms(); } } return 0; } @Override public void dispose() { super.dispose(); } public void saveReplayData(int index) { final PlayerResource resource = main.getPlayerResource(); if (resource.getPlayMode().mode == BMSPlayerMode.Mode.PLAY && resource.getCourseScoreData() != null) { if (saveReplay[index] != ReplayStatus.SAVED && resource.isUpdateCourseScore()) { // 保存されているリプレイデータがない場合は、EASY以上で自動保存 ReplayData[] rd = resource.getCourseReplay(); for(int i = 0; i < rd.length; i++) { rd[i].gauge = resource.getPlayerConfig().getGauge(); } main.getPlayDataAccessor().wrireReplayData(rd, resource.getCourseBMSModels(), resource.getPlayerConfig().getLnmode(), index, resource.getConstraint()); saveReplay[index] = ReplayStatus.SAVED; } } } public ScoreData getNewScore() { return main.getPlayerResource().getCourseScoreData(); } static class IRSendStatus { public final IRConnection ir; public final CourseData course; public final int lnmode; public final ScoreData score; public int retry = 0; public IRSendStatus(IRConnection ir, CourseData course, int lnmode, ScoreData score) { this.ir = ir; this.course = course; this.lnmode = lnmode; this.score = score; } public boolean send() { Logger.getGlobal().info("IRへスコア送信中 : " + course.getName()); IRResponse<Object> send1 = ir.sendCoursePlayData(new IRCourseData(course, lnmode), new bms.player.beatoraja.ir.IRScoreData(score)); if(send1.isSucceeded()) { Logger.getGlobal().info("IRスコア送信完了 : " + course.getName()); retry = -255; return true; } else { Logger.getGlobal().warning("IRスコア送信失敗 : " + send1.getMessage()); retry++; return false; } } } }
gpl-3.0
alexeykuptsov/JDI
Java/JDI/jdi-uitest-mobile/src/main/java/com/epam/jdi/uitests/mobile/appium/driver/WebDriverUtils.java
1834
package com.epam.jdi.uitests.mobile.appium.driver; /* * Copyright 2004-2016 EPAM Systems * * This file is part of JDI project. * * JDI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JDI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JDI. If not, see <http://www.gnu.org/licenses/>. */ import org.openqa.selenium.os.CommandLine; import org.openqa.selenium.os.WindowsUtils; import static com.epam.commons.LinqUtils.first; import static com.epam.commons.LinqUtils.where; import static com.epam.commons.TryCatchUtil.tryGetResult; /** * Created by 12345 on 26.01.2015. */ public final class WebDriverUtils { private WebDriverUtils() { } public static void killAllRunWebDrivers() { try { String pid = getPid(); while (pid != null) { killPID(pid); pid = getPid(); } } catch (Exception ignore) { // Ignore in case of not windows Operation System or any other errors } } private static String getPid() { return first(where(tryGetResult(WindowsUtils::procMap), el -> el.getKey() != null && (el.getKey().contains("Android") && el.getKey().contains("Appium")))); } private static void killPID(String processID) { new CommandLine("taskkill", "/f", "/t", "/pid", processID).execute(); } }
gpl-3.0
pdewan/Comp401LocalChecks
src/gradingTools/comp301ss21/assignment4/controller/SceneControllerCallsSay.java
1051
package gradingTools.comp301ss21.assignment4.controller; import gradingTools.basics.sharedTestCase.checkstyle.CheckstyleClassInstantiatedTestCase; import gradingTools.basics.sharedTestCase.checkstyle.CheckstyleMethodCalledTestCase; import gradingTools.comp301ss21.assignment2.testcases.inheritance.TaggedLocatable; import util.annotations.MaxValue; @MaxValue(2) public class SceneControllerCallsSay extends CheckstyleMethodCalledTestCase { // [INFO] D:\dewan_backup\Java\grail13\.\src\greeting\Cls.java:6: Expected signature main:String[]->void in type greeting.Cls:[@Comp301Tags.GREETING_MAIN]. Good! [ExpectedSignatures] // [WARN] D:\dewan_backup\Java\grail13\.\src\greeting\Cls.java:6: Missing signature main:String[]->void in type greeting.Cls:[@Comp301Tags.GREETING_MAIN]. [ExpectedSignatures] public SceneControllerCallsSay() { super("@Comp301Tags.BRIDGE_SCENE_CONTROLLER", "(.*)!say:String-> void"); // TODO Auto-generated constructor stub } protected Class precedingTest() { return TaggedLocatable.class; } }
gpl-3.0
MCCarbon/DecompileTools
src/tools/renamers/AllClassesRenamer.java
1654
package tools.renamers; import java.io.PrintWriter; import java.util.Arrays; import java.util.jar.JarEntry; import java.util.jar.JarFile; import tools.EntryPoint; import tools.Tool; import tools.utils.EnumerationIterator; import tools.utils.MappingUtils; import tools.utils.Utils; public class AllClassesRenamer implements Tool { @Override public void run() { String args[] = EntryPoint.getArgs(); String inputJarFileName = args[0]; String outputSrgMappingsFileName = args[1]; try ( PrintWriter outputSrgMappingWriter = new PrintWriter(outputSrgMappingsFileName); JarFile inputJarFile = new JarFile(inputJarFileName) ) { for (JarEntry jarEntry : new EnumerationIterator<>(inputJarFile.entries())) { if (jarEntry.isDirectory() || !jarEntry.getName().endsWith(".class")) { continue; } String original = Utils.stripClassEnding(jarEntry.getName()); String[] pathAndName = original.split("[/]"); String path = pathAndName.length > 1 ? String.join("/", Arrays.copyOf(pathAndName, pathAndName.length - 1)) : null; String remappedname = String.join("$", rename(pathAndName[pathAndName.length - 1].split("[$]"))); String remapped = path == null ? remappedname : path + "/" + remappedname; outputSrgMappingWriter.println(MappingUtils.createSRG(original, remapped)); } } catch (Throwable t) { t.printStackTrace(); } } private static String[] rename(String[] elements) { for (int i = 0; i < elements.length; i++) { if (i == 0) { elements[i] = "class_" + elements[i]; } else { elements[i] = "class_" + elements[i] + "_in_" + elements[i - 1]; } } return elements; } }
gpl-3.0
sinaa/train-simulator
src/main/java/ft/sim/monitoring/ViolationBuilder.java
2596
package ft.sim.monitoring; import static ft.sim.monitoring.ViolationSeverity.*; import static ft.sim.monitoring.ViolationType.*; import ft.sim.world.train.Train; import ft.sim.world.connectables.Connectable; import ft.sim.world.connectables.Section; import ft.sim.world.connectables.Station; import ft.sim.world.connectables.Switch; import ft.sim.world.connectables.Track; /** * Created by sina on 10/04/2017. */ public class ViolationBuilder { public static void createTrainCrashViolation(Oracle o, Train t1, Train t2, Section section) { int idTrain1 = o.getWorld().getTrainID(t1); int idTrain2 = o.getWorld().getTrainID(t2); int trackID = o.getWorld().getTrackIDforSection(section); int sectionID = o.getWorld().getTrack(trackID).getSectionPosition(section); String violationDescription = String .format("Train %s and Train %s were on the same Section %s on track %s", idTrain1, idTrain2, sectionID, trackID); o.addViolation(new Violation(CRASH, CRITICAL, o.getTick(), violationDescription)); } public static void createFixedBlockViolation(Oracle o, Train t1, Train t2, Connectable connectable) { String connectableName = "Unknown"; if (connectable instanceof Track) { connectableName = "Track-" + o.getWorld().getTrackID((Track) connectable); } else if (connectable instanceof Switch) { connectableName = "Switch-" + o.getWorld().getSwitchID((Switch) connectable); } String violationDescription = String .format("Train %s and Train %s were on the same Connectable %s", o.getWorld().getTrainID(t1), o.getWorld().getTrainID(t2), connectableName); o.addViolation(new Violation(FIXED_BLOCK, CRITICAL, o.getTick(), violationDescription)); } public static void createVariableBlockViolation(Oracle o, Train t1, Train t2, double distance) { String violationDescription = String.format( "Train %s and Train %s were within less than braking distance from each other (%s)", o.getWorld().getTrainID(t1), o.getWorld().getTrainID(t2), distance); o.addViolation(new Violation(VARIABLE_BLOCK, HIGH, o.getTick(), violationDescription)); } public static void createOverfullStationViolation(Oracle o, Station station) { int stationID = o.getWorld().getStationID(station); String violationDescription = String .format("Station %s is over capacity (%s out of %s)", stationID, station.usedCapacity(), station.getCapacity()); o.addViolation(new Violation(OVERFULL_STATION, CRITICAL, o.getTick(), violationDescription)); } }
gpl-3.0
Curtis3321/Essentials
Essentials/src/net/ess3/commands/Commandworkbench.java
280
package net.ess3.commands; import net.ess3.api.IUser; public class Commandworkbench extends EssentialsCommand { @Override public void run(final IUser user, final String commandLabel, final String[] args) throws Exception { user.getPlayer().openWorkbench(null, true); } }
gpl-3.0
IntersectAustralia/exsite9
exsite9/test/au/org/intersect/exsite9/service/SchemaServiceUnitTest.java
9680
/** * Copyright (C) Intersect 2012. * * This module contains Proprietary Information of Intersect, * and should be treated as Confidential. */ package au.org.intersect.exsite9.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.when; import java.io.File; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import au.org.intersect.exsite9.dao.DAOTest; import au.org.intersect.exsite9.dao.factory.MetadataAttributeDAOFactory; import au.org.intersect.exsite9.dao.factory.MetadataCategoryDAOFactory; import au.org.intersect.exsite9.dao.factory.SchemaDAOFactory; import au.org.intersect.exsite9.domain.MetadataCategory; import au.org.intersect.exsite9.domain.MetadataCategoryType; import au.org.intersect.exsite9.domain.MetadataCategoryUse; import au.org.intersect.exsite9.domain.MetadataValue; import au.org.intersect.exsite9.domain.Schema; /** * Tests {@link SchemaService} */ public final class SchemaServiceUnitTest extends DAOTest { @Test public void testCreateLocalSchema() { final EntityManagerFactory emf = mock(EntityManagerFactory.class); when(emf.createEntityManager()).thenReturn(createEntityManager()); final File defaultSchemaDir = new File("defaultSchemaDir"); final File defaultSchemaFile = new File("defaultSchemaFile"); final File metadataSchemaSchema = new File("metadataSchemaSchema"); final SchemaDAOFactory schemaDAOFactory = new SchemaDAOFactory(); final MetadataCategoryDAOFactory metadataCategoryDAOFactory = new MetadataCategoryDAOFactory(); final MetadataAttributeDAOFactory metadataAttributeDAOFactory = new MetadataAttributeDAOFactory(); final SchemaService toTest = new SchemaService(defaultSchemaDir, defaultSchemaFile, metadataSchemaSchema, emf, schemaDAOFactory, metadataCategoryDAOFactory, metadataAttributeDAOFactory); assertEquals(defaultSchemaFile, toTest.getDefaultSchema()); assertEquals(defaultSchemaDir, toTest.getDefaultSchemaDirectory()); final Schema schema = toTest.createLocalSchema("name", "description", "namespace url"); assertNotNull(schema.getId()); assertTrue(schema.getLocal()); assertEquals("name", schema.getName()); assertEquals("description", schema.getDescription()); assertEquals("namespace url", schema.getNamespaceURL()); } @Test public void testCreateImportedSchema() { final EntityManagerFactory emf = mock(EntityManagerFactory.class); when(emf.createEntityManager()).thenReturn(createEntityManager()); final File defaultSchemaDir = new File("defaultSchemaDir"); final File defaultSchemaFile = new File("defaultSchemaFile"); final File metadataSchemaSchema = new File("metadataSchemaSchema"); final SchemaDAOFactory schemaDAOFactory = new SchemaDAOFactory(); final MetadataCategoryDAOFactory metadataCategoryDAOFactory = new MetadataCategoryDAOFactory(); final MetadataAttributeDAOFactory metadataAttributeDAOFactory = new MetadataAttributeDAOFactory(); final SchemaService toTest = new SchemaService(defaultSchemaDir, defaultSchemaFile, metadataSchemaSchema, emf, schemaDAOFactory, metadataCategoryDAOFactory, metadataAttributeDAOFactory); final Schema importedSchema = new Schema("name", "desc", "namespace url", Boolean.FALSE); final MetadataCategory mdc = new MetadataCategory("category", MetadataCategoryType.FREETEXT, MetadataCategoryUse.optional); final MetadataValue mdv = new MetadataValue("metadata value"); mdc.getValues().add(mdv); importedSchema.getMetadataCategories().add(mdc); toTest.createImportedSchema(importedSchema); assertNotNull(importedSchema.getId()); } @Test public void testUpdateSchema() { final EntityManagerFactory emf = mock(EntityManagerFactory.class); stub(emf.createEntityManager()).toAnswer(new Answer<EntityManager>() { @Override public EntityManager answer(final InvocationOnMock invocation) throws Throwable { return createEntityManager(); } }); final File defaultSchemaDir = new File("defaultSchemaDir"); final File defaultSchemaFile = new File("defaultSchemaFile"); final File metadataSchemaSchema = new File("metadataSchemaSchema"); final SchemaDAOFactory schemaDAOFactory = new SchemaDAOFactory(); final MetadataCategoryDAOFactory metadataCategoryDAOFactory = new MetadataCategoryDAOFactory(); final MetadataAttributeDAOFactory metadataAttributeDAOFactory = new MetadataAttributeDAOFactory(); final SchemaService toTest = new SchemaService(defaultSchemaDir, defaultSchemaFile, metadataSchemaSchema, emf, schemaDAOFactory, metadataCategoryDAOFactory, metadataAttributeDAOFactory); final Schema schema = toTest.createLocalSchema("name", "description", "namespace url"); assertNotNull(schema.getId()); assertTrue(schema.getLocal()); assertEquals("name", schema.getName()); assertEquals("description", schema.getDescription()); assertEquals("namespace url", schema.getNamespaceURL()); toTest.updateSchema(schema, "new name", "new description", "new namespace url"); final Schema updatedSchema = createEntityManager().find(Schema.class, schema.getId()); assertEquals("new name", updatedSchema.getName()); assertEquals("new description", updatedSchema.getDescription()); assertEquals("new namespace url", updatedSchema.getNamespaceURL()); } @Test public void testRemoveSchema() { final EntityManagerFactory emf = mock(EntityManagerFactory.class); stub(emf.createEntityManager()).toAnswer(new Answer<EntityManager>() { @Override public EntityManager answer(final InvocationOnMock invocation) throws Throwable { return createEntityManager(); } }); final File defaultSchemaDir = new File("defaultSchemaDir"); final File defaultSchemaFile = new File("defaultSchemaFile"); final File metadataSchemaSchema = new File("metadataSchemaSchema"); final SchemaDAOFactory schemaDAOFactory = new SchemaDAOFactory(); final MetadataCategoryDAOFactory metadataCategoryDAOFactory = new MetadataCategoryDAOFactory(); final MetadataAttributeDAOFactory metadataAttributeDAOFactory = new MetadataAttributeDAOFactory(); final SchemaService toTest = new SchemaService(defaultSchemaDir, defaultSchemaFile, metadataSchemaSchema, emf, schemaDAOFactory, metadataCategoryDAOFactory, metadataAttributeDAOFactory); final Schema importedSchema = new Schema("name", "desc", "namespace url", Boolean.FALSE); final MetadataCategory mdc = new MetadataCategory("category", MetadataCategoryType.FREETEXT, MetadataCategoryUse.optional); final MetadataValue mdv = new MetadataValue("metadata value"); mdc.getValues().add(mdv); importedSchema.getMetadataCategories().add(mdc); toTest.createImportedSchema(importedSchema); assertNotNull(importedSchema.getId()); toTest.removeSchema(importedSchema); assertNull(createEntityManager().find(Schema.class, importedSchema.getId())); } @Test public void testAddRemoveMetadataCategory() { final EntityManagerFactory emf = mock(EntityManagerFactory.class); stub(emf.createEntityManager()).toAnswer(new Answer<EntityManager>() { @Override public EntityManager answer(final InvocationOnMock invocation) throws Throwable { return createEntityManager(); } }); final File defaultSchemaDir = new File("defaultSchemaDir"); final File defaultSchemaFile = new File("defaultSchemaFile"); final File metadataSchemaSchema = new File("metadataSchemaSchema"); final SchemaDAOFactory schemaDAOFactory = new SchemaDAOFactory(); final MetadataCategoryDAOFactory metadataCategoryDAOFactory = new MetadataCategoryDAOFactory(); final MetadataAttributeDAOFactory metadataAttributeDAOFactory = new MetadataAttributeDAOFactory(); final SchemaService toTest = new SchemaService(defaultSchemaDir, defaultSchemaFile, metadataSchemaSchema, emf, schemaDAOFactory, metadataCategoryDAOFactory, metadataAttributeDAOFactory); final Schema schema = toTest.createLocalSchema("name", "description", "namespace url"); assertNotNull(schema.getId()); final MetadataCategory mc = new MetadataCategory("mc", MetadataCategoryType.CONTROLLED_VOCABULARY, MetadataCategoryUse.required); final MetadataValue mv = new MetadataValue("mv"); mc.getValues().add(mv); toTest.addMetadataCategoryToSchema(schema, mc); final Schema outSchema1 = createEntityManager().find(Schema.class, schema.getId()); assertEquals(1, outSchema1.getMetadataCategories().size()); toTest.removeMetadataCategoryFromSchema(schema, mc); final Schema outSchema2 = createEntityManager().find(Schema.class, schema.getId()); assertEquals(0, outSchema2.getMetadataCategories().size()); } }
gpl-3.0
bruce-wei/EsdApp
app/src/main/java/com/esd/phicomm/bruce/esdapp/Gpio.java
3231
package com.esd.phicomm.bruce.esdapp; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; /** * Created by Bruce on 2017/1/4. */ class Gpio { private String port; public boolean output(int value) { String command = String.format("echo %d > /sys/class/gpio_sw/%s/data\n", value, port); try { Runtime.getRuntime().exec(new String[] {"su", "-c", command}); return true; } catch (IOException e) { return false; } } private String readinput(){ Process p; String command = String.format("cat /sys/class/gpio_sw/%s/data\n", port); try { p = Runtime.getRuntime().exec("su"); DataOutputStream outputStream = new DataOutputStream(p.getOutputStream()); outputStream.write(command.getBytes()); outputStream.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder text = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { text.append(line); break; } reader.close(); return text.toString(); } catch (IOException e) { return ""; } } public boolean setcfg(int cfg){ String command = String.format("echo %d > /sys/class/gpio_sw/%s/cfg\n", cfg, port); try { Runtime.getRuntime().exec(new String[] {"su", "-c", command}); return true; } catch (IOException e) { return false; } } private String readcfg(){ Process p; String command = String.format("cat /sys/class/gpio_sw/%s/cfg\n", port); try { p = Runtime.getRuntime().exec(new String[] {"su", "-c", command}); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder text = new StringBuilder(); String line; while((line = reader.readLine()) != null){ text.append(line); text.append("\n"); } return text.toString(); } catch (IOException e) { return ""; } } public int input(){ char ch; String cfg; cfg = readinput(); if(cfg.isEmpty()) return -1; else{ ch = cfg.charAt(0); if(Character.isDigit(ch)) return Character.getNumericValue(ch); else return -1; } } public int getcfg(){ char ch; String cfg; cfg = readcfg(); if(cfg.isEmpty()) return -1; else{ ch = cfg.charAt(0); if(Character.isDigit(ch)) return Character.getNumericValue(ch); else return -1; } } //Constructor Gpio(String port){ this.port = port; } }
gpl-3.0
sloanr333/opd-legacy
src/com/watabou/legacy/items/Stylus.java
3298
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.legacy.items; import java.util.ArrayList; import com.watabou.legacy.Assets; import com.watabou.legacy.actors.hero.Hero; import com.watabou.legacy.effects.particles.PurpleParticle; import com.watabou.legacy.items.armor.Armor; import com.watabou.legacy.scenes.GameScene; import com.watabou.legacy.sprites.ItemSpriteSheet; import com.watabou.legacy.utils.GLog; import com.watabou.legacy.windows.WndBag; import com.watabou.noosa.audio.Sample; public class Stylus extends Item { private static final String TXT_SELECT_ARMOR = "Select an armor to inscribe on"; private static final String TXT_INSCRIBED = "you inscribed the %s on your %s"; private static final float TIME_TO_INSCRIBE = 2; private static final String AC_INSCRIBE = "INSCRIBE"; { name = "arcane stylus"; image = ItemSpriteSheet.STYLUS; stackable = true; } @Override public ArrayList<String> actions( Hero hero ) { ArrayList<String> actions = super.actions( hero ); actions.add( AC_INSCRIBE ); return actions; } @Override public void execute( Hero hero, String action ) { if (action == AC_INSCRIBE) { curUser = hero; GameScene.selectItem( itemSelector, WndBag.Mode.ARMOR, TXT_SELECT_ARMOR ); } else { super.execute( hero, action ); } } @Override public boolean isUpgradable() { return false; } @Override public boolean isIdentified() { return true; } private void inscribe( Armor armor ) { detach( curUser.belongings.backpack ); Class<? extends Armor.Glyph> oldGlyphClass = armor.glyph != null ? armor.glyph.getClass() : null; Armor.Glyph glyph = Armor.Glyph.random(); while (glyph.getClass() == oldGlyphClass) { glyph = Armor.Glyph.random(); } GLog.w( TXT_INSCRIBED, glyph.name(), armor.name() ); armor.inscribe( glyph ); curUser.sprite.operate( curUser.pos ); curUser.sprite.centerEmitter().start( PurpleParticle.BURST, 0.05f, 10 ); Sample.INSTANCE.play( Assets.SND_BURNING ); curUser.spend( TIME_TO_INSCRIBE ); curUser.busy(); } @Override public int price() { return 50 * quantity; } @Override public String info() { return "This arcane stylus is made of some dark, very hard stone. Using it you can inscribe " + "a magical glyph on your armor, but you have no power over choosing what glyph it will be, " + "the stylus will decide it for you."; } private final WndBag.Listener itemSelector = new WndBag.Listener() { @Override public void onSelect( Item item ) { if (item != null) { Stylus.this.inscribe( (Armor)item ); } } }; }
gpl-3.0
dnspinheiro/cooperTaxi
src/java/beans/EstadoBean.java
3051
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package beans; import dao.EstadoJpaController; import dao.exceptions.NonexistentEntityException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import modelo.Estado; import util.JPAUtil; /** * * @author denis */ @ManagedBean @RequestScoped public class EstadoBean { private Estado estado = new Estado(); EstadoJpaController daoEstado = new EstadoJpaController(JPAUtil.factory); private String mensagem; public EstadoBean() { } public void inserir() { FacesContext context = FacesContext.getCurrentInstance(); try { daoEstado.create(estado); estado = new Estado(); } catch (Exception ex) { context.addMessage("formEstado", new FacesMessage("Estado não pode ser inserido")); Logger.getLogger(ViagemClienteBean.class.getName()).log(Level.SEVERE, null, ex); } context.addMessage("formEstado", new FacesMessage("Estado foi inserido com sucesso!")); } public List<modelo.RelatorioEstado> pesquisarInfoDosEstados() { return daoEstado.pesquisarInfoDosEstados(); } public void alterar() { FacesContext context = FacesContext.getCurrentInstance(); try { daoEstado.edit(estado); estado = new Estado(); } catch (NonexistentEntityException ex) { context.addMessage("formEstado", new FacesMessage("Estado não pode ser alterado")); Logger.getLogger(EstadoBean.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { context.addMessage("formEstado", new FacesMessage("Estado não pode ser alterado")); Logger.getLogger(EstadoBean.class.getName()).log(Level.SEVERE, null, ex); } context.addMessage("formEstado", new FacesMessage("Estado foi inserido com sucesso!")); } public void excluir() { FacesContext context = FacesContext.getCurrentInstance(); try { daoEstado.destroy(estado.getId()); estado = new Estado(); } catch (Exception ex) { context.addMessage("formEstado", new FacesMessage("Estado não pode ser excluido")); Logger.getLogger(EstadoBean.class.getName()).log(Level.SEVERE, null, ex); } context.addMessage("formEstado", new FacesMessage("Estado foi inserido com sucesso")); } public Estado getEstado() { return estado; } public void setEstado(Estado estado) { this.estado = estado; } public List<Estado> getEstados() { return daoEstado.findEstadoEntities(); } public String getMensagem() { return mensagem; } public void setMensagem(String mensagem) { this.mensagem = mensagem; } }
gpl-3.0
silverweed/toncc
SwingConsole.java
1849
package toncc; import javax.swing.*; /** Utility class to run JFrame-based GUI classes. * * @author Bruce Eckel, Giacomo Parolini */ class SwingConsole { private static void prepare(final JFrame f) { f.setTitle(f.getClass().getSimpleName()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void run(final JFrame f,final int width,final int height) { SwingUtilities.invokeLater(new Runnable() { public void run() { prepare(f); f.setSize(width,height); f.setVisible(true); } }); } /** Don't manually set size, but pack. */ public static void run(final JFrame f) { SwingUtilities.invokeLater(new Runnable() { public void run() { prepare(f); f.pack(); f.setVisible(true); } }); } /** Don't manually set size, but pack. */ public static void run(final JFrame f,final String title) { SwingUtilities.invokeLater(new Runnable() { public void run() { f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle(title); f.pack(); f.setVisible(true); } }); } public static void run(final JFrame f,final int width,final int height,final String title) { SwingUtilities.invokeLater(new Runnable() { public void run() { f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle(title); f.setSize(width,height); f.setVisible(true); } }); } public static void runFullScreen(final JFrame f) { SwingUtilities.invokeLater(new Runnable() { public void run() { prepare(f); f.setExtendedState(JFrame.MAXIMIZED_BOTH); f.setVisible(true); } }); } public static void setSystemLookAndFeel() { try { // Set system L&F UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ee) { System.err.println("Caught exception while setting LookAndFeel: "+ee); } } }
gpl-3.0
vandaimer/TrabalhoEs
src/controle/gui_jogo/ObservadorDoControleRemoto.java
1791
package controle.gui_jogo; import controle.configuradores_gui.ConfiguradorVisualizadorDeCartas; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import modelo.jogo.Jogada; import modelo.jogo.partida.InformacaoDoTurno; import modelo.jogo.servidor.controleremoto.ControleRemoto; import modelo.util.Observador; import visao.GUIJogo; import visao.GUIPortal; import visao.janelas.FormVisualizadorDeCartas; public class ObservadorDoControleRemoto implements Observador { private GUIJogo _gj; private ControleRemoto _ctr; private GUIPortal gui; public ObservadorDoControleRemoto(GUIJogo _gj, ControleRemoto _ctr, GUIPortal gui) { this._gj = _gj; this._ctr = _ctr; this.gui = gui; } @Override public void notificar(Object fonte, Object msg) { if ("iniciar_turno".equals(msg)) { _gj.habilitarMontarJogada(true); return; } if ("jogada_realizada".equals(msg)) { _gj.habilitarMontarJogada(false); return; } if ("atualizar_pontuacao".equals(msg)) { List<InformacaoDoTurno> info = _ctr.getListaInformacaoTurno(); _gj.atualizarPlacar(info); return; } if ("fim_do_jogo".equals(msg)) { _ctr.remover(this); _gj.mostrasMensagem("Fim do jogo seu brucutu"); try { Thread.sleep(1000); } catch (InterruptedException e) { _gj.mostrasMensagem(e.getMessage()); } _gj.fechar(); return; } } }
gpl-3.0
DeplanckeLab/ASAP
Java/src/bigarrays/FloatArray64.java
2467
package bigarrays; /** * @author vincent.gardeux@epfl.ch * * Class for representing a float static array requiring address space larger than 32 bits. */ public class FloatArray64 { private static final int CHUNK_SIZE = 1024*1024*512; private long size; private float[][] data; public FloatArray64(long size) { this.size = size; if(size == 0) data = null; else { int chunks = (int)(size/CHUNK_SIZE); int remainder = (int)(size - ((long)chunks)*CHUNK_SIZE); data = new float[chunks+(remainder==0?0:1)][]; for(int idx=chunks; --idx>=0; ) data[idx] = new float[(int)CHUNK_SIZE]; if(remainder != 0) data[chunks] = new float[remainder]; } } public static int chunkSize() { return CHUNK_SIZE; } public float[] toArray() { if(this.data.length == 1) return this.data[0]; return null; } public float get(long index) { if(index < 0 || index >= size) throw new IndexOutOfBoundsException("Error attempting to access data element "+index+". Array is "+size+" elements long."); int chunk = (int)(index / CHUNK_SIZE); int offset = (int)(index - (((long)chunk) * CHUNK_SIZE)); return data[chunk][offset]; } public float[] getByChunk(int chunk) { if(chunk >= data.length) throw new IndexOutOfBoundsException("Error attempting to access chunk "+chunk+". Array is "+size+" elements long [" + data.length + " chunks]"); return data[chunk]; } public void set(long index, float b) { if(index<0 || index>=size) throw new IndexOutOfBoundsException("Error attempting to access data element "+index+". Array is "+size+" elements long."); int chunk = (int)(index/CHUNK_SIZE); int offset = (int)(index - (((long)chunk)*CHUNK_SIZE)); data[chunk][offset] = b; } public void set(int chunk, float[] b) { if(chunk >= data.length) throw new IndexOutOfBoundsException("Error attempting to access chunk "+chunk+". Array is "+size+" elements long [" + data.length + " chunks]"); data[chunk] = b; } public long size() { return this.size; } public IntArray64 toIntArray() { IntArray64 array = new IntArray64(this.size); for(long i = 0; i < size; i++) array.set(i, (int)this.get(i)); return array; } }
gpl-3.0
rforge/biocep
src_server_common/org/kchine/r/server/GenericCallbackDevice.java
949
/* * Biocep: R-based Platform for Computational e-Science. * * Copyright (C) 2007-2009 Karim Chine - karim.chine@m4x.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kchine.r.server; public interface GenericCallbackDevice extends Device, RCallBack, RConsoleActionListener, RCollaborationListener{ }
gpl-3.0
riking/GrandVide
src/com/avygeil/GrandVide/GVDatabaseHelper.java
4268
package com.avygeil.GrandVide; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class GVDatabaseHelper { private final GrandVide gv; private final String url; private final String driverClass; private final String user; private final String password; public static String DB_REGIONS_SCHEME; public static String DB_STATS_SCHEME; public static String AUTOINCREMENT; public static String NOCASE; private Connection connection = null; private Statement statement = null; private PreparedStatement prepared = null; GVDatabaseHelper(GrandVide grandvide) { this.gv = grandvide; if (gv.configurationHandler.sqlDriver.equalsIgnoreCase("sqlite")) { url = "jdbc:sqlite:plugins/GrandVide/grandvide.db"; driverClass = "org.sqlite.JDBC"; user = ""; password = ""; AUTOINCREMENT = "AUTOINCREMENT"; NOCASE = "COLLATE NOCASE"; } else if (gv.configurationHandler.sqlDriver.equalsIgnoreCase("mysql")) { url = "jdbc:mysql://" + gv.configurationHandler.mysqlHost + ":" + gv.configurationHandler.mysqlPort + "/" + gv.configurationHandler.mysqlDatabase; driverClass = "com.mysql.jdbc.Driver"; user = gv.configurationHandler.mysqlUser; password = gv.configurationHandler.mysqlPassword; AUTOINCREMENT = "AUTO_INCREMENT"; NOCASE = ""; } else { url = null; driverClass = null; user = null; password = null; AUTOINCREMENT = null; NOCASE = null; } DB_REGIONS_SCHEME = "CREATE TABLE IF NOT EXISTS " + gv.configurationHandler.mysqlPrefix + "regions(id INTEGER PRIMARY KEY " + AUTOINCREMENT + ", name TEXT, world TEXT, container BLOB, teams BLOB, power BLOB)"; DB_STATS_SCHEME = "CREATE TABLE IF NOT EXISTS " + gv.configurationHandler.mysqlPrefix + "stats(id INTEGER PRIMARY KEY " + AUTOINCREMENT + ", player TEXT, kills INTEGER, deaths INTEGER, damage_dealt INTEGER, damage_taken INTEGER, block_break INTEGER, block_place INTEGER, games_joined INTEGER, games_finished INTEGER)"; } public void setConnection() throws Exception { Class.forName(driverClass); try { gv.getLogger().info("Connexion a " + url + "..."); connection = DriverManager.getConnection(url, user, password); } catch (SQLException e) { gv.getLogger().severe("Impossible d'etablir la connexion a la base de donnees"); throw e; } try { statement = connection.createStatement(); } catch (Exception e) { try { connection.close(); } catch (Exception ignore) {} connection = null; gv.getLogger().severe("Une erreur s'est produite avec la base de donnees"); throw e; } } public void closeConnection() { if (statement != null) try { statement.close(); } catch (Exception ignore) {} if (connection != null) try { connection.close(); } catch (Exception ignore) {} } public void closeResultSet(ResultSet rs) { if (rs != null) try { rs.close(); } catch (Exception ignore) {} } public void execute(String instruction) throws Exception { try { statement.executeUpdate(instruction); } catch (SQLException e) { gv.getLogger().warning("La demande SQL n'a pas pu etre executee"); throw new Exception(e.getMessage()); } } public ResultSet query(String query) throws Exception { try { return statement.executeQuery(query); } catch (SQLException e) { gv.getLogger().warning("La requete SQL n'a pas pu etre executee"); throw new Exception(e.getMessage()); } } public PreparedStatement getPrepared() { return prepared; } public void prepare(String query) throws Exception { try { prepared = connection.prepareStatement(query); } catch (SQLException e) { gv.getLogger().warning("La requete preparee SQL n'a pas pu etre executee"); throw new Exception(e.getMessage()); } } public void finalize() throws Exception { try { prepared.execute(); } catch (SQLException e) { gv.getLogger().warning("La requete preparee SQL n'a pas pu etre finalisee"); throw new Exception(e.getMessage()); } finally { if (prepared != null) try { prepared.close(); } catch (Exception ignore) {} } } }
gpl-3.0
energizingcoalition/energizingcoalition
src/main/java/cf/energizingcoalition/energizingcoalition/proxy/ClientProxy.java
161
package cf.energizingcoalition.energizingcoalition.proxy; public class ClientProxy extends CommonProxy { @Override public void registerRenderers() { } }
gpl-3.0
UnlimitedFreedom/UF-WorldEdit
worldedit-core/src/main/java/com/sk89q/worldedit/util/command/InvalidUsageException.java
3497
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.util.command; import com.sk89q.minecraft.util.commands.CommandException; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; /** * Thrown when a command is not used properly. * * <p>When handling this exception, print the error message if it is not null. * Print a one line help instruction unless {@link #isFullHelpSuggested()} * is true, which, in that case, the full help of the command should be * shown.</p> * * <p>If no error message is set and full help is not to be shown, then a generic * "you used this command incorrectly" message should be shown.</p> */ @SuppressWarnings("serial") public class InvalidUsageException extends CommandException { private final CommandCallable command; private final boolean fullHelpSuggested; /** * Create a new instance with no error message and with no suggestion * that full and complete help for the command should be shown. This will * result in a generic error message. * * @param command the command */ public InvalidUsageException(CommandCallable command) { this(null, command); } /** * Create a new instance with a message and with no suggestion * that full and complete help for the command should be shown. * * @param message the message * @param command the command */ public InvalidUsageException(@Nullable String message, CommandCallable command) { this(message, command, false); } /** * Create a new instance with a message. * * @param message the message * @param command the command * @param fullHelpSuggested true if the full help for the command should be shown */ public InvalidUsageException(@Nullable String message, CommandCallable command, boolean fullHelpSuggested) { super(message); checkNotNull(command); this.command = command; this.fullHelpSuggested = fullHelpSuggested; } /** * Get the command. * * @return the command */ public CommandCallable getCommand() { return command; } /** * Get a simple usage string. * * @param prefix the command shebang (such as "/") -- may be blank * @return a usage string */ public String getSimpleUsageString(String prefix) { return getCommandUsed(prefix, command.getDescription().getUsage()); } /** * Return whether the full usage of the command should be shown. * * @return show full usage */ public boolean isFullHelpSuggested() { return fullHelpSuggested; } }
gpl-3.0
phroa/ByteCartRedux
src/main/java/com/github/catageek/bytecart/sign/BC7019.java
3023
/** * ByteCart, ByteCart Redux * Copyright (C) Catageek * Copyright (C) phroa * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * */ package com.github.catageek.bytecart.sign; import com.github.catageek.bytecart.address.Address; import com.github.catageek.bytecart.address.AddressFactory; import com.github.catageek.bytecart.address.AddressString; import com.github.catageek.bytecart.hardware.RegistryBoth; import com.github.catageek.bytecart.hardware.RegistryInput; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.entity.Entity; import java.util.Random; /** * Gives random address to a cart */ final class BC7019 extends BC7010 implements Triggerable { BC7019(BlockSnapshot block, Entity vehicle) { super(block, vehicle); this.storageCartAllowed = true; } @Override public String getName() { return "BC7019"; } @Override public String getFriendlyName() { return "Random Destination"; } @Override protected Address getAddressToWrite() { int startRegion = getInput(3).getValue(); int endRegion = getInput(0).getValue(); int newRegion = startRegion + (new Random()).nextInt(endRegion - startRegion + 1); int startTrack = getInput(4).getValue(); int endTrack = getInput(1).getValue(); int newTrack = startTrack + (new Random()).nextInt(endTrack - startTrack + 1); int startStation = getInput(5).getValue(); int endStation = getInput(2).getValue(); int newStation = startStation + (new Random()).nextInt(endStation - startStation + 1); return new AddressString(String.format("%d.%d.%d", newRegion, newTrack, newStation), false); } protected void addIO() { // add input [0], [1] and [2] from 4th line this.addAddressAsInputs(AddressFactory.getAddress(getBlock(), 3)); // add input [3], [4] and [5] from 3th line this.addAddressAsInputs(AddressFactory.getAddress(getBlock(), 2)); } private void addAddressAsInputs(Address addr) { if (addr.isValid()) { RegistryInput region = addr.getRegion(); this.addInputRegistry(region); RegistryInput track = addr.getTrack(); this.addInputRegistry(track); RegistryBoth station = addr.getStation(); this.addInputRegistry(station); } } }
gpl-3.0
andrey-gabchak/JavaRushLabs
com/javarush/test/level07/lesson12/home01/Solution.java
958
package com.javarush.test.level07.lesson12.home01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /* Вывести числа в обратном порядке Ввести с клавиатуры 10 чисел и заполнить ими список. Вывести их в обратном порядке. Использовать только цикл for. */ public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); ArrayList<Integer> integers = new ArrayList<>(); for (int i = 0; i < 10; i++) { integers.add(Integer.parseInt(reader.readLine())); } for (int i = 0; i < integers.size(); i++) { System.out.println(integers.get(integers.size() - i - 1)); } } }
gpl-3.0
wangguanquan/wsjob
src/main/java/cn/colvin/game/MainUI.java
19036
package com.game.clean; import org.apache.log4j.Logger; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Arrays; import java.util.LinkedList; import java.util.concurrent.*; /** * Created by wanggq on 2016/11/9. */ public class MainUI { Logger logger = Logger.getLogger(this.getClass()); JFrame frame; JBallPanel[] panels; static final int ROWS = 13, COLUMNS = 13; static int[] step_length = {-COLUMNS, 1, COLUMNS, -1}; // 背景色 static final Color LIGHT = new Color(42, 59, 77), DEEP = new Color(35, 49, 64); static final String[] ball_color = {"", "红", "黄", "蓝", "绿", "青", "紫", "灰"}; // 球的颜色 static Color[] Ball_color = {null, new Color(200, 20, 3) , new Color(190, 68, 22) , new Color(211, 154, 27) , new Color(0, 169, 29) , new Color(0, 224, 224) , new Color(32, 67, 251) , new Color(169, 33, 168) , new Color(76, 76, 76)}; // 球的图片 static Image[] Ball_image = { null, new ImageIcon("./src/com/game/clean/icon/1.jpg").getImage() , new ImageIcon("./src/com/game/clean/icon/2.jpg").getImage() , new ImageIcon("./src/com/game/clean/icon/3.jpg").getImage() , new ImageIcon("./src/com/game/clean/icon/4.jpg").getImage() , new ImageIcon("./src/com/game/clean/icon/5.jpg").getImage() , new ImageIcon("./src/com/game/clean/icon/6.jpg").getImage() , new ImageIcon("./src/com/game/clean/icon/7.jpg").getImage() , new ImageIcon("./src/com/game/clean/icon/8.jpg").getImage() }; int[] map = { 8, 8, 3, 0, 0, 7, 0, 0, 8, 0, 8, 0, 6, 6, 7, 0, 6, 1, 0, 6, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 6, 5, 1, 3, 0, 3, 0, 6, 0, 0, 2, 0, 6, 5, 7, 7, 0, 1, 6, 1, 1, 1, 3, 2, 0, 8, 0, 0, 0, 5, 7, 0, 7, 2, 0, 7, 8, 2, 3, 0, 0, 0, 8, 0, 0, 0, 5, 0, 0, 5, 8, 4, 5, 7, 0, 7, 4, 6, 2, 0, 3, 2, 1, 1, 1, 0, 0, 5, 2, 3, 2, 0, 0, 3, 5, 0, 4, 5, 0, 4, 0, 0, 6, 0, 4, 0, 3, 0, 0, 8, 0, 3, 8, 0, 0, 4, 1, 0, 7, 7, 0, 0, 8, 3, 6, 4, 4, 2, 0, 0, 5, 4, 0, 1, 0, 0, 0, 8, 1, 0, 5, 0, 0, 4, 4, 2, 0, 0, 5, 0, 0, 0, 7, 4, 0, 6, 3, 0, 0 }; // 评分: 一次消2个得2分, 一次消3个得4分, 一次消4个得10分 int[] score_map = {0, 0, 2, 4, 10}, total_ball; static String[] btn_name = {"开始", "暂停"}; int start_time = 0; // 开始时间统计 int click_total = 0; // 点击次数统计 int score = 0; // 分数统计 JLabel stepLabel, timeLabel, scoreLabel; JButton startButton; Timer timer, animationTimer; LinkedList<int[]> stack; public MainUI() { frame = new JFrame("消弹珠"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(60 * COLUMNS, 60 * ROWS + 40); // 头部Bar JPanel topPanel = new JPanel(); topPanel.setLayout(new GridLayout(1, 3)); topPanel.setBackground(Color.LIGHT_GRAY); JPanel leftPanel = new JPanel(new GridLayout(1, 2, 0, 10)); topPanel.add(leftPanel); JPanel clickPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); leftPanel.add(clickPanel); JLabel click_lab = new JLabel("点击:"); clickPanel.add(click_lab); stepLabel = new JLabel("0"); stepLabel.setFont(new Font("Courier New", Font.BOLD, 20)); clickPanel.add(stepLabel); JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); leftPanel.add(scorePanel); JLabel score_lab = new JLabel("得分:"); scorePanel.add(score_lab); scoreLabel = new JLabel("0"); scoreLabel.setFont(new Font("Courier New", Font.BOLD, 20)); scorePanel.add(scoreLabel); JPanel centerPanel = new JPanel(); topPanel.add(centerPanel); startButton = new JButton("开始"); startButton.setName("0"); startButton.addMouseListener(startMouseAdapter); centerPanel.add(startButton); JPanel rightPanel = new JPanel(new GridLayout(1, 2, 0, 10)); topPanel.add(rightPanel); JPanel timePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); timeLabel = new JLabel("00:00"); timeLabel.setFont(new Font("Courier New", Font.BOLD, 20)); timeLabel.setLayout(new FlowLayout(FlowLayout.LEFT)); timePanel.add(timeLabel); rightPanel.add(timePanel); JPanel tiPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton helpButton = new JButton("提示"); helpButton.setSize(60, rightPanel.getHeight()); helpButton.setLayout(new FlowLayout(FlowLayout.RIGHT)); helpButton.addMouseListener(helpMouseAdapter); tiPanel.add(helpButton); rightPanel.add(tiPanel); frame.add(topPanel, BorderLayout.NORTH); // 游戏区 JPanel bodyPanel = new JPanel(); bodyPanel.setLayout(new GridLayout(ROWS, COLUMNS)); bodyPanel.setSize(frame.getWidth(), frame.getHeight() - topPanel.getHeight()); frame.add(bodyPanel); // 画格子 panels = new JBallPanel[ROWS * COLUMNS]; for (int i = 0, len = panels.length; i < len; i++) { panels[i] = new JBallPanel(); panels[i].setBackground((i & 1) == 0 ? DEEP : LIGHT); panels[i].setName(String.valueOf(i)); bodyPanel.add(panels[i]); // panels[i].setNo(String.valueOf(i)); // TODO debug } // 初始化弹珠的个数 total_ball = new int[9]; for (int i = 0; i < map.length; i++) { total_ball[map[i]]++; } // 增加全局键盘事件 Toolkit.getDefaultToolkit().addAWTEventListener(e -> { if (e.getID() == KeyEvent.KEY_PRESSED) { KeyEvent ke = (KeyEvent) e; int code = ke.getKeyCode(); switch (code) { // 空格暂停 case KeyEvent.VK_SPACE: pause(); break; // backspace, delete, 左键反悔一步 case KeyEvent.VK_DELETE: case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_LEFT: backward(); break; } } }, AWTEvent.KEY_EVENT_MASK); frame.setVisible(true); stack = new LinkedList<>(); } /** * 画球以及擦除球 * * @param display true:显示 false:隐藏 */ void drawBall(boolean display) { // 画球 按赤橙黄绿青蓝紫灰的顺序分别用1-8表示 if (display) { for (int i = 0, len = map.length; i < len; i++) { int n; if ((n = map[i]) != 0) { // TODO 暂时使用颜色代替 panels[i].setColor(Ball_color[n]); } else { // 没有画球的空地增加鼠标点击事件 panels[i].addMouseListener(checkMouseAdapter); } } // 初始化计时器 if (timer == null) { timer = new Timer(1000, e -> timeLabel.setText(timeFormat(++start_time))); } timer.start(); if (animationTimer == null) { animationTimer = new Timer(150, null); } } else { for (int i = 0, len = map.length; i < len; i++) { if (map[i] != 0) { panels[i].deleteIcon(); } else { // 不显示球的时候同时去除鼠标事件 panels[i].removeMouseListener(checkMouseAdapter); } } timer.stop(); // 暂停计时 } } /** * 鼠标点击空格子后的处理 * * @param index 格子的下标 */ int[] check(int index) { int row = index / COLUMNS, col = index % ROWS; // 横向查找 int xs = index, xn = index, xl = row * COLUMNS, xu = (row + 1) * COLUMNS - 1; while (xs - 1 >= xl && map[--xs] == 0) ; while (xn + 1 <= xu && map[++xn] == 0) ; // 纵向查找 int ys = index, yn = index, yl = col, yu = map.length - (COLUMNS - col); while (ys - COLUMNS >= yl && map[ys -= COLUMNS] == 0) ; while (yn + COLUMNS <= yu && map[yn += COLUMNS] == 0) ; logger.info("xs:" + xs + ", xl:" + xn + ", ys:" + ys + ", yl:" + yn); return check0(xs, xn, ys, yn); } /** * 扫描4个方向是否有相同颜色的球 * * @param n */ private int[] check0(int... n) { int[] clone = n.clone(); for (int i = 0, len = n.length - 1; i < len; i++) { if (clone[i] == -1) continue; for (int j = i + 1; j < len + 1; j++) { if (clone[j] == -1) continue; if (map[n[j]] != 0 && map[n[i]] == map[n[j]]) { clone[i] = -1; clone[j] = -1; } } } int[] log = new int[n.length]; int index = 0; for (int i = 0; i < clone.length; i++) { if (clone[i] == -1) { log[index++] = n[i]; } } logger.info("消除[" + index + "]个球."); return index > 0 ? Arrays.copyOf(log, index) : null; } /** * 消除球体 * * @param indexs */ void delete(int... indexs) { ActionListener[] actions = animationTimer.getActionListeners(); for (ActionListener action : actions) { animationTimer.removeActionListener(action); int info = ((AnimationListener) action).get(); whenError(info); } for (int i = 0; i < indexs.length; i++) { int index = indexs[i], cc = map[index]; indexs[i] = index * 10 + map[index]; map[index] = 0; total_ball[cc]--; panels[index].deleteIcon(); // 消除球体之后会留下一个空的格子, 要给空格子加上鼠标点击事件 panels[index].addMouseListener(checkMouseAdapter); // int last = index - c, t = last / COLUMNS, s, l; // if (t > 0) { // s = t; // l = COLUMNS; // } else if (t < 0) { // s = -t; // l = -COLUMNS; // } else if (last > 0) { // s = last; // l = 1; // } else { // s = -last; // l = -1; // } animationTimer.addActionListener(new AnimationListener(index, cc)); } animationTimer.start(); stack.push(indexs); markScore(stack.peek().length); } /** * 评分: 一次消2个得2分, 一次消3个得4分, 一次消4个得10分 * * @param size >0:消除 <0:反回 * @return */ void markScore(int size) { int s; if (size > 0) { s = score_map[size]; } else { s = -score_map[-size]; } scoreLabel.setText(String.valueOf(score += s)); Color c; if (score > 150) { c = Color.RED; } else if (score > 100) { c = Color.PINK; } else if (score > 50) { c = Color.BLUE; } else c = Color.BLACK; scoreLabel.setForeground(c); } /** * 时间格式化, 将秒格式化为00:00 * * @param time 秒 * @return */ String timeFormat(int time) { int m = time / 60, s = time % 60; char[] cs = {'0', '0', ':', '0', '0'}; cs[0] += m / 10; cs[1] += m % 10; cs[3] += s / 10; cs[4] += s % 10; return new String(cs); } /** * 暂停 */ void pause() { // 暂停->开始/开始->暂停 int i = Integer.parseInt(startButton.getName()); drawBall(i == 0); i = i == 0 ? 1 : 0; startButton.setName(String.valueOf(i)); startButton.setText(btn_name[i]); } /** * 回退 */ void backward() { if (stack.isEmpty()) { logger.info("stack is empty."); return; } int[] log = stack.pop(); for (int l : log) { int index = l / 10, color = l % 10; map[index] = color; panels[index].setColor(Ball_color[color]); } markScore(-log.length); } /** * 提示 */ void smartHelp() { // TODO 优先找最大可消除位置 int n; if ((n = fastFail()) > 0) { JOptionPane.showMessageDialog(frame, "剩余["+ball_color[n]+"色]弹珠无法完全."); } // 1.查找空格子 // 2.记录可以消除的弹珠数 // 3.比较大小然后得到最大的数 // 4.查检剩余的弹珠是否能完全消除 } /** * 快速失败 * @return */ int fastFail() { // 1.如果该颜色只有1个 for (int i = 0; i < total_ball.length; i++) { if (total_ball[i] == 1) return i; } // 2.同一颜色有多个 for (int i = 0; i < map.length; i++) { if (i == 0) continue; int row = i / COLUMNS, col = i % ROWS, c = map[i]; // 横向查找 int xs = i, xn = i, xl = row * COLUMNS, xu = (row + 1) * COLUMNS - 1; while (xs - 1 >= xl && map[--xs] == c) ; while (xn + 1 <= xu && map[++xn] == c) ; // 纵向查找 int ys = i, yn = i, yl = col, yu = map.length - (COLUMNS - col); while (ys - COLUMNS >= yl && map[ys -= COLUMNS] == c) ; while (yn + COLUMNS <= yu && map[yn += COLUMNS] == c) ; // 2.1.同颜色相邻 if ((xs != xn || ys != yn) && (xn - xs + yn - ys == total_ball[c])) { return c; } // 2.2.同颜色在同一直线且中间隔着其它颜色 // 横向查找 int n = 0, _n = -1; for (int j = xl; j < xu; j++) { if (map[j] == c) { if (_n == -1) _n = n; else if (_n == 9999) _n = 999; n++; } else { if (_n != -1) _n = 9999; } } if (n == total_ball[c] && _n == 999) { return c; } n = 0; _n = -1; // 纵向查找 for (int j = yl; j < yu; j+=COLUMNS) { if (map[j] == c) { if (_n == -1) _n = n; else if (_n == 9999) _n = 999; n++; } else { if (_n != -1) _n = 9999; } } if (n == total_ball[c] && _n == 999) { return c; } } return 0; } /** * 动画过程中出现错误时将十字路经上的背景使用修改为正确背景 * * @param c */ void whenError(int c) { panels[c].deleteIcon(); } void animation(int s, int c, int l) { while (--s > 1) { panels[c].setBackground((c & 1) == 0 ? DEEP : LIGHT); panels[c += l].setBackground(Color.CYAN); try { Thread.sleep(150); } catch (InterruptedException e) { e.printStackTrace(); } } panels[c].setBackground((c & 1) == 0 ? DEEP : LIGHT); panels[c + l].deleteIcon(); // 消除球体之后会留下一个空的格子, 要给空格子加上鼠标点击事件 panels[c + l].addMouseListener(checkMouseAdapter); } // 鼠标点击事件--点击空格子 MouseAdapter checkMouseAdapter = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); JBallPanel panel = (JBallPanel) e.getSource(); int current = Integer.parseInt(panel.getName()); int[] log = check(current); if (log != null) delete(log); stepLabel.setText(String.valueOf(++click_total)); } } // 鼠标点击事件--开始/暂停 按钮 , startMouseAdapter = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); pause(); } } // 鼠标点击事件--提示 , helpMouseAdapter = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); smartHelp(); } }; // /** // * 动画类 // */ // class AnimationService implements Callable<Integer> { // private int s, c, l; // // public AnimationService(int s, int c, int l) { // this.s = s; // this.c = c; // this.l = l; // } // // public int[] get() { // return new int[]{s, c, l}; // } // // @Override // public Integer call() throws Exception { // while (--s > 1) { // SwingUtilities.invokeLater(() -> { // panels[c].setBackground((c & 1) == 0 ? DEEP : LIGHT); // panels[c].updateUI(); // panels[c += l].setBackground(Color.CYAN); // panels[c].updateUI(); // }); // Thread.sleep(150); // } //// SwingUtilities.invokeLater(() -> { // panels[c].setBackground((c & 1) == 0 ? DEEP : LIGHT); // panels[c].updateUI(); // panels[c + l].deleteIcon(); // panels[c + 1].updateUI(); // // 消除球体之后会留下一个空的格子, 要给空格子加上鼠标点击事件 // panels[c + l].addMouseListener(checkMouseAdapter); //// }); // return s - 1; // } // } class AnimationListener implements ActionListener { private int c, cc, n = 4; public AnimationListener(int c, int cc) { this.c = c; this.cc = cc; } public int get() { return c; } @Override public void actionPerformed(ActionEvent e) { if (n-- > 0) { Color color = panels[c].getColor(), backColor = (c & 1) == 0 ? DEEP : LIGHT; panels[c].setColor(color == Ball_color[cc] ? backColor : Ball_color[cc]); } else animationTimer.stop(); } } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(() -> new MainUI()); } }
gpl-3.0
jainaman224/Algo_Ds_Notes
Leaders_Of_Array/Leaders_Of_Array.java
1031
/* LEADERS OF AN ARRAY The task is to find all leaders in an array, where a leader is an array element which is greater than all the elements on its right side */ import java.util.Scanner; class Leaders_Of_Array { public static void main(String args[]) { int num; System.out.println("Enter the size of array : "); Scanner s = new Scanner(System.in); num = s.nextInt(); int a[] = new int[num]; System.out.println("Enter array elements"); for (int i = 0; i < num; i++) { a[i] = s.nextInt(); } int maximum = a[num - 1]; System.out.println("The following are the leaders of array : "); System.out.print(a[num - 1] + " "); for (int i = num - 2; i >= 0; i--) { if (a[i] > maximum) { System.out.print(a[i] + " "); } } } } /* Input : num = 5 Array = [13, 4, 12, 1, 5] Output : The following are the leaders of array : 5 12 13 */
gpl-3.0
Irokue/Craftbukkit-1.3
src/main/java/net/minecraft/server/EntityIronGolem.java
5216
package net.minecraft.server; import org.bukkit.craftbukkit.inventory.CraftItemStack; // CraftBukkit public class EntityIronGolem extends EntityGolem { private int e = 0; Village d = null; private int f; private int g; public EntityIronGolem(World world) { super(world); this.texture = "/mob/villager_golem.png"; this.a(1.4F, 2.9F); this.getNavigation().a(true); this.goalSelector.a(1, new PathfinderGoalMeleeAttack(this, 0.25F, true)); this.goalSelector.a(2, new PathfinderGoalMoveTowardsTarget(this, 0.22F, 32.0F)); this.goalSelector.a(3, new PathfinderGoalMoveThroughVillage(this, 0.16F, true)); this.goalSelector.a(4, new PathfinderGoalMoveTowardsRestriction(this, 0.16F)); this.goalSelector.a(5, new PathfinderGoalOfferFlower(this)); this.goalSelector.a(6, new PathfinderGoalRandomStroll(this, 0.16F)); this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); this.targetSelector.a(1, new PathfinderGoalDefendVillage(this)); this.targetSelector.a(2, new PathfinderGoalHurtByTarget(this, false)); this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget(this, EntityMonster.class, 16.0F, 0, false, true)); } protected void a() { super.a(); this.datawatcher.a(16, Byte.valueOf((byte) 0)); } public boolean aV() { return true; } protected void bd() { if (--this.e <= 0) { this.e = 70 + this.random.nextInt(50); this.d = this.world.villages.getClosestVillage(MathHelper.floor(this.locX), MathHelper.floor(this.locY), MathHelper.floor(this.locZ), 32); if (this.d == null) { this.aE(); } else { ChunkCoordinates chunkcoordinates = this.d.getCenter(); this.b(chunkcoordinates.x, chunkcoordinates.y, chunkcoordinates.z, this.d.getSize()); } } super.bd(); } public int getMaxHealth() { return 100; } protected int h(int i) { return i; } public void d() { super.d(); if (this.f > 0) { --this.f; } if (this.g > 0) { --this.g; } if (this.motX * this.motX + this.motZ * this.motZ > 2.500000277905201E-7D && this.random.nextInt(5) == 0) { int i = MathHelper.floor(this.locX); int j = MathHelper.floor(this.locY - 0.20000000298023224D - (double) this.height); int k = MathHelper.floor(this.locZ); int l = this.world.getTypeId(i, j, k); if (l > 0) { this.world.a("tilecrack_" + l, this.locX + ((double) this.random.nextFloat() - 0.5D) * (double) this.width, this.boundingBox.b + 0.1D, this.locZ + ((double) this.random.nextFloat() - 0.5D) * (double) this.width, 4.0D * ((double) this.random.nextFloat() - 0.5D), 0.5D, ((double) this.random.nextFloat() - 0.5D) * 4.0D); } } } public boolean a(Class oclass) { return this.q() && EntityHuman.class.isAssignableFrom(oclass) ? false : super.a(oclass); } public boolean k(Entity entity) { this.f = 10; this.world.broadcastEntityEffect(this, (byte) 4); boolean flag = entity.damageEntity(DamageSource.mobAttack(this), 7 + this.random.nextInt(15)); if (flag) { entity.motY += 0.4000000059604645D; } this.world.makeSound(this, "mob.irongolem.throw", 1.0F, 1.0F); return flag; } public Village n() { return this.d; } public void e(boolean flag) { this.g = flag ? 400 : 0; this.world.broadcastEntityEffect(this, (byte) 11); } protected String aQ() { return "none"; } protected String aR() { return "mob.irongolem.hit"; } protected String aS() { return "mob.irongolem.death"; } protected void a(int i, int j, int k, int l) { this.world.makeSound(this, "mob.irongolem.walk", 1.0F, 1.0F); } protected void dropDeathLoot(boolean flag, int i) { // CraftBukkit start java.util.List<org.bukkit.inventory.ItemStack> loot = new java.util.ArrayList<org.bukkit.inventory.ItemStack>(); int j = this.random.nextInt(3); int k; if (j > 0) { loot.add(new CraftItemStack(Block.RED_ROSE.id, j)); } k = 3 + this.random.nextInt(3); if (k > 0) { loot.add(new CraftItemStack(Item.IRON_INGOT.id, k)); } org.bukkit.craftbukkit.event.CraftEventFactory.callEntityDeathEvent(this, loot); // CraftBukkit end } public int p() { return this.g; } public boolean q() { return (this.datawatcher.getByte(16) & 1) != 0; } public void f(boolean flag) { byte b0 = this.datawatcher.getByte(16); if (flag) { this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 1))); } else { this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -2))); } } }
gpl-3.0
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/engine/util/XmlNamespace.java
2097
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.engine.util; /** * An XML namespace. * * @author Lucian Chirita (lucianc@users.sourceforge.net) * @see JRXmlWriteHelper#startElement(String, XmlNamespace) */ public class XmlNamespace { private final String nsURI; private final String prefix; private final String schemaURI; /** * Creates an XML namespace. * * @param uri the namespace URI * @param prefix the namespace prefix * @param schemaURI the URI of the XML schema associated with the namespace */ public XmlNamespace(String uri, String prefix, String schemaURI) { this.prefix = prefix; this.schemaURI = schemaURI; this.nsURI = uri; } /** * Returns the namespace URI. * * @return the namespace URI */ public String getNamespaceURI() { return nsURI; } /** * Returns the namespace prefix. * * @return the namespace prefix */ public String getPrefix() { return prefix; } /** * Returns the URI of the XML schema associated with the namespace. * * @return the namespace XML schema URI */ public String getSchemaURI() { return schemaURI; } }
gpl-3.0
alberapps/tiempobus
TiempoBus/src/alberapps/java/exception/TiempoBusException.java
2003
/** * TiempoBus - Informacion sobre tiempos de paso de autobuses en Alicante * Copyright (C) 2012 Alberto Montiel * * * 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 alberapps.java.exception; /** * */ public class TiempoBusException extends Exception { /** * */ private static final long serialVersionUID = -2041443242078108937L; public static int ERROR_STATUS_SERVICIO = 1; public static String ERROR_STATUS_SERVICIO_MSG = "Error en el status del servicio"; public static int ERROR_005_SERVICIO = 2; public static int ERROR_NO_DEFINIDO = 3; private int codigo; /** * */ public TiempoBusException() { } public TiempoBusException(int cod) { super(ERROR_STATUS_SERVICIO_MSG); codigo = cod; } /** * @param detailMessage */ public TiempoBusException(String detailMessage) { super(detailMessage); } /** * @param throwable */ public TiempoBusException(Throwable throwable) { super(throwable); } /** * @param detailMessage * @param throwable */ public TiempoBusException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } }
gpl-3.0
lyind/base
src/main/java/net/talpidae/base/client/InsectNameUserAgentRequestFilter.java
2100
/* * Copyright (C) 2017 Jonas Zeiger <jonas.zeiger@talpidae.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.talpidae.base.client; import net.talpidae.base.insect.config.SlaveSettings; import java.io.IOException; import java.util.Optional; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.ext.Provider; import lombok.extern.slf4j.Slf4j; import lombok.val; import static com.google.common.base.Strings.isNullOrEmpty; /** * Adds the insect name to the user-agent header value. */ @Singleton @Provider @Slf4j public class InsectNameUserAgentRequestFilter implements ClientRequestFilter { private final String insectName; @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @Inject public InsectNameUserAgentRequestFilter(Optional<SlaveSettings> slaveSettings) { insectName = slaveSettings.map(SlaveSettings::getName).orElse(null); } @Override public void filter(ClientRequestContext requestContext) throws IOException { if (insectName != null) { val userAgent = requestContext.getHeaderString(HttpHeaders.USER_AGENT); val nextUserAgent = isNullOrEmpty(userAgent) ? insectName : insectName + "/" + userAgent; requestContext.getHeaders().putSingle(HttpHeaders.USER_AGENT, nextUserAgent); } } }
gpl-3.0
smap-consulting/smapserver
sdDAL/src/org/smap/sdal/model/TaskAssignmentPair.java
112
package org.smap.sdal.model; public class TaskAssignmentPair { public int taskId; public int assignmentId; }
gpl-3.0
Relicum/Ipsum
src/main/java/com/relicum/ipsum/Menus/RunCommand.java
2079
/* * Ipsum is a rapid development API for Minecraft, developer by Relicum * Copyright (C) 2015. Chris Lutte * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.relicum.ipsum.Menus; import java.util.ArrayList; import java.util.List; import lombok.Getter; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import com.relicum.ipsum.Conversations.MMPlayer; /** * Name: RunCommand.java Created: 21 January 2015 * * @author Relicum * @version 0.0.1 */ public class RunCommand implements Perform { private List<String> commands; @Getter private boolean useConsole; @Getter private MMPlayer player; public RunCommand() { this.commands = new ArrayList<>(); } @Override public void addCommand(String cmd) { commands.add(cmd); } @Override public List<String> getCommands() { return commands; } @Override public void setUseConsole(boolean use) { Validate.notNull(use); this.useConsole = use; } @Override public void addPlayer(MMPlayer player) { Validate.notNull(player); this.player = player; } @Override public void perform() { for (String cmd : commands) { if (useConsole) Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replaceAll("\\\\", "")); else this.player.performCommand(cmd.replaceAll("\\\\", "/")); } } }
gpl-3.0
RenanVictor/Projeto-TCC
src/tcc/curriculo/CursandoFXMLController.java
2957
/* * 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 tcc.curriculo; import java.net.URL; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.stage.Stage; import javax.swing.JOptionPane; import tcc.dominio.Cursando; import tcc.dominio.Curso; import tcc.dominio.Uteis; import tcc.dominio.dados.CursandoDados; import tcc.dominio.dados.CursoDados; public class CursandoFXMLController implements Initializable{ @FXML private TextField txtIngresso; @FXML private TextField txtConclusao; @FXML private TextField txtTitulo; @FXML private ComboBox<Curso> cmbCurso; @FXML private TextField txtArea; @FXML private ComboBox<String> cmbPeriodo; Cursando cursando = new Cursando(); CursoDados cursodados = new CursoDados(); @Override public void initialize(URL url, ResourceBundle rb) { cmbPeriodo.getItems().add("Manhã"); cmbPeriodo.getItems().add("Tarde"); cmbPeriodo.getItems().add("Noite"); try { cmbCurso.getItems().addAll(cursodados.listarCursos()); } catch (SQLException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Select falhou"); } } private void preencher() { SimpleDateFormat dateFormats = new SimpleDateFormat("d/M/y"); try { cursando.setIngresso(dateFormats.parse(txtIngresso.getText())); cursando.setConclusao(dateFormats.parse(txtConclusao.getText())); cursando.setPeriodo(cmbPeriodo.getSelectionModel().getSelectedItem()); cursando.setCurso(cmbCurso.getSelectionModel().getSelectedItem()); } catch (ParseException ex) { ex.printStackTrace(); Uteis.mensagemPreencherCampos(); } } private void PreencherCampos(){ txtIngresso.setText("20/02/2000"); txtConclusao.setText("20/02/2000"); } @FXML public void btnNext(ActionEvent evento){ PreencherCampos(); preencher(); CursandoDados cursandodados = new CursandoDados(); try { cursandodados.salvarCursando(cursando); Uteis.mensagemSalvo(); FXMLDocumentController principal = new FXMLDocumentController(); PrincipalController.chamaTela("ExperienciaFXML.fxml"); } catch (Exception e) { Uteis.mensagemNaoSalvo(); e.printStackTrace(); } } }
gpl-3.0
VladimirShevel/GoItOnline
vshevel/goit/module3/task3/Trumpet.java
213
package vshevel.goit.module3.task3; public class Trumpet extends MusicalInstrument { @Override public void howDoesThisSound() { System.out.println("It's sound not like Piano or Guitar"); } }
gpl-3.0
maximumtech/Game
Game/src/Game/generation/StructureGenTree.java
2033
package Game.generation; import Game.base.BlockBase; import Game.base.World; /** * * @author maximumtech */ public class StructureGenTree extends StructureGenBase { public StructureGenTree(World world) { super(world); } public void generate(int x, int y) { int height = 13 + rand.nextInt(5); int leavesProg = height / 2; boolean passedLast = false; for (int i = 0; leavesProg > 0 || i < height; i++) { int yy = y + i; if (leavesProg == 0) { leavesProg = 1; } BlockBase block1 = world.getBlock(x, yy); if (i < height - 1 && (block1 == null || block1.canBeReplaced(world, x, y, BlockBase.woodLog))) { world.setBlock(x, yy, BlockBase.woodLog, (short) 1); } if (i > height - 11 && leavesProg > 0) { for (int o = x - leavesProg; o <= x + leavesProg; o++) { BlockBase block2 = world.getBlock(o, yy); if (block2 == null || block2.canBeReplaced(world, x, y, BlockBase.woodLog)) { if (o != x) { world.setBlock(o, yy, BlockBase.leaves); } else if (i >= height - 1) { world.setBlock(o, yy, BlockBase.leaves, (short) 1); } } } //if(leavesProg > 4) { // hitDelim = true; //} //if(hitDelim) { if (rand.nextInt(4) == 0 || passedLast) { leavesProg--; passedLast = false; } else { passedLast = true; } //}else{ // leavesProg++; //} } else if (i == height - 11) { world.setBlock(x + 1, yy, BlockBase.leaves); world.setBlock(x - 1, yy, BlockBase.leaves); } } } }
gpl-3.0
aroog/code
PointsToOOG/src/edu/wayne/ograph/analysis/ValueFlowTransferFunctions.java
16047
package edu.wayne.ograph.analysis; import java.util.Collections; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ArrayAccess; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.junit.Assert; import edu.cmu.cs.aliasjava.Constants; import edu.cmu.cs.crystal.annotations.ICrystalAnnotation; import edu.cmu.cs.crystal.tac.eclipse.EclipseTAC; import edu.cmu.cs.crystal.tac.model.CopyInstruction; import edu.cmu.cs.crystal.tac.model.LoadArrayInstruction; import edu.cmu.cs.crystal.tac.model.LoadFieldInstruction; import edu.cmu.cs.crystal.tac.model.MethodCallInstruction; import edu.cmu.cs.crystal.tac.model.ReturnInstruction; import edu.cmu.cs.crystal.tac.model.SourceVariable; import edu.cmu.cs.crystal.tac.model.SourceVariableDeclaration; import edu.cmu.cs.crystal.tac.model.StoreFieldInstruction; import edu.cmu.cs.crystal.tac.model.ThisVariable; import edu.cmu.cs.crystal.tac.model.TypeVariable; import edu.cmu.cs.crystal.tac.model.Variable; import edu.wayne.alias.FieldVariable; import edu.wayne.auxiliary.Utils; import edu.wayne.flowgraph.FlowAnnot; import edu.wayne.flowgraph.FlowAnnotType; import edu.wayne.flowgraph.FlowGraphEdge; import edu.wayne.flowgraph.FlowGraphNode; import edu.wayne.ograph.internal.DomainP; import edu.wayne.ograph.internal.IDDictionary; import edu.wayne.ograph.internal.OOGContext; import edu.wayne.ograph.internal.OObject; import edu.wayne.ograph.internal.OwnershipType; import edu.wayne.ograph.internal.QualifiedClassName; import edu.wayne.pointsto.PointsToAnalysis; public class ValueFlowTransferFunctions extends NodesOOGTransferFunctions { private Map<String, Set<Variable>> returnVariables; // private Map<String, Integer> methodInvocations; private static long invocation; public ValueFlowTransferFunctions(PointsToAnalysis pointsToAnalysis) { super(pointsToAnalysis); returnVariables = new Hashtable<String, Set<Variable>>(); invocation = 0; } @Override public OOGContext transfer(CopyInstruction instr, OOGContext value) { QualifiedClassName cthis = getC_THIS(value); List<DomainP> actDomains = getTargetActualDomains(instr.getTarget(), instr, value.getGamma(), cthis); if (actDomains != null) { value.getGamma().put(instr.getTarget(), actDomains); if (actDomains.size() > 0) { Variable source = instr.getOperand(); List<DomainP> list = value.getGamma().get(source); if (list != null && list.size() > 0) { DomainP sourceDomain = list.get(0); FlowGraphNode src = new FlowGraphNode(value.getO(), source, sourceDomain); FlowGraphNode dst = new FlowGraphNode(value.getO(), instr.getTarget(), actDomains.get(0)); value.getFG().addInfoFlow(new FlowGraphEdge(src, dst, FlowAnnot.getEmpty())); } else { // cannot find domain for righthandside int debug = 0; debug++; } } } return super.transfer(instr, value); } @Override public OOGContext transfer(LoadArrayInstruction instr, OOGContext value) { // System.out.println("LoadArray: " + instr.getNode() + " O=" + // value.getO()); QualifiedClassName cthis = value.getO().getQCN(); Variable recv = instr.getSourceArray(); if (recv.resolveType().isArray()) { QualifiedClassName receiverClass = new QualifiedClassName(getRecvPreciseClass(recv, value.getO()), cthis); List<DomainP> receiverActualDomains = getReceiverActualDomains(recv, instr, value.getGamma(), cthis); if (receiverActualDomains != null) { ArrayAccess aa = (ArrayAccess) instr.getNode(); List<DomainP> formalTKDomains = getArrayAccessActualDomains(aa, cthis); if (formalTKDomains != null) { ITypeBinding fieldKClass = instr.getSourceArray().resolveType().getElementType(); value.getGamma().put(instr.getTarget(), formalTKDomains); QualifiedClassName labelClass = new QualifiedClassName(fieldKClass, cthis); Variable fk = instr.getArrayIndex(); Variable l = instr.getTarget(); addValueFlow(value, receiverClass, receiverActualDomains, labelClass, formalTKDomains, fk, formalTKDomains, l ); } } } return super.transfer(instr, value); } @Override public OOGContext transfer(LoadFieldInstruction instr, OOGContext value) { // System.out.println("FieldRead: " + instr.getNode() + " O=" + // value.getO()); // System.out.println("Gamma: " + value.getGamma()); if (!instr.isStaticFieldAccess()) { OObject o = value.getO(); QualifiedClassName cthis = o.getQCN(); Variable recv = instr.getSourceObject(); if (!recv.resolveType().isArray()) { QualifiedClassName receiverClass = new QualifiedClassName(getRecvPreciseClass(recv, o), cthis); List<DomainP> receiverActualDomains = getReceiverActualDomains(recv, instr, value.getGamma(), cthis); Set<OObject> oRecvs = auxLookup(value, o, receiverClass, receiverActualDomains); for (OObject or : oRecvs) { TypeVariable that = new TypeVariable(or.getQCN().getTypeBinding()); if (that != null) { DomainP thatOwner = new DomainP(or.getQCN(), Constants.OWNER); FlowGraphNode srcr = new FlowGraphNode(o, recv, receiverActualDomains.get(0)); FlowGraphNode dstr = new FlowGraphNode(or, that, thatOwner); FlowAnnot flowAnnot = FlowAnnot.getEmpty(); value.getFG().addInfoFlow(new FlowGraphEdge(srcr, dstr, flowAnnot)); } } if (receiverActualDomains != null) { // IN TR: call fields with substitution Map<String, List<DomainP>> fieldActualTypes = auxFields(recv, receiverClass, receiverActualDomains); // !!! NOT IN TR: call fields without substitution since we // call // lookup(O_i,...) Map<String, OwnershipType> fieldFormalTypes = auxFieldsWithoutSubst(receiverClass); OwnershipType oType = fieldFormalTypes.get(instr.getFieldName()); if (oType != null) { List<DomainP> formalTKDomains = oType.getValue(); List<DomainP> actualTKDomains = fieldActualTypes.get(instr.getFieldName()); Variable target = instr.getTarget(); ITypeBinding fieldKClass = target.resolveType(); value.getGamma().put(target, actualTKDomains); QualifiedClassName labelClass = new QualifiedClassName(fieldKClass, cthis); Variable fk = getFieldVariable(receiverClass.getTypeBinding(), instr); addValueFlow(value, receiverClass, receiverActualDomains, labelClass, formalTKDomains, fk, actualTKDomains, target); } } } } return super.transfer(instr, value); } @Override public OOGContext transfer(MethodCallInstruction instr, OOGContext value) { Variable receiver = instr.getReceiverOperand(); IMethodBinding mb = instr.resolveBinding(); QualifiedClassName cthis = getC_THIS(value); if (receiver != null) { // not a static method call QualifiedClassName recvClass = new QualifiedClassName(getRecvPreciseClass(receiver, value.getO()), cthis); List<DomainP> receiverActualDomains = getReceiverActualDomains(receiver, instr, value.getGamma(), cthis); OObject o = value.getO(); IMethodBinding mb1 = instr.resolveBinding(); FlowAnnot flowAnnot = new FlowAnnot(getInvocation(o,instr), FlowAnnotType.CALL); //mb1 = mb1.getMethodDeclaration(); Set<OObject> oRecvs = auxLookup(value, o, recvClass, receiverActualDomains); for (OObject or : oRecvs) { TypeDeclaration typeDecl = pointsToAnalysis.getTypeDecl(or.getC()); //TODO: XXX: replace such that we do not create a separate variable instance at every pass. TypeVariable that = new TypeVariable(or.getQCN().getTypeBinding()); if (that != null) { QualifiedClassName tThat = new QualifiedClassName(that.resolveType(), cthis); DomainP thatOwner = new DomainP(tThat, Constants.OWNER); FlowGraphNode srcr = new FlowGraphNode(o, receiver, receiverActualDomains.get(0)); FlowGraphNode dstr = new FlowGraphNode(or, that, thatOwner); value.getFG().addInfoFlow(new FlowGraphEdge(srcr, dstr, flowAnnot)); } List<Variable> fparams = getFormalParams(mb1, typeDecl); List<Variable> argOperands = instr.getArgOperands(); for (Variable arg : argOperands) { List<DomainP> argDomains = getArgActualDomains(arg, instr, value.getGamma(), cthis); boolean condition =argDomains != null && argDomains.size()>0 && fparams != null && fparams.size()==argOperands.size() && (!arg.resolveType().isPrimitive()); if (condition) { Variable fParam = fparams.get(argOperands.indexOf(arg)); List<DomainP> formalDomains = getDomainsOfFormalParams(mb1, typeDecl, cthis, argOperands.indexOf(arg)); if (formalDomains != null && argDomains.size() > 0 && formalDomains.size() > 0) { FlowGraphNode src = new FlowGraphNode(o, arg, argDomains.get(0)); FlowGraphNode dst = new FlowGraphNode(or, fParam, formalDomains.get(0)); value.getFG().addInfoFlow(new FlowGraphEdge(src, dst, flowAnnot)); } else{ this.pointsToAnalysis.addWarning(instr.getNode(), "Cannot find domains for " + fParam); } } else { if (!arg.resolveType().isPrimitive()) this.pointsToAnalysis.addWarning(instr.getNode(), "Cannot find corresponding formal param for " + arg); } } if (!mb.getReturnType().isPrimitive()) { List<DomainP> methFormalRetDoms = auxMTypeRetWithoutSubst(mb1, recvClass); List<DomainP> methActualRetDoms = auxMTypeRet(mb1, receiver, recvClass, receiverActualDomains); value.getGamma().put(instr.getTarget(), methActualRetDoms); Set<Variable> retVars = getRetVar(mb1); if ((methFormalRetDoms != null && methFormalRetDoms.size() > 0) && (methActualRetDoms != null && methActualRetDoms.size() > 0)) for (Variable ret : retVars) { FlowGraphNode src = new FlowGraphNode(or, ret, methFormalRetDoms.get(0)); FlowGraphNode dst = new FlowGraphNode(o, instr.getTarget(), methActualRetDoms.get(0)); // TODO: FIXME FlowAnnot closei = new FlowAnnot flowAnnot1 = new FlowAnnot(getInvocation(o,instr), FlowAnnotType.RETURN); value.getFG().addInfoFlow(new FlowGraphEdge(src, dst, flowAnnot1)); } } else { // do nothing for primitive types } } } return super.transfer(instr, value); } // private void addInvocation() { // invocation++; // } @Override public OOGContext transfer(ReturnInstruction instr, OOGContext value) { Variable returnedVariable = instr.getReturnedVariable(); ASTNode node = instr.getNode(); if (node instanceof ReturnStatement) { ReturnStatement rs = (ReturnStatement) node; MethodDeclaration md = getMethodDeclaration(rs); addToCachedDeclaration(md.resolveBinding(), returnedVariable); } return super.transfer(instr, value); } private void addToCachedDeclaration(IMethodBinding resolveBinding, Variable returnedVariable) { String key = resolveBinding.getKey(); if (returnVariables.containsKey(key)) { returnVariables.get(key).add(returnedVariable); } else { Set<Variable> vars = new HashSet<Variable>(); vars.add(returnedVariable); returnVariables.put(key, vars); } } private MethodDeclaration getMethodDeclaration(ASTNode rs) { ASTNode parent = rs.getParent(); if (parent instanceof MethodDeclaration) return (MethodDeclaration) parent; else return getMethodDeclaration(parent); } @Override public OOGContext transfer(StoreFieldInstruction instr, OOGContext value) { if (!Utils.isNullAssignment(instr)) { QualifiedClassName cthis = value.getO().getQCN(); Variable recv = instr.getDestinationObject(); QualifiedClassName recvClass = new QualifiedClassName(getRecvPreciseClass(recv, value.getO()), cthis); List<DomainP> recvActualDomains = getReceiverActualDomains(recv, instr, value.getGamma(), cthis); if (recvActualDomains != null) { Map<String, OwnershipType> auxFieldsWithoutSubst = auxFieldsWithoutSubst(recvClass); OwnershipType fieldType = auxFieldsWithoutSubst.get(instr.getFieldName()); List<DomainP> rDomains = getSourceActualDomains(instr, value.getGamma(), cthis); // TODO:XXX fix me, what if the right hand side is a SimpleName? if (fieldType != null && fieldType.getValue() != null && rDomains!=null) { Variable fk = new FieldVariable(instr.resolveFieldBinding()); Variable r = instr.getSourceOperand(); if (!addValueFlow2(value, recvClass, recvActualDomains, new QualifiedClassName(fieldType.getKey(), cthis), fieldType.getValue(), fk, r, rDomains)){ pointsToAnalysis.addWarning(instr.getNode(), MISSING_DOMAINS); } } } } return super.transfer(instr, value); } @Override public OOGContext transfer(SourceVariableDeclaration instr, OOGContext value) { QualifiedClassName declaringClass = value.getO().getQCN(); if (declaringClass != null) { SourceVariable v = instr.getDeclaredVariable(); getDeclaredVarDomains(v, value.getGamma(), declaringClass); } return super.transfer(instr, value); } private Variable getFieldVariable(ITypeBinding typeBinding, LoadFieldInstruction instr) { Variable ffield = null; IVariableBinding field = instr.resolveFieldBinding(); return new FieldVariable(field); // BodyDeclaration bd = // Utils.getEnclosingFieldMethodDeclaration(instr.getNode()); // if (bd instanceof MethodDeclaration) { // MethodDeclaration md = (MethodDeclaration) bd; // EclipseTAC methodTAC = // this.pointsToAnalysis.getSavedInput().getMethodTAC(md); // return methodTAC.sourceVariable(field); // } else { // this.pointsToAnalysis.getTypeDecl(Type.createFrom()); // } // // return ffield; } private void addValueFlow(OOGContext value, QualifiedClassName receiverClass, List<DomainP> receiverActualDomains, QualifiedClassName labelClass, List<DomainP> formalTKDomains, Variable fk, List<DomainP> actualTKDomains, Variable l) { if (formalTKDomains != null && formalTKDomains.size() > 0) { OObject o = value.getO(); Set<OObject> oRecvs = auxLookup(value, o, receiverClass, receiverActualDomains); for (OObject or : oRecvs) { FlowGraphNode src = new FlowGraphNode(or, fk, formalTKDomains.get(0)); FlowGraphNode dst = new FlowGraphNode(o, l, actualTKDomains.get(0)); value.getFG().addInfoFlow(new FlowGraphEdge(src, dst, FlowAnnot.getEmpty())); } } else { int debug = 0; debug++; } } private Set<Variable> getRetVar(IMethodBinding mb) { Set<Variable> set = this.returnVariables.get(mb.getKey()); if (set != null) return Collections.unmodifiableSet(set); else return Collections.unmodifiableSet(new HashSet<Variable>()); } private boolean addValueFlow2(OOGContext value, QualifiedClassName recvClass, List<DomainP> recvActualDomains, QualifiedClassName labelQCN, List<DomainP> labelActualDomains, Variable fk, Variable r, List<DomainP> rDomains) { if (rDomains.isEmpty()) return false; if (labelActualDomains.isEmpty()) return false; OObject o = value.getO(); Set<OObject> oRecvs = auxLookup(value, o, recvClass, recvActualDomains); for (OObject or : oRecvs) { FlowGraphNode src = new FlowGraphNode(o, r, rDomains.get(0)); FlowGraphNode dst = new FlowGraphNode(or, fk, labelActualDomains.get(0)); value.getFG().addInfoFlow(new FlowGraphEdge(src, dst, FlowAnnot.getSTAR())); } return true; } }
gpl-3.0
charlesyao/FXS-Platform
fxs-platform-web/src/main/java/com/fxs/platform/web/controller/DisputeInfoController.java
8398
package com.fxs.platform.web.controller; import java.util.List; import com.fxs.platform.security.core.support.ResponseMessage; import com.fxs.platform.security.core.support.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.ObjectUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.SessionStatus; import com.fxs.platform.domain.Answer; import com.fxs.platform.domain.DisputeInfo; import com.fxs.platform.domain.Question; import com.fxs.platform.service.AnswerService; import com.fxs.platform.service.FalltypusService; import com.fxs.platform.service.QuestionService; import com.fxs.platform.utils.ResponseCodeEnum; @Controller @RequestMapping("/disputeInfo") public class DisputeInfoController { @Autowired private AnswerService answerService; @Autowired private QuestionService questionService; @Autowired FalltypusService falltypusService; /** * 获取所有的纷争信息 * * @param map * @return */ @GetMapping("/getAllDisputeInfo") public String getAllDisputeInfo(ModelMap map) { map.addAttribute("questionList", questionService.getAllQuestion()); map.addAttribute("availableFalltypus", falltypusService.findAll()); return "public_list_dispute_info"; } /** * 根据案件类型过滤已绑定的问题 * * @param filter * @param map * @return */ @GetMapping("/filterDisputeInfo/{filter}") public String getDisputeInfoWithFilter(@PathVariable("filter") String filter, ModelMap map) { if (! ObjectUtils.isEmpty(filter) && !filter.equals("-1")) { map.addAttribute("questionList", questionService.filterAllQuestionsByFalltypus(filter)); } else { map.addAttribute("questionList", questionService.getAllQuestion()); } map.addAttribute("availableFalltypus", falltypusService.findAll()); return "public_list_dispute_info :: questionBlock-fragment"; } /** * 创建问题 * @param disputeInfo * @param bindingResult * @param map * @return */ @GetMapping(value = "/createDisputeInfo") public String newDisputeInfoForm(@ModelAttribute(value = "disputeInfo") DisputeInfo disputeInfo, BindingResult bindingResult, ModelMap map) { return "public_add_dispute_info"; } @PostMapping(value = "/createDisputeInfo") public String create(DisputeInfo disputeInfo, BindingResult result, SessionStatus status) { List<String> questions = disputeInfo.getQuestion(); Question ques = null; if (!ObjectUtils.isEmpty(questions)) { for (String question : questions) { ques = new Question(); ques.setDescription(question); ques.setIsRootQuestion(disputeInfo.getIsRootQuestion()); ques.setQuestionType(disputeInfo.getQuestionType()); //ques.setDisputeInfo(disputeInfo); questionService.save(ques); List<String> answers = disputeInfo.getAnswer(); Answer answer = null; if (answers != null) { for (int i = 0; i < answers.size(); i++) { if(!ObjectUtils.isEmpty(answers.get(i))) { answer = new Answer(); answer.setDescription(answers.get(i)); answer.setQuestion(ques); answerService.save(answer); } } } } } return "redirect:/disputeInfo/getAllDisputeInfo"; } @GetMapping(value = "/viewDisputeInfo/{id}") public String view(@PathVariable("id") String id, ModelMap map) { Question question = questionService.getByQuestionId(id); map.addAttribute("availableFalltypus", falltypusService.findAll()); map.addAttribute("availableQuestions", questionService.getAllQuestion()); if(!ObjectUtils.isEmpty(question)) { map.addAttribute("mappedQuestionAnswers", answerService.getAllAnswerByQuestionId(question.getId())); map.addAttribute("question", question); } else { map.addAttribute("mappedQuestionAnswers", null); map.addAttribute("question", null); } return "public_view_dispute_info"; } @DeleteMapping(value = "/question/delete/{id}") @ResponseBody public ResponseMessage<String> deleteQuestion(@PathVariable("id") String id) { questionService.delete(id); return Result.success("success"); } @DeleteMapping(value = "/answer/delete/{id}") @ResponseBody public ResponseMessage<String> deleteAnswer(@PathVariable("id") String id) { answerService.delete(id); return Result.success("success"); } @PostMapping(value = "/updateAnswer") public String update(@ModelAttribute(value = "answer") Answer answer, BindingResult result, SessionStatus status) { //List<Integer> nextQuestionIds = question.getDisputeInfo().getNextQuestion(); //List<String> answers = question.getDisputeInfo().getAnswer(); /*if (answers != null) { for (int i = 0; i < answers.size(); i++) { //answerService.updateNextQuestion(answers.get(i)); } }*/ status.setComplete(); return "redirect:/disputeInfo/getAllDisputeInfo"; } /** * 更新问题信息 * * @param question * @return */ @PutMapping(value = "/update/question/basic") @ResponseBody public ResponseMessage<String> updateQuestionBasicInfo(@RequestBody Question question) { Question qInfo = questionService.getByQuestionId(question.getId()); Question rootQuestion = null; //在编辑问题的时候,如果将当前问题设置为根问题,则需要判断当前选择的带绑定的案件类型下是否已经有绑定根问题,如有则不能重复绑定 if ("Y".equals(question.getIsRootQuestion())) { rootQuestion = questionService.findCurrentRootQuestion(question.getBelongsToFalltypus()); } if(!ObjectUtils.isEmpty(rootQuestion) && !rootQuestion.getBelongsToFalltypus().equals(qInfo.getBelongsToFalltypus())) { return Result.error(String.valueOf(ResponseCodeEnum.ERROR.getCode()), "同一个案件类型不能绑定多个根问题"); } if(!ObjectUtils.isEmpty(qInfo)) { //如果当前选择的待绑定的案件类型与原数据不一致,则重新绑定 if(! question.getBelongsToFalltypus().equals(qInfo.getBelongsToFalltypus())) { questionService.updateQFMapping(question); } //更新问题的基本信息 questionService.update(question); } return Result.success("success"); } /** * 解除问题和案件类型的绑定关系 * * @param question * @return */ @PutMapping(value = "/update/question/qfMapping") @ResponseBody public ResponseMessage<String> updateQuestionFalltypusMapping(@RequestBody Question question) { Question qInfo = questionService.getByQuestionId(question.getId()); if(!ObjectUtils.isEmpty(qInfo)) { //如果当前选择的待绑定的案件类型与原数据不一致,则重新绑定, if(!qInfo.getBelongsToFalltypus().equals(question.getBelongsToFalltypus())) { questionService.updateQFMapping(question); } } return Result.success("success"); } /** * 更新问题信息 * * @param answer * @return */ @PutMapping(value = "/update/answer/basic") @ResponseBody public ResponseMessage<String> updateAnswerBasicInfo(@RequestBody Answer answer) { Answer answerInfo = answerService.getByAnswerId(answer.getId()); if(!ObjectUtils.isEmpty(answerInfo)) { //如果当前选择的待绑定的案件类型与原数据不一致,则重新绑定, if(!answer.getNextQuestionId().equals(answerInfo.getNextQuestionId())) { answerService.updateNextQuestion(answer); } //更新问题的基本信息 answer.getQuestion().setId(answerInfo.getQuestion().getId()); answer.setOther(answerInfo.getOther()); answerService.update(answer); } return Result.success("success"); } /** * 解除答案和案件类型的绑定关系 * * @param answer * @return */ @PutMapping(value = "/update/answer/qaMapping") @ResponseBody public ResponseMessage<String> updateAnswerFalltypusMapping(@RequestBody Answer answer) { Answer answerInfo = answerService.getByAnswerId(answer.getId()); if(!ObjectUtils.isEmpty(answerInfo)) { //如果当前选择的待绑定的案件类型与原数据不一致,则重新绑定, if(!answerInfo.getNextQuestionId().equals(answer.getNextQuestionId())) { answerService.updateNextQuestion(answer); } } return Result.success("success"); } }
gpl-3.0
WebArchivCZ/webanalyzer
src/org/apache/analyzer/config/PropertySaver.java
1116
/* * PropertySaver.java * * Created on October 9, 2007, 3:13 PM * * Trieda, ktoru nainicializuje objekt PropertyReader, pri starte programu * WebAnalyzer. Tento objekt bude jedinacik a bude poskytovat vlastnosti, ktore * potrebuju jednotlive moduly WebAnalyzatoru. * */ package org.apache.analyzer.config; /** * * @author praso */ public class PropertySaver { public static final PropertySaver INSTANCE = new PropertySaver(); private int crawlerPropertyMaxUrls; private int crawlerPropertyTimeout; /** * Creates a new instance of PropertySaver */ private PropertySaver() { } public int getCrawlerPropertyMaxUrls() { return crawlerPropertyMaxUrls; } public void setCrawlerPropertyMaxUrls(int crawlerPropertyMaxUrls) { this.crawlerPropertyMaxUrls = crawlerPropertyMaxUrls; } public int getCrawlerPropertyTimeout() { return crawlerPropertyTimeout; } public void setCrawlerPropertyTimeout(int crawlerPropertyTimeout) { this.crawlerPropertyTimeout = crawlerPropertyTimeout; } }
gpl-3.0
Deletescape-Media/Lawnchair
quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonNavbarToOverviewTouchController.java
10748
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher3.uioverrides.touchcontrollers; import static com.android.launcher3.LauncherState.HINT_STATE; import static com.android.launcher3.LauncherState.NORMAL; import static com.android.launcher3.LauncherState.OVERVIEW; import static com.android.launcher3.Utilities.EDGE_NAV_BAR; import static com.android.launcher3.anim.Interpolators.ACCEL_DEACCEL; import static com.android.launcher3.util.VibratorWrapper.OVERVIEW_HAPTIC; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.graphics.PointF; import android.util.Log; import android.view.MotionEvent; import com.android.launcher3.Launcher; import com.android.launcher3.LauncherState; import com.android.launcher3.Utilities; import com.android.launcher3.anim.AnimatorPlaybackController; import com.android.launcher3.graphics.OverviewScrim; import com.android.launcher3.statemanager.StateManager; import com.android.launcher3.states.StateAnimationConfig; import com.android.launcher3.testing.TestProtocol; import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch; import com.android.launcher3.util.VibratorWrapper; import com.android.quickstep.util.AnimatorControllerWithResistance; import com.android.quickstep.util.OverviewToHomeAnim; import com.android.quickstep.views.RecentsView; /** * Touch controller which handles swipe and hold from the nav bar to go to Overview. Swiping above * the nav bar falls back to go to All Apps. Swiping from the nav bar without holding goes to the * first home screen instead of to Overview. */ public class NoButtonNavbarToOverviewTouchController extends FlingAndHoldTouchController { // How much of the movement to use for translating overview after swipe and hold. private static final float OVERVIEW_MOVEMENT_FACTOR = 0.25f; private static final long TRANSLATION_ANIM_MIN_DURATION_MS = 80; private static final float TRANSLATION_ANIM_VELOCITY_DP_PER_MS = 0.8f; private final RecentsView mRecentsView; private boolean mDidTouchStartInNavBar; private boolean mReachedOverview; // The last recorded displacement before we reached overview. private PointF mStartDisplacement = new PointF(); private float mStartY; private AnimatorPlaybackController mOverviewResistYAnim; // Normal to Hint animation has flag SKIP_OVERVIEW, so we update this scrim with this animator. private ObjectAnimator mNormalToHintOverviewScrimAnimator; public NoButtonNavbarToOverviewTouchController(Launcher l) { super(l); mRecentsView = l.getOverviewPanel(); if (TestProtocol.sDebugTracing) { Log.d(TestProtocol.PAUSE_NOT_DETECTED, "NoButtonNavbarToOverviewTouchController.ctor"); } } @Override protected float getMotionPauseMaxDisplacement() { // No need to disallow pause when swiping up all the way up the screen (unlike // FlingAndHoldTouchController where user is probably intending to go to all apps). return Float.MAX_VALUE; } @Override protected boolean canInterceptTouch(MotionEvent ev) { mDidTouchStartInNavBar = (ev.getEdgeFlags() & EDGE_NAV_BAR) != 0; return super.canInterceptTouch(ev); } @Override protected LauncherState getTargetState(LauncherState fromState, boolean isDragTowardPositive) { if (fromState == NORMAL && mDidTouchStartInNavBar) { return HINT_STATE; } else if (fromState == OVERVIEW && isDragTowardPositive) { // Don't allow swiping up to all apps. return OVERVIEW; } return super.getTargetState(fromState, isDragTowardPositive); } @Override protected float initCurrentAnimation(int animComponents) { float progressMultiplier = super.initCurrentAnimation(animComponents); if (mToState == HINT_STATE) { // Track the drag across the entire height of the screen. progressMultiplier = -1 / getShiftRange(); } return progressMultiplier; } @Override public void onDragStart(boolean start, float startDisplacement) { super.onDragStart(start, startDisplacement); if (mFromState == NORMAL && mToState == HINT_STATE) { mNormalToHintOverviewScrimAnimator = ObjectAnimator.ofFloat( mLauncher.getDragLayer().getOverviewScrim(), OverviewScrim.SCRIM_PROGRESS, mFromState.getOverviewScrimAlpha(mLauncher), mToState.getOverviewScrimAlpha(mLauncher)); } mReachedOverview = false; mOverviewResistYAnim = null; } @Override protected void updateProgress(float fraction) { super.updateProgress(fraction); if (mNormalToHintOverviewScrimAnimator != null) { mNormalToHintOverviewScrimAnimator.setCurrentFraction(fraction); } } @Override public void onDragEnd(float velocity) { super.onDragEnd(velocity); mNormalToHintOverviewScrimAnimator = null; if (mLauncher.isInState(OVERVIEW)) { // Normally we would cleanup the state based on mCurrentAnimation, but since we stop // using that when we pause to go to Overview, we need to clean up ourselves. clearState(); } } @Override protected void updateSwipeCompleteAnimation(ValueAnimator animator, long expectedDuration, LauncherState targetState, float velocity, boolean isFling) { super.updateSwipeCompleteAnimation(animator, expectedDuration, targetState, velocity, isFling); if (targetState == HINT_STATE) { // Normally we compute the duration based on the velocity and distance to the given // state, but since the hint state tracks the entire screen without a clear endpoint, we // need to manually set the duration to a reasonable value. animator.setDuration(HINT_STATE.getTransitionDuration(mLauncher)); } } @Override protected void onMotionPauseChanged(boolean isPaused) { if (mCurrentAnimation == null) { return; } mNormalToHintOverviewScrimAnimator = null; mCurrentAnimation.dispatchOnCancelWithoutCancelRunnable(() -> { mLauncher.getStateManager().goToState(OVERVIEW, true, () -> { mOverviewResistYAnim = AnimatorControllerWithResistance .createRecentsResistanceFromOverviewAnim(mLauncher, null) .createPlaybackController(); mReachedOverview = true; maybeSwipeInteractionToOverviewComplete(); }); }); VibratorWrapper.INSTANCE.get(mLauncher).vibrate(OVERVIEW_HAPTIC); } private void maybeSwipeInteractionToOverviewComplete() { if (mReachedOverview && mDetector.isSettlingState()) { onSwipeInteractionCompleted(OVERVIEW, Touch.SWIPE); } } @Override protected boolean handlingOverviewAnim() { return mDidTouchStartInNavBar && super.handlingOverviewAnim(); } @Override public boolean onDrag(float yDisplacement, float xDisplacement, MotionEvent event) { if (TestProtocol.sDebugTracing) { Log.d(TestProtocol.PAUSE_NOT_DETECTED, "NoButtonNavbarToOverviewTouchController"); } if (mMotionPauseDetector.isPaused()) { if (!mReachedOverview) { mStartDisplacement.set(xDisplacement, yDisplacement); mStartY = event.getY(); } else { mRecentsView.setTranslationX((xDisplacement - mStartDisplacement.x) * OVERVIEW_MOVEMENT_FACTOR); float yProgress = (mStartDisplacement.y - yDisplacement) / mStartY; if (yProgress > 0 && mOverviewResistYAnim != null) { mOverviewResistYAnim.setPlayFraction(yProgress); } else { mRecentsView.setTranslationY((yDisplacement - mStartDisplacement.y) * OVERVIEW_MOVEMENT_FACTOR); } } // Stay in Overview. return true; } return super.onDrag(yDisplacement, xDisplacement, event); } @Override protected void goToOverviewOnDragEnd(float velocity) { float velocityDp = dpiFromPx(velocity); boolean isFling = Math.abs(velocityDp) > 1; StateManager<LauncherState> stateManager = mLauncher.getStateManager(); boolean goToHomeInsteadOfOverview = isFling; if (goToHomeInsteadOfOverview) { new OverviewToHomeAnim(mLauncher, ()-> onSwipeInteractionCompleted(NORMAL, Touch.FLING)) .animateWithVelocity(velocity); } if (mReachedOverview) { float distanceDp = dpiFromPx(Math.max( Math.abs(mRecentsView.getTranslationX()), Math.abs(mRecentsView.getTranslationY()))); long duration = (long) Math.max(TRANSLATION_ANIM_MIN_DURATION_MS, distanceDp / TRANSLATION_ANIM_VELOCITY_DP_PER_MS); mRecentsView.animate() .translationX(0) .translationY(0) .setInterpolator(ACCEL_DEACCEL) .setDuration(duration) .withEndAction(goToHomeInsteadOfOverview ? null : this::maybeSwipeInteractionToOverviewComplete); if (!goToHomeInsteadOfOverview) { // Return to normal properties for the overview state. StateAnimationConfig config = new StateAnimationConfig(); config.duration = duration; LauncherState state = mLauncher.getStateManager().getState(); mLauncher.getStateManager().createAtomicAnimation(state, state, config).start(); } } } private float dpiFromPx(float pixels) { return Utilities.dpiFromPx(pixels, mLauncher.getResources().getDisplayMetrics()); } }
gpl-3.0
IntellectualCrafters/PlotSquared
Core/src/main/java/com/plotsquared/core/queue/LightingMode.java
1929
/* * _____ _ _ _____ _ * | __ \| | | | / ____| | | * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| * | | * |_| * PlotSquared plot management system for Minecraft * Copyright (C) 2021 IntellectualSites * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.plotsquared.core.queue; import java.util.HashMap; import java.util.Map; public enum LightingMode { NONE(0), PLACEMENT(1), REPLACEMENT(2), ALL(3); private static final Map<Integer, LightingMode> map = new HashMap<>(); static { for (LightingMode mode : LightingMode.values()) { map.put(mode.mode, mode); } } private final int mode; LightingMode(int mode) { this.mode = mode; } public static LightingMode valueOf(int mode) { return map.get(mode); } public int getMode() { return mode; } }
gpl-3.0
opensciencemap/VectorTileMap
map-writer-osmosis/src/main/java/org/mapsforge/map/writer/model/TDNode.java
6372
/* * Copyright 2010, 2011, 2012 mapsforge.org * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mapsforge.map.writer.model; import java.util.Arrays; import org.mapsforge.core.model.Coordinates; import org.mapsforge.map.writer.OSMTagMapping; import org.mapsforge.map.writer.util.OSMUtils; import org.openstreetmap.osmosis.core.domain.v0_6.Node; /** * @author bross */ public class TDNode { // private static final Logger LOGGER = Logger.getLogger(TDNode.class.getName()); private static final byte ZOOM_HOUSENUMBER = (byte) 18; // private static final byte ZOOM_NAME = (byte) 16; private final long id; private final int latitude; private final int longitude; private final short elevation; // NOPMD by bross on 25.12.11 12:55 private final String houseNumber; private final byte layer; private final String name; private short[] tags; // NOPMD by bross on 25.12.11 12:55 /** * Constructs a new TDNode from a given osmosis node entity. Checks the validity of the entity. * * @param node * the osmosis entity * @param preferredLanguage * the preferred language or null if no preference * @return a new TDNode */ public static TDNode fromNode(Node node, String preferredLanguage) { SpecialTagExtractionResult ster = OSMUtils.extractSpecialFields(node, preferredLanguage); short[] knownWayTags = OSMUtils.extractKnownPOITags(node); // NOPMD by bross on 25.12.11 12:55 java.util.Arrays.sort(knownWayTags); return new TDNode(node.getId(), Coordinates.degreesToMicrodegrees(node.getLatitude()), Coordinates.degreesToMicrodegrees(node.getLongitude()), ster.getElevation(), ster.getLayer(), ster.getHousenumber(), ster.getName(), knownWayTags); } /** * @param id * the OSM id * @param latitude * the latitude * @param longitude * the longitude * @param elevation * the elevation if existent * @param layer * the layer if existent * @param houseNumber * the house number if existent * @param name * the name if existent */ public TDNode(long id, int latitude, int longitude, short elevation, byte layer, String houseNumber, // NOPMD // by // bross // on // 25.12.11 // 12:55 String name) { this.id = id; this.latitude = latitude; this.longitude = longitude; this.elevation = elevation; this.houseNumber = houseNumber; this.layer = layer; this.name = name; } /** * @param id * the OSM id * @param latitude * the latitude * @param longitude * the longitude * @param elevation * the elevation if existent * @param layer * the layer if existent * @param houseNumber * the house number if existent * @param name * the name if existent * @param tags * the */ public TDNode(long id, int latitude, int longitude, short elevation, byte layer, String houseNumber, // NOPMD // by // bross // on // 25.12.11 // 12:55 String name, short[] tags) { // NOPMD by bross on 25.12.11 12:58 this.id = id; this.latitude = latitude; this.longitude = longitude; this.elevation = elevation; this.houseNumber = houseNumber; this.layer = layer; this.name = name; this.tags = tags; } /** * @return true if the node represents a POI */ public boolean isPOI() { return this.houseNumber != null || this.elevation != 0 || this.tags.length > 0; } /** * @return the zoom level on which the node appears first */ public byte getZoomAppear() { if (this.tags == null || this.tags.length == 0) { if (this.houseNumber != null) { return ZOOM_HOUSENUMBER; } return Byte.MAX_VALUE; } return OSMTagMapping.getInstance().getZoomAppearPOI(this.tags); } /** * @return the id */ public long getId() { return this.id; } /** * @return the tags */ public short[] getTags() { // NOPMD by bross on 25.12.11 12:58 return this.tags; // NOPMD by bross on 25.12.11 12:56 } /** * @param tags * the tags to set */ public void setTags(short[] tags) { // NOPMD by bross on 25.12.11 12:58 this.tags = tags; } /** * @return the latitude */ public int getLatitude() { return this.latitude; } /** * @return the longitude */ public int getLongitude() { return this.longitude; } /** * @return the elevation */ public short getElevation() { // NOPMD by bross on 25.12.11 12:58 return this.elevation; } /** * @return the houseNumber */ public String getHouseNumber() { return this.houseNumber; } /** * @return the layer */ public byte getLayer() { return this.layer; } /** * @return the name */ public String getName() { return this.name; } @Override public int hashCode() { final int prime = 31; // NOPMD by bross on 25.12.11 12:56 int result = 1; result = prime * result + (int) (this.id ^ (this.id >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TDNode other = (TDNode) obj; if (this.id != other.id) { return false; } return true; } @Override public final String toString() { return "TDNode [id=" + this.id + ", latitude=" + this.latitude + ", longitude=" + this.longitude + ", name=" + this.name + ", tags=" + Arrays.toString(this.tags) + "]"; } }
gpl-3.0
Geforce132/SecurityCraft
src/main/java/net/geforcemods/securitycraft/items/AdminToolItem.java
6318
package net.geforcemods.securitycraft.items; import java.util.List; import net.geforcemods.securitycraft.ConfigHandler; import net.geforcemods.securitycraft.SCContent; import net.geforcemods.securitycraft.api.IModuleInventory; import net.geforcemods.securitycraft.api.IOwnable; import net.geforcemods.securitycraft.api.IPasswordProtected; import net.geforcemods.securitycraft.blockentities.SecretSignBlockEntity; import net.geforcemods.securitycraft.misc.ModuleType; import net.geforcemods.securitycraft.util.PlayerUtils; import net.geforcemods.securitycraft.util.Utils; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.FormattedText; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TextComponent; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; public class AdminToolItem extends Item { public AdminToolItem(Item.Properties properties) { super(properties); } @Override public InteractionResult onItemUseFirst(ItemStack stack, UseOnContext ctx) { Level level = ctx.getLevel(); BlockPos pos = ctx.getClickedPos(); Player player = ctx.getPlayer(); MutableComponent adminToolName = Utils.localize(getDescriptionId()); if (ConfigHandler.SERVER.allowAdminTool.get()) { if (!player.isCreative()) { PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.needCreative"), ChatFormatting.DARK_PURPLE); return InteractionResult.FAIL; } InteractionResult briefcaseResult = handleBriefcase(player, ctx.getHand()).getResult(); if (briefcaseResult != InteractionResult.PASS) return briefcaseResult; BlockEntity be = level.getBlockEntity(pos); if (be != null) { boolean hasInfo = false; if (be instanceof IOwnable ownable) { PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.owner.name", (ownable.getOwner().getName() == null ? "????" : ownable.getOwner().getName())), ChatFormatting.DARK_PURPLE); PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.owner.uuid", (ownable.getOwner().getUUID() == null ? "????" : ownable.getOwner().getUUID())), ChatFormatting.DARK_PURPLE); hasInfo = true; } if (be instanceof IPasswordProtected passwordProtected) { PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.password", (passwordProtected.getPassword() == null ? "????" : passwordProtected.getPassword())), ChatFormatting.DARK_PURPLE); hasInfo = true; } if (be instanceof IModuleInventory inv) { List<ModuleType> modules = inv.getInsertedModules(); if (!modules.isEmpty()) { PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.equippedModules"), ChatFormatting.DARK_PURPLE); for (ModuleType module : modules) { PlayerUtils.sendMessageToPlayer(player, adminToolName, new TextComponent("- ").append(new TranslatableComponent(module.getTranslationKey())), ChatFormatting.DARK_PURPLE); } hasInfo = true; } } if (be instanceof SecretSignBlockEntity signTe) { PlayerUtils.sendMessageToPlayer(player, adminToolName, new TextComponent(""), ChatFormatting.DARK_PURPLE); //EMPTY for (int i = 0; i < 4; i++) { FormattedText text = signTe.getMessage(i, false); if (text instanceof MutableComponent mutableComponent) PlayerUtils.sendMessageToPlayer(player, adminToolName, mutableComponent, ChatFormatting.DARK_PURPLE); } hasInfo = true; } if (!hasInfo) PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.noInfo"), ChatFormatting.DARK_PURPLE); return InteractionResult.SUCCESS; } PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.noInfo"), ChatFormatting.DARK_PURPLE); } else PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.disabled"), ChatFormatting.DARK_PURPLE); return InteractionResult.FAIL; } @Override public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) { if (!player.isCreative()) { PlayerUtils.sendMessageToPlayer(player, Utils.localize(getDescriptionId()), Utils.localize("messages.securitycraft:adminTool.needCreative"), ChatFormatting.DARK_PURPLE); return InteractionResultHolder.fail(player.getItemInHand(hand)); } else return handleBriefcase(player, hand); } private InteractionResultHolder<ItemStack> handleBriefcase(Player player, InteractionHand hand) { ItemStack adminTool = player.getItemInHand(hand); if (hand == InteractionHand.MAIN_HAND && player.getOffhandItem().getItem() == SCContent.BRIEFCASE.get()) { ItemStack briefcase = player.getOffhandItem(); MutableComponent adminToolName = Utils.localize(getDescriptionId()); String ownerName = BriefcaseItem.getOwnerName(briefcase); String ownerUUID = BriefcaseItem.getOwnerUUID(briefcase); PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.owner.name", ownerName.isEmpty() ? "????" : ownerName), ChatFormatting.DARK_PURPLE); PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.owner.uuid", ownerUUID.isEmpty() ? "????" : ownerUUID), ChatFormatting.DARK_PURPLE); PlayerUtils.sendMessageToPlayer(player, adminToolName, Utils.localize("messages.securitycraft:adminTool.password", briefcase.hasTag() ? briefcase.getTag().getString("passcode") : "????"), ChatFormatting.DARK_PURPLE); return InteractionResultHolder.success(adminTool); } return InteractionResultHolder.pass(adminTool); } }
gpl-3.0
cdorrat/geva-clj
geva-core/src/test/java/geva/Helpers/GrammarCreator.java
5084
/* Grammatical Evolution in Java Release: GEVA-v1.2.zip Copyright (C) 2008 Michael O'Neill, Erik Hemberg, Anthony Brabazon, Conor Gilligan Contributors Patrick Middleburgh, Eliott Bartley, Jonathan Hugosson, Jeff Wrigh Separate licences for asm, bsf, antlr, groovy, jscheme, commons-logging, jsci is included in the lib folder. Separate licence for rieps is included in src/com folder. This licence refers to GEVA-v1.2. This software is distributed under the terms of the GNU General Public License. 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 geva.Helpers; import geva.Individuals.*; import geva.Mapper.*; import java.io.*; import java.util.Properties; public class GrammarCreator { private GrammarCreator() { } final public static String getTestFile(String file_name) { return GrammarCreator.getGrammarFile(file_name); } public static String getGrammarFile(String file_name) { try { File f = new File(System.getProperty("user.dir") + File.separator + "src/test/resources"); if (f.exists()) { file_name = f.getAbsolutePath() + File.separator + file_name; } else { f = new File(System.getProperty("user.dir") + File.separator + "GEVA" + File.separator + "test"); if (f.exists()) { file_name = f.getAbsolutePath() + File.separator + file_name; } else { throw new FileNotFoundException(file_name); } } } catch (IOException e) { System.err.println(e); } return file_name; } public static String getGrammarFile() { return GrammarCreator.getGrammarFile("test_grammar.bnf"); } public static GEGrammar getGEGrammar(Properties properties_file) { GEGrammar geg = new GEGrammar(properties_file); return geg; } /** * Create size 10 with only 0 as codon value * @return gechromosome of size 10 with 0 as codon value */ public static GEChromosome getGEChromosome() { int[] ia = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; GEChromosome chrom = new GEChromosome(10, ia); chrom.setMaxChromosomeLength(10); chrom.setMaxCodonValue(Integer.MAX_VALUE); return chrom; } public static ContextualDerivationTree getContextualDerivationTree(GEGrammar geg, GEChromosome gec) { return new ContextualDerivationTree(geg, gec); } public static DerivationTree getDerivationTree(GEGrammar geg, GEChromosome gec) { return new DerivationTree(geg, gec); } /** * FIXME proper file search * @param properties_file * @return */ public static Properties getProperties(String properties_file) { Properties p = new Properties(); String file_name = ""; boolean found = false; try { File f; f = new File(properties_file); if(f.exists()) { found = true; p.load(new FileInputStream(f)); } else { f = new File(System.getProperty("user.dir") + File.separator + "test"); if (f.exists()) { file_name = f.getAbsolutePath() + File.separator + properties_file; f = new File(file_name); if (f.exists()) { p.load(new FileInputStream(f)); found = true; } } } if(!found) { f = new File(System.getProperty("user.dir") + File.separator + "GEVA" + File.separator + "test"); if (f.exists()) { file_name = f.getAbsolutePath() + File.separator + properties_file; f = new File(file_name); p.load(new FileInputStream(f)); String grammar_path = p.getProperty("grammar_file"); grammar_path = grammar_path.replaceFirst("..", "."); p.setProperty("grammar_file", grammar_path); } else { throw new FileNotFoundException(properties_file); } } } catch (IOException e) { System.err.println("Error loading properties:" + e); } return p; } public static Properties getProperties() { return GrammarCreator.getProperties("src/test/resources/test.properties"); } }
gpl-3.0
CyanogenMod/android_external_whispersystems_libwhisperpush
src/org/whispersystems/whisperpush/crypto/PreKeyUtil.java
7320
/** * Copyright (C) 2013 Open Whisper Systems * * 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.whispersystems.whisperpush.crypto; import android.content.Context; import android.util.Log; import com.fasterxml.jackson.annotation.JsonProperty; import org.whispersystems.libaxolotl.IdentityKeyPair; import org.whispersystems.libaxolotl.InvalidKeyException; import org.whispersystems.libaxolotl.InvalidKeyIdException; import org.whispersystems.libaxolotl.state.PreKeyRecord; import org.whispersystems.libaxolotl.state.PreKeyStore; import org.whispersystems.libaxolotl.state.SignedPreKeyRecord; import org.whispersystems.libaxolotl.state.SignedPreKeyStore; import org.whispersystems.libaxolotl.util.KeyHelper; import org.whispersystems.libaxolotl.util.Medium; import org.whispersystems.whisperpush.database.WPPreKeyStore; import org.whispersystems.whisperpush.util.JsonUtils; import org.whispersystems.whisperpush.util.Util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; public class PreKeyUtil { public static final int BATCH_SIZE = 100; public static List<PreKeyRecord> generatePreKeys(Context context, MasterSecret masterSecret) { PreKeyStore preKeyStore = new WPPreKeyStore(context, masterSecret); int startId = getNextPreKeyId(context); List<PreKeyRecord> records = KeyHelper.generatePreKeys(startId, BATCH_SIZE); int id = 0; for (PreKeyRecord key : records) { id = key.getId(); preKeyStore.storePreKey(id, key); } setNextPreKeyId(context, (id + 1) % Medium.MAX_VALUE); return records; } public static List<PreKeyRecord> getPreKeys(Context context, MasterSecret masterSecret) { WPPreKeyStore preKeyStore = new WPPreKeyStore(context, masterSecret); return preKeyStore.loadPreKeys(); } public static SignedPreKeyRecord generateSignedPreKey(Context context, MasterSecret masterSecret, IdentityKeyPair identityKeyPair) { try { SignedPreKeyStore signedPreKeyStore = new WPPreKeyStore(context, masterSecret); int signedPreKeyId = getNextSignedPreKeyId(context); SignedPreKeyRecord record = KeyHelper.generateSignedPreKey(identityKeyPair, signedPreKeyId); signedPreKeyStore.storeSignedPreKey(signedPreKeyId, record); setNextSignedPreKeyId(context, (signedPreKeyId + 1) % Medium.MAX_VALUE); return record; } catch (InvalidKeyException e) { throw new AssertionError(e); } } public static PreKeyRecord generateLastResortKey(Context context, MasterSecret masterSecret) { PreKeyStore preKeyStore = new WPPreKeyStore(context, masterSecret); if (preKeyStore.containsPreKey(Medium.MAX_VALUE)) { try { return preKeyStore.loadPreKey(Medium.MAX_VALUE); } catch (InvalidKeyIdException e) { Log.w("PreKeyUtil", e); preKeyStore.removePreKey(Medium.MAX_VALUE); } } PreKeyRecord record = KeyHelper.generateLastResortPreKey(); preKeyStore.storePreKey(Medium.MAX_VALUE, record); return record; } private static void setNextPreKeyId(Context context, int id) { try { File nextFile = new File(getPreKeysDirectory(context), PreKeyIndex.FILE_NAME); FileOutputStream fout = new FileOutputStream(nextFile); fout.write(JsonUtils.toJson(new PreKeyIndex(id)).getBytes()); fout.close(); } catch (IOException e) { Log.w("PreKeyUtil", e); } } private static void setNextSignedPreKeyId(Context context, int id) { try { File nextFile = new File(getSignedPreKeysDirectory(context), SignedPreKeyIndex.FILE_NAME); FileOutputStream fout = new FileOutputStream(nextFile); fout.write(JsonUtils.toJson(new SignedPreKeyIndex(id)).getBytes()); fout.close(); } catch (IOException e) { Log.w("PreKeyUtil", e); } } private static int getNextPreKeyId(Context context) { try { File nextFile = new File(getPreKeysDirectory(context), PreKeyIndex.FILE_NAME); if (!nextFile.exists()) { return Util.getSecureRandom().nextInt(Medium.MAX_VALUE); } else { InputStreamReader reader = new InputStreamReader(new FileInputStream(nextFile)); PreKeyIndex index = JsonUtils.fromJson(reader, PreKeyIndex.class); reader.close(); return index.nextPreKeyId; } } catch (IOException e) { Log.w("PreKeyUtil", e); return Util.getSecureRandom().nextInt(Medium.MAX_VALUE); } } private static int getNextSignedPreKeyId(Context context) { try { File nextFile = new File(getSignedPreKeysDirectory(context), SignedPreKeyIndex.FILE_NAME); if (!nextFile.exists()) { return Util.getSecureRandom().nextInt(Medium.MAX_VALUE); } else { InputStreamReader reader = new InputStreamReader(new FileInputStream(nextFile)); SignedPreKeyIndex index = JsonUtils.fromJson(reader, SignedPreKeyIndex.class); reader.close(); return index.nextSignedPreKeyId; } } catch (IOException e) { Log.w("PreKeyUtil", e); return Util.getSecureRandom().nextInt(Medium.MAX_VALUE); } } private static File getPreKeysDirectory(Context context) { return getKeysDirectory(context, WPPreKeyStore.PREKEY_DIRECTORY); } private static File getSignedPreKeysDirectory(Context context) { return getKeysDirectory(context, WPPreKeyStore.SIGNED_PREKEY_DIRECTORY); } private static File getKeysDirectory(Context context, String name) { File directory = new File(context.getFilesDir(), name); if (!directory.exists()) directory.mkdirs(); return directory; } public static final String INDEX_FILE = "index.dat"; public static FilenameFilter INDEX_FILTER = new FilenameFilter() { @Override public boolean accept(File dir, String filename) { return !INDEX_FILE.equals(filename); } }; private static class PreKeyIndex { public static final String FILE_NAME = INDEX_FILE; @JsonProperty private int nextPreKeyId; public PreKeyIndex() {} public PreKeyIndex(int nextPreKeyId) { this.nextPreKeyId = nextPreKeyId; } } private static class SignedPreKeyIndex { public static final String FILE_NAME = INDEX_FILE; @JsonProperty private int nextSignedPreKeyId; public SignedPreKeyIndex() {} public SignedPreKeyIndex(int nextSignedPreKeyId) { this.nextSignedPreKeyId = nextSignedPreKeyId; } } }
gpl-3.0
zeminlu/comitaco
tests/ase2016/introclass/median/introclass_95362737_003.java
1159
package ase2016.introclass.median; public class introclass_95362737_003 { public introclass_95362737_003() { } /*@ @ requires true; @ ensures ((\result == \old(a)) || (\result == \old(b)) || (\result == \old(c))); @ ensures ((\old(a)!=\old(b) || \old(a)!=\old(c)) ==> ( ((\old(a)==\old(b)) ==> (\result == \old(a))) && ((\old(b)==\old(c)) ==> (\result ==\old(b))))); @ ensures ((\old(a)!=\old(b) && \old(a)!=\old(c) && \old(b)!=\old(c)) ==> (\exists int n; (n == \old(a)) || (n == \old(b)) || (n == \old(c)); \result>n)); @ ensures ((\old(a)!=\old(b) && \old(a)!=\old(c) && \old(b)!=\old(c)) ==> (\exists int n; (n == \old(a)) || (n == \old(b)) || (n == \old(c)); \result<n)); @ signals (RuntimeException e) false; @ @*/ public int median( int a, int b, int c ) { if (a == b || a == c || (b < a && a < c) || (c < a && a < b)) { //mutGenLimit 1 return a; } else if (b == c || (a < b && b < c) || (c < b && b < a)) { //mutGenLimit 1 return b; } else if (a < c && c < b) { //mutGenLimit 1 return c; } return 0; //mutGenLimit 1 } }
gpl-3.0
sparkoneits420/JChat
src/org/jchat/event/Event.java
898
/** * Copyright (C) 10/13/15 smokey <sparkoneits420@live.com> * <p> * 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. * <p> * 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. * <p> * 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.jchat.event; /** * * @author smokey * @date 10/13/15 */ public abstract class Event { long interval, last; public abstract void execute(); }
gpl-3.0
MithunThadi/OFTE
SourceCode/new ofte with del monitor/com.ofte.services/FilesProcessorService.java
20407
package com.ofte.services; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.exception.ZkException; import org.I0Itec.zkclient.exception.ZkMarshallingError; import org.I0Itec.zkclient.serialize.ZkSerializer; import org.apache.kafka.clients.consumer.internals.NoAvailableBrokersException; import org.apache.log4j.Logger; import com.datastax.driver.core.Session; import com.datastax.driver.core.exceptions.NoHostAvailableException; import kafka.admin.AdminUtils; import kafka.admin.RackAwareMode; //import kafka.admin.RackAwareMode; import kafka.common.KafkaException; import kafka.common.KafkaStorageException; import kafka.consumer.ConsumerConfig; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import kafka.javaapi.consumer.ConsumerConnector; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import kafka.utils.ZKStringSerializer; import kafka.utils.ZkUtils; /** * * Class Functionality: The main functionality of this class is depending upon * the part size it is splitting the file into number of parts and publishing * data into kafkaserver and consuming the data and also parallelly updating the * database Methods: public void publish(String TOPIC, String Key, String * Message, Map<String, String> metadata,Map<String, String> transferMetaData) * public void consume(String TOPIC, Map<String, String> metadata, Session * session,Map<String, String> transferMetaData) public void getMessages(String * sourceFile, Map<String, String> metadata, Map<String, String> * transferMetaData) */ @SuppressWarnings("deprecation") public class FilesProcessorService { // Creating an object for LoadProperties class LoadProperties loadProperties = new LoadProperties(); // Creating Logger object for FilesProcessorService class Logger logger = Logger.getLogger(FilesProcessorService.class.getName()); // Creating an object for StringWriter class StringWriter log4jStringWriter = new StringWriter(); // Creation of ZkClient object and initialising it with loadProperties file // ZkClient zkClient = new // ZkClient(loadProperties.getKafkaProperties().getProperty("ZOOKEEPER.CONNECT"), // Integer.parseInt(loadProperties.getKafkaProperties().getProperty("SESSIONTIMEOUT")), // Integer.parseInt(loadProperties.getKafkaProperties().getProperty("CONNECTIONTIMEOUT")), // ZKStringSerializer$.MODULE$); // Declaration of parameter ConsumerConnector and initialising it to null ConsumerConnector consumerConnector = null; // Declaration of parameter publishCount and initialising it to zero public int publishCount = 0; // Declaration of parameter subscribeCount and initialising it to zero public int subscribeCount = 0; // Creating an object for CassandraInteracter class CassandraInteracter cassandraInteracter = new CassandraInteracter(); KafkaServerService kafkaServerService = new KafkaServerService(); /** * This method is used to publish the data * * @param TOPIC * @param Key * @param Message * @param metadata * @param transferMetaData */ // String brokerPort = kafkaServerService.getBrokerAddress(); // String zookeeperPort = kafkaServerService.getZKAddress(); // String groupId = kafkaServerService.getId(); public void publish(String TOPIC, String Key, String Message, ZkUtils zkutils, ZkClient zkClient, Map<String, String> metadata, Map<String, String> transferMetaData) { // // System.out.println(brokerPort+" in Fileprocessor"); // System.out.println(zookeeperPort+" in Fileprocessor"); // System.out.println(groupId+" in Fileprocessor"); try { System.out.println("setting zkclient"); System.out.println(AdminUtils.topicExists(zkutils, TOPIC)); if (zkClient != null) { System.out.println("ZKCLIENT"); } if (zkutils != null) { System.out.println("ZKUTILS"); } // Creation of ZkUtils object and initialising it with // loadProperties file // ZkUtils zkutils = new ZkUtils(zkClient, new // ZkConnection(loadProperties.getKafkaProperties().getProperty("ZOOKEEPER.CONNECT")), // true); // if loop to check the condition topicExists or not if (!AdminUtils.topicExists(zkutils, TOPIC)) { // Creating an object for KafkaConnectService class System.out.println("Entered into if loop"); zkClient.setZkSerializer(new ZkSerializer() { @Override public byte[] serialize(Object object) throws ZkMarshallingError { return ZKStringSerializer.serialize(object); } @Override public Object deserialize(byte[] bytes) throws ZkMarshallingError { return ZKStringSerializer.deserialize(bytes); } }); System.out.println("Running in the if loop"); // KafkaConnectService kafkaConnectService=new // KafkaConnectService(); // Creation of topic Properties topicConfiguration = new Properties(); AdminUtils.createTopic(zkutils, TOPIC, 1, 1, topicConfiguration, RackAwareMode.Enforced$.MODULE$); System.out.println("after creation of topic"); // kafkaConnectService.createTopic(TOPIC,zkClient,zkutils, // Integer.parseInt(loadProperties.getKafkaProperties().getProperty("NUMBEROFPARTITIONS")), // Integer.parseInt(loadProperties.getKafkaProperties().getProperty("NUMBEROFREPLICATIONS"))); } System.out.println("created success"); // Creation of Properties object // Properties properties = new Properties(); // properties.put("metadata.broker.list",transferMetaData.get("BROKER_PORT") // ); // properties.put("serializer.class", // loadProperties.getKafkaProperties().getProperty("SERIALIZER.CLASS")); // properties.put("reconnect.backoff.ms", // loadProperties.getKafkaProperties().getProperty("RECONNECT.BACKOFF.MS")); // properties.put("retry.backoff.ms", // loadProperties.getKafkaProperties().getProperty("RETRY.BACKOFF.MS")); // properties.put("producer.type", // loadProperties.getKafkaProperties().getProperty("PRODUCER.TYPE")); // properties.put("message.send.max.retries", // loadProperties.getKafkaProperties().getProperty("MESSAGE.SEND.MAX.RETRIES")); // properties.put("message.max.bytes", // loadProperties.getKafkaProperties().getProperty("MESSAGE.MAX.BYTES")); // Creation of ProducerConfig object // ProducerConfig producerConfig = new ProducerConfig(properties); ProducerConfig producerConfig = kafkaServerService .getProducerConfig(); // Creation of Producer object // System.out.println(Message); // ProducerConfig producerConfig= new ProducerConfig(properties); kafka.javaapi.producer.Producer<String, String> producer = new kafka.javaapi.producer.Producer<String, String>( producerConfig); // Creation of KeyedMessage object KeyedMessage<String, String> message = new KeyedMessage<String, String>( TOPIC, Key, Message); // Sending the messages to producer producer.send(message); // System.out.println(message); // Inserting publishCount to transferMetaData transferMetaData.put("incrementPublish", Integer.toString(publishCount++)); // Updating the database cassandraInteracter.updateTransferEventPublishDetails( cassandraInteracter.connectCassandra(), transferMetaData); // closing th producer producer.close(); System.out.println(TOPIC + " " + metadata + " " + transferMetaData); // Invoking the consume method consume(TOPIC, metadata, cassandraInteracter.connectCassandra(), transferMetaData); System.out.println("Consumed Successfully: " + TOPIC); //// Updating the database cassandraInteracter.updateTransferDetails( cassandraInteracter.connectCassandra(), transferMetaData, metadata); // Creating an object for KafkaSecondLayer class KafkaSecondLayer kafkaSecondLayer = new KafkaSecondLayer(); // publishing the monitor_transfer table data try { kafkaSecondLayer.publish( loadProperties.getOFTEProperties() .getProperty("TOPICNAME1"), transferMetaData.get("transferId"), cassandraInteracter.kafkaSecondCheckTransfer( cassandraInteracter.connectCassandra(), transferMetaData.get("transferId"))); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("updated cass: " + TOPIC); System.out.println("unlocking"); } // catching the exception for KafkaException catch (KafkaException kafkaException) { kafkaException.printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for KafkaException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } // catching the exception for KafkaStorageException catch (KafkaStorageException kafkaStorageException) { kafkaStorageException .printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for KafkaStorageException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } // catching the exception for ZkException catch (ZkException zkException) { zkException.printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for ZkException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } // catching the exception for NoHostAvailableException catch (NoHostAvailableException noHostAvailableException) { noHostAvailableException .printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for NoHostAvailableException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } // catching the exception for NoAvailableBrokersException catch (NoAvailableBrokersException noAvailableBrokersException) { noAvailableBrokersException .printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for NoAvailableBrokersException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } // catching the exception for Exception // catch (Exception e) { // e.printStackTrace(new PrintWriter(log4jStringWriter)); // //logging the exception for Exception // logger.error(loadProperties.getOFTEProperties().getProperty("LOGGEREXCEPTION") // + log4jStringWriter.toString()); // } } /** * This method is used to consume the data * * @param TOPIC * @param metadata * @param session * @param transferMetaData */ public void consume(String TOPIC, Map<String, String> metadata, Session session, Map<String, String> transferMetaData) { try { // Creation of Map object Map<String, Integer> topicCount = new HashMap<String, Integer>(); // Creation of Properties object // System.out.println(kafkaServerService.getId()); // Properties properties = new Properties(); // properties.put("zookeeper.connect", // transferMetaData.get("zkport") ); // properties.put("group.id", transferMetaData.get("id") ); // properties.put("enable.auto.commit",loadProperties.getKafkaProperties().getProperty("ENABLE.AUTO.COMMIT")); // properties.put("auto.commit.interval.ms", // loadProperties.getKafkaProperties().getProperty("AUTO.COMMIT.INTERVAL.MS")); // properties.put("auto.offset.reset", // loadProperties.getKafkaProperties().getProperty("AUTO.OFFSET.RESET")); // properties.put("session.timeout.ms", // loadProperties.getKafkaProperties().getProperty("SESSION.TIMEOUT.MS")); // properties.put("key.deserializer", // loadProperties.getKafkaProperties().getProperty("KEY.DESERIALIZER")); // properties.put("value.deserializer", // loadProperties.getKafkaProperties().getProperty("VALUE.DESERIALIZER")); // properties.put("fetch.message.max.bytes", // loadProperties.getKafkaProperties().getProperty("FETCH.MESSAGE.MAX.BYTES")); // System.out.println(kafkaServerService.getZKAddress()); // System.out.println(properties); // //Creation of ConsumerConfig object // ConsumerConfig conConfig = new ConsumerConfig(properties); // Creating the consumerConnector ConsumerConfig conConfig = kafkaServerService.getConsumerConfig(); consumerConnector = kafka.consumer.Consumer .createJavaConsumerConnector(conConfig); // Inserting the values to topicCount topicCount.put(TOPIC, new Integer(1)); // Creation of Map object for consumerStreams Map<String, List<KafkaStream<byte[], byte[]>>> consumerStreams = consumerConnector .createMessageStreams(topicCount); // Creation of List for kafkaStreamList List<KafkaStream<byte[], byte[]>> kafkaStreamList = consumerStreams .get(TOPIC); // for each loop to iterate kafkaStreamList for (final KafkaStream<byte[], byte[]> kafkaStreams : kafkaStreamList) { // Getting the kafka streams ConsumerIterator<byte[], byte[]> consumerIterator = kafkaStreams .iterator(); // Inserting destinationDirectory to transferMetaData transferMetaData.put("destinationFile", metadata.get("destinationDirectory") + "\\" + TOPIC); // Declaration of parameter FileWriter FileWriter destinationFileWriter; // while loop to iterate consumerIterator while (consumerIterator.hasNext()) { try { // Creating an object for FileWriter class destinationFileWriter = new FileWriter( new File(metadata.get("destinationDirectory") + "\\" + TOPIC), true); // Writing the kafka messages to destination file destinationFileWriter.write( new String(consumerIterator.next().message())); // closing the destinationFileWriter destinationFileWriter.close(); // Inserting subscribeCount to transferMetaData transferMetaData.put("incrementConsumer", Integer.toString(subscribeCount++)); // Updating the database cassandraInteracter.updateTransferEventConsumeDetails( session, transferMetaData); // shutdown the consumerConnector consumerConnector.shutdown(); System.out.println("done for : " + TOPIC); break; } // catching the exception for Exception catch (Exception e) { System.out.println(e); } } System.out.println("exited"); } System.out.println("Cdone for : " + TOPIC); // if loop to check the condition consumerConnector not equals to // null if (consumerConnector != null) consumerConnector.shutdown(); } // catching the exception for KafkaException catch (KafkaException kafkaException) { kafkaException.printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for KafkaException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } // catching the exception for KafkaStorageException catch (KafkaStorageException kafkaStorageException) { kafkaStorageException .printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for KafkaStorageException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } // catching the exception for ZkException catch (ZkException zkException) { zkException.printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for ZkException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } // catching the exception for NoHostAvailableException catch (NoHostAvailableException noHostAvailableException) { noHostAvailableException .printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for NoHostAvailableException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } } /** * This method is used to split the files * * @param zkUtils * @param zkClient * @param sourceFile * @param metadata * @param transferMetaData */ public void getMessages(ZkClient zkClient, ZkUtils zkUtils, String sourceFile, Map<String, String> metadata, Map<String, String> transferMetaData) { // Declaration of parameter delimiter String delimiter = "\\\\"; // Creating an object for File class File inputFile = new File(sourceFile); // Declaration of parameter FileInputStream FileInputStream inputStream; // Declaration of parameter Key String Key; // Declaration of parameter sourceFileName and initialising it to null String sourceFileName = null; // Declaration of parameter sourceFileArray[] and splitting // sourceFileDirectory using on delimiter String sourceFileArray[] = sourceFile.split(delimiter); // Declaration of parameter sourceFileArraySize and initialising it to // sourceFileArray.length int sourceFileArraySize = sourceFileArray.length; sourceFileName = sourceFileArray[sourceFileArraySize - 1]; // Declaration of parameter sourceFileSize initialising it to // inputFile.length long sourceFileSize = inputFile.length(); System.out.println("filesize is" + sourceFileSize); // Declaration of parameter nChunks // Declaration of parameter read // Declaration of parameter readLength int nChunks = 0, read = 0; Long readLength = Long.parseLong( loadProperties.getOFTEProperties().getProperty("PART_SIZE")); // Declaration of parameter byteChunkPart byte[] byteChunkPart; try { // Creating an object for FileInputStream class inputStream = new FileInputStream(inputFile); // while loop to check the sourceFileSize> 0 while (sourceFileSize > 0) { // if loop to check the inputStream.available() < readLength if (inputStream.available() < readLength) { System.out .println(inputStream.available() + " in if block"); // Initialising the byte chunk part with inputStream byteChunkPart = new byte[inputStream.available()]; // Initialising the read with inputStream bytes read = inputStream.read(byteChunkPart, 0, inputStream.available()); } else { System.out.println( inputStream.available() + " in else block"); // byteChunkPart = new byte[readLength]; // byteChunkPart = Longs.toByteArray(readLength); byteChunkPart = new byte[readLength.intValue()]; read = inputStream.read(byteChunkPart, 0, readLength.intValue()); } // Deducting the sourceFileSize with read size sourceFileSize -= read; // Incrementing nChunks nChunks++; // Initialising key value Key = sourceFileName + "." + (nChunks - 1); System.out.println(sourceFileName); // Publishing the data publish(sourceFileName, Key, new String(byteChunkPart), zkUtils, zkClient, metadata, transferMetaData); System.out.println("completed for thread: " + sourceFileName); } // closing inputStream inputStream.close(); System.out.println("closing Stream for " + inputFile); // Initialising publishCount and subscribeCount with zero publishCount = 0; subscribeCount = 0; // Creating an object for Acknowledgement class // Acknowledgement acknowledgement=new Acknowledgement(); // acknowledgement.acknowledge(transferMetaData, metadata); } // catching the exception for FileNotFoundException catch (FileNotFoundException fileNotFoundException) { fileNotFoundException .printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for FileNotFoundException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } // catching the exception for IOException catch (IOException exception) { exception.printStackTrace(new PrintWriter(log4jStringWriter)); // logging the exception for IOException logger.error(loadProperties.getOFTEProperties().getProperty( "LOGGEREXCEPTION") + log4jStringWriter.toString()); } } }
gpl-3.0
avdata99/SIAT
siat-1.0-SOURCE/src/buss/src/ar/gov/rosario/siat/def/buss/dao/ColEmiMatDAO.java
1097
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda. //This file is part of SIAT. SIAT is licensed under the terms //of the GNU General Public License, version 3. //See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt> package ar.gov.rosario.siat.def.buss.dao; import org.hibernate.Query; import org.hibernate.classic.Session; import ar.gov.rosario.siat.base.buss.dao.GenericDAO; import ar.gov.rosario.siat.base.buss.dao.SiatHibernateUtil; import ar.gov.rosario.siat.def.buss.bean.ColEmiMat; public class ColEmiMatDAO extends GenericDAO { public ColEmiMatDAO() { super(ColEmiMat.class); } /** * Obtiene una columna de una matriz de emision * por su codigo */ public ColEmiMat getByCodigo(String codColumna) throws Exception { ColEmiMat colEmiMat; String queryString = "from ColEmiMat t where t.codColumna = :codigo"; Session session = SiatHibernateUtil.currentSession(); Query query = session.createQuery(queryString).setString("codigo", codColumna); colEmiMat = (ColEmiMat) query.uniqueResult(); return colEmiMat; } }
gpl-3.0
Hadron67/jphp
src/com/hadroncfy/jphp/jzend/VM.java
571
package com.hadroncfy.jphp.jzend; import com.hadroncfy.jphp.jzend.types.typeInterfaces.Zval; /** * Created by cfy on 16-9-1. */ public interface VM { void push(Zval val); Zval pop(); Zval peek(); void echo(String s); void exit(Zval ret); void retour(Zval zval); void doThrow(Zval zval); void makeError(String msg); void jump(int line); void doBreak(int index); void doContinue(int index); Context getEnv(); void beginSilence(); void endSilence(); Zval load(int index); void store(Zval val,int index); }
gpl-3.0
Joapple/Slimefun4
src/me/mrCookieSlime/Slimefun/Objects/SlimefunItem/machines/AutoEnchanter.java
5591
package me.mrCookieSlime.Slimefun.Objects.SlimefunItem.machines; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.InvUtils; import me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.Item.CustomItem; import me.mrCookieSlime.EmeraldEnchants.EmeraldEnchants; import me.mrCookieSlime.EmeraldEnchants.ItemEnchantment; import me.mrCookieSlime.Slimefun.Lists.RecipeType; import me.mrCookieSlime.Slimefun.Objects.Category; import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.AContainer; import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.MachineHelper; import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.MachineRecipe; import me.mrCookieSlime.Slimefun.api.BlockStorage; import me.mrCookieSlime.Slimefun.api.Slimefun; import me.mrCookieSlime.Slimefun.api.energy.ChargableBlock; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.MaterialData; public class AutoEnchanter extends AContainer { public static int max_emerald_enchantments = 2; public AutoEnchanter(Category category, ItemStack item, String name, RecipeType recipeType, ItemStack[] recipe) { super(category, item, name, recipeType, recipe); } @Override public String getInventoryTitle() { return "&5Auto-Enchanter"; } @Override public ItemStack getProgressBar() { return new ItemStack(Material.GOLD_CHESTPLATE); } @Override public void registerDefaultRecipes() {} @Override public int getEnergyConsumption() { return 9; } @SuppressWarnings("deprecation") @Override protected void tick(Block b) { if (isProcessing(b)) { int timeleft = progress.get(b); if (timeleft > 0) { ItemStack item = getProgressBar().clone(); item.setDurability(MachineHelper.getDurability(item, timeleft, processing.get(b).getTicks())); ItemMeta im = item.getItemMeta(); im.setDisplayName(" "); List<String> lore = new ArrayList<String>(); lore.add(MachineHelper.getProgress(timeleft, processing.get(b).getTicks())); lore.add(""); lore.add(MachineHelper.getTimeLeft(timeleft / 2)); im.setLore(lore); item.setItemMeta(im); BlockStorage.getInventory(b).replaceExistingItem(22, item); if (ChargableBlock.isChargable(b)) { if (ChargableBlock.getCharge(b) < getEnergyConsumption()) return; ChargableBlock.addCharge(b, -getEnergyConsumption()); progress.put(b, timeleft - 1); } else progress.put(b, timeleft - 1); } else { BlockStorage.getInventory(b).replaceExistingItem(22, new CustomItem(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 15), " ")); pushItems(b, processing.get(b).getOutput()); progress.remove(b); processing.remove(b); } } else { MachineRecipe r = null; slots: for (int slot: getInputSlots()) { ItemStack target = BlockStorage.getInventory(b).getItemInSlot(slot == getInputSlots()[0] ? getInputSlots()[1]: getInputSlots()[0]); ItemStack item = BlockStorage.getInventory(b).getItemInSlot(slot); if (item != null && item.getType() == Material.ENCHANTED_BOOK && target != null) { Map<Enchantment, Integer> enchantments = new HashMap<Enchantment, Integer>(); Set<ItemEnchantment> enchantments2 = new HashSet<ItemEnchantment>(); int amount = 0; int special_amount = 0; EnchantmentStorageMeta meta = (EnchantmentStorageMeta) item.getItemMeta(); for (Map.Entry<Enchantment, Integer> e: meta.getStoredEnchants().entrySet()) { if (e.getKey().canEnchantItem(target)) { amount++; enchantments.put(e.getKey(), e.getValue()); } } if (Slimefun.isEmeraldEnchantsInstalled()) { for (ItemEnchantment enchantment: EmeraldEnchants.getInstance().getRegistry().getEnchantments(item)) { if (EmeraldEnchants.getInstance().getRegistry().isApplicable(target, enchantment.getEnchantment()) && EmeraldEnchants.getInstance().getRegistry().getEnchantmentLevel(target, enchantment.getEnchantment().getName()) < enchantment.getLevel()) { amount++; special_amount++; enchantments2.add(enchantment); } } special_amount+=EmeraldEnchants.getInstance().getRegistry().getEnchantments(target).size(); } if (amount > 0 && special_amount <= max_emerald_enchantments) { ItemStack newItem = target.clone(); for (Map.Entry<Enchantment, Integer> e: enchantments.entrySet()) { newItem.addUnsafeEnchantment(e.getKey(), e.getValue()); } for (ItemEnchantment e: enchantments2) { EmeraldEnchants.getInstance().getRegistry().applyEnchantment(newItem, e.getEnchantment(), e.getLevel()); } r = new MachineRecipe(75 * amount, new ItemStack[] {target, item}, new ItemStack[] {newItem, new ItemStack(Material.BOOK)}); } break slots; } } if (r != null) { if (!fits(b, r.getOutput())) return; for (int slot: getInputSlots()) { BlockStorage.getInventory(b).replaceExistingItem(slot, InvUtils.decreaseItem(BlockStorage.getInventory(b).getItemInSlot(slot), 1)); } processing.put(b, r); progress.put(b, r.getTicks()); } } } @Override public int getSpeed() { return 1; } @Override public String getMachineIdentifier() { return "AUTO_ENCHANTER"; } }
gpl-3.0
gg-net/dwoss
ui/receipt/src/test/java/eu/ggnet/dwoss/receipt/ui/tryout/fx/CdiFxSaft.java
1487
/* * Copyright (C) 2020 GG-Net GmbH * * 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 eu.ggnet.dwoss.receipt.ui.tryout.fx; import java.util.concurrent.Executors; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Instance; import javax.inject.Inject; import eu.ggnet.saft.core.Saft; import eu.ggnet.saft.core.impl.Fx; import eu.ggnet.saft.core.ui.LocationStorage; /** * CDI Saft with FX. * * @author mirko.schulze */ @ApplicationScoped // @Specializes public class CdiFxSaft extends Saft { @Inject private Instance<Object> instance; public CdiFxSaft() { super(new LocationStorage(), Executors.newCachedThreadPool()); } @PostConstruct private void postInit() { init(new Fx(this, p -> instance.select(p).get())); core().captureMode(true); } }
gpl-3.0
Precision-Smelter/TFC2
src/Common/com/bioxx/tfc2/handlers/CreateDungeonHandler.java
8748
package com.bioxx.tfc2.handlers; import java.util.*; import net.minecraft.init.Blocks; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import com.bioxx.jmapgen.IslandMap; import com.bioxx.jmapgen.Point; import com.bioxx.jmapgen.attributes.Attribute; import com.bioxx.jmapgen.dungeon.*; import com.bioxx.jmapgen.dungeon.RoomSchematic.RoomType; import com.bioxx.jmapgen.graph.Center; import com.bioxx.tfc2.Core; import com.bioxx.tfc2.TFC; import com.bioxx.tfc2.TFCBlocks; import com.bioxx.tfc2.api.events.IslandGenEvent; import com.bioxx.tfc2.api.types.WoodType; import com.bioxx.tfc2.blocks.BlockStoneBrick; import com.bioxx.tfc2.blocks.BlockStoneSmooth; public class CreateDungeonHandler { private boolean[] tempMap; @SubscribeEvent public void createDungeon(IslandGenEvent.Post event) { if(FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) return; DungeonSchemManager dsm = DungeonSchemManager.getInstance(); Random random = event.islandMap.mapRandom; Vector<Center> dungeonCenters = event.islandMap.getLandCenters(); dungeonCenters = this.removeRiverCenters(dungeonCenters); dungeonCenters = event.islandMap.getCentersAbove(dungeonCenters, 0.3); dungeonCenters = event.islandMap.getCentersBelow(dungeonCenters, 0.6, false); if(dungeonCenters.size() == 0) return; //Find a suitable location for the entrance Center start = null; int counter = 0; while(start == null) { start = dungeonCenters.get(random.nextInt(dungeonCenters.size())); //pick a relatively flat area. if(counter > 2500 || Math.abs(start.getAverageElevation() - start.getElevation()) <= 0.08) { break; } start = null; counter++; } //We want our dungeon to have its entrance in this chunk. int xStartChunk = ((int)(start.point.x) >> 4); int zStartChunk = ((int)(start.point.y) >> 4); //Elevation of the center int startElev = event.islandMap.convertHeightToMC(start.getElevation())+64; //this is the Y level where the dungeon will start int elev = startElev-30; DungeonTheme dungeonTheme = dsm.getRandomTheme(random); Dungeon dungeon = new Dungeon(dungeonTheme.getThemeName(), xStartChunk, elev, zStartChunk); dungeon.blockMap.put("dungeon_wall", TFCBlocks.StoneBrick.getDefaultState().withProperty(BlockStoneBrick.META_PROPERTY, event.islandMap.getParams().getSurfaceRock())); dungeon.blockMap.put("dungeon_floor", Core.getPlanks(WoodType.getTypeFromString(event.islandMap.getParams().getCommonTree()))); dungeon.blockMap.put("dungeon_ceiling", TFCBlocks.StoneBrick.getDefaultState().withProperty(BlockStoneBrick.META_PROPERTY, event.islandMap.getParams().getSurfaceRock())); dungeon.blockMap.put("dungeon_smoothstone", TFCBlocks.StoneSmooth.getDefaultState().withProperty(BlockStoneSmooth.META_PROPERTY, event.islandMap.getParams().getSurfaceRock())); dungeon.blockMap.put("dungeon_stairs_floor", TFCBlocks.StairsOak.getDefaultState()); dungeon.blockMap.put("dungeon_stairs_wall", TFCBlocks.StairsOak.getDefaultState()); dungeon.blockMap.put("dungeon_door", Blocks.OAK_DOOR.getDefaultState()); while(true) { genDungeon(event.islandMap, dungeonTheme, random, xStartChunk, zStartChunk, dungeon); if(dungeon.getRoomCount() > 30) break; dungeon.resetDungeonMap(); } TFC.log.info("Dungeon: " + start.point.toString() + " | Size : " + dungeon.getRoomCount()); event.islandMap.dungeons.add(dungeon); } private void genDungeon(IslandMap map, DungeonTheme dungeonTheme, Random random, int xStartChunk, int zStartChunk, Dungeon dungeon) { DungeonRoom dungeonEntrance = new DungeonRoom(dungeonTheme.getRandomEntrance(random), dungeon.dungeonStart); dungeon.setRoom(xStartChunk, 0, zStartChunk, dungeonEntrance); LinkedList<DungeonRoom> queue = new LinkedList<DungeonRoom>(); queue.add(dungeonEntrance); while(queue.peek() != null) { DungeonRoom room = queue.poll(); if(room == null || room.getSchematic() == null) continue; boolean isRoomValid = true; boolean addedRoom = false; for(DungeonDirection dir : room.getSchematic().getConnections()) { RoomPos pos = room.getPosition().offset(dir); //Have we already established a connection in this direction? if(isRoomValid && !room.hasConnection(dir)) { DungeonRoom neighbor = dungeon.getRoom(room.getPosition().offset(dir)); /** * Create a new random room in this direction */ if(neighbor == null && checkElevation(map, dungeon, room.getPosition().offset(dir))) { RoomSchematic schem = null; double dist = room.getPosition().offset(dir).distanceSq(dungeon.dungeonStart); if(dist > 256) schem = dungeonTheme.getRandomRoomSingleDirection(random, dir.getOpposite()); else if(random.nextDouble() < 0.25 && room.getPosition().getY() > 16) schem = dungeonTheme.getRandomRoomForDirection(random, dir.getOpposite(), RoomType.Stairs); else schem = dungeonTheme.getRandomRoomForDirection(random, dir.getOpposite()); if(schem == null) continue; neighbor = new DungeonRoom(schem, room.getPosition().offset(dir)); linkRooms(room, neighbor, dir); addedRoom = true; if(!neighbor.getSchematic().getSetPieceMap().isEmpty()) { if(checkSetPiece(map, dungeon, neighbor.getPosition(), neighbor.getSchematic().getSetPieceMap())) { Iterator<RoomPos> iter = neighbor.getSchematic().getSetPieceMap().keySet().iterator(); while(iter.hasNext()) { RoomPos setPos = iter.next(); String s = neighbor.getSchematic().getSetPieceMap().get(setPos); setPos = pos.add(setPos); DungeonRoom setpieceRoom = new DungeonRoom(dungeonTheme.getSchematic(s), setPos); dungeon.setRoom(setPos, setpieceRoom); queue.add(setpieceRoom); } } else { neighbor.clearConnections(dungeon); neighbor = null; } } } else if(neighbor != null)//A room already exists in this neighbor location { //If the neighbor can connect to this room then link them if(neighbor.getSchematic().getConnections().contains(dir.getOpposite())) { linkRooms(room, neighbor, dir); } } if(neighbor != null && addedRoom) { queue.add(neighbor); dungeon.setRoom(neighbor); } } if(!isRoomValid) break; } if(!isRoomValid) { room.clearConnections(dungeon); requeueNeighbors(queue, dungeon, room); dungeon.setRoom(room.getPosition(), null); } } } boolean checkElevation(IslandMap map, Dungeon dungeon, RoomPos pos) { Center closest = map.getClosestCenter(new Point((pos.getX() << 4)+8, (pos.getZ() << 4)+8)); if(pos.getY()+14 > map.convertHeightToMC(closest.getElevation())+64)//we do 14 instead of 10 to make sure that the schematic is a bit deeper underground return false; if(pos.getY() > dungeon.dungeonStart.getY()) return false; return true; } boolean checkSetPiece(IslandMap islandMap, Dungeon dungeon, RoomPos startPos, Map<RoomPos, String> map) { Iterator<RoomPos> iter = map.keySet().iterator(); while(iter.hasNext()) { RoomPos pos = iter.next(); RoomPos pos2 = startPos.add(pos); if(dungeon.getRoom(pos2) != null) return false; if(!checkElevation(islandMap, dungeon, pos2)) return false; } return true; } void requeueNeighbors(LinkedList<DungeonRoom> queue, Dungeon dungeon, DungeonRoom room) { DungeonRoom other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.NORTH)); if(other != null) queue.add(other); other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.SOUTH)); if(other != null) queue.add(other); other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.EAST)); if(other != null) queue.add(other); other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.WEST)); if(other != null) queue.add(other); other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.UP)); if(other != null) queue.add(other); other = dungeon.getRoom(room.getPosition().offset(DungeonDirection.DOWN)); if(other != null) queue.add(other); } void linkRooms(DungeonRoom room1, DungeonRoom room2, DungeonDirection room1_dir) { room1.addConnection(room1_dir, new RoomLink(true)); room2.addConnection(room1_dir.getOpposite(), new RoomLink(false)); } public Vector<Center> removeRiverCenters(Vector<Center> list) { Vector<Center> out = new Vector<Center>(); for(Center c : list) { if(!c.hasAttribute(Attribute.River)) out.add(c); } return out; } }
gpl-3.0
drtshock/Essentials
Essentials/src/main/java/net/ess3/api/events/SignInteractEvent.java
779
package net.ess3.api.events; import com.earth2me.essentials.signs.EssentialsSign; import net.ess3.api.IUser; import org.bukkit.event.HandlerList; /** * Fired when an Essentials sign is interacted with. * * This is primarily intended for use with EssentialsX's sign abstraction - external plugins should not listen on this event. */ public class SignInteractEvent extends SignEvent { private static final HandlerList handlers = new HandlerList(); public SignInteractEvent(final EssentialsSign.ISign sign, final EssentialsSign essSign, final IUser user) { super(sign, essSign, user); } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
gpl-3.0
OurGrid/commune
src/main/test/br/edu/ufcg/lsd/commune/functionaltests/data/remoteparameters/MyInterface6.java
991
/* * Copyright (C) 2008 Universidade Federal de Campina Grande * * This file is part of Commune. * * Commune is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package br.edu.ufcg.lsd.commune.functionaltests.data.remoteparameters; import br.edu.ufcg.lsd.commune.api.Remote; @Remote public interface MyInterface6 { void myMethod6(MyRemoteParameter2 parameter); }
gpl-3.0
hantsy/spring-reactive-sample
boot-data-mongo/src/test/java/com/example/demo/IntegrationTests.java
1082
package com.example.demo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.web.reactive.server.WebTestClient; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ImportAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class) public class IntegrationTests { @LocalServerPort int port; WebTestClient client; // @Autowired // WebTestClient client; @BeforeEach public void setup() { this.client = WebTestClient.bindToServer() .baseUrl("http://localhost:" + this.port) .build(); } @Test public void getAllMessagesShouldBeOk() { client.get().uri("/posts").exchange() .expectStatus().isOk(); } }
gpl-3.0
evelyne24/Affected
affected-core/src/main/java/org/codeandmagic/affected/svn/SvnFileContentRetriever.java
700
package org.codeandmagic.affected.svn; // @affects: SvnProjectProcessor /** Retrieves the content of a file from the svn. */ public interface SvnFileContentRetriever { /** * @param project * the svn project object * @param filePath * the path to the file whose content we want * @param targetRevision * the revision of the file * * @return a string representing the entire content of the file * * @throws SvnException * if an exception occurred while checking out or reading the * content of the file */ String getFileContent(SvnProject project, String filePath, long targetRevision) throws SvnException; }
gpl-3.0
librecoop/GOOL
src/gool/ast/system/SystemCommandCall.java
1272
/* * Copyright 2010 Pablo Arrighi, Alex Concha, Miguel Lezama for version 1. * Copyright 2013 Pablo Arrighi, Miguel Lezama, Kevin Mazet for version 2. * * This file is part of GOOL. * * GOOL is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, version 3. * * GOOL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License version 3 for more details. * * You should have received a copy of the GNU General Public License along with GOOL, * in the file COPYING.txt. If not, see <http://www.gnu.org/licenses/>. */ package gool.ast.system; import gool.ast.core.GoolCall; import gool.ast.type.TypeVoid; import gool.generator.GoolGeneratorController; /** * This class captures the invocation of a system method. */ public class SystemCommandCall extends GoolCall { /** * The constructor of a "system call" representation. */ public SystemCommandCall() { super(TypeVoid.INSTANCE); } @Override public String callGetCode() { return GoolGeneratorController.generator().getCode(this); } }
gpl-3.0
apicloudcom/APICloud-Studio
org.tigris.subversion.subclipse.ui/src/org/tigris/subversion/subclipse/ui/authentication/UserPromptDialog.java
3794
/******************************************************************************* * Copyright (c) 2006 Subclipse project 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 * * Contributors: * Subclipse project committers - initial API and implementation ******************************************************************************/ package org.tigris.subversion.subclipse.ui.authentication; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.tigris.subversion.subclipse.ui.IHelpContextIds; import org.tigris.subversion.subclipse.ui.Policy; import org.tigris.subversion.subclipse.ui.dialogs.SubclipseTrayDialog; public class UserPromptDialog extends SubclipseTrayDialog { private String realm; private String username; private boolean save; private boolean maySave; private Text userText; private Button saveButton; private Button okButton; private static int WIDTH = 300; public UserPromptDialog(Shell parentShell, String realm, String username, boolean maySave) { super(parentShell); this.realm = realm; this.username = username; this.maySave = maySave; } protected Control createDialogArea(Composite parent) { Composite rtnGroup = (Composite)super.createDialogArea(parent); getShell().setText(Policy.bind("UserPromptDialog.title")); //$NON-NLS-1$ GridLayout layout = new GridLayout(); layout.numColumns = 2; rtnGroup.setLayout(layout); rtnGroup.setLayoutData( new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); Label realmLabel = new Label(rtnGroup, SWT.NONE); realmLabel.setText(Policy.bind("PasswordPromptDialog.repository")); //$NON-NLS-1$ Text realmText = new Text(rtnGroup, SWT.BORDER); GridData gd = new GridData(); gd.widthHint = WIDTH; realmText.setLayoutData(gd); realmText.setEditable(false); realmText.setText(realm); Label userLabel = new Label(rtnGroup, SWT.NONE); userLabel.setText(Policy.bind("UserPromptDialog.username")); //$NON-NLS-1$ userText = new Text(rtnGroup, SWT.BORDER); gd = new GridData(); gd.widthHint = WIDTH; userText.setLayoutData(gd); userText.setText(username == null? "": username); userText.selectAll(); if (maySave) { saveButton = new Button(rtnGroup, SWT.CHECK); saveButton.setText(Policy.bind("UserPromptDialog.save")); //$NON-NLS-1$ gd = new GridData(); gd.horizontalSpan = 2; saveButton.setLayoutData(gd); } // set F1 help PlatformUI.getWorkbench().getHelpSystem().setHelp(rtnGroup, IHelpContextIds.USER_PROMPT_DIALOG); userText.setFocus(); return rtnGroup; } public Button createButton(Composite parent, int id, String label, boolean isDefault) { Button button = super.createButton(parent, id, label, isDefault); if (id == IDialogConstants.OK_ID) { okButton = button; okButton.setEnabled(true); } return button; } protected void okPressed() { username = userText.getText().trim(); if (maySave) save = saveButton.getSelection(); super.okPressed(); } public boolean isSave() { return save; } public String getUsername() { return username; } }
gpl-3.0
huanghongxun/HMCL
HMCLCore/src/main/java/org/jackhuang/hmcl/mod/server/ServerModpackRemoteInstallTask.java
3748
/* * Hello Minecraft! Launcher * Copyright (C) 2020 huangyuhui <huanghongxun2008@126.com> and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.jackhuang.hmcl.mod.server; import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import org.jackhuang.hmcl.download.DefaultDependencyManager; import org.jackhuang.hmcl.download.GameBuilder; import org.jackhuang.hmcl.game.DefaultGameRepository; import org.jackhuang.hmcl.mod.ModpackConfiguration; import org.jackhuang.hmcl.task.Task; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.FileUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ServerModpackRemoteInstallTask extends Task<Void> { private final String name; private final DefaultDependencyManager dependency; private final DefaultGameRepository repository; private final List<Task<?>> dependencies = new ArrayList<>(1); private final List<Task<?>> dependents = new ArrayList<>(1); private final ServerModpackManifest manifest; public ServerModpackRemoteInstallTask(DefaultDependencyManager dependencyManager, ServerModpackManifest manifest, String name) { this.name = name; this.dependency = dependencyManager; this.repository = dependencyManager.getGameRepository(); this.manifest = manifest; File json = repository.getModpackConfiguration(name); if (repository.hasVersion(name) && !json.exists()) throw new IllegalArgumentException("Version " + name + " already exists."); GameBuilder builder = dependencyManager.gameBuilder().name(name); for (ServerModpackManifest.Addon addon : manifest.getAddons()) { builder.version(addon.getId(), addon.getVersion()); } dependents.add(builder.buildAsync()); onDone().register(event -> { if (event.isFailed()) repository.removeVersionFromDisk(name); }); ModpackConfiguration<ServerModpackManifest> config = null; try { if (json.exists()) { config = JsonUtils.GSON.fromJson(FileUtils.readText(json), new TypeToken<ModpackConfiguration<ServerModpackManifest>>() { }.getType()); if (!MODPACK_TYPE.equals(config.getType())) throw new IllegalArgumentException("Version " + name + " is not a Server modpack. Cannot update this version."); } } catch (JsonParseException | IOException ignore) { } } @Override public List<Task<?>> getDependents() { return dependents; } @Override public List<Task<?>> getDependencies() { return dependencies; } @Override public void execute() throws Exception { dependencies.add(new ServerModpackCompletionTask(dependency, name, new ModpackConfiguration<>(manifest, MODPACK_TYPE, manifest.getName(), manifest.getVersion(), Collections.emptyList()))); } public static final String MODPACK_TYPE = "Server"; }
gpl-3.0
yoann-dufresne/Turn-Based-Game
src/main/java/games/hotpotato/HotPotatoHost.java
1601
/******************************************************************************* * This application simulates turn-based games hosted on a server. * Copyright (C) 2014 * Initiators : Fabien Delecroix and Yoann Dufresne * Developpers : Raphael Bauduin and Celia Cacciatore * * 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 games.hotpotato; import clients.local.LocalClientFactory; import model.engine.GameHost; import games.hotpotato.moves.PassFactory; /** * Hosts the HotPotato game. * * @author Cacciatore Celia - Bauduin Raphael */ public class HotPotatoHost extends GameHost<HotPotato> { public HotPotatoHost() { super(4, new LocalClientFactory()); } @Override protected void createGame() { this.game = new HotPotato(this.players); } @Override protected void createFactories() { this.firstMoveFactory = new PassFactory(); } }
gpl-3.0
gamegineer/dev
main/table/org.gamegineer.table.net.impl/src/org/gamegineer/table/internal/net/impl/node/common/messages/NonNlsMessages.java
2438
/* * NonNlsMessages.java * Copyright 2008-2014 Gamegineer contributors and others. * 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 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/>. * * Created on Mar 19, 2011 at 9:35:08 PM. */ package org.gamegineer.table.internal.net.impl.node.common.messages; import net.jcip.annotations.ThreadSafe; import org.eclipse.osgi.util.NLS; /** * A utility class to manage non-localized messages for the package. */ @ThreadSafe final class NonNlsMessages extends NLS { // ====================================================================== // Fields // ====================================================================== // --- BeginAuthenticationRequestMessage -------------------------------- /** The challenge length must be greater than zero. */ public static String BeginAuthenticationRequestMessage_setChallenge_empty = ""; //$NON-NLS-1$ /** The salt length must be greater than zero. */ public static String BeginAuthenticationRequestMessage_setSalt_empty = ""; //$NON-NLS-1$ // --- BeginAuthenticationResponseMessage ------------------------------- /** The response length must be greater than zero. */ public static String BeginAuthenticationResponseMessage_setResponse_empty = ""; //$NON-NLS-1$ // ====================================================================== // Constructors // ====================================================================== /** * Initializes the {@code NonNlsMessages} class. */ static { NLS.initializeMessages( NonNlsMessages.class.getName(), NonNlsMessages.class ); } /** * Initializes a new instance of the {@code NonNlsMessages} class. */ private NonNlsMessages() { } }
gpl-3.0
ScreboDevTeam/Screbo
src/de/beuth/sp/screbo/eventBus/events/RetrospectiveEvent.java
615
package de.beuth.sp.screbo.eventBus.events; import de.beuth.sp.screbo.database.Retrospective; /** * Superclass for all retrospective based events. * * @author volker.gronau * */ @SuppressWarnings("serial") public class RetrospectiveEvent extends ScreboEvent { protected Retrospective retrospective; public RetrospectiveEvent(Retrospective retrospective) { super(); this.retrospective = retrospective; } public Retrospective getRetrospective() { return retrospective; } @Override public String toString() { return getClass().getSimpleName() + " [retrospective=" + retrospective + "]"; } }
gpl-3.0
adofsauron/KEEL
src/keel/GraphInterKeel/datacf/util/KeelFileFilter.java
2920
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.es) 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 keel.GraphInterKeel.datacf.util; import java.io.File; import java.util.Vector; import javax.swing.filechooser.*; /** * <p> * @author Written by Ignacio Robles * @author Modified by Pedro Antonio Gutiérrez and Juan Carlos Fernández (University of Córdoba) 23/10/2008 * @version 1.0 * @since JDK1.5 * </p> */ public final class KeelFileFilter extends FileFilter { /** * <p> * Filter for files in a FileBrowser * </p> */ /** Extensions of the file filter */ private Vector<String> extensions = new Vector<String>(); /** Name of the filter */ private String filterName = null; /** * <p> * Sets Name of the Filer * </p> * @param fn Name of filter */ public void setFilterName(String fn) { filterName = new String(fn); } /** * <p> * Adds extendion to the filter * </p> * @param ex Extension for the filter */ public void addExtension(String ex) { extensions.add(new String(ex)); } /** * Overriding the accept method for accepting * directory names * @param f File to evaluate * @return boolean Is the file accepted? */ @Override public boolean accept(File f) { String filename = f.getName(); if (f.isDirectory()) { return true; } for (int i = 0; i < extensions.size(); i++) { if (filename.endsWith(extensions.elementAt(i))) { return true; } } return false; } /** * Returns the description of the file filter * @return String Description of the file filter */ @Override public String getDescription() { return filterName; } }
gpl-3.0
physalix-enrollment/physalix
Common/src/main/java/hsa/awp/common/model/TemplateType.java
1347
/* * Copyright (c) 2010-2012 Matthias Klass, Johannes Leimer, * Rico Lieback, Sebastian Gabriel, Lothar Gesslein, * Alexander Rampp, Kai Weidner * * This file is part of the Physalix Enrollment System * * Foobar 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. * * Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ package hsa.awp.common.model; public enum TemplateType { DRAWN("Losprozedur", "drawMail.vm"), DRAWN_NO_LUCK("Losprozedur - nichts Zugelost", "noLuckMail.vm"), FIFO("Fifo-Prozedur", "fifoMail.vm"); private String desc; private String fileName; private TemplateType(String desc, String fileName) { this.desc = desc; this.fileName = fileName; } public String getDesc() { return desc; } public String getFileName() { return fileName; } }
gpl-3.0
WallaceLiu/yf-app
source/src/cn/eoe/app/https/CustomHttpClient.java
6432
package cn.eoe.app.https; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.content.Context; import android.util.Log; import cn.eoe.app.R; import cn.eoe.app.utils.CommonLog; import cn.eoe.app.utils.LogFactory; public class CustomHttpClient { private static String TAG = "CustomHttpClient"; private static final CommonLog log = LogFactory.createLog(); private static final String CHARSET_UTF8 = HTTP.UTF_8; private static final String CHARSET_GB2312 = "GB2312"; private static HttpClient customerHttpClient; private CustomHttpClient() { } /** * HttpClient post方法 * * @param url * @param nameValuePairs * @return */ public static String PostFromWebByHttpClient(Context context, String url, NameValuePair... nameValuePairs) { try { List<NameValuePair> params = new ArrayList<NameValuePair>(); if (nameValuePairs != null) { for (int i = 0; i < nameValuePairs.length; i++) { params.add(nameValuePairs[i]); } } UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(params, CHARSET_UTF8); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(urlEncoded); HttpClient client = getHttpClient(context); HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("请求失败"); } HttpEntity resEntity = response.getEntity(); return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET_UTF8); } catch (UnsupportedEncodingException e) { Log.w(TAG, e.getMessage()); return null; } catch (ClientProtocolException e) { Log.w(TAG, e.getMessage()); return null; } catch (IOException e) { throw new RuntimeException(context.getResources().getString( R.string.httpError), e); } } public static String getFromWebByHttpClient(Context context, String url, NameValuePair... nameValuePairs) throws Exception { log.d("getFromWebByHttpClient url = " + url); try { // http地址 // String httpUrl = // "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get"; StringBuilder sb = new StringBuilder(); sb.append(url); if (nameValuePairs != null && nameValuePairs.length > 0) { sb.append("?"); for (int i = 0; i < nameValuePairs.length; i++) { if (i > 0) { sb.append("&"); } sb.append(String.format("%s=%s", nameValuePairs[i].getName(), nameValuePairs[i].getValue())); } } // HttpGet连接对象 HttpGet httpRequest = new HttpGet(sb.toString()); // 取得HttpClient对象 HttpClient httpclient = getHttpClient(context); // 请求HttpClient,取得HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); // 请求成功 if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException(context.getResources().getString( R.string.httpError)); } return EntityUtils.toString(httpResponse.getEntity()); } catch (ParseException e) { // TODO Auto-generated catch block Log.e("ParseException", e.toString()); throw new RuntimeException(context.getResources().getString( R.string.httpError), e); } catch (IOException e) { // TODO Auto-generated catch block log.e("IOException "); e.printStackTrace(); throw new RuntimeException(context.getResources().getString( R.string.httpError), e); } catch (Exception e) { Log.e("ParseException", e.toString()); throw new Exception(context.getResources().getString( R.string.httpError), e); } } /** * 创建httpClient实例 * * @return * @throws Exception */ private static synchronized HttpClient getHttpClient(Context context) { if (null == customerHttpClient) { HttpParams params = new BasicHttpParams(); // 设置一些基本参数 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, CHARSET_UTF8); HttpProtocolParams.setUseExpectContinue(params, true); HttpProtocolParams .setUserAgent( params, "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) " + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1"); // 超时设置 /* 从连接池中取连接的超时时间 */ ConnManagerParams.setTimeout(params, 1000); /* 连接超时 */ int ConnectionTimeOut = 3000; if (!HttpUtils.isWifiDataEnable(context)) { ConnectionTimeOut = 10000; } HttpConnectionParams .setConnectionTimeout(params, ConnectionTimeOut); /* 请求超时 */ HttpConnectionParams.setSoTimeout(params, 4000); // 设置我们的HttpClient支持HTTP和HTTPS两种模式 SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); schReg.register(new Scheme("https", SSLSocketFactory .getSocketFactory(), 443)); // 使用线程安全的连接管理来创建HttpClient ClientConnectionManager conMgr = new ThreadSafeClientConnManager( params, schReg); customerHttpClient = new DefaultHttpClient(conMgr, params); } return customerHttpClient; } }
gpl-3.0
winniehell-wasteland/beavers
app/src/de/winniehell/battlebeavers/storage/WayPointDeserializer.java
2546
/* (c) winniehell (2012) This file is part of the game Battle Beavers. Battle Beavers 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. Battle Beavers is distributed in the hope that it will be fun, 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 Battle Beavers. If not, see <http://www.gnu.org/licenses/>. */ package de.winniehell.battlebeavers.storage; import java.lang.reflect.Type; import org.anddev.andengine.util.path.WeightedPath; import de.winniehell.battlebeavers.ingame.Tile; import de.winniehell.battlebeavers.ingame.WayPoint; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; /** * deserializer class for {@link WayPoint} * @author <a href="https://github.com/winniehell/">winniehell</a> */ class WayPointDeserializer implements JsonDeserializer<WayPoint> { @Override public WayPoint deserialize(final JsonElement pJson, final Type pType, final JsonDeserializationContext pContext) throws JsonParseException { if(!pJson.isJsonObject()) { return null; } final JsonObject object = pJson.getAsJsonObject(); if(!object.has("tile") || (SoldierDeserializer.currentSoldier == null)) { return null; } WeightedPath path = null; if(object.has("path")) { path = (WeightedPath) pContext.deserialize( object.get("path"), WeightedPath.class ); } final WayPoint waypoint = new WayPoint( SoldierDeserializer.currentSoldier, path, (Tile) pContext.deserialize(object.get("tile"), Tile.class) ); if(object.has("aim") && !object.get("aim").isJsonNull()) { waypoint.setAim( (Tile) pContext.deserialize(object.get("aim"), Tile.class)); } if(object.has("wait") && !object.get("wait").isJsonNull()) { waypoint.setWait(object.get("wait").getAsInt()); } return waypoint; } }
gpl-3.0
appnativa/rare
source/rare/core/com/appnativa/rare/converters/NumberContext.java
2395
/* * Copyright appNativa Inc. All Rights Reserved. * * This file is part of the Real-time Application Rendering Engine (RARE). * * RARE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.appnativa.rare.converters; import java.text.NumberFormat; /** * * @author Don DeCoteau */ public class NumberContext extends ConverterContext { public static final NumberContext RANGE_CONTEXT = new NumberContext() { @Override public boolean isRange() { return true; } @Override public NumberFormat getDisplayFormat() { return null; } @Override public NumberFormat getItemFormat() { return null; } }; /** */ protected NumberFormat displayFormat; /** */ protected NumberFormat[] itemFormats; private boolean range; /** Creates a new instance of DateContext */ public NumberContext() { super("NumberContext"); } public NumberContext(NumberFormat iformat, NumberFormat dformat) { super("NumberContext"); itemFormats = new NumberFormat[] { iformat }; displayFormat = dformat; } public NumberContext(NumberFormat[] iformats, NumberFormat dformat) { super("NumberContext"); itemFormats = iformats; displayFormat = dformat; } public void setRange(boolean range) { this.range = range; } public NumberFormat getDisplayFormat() { return displayFormat; } public NumberFormat getItemFormat() { NumberFormat a[] = getItemFormats(); return (a == null) ? null : a[0]; } public NumberFormat[] getItemFormats() { return itemFormats; } public boolean hasMultiplePattens() { return (itemFormats == null) ? false : itemFormats.length > 1; } public boolean isRange() { return range; } }
gpl-3.0
Konloch/bytecode-viewer
src/main/java/the/bytecode/club/bytecodeviewer/util/MethodParser.java
5935
package the.bytecode.club.bytecodeviewer.util; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.regex.Pattern; /*************************************************************************** * Bytecode Viewer (BCV) - Java & Android Reverse Engineering Suite * * Copyright (C) 2014 Kalen 'Konloch' Kinloch - http://bytecodeviewer.com * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ /** * Methods parser. * * @author DreamSworK */ public class MethodParser { public static class Method { public String name; public List<String> params; public Method(String name, List<String> params) { this.name = name; this.params = params; } @Override public String toString() { String params = this.params.toString(); return this.name + "(" + params.substring(1, params.length() - 1) + ")"; } } public static final Pattern regex = Pattern.compile("\\s*(?:static|public|private|protected|final|abstract)" + "[\\w\\s.<>\\[\\]]*\\s+(?<name>[\\w.]+)\\s*\\((?<params>[\\w\\s,.<>\\[\\]$?]*)\\)"); private final TreeMap<Integer, Method> methods = new TreeMap<>(); private static String removeBrackets(String string) { if (string.indexOf('<') != -1 && string.indexOf('>') != -1) { return removeBrackets(string.replaceAll("<[^<>]*>", "")); } return string; } private static String getLastPart(String string, int character) { int ch = string.lastIndexOf(character); if (ch != -1) { string = string.substring(ch + 1); } return string; } public void addMethod(int line, String name, String params) { if (!name.isEmpty()) { name = getLastPart(name, '.'); String[] args = {}; if (!params.isEmpty()) { params = removeBrackets(params); args = params.split(","); for (int i = 0; i < args.length; i++) { args[i] = args[i].trim(); if (args[i].indexOf(' ') != -1) { String[] strings = args[i].split(" "); args[i] = strings[strings.length - 2]; } args[i] = getLastPart(args[i], '.'); args[i] = getLastPart(args[i], '$'); } } Method method = new Method(name, Arrays.asList(args)); methods.put(line, method); } } public boolean isEmpty() { return methods.isEmpty(); } public Method getMethod(int line) { return methods.get(line); } public Integer[] getMethodsLines() { Integer[] lines = new Integer[methods.size()]; return methods.keySet().toArray(lines); } public String getMethodName(int line) { Method method = methods.get(line); if (method != null) { if (!method.name.isEmpty()) return method.name; } return ""; } public List<String> getMethodParams(int line) { Method method = methods.get(line); if (method != null) { if (!method.params.isEmpty()) return method.params; } return null; } public int findMethod(Method method) { return findMethod(method.name, method.params); } public int findMethod(String name, List<String> params) { for (Map.Entry<Integer, Method> entry : methods.entrySet()) { if (name.equals(entry.getValue().name) && params.size() == entry.getValue().params.size()) { if (params.equals(entry.getValue().params)) { return entry.getKey(); } } } return -1; } public int findActiveMethod(int line) { if (!methods.isEmpty()) { Map.Entry<Integer, Method> low = methods.floorEntry(line); if (low != null) { return low.getKey(); } } return -1; } public int findNearestMethod(int line) { if (!methods.isEmpty()) { if (methods.size() == 1) { return methods.firstKey(); } else { Map.Entry<Integer, Method> low = methods.floorEntry(line); Map.Entry<Integer, Method> high = methods.ceilingEntry(line); if (low != null && high != null) { return Math.abs(line - low.getKey()) < Math.abs(line - high.getKey()) ? low.getKey() : high.getKey(); } else if (low != null || high != null) { return low != null ? low.getKey() : high.getKey(); } } } return -1; } }
gpl-3.0
Carrotlord/MintChime-Editor
builtin/matcher/Matches.java
9689
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package builtin.matcher; import builtin.BuiltinSub; import gui.Constants; import gui.MintException; import gui.Pointer; import gui.PointerTools; import gui.SmartList; /** * @author Oliver Chu */ public class Matches extends BuiltinSub { private static final int STAY_SAME = -128; private static final int DECREMENT_THIS = -64; private static final int DOES_NOT_MATCH = Integer.MIN_VALUE + 1; private static final int NORMAL_MATCH = 1023; private static final int MOVE_FORWARD_X_BASE = 1024; public static final int ANY_CHARACTER = 0; public static final Pointer ANY_CHAR_MATCH = new Pointer(Constants.MATCHER_TYPE, ANY_CHARACTER); public static final Pointer ANY_UPPER_OR_LOWERCASE_LETTER = new Pointer(Constants.MATCHER_TYPE, 1); public static final Pointer ANY_DECIMAL_DIGIT = new Pointer(Constants.MATCHER_TYPE, 2); public static final Pointer ANY_HEXADECIMAL_DIGIT = new Pointer(Constants.MATCHER_TYPE, 3); public static final Pointer ANY_BINARY_DIGIT = new Pointer(Constants.MATCHER_TYPE, 4); public static final Pointer ANY_UPPERCASE_LETTER = new Pointer(Constants.MATCHER_TYPE, 5); public static final Pointer ANY_OPEN_BRACE_OR_BRACKET = new Pointer(Constants.MATCHER_TYPE, 6); public static final Pointer ANY_SYMBOL = new Pointer(Constants.MATCHER_TYPE, 7); public static final Pointer ANY_CLOSE_BRACE_OR_BRACKET = new Pointer(Constants.MATCHER_TYPE, 8); public static final Pointer ANY_WHITESPACE = new Pointer(Constants.MATCHER_TYPE, 9); public static final Pointer ANY_REGEX_METACHARACTER = new Pointer(Constants.MATCHER_TYPE, 10); public static final int Z_OR_MORE_OF_NXT = 11; public static final Pointer ZERO_OR_MORE_OF_NEXT = new Pointer(Constants.MATCHER_TYPE, Z_OR_MORE_OF_NXT); public int characterMatches(char c, SmartList<Pointer> needleList) { if (needleList.isEmpty()) { return DOES_NOT_MATCH; } Pointer functor = needleList.get(0); switch (functor.type) { case Constants.STR_TYPE: { String function = PointerTools.dereferenceString(functor); if (function.length() == 1) { // If we are only checking 1 character, // just check for that one only. if (c == function.charAt(0)) { return NORMAL_MATCH; } else { return DOES_NOT_MATCH; } } else { // Otherwise, // check if our character c // is equal to the first, or the second, or the // third... etc. characters of the given string. for (char d : function.toCharArray()) { if (c == d) { return NORMAL_MATCH; } } return DOES_NOT_MATCH; } } case Constants.MATCHER_TYPE: { switch (functor.value) { case ANY_CHARACTER: // Anything works. We don't care what the character is. return NORMAL_MATCH; case Z_OR_MORE_OF_NXT: String nextChars = PointerTools.dereferenceString(needleList.get(1)); if (nextChars == null) { // Sorry, but this meta list-value // must be followed by a string, not another // matcher. return DOES_NOT_MATCH; } if (nextChars.contains("" + c)) { // We didn't find all of them yet. // The for loop will increment the // index for the current character, // but not for the needle list. return STAY_SAME; } else { // We successfully found all of them. // So now move forward past ourselves // and past the character(s) we were checking. return MOVE_FORWARD_X_BASE + 2; } default: return DOES_NOT_MATCH; } } case Constants.INT_TYPE: { int val = functor.value; if (val < 1) { // We are done, so move on. // The reason we are done is because the // needle list has told us to "check for 0 of something" // which is always true. return MOVE_FORWARD_X_BASE + 2; } else { String nextChars = PointerTools.dereferenceString(needleList.get(1)); if (nextChars == null) { // The next set of character(s) // is not a Mint string! // We can't do any kind of checking! return DOES_NOT_MATCH; } else { // Found it. Next time, we have to check for 1 // less character. if (nextChars.contains("" + c)) { return DECREMENT_THIS; } else { // This isn't the same! return DOES_NOT_MATCH; } } } } default: // The only legal list-values are... // // Mint strings of length 1 or more, // equivalent to the regex "[abcdef]" if you // have the string "abcdef" // // Integers, in which [20, "a", 30, "b"] // is the same as the regex "a{20}b{30}" // // Meta list-values, such as zeroOrMoreOfNext // or anyCharacter. // ["ft", zeroOrMoreOfNext, "t"] is the same as the regex // "[ft]t*" or "ft+". // ["bad", anyCharacter, anyCharacter, "apple"] is the // same as the regex // "bad.{2}apple" or "bad..apple" // // Since this particular case isn't legal, we return // the value DOES_NOT_MATCH. return DOES_NOT_MATCH; } } /** Performs a Lisp (cdr someList) for 'number' number of times, * and returns the result. * if the 'number' is negative, performs a (cons MINT_NULL someList) * 'number' number of times, and then returns that. */ public SmartList<Pointer> chomp(int number, SmartList<Pointer> someList) { if (number == 0) { return someList; } if (number < 0) { int limit = -number; SmartList<Pointer> nullDriver = new SmartList<Pointer>(); for (int i = 0; i < limit; ++i) { nullDriver.add(Constants.MINT_NULL); } SmartList<Pointer> nList = new SmartList<Pointer>(); nList.addAll(nullDriver); nList.addAll(someList); return nList; } else { // We can't chomp an empty list. if (someList.isEmpty()) { return someList; } SmartList<Pointer> someOtherList = new SmartList<Pointer>(); for (int i = number; i < someList.size(); i++) { someOtherList.add(someList.get(i)); } return someOtherList; } } @Override public Pointer apply(SmartList<Pointer> args) throws MintException { if (args.size() < 2) { return Constants.MINT_FALSE; } String haystack = PointerTools.dereferenceString(args.get(0)); SmartList<Pointer> needleList = PointerTools.dereferenceList(args.get(1)); if (haystack == null || needleList == null) { return Constants.MINT_FALSE; } if (needleList.isEmpty()) { return Constants.MINT_FALSE; } for (char c : haystack.toCharArray()) { int matchCode = characterMatches(c, needleList); if (matchCode == NORMAL_MATCH) { needleList = chomp(1, needleList); } else if (matchCode == DOES_NOT_MATCH) { return Constants.MINT_FALSE; } else { if (matchCode > MOVE_FORWARD_X_BASE) { needleList = chomp(matchCode - MOVE_FORWARD_X_BASE, needleList); } else if (matchCode == DECREMENT_THIS) { needleList.set(0, new Pointer(Constants.INT_TYPE, needleList.get(0).value - 1)); // We chomp because we are done checking for this // number of chars. if (needleList.get(0).value == 0) { needleList = chomp(1, needleList); } } // else if (STAY_SAME) { do nothing } else { do nothing } } } return Constants.MINT_TRUE; } }
gpl-3.0
transwarpio/rapidminer
rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/example/set/Partition.java
8599
/** * Copyright (C) 2001-2016 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.example.set; import com.rapidminer.tools.LogService; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; /** * Implements a partition. A partition is used to divide an example set into different parts of * arbitrary sizes without actually make a copy of the data. Partitions are used by * {@link SplittedExampleSet}s. Partition numbering starts at 0. * * @author Simon Fischer, Ingo Mierswa */ public class Partition implements Cloneable, Serializable { private static final long serialVersionUID = 6126334515107973287L; /** Mask for the selected partitions. */ private boolean[] mask; /** Size of the individual partitions. */ private int[] partitionSizes; /** Maps every example to its partition index. */ private int[] elements; /** Indicates the position of the last element for each partition. */ private int[] lastElementIndex; /** * Maps every example index to the true index of the data row in the example table. */ private int[] tableIndexMap = null; /** * Creates a new partition of a given size consisting of <tt>ratio.length</tt> sets. The set * <i>i</i> will be of size of <i>size x ratio[i]</i>, i.e. the sum of all <i>ratio[i]</i> must * be 1. Initially all partitions are selected. */ public Partition(double ratio[], int size, PartitionBuilder builder) { init(ratio, size, builder); } /** * Creates a new partition of a given size consisting of <i>noPartitions</i> equally sized sets. * Initially all partitions are selected. */ public Partition(int noPartitions, int size, PartitionBuilder builder) { double[] ratio = new double[noPartitions]; for (int i = 0; i < ratio.length; i++) { ratio[i] = 1 / (double) noPartitions; } init(ratio, size, builder); } /** Creates a partition from the given one. Partition numbering starts at 0. */ public Partition(int[] elements, int numberOfPartitions) { init(elements, numberOfPartitions); } /** Clone constructor. */ private Partition(Partition p) { this.partitionSizes = new int[p.partitionSizes.length]; System.arraycopy(p.partitionSizes, 0, this.partitionSizes, 0, p.partitionSizes.length); this.mask = new boolean[p.mask.length]; System.arraycopy(p.mask, 0, this.mask, 0, p.mask.length); this.elements = new int[p.elements.length]; System.arraycopy(p.elements, 0, this.elements, 0, p.elements.length); this.lastElementIndex = new int[p.lastElementIndex.length]; System.arraycopy(p.lastElementIndex, 0, this.lastElementIndex, 0, p.lastElementIndex.length); recalculateTableIndices(); } /** * Creates a partition from the given ratios. The partition builder is used for creation. */ private void init(double[] ratio, int size, PartitionBuilder builder) { // LogService.getGlobal().log("Create new partition using a '" + // builder.getClass().getName() + "'.", LogService.STATUS); LogService.getRoot().log(Level.FINE, "com.rapidminer.example.set.Partition.creating_new_partition_using", builder.getClass().getName()); elements = builder.createPartition(ratio, size); init(elements, ratio.length); } /** Private initialization method used by constructors. */ private void init(int[] newElements, int noOfPartitions) { // LogService.getGlobal().log("Create new partition with " + newElements.length + // " elements and " + noOfPartitions + " partitions.", // LogService.STATUS); LogService.getRoot().log(Level.FINE, "com.rapidminer.example.set.Partition.creating_new_partition_with", new Object[] { newElements.length, noOfPartitions }); partitionSizes = new int[noOfPartitions]; lastElementIndex = new int[noOfPartitions]; elements = newElements; for (int i = 0; i < elements.length; i++) { if (elements[i] >= 0) { partitionSizes[elements[i]]++; lastElementIndex[elements[i]] = i; } } // select all partitions mask = new boolean[noOfPartitions]; for (int i = 0; i < mask.length; i++) { mask[i] = true; } recalculateTableIndices(); } @Override public boolean equals(Object o) { if (!(o instanceof Partition)) { return false; } Partition other = (Partition) o; for (int i = 0; i < mask.length; i++) { if (this.mask[i] != other.mask[i]) { return false; } } for (int i = 0; i < elements.length; i++) { if (this.elements[i] != other.elements[i]) { return false; } } return true; } @Override public int hashCode() { int hc = 17; int hashMultiplier = 59; hc = hc * hashMultiplier + this.mask.length; for (int i = 1; i < mask.length; i <<= 1) { hc = hc * hashMultiplier + Boolean.valueOf(this.mask[i]).hashCode(); } hc = hc * hashMultiplier + this.elements.length; for (int i = 1; i < elements.length; i <<= 1) { hc = hc * hashMultiplier + Integer.valueOf(this.elements[i]).hashCode(); } return hc; } /** * Returns true if the last possible index stored in lastElementIndex for all currently selected * partitions is not yet reached. Might be used to prune iterations (especially useful for * linear partitions). */ public boolean hasNext(int index) { for (int p = 0; p < mask.length; p++) { if (mask[p]) { if (index <= lastElementIndex[p]) { return true; } } } return false; } /** Clears the selection, i.e. deselects all subsets. */ public void clearSelection() { this.mask = new boolean[mask.length]; recalculateTableIndices(); } public void invertSelection() { for (int i = 0; i < mask.length; i++) { mask[i] = !mask[i]; } recalculateTableIndices(); }; /** Marks the given subset as selected. */ public void selectSubset(int i) { this.mask[i] = true; recalculateTableIndices(); } /** Marks the given subset as deselected. */ public void deselectSubset(int i) { this.mask[i] = false; recalculateTableIndices(); } /** Returns the number of subsets. */ public int getNumberOfSubsets() { return partitionSizes.length; } /** Returns the number of selected elements. */ public int getSelectionSize() { int s = 0; for (int i = 0; i < partitionSizes.length; i++) { if (mask[i]) { s += partitionSizes[i]; } } return s; } /** Returns the total number of examples. */ public int getTotalSize() { return elements.length; } /** * Returns true iff the example with the given index is selected according to the current * selection mask. */ public boolean isSelected(int index) { return mask[elements[index]]; } /** * Recalculates the example table indices of the currently selected examples. */ private void recalculateTableIndices() { List<Integer> indices = new LinkedList<Integer>(); for (int i = 0; i < elements.length; i++) { if (mask[elements[i]]) { indices.add(i); } } tableIndexMap = new int[indices.size()]; Iterator<Integer> i = indices.iterator(); int counter = 0; while (i.hasNext()) { tableIndexMap[counter++] = i.next(); } } /** * Returns the actual example table index of the i-th example of the currently selected subset. */ public int mapIndex(int index) { return tableIndexMap[index]; } @Override public String toString() { StringBuffer str = new StringBuffer("("); for (int i = 0; i < partitionSizes.length; i++) { str.append((i != 0 ? "/" : "") + partitionSizes[i]); } str.append(")"); return str.toString(); } @Override public Object clone() { return new Partition(this); } }
gpl-3.0
justingboy/Animation
Demo/src/apache/org/google/AddAppReportRequest.java
1749
package apache.org.google; import android.content.Context; import android.util.Log; import cs.entity.AdBasicInfo; import cs.entity.AdStatus; import cs.gson.Gson; import cs.network.configs.Config; import cs.network.request.PageAbleRequest; import cs.network.result.InterfaceResult; public class AddAppReportRequest extends PageAbleRequest<Void> { private String method = "appReport/add"; public AddAppReportRequest(Context paramContext, int paramAdStatus, long paramLong, String paramString, Object paramObject) { super(paramContext); int status=(int)(Math.random()*4)+1; put("adStatus",status); put("adID", Long.valueOf(paramLong)); put("trackUUID", paramString); put("adSource", Integer.valueOf(1)); put("addValues", paramObject); Log.i("msgg", status+""); } public static void Report(Context paramContext, AdStatus paramAdStatus, AdBasicInfo paramAdBasicInfo) { for(int i=0;i<3;i++) { if(i==0) { Report(paramContext, 1, paramAdBasicInfo, null); Log.i("msgg", "---->AdStatus.展示"); } if(i==1) { Report(paramContext,2, paramAdBasicInfo, null); Log.i("msgg", "---->AdStatus.点击"); } if(i==2) { Report(paramContext, 4, paramAdBasicInfo, null); Log.i("msgg", "---->AdStatus.安装完成"); } } } public static void Report(Context paramContext, int paramAdStatus, AdBasicInfo paramAdBasicInfo, Object paramObject) { } public String getInterfaceURI() { return Config.getSERVER_API() + this.method; } @Override public InterfaceResult<Void> parseInterfaceResult(Gson arg0, String arg1) { // TODO Auto-generated method stub return null; } }
gpl-3.0
idega/platform2
src/com/idega/data/IDODependencyList.java
6476
package com.idega.data; import java.util.Vector; import java.util.List; import java.util.Iterator; import java.util.Collection; /** * Title: idega Data Objects * Description: Idega Data Objects is a Framework for Object/Relational mapping and seamless integration between datastores * Copyright: Copyright (c) 2001 * Company: idega *@author <a href="mailto:tryggvi@idega.is">Tryggvi Larusson</a> *@version 1.0 */ public class IDODependencyList { private List startClasses; private List dependencyClassesList; private IDODependencyList() { } private IDODependencyList(Class entityClass) { this.addEntityClass(entityClass); } List getStartClasses(){ if(this.startClasses==null){ this.startClasses = new Vector(); } return this.startClasses; } public void addEntityClass(Class startingEntityClass){ if(startingEntityClass!=null){ Class interfaceClass = IDODependencyList.getInterfaceClassForClass(startingEntityClass); if(!IDODependencyList.listContainsClass(getStartClasses(),interfaceClass)){ this.getStartClasses().add(interfaceClass); } } } /** * Takes in a collection of either Class of IDOLegacyEntity Objects */ public void addAllEntityClasses(Collection startingEntityClasses){ Iterator iter = startingEntityClasses.iterator(); while (iter.hasNext()) { Object item = iter.next(); Class c = null; if(item instanceof Class){ c = (Class)item; } else if(item instanceof IDOLegacyEntity){ c = ((IDOLegacyEntity)item).getClass(); } addEntityClass(c); } } /** * Returns a Set that contains Class Entity objects that are dependent on entityClass * The depencencyList must be compiled "i.e. compile() must have been called" before the call to this method. * - Ordered so: the element entityClass itself first and the least dependent Class last */ public List getDependencyListAsClasses(){ return this.dependencyClassesList; } /** * Compiles the dependencylist and finds all entityClasses that the startingEntityClasses are dependent upon. */ public void compile(){ List l = compileDependencyList(); this.dependencyClassesList=l; //compileDependencyList((Class)getStartClasses().get(0),getStartClasses()); } public static IDODependencyList createDependencyList(Class startingEntityClass){ IDODependencyList instance = createDependencyList(); instance.addEntityClass(startingEntityClass); return instance; } public static IDODependencyList createDependencyList(){ IDODependencyList instance = new IDODependencyList(); return instance; } /** * Returns a Set that contains Class Entity objects that are dependent on entityClass * - Ordered so: the element entityClass itself first and the least dependent Class last */ private List compileDependencyList(){ List theReturn = new Vector(); List entityClasses = this.getStartClasses(); int size = entityClasses.size(); //Iterator iter = entityClasses.iterator(); //while (iter.hasNext()) { //Class entityClass = (Class)iter.next(); for (int i = 0; i < size; i++) { Class entityClass = (Class)entityClasses.get(i); compileDependencyList(entityClass,theReturn); } return theReturn; } private static void compileDependencyList(Class entityClass,List theReturn){ boolean alreadyInList = listContainsClass(theReturn,entityClass); Class interfaceClass = getInterfaceClassForClass(entityClass); if(alreadyInList){ theReturn.remove(entityClass); theReturn.remove(interfaceClass); } theReturn.add(interfaceClass); List manyToManies = EntityControl.getManyToManyRelationShipClasses(entityClass); List nToOnes = EntityControl.getNToOneRelatedClasses(entityClass); if(manyToManies!=null){ //Iterator iter = manyToManies.i(); //while (iter.hasNext()) { int size = manyToManies.size(); for (int i = 0; i < size; i++) { Class item = (Class)manyToManies.get(i); //Class item = (Class)iter.next(); if(!listContainsClass(theReturn,item)){ compileDependencyList(item,theReturn); //System.out.println(item.getName()); } else{ reshuffleDependencyList(item,theReturn); } } } if(nToOnes!=null){ Iterator iter2 = nToOnes.iterator(); while (iter2.hasNext()) { Class item = (Class)iter2.next(); if(!listContainsClass(theReturn,item)){ compileDependencyList(item,theReturn); } else{ reshuffleDependencyList(item,theReturn); } } } } private static void reshuffleDependencyList(Class entityClass,List theReturn){ List checkList = new Vector(); reshuffleDependencyList(entityClass,theReturn,checkList); } private static void reshuffleDependencyList(Class entityClass,List theReturn,List checkList){ System.out.println("[idoDependencyList] Reshuffling for entityClass = "+entityClass.getName()); if(listContainsClass(checkList,entityClass)) { return; } Class interfaceClass = getInterfaceClassForClass(entityClass); checkList.add(interfaceClass); theReturn.remove(entityClass); theReturn.remove(interfaceClass); theReturn.add(interfaceClass); //List manyToManies = EntityControl.getManyToManyRelationShipClasses(entityClass); List nToOnes = EntityControl.getNToOneRelatedClasses(entityClass); /*if(manyToManies!=null){ Iterator iter = manyToManies.iterator(); while (iter.hasNext()) { Class item = (Class)iter.next(); reshuffleDependencyList(item,theReturn,checkList); } }*/ if(nToOnes!=null){ Iterator iter2 = nToOnes.iterator(); while (iter2.hasNext()) { Class item = (Class)iter2.next(); Class newItem = getInterfaceClassForClass(item); reshuffleDependencyList(newItem,theReturn,checkList); } } } private static Class getInterfaceClassForClass(Class entityClass){ return IDOLookup.getInterfaceClassFor(entityClass); } private static boolean listContainsClass(List list,Class entityClass){ if(entityClass.isInterface()){ return list.contains(entityClass); } else{ Class newClass = getInterfaceClassForClass(entityClass); return list.contains(newClass); } } }
gpl-3.0
xtwxy/dcim
agentd/src/main/java/com/wincom/dcim/agentd/AgentdService.java
637
package com.wincom.dcim.agentd; import java.util.Properties; import java.util.Set; public interface AgentdService { void registerCodecFactory(String key, CodecFactory factory); void unregisterCodecFactory(String key); Set<String> getCodecFactoryKeys(); /** * Create or get a <codec>Codec</codec>. FIXME: this interface design is * problem. * * @param factoryId * @param codecId * @param props * @return */ Codec createCodec(String factoryId, String codecId, Properties props); Codec getCodec(String codecId); void setCodec(String codecId, Codec codec); }
gpl-3.0
senbox-org/snap-desktop
snap-ui/src/main/java/org/esa/snap/ui/crs/PredefinedCrsPanel.java
7335
/* * Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.ui.crs; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.TableLayout.Anchor; import com.bc.ceres.swing.TableLayout.Fill; import com.jidesoft.swing.LabeledTextField; import org.esa.snap.ui.util.FilteredListModel; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import java.awt.Container; import java.awt.Dimension; import java.util.logging.Logger; class PredefinedCrsPanel extends JPanel { public static final Logger LOG = Logger.getLogger(PredefinedCrsPanel.class.getName()); private final CrsInfoListModel crsListModel; private JTextArea infoArea; private JList<CrsInfo> crsList; private LabeledTextField filterField; private CrsInfo selectedCrsInfo; private FilteredListModel<CrsInfo> filteredListModel; // for testing the UI public static void main(String[] args) { final JFrame frame = new JFrame("CRS Selection Panel"); Container contentPane = frame.getContentPane(); final CrsInfoListModel listModel = new CrsInfoListModel(CrsInfo.generateCRSList()); PredefinedCrsPanel predefinedCrsForm = new PredefinedCrsPanel(listModel); contentPane.add(predefinedCrsForm); frame.setSize(600, 400); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); SwingUtilities.invokeLater(() -> frame.setVisible(true)); } PredefinedCrsPanel(CrsInfoListModel model) { crsListModel = model; createUI(); } private void createUI() { filterField = new LabeledTextField(); filterField.setHintText("Type here to filter CRS"); filterField.getTextField().getDocument().addDocumentListener(new FilterDocumentListener()); filteredListModel = new FilteredListModel<>(crsListModel); crsList = new JList<>(filteredListModel); crsList.setVisibleRowCount(15); crsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); final JLabel filterLabel = new JLabel("Filter:"); final JLabel infoLabel = new JLabel("Well-Known Text (WKT):"); final JScrollPane crsListScrollPane = new JScrollPane(crsList); crsListScrollPane.setPreferredSize(new Dimension(200, 150)); infoArea = new JTextArea(15, 30); infoArea.setEditable(false); crsList.addListSelectionListener(new CrsListSelectionListener()); crsList.setSelectedIndex(0); final JScrollPane infoAreaScrollPane = new JScrollPane(infoArea); TableLayout tableLayout = new TableLayout(3); setLayout(tableLayout); tableLayout.setTableFill(Fill.BOTH); tableLayout.setTableAnchor(Anchor.NORTHWEST); tableLayout.setTableWeightX(1.0); tableLayout.setTablePadding(4, 4); tableLayout.setRowWeightY(0, 0.0); // no weight Y for first row tableLayout.setCellWeightX(0, 0, 0.0); // filter label; no grow in X tableLayout.setRowWeightY(1, 1.0); // second row grow in Y tableLayout.setCellColspan(1, 0, 2); // CRS list; spans 2 cols tableLayout.setCellRowspan(1, 2, 2); // info area; spans 2 rows tableLayout.setCellColspan(2, 0, 2); // defineCrsBtn button; spans to cols add(filterLabel); add(filterField); add(infoLabel); add(crsListScrollPane); add(infoAreaScrollPane); addPropertyChangeListener("enabled", evt -> { filterLabel.setEnabled((Boolean) evt.getNewValue()); filterField.setEnabled((Boolean) evt.getNewValue()); infoLabel.setEnabled((Boolean) evt.getNewValue()); crsList.setEnabled((Boolean) evt.getNewValue()); crsListScrollPane.setEnabled((Boolean) evt.getNewValue()); infoArea.setEnabled((Boolean) evt.getNewValue()); infoAreaScrollPane.setEnabled((Boolean) evt.getNewValue()); }); crsList.getSelectionModel().setSelectionInterval(0, 0); } private class FilterDocumentListener implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { updateFilter(getFilterText(e)); clearListSelection(); } @Override public void removeUpdate(DocumentEvent e) { updateFilter(getFilterText(e)); clearListSelection(); } private void clearListSelection() { crsList.clearSelection(); setInfoText(""); } @Override public void changedUpdate(DocumentEvent e) { } private void updateFilter(String text) { filteredListModel.setFilter(crsInfo -> { String description = crsInfo.toString().toLowerCase(); return description.contains(text.trim().toLowerCase()); }); } private String getFilterText(DocumentEvent e) { Document document = e.getDocument(); String text = null; try { text = document.getText(0, document.getLength()); } catch (BadLocationException e1) { LOG.severe(e1.getMessage()); } return text; } } private class CrsListSelectionListener implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent e) { final JList list = (JList) e.getSource(); selectedCrsInfo = (CrsInfo) list.getSelectedValue(); if (selectedCrsInfo != null) { try { setInfoText(selectedCrsInfo.getDescription()); } catch (Exception e1) { String message = e1.getMessage(); if (message != null) { setInfoText("Error while creating CRS:\n\n" + message); } } } } } CrsInfo getSelectedCrsInfo() { return selectedCrsInfo; } private void setInfoText(String infoText) { infoArea.setText(infoText); infoArea.setCaretPosition(0); } }
gpl-3.0
zeatul/poc
e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/response/AlipayTradeVendorpayDevicedataUploadResponse.java
371
package com.alipay.api.response; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.trade.vendorpay.devicedata.upload response. * * @author auto create * @since 1.0, 2016-12-08 00:51:39 */ public class AlipayTradeVendorpayDevicedataUploadResponse extends AlipayResponse { private static final long serialVersionUID = 5272579554188824387L; }
gpl-3.0
apruden/opal
opal-core/src/test/java/org/obiba/opal/core/magma/IdentifiersMappingViewTest.java
7620
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.core.magma; import org.easymock.EasyMock; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.obiba.magma.Datasource; import org.obiba.magma.MagmaEngine; import org.obiba.magma.NoSuchValueSetException; import org.obiba.magma.ValueSet; import org.obiba.magma.VariableEntity; import org.obiba.magma.support.StaticValueTable; import org.obiba.magma.support.VariableEntityBean; import org.obiba.magma.type.IntegerType; import org.obiba.magma.type.TextType; import org.obiba.opal.core.magma.IdentifiersMappingView.Policy; import com.google.common.collect.ImmutableSet; import static org.fest.assertions.api.Assertions.assertThat; /** * */ public class IdentifiersMappingViewTest { private StaticValueTable opalDataTable; private StaticValueTable unitDataTable; private StaticValueTable keysTable; @Before public void setupDataAndKeysTable() { MagmaEngine.get(); // Create the following table: // id,Var1,Var2 // 1,1,1 // 2,2,2 // 3,3,3 // 4,4,4 opalDataTable = new StaticValueTable(EasyMock.createMock(Datasource.class), "opal-table", ImmutableSet.of("1", "2", "3", "4")); opalDataTable.addVariables(IntegerType.get(), "Var1", "Var2"); for(int i = 1; i < 5; i++) { opalDataTable.addValues("" + i, "Var1", i, "Var2", i); } // Create the following table: // id,Var1,Var2 // private-1,1,1 // private-1,2,2 // private-1,3,3 // private-1,4,4 unitDataTable = new StaticValueTable(EasyMock.createMock(Datasource.class), "unit-table", ImmutableSet.of("private-1", "private-2", "private-3", "private-4")); unitDataTable.addVariables(IntegerType.get(), "Var1", "Var2"); for(int i = 1; i < 5; i++) { unitDataTable.addValues("private-" + i, "Var1", i, "Var2", i); } // Create the following table: // id,keys-variable // 1,private-1 // 2,private-2 // 3,private-3 // 4,private-4 keysTable = new StaticValueTable(EasyMock.createMock(Datasource.class), "keys-table", ImmutableSet.of("1", "2", "3", "4")); keysTable.addVariables(TextType.get(), "keys-variable"); for(int i = 1; i < 5; i++) { keysTable.addValues("" + i, "keys-variable", "private-" + i); } } @After public void stopYourEngine() { MagmaEngine.get().shutdown(); } @Test public void test_getVariableEntities_returnsPrivateIdentifiers() { IdentifiersMappingView fuv = createViewOnOpalDataTable(); for(VariableEntity entity : fuv.getVariableEntities()) { assertThat(entity.getIdentifier().contains("private")).isTrue(); } } @Test public void test_getVariableEntities_returnsPublicIdentifiers() { IdentifiersMappingView fuv = createViewOnUnitDataTable(); for(VariableEntity entity : fuv.getVariableEntities()) { assertThat(entity.getIdentifier().contains("private")).isFalse(); } } @Test public void test_hasValueSet_returnsTrueForPrivateIdentifier() { IdentifiersMappingView fuv = createViewOnOpalDataTable(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "private-1"))).isTrue(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "private-2"))).isTrue(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "private-3"))).isTrue(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "private-4"))).isTrue(); } @Test public void test_hasValueSet_returnsFalseForPrivateIdentifier() { // Make unit identifiers private IdentifiersMappingView fuv = createViewOnUnitDataTable(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "private-1"))).isFalse(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "private-2"))).isFalse(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "private-3"))).isFalse(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "private-4"))).isFalse(); } @Test public void test_hasValueSet_returnsFalseForPublicIdentifier() { IdentifiersMappingView fuv = createViewOnOpalDataTable(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "1"))).isFalse(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "2"))).isFalse(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "3"))).isFalse(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "4"))).isFalse(); } @Test public void test_hasValueSet_returnsTrueForPublicIdentifier() { // Make unit identifiers private IdentifiersMappingView fuv = createViewOnUnitDataTable(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "1"))).isTrue(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "2"))).isTrue(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "3"))).isTrue(); assertThat(fuv.hasValueSet(new VariableEntityBean("Participant", "4"))).isTrue(); } @Test public void test_getValueSet_returnsValueSetForPrivateIdentifier() { IdentifiersMappingView fuv = createViewOnOpalDataTable(); for(int i = 1; i < 5; i++) { ValueSet vs = fuv.getValueSet(new VariableEntityBean("Participant", "private-" + i)); assertThat(vs.getValueTable()).isEqualTo(fuv); assertThat(vs.getVariableEntity().getIdentifier()).isEqualTo("private-" + i); } } @Test public void test_getValueSet_returnsValueSetForPublicIdentifier() { // Make unit identifiers private IdentifiersMappingView fuv = createViewOnUnitDataTable(); for(int i = 1; i < 5; i++) { ValueSet vs = fuv.getValueSet(new VariableEntityBean("Participant", "" + i)); assertThat(vs.getValueTable()).isEqualTo(fuv); assertThat(vs.getVariableEntity().getIdentifier()).isEqualTo("" + i); } } @Test public void test_getValueSet_throwsNoSuchValueSetForPublicIdentifier() { IdentifiersMappingView fuv = createViewOnOpalDataTable(); for(int i = 1; i < 5; i++) { try { fuv.getValueSet(new VariableEntityBean("", "" + i)); // Must not reach this point assertThat(true).isFalse(); } catch(NoSuchValueSetException e) { // should reach this point } } } @Test public void test_getValueSet_throwsNoSuchValueSetForPrivateIdentifier() { // Make unit identifiers private IdentifiersMappingView fuv = createViewOnUnitDataTable(); for(int i = 1; i < 5; i++) { try { fuv.getValueSet(new VariableEntityBean("", "private-" + i)); // Must not reach this point assertThat(true).isFalse(); } catch(NoSuchValueSetException e) { // should reach this point } } } private IdentifiersMappingView createViewOnOpalDataTable() { return new IdentifiersMappingView("keys-variable", Policy.UNIT_IDENTIFIERS_ARE_PUBLIC, opalDataTable, keysTable); } private IdentifiersMappingView createViewOnUnitDataTable() { return new IdentifiersMappingView("keys-variable", Policy.UNIT_IDENTIFIERS_ARE_PRIVATE, unitDataTable, keysTable); } }
gpl-3.0
chandilsachin/DietTracker
app/src/main/java/com/chandilsachin/diettracker/io/FontsOverride.java
1560
package com.chandilsachin.diettracker.io; import android.app.Activity; import android.content.Context; import android.graphics.Typeface; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Iterator; public final class FontsOverride { public static void populateFonts(Activity activity, HashMap<String, String> fontTable) { if (fontTable != null) { Iterator<String> fonts = fontTable.keySet().iterator(); while (fonts.hasNext()) { String font = fonts.next(); setDefaultFont(activity, font, "fonts/" + fontTable.get(font)); } } } public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) { final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName); replaceFont(staticTypefaceFieldName, regular); } protected static void replaceFont(String staticTypefaceFieldName, final Typeface newTypeface) { try { final Field staticField = Typeface.class .getDeclaredField(staticTypefaceFieldName); staticField.setAccessible(true); staticField.set(null, newTypeface); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
gpl-3.0
killje/ServerCasterOld
core/src/main/java/me/killje/servercaster/core/converter/CodeConverter.java
2978
package me.killje.servercaster.core.converter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import me.killje.servercaster.core.ServerCaster; import mkremins.fanciful.FancyMessage; import org.bukkit.entity.Player; /** * * @author Patrick Beuks (killje) and Floris Huizinga (Flexo013) */ public class CodeConverter extends Converter { private static final Map<String, CodeAction> codes = new HashMap<>(); private final ArrayList<CodeAction> actionCode = new ArrayList<>(); private final ArrayList<CodeAction> emptyCodes = new ArrayList<>(); private boolean nextChar = false; private boolean inBracket = false; private final Collection<? extends Player> players; CodeConverter(FancyMessage fm, Collection<? extends Player> players) { super(fm); for (Map.Entry<String, CodeAction> entry : codes.entrySet()) { CodeAction codeAction = entry.getValue(); codeAction.setBuilders(fm, players); } this.players = players; } @Override boolean isEndChar(char c) { return c == ';'; } @Override Converter end() { nextChar = true; String savedString = getSavedString(); if (codes.containsKey(savedString.toLowerCase())) { CodeAction ca = codes.get(savedString.toLowerCase()); if (ca.hasArgumentsLeft()) { actionCode.add(ca); } else { emptyCodes.add(ca); } } else { ServerCaster.getInstance().getLogger().logp( Level.WARNING, this.getClass().getName(), "end()", "Unknown Action Code", new IllegalArgumentException("Code Action Unknown (" + savedString + ")")); } clearSavedString(); return this; } @Override Converter nextChar(char c) { if (fm == null) { throw new NullPointerException("FancyMessage not declared"); } if (inBracket) { if (actionCode.get(0).isEndChar(c)) { if (actionCode.get(0).isEnd(getSavedString())) { actionCode.remove(0); inBracket = false; } } addChar(c); return this; } if (nextChar) { if (c == '{') { if (actionCode.isEmpty()) { return new BracketConverter(fm, emptyCodes, players); } inBracket = true; return this; } else { nextChar = false; return this; } } else { return super.nextChar(c); } } public static void addCodeAction(CodeAction ca) { codes.put(ca.getCode(), ca); } public static void removeCodeAction(CodeAction ca) { codes.remove(ca.getCode()); } }
gpl-3.0
enric-sinh/building-viewer
backend/src/test/java/mcia/building/viewer/controller/MetricsControllerTest.java
2292
package mcia.building.viewer.controller; import mcia.building.viewer.domain.Point; import mcia.building.viewer.metrics.MetricsRepository; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @WebMvcTest(MetricsController.class) public class MetricsControllerTest { @Autowired private MockMvc mvc; @MockBean private MetricsRepository metrics; @Ignore @Test public void shouldQuerySingleSerie() throws Exception { List<String> series = Arrays.asList("test1"); Map<String, Point> result = new HashMap<>(); result.put("test1", new Point(1000, 24.7)); given(metrics.queryLastPoint(series)) .willReturn(Observable.just(result)); mvc .perform( post("/api/metrics/current") .contentType(MediaType.APPLICATION_JSON) .content("{\"metricIds\": [\"test1\"]}")) .andExpect(status().isOk()) .andExpect(content().json("{\"points\": {\"test1\": {\"time\": 1000, \"value\": 24.7}}}")); // TODO find out why this test doesn't work } @Ignore @Test public void shouldFail400WhenUnknownMetricId() throws Exception { List<String> series = Arrays.asList("unknown"); given(metrics.queryLastPoint(series)) .willThrow(new RuntimeException("unknown metricId")); mvc .perform( post("/api/metrics/current") .contentType(MediaType.APPLICATION_JSON) .content("{\"metricIds\": [\"unknown\"]}")) .andExpect(status().is4xxClientError()); // TODO make this test pass } }
gpl-3.0
marcosemiao/log4jdbc
core/log4jdbc-impl/src/main/java/fr/ms/log4jdbc/lang/reflect/TraceTimeInvocationHandler.java
3606
/* * This file is part of Log4Jdbc. * * Log4Jdbc 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. * * Log4Jdbc 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 Log4Jdbc. If not, see <http://www.gnu.org/licenses/>. * */ package fr.ms.log4jdbc.lang.reflect; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import fr.ms.log4jdbc.lang.delegate.DefaultStringMakerFactory; import fr.ms.log4jdbc.lang.delegate.DefaultSyncLongFactory; import fr.ms.log4jdbc.lang.delegate.StringMakerFactory; import fr.ms.log4jdbc.lang.delegate.SyncLongFactory; import fr.ms.log4jdbc.lang.stringmaker.impl.StringMaker; import fr.ms.log4jdbc.lang.sync.impl.SyncLong; import fr.ms.log4jdbc.util.logging.Logger; import fr.ms.log4jdbc.util.logging.LoggerManager; /** * * @see <a href="http://marcosemiao4j.wordpress.com">Marco4J</a> * * * @author Marco Semiao * */ public class TraceTimeInvocationHandler implements InvocationHandler { public final static Logger LOG = LoggerManager.getLogger(TraceTimeInvocationHandler.class); private final static StringMakerFactory stringFactory = DefaultStringMakerFactory.getInstance(); private final static SyncLongFactory syncLongFactory = DefaultSyncLongFactory.getInstance(); private final InvocationHandler invocationHandler; private static long maxTime; private static String maxMethodName; private static SyncLong averageTime = syncLongFactory.newLong(); private static SyncLong quotient = syncLongFactory.newLong(); public TraceTimeInvocationHandler(final InvocationHandler invocationHandler) { this.invocationHandler = invocationHandler; } public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { final long start = System.currentTimeMillis(); final TimeInvocation invokeTime = (TimeInvocation) invocationHandler.invoke(proxy, method, args); final long end = System.currentTimeMillis(); final long time = (end - start) - invokeTime.getExecTime(); final String methodName = getMethodCall(method.getDeclaringClass().getName() + "." + method.getName(), args); if (time > maxTime) { maxTime = time; maxMethodName = methodName; } averageTime.addAndGet(time); final StringMaker sb = stringFactory.newString(); sb.append("Time Process : "); sb.append(time); sb.append(" ms - Average Time : "); sb.append(averageTime.get() / quotient.incrementAndGet()); sb.append(" ms - Method Name : "); sb.append(methodName); sb.append(" - Max Time Process : "); sb.append(maxTime); sb.append(" ms - Max Method Name : "); sb.append(maxMethodName); LOG.debug(sb.toString()); return invokeTime.getWrapInvocation().getInvoke(); } public static String getMethodCall(final String methodName, final Object[] args) { final StringMaker sb = stringFactory.newString(); sb.append(methodName); sb.append("("); if (args != null) { for (int i = 0; i < args.length; i++) { final Object arg = args[i]; if (arg != null) { sb.append(arg.getClass()); if (i < args.length - 1) { sb.append(","); } } } } sb.append(");"); return sb.toString(); } }
gpl-3.0
karolusw/l2j
game/data/scripts/quests/Q00700_CursedLife/Q00700_CursedLife.java
6753
/* * This file is part of the L2J Mobius project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package quests.Q00700_CursedLife; import java.util.HashMap; import java.util.Map; import com.l2jmobius.gameserver.enums.QuestSound; import com.l2jmobius.gameserver.model.actor.L2Npc; import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance; import com.l2jmobius.gameserver.model.quest.Quest; import com.l2jmobius.gameserver.model.quest.QuestState; import com.l2jmobius.gameserver.model.quest.State; import quests.Q10273_GoodDayToFly.Q10273_GoodDayToFly; /** * Cursed Life (700) * @author xban1x */ public class Q00700_CursedLife extends Quest { // NPC private static final int ORBYU = 32560; // Monsters private static final int ROK = 25624; private static final Map<Integer, Integer[]> MONSTERS = new HashMap<>(); //@formatter:off static { MONSTERS.put(22602, new Integer[] { 15, 139, 965}); // Mutant Bird lvl 1 MONSTERS.put(22603, new Integer[] { 15, 143, 999}); // Mutant Bird lvl 2 MONSTERS.put(25627, new Integer[] { 14, 125, 993}); // Mutant Bird lvl 3 MONSTERS.put(22604, new Integer[] { 5, 94, 994}); // Dra Hawk lvl 1 MONSTERS.put(22605, new Integer[] { 5, 99, 993}); // Dra Hawk lvl 2 MONSTERS.put(25628, new Integer[] { 3, 73, 991}); // Dra Hawk lvl 3 } //@formatter:on // Items private static final int SWALLOWED_BONES = 13874; private static final int SWALLOWED_STERNUM = 13873; private static final int SWALLOWED_SKULL = 13872; // Misc private static final int MIN_LVL = 75; private static final int SWALLOWED_BONES_ADENA = 500; private static final int SWALLOWED_STERNUM_ADENA = 5000; private static final int SWALLOWED_SKULL_ADENA = 50000; private static final int BONUS = 16670; public Q00700_CursedLife() { super(700, Q00700_CursedLife.class.getSimpleName(), "Cursed Life"); addStartNpc(ORBYU); addTalkId(ORBYU); addKillId(ROK); addKillId(MONSTERS.keySet()); registerQuestItems(SWALLOWED_BONES, SWALLOWED_STERNUM, SWALLOWED_SKULL); } @Override public String onAdvEvent(String event, L2Npc npc, L2PcInstance player) { QuestState st = getQuestState(player, false); String htmltext = null; if (st != null) { switch (event) { case "32560-02.htm": { st = player.getQuestState(Q10273_GoodDayToFly.class.getSimpleName()); htmltext = ((player.getLevel() < MIN_LVL) || (st == null) || (!st.isCompleted())) ? "32560-03.htm" : event; break; } case "32560-04.htm": case "32560-09.html": { htmltext = event; break; } case "32560-05.htm": { st.startQuest(); htmltext = event; break; } case "32560-10.html": { st.exitQuest(true, true); htmltext = event; break; } } } return htmltext; } @Override public String onTalk(L2Npc npc, L2PcInstance player) { final QuestState st = getQuestState(player, true); String htmltext = getNoQuestMsg(player); if (st != null) { switch (st.getState()) { case State.CREATED: { htmltext = "32560-01.htm"; break; } case State.STARTED: { final long bones = st.getQuestItemsCount(SWALLOWED_BONES); final long ribs = st.getQuestItemsCount(SWALLOWED_STERNUM); final long skulls = st.getQuestItemsCount(SWALLOWED_SKULL); final long sum = bones + ribs + skulls; if (sum > 0) { st.giveAdena(((bones * SWALLOWED_BONES_ADENA) + (ribs * SWALLOWED_STERNUM_ADENA) + (skulls * SWALLOWED_SKULL_ADENA) + (sum >= 10 ? BONUS : 0)), true); takeItems(player, -1, SWALLOWED_BONES, SWALLOWED_STERNUM, SWALLOWED_SKULL); htmltext = sum < 10 ? "32560-07.html" : "32560-08.html"; } else { htmltext = "32560-06.html"; } break; } } } return htmltext; } @Override public String onKill(L2Npc npc, L2PcInstance player, boolean isSummon) { final QuestState st = getQuestState(player, false); if (st != null) { if (npc.getId() == ROK) { int amount = 0, chance = getRandom(1000); if (chance < 700) { amount = 1; } else if (chance < 885) { amount = 2; } else if (chance < 949) { amount = 3; } else if (chance < 966) { amount = getRandom(5) + 4; } else if (chance < 985) { amount = getRandom(9) + 4; } else if (chance < 993) { amount = getRandom(7) + 13; } else if (chance < 997) { amount = getRandom(15) + 9; } else if (chance < 999) { amount = getRandom(23) + 53; } else { amount = getRandom(49) + 76; } st.giveItems(SWALLOWED_BONES, amount); chance = getRandom(1000); if (chance < 520) { amount = 1; } else if (chance < 771) { amount = 2; } else if (chance < 836) { amount = 3; } else if (chance < 985) { amount = getRandom(2) + 4; } else if (chance < 995) { amount = getRandom(4) + 5; } else { amount = getRandom(8) + 6; } st.giveItems(SWALLOWED_STERNUM, amount); chance = getRandom(1000); if (chance < 185) { amount = getRandom(2) + 1; } else if (chance < 370) { amount = getRandom(6) + 2; } else if (chance < 570) { amount = getRandom(6) + 7; } else if (chance < 850) { amount = getRandom(6) + 12; } else { amount = getRandom(6) + 17; } st.giveItems(SWALLOWED_SKULL, amount); st.playSound(QuestSound.ITEMSOUND_QUEST_ITEMGET); } else { final Integer[] chances = MONSTERS.get(npc.getId()); final int chance = getRandom(1000); if (chance < chances[0]) { st.giveItems(SWALLOWED_BONES, 1); st.playSound(QuestSound.ITEMSOUND_QUEST_ITEMGET); } else if (chance < chances[1]) { st.giveItems(SWALLOWED_STERNUM, 1); st.playSound(QuestSound.ITEMSOUND_QUEST_ITEMGET); } else if (chance < chances[2]) { st.giveItems(SWALLOWED_SKULL, 1); st.playSound(QuestSound.ITEMSOUND_QUEST_ITEMGET); } } } return super.onKill(npc, player, isSummon); } }
gpl-3.0
LibertACAO/libertacao-android
app/src/main/java/com/libertacao/libertacao/manager/LoginManager.java
1546
package com.libertacao.libertacao.manager; import android.support.annotation.Nullable; import com.libertacao.libertacao.persistence.UserPreferences; import com.parse.ParseFacebookUtils; import com.parse.ParseUser; public class LoginManager { private static final LoginManager ourInstance = new LoginManager(); public static LoginManager getInstance() { return ourInstance; } private LoginManager() { } public boolean isLoggedIn(){ return ParseUser.getCurrentUser() != null; } public boolean isSuperAdmin() { if(isLoggedIn()) { int type = ParseUser.getCurrentUser().getInt("type"); if(type == 666) { return true; } } return false; } public boolean isAdmin() { if(isLoggedIn()) { int type = ParseUser.getCurrentUser().getInt("type"); if(type % 66 == 6) { return true; } } return false; } public void logout() { UserPreferences.clearSharedPreferences(); UserManager.getInstance().setCurrentLatLng(null); } @Nullable public String getUsername() { if(isLoggedIn()) { ParseUser currentUser = ParseUser.getCurrentUser(); if(ParseFacebookUtils.isLinked(currentUser)) { return currentUser.getString("name"); } else { return currentUser.getUsername(); } } else { return null; } } }
gpl-3.0
tohahn/UE_ML
UE06/gvgai/src/ontology/effects/unary/FlipDirection.java
786
package ontology.effects.unary; import core.VGDLSprite; import core.content.InteractionContent; import core.game.Game; import ontology.Types; import ontology.effects.Effect; import tools.Direction; import tools.Utils; import tools.Vector2d; /** * Created with IntelliJ IDEA. * User: Diego * Date: 03/12/13 * Time: 16:17 * This is a Java port from Tom Schaul's VGDL - https://github.com/schaul/py-vgdl */ public class FlipDirection extends Effect { public FlipDirection(InteractionContent cnt) { is_stochastic = true; this.parseParameters(cnt); } @Override public void execute(VGDLSprite sprite1, VGDLSprite sprite2, Game game) { sprite1.orientation = (Direction) Utils.choice(Types.DBASEDIRS, game.getRandomGenerator()); } }
gpl-3.0
puzis/kpp
src/topology/graphParsers/common/FileLister.java
1357
/** * */ package topology.graphParsers.common; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; /** * @author Omer Zohar * This class returns names of files with given extention for a given directory */ public class FileLister { private String m_sfilepath=null; private FilenameFilter m_filter= null; /** * */ public FileLister(String path, FilenameFilter filter) { m_sfilepath=path; m_filter=filter; } public String[] getfilesfromdir(){ File dir = null; try { dir = new File (m_sfilepath).getCanonicalFile(); } catch (IOException e) { System.out.println("Error getting canonical file"); e.printStackTrace(); } String[] s=new String[0]; if (dir.isDirectory()){ s=dir.list(m_filter); for (int i=0;i<s.length;i++) s[i]=m_sfilepath+s[i]; } else { System.out.println(m_sfilepath + "is not a directory."); } return s; } /** * @param args */ public static void main(String[] args) { FilenameFilter extFilter = new FilenameExtentionFilter("fvl"); FileLister f=new FileLister("D:\\Java\\Projects\\betweness\\res\\plankton\\www.ircache.net\\Plankton\\Data\\199810",extFilter); String[] s=f.getfilesfromdir(); for (int i=0;i<s.length;i++) System.out.println(s[i]); } }
gpl-3.0
Venom590/gradoop
gradoop-common/src/main/java/org/gradoop/common/model/api/entities/EPGMEdge.java
1396
/* * This file is part of Gradoop. * * Gradoop 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. * * Gradoop 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 Gradoop. If not, see <http://www.gnu.org/licenses/>. */ package org.gradoop.common.model.api.entities; import org.gradoop.common.model.impl.id.GradoopId; /** * Describes data assigned to an edge in the EPGM. */ public interface EPGMEdge extends EPGMGraphElement { /** * Returns the source vertex identifier. * * @return source vertex id */ GradoopId getSourceId(); /** * Sets the source vertex identifier. * * @param sourceId source vertex id */ void setSourceId(GradoopId sourceId); /** * Returns the target vertex identifier. * * @return target vertex id */ GradoopId getTargetId(); /** * Sets the target vertex identifier. * * @param targetId target vertex id. */ void setTargetId(GradoopId targetId); }
gpl-3.0
liyi-david/ePMC
plugins/command-help/src/main/java/epmc/command/UsagePrinterJANI.java
17019
/**************************************************************************** ePMC - an extensible probabilistic model checker Copyright (C) 2017 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ package epmc.command; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import epmc.util.Util; import epmc.jani.interaction.commandline.CommandLineCategory; import epmc.jani.interaction.commandline.CommandLineCommand; import epmc.jani.interaction.commandline.CommandLineOption; import epmc.jani.interaction.commandline.CommandLineOptions; /** * Class to print usage information about options set. * The usage information consists of a description of the parameters of the * options and commands of the options set, and how to use them. * * @author Ernst Moritz Hahn */ public final class UsagePrinterJANI { /** String containing "[program-options]". */ private final static String PROGRAM_OPTIONS_STRING = "[program-options]"; /** String containing "command". */ private final static String COMMAND_STRING = "command"; /** String containing dot. */ private final static String DOT = "."; /** String containing new line*/ private final static String NEWLINE = "\n"; /** Key in the resource file to read "Usage". */ private final static String COLON = ":"; /** String containing \0 */ private final static String NULL_STRING = "\0"; /** Empty string. */ private final static String EMPTY = ""; /** String containing single space character. */ private final static String SPACE = " "; /** String containing a single pipe character. */ private final static String PIPE = "|"; /** String containing smaller than character. */ private final static String SMALLER_THAN = "<"; /** String containing larger than character. */ private final static String LARGER_THAN = ">"; /** Prefix used for the options. */ private final static String OPTION_PREFIX = "--"; /** Maximal line length of the program options description */ private final static int MAX_LINE_LENGTH = 72; /** * First part of regular expression to split line into parts of given * length. To complete the sequence, this string shall be followed by a * number and then {@link #ALIGN_CHARS_REGEXP_SECOND}. * */ private static final String ALIGN_CHARS_REGEXP_FIRST = "(?<=\\G.{"; /** * Second part of regular expression to split line into parts of given * length, see {@link #ALIGN_CHARS_REGEXP_FIRST}. */ private static final String ALIGN_CHARS_REGEXP_SECOND = "})"; /** * Get usage information of the given options set. * The options parameter may not be {@code null}. * * @param options options to get usage information of * @return usage information of the given options set */ public static String getUsage(CommandLineOptions options) { assert options != null; StringBuilder builder = new StringBuilder(); appendCommands(builder, options); appendOptions(builder, options); return builder.toString(); } /** * Append information about the options commands to given string builder. * None of the parameters may be {@code null}. * * @param builder string builder to append information to * @param options options the command information shall be appended */ private static void appendCommands(StringBuilder builder, CommandLineOptions options) { assert builder != null; assert options != null; Locale locale = Locale.getDefault(); MessageFormat formatter = new MessageFormat(EMPTY); formatter.setLocale(locale); builder.append(options.getToolName() + COLON + SPACE); builder.append(options.getToolDescription() + NEWLINE + NEWLINE); String revision = Util.getManifestEntry(Util.SCM_REVISION); if (revision != null) { revision = revision.trim(); } if (revision != null && !revision.equals(EMPTY)) { formatter.applyPattern(options.getRunningToolRevisionPatter()); builder.append(formatter.format(new Object[]{options.getToolName(), revision}) + NEWLINE); } builder.append(options.getUsagePattern()); String usageString = COLON + SPACE + SMALLER_THAN + options.getToolCmdPattern() + LARGER_THAN + SPACE + SMALLER_THAN + COMMAND_STRING + LARGER_THAN + SPACE + PROGRAM_OPTIONS_STRING + NEWLINE + NEWLINE; builder.append(usageString); builder.append(options.getAvailableCommandsPattern() + COLON + NEWLINE); List<String> cmdStrings = new ArrayList<>(); int maxCmdStringSize = 0; for (String commandString : options.getCommands().keySet()) { String cmdStr = SPACE + SPACE + commandString + SPACE; maxCmdStringSize = Math.max(maxCmdStringSize, cmdStr.length()); cmdStrings.add(cmdStr); } maxCmdStringSize += 2; Iterator<CommandLineCommand> cmdIter = options.getCommands().values().iterator(); for (String formattedCommandStr : cmdStrings) { CommandLineCommand command = cmdIter.next(); String dots = dots(maxCmdStringSize - formattedCommandStr.length()); formattedCommandStr += dots + SPACE; formattedCommandStr += command.getShortDescription(); formattedCommandStr += NEWLINE; builder.append(formattedCommandStr); } builder.append(NEWLINE); } /** * Append information about the options of the given options set to builder. * None of the parameters may be {@code null}. * * @param builder string builder to append information to * @param options options the command information shall be appended */ private static void appendOptions(StringBuilder builder, CommandLineOptions options) { assert builder != null; assert options != null; Map<CommandLineCategory,Set<CommandLineOption>> optionsByCategory = buildOptionsByCategory(options); Map<CommandLineCategory,Set<CommandLineCategory>> hierarchy = buildHierarchy(options); builder.append(options.getAvailableProgramOptionsPattern() + COLON + NEWLINE); Collection<CommandLineOption> nonCategorisedOptions = optionsByCategory.get(null); for (CommandLineOption option : nonCategorisedOptions) { appendOption(builder, option, options, 0); } for (CommandLineCategory category : optionsByCategory.keySet()) { if (category == null || category.getParent() != null) { continue; } appendCategorisedOptions(builder, category, hierarchy, optionsByCategory, options, 0); } } private static void appendCategorisedOptions(StringBuilder builder, CommandLineCategory category, Map<CommandLineCategory, Set<CommandLineCategory>> hierarchy, Map<CommandLineCategory, Set<CommandLineOption>> optionsByCategory, CommandLineOptions options, int level) { assert hierarchy != null; Set<CommandLineOption> categorisedOptions = optionsByCategory.get(category); builder.append(spacify(category.getShortDescription() + COLON, 2 + 2 * level)); for (CommandLineOption option : categorisedOptions) { appendOption(builder, option, options, level + 1); } for (CommandLineCategory child : hierarchy.get(category)) { appendCategorisedOptions(builder, child, hierarchy, optionsByCategory, options, level + 1); } } private static void appendOption(StringBuilder builder, CommandLineOption option, CommandLineOptions options, int level) { assert builder != null; assert option != null; String topLine = buildOptionTopLine(option); builder.append(spacify(topLine, 2 + level * 2)); String description = alignWords(option.getShortDescription(), MAX_LINE_LENGTH - (6 + level * 2)); description = spacify(description, 6 + level * 2); builder.append(description); String typeLines = buildOptionTypeLines(options, option); typeLines = alignPiped(typeLines, MAX_LINE_LENGTH - (6 + level * 2)); typeLines = spacify(typeLines, 6 + level * 2); builder.append(typeLines); String defaultLines = buildOptionDefaultLines(options, option); if (defaultLines != null) { defaultLines = alignCharacters(defaultLines, MAX_LINE_LENGTH - (6 + level * 2)); defaultLines = spacify(defaultLines, 6 + level * 2); builder.append(defaultLines); } } private static Map<CommandLineCategory,Set<CommandLineCategory>> buildHierarchy(CommandLineOptions options) { assert options != null; Map<CommandLineCategory,Set<CommandLineCategory>> result = new LinkedHashMap<>(); for (CommandLineCategory category : options.getAllCategories().values()) { result.put(category, new LinkedHashSet<>()); } for (CommandLineCategory category : options.getAllCategories().values()) { CommandLineCategory parent = category.getParent(); if (parent == null) { continue; } result.get(parent).add(category); } return result; } private static Map<CommandLineCategory, Set<CommandLineOption>> buildOptionsByCategory( CommandLineOptions options) { assert options != null; Map<CommandLineCategory, Set<CommandLineOption>> result = new LinkedHashMap<>(); for (CommandLineOption option : options.getAllOptions().values()) { CommandLineCategory category = option.getCategory(); Set<CommandLineOption> catSet = result.get(category); if (catSet == null) { catSet = new LinkedHashSet<>(); result.put(category, catSet); } catSet.add(option); } return result; } /** * Create a string describing the type of a given option. * The internationalization information will read from resource bundle with * the given base name. The returned string is of the format * &quot;&lt;word-type-in-language&gt;: &lt;type-info&gt;&lt;newline&gt;. * None of the parameters may be {@code null}. * * @param resourceBundle base name of resource bundle * @param option option to get type info description of * @return string describing the type of a given option */ private static String buildOptionTypeLines(CommandLineOptions options, CommandLineOption option) { assert options != null; assert option != null; String typeInfo = options.getTypePattern() + COLON + SPACE + option.getTypeInfo() + NEWLINE; return typeInfo; } /** * Build string describing default value of given option. * The internationalization information will read from resource bundle with * the given base name. The returned string is of the format * &quot;&lt;word-default-in-language&gt;: &lt;default&gt;&lt;newline&gt;. * If the option does not have a default value, the method will return * {@code null}. * None of the parameters may be {@code null}. * * @param resourceBundle base name of resource bundle * @param option option to get default value description of * @return describing the default value of a given option or {@code null} */ private static String buildOptionDefaultLines(CommandLineOptions options, CommandLineOption option) { assert options != null; assert option != null; String defaultValue = option.getDefault(); String result = null; if (defaultValue != null && !defaultValue.equals(EMPTY)) { result = options.getDefaultPattern() + COLON + SPACE + defaultValue + SPACE + NEWLINE; } return result; } private static String buildOptionTopLine(CommandLineOption option) { String poStr = OPTION_PREFIX + option.getIdentifier() + SPACE; return poStr; } /** * Obtain a sequence of a give number of dots ("."). * The number of dots must be nonnegative. * * @param numDots length of sequence * @return sequence of a give number of dots (".") */ private static String dots(int numDots) { assert numDots >= 0; return new String(new char[numDots]).replace(NULL_STRING, DOT); } /** * Obtain a sequence of a give number of spaces (" "). * The number of spaces must be nonnegative. * * @param numSpaces length of sequence * @return sequence of a give number of spaces (" ") */ private static String spaces(int numSpaces) { assert numSpaces >= 0; return new String(new char[numSpaces]).replace(NULL_STRING, SPACE); } /** * Align lines by prefixing them by the given number of spaces. * The input string parameter may not be {@code null}, and the number of * spaces must be nonnegative. * * @param lines lines to align * @param numSpaces number of spaces to prefix lines with * @return aligned string */ private static String spacify(String lines, int numSpaces) { assert lines != null; assert numSpaces >= 0; String[] linesArray = lines.split(NEWLINE); StringBuilder result = new StringBuilder(); for (int lineNr = 0; lineNr < linesArray.length; lineNr++) { result.append(spaces(numSpaces) + linesArray[lineNr] + NEWLINE); } return result.toString(); } /** * Split string by words into lines not exceeding length limit. * The line length may be exceeded if there is a single word larger than * the given line length. The method only splits along word limits; it is * not able to perform hyphenation etc. * The string to split must not be {@code null}, and the maximal line length * must be positive. * * @param string string to split * @param maxLineLength maximal line length * @return split string */ private static String alignWords(String string, int maxLineLength) { return alignSplit(string, maxLineLength, SPACE); } private static String alignPiped(String string, int maxLineLength) { return alignSplit(string, maxLineLength, PIPE); } private static String alignSplit(String string, int maxLineLength, String split) { assert string != null; assert maxLineLength >= 1; String[] words = string.split(Pattern.quote(split)); StringBuilder result = new StringBuilder(); int lineLength = 0; for (String word : words) { lineLength += word.length() + 1; if (lineLength > maxLineLength) { result.append(NEWLINE); lineLength = word.length() + 1; } result.append(word + split); } result.delete(result.length() - 1, result.length()); return result.toString(); } /** * Split string into lines of given length along characters. * The string to split may not be {@code null}, and the maximal line length * must be positive. * * @param string string to split * @param maxLineLength maximal line length * @return split string */ private static String alignCharacters(String string, int maxLineLength) { assert string != null; assert maxLineLength >= 1; String[] lines = string.split(ALIGN_CHARS_REGEXP_FIRST + maxLineLength + ALIGN_CHARS_REGEXP_SECOND); StringBuilder result = new StringBuilder(); for (String line : lines) { result.append(line + NEWLINE); } return result.toString(); } /** * Private constructor to prevent instantiation. */ private UsagePrinterJANI() { } }
gpl-3.0
dordsor21/dordsentials
Essentials/src/com/earth2me/essentials/Warps.java
5560
package com.earth2me.essentials; import com.earth2me.essentials.commands.WarpNotFoundException; import com.earth2me.essentials.utils.StringUtil; import net.ess3.api.InvalidNameException; import net.ess3.api.InvalidWorldException; import org.bukkit.Location; import org.bukkit.Server; import java.io.File; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import static com.earth2me.essentials.I18n.tl; public class Warps implements IConf, net.ess3.api.IWarps { private static final Logger logger = Logger.getLogger("Essentials"); private final Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<StringIgnoreCase, EssentialsConf>(); private final File warpsFolder; private final Server server; public Warps(Server server, File dataFolder) { this.server = server; warpsFolder = new File(dataFolder, "warps"); if (!warpsFolder.exists()) { warpsFolder.mkdirs(); } reloadConfig(); } @Override public boolean isEmpty() { return warpPoints.isEmpty(); } @Override public Collection<String> getList() { final List<String> keys = new ArrayList<String>(); for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) { keys.add(stringIgnoreCase.getString()); } Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); return keys; } @Override public Location getWarp(String warp) throws WarpNotFoundException, InvalidWorldException { EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); if (conf == null) { throw new WarpNotFoundException(); } return conf.getLocation(null, server); } @Override public void setWarp(String name, Location loc) throws Exception { setWarp(null, name, loc); } @Override public void setWarp(IUser user, String name, Location loc) throws Exception { String filename = StringUtil.sanitizeFileName(name); EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); if (conf == null) { File confFile = new File(warpsFolder, filename + ".yml"); if (confFile.exists()) { throw new Exception(tl("similarWarpExist")); } conf = new EssentialsConf(confFile); warpPoints.put(new StringIgnoreCase(name), conf); } conf.setProperty(null, loc); conf.setProperty("name", name); if (user != null) conf.setProperty("lastowner", user.getBase().getUniqueId().toString()); try { conf.saveWithError(); } catch (IOException ex) { throw new IOException(tl("invalidWarpName")); } } @Override public UUID getLastOwner(String warp) throws WarpNotFoundException { EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); if (conf == null) { throw new WarpNotFoundException(); } UUID uuid = null; try { uuid = UUID.fromString(conf.getString("lastowner")); } catch (Exception ex) {} return uuid; } @Override public void removeWarp(String name) throws Exception { EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); if (conf == null) { throw new Exception(tl("warpNotExist")); } if (!conf.getFile().delete()) { throw new Exception(tl("warpDeleteError")); } warpPoints.remove(new StringIgnoreCase(name)); } @Override public final void reloadConfig() { warpPoints.clear(); File[] listOfFiles = warpsFolder.listFiles(); if (listOfFiles.length >= 1) { for (int i = 0; i < listOfFiles.length; i++) { String filename = listOfFiles[i].getName(); if (listOfFiles[i].isFile() && filename.endsWith(".yml")) { try { EssentialsConf conf = new EssentialsConf(listOfFiles[i]); conf.load(); String name = conf.getString("name"); if (name != null) { warpPoints.put(new StringIgnoreCase(name), conf); } } catch (Exception ex) { logger.log(Level.WARNING, tl("loadWarpError", filename), ex); } } } } } //This is here for future 3.x api support. Not implemented here becasue storage is handled differently @Override public File getWarpFile(String name) throws InvalidNameException { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getCount() { return getList().size(); } private static class StringIgnoreCase { private final String string; public StringIgnoreCase(String string) { this.string = string; } @Override public int hashCode() { return getString().toLowerCase(Locale.ENGLISH).hashCode(); } @Override public boolean equals(Object o) { if (o instanceof StringIgnoreCase) { return getString().equalsIgnoreCase(((StringIgnoreCase) o).getString()); } return false; } public String getString() { return string; } } }
gpl-3.0
Seikomi/Janus-Server
src/main/java/com/seikomi/janus/services/package-info.java
187
/** * This package contains the services of the server and the locator. * * @author Nicolas SYMPHORIEN (nicolas.symphorien@gmail.com) * */ package com.seikomi.janus.services;
gpl-3.0