repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
jj-io/jj-android
mylibrary/src/main/java/me/yugy/app/common/utils/StorageUtils.java
3221
package me.yugy.app.common.utils; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Environment; import android.os.StatFs; import java.io.File; import java.io.IOException; import static android.os.Environment.MEDIA_MOUNTED; /** * Created by yugy on 2014/7/4. */ public class StorageUtils { @SuppressWarnings("deprecation") @TargetApi(18) public static long getAvailableStorage() { String storageDirectory; storageDirectory = Environment.getExternalStorageDirectory().toString(); try { StatFs stat = new StatFs(storageDirectory); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { return ((long) stat.getAvailableBlocks() * (long) stat.getBlockSize()); }else{ return (stat.getAvailableBlocksLong() * stat.getBlockSizeLong()); } } catch (RuntimeException ex) { return 0; } } public static boolean isSDCardPresent() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } public static boolean isSdCardWrittable() { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return true; } return false; } public static File getCacheDirectory(Context context, boolean preferExternal) { File appCacheDir = null; if (preferExternal && MEDIA_MOUNTED .equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) { appCacheDir = getExternalCacheDir(context); } if (appCacheDir == null) { appCacheDir = context.getCacheDir(); } if (appCacheDir == null) { String cacheDirPath = context.getFilesDir().getPath() + "/cache/"; DebugUtils.log("Can't define system cache directory! " + cacheDirPath + " will be used."); appCacheDir = new File(cacheDirPath); } return appCacheDir; } private static boolean hasExternalStoragePermission(Context context) { int perm = context.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE"); return perm == PackageManager.PERMISSION_GRANTED; } private static File getExternalCacheDir(Context context) { File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data"); File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache"); if (!appCacheDir.exists()) { if (!appCacheDir.mkdirs()) { DebugUtils.log("Unable to create external cache directory"); return null; } try { new File(appCacheDir, ".nomedia").createNewFile(); } catch (IOException e) { DebugUtils.log("Can't create \".nomedia\" file in application external cache directory"); } } return appCacheDir; } }
gpl-2.0
msmobility/silo
siloCore/src/main/java/de/tum/bgu/msm/utils/DeferredAcceptanceMatching.java
2026
package de.tum.bgu.msm.utils; import cern.colt.matrix.tdouble.DoubleMatrix2D; import org.matsim.core.utils.collections.Tuple; import java.util.*; public class DeferredAcceptanceMatching { public static Map<Integer, Integer> match(Collection<Integer> set1, Collection<Integer> set2, DoubleMatrix2D preferences) { Map<Integer, Integer> matches; do { matches = iteration(set1, set2, preferences); } while (matches.size() < set1.size()); return matches; } private static Map<Integer, Integer> iteration(Collection<Integer> set, Collection<Integer> set2, DoubleMatrix2D preferences) { Map<Integer, Integer> matches = new HashMap<>(); Map<Integer, List<Tuple<Integer, Double>>> offers = new HashMap<>(); for (int id: set) { double[] max = preferences.viewRow(id).getMaxLocation(); if (offers.containsKey((int) max[1])) { offers.get((int) max[1]).add(new Tuple<>(id, max[0])); } else { List<Tuple<Integer, Double>> list = new ArrayList<>(); list.add(new Tuple<>(id, max[0])); offers.put((int) max[1], list); } } for (Integer id : set2) { if (offers.containsKey(id)) { List<Tuple<Integer, Double>> personalOffers = offers.get(id); if (!personalOffers.isEmpty()) { Tuple<Integer, Double> maxOffer = personalOffers.stream().max(Comparator.comparing(Tuple::getSecond)).get(); matches.put(id, maxOffer.getFirst()); personalOffers.remove(maxOffer); for (Tuple<Integer, Double> offer : personalOffers) { preferences.setQuick(offer.getFirst(), id, 0); } } } } return matches; } }
gpl-2.0
ParallelAndReconfigurableComputing/Pyjama
test/PyjamaCode/TestingDirectives/Sections/section_positive_test1.java
10076
//Pyjama compiler version:v1.5.3 package PyjamaCode.TestingDirectives.Sections; import pj.Pyjama; import pj.pr.*; import pj.PjRuntime; import pj.Pyjama; import pi.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import javax.swing.SwingUtilities; import java.lang.reflect.InvocationTargetException; import pj.pr.exceptions.OmpParallelRegionLocalCancellationException; public class section_positive_test1 { /** * return 2 because nomater how many threads are allowed there are only two section * */ public int[] parallel_sections(int threadNumber) {{ Pyjama.omp_set_num_threads(threadNumber); int[] array = new int[threadNumber]; int index = 0; /*OpenMP Parallel region (#0) -- START */ InternalControlVariables icv_previous__OMP_ParallelRegion_0 = PjRuntime.getCurrentThreadICV(); InternalControlVariables icv__OMP_ParallelRegion_0 = PjRuntime.inheritICV(icv_previous__OMP_ParallelRegion_0); int _threadNum__OMP_ParallelRegion_0 = icv__OMP_ParallelRegion_0.nthreads_var.get(icv__OMP_ParallelRegion_0.levels_var); ConcurrentHashMap<String, Object> inputlist__OMP_ParallelRegion_0 = new ConcurrentHashMap<String,Object>(); ConcurrentHashMap<String, Object> outputlist__OMP_ParallelRegion_0 = new ConcurrentHashMap<String,Object>(); inputlist__OMP_ParallelRegion_0.put("array",array); inputlist__OMP_ParallelRegion_0.put("index",index); _OMP_ParallelRegion_0 _OMP_ParallelRegion_0_in = new _OMP_ParallelRegion_0(_threadNum__OMP_ParallelRegion_0,icv__OMP_ParallelRegion_0,inputlist__OMP_ParallelRegion_0,outputlist__OMP_ParallelRegion_0); _OMP_ParallelRegion_0_in.runParallelCode(); array = (int[])outputlist__OMP_ParallelRegion_0.get("array"); index = (Integer)outputlist__OMP_ParallelRegion_0.get("index"); PjRuntime.recoverParentICV(icv_previous__OMP_ParallelRegion_0); RuntimeException OMP_ee_0 = (RuntimeException) _OMP_ParallelRegion_0_in.OMP_CurrentParallelRegionExceptionSlot.get(); if (OMP_ee_0 != null) {throw OMP_ee_0;} /*OpenMP Parallel region (#0) -- END */ return array; } } class _OMP_ParallelRegion_0{ private int OMP_threadNumber = 1; private InternalControlVariables icv; private ConcurrentHashMap<String, Object> OMP_inputList = new ConcurrentHashMap<String, Object>(); private ConcurrentHashMap<String, Object> OMP_outputList = new ConcurrentHashMap<String, Object>(); private ReentrantLock OMP_lock; private ParIterator<?> OMP__ParIteratorCreator; public AtomicReference<Throwable> OMP_CurrentParallelRegionExceptionSlot = new AtomicReference<Throwable>(null); //#BEGIN shared variables defined here int[] array = null; int index = 0; //#END shared variables defined here public _OMP_ParallelRegion_0(int thread_num, InternalControlVariables icv, ConcurrentHashMap<String, Object> inputlist, ConcurrentHashMap<String, Object> outputlist) { this.icv = icv; if ((false == Pyjama.omp_get_nested()) && (Pyjama.omp_get_level() > 0)) { this.OMP_threadNumber = 1; }else { this.OMP_threadNumber = thread_num; } this.OMP_inputList = inputlist; this.OMP_outputList = outputlist; icv.currentParallelRegionThreadNumber = this.OMP_threadNumber; icv.OMP_CurrentParallelRegionBarrier = new PjCyclicBarrier(this.OMP_threadNumber); //#BEGIN shared variables initialised here array = (int[])OMP_inputList.get("array"); index = (Integer)OMP_inputList.get("index"); //#END shared variables initialised here } private void updateOutputListForSharedVars() { //BEGIN update outputlist OMP_outputList.put("array",array); OMP_outputList.put("index",index); //END update outputlist } class MyCallable implements Callable<ConcurrentHashMap<String,Object>> { private int alias_id; private ConcurrentHashMap<String, Object> OMP_inputList; private ConcurrentHashMap<String, Object> OMP_outputList; //#BEGIN private/firstprivate reduction variables defined here //#END private/firstprivate reduction variables defined here MyCallable(int id, ConcurrentHashMap<String,Object> inputlist, ConcurrentHashMap<String,Object> outputlist){ this.alias_id = id; this.OMP_inputList = inputlist; this.OMP_outputList = outputlist; //#BEGIN firstprivate reduction variables initialised here //#END firstprivate reduction variables initialised here } @Override public ConcurrentHashMap<String,Object> call() { try { /****User Code BEGIN***/ /*OpenMP Work Share region (#0) -- START */ {//#BEGIN firstprivate lastprivate reduction variables defined and initialized here //#set implicit barrier here, otherwise unexpected initial value happens PjRuntime.setBarrier(); //#END firstprivate lastprivate reduction variables defined and initialized here try{ int _OMP_VANCY_ITERATOR_=0; int OMP_iterator = 0; int OMP_end = (int)((2)-(0))/(1); if (((2)-(0))%(1) == 0) { OMP_end = OMP_end - 1; } if (0 == Pyjama.omp_get_thread_num()) { PjRuntime.get_OMP_loopCursor().getAndSet(0);} PjRuntime.setBarrier(); while ((OMP_iterator = PjRuntime.get_OMP_loopCursor().getAndAdd(1)) <= OMP_end) { for (int OMP_local_iterator = OMP_iterator; OMP_local_iterator<OMP_iterator+1 && OMP_local_iterator<=OMP_end; OMP_local_iterator++){ _OMP_VANCY_ITERATOR_ = 0 + OMP_local_iterator * (1); switch(_OMP_VANCY_ITERATOR_) { case 0: { index = Pyjama.omp_get_thread_num(); array[index] += 1; } break; case 1: { index = Pyjama.omp_get_thread_num(); array[index] += 1; } break; default: break; }if (OMP_end == OMP_local_iterator) { //BEGIN lastprivate variables value set //END lastprivate variables value set } } } } catch (pj.pr.exceptions.OmpWorksharingLocalCancellationException wse){ } catch (Exception e){throw e;} //BEGIN reduction PjRuntime.reductionLockForWorksharing.lock(); PjRuntime.reductionLockForWorksharing.unlock();//END reduction PjRuntime.setBarrier(); } PjRuntime.setBarrier(); PjRuntime.reset_OMP_orderCursor(); /*OpenMP Work Share region (#0) -- END */ /****User Code END***/ //BEGIN reduction procedure //END reduction procedure PjRuntime.setBarrier(); } catch (OmpParallelRegionLocalCancellationException e) { PjRuntime.decreaseBarrierCount(); } catch (Exception e) { PjRuntime.decreaseBarrierCount(); PjExecutor.cancelCurrentThreadGroup(); OMP_CurrentParallelRegionExceptionSlot.compareAndSet(null, e); } if (0 == this.alias_id) { updateOutputListForSharedVars(); } return null; } } public void runParallelCode() { for (int i = 1; i <= this.OMP_threadNumber-1; i++) { Callable<ConcurrentHashMap<String,Object>> slaveThread = new MyCallable(i, OMP_inputList, OMP_outputList); PjRuntime.submit(i, slaveThread, icv); } Callable<ConcurrentHashMap<String,Object>> masterThread = new MyCallable(0, OMP_inputList, OMP_outputList); PjRuntime.getCurrentThreadICV().currentThreadAliasID = 0; try { masterThread.call(); } catch (Exception e) { e.printStackTrace(); } } } }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/jackson/com/fasterxml/jackson/databind/deser/NullValueProvider.java
1303
package com.fasterxml.jackson.databind.deser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.util.AccessPattern; /** * Helper interface implemented by classes that are to be used as * null providers during deserialization. Most importantly implemented by * {@link com.fasterxml.jackson.databind.JsonDeserializer} (as a mix-in * interface), but also by converters used to support more configurable * null replacement. * * @since 2.9 */ public interface NullValueProvider { /** * Method called to possibly convert incoming `null` token (read via * underlying streaming input source) into other value of type accessor * supports. May return `null`, or value compatible with type binding. *<p> * NOTE: if {@link #getNullAccessPattern()} returns `ALWAYS_NULL` or * `CONSTANT`, this method WILL NOT use provided `ctxt` and it may thus * be passed as `null`. */ public Object getNullValue(DeserializationContext ctxt) throws JsonMappingException; /** * Accessor that may be used to determine if and when provider must be called to * access null replacement value. */ public AccessPattern getNullAccessPattern(); }
gpl-2.0
iucn-whp/world-heritage-outlook
portlets/iucn-dbservice-portlet/docroot/WEB-INF/service/com/iucn/whp/dbservice/NoSuch_sites_countryException.java
1074
/** * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.iucn.whp.dbservice; import com.liferay.portal.NoSuchModelException; /** * @author alok.sen */ public class NoSuch_sites_countryException extends NoSuchModelException { public NoSuch_sites_countryException() { super(); } public NoSuch_sites_countryException(String msg) { super(msg); } public NoSuch_sites_countryException(String msg, Throwable cause) { super(msg, cause); } public NoSuch_sites_countryException(Throwable cause) { super(cause); } }
gpl-2.0
HotswapProjects/HotswapAgent
hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/WritableResource.java
1809
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hotswap.agent.util.spring.io.resource; import java.io.IOException; import java.io.OutputStream; /** * Extended interface for a resource that supports writing to it. Provides an * {@link #getOutputStream() OutputStream accessor}. * * @author Juergen Hoeller * @since 3.1 * @see java.io.OutputStream */ public interface WritableResource extends Resource { /** * Return whether the contents of this resource can be modified, e.g. via * {@link #getOutputStream()} or {@link #getFile()}. * <p> * Will be {@code true} for typical resource descriptors; note that actual * content writing may still fail when attempted. However, a value of * {@code false} is a definitive indication that the resource content cannot * be modified. * * @see #getOutputStream() * @see #isReadable() */ boolean isWritable(); /** * Return an {@link OutputStream} for the underlying resource, allowing to * (over-)write its content. * * @throws IOException * if the stream could not be opened * @see #getInputStream() */ OutputStream getOutputStream() throws IOException; }
gpl-2.0
flyroom/PeerfactSimKOM_Clone
src/org/peerfact/impl/application/infodissemination/moveModels/IMoveModel.java
1841
/* * Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org> * Copyright (c) 2011-2012 University of Paderborn - UPB * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * * This file is part of PeerfactSim.KOM. * * PeerfactSim.KOM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * PeerfactSim.KOM 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 PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * */ package org.peerfact.impl.application.infodissemination.moveModels; import java.awt.Point; import org.peerfact.impl.application.infodissemination.IDOApplication; /** * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * This part of the Simulator is not maintained in the current version of * PeerfactSim.KOM. There is no intention of the authors to fix this * circumstances, since the changes needed are huge compared to overall benefit. * * If you want it to work correctly, you are free to make the specific changes * and provide it to the community. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!! * * This interface is used to allow the interchangeability of the move model for * the peers. * * @author Julius Rueckert <peerfact@kom.tu-darmstadt.de> * @version 01/06/2011 * */ public interface IMoveModel { public Point getNextPosition(IDOApplication app); }
gpl-2.0
mwalercz/sicxe-sim-mvn
src/main/java/sicxe/model/simulator/assembler/command/bits/FormatFourBits.java
563
package sicxe.model.simulator.assembler.command.bits; /** * Created by maciek on 14/01/16. */ public class FormatFourBits extends Bits{ private final int e = 1 << 20; private final int b = 0; private final int p = 0; private int x = 0; public int getX() { return x; } public void setX() { this.x = 1 << 23; } public void zeroX(){ this.x = 0; } public int getE() { return e; } public int getB() { return b; } public int getP() { return p; } }
gpl-2.0
nazareno/diferentonas-server
app/controllers/AtualizacaoController.java
4867
package controllers; import static akka.pattern.Patterns.ask; import static play.libs.Json.toJson; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Date; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import models.Atualizacao; import models.AtualizacaoDAO; import models.CidadaoDAO; import play.Configuration; import play.Logger; import play.db.jpa.JPAApi; import play.db.jpa.Transactional; import play.libs.ws.WSClient; import play.libs.ws.WSRequest; import play.mvc.Controller; import play.mvc.Result; import scala.concurrent.duration.Duration; import actors.AtualizadorActorProtocol; import akka.actor.ActorRef; import akka.actor.ActorSystem; @Singleton public class AtualizacaoController extends Controller { private ActorRef atualizador; private AtualizacaoDAO daoAtualizacao; private WSRequest atualizacaoURL; private Pattern padraoDaDataDePublicacao; private JPAApi jpaAPI; private boolean atualizacaoAtivada; private String identificadorUnicoDoServidor; private String dataVotada; @Inject public AtualizacaoController(AtualizacaoDAO daoAtualizacao, CidadaoDAO daoCidadao, @Named("atualizador-actor") ActorRef atualizador, ActorSystem system, Configuration configuration, WSClient client, JPAApi jpaAPI) { this.daoAtualizacao = daoAtualizacao; this.atualizador = atualizador; this.jpaAPI = jpaAPI; this.atualizacaoAtivada = configuration.getBoolean("diferentonas.atualizacao.automatica", false); if(atualizacaoAtivada){ LocalDateTime now = LocalDateTime.now(); LocalDateTime manha = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 6, 0); LocalDateTime noite = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 18, 0); long delay; if(now.isBefore(manha)){ delay = manha.atZone(ZoneOffset.systemDefault()).toEpochSecond() - now.atZone(ZoneOffset.systemDefault()).toEpochSecond(); }else if(now.isBefore(noite)){ delay = noite.atZone(ZoneOffset.systemDefault()).toEpochSecond() - now.atZone(ZoneOffset.systemDefault()).toEpochSecond(); }else{ delay = manha.plusDays(1).atZone(ZoneOffset.systemDefault()).toEpochSecond() - now.atZone(ZoneOffset.systemDefault()).toEpochSecond(); } system.scheduler().schedule(Duration.create(delay, TimeUnit.SECONDS), Duration.create(12, TimeUnit.HOURS), () -> { this.votaEmLider(); }, system.dispatcher()); system.scheduler().schedule(Duration.create(delay + 3600, TimeUnit.SECONDS), Duration.create(12, TimeUnit.HOURS), () -> { this.elegeLiderEAtualiza(); }, system.dispatcher()); this.atualizacaoURL = client.url(configuration.getString("diferentonas.url", "http://portal.convenios.gov.br/download-de-dados")); this.padraoDaDataDePublicacao = Pattern.compile("\\d\\d\\/\\d\\d\\/\\d\\d\\d\\d\\s\\d\\d:\\d\\d:\\d\\d"); this.identificadorUnicoDoServidor = UUID.randomUUID().toString(); Logger.info("ID do servidor: " + this.identificadorUnicoDoServidor); if(configuration.getBoolean("diferentonas.demo.forcaatualizacao", false)){ Logger.info("Iniciando votação extraordinária!"); this.votaEmLider(); try { Thread.sleep(10000); } catch (InterruptedException e) { Logger.error("Dormiu durante a eleição!", e); } Logger.info("Elegendo lider para atualização de urgência!"); this.elegeLiderEAtualiza(); } } } private void votaEmLider() { atualizacaoURL.get().thenApply(response -> { Logger.info("Conexão realizada."); String body = response.getBody(); Matcher matcher = padraoDaDataDePublicacao.matcher(body); if(matcher.find()){ String data = matcher.group(0); this.dataVotada = data; Logger.info("Votando para " + data + " em " + identificadorUnicoDoServidor); jpaAPI.withTransaction(()->daoAtualizacao.vota(data, identificadorUnicoDoServidor)); }else{ Logger.info("Problemas ao acessar página em: " + atualizacaoURL.getUrl()); } return ok(); }); } private void elegeLiderEAtualiza() { Atualizacao lider = jpaAPI.withTransaction(()->daoAtualizacao.getLider(dataVotada)); if(lider == null){ Logger.warn("Impossível eleger lider! Não houveram votos para data: " + dataVotada); return; } if(this.identificadorUnicoDoServidor.equals(lider.getServidorResponsavel())){ Logger.info("Iniciando atualização de dados às: " + new Date() + " com dados publicados em: " + dataVotada); ask(atualizador, new AtualizadorActorProtocol.AtualizaIniciativasEScores(dataVotada, identificadorUnicoDoServidor), 1000L); } } @Transactional public Result getStatus() { return ok(toJson(daoAtualizacao.getMaisRecentes())); } }
gpl-2.0
zyclonite/nassh-relay
src/main/java/net/zyclonite/nassh/util/RequestHelper.java
953
/* * nassh-relay - Relay Server for tunneling ssh through a http endpoint * * Website: https://github.com/zyclonite/nassh-relay * * Copyright 2014-2020 zyclonite networx * http://zyclonite.net * Developer: Lukas Prettenthaler */ package net.zyclonite.nassh.util; import io.vertx.core.http.HttpServerRequest; public class RequestHelper { private RequestHelper() { // } public static String getHost(final HttpServerRequest request) { if (request.headers().contains("X-Forwarded-Host")) { return request.headers().get("X-Forwarded-Host"); } else { return request.host(); } } public static String getRemoteHost(final HttpServerRequest request) { if (request.headers().contains("X-Real-IP")) { return request.headers().get("X-Real-IP"); } else { return request.remoteAddress().host(); } } }
gpl-2.0
a97381416/jack.github.io
my_project/springcloud/jack-spring-cloud/jack-consomer-movie-ribbon/src/main/java/com/jack/cloud/movie/ConsumerMovieRibbonApplication.java
897
package com.jack.cloud.movie; import com.jack.cloud.config.TestConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableEurekaClient @RibbonClient(name = "provider-user", configuration = TestConfiguration.class) public class ConsumerMovieRibbonApplication { @Bean @LoadBalanced // ribbon 注解 public RestTemplate restTemplate(){ return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ConsumerMovieRibbonApplication.class, args); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest05767.java
2444
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest05767") public class BenchmarkTest05767 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] values = request.getParameterValues("foo"); String param; if (values.length != 0) param = request.getParameterValues("foo")[0]; else param = null; String bar; // Simple if statement that assigns constant to bar on true condition int i = 86; if ( (7*42) - i > 200 ) bar = "This_should_always_happen"; else bar = param; try { java.util.Random numGen = java.security.SecureRandom.getInstance("SHA1PRNG"); boolean randNumber = getNextNumber(numGen); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing SecureRandom.nextBoolean() - TestCase"); throw new ServletException(e); } response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextBoolean() executed"); } boolean getNextNumber(java.util.Random generator) { return generator.nextBoolean(); } }
gpl-2.0
uttmkl/etno
sites/all/modules/CKFinder/ckfinder/_sources/CKFinder for Java/CKFinder/src/main/java/com/ckfinder/connector/package-info.java
500
/** * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2013, CKSource - Frederico Knabben. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. */ /** * CKFinder for Java - server connector. */ package com.ckfinder.connector;
gpl-2.0
MultiTool/Clay
src/clay/Things.java
9794
/* * 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 clay; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * * @author MultiTool Need spring force of repulsion, spring force of attraction also need binding radius and un-binding (bond breaking) radius. */ public class Things { public static int NDims = 2; /* **************************************************************************** */ public static class Point { double[] V = new double[NDims]; /* **************************************************************************** */ public double Magnitude() {// pythagoras double dif, sumsq = 0.0; for (int dcnt = 0; dcnt < NDims; dcnt++) { dif = this.V[dcnt]; sumsq += dif * dif; } return Math.sqrt(sumsq); } /* **************************************************************************** */ public double DeltaMag(Point other) {// pythagoras double dif, sumsq = 0.0; for (int dcnt = 0; dcnt < NDims; dcnt++) { dif = this.V[dcnt] - other.V[dcnt]; sumsq += dif * dif; } return Math.sqrt(sumsq); } /* **************************************************************************** */ public void DeltaVec(Point origin, Point diff) { for (int dcnt = 0; dcnt < NDims; dcnt++) { diff.V[dcnt] = this.V[dcnt] - origin.V[dcnt]; } } /* **************************************************************************** */ public void AddVec(Point other) { for (int dcnt = 0; dcnt < NDims; dcnt++) { this.V[dcnt] += other.V[dcnt]; } } /* **************************************************************************** */ public void Unitize() { double length = this.Magnitude(); for (int dcnt = 0; dcnt < NDims; dcnt++) { this.V[dcnt] = this.V[dcnt] / length; } } /* **************************************************************************** */ public void Multiply(double magnitude) { for (int dcnt = 0; dcnt < NDims; dcnt++) { this.V[dcnt] *= magnitude; } } /* **************************************************************************** */ public void Clear() { for (int dcnt = 0; dcnt < NDims; dcnt++) { this.V[dcnt] = 0.0; } } /* **************************************************************************** */ public void Copy(Point other) { System.arraycopy(other.V, 0, this.V, 0, NDims); } } /* **************************************************************************** */ public static class SpringVec extends Point { public int GenStamp; } /* **************************************************************************** */ public static class Link { public Atom mine; public Link parallel; public static double RestingRadius = 10; public static double Radius = 5.0; public static double BindingRadius = 5.0; public static double BreakingRadius = BindingRadius + 1.0; public SpringVec Spring; // should we have two links between atoms or one? // with a planet/grav model, two gravity wells would fit // a spring is symmetrical. public void InterLink(Link other) { other.parallel = this; this.parallel = other; other.Spring = this.Spring = new SpringVec();// to do: rewrite this for single two-way links rather than twin links. } public Atom GetOtherAtom() { return this.parallel.mine; } public void CalcForceVector(Point Delta) { Point diffv; double distortion, dif; Atom me = this.mine; Atom you = this.GetOtherAtom(); diffv = new Point(); me.Loc.DeltaVec(you.Loc, diffv); dif = diffv.Magnitude(); distortion = dif - Link.RestingRadius;// distortion is displacement from resting length of spring diffv.Unitize(); diffv.Multiply(-distortion);// to do: since this force is applied once to each atom, the displacement back to resting is wrongly doubled // other issue is that we are wastefully calculating the dif vector twice, once for each end of the link pair. // a = f/m // the link pair COULD have a common storage object that keeps reusable info such as vector. baroque. // get locations of both of my ends // get my distortion from my resting length // normalize my direction vector, multiply by magnitude of distortion. } } /* **************************************************************************** */ public static class Atom { // public double Radius = 5.0; // public double BindingRadius = 5.0; // public double BreakingRadius = BindingRadius + 1.0; public Point Loc = new Point(); public Point LocNext = new Point(); public Point Vel = new Point(); public Map<Atom, Link> Bindings; public Atom() { this.Bindings = new HashMap<>(); } public void Bind(Atom other) { Link OtherLnk = new Link(); OtherLnk.mine = other; Link MeLnk = new Link(); MeLnk.mine = this; MeLnk.InterLink(OtherLnk); this.Bindings.put(other, MeLnk); other.Bindings.put(this, OtherLnk); } public void Rollover() { this.Loc.Copy(this.LocNext); } /* **************************************************************************** */ public void Seek_Bindings(Atom[] Atoms) { Atom you;// ultimately replace this with 2d array-based collision detection. double dif; int NumAtoms = Atoms.length; for (int acnt1 = 0; acnt1 < NumAtoms; acnt1++) { you = Atoms[acnt1]; if (this != you) { if (!this.Bindings.containsKey(you)) {// Find out if you are already connected to me. dif = this.Loc.DeltaMag(you.Loc); if (dif < Link.BindingRadius) {// if not bound, then bind this.Bind(you); } } } } } /* **************************************************************************** */ public void Seek_Unbindings() { Atom YouAtom; Link MeLnk; double dif; Iterator it = this.Bindings.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); MeLnk = (Link) pair.getValue(); // System.out.println(pair.getKey() + " = " + pair.getValue()); //YouAtom = MeLnk.GetOtherAtom(); YouAtom = (Atom) pair.getKey(); dif = this.Loc.DeltaMag(YouAtom.Loc); if (dif > Link.BreakingRadius) {// if bound, then break // here we remove from my table via iterator, and from your table via remove(key) YouAtom.Bindings.remove(this); it.remove(); MeLnk.mine = null; MeLnk.parallel.mine = null; } } } } /* **************************************************************************** */ public int NumAtoms = 100; public Atom[] Atoms; public int GenCnt = 0; /* **************************************************************************** */ public Things() { Atoms = new Atom[NumAtoms]; } /* **************************************************************************** */ public void React() { GenCnt++; Atom me; Link MeLnk; Point DiffV = new Point(); for (int acnt0 = 0; acnt0 < NumAtoms; acnt0++) { me = this.Atoms[acnt0]; me.LocNext.Clear(); Map<Atom, Link> yall = me.Bindings; int younum = yall.size(); for (int acnt1 = 0; acnt1 < younum; acnt1++) { MeLnk = yall.get(acnt1); if (MeLnk.Spring.GenStamp < GenCnt) { MeLnk.CalcForceVector(DiffV);// f=ma but m is always 1 for now MeLnk.Spring.Copy(DiffV); MeLnk.Spring.GenStamp = GenCnt; } // to do: gotta fix this so force is going opposite directions for each end of the spring me.LocNext.AddVec(MeLnk.Spring);// Accumulate all displacements into my next move. //you = MeLnk.GetOtherAtom(); dif = me.Loc.DeltaMag(you.Loc); // do physics here // spring physics, then define new locations and speeds // phys 0: go through all my neighbors and see which springs are bent. apply force to myself accordingly for each spring. // phys 1: after all personal next locs are calculated, then rollover for everybody. } } } /* **************************************************************************** */ public void Rebind() { Atom me; for (int acnt0 = 0; acnt0 < NumAtoms; acnt0++) { me = this.Atoms[acnt0]; /* I can scan all nbrs for new bindings. Though I only need to scan my own connections for UNbindings. so I'm already pointing to the link in question when/if I want to break it. */ me.Seek_Unbindings(); me.Seek_Bindings(this.Atoms); } } } /* Set<String> keys = hm.keySet(); for(String key: keys){ System.out.println("Value of "+key+" is: "+hm.get(key)); } Enumeration e = ht.elements(); while (e.hasMoreElements()){ System.out.println(e.nextElement()); } public static void printMap(Map mp) {// http://stackoverflow.com/questions/1066589/iterate-through-a-hashmap Iterator it = mp.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); System.out.println(pair.getKey() + " = " + pair.getValue()); it.remove(); // avoids a ConcurrentModificationException } } for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // ... } for (Object value : map.values()) { // ... } */
gpl-2.0
chbrown/stanford-parser
edu/stanford/nlp/parser/lexparser/Options.java
45340
package edu.stanford.nlp.parser.lexparser; import edu.stanford.nlp.trees.CompositeTreeTransformer; import edu.stanford.nlp.trees.TreebankLanguagePack; import edu.stanford.nlp.trees.TreeTransformer; import edu.stanford.nlp.util.Function; import edu.stanford.nlp.util.ReflectionLoading; import edu.stanford.nlp.util.StringUtils; import java.io.*; import java.util.*; import org.apache.log4j.Logger; /** * This class contains options to the parser which MUST be the SAME at * both training and testing (parsing) time in order for the parser to * work properly. It also contains an object which stores the options * used by the parser at training time and an object which contains * default options for test use. * * @author Dan Klein * @author Christopher Manning * @author John Bauer */ public class Options implements Serializable { protected static Logger logger = Logger.getRootLogger(); public Options() { this(new EnglishTreebankParserParams()); } public Options(TreebankLangParserParams tlpParams) { this.tlpParams = tlpParams; } /** * Set options based on a String array in the style of * commandline flags. This method goes through the array until it ends, * processing options, as for {@link #setOption}. * * @param flags Array of options (or as a varargs list of arguments). * The options passed in should * be specified like command-line arguments, including with an initial * minus sign for example, * {"-outputFormat", "typedDependencies", "-maxLength", "70"} * @throws IllegalArgumentException If an unknown flag is passed in */ public void setOptions(String... flags) { setOptions(flags, 0, flags.length); } /** * Set options based on a String array in the style of * commandline flags. This method goes through the array until it ends, * processing options, as for {@link #setOption}. * * @param flags Array of options. The options passed in should * be specified like command-line arguments, including with an initial * minus sign for example, * {"-outputFormat", "typedDependencies", "-maxLength", "70"} * @param startIndex The index in the array to begin processing options at * @param endIndexPlusOne A number one greater than the last array index at * which options should be processed * @throws IllegalArgumentException If an unknown flag is passed in */ public void setOptions(final String[] flags, final int startIndex, final int endIndexPlusOne) { for (int i = startIndex; i < endIndexPlusOne;) { i = setOption(flags, i); } } /** * Set options based on a String array in the style of * commandline flags. This method goes through the array until it ends, * processing options, as for {@link #setOption}. * * @param flags Array of options (or as a varargs list of arguments). * The options passed in should * be specified like command-line arguments, including with an initial * minus sign for example, * {"-outputFormat", "typedDependencies", "-maxLength", "70"} * @throws IllegalArgumentException If an unknown flag is passed in */ public void setOptionsOrWarn(String... flags) { setOptionsOrWarn(flags, 0, flags.length); } /** * Set options based on a String array in the style of * commandline flags. This method goes through the array until it ends, * processing options, as for {@link #setOption}. * * @param flags Array of options. The options passed in should * be specified like command-line arguments, including with an initial * minus sign for example, * {"-outputFormat", "typedDependencies", "-maxLength", "70"} * @param startIndex The index in the array to begin processing options at * @param endIndexPlusOne A number one greater than the last array index at * which options should be processed * @throws IllegalArgumentException If an unknown flag is passed in */ public void setOptionsOrWarn(final String[] flags, final int startIndex, final int endIndexPlusOne) { for (int i = startIndex; i < endIndexPlusOne;) { i = setOptionOrWarn(flags, i); } } /** * Set an option based on a String array in the style of * commandline flags. The option may * be either one known by the Options object, or one recognized by the * TreebankLangParserParams which has already been set up inside the Options * object, and then the option is set in the language-particular * TreebankLangParserParams. * Note that despite this method being an instance method, many flags * are actually set as static class variables in the Train and Test * classes (this should be fixed some day). * Some options (there are many others; see the source code): * <ul> * <li> <code>-maxLength n</code> set the maximum length sentence to parse (inclusively) * <li> <code>-printTT</code> print the training trees in raw, annotated, and annotated+binarized form. Useful for debugging and other miscellany. * <li> <code>-printAnnotated filename</code> use only in conjunction with -printTT. Redirects printing of annotated training trees to <code>filename</code>. * <li> <code>-forceTags</code> when the parser is tested against a set of gold standard trees, use the tagged yield, instead of just the yield, as input. * </ul> * * @param flags An array of options arguments, command-line style. E.g. {"-maxLength", "50"}. * @param i The index in flags to start at when processing an option * @return The index in flags of the position after the last element used in * processing this option. If the current array position cannot be processed as a valid * option, then a warning message is printed to stderr and the return value is <code>i+1</code> */ public int setOptionOrWarn(String[] flags, int i) { int j = setOptionFlag(flags, i); if (j == i) { j = tlpParams.setOptionFlag(flags, i); } if (j == i) { System.err.println("WARNING! lexparser.Options: Unknown option ignored: " + flags[i]); j++; } return j; } /** * Set an option based on a String array in the style of * commandline flags. The option may * be either one known by the Options object, or one recognized by the * TreebankLangParserParams which has already been set up inside the Options * object, and then the option is set in the language-particular * TreebankLangParserParams. * Note that despite this method being an instance method, many flags * are actually set as static class variables in the Train and Test * classes (this should be fixed some day). * Some options (there are many others; see the source code): * <ul> * <li> <code>-maxLength n</code> set the maximum length sentence to parse (inclusively) * <li> <code>-printTT</code> print the training trees in raw, annotated, and annotated+binarized form. Useful for debugging and other miscellany. * <li> <code>-printAnnotated filename</code> use only in conjunction with -printTT. Redirects printing of annotated training trees to <code>filename</code>. * <li> <code>-forceTags</code> when the parser is tested against a set of gold standard trees, use the tagged yield, instead of just the yield, as input. * </ul> * * @param flags An array of options arguments, command-line style. E.g. {"-maxLength", "50"}. * @param i The index in flags to start at when processing an option * @return The index in flags of the position after the last element used in * processing this option. * @throws IllegalArgumentException If the current array position cannot be * processed as a valid option */ public int setOption(String[] flags, int i) { int j = setOptionFlag(flags, i); if (j == i) { j = tlpParams.setOptionFlag(flags, i); } if (j == i) { throw new IllegalArgumentException("Unknown option: " + flags[i]); } return j; } /** * Set an option in this object, based on a String array in the style of * commandline flags. The option is only processed with respect to * options directly known by the Options object. * Some options (there are many others; see the source code): * <ul> * <li> <code>-maxLength n</code> set the maximum length sentence to parse (inclusively) * <li> <code>-printTT</code> print the training trees in raw, annotated, and annotated+binarized form. Useful for debugging and other miscellany. * <li> <code>-printAnnotated filename</code> use only in conjunction with -printTT. Redirects printing of annotated training trees to <code>filename</code>. * <li> <code>-forceTags</code> when the parser is tested against a set of gold standard trees, use the tagged yield, instead of just the yield, as input. * </ul> * * @param args An array of options arguments, command-line style. E.g. {"-maxLength", "50"}. * @param i The index in args to start at when processing an option * @return The index in args of the position after the last element used in * processing this option, or the value i unchanged if a valid option couldn't * be processed starting at position i. */ private int setOptionFlag(String[] args, int i) { if (args[i].equalsIgnoreCase("-PCFG")) { doDep = false; doPCFG = true; i++; } else if (args[i].equalsIgnoreCase("-dep")) { doDep = true; doPCFG = false; i++; } else if (args[i].equalsIgnoreCase("-factored")) { doDep = true; doPCFG = true; testOptions.useFastFactored = false; i++; } else if (args[i].equalsIgnoreCase("-fastFactored")) { doDep = true; doPCFG = true; testOptions.useFastFactored = true; i++; } else if (args[i].equalsIgnoreCase("-noRecoveryTagging")) { testOptions.noRecoveryTagging = true; i++; } else if (args[i].equalsIgnoreCase("-useLexiconToScoreDependencyPwGt")) { testOptions.useLexiconToScoreDependencyPwGt = true; i++; } else if (args[i].equalsIgnoreCase("-useSmoothTagProjection")) { useSmoothTagProjection = true; i++; } else if (args[i].equalsIgnoreCase("-useUnigramWordSmoothing")) { useUnigramWordSmoothing = true; i++; } else if (args[i].equalsIgnoreCase("-useNonProjectiveDependencyParser")) { testOptions.useNonProjectiveDependencyParser = true; i++; } else if (args[i].equalsIgnoreCase("-maxLength") && (i + 1 < args.length)) { testOptions.maxLength = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-MAX_ITEMS") && (i + 1 < args.length)) { testOptions.MAX_ITEMS = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-trainLength") && (i + 1 < args.length)) { // train on only short sentences trainOptions.trainLengthLimit = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-lengthNormalization")) { testOptions.lengthNormalization = true; i++; } else if (args[i].equalsIgnoreCase("-iterativeCKY")) { testOptions.iterativeCKY = true; i++; } else if (args[i].equalsIgnoreCase("-vMarkov") && (i + 1 < args.length)) { int order = Integer.parseInt(args[i + 1]); if (order <= 1) { trainOptions.PA = false; trainOptions.gPA = false; } else if (order == 2) { trainOptions.PA = true; trainOptions.gPA = false; } else if (order >= 3) { trainOptions.PA = true; trainOptions.gPA = true; } i += 2; } else if (args[i].equalsIgnoreCase("-vSelSplitCutOff") && (i + 1 < args.length)) { trainOptions.selectiveSplitCutOff = Double.parseDouble(args[i + 1]); trainOptions.selectiveSplit = trainOptions.selectiveSplitCutOff > 0.0; i += 2; } else if (args[i].equalsIgnoreCase("-vSelPostSplitCutOff") && (i + 1 < args.length)) { trainOptions.selectivePostSplitCutOff = Double.parseDouble(args[i + 1]); trainOptions.selectivePostSplit = trainOptions.selectivePostSplitCutOff > 0.0; i += 2; } else if (args[i].equalsIgnoreCase("-deleteSplitters") && (i+1 < args.length)) { String[] toDel = args[i+1].split(" *, *"); trainOptions.deleteSplitters = new HashSet<String>(Arrays.asList(toDel)); i += 2; } else if (args[i].equalsIgnoreCase("-postSplitWithBaseCategory")) { trainOptions.postSplitWithBaseCategory = true; i += 1; } else if (args[i].equalsIgnoreCase("-vPostMarkov") && (i + 1 < args.length)) { int order = Integer.parseInt(args[i + 1]); if (order <= 1) { trainOptions.postPA = false; trainOptions.postGPA = false; } else if (order == 2) { trainOptions.postPA = true; trainOptions.postGPA = false; } else if (order >= 3) { trainOptions.postPA = true; trainOptions.postGPA = true; } i += 2; } else if (args[i].equalsIgnoreCase("-hMarkov") && (i + 1 < args.length)) { int order = Integer.parseInt(args[i + 1]); if (order >= 0) { trainOptions.markovOrder = order; trainOptions.markovFactor = true; } else { trainOptions.markovFactor = false; } i += 2; } else if (args[i].equalsIgnoreCase("-distanceBins") && (i + 1 < args.length)) { int numBins = Integer.parseInt(args[i + 1]); if (numBins <= 1) { distance = false; } else if (numBins == 4) { distance = true; coarseDistance = true; } else if (numBins == 5) { distance = true; coarseDistance = false; } else { throw new IllegalArgumentException("Invalid value for -distanceBin: " + args[i+1]); } i += 2; } else if (args[i].equalsIgnoreCase("-noStop")) { genStop = false; i++; } else if (args[i].equalsIgnoreCase("-nonDirectional")) { directional = false; i++; } else if (args[i].equalsIgnoreCase("-depWeight") && (i + 1 < args.length)) { testOptions.depWeight = Double.parseDouble(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-printPCFGkBest") && (i + 1 < args.length)) { testOptions.printPCFGkBest = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-evalPCFGkBest") && (i + 1 < args.length)) { testOptions.evalPCFGkBest = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-printFactoredKGood") && (i + 1 < args.length)) { testOptions.printFactoredKGood = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-smoothTagsThresh") && (i + 1 < args.length)) { lexOptions.smoothInUnknownsThreshold = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-unseenSmooth") && (i + 1 < args.length)) { testOptions.unseenSmooth = Double.parseDouble(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-fractionBeforeUnseenCounting") && (i + 1 < args.length)) { trainOptions.fractionBeforeUnseenCounting = Double.parseDouble(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-hSelSplitThresh") && (i + 1 < args.length)) { trainOptions.HSEL_CUT = Integer.parseInt(args[i + 1]); trainOptions.hSelSplit = trainOptions.HSEL_CUT > 0; i += 2; } else if (args[i].equalsIgnoreCase("-tagPA")) { trainOptions.tagPA = true; i += 1; } else if (args[i].equalsIgnoreCase("-tagSelSplitCutOff") && (i + 1 < args.length)) { trainOptions.tagSelectiveSplitCutOff = Double.parseDouble(args[i + 1]); trainOptions.tagSelectiveSplit = trainOptions.tagSelectiveSplitCutOff > 0.0; i += 2; } else if (args[i].equalsIgnoreCase("-tagSelPostSplitCutOff") && (i + 1 < args.length)) { trainOptions.tagSelectivePostSplitCutOff = Double.parseDouble(args[i + 1]); trainOptions.tagSelectivePostSplit = trainOptions.tagSelectivePostSplitCutOff > 0.0; i += 2; } else if (args[i].equalsIgnoreCase("-noTagSplit")) { trainOptions.noTagSplit = true; i += 1; } else if (args[i].equalsIgnoreCase("-uwm") && (i + 1 < args.length)) { lexOptions.useUnknownWordSignatures = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-unknownSuffixSize") && (i + 1 < args.length)) { lexOptions.unknownSuffixSize = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-unknownPrefixSize") && (i + 1 < args.length)) { lexOptions.unknownPrefixSize = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-uwModelTrainer") && (i + 1 < args.length)) { lexOptions.uwModelTrainer = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-openClassThreshold") && (i + 1 < args.length)) { trainOptions.openClassTypesThreshold = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-unary") && i+1 < args.length) { trainOptions.markUnary = Integer.parseInt(args[i+1]); i += 2; } else if (args[i].equalsIgnoreCase("-unaryTags")) { trainOptions.markUnaryTags = true; i += 1; } else if (args[i].equalsIgnoreCase("-mutate")) { lexOptions.smartMutation = true; i += 1; } else if (args[i].equalsIgnoreCase("-useUnicodeType")) { lexOptions.useUnicodeType = true; i += 1; } else if (args[i].equalsIgnoreCase("-rightRec")) { trainOptions.rightRec = true; i += 1; } else if (args[i].equalsIgnoreCase("-noRightRec")) { trainOptions.rightRec = false; i += 1; } else if (args[i].equalsIgnoreCase("-preTag")) { testOptions.preTag = true; i += 1; } else if (args[i].equalsIgnoreCase("-forceTags")) { testOptions.forceTags = true; i += 1; } else if (args[i].equalsIgnoreCase("-taggerSerializedFile")) { testOptions.taggerSerializedFile = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-forceTagBeginnings")) { testOptions.forceTagBeginnings = true; i += 1; } else if (args[i].equalsIgnoreCase("-noFunctionalForcing")) { testOptions.noFunctionalForcing = true; i += 1; } else if (args[i].equalsIgnoreCase("-scTags")) { dcTags = false; i += 1; } else if (args[i].equalsIgnoreCase("-dcTags")) { dcTags = true; i += 1; } else if (args[i].equalsIgnoreCase("-basicCategoryTagsInDependencyGrammar")) { trainOptions.basicCategoryTagsInDependencyGrammar = true; i+= 1; } else if (args[i].equalsIgnoreCase("-evalb")) { testOptions.evalb = true; i += 1; } else if (args[i].equalsIgnoreCase("-v") || args[i].equalsIgnoreCase("-verbose")) { testOptions.verbose = true; i += 1; } else if (args[i].equalsIgnoreCase("-outputFilesDirectory") && i+1 < args.length) { testOptions.outputFilesDirectory = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-outputFilesExtension") && i+1 < args.length) { testOptions.outputFilesExtension = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-outputFilesPrefix") && i+1 < args.length) { testOptions.outputFilesPrefix = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-outputkBestEquivocation") && i+1 < args.length) { testOptions.outputkBestEquivocation = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-writeOutputFiles")) { testOptions.writeOutputFiles = true; i += 1; } else if (args[i].equalsIgnoreCase("-printAllBestParses")) { testOptions.printAllBestParses = true; i += 1; } else if (args[i].equalsIgnoreCase("-outputTreeFormat") || args[i].equalsIgnoreCase("-outputFormat")) { testOptions.outputFormat = args[i + 1]; i += 2; } else if (args[i].equalsIgnoreCase("-outputTreeFormatOptions") || args[i].equalsIgnoreCase("-outputFormatOptions")) { testOptions.outputFormatOptions = args[i + 1]; i += 2; } else if (args[i].equalsIgnoreCase("-addMissingFinalPunctuation")) { testOptions.addMissingFinalPunctuation = true; i += 1; } else if (args[i].equalsIgnoreCase("-flexiTag")) { lexOptions.flexiTag = true; i += 1; } else if (args[i].equalsIgnoreCase("-lexiTag")) { lexOptions.flexiTag = false; i += 1; } else if (args[i].equalsIgnoreCase("-useSignatureForKnownSmoothing")) { lexOptions.useSignatureForKnownSmoothing = true; i += 1; } else if (args[i].equalsIgnoreCase("-compactGrammar")) { trainOptions.compactGrammar = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-markFinalStates")) { trainOptions.markFinalStates = args[i + 1].equalsIgnoreCase("true"); i += 2; } else if (args[i].equalsIgnoreCase("-leftToRight")) { trainOptions.leftToRight = args[i + 1].equals("true"); i += 2; } else if (args[i].equalsIgnoreCase("-cnf")) { forceCNF = true; i += 1; } else if(args[i].equalsIgnoreCase("-smoothRules")) { trainOptions.ruleSmoothing = true; trainOptions.ruleSmoothingAlpha = Double.valueOf(args[i+1]); i += 2; } else if (args[i].equalsIgnoreCase("-nodePrune") && i+1 < args.length) { nodePrune = args[i+1].equalsIgnoreCase("true"); i += 2; } else if (args[i].equalsIgnoreCase("-noDoRecovery")) { testOptions.doRecovery = false; i += 1; } else if (args[i].equalsIgnoreCase("-acl03chinese")) { trainOptions.markovOrder = 1; trainOptions.markovFactor = true; // no increment } else if (args[i].equalsIgnoreCase("-wordFunction")) { wordFunction = ReflectionLoading.loadByReflection(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-acl03pcfg")) { doDep = false; doPCFG = true; // lexOptions.smoothInUnknownsThreshold = 30; trainOptions.markUnary = 1; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.tagPA = true; trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = true; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 400.0; trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; lexOptions.useUnknownWordSignatures = 2; lexOptions.flexiTag = true; // DAN: Tag double-counting is BAD for PCFG-only parsing dcTags = false; // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-jenny")) { doDep = false; doPCFG = true; // lexOptions.smoothInUnknownsThreshold = 30; trainOptions.markUnary = 1; trainOptions.PA = false; trainOptions.gPA = false; trainOptions.tagPA = false; trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = true; trainOptions.selectiveSplit = false; // trainOptions.selectiveSplitCutOff = 400.0; trainOptions.markovFactor = false; // trainOptions.markovOrder = 2; trainOptions.hSelSplit = false; lexOptions.useUnknownWordSignatures = 2; lexOptions.flexiTag = true; // DAN: Tag double-counting is BAD for PCFG-only parsing dcTags = false; // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-goodPCFG")) { doDep = false; doPCFG = true; // op.lexOptions.smoothInUnknownsThreshold = 30; trainOptions.markUnary = 1; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.tagPA = true; trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = true; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 400.0; trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; lexOptions.useUnknownWordSignatures = 2; lexOptions.flexiTag = true; // DAN: Tag double-counting is BAD for PCFG-only parsing dcTags = false; String[] delSplit = { "-deleteSplitters", "VP^NP,VP^VP,VP^SINV,VP^SQ" }; if (this.setOptionFlag(delSplit, 0) != 2) { System.err.println("Error processing deleteSplitters"); } // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-linguisticPCFG")) { doDep = false; doPCFG = true; // op.lexOptions.smoothInUnknownsThreshold = 30; trainOptions.markUnary = 1; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.tagPA = true; // on at the moment, but iffy trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = false; // not for linguistic trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 400.0; trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; lexOptions.useUnknownWordSignatures = 5; // different from acl03pcfg lexOptions.flexiTag = false; // different from acl03pcfg // DAN: Tag double-counting is BAD for PCFG-only parsing dcTags = false; // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-ijcai03")) { doDep = true; doPCFG = true; trainOptions.markUnary = 0; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.tagPA = false; trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = false; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 300.0; trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; trainOptions.compactGrammar = 0; /// cdm: May 2005 compacting bad for factored? lexOptions.useUnknownWordSignatures = 2; lexOptions.flexiTag = false; dcTags = true; // op.nodePrune = true; // cdm: May 2005: this doesn't help // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-goodFactored")) { doDep = true; doPCFG = true; trainOptions.markUnary = 0; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.tagPA = false; trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = false; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 300.0; trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; trainOptions.compactGrammar = 0; /// cdm: May 2005 compacting bad for factored? lexOptions.useUnknownWordSignatures = 5; // different from ijcai03 lexOptions.flexiTag = false; dcTags = true; // op.nodePrune = true; // cdm: May 2005: this doesn't help // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-chineseFactored")) { // Single counting tag->word rewrite is also much better for Chinese // Factored. Bracketing F1 goes up about 0.7%. dcTags = false; lexOptions.useUnicodeType = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; trainOptions.markovFactor = true; trainOptions.HSEL_CUT = 50; // trainOptions.openClassTypesThreshold=1; // so can get unseen punctuation // trainOptions.fractionBeforeUnseenCounting=0.0; // so can get unseen punctuation // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-arabicFactored")) { doDep = true; doPCFG = true; dcTags = false; // "false" seems to help Arabic about 0.1% F1 trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; trainOptions.HSEL_CUT = 75; // 75 bit better than 50, 100 a bit worse trainOptions.PA = true; trainOptions.gPA = false; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 300.0; trainOptions.markUnary = 1; // Helps PCFG and marginally factLB // trainOptions.compactGrammar = 0; // Doesn't seem to help or only 0.05% F1 lexOptions.useUnknownWordSignatures = 9; lexOptions.unknownPrefixSize = 1; lexOptions.unknownSuffixSize = 1; testOptions.MAX_ITEMS = 500000; // Arabic sentences are long enough that this helps a fraction // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-frenchFactored")) { doDep = true; doPCFG = true; dcTags = false; //wsg2011: Setting to false improves F1 by 0.5% trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; trainOptions.HSEL_CUT = 75; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 300.0; trainOptions.markUnary = 0; //Unary rule marking bad for french..setting to 0 gives +0.3 F1 lexOptions.useUnknownWordSignatures = 1; lexOptions.unknownPrefixSize = 1; lexOptions.unknownSuffixSize = 2; } else if (args[i].equalsIgnoreCase("-chinesePCFG")) { trainOptions.markovOrder = 2; trainOptions.markovFactor = true; trainOptions.HSEL_CUT = 5; trainOptions.PA = true; trainOptions.gPA = true; trainOptions.selectiveSplit = false; doDep = false; doPCFG = true; // Single counting tag->word rewrite is also much better for Chinese PCFG // Bracketing F1 is up about 2% and tag accuracy about 1% (exact by 6%) dcTags = false; // no increment } else if (args[i].equalsIgnoreCase("-printTT") && (i+1 < args.length)) { trainOptions.printTreeTransformations = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-printAnnotatedRuleCounts")) { trainOptions.printAnnotatedRuleCounts = true; i++; } else if (args[i].equalsIgnoreCase("-printAnnotatedStateCounts")) { trainOptions.printAnnotatedStateCounts = true; i++; } else if (args[i].equalsIgnoreCase("-printAnnotated") && (i + 1 < args.length)) { try { trainOptions.printAnnotatedPW = tlpParams.pw(new FileOutputStream(args[i + 1])); } catch (IOException ioe) { trainOptions.printAnnotatedPW = null; } i += 2; } else if (args[i].equalsIgnoreCase("-printBinarized") && (i + 1 < args.length)) { try { trainOptions.printBinarizedPW = tlpParams.pw(new FileOutputStream(args[i + 1])); } catch (IOException ioe) { trainOptions.printBinarizedPW = null; } i += 2; } else if (args[i].equalsIgnoreCase("-printStates")) { trainOptions.printStates = true; i++; } else if (args[i].equalsIgnoreCase("-preTransformer") && (i + 1 < args.length)) { String[] classes = args[i + 1].split(","); i += 2; if (classes.length == 1) { trainOptions.preTransformer = ReflectionLoading.loadByReflection(classes[0], this); } else if (classes.length > 1) { CompositeTreeTransformer composite = new CompositeTreeTransformer(); trainOptions.preTransformer = composite; for (String clazz : classes) { TreeTransformer transformer = ReflectionLoading.loadByReflection(clazz, this); composite.addTransformer(transformer); } } } else if (args[i].equalsIgnoreCase("-taggedFiles") && (i + 1 < args.length)) { trainOptions.taggedFiles = args[i + 1]; i += 2; } else if (args[i].equalsIgnoreCase("-predictSplits")) { // This is an experimental (and still in development) // reimplementation of Berkeley's state splitting grammar. trainOptions.predictSplits = true; trainOptions.compactGrammar = 0; i++; } else if (args[i].equalsIgnoreCase("-splitCount")) { trainOptions.splitCount = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-splitRecombineRate")) { trainOptions.splitRecombineRate = Double.parseDouble(args[i + 1]); i +=2; } else if (args[i].equalsIgnoreCase("-splitTrainingThreads")) { trainOptions.splitTrainingThreads = Integer.parseInt(args[i + 1]); i +=2; } else if (args[i].equalsIgnoreCase("-evals")) { testOptions.evals = StringUtils.stringToProperties(args[i+1], testOptions.evals); i += 2; } else if (args[i].equalsIgnoreCase("-fastFactoredCandidateMultiplier")) { testOptions.fastFactoredCandidateMultiplier = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-fastFactoredCandidateAddend")) { testOptions.fastFactoredCandidateAddend = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-simpleBinarizedLabels")) { trainOptions.simpleBinarizedLabels = true; i += 1; } else if (args[i].equalsIgnoreCase("-noRebinarization")) { trainOptions.noRebinarization = true; i += 1; } return i; } public static class LexOptions implements Serializable { /** * Whether to use suffix and capitalization information for unknowns. * Within the BaseLexicon model options have the following meaning: * 0 means a single unknown token. 1 uses suffix, and capitalization. * 2 uses a variant (richer) form of signature. Good. * Use this one. Using the richer signatures in versions 3 or 4 seems * to have very marginal or no positive value. * 3 uses a richer form of signature that mimics the NER word type * patterns. 4 is a variant of 2. 5 is another with more English * specific morphology (good for English unknowns!). * 6-9 are options for Arabic. 9 codes some patterns for numbers and * derivational morphology, but also supports unknownPrefixSize and * unknownSuffixSize. * For German, 0 means a single unknown token, and non-zero means to use * capitalization of first letter and a suffix of length * unknownSuffixSize. */ public int useUnknownWordSignatures = 0; /** * Words more common than this are tagged with MLE P(t|w). Default 100. The * smoothing is sufficiently slight that changing this has little effect. * But set this to 0 to be able to use the parser as a vanilla PCFG with * no smoothing (not as a practical parser but for exposition or debugging). */ public int smoothInUnknownsThreshold = 100; /** * Smarter smoothing for rare words. */ public boolean smartMutation = false; /** * Make use of unicode code point types in smoothing. */ public boolean useUnicodeType = false; /** For certain Lexicons, a certain number of word-final letters are * used to subclassify the unknown token. This gives the number of * letters. */ public int unknownSuffixSize = 1; /** For certain Lexicons, a certain number of word-initial letters are * used to subclassify the unknown token. This gives the number of * letters. */ public int unknownPrefixSize = 1; /** * Trainer which produces model for unknown words that the lexicon * should use */ public String uwModelTrainer; // = null; /* If this option is false, then all words that were seen in the training * data (even once) are constrained to only have seen tags. That is, * mle is used for the lexicon. * If this option is true, then if a word has been seen more than * smoothInUnknownsThreshold, then it will still only get tags with which * it has been seen, but rarer words will get all tags for which the * unknown word model (or smart mutation) does not give a score of -Inf. * This will normally be all open class tags. * If floodTags is invoked by the parser, all other tags will also be * given a minimal non-zero, non-infinite probability. */ public boolean flexiTag = false; /** Whether to use signature rather than just being unknown as prior in * known word smoothing. Currently only works if turned on for English. */ public boolean useSignatureForKnownSmoothing; private static final long serialVersionUID = 2805351374506855632L; private static final String[] params = { "useUnknownWordSignatures", "smoothInUnknownsThreshold", "smartMutation", "useUnicodeType", "unknownSuffixSize", "unknownPrefixSize", "flexiTag", "useSignatureForKnownSmoothing"}; @Override public String toString() { return params[0] + " " + useUnknownWordSignatures + "\n" + params[1] + " " + smoothInUnknownsThreshold + "\n" + params[2] + " " + smartMutation + "\n" + params[3] + " " + useUnicodeType + "\n" + params[4] + " " + unknownSuffixSize + "\n" + params[5] + " " + unknownPrefixSize + "\n" + params[6] + " " + flexiTag + "\n" + params[7] + " " + useSignatureForKnownSmoothing + "\n"; } public void readData(BufferedReader in) throws IOException { for (int i = 0; i < params.length; i++) { String line = in.readLine(); int idx = line.indexOf(' '); String key = line.substring(0, idx); String value = line.substring(idx + 1); if ( ! key.equalsIgnoreCase(params[i])) { System.err.println("Yikes!!! Expected " + params[i] + " got " + key); } switch (i) { case 0: useUnknownWordSignatures = Integer.parseInt(value); break; case 1: smoothInUnknownsThreshold = Integer.parseInt(value); break; case 2: smartMutation = Boolean.parseBoolean(value); break; case 3: useUnicodeType = Boolean.parseBoolean(value); break; case 4: unknownSuffixSize = Integer.parseInt(value); break; case 5: unknownPrefixSize = Integer.parseInt(value); break; case 6: flexiTag = Boolean.parseBoolean(value); } } } } // end class LexOptions public LexOptions lexOptions = new LexOptions(); /** * The treebank-specific parser parameters to use. */ public TreebankLangParserParams tlpParams; /** * @return The treebank language pack for the treebank the parser * is trained on. */ public TreebankLanguagePack langpack() { return tlpParams.treebankLanguagePack(); } /** * Forces parsing with strictly CNF grammar -- unary chains are converted * to XP&YP symbols and back */ public boolean forceCNF = false; /** * Do a PCFG parse of the sentence. If both variables are on, * also do a combined parse of the sentence. */ public boolean doPCFG = true; /** * Do a dependency parse of the sentence. */ public boolean doDep = true; /** * if true, any child can be the head (seems rather bad!) */ public boolean freeDependencies = false; /** * Whether dependency grammar considers left/right direction. Good. */ public boolean directional = true; public boolean genStop = true; public boolean useSmoothTagProjection = false; public boolean useUnigramWordSmoothing = false; /** * Use distance bins in the dependency calculations */ public boolean distance = true; /** * Use coarser distance (4 bins) in dependency calculations */ public boolean coarseDistance = false; /** * "double count" tags rewrites as word in PCFG and Dep parser. Good for * combined parsing only (it used to not kick in for PCFG parsing). This * option is only used at Test time, but it is now in Options, so the * correct choice for a grammar is recorded by a serialized parser. * You should turn this off for a vanilla PCFG parser. */ public boolean dcTags = true; /** * If true, inside the factored parser, remove any node from the final * chosen tree which improves the PCFG score. This was added as the * dependency factor tends to encourage 'deep' trees. */ public boolean nodePrune = false; public TrainOptions trainOptions = new TrainOptions(); /** * Note that the TestOptions is transient. This means that whatever * options get set at creation time are forgotten when the parser is * serialized. If you want an option to be remembered when the * parser is reloaded, put it in either TrainOptions or in this * class itself. */ public transient TestOptions testOptions = new TestOptions(); /** * A function that maps words used in training and testing to new * words. For example, it could be a function to lowercase text, * such as edu.stanford.nlp.util.LowercaseFunction (which makes the * parser case insensitive). This function is applied in * LexicalizedParserQuery.parse and in the training methods which * build a new parser. */ public Function<String, String> wordFunction = null; /** * Making the TestOptions transient means it won't even be * constructed when you deserialize an Options, so we need to * construct it on our own when deserializing */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); testOptions = new TestOptions(); } public void display() { // try { logger.trace("Options parameters:"); writeData(); /* } catch (IOException e) { e.printStackTrace(); }*/ } public void writeData() {//throws IOException { StringBuilder sb = new StringBuilder(); sb.append(lexOptions.toString()); sb.append("parserParams ").append(tlpParams.getClass().getName()).append("\n"); sb.append("forceCNF ").append(forceCNF).append("\n"); sb.append("doPCFG ").append(doPCFG).append("\n"); sb.append("doDep ").append(doDep).append("\n"); sb.append("freeDependencies ").append(freeDependencies).append("\n"); sb.append("directional ").append(directional).append("\n"); sb.append("genStop ").append(genStop).append("\n"); sb.append("distance ").append(distance).append("\n"); sb.append("coarseDistance ").append(coarseDistance).append("\n"); sb.append("dcTags ").append(dcTags).append("\n"); sb.append("nPrune ").append(nodePrune).append("\n"); logger.trace(sb.toString()); } /** * Populates data in this Options from the character stream. * @param in The Reader * @throws IOException If there is a problem reading data */ public void readData(BufferedReader in) throws IOException { String line, value; // skip old variables if still present lexOptions.readData(in); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); try { tlpParams = (TreebankLangParserParams) Class.forName(value).newInstance(); } catch (Exception e) { IOException ioe = new IOException("Problem instantiating parserParams: " + line); ioe.initCause(e); throw ioe; } line = in.readLine(); // ensure backwards compatibility if (line.matches("^forceCNF.*")) { value = line.substring(line.indexOf(' ') + 1); forceCNF = Boolean.parseBoolean(value); line = in.readLine(); } value = line.substring(line.indexOf(' ') + 1); doPCFG = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); doDep = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); freeDependencies = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); directional = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); genStop = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); distance = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); coarseDistance = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); dcTags = Boolean.parseBoolean(value); line = in.readLine(); if ( ! line.matches("^nPrune.*")) { throw new RuntimeException("Expected nPrune, found: " + line); } value = line.substring(line.indexOf(' ') + 1); nodePrune = Boolean.parseBoolean(value); line = in.readLine(); // get rid of last line if (line.length() != 0) { throw new RuntimeException("Expected blank line, found: " + line); } } private static final long serialVersionUID = 4L; } // end class Options
gpl-2.0
lanoxx/masterylearning
backend/src/main/java/org/masterylearning/domain/data/EntryData.java
1748
package org.masterylearning.domain.data; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.masterylearning.domain.Entry; import org.masterylearning.dto.out.EntryDataOutDto; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToOne; /** * For use of JsonTypeInfo and JsonSubType see this stackoverflow answer: * http://stackoverflow.com/questions/6542833/how-can-i-polymorphic-deserialization-json-string-using-java-and-jackson-library */ @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes({ @Type(value = Section.class, name = "section"), @Type(value = Unit.class, name = "unit"), @Type(value = Paragraph.class, name = "paragraph"), @Type(value = ContinueButton.class, name = "continue-button"), @Type(value = InteractiveContent.class, name = "interactive-content"), @Type(value = YesNoExercise.class, name = "yesnoexercise"), @Type(value = MultiAnswerExercise.class, name = "multianswerexercise") }) @Entity (name = "EntryData") @Inheritance (strategy = InheritanceType.TABLE_PER_CLASS) public abstract class EntryData { @Id @GeneratedValue(strategy = GenerationType.TABLE) public Long id; public String type; @JsonBackReference("entry-data") @OneToOne public Entry container; public abstract EntryDataOutDto toDto (); }
gpl-2.0
riking/dolphin
Source/Android/app/src/main/java/org/dolphinemu/dolphinemu/features/settings/ui/viewholder/SliderViewHolder.java
1213
package org.dolphinemu.dolphinemu.features.settings.ui.viewholder; import android.view.View; import android.widget.TextView; import org.dolphinemu.dolphinemu.R; import org.dolphinemu.dolphinemu.features.settings.model.view.SettingsItem; import org.dolphinemu.dolphinemu.features.settings.model.view.SliderSetting; import org.dolphinemu.dolphinemu.features.settings.ui.SettingsAdapter; public final class SliderViewHolder extends SettingViewHolder { private SliderSetting mItem; private TextView mTextSettingName; private TextView mTextSettingDescription; public SliderViewHolder(View itemView, SettingsAdapter adapter) { super(itemView, adapter); } @Override protected void findViews(View root) { mTextSettingName = (TextView) root.findViewById(R.id.text_setting_name); mTextSettingDescription = (TextView) root.findViewById(R.id.text_setting_description); } @Override public void bind(SettingsItem item) { mItem = (SliderSetting) item; mTextSettingName.setText(item.getNameId()); if (item.getDescriptionId() > 0) { mTextSettingDescription.setText(item.getDescriptionId()); } } @Override public void onClick(View clicked) { getAdapter().onSliderClick(mItem); } }
gpl-2.0
dhleong/ideavim
test/org/jetbrains/plugins/ideavim/action/AutoIndentTest.java
5517
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jetbrains.plugins.ideavim.action; import org.jetbrains.plugins.ideavim.VimTestCase; import static com.maddyhome.idea.vim.helper.StringHelper.parseKeys; /** * @author Aleksey Lagoshin */ public class AutoIndentTest extends VimTestCase { // VIM-256 |==| public void testCaretPositionAfterAutoIndent() { configureByJavaText("class C {\n" + " int a;\n" + " int <caret>b;\n" + " int c;\n" + "}\n"); typeText(parseKeys("==")); myFixture.checkResult("class C {\n" + " int a;\n" + " <caret>int b;\n" + " int c;\n" + "}\n"); } // |2==| public void testAutoIndentWithCount() { configureByJavaText("class C {\n" + " int a;\n" + " int <caret>b;\n" + " int c;\n" + " int d;\n" + "}\n"); typeText(parseKeys("2==")); myFixture.checkResult("class C {\n" + " int a;\n" + " <caret>int b;\n" + " int c;\n" + " int d;\n" + "}\n"); } // |=k| public void testAutoIndentWithUpMotion() { configureByJavaText("class C {\n" + " int a;\n" + " int b;\n" + " int <caret>c;\n" + " int d;\n" + "}\n"); typeText(parseKeys("=k")); myFixture.checkResult("class C {\n" + " int a;\n" + " <caret>int b;\n" + " int c;\n" + " int d;\n" + "}\n"); } // |=l| public void testAutoIndentWithRightMotion() { configureByJavaText("class C {\n" + " int a;\n" + " int <caret>b;\n" + " int c;\n" + "}\n"); typeText(parseKeys("=l")); myFixture.checkResult("class C {\n" + " int a;\n" + " <caret>int b;\n" + " int c;\n" + "}\n"); } // |2=j| public void testAutoIndentWithCountsAndDownMotion() { configureByJavaText("class C {\n" + " int <caret>a;\n" + " int b;\n" + " int c;\n" + " int d;\n" + "}\n"); typeText(parseKeys("2=j")); myFixture.checkResult("class C {\n" + " <caret>int a;\n" + " int b;\n" + " int c;\n" + " int d;\n" + "}\n"); } // |v| |l| |=| public void testVisualAutoIndent() { configureByJavaText("class C {\n" + " int a;\n" + " int <caret>b;\n" + " int c;\n" + "}\n"); typeText(parseKeys("v", "l", "=")); myFixture.checkResult("class C {\n" + " int a;\n" + " <caret>int b;\n" + " int c;\n" + "}\n"); } // |v| |j| |=| public void testVisualMultilineAutoIndent() { configureByJavaText("class C {\n" + " int a;\n" + " int <caret>b;\n" + " int c;\n" + " int d;\n" + "}\n"); typeText(parseKeys("v", "j", "=")); myFixture.checkResult("class C {\n" + " int a;\n" + " <caret>int b;\n" + " int c;\n" + " int d;\n" + "}\n"); } // |C-v| |j| |=| public void testVisualBlockAutoIndent() { configureByJavaText("class C {\n" + " int a;\n" + " int <caret>b;\n" + " int c;\n" + " int d;\n" + "}\n"); typeText(parseKeys("<C-V>", "j", "=")); myFixture.checkResult("class C {\n" + " int a;\n" + " <caret>int b;\n" + " int c;\n" + " int d;\n" + "}\n"); } }
gpl-2.0
autoplot/app
QDataSet/src/org/das2/qds/util/LSpec.java
16160
/* * LSpec.java * * Created on April 24, 2007, 11:06 PM */ package org.das2.qds.util; import java.util.LinkedHashMap; import java.util.Map; import org.das2.datum.Datum; import org.das2.datum.Units; import org.das2.qds.ArrayDataSet; import org.das2.qds.DDataSet; import org.das2.qds.DataSetUtil; import org.das2.qds.QDataSet; import org.das2.qds.SemanticOps; import org.das2.qds.ops.Ops; /** * Form a rank 2 dataset with L and Time for tags by identifying monotonic sweeps * in two rank 1 datasets. * @author jbf */ public class LSpec { /** * identifies the sweep of each record */ public static final String USER_PROP_SWEEPS = "sweeps"; /** Creates a new instance of LSpec */ private LSpec() { } /** * just the inward sweeps */ public static int DIR_INWARD= -1; /** * just the outward sweeps */ public static int DIR_OUTWARD= 1; /** * include both sweeps */ public static int DIR_BOTH= 0; /** * identify monotonically increasing or decreasing segments of the dataset. * @param lds the dataset which sweeps back and forth, such as LShell or MagLat (or a sine wave for testing). * @param dir 0=both 1=outward 2= inward * @return rank 2 data set of sweep indeces, dim0 is sweep number, dim1 is two-element [ start, end(inclusive) ]. */ public static QDataSet identifySweeps( QDataSet lds, int dir ) { DataSetBuilder builder= new DataSetBuilder( 2, 100, 2 ); DataSetBuilder dep0builder= new DataSetBuilder( 2, 100, 2 ); double slope0= lds.value(1) - lds.value(0); int start=0; int end=0; // index of the right point of slope0. QDataSet wds= SemanticOps.weightsDataSet(lds); ArrayDataSet tds= ArrayDataSet.copy( SemanticOps.xtagsDataSet(lds) ); wds= Ops.multiply( wds, SemanticOps.weightsDataSet(tds) ); Datum cadence= SemanticOps.guessXTagWidth( tds, lds ); cadence= cadence.multiply(10.0); // kludge for data on 2012-10-25 tds.putProperty( QDataSet.CADENCE, DataSetUtil.asDataSet(cadence) ); QDataSet nonGap= SemanticOps.cadenceCheck(tds,lds); for ( int i=1; i<lds.length(); i++ ) { double slope1= lds.value(i) - lds.value(i-1); if ( slope0 * slope1 <= 0. || ( nonGap.value(i-1)==1 && nonGap.value(i)==0 ) ) { if ( slope0!=0. && ( dir==0 || ( slope0*dir>0 && end-start>1 ) ) ) { //TODO: detect jumps in the LShell, e.g. only downward: \\\\\ if ( start<end ) { builder.putValue( -1, 0, start ); builder.putValue( -1, 1, end-1 ); builder.nextRecord(); dep0builder.putValue( -1, 0, tds.value(start) ); dep0builder.putValue( -1, 1, tds.value(end-1) ); dep0builder.nextRecord(); } else { // all fill. } } if ( slope1!=0. || nonGap.value(i)>0 ) { start= i; } } else if ( wds.value(i)>0 ) { if ( nonGap.value(i-1)==0 && nonGap.value(i)==1 ) { start= i; end= i+1; } else { end= i+1; // end is not inclusive } } slope0= slope1; } dep0builder.putProperty( QDataSet.BINS_1, "min,maxInclusive" ); dep0builder.putProperty( QDataSet.UNITS, SemanticOps.getUnits(tds) ); DDataSet result= builder.getDataSet(); result.putProperty( QDataSet.DEPEND_0, dep0builder.getDataSet() ); result.putProperty( QDataSet.RENDER_TYPE, "eventsBar" ); return result; } /** * * @param datax data series that is aggregation of monotonic series (up and down) * @param start start index limiting search * @param end end index inclusive limiting search * @param x the value to locate. * @param guess guess index, because we are calling this repeatedly * @param dir 1 if datax is increasing, -1 if decreasing * @return index */ private static int findIndex( QDataSet datax, int start, int end, double x, int guess, int dir ) { int index= Math.max( Math.min( guess, end-1 ), start ); if ( dir > 0 ) { while ( index<end && datax.value(index+1) < x ) index++; while ( index>start && datax.value(index) > x ) index--; } else { while ( index<end && datax.value(index+1) > x ) index++; while ( index>start && datax.value(index) < x ) index--; } return index; } /** * this is probably old and shouldn't be used. * @param lds * @param zds * @param start * @param end * @param col * @param lgrid * @param ds */ private static void interpolate( QDataSet lds, QDataSet zds, int start, int end, int col, QDataSet lgrid, DDataSet ds ) { Units u= SemanticOps.getUnits( ds ); double fill= u.getFillDouble(); ds.putProperty( QDataSet.FILL_VALUE, fill ); if ( ! u.equals( SemanticOps.getUnits( zds ) ) ) { throw new IllegalArgumentException("zds units must be the same as ds units!"); } QDataSet wds= Ops.valid(zds); int index; int dir= (int) Math.signum( lds.value(end) - lds.value( start ) ); if ( dir > 0 ) index= start; else index= end; for ( int i=0; i<lgrid.length(); i++ ) { double ll= lgrid.value(i); index= findIndex( lds, start, end, ll, index, dir ); double alpha= ( ll - lds.value(index) ) / ( lds.value(index+1) - lds.value(index) ); if ( alpha < 0 ) { ds.putValue( col, i, fill ); } else if ( alpha > 1 ) { ds.putValue( col, i, fill ); } else if ( alpha == 0 ) { ds.putValue( col, i, zds.value(index) ); } else { if ( ( wds.value(index)==0 ) || wds.value( index+1 )==0 ) { ds.putValue( col, i, fill ); } else { ds.putValue( col, i, zds.value(index) * ( 1.0 - alpha ) + zds.value(index+1) * alpha ); } } } } private static double guessCadence( QDataSet xds, final int skip ) { double cadence = 0; // calculate average cadence for consistent points. Preload to avoid extra branch. double cadenceS= 0; int cadenceN= 1; for ( int i=skip; i < xds.length(); i++) { double cadenceAvg; cadenceAvg= cadenceS/cadenceN; cadence = xds.value(i) - xds.value(i-skip); if ( cadence > 1.5 * cadenceAvg) { cadenceS= cadence; cadenceN= 1; } else if ( cadence < 1.5 * cadenceAvg ) { cadenceS+= cadence; cadenceN+= 1; } } return cadenceS/cadenceN; } /** * rebin the datasets to rank 2 dataset ( time, LShell ), by interpolating along sweeps. This * dataset has the property "sweeps", which is a dataset that indexes the input datasets. * @param lds rank 1 dataset of length N * @param zds rank 1 dataset of length N, indexed along with <tt>lds</tt> * @param lgrid rank 1 dataset indicating the dim 1 tags for the result dataset. * @return a rank 2 dataset, with one column per sweep, interpolated to <tt>lgrid</tt> */ public static QDataSet rebin( QDataSet lds, QDataSet zds, QDataSet lgrid ) { return rebin( lds, zds, lgrid, 0 ); } /** * alternate, convenient interface which where tlz is a bundle of buckshot data (T,L,Z) * * @param tlz x,y,z (T,L,Z) bundle of Z values collected along inward and outward sweeps of L in time. * @param lgrid desired uniform grid of L values. * @param dir =1 increasing (outward) only, =-1 decreasing (inward) only, 0 both. * @return a rank 2 dataset, with one column per sweep, interpolated to <tt>lgrid</tt> */ public static QDataSet rebin( QDataSet tlz, QDataSet lgrid, int dir ) { QDataSet lds= Ops.link( Ops.slice1(tlz,0), Ops.slice1(tlz,1) ); QDataSet zds= Ops.slice1(tlz,2); return rebin( lds, zds, lgrid, dir ); } /** * alternate algorithm following Brian Larson's algorithm that rebin the datasets to rank 2 dataset ( time, LShell ), by interpolating along sweeps. This * dataset has the property "sweeps", which is a dataset that indexes the input datasets. * @param lds The L values corresponding to y axis position, which should be a function of time. * @param tt The Time values corresponding to x axis position. If null, then use lds.property(QDataSet.DEPEND_0). * @param zds the Z values corresponding to the parameter we wish to organize * @param tspace rank 0 cadence, such as dataset('9 hr') * @param lgrid rank 1 data is the grid points, such as linspace( 2.,8.,30 ) * @param dir =1 increasing (outward) only, =-1 decreasing (inward) only, 0 both * @return a rank 2 dataset, with one column per sweep, interpolated to <tt>lgrid</tt> */ public static QDataSet rebin( QDataSet tt, QDataSet lds, QDataSet zds, QDataSet tspace, QDataSet lgrid, int dir ) { final QDataSet sweeps= identifySweeps( lds, dir ); if ( tt==null ) { tt= (QDataSet) lds.property(QDataSet.DEPEND_0); } Units tu= SemanticOps.getUnits(tt); Number fill= (Number) zds.property( QDataSet.FILL_VALUE ); double dfill= fill==null ? -1e31 : fill.doubleValue(); QDataSet wds= DataSetUtil.weightsDataSet(zds); int ny= lgrid.length(); double[] ss= new double[ny]; double[] nn= new double[ny]; DataSetBuilder builder= new DataSetBuilder( 2, 100, ny ); DataSetBuilder tbuilder= new DataSetBuilder( 1, 100 ); tbuilder.putProperty( QDataSet.UNITS, tu ); builder.putProperty( QDataSet.FILL_VALUE,dfill ); int ix=-1; double nextx= Double.MAX_VALUE; double dt= DataSetUtil.asDatum( tspace ).doubleValue( tu.getOffsetUnits() ); double t0= -1; double dg= lgrid.value(1)-lgrid.value(0); double g0= lgrid.value(0); int n= ny-1; for ( int i=2; i<n; i++ ) { //if ( (lgrid.value(i)-lgrid.value(i-1)/dg ) throw new IllegalArgumentException( "lgrid must be uniform linear" ); } for ( int i=0; i<sweeps.length(); i++ ) { int ist= (int)sweeps.value(i,0); int ien= (int)sweeps.value(i,1); for ( int j= ist; j<ien; j++ ) { if ( ix==-1 || tt.value(j)-nextx >= 0 ) { //reset the accumulators nextx= dt * Math.ceil( tt.value(j) / dt ); // next threshold if ( ix>-1 ) { for ( int k=0; k<ny; k++ ) { if ( nn[k]==0 ) { builder.putValue( -1, k, dfill ); } else { builder.putValue( -1, k, ss[k]/nn[k] ); } } builder.nextRecord(); tbuilder.putValue( -1, t0-dt/2 ); tbuilder.nextRecord(); } t0= nextx; for ( int k=0; k<ny; k++ ) { ss[k]=0; nn[k]=0; } ix++; } int iy= (int)Math.floor( ( lds.value(j) - g0 ) / dg ); if ( iy>=0 && iy<ny ) { double w= wds.value(j); ss[iy]+= w*zds.value(j); nn[iy]+= w; } } } DDataSet result= builder.getDataSet(); result.putProperty(QDataSet.DEPEND_0,tbuilder.getDataSet()); result.putProperty(QDataSet.DEPEND_1,lgrid); DataSetUtil.copyDimensionProperties( zds, result ); String title= (String) result.property( QDataSet.TITLE ); if ( title==null ) title=""; if ( dir==-1 ) { title+= "!cinward"; } else if ( dir==1 ) { title+= "!coutward"; } result.putProperty( QDataSet.TITLE, title ); result.putProperty( QDataSet.FILL_VALUE, dfill ); return result; } /** * rebin the datasets to rank 2 dataset ( time, LShell ), by interpolating along sweeps. This * dataset has the property "sweeps", which is a dataset that indexes the input datasets. * @param lds rank 1 dataset of length N * @param zds rank 1 dataset of length N, indexed along with <tt>lds</tt> * @param lgrid rank 1 dataset indicating the dim 1 tags for the result dataset. * @param dir =1 increasing (outward) only, =-1 decreasing (inward) only, 0 both * @return a rank 2 dataset, with one column per sweep, interpolated to <tt>lgrid</tt> */ public static QDataSet rebin( QDataSet lds, QDataSet zds, QDataSet lgrid, int dir ) { final QDataSet sweeps= identifySweeps( lds, dir ); DDataSet result= DDataSet.createRank2( sweeps.length(), lgrid.length() ); result.putProperty( QDataSet.UNITS, zds.property( QDataSet.UNITS ) ); for ( int i=0; i<sweeps.length(); i++ ) { interpolate( lds, zds, (int) sweeps.value( i,0 ), (int) sweeps.value( i,1 ), i, lgrid, result ); } DDataSet xtags= DDataSet.createRank2( sweeps.length(), 2 ); QDataSet dep0= (QDataSet) lds.property(QDataSet.DEPEND_0); if ( dep0!=null ) { for ( int i=0; i<sweeps.length(); i++ ) { xtags.putValue( i,0,dep0.value( (int)sweeps.value( i,0 ) ) ); xtags.putValue( i,1,dep0.value( (int)sweeps.value( i,1 ) ) ); } DataSetUtil.putProperties( DataSetUtil.getDimensionProperties(dep0,null), xtags ); Units xunits= SemanticOps.getUnits(dep0); xtags.putProperty( QDataSet.UNITS, xunits ); xtags.putProperty( QDataSet.BINS_1, QDataSet.VALUE_BINS_MIN_MAX ); xtags.putProperty(QDataSet.MONOTONIC, org.das2.qds.DataSetUtil.isMonotonic(dep0) ); } else { for ( int i=0; i<sweeps.length(); i++ ) { xtags.putValue( i,0, sweeps.value( i,0 ) ); xtags.putValue( i,1, sweeps.value( i,1 ) ); } } Map<String,Object> userProps= new LinkedHashMap(); userProps.put(USER_PROP_SWEEPS, sweeps); result.putProperty( QDataSet.USER_PROPERTIES, userProps ); if ( lgrid.property(QDataSet.UNITS)==null ) { ArrayDataSet lgridCopy= ArrayDataSet.copy(lgrid); // often linspace( 4, 10, 30 ) is used to specify locations. Go ahead and copy over units. Units u= (Units) lds.property( QDataSet.UNITS ); if ( u!=null ) lgridCopy.putProperty( QDataSet.UNITS, u ); lgrid= lgridCopy; } result.putProperty( QDataSet.DEPEND_1, lgrid ); result.putProperty( QDataSet.DEPEND_0, xtags ); DataSetUtil.putProperties( DataSetUtil.getDimensionProperties( zds, null ), result ); return result; } }
gpl-2.0
tylerm007/MetaRepos
Source/VLS/DataObjects/WorkFlow/ActivityImpl.java
947
//{{COMPONENT_IMPORT_STMTS package MetaRepos; import java.util.Enumeration; import java.util.Vector; import versata.common.*; import versata.common.vstrace.*; import versata.vls.*; import java.util.*; import java.math.*; import versata.vls.cache.*; //END_COMPONENT_IMPORT_STMTS}} /* ** Activity */ //{{COMPONENT_RULES_CLASS_DECL public class ActivityImpl extends ActivityBaseImpl //END_COMPONENT_RULES_CLASS_DECL}} { //{{COMP_CLASS_CTOR public ActivityImpl (){ super(); } public ActivityImpl(Session session, boolean makeDefaults) { super(session, makeDefaults); //END_COMP_CLASS_CTOR}} } //{{EVENT_CODE //END_EVENT_CODE}} public void addListeners() { //{{EVENT_ADD_LISTENERS //END_EVENT_ADD_LISTENERS}} } //{{COMPONENT_RULES public static ActivityImpl getNewObject(Session session, boolean makeDefaults) { return new ActivityImpl(session, makeDefaults); } //END_COMPONENT_RULES}} }
gpl-2.0
kdeforche/jwt
src/eu/webtoolkit/jwt/auth/UpdatePasswordWidget.java
7657
/* * Copyright (C) 2020 Emweb bv, Herent, Belgium. * * See the LICENSE file for terms of use. */ package eu.webtoolkit.jwt.auth; import eu.webtoolkit.jwt.*; import eu.webtoolkit.jwt.chart.*; import eu.webtoolkit.jwt.servlet.*; import eu.webtoolkit.jwt.utils.*; import java.io.*; import java.lang.ref.*; import java.time.*; import java.util.*; import java.util.regex.*; import javax.servlet.*; import javax.servlet.http.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A widget which allows a user to choose a new password. * * <p>This widget lets a user choose a new password. * * <p>The widget renders the <code>&quot;Wt.Auth.template.update-password&quot;</code> template. * Optionally, it asks for the current password, as well as a new password. * * <p> * * @see AuthWidget#createUpdatePasswordView(User user, boolean promptPassword) */ public class UpdatePasswordWidget extends WTemplateFormView { private static Logger logger = LoggerFactory.getLogger(UpdatePasswordWidget.class); /** * Constructor. * * <p>If <code>authModel</code> is not <code>null</code>, the user also has to authenticate first * using his current password. */ public UpdatePasswordWidget( final User user, RegistrationModel registrationModel, final AuthModel authModel, WContainerWidget parentContainer) { super(tr("Wt.Auth.template.update-password"), (WContainerWidget) null); this.user_ = user; this.registrationModel_ = registrationModel; this.authModel_ = authModel; this.updated_ = new Signal(); this.canceled_ = new Signal(); this.registrationModel_.setValue( RegistrationModel.LoginNameField, user.getIdentity(Identity.LoginName)); this.registrationModel_.setReadOnly(RegistrationModel.LoginNameField, true); if (user.getPassword().isEmpty()) { this.authModel_ = null; } else { if (this.authModel_ != null) { this.authModel_.reset(); } } if (this.authModel_ != null && this.authModel_.getBaseAuth().isEmailVerificationEnabled()) { this.registrationModel_.setValue( RegistrationModel.EmailField, user.getEmail() + " " + user.getUnverifiedEmail()); } this.registrationModel_.setVisible(RegistrationModel.EmailField, false); WPushButton okButton = new WPushButton(tr("Wt.WMessageBox.Ok")); this.bindWidget("ok-button", okButton); WPushButton cancelButton = new WPushButton(tr("Wt.WMessageBox.Cancel")); this.bindWidget("cancel-button", cancelButton); if (this.authModel_ != null) { this.authModel_.setValue(AuthModel.LoginNameField, user.getIdentity(Identity.LoginName)); this.updateViewField(this.authModel_, AuthModel.PasswordField); this.authModel_.configureThrottling(okButton); WLineEdit password = (WLineEdit) this.resolveWidget(AuthModel.PasswordField); password.setFocus(true); } this.updateView(this.registrationModel_); WLineEdit password = (WLineEdit) this.resolveWidget(RegistrationModel.ChoosePasswordField); WLineEdit password2 = (WLineEdit) this.resolveWidget(RegistrationModel.RepeatPasswordField); WText password2Info = (WText) this.resolveWidget(RegistrationModel.RepeatPasswordField + "-info"); this.registrationModel_.validatePasswordsMatchJS(password, password2, password2Info); if (!(this.authModel_ != null)) { password.setFocus(true); } okButton .clicked() .addListener( this, (WMouseEvent e1) -> { UpdatePasswordWidget.this.doUpdate(); }); cancelButton .clicked() .addListener( this, (WMouseEvent e1) -> { UpdatePasswordWidget.this.cancel(); }); if (parentContainer != null) parentContainer.addWidget(this); } /** * Constructor. * * <p>Calls {@link #UpdatePasswordWidget(User user, RegistrationModel registrationModel, AuthModel * authModel, WContainerWidget parentContainer) this(user, registrationModel, authModel, * (WContainerWidget)null)} */ public UpdatePasswordWidget( final User user, RegistrationModel registrationModel, final AuthModel authModel) { this(user, registrationModel, authModel, (WContainerWidget) null); } /** {@link Signal} emitted when the password was updated. */ public Signal updated() { return this.updated_; } /** {@link Signal} emitted when cancel clicked. */ public Signal canceled() { return this.canceled_; } protected WWidget createFormWidget(String field) { WFormWidget result = null; if (field == RegistrationModel.LoginNameField) { result = new WLineEdit(); } else { if (field == AuthModel.PasswordField) { WLineEdit p = new WLineEdit(); p.setEchoMode(EchoMode.Password); result = p; } else { if (field == RegistrationModel.ChoosePasswordField) { WLineEdit p = new WLineEdit(); p.setEchoMode(EchoMode.Password); p.keyWentUp() .addListener( this, (WKeyEvent e1) -> { UpdatePasswordWidget.this.checkPassword(); }); p.changed() .addListener( this, () -> { UpdatePasswordWidget.this.checkPassword(); }); result = p; } else { if (field == RegistrationModel.RepeatPasswordField) { WLineEdit p = new WLineEdit(); p.setEchoMode(EchoMode.Password); p.changed() .addListener( this, () -> { UpdatePasswordWidget.this.checkPassword2(); }); result = p; } } } } return result; } private User user_; private RegistrationModel registrationModel_; private AuthModel authModel_; private Signal updated_; private Signal canceled_; private void checkPassword() { this.updateModelField(this.registrationModel_, RegistrationModel.ChoosePasswordField); this.registrationModel_.validateField(RegistrationModel.ChoosePasswordField); this.updateViewField(this.registrationModel_, RegistrationModel.ChoosePasswordField); } private void checkPassword2() { this.updateModelField(this.registrationModel_, RegistrationModel.RepeatPasswordField); this.registrationModel_.validateField(RegistrationModel.RepeatPasswordField); this.updateViewField(this.registrationModel_, RegistrationModel.RepeatPasswordField); } private boolean validate() { boolean valid = true; if (this.authModel_ != null) { this.updateModelField(this.authModel_, AuthModel.PasswordField); if (!this.authModel_.validate()) { this.updateViewField(this.authModel_, AuthModel.PasswordField); valid = false; } } this.registrationModel_.validateField(RegistrationModel.LoginNameField); this.checkPassword(); this.checkPassword2(); this.registrationModel_.validateField(RegistrationModel.EmailField); if (!this.registrationModel_.isValid()) { valid = false; } return valid; } private void doUpdate() { if (this.validate()) { String password = this.registrationModel_.valueText(RegistrationModel.ChoosePasswordField); this.registrationModel_.getPasswordAuth().updatePassword(this.user_, password); this.registrationModel_.getLogin().login(this.user_); this.updated_.trigger(); } } private void cancel() { this.canceled_.trigger(); } }
gpl-2.0
CleverCloud/Quercus
quercus/src/main/java/com/caucho/quercus/env/DefaultValue.java
3172
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.quercus.env; import java.io.IOException; import java.io.PrintWriter; /** * Represents a PHP default value. */ @SuppressWarnings("serial") public class DefaultValue extends NullValue { public static final DefaultValue DEFAULT = new DefaultValue(); private DefaultValue() { } /** * Returns the null value singleton. */ public static DefaultValue create() { return DEFAULT; } /** * Returns true for a DefaultValue */ @Override public boolean isDefault() { return true; } /** * Converts to a boolean. */ @Override public boolean toBoolean() { return false; } /** * Converts to a long. */ @Override public long toLong() { return 0; } /** * Converts to a double. */ @Override public double toDouble() { return 0; } /** * Converts to an object. */ public Object toObject() { return ""; } /** * Converts to a callable */ @Override public Callable toCallable(Env env) { return null; } /** * Prints the value. * @param env */ @Override public void print(Env env) { } /** * Converts to a string. * @param env */ @Override public String toString() { return ""; } /** * Generates code to recreate the expression. * * @param out the writer to the Java source code. */ @Override public void generate(PrintWriter out) throws IOException { out.print("DefaultValue.DEFAULT"); } /** * Generates code to recreate the expression. * * @param out the writer to the Java source code. */ public void generateLong(PrintWriter out) throws IOException { out.print("0"); } /** * Generates code to recreate the expression. * * @param out the writer to the Java source code. */ public void generateString(PrintWriter out) throws IOException { out.print("\"\""); } // // Java Serialization // private Object readResolve() { return DEFAULT; } }
gpl-2.0
bairutai/SinaWeibo
src/com/convenientbanner/CBLoopViewPager.java
6473
/* * Copyright (C) 2013 Leszek Mzyk * * 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.convenientbanner; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; /** * A ViewPager subclass enabling infinte scrolling of the viewPager elements * * When used for paginating views (in opposite to fragments), no code changes * should be needed only change xml's from <android.support.v4.view.ViewPager> * to <com.imbryk.viewPager.LoopViewPager> * * If "blinking" can be seen when paginating to first or last view, simply call * seBoundaryCaching( true ), or change DEFAULT_BOUNDARY_CASHING to true * * When using a FragmentPagerAdapter or FragmentStatePagerAdapter, * additional changes in the adapter must be done. * The adapter must be prepared to create 2 extra items e.g.: * * The original adapter creates 4 items: [0,1,2,3] * The modified adapter will have to create 6 items [0,1,2,3,4,5] * with mapping realPosition=(position-1)%count * [0->3, 1->0, 2->1, 3->2, 4->3, 5->0] */ public class CBLoopViewPager extends ViewPager { private static final boolean DEFAULT_BOUNDARY_CASHING = false; OnPageChangeListener mOuterPageChangeListener; private CBLoopPagerAdapterWrapper mAdapter; private boolean mBoundaryCaching = DEFAULT_BOUNDARY_CASHING; /** * helper function which may be used when implementing FragmentPagerAdapter * * @param position * @param count * @return (position-1)%count */ public static int toRealPosition( int position, int count ){ position = position-1; if( position < 0 ){ position += count; }else{ position = position%count; } return position; } /** * If set to true, the boundary views (i.e. first and last) will never be destroyed * This may help to prevent "blinking" of some views * * @param flag */ public void setBoundaryCaching(boolean flag) { mBoundaryCaching = flag; if (mAdapter != null) { mAdapter.setBoundaryCaching(flag); } } @Override public void setAdapter(PagerAdapter adapter) { mAdapter = new CBLoopPagerAdapterWrapper(adapter); mAdapter.setBoundaryCaching(mBoundaryCaching); super.setAdapter(mAdapter); setCurrentItem(0, false); } @Override public PagerAdapter getAdapter() { return mAdapter != null ? mAdapter.getRealAdapter() : mAdapter; } @Override public int getCurrentItem() { return mAdapter != null ? mAdapter.toRealPosition(super.getCurrentItem()) : 0; } public void setCurrentItem(int item, boolean smoothScroll) { int realItem = mAdapter.toInnerPosition(item); super.setCurrentItem(realItem, smoothScroll); } @Override public void setCurrentItem(int item) { if (getCurrentItem() != item) { setCurrentItem(item, true); } } @Override public void setOnPageChangeListener(OnPageChangeListener listener) { mOuterPageChangeListener = listener; }; public CBLoopViewPager(Context context) { super(context); init(); } public CBLoopViewPager(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { super.setOnPageChangeListener(onPageChangeListener); } private OnPageChangeListener onPageChangeListener = new OnPageChangeListener() { private float mPreviousOffset = -1; private float mPreviousPosition = -1; @Override public void onPageSelected(int position) { int realPosition = mAdapter.toRealPosition(position); if (mPreviousPosition != realPosition) { mPreviousPosition = realPosition; if (mOuterPageChangeListener != null) { mOuterPageChangeListener.onPageSelected(realPosition); } } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { int realPosition = position; if (mAdapter != null) { realPosition = mAdapter.toRealPosition(position); if (positionOffset == 0 && mPreviousOffset == 0 && (position == 0 || position == mAdapter.getCount() - 1)) { setCurrentItem(realPosition, false); } } mPreviousOffset = positionOffset; if (mOuterPageChangeListener != null) { if (realPosition != mAdapter.getRealCount() - 1) { mOuterPageChangeListener.onPageScrolled(realPosition, positionOffset, positionOffsetPixels); } else { if (positionOffset > .5) { mOuterPageChangeListener.onPageScrolled(0, 0, 0); } else { mOuterPageChangeListener.onPageScrolled(realPosition, 0, 0); } } } } @Override public void onPageScrollStateChanged(int state) { if (mAdapter != null) { int position = CBLoopViewPager.super.getCurrentItem(); int realPosition = mAdapter.toRealPosition(position); if (state == ViewPager.SCROLL_STATE_IDLE && (position == 0 || position == mAdapter.getCount() - 1)) { setCurrentItem(realPosition, false); } } if (mOuterPageChangeListener != null) { mOuterPageChangeListener.onPageScrollStateChanged(state); } } }; }
gpl-2.0
scoophealth/oscar
src/main/java/org/oscarehr/common/model/ConsultationRequest.java
10011
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL 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 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. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.common.model; import java.io.Serializable; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.apache.commons.lang.StringUtils; @Entity @Table(name = "consultationRequests") public class ConsultationRequest extends AbstractModel<Integer> implements Serializable { private static final String ACTIVE_MARKER = "1"; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "requestId") private Integer id; @Column(name = "referalDate") @Temporal(TemporalType.DATE) private Date referralDate; private Integer serviceId; @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name="specId") private ProfessionalSpecialist professionalSpecialist; @Temporal(TemporalType.DATE) private Date appointmentDate; @Temporal(TemporalType.TIME) private Date appointmentTime; @Column(name = "reason") private String reasonForReferral; private String clinicalInfo; private String currentMeds; private String allergies; private String providerNo; @Column(name = "demographicNo") private Integer demographicId; private String status = ACTIVE_MARKER; private String statusText; private String sendTo; private String concurrentProblems; private String urgency; private String appointmentInstructions; private boolean patientWillBook; @Column(name = "site_name") private String siteName; @Temporal(TemporalType.DATE) private Date followUpDate; @Column(name = "signature_img") private String signatureImg; private String letterheadName; private String letterheadAddress; private String letterheadPhone; private String letterheadFax; @Temporal(TemporalType.TIMESTAMP) private Date lastUpdateDate; private Integer fdid = null; private String source; @ManyToOne(fetch=FetchType.EAGER, targetEntity=LookupListItem.class) @JoinColumn(name="appointmentInstructions", referencedColumnName="value", insertable = false, updatable = false) private LookupListItem lookupListItem; @Override public Integer getId() { return(id); } public Date getReferralDate() { return referralDate; } public void setReferralDate(Date referralDate) { this.referralDate = referralDate; } public Integer getServiceId() { return serviceId; } public void setServiceId(Integer serviceId) { this.serviceId = serviceId; } public Date getAppointmentDate() { return appointmentDate; } public void setAppointmentDate(Date appointmentDate) { this.appointmentDate = appointmentDate; } public Date getAppointmentTime() { return appointmentTime; } public void setAppointmentTime(Date appointmentTime) { this.appointmentTime = appointmentTime; } public String getReasonForReferral() { return reasonForReferral; } public void setReasonForReferral(String reasonForReferral) { this.reasonForReferral = StringUtils.trimToNull(reasonForReferral); } public String getClinicalInfo() { return clinicalInfo; } public void setClinicalInfo(String clinicalInfo) { this.clinicalInfo = StringUtils.trimToNull(clinicalInfo); } public String getCurrentMeds() { return currentMeds; } public void setCurrentMeds(String currentMeds) { this.currentMeds = StringUtils.trimToNull(currentMeds); } public String getAllergies() { return allergies; } public void setAllergies(String allergies) { this.allergies = StringUtils.trimToNull(allergies); } public String getProviderNo() { return providerNo; } public void setProviderNo(String providerNo) { this.providerNo = StringUtils.trimToNull(providerNo); } public Integer getDemographicId() { return demographicId; } public void setDemographicId(Integer demographicId) { this.demographicId = demographicId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = StringUtils.trimToNull(status); } public String getStatusText() { return statusText; } public void setStatusText(String statusText) { this.statusText = StringUtils.trimToNull(statusText); } public String getSendTo() { return sendTo; } public void setSendTo(String sendTo) { this.sendTo = StringUtils.trimToNull(sendTo); } public String getConcurrentProblems() { return concurrentProblems; } public void setConcurrentProblems(String concurrentProblems) { this.concurrentProblems = StringUtils.trimToNull(concurrentProblems); } public String getUrgency() { return urgency; } public void setUrgency(String urgency) { this.urgency = StringUtils.trimToNull(urgency); } public String getSiteName() { return siteName; } public void setSiteName(String siteName) { this.siteName = siteName; } public boolean isPatientWillBook() { return patientWillBook; } public void setPatientWillBook(boolean patientWillBook) { this.patientWillBook = patientWillBook; } /** * @return the followUpDate */ public Date getFollowUpDate() { return followUpDate; } /** * @param followUpDate the followUpDate to set */ public void setFollowUpDate(Date followUpDate) { this.followUpDate = followUpDate; } /** * @return the professionalSpecialist */ public ProfessionalSpecialist getProfessionalSpecialist() { return professionalSpecialist; } /** * @param professionalSpecialist the professionalSpecialist to set */ public void setProfessionalSpecialist(ProfessionalSpecialist professionalSpecialist) { this.professionalSpecialist = professionalSpecialist; } public Integer getSpecialistId() { if(professionalSpecialist != null) return this.professionalSpecialist.getId(); else return null; } public String getSignatureImg() { return signatureImg; } public void setSignatureImg(String signatureImg) { this.signatureImg = signatureImg; } public String getLetterheadName() { return letterheadName; } public void setLetterheadName(String letterheadName) { this.letterheadName = letterheadName; } public String getLetterheadAddress() { return letterheadAddress; } public void setLetterheadAddress(String letterheadAddress) { this.letterheadAddress = letterheadAddress; } public String getLetterheadPhone() { return letterheadPhone; } public void setLetterheadPhone(String letterheadPhone) { this.letterheadPhone = letterheadPhone; } public String getLetterheadFax() { return letterheadFax; } public void setLetterheadFax(String letterheadFax) { this.letterheadFax = letterheadFax; } public Integer getFdid() { return fdid; } public void setFdid(Integer fdid) { this.fdid = fdid; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } @PrePersist @PreUpdate protected void jpa_updateLastDateUpdated() { lastUpdateDate = new Date(); } /** * returns the appointment instructions value. * This can be a display value or select list value * if the Lookup List interface is used. * If the table contains a hash key it most likely is a * primary key association in the LookupListItem table. */ public String getAppointmentInstructions() { return appointmentInstructions; } public void setAppointmentInstructions(String appointmentInstructions) { this.appointmentInstructions = appointmentInstructions; } /** * Returns the display label of the Appointment Instruction if * the Lookup List interface is being used. * Empty string otherwise. */ @Transient public String getAppointmentInstructionsLabel() { if( lookupListItem != null ) { return lookupListItem.getLabel(); } return ""; } /** * This will be bound if the Appointment Instructions * value is found as a unique match in the LookupListItem * table. */ public LookupListItem getLookupListItem() { return lookupListItem; } public void setLookupListItem(LookupListItem lookupListItem) { this.lookupListItem = lookupListItem; } public Date getLastUpdateDate() { return lastUpdateDate; } public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } }
gpl-2.0
TranceCake/SoftwareEngineering
leertaak3DynamicProgramming/leertaak4MobileRobot/src/model/device/Device.java
3923
package model.device; /** * Title : The Mobile Robot Explorer Simulation Environment v2.0 * Copyright: GNU General Public License as published by the Free Software Foundation * Company : Hanze University of Applied Sciences * * @author Dustin Meijer (2012) * @author Alexander Jeurissen (2012) * @author Davide Brugali (2002) * @version 2.0 */ import model.environment.Environment; import model.environment.Position; import model.robot.MobileRobot; import java.awt.Polygon; import java.awt.Color; import java.io.PrintWriter; import java.util.ArrayList; public abstract class Device implements Runnable { // A final object to make sure the lock cannot be overwritten with another Object private final Object lock = new Object(); private final String name; // the name of this device private final Polygon shape; // the device's shape in local coords // a reference to the environment protected final Environment environment; // a reference to the robot protected final MobileRobot robot; // origin of the device reference frame with regards to the robot frame protected final Position localPosition; // the robot current position protected Position robotPosition; // the arrayList with all the commands protected final ArrayList<String> commands; // the colors of the devices protected Color backgroundColor = Color.red; protected Color foregroundColor = Color.blue; // Is the device running? protected boolean running; // Is the device executingCommand a command? protected boolean executingCommand; private PrintWriter output; // the constructor protected Device(String name, MobileRobot robot, Position local, Environment environment) { this.name = name; this.robot = robot; this.localPosition = local; this.environment = environment; this.shape = new Polygon(); this.robotPosition = new Position(); this.running = true; this.executingCommand = false; this.commands = new ArrayList<String>(); this.output = null; robot.readPosition(this.robotPosition); } // this method is invoked when the geometric shape of the device is defined protected void addPoint(int x, int y) { shape.addPoint(x, y); } public boolean sendCommand(String command) { commands.add(command); synchronized (lock) { // Notify the tread that is waiting for commands. lock.notify(); } return true; } protected synchronized void writeOut(String data) { if (output != null) { output.println(data); } else { System.out.println(this.name + " output not initialized"); } } public void setOutput(PrintWriter output) { this.output = output; } public void run() { System.out.println("Device " + this.name + " running"); do { try { if (executingCommand) { // pause before the next step synchronized (this) { Thread.sleep(MobileRobot.delay); } } else if (commands.size() > 0) { // extracts the the next command and executes it String command = commands.remove(0); executeCommand(command); } else { // waits for a new command synchronized (lock) { // Wait to be notified about a new command (in sendCommand()). lock.wait(); } } // processes a new step nextStep(); } catch (InterruptedException ie) { System.err.println("Device : Run was interrupted."); } } while (this.running); } public Position getRobotPosition() { return robotPosition; } public Position getLocalPosition() { return localPosition; } public Polygon getShape() { return shape; } public Color getBackgroundColor() { return backgroundColor; } public Color getForegroundColor() { return foregroundColor; } public String getName() { return name; } protected abstract void executeCommand(String command); protected abstract void nextStep(); }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/commons-validator/org/apache/commons/validator/routines/AbstractCalendarValidator.java
16430
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.DateFormatSymbols; import java.text.Format; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; /** * <p>Abstract class for Date/Time/Calendar validation.</p> * * <p>This is a <i>base</i> class for building Date / Time * Validators using format parsing.</p> * * @version $Revision: 1739356 $ * @since Validator 1.3.0 */ public abstract class AbstractCalendarValidator extends AbstractFormatValidator { private static final long serialVersionUID = -1410008585975827379L; private final int dateStyle; private final int timeStyle; /** * Construct an instance with the specified <i>strict</i>, * <i>time</i> and <i>date</i> style parameters. * * @param strict <code>true</code> if strict * <code>Format</code> parsing should be used. * @param dateStyle the date style to use for Locale validation. * @param timeStyle the time style to use for Locale validation. */ public AbstractCalendarValidator(boolean strict, int dateStyle, int timeStyle) { super(strict); this.dateStyle = dateStyle; this.timeStyle = timeStyle; } /** * <p>Validate using the specified <code>Locale</code>. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format, defaults to the default * @return <code>true</code> if the value is valid. */ @Override public boolean isValid(String value, String pattern, Locale locale) { Object parsedValue = parse(value, pattern, locale, (TimeZone)null); return (parsedValue == null ? false : true); } /** * <p>Format an object into a <code>String</code> using * the default Locale.</p> * * @param value The value validation is being performed on. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a <code>Calendar</code>. * @return The value formatted as a <code>String</code>. */ public String format(Object value, TimeZone timeZone) { return format(value, (String)null, (Locale)null, timeZone); } /** * <p>Format an object into a <code>String</code> using * the specified pattern.</p> * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a <code>Calendar</code>. * @return The value formatted as a <code>String</code>. */ public String format(Object value, String pattern, TimeZone timeZone) { return format(value, pattern, (Locale)null, timeZone); } /** * <p>Format an object into a <code>String</code> using * the specified Locale.</p> * * @param value The value validation is being performed on. * @param locale The locale to use for the Format. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a <code>Calendar</code>. * @return The value formatted as a <code>String</code>. */ public String format(Object value, Locale locale, TimeZone timeZone) { return format(value, (String)null, locale, timeZone); } /** * <p>Format an object using the specified pattern and/or * <code>Locale</code>. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format. * @return The value formatted as a <code>String</code>. */ @Override public String format(Object value, String pattern, Locale locale) { return format(value, pattern, locale, (TimeZone)null); } /** * <p>Format an object using the specified pattern and/or * <code>Locale</code>. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a <code>Calendar</code>. * @return The value formatted as a <code>String</code>. */ public String format(Object value, String pattern, Locale locale, TimeZone timeZone) { DateFormat formatter = (DateFormat)getFormat(pattern, locale); if (timeZone != null) { formatter.setTimeZone(timeZone); } else if (value instanceof Calendar) { formatter.setTimeZone(((Calendar)value).getTimeZone()); } return format(value, formatter); } /** * <p>Format a value with the specified <code>DateFormat</code>.</p> * * @param value The value to be formatted. * @param formatter The Format to use. * @return The formatted value. */ @Override protected String format(Object value, Format formatter) { if (value == null) { return null; } else if (value instanceof Calendar) { value = ((Calendar)value).getTime(); } return formatter.format(value); } /** * <p>Checks if the value is valid against a specified pattern.</p> * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the <code>Locale</code> if <code>null</code>. * @param locale The locale to use for the date format, system default if null. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed value if valid or <code>null</code> if invalid. */ protected Object parse(String value, String pattern, Locale locale, TimeZone timeZone) { value = (value == null ? null : value.trim()); if (value == null || value.length() == 0) { return null; } DateFormat formatter = (DateFormat)getFormat(pattern, locale); if (timeZone != null) { formatter.setTimeZone(timeZone); } return parse(value, formatter); } /** * <p>Process the parsed value, performing any further validation * and type conversion required.</p> * * @param value The parsed object created. * @param formatter The Format used to parse the value with. * @return The parsed value converted to the appropriate type * if valid or <code>null</code> if invalid. */ @Override protected abstract Object processParsedValue(Object value, Format formatter); /** * <p>Returns a <code>DateFormat</code> for the specified <i>pattern</i> * and/or <code>Locale</code>.</p> * * @param pattern The pattern used to validate the value against or * <code>null</code> to use the default for the <code>Locale</code>. * @param locale The locale to use for the currency format, system default if null. * @return The <code>DateFormat</code> to created. */ @Override protected Format getFormat(String pattern, Locale locale) { DateFormat formatter = null; boolean usePattern = (pattern != null && pattern.length() > 0); if (!usePattern) { formatter = (DateFormat)getFormat(locale); } else if (locale == null) { formatter = new SimpleDateFormat(pattern); } else { DateFormatSymbols symbols = new DateFormatSymbols(locale); formatter = new SimpleDateFormat(pattern, symbols); } formatter.setLenient(false); return formatter; } /** * <p>Returns a <code>DateFormat</code> for the specified Locale.</p> * * @param locale The locale a <code>DateFormat</code> is required for, * system default if null. * @return The <code>DateFormat</code> to created. */ protected Format getFormat(Locale locale) { DateFormat formatter = null; if (dateStyle >= 0 && timeStyle >= 0) { if (locale == null) { formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle); } else { formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); } } else if (timeStyle >= 0) { if (locale == null) { formatter = DateFormat.getTimeInstance(timeStyle); } else { formatter = DateFormat.getTimeInstance(timeStyle, locale); } } else { int useDateStyle = dateStyle >= 0 ? dateStyle : DateFormat.SHORT; if (locale == null) { formatter = DateFormat.getDateInstance(useDateStyle); } else { formatter = DateFormat.getDateInstance(useDateStyle, locale); } } formatter.setLenient(false); return formatter; } /** * <p>Compares a calendar value to another, indicating whether it is * equal, less then or more than at a specified level.</p> * * @param value The Calendar value. * @param compare The <code>Calendar</code> to check the value against. * @param field The field <i>level</i> to compare to - e.g. specifying * <code>Calendar.MONTH</code> will compare the year and month * portions of the calendar. * @return Zero if the first value is equal to the second, -1 * if it is less than the second or +1 if it is greater than the second. */ protected int compare(Calendar value, Calendar compare, int field) { int result = 0; // Compare Year result = calculateCompareResult(value, compare, Calendar.YEAR); if (result != 0 || field == Calendar.YEAR) { return result; } // Compare Week of Year if (field == Calendar.WEEK_OF_YEAR) { return calculateCompareResult(value, compare, Calendar.WEEK_OF_YEAR); } // Compare Day of the Year if (field == Calendar.DAY_OF_YEAR) { return calculateCompareResult(value, compare, Calendar.DAY_OF_YEAR); } // Compare Month result = calculateCompareResult(value, compare, Calendar.MONTH); if (result != 0 || field == Calendar.MONTH) { return result; } // Compare Week of Month if (field == Calendar.WEEK_OF_MONTH) { return calculateCompareResult(value, compare, Calendar.WEEK_OF_MONTH); } // Compare Date result = calculateCompareResult(value, compare, Calendar.DATE); if (result != 0 || (field == Calendar.DATE || field == Calendar.DAY_OF_WEEK || field == Calendar.DAY_OF_WEEK_IN_MONTH)) { return result; } // Compare Time fields return compareTime(value, compare, field); } /** * <p>Compares a calendar time value to another, indicating whether it is * equal, less then or more than at a specified level.</p> * * @param value The Calendar value. * @param compare The <code>Calendar</code> to check the value against. * @param field The field <i>level</i> to compare to - e.g. specifying * <code>Calendar.MINUTE</code> will compare the hours and minutes * portions of the calendar. * @return Zero if the first value is equal to the second, -1 * if it is less than the second or +1 if it is greater than the second. */ protected int compareTime(Calendar value, Calendar compare, int field) { int result = 0; // Compare Hour result = calculateCompareResult(value, compare, Calendar.HOUR_OF_DAY); if (result != 0 || (field == Calendar.HOUR || field == Calendar.HOUR_OF_DAY)) { return result; } // Compare Minute result = calculateCompareResult(value, compare, Calendar.MINUTE); if (result != 0 || field == Calendar.MINUTE) { return result; } // Compare Second result = calculateCompareResult(value, compare, Calendar.SECOND); if (result != 0 || field == Calendar.SECOND) { return result; } // Compare Milliseconds if (field == Calendar.MILLISECOND) { return calculateCompareResult(value, compare, Calendar.MILLISECOND); } throw new IllegalArgumentException("Invalid field: " + field); } /** * <p>Compares a calendar's quarter value to another, indicating whether it is * equal, less then or more than the specified quarter.</p> * * @param value The Calendar value. * @param compare The <code>Calendar</code> to check the value against. * @param monthOfFirstQuarter The month that the first quarter starts. * @return Zero if the first quarter is equal to the second, -1 * if it is less than the second or +1 if it is greater than the second. */ protected int compareQuarters(Calendar value, Calendar compare, int monthOfFirstQuarter) { int valueQuarter = calculateQuarter(value, monthOfFirstQuarter); int compareQuarter = calculateQuarter(compare, monthOfFirstQuarter); if (valueQuarter < compareQuarter) { return -1; } else if (valueQuarter > compareQuarter) { return 1; } else { return 0; } } /** * <p>Calculate the quarter for the specified Calendar.</p> * * @param calendar The Calendar value. * @param monthOfFirstQuarter The month that the first quarter starts. * @return The calculated quarter. */ private int calculateQuarter(Calendar calendar, int monthOfFirstQuarter) { // Add Year int year = calendar.get(Calendar.YEAR); int month = (calendar.get(Calendar.MONTH) + 1); int relativeMonth = (month >= monthOfFirstQuarter) ? (month - monthOfFirstQuarter) : (month + (12 - monthOfFirstQuarter)); // CHECKSTYLE IGNORE MagicNumber int quarter = ((relativeMonth / 3) + 1); // CHECKSTYLE IGNORE MagicNumber // adjust the year if the quarter doesn't start in January if (month < monthOfFirstQuarter) { --year; } return (year * 10) + quarter; // CHECKSTYLE IGNORE MagicNumber } /** * <p>Compares the field from two calendars indicating whether the field for the * first calendar is equal to, less than or greater than the field from the * second calendar. * * @param value The Calendar value. * @param compare The <code>Calendar</code> to check the value against. * @param field The field to compare for the calendars. * @return Zero if the first calendar's field is equal to the seconds, -1 * if it is less than the seconds or +1 if it is greater than the seconds. */ private int calculateCompareResult(Calendar value, Calendar compare, int field) { int difference = value.get(field) - compare.get(field); if (difference < 0) { return -1; } else if (difference > 0) { return 1; } else { return 0; } } }
gpl-2.0
haroldoramirez/geocab
implementation/solution/src/test/java/br/com/geocab/tests/service/DataSourceServiceTest.java
2971
/** * */ package br.com.geocab.tests.service; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import br.com.geocab.domain.entity.datasource.DataSource; import br.com.geocab.domain.service.DataSourceService; import br.com.geocab.tests.AbstractIntegrationTest; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; /** * @author Lucas * */ public class DataSourceServiceTest extends AbstractIntegrationTest { @Autowired private DataSourceService dataSourceService; @Test @DatabaseSetup(type=DatabaseOperation.INSERT, value={ "/dataset/AccountDataSet.xml" }) public void insertDataSouce() { this.authenticate(100L); DataSource dataSource = new DataSource(); dataSource.setName("Data Source"); dataSource.setLogin("user"); dataSource.setPassword("password123"); // dataSource.setInternal(true); dataSource.setUrl("url1"); dataSource = dataSourceService.insertDataSource(dataSource); Assert.assertNotNull(dataSource); Assert.assertEquals("Data Source", dataSource.getName()); Assert.assertEquals("user", dataSource.getLogin()); Assert.assertEquals("password123", dataSource.getPassword()); Assert.assertEquals("url1", dataSource.getUrl()); // Assert.assertTrue(dataSource.getInternal()); } @Test @DatabaseSetup(type=DatabaseOperation.INSERT, value={ "/dataset/DataSourceDataSet.xml", "/dataset/AccountDataSet.xml" }) public void updateDataSource() throws Exception { this.authenticate(100L); DataSource dataSource = dataSourceService.findDataSourceById(100L); dataSource.setName("Data Source changed"); dataSource.setLogin("user changed"); dataSource.setPassword("password123 changed"); dataSource.setUrl("url1 changed"); // dataSource.setInternal(false); dataSource = dataSourceService.updateDataSource(dataSource); Assert.assertNotNull(dataSource); Assert.assertEquals("Data Source changed", dataSource.getName()); Assert.assertEquals("user changed", dataSource.getLogin()); Assert.assertEquals("password123 changed", dataSource.getPassword()); Assert.assertEquals("url1 changed", dataSource.getUrl()); // Assert.assertFalse(dataSource.getInternal()); } @Test @DatabaseSetup(type=DatabaseOperation.INSERT, value={ "/dataset/DataSourceDataSet.xml", "/dataset/AccountDataSet.xml" }) public void findFonteDadosById() throws Exception { this.authenticate(100L); DataSource dataSource = dataSourceService.findDataSourceById(100L); Assert.assertNotNull(dataSource); Assert.assertTrue(dataSource.getId().equals(100L)); } @Test @DatabaseSetup(type=DatabaseOperation.INSERT, value={ "/dataset/DataSourceDataSet.xml", "/dataset/AccountDataSet.xml" }) public void removeDataSource() { this.authenticate(100L); this.dataSourceService.removeDataSource(100L); } }
gpl-2.0
beckpalmx/ImportTask
src/com/cgc/bean/MessageBean.java
3859
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.cgc.bean; import java.sql.Timestamp; /** * * @author com02 */ public class MessageBean { private int runno; private String message_id; private String message_detail; private String status; private Timestamp create_date; private String create_by; private Timestamp update_date; private String update_by; private String delete_flag; private Timestamp delete_date; private String delete_by; private String company_id; /** * @return the runno */ public int getRunno() { return runno; } /** * @param runno the runno to set */ public void setRunno(int runno) { this.runno = runno; } /** * @return the message_id */ public String getMessage_id() { return message_id; } /** * @param message_id the message_id to set */ public void setMessage_id(String message_id) { this.message_id = message_id; } /** * @return the message_detail */ public String getMessage_detail() { return message_detail; } /** * @param message_detail the message_detail to set */ public void setMessage_detail(String message_detail) { this.message_detail = message_detail; } /** * @return the status */ public String getStatus() { return status; } /** * @param status the status to set */ public void setStatus(String status) { this.status = status; } /** * @return the create_date */ public Timestamp getCreate_date() { return create_date; } /** * @param create_date the create_date to set */ public void setCreate_date(Timestamp create_date) { this.create_date = create_date; } /** * @return the create_by */ public String getCreate_by() { return create_by; } /** * @param create_by the create_by to set */ public void setCreate_by(String create_by) { this.create_by = create_by; } /** * @return the update_date */ public Timestamp getUpdate_date() { return update_date; } /** * @param update_date the update_date to set */ public void setUpdate_date(Timestamp update_date) { this.update_date = update_date; } /** * @return the update_by */ public String getUpdate_by() { return update_by; } /** * @param update_by the update_by to set */ public void setUpdate_by(String update_by) { this.update_by = update_by; } /** * @return the delete_flag */ public String getDelete_flag() { return delete_flag; } /** * @param delete_flag the delete_flag to set */ public void setDelete_flag(String delete_flag) { this.delete_flag = delete_flag; } /** * @return the delete_date */ public Timestamp getDelete_date() { return delete_date; } /** * @param delete_date the delete_date to set */ public void setDelete_date(Timestamp delete_date) { this.delete_date = delete_date; } /** * @return the delete_by */ public String getDelete_by() { return delete_by; } /** * @param delete_by the delete_by to set */ public void setDelete_by(String delete_by) { this.delete_by = delete_by; } /** * @return the company_id */ public String getCompany_id() { return company_id; } /** * @param company_id the company_id to set */ public void setCompany_id(String company_id) { this.company_id = company_id; } }
gpl-2.0
vince-from-nice/osmaxil
src/main/java/org/openstreetmap/osmaxil/Application.java
1528
package org.openstreetmap.osmaxil; import org.apache.log4j.Logger; import org.openstreetmap.osmaxil.flow.__AbstractImportFlow; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Component; @Component("OsmaxilApp") public class Application { @Value("${osmaxil.flow}") public String flow; public static final String NAME = "Osmaxil"; private static ClassPathXmlApplicationContext applicationContext; static private final Logger LOGGER = Logger.getLogger(Application.class); static protected final Logger LOGGER_FOR_STATS = Logger.getLogger("LoggerForStats"); public static void main(String[] args) { applicationContext = new ClassPathXmlApplicationContext("spring.xml"); Application app = (Application) applicationContext.getBean("OsmaxilApp"); LOGGER.info("=== Starting Osmaxil ==="); long startTime = System.currentTimeMillis(); try { app.run(); } catch (Exception e) { LOGGER.error(e); } LOGGER_FOR_STATS.info("Job has been executed in " + (System.currentTimeMillis() - startTime) / 1000 + " seconds"); LOGGER.info("=== Osmaxil has finished its job ==="); applicationContext.close(); } public void run() throws Exception { __AbstractImportFlow<?, ?> flow = (__AbstractImportFlow<?, ?>) applicationContext.getBean(this.flow); flow.load(); flow.process(); flow.synchronize(); flow.displayLoadingStatistics(); flow.displayProcessingStatistics(); } }
gpl-2.0
AlanGuerraQuispe/SisAtuxPerfumeria
atux-jrcp/src/main/java/com/aw/swing/mvp/action/BackBeanProvider.java
1684
package com.aw.swing.mvp.action; import com.aw.swing.mvp.Presenter; import com.aw.swing.mvp.navigation.Flow; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import java.util.Iterator; import java.util.Map; /** * User: gmc * Date: 16/05/2009 */ public class BackBeanProvider { protected Log logger = LogFactory.getLog(getClass()); public BackBeanProvider() { } /** * Return the back bean that must be used. * * @return */ public Object getBackBean(Presenter targetPst,Flow flow) { Object backBean = null; backBean = flow.getTargetBackBeanAttr(); if (backBean == null) { backBean = targetPst.createBackBean(); } decorateBackBeanWithFlowAttributes(backBean, flow); return backBean; } /** * Decorate the back bean with the attributes sent in the flow * * @param backBean * @param flow */ private void decorateBackBeanWithFlowAttributes(Object backBean, Flow flow) { Map flowAttributes = flow.getAttributes(); BeanWrapper bwBackBean = new BeanWrapperImpl(backBean); for (Iterator iterator = flowAttributes.keySet().iterator(); iterator.hasNext();) { String flowAttributeName = (String) iterator.next(); if (bwBackBean.isWritableProperty(flowAttributeName)) { bwBackBean.setPropertyValue(flowAttributeName, flowAttributes.get(flowAttributeName)); } } } }
gpl-2.0
tomaszbabiuk/geekhome-asymptote
asymptote/src/main/java/eu/geekhome/asymptote/model/SyncUpdateBase.java
335
package eu.geekhome.asymptote.model; public abstract class SyncUpdateBase<T> implements SyncUpdate<T> { private T _value; @Override public T getValue() { return _value; } public void setValue(T value) { _value = value; } public SyncUpdateBase(T value) { _value = value; } }
gpl-2.0
lazcatluc/agileim
src/main/java/com/meetup/agileim/web/rest/errors/ExceptionTranslator.java
2547
package com.meetup.agileim.web.rest.errors; import java.util.List; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.*; /** * Controller advice to translate the server side exceptions to client-friendly json structures. */ @ControllerAdvice public class ExceptionTranslator { @ExceptionHandler(ConcurrencyFailureException.class) @ResponseStatus(HttpStatus.CONFLICT) @ResponseBody public ErrorDTO processConcurencyError(ConcurrencyFailureException ex) { return new ErrorDTO(ErrorConstants.ERR_CONCURRENCY_FAILURE); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorDTO processValidationError(MethodArgumentNotValidException ex) { BindingResult result = ex.getBindingResult(); List<FieldError> fieldErrors = result.getFieldErrors(); return processFieldErrors(fieldErrors); } @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ParameterizedErrorDTO processParameterizedValidationError(CustomParameterizedException ex) { return ex.getErrorDTO(); } @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody public ErrorDTO processAccessDeniedExcpetion(AccessDeniedException e) { return new ErrorDTO(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage()); } private ErrorDTO processFieldErrors(List<FieldError> fieldErrors) { ErrorDTO dto = new ErrorDTO(ErrorConstants.ERR_VALIDATION); for (FieldError fieldError : fieldErrors) { dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode()); } return dto; } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) public ErrorDTO processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) { return new ErrorDTO(ErrorConstants.ERR_METHOD_NOT_SUPPORTED, exception.getMessage()); } }
gpl-2.0
ncedu-tlt/ecomm
src/main/java/ru/ncedu/ecomm/servlets/services/passwordRecovery/PasswordRecoveryService.java
2999
package ru.ncedu.ecomm.servlets.services.passwordRecovery; import ru.ncedu.ecomm.data.models.dao.UserDAOObject; import java.util.ArrayList; import java.util.List; import java.util.Random; import static ru.ncedu.ecomm.data.DAOFactory.getDAOFactory; public class PasswordRecoveryService { private final static String ERROR_FOUND_EMAIL = "ErrorEmailNotFound"; private final static String SUCCESS_SEND = "SuccessSend"; private final static String ERROR_SEND = "ErrorSend"; private final static int MAX_HASH = 10; private final static int MAX_NUMBER = 9; private PasswordRecoveryService() { } private static PasswordRecoveryService instance; public static synchronized PasswordRecoveryService getInstance() { if (instance == null) { instance = new PasswordRecoveryService(); } return instance; } public String sendMailToUser(String toEmail, String contextPath) { UserDAOObject userByEmail = getDAOFactory().getUserDAO().getUserByEmail(toEmail); if (userByEmail == null) return ERROR_FOUND_EMAIL; userByEmail.setRecoveryHash(getRecoveryHash()); return sendMailToUser(userByEmail, contextPath); } private String getRecoveryHash() { String recoveryHash; UserDAOObject userByHash; do { recoveryHash = generateRecoveryHash(); userByHash = getDAOFactory().getUserDAO().getUserByRecoveryHash(recoveryHash); } while (userByHash != null); return recoveryHash; } private String generateRecoveryHash() { List<Integer> uniqueHashCollection = new ArrayList<>(); addHashToCollection(uniqueHashCollection); return getHashFromCollection(uniqueHashCollection); } private void addHashToCollection(List<Integer> uniqueHash) { Random random = new Random(); while (uniqueHash.size() < MAX_HASH) { uniqueHash.add(random.nextInt(MAX_NUMBER)); } } private String getHashFromCollection(List<Integer> uniqueHashCollection) { StringBuilder recoveryHash = new StringBuilder(MAX_HASH); for (int hash : uniqueHashCollection) { recoveryHash.append(hash); } return recoveryHash.toString(); } private String sendMailToUser(UserDAOObject user, String contextPath) { String textHTML = getTextHtml(user.getEmail(), user.getRecoveryHash(), contextPath); getDAOFactory().getUserDAO().updateUser(user); return SendMailService.getInstance().isSentLetterToEmail(user.getEmail(), textHTML) ? SUCCESS_SEND : ERROR_SEND; } private String getTextHtml(String toEmail, String recoveryHash, String contextPath) { return "<p>Please change your password in here:</p>" + "<a href='" + contextPath + "/passwordChange?email=" + toEmail + "&recoveryHash=" + recoveryHash + "'>Change Password</a>"; } }
gpl-3.0
casetools/rcase
rcase/src/main/java/edu/casetools/rcase/modelio/diagrams/requirements/tools/relations/SatisfyTool.java
3013
/* * Copyright 2015 @author Unai Alegre * * This file is part of R-CASE (Requirements for Context-Aware Systems Engineering), a module * of Modelio that aids the requirements elicitation phase of a Context-Aware System (C-AS). * * R-CASE 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. * * R-CASE 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 Modelio. If not, see <http://www.gnu.org/licenses/>. * */ package edu.casetools.rcase.modelio.diagrams.requirements.tools.relations; import org.modelio.api.modelio.diagram.IDiagramGraphic; import org.modelio.api.modelio.diagram.IDiagramHandle; import org.modelio.metamodel.uml.infrastructure.Dependency; import org.modelio.metamodel.uml.infrastructure.ModelElement; import edu.casetools.rcase.modelio.diagrams.RelationTool; import edu.casetools.rcase.module.api.RCaseStereotypes; import edu.casetools.rcase.module.impl.RCaseModule; import edu.casetools.rcase.module.impl.RCasePeerModule; import edu.casetools.rcase.utils.ElementUtils; /** * The Class SatisfyTool is the tool for creating a Satisfy relation. */ public class SatisfyTool extends RelationTool { /* * (non-Javadoc) * * @see * org.modelio.api.diagram.tools.DefaultLinkTool#acceptFirstElement(org. * modelio.api.diagram.IDiagramHandle, * org.modelio.api.diagram.IDiagramGraphic) */ @Override public boolean acceptFirstElement(IDiagramHandle representation, IDiagramGraphic target) { return acceptAnyElement(target); } /* * (non-Javadoc) * * @see * org.modelio.api.diagram.tools.DefaultLinkTool#acceptSecondElement(org * .modelio.api.diagram.IDiagramHandle, * org.modelio.api.diagram.IDiagramGraphic, * org.modelio.api.diagram.IDiagramGraphic) */ @Override public boolean acceptSecondElement(IDiagramHandle representation, IDiagramGraphic source, IDiagramGraphic target) { return acceptElement(RCasePeerModule.MODULE_NAME, target, RCaseStereotypes.STEREOTYPE_REQUIREMENT); } /* * (non-Javadoc) * * @see edu.casesuite.modelio.diagrams.RelationTool# * createDependency(org.modelio.metamodel.uml.infrastructure.ModelElement, * org.modelio.metamodel.uml.infrastructure.ModelElement) */ @Override public Dependency createDependency(ModelElement originElement, ModelElement targetElement) { return ElementUtils.getInstance().createDependency(RCaseModule.getInstance(), RCasePeerModule.MODULE_NAME, originElement, targetElement, RCaseStereotypes.STEREOTYPE_SATISFY); } }
gpl-3.0
PhoenixDevTeam/Phoenix-for-VK
app/src/main/java/biz/dealnote/messenger/util/FormatUtil.java
1322
package biz.dealnote.messenger.util; import android.content.Context; import android.text.Spannable; import java.text.DateFormat; import java.util.Date; import biz.dealnote.messenger.R; import biz.dealnote.messenger.link.internal.OwnerLinkSpanFactory; /** * Created by admin on 17.06.2017. * phoenix */ public class FormatUtil { public static Spannable formatCommunityBanInfo(Context context, int adminId, String adminName, long endDate, OwnerLinkSpanFactory.ActionListener adminClickListener){ String endDateString; if(endDate == 0){ endDateString = context.getString(R.string.forever).toLowerCase(); } else { Date date = new Date(endDate * 1000); String formattedDate = DateFormat.getDateInstance().format(date); String formattedTime = DateFormat.getTimeInstance().format(date); endDateString = context.getString(R.string.until_date_time, formattedDate, formattedTime); } String adminLink = OwnerLinkSpanFactory.genOwnerLink(adminId, adminName); String fullInfoText = context.getString(R.string.ban_admin_and_date_text, adminLink, endDateString); return OwnerLinkSpanFactory.withSpans(fullInfoText, true, false, adminClickListener); } }
gpl-3.0
waikato-datamining/adams-base
adams-core/src/main/java/adams/core/base/MavenArtifactExclusion.java
2905
/* * 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/>. */ /* * MavenArtifactExclusion.java * Copyright (C) 2021 University of Waikato, Hamilton, NZ */ package adams.core.base; /** * Encapsulates Maven artifact exclusions. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class MavenArtifactExclusion extends AbstractBaseString { private static final long serialVersionUID = 1516586362049381050L; public final static String SEPARATOR = ":"; /** * Initializes the string with length 0. */ public MavenArtifactExclusion() { this(""); } /** * Initializes the object with the string to parse. * * @param s the string to parse */ public MavenArtifactExclusion(String s) { super(s); } /** * Initializes the object with the artifact coordinates. * * @param groupId the group ID * @param artifactId the artifact ID */ public MavenArtifactExclusion(String groupId, String artifactId) { super(groupId + SEPARATOR + artifactId); } /** * Checks whether the string value is a valid presentation for this class. * * @param value the string value to check * @return true if non-null */ @Override public boolean isValid(String value) { return (value != null) && (value.split(SEPARATOR).length == 2); } /** * Returns the specified part of the coordinate triplet. * * @param index the index from the triplet to return * @return the value or empty string if invalid string or index */ protected String getPart(int index) { String[] parts; if (isEmpty()) return ""; parts = getValue().split(SEPARATOR); if (parts.length != 2) return ""; return parts[index]; } /** * Returns the group ID part, if possible. * * @return the group ID */ public String groupIdValue() { return getPart(0); } /** * Returns the artifact ID part, if possible. * * @return the artifact ID */ public String artifactIdValue() { return getPart(1); } /** * Returns a tool tip for the GUI editor (ignored if null is returned). * * @return the tool tip */ @Override public String getTipText() { return "The two coordinates of a Maven artifact exclusion: groupId:artifactId"; } }
gpl-3.0
sandakith/TRRuSST
TrWebApp/src/main/java/org/trrusst/software/recommender/TrustBasedServiceRecommender.java
2115
package org.trrusst.software.recommender; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by lahiru.gallege */ public class TrustBasedServiceRecommender extends HttpServlet implements Servlet { // Logger for the servlet private static final Logger log = Logger.getLogger(TrustBasedServiceRecommender.class.getName()); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the form parameters //String spList = (String)request.getParameter("spList"); String query = (String)request.getParameter("TrustBased"); String qos = (String)request.getParameter("QoS"); //System.out.println("Inside A : " + query); String sqlQuery = "select id,title,score from App.AzSoftware where title like '%" + query + "%' and text like '%" + qos +"%'"; String[] resultSet = DerbyDBUtil.getResults(sqlQuery); List<ServiceDAO> spList = new ArrayList<ServiceDAO>(); for (int i = 0 ; i < resultSet.length ; i++){ String[] resultArray = resultSet[i].split(","); ServiceDAO serviceDAO = new ServiceDAO(); serviceDAO.setId(resultArray[0]); serviceDAO.setName(resultArray[1]); serviceDAO.setRating(resultArray[2]); spList.add(serviceDAO); } // Set Request Attributes request.setAttribute("recommendedTrustList", spList); request.setAttribute("selection", "TrustBased"); // Log the request status log.log(Level.INFO, "Tagging Automatic Recommendations : " + "| Description : " + "None"); // Forward the request back request.getRequestDispatcher("/recommendServiceProviders.jsp").forward(request, response); } }
gpl-3.0
beia/beialand
projects/solomon/Server/SolomonServer/src/solomonserver/SolomonServer.java
11938
/* * 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 solomonserver; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import runnables.ConnectClientsRunnable; import runnables.ConnectToUnityDemoRunnable; import runnables.ProcessDatabaseDataRunnable; /** * * @author beia */ public class SolomonServer { //solomon server variables public static ServerSocket serverSocket; public static Thread connectClients; public static Thread processDatabaseData; //unity demo server variables public static ServerSocket unityDemoServerSocket; public static Socket unityDemoSocket; public static Thread connectToUnityDemoThread; //sql server variables public static String error; public static Connection con; //data processing variables public static volatile int lastLocationEntryId = 1; public static void main(String[] args) throws IOException, SQLException, Exception { //connect to a mySql database connectToDatabase(); //create a tcp serverSocket and wait for client connections serverSocket = new ServerSocket(8000); connectClients = new Thread(new ConnectClientsRunnable(serverSocket)); connectClients.start(); unityDemoServerSocket = new ServerSocket(7000); connectToUnityDemoThread = new Thread(new ConnectToUnityDemoRunnable(unityDemoServerSocket)); connectToUnityDemoThread.start(); //extract user location data from the database and process it at a fixed amount of time processDatabaseData = new Thread(new ProcessDatabaseDataRunnable()); processDatabaseData.start(); } public static void connectToDatabase() throws ClassNotFoundException, SQLException, Exception { try { Class.forName("com.mysql.cj.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/solomondb?autoReconnect=true&useJDBCCompliantTimezoneShift=true&useJDBCCompliantTimezoneShift=true&serverTimezone=UTC&useSSL=false", "root", "Puihoward_1423"); // nu uitati sa puneti parola corecta de root pe care o aveti setata pe serverul vostru de MySql. System.out.println("Successfully connected to the database!"); } catch (ClassNotFoundException cnfe) { error = "ClassNotFoundException: Can't find the driver for the database."; throw new ClassNotFoundException(error); } catch (SQLException cnfe) { cnfe.printStackTrace(); error = "SQLException: Can't connect to the database."; throw new SQLException(error); } catch (Exception e) { error = "Exception: Unexpected exception occured while we tried to connect to the database."; throw new Exception(error); } } public static void addUser(String username, String password, String lastName, String firstName, int age) throws SQLException, Exception { if (con != null) { try { // create a prepared SQL statement String userInsertionStatement = "insert into users(username, password, lastName, firstName, age) values(?,?,?,?,?)"; PreparedStatement updateUsers = con.prepareStatement(userInsertionStatement); updateUsers.setString(1, username); updateUsers.setString(2, password); updateUsers.setString(3, lastName); updateUsers.setString(4, firstName); updateUsers.setInt(5, age); updateUsers.executeUpdate(); System.out.println("Inserted user '" + username + "'\n password: " + password + "\nlast name: " + lastName + "\nfirst name: " + firstName + "\nage: " + age + " into the database\n\n"); } catch (SQLException sqle) { error = "SqlException: Update failed; duplicates may exist."; throw new SQLException(error); } } else { error = "Exception : Database connection was lost."; throw new Exception(error); } } public static void addLocationData(int idUser, int idStore, String zoneName, boolean zoneEntered, String time) throws SQLException, Exception { if (con != null) { try { // create a prepared SQL statement String userLocationInsertionStatement = "insert into userlocations(idUser, idStore, zoneName, zoneEntered, time) values(?,?,?,?,?)"; PreparedStatement updateUserLocation = con.prepareStatement(userLocationInsertionStatement); updateUserLocation.setInt(1, idUser); updateUserLocation.setInt(2, idStore); updateUserLocation.setString(3, zoneName); updateUserLocation.setBoolean(4, zoneEntered); updateUserLocation.setString(5, time); updateUserLocation.executeUpdate(); System.out.println("Inserted userLocation into the database\nuser id: " + idUser + "\nstore id: " + idStore + "\nzone name: " + zoneName + "\nzone entered: " + zoneEntered + "\ntime: " + time + "\n\n"); } catch (SQLException sqle) { sqle.printStackTrace(); } } else { error = "Exception : Database connection was lost."; throw new Exception(error); } } public static void addZoneTimeData(int idUser, int idStore, String[] zonesTime) throws SQLException, Exception { if (con != null) { try { // create a prepared SQL statement String userRoomTimeInsertionStatementFirstPart = "insert into userroomtime(idUser, idStore"; String userRoomTimeInsertionStatementLastPart = "values(" + idUser + ", " + idStore; String outputFeedBackString; Statement updateRoomTimeData = con.createStatement(); outputFeedBackString = "Inserted user room time data "; for(int i = 0; i < zonesTime.length; i++) { userRoomTimeInsertionStatementFirstPart += ", room" + (i + 1) + "Time"; userRoomTimeInsertionStatementLastPart += ", '" + zonesTime[i] + "'"; outputFeedBackString += "room" + (i + 1) + " time = " + zonesTime[i]; } userRoomTimeInsertionStatementFirstPart += ") "; userRoomTimeInsertionStatementLastPart += ")"; String statementString = userRoomTimeInsertionStatementFirstPart + userRoomTimeInsertionStatementLastPart; updateRoomTimeData.executeUpdate(statementString); } catch (SQLException sqle) { sqle.printStackTrace(); } } else { error = "Exception : Database connection was lost."; throw new Exception(error); } } public static void updateZoneTimeData(int idUser, int idStore, String zoneName, String zoneTime) throws SQLException, Exception { if (con != null) { try { // create a prepared SQL statement Statement updateStatement = con.createStatement(); String userRoomTimeUpdateStatement = "update userroomtime set " + zoneName + "='" + zoneTime + "' where idUser=" + idUser + " and idStore=" + idStore; updateStatement.executeUpdate(userRoomTimeUpdateStatement); } catch (SQLException sqle) { sqle.printStackTrace(); } } else { error = "Exception : Database connection was lost."; throw new Exception(error); } } public static ResultSet getUserDataFromDatabase(String tabelName, String username) throws SQLException, Exception { ResultSet rs = null; try { // Execute query String queryString = ("select * from " + tabelName + " where username = '" + username + "';"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(queryString); //sql exception } catch (SQLException sqle) { error = "SQLException: Query was not possible."; sqle.printStackTrace(); throw new SQLException(error); } catch (Exception e) { error = "Exception occured when we extracted the data."; throw new Exception(error); } return rs; } public static ResultSet getRoomTimeDataFromDatabase(String tableName, int idUser, int idStore) throws SQLException, Exception { ResultSet rs = null; try { // Execute query String queryString = ("select * from " + tableName + " where idUser=" + idUser + " and idStore=" + idStore); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(queryString); //sql exception } catch (SQLException sqle) { error = "SQLException: Query was not possible."; sqle.printStackTrace(); throw new SQLException(error); } catch (Exception e) { error = "Exception occured when we extracted the data."; throw new Exception(error); } return rs; } public static ResultSet getTableData(String tabelName) throws SQLException, Exception { ResultSet rs = null; try { // Execute query String queryString = ("select * from " + tabelName + ";"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(queryString); //sql exception } catch (SQLException sqle) { error = "SQLException: Query was not possible."; sqle.printStackTrace(); throw new SQLException(error); } catch (Exception e) { error = "Exception occured when we extracted the data."; throw new Exception(error); } return rs; } public static ResultSet getNewTableData(String tabelName, String idName, int lastId) throws SQLException, Exception { ResultSet rs = null; try { // Execute query String queryString = ("select * from "+ tabelName + " where " + idName + " > " + lastId); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(queryString); //sql exception } catch (SQLException sqle) { error = "SQLException: Query was not possible."; sqle.printStackTrace(); throw new SQLException(error); } catch (Exception e) { error = "Exception occured when we extracted the data."; throw new Exception(error); } return rs; } }
gpl-3.0
optimizationBenchmarking/evaluator-attributes
src/main/java/org/optimizationBenchmarking/evaluator/attributes/clusters/propertyValueGroups/EGroupingMode.java
24903
package org.optimizationBenchmarking.evaluator.attributes.clusters.propertyValueGroups; import org.optimizationBenchmarking.utils.math.NumericalTypes; import org.optimizationBenchmarking.utils.math.functions.arithmetic.Div; import org.optimizationBenchmarking.utils.math.functions.arithmetic.Mul; import org.optimizationBenchmarking.utils.math.functions.arithmetic.SaturatingAdd; import org.optimizationBenchmarking.utils.math.functions.arithmetic.SaturatingSub; import org.optimizationBenchmarking.utils.math.functions.power.Log; import org.optimizationBenchmarking.utils.math.functions.power.Pow; import org.optimizationBenchmarking.utils.text.TextUtils; /** * A set of different modi for grouping elements. */ public enum EGroupingMode { /** Group distinct values, i.e., each value becomes an own group */ DISTINCT { /** {@inheritDoc} */ @Override _Groups _groupObjects(final Number param, final Object[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { int count; count = 0; for (final _Group group : buffer) { group.m_size = 1; group.m_isUpperExclusive = false; group.m_lower = group.m_upper = data[count++]; } return new _Groups(buffer, minGroups, maxGroups, this, null); } /** {@inheritDoc} */ @Override _Groups _groupLongs(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { return this._groupObjects(param, data, minGroups, maxGroups, buffer); } /** {@inheritDoc} */ @Override _Groups _groupDoubles(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { return this._groupObjects(param, data, minGroups, maxGroups, buffer); } }, /** * Group elements in terms of reasonable powers, including powers of * {@code 2}, {@code 10}, etc. */ POWERS { /** {@inheritDoc} */ @Override final _Groups _groupLongs(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { final long pl; _Groups best, current; if (param != null) { pl = param.longValue(); best = EGroupingMode._groupLongsByPowerRange(pl, data, minGroups, maxGroups, buffer); if ((param instanceof Float) || (param instanceof Double)) { if ((pl < Long.MAX_VALUE) && (pl != param.doubleValue())) { current = EGroupingMode._groupLongsByPowerRange((pl + 1L), data, minGroups, maxGroups, buffer); if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best != null) { return best; } } else { best = null; } for (final long power : EGroupingMode.POWER_CHOICES) { current = EGroupingMode._groupLongsByPowerRange(power, data, minGroups, maxGroups, buffer); if (current != null) { if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best == null) { return DISTINCT._groupLongs(param, data, minGroups, maxGroups, buffer); } return best; } /** {@inheritDoc} */ @Override final _Groups _groupDoubles(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { final double dl; _Groups best, current; if (param != null) { dl = param.doubleValue(); best = EGroupingMode._groupDoublesByPowerRange(dl, data, minGroups, maxGroups, buffer); if (best != null) { return best; } } else { best = null; } for (final long power : EGroupingMode.POWER_CHOICES) { current = EGroupingMode._groupDoublesByPowerRange(power, data, minGroups, maxGroups, buffer); if (current != null) { if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best == null) { return DISTINCT._groupDoubles(param, data, minGroups, maxGroups, buffer); } return best; } }, /** * Group elements in terms of reasonable multiples, including multipes of * {@code 1}, {@code 2}, {@code 10}, etc. */ MULTIPLES { /** {@inheritDoc} */ @Override final _Groups _groupLongs(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { final long pl; _Groups best, current; if (param != null) { pl = param.longValue(); best = EGroupingMode._groupLongsByMultipleRange(pl, data, minGroups, maxGroups, buffer); if ((param instanceof Float) || (param instanceof Double)) { if ((pl < Long.MAX_VALUE) && (pl != param.doubleValue())) { current = EGroupingMode._groupLongsByMultipleRange((pl + 1L), data, minGroups, maxGroups, buffer); if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best != null) { return best; } } else { best = null; } for (final long range : EGroupingMode.MULTIPLE_CHOICES_L) { current = EGroupingMode._groupLongsByMultipleRange(range, data, minGroups, maxGroups, buffer); if (current != null) { if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best == null) { return DISTINCT._groupLongs(param, data, minGroups, maxGroups, buffer); } return best; } /** {@inheritDoc} */ @Override final _Groups _groupDoubles(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { final double dl; _Groups best, current; if (param != null) { dl = param.doubleValue(); best = EGroupingMode._groupDoublesByMultipleRange(dl, data, minGroups, maxGroups, buffer); if (best != null) { return best; } } else { best = null; } for (final double range : EGroupingMode.MULTIPLE_CHOICES_D) { current = EGroupingMode._groupDoublesByMultipleRange(range, data, minGroups, maxGroups, buffer); if (current != null) { if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best == null) { return DISTINCT._groupDoubles(param, data, minGroups, maxGroups, buffer); } return best; } }, /** Group according to any possible choice */ ANY { /** {@inheritDoc} */ @Override final _Groups _groupObjects(final Number param, final Object[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { return DISTINCT._groupObjects(param, data, minGroups, maxGroups, buffer); } /** {@inheritDoc} */ @Override _Groups _groupLongs(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { _Groups best, current; best = DISTINCT._groupLongs(param, data, minGroups, maxGroups, buffer); current = POWERS._groupLongs(param, data, minGroups, maxGroups, buffer); if (current.compareTo(best) < 0) { best = current; } current = MULTIPLES._groupLongs(param, data, minGroups, maxGroups, buffer); if ((current != null) && (current.compareTo(best) < 0)) { best = current; } return best; } /** {@inheritDoc} */ @Override _Groups _groupDoubles(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { _Groups best, current; best = DISTINCT._groupDoubles(param, data, minGroups, maxGroups, buffer); current = POWERS._groupDoubles(param, data, minGroups, maxGroups, buffer); if (current.compareTo(best) < 0) { best = current; } current = MULTIPLES._groupDoubles(param, data, minGroups, maxGroups, buffer); if ((current != null) && (current.compareTo(best) < 0)) { best = current; } return best; } } ; /** the power choices */ static final long[] POWER_CHOICES = { 10L, 2L, 100L, 4L, 1000L, 8L, 16L, 10000L, 1024L, 32L, 64L, 256L, 512L, }; /** the choices for the {@code long} multiples */ static final long[] MULTIPLE_CHOICES_L = { 2L, 3L, 4L, 5L, 10L, 15L, 20L, 25L, 30L, 40L, 50L, 75L, 100L, 200L, 250L, 500L, 750L, 1_000L, 1_500L, 2_000L, 2_500L, 5_000L, 10_000L, 100_000L, 1_000_000L, 10_000_000L, 100_000_000L, 1_000_000_000L, 10_000_000_000L, 100_000_000_000L, 1_000_000_000_000L }; /** the choices for the {@code double} multiples */ static final double[] MULTIPLE_CHOICES_D = { 1e-30d, 1e-24d, 1e-21d, 1e-18d, 1e-15d, 1e-12d, 1e-9d, 1e-6, 1e-5, 1e-4d, 1E-3d, 1E-2d, 1E-1d, 0.125d, 0.2d, 0.25d, 0.3d, (1d / 3d), 0.4d, 0.5d, 0.75d, 1d, 1.5d, 2d, 2.5d, 3d, 4d, 5d, 7.5d, 10d, 15d, 20d, 25d, 30d, 40d, 50d, 75d, 100d, 200d, 250d, 500d, 750d, 1_000d, 1_500d, 2_000d, 2_500d, 5_000d, 1e4d, 1e5d, 1e6d, 1e7d, 1e8d, 1e9d, 1e10d, 1e12d, 1e15d, 1e18d, 1e20d, 1e21d, 1e24d, 1e27d, 1e30d, 1e35d, 1e40d, 1e50d, 1e60d, 1e70d, 1e100d, 1e200d, 1e300d }; /** the name */ private final String m_name; /** * Create a grouping * * @param param * the parameter * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ _Groups _groupObjects(final Number param, final Object[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { throw new UnsupportedOperationException("Mode " + this + //$NON-NLS-1$ " can only apply to numbers."); //$NON-NLS-1$ } /** * Create a grouping * * @param param * the parameter * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ abstract _Groups _groupLongs(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer); /** * Create a grouping * * @param param * the parameter * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ abstract _Groups _groupDoubles(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer); /** * @param power * the power to group by * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ static _Groups _groupLongsByPowerRange(final long power, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { long prev, next, cur; int minIndex, exclusiveMaxIndex, groupIndex; _Group group; boolean exclusive; if (power <= 1L) { return null; } next = power; do { prev = next; next *= power; } while (next > prev); next = (-prev); prev = Long.MIN_VALUE; exclusiveMaxIndex = 0; groupIndex = 0; exclusive = true; // First, we want to find all the negative powers, then the positive // ones. outer: for (;;) { if (exclusiveMaxIndex >= data.length) { break outer; } minIndex = exclusiveMaxIndex; inner: for (;;) { cur = data[exclusiveMaxIndex].longValue(); if (cur < prev) { break inner; } if (exclusive) { if (cur >= next) { break inner; } } else { if (cur > next) { break inner; } } exclusiveMaxIndex++; if (exclusiveMaxIndex >= data.length) { break inner; } } if (exclusiveMaxIndex > minIndex) { group = buffer[groupIndex++]; group.m_lower = NumericalTypes.valueOf(prev); group.m_upper = NumericalTypes.valueOf(next); group.m_isUpperExclusive = exclusive; group.m_size = (exclusiveMaxIndex - minIndex); if ((exclusiveMaxIndex >= data.length) || // (groupIndex >= buffer.length)) { break outer; } } prev = next; if (prev > 0L) { if (next >= Long.MAX_VALUE) { throw new IllegalStateException(// "There are long values bigger than MAX_LONG??"); //$NON-NLS-1$ } next *= power; if (next <= prev) { next = Long.MAX_VALUE; exclusive = false; } } else { if (prev == 0L) { next = power; } else { next /= power; } } } if (groupIndex < buffer.length) { buffer[groupIndex].m_size = (-1); } return new _Groups(buffer, minGroups, maxGroups, POWERS, // NumericalTypes.valueOf(power)); } /** * @param power * the power to group by * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ static _Groups _groupDoublesByPowerRange(final double power, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { double prev, next, cur; long pwr; int minIndex, exclusiveMaxIndex, groupIndex; _Group group; boolean exclusive; if ((power <= 1d) || (power != power) || (power >= Double.POSITIVE_INFINITY)) { return null; } pwr = (((long) (Log.INSTANCE.computeAsDouble(power, Double.MAX_VALUE))) + 1L); prev = Double.NEGATIVE_INFINITY; while ((next = (-Pow.INSTANCE.computeAsDouble(power, pwr))) <= prev) { pwr--; } if ((prev != prev) || (next != next)) { return null; // not possible. } exclusiveMaxIndex = 0; groupIndex = 0; exclusive = true; // First, we want to find all the negative powers, then the positive // ones. outer: for (;;) { if (exclusiveMaxIndex >= data.length) { break outer; } minIndex = exclusiveMaxIndex; inner: for (;;) { cur = data[exclusiveMaxIndex].doubleValue(); if (cur < prev) { break inner; } if (exclusive) { if (cur >= next) { break inner; } } else { if (cur > next) { break inner; } } exclusiveMaxIndex++; if (exclusiveMaxIndex >= data.length) { break inner; } } if (exclusiveMaxIndex > minIndex) { group = buffer[groupIndex++]; group.m_lower = NumericalTypes.valueOf(prev); group.m_upper = NumericalTypes.valueOf(next); group.m_isUpperExclusive = exclusive; group.m_size = (exclusiveMaxIndex - minIndex); if ((exclusiveMaxIndex >= data.length) || // (groupIndex >= buffer.length)) { break outer; } } prev = next; if (next > 0d) { if (next >= Double.POSITIVE_INFINITY) { throw new IllegalStateException(// "There are double values bigger than POSITIVE_INFINITY??"); //$NON-NLS-1$ } next = Pow.INSTANCE.computeAsDouble(power, (++pwr)); if (next >= Double.POSITIVE_INFINITY) { exclusive = false; } else { if (next != next) { return null; } } } else { if (prev == 0d) { pwr = (((long) (Log.INSTANCE.computeAsDouble(power, Double.MIN_VALUE))) - 1L); while ((next = Pow.INSTANCE.computeAsDouble(power, pwr)) <= 0d) { pwr++; } } else { next = (-(Pow.INSTANCE.computeAsDouble(power, (--pwr)))); if (next == 0d) { next = 0d; // deal with -0d -> 0d } else { if (next != next) { return null; } } } } } if (groupIndex < buffer.length) { buffer[groupIndex].m_size = (-1); } return new _Groups(buffer, minGroups, maxGroups, POWERS, // NumericalTypes.valueOf(pwr)); } /** * Group longs by range * * @param range * the range to group by * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ static _Groups _groupLongsByMultipleRange(final long range, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { long prev, next, cur; int minIndex, exclusiveMaxIndex, groupIndex; _Group group; boolean exclusive; if (range <= 0L) { return null; } cur = data[0].longValue(); next = (cur / range); prev = (data[data.length - 1].longValue() / range); if (SaturatingAdd.INSTANCE.computeAsLong(// ((next > Long.MIN_VALUE) ? Math.abs(next) : Long.MAX_VALUE), // ((prev > Long.MIN_VALUE) ? Math.abs(prev) : Long.MAX_VALUE)) >= 1000L) { return null; // too many steps! } if (next >= prev) { return null;// range to big } next *= range; prev = next; if (prev <= 0L) { while (prev > cur) { prev = SaturatingSub.INSTANCE.computeAsLong(prev, range); } } next = SaturatingAdd.INSTANCE.computeAsLong(prev, range); exclusiveMaxIndex = 0; groupIndex = 0; exclusive = true; // First, we want to find all the negative powers, then the positive // ones. outer: for (;;) { if (exclusiveMaxIndex >= data.length) { break outer; } minIndex = exclusiveMaxIndex; inner: for (;;) { cur = data[exclusiveMaxIndex].longValue(); if (cur < prev) { break inner; } if (exclusive) { if (cur >= next) { break inner; } } else { if (cur > next) { break inner; } } exclusiveMaxIndex++; if (exclusiveMaxIndex >= data.length) { break inner; } } if (exclusiveMaxIndex > minIndex) { group = buffer[groupIndex++]; group.m_lower = Long.valueOf(prev); group.m_upper = Long.valueOf(next); group.m_isUpperExclusive = exclusive; group.m_size = (exclusiveMaxIndex - minIndex); if ((exclusiveMaxIndex >= data.length) || // (groupIndex >= buffer.length)) { break outer; } } prev = next; if (next >= Long.MAX_VALUE) { throw new IllegalStateException(// "There are long values bigger than MAX_LONG??"); //$NON-NLS-1$ } next = SaturatingAdd.INSTANCE.computeAsLong(next, range); if (next >= Long.MAX_VALUE) { exclusive = false; } } if (groupIndex < buffer.length) { buffer[groupIndex].m_size = (-1); } return new _Groups(buffer, minGroups, maxGroups, MULTIPLES, NumericalTypes.valueOf(range)); } /** * Group longs by range * * @param range * the range to group by * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ static _Groups _groupDoublesByMultipleRange(final double range, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { double prev, next, cur, span; long prevMul; int minIndex, exclusiveMaxIndex, groupIndex; _Group group; if ((range <= 0d) || (range != range) || (range >= Double.POSITIVE_INFINITY)) { return null; } cur = data[0].doubleValue(); prev = Div.INSTANCE.computeAsDouble(cur, range); next = Div.INSTANCE .computeAsDouble(data[data.length - 1].doubleValue(), range); if ((prev != prev) || // (next != next) || // ((span = (Math.abs(next) + Math.abs(prev))) >= 1000d) || // (span != span) || // (Math.ceil(prev) >= Math.floor(next))) { return null; // too many steps! } prevMul = ((long) (prev)); if (prevMul != prev) { return null; // cannot use the range due to imprecision } next = prev = Mul.INSTANCE.computeAsDouble(prevMul, range); if ((prev + range) <= prev) { return null; } if (prev <= 0d) { while (prev > cur) { if (prevMul <= Long.MIN_VALUE) { return null; } prevMul--; prev = Mul.INSTANCE.computeAsDouble(prevMul, range); if ((prev + range) <= prev) { return null; } } } if (prevMul >= Long.MAX_VALUE) { return null; } next = Mul.INSTANCE.computeAsDouble((++prevMul), range); if (next <= prev) { return null; } exclusiveMaxIndex = 0; groupIndex = 0; // First, we want to find all the negative powers, then the positive // ones. outer: for (;;) { if (exclusiveMaxIndex >= data.length) { break outer; } minIndex = exclusiveMaxIndex; inner: for (;;) { cur = data[exclusiveMaxIndex].longValue(); if ((cur < prev) || (cur >= next)) { break inner; } exclusiveMaxIndex++; if (exclusiveMaxIndex >= data.length) { break inner; } } if (exclusiveMaxIndex > minIndex) { group = buffer[groupIndex++]; group.m_lower = Double.valueOf(prev); group.m_upper = Double.valueOf(next); group.m_isUpperExclusive = true; group.m_size = (exclusiveMaxIndex - minIndex); if ((exclusiveMaxIndex >= data.length) || // (groupIndex >= buffer.length)) { break outer; } } prev = next; if (prevMul >= Long.MAX_VALUE) { return null; } prevMul++; next = Mul.INSTANCE.computeAsDouble(prevMul, range); if (next <= prev) { return null; } } if (groupIndex < buffer.length) { buffer[groupIndex].m_size = (-1); } return new _Groups(buffer, minGroups, maxGroups, MULTIPLES, NumericalTypes.valueOf(range)); } /** create the grouping mode */ EGroupingMode() { this.m_name = TextUtils.toLowerCase(super.toString()); } /** {@inheritDoc} */ @Override public final String toString() { return this.m_name; } }
gpl-3.0
fjbatresv/MascotasSociales
app/src/main/java/com/jmbsystems/fjbatresv/mascotassociales/photoList/ui/PhotoListActivity.java
5594
package com.jmbsystems.fjbatresv.mascotassociales.photoList.ui; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable; import com.jmbsystems.fjbatresv.mascotassociales.MascotasSocialesApp; import com.jmbsystems.fjbatresv.mascotassociales.R; import com.jmbsystems.fjbatresv.mascotassociales.enitites.Photo; import com.jmbsystems.fjbatresv.mascotassociales.enitites.Session; import com.jmbsystems.fjbatresv.mascotassociales.libs.base.ImageLoader; import com.jmbsystems.fjbatresv.mascotassociales.main.ui.MainActivity; import com.jmbsystems.fjbatresv.mascotassociales.photo.ui.PhotoActivity; import com.jmbsystems.fjbatresv.mascotassociales.photoList.PhotoListPresenter; import com.jmbsystems.fjbatresv.mascotassociales.photoList.ui.adapters.OnItemClickListener; import com.jmbsystems.fjbatresv.mascotassociales.photoList.ui.adapters.PhotoListAdapter; import java.io.ByteArrayOutputStream; import java.util.List; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import de.hdodenhof.circleimageview.CircleImageView; public class PhotoListActivity extends AppCompatActivity implements PhotoListView, OnItemClickListener { @Bind(R.id.container) RelativeLayout container; @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.loggedAvatar) CircleImageView loggedAvatar; @Bind(R.id.loggedName) TextView loggedName; @Bind(R.id.progressBar) ProgressBar progressBar; @Bind(R.id.reclyclerView) RecyclerView recyclerView; @Bind(R.id.fab) FloatingActionButton fab; @Inject PhotoListPresenter presenter; @Inject ImageLoader imageLoader; @Inject PhotoListAdapter adapter; private MascotasSocialesApp app; public final static String NOMBRE_ORIGEN = "photoList"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_photo_list); ButterKnife.bind(this); app = (MascotasSocialesApp) getApplication(); app.validSessionInit(); setupInjection(); setupToolbar(); setUpRecyclerView(); presenter.onCreate(); } @Override protected void onDestroy() { presenter.onDestroy(); super.onDestroy(); } @Override public void onBackPressed() { startActivity(new Intent(this, MainActivity.class)); } @OnClick(R.id.fab) public void takePhoto(){ startActivity( new Intent(this, PhotoActivity.class) .putExtra(PhotoActivity.ORIGEN, NOMBRE_ORIGEN) ); } private void setupInjection() { app.getPhotoListComponent(this, this).inject(this); } private void setUpRecyclerView() { recyclerView.setLayoutManager(new GridLayoutManager(this, 1)); recyclerView.setAdapter(adapter); } private void setupToolbar() { loggedName.setText(Session.getInstancia().getNombre()); imageLoader.load(loggedAvatar, Session.getInstancia().getImage()); setSupportActionBar(toolbar); } @Override public void onError(String error) { loggedName.setText(Session.getInstancia().getNombre()); imageLoader.load(loggedAvatar, Session.getInstancia().getImage()); Snackbar.make(container, error, Snackbar.LENGTH_LONG).show(); } @Override public void toggleContent(boolean mostrar) { int visible = View.VISIBLE; if (!mostrar){ visible = View.GONE; } fab.setVisibility(visible); recyclerView.setVisibility(visible); } @Override public void toggleProgress(boolean mostrar) { int visible = View.VISIBLE; if (!mostrar){ visible = View.GONE; } progressBar.setVisibility(visible); } @Override public void addPhoto(Photo foto) { adapter.addPhoto(foto); } @Override public void removePhoto(Photo foto) { adapter.removePhoto(foto); } @Override public void onShareClick(Photo foto, ImageView img) { Bitmap bitmap = ((GlideBitmapDrawable)img.getDrawable()).getBitmap(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); String path = MediaStore.Images.Media.insertImage(this.getContentResolver(), bitmap, null, null); Uri uri = Uri.parse(path); Intent share = new Intent(Intent.ACTION_SEND) .setType("image/jpeg") .putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(share, getString(R.string.photolist_message_share))); } @Override public void onDeleteClick(Photo foto) { presenter.removePhoto(foto); } }
gpl-3.0
rgorosito/penrose
common/src/main/java/org/safehaus/penrose/ldap/RDNBuilder.java
1607
package org.safehaus.penrose.ldap; import java.util.Map; import java.util.TreeMap; /** * @author Endi S. Dewata */ public class RDNBuilder { public Map<String,Object> values = new TreeMap<String,Object>(); public RDNBuilder() { } public boolean isEmpty() { return values.isEmpty(); } public void clear() { values.clear(); } public void add(RDN rdn) { values.putAll(rdn.getValues()); } public void set(RDN rdn) { values.clear(); values.putAll(rdn.getValues()); } public void add(String prefix, RDN rdn) { for (String name : rdn.getNames()) { Object value = rdn.get(name); values.put(prefix == null ? name : prefix + "." + name, value); } } public void set(String prefix, RDN rdn) { values.clear(); for (String name : rdn.getNames()) { Object value = rdn.get(name); values.put(prefix == null ? name : prefix + "." + name, value); } } public void set(String name, Object value) { this.values.put(name, value); } public Object remove(String name) { return values.remove(name); } public void normalize() { for (String name : values.keySet()) { Object value = values.get(name); if (value == null) continue; if (value instanceof String) { value = ((String) value).toLowerCase(); } values.put(name, value); } } public RDN toRdn() { return new RDN(values); } }
gpl-3.0
pkiraly/metadata-qa-marc
src/test/java/de/gwdg/metadataqa/marc/definition/general/validator/ISBNValidatorTest.java
6003
package de.gwdg.metadataqa.marc.definition.general.validator; import de.gwdg.metadataqa.marc.dao.DataField; import de.gwdg.metadataqa.marc.dao.MarcRecord; import de.gwdg.metadataqa.marc.MarcSubfield; import de.gwdg.metadataqa.marc.definition.ValidatorResponse; import de.gwdg.metadataqa.marc.definition.tags.tags01x.Tag020; import de.gwdg.metadataqa.marc.model.validation.ValidationError; import de.gwdg.metadataqa.marc.model.validation.ValidationErrorType; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.junit.Assert.assertNotNull; public class ISBNValidatorTest { @Test public void testInvalid() { MarcSubfield subfield = createMarcSubfield("3p"); assertNotNull(subfield); assertTrue(subfield.getDefinition().hasValidator()); SubfieldValidator validator = subfield.getDefinition().getValidator(); assertNotNull(validator); ValidatorResponse response = validator.isValid(subfield); assertFalse(response.isValid()); ValidationError validationError = response.getValidationErrors().get(0); assertNotNull(validationError); assertEquals("test", validationError.getRecordId()); assertEquals("020$a", validationError.getMarcPath()); assertEquals(ValidationErrorType.SUBFIELD_ISBN, validationError.getType()); assertEquals("ISBN does not fit the pattern \\d[\\d-]+[\\dxX].", validationError.getMessage()); /* assertEquals("'3p' does not a have an ISBN value, it does not fit the pattern \\d[\\d-]+[\\dxX].", validationError.getMessage()); */ assertEquals("https://en.wikipedia.org/wiki/International_Standard_Book_Number", validationError.getUrl()); } @Test public void test9992158107() { MarcSubfield subfield = createMarcSubfield("99921-58-10-7"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void test9971502100() { MarcSubfield subfield = createMarcSubfield("9971-5-0210-0"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void test9604250590() { MarcSubfield subfield = createMarcSubfield("960-425-059-0"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void test8090273416() { MarcSubfield subfield = createMarcSubfield("80-902734-1-6"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void test8535902775() { MarcSubfield subfield = createMarcSubfield("85-359-0277-5"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void test1843560283() { MarcSubfield subfield = createMarcSubfield("1-84356-028-3"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void test0684843285() { MarcSubfield subfield = createMarcSubfield("0684843285"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void test080442957X() { MarcSubfield subfield = createMarcSubfield("0-8044-2957-X"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void test0851310419() { MarcSubfield subfield = createMarcSubfield("0851310419"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void test0943396042() { MarcSubfield subfield = createMarcSubfield("0943396042"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void testWithSpaces() { MarcSubfield subfield = createMarcSubfield("0 405 05352 5"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } @Test public void testMultiple() { List<String> isbns = Arrays.asList("0-9752298-0-X", "0-9752298-0-X (fűzött)"); for (String ISBN : isbns) { MarcSubfield subfield = createMarcSubfield(ISBN); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(ISBN, response.isValid()); assertEquals(0, response.getValidationErrors().size()); } } @Test public void testSuffixes() { MarcSubfield subfield = createMarcSubfield("9782070769148 (broché) :"); ValidatorResponse response = subfield.getDefinition().getValidator().isValid(subfield); assertTrue(response.isValid()); assertEquals(0, response.getValidationErrors().size()); } private MarcSubfield createMarcSubfield(String ISBN) { MarcRecord marcRecord = new MarcRecord("test"); DataField field = new DataField(Tag020.getInstance(), " ", " ", "a", ISBN); field.setMarcRecord(marcRecord); return field.getSubfield("a").get(0); } }
gpl-3.0
bovard/battlecode-server-2014
src/main/battlecode/world/GameMap.java
12224
package battlecode.world; import battlecode.common.Direction; import battlecode.common.GameConstants; import battlecode.common.MapLocation; import battlecode.common.RobotType; import battlecode.common.TerrainTile; import battlecode.serial.GenericGameMap; import java.util.Arrays; import java.util.EnumMap; import java.util.Map; import java.util.Random; /** * The class represents the map in the game world on which * objects interact. */ public class GameMap implements GenericGameMap { private static final long serialVersionUID = -2068896916199851260L; /** * The default game seed. */ public static final int GAME_DEFAULT_SEED = 6370; /** * The default game maxiumum number of rounds. */ public static final int GAME_DEFAULT_MAX_ROUNDS = 10000; /** The default game minimum number of points. */ //public static final int GAME_DEFAULT_MIN_POINTS = 5000; /** * The width and height of the map. */ private final int mapWidth, mapHeight; /** * The tiles on the map. */ private final TerrainTile[][] mapTiles; /** * The scalar field of neutral characters on the map. */ private final NeutralsMap neutralsMap; /** * The coordinates of the origin. */ private final int mapOriginX, mapOriginY; /** * The name of the map theme. */ private String mapTheme; /** * The random seed contained in the map file */ private final int seed; /** * The maximum number of rounds in the game */ private final int maxRounds; /** * The name of the map */ private final String mapName; /** The minimum number of points needed to win the game */ //private final int minPoints; /** * Represents the various integer properties a GameMap * can have. */ static enum MapProperties { WIDTH, HEIGHT, SEED, MAX_ROUNDS, THEME /*, MIN_POINTS*/ } public GameMap(GameMap gm) { this.mapWidth = gm.mapWidth; this.mapHeight = gm.mapHeight; this.mapTiles = new TerrainTile[this.mapWidth][this.mapHeight]; this.neutralsMap = new NeutralsMap(gm.neutralsMap); for (int i = 0; i < this.mapWidth; i++) { System.arraycopy(gm.mapTiles[i], 0, this.mapTiles[i], 0, this.mapHeight); } this.mapOriginX = gm.mapOriginX; this.mapOriginY = gm.mapOriginY; this.mapTheme = gm.mapTheme; this.seed = gm.seed; this.maxRounds = gm.maxRounds; this.mapName = gm.mapName; //this.minPoints = gm.minPoints; } /** * Creates a new GameMap from the given properties, tiles, and territory * locations. * * @param mapProperties a map of MapProperties to their integer values containing dimensions, etc. * @param mapTiles a matrix of TerrainTypes representing the map * @param neutralsMap a NeutralsMap to copy */ GameMap(Map<MapProperties, Integer> mapProperties, TerrainTile[][] mapTiles, NeutralsMap neutralsMap, String mapName) { if (mapProperties.containsKey(MapProperties.WIDTH)) this.mapWidth = mapProperties.get(MapProperties.WIDTH); else this.mapWidth = mapTiles[0].length; if (mapProperties.containsKey(MapProperties.HEIGHT)) this.mapHeight = mapProperties.get(MapProperties.HEIGHT); else this.mapHeight = mapTiles.length; if (mapProperties.containsKey(MapProperties.SEED)) this.seed = mapProperties.get(MapProperties.SEED); else this.seed = GAME_DEFAULT_SEED; if (mapProperties.containsKey(MapProperties.MAX_ROUNDS)) this.maxRounds = mapProperties.get(MapProperties.MAX_ROUNDS); else this.maxRounds = GAME_DEFAULT_MAX_ROUNDS; //if (mapProperties.containsKey(MapProperties.MIN_POINTS)) // this.minPoints = mapProperties.get(MapProperties.MIN_POINTS); //else this.minPoints = GAME_DEFAULT_MIN_POINTS; // Random rand = new Random(this.seed); // this.mapOriginX = rand.nextInt(32000); // this.mapOriginY = rand.nextInt(32000); // Maps are normalized to 0,0 (2013 change) this.mapOriginX = 0; this.mapOriginY = 0; this.mapTiles = mapTiles; this.neutralsMap = neutralsMap; this.mapName = mapName; } public void setTheme(String theme) { this.mapTheme = theme; } /** * Returns the width of this map. * * @return the width of this map */ public int getWidth() { return mapWidth; } /** * Returns the height of this map. * * @return the height of this map */ public int getHeight() { return mapHeight; } /** * Returns the name of the suggested map * theme to use when displaying the map. * * @return the string name of the map theme */ public String getThemeName() { return mapTheme; } public String getMapName() { return mapName; } //public int getMinPoints() { // return minPoints; //} /** * Determines whether or not the location at the specified * unshifted coordinates is on the map. * * @param x the (shifted) x-coordinate of the location * @param y the (shifted) y-coordinate of the location * @return true if the given coordinates are on the map, * false if they're not */ private boolean onTheMap(int x, int y) { return (x >= mapOriginX && y >= mapOriginY && x < mapOriginX + mapWidth && y < mapOriginY + mapHeight); } /** * Determines whether or not the specified location is on the map. * * @param location the MapLocation to test * @return true if the given location is on the map, * false if it's not */ public boolean onTheMap(MapLocation location) { return onTheMap(location.x, location.y); } /** * Determines the type of the terrain on the map at the * given location. * * @param location the MapLocation to test * @return the TerrainTile at the given location * of the map, and TerrainTile.OFF_MAP if the given location is * off the map. */ public TerrainTile getTerrainTile(MapLocation location) { if (!onTheMap(location)) return TerrainTile.OFF_MAP; return mapTiles[location.x - mapOriginX][location.y - mapOriginY]; } /** * Returns a two-dimensional array of terrain data for this map. * * @return the map's terrain in a 2D array */ public TerrainTile[][] getTerrainMatrix() { return mapTiles; } /** * Updates the neutrals map for the next turn. */ public NeutralsMap getNeutralsMap() { return neutralsMap; } /** * Gets the maximum number of rounds for this game. * * @return the maximum number of rounds for this game */ public int getMaxRounds() { return maxRounds; } public int getStraightMaxRounds() { return maxRounds; } public int getSeed() { return seed; } /** * Gets the origin (i.e., upper left corner) of the map * * @return the origin of the map */ public MapLocation getMapOrigin() { return new MapLocation(mapOriginX, mapOriginY); } public static class MapMemory { // should be ge the max of all robot sensor ranges private final static int BUFFER; static { int buf = 0; for (RobotType t : RobotType.values()) { if (t.sensorRadiusSquared > buf) buf = t.sensorRadiusSquared; } BUFFER = buf;// + GameConstants.VISION_UPGRADE_BONUS; } private final boolean data[][]; private final GameMap map; private final int Xwidth; private final int Ywidth; public MapMemory(GameMap map) { this.map = map; Xwidth = map.mapWidth + (2 * BUFFER); Ywidth = map.mapHeight + (2 * BUFFER); data = new boolean[Xwidth][Ywidth]; } public void rememberLocations(MapLocation loc, int[] offsetsX, int[] offsetsY) { int X = loc.x - map.mapOriginX + BUFFER; int Y = loc.y - map.mapOriginY + BUFFER; for (int i = 0; i < offsetsX.length; i++) { data[X + offsetsX[i]][Y + offsetsY[i]] = true; } } public TerrainTile recallTerrain(MapLocation loc) { int X = loc.x - map.mapOriginX + BUFFER; int Y = loc.y - map.mapOriginY + BUFFER; if (X >= 0 && X < Xwidth && Y >= 0 && Y < Ywidth && data[X][Y]) return map.getTerrainTile(loc); else return null; } } public static int[][] computeOffsets360(int radiusSquared) { int[] XOffsets = new int[4 * radiusSquared + 7]; int[] YOffsets = new int[4 * radiusSquared + 7]; int nOffsets = 0; for (int y = 0; y * y <= radiusSquared; y++) { XOffsets[nOffsets] = 0; YOffsets[nOffsets] = y; nOffsets++; if (y > 0) { XOffsets[nOffsets] = 0; YOffsets[nOffsets] = -y; nOffsets++; } for (int x = 1; x * x + y * y <= radiusSquared; x++) { MapLocation loc = new MapLocation(x, y); XOffsets[nOffsets] = x; YOffsets[nOffsets] = y; nOffsets++; XOffsets[nOffsets] = -x; YOffsets[nOffsets] = y; nOffsets++; if (y > 0) { XOffsets[nOffsets] = x; YOffsets[nOffsets] = -y; nOffsets++; XOffsets[nOffsets] = -x; YOffsets[nOffsets] = -y; nOffsets++; } } } return new int[][]{Arrays.copyOf(XOffsets, nOffsets), Arrays.copyOf(YOffsets, nOffsets)}; } public static Map<RobotType, int[][][]> computeVisibleOffsets() { int MAX_RANGE; final MapLocation CENTER = new MapLocation(0, 0); Map<RobotType, int[][][]> offsets = new EnumMap<RobotType, int[][][]>(RobotType.class); int[][][] offsetsForType; int[] XOffsets = new int[169]; int[] YOffsets = new int[169]; int nOffsets; for (RobotType type : RobotType.values()) { offsetsForType = new int[9][][]; offsets.put(type, offsetsForType); if ((type.sensorAngle >= 360.0)) { // Same range of vision independent of direction; // save memory by using the same array each time int[][] tmpOffsets = computeOffsets360(type.sensorRadiusSquared); for (int i = 0; i < 8; i++) { offsetsForType[i] = tmpOffsets; } } else { for (int i = 0; i < 8; i++) { Direction dir = Direction.values()[i]; nOffsets = 0; MAX_RANGE = (int) Math.sqrt(type.sensorRadiusSquared); for (int y = -MAX_RANGE; y <= MAX_RANGE; y++) { for (int x = -MAX_RANGE; x <= MAX_RANGE; x++) { MapLocation loc = new MapLocation(x, y); if (CENTER.distanceSquaredTo(loc) <= type.sensorRadiusSquared && GameWorld.inAngleRange(CENTER, dir, loc, type.sensorCosHalfTheta)) { XOffsets[nOffsets] = x; YOffsets[nOffsets] = y; nOffsets++; } } } offsetsForType[i] = new int[][]{Arrays.copyOf(XOffsets, nOffsets), Arrays.copyOf(YOffsets, nOffsets)}; } } } return offsets; } }
gpl-3.0
juanmont/ABD
practica1User/src/main/java/abd/p1/model/MensajeAmistad.java
542
package abd.p1.model; import java.util.Date; import javax.persistence.*; @Entity public class MensajeAmistad extends Mensaje{ @Column private boolean aceptado; public MensajeAmistad(){ super(); } public MensajeAmistad(Usuario usu, Usuario amigo){ super(usu, amigo); aceptado = true; } public boolean isAceptado() { return aceptado; } public void setAceptado(boolean aceptado) { this.aceptado = aceptado; } @Override public String toString() { return "MensajeAmistad [aceptado=" + aceptado + "]"; } }
gpl-3.0
Keltek/mucommander
src/main/com/mucommander/ui/action/impl/ToggleTableViewModeCompactAction.java
2674
/* * This file is part of trolCommander, http://www.trolsoft.ru/en/soft/trolcommander * Copyright (C) 2014-2016 Oleg Trifonov * * trolCommander 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. * * trolCommander 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.mucommander.ui.action.impl; import com.mucommander.ui.action.AbstractActionDescriptor; import com.mucommander.ui.action.ActionCategory; import com.mucommander.ui.action.ActionDescriptor; import com.mucommander.ui.action.MuAction; import com.mucommander.ui.main.MainFrame; import com.mucommander.ui.main.table.views.TableViewMode; import javax.swing.KeyStroke; import java.awt.event.KeyEvent; import java.util.Map; /** * @author Oleg Trifonov * Created on 15/04/15. */ public class ToggleTableViewModeCompactAction extends MuAction { /** * Creates a new <code>ToggleTableViewModeCompactAction</code> * * @param mainFrame the MainFrame to associate with this new MuAction * @param properties the initial properties to use in this action. The Hashtable may simply be empty if no initial */ ToggleTableViewModeCompactAction(MainFrame mainFrame, Map<String, Object> properties) { super(mainFrame, properties); } @Override public void performAction() { getMainFrame().getActiveTable().setViewMode(TableViewMode.COMPACT); } @Override public ActionDescriptor getDescriptor() { return new Descriptor(); } public static final class Descriptor extends AbstractActionDescriptor { public static final String ACTION_ID = "ToggleTableViewModeCompact"; public String getId() { return ACTION_ID; } public ActionCategory getCategory() { return ActionCategory.VIEW; } public KeyStroke getDefaultAltKeyStroke() { return null; } public KeyStroke getDefaultKeyStroke() { return KeyStroke.getKeyStroke(KeyEvent.VK_2, KeyEvent.CTRL_DOWN_MASK); } public MuAction createAction(MainFrame mainFrame, Map<String, Object> properties) { return new ToggleTableViewModeCompactAction(mainFrame, properties); } } }
gpl-3.0
syslover33/ctank
java/android-sdk-linux_r24.4.1_src/sources/android-23/android/support/v17/leanback/widget/SearchOrbView.java
12627
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v17.leanback.widget; import android.animation.ArgbEvaluator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.R; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; /** * <p>A widget that draws a search affordance, represented by a round background and an icon.</p> * * The background color and icon can be customized. */ public class SearchOrbView extends FrameLayout implements View.OnClickListener { private OnClickListener mListener; private View mRootView; private View mSearchOrbView; private ImageView mIcon; private Drawable mIconDrawable; private Colors mColors; private final float mFocusedZoom; private final int mPulseDurationMs; private final int mScaleDurationMs; private final float mUnfocusedZ; private final float mFocusedZ; private ValueAnimator mColorAnimator; /** * A set of colors used to display the search orb. */ public static class Colors { private static final float sBrightnessAlpha = 0.15f; /** * Constructs a color set using the given color for the search orb. * Other colors are provided by the framework. * * @param color The main search orb color. */ public Colors(@ColorInt int color) { this(color, color); } /** * Constructs a color set using the given colors for the search orb. * Other colors are provided by the framework. * * @param color The main search orb color. * @param brightColor A brighter version of the search orb used for animation. */ public Colors(@ColorInt int color, @ColorInt int brightColor) { this(color, brightColor, Color.TRANSPARENT); } /** * Constructs a color set using the given colors. * * @param color The main search orb color. * @param brightColor A brighter version of the search orb used for animation. * @param iconColor A color used to tint the search orb icon. */ public Colors(@ColorInt int color, @ColorInt int brightColor, @ColorInt int iconColor) { this.color = color; this.brightColor = brightColor == color ? getBrightColor(color) : brightColor; this.iconColor = iconColor; } /** * The main color of the search orb. */ @ColorInt public int color; /** * A brighter version of the search orb used for animation. */ @ColorInt public int brightColor; /** * A color used to tint the search orb icon. */ @ColorInt public int iconColor; /** * Computes a default brighter version of the given color. */ public static int getBrightColor(int color) { final float brightnessValue = 0xff * sBrightnessAlpha; int red = (int)(Color.red(color) * (1 - sBrightnessAlpha) + brightnessValue); int green = (int)(Color.green(color) * (1 - sBrightnessAlpha) + brightnessValue); int blue = (int)(Color.blue(color) * (1 - sBrightnessAlpha) + brightnessValue); int alpha = (int)(Color.alpha(color) * (1 - sBrightnessAlpha) + brightnessValue); return Color.argb(alpha, red, green, blue); } } private final ArgbEvaluator mColorEvaluator = new ArgbEvaluator(); private final ValueAnimator.AnimatorUpdateListener mUpdateListener = new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animator) { Integer color = (Integer) animator.getAnimatedValue(); setOrbViewColor(color.intValue()); } }; private ValueAnimator mShadowFocusAnimator; private final ValueAnimator.AnimatorUpdateListener mFocusUpdateListener = new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { setSearchOrbZ(animation.getAnimatedFraction()); } }; private void setSearchOrbZ(float fraction) { ShadowHelper.getInstance().setZ(mSearchOrbView, mUnfocusedZ + fraction * (mFocusedZ - mUnfocusedZ)); } public SearchOrbView(Context context) { this(context, null); } public SearchOrbView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.searchOrbViewStyle); } public SearchOrbView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); final Resources res = context.getResources(); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mRootView = inflater.inflate(getLayoutResourceId(), this, true); mSearchOrbView = mRootView.findViewById(R.id.search_orb); mIcon = (ImageView) mRootView.findViewById(R.id.icon); mFocusedZoom = context.getResources().getFraction( R.fraction.lb_search_orb_focused_zoom, 1, 1); mPulseDurationMs = context.getResources().getInteger( R.integer.lb_search_orb_pulse_duration_ms); mScaleDurationMs = context.getResources().getInteger( R.integer.lb_search_orb_scale_duration_ms); mFocusedZ = context.getResources().getDimensionPixelSize( R.dimen.lb_search_orb_focused_z); mUnfocusedZ = context.getResources().getDimensionPixelSize( R.dimen.lb_search_orb_unfocused_z); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.lbSearchOrbView, defStyleAttr, 0); Drawable img = a.getDrawable(R.styleable.lbSearchOrbView_searchOrbIcon); if (img == null) { img = res.getDrawable(R.drawable.lb_ic_in_app_search); } setOrbIcon(img); int defColor = res.getColor(R.color.lb_default_search_color); int color = a.getColor(R.styleable.lbSearchOrbView_searchOrbColor, defColor); int brightColor = a.getColor( R.styleable.lbSearchOrbView_searchOrbBrightColor, color); int iconColor = a.getColor(R.styleable.lbSearchOrbView_searchOrbIconColor, Color.TRANSPARENT); setOrbColors(new Colors(color, brightColor, iconColor)); a.recycle(); setFocusable(true); setClipChildren(false); setOnClickListener(this); setSoundEffectsEnabled(false); setSearchOrbZ(0); // Icon has no background, but must be on top of the search orb view ShadowHelper.getInstance().setZ(mIcon, mFocusedZ); } int getLayoutResourceId() { return R.layout.lb_search_orb; } void scaleOrbViewOnly(float scale) { mSearchOrbView.setScaleX(scale); mSearchOrbView.setScaleY(scale); } float getFocusedZoom() { return mFocusedZoom; } @Override public void onClick(View view) { if (null != mListener) { mListener.onClick(view); } } private void startShadowFocusAnimation(boolean gainFocus, int duration) { if (mShadowFocusAnimator == null) { mShadowFocusAnimator = ValueAnimator.ofFloat(0f, 1f); mShadowFocusAnimator.addUpdateListener(mFocusUpdateListener); } if (gainFocus) { mShadowFocusAnimator.start(); } else { mShadowFocusAnimator.reverse(); } mShadowFocusAnimator.setDuration(duration); } @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); animateOnFocus(gainFocus); } void animateOnFocus(boolean hasFocus) { final float zoom = hasFocus ? mFocusedZoom : 1f; mRootView.animate().scaleX(zoom).scaleY(zoom).setDuration(mScaleDurationMs).start(); startShadowFocusAnimation(hasFocus, mScaleDurationMs); enableOrbColorAnimation(hasFocus); } /** * Sets the orb icon. * @param icon the drawable to be used as the icon */ public void setOrbIcon(Drawable icon) { mIconDrawable = icon; mIcon.setImageDrawable(mIconDrawable); } /** * Returns the orb icon * @return the drawable used as the icon */ public Drawable getOrbIcon() { return mIconDrawable; } /** * Sets the on click listener for the orb. * @param listener The listener. */ public void setOnOrbClickedListener(OnClickListener listener) { mListener = listener; if (null != listener) { setVisibility(View.VISIBLE); } else { setVisibility(View.INVISIBLE); } } /** * Sets the background color of the search orb. * Other colors will be provided by the framework. * * @param color the RGBA color */ public void setOrbColor(int color) { setOrbColors(new Colors(color, color, Color.TRANSPARENT)); } /** * Sets the search orb colors. * Other colors are provided by the framework. * @deprecated Use {@link #setOrbColors(Colors)} instead. */ @Deprecated public void setOrbColor(@ColorInt int color, @ColorInt int brightColor) { setOrbColors(new Colors(color, brightColor, Color.TRANSPARENT)); } /** * Returns the orb color * @return the RGBA color */ @ColorInt public int getOrbColor() { return mColors.color; } /** * Sets the {@link Colors} used to display the search orb. */ public void setOrbColors(Colors colors) { mColors = colors; mIcon.setColorFilter(mColors.iconColor); if (mColorAnimator == null) { setOrbViewColor(mColors.color); } else { enableOrbColorAnimation(true); } } /** * Returns the {@link Colors} used to display the search orb. */ public Colors getOrbColors() { return mColors; } /** * Enables or disables the orb color animation. * * <p> * Orb color animation is handled automatically when the orb is focused/unfocused, * however, an app may choose to override the current animation state, for example * when an activity is paused. * </p> */ public void enableOrbColorAnimation(boolean enable) { if (mColorAnimator != null) { mColorAnimator.end(); mColorAnimator = null; } if (enable) { // TODO: set interpolator (material if available) mColorAnimator = ValueAnimator.ofObject(mColorEvaluator, mColors.color, mColors.brightColor, mColors.color); mColorAnimator.setRepeatCount(ValueAnimator.INFINITE); mColorAnimator.setDuration(mPulseDurationMs * 2); mColorAnimator.addUpdateListener(mUpdateListener); mColorAnimator.start(); } } private void setOrbViewColor(int color) { if (mSearchOrbView.getBackground() instanceof GradientDrawable) { ((GradientDrawable) mSearchOrbView.getBackground()).setColor(color); } } @Override protected void onDetachedFromWindow() { // Must stop infinite animation to prevent activity leak enableOrbColorAnimation(false); super.onDetachedFromWindow(); } }
gpl-3.0
nikolamilosevic86/TableAnnotator
src/classifiers/PragmaticClassifier.java
12768
package classifiers; import java.io.File; import java.io.PrintWriter; import Utils.Utilities; import stats.Statistics; import tablInEx.Table; import weka.classifiers.misc.InputMappedClassifier; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.FastVector; import weka.core.Instance; import weka.core.Instances; import weka.core.SelectedTag; import weka.core.stemmers.SnowballStemmer; import weka.core.stopwords.WordsFromFile; import weka.filters.Filter; import weka.filters.unsupervised.attribute.StringToWordVector; public class PragmaticClassifier { private String ClassifierPath=""; //private Classifier classifier; InputMappedClassifier classifier = new InputMappedClassifier(); public PragmaticClassifier(String path) { ClassifierPath = path; try { classifier.setModelPath(ClassifierPath); classifier.setTrim(true); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String Classify(Table t) { String prediction = ""; Instances ins = null; // Declare attributes Attribute Attribute1 = new Attribute("num_of_rows"); Attribute Attribute2 = new Attribute("num_of_columns"); Attribute Attribute3 = new Attribute("num_of_header_rows"); Attribute Attribute4 = new Attribute("percentage_of_numeric_cells"); Attribute Attribute5 = new Attribute("percentage_of_seminumeric_cells"); Attribute Attribute6 = new Attribute("percentage_of_string_cells"); Attribute Attribute7 = new Attribute("percentage_of_empty_cells"); Attribute Attribute8 = new Attribute("header_strings",(FastVector)null); Attribute Attribute9 = new Attribute("stub_strings",(FastVector)null); Attribute Attribute10 = new Attribute("caption",(FastVector)null); Attribute Attribute11 = new Attribute("footer",(FastVector)null); FastVector fvClassVal = new FastVector(3); fvClassVal.addElement("findings"); fvClassVal.addElement("settings"); fvClassVal.addElement("support-knowledge"); Attribute ClassAttribute = new Attribute("table_class", fvClassVal); // Declare the feature vector FastVector fvWekaAttributes = new FastVector(11); String header = ""; String stub = ""; int empty = 0; int string = 0; int seminum = 0; int num = 0; int cells_num = 0; if (t.cells != null) for (int i = 0; i < t.cells.length; i++) { for (int k = 0; k < t.cells[i].length; k++) { cells_num++; if(t.cells[i][k]==null||t.cells[i][k].getCell_content()==null) continue; if(Utilities.isSpaceOrEmpty(t.cells[i][k].getCell_content())) { empty++; } else if (t.cells[i][k].getCellType().equals("Partially Numeric")) { seminum++; } else if (t.cells[i][k].getCellType().equals("Numeric")) { num++; } else if (t.cells[i][k].getCellType().equals("Text")) { string++; } if (t.cells[i][k].isIs_header()) header += t.cells[i][k].getCell_content() + " "; if (t.cells[i][k].isIs_stub()) stub += t.cells[i][k].getCell_content() + " "; } } float perc_num = (float)num/(float)cells_num; float perc_seminum = (float)seminum/(float)cells_num; float perc_string = (float)string/(float)cells_num; float perc_empty = (float)empty/(float)cells_num; fvWekaAttributes.addElement(Attribute1); fvWekaAttributes.addElement(Attribute2); fvWekaAttributes.addElement(Attribute3); fvWekaAttributes.addElement(Attribute4); fvWekaAttributes.addElement(Attribute5); fvWekaAttributes.addElement(Attribute6); fvWekaAttributes.addElement(Attribute7); fvWekaAttributes.addElement(Attribute8); fvWekaAttributes.addElement(Attribute9); fvWekaAttributes.addElement(Attribute10); fvWekaAttributes.addElement(Attribute11); fvWekaAttributes.addElement(ClassAttribute); Instances Instances = new Instances("Rel", fvWekaAttributes, 0); Instance iExample = new DenseInstance(12); if(t.getTable_caption()==null) { t.setTable_caption(""); } Attribute attribute = (Attribute)fvWekaAttributes.elementAt(0); iExample.setValue((Attribute)fvWekaAttributes.elementAt(0), t.getNum_of_rows()); iExample.setValue((Attribute)fvWekaAttributes.elementAt(1), t.getNum_of_columns()); iExample.setValue((Attribute)fvWekaAttributes.elementAt(2), t.stat.getNum_of_header_rows()); iExample.setValue((Attribute)fvWekaAttributes.elementAt(3), perc_num); iExample.setValue((Attribute)fvWekaAttributes.elementAt(4), perc_seminum); iExample.setValue((Attribute)fvWekaAttributes.elementAt(5), perc_string); iExample.setValue((Attribute)fvWekaAttributes.elementAt(6), perc_empty); iExample.setValue((Attribute)fvWekaAttributes.elementAt(7), header); iExample.setValue((Attribute)fvWekaAttributes.elementAt(8), stub); iExample.setValue((Attribute)fvWekaAttributes.elementAt(9), t.getTable_caption()); iExample.setValue((Attribute)fvWekaAttributes.elementAt(10), t.getTable_footer()); Instances.add(iExample); Instances.setClassIndex(11); StringToWordVector filter = new StringToWordVector(); filter.setAttributeIndices("first-last"); filter.setMinTermFreq(1); filter.setIDFTransform(true); filter.setTFTransform(true); filter.setLowerCaseTokens(true); filter.setNormalizeDocLength(new SelectedTag(StringToWordVector.FILTER_NORMALIZE_ALL, StringToWordVector.TAGS_FILTER)); filter.setOutputWordCounts(true); SnowballStemmer stemmer = new SnowballStemmer(); //stemmer.setStemmer("English"); filter.setStemmer(stemmer); WordsFromFile sw = new WordsFromFile(); sw.setStopwords(new File("Models/stop-words-english1.txt")); filter.setStopwordsHandler(sw); Instances newData; try { filter.setInputFormat(Instances); filter.input(Instances.instance(0)); filter.batchFinished(); ins= Filter.useFilter(Instances,filter); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { double result = classifier.classifyInstance(ins.firstInstance()); ins.firstInstance().setClassValue(result); prediction=ins.firstInstance().classAttribute().value((int)result); t.PragmaticClass = prediction; System.out.println(t.PragmaticClass); new File(t.PragmaticClass).mkdirs(); PrintWriter writer = new PrintWriter(t.PragmaticClass+File.separator+t.getDocumentFileName()+t.getTable_title()+".html", "UTF-8"); writer.println(t.getXml()); writer.close(); Statistics.addPragmaticTableType(prediction); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return prediction; } public String Classify2(Table t,String class1, String class2) { String prediction = ""; Instances ins = null; // Declare attributes Attribute Attribute1 = new Attribute("num_of_rows"); Attribute Attribute2 = new Attribute("num_of_columns"); Attribute Attribute3 = new Attribute("num_of_header_rows"); Attribute Attribute4 = new Attribute("percentage_of_numeric_cells"); Attribute Attribute5 = new Attribute("percentage_of_seminumeric_cells"); Attribute Attribute6 = new Attribute("percentage_of_string_cells"); Attribute Attribute7 = new Attribute("percentage_of_empty_cells"); Attribute Attribute8 = new Attribute("header_strings",(FastVector)null); Attribute Attribute9 = new Attribute("stub_strings",(FastVector)null); Attribute Attribute10 = new Attribute("caption",(FastVector)null); Attribute Attribute11 = new Attribute("footer",(FastVector)null); FastVector fvClassVal = new FastVector(2); fvClassVal.addElement(class1); fvClassVal.addElement(class2); Attribute ClassAttribute = new Attribute("table_class", fvClassVal); // Declare the feature vector FastVector fvWekaAttributes = new FastVector(11); String header = ""; String stub = ""; int empty = 0; int string = 0; int seminum = 0; int num = 0; int cells_num = 0; if (t.cells != null) for (int i = 0; i < t.cells.length; i++) { for (int k = 0; k < t.cells[i].length; k++) { cells_num++; if(t.cells[i][k]==null||t.cells[i][k].getCell_content()==null) continue; if(Utilities.isSpaceOrEmpty(t.cells[i][k].getCell_content())) { empty++; } else if (t.cells[i][k].getCellType().equals("Partially Numeric")) { seminum++; } else if (t.cells[i][k].getCellType().equals("Numeric")) { num++; } else if (t.cells[i][k].getCellType().equals("Text")) { string++; } if (t.cells[i][k].isIs_header()) header += t.cells[i][k].getCell_content() + " "; if (t.cells[i][k].isIs_stub()) stub += t.cells[i][k].getCell_content() + " "; } } float perc_num = (float)num/(float)cells_num; float perc_seminum = (float)seminum/(float)cells_num; float perc_string = (float)string/(float)cells_num; float perc_empty = (float)empty/(float)cells_num; fvWekaAttributes.addElement(Attribute1); fvWekaAttributes.addElement(Attribute2); fvWekaAttributes.addElement(Attribute3); fvWekaAttributes.addElement(Attribute4); fvWekaAttributes.addElement(Attribute5); fvWekaAttributes.addElement(Attribute6); fvWekaAttributes.addElement(Attribute7); fvWekaAttributes.addElement(Attribute8); fvWekaAttributes.addElement(Attribute9); fvWekaAttributes.addElement(Attribute10); fvWekaAttributes.addElement(Attribute11); fvWekaAttributes.addElement(ClassAttribute); Instances Instances = new Instances("Rel", fvWekaAttributes, 0); Instance iExample = new DenseInstance(12); Attribute attribute = (Attribute)fvWekaAttributes.elementAt(0); iExample.setValue((Attribute)fvWekaAttributes.elementAt(0), t.getNum_of_rows()); iExample.setValue((Attribute)fvWekaAttributes.elementAt(1), t.getNum_of_columns()); iExample.setValue((Attribute)fvWekaAttributes.elementAt(2), t.stat.getNum_of_header_rows()); iExample.setValue((Attribute)fvWekaAttributes.elementAt(3), perc_num); iExample.setValue((Attribute)fvWekaAttributes.elementAt(4), perc_seminum); iExample.setValue((Attribute)fvWekaAttributes.elementAt(5), perc_string); iExample.setValue((Attribute)fvWekaAttributes.elementAt(6), perc_empty); iExample.setValue((Attribute)fvWekaAttributes.elementAt(7), header); iExample.setValue((Attribute)fvWekaAttributes.elementAt(8), stub); iExample.setValue((Attribute)fvWekaAttributes.elementAt(9), t.getTable_caption()); iExample.setValue((Attribute)fvWekaAttributes.elementAt(10), t.getTable_footer()); Instances.add(iExample); Instances.setClassIndex(11); StringToWordVector filter = new StringToWordVector(); filter.setAttributeIndices("first-last"); filter.setMinTermFreq(1); filter.setIDFTransform(true); filter.setTFTransform(true); filter.setLowerCaseTokens(true); filter.setNormalizeDocLength(new SelectedTag(StringToWordVector.FILTER_NORMALIZE_ALL, StringToWordVector.TAGS_FILTER)); filter.setOutputWordCounts(true); SnowballStemmer stemmer = new SnowballStemmer(); //stemmer.setStemmer("English"); filter.setStemmer(stemmer); WordsFromFile sw = new WordsFromFile(); sw.setStopwords(new File("Models/stop-words-english1.txt")); filter.setStopwordsHandler(sw); Instances newData; try { filter.setInputFormat(Instances); filter.input(Instances.instance(0)); filter.batchFinished(); ins= Filter.useFilter(Instances,filter); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { double result = classifier.classifyInstance(ins.firstInstance()); ins.firstInstance().setClassValue(result); prediction=ins.firstInstance().classAttribute().value((int)result); t.PragmaticClass = prediction; System.out.println(t.PragmaticClass); new File(t.PragmaticClass).mkdirs(); PrintWriter writer = new PrintWriter(t.PragmaticClass+File.separator+t.getDocumentFileName()+t.getTable_title()+".html", "UTF-8"); writer.println(t.getXml()); writer.close(); Statistics.addPragmaticTableType(prediction); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return prediction; } }
gpl-3.0
jbeerdev/Switch-
src/es/task/switcher/model/entities/Category.java
335
package es.task.switcher.model.entities; import com.mobandme.ada.Entity; import com.mobandme.ada.annotations.Table; import com.mobandme.ada.annotations.TableField; @Table(name = "Category") public class Category extends Entity{ @TableField(name = "name", datatype = DATATYPE_STRING, maxLength = 100) public String name = ""; }
gpl-3.0
JDuligall/ZombieSim
honorsWorkspace/ZombieSim2/src/mapContents/Nd.java
1846
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.05.02 at 06:10:56 PM NZST // package mapContents; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="ref" use="required" type="{http://www.w3.org/2001/XMLSchema}unsignedLong" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "nd") public class Nd { @XmlAttribute(name = "ref", required = true) @XmlSchemaType(name = "unsignedLong") protected BigInteger ref; /** * Gets the value of the ref property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getRef() { return ref; } /** * Sets the value of the ref property. * * @param value * allowed object is * {@link BigInteger } * */ public void setRef(BigInteger value) { this.ref = value; } }
gpl-3.0
CCAFS/MARLO
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/ReportSynthesisKeyPartnershipPmu.java
2592
package org.cgiar.ccafs.marlo.data.model; // Generated Jun 20, 2018 1:50:25 PM by Hibernate Tools 3.4.0.CR1 import org.cgiar.ccafs.marlo.data.IAuditLog; import com.google.gson.annotations.Expose; /** * ReportSynthesisMeliaStudy generated by hbm2java */ public class ReportSynthesisKeyPartnershipPmu extends MarloAuditableEntity implements java.io.Serializable, IAuditLog { private static final long serialVersionUID = 5761871053421733437L; @Expose private ReportSynthesisKeyPartnership reportSynthesisKeyPartnership; @Expose private ReportSynthesisKeyPartnershipExternal reportSynthesisKeyPartnershipExternal; public ReportSynthesisKeyPartnershipPmu() { } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } ReportSynthesisKeyPartnershipPmu other = (ReportSynthesisKeyPartnershipPmu) obj; if (this.getReportSynthesisKeyPartnershipExternal() == null) { if (other.getReportSynthesisKeyPartnershipExternal() != null) { return false; } } else if (!this.getReportSynthesisKeyPartnershipExternal() .equals(other.getReportSynthesisKeyPartnershipExternal())) { return false; } if (this.getReportSynthesisKeyPartnership() == null) { if (other.getReportSynthesisKeyPartnership() != null) { return false; } } else if (!this.getReportSynthesisKeyPartnership().getId() .equals(other.getReportSynthesisKeyPartnership().getId())) { return false; } return true; } @Override public String getLogDeatil() { StringBuilder sb = new StringBuilder(); sb.append("Id : ").append(this.getId()); return sb.toString(); } public ReportSynthesisKeyPartnership getReportSynthesisKeyPartnership() { return reportSynthesisKeyPartnership; } public ReportSynthesisKeyPartnershipExternal getReportSynthesisKeyPartnershipExternal() { return reportSynthesisKeyPartnershipExternal; } public void setReportSynthesisKeyPartnership(ReportSynthesisKeyPartnership reportSynthesisKeyPartnership) { this.reportSynthesisKeyPartnership = reportSynthesisKeyPartnership; } public void setReportSynthesisKeyPartnershipExternal( ReportSynthesisKeyPartnershipExternal reportSynthesisKeyPartnershipExternal) { this.reportSynthesisKeyPartnershipExternal = reportSynthesisKeyPartnershipExternal; } }
gpl-3.0
mrlolethan/Buttered-Pixel-Dungeon
src/com/mrlolethan/butteredpd/effects/particles/SmokeParticle.java
1728
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2015 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.mrlolethan.butteredpd.effects.particles; import com.watabou.noosa.particles.Emitter; import com.watabou.noosa.particles.Emitter.Factory; import com.watabou.noosa.particles.PixelParticle; import com.watabou.utils.Random; public class SmokeParticle extends PixelParticle { public static final Factory FACTORY = new Factory() { @Override public void emit( Emitter emitter, int index, float x, float y ) { ((SmokeParticle)emitter.recycle( SmokeParticle.class )).reset( x, y ); } }; public SmokeParticle() { super(); color( 0x222222 ); acc.set( 0, -40 ); } public void reset( float x, float y ) { revive(); this.x = x; this.y = y; left = lifespan = Random.Float( 0.6f, 1f ); speed.set( Random.Float( -4, +4 ), Random.Float( -8, +8 ) ); } @Override public void update() { super.update(); float p = left / lifespan; am = p > 0.8f ? 2 - 2*p : p * 0.5f; size( 16 - p * 8 ); } }
gpl-3.0
ftninformatika/bisis-v5
bisis-model/src/main/java/com/ftninformatika/bisis/opac/search/Sort.java
788
package com.ftninformatika.bisis.opac.search; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * @author badf00d21 15.8.19. */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class Sort { private SortType type; private Boolean ascending; public SortType getType() { return type; } public void setType(String st) { switch (st) { case "AU_sort" : this.type = SortType.SORT_AUTHOR; break; case "PY_sort" : this.type = SortType.SORT_YEAR; break; case "PU_sort" : this.type = SortType.SORT_PUBLISHER; break; case "TI_sort" : this.type = SortType.SORT_TITLE; break; default: this.type = null; } } }
gpl-3.0
chubbymaggie/jbse
src/jbse/tree/DecisionAlternative_XNEWARRAY_Wrong.java
758
package jbse.tree; public final class DecisionAlternative_XNEWARRAY_Wrong extends DecisionAlternative_XNEWARRAY { private static final String WRONG_ID = "XNEWARRAY_Wrong"; private static final int HASH_CODE = 2; DecisionAlternative_XNEWARRAY_Wrong(boolean isConcrete) { super(isConcrete, (isConcrete ? 1 : HASH_CODE)); } @Override public boolean ok() { return false; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return true; } @Override public int hashCode() { return HASH_CODE; } @Override public String toString() { return WRONG_ID; } }
gpl-3.0
januar/KulinARMedan
src/org/medankulinar/mgr/downloader/DownloadManager.java
2100
/* * Copyright (C) 2010- Peer internet solutions * * This file is part of mixare. * * 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.medankulinar.mgr.downloader; /** * This class establishes a connection and downloads the data for each entry in * its todo list one after another. */ public interface DownloadManager { /** * Possible state of this Manager */ enum DownloadManagerState { OnLine, //manage downlad request OffLine, // No OnLine Downloading, //Process some Download Request Confused // Internal state not congruent } /** * Reset all Request and Responce */ void resetActivity(); /** * Submit new DownloadRequest * * @param job * @return reference Of Job or null if job is rejected */ String submitJob(DownloadRequest job); /** * Get result of job if exist, null otherwise * * @param jobId reference of Job * @return result */ DownloadResult getReqResult(String jobId); /** * Pseudo Iterator on results * @return actual Download Result */ DownloadResult getNextResult(); /** * Gets the number of downloaded results * @return the number of results */ int getResultSize(); /** * check if all Download request is done * * @return BOOLEAN */ Boolean isDone(); /** * Request to active the service */ void switchOn(); /** * Request to deactive the service */ void switchOff(); /** * Request state of service * @return */ DownloadManagerState getState(); }
gpl-3.0
mrbradleyjh/BlazeFly
com/bradleyjh/blazefly/Main.java
16141
//////////////////////////////////////////////////////////////////////////// // This file is part of BlazeFly. // // // // BlazeFly 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. // // // // BlazeFly 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 BlazeFly. If not, see <http://www.gnu.org/licenses/>. // //////////////////////////////////////////////////////////////////////////// package com.bradleyjh.blazefly; import java.util.HashMap; import java.io.File; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.event.Listener; import org.bukkit.entity.Player; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.GameMode; import org.bukkit.configuration.file.YamlConfiguration; public class Main extends JavaPlugin implements Listener { Core core = new Core(); String updateAvailable; public void onEnable() { saveDefaultConfig(); core.stringsFile = new File(getDataFolder() + File.separator + "strings.yml"); if (! core.stringsFile.exists()) { saveResource("strings.yml", false); } core.strings = YamlConfiguration.loadConfiguration(core.stringsFile); core.playersFile = new File(getDataFolder() + File.separator + "players.yml"); core.players = YamlConfiguration.loadConfiguration(core.playersFile); core.retrieveAll(); core.disabledWorlds = getConfig().getStringList("disabledWorlds"); getServer().getPluginManager().registerEvents(this, this); if (getConfig().getBoolean("updateChecker")) { getServer().getScheduler().runTaskAsynchronously(this, new Updater(this, getDescription().getVersion())); } getServer().getScheduler().scheduleSyncRepeatingTask(this, new Timer(this), 10L, 10L); } public void onDisable() { core.storeAll(); } // Replaces the deprecated getServer().getPlayer() public Player getPlayer(String name) { for (Player player : getServer().getOnlinePlayers()) { if (player.getName().equalsIgnoreCase(name)) { return player; } } return null; } // Check permissions public boolean hasPermission (CommandSender sender, String permission) { if (sender.hasPermission("blazefly." + permission)) { return true; } return false; } // Get the fuel block currently used public String fuelBlock(Player player) { if (hasPermission(player, "vip")) { return getConfig().getString("VIPBlock").toUpperCase(); } else { return getConfig().getString("fuelBlock").toUpperCase(); } } // Get the fuel subdata currently used public Integer fuelSubdata(Player player) { if (hasPermission(player, "vip")) { return getConfig().getInt("VIPSubdata"); } else { return getConfig().getInt("fuelSubdata"); } } // Get the time each fuel block should last (-1 because Timer adds a second at 0) public Double fuelTime(Player player) { if (hasPermission(player, "vip")) { return getConfig().getDouble("VIPTime") - 1; } else { return getConfig().getDouble("fuelTime") - 1; } } // Make sure the gamemode is applicable for BlazeFly public Boolean correctMode (Player player) { if (player.getGameMode() == GameMode.SURVIVAL) { return true; } if (player.getGameMode() == GameMode.ADVENTURE) { return true; } return false; } // Process incoming commands public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { // Reload the configuration file if (commandLabel.equalsIgnoreCase("bfreload")) { if (! hasPermission(sender, "reload")) { core.messagePlayer(sender, "permission", null); return true; } reloadConfig(); core.stringsFile = new File(getDataFolder() + File.separator + "strings.yml"); core.strings = YamlConfiguration.loadConfiguration(core.stringsFile); core.disabledWorlds = getConfig().getStringList("disabledWorlds"); core.messagePlayer(sender, "reload", null); return true; } // Disable a given users flight if (commandLabel.equalsIgnoreCase("flyoff")) { if (hasPermission(sender, "flyoff")) { if (args.length != 1) { return false; } Player target = getPlayer(args[0]); if ((target == null) || (!target.isOnline())) { HashMap<String, String> keywords = new HashMap<>(); keywords.put("%player%", args[0]); core.messagePlayer(sender, "notOnline", keywords); return true; } if (! target.getAllowFlight()) { HashMap<String, String> keywords = new HashMap<>(); keywords.put("%player%", args[0]); core.messagePlayer(sender, "notFlying", keywords); return true; } core.setFalling(target, true); core.setFlying(target, false); HashMap<String, String> keywords = new HashMap<>(); keywords.put("%player%", args[0]); core.messagePlayer(sender, "flyoffAdmin", keywords); core.messagePlayer(target, "flyoffPlayer", null); return true; } else { core.messagePlayer(sender, "permission", null); } return true; } // Prevent console from using flight commands if (! (sender instanceof Player)) { sender.sendMessage("Console cannot fly"); return true; } Player player = (Player)sender; // If they aren't in the correct mode, ignore commands if (! correctMode(player)) { core.messagePlayer(player, "mode", null); return true; } if ((core.disabledWorlds.contains(player.getWorld().getName())) && (! hasPermission(player, "anyworld"))) { core.messagePlayer(player, "disabled", null); return true; } // Fly (or bfly) command to enable/disable flight if (commandLabel.equalsIgnoreCase("fly") || commandLabel.equalsIgnoreCase("bfly")) { if (! hasPermission(player, "use")) { core.messagePlayer(player, "permission", null); return true; } if (args.length > 0) { return false; } // Disable flight if (player.getAllowFlight()) { core.setFalling(player, true); core.setFlying(player, false); player.setAllowFlight(false); core.messagePlayer(player, "fDisabled", null); return true; } // Enable flight else { // Wings are broken, can't fly if (core.isBroken(player)) { core.messagePlayer(player, "wBroken", null); return true; } // Doesn't require fuel if (hasPermission(player, "nofuel")) { core.messagePlayer(player, "fEnabled", null); core.setFlying(player, true); player.setAllowFlight(true); return true; } // Regular and VIP players if (core.hasFuel(player, fuelBlock(player), fuelSubdata(player)) || core.hasFuelCount(player)) { core.messagePlayer(player, "fEnabled", null); core.setFlying(player, true); player.setAllowFlight(true); if (! core.hasFuelCount(player)) { core.increaseFuelCount(player, fuelTime(player)); core.removeFuel(player, fuelBlock(player), fuelSubdata(player)); } if (! core.hasFuel(player, fuelBlock(player), fuelSubdata(player))) { core.messagePlayer(player, "fLast", null); } } else { String fuelName = getConfig().getString("fuelName"); if (hasPermission(player, "vip")) { fuelName = getConfig().getString("VIPName"); } HashMap<String, String> keywords = new HashMap<>(); keywords.put("%fuel%", fuelName); core.messagePlayer(player, "fRequired", keywords); return true; } return true; } } // Change your speed of flight (1x, 2x or 4x speed) if (commandLabel.equalsIgnoreCase("flyspeed")) { if (! hasPermission(player, "flyspeed")) { core.messagePlayer(player, "permission", null); return true; } if (getConfig().getString("allowSpeed").equalsIgnoreCase("false")) { core.messagePlayer(player, "fsDisabled", null); return true; } if (! player.getAllowFlight()) { core.messagePlayer(player, "fsFlight", null); return true; } if (args.length == 0) { if (player.getFlySpeed() == 0.1F) { core.messagePlayer(player, "fs1", null); return true; } if (player.getFlySpeed() == 0.2F) { core.messagePlayer(player, "fs2", null); return true; } if (player.getFlySpeed() == 0.4F) { core.messagePlayer(player, "fs4", null); return true; } } else { if (args[0].equals("1")) { player.setFlySpeed(0.1F); core.messagePlayer(player, "fs1", null); return true; } if (args[0].equals("2")) { player.setFlySpeed(0.2F); core.messagePlayer(player, "fs2", null); return true; } if (args[0].equals("4")) { player.setFlySpeed(0.4F); core.messagePlayer(player, "fs4", null); return true; } core.messagePlayer(player, "fsOptions", null); return true; } } // Fuel command to check how many seconds of fuel are remaining if (commandLabel.equalsIgnoreCase("fuel")) { if (! hasPermission(player, "use")) { core.messagePlayer(player, "permission", null); return true; } if (args.length > 0) { return false; } if (! core.hasFuelCount(player)) { if (hasPermission(player, "nofuel")) { core.messagePlayer(player, "fuelNA", null); return true; } else { core.messagePlayer(player, "fuelStart", null); return true; } } HashMap<String, String> keywords = new HashMap<>(); Integer flySpeed = Math.round(player.getFlySpeed() * 10); Double rawSeconds = core.getFuelCount(player) / flySpeed; Integer roundSeconds = Math.round(rawSeconds.longValue()); keywords.put("%seconds%", roundSeconds.toString()); keywords.put("%flyspeed%", flySpeed.toString()); core.messagePlayer(sender, "fuelMessage", keywords); return true; } return false; } @EventHandler public void onDamage(EntityDamageEvent event) { if ((event.getEntity() instanceof Player)) { Player player = (Player)event.getEntity(); // Protect players falling due to running out of fuel, if enabled if ((event.getCause().equals(EntityDamageEvent.DamageCause.FALL)) && (core.isFalling(player))) { if (getConfig().getBoolean("fallProtection")) { event.setCancelled(true); return; } } // Ignore these types of damage if (event.getCause().equals(EntityDamageEvent.DamageCause.DROWNING)) { return; } if (event.getCause().equals(EntityDamageEvent.DamageCause.STARVATION)) { return; } if (event.getDamage() == 0) { return; } // PvP stuff, break wings (disallow flight) if player takes damage if ((getConfig().getBoolean("breakableWings")) && (! hasPermission(player, "superwings")) && (core.isFlying(player))) { core.setFalling(player, true); core.setFlying(player, false); core.setBrokenCounter(player, getConfig().getDouble("healTime")); player.setAllowFlight(false); core.messagePlayer(player, "wBroke", null); } } } // Reset flyspeed & message admins for new versions @EventHandler public void onPlayerJoin(PlayerJoinEvent event){ Player player = event.getPlayer(); player.setFlySpeed(0.1F); core.retrievePlayer(player); if (hasPermission(player, "updates") && updateAvailable != null) { String header = getConfig().getString("header"); String message = header + updateAvailable + " is available for download"; player.sendMessage(ChatColor.translateAlternateColorCodes('&', message)); } } // Clear broken wing counter if player dies @EventHandler public void onDeath(PlayerDeathEvent event) { if ((event.getEntity() instanceof Player)) { Player player = (Player)event.getEntity(); if (core.isBroken(player)) { core.removeBroken(player); player.setAllowFlight(true); core.setFlying(player, true); core.messagePlayer(player, "wHealed", null); } } } // Prevent flight toggle for mode switch @EventHandler public void onGameMode(PlayerGameModeChangeEvent event) { if (event.getNewGameMode() == GameMode.SURVIVAL || event.getNewGameMode() == GameMode.ADVENTURE) { if (core.isFlying(event.getPlayer())) { final Player player = event.getPlayer(); getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { player.setAllowFlight(true); player.getPlayer().setFlying(true); } }, 2L); } } } }
gpl-3.0
rbi/trading4j
core/src/main/java/de/voidnode/trading4j/strategyexpertadvisor/StrategyExpertAdvisor.java
3923
package de.voidnode.trading4j.strategyexpertadvisor; import java.time.Instant; import java.util.Optional; import de.voidnode.trading4j.api.Broker; import de.voidnode.trading4j.api.ExpertAdvisor; import de.voidnode.trading4j.api.Failed; import de.voidnode.trading4j.api.OrderEventListener; import de.voidnode.trading4j.domain.marketdata.MarketData; import de.voidnode.trading4j.domain.monetary.Price; import de.voidnode.trading4j.domain.orders.BasicPendingOrder; /** * Creates and manages orders based on a strategy taken as input. * * @author Raik Bieniek * @param <C> * The concrete type of {@link MarketData}s that are used as input. */ public class StrategyExpertAdvisor<C extends MarketData> implements ExpertAdvisor<C>, OrderEventListener { private final TradingStrategy<C> strategy; private final PendingOrderCreator creator; private final PendingOrderManager orderManager; private final TradeManager tradeManager; private State currentState = State.TRY_CREATE; private Optional<Order> currentOrder; /** * Initial the expert advisor. * * @param strategy * A calculator thats values should be updated when new market data arrives. * @param broker * The broker that should be used to execute orders. */ public StrategyExpertAdvisor(final TradingStrategy<C> strategy, final Broker<BasicPendingOrder> broker) { this.strategy = strategy; this.creator = new PendingOrderCreator(strategy, broker); this.orderManager = new PendingOrderManager(strategy, broker); this.tradeManager = new TradeManager(strategy); } /** * Initializes the expert advisor. * * @param strategy * A calculator thats values should be updated when new market data arrives. * @param creator * Used to place pending orders. * @param orderManager * Used to manage opened pending orders. * @param tradeManager * Used to manage active trades. */ StrategyExpertAdvisor(final TradingStrategy<C> strategy, final PendingOrderCreator creator, final PendingOrderManager orderManager, final TradeManager tradeManager) { this.strategy = strategy; this.creator = creator; this.orderManager = orderManager; this.tradeManager = tradeManager; } @Override public void newData(final C candleStick) { strategy.update(candleStick); switch (currentState) { case TRY_CREATE: currentOrder = creator.checkMarketEntry(this); if (currentOrder.isPresent()) { currentState = State.MANAGE_ORDER; } break; case MANAGE_ORDER: currentOrder = orderManager.manageOrder(currentOrder.get(), this); if (!currentOrder.isPresent()) { currentState = State.TRY_CREATE; } break; case MANAGE_TRADE: currentOrder = tradeManager.manageTrade(currentOrder.get()); if (!currentOrder.isPresent()) { currentState = State.TRY_CREATE; } break; default: throw new IllegalStateException("Unhandled state " + currentState); } } @Override public void orderRejected(final Failed failure) { currentState = State.TRY_CREATE; } @Override public void orderOpened(final Instant time, final Price price) { currentState = State.MANAGE_TRADE; } @Override public void orderClosed(final Instant time, final Price price) { currentState = State.TRY_CREATE; } /** * The current state the strategy is in. */ private enum State { TRY_CREATE, MANAGE_ORDER, MANAGE_TRADE } }
gpl-3.0
IsThisThePayneResidence/intellidots
src/main/java/ua/edu/hneu/ast/parsers/RParser.java
34879
// Generated from /mnt/hdd/Programming/Projects/Groovy/intellidots/src/main/antlr/R.g4 by ANTLR 4.2.2 package ua.edu.hneu.ast.parsers; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; import java.util.List; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class RParser extends Parser { protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int T__53=1, T__52=2, T__51=3, T__50=4, T__49=5, T__48=6, T__47=7, T__46=8, T__45=9, T__44=10, T__43=11, T__42=12, T__41=13, T__40=14, T__39=15, T__38=16, T__37=17, T__36=18, T__35=19, T__34=20, T__33=21, T__32=22, T__31=23, T__30=24, T__29=25, T__28=26, T__27=27, T__26=28, T__25=29, T__24=30, T__23=31, T__22=32, T__21=33, T__20=34, T__19=35, T__18=36, T__17=37, T__16=38, T__15=39, T__14=40, T__13=41, T__12=42, T__11=43, T__10=44, T__9=45, T__8=46, T__7=47, T__6=48, T__5=49, T__4=50, T__3=51, T__2=52, T__1=53, T__0=54, HEX=55, INT=56, FLOAT=57, COMPLEX=58, STRING=59, ID=60, USER_OP=61, NL=62, WS=63; public static final String[] tokenNames = { "<INVALID>", "'->>'", "'!='", "'while'", "'{'", "'&&'", "'::'", "'='", "'for'", "'^'", "'$'", "'('", "'Inf'", "','", "'repeat'", "'NA'", "'<-'", "'FALSE'", "':::'", "'>='", "'[['", "'<'", "']'", "'~'", "'@'", "'function'", "'NULL'", "'+'", "'TRUE'", "'/'", "'||'", "';'", "'}'", "'if'", "'?'", "':='", "'<='", "'break'", "'&'", "'*'", "'->'", "'...'", "'NaN'", "':'", "'['", "'|'", "'=='", "'>'", "'!'", "'in'", "'else'", "'next'", "')'", "'-'", "'<<-'", "HEX", "INT", "FLOAT", "COMPLEX", "STRING", "ID", "USER_OP", "NL", "WS" }; public static final int RULE_prog = 0, RULE_expr = 1, RULE_exprlist = 2, RULE_formlist = 3, RULE_form = 4, RULE_sublist = 5, RULE_sub = 6; public static final String[] ruleNames = { "prog", "expr", "exprlist", "formlist", "form", "sublist", "sub" }; @Override public String getGrammarFileName() { return "R.g4"; } @Override public String[] getTokenNames() { return tokenNames; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public RParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class ProgContext extends ParserRuleContext { public List<TerminalNode> NL() { return getTokens(RParser.NL); } public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public TerminalNode EOF() { return getToken(RParser.EOF, 0); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public TerminalNode NL(int i) { return getToken(RParser.NL, i); } public ProgContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_prog; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).enterProg(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).exitProg(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitProg(this); else return visitor.visitChildren(this); } } public final ProgContext prog() throws RecognitionException { ProgContext _localctx = new ProgContext(_ctx, getState()); enterRule(_localctx, 0, RULE_prog); int _la; try { enterOuterAlt(_localctx, 1); { setState(20); _errHandler.sync(this); _la = _input.LA(1); while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << 3) | (1L << 4) | (1L << 8) | (1L << 11) | (1L << 12) | (1L << 14) | (1L << 15) | (1L << 17) | (1L << 23) | (1L << 25) | (1L << 26) | (1L << 27) | (1L << 28) | (1L << 33) | (1L << 34) | (1L << 37) | (1L << 42) | (1L << 48) | (1L << 51) | (1L << 53) | (1L << HEX) | (1L << INT) | (1L << FLOAT) | (1L << COMPLEX) | (1L << STRING) | (1L << ID) | (1L << NL))) != 0)) { { setState(18); switch (_input.LA(1)) { case 3: case 4: case 8: case 11: case 12: case 14: case 15: case 17: case 23: case 25: case 26: case 27: case 28: case 33: case 34: case 37: case 42: case 48: case 51: case 53: case HEX: case INT: case FLOAT: case COMPLEX: case STRING: case ID: { setState(14); expr(0); setState(15); _la = _input.LA(1); if ( !(_la==31 || _la==NL) ) { _errHandler.recoverInline(this); } consume(); } break; case NL: { setState(17); match(NL); } break; default: throw new NoViableAltException(this); } } setState(22); _errHandler.sync(this); _la = _input.LA(1); } setState(23); match(EOF); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ExprContext extends ParserRuleContext { public TerminalNode ID() { return getToken(RParser.ID, 0); } public TerminalNode HEX() { return getToken(RParser.HEX, 0); } public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public TerminalNode USER_OP() { return getToken(RParser.USER_OP, 0); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public SublistContext sublist() { return getRuleContext(SublistContext.class,0); } public FormlistContext formlist() { return getRuleContext(FormlistContext.class,0); } public TerminalNode STRING() { return getToken(RParser.STRING, 0); } public ExprlistContext exprlist() { return getRuleContext(ExprlistContext.class,0); } public TerminalNode INT() { return getToken(RParser.INT, 0); } public TerminalNode COMPLEX() { return getToken(RParser.COMPLEX, 0); } public TerminalNode FLOAT() { return getToken(RParser.FLOAT, 0); } public ExprContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_expr; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).enterExpr(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).exitExpr(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitExpr(this); else return visitor.visitChildren(this); } } public final ExprContext expr() throws RecognitionException { return expr(0); } private ExprContext expr(int _p) throws RecognitionException { ParserRuleContext _parentctx = _ctx; int _parentState = getState(); ExprContext _localctx = new ExprContext(_ctx, _parentState); ExprContext _prevctx = _localctx; int _startState = 2; enterRecursionRule(_localctx, 2, RULE_expr, _p); int _la; try { int _alt; enterOuterAlt(_localctx, 1); { setState(93); switch ( getInterpreter().adaptivePredict(_input,3,_ctx) ) { case 1: { setState(26); _la = _input.LA(1); if ( !(_la==27 || _la==53) ) { _errHandler.recoverInline(this); } consume(); setState(27); expr(36); } break; case 2: { setState(28); match(48); setState(29); expr(30); } break; case 3: { setState(30); match(23); setState(31); expr(27); } break; case 4: { setState(32); match(25); setState(33); match(11); setState(35); _la = _input.LA(1); if (_la==41 || _la==ID) { { setState(34); formlist(); } } setState(37); match(52); setState(38); expr(24); } break; case 5: { setState(39); match(14); setState(40); expr(17); } break; case 6: { setState(41); match(34); setState(42); expr(16); } break; case 7: { setState(43); match(4); setState(44); exprlist(); setState(45); match(32); } break; case 8: { setState(47); match(33); setState(48); match(11); setState(49); expr(0); setState(50); match(52); setState(51); expr(0); } break; case 9: { setState(53); match(33); setState(54); match(11); setState(55); expr(0); setState(56); match(52); setState(57); expr(0); setState(58); match(50); setState(59); expr(0); } break; case 10: { setState(61); match(8); setState(62); match(11); setState(63); match(ID); setState(64); match(49); setState(65); expr(0); setState(66); match(52); setState(67); expr(0); } break; case 11: { setState(69); match(3); setState(70); match(11); setState(71); expr(0); setState(72); match(52); setState(73); expr(0); } break; case 12: { setState(75); match(51); } break; case 13: { setState(76); match(37); } break; case 14: { setState(77); match(11); setState(78); expr(0); setState(79); match(52); } break; case 15: { setState(81); match(ID); } break; case 16: { setState(82); match(STRING); } break; case 17: { setState(83); match(HEX); } break; case 18: { setState(84); match(INT); } break; case 19: { setState(85); match(FLOAT); } break; case 20: { setState(86); match(COMPLEX); } break; case 21: { setState(87); match(26); } break; case 22: { setState(88); match(15); } break; case 23: { setState(89); match(12); } break; case 24: { setState(90); match(42); } break; case 25: { setState(91); match(28); } break; case 26: { setState(92); match(17); } break; } _ctx.stop = _input.LT(-1); setState(149); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,5,_ctx); while ( _alt!=2 && _alt!=ATN.INVALID_ALT_NUMBER ) { if ( _alt==1 ) { if ( _parseListeners!=null ) triggerExitRuleEvent(); _prevctx = _localctx; { setState(147); switch ( getInterpreter().adaptivePredict(_input,4,_ctx) ) { case 1: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(95); if (!(precpred(_ctx, 39))) throw new FailedPredicateException(this, "precpred(_ctx, 39)"); setState(96); _la = _input.LA(1); if ( !(_la==6 || _la==18) ) { _errHandler.recoverInline(this); } consume(); setState(97); expr(40); } break; case 2: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(98); if (!(precpred(_ctx, 38))) throw new FailedPredicateException(this, "precpred(_ctx, 38)"); setState(99); _la = _input.LA(1); if ( !(_la==10 || _la==24) ) { _errHandler.recoverInline(this); } consume(); setState(100); expr(39); } break; case 3: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(101); if (!(precpred(_ctx, 37))) throw new FailedPredicateException(this, "precpred(_ctx, 37)"); setState(102); match(9); setState(103); expr(38); } break; case 4: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(104); if (!(precpred(_ctx, 35))) throw new FailedPredicateException(this, "precpred(_ctx, 35)"); setState(105); match(43); setState(106); expr(36); } break; case 5: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(107); if (!(precpred(_ctx, 34))) throw new FailedPredicateException(this, "precpred(_ctx, 34)"); setState(108); match(USER_OP); setState(109); expr(35); } break; case 6: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(110); if (!(precpred(_ctx, 33))) throw new FailedPredicateException(this, "precpred(_ctx, 33)"); setState(111); _la = _input.LA(1); if ( !(_la==29 || _la==39) ) { _errHandler.recoverInline(this); } consume(); setState(112); expr(34); } break; case 7: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(113); if (!(precpred(_ctx, 32))) throw new FailedPredicateException(this, "precpred(_ctx, 32)"); setState(114); _la = _input.LA(1); if ( !(_la==27 || _la==53) ) { _errHandler.recoverInline(this); } consume(); setState(115); expr(33); } break; case 8: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(116); if (!(precpred(_ctx, 31))) throw new FailedPredicateException(this, "precpred(_ctx, 31)"); setState(117); _la = _input.LA(1); if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << 2) | (1L << 19) | (1L << 21) | (1L << 36) | (1L << 46) | (1L << 47))) != 0)) ) { _errHandler.recoverInline(this); } consume(); setState(118); expr(32); } break; case 9: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(119); if (!(precpred(_ctx, 29))) throw new FailedPredicateException(this, "precpred(_ctx, 29)"); setState(120); _la = _input.LA(1); if ( !(_la==5 || _la==38) ) { _errHandler.recoverInline(this); } consume(); setState(121); expr(30); } break; case 10: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(122); if (!(precpred(_ctx, 28))) throw new FailedPredicateException(this, "precpred(_ctx, 28)"); setState(123); _la = _input.LA(1); if ( !(_la==30 || _la==45) ) { _errHandler.recoverInline(this); } consume(); setState(124); expr(29); } break; case 11: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(125); if (!(precpred(_ctx, 26))) throw new FailedPredicateException(this, "precpred(_ctx, 26)"); setState(126); match(23); setState(127); expr(27); } break; case 12: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(128); if (!(precpred(_ctx, 25))) throw new FailedPredicateException(this, "precpred(_ctx, 25)"); setState(129); _la = _input.LA(1); if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << 1) | (1L << 7) | (1L << 16) | (1L << 35) | (1L << 40) | (1L << 54))) != 0)) ) { _errHandler.recoverInline(this); } consume(); setState(130); expr(26); } break; case 13: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(131); if (!(precpred(_ctx, 41))) throw new FailedPredicateException(this, "precpred(_ctx, 41)"); setState(132); match(20); setState(133); sublist(); setState(134); match(22); setState(135); match(22); } break; case 14: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(137); if (!(precpred(_ctx, 40))) throw new FailedPredicateException(this, "precpred(_ctx, 40)"); setState(138); match(44); setState(139); sublist(); setState(140); match(22); } break; case 15: { _localctx = new ExprContext(_parentctx, _parentState); pushNewRecursionContext(_localctx, _startState, RULE_expr); setState(142); if (!(precpred(_ctx, 23))) throw new FailedPredicateException(this, "precpred(_ctx, 23)"); setState(143); match(11); setState(144); sublist(); setState(145); match(52); } break; } } } setState(151); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,5,_ctx); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { unrollRecursionContexts(_parentctx); } return _localctx; } public static class ExprlistContext extends ParserRuleContext { public List<TerminalNode> NL() { return getTokens(RParser.NL); } public List<ExprContext> expr() { return getRuleContexts(ExprContext.class); } public ExprContext expr(int i) { return getRuleContext(ExprContext.class,i); } public TerminalNode NL(int i) { return getToken(RParser.NL, i); } public ExprlistContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_exprlist; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).enterExprlist(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).exitExprlist(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitExprlist(this); else return visitor.visitChildren(this); } } public final ExprlistContext exprlist() throws RecognitionException { ExprlistContext _localctx = new ExprlistContext(_ctx, getState()); enterRule(_localctx, 4, RULE_exprlist); int _la; try { setState(163); switch (_input.LA(1)) { case 3: case 4: case 8: case 11: case 12: case 14: case 15: case 17: case 23: case 25: case 26: case 27: case 28: case 33: case 34: case 37: case 42: case 48: case 51: case 53: case HEX: case INT: case FLOAT: case COMPLEX: case STRING: case ID: enterOuterAlt(_localctx, 1); { setState(152); expr(0); setState(159); _errHandler.sync(this); _la = _input.LA(1); while (_la==31 || _la==NL) { { { setState(153); _la = _input.LA(1); if ( !(_la==31 || _la==NL) ) { _errHandler.recoverInline(this); } consume(); setState(155); _la = _input.LA(1); if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << 3) | (1L << 4) | (1L << 8) | (1L << 11) | (1L << 12) | (1L << 14) | (1L << 15) | (1L << 17) | (1L << 23) | (1L << 25) | (1L << 26) | (1L << 27) | (1L << 28) | (1L << 33) | (1L << 34) | (1L << 37) | (1L << 42) | (1L << 48) | (1L << 51) | (1L << 53) | (1L << HEX) | (1L << INT) | (1L << FLOAT) | (1L << COMPLEX) | (1L << STRING) | (1L << ID))) != 0)) { { setState(154); expr(0); } } } } setState(161); _errHandler.sync(this); _la = _input.LA(1); } } break; case 32: enterOuterAlt(_localctx, 2); { } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class FormlistContext extends ParserRuleContext { public FormContext form(int i) { return getRuleContext(FormContext.class,i); } public List<FormContext> form() { return getRuleContexts(FormContext.class); } public FormlistContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_formlist; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).enterFormlist(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).exitFormlist(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitFormlist(this); else return visitor.visitChildren(this); } } public final FormlistContext formlist() throws RecognitionException { FormlistContext _localctx = new FormlistContext(_ctx, getState()); enterRule(_localctx, 6, RULE_formlist); int _la; try { enterOuterAlt(_localctx, 1); { setState(165); form(); setState(170); _errHandler.sync(this); _la = _input.LA(1); while (_la==13) { { { setState(166); match(13); setState(167); form(); } } setState(172); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class FormContext extends ParserRuleContext { public TerminalNode ID() { return getToken(RParser.ID, 0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public FormContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_form; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).enterForm(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).exitForm(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitForm(this); else return visitor.visitChildren(this); } } public final FormContext form() throws RecognitionException { FormContext _localctx = new FormContext(_ctx, getState()); enterRule(_localctx, 8, RULE_form); try { setState(178); switch ( getInterpreter().adaptivePredict(_input,10,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(173); match(ID); } break; case 2: enterOuterAlt(_localctx, 2); { setState(174); match(ID); setState(175); match(7); setState(176); expr(0); } break; case 3: enterOuterAlt(_localctx, 3); { setState(177); match(41); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SublistContext extends ParserRuleContext { public SubContext sub(int i) { return getRuleContext(SubContext.class,i); } public List<SubContext> sub() { return getRuleContexts(SubContext.class); } public SublistContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_sublist; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).enterSublist(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).exitSublist(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitSublist(this); else return visitor.visitChildren(this); } } public final SublistContext sublist() throws RecognitionException { SublistContext _localctx = new SublistContext(_ctx, getState()); enterRule(_localctx, 10, RULE_sublist); int _la; try { enterOuterAlt(_localctx, 1); { setState(180); sub(); setState(185); _errHandler.sync(this); _la = _input.LA(1); while (_la==13) { { { setState(181); match(13); setState(182); sub(); } } setState(187); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SubContext extends ParserRuleContext { public TerminalNode ID() { return getToken(RParser.ID, 0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public TerminalNode STRING() { return getToken(RParser.STRING, 0); } public SubContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_sub; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).enterSub(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof RListener ) ((RListener)listener).exitSub(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitSub(this); else return visitor.visitChildren(this); } } public final SubContext sub() throws RecognitionException { SubContext _localctx = new SubContext(_ctx, getState()); enterRule(_localctx, 12, RULE_sub); try { setState(206); switch ( getInterpreter().adaptivePredict(_input,12,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(188); expr(0); } break; case 2: enterOuterAlt(_localctx, 2); { setState(189); match(ID); setState(190); match(7); } break; case 3: enterOuterAlt(_localctx, 3); { setState(191); match(ID); setState(192); match(7); setState(193); expr(0); } break; case 4: enterOuterAlt(_localctx, 4); { setState(194); match(STRING); setState(195); match(7); } break; case 5: enterOuterAlt(_localctx, 5); { setState(196); match(STRING); setState(197); match(7); setState(198); expr(0); } break; case 6: enterOuterAlt(_localctx, 6); { setState(199); match(26); setState(200); match(7); } break; case 7: enterOuterAlt(_localctx, 7); { setState(201); match(26); setState(202); match(7); setState(203); expr(0); } break; case 8: enterOuterAlt(_localctx, 8); { setState(204); match(41); } break; case 9: enterOuterAlt(_localctx, 9); { } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) { switch (ruleIndex) { case 1: return expr_sempred((ExprContext)_localctx, predIndex); } return true; } private boolean expr_sempred(ExprContext _localctx, int predIndex) { switch (predIndex) { case 0: return precpred(_ctx, 39); case 1: return precpred(_ctx, 38); case 2: return precpred(_ctx, 37); case 3: return precpred(_ctx, 35); case 4: return precpred(_ctx, 34); case 5: return precpred(_ctx, 33); case 6: return precpred(_ctx, 32); case 7: return precpred(_ctx, 31); case 8: return precpred(_ctx, 29); case 9: return precpred(_ctx, 28); case 10: return precpred(_ctx, 26); case 11: return precpred(_ctx, 25); case 12: return precpred(_ctx, 41); case 13: return precpred(_ctx, 40); case 14: return precpred(_ctx, 23); } return true; } public static final String _serializedATN = "\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3A\u00d3\4\2\t\2\4"+ "\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\3\2\3\2\3\2\3\2\7\2\25"+ "\n\2\f\2\16\2\30\13\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\5\3&\n\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\5\3`\n\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\7\3\u0096\n\3\f\3\16\3\u0099\13\3\3\4"+ "\3\4\3\4\5\4\u009e\n\4\7\4\u00a0\n\4\f\4\16\4\u00a3\13\4\3\4\5\4\u00a6"+ "\n\4\3\5\3\5\3\5\7\5\u00ab\n\5\f\5\16\5\u00ae\13\5\3\6\3\6\3\6\3\6\3\6"+ "\5\6\u00b5\n\6\3\7\3\7\3\7\7\7\u00ba\n\7\f\7\16\7\u00bd\13\7\3\b\3\b\3"+ "\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\5\b\u00d1"+ "\n\b\3\b\2\3\4\t\2\4\6\b\n\f\16\2\13\4\2!!@@\4\2\35\35\67\67\4\2\b\b\24"+ "\24\4\2\f\f\32\32\4\2\37\37))\7\2\4\4\25\25\27\27&&\60\61\4\2\7\7((\4"+ "\2 //\b\2\3\3\t\t\22\22%%**88\u0105\2\26\3\2\2\2\4_\3\2\2\2\6\u00a5\3"+ "\2\2\2\b\u00a7\3\2\2\2\n\u00b4\3\2\2\2\f\u00b6\3\2\2\2\16\u00d0\3\2\2"+ "\2\20\21\5\4\3\2\21\22\t\2\2\2\22\25\3\2\2\2\23\25\7@\2\2\24\20\3\2\2"+ "\2\24\23\3\2\2\2\25\30\3\2\2\2\26\24\3\2\2\2\26\27\3\2\2\2\27\31\3\2\2"+ "\2\30\26\3\2\2\2\31\32\7\2\2\3\32\3\3\2\2\2\33\34\b\3\1\2\34\35\t\3\2"+ "\2\35`\5\4\3&\36\37\7\62\2\2\37`\5\4\3 !\7\31\2\2!`\5\4\3\35\"#\7\33"+ "\2\2#%\7\r\2\2$&\5\b\5\2%$\3\2\2\2%&\3\2\2\2&\'\3\2\2\2\'(\7\66\2\2(`"+ "\5\4\3\32)*\7\20\2\2*`\5\4\3\23+,\7$\2\2,`\5\4\3\22-.\7\6\2\2./\5\6\4"+ "\2/\60\7\"\2\2\60`\3\2\2\2\61\62\7#\2\2\62\63\7\r\2\2\63\64\5\4\3\2\64"+ "\65\7\66\2\2\65\66\5\4\3\2\66`\3\2\2\2\678\7#\2\289\7\r\2\29:\5\4\3\2"+ ":;\7\66\2\2;<\5\4\3\2<=\7\64\2\2=>\5\4\3\2>`\3\2\2\2?@\7\n\2\2@A\7\r\2"+ "\2AB\7>\2\2BC\7\63\2\2CD\5\4\3\2DE\7\66\2\2EF\5\4\3\2F`\3\2\2\2GH\7\5"+ "\2\2HI\7\r\2\2IJ\5\4\3\2JK\7\66\2\2KL\5\4\3\2L`\3\2\2\2M`\7\65\2\2N`\7"+ "\'\2\2OP\7\r\2\2PQ\5\4\3\2QR\7\66\2\2R`\3\2\2\2S`\7>\2\2T`\7=\2\2U`\7"+ "9\2\2V`\7:\2\2W`\7;\2\2X`\7<\2\2Y`\7\34\2\2Z`\7\21\2\2[`\7\16\2\2\\`\7"+ ",\2\2]`\7\36\2\2^`\7\23\2\2_\33\3\2\2\2_\36\3\2\2\2_ \3\2\2\2_\"\3\2\2"+ "\2_)\3\2\2\2_+\3\2\2\2_-\3\2\2\2_\61\3\2\2\2_\67\3\2\2\2_?\3\2\2\2_G\3"+ "\2\2\2_M\3\2\2\2_N\3\2\2\2_O\3\2\2\2_S\3\2\2\2_T\3\2\2\2_U\3\2\2\2_V\3"+ "\2\2\2_W\3\2\2\2_X\3\2\2\2_Y\3\2\2\2_Z\3\2\2\2_[\3\2\2\2_\\\3\2\2\2_]"+ "\3\2\2\2_^\3\2\2\2`\u0097\3\2\2\2ab\f)\2\2bc\t\4\2\2c\u0096\5\4\3*de\f"+ "(\2\2ef\t\5\2\2f\u0096\5\4\3)gh\f\'\2\2hi\7\13\2\2i\u0096\5\4\3(jk\f%"+ "\2\2kl\7-\2\2l\u0096\5\4\3&mn\f$\2\2no\7?\2\2o\u0096\5\4\3%pq\f#\2\2q"+ "r\t\6\2\2r\u0096\5\4\3$st\f\"\2\2tu\t\3\2\2u\u0096\5\4\3#vw\f!\2\2wx\t"+ "\7\2\2x\u0096\5\4\3\"yz\f\37\2\2z{\t\b\2\2{\u0096\5\4\3 |}\f\36\2\2}~"+ "\t\t\2\2~\u0096\5\4\3\37\177\u0080\f\34\2\2\u0080\u0081\7\31\2\2\u0081"+ "\u0096\5\4\3\35\u0082\u0083\f\33\2\2\u0083\u0084\t\n\2\2\u0084\u0096\5"+ "\4\3\34\u0085\u0086\f+\2\2\u0086\u0087\7\26\2\2\u0087\u0088\5\f\7\2\u0088"+ "\u0089\7\30\2\2\u0089\u008a\7\30\2\2\u008a\u0096\3\2\2\2\u008b\u008c\f"+ "*\2\2\u008c\u008d\7.\2\2\u008d\u008e\5\f\7\2\u008e\u008f\7\30\2\2\u008f"+ "\u0096\3\2\2\2\u0090\u0091\f\31\2\2\u0091\u0092\7\r\2\2\u0092\u0093\5"+ "\f\7\2\u0093\u0094\7\66\2\2\u0094\u0096\3\2\2\2\u0095a\3\2\2\2\u0095d"+ "\3\2\2\2\u0095g\3\2\2\2\u0095j\3\2\2\2\u0095m\3\2\2\2\u0095p\3\2\2\2\u0095"+ "s\3\2\2\2\u0095v\3\2\2\2\u0095y\3\2\2\2\u0095|\3\2\2\2\u0095\177\3\2\2"+ "\2\u0095\u0082\3\2\2\2\u0095\u0085\3\2\2\2\u0095\u008b\3\2\2\2\u0095\u0090"+ "\3\2\2\2\u0096\u0099\3\2\2\2\u0097\u0095\3\2\2\2\u0097\u0098\3\2\2\2\u0098"+ "\5\3\2\2\2\u0099\u0097\3\2\2\2\u009a\u00a1\5\4\3\2\u009b\u009d\t\2\2\2"+ "\u009c\u009e\5\4\3\2\u009d\u009c\3\2\2\2\u009d\u009e\3\2\2\2\u009e\u00a0"+ "\3\2\2\2\u009f\u009b\3\2\2\2\u00a0\u00a3\3\2\2\2\u00a1\u009f\3\2\2\2\u00a1"+ "\u00a2\3\2\2\2\u00a2\u00a6\3\2\2\2\u00a3\u00a1\3\2\2\2\u00a4\u00a6\3\2"+ "\2\2\u00a5\u009a\3\2\2\2\u00a5\u00a4\3\2\2\2\u00a6\7\3\2\2\2\u00a7\u00ac"+ "\5\n\6\2\u00a8\u00a9\7\17\2\2\u00a9\u00ab\5\n\6\2\u00aa\u00a8\3\2\2\2"+ "\u00ab\u00ae\3\2\2\2\u00ac\u00aa\3\2\2\2\u00ac\u00ad\3\2\2\2\u00ad\t\3"+ "\2\2\2\u00ae\u00ac\3\2\2\2\u00af\u00b5\7>\2\2\u00b0\u00b1\7>\2\2\u00b1"+ "\u00b2\7\t\2\2\u00b2\u00b5\5\4\3\2\u00b3\u00b5\7+\2\2\u00b4\u00af\3\2"+ "\2\2\u00b4\u00b0\3\2\2\2\u00b4\u00b3\3\2\2\2\u00b5\13\3\2\2\2\u00b6\u00bb"+ "\5\16\b\2\u00b7\u00b8\7\17\2\2\u00b8\u00ba\5\16\b\2\u00b9\u00b7\3\2\2"+ "\2\u00ba\u00bd\3\2\2\2\u00bb\u00b9\3\2\2\2\u00bb\u00bc\3\2\2\2\u00bc\r"+ "\3\2\2\2\u00bd\u00bb\3\2\2\2\u00be\u00d1\5\4\3\2\u00bf\u00c0\7>\2\2\u00c0"+ "\u00d1\7\t\2\2\u00c1\u00c2\7>\2\2\u00c2\u00c3\7\t\2\2\u00c3\u00d1\5\4"+ "\3\2\u00c4\u00c5\7=\2\2\u00c5\u00d1\7\t\2\2\u00c6\u00c7\7=\2\2\u00c7\u00c8"+ "\7\t\2\2\u00c8\u00d1\5\4\3\2\u00c9\u00ca\7\34\2\2\u00ca\u00d1\7\t\2\2"+ "\u00cb\u00cc\7\34\2\2\u00cc\u00cd\7\t\2\2\u00cd\u00d1\5\4\3\2\u00ce\u00d1"+ "\7+\2\2\u00cf\u00d1\3\2\2\2\u00d0\u00be\3\2\2\2\u00d0\u00bf\3\2\2\2\u00d0"+ "\u00c1\3\2\2\2\u00d0\u00c4\3\2\2\2\u00d0\u00c6\3\2\2\2\u00d0\u00c9\3\2"+ "\2\2\u00d0\u00cb\3\2\2\2\u00d0\u00ce\3\2\2\2\u00d0\u00cf\3\2\2\2\u00d1"+ "\17\3\2\2\2\17\24\26%_\u0095\u0097\u009d\u00a1\u00a5\u00ac\u00b4\u00bb"+ "\u00d0"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
gpl-3.0
Unisay/preferanser
web-test/src/test/java/com/preferanser/webtest/CardsPresenceTest.java
1414
/* * Preferanser is a program to simulate and calculate Russian Preferans Card game deals. * * Copyright (C) 2013 Yuriy Lazarev <Yuriy.Lazarev@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.preferanser.webtest; import com.preferanser.shared.domain.Card; import com.preferanser.webtest.requirements.Application; import net.thucydides.core.annotations.Story; import org.junit.Test; import static com.preferanser.shared.domain.TableLocation.*; @Story(Application.Table.Cards.Presence.class) public class CardsPresenceTest extends TableTest { @Test public void allCardsShouldBePresentOnSouth() { endUser.onTheTablePage() .canSeeCardsAt(SOUTH, Card.values()) .canSeeNoCardsAt(EAST, WEST); } }
gpl-3.0
ovgu-ccd/jchess
jchess/game/IOSystem.java
847
package jchess.game; import jchess.eventbus.events.*; import net.engio.mbassy.listener.Handler; /** * Bridge between GL and User Input. * * Created by andreas on 06.12.14. * * @trace [$REQ07] */ @SuppressWarnings("UnusedDeclaration") public interface IOSystem { @Handler void handleSelectEvent(SelectEvent selectEvent); @Handler void handleUpdateBoardEvent(UpdateBoardEvent updateBoardEvent); @Handler void handlePossibleMovesEvent(PossibleMovesEvent possibleMovesEvent); @Handler void handlePossiblePromotionsEvent(PossiblePromotionsEvent possiblePromotionsEvent); @Handler void handlePromotionSelectEvent(PromotionSelectEvent promotionSelectEvent); @Handler void handleUpdateStatusMessageEvent(UpdateStatusMessageEvent updateStatusMessageEvent); void setPlayer(Player player); }
gpl-3.0
mastablasta1/a-star-w-algorithm
src/main/java/pl/edu/agh/idziak/asw/common/Pair.java
765
package pl.edu.agh.idziak.asw.common; import com.google.common.base.Preconditions; /** * Created by Tomasz on 13.07.2016. */ public class Pair<X, Y> { private final X one; private final Y two; Pair(X one, Y two) { this.one = Preconditions.checkNotNull(one); this.two = Preconditions.checkNotNull(two); } public static <X, Y> Pair<X, Y> of(X one, Y two) { return new Pair<>(one, two); } public static <T> SingleTypePair<T> ofSingleType(T one, T two) { return new SingleTypePair<>(one, two); } public Y getTwo() { return two; } public X getOne() { return one; } @Override public String toString() { return "[" + one + ", " + two + ']'; } }
gpl-3.0
dmolony/DiskBrowser
src/com/bytezone/diskbrowser/visicalc/Asin.java
823
package com.bytezone.diskbrowser.visicalc; // -----------------------------------------------------------------------------------// class Asin extends ValueFunction // -----------------------------------------------------------------------------------// { // ---------------------------------------------------------------------------------// Asin (Cell cell, String text) // ---------------------------------------------------------------------------------// { super (cell, text); assert text.startsWith ("@ASIN(") : text; } // ---------------------------------------------------------------------------------// @Override public double calculateValue () // ---------------------------------------------------------------------------------// { return Math.asin (source.getDouble ()); } }
gpl-3.0
yuripourre/e-motion
src/main/java/com/harium/keel/filter/selection/skin/SkinColorRGBHCbCrStrategy.java
1693
package com.harium.keel.filter.selection.skin; import com.harium.keel.core.helper.ColorHelper; import com.harium.keel.core.strategy.SelectionStrategy; import com.harium.keel.filter.selection.SimpleToleranceStrategy; /** * Based on: Nusirwan Anwar bin Abdul Rahman, Kit Chong Wei and John See * RGB-H-CbCr Skin Colour Model for Human Face Detection */ public class SkinColorRGBHCbCrStrategy extends SimpleToleranceStrategy implements SelectionStrategy { public SkinColorRGBHCbCrStrategy() { super(); } public SkinColorRGBHCbCrStrategy(int tolerance) { super(tolerance); } @Override public boolean valid(int rgb, int j, int i) { return isSkin(rgb, tolerance); } public static boolean isSkin(int rgb) { return isSkin(rgb, 0); } public static boolean isSkin(int rgb, int tolerance) { boolean ruleA = SkinColorKovacStrategy.isSkin(rgb); final int R = ColorHelper.getRed(rgb); final int G = ColorHelper.getGreen(rgb); final int B = ColorHelper.getBlue(rgb); //final int Y = ColorHelper.getY(R,G,B); final int CB = ColorHelper.getCB(R, G, B); final int CR = ColorHelper.getCR(R, G, B); final float H = ColorHelper.getH(R, G, B); boolean rule3 = CR <= 1.5862 * CB + 20; boolean rule4 = CR >= 0.3448 * CB + 76.2069; boolean rule5 = CR >= -4.5652 * CB + 234.5652; boolean rule6 = CR <= -1.15 * CB + 301.75; boolean rule7 = CR <= -2.2857 * CB + 432.8; boolean ruleB = rule3 && rule4 && rule5 && rule6 && rule7; boolean ruleC = H < 25 && H > 230; return ruleA && ruleB && ruleC; } }
gpl-3.0
mkulesh/microMathematics
app/src/main/java/com/mkulesh/micromath/properties/AxisProperties.java
6711
/* * microMathematics - Extended Visual Calculator * Copyright (C) 2014-2021 by Mikhail Kulesh * * 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. */ package com.mkulesh.micromath.properties; import android.content.res.TypedArray; import android.graphics.Color; import android.os.Parcel; import android.os.Parcelable; import com.mkulesh.micromath.formula.FormulaList; import com.mkulesh.micromath.math.AxisTypeConverter; import com.mkulesh.micromath.plus.R; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; import java.util.Locale; public class AxisProperties implements Parcelable { private static final String XML_PROP_XLABELSNUMBER = "xLabelsNumber"; private static final String XML_PROP_YLABELSNUMBER = "yLabelsNumber"; private static final String XML_PROP_GRIDLINECOLOR = "gridLineColor"; private static final String XML_PROP_XTYPE = "xType"; private static final String XML_PROP_YTYPE = "yType"; public float scaleFactor = 1; public int gridLineColor = Color.GRAY; public int xLabelsNumber = 3; public int yLabelsNumber = 3; public AxisTypeConverter.Type xType = AxisTypeConverter.Type.LINEAR; public AxisTypeConverter.Type yType = AxisTypeConverter.Type.LINEAR; private int labelLineSize = 5; private int labelTextSize = 20; private int gridLineWidth = 1; /** * Parcelable interface */ private AxisProperties(Parcel in) { super(); readFromParcel(in); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(labelLineSize); dest.writeInt(labelTextSize); dest.writeInt(gridLineColor); dest.writeInt(gridLineWidth); dest.writeInt(xLabelsNumber); dest.writeInt(yLabelsNumber); dest.writeInt(xType.ordinal()); dest.writeInt(yType.ordinal()); } private void readFromParcel(Parcel in) { labelLineSize = in.readInt(); labelTextSize = in.readInt(); gridLineColor = in.readInt(); gridLineWidth = in.readInt(); xLabelsNumber = in.readInt(); yLabelsNumber = in.readInt(); xType = AxisTypeConverter.Type.values()[in.readInt()]; yType = AxisTypeConverter.Type.values()[in.readInt()]; } public static final Parcelable.Creator<AxisProperties> CREATOR = new Parcelable.Creator<AxisProperties>() { public AxisProperties createFromParcel(Parcel in) { return new AxisProperties(in); } public AxisProperties[] newArray(int size) { return new AxisProperties[size]; } }; /** * Default constructor */ public AxisProperties() { // empty } public void assign(AxisProperties a) { scaleFactor = a.scaleFactor; gridLineColor = a.gridLineColor; xLabelsNumber = a.xLabelsNumber; yLabelsNumber = a.yLabelsNumber; labelLineSize = a.labelLineSize; labelTextSize = a.labelTextSize; gridLineWidth = a.gridLineWidth; xType = a.xType; yType = a.yType; } public void initialize(TypedArray a) { labelLineSize = a.getDimensionPixelSize(R.styleable.PlotViewExtension_labelLineSize, labelLineSize); labelTextSize = a.getDimensionPixelSize(R.styleable.PlotViewExtension_labelTextSize, labelTextSize); gridLineColor = a.getColor(R.styleable.PlotViewExtension_gridLineColor, gridLineColor); gridLineWidth = a.getDimensionPixelSize(R.styleable.PlotViewExtension_gridLineWidth, gridLineWidth); xLabelsNumber = a.getInt(R.styleable.PlotViewExtension_xLabelsNumber, xLabelsNumber); yLabelsNumber = a.getInt(R.styleable.PlotViewExtension_yLabelsNumber, yLabelsNumber); xType = AxisTypeConverter.Type.LINEAR; yType = AxisTypeConverter.Type.LINEAR; } public void readFromXml(XmlPullParser parser) { String attr = parser.getAttributeValue(null, XML_PROP_XLABELSNUMBER); if (attr != null) { xLabelsNumber = Integer.parseInt(attr); } attr = parser.getAttributeValue(null, XML_PROP_YLABELSNUMBER); if (attr != null) { yLabelsNumber = Integer.parseInt(attr); } attr = parser.getAttributeValue(null, XML_PROP_GRIDLINECOLOR); if (attr != null) { gridLineColor = Color.parseColor(attr); } attr = parser.getAttributeValue(null, XML_PROP_XTYPE); if (attr != null) { try { xType = AxisTypeConverter.Type.valueOf(attr.toUpperCase(Locale.ENGLISH)); } catch (Exception e) { // nothing to do } } attr = parser.getAttributeValue(null, XML_PROP_YTYPE); if (attr != null) { try { yType = AxisTypeConverter.Type.valueOf(attr.toUpperCase(Locale.ENGLISH)); } catch (Exception e) { // nothing to do } } } public void writeToXml(XmlSerializer serializer) throws Exception { serializer.attribute(FormulaList.XML_NS, XML_PROP_XLABELSNUMBER, String.valueOf(xLabelsNumber)); serializer.attribute(FormulaList.XML_NS, XML_PROP_YLABELSNUMBER, String.valueOf(yLabelsNumber)); serializer.attribute(FormulaList.XML_NS, XML_PROP_GRIDLINECOLOR, String.format("#%08X", gridLineColor)); serializer.attribute(FormulaList.XML_NS, XML_PROP_XTYPE, xType.toString().toLowerCase(Locale.ENGLISH)); serializer.attribute(FormulaList.XML_NS, XML_PROP_YTYPE, yType.toString().toLowerCase(Locale.ENGLISH)); } public int getLabelLineSize() { return Math.round(labelLineSize * scaleFactor); } public int getLabelTextSize() { return Math.round(labelTextSize * scaleFactor); } public int getGridLineWidth() { return Math.round(gridLineWidth * scaleFactor); } }
gpl-3.0
epsilony/mf
src/main/java/net/epsilony/mf/model/search/config/TwoDLRTreeSearcherConfig.java
1175
/* * Copyright (C) 2013 Man YUAN <epsilon@epsilony.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.epsilony.mf.model.search.config; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** * @author Man YUAN <epsilonyuan@gmail.com> * */ @Configuration @Import({ SearcherBaseConfig.class, LRTreeNodesRangeSearcherConfig.class, TwoDBoundariesSearcherConfig.class, TwoDLRTreeBoundariesRangeSearcherConfig.class }) public class TwoDLRTreeSearcherConfig { }
gpl-3.0
Lzw2016/cleverframe
clever-sys/src/main/java/org/cleverframe/sys/controller/MenuController.java
5364
package org.cleverframe.sys.controller; import org.cleverframe.common.controller.BaseController; import org.cleverframe.common.mapper.BeanMapper; import org.cleverframe.common.persistence.Page; import org.cleverframe.common.vo.response.AjaxMessage; import org.cleverframe.sys.SysBeanNames; import org.cleverframe.sys.SysJspUrlPath; import org.cleverframe.sys.entity.Menu; import org.cleverframe.sys.service.MenuService; import org.cleverframe.sys.vo.request.*; import org.cleverframe.webui.easyui.data.DataGridJson; import org.cleverframe.webui.easyui.data.TreeGridNodeJson; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.util.List; import java.util.Map; /** * Controller * <p> * 作者:LiZW <br/> * 创建时间:2016-08-24 22:47:29 <br/> */ @SuppressWarnings("MVCPathVariableInspection") @Controller @RequestMapping(value = "/${base.mvcPath}/sys/menu") public class MenuController extends BaseController { @Autowired @Qualifier(SysBeanNames.MenuService) private MenuService menuService; @RequestMapping("/Menu" + VIEW_PAGE_SUFFIX) public ModelAndView getMenuJsp(HttpServletRequest request, HttpServletResponse response) { return new ModelAndView(SysJspUrlPath.Menu); } /** * 分页查询 */ @RequestMapping("/findByPage") @ResponseBody public DataGridJson<Menu> findByPage( HttpServletRequest request, HttpServletResponse response, @Valid MenuQueryVo menuQueryVo, BindingResult bindingResult) { DataGridJson<Menu> json = new DataGridJson<>(); Page<Menu> page = menuService.findByPage(new Page<>(request, response), menuQueryVo.getMenuType(), menuQueryVo.getName(), menuQueryVo.getOpenMode()); json.setRows(page.getList()); json.setTotal(page.getCount()); return json; } /** * 查询所有菜单类型 */ @RequestMapping("/findAllMenuType") @ResponseBody public List<Map<String, Object>> findAllMenuType(HttpServletRequest request, HttpServletResponse response) { return menuService.findAllMenuType(); } /** * 查询菜单树 */ @RequestMapping("/findMenuTreeByType") @ResponseBody public Object findMenuTreeByType( HttpServletRequest request, HttpServletResponse response, @Valid MenuTreeQueryVo menuTreeQueryVo, BindingResult bindingResult) { AjaxMessage<String> message = new AjaxMessage<>(true, "查询菜单树成功", null); if (!beanValidator(bindingResult, message)) { return message; } DataGridJson<TreeGridNodeJson<Menu>> treeGrid = new DataGridJson<>(); List<Menu> menuList = menuService.findMenuByType(menuTreeQueryVo.getMenuType()); for (Menu menu : menuList) { TreeGridNodeJson<Menu> node = new TreeGridNodeJson<>(menu.getParentId(), menu); treeGrid.addRow(node); } return treeGrid; } /** * 增加菜单信息 */ @RequestMapping("/addMenu") @ResponseBody public AjaxMessage<String> addMenu( HttpServletRequest request, HttpServletResponse response, @Valid MenuAddVo menuAddVo, BindingResult bindingResult) { AjaxMessage<String> message = new AjaxMessage<>(true, "新增菜单成功", null); if (beanValidator(bindingResult, message)) { Menu menu = BeanMapper.mapper(menuAddVo, Menu.class); menuService.saveMenu(message, menu); } return message; } /** * 更新菜单信息 */ @RequestMapping("/updateMenu") @ResponseBody public AjaxMessage<String> updateMenu( HttpServletRequest request, HttpServletResponse response, @Valid MenuUpdateVo menuUpdateVo, BindingResult bindingResult) { AjaxMessage<String> message = new AjaxMessage<>(true, "更新菜单成功", null); if (beanValidator(bindingResult, message)) { Menu menu = BeanMapper.mapper(menuUpdateVo, Menu.class); if (!menuService.updateMenu(menu)) { message.setSuccess(false); message.setFailMessage("更新菜单失败"); } } return message; } /** * 删除菜单 */ @RequestMapping("/deleteMenu") @ResponseBody public AjaxMessage<String> deleteMenu( HttpServletRequest request, HttpServletResponse response, @Valid MenuDeleteVo menuDeleteVoe, BindingResult bindingResult) { AjaxMessage<String> message = new AjaxMessage<>(true, "删除菜单成功", null); if (beanValidator(bindingResult, message)) { menuService.deleteMenu(message, menuDeleteVoe.getId()); } return message; } }
gpl-3.0
Bunsan/TerraFirmaStuff
src/main/java/com/technode/terrafirmastuff/core/proxy/CommonProxy.java
1619
package com.technode.terrafirmastuff.core.proxy; import com.bioxx.tfc.api.Tools.ChiselManager; import com.technode.terrafirmastuff.handler.ServerTickHandler; import com.technode.terrafirmastuff.tileentity.TEOilLampMod; import com.technode.terrafirmastuff.tools.ChiselMode_Chiseled; import com.technode.terrafirmastuff.tools.ChiselMode_Circle; import com.technode.terrafirmastuff.tools.ChiselMode_Paver; import com.technode.terrafirmastuff.tools.ChiselMode_Pillar; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.registry.GameRegistry; public abstract class CommonProxy { public void registerChiselModes() { ChiselManager.getInstance().addChiselMode(new ChiselMode_Paver("Paver")); ChiselManager.getInstance().addChiselMode(new ChiselMode_Circle("Circle")); ChiselManager.getInstance().addChiselMode(new ChiselMode_Chiseled("Chiseled")); ChiselManager.getInstance().addChiselMode(new ChiselMode_Pillar("Pillar")); } public void hideNEIItems() {} public void registerRenderInformation() { // NOOP on server } public void registerWailaClasses() { FMLInterModComms.sendMessage("Waila", "register", "com.technode.terrafirmastuff.core.compat.WAILADataMod.onCallbackRegister");// Block } public void registerTileEntities(boolean b) { GameRegistry.registerTileEntity(TEOilLampMod.class, "Oil Lamp Mod"); } public void registerTickHandler() { FMLCommonHandler.instance().bus().register(new ServerTickHandler()); } }
gpl-3.0
kuiwang/my-dev
src/main/java/com/aliyun/api/ess/ess20140828/response/DetachInstancesResponse.java
969
package com.aliyun.api.ess.ess20140828.response; import com.aliyun.api.AliyunResponse; import com.taobao.api.internal.mapping.ApiField; /** * TOP API: ess.aliyuncs.com.DetachInstances.2014-08-28 response. * * @author auto create * @since 1.0, null */ public class DetachInstancesResponse extends AliyunResponse { private static final long serialVersionUID = 3317111479582962569L; /** * 1 */ @ApiField("RequestId") private String requestId; /** * 伸缩活动id */ @ApiField("ScalingActivityId") private String scalingActivityId; public String getRequestId() { return this.requestId; } public String getScalingActivityId() { return this.scalingActivityId; } public void setRequestId(String requestId) { this.requestId = requestId; } public void setScalingActivityId(String scalingActivityId) { this.scalingActivityId = scalingActivityId; } }
gpl-3.0
MartyParty21/AwakenDreamsClient
mcp/src/minecraft/net/minecraft/client/gui/GuiCreateWorld.java
21756
package net.minecraft.client.gui; import java.io.IOException; import java.util.Random; import net.minecraft.client.resources.I18n; import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.world.GameType; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; import net.minecraft.world.storage.ISaveFormat; import net.minecraft.world.storage.WorldInfo; import org.apache.commons.lang3.StringUtils; import org.lwjgl.input.Keyboard; public class GuiCreateWorld extends GuiScreen { private final GuiScreen parentScreen; private GuiTextField worldNameField; private GuiTextField worldSeedField; private String saveDirName; private String gameMode = "survival"; /** * Used to save away the game mode when the current "debug" world type is chosen (forcing it to spectator mode) */ private String savedGameMode; private boolean generateStructuresEnabled = true; /** If cheats are allowed */ private boolean allowCheats; /** * User explicitly clicked "Allow Cheats" at some point * Prevents value changes due to changing game mode */ private boolean allowCheatsWasSetByUser; private boolean bonusChestEnabled; /** Set to true when "hardcore" is the currently-selected gamemode */ private boolean hardCoreMode; private boolean alreadyGenerated; private boolean inMoreWorldOptionsDisplay; private GuiButton btnGameMode; private GuiButton btnMoreOptions; private GuiButton btnMapFeatures; private GuiButton btnBonusItems; private GuiButton btnMapType; private GuiButton btnAllowCommands; private GuiButton btnCustomizeType; private String gameModeDesc1; private String gameModeDesc2; private String worldSeed; private String worldName; private int selectedIndex; public String chunkProviderSettingsJson = ""; /** These filenames are known to be restricted on one or more OS's. */ private static final String[] DISALLOWED_FILENAMES = new String[] {"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}; public GuiCreateWorld(GuiScreen p_i46320_1_) { this.parentScreen = p_i46320_1_; this.worldSeed = ""; this.worldName = I18n.format("selectWorld.newWorld", new Object[0]); } /** * Called from the main game loop to update the screen. */ public void updateScreen() { this.worldNameField.updateCursorCounter(); this.worldSeedField.updateCursorCounter(); } /** * Adds the buttons (and other controls) to the screen in question. Called when the GUI is displayed and when the * window resizes, the buttonList is cleared beforehand. */ public void initGui() { Keyboard.enableRepeatEvents(true); this.buttonList.clear(); this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, I18n.format("selectWorld.create", new Object[0]))); this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, I18n.format("gui.cancel", new Object[0]))); this.btnGameMode = this.func_189646_b(new GuiButton(2, this.width / 2 - 75, 115, 150, 20, I18n.format("selectWorld.gameMode", new Object[0]))); this.btnMoreOptions = this.func_189646_b(new GuiButton(3, this.width / 2 - 75, 187, 150, 20, I18n.format("selectWorld.moreWorldOptions", new Object[0]))); this.btnMapFeatures = this.func_189646_b(new GuiButton(4, this.width / 2 - 155, 100, 150, 20, I18n.format("selectWorld.mapFeatures", new Object[0]))); this.btnMapFeatures.visible = false; this.btnBonusItems = this.func_189646_b(new GuiButton(7, this.width / 2 + 5, 151, 150, 20, I18n.format("selectWorld.bonusItems", new Object[0]))); this.btnBonusItems.visible = false; this.btnMapType = this.func_189646_b(new GuiButton(5, this.width / 2 + 5, 100, 150, 20, I18n.format("selectWorld.mapType", new Object[0]))); this.btnMapType.visible = false; this.btnAllowCommands = this.func_189646_b(new GuiButton(6, this.width / 2 - 155, 151, 150, 20, I18n.format("selectWorld.allowCommands", new Object[0]))); this.btnAllowCommands.visible = false; this.btnCustomizeType = this.func_189646_b(new GuiButton(8, this.width / 2 + 5, 120, 150, 20, I18n.format("selectWorld.customizeType", new Object[0]))); this.btnCustomizeType.visible = false; this.worldNameField = new GuiTextField(9, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20); this.worldNameField.setFocused(true); this.worldNameField.setText(this.worldName); this.worldSeedField = new GuiTextField(10, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20); this.worldSeedField.setText(this.worldSeed); this.showMoreWorldOptions(this.inMoreWorldOptionsDisplay); this.calcSaveDirName(); this.updateDisplayState(); } /** * Determine a save-directory name from the world name */ private void calcSaveDirName() { this.saveDirName = this.worldNameField.getText().trim(); for (char c0 : ChatAllowedCharacters.ILLEGAL_FILE_CHARACTERS) { this.saveDirName = this.saveDirName.replace(c0, '_'); } if (StringUtils.isEmpty(this.saveDirName)) { this.saveDirName = "World"; } this.saveDirName = getUncollidingSaveDirName(this.mc.getSaveLoader(), this.saveDirName); } /** * Sets displayed GUI elements according to the current settings state */ private void updateDisplayState() { this.btnGameMode.displayString = I18n.format("selectWorld.gameMode", new Object[0]) + ": " + I18n.format("selectWorld.gameMode." + this.gameMode, new Object[0]); this.gameModeDesc1 = I18n.format("selectWorld.gameMode." + this.gameMode + ".line1", new Object[0]); this.gameModeDesc2 = I18n.format("selectWorld.gameMode." + this.gameMode + ".line2", new Object[0]); this.btnMapFeatures.displayString = I18n.format("selectWorld.mapFeatures", new Object[0]) + " "; if (this.generateStructuresEnabled) { this.btnMapFeatures.displayString = this.btnMapFeatures.displayString + I18n.format("options.on", new Object[0]); } else { this.btnMapFeatures.displayString = this.btnMapFeatures.displayString + I18n.format("options.off", new Object[0]); } this.btnBonusItems.displayString = I18n.format("selectWorld.bonusItems", new Object[0]) + " "; if (this.bonusChestEnabled && !this.hardCoreMode) { this.btnBonusItems.displayString = this.btnBonusItems.displayString + I18n.format("options.on", new Object[0]); } else { this.btnBonusItems.displayString = this.btnBonusItems.displayString + I18n.format("options.off", new Object[0]); } this.btnMapType.displayString = I18n.format("selectWorld.mapType", new Object[0]) + " " + I18n.format(WorldType.WORLD_TYPES[this.selectedIndex].getTranslateName(), new Object[0]); this.btnAllowCommands.displayString = I18n.format("selectWorld.allowCommands", new Object[0]) + " "; if (this.allowCheats && !this.hardCoreMode) { this.btnAllowCommands.displayString = this.btnAllowCommands.displayString + I18n.format("options.on", new Object[0]); } else { this.btnAllowCommands.displayString = this.btnAllowCommands.displayString + I18n.format("options.off", new Object[0]); } } /** * Ensures that a proposed directory name doesn't collide with existing names. * Returns the name, possibly modified to avoid collisions. */ public static String getUncollidingSaveDirName(ISaveFormat saveLoader, String name) { name = name.replaceAll("[\\./\"]", "_"); for (String s : DISALLOWED_FILENAMES) { if (name.equalsIgnoreCase(s)) { name = "_" + name + "_"; } } while (saveLoader.getWorldInfo(name) != null) { name = name + "-"; } return name; } /** * Called when the screen is unloaded. Used to disable keyboard repeat events */ public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } /** * Called by the controls from the buttonList when activated. (Mouse pressed for buttons) */ protected void actionPerformed(GuiButton button) throws IOException { if (button.enabled) { if (button.id == 1) { this.mc.displayGuiScreen(this.parentScreen); } else if (button.id == 0) { this.mc.displayGuiScreen((GuiScreen)null); if (this.alreadyGenerated) { return; } this.alreadyGenerated = true; long i = (new Random()).nextLong(); String s = this.worldSeedField.getText(); if (!StringUtils.isEmpty(s)) { try { long j = Long.parseLong(s); if (j != 0L) { i = j; } } catch (NumberFormatException var7) { i = (long)s.hashCode(); } } WorldSettings worldsettings = new WorldSettings(i, GameType.getByName(this.gameMode), this.generateStructuresEnabled, this.hardCoreMode, WorldType.WORLD_TYPES[this.selectedIndex]); worldsettings.setGeneratorOptions(this.chunkProviderSettingsJson); if (this.bonusChestEnabled && !this.hardCoreMode) { worldsettings.enableBonusChest(); } if (this.allowCheats && !this.hardCoreMode) { worldsettings.enableCommands(); } this.mc.launchIntegratedServer(this.saveDirName, this.worldNameField.getText().trim(), worldsettings); } else if (button.id == 3) { this.toggleMoreWorldOptions(); } else if (button.id == 2) { if ("survival".equals(this.gameMode)) { if (!this.allowCheatsWasSetByUser) { this.allowCheats = false; } this.hardCoreMode = false; this.gameMode = "hardcore"; this.hardCoreMode = true; this.btnAllowCommands.enabled = false; this.btnBonusItems.enabled = false; this.updateDisplayState(); } else if ("hardcore".equals(this.gameMode)) { if (!this.allowCheatsWasSetByUser) { this.allowCheats = true; } this.hardCoreMode = false; this.gameMode = "creative"; this.updateDisplayState(); this.hardCoreMode = false; this.btnAllowCommands.enabled = true; this.btnBonusItems.enabled = true; } else { if (!this.allowCheatsWasSetByUser) { this.allowCheats = false; } this.gameMode = "survival"; this.updateDisplayState(); this.btnAllowCommands.enabled = true; this.btnBonusItems.enabled = true; this.hardCoreMode = false; } this.updateDisplayState(); } else if (button.id == 4) { this.generateStructuresEnabled = !this.generateStructuresEnabled; this.updateDisplayState(); } else if (button.id == 7) { this.bonusChestEnabled = !this.bonusChestEnabled; this.updateDisplayState(); } else if (button.id == 5) { ++this.selectedIndex; if (this.selectedIndex >= WorldType.WORLD_TYPES.length) { this.selectedIndex = 0; } while (!this.canSelectCurWorldType()) { ++this.selectedIndex; if (this.selectedIndex >= WorldType.WORLD_TYPES.length) { this.selectedIndex = 0; } } this.chunkProviderSettingsJson = ""; this.updateDisplayState(); this.showMoreWorldOptions(this.inMoreWorldOptionsDisplay); } else if (button.id == 6) { this.allowCheatsWasSetByUser = true; this.allowCheats = !this.allowCheats; this.updateDisplayState(); } else if (button.id == 8) { if (WorldType.WORLD_TYPES[this.selectedIndex] == WorldType.FLAT) { this.mc.displayGuiScreen(new GuiCreateFlatWorld(this, this.chunkProviderSettingsJson)); } else { this.mc.displayGuiScreen(new GuiCustomizeWorldScreen(this, this.chunkProviderSettingsJson)); } } } } /** * Returns whether the currently-selected world type is actually acceptable for selection * Used to hide the "debug" world type unless the shift key is depressed. */ private boolean canSelectCurWorldType() { WorldType worldtype = WorldType.WORLD_TYPES[this.selectedIndex]; return worldtype != null && worldtype.getCanBeCreated() ? (worldtype == WorldType.DEBUG_WORLD ? isShiftKeyDown() : true) : false; } /** * Toggles between initial world-creation display, and "more options" display. * Called when user clicks "More World Options..." or "Done" (same button, different labels depending on current * display). */ private void toggleMoreWorldOptions() { this.showMoreWorldOptions(!this.inMoreWorldOptionsDisplay); } /** * Shows additional world-creation options if toggle is true, otherwise shows main world-creation elements */ private void showMoreWorldOptions(boolean toggle) { this.inMoreWorldOptionsDisplay = toggle; if (WorldType.WORLD_TYPES[this.selectedIndex] == WorldType.DEBUG_WORLD) { this.btnGameMode.visible = !this.inMoreWorldOptionsDisplay; this.btnGameMode.enabled = false; if (this.savedGameMode == null) { this.savedGameMode = this.gameMode; } this.gameMode = "spectator"; this.btnMapFeatures.visible = false; this.btnBonusItems.visible = false; this.btnMapType.visible = this.inMoreWorldOptionsDisplay; this.btnAllowCommands.visible = false; this.btnCustomizeType.visible = false; } else { this.btnGameMode.visible = !this.inMoreWorldOptionsDisplay; this.btnGameMode.enabled = true; if (this.savedGameMode != null) { this.gameMode = this.savedGameMode; this.savedGameMode = null; } this.btnMapFeatures.visible = this.inMoreWorldOptionsDisplay && WorldType.WORLD_TYPES[this.selectedIndex] != WorldType.CUSTOMIZED; this.btnBonusItems.visible = this.inMoreWorldOptionsDisplay; this.btnMapType.visible = this.inMoreWorldOptionsDisplay; this.btnAllowCommands.visible = this.inMoreWorldOptionsDisplay; this.btnCustomizeType.visible = this.inMoreWorldOptionsDisplay && (WorldType.WORLD_TYPES[this.selectedIndex] == WorldType.FLAT || WorldType.WORLD_TYPES[this.selectedIndex] == WorldType.CUSTOMIZED); } this.updateDisplayState(); if (this.inMoreWorldOptionsDisplay) { this.btnMoreOptions.displayString = I18n.format("gui.done", new Object[0]); } else { this.btnMoreOptions.displayString = I18n.format("selectWorld.moreWorldOptions", new Object[0]); } } /** * Fired when a key is typed (except F11 which toggles full screen). This is the equivalent of * KeyListener.keyTyped(KeyEvent e). Args : character (character on the key), keyCode (lwjgl Keyboard key code) */ protected void keyTyped(char typedChar, int keyCode) throws IOException { if (this.worldNameField.isFocused() && !this.inMoreWorldOptionsDisplay) { this.worldNameField.textboxKeyTyped(typedChar, keyCode); this.worldName = this.worldNameField.getText(); } else if (this.worldSeedField.isFocused() && this.inMoreWorldOptionsDisplay) { this.worldSeedField.textboxKeyTyped(typedChar, keyCode); this.worldSeed = this.worldSeedField.getText(); } if (keyCode == 28 || keyCode == 156) { this.actionPerformed((GuiButton)this.buttonList.get(0)); } ((GuiButton)this.buttonList.get(0)).enabled = !this.worldNameField.getText().isEmpty(); this.calcSaveDirName(); } /** * Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton */ protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { super.mouseClicked(mouseX, mouseY, mouseButton); if (this.inMoreWorldOptionsDisplay) { this.worldSeedField.mouseClicked(mouseX, mouseY, mouseButton); } else { this.worldNameField.mouseClicked(mouseX, mouseY, mouseButton); } } /** * Draws the screen and all the components in it. */ public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); this.drawCenteredString(this.fontRendererObj, I18n.format("selectWorld.create", new Object[0]), this.width / 2, 20, -1); if (this.inMoreWorldOptionsDisplay) { this.drawString(this.fontRendererObj, I18n.format("selectWorld.enterSeed", new Object[0]), this.width / 2 - 100, 47, -6250336); this.drawString(this.fontRendererObj, I18n.format("selectWorld.seedInfo", new Object[0]), this.width / 2 - 100, 85, -6250336); if (this.btnMapFeatures.visible) { this.drawString(this.fontRendererObj, I18n.format("selectWorld.mapFeatures.info", new Object[0]), this.width / 2 - 150, 122, -6250336); } if (this.btnAllowCommands.visible) { this.drawString(this.fontRendererObj, I18n.format("selectWorld.allowCommands.info", new Object[0]), this.width / 2 - 150, 172, -6250336); } this.worldSeedField.drawTextBox(); if (WorldType.WORLD_TYPES[this.selectedIndex].showWorldInfoNotice()) { this.fontRendererObj.drawSplitString(I18n.format(WorldType.WORLD_TYPES[this.selectedIndex].getTranslatedInfo(), new Object[0]), this.btnMapType.xPosition + 2, this.btnMapType.yPosition + 22, this.btnMapType.getButtonWidth(), 10526880); } } else { this.drawString(this.fontRendererObj, I18n.format("selectWorld.enterName", new Object[0]), this.width / 2 - 100, 47, -6250336); this.drawString(this.fontRendererObj, I18n.format("selectWorld.resultFolder", new Object[0]) + " " + this.saveDirName, this.width / 2 - 100, 85, -6250336); this.worldNameField.drawTextBox(); this.drawString(this.fontRendererObj, this.gameModeDesc1, this.width / 2 - 100, 137, -6250336); this.drawString(this.fontRendererObj, this.gameModeDesc2, this.width / 2 - 100, 149, -6250336); } super.drawScreen(mouseX, mouseY, partialTicks); } /** * Set the initial values of a new world to create, from the values from an existing world. * * Called after construction when a user selects the "Recreate" button. */ public void recreateFromExistingWorld(WorldInfo original) { this.worldName = I18n.format("selectWorld.newWorld.copyOf", new Object[] {original.getWorldName()}); this.worldSeed = original.getSeed() + ""; this.selectedIndex = original.getTerrainType().getWorldTypeID(); this.chunkProviderSettingsJson = original.getGeneratorOptions(); this.generateStructuresEnabled = original.isMapFeaturesEnabled(); this.allowCheats = original.areCommandsAllowed(); if (original.isHardcoreModeEnabled()) { this.gameMode = "hardcore"; } else if (original.getGameType().isSurvivalOrAdventure()) { this.gameMode = "survival"; } else if (original.getGameType().isCreative()) { this.gameMode = "creative"; } } }
gpl-3.0
xminds/cognitowrapper
src/main/java/com/xminds/aws/cognito/CognitoIdentityProviderClientConfig.java
1333
package com.xminds.aws.cognito; /** * Maintains SDK configuration. */ public final class CognitoIdentityProviderClientConfig { /** * Maximum threshold for refresh tokens, in milli seconds. */ private static long REFRESH_THRESHOLD_MAX = 1800 * 1000; /** * Minimum threshold for refresh tokens, in milli seconds. */ private static long REFRESH_THRESHOLD_MIN = 0; /** * Threshold for refresh tokens, in milli seconds. * Tokens are refreshed if the session is valid for less than this value. */ private static long refreshThreshold = 300 * 1000; /** * Set the threshold for token refresh. * * @param threshold REQUIRED: Threshold for token refresh in milli seconds. * @throws CognitoParameterInvalidException */ public static void setRefreshThreshold(long threshold) throws CognitoParameterInvalidException { if (threshold > REFRESH_THRESHOLD_MAX || threshold < REFRESH_THRESHOLD_MIN) { throw new CognitoParameterInvalidException(String.format("The value of refreshThreshold must between %d and %d seconds", REFRESH_THRESHOLD_MIN, REFRESH_THRESHOLD_MAX)); } refreshThreshold = threshold; } public static long getRefreshThreshold() { return refreshThreshold; } }
gpl-3.0
ZsoltToth/ilona-positioning
web/src/main/java/uni/miskolc/ips/ilona/positioning/web/IlonaPositioningApplicationContext.java
5114
package uni.miskolc.ips.ilona.positioning.web; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import uni.miskolc.ips.ilona.measurement.model.measurement.MeasurementDistanceCalculator; import uni.miskolc.ips.ilona.measurement.model.measurement.MeasurementDistanceCalculatorImpl; import uni.miskolc.ips.ilona.measurement.model.measurement.wifi.VectorIntersectionWiFiRSSIDistance; import uni.miskolc.ips.ilona.positioning.service.PositioningService; import uni.miskolc.ips.ilona.positioning.service.gateway.MeasurementGateway; import uni.miskolc.ips.ilona.positioning.service.gateway.MeasurementGatewaySIConfig; import uni.miskolc.ips.ilona.positioning.service.impl.classification.bayes.NaiveBayesPositioningService; import uni.miskolc.ips.ilona.positioning.service.impl.knn.KNNPositioning; import uni.miskolc.ips.ilona.positioning.service.impl.knn.KNNSimplePositioning; import uni.miskolc.ips.ilona.positioning.service.impl.knn.KNNWeightedPositioning; @Configuration @EnableWebMvc @ComponentScan(basePackages = "uni.miskolc.ips.ilona.positioning.controller") public class IlonaPositioningApplicationContext extends WebMvcConfigurerAdapter { @Bean public VectorIntersectionWiFiRSSIDistance wifiDistanceCalculator() { return new VectorIntersectionWiFiRSSIDistance(); } @Bean public MeasurementDistanceCalculator measurementDistanceCalculator() { //TODO double wifiDistanceWeight = 1.0; double magnetometerDistanceWeight = 0.5; double gpsDistanceWeight = 0.0; double bluetoothDistanceWeight = 1.0; double rfidDistanceWeight = 0.0; return new MeasurementDistanceCalculatorImpl(wifiDistanceCalculator(), wifiDistanceWeight, magnetometerDistanceWeight, gpsDistanceWeight, bluetoothDistanceWeight, rfidDistanceWeight); } @Bean public KNNPositioning positioningService() { //TODO MeasurementDistanceCalculator distanceCalculator = measurementDistanceCalculator(); ApplicationContext context = new AnnotationConfigApplicationContext(MeasurementGatewaySIConfig.class); MeasurementGateway measurementGateway = context.getBean("MeasurementQueryGateway", MeasurementGateway.class); int k = 3; return new KNNSimplePositioning(distanceCalculator, measurementGateway, k); } @Bean public KNNPositioning knnpositioningService() { //TODO /* MeasurementDistanceCalculator distanceCalculator = measurementDistanceCalculator(); MeasurementGateway measurementGateway = null; int k = 3; return new KNNSimplePositioning(distanceCalculator, measurementGateway, k); */ return positioningService(); } @Bean public KNNPositioning knnWpositioningService() { //TODO MeasurementDistanceCalculator distanceCalculator = measurementDistanceCalculator(); ApplicationContext context = new AnnotationConfigApplicationContext(MeasurementGatewaySIConfig.class); MeasurementGateway measurementGateway = context.getBean("MeasurementQueryGateway", MeasurementGateway.class); int k = 3; return new KNNWeightedPositioning(distanceCalculator, measurementGateway, k); } @Bean public PositioningService naivebayespositioningService() { //TODO int maxMeasurementDistance = 50; ApplicationContext context = new AnnotationConfigApplicationContext(MeasurementGatewaySIConfig.class); MeasurementGateway measurementGateway = context.getBean("MeasurementQueryGateway", MeasurementGateway.class); MeasurementDistanceCalculator measDistanceCalculator = measurementDistanceCalculator(); return new NaiveBayesPositioningService(measurementGateway, measDistanceCalculator, maxMeasurementDistance); } @Bean public InternalResourceViewResolver jspViewResolver() { InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setPrefix("/WEB-INF/views/"); bean.setSuffix(".jsp"); return bean; } @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/img/**").addResourceLocations("/img/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); registry.addResourceHandler("/fonts/**").addResourceLocations("/fonts/"); } }
gpl-3.0
pantelis60/L2Scripts_Underground
authserver/src/main/java/l2s/authserver/network/l2/L2LoginClient.java
5175
/* * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2, or (at your option) any later version. This * program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ package l2s.authserver.network.l2; import java.io.IOException; import java.nio.ByteBuffer; import java.security.interfaces.RSAPrivateKey; import l2s.authserver.Config; import l2s.authserver.accounts.Account; import l2s.authserver.crypt.LoginCrypt; import l2s.authserver.crypt.ScrambledKeyPair; import l2s.authserver.network.l2.s2c.AccountKicked; import l2s.authserver.network.l2.s2c.AccountKicked.AccountKickedReason; import l2s.authserver.network.l2.s2c.L2LoginServerPacket; import l2s.authserver.network.l2.s2c.LoginFail; import l2s.authserver.network.l2.s2c.LoginFail.LoginFailReason; import l2s.commons.net.nio.impl.MMOClient; import l2s.commons.net.nio.impl.MMOConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class L2LoginClient extends MMOClient<MMOConnection<L2LoginClient>> { private final static Logger _log = LoggerFactory.getLogger(L2LoginClient.class); public static enum LoginClientState { CONNECTED, AUTHED_GG, AUTHED, DISCONNECTED } private static final int PROTOCOL_VERSION = 0xc621; private LoginClientState _state; private LoginCrypt _loginCrypt; private ScrambledKeyPair _scrambledPair; private byte[] _blowfishKey; private String _login; private SessionKey _skey; private Account _account; private String _ipAddr; private int _sessionId; private boolean _passwordCorrect; public L2LoginClient(MMOConnection<L2LoginClient> con) { super(con); _state = LoginClientState.CONNECTED; _scrambledPair = Config.getScrambledRSAKeyPair(); _blowfishKey = Config.getBlowfishKey(); _loginCrypt = new LoginCrypt(); _loginCrypt.setKey(_blowfishKey); _sessionId = con.hashCode(); _ipAddr = getConnection().getSocket().getInetAddress().getHostAddress(); _passwordCorrect = false; } @Override public boolean decrypt(ByteBuffer buf, int size) { boolean ret; try { ret = _loginCrypt.decrypt(buf.array(), buf.position(), size); } catch(IOException e) { _log.error("", e); closeNow(true); return false; } if(!ret) closeNow(true); return ret; } @Override public boolean encrypt(ByteBuffer buf, int size) { final int offset = buf.position(); try { size = _loginCrypt.encrypt(buf.array(), offset, size); } catch(IOException e) { _log.error("", e); return false; } buf.position(offset + size); return true; } public LoginClientState getState() { return _state; } public void setState(LoginClientState state) { _state = state; } public byte[] getBlowfishKey() { return _blowfishKey; } public byte[] getScrambledModulus() { return _scrambledPair.getScrambledModulus(); } public RSAPrivateKey getRSAPrivateKey() { return (RSAPrivateKey) _scrambledPair.getKeyPair().getPrivate(); } public String getLogin() { return _login; } public void setLogin(String login) { _login = login; } public Account getAccount() { return _account; } public void setAccount(Account account) { _account = account; } public SessionKey getSessionKey() { return _skey; } public void setSessionKey(SessionKey skey) { _skey = skey; } public void setSessionId(int val) { _sessionId = val; } public int getSessionId() { return _sessionId; } public void setPasswordCorrect(boolean val) { _passwordCorrect = val; } public boolean isPasswordCorrect() { return _passwordCorrect; } public void sendPacket(L2LoginServerPacket lsp) { if(isConnected()) getConnection().sendPacket(lsp); } public void close(LoginFailReason reason) { if(isConnected()) getConnection().close(new LoginFail(reason)); } public void close(AccountKickedReason reason) { if(isConnected()) getConnection().close(new AccountKicked(reason)); } public void close(L2LoginServerPacket lsp) { if(isConnected()) getConnection().close(lsp); } @Override public void onDisconnection() { _state = LoginClientState.DISCONNECTED; _skey = null; _loginCrypt = null; _scrambledPair = null; _blowfishKey = null; } @Override public String toString() { switch(_state) { case AUTHED: return "[ Account : " + getLogin() + " IP: " + getIpAddress() + "]"; default: return "[ State : " + getState() + " IP: " + getIpAddress() + "]"; } } public String getIpAddress() { return _ipAddr; } @Override protected void onForcedDisconnection() { } public int getProtocol() { return PROTOCOL_VERSION; } }
gpl-3.0
shovonis/bookworm
application/book-worm/src/main/java/net/therap/controller/NotificationController.java
2867
package net.therap.controller; import net.therap.domain.Notification; import net.therap.domain.User; import net.therap.service.NotificationService; import net.therap.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpSession; import java.util.List; /** * @author rifatul.islam * @since 8/12/14. */ @Controller public class NotificationController { @Autowired private NotificationService notificationService; @Autowired private UserService userService; @RequestMapping(value = "/notification/{receiverId}", method = RequestMethod.GET) public ModelAndView showAllNotification(@PathVariable int receiverId) { List<Notification> notificationList = notificationService.getAllNotification(receiverId); ModelAndView modelAndView = new ModelAndView("user/notification"); modelAndView.addObject("notificationList", notificationList); return modelAndView; } @RequestMapping("/getSenderImage/{userId}") @ResponseBody public byte[] getProfilePicture(@PathVariable int userId) { User user = userService.getUserById(userId); return user.getProfilePicture(); } @RequestMapping(value = "/sendNotification", method = RequestMethod.POST) @ResponseBody public void sendNotification(@RequestParam("receiverId") int receiverId, @RequestParam("bookId") int bookId , @RequestParam("type") int type, @RequestParam("isSeen") boolean isSeen, HttpSession session) { User user = (User) session.getAttribute("user"); notificationService.addNewNotification(user.getUserId(), receiverId, bookId, type, isSeen); } @RequestMapping(value = "/updateNotification", method = RequestMethod.POST) @ResponseBody public void updateNotification(@RequestParam("id") int notificationId, @RequestParam("receiverId") int receiverId, @RequestParam("bookId") int bookId, @RequestParam("type") int type, @RequestParam("isSeen") boolean isSeen, HttpSession session) { User user = (User) session.getAttribute("user"); notificationService.updateAndInsertNotification(notificationId, user.getUserId(), receiverId, bookId, type, isSeen); } @RequestMapping(value = "/notification/getNotificationCounter", method = RequestMethod.GET) @ResponseBody public long getNotificationCounter(HttpSession session) { User user = (User) session.getAttribute("user"); long total = notificationService.getUnseenNotification(user.getUserId()); System.out.println("total = " + total); return total; } }
gpl-3.0
oapa/timely
CalendarSync/src/com/sigmasq/timely/solver/CloudComputer.java
431
package com.sigmasq.timely.solver; public class CloudComputer { private int cpuPower; private int memory; private int networkBandwidth; private int cost; public int getCpuPower() { return cpuPower; } public int getMemory() { return memory; } public int getNetworkBandwidth() { return networkBandwidth; } public int getCost() { return cost; } }
gpl-3.0
k0shk0sh/FastHub
app/src/main/java/com/fastaccess/data/dao/types/IssueState.java
374
package com.fastaccess.data.dao.types; import androidx.annotation.StringRes; import com.fastaccess.R; public enum IssueState { open(R.string.opened), closed(R.string.closed), all(R.string.all); int status; IssueState(@StringRes int status) { this.status = status; } @StringRes public int getStatus() { return status; } }
gpl-3.0
houtekamert/Testmod
src/main/java/com/houtekamert/testmod1/item/ItemTM1.java
1334
package com.houtekamert.testmod1.item; import com.houtekamert.testmod1.creativetab.CreativeTabTM1; import com.houtekamert.testmod1.reference.Reference; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public class ItemTM1 extends Item { public ItemTM1() { super(); this.setCreativeTab(CreativeTabTM1.TMI_TAB); } @Override public String getUnlocalizedName() { return String.format("item.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override public String getUnlocalizedName(ItemStack itemStack) { return String.format("item.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconRegister) { itemIcon = iconRegister.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".") + 1)); } protected String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } }
gpl-3.0
qt-haiku/LibreOffice
odk/examples/java/Inspector/UnoTreeRenderer.java
5903
/************************************************************************* * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright 2000, 2010 Oracle and/or its affiliates. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ import java.awt.Component; import java.awt.FontMetrics; import java.awt.Graphics; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; public class UnoTreeRenderer extends DefaultTreeCellRenderer{ private Icon m_oMethodIcon; private Icon m_oPropertyIcon; private Icon m_oContainerIcon; private Icon m_oContentIcon; private Icon m_oServiceIcon; private Icon m_oInterfaceIcon; private Icon m_oPropertyValueIcon; private boolean bSelected; private int nWidth = 0; /** Creates a new instance of UnoTreeRenderer */ public UnoTreeRenderer(){ super(); try { final ClassLoader loader = ClassLoader.getSystemClassLoader(); m_oMethodIcon = new ImageIcon(loader.getResource("images/methods_16.png")); m_oPropertyIcon = new ImageIcon("images/properties_16.png"); m_oPropertyValueIcon = new ImageIcon("images/properties_16.png"); m_oContainerIcon = new ImageIcon("images/containers_16.png"); m_oServiceIcon = new ImageIcon("images/services_16.png"); m_oInterfaceIcon = new ImageIcon("images/interfaces_16.png"); m_oContentIcon = new ImageIcon("images/content_16.png"); } catch (RuntimeException e) { System.out.println("Sorry, could not locate resourecs, treecell icons will not be displayed."); } } public synchronized Component getTreeCellRendererComponent(JTree tree,Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus){ try{ bSelected = sel; DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Component rc = super.getTreeCellRendererComponent( tree, value, sel,expanded, leaf, row,hasFocus); String sLabelText = (String)node.getUserObject(); if (sLabelText != null){ if (sLabelText.equals(XUnoFacetteNode.SCONTAINERDESCRIPTION)){ // setIcon(m_oContainerIcon); } else if (sLabelText.equals(XUnoFacetteNode.SCONTENTDESCRIPTION)){ // setIcon(m_oContentIcon); } else if (sLabelText.equals(XUnoFacetteNode.SINTERFACEDESCRIPTION)){ // setIcon(m_oInterfaceIcon); } else if (sLabelText.equals(XUnoFacetteNode.SMETHODDESCRIPTION)){ // setIcon(m_oMethodIcon); } else if (sLabelText.equals(XUnoFacetteNode.SPROPERTYDESCRIPTION)){ // setIcon(m_oPropertyIcon); } else if (sLabelText.startsWith(XUnoFacetteNode.SPROPERTYINFODESCRIPTION)){ // setIcon(m_oPropertyIcon); } else if (sLabelText.equals(XUnoFacetteNode.SPROPERTYVALUEDESCRIPTION)){ // setIcon(m_oPropertyValueIcon); } else if (sLabelText.equals(XUnoFacetteNode.SSERVICEDESCRIPTION)){ // setIcon(m_oServiceIcon); } else{ setText(sLabelText); rc.validate(); } setSize(getPreferredSize()); //fm.stringWidth(sLabelText), (int) getSize().getHeight()); rc.validate(); // nWidth = (int) rc.getPreferredSize().getWidth(); doLayout(); } } catch (RuntimeException e) { System.out.println("Sorry, icon for treecell could not be displayed."); } return this; } public void paintComponent(Graphics g) { FontMetrics fm = getFontMetrics(getFont()); int x, y; y = fm.getAscent() + 2; if(getIcon() == null) { x = 0; } else { x = getIcon().getIconWidth() + getIconTextGap(); } g.setColor(getForeground()); // g.fillRect(x,y,x + fm.stringWidth(getText()),y); // System.out.println("Text: " + getText()); super.paintComponent(g); } }
gpl-3.0
salcedonia/acide-0-8-release-2010-2011
acide/antlr/TreeBlockContext.java
1263
package antlr; /* ANTLR Translator Generator * Project led by Terence Parr at http://www.cs.usfca.edu * Software rights: http://www.antlr.org/license.html * * $Id: //depot/code/org.antlr/release/antlr-2.7.7/antlr/TreeBlockContext.java#2 $ */ /**The context needed to add root,child elements to a Tree. There * is only one alternative (i.e., a list of children). We subclass to * specialize. MakeGrammar.addElementToCurrentAlt will work correctly * now for either a block of alts or a Tree child list. * * The first time addAlternativeElement is called, it sets the root element * rather than adding it to one of the alternative lists. Rather than have * the grammar duplicate the rules for grammar atoms etc... we use the same * grammar and same refToken behavior etc... We have to special case somewhere * and here is where we do it. */ class TreeBlockContext extends BlockContext { protected boolean nextElementIsRoot = true; public void addAlternativeElement(AlternativeElement e) { TreeElement tree = (TreeElement)block; if (nextElementIsRoot) { tree.root = (GrammarAtom)e; nextElementIsRoot = false; } else { super.addAlternativeElement(e); } } }
gpl-3.0
SamuelGjk/DiyCode
app/src/main/java/moe/yukinoneko/diycode/module/about/AboutActivity.java
1987
/* * Copyright (c) 2017 SamuelGjk <samuel.alva@outlook.com> * * This file is part of DiyCode * * DiyCode 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. * * DiyCode 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 DiyCode. If not, see <http://www.gnu.org/licenses/>. */ package moe.yukinoneko.diycode.module.about; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.AppCompatTextView; import android.webkit.WebView; import java.util.Locale; import butterknife.BindView; import butterknife.OnClick; import moe.yukinoneko.diycode.R; import moe.yukinoneko.diycode.base.BaseActivity; import moe.yukinoneko.diycode.tool.Tools; /** * MVPPlugin * 邮箱 784787081@qq.com */ public class AboutActivity extends BaseActivity { @BindView(R.id.text_app_version) AppCompatTextView textAppVersion; @Override protected int provideContentViewId() { return R.layout.activity_about; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); textAppVersion.setText(String.format(Locale.getDefault(), "Version %s", Tools.getVersionName(this))); } @OnClick(R.id.card_open_source_licenses) public void onViewClicked() { WebView v = new WebView(this); v.loadUrl("file:///android_asset/licenses.html"); new AlertDialog.Builder(this) .setView(v) .setNegativeButton(R.string.close, null) .show(); } }
gpl-3.0
heig-iict-ida/ardrone_gesture
src/madsdf/ardrone/controller/neuralnet/MeanDifferenceMedianMovement.java
4036
package madsdf.ardrone.controller.neuralnet; import com.google.common.eventbus.EventBus; import java.util.Arrays; import java.util.LinkedList; import java.util.ListIterator; import madsdf.shimmer.gui.AccelGyro; /** * Movement model implementing the abstract MovementModel and implementing the * processFeatures methods with only three features. This movement model * is a specific implementation for the networks which need only the mean, * difference and median features. * * Java version : JDK 1.6.0_21 * IDE : Netbeans 7.1.1 * * @author Gregoire Aubert * @version 1.0 */ public class MeanDifferenceMedianMovement extends MovementModel { // Number of line and number of features private final static int NB_FEATURES = 3; private final static int NB_LINES = 6; // Constants for the normalization private static final float COL_MAX = 4100; private static final float COL_MIN = 0; private static final float NORM_MAX = 0.95f; private static final float NORM_MIN = -0.95f; public MeanDifferenceMedianMovement(EventBus ebus, int[] windowSize, int[] movementSize){ super(ebus, windowSize, movementSize); } /** * Process all the three feature, normalize them and return them. * @param iterator the iterator used to process the features */ @Override protected float[] processFeatures(AccelGyro.UncalibratedSample[] window) { // Verify the feature array float[] features = new float[NB_FEATURES * NB_LINES]; // Copy all the sample values LinkedList<Float>[] sampleCopy = new LinkedList[NB_LINES]; for(int i = 0; i < sampleCopy.length; i++) sampleCopy[i] = new LinkedList<Float>(); // Initialisation of the features array AccelGyro.UncalibratedSample sample = window[0]; // The maximum values float[] maxValue = new float[NB_LINES]; // The minimum values float[] minValue = new float[NB_LINES]; // For each value of the first AccelGyroSample, initialise the features for(int i = 0; i < NB_LINES; i++){ // Copy the sample sampleCopy[i].add((float)getVal(sample, i+1)); // Initialize the mean, min and max features[NB_FEATURES * i] = getVal(sample, i+1); minValue[i] = getVal(sample, i+1); maxValue[i] = getVal(sample, i+1); } // For each sample for (int j = 1; j < window.length; ++j) { sample = window[j]; // For each value of the AccelGyroSample for(int i = 0; i < NB_LINES; i++){ // Copy sampleCopy[i].add((float)getVal(sample, i+1)); // Mean features[NB_FEATURES * i] += getVal(sample, i+1); // Min minValue[i] = Math.min(getVal(sample, i+1), minValue[i]); // Max maxValue[i] = Math.max(getVal(sample, i+1), maxValue[i]); } } // For each value of the AccelGyroSample, process the remaining features for(int i = 0; i < NB_LINES; i++){ // Mean features[NB_FEATURES * i] /= sampleCopy[i].size(); // Difference features[1+NB_FEATURES * i] = maxValue[i] - minValue[i]; // Median Float[] med = sampleCopy[i].toArray(new Float[0]); Arrays.sort(med); if(med.length % 2 == 0) features[2+NB_FEATURES * i] = (med[med.length / 2] + med[med.length / 2 + 1]) / 2.f; else features[2+NB_FEATURES * i] = med[med.length / 2 + 1]; } // Normalize the features for(int i = 0; i < features.length; i++) features[i] = (NORM_MAX - NORM_MIN) * ((features[i] - COL_MIN) / (COL_MAX - COL_MIN)) + NORM_MIN; return features; } }
gpl-3.0
lisiyuan656/dieta
src/Dieta/app/src/main/java/edu/osu/cse5236/group9/dieta/DetailedResultsActivity.java
4468
package edu.osu.cse5236.group9.dieta; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.View; import android.widget.TextView; public class DetailedResultsActivity extends FragmentActivity implements View.OnClickListener{ private static final String ACTIVITYNAME = "DetailedResultsActivity"; private Meal mMeal; private int currentIndex; private int mealSize; private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(ACTIVITYNAME, "onCreate(Bundle) called"); setContentView(R.layout.activity_detailed_results); // TODO: get meal from prior class mMeal=getIntent().getParcelableExtra("mMeal"); mealSize=mMeal.getFoods().size(); if(savedInstanceState!=null) { currentIndex = savedInstanceState.getInt("curIndex"); } else { currentIndex=0; } ResultsFragment resultsFragment= new ResultsFragment(); if (mealSize > 0) { resultsFragment.passFood(mMeal.getFoods().get(currentIndex)); } FragmentManager fragmentManager=getSupportFragmentManager(); FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.detailedresults_nfacts,resultsFragment); fragmentTransaction.commit(); View buttonLeft=findViewById(R.id.detailedresults_left); View buttonRight=findViewById(R.id.detailedresults_right); View buttonFinish=findViewById(R.id.detailedresults_finish); mTextView=(TextView) findViewById(R.id.textView_foodname); buttonLeft.setOnClickListener(this); buttonRight.setOnClickListener(this); buttonFinish.setOnClickListener(this); if (mealSize>0) { mTextView.setText(mMeal.getFoods().get(currentIndex).getName()); } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putInt("curIndex",currentIndex); } public void onClick(View v) { switch (v.getId()) { case R.id.detailedresults_left: if (currentIndex>0) { currentIndex--; if(getSupportFragmentManager().findFragmentById(R.id.detailedresults_nfacts) != null) { ResultsFragment resultsFragment= new ResultsFragment(); resultsFragment.passFood(mMeal.getFoods().get(currentIndex)); mTextView.setText(mMeal.getFoods().get(currentIndex).getName()); getSupportFragmentManager().beginTransaction().replace(R.id.detailedresults_nfacts,resultsFragment).commit(); } } break; case R.id.detailedresults_right: if (currentIndex<mealSize-1) { currentIndex++; if(getSupportFragmentManager().findFragmentById(R.id.detailedresults_nfacts) != null) { ResultsFragment resultsFragment= new ResultsFragment(); resultsFragment.passFood(mMeal.getFoods().get(currentIndex)); mTextView.setText(mMeal.getFoods().get(currentIndex).getName()); getSupportFragmentManager().beginTransaction().replace(R.id.detailedresults_nfacts,resultsFragment).commit(); } } break; case R.id.detailedresults_finish: startActivity(new Intent(this,NewFoodActivity.class)); break; } } @Override public void onStart() { super.onStart(); Log.d(ACTIVITYNAME, "onStart() called"); } @Override public void onPause() { super.onPause(); Log.d(ACTIVITYNAME, "onPause() called"); } @Override public void onResume() { super.onResume(); Log.d(ACTIVITYNAME, "onResume() called"); } @Override public void onStop() { super.onStop(); Log.d(ACTIVITYNAME, "onStop() called"); } @Override public void onDestroy() { super.onDestroy(); Log.d(ACTIVITYNAME, "onDestroy() called"); } }
gpl-3.0
WebArchivCZ/webanalyzer
src/cz/webarchiv/webanalyzer/dictionary/Word.java
800
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cz.webarchiv.webanalyzer.dictionary; /** * * @author praso */ class Word implements java.lang.Comparable<Word> { private String word; public String getWord() { return word; } public void setWord(String word) { this.word = word; } @Override public boolean equals(Object o) { if (o instanceof Word) { Word w = (Word) o; return getWord().equals(w.getWord()); } else { return false; } } @Override public int hashCode() { return this.getWord().hashCode(); } public int compareTo(Word o) { return this.word.compareTo(o.getWord()); } }
gpl-3.0
arksu/origin
server/src/com/a4server/gameserver/network/packets/clientpackets/InventoryClick.java
5303
package com.a4server.gameserver.network.packets.clientpackets; import com.a4server.gameserver.model.GameLock; import com.a4server.gameserver.model.GameObject; import com.a4server.gameserver.model.Hand; import com.a4server.gameserver.model.Player; import com.a4server.gameserver.model.inventory.AbstractItem; import com.a4server.gameserver.model.inventory.Inventory; import com.a4server.gameserver.model.inventory.InventoryItem; import com.a4server.gameserver.network.packets.serverpackets.InventoryUpdate; import com.a4server.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.a4server.gameserver.model.GameObject.WAIT_LOCK; /** * клик по объекту в инвентаре * Created by arksu on 26.02.15. */ public class InventoryClick extends GameClientPacket { private static final Logger _log = LoggerFactory.getLogger(InventoryClick.class.getName()); private int _inventoryId; private int _objectId; private int _btn; private int _mod; /** * отступ в пикселах внутри вещи где произошел клик */ private int _offsetX; private int _offsetY; /** * слот в который тыкнули */ private int _x; private int _y; @Override public void readImpl() { _inventoryId = readD(); _objectId = readD(); _btn = readC(); _mod = readC(); _offsetX = readC(); _offsetY = readC(); _x = readC(); _y = readC(); } @Override public void run() { _log.debug("obj=" + _objectId + " inv=" + _inventoryId + " (" + _x + ", " + _y + ")" + " offset=" + _offsetX + ", " + _offsetY + " mod=" + _mod); Player player = client.getPlayer(); if (player != null && _btn == 0) { try (GameLock ignored = player.lock()) { // держим в руке что-то? if (player.getHand() == null) { // в руке ничего нет. возьмем из инвентаря InventoryItem item = null; if (player.getInventory() != null) { item = player.getInventory().findItem(_objectId); } // не нашли эту вещь у себя в инвентаре // попробуем найти в объекте с которым взаимодействуем if (item == null && player.isInteractive()) { for (GameObject object : player.getInteractWith()) { item = object.getInventory() != null ? object.getInventory().findItem(_objectId) : null; if (item != null) { break; } } } // пробуем взять вещь из инвентаря if (item != null) { GameObject object = item.getParentInventory().getObject(); try (GameLock ignored2 = object.lock()) { InventoryItem taked = item.getParentInventory().takeItem(item); // взяли вещь из инвентаря if (taked != null) { object.sendInteractPacket(new InventoryUpdate(item.getParentInventory())); // какая кнопка была зажата switch (_mod) { case Utils.MOD_ALT: // сразу перекинем вещь в инвентарь if (!putItem(player, taked, -1, -1)) { setHand(player, taked); } break; default: // ничего не нажато. пихаем в руку setHand(player, taked); break; } } } } else { // возможно какой-то баг или ошибка. привлечем внимание _log.error("InventoryClick: item=null"); } } else { // положим в инвентарь то что держим в руке Hand hand = player.getHand(); if (putItem(player, hand.getItem(), _x - hand.getOffsetX(), _y - hand.getOffsetY())) { player.setHand(null); } } } } } /** * положить вещь в инвентарь * @param item вещь которую кладем */ public boolean putItem(Player player, AbstractItem item, int x, int y) { Inventory to = null; // ищем нужный инвентарь у себя if (player.getInventory() != null) { to = player.getInventory().findInventory(_inventoryId); } // а потом в объектах с которыми взаимодействую if (to == null && player.isInteractive()) { for (GameObject object : player.getInteractWith()) { to = object.getInventory() != null ? object.getInventory().findInventory(_inventoryId) : null; if (to != null) { break; } } } // положим в инвентарь if (to != null) { if (to.getObject().tryLock(WAIT_LOCK)) { try { InventoryItem putItem = to.putItem(item, x, y); if (putItem != null) { to.getObject().sendInteractPacket(new InventoryUpdate(to)); return true; } } finally { to.getObject().unlock(); } } } return false; } private void setHand(Player player, InventoryItem taked) { player.setHand(new Hand(player, taked, _x - taked.getX(), _y - taked.getY(), _offsetX, _offsetY )); } }
gpl-3.0
cuongtlv/Science24-7
app/src/main/java/com/a7av/news24h/MyApplication.java
483
package com.a7av.news24h; import android.app.Application; import android.content.Context; import android.support.multidex.MultiDex; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; /** * MultiDex configuration */ public class MyApplication extends Application { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } }
gpl-3.0
openflexo-team/gina
gina-api/src/main/java/org/openflexo/gina/model/widget/FIBTableAction.java
8774
/** * * Copyright (c) 2013-2014, Openflexo * Copyright (c) 2011-2012, AgileBirds * * This file is part of Gina-core, a component of the software infrastructure * developed at Openflexo. * * * Openflexo is dual-licensed under the European Union Public License (EUPL, either * version 1.1 of the License, or any later version ), which is available at * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * and the GNU General Public License (GPL, either version 3 of the License, or any * later version), which is available at http://www.gnu.org/licenses/gpl.html . * * You can redistribute it and/or modify under the terms of either of these licenses * * If you choose to redistribute it and/or modify under the terms of the GNU GPL, you * must include the following additional permission. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with software containing parts covered by the terms * of EPL 1.0, the licensors of this Program grant you additional permission * to convey the resulting work. * * * This software is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. * * See http://www.openflexo.org/license.html for details. * * * Please contact Openflexo (openflexo-contacts@openflexo.org) * or visit www.openflexo.org if you need additional information. * */ package org.openflexo.gina.model.widget; import java.util.logging.Logger; import org.openflexo.connie.BindingModel; import org.openflexo.connie.DataBinding; import org.openflexo.gina.model.FIBComponent.LocalizationEntryRetriever; import org.openflexo.gina.model.FIBModelObject; import org.openflexo.pamela.annotations.CloningStrategy; import org.openflexo.pamela.annotations.CloningStrategy.StrategyType; import org.openflexo.pamela.annotations.DefineValidationRule; import org.openflexo.pamela.annotations.DeserializationFinalizer; import org.openflexo.pamela.annotations.Getter; import org.openflexo.pamela.annotations.ImplementationClass; import org.openflexo.pamela.annotations.Import; import org.openflexo.pamela.annotations.Imports; import org.openflexo.pamela.annotations.ModelEntity; import org.openflexo.pamela.annotations.PropertyIdentifier; import org.openflexo.pamela.annotations.Setter; import org.openflexo.pamela.annotations.XMLAttribute; import org.openflexo.pamela.annotations.XMLElement; @ModelEntity(isAbstract = true) @ImplementationClass(FIBTableAction.FIBTableActionImpl.class) @Imports({ @Import(FIBTableAction.FIBAddAction.class), @Import(FIBTableAction.FIBRemoveAction.class), @Import(FIBTableAction.FIBCustomAction.class) }) public abstract interface FIBTableAction extends FIBModelObject { public static enum ActionType { Add, Delete, Custom } @PropertyIdentifier(type = FIBTable.class) public static final String OWNER_KEY = "owner"; @PropertyIdentifier(type = DataBinding.class) public static final String METHOD_KEY = "method"; @PropertyIdentifier(type = DataBinding.class) public static final String IS_AVAILABLE_KEY = "isAvailable"; @PropertyIdentifier(type = Boolean.class) public static final String ALLOWS_BATCH_EXECUTION_KEY = "allowsBatchExecution"; @Getter(value = OWNER_KEY /*, inverse = FIBTable.ACTIONS_KEY*/) @CloningStrategy(StrategyType.IGNORE) public FIBTable getOwner(); @Setter(OWNER_KEY) public void setOwner(FIBTable table); @Getter(value = METHOD_KEY) @XMLAttribute public DataBinding<Object> getMethod(); @Setter(METHOD_KEY) public void setMethod(DataBinding<Object> method); @Getter(value = IS_AVAILABLE_KEY) @XMLAttribute public DataBinding<Boolean> getIsAvailable(); @Setter(IS_AVAILABLE_KEY) public void setIsAvailable(DataBinding<Boolean> isAvailable); public abstract ActionType getActionType(); @DeserializationFinalizer public void finalizeDeserialization(); public void searchLocalized(LocalizationEntryRetriever retriever); @Getter(value = ALLOWS_BATCH_EXECUTION_KEY, defaultValue = "true") @XMLAttribute public boolean getAllowsBatchExecution(); @Setter(ALLOWS_BATCH_EXECUTION_KEY) public void setAllowsBatchExecution(boolean allowsBatchExecution); public static abstract class FIBTableActionImpl extends FIBModelObjectImpl implements FIBTableAction { private static final Logger logger = Logger.getLogger(FIBTableAction.class.getPackage().getName()); private DataBinding<Object> method; private DataBinding<Boolean> isAvailable; @Override public FIBTable getComponent() { return getOwner(); } @Override public void setOwner(FIBTable ownerTable) { // BindingModel oldBindingModel = getBindingModel(); performSuperSetter(OWNER_KEY, ownerTable); } @Override public DataBinding<Object> getMethod() { if (method == null) { method = new DataBinding<>(this, Object.class, DataBinding.BindingDefinitionType.EXECUTE); method.setBindingName("method"); } return method; } @Override public void setMethod(DataBinding<Object> method) { if (method != null) { method.setOwner(this); method.setDeclaredType(Object.class); method.setBindingDefinitionType(DataBinding.BindingDefinitionType.EXECUTE); method.setBindingName("method"); } this.method = method; } @Override public DataBinding<Boolean> getIsAvailable() { if (isAvailable == null) { isAvailable = new DataBinding<>(this, Boolean.class, DataBinding.BindingDefinitionType.GET); isAvailable.setBindingName("isAvailable"); } return isAvailable; } @Override public void setIsAvailable(DataBinding<Boolean> isAvailable) { if (isAvailable != null) { isAvailable.setOwner(this); isAvailable.setDeclaredType(Boolean.class); isAvailable.setBindingDefinitionType(DataBinding.BindingDefinitionType.GET); isAvailable.setBindingName("isAvailable"); } this.isAvailable = isAvailable; } @Override public BindingModel getBindingModel() { if (getOwner() != null) { return getOwner().getActionBindingModel(); } return null; } @Override public void finalizeDeserialization() { logger.fine("finalizeDeserialization() for FIBTableAction " + getName()); if (method != null) { method.decode(); } } @Override public abstract ActionType getActionType(); @Override public void searchLocalized(LocalizationEntryRetriever retriever) { retriever.foundLocalized(getName()); } @Override public String getPresentationName() { return getName(); } } @ModelEntity @ImplementationClass(FIBAddAction.FIBAddActionImpl.class) @XMLElement(xmlTag = "AddAction") public static interface FIBAddAction extends FIBTableAction { public static abstract class FIBAddActionImpl extends FIBTableActionImpl implements FIBAddAction { @Override public ActionType getActionType() { return ActionType.Add; } } } @ModelEntity @ImplementationClass(FIBRemoveAction.FIBRemoveActionImpl.class) @XMLElement(xmlTag = "RemoveAction") public static interface FIBRemoveAction extends FIBTableAction { public static abstract class FIBRemoveActionImpl extends FIBTableActionImpl implements FIBRemoveAction { @Override public ActionType getActionType() { return ActionType.Delete; } } } @ModelEntity @ImplementationClass(FIBCustomAction.FIBCustomActionImpl.class) @XMLElement(xmlTag = "CustomAction") public static interface FIBCustomAction extends FIBTableAction { @PropertyIdentifier(type = boolean.class) public static final String IS_STATIC_KEY = "isStatic"; @Getter(value = IS_STATIC_KEY, defaultValue = "false") @XMLAttribute public boolean isStatic(); @Setter(IS_STATIC_KEY) public void setStatic(boolean isStatic); public static abstract class FIBCustomActionImpl extends FIBTableActionImpl implements FIBCustomAction { @Override public ActionType getActionType() { return ActionType.Custom; } } } @DefineValidationRule public static class MethodBindingMustBeValid extends BindingMustBeValid<FIBTableAction> { public MethodBindingMustBeValid() { super("'method'_binding_is_not_valid", FIBTableAction.class); } @Override public DataBinding<?> getBinding(FIBTableAction object) { return object.getMethod(); } } @DefineValidationRule public static class IsAvailableBindingMustBeValid extends BindingMustBeValid<FIBTableAction> { public IsAvailableBindingMustBeValid() { super("'is_available'_binding_is_not_valid", FIBTableAction.class); } @Override public DataBinding<?> getBinding(FIBTableAction object) { return object.getIsAvailable(); } } }
gpl-3.0
thelasteiko/practice
algorithms/src/eiko/collections/CircularQueue.java
587
package eiko.collections; public class CircularQueue<E extends Comparable<? super E>> extends AbstractCircularArray<E> { @SuppressWarnings("unchecked") public CircularQueue() { elements = (E[]) new Comparable[START_SIZE]; size = 0; start = 0; stop = 0; } public void enqueue(E element) { check_size(size+1); elements[stop] = element; stop = (stop+1) % elements.length; size++; } public E dequeue() { E element = elements[start]; elements[start] = null; start = (start+1) % elements.length; size--; return element; } }
gpl-3.0
rranelli/engsoft-progressoes
src/test/java/engsoft/EProgressaoTest.java
6340
package engsoft; import junit.framework.TestCase; import java.lang.System; public class EProgressaoTest extends TestCase { public void testProgressaoAritmetica() { Progressao p = new ProgressaoAritmetica(); assertEquals(0, p.inicia()); assertEquals(1, p.proxTermo()); assertEquals(2, p.proxTermo()); assertEquals(4, p.iesimoTermo(4)); assertEquals(6, p.iesimoTermo(6)); assertEquals("0 1 2 3 4 5 6 7 8 9 10\n", p.imprimeProgressao(10)); p = new ProgressaoAritmetica(5); assertEquals(0, p.inicia()); assertEquals(5, p.proxTermo()); assertEquals(10, p.proxTermo()); assertEquals(20, p.iesimoTermo(4)); assertEquals(30, p.iesimoTermo(6)); assertEquals("0 5 10 15 20 25 30 35 40 45 50\n", p.imprimeProgressao(10)); } public void testProgressaoGeometrica() { Progressao p = new ProgressaoGeometrica(); assertEquals(1, p.inicia()); assertEquals(2, p.proxTermo()); assertEquals(4, p.proxTermo()); assertEquals(16, p.iesimoTermo(4)); assertEquals(64, p.iesimoTermo(6)); assertEquals("1 2 4 8 16 32 64 128 256 512 1024\n", p.imprimeProgressao(10)); p = new ProgressaoGeometrica(5); assertEquals(1, p.inicia()); assertEquals(5, p.proxTermo()); assertEquals(25, p.proxTermo()); assertEquals(625, p.iesimoTermo(4)); assertEquals(15625, p.iesimoTermo(6)); assertEquals("1 5 25 125 625 3125 15625 78125 390625 1953125 9765625\n", p.imprimeProgressao(10)); } public void testProgressaoFibonacci() { Progressao p = new ProgressaoFibonacci(); assertEquals(0, p.inicia()); assertEquals(1, p.proxTermo()); assertEquals(1, p.proxTermo()); assertEquals(3, p.iesimoTermo(4)); assertEquals(8, p.iesimoTermo(6)); assertEquals("0 1 1 2 3 5 8 13 21 34 55\n", p.imprimeProgressao(10)); } public void testProgressaoJosephus() { Progressao p = new ProgressaoJosephus(); assertEquals(0, p.inicia()); assertEquals(2, p.proxTermo()); assertEquals(4, p.proxTermo()); assertEquals(8, p.iesimoTermo(4)); assertEquals(12, p.iesimoTermo(6)); assertEquals("0 2 4 6 8 10 12 14 16 18 20\n", p.imprimeProgressao(10)); assertEquals(17, p.iesimoTermo(40)); assertEquals(0, p.iesimoTermo(41)); p = new ProgressaoJosephus(41, 10); assertEquals(0, p.inicia()); assertEquals(10, p.proxTermo()); assertEquals(20, p.proxTermo()); assertEquals(30, p.proxTermo()); assertEquals(40, p.proxTermo()); assertEquals(11, p.proxTermo()); assertEquals(40, p.iesimoTermo(4)); assertEquals(22, p.iesimoTermo(6)); assertEquals("0 10 20 30 40 11 22 33 4 16 28\n", p.imprimeProgressao(10)); assertEquals(25, p.iesimoTermo(40)); assertEquals(0, p.iesimoTermo(41)); } public void testProgressaoRapida() { Progressao p = new ProgressaoRapida(new ProgressaoAritmetica()); // Speed test: begin. Progressao q = new ProgressaoAritmetica(); int it = p.iesimoTermo(100); long pt = System.nanoTime(); it = p.iesimoTermo(100); pt = System.nanoTime() - pt; long bt = System.nanoTime(); int iq = q.iesimoTermo(100); bt = System.nanoTime() - bt; assertEquals(it,iq); assertTrue((bt - pt) > 0); // Speed test: end. q.iesimoTermo(100); assertEquals(0, p.inicia()); assertEquals(1, p.proxTermo()); assertEquals(2, p.proxTermo()); assertEquals(4, p.iesimoTermo(4)); assertEquals(6, p.iesimoTermo(6)); assertEquals("0 1 2 3 4 5 6 7 8 9 10\n", p.imprimeProgressao(10)); p = new ProgressaoRapida(new ProgressaoGeometrica()); // Speed test: begin. q = new ProgressaoGeometrica(); it = p.iesimoTermo(50); pt = System.nanoTime(); it = p.iesimoTermo(50); pt = System.nanoTime() - pt; bt = System.nanoTime(); iq = q.iesimoTermo(50); bt = System.nanoTime() - bt; assertEquals(it,iq); assertTrue((bt - pt) > 0); // Speed test: end. assertEquals(1, p.inicia()); assertEquals(2, p.proxTermo()); assertEquals(4, p.proxTermo()); assertEquals(16, p.iesimoTermo(4)); assertEquals(64, p.iesimoTermo(6)); assertEquals("1 2 4 8 16 32 64 128 256 512 1024\n", p.imprimeProgressao(10)); p = new ProgressaoRapida(new ProgressaoFibonacci()); // Speed test: begin. q = new ProgressaoFibonacci(); it = p.iesimoTermo(50); pt = System.nanoTime(); it = p.iesimoTermo(50); pt = System.nanoTime() - pt; bt = System.nanoTime(); iq = q.iesimoTermo(50); bt = System.nanoTime() - bt; assertEquals(it,iq); assertTrue((bt - pt) > 0); // Speed test: end. assertEquals(0, p.inicia()); assertEquals(1, p.proxTermo()); assertEquals(1, p.proxTermo()); assertEquals(3, p.iesimoTermo(4)); assertEquals(8, p.iesimoTermo(6)); assertEquals("0 1 1 2 3 5 8 13 21 34 55\n", p.imprimeProgressao(10)); p = new ProgressaoRapida(new ProgressaoJosephus()); // Speed test: begin. q = new ProgressaoJosephus(); it = p.iesimoTermo(40); pt = System.nanoTime(); it = p.iesimoTermo(40); pt = System.nanoTime() - pt; bt = System.nanoTime(); iq = q.iesimoTermo(40); bt = System.nanoTime() - bt; assertEquals(it,iq); assertTrue((bt - pt) > 0); // Speed test: end. assertEquals(0, p.inicia()); assertEquals(2, p.proxTermo()); assertEquals(4, p.proxTermo()); assertEquals(8, p.iesimoTermo(4)); assertEquals(12, p.iesimoTermo(6)); assertEquals("0 2 4 6 8 10 12 14 16 18 20\n", p.imprimeProgressao(10)); assertEquals(17, p.iesimoTermo(40)); assertEquals(0, p.iesimoTermo(41)); } }
gpl-3.0
wiki2014/Learning-Summary
alps/cts/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java
7246
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.uirendering.cts.testclasses; import android.annotation.ColorInt; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.MediumTest; import android.uirendering.cts.bitmapverifiers.ColorVerifier; import android.uirendering.cts.testinfrastructure.ActivityTestBase; import android.uirendering.cts.testinfrastructure.ViewInitializer; import android.view.Gravity; import android.view.View; import android.view.ViewTreeObserver; import android.uirendering.cts.R; import android.widget.FrameLayout; import org.junit.Test; import org.junit.runner.RunWith; @MediumTest @RunWith(AndroidJUnit4.class) public class LayerTests extends ActivityTestBase { @Test public void testLayerPaintAlpha() { // red channel full strength, other channels 75% strength // (since 25% alpha red subtracts from them) @ColorInt final int expectedColor = Color.rgb(255, 191, 191); createTest() .addLayout(R.layout.simple_red_layout, (ViewInitializer) view -> { // reduce alpha by 50% Paint paint = new Paint(); paint.setAlpha(128); view.setLayerType(View.LAYER_TYPE_HARDWARE, paint); // reduce alpha by another 50% (ensuring two alphas combine correctly) view.setAlpha(0.5f); }) .runWithVerifier(new ColorVerifier(expectedColor)); } @Test public void testLayerPaintColorFilter() { // Red, fully desaturated. Note that it's not 255/3 in each channel. // See ColorMatrix#setSaturation() @ColorInt final int expectedColor = Color.rgb(54, 54, 54); createTest() .addLayout(R.layout.simple_red_layout, (ViewInitializer) view -> { Paint paint = new Paint(); ColorMatrix desatMatrix = new ColorMatrix(); desatMatrix.setSaturation(0.0f); paint.setColorFilter(new ColorMatrixColorFilter(desatMatrix)); view.setLayerType(View.LAYER_TYPE_HARDWARE, paint); }) .runWithVerifier(new ColorVerifier(expectedColor)); } @Test public void testLayerPaintBlend() { // Red, drawn underneath opaque white, so output should be white. // TODO: consider doing more interesting blending test here @ColorInt final int expectedColor = Color.WHITE; createTest() .addLayout(R.layout.simple_red_layout, (ViewInitializer) view -> { Paint paint = new Paint(); /* Note that when drawing in SW, we're blending within an otherwise empty * SW layer, as opposed to in the frame buffer (which has a white * background). * * For this reason we use just use DST, which just throws out the SRC * content, regardless of the DST alpha channel. */ paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST)); view.setLayerType(View.LAYER_TYPE_HARDWARE, paint); }) .runWithVerifier(new ColorVerifier(expectedColor)); } @Test public void testLayerInitialSizeZero() { createTest() .addLayout(R.layout.frame_layout, view -> { FrameLayout root = (FrameLayout) view.findViewById(R.id.frame_layout); // disable clipChildren, to ensure children aren't rejected by bounds root.setClipChildren(false); for (int i = 0; i < 2; i++) { View child = new View(view.getContext()); child.setLayerType(View.LAYER_TYPE_HARDWARE, null); // add rendering content, so View isn't skipped at render time child.setBackgroundColor(Color.RED); // add one with width=0, one with height=0 root.addView(child, new FrameLayout.LayoutParams( i == 0 ? 0 : 90, i == 0 ? 90 : 0, Gravity.TOP | Gravity.LEFT)); } }, true) .runWithVerifier(new ColorVerifier(Color.WHITE, 0 /* zero tolerance */)); } @Test public void testLayerResizeZero() { createTest() .addLayout(R.layout.frame_layout, view -> { FrameLayout root = (FrameLayout) view.findViewById(R.id.frame_layout); // disable clipChildren, to ensure child isn't rejected by bounds root.setClipChildren(false); for (int i = 0; i < 2; i++) { View child = new View(view.getContext()); child.setLayerType(View.LAYER_TYPE_HARDWARE, null); // add rendering content, so View isn't skipped at render time child.setBackgroundColor(Color.BLUE); root.addView(child, new FrameLayout.LayoutParams(90, 90, Gravity.TOP | Gravity.LEFT)); } // post invalid dimensions a few frames in, so initial layer allocation succeeds // NOTE: this must execute before capture, or verification will fail root.getViewTreeObserver().addOnPreDrawListener( new ViewTreeObserver.OnPreDrawListener() { int mDrawCount = 0; @Override public boolean onPreDraw() { if (mDrawCount++ == 5) { root.getChildAt(0).getLayoutParams().width = 0; root.getChildAt(0).requestLayout(); root.getChildAt(1).getLayoutParams().height = 0; root.getChildAt(1).requestLayout(); } return true; } }); }, true) .runWithVerifier(new ColorVerifier(Color.WHITE, 0 /* zero tolerance */)); } }
gpl-3.0
dbmi-pitt/xmeso
src/main/java/edu/pitt/dbmi/xmeso/model/Model/XmesoSentence_Type.java
5475
/* First created by JCasGen Wed Sep 07 16:18:03 EDT 2016 */ package edu.pitt.dbmi.xmeso.model.Model; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** Type defined in edu.pitt.dbmi.xmeso.model.Model * Updated by JCasGen Wed Sep 07 16:18:03 EDT 2016 * @generated */ public class XmesoSentence_Type extends Annotation_Type { /** @generated * @return the generator for this type */ @Override protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (XmesoSentence_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = XmesoSentence_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new XmesoSentence(addr, XmesoSentence_Type.this); XmesoSentence_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new XmesoSentence(addr, XmesoSentence_Type.this); } }; /** @generated */ @SuppressWarnings ("hiding") public final static int typeIndexID = XmesoSentence.typeIndexID; /** @generated @modifiable */ @SuppressWarnings ("hiding") public final static boolean featOkTst = JCasRegistry.getFeatOkTst("edu.pitt.dbmi.xmeso.model.Model.XmesoSentence"); /** @generated */ final Feature casFeat_sectionName; /** @generated */ final int casFeatCode_sectionName; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getSectionName(int addr) { if (featOkTst && casFeat_sectionName == null) jcas.throwFeatMissing("sectionName", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence"); return ll_cas.ll_getStringValue(addr, casFeatCode_sectionName); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setSectionName(int addr, String v) { if (featOkTst && casFeat_sectionName == null) jcas.throwFeatMissing("sectionName", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence"); ll_cas.ll_setStringValue(addr, casFeatCode_sectionName, v);} /** @generated */ final Feature casFeat_partNumber; /** @generated */ final int casFeatCode_partNumber; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public int getPartNumber(int addr) { if (featOkTst && casFeat_partNumber == null) jcas.throwFeatMissing("partNumber", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence"); return ll_cas.ll_getIntValue(addr, casFeatCode_partNumber); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setPartNumber(int addr, int v) { if (featOkTst && casFeat_partNumber == null) jcas.throwFeatMissing("partNumber", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence"); ll_cas.ll_setIntValue(addr, casFeatCode_partNumber, v);} /** @generated */ final Feature casFeat_sentenceNumber; /** @generated */ final int casFeatCode_sentenceNumber; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public int getSentenceNumber(int addr) { if (featOkTst && casFeat_sentenceNumber == null) jcas.throwFeatMissing("sentenceNumber", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence"); return ll_cas.ll_getIntValue(addr, casFeatCode_sentenceNumber); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setSentenceNumber(int addr, int v) { if (featOkTst && casFeat_sentenceNumber == null) jcas.throwFeatMissing("sentenceNumber", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence"); ll_cas.ll_setIntValue(addr, casFeatCode_sentenceNumber, v);} /** initialize variables to correspond with Cas Type and Features * @generated * @param jcas JCas * @param casType Type */ public XmesoSentence_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_sectionName = jcas.getRequiredFeatureDE(casType, "sectionName", "uima.cas.String", featOkTst); casFeatCode_sectionName = (null == casFeat_sectionName) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_sectionName).getCode(); casFeat_partNumber = jcas.getRequiredFeatureDE(casType, "partNumber", "uima.cas.Integer", featOkTst); casFeatCode_partNumber = (null == casFeat_partNumber) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_partNumber).getCode(); casFeat_sentenceNumber = jcas.getRequiredFeatureDE(casType, "sentenceNumber", "uima.cas.Integer", featOkTst); casFeatCode_sentenceNumber = (null == casFeat_sentenceNumber) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_sentenceNumber).getCode(); } }
gpl-3.0
potty-dzmeia/db4o
src/db4oj/core/src/com/db4o/io/CachedIoAdapter.java
13271
/* This file is part of the db4o object database http://www.db4o.com Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com db4o is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation. db4o is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ package com.db4o.io; import com.db4o.ext.*; import com.db4o.internal.fileheader.*; /** * CachedIoAdapter is an IOAdapter for random access files, which caches data * for IO access. Its functionality is similar to OS cache.<br> * Example:<br> * <code>delegateAdapter = new RandomAccessFileAdapter();</code><br> * <code>Db4o.configure().io(new CachedIoAdapter(delegateAdapter));</code><br> * @deprecated Use {@link CachingStorage} instead. */ public class CachedIoAdapter extends IoAdapter { private Page _head; private Page _tail; private long _position; private int _pageSize; private int _pageCount; private long _fileLength; private long _filePointer; private IoAdapter _io; private boolean _readOnly; private static int DEFAULT_PAGE_SIZE = 1024; private static int DEFAULT_PAGE_COUNT = 64; // private Hashtable4 _posPageMap = new Hashtable4(PAGE_COUNT); /** * Creates an instance of CachedIoAdapter with the default page size and * page count. * * @param ioAdapter * delegate IO adapter (RandomAccessFileAdapter by default) */ public CachedIoAdapter(IoAdapter ioAdapter) { this(ioAdapter, DEFAULT_PAGE_SIZE, DEFAULT_PAGE_COUNT); } /** * Creates an instance of CachedIoAdapter with a custom page size and page * count.<br> * * @param ioAdapter * delegate IO adapter (RandomAccessFileAdapter by default) * @param pageSize * cache page size * @param pageCount * allocated amount of pages */ public CachedIoAdapter(IoAdapter ioAdapter, int pageSize, int pageCount) { _io = ioAdapter; _pageSize = pageSize; _pageCount = pageCount; } /** * Creates an instance of CachedIoAdapter with extended parameters.<br> * * @param path * database file path * @param lockFile * determines if the file should be locked * @param initialLength * initial file length, new writes will start from this point * @param readOnly * if the file should be used in read-onlyt mode. * @param io * delegate IO adapter (RandomAccessFileAdapter by default) * @param pageSize * cache page size * @param pageCount * allocated amount of pages */ public CachedIoAdapter(String path, boolean lockFile, long initialLength, boolean readOnly, IoAdapter io, int pageSize, int pageCount) throws Db4oIOException { _readOnly = readOnly; _pageSize = pageSize; _pageCount = pageCount; initCache(); initIOAdaptor(path, lockFile, initialLength, readOnly, io); _position = initialLength; _filePointer = initialLength; _fileLength = _io.getLength(); } /** * Creates and returns a new CachedIoAdapter <br> * * @param path * database file path * @param lockFile * determines if the file should be locked * @param initialLength * initial file length, new writes will start from this point */ public IoAdapter open(String path, boolean lockFile, long initialLength, boolean readOnly) throws Db4oIOException { return new CachedIoAdapter(path, lockFile, initialLength, readOnly, _io, _pageSize, _pageCount); } /** * Deletes the database file * * @param path * file path */ public void delete(String path) { _io.delete(path); } /** * Checks if the file exists * * @param path * file path */ public boolean exists(String path) { return _io.exists(path); } private void initIOAdaptor(String path, boolean lockFile, long initialLength, boolean readOnly, IoAdapter io) throws Db4oIOException { _io = io.open(path, lockFile, initialLength, readOnly); } private void initCache() { _head = new Page(_pageSize); _head._prev = null; Page page = _head; Page next = _head; for (int i = 0; i < _pageCount - 1; ++i) { next = new Page(_pageSize); page._next = next; next._prev = page; page = next; } _tail = next; } /** * Reads the file into the buffer using pages from cache. If the next page * is not cached it will be read from the file. * * @param buffer * destination buffer * @param length * how many bytes to read */ public int read(byte[] buffer, int length) throws Db4oIOException { long startAddress = _position; int bytesToRead = length; int totalRead = 0; while (bytesToRead > 0) { final Page page = getPage(startAddress, true); final int readBytes = page.read(buffer, totalRead, startAddress, bytesToRead); movePageToHead(page); if (readBytes <= 0) { break; } bytesToRead -= readBytes; startAddress += readBytes; totalRead += readBytes; } _position = startAddress; return totalRead == 0 ? -1 : totalRead; } /** * Writes the buffer to cache using pages * * @param buffer * source buffer * @param length * how many bytes to write */ public void write(byte[] buffer, int length) throws Db4oIOException { validateReadOnly(); long startAddress = _position; int bytesToWrite = length; int bufferOffset = 0; while (bytesToWrite > 0) { // page doesn't need to loadFromDisk if the whole page is dirty boolean loadFromDisk = (bytesToWrite < _pageSize) || (startAddress % _pageSize != 0); final Page page = getPage(startAddress, loadFromDisk); page.ensureEndAddress(getLength()); final int writtenBytes = page.write(buffer, bufferOffset, startAddress, bytesToWrite); flushIfHeaderBlockPage(page); movePageToHead(page); bytesToWrite -= writtenBytes; startAddress += writtenBytes; bufferOffset += writtenBytes; } long endAddress = startAddress; _position = endAddress; _fileLength = Math.max(endAddress, _fileLength); } private void flushIfHeaderBlockPage(final Page page) { if(containsHeaderBlock(page)) { flushPage(page); } } private void validateReadOnly() { if(_readOnly) { throw new Db4oIOException(); } } /** * Flushes cache to a physical storage */ public void sync() throws Db4oIOException { validateReadOnly(); flushAllPages(); _io.sync(); } /** * Returns the file length */ public long getLength() throws Db4oIOException { return _fileLength; } /** * Flushes and closes the file */ public void close() throws Db4oIOException { try { flushAllPages(); } finally { _io.close(); } } public IoAdapter delegatedIoAdapter() { return _io.delegatedIoAdapter(); } private Page getPage(long startAddress, boolean loadFromDisk) throws Db4oIOException { Page page = getPageFromCache(startAddress); if (page != null) { if (containsHeaderBlock(page)) { getPageFromDisk(page, startAddress); } page.ensureEndAddress(_fileLength); return page; } // in case that page is not found in the cache page = getFreePageFromCache(); if (loadFromDisk) { getPageFromDisk(page, startAddress); } else { resetPageAddress(page, startAddress); } return page; } private boolean containsHeaderBlock(Page page) { return page.startAddress() <= FileHeader1.HEADER_LENGTH; } private void resetPageAddress(Page page, long startAddress) { page.startAddress(startAddress); page.endAddress(startAddress + _pageSize); } private Page getFreePageFromCache() throws Db4oIOException { if (!_tail.isFree()) { flushPage(_tail); // _posPageMap.remove(new Long(tail.startPosition / PAGE_SIZE)); } return _tail; } private Page getPageFromCache(long pos) throws Db4oIOException { Page page = _head; while (page != null) { if (page.contains(pos)) { return page; } page = page._next; } return null; // Page page = (Page) _posPageMap.get(new Long(pos/PAGE_SIZE)); // return page; } private void flushAllPages() throws Db4oIOException { Page node = _head; while (node != null) { flushPage(node); node = node._next; } } private void flushPage(Page page) throws Db4oIOException { if (!page._dirty) { return; } ioSeek(page.startAddress()); writePageToDisk(page); return; } private void getPageFromDisk(Page page, long pos) throws Db4oIOException { long startAddress = pos - pos % _pageSize; page.startAddress(startAddress); ioSeek(page._startAddress); int count = ioRead(page); if (count > 0) { page.endAddress(startAddress + count); } else { page.endAddress(startAddress); } // _posPageMap.put(new Long(page.startPosition / PAGE_SIZE), page); } private int ioRead(Page page) throws Db4oIOException { int count = _io.read(page._buffer); if (count > 0) { _filePointer = page._startAddress + count; } return count; } private void movePageToHead(Page page) { if (page == _head) { return; } if (page == _tail) { Page tempTail = _tail._prev; tempTail._next = null; _tail._next = _head; _tail._prev = null; _head._prev = page; _head = _tail; _tail = tempTail; } else { page._prev._next = page._next; page._next._prev = page._prev; page._next = _head; _head._prev = page; page._prev = null; _head = page; } } private void writePageToDisk(Page page) throws Db4oIOException { validateReadOnly(); try{ _io.write(page._buffer, page.size()); _filePointer = page.endAddress(); page._dirty = false; }catch (Db4oIOException e){ _readOnly = true; throw e; } } /** * Moves the pointer to the specified file position * * @param pos * position within the file */ public void seek(long pos) throws Db4oIOException { _position = pos; } private void ioSeek(long pos) throws Db4oIOException { if (_filePointer != pos) { _io.seek(pos); _filePointer = pos; } } private static class Page { byte[] _buffer; long _startAddress = -1; long _endAddress; final int _bufferSize; boolean _dirty; Page _prev; Page _next; private byte[] zeroBytes; public Page(int size) { _bufferSize = size; _buffer = new byte[_bufferSize]; } /* * This method must be invoked before page.write/read, because seek and * write may write ahead the end of file. */ void ensureEndAddress(long fileLength) { long bufferEndAddress = _startAddress + _bufferSize; if (_endAddress < bufferEndAddress && fileLength > _endAddress) { long newEndAddress = Math.min(fileLength, bufferEndAddress); if (zeroBytes == null) { zeroBytes = new byte[_bufferSize]; } System.arraycopy(zeroBytes, 0, _buffer, (int) (_endAddress - _startAddress), (int) (newEndAddress - _endAddress)); _endAddress = newEndAddress; } } long endAddress() { return _endAddress; } void startAddress(long address) { _startAddress = address; } long startAddress() { return _startAddress; } void endAddress(long address) { _endAddress = address; } int size() { return (int) (_endAddress - _startAddress); } int read(byte[] out, int outOffset, long startAddress, int length) { int bufferOffset = (int) (startAddress - _startAddress); int pageAvailbeDataSize = (int) (_endAddress - startAddress); int readBytes = Math.min(pageAvailbeDataSize, length); if (readBytes <= 0) { // meaning reach EOF return -1; } System.arraycopy(_buffer, bufferOffset, out, outOffset, readBytes); return readBytes; } int write(byte[] data, int dataOffset, long startAddress, int length) { int bufferOffset = (int) (startAddress - _startAddress); int pageAvailabeBufferSize = _bufferSize - bufferOffset; int writtenBytes = Math.min(pageAvailabeBufferSize, length); System.arraycopy(data, dataOffset, _buffer, bufferOffset, writtenBytes); long endAddress = startAddress + writtenBytes; if (endAddress > _endAddress) { _endAddress = endAddress; } _dirty = true; return writtenBytes; } boolean contains(long address) { return (_startAddress != -1 && address >= _startAddress && address < _startAddress + _bufferSize); } boolean isFree() { return _startAddress == -1; } } }
gpl-3.0
maxfoow/MalmoExperience
Malmo-0.16.0-Windows-64bit/Minecraft/src/main/java/com/microsoft/Malmo/Utils/JSONWorldDataHelper.java
8861
// -------------------------------------------------------------------------------------------------- // Copyright (c) 2016 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // -------------------------------------------------------------------------------------------------- package com.microsoft.Malmo.Utils; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.stats.StatBase; import net.minecraft.stats.StatFileWriter; import net.minecraft.stats.StatList; import net.minecraft.util.BlockPos; import net.minecraft.util.ResourceLocation; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; /** * Helper class for building the "World data" to be passed from Minecraft back to the agent.<br> * This class contains helper methods to build up a JSON tree of useful information, such as health, XP, food levels, distance travelled, etc.etc.<br> * It can also build up a grid of the block types around the player. * Call this on the Server side only. */ public class JSONWorldDataHelper { /** * Simple class to hold the dimensions of the environment around the player * that we want to return in the World Data.<br> * Min and max define an inclusive range, where the player's feet are situated at (0,0,0) */ static public class ImmediateEnvironmentDimensions { public int xMin; public int xMax; public int yMin; public int yMax; public int zMin; public int zMax; /** * Default constructor asks for an environment just big enough to contain * the player and one block all around him. */ public ImmediateEnvironmentDimensions() { this.xMin = -1; this.xMax = 1; this.zMin = -1; this.zMax = 1; this.yMin = -1; this.yMax = 2; } /** * Convenient constructor - effectively specifies the margin around the player<br> * Passing (1,1,1) will have the same effect as the default constructor. * @param xMargin number of blocks to the left and right of the player * @param yMargin number of blocks above and below player * @param zMargin number of blocks in front of and behind player */ public ImmediateEnvironmentDimensions(int xMargin, int yMargin, int zMargin) { this.xMin = -xMargin; this.xMax = xMargin; this.yMin = -yMargin; this.yMax = yMargin + 1; // +1 because the player is two blocks tall. this.zMin = -zMargin; this.zMax = zMargin; } /** * Convenient constructor for the case where all that is required is the flat patch of ground<br> * around the player's feet. * @param xMargin number of blocks around the player in the x-axis * @param zMargin number of blocks around the player in the z-axis */ public ImmediateEnvironmentDimensions(int xMargin, int zMargin) { this.xMin = -xMargin; this.xMax = xMargin; this.yMin = -1; this.yMax = -1; // Flat patch of ground at the player's feet. this.zMin = -zMargin; this.zMax = zMargin; } }; /** Builds the basic achievement world data to be used as observation signals by the listener. * @param json a JSON object into which the achievement stats will be added. */ public static void buildAchievementStats(JsonObject json, EntityPlayerMP player) { StatFileWriter sfw = player.getStatFile(); json.addProperty("DistanceTravelled", sfw.readStat((StatBase)StatList.distanceWalkedStat) + sfw.readStat((StatBase)StatList.distanceSwumStat) + sfw.readStat((StatBase)StatList.distanceDoveStat) + sfw.readStat((StatBase)StatList.distanceFallenStat) ); // TODO: there are many other ways of moving! json.addProperty("TimeAlive", sfw.readStat((StatBase)StatList.timeSinceDeathStat)); json.addProperty("MobsKilled", sfw.readStat((StatBase)StatList.mobKillsStat)); json.addProperty("DamageTaken", sfw.readStat((StatBase)StatList.damageTakenStat)); /* Other potential reinforcement signals that may be worth researching: json.addProperty("BlocksDestroyed", sfw.readStat((StatBase)StatList.objectBreakStats) - but objectBreakStats is an array of 32000 StatBase objects - indexed by block type.); json.addProperty("Blocked", ev.player.isMovementBlocked()) - but isMovementBlocker() is a protected method (can get round this with reflection) */ } /** Builds the basic life world data to be used as observation signals by the listener. * @param json a JSON object into which the life stats will be added. */ public static void buildLifeStats(JsonObject json, EntityPlayerMP player) { json.addProperty("Life", player.getHealth()); json.addProperty("Score", player.getScore()); // Might always be the same as XP? json.addProperty("Food", player.getFoodStats().getFoodLevel()); json.addProperty("XP", player.experienceTotal); json.addProperty("IsAlive", !player.isDead); json.addProperty("Air", player.getAir()); } /** Builds the player position data to be used as observation signals by the listener. * @param json a JSON object into which the positional information will be added. */ public static void buildPositionStats(JsonObject json, EntityPlayerMP player) { json.addProperty("XPos", player.posX); json.addProperty("YPos", player.posY); json.addProperty("ZPos", player.posZ); json.addProperty("Pitch", player.rotationPitch); json.addProperty("Yaw", player.rotationYaw); } /** * Build a signal for the cubic block grid centred on the player.<br> * Default is 3x3x4. (One cube all around the player.)<br> * Blocks are returned as a 1D array, in order * along the x, then z, then y axes.<br> * Data will be returned in an array called "Cells" * @param json a JSON object into which the info for the object under the mouse will be added. * @param environmentDimensions object which specifies the required dimensions of the grid to be returned. * @param jsonName name to use for identifying the returned JSON array. */ public static void buildGridData(JsonObject json, ImmediateEnvironmentDimensions environmentDimensions, EntityPlayerMP player, String jsonName) { if (player == null || json == null) return; JsonArray arr = new JsonArray(); BlockPos pos = player.getPosition(); for (int y = environmentDimensions.yMin; y <= environmentDimensions.yMax; y++) { for (int z = environmentDimensions.zMin; z <= environmentDimensions.zMax; z++) { for (int x = environmentDimensions.xMin; x <= environmentDimensions.xMax; x++) { BlockPos p = pos.add(x, y, z); String name = ""; IBlockState state = player.worldObj.getBlockState(p); Object blockName = Block.blockRegistry.getNameForObject(state.getBlock()); if (blockName instanceof ResourceLocation) { name = ((ResourceLocation)blockName).getResourcePath(); } JsonElement element = new JsonPrimitive(name); arr.add(element); } } } json.add(jsonName, arr); } }
gpl-3.0
Borlea/EchoPet
modules/v1_14_R1/src/com/dsh105/echopet/compat/nms/v1_14_R1/entity/type/EntityEvokerPet.java
2379
/* * This file is part of EchoPet. * * EchoPet 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. * * EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.echopet.compat.nms.v1_14_R1.entity.type; import com.dsh105.echopet.compat.api.entity.EntityPetType; import com.dsh105.echopet.compat.api.entity.EntitySize; import com.dsh105.echopet.compat.api.entity.IPet; import com.dsh105.echopet.compat.api.entity.PetType; import com.dsh105.echopet.compat.api.entity.SizeCategory; import com.dsh105.echopet.compat.api.entity.type.nms.IEntityEvokerPet; import net.minecraft.server.v1_14_R1.DataWatcher; import net.minecraft.server.v1_14_R1.DataWatcherObject; import net.minecraft.server.v1_14_R1.DataWatcherRegistry; import net.minecraft.server.v1_14_R1.EntityInsentient; import net.minecraft.server.v1_14_R1.EntityTypes; import net.minecraft.server.v1_14_R1.World; /** * @since Nov 19, 2016 */ @EntitySize(width = 0.6F, height = 1.95F) @EntityPetType(petType = PetType.EVOKER) public class EntityEvokerPet extends EntityIllagerAbstractPet implements IEntityEvokerPet{ // EntityIllagerWizard private static final DataWatcherObject<Byte> c = DataWatcher.a(EntityEvokerPet.class, DataWatcherRegistry.a);// some sorta spell shit public EntityEvokerPet(EntityTypes<? extends EntityInsentient> type, World world){ super(type, world); } public EntityEvokerPet(EntityTypes<? extends EntityInsentient> type, World world, IPet pet){ super(type, world, pet); } public EntityEvokerPet(World world){ this(EntityTypes.EVOKER, world); } public EntityEvokerPet(World world, IPet pet){ this(EntityTypes.EVOKER, world, pet); } @Override protected void initDatawatcher(){ super.initDatawatcher(); this.datawatcher.register(c, (byte) 0); } @Override public SizeCategory getSizeCategory(){ return SizeCategory.REGULAR; } }
gpl-3.0
andrewtikhonov/RCloud
rcloud-bench/src/main/java/workbench/views/basiceditor/highlighting/DocumentBlockLevels.java
3628
/* * R Cloud - R-based Cloud Platform for Computational Research * at EMBL-EBI (European Bioinformatics Institute) * * Copyright (C) 2007-2015 European Bioinformatics Institute * Copyright (C) 2009-2015 Andrew Tikhonov - andrew.tikhonov@gmail.com * 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 workbench.views.basiceditor.highlighting; import workbench.util.EditorUtil; /** * Created by IntelliJ IDEA. * User: andrew * Date: 17/02/2012 * Time: 17:27 * To change this template use File | Settings | File Templates. */ public class DocumentBlockLevels { public int insideCodeBlock = 0; public int insideArgsBlock = 0; public int insideArrayBlock = 0; public static DocumentBlockLevels analyzeNestedLevels(String text, int pos) { int start = pos; int i_code_b = 0; int i_args_b = 0; int i_arra_b = 0; char i_am_in_text = EditorUtil.EMPTY; DocumentBlockLevels structure = new DocumentBlockLevels(); while (start >= 0) { char c = text.charAt(start); if (i_am_in_text == EditorUtil.EMPTY) { if (c == EditorUtil.CODEOPEN) { i_code_b++; } else if (c == EditorUtil.CODECLOSE) { i_code_b--; } else if (c == EditorUtil.ARGSOPEN) { i_args_b++; } else if (c == EditorUtil.ARGSCLOSE) { i_args_b--; } else if (c == EditorUtil.ARRAYOPEN) { i_arra_b++; } else if (c == EditorUtil.ARRAYCLOSE) { i_arra_b--; } } if (c == EditorUtil.QUOTE1) { if (i_am_in_text == EditorUtil.EMPTY) { // entering text i_am_in_text = EditorUtil.QUOTE1; } else if (i_am_in_text == EditorUtil.QUOTE1) { // exiting text i_am_in_text = EditorUtil.EMPTY; } } if (c == EditorUtil.QUOTE2) { if (i_am_in_text == EditorUtil.EMPTY) { // entering text i_am_in_text = EditorUtil.QUOTE2; } else if (i_am_in_text == EditorUtil.QUOTE2) { // exiting text i_am_in_text = EditorUtil.EMPTY; } } if (c == EditorUtil.COMMENT) { i_code_b = 0; i_args_b = 0; i_arra_b = 0; } if (c == EditorUtil.NEWLINE || start == 0) { structure.insideCodeBlock += i_code_b; structure.insideArgsBlock += i_args_b; structure.insideArrayBlock += i_arra_b; i_code_b = 0; i_args_b = 0; i_arra_b = 0; } start--; } return structure; } }
gpl-3.0
gigaSproule/cloud-services
src/main/java/com/benjaminsproule/cloud/domain/Track.java
618
package com.benjaminsproule.cloud.domain; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.Setter; @Data @Setter(AccessLevel.PACKAGE) @NoArgsConstructor(access = AccessLevel.PACKAGE) public class Track { private String id; private String path; private Long trackNumber; private String title; private String artist; private String album; private String genre; private String rating; private Long length; private boolean offline; private String encodingType; private ServiceName serviceName; private Long lastModified; }
gpl-3.0
kmycode/jstorybook
src/jstorybook/view/pane/IComparablePane.java
1126
/* * jStorybook: すべての小説家・作者のためのオープンソース・ソフトウェア * Copyright (C) 2008 - 2012 Martin Mustun * (このソースの製作者) KMY * * このプログラムはフリーソフトです。 * あなたは、自由に修正し、再配布することが出来ます。 * あなたの権利は、the Free Software Foundationによって発表されたGPL ver.2以降によって保護されています。 * * このプログラムは、小説・ストーリーの制作がよりよくなるようにという願いを込めて再配布されています。 * あなたがこのプログラムを再配布するときは、GPLライセンスに同意しなければいけません。 * <http://www.gnu.org/licenses/>. */ package jstorybook.view.pane; /** * 比較可能なペイン * * @author KMY */ public interface IComparablePane { public PaneType getPaneType (); public long getPaneId (); public default boolean isEqualPane (IComparablePane other) { return this.getPaneType() == other.getPaneType() && this.getPaneId() == other.getPaneId(); } }
gpl-3.0
fppt/mindmapsdb
grakn-graph/src/main/java/ai/grakn/graph/internal/CastingImpl.java
3785
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.graph.internal; import ai.grakn.concept.Concept; import ai.grakn.concept.Instance; import ai.grakn.concept.Relation; import ai.grakn.concept.RoleType; import ai.grakn.exception.NoEdgeException; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; /** * An internal concept used to represent the link between a roleplayer and it's role. * For example Pacino as an actor would be represented by a single casting regardless of the number of movies he acts in. */ class CastingImpl extends ConceptImpl { CastingImpl(Vertex v, RoleType type, AbstractGraknGraph graknGraph) { super(v, type, graknGraph); } /** * * @return The {@link RoleType} this casting is linked with */ public RoleType getRole() { Concept concept = getParentIsa(); if(concept != null) return concept.asRoleType(); else throw new NoEdgeException(toString(), Schema.BaseType.ROLE_TYPE.name()); } /** * * @return The {@link Instance} which is the roleplayer in this casting */ public InstanceImpl getRolePlayer() { Concept concept = getOutgoingNeighbour(Schema.EdgeLabel.ROLE_PLAYER); if(concept != null) return (InstanceImpl) concept; else return null; } /** * Sets thew internal index of this casting toi allow for faster lookup. * @param role The {@link RoleType} this casting is linked with * @param rolePlayer The {@link Instance} which is the roleplayer in this casting * @return The casting itself. */ public CastingImpl setHash(RoleTypeImpl role, InstanceImpl rolePlayer){ String hash; if(getGraknGraph().isBatchLoadingEnabled()) hash = "CastingBaseId_" + this.getBaseIdentifier() + UUID.randomUUID().toString(); else hash = generateNewHash(role, rolePlayer); setUniqueProperty(Schema.ConceptProperty.INDEX, hash); return this; } /** * * @param role The {@link RoleType} this casting is linked with * @param rolePlayer The {@link Instance} which is the roleplayer in this casting * @return A unique hash for the casting. */ public static String generateNewHash(RoleTypeImpl role, InstanceImpl rolePlayer){ return "Casting-Role-" + role.getId() + "-RolePlayer-" + rolePlayer.getId(); } /** * * @return All the {@link Relation} this casting is linked with. */ public Set<RelationImpl> getRelations() { ConceptImpl<?, ?> thisRef = this; Set<RelationImpl> relations = new HashSet<>(); Set<ConceptImpl> concepts = thisRef.getIncomingNeighbours(Schema.EdgeLabel.CASTING); if(concepts.size() > 0){ relations.addAll(concepts.stream().map(concept -> (RelationImpl) concept).collect(Collectors.toList())); } return relations; } }
gpl-3.0
Nilhcem/bblfr-android
app/src/main/java/com/nilhcem/bblfr/core/dagger/BBLModule.java
1947
package com.nilhcem.bblfr.core.dagger; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.jakewharton.picasso.OkHttp3Downloader; import com.nilhcem.bblfr.BBLApplication; import com.nilhcem.bblfr.BuildConfig; import com.nilhcem.bblfr.core.map.LocationProvider; import com.nilhcem.bblfr.core.prefs.Preferences; import com.squareup.picasso.Picasso; import java.io.File; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.OkHttpClient; import timber.log.Timber; @Module public class BBLModule { private static final int DISK_CACHE_SIZE = 52_428_800; // 50MB (50 * 1024 * 1024) private final BBLApplication mApp; public BBLModule(BBLApplication app) { mApp = app; } @Provides @Singleton LocationProvider provideLocationProvider() { return new LocationProvider(); } @Provides @Singleton Preferences providePreferences() { return new Preferences(mApp); } @Provides @Singleton OkHttpClient provideOkHttpClient() { // Install an HTTP cache in the application cache directory. File cacheDir = new File(mApp.getCacheDir(), "http"); Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE); return new OkHttpClient.Builder().cache(cache).build(); } @Provides @Singleton ObjectMapper provideObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); return mapper; } @Provides @Singleton Picasso providePicasso(OkHttpClient client) { Picasso.Builder builder = new Picasso.Builder(mApp).downloader(new OkHttp3Downloader(client)); if (BuildConfig.DEBUG) { builder.listener((picasso, uri, e) -> Timber.e(e, "Failed to load image: %s", uri)); } return builder.build(); } }
gpl-3.0
avdata99/SIAT
siat-1.0-SOURCE/src/buss/src/ar/gov/rosario/siat/gde/buss/bean/SerBanDesGen.java
4361
//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.gde.buss.bean; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import ar.gov.rosario.siat.base.iface.util.BaseError; import ar.gov.rosario.siat.def.buss.bean.ServicioBanco; import ar.gov.rosario.siat.def.iface.util.DefError; import ar.gov.rosario.siat.gde.buss.dao.GdeDAOFactory; import ar.gov.rosario.siat.gde.iface.util.GdeError; import coop.tecso.demoda.buss.bean.BaseBO; import coop.tecso.demoda.iface.helper.DateUtil; /** * Bean correspondiente a Servicio Banco Descuentos Generales * * @author tecso */ @Entity @Table(name = "gde_serBanDesGen") public class SerBanDesGen extends BaseBO { private static final long serialVersionUID = 1L; @Column(name = "fechaDesde") private Date fechaDesde; @Column(name = "fechaHasta") private Date fechaHasta; @ManyToOne() @JoinColumn(name="idServicioBanco") private ServicioBanco servicioBanco; @ManyToOne() @JoinColumn(name="idDesGen") private DesGen desGen; //Constructores public SerBanDesGen(){ super(); } // Getters y Setters public Date getFechaDesde(){ return fechaDesde; } public void setFechaDesde(Date fechaDesde){ this.fechaDesde = fechaDesde; } public Date getFechaHasta(){ return fechaHasta; } public void setFechaHasta(Date fechaHasta){ this.fechaHasta = fechaHasta; } public ServicioBanco getServicioBanco(){ return servicioBanco; } public void setServicioBanco(ServicioBanco servicioBanco){ this.servicioBanco = servicioBanco; } public DesGen getDesGen(){ return desGen; } public void setDesGen(DesGen desGen){ this.desGen = desGen; } // Metodos de Clase public static SerBanDesGen getById(Long id) { return (SerBanDesGen) GdeDAOFactory.getSerBanDesGenDAO().getById(id); } public static SerBanDesGen getByIdNull(Long id) { return (SerBanDesGen) GdeDAOFactory.getSerBanDesGenDAO().getByIdNull(id); } public static List<SerBanDesGen> getList() { return (ArrayList<SerBanDesGen>) GdeDAOFactory.getSerBanDesGenDAO().getList(); } public static List<SerBanDesGen> getListActivos() { return (ArrayList<SerBanDesGen>) GdeDAOFactory.getSerBanDesGenDAO().getListActiva(); } // Metodos de Instancia // Validaciones /** * Valida la creacion * @author */ public boolean validateCreate() throws Exception{ //limpiamos la lista de errores clearError(); this.validate(); if (hasError()) { return false; } return !hasError(); } /** * Valida la actualizacion * @author */ public boolean validateUpdate() throws Exception{ //limpiamos la lista de errores clearError(); this.validate(); if (hasError()) { return false; } return !hasError(); } private boolean validate() throws Exception{ //limpiamos la lista de errores clearError(); //UniqueMap uniqueMap = new UniqueMap(); //Validaciones de Requeridos if (getServicioBanco()==null) { addRecoverableError(BaseError.MSG_CAMPO_REQUERIDO, GdeError.SERBANDESGEN_SERVICIOBANCO); } if (getDesGen()==null) { addRecoverableError(BaseError.MSG_CAMPO_REQUERIDO, GdeError.SERBANDESGEN_DESGEN); } if (getFechaDesde()==null) { addRecoverableError(BaseError.MSG_CAMPO_REQUERIDO, GdeError.SERBANDESGEN_FECHADESDE); } if (hasError()) { return false; } // Validaciones de Unicidad // Otras Validaciones // Valida que la Fecha Desde no sea mayor que la fecha Hasta if(!DateUtil.isDateBefore(this.fechaDesde, this.fechaHasta)){ addRecoverableError(BaseError.MSG_VALORMAYORQUE, DefError.SERBANREC_FECHADESDE, DefError.SERBANREC_FECHAHASTA); } return !hasError(); } /** * Valida la eliminacion * @author */ public boolean validateDelete() { //limpiamos la lista de errores clearError(); //Validaciones de VO if (hasError()) { return false; } // Validaciones de Negocio return true; } // Metodos de negocio }
gpl-3.0
stefan-niedermann/OwnCloud-Notes
app/src/main/java/it/niedermann/owncloud/notes/main/items/selection/ItemIdKeyProvider.java
1115
package it.niedermann.owncloud.notes.main.items.selection; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.selection.ItemKeyProvider; import androidx.recyclerview.widget.RecyclerView; import static androidx.recyclerview.widget.RecyclerView.NO_POSITION; public class ItemIdKeyProvider extends ItemKeyProvider<Long> { private final RecyclerView recyclerView; public ItemIdKeyProvider(RecyclerView recyclerView) { super(SCOPE_MAPPED); this.recyclerView = recyclerView; } @Nullable @Override public Long getKey(int position) { final RecyclerView.Adapter<?> adapter = recyclerView.getAdapter(); if (adapter == null) { throw new IllegalStateException("RecyclerView adapter is not set!"); } return adapter.getItemId(position); } @Override public int getPosition(@NonNull Long key) { final RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForItemId(key); return viewHolder == null ? NO_POSITION : viewHolder.getLayoutPosition(); } }
gpl-3.0
cunvoas/springsecurity_iam
iam-core/src/main/java/com/github/cunvoas/iam/persistance/entity/Valeur_.java
666
package com.github.cunvoas.iam.persistance.entity; import com.github.cunvoas.iam.persistance.entity.RessourceValeur; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.0.v20130507-rNA", date="2014-12-29T14:58:17") @StaticMetamodel(Valeur.class) public class Valeur_ { public static volatile SingularAttribute<Valeur, Integer> id; public static volatile SingularAttribute<Valeur, String> valeur; public static volatile ListAttribute<Valeur, RessourceValeur> ressourceValues; }
gpl-3.0
izstas/jpexs-decompiler
src/com/jpexs/decompiler/flash/gui/player/MediaDisplayListener.java
951
/* * Copyright (C) 2010-2015 JPEXS * * 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.jpexs.decompiler.flash.gui.player; /** * * @author JPEXS */ public interface MediaDisplayListener { void mediaDisplayStateChanged(MediaDisplay source); void playingFinished(MediaDisplay source); }
gpl-3.0