repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Rima-B/mica2
mica-core/src/main/java/org/obiba/mica/dataset/event/StudyDatasetIndexedEvent.java
403
/* * Copyright (c) 2017 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.obiba.mica.dataset.event; public class StudyDatasetIndexedEvent {}
gpl-3.0
theritty/twitterEventDetectionClustering
src/main/java/algorithms/CountCalculatorKeyBased.java
3430
package algorithms; import cassandraConnector.CassandraDaoKeyBased; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; public class CountCalculatorKeyBased { public HashMap<String, Long> addNewEntryToCassCounts(CassandraDaoKeyBased cassandraDao, long round, String word, String country) { long count=0L, allcount=0L; HashMap<String, Long> counts = new HashMap<>(); ResultSet resultSet2 ; try { resultSet2 = cassandraDao.getTweetsByRoundAndCountry(round, country); Iterator<Row> iterator2 = resultSet2.iterator(); while(iterator2.hasNext()) { Row row = iterator2.next(); String tweet = row.getString("tweet"); if(tweet == null || !row.getString("country").equals(country)) continue; String[] splittedList = tweet.split(" "); for(String s : splittedList) { allcount++; if ((s != null || s.length() > 0) && s.equals(word) ) { count++; } } } counts.put("count", count); counts.put("allcount", allcount); insertValuesToCass(cassandraDao, round, word, country, count, allcount); } catch (Exception e) { e.printStackTrace(); } return counts; } public HashMap<String, Double> getCountOfWord(CassandraDaoKeyBased cassandraDao, String word, long round, String country) { double count, allcount; HashMap<String, Double> hm = null; try { ResultSet resultSet =cassandraDao.getFromCounts(round, word, country); Iterator<Row> iterator = resultSet.iterator(); if (!iterator.hasNext()) { HashMap<String, Long> tmp = addNewEntryToCassCounts(cassandraDao, round, word, country); count = tmp.get("count"); allcount = tmp.get("allcount"); } else{ Row row = iterator.next(); if(row.getLong("count")<0 || row.getLong("totalnumofwords")<0 ) { HashMap<String, Long> tmp = addNewEntryToCassCounts(cassandraDao, round, word, country); count = tmp.get("count"); allcount = tmp.get("allcount"); } else { count = row.getLong("count"); allcount = row.getLong("totalnumofwords"); } } hm = new HashMap<>(); hm.put("count", count); hm.put("totalnumofwords", allcount); } catch (Exception e) { e.printStackTrace(); } return hm; } private void insertValuesToCass(CassandraDaoKeyBased cassandraDao, long round, String word, String country, long count, long allcount) { try { List<Object> values = new ArrayList<>(); values.add(round); values.add(word); values.add(country); values.add(count); values.add(allcount); cassandraDao.insertIntoCounts(values.toArray()); } catch (Exception e) { e.printStackTrace(); } } }
gpl-3.0
Borlea/EchoPet
modules/API/src/com/dsh105/echopet/compat/api/entity/type/pet/ISkeletonAbstractPet.java
838
/* * 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.api.entity.type.pet; import com.dsh105.echopet.compat.api.entity.IPet; public interface ISkeletonAbstractPet extends IPet{ }
gpl-3.0
opcode81/ProbCog
src/main/java/probcog/bayesnets/conversion/BNDB2ErgEvid.java
2601
/******************************************************************************* * Copyright (C) 2010 Paul Maier, Dominik Jain. * * This file is part of ProbCog. * * ProbCog 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. * * ProbCog 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 ProbCog. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package probcog.bayesnets.conversion; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Map.Entry; import edu.ksu.cis.bnj.ver3.core.Domain; import probcog.bayesnets.core.BNDatabase; import probcog.bayesnets.core.BeliefNetworkEx; import probcog.exception.ProbCogException; /** * converts a Bayesian network evidence database given in .bndb format to the Ergo evidence * format (.erg.evid) * @author Dominik Jain */ public class BNDB2ErgEvid { public static void main(String[] args) throws ProbCogException, FileNotFoundException { if (args.length != 5) { System.err.println("usage: bndb2ergevid <Bayesian network file> <.bndb file> <.erg.evid file to write to>"); return; } BeliefNetworkEx bn = new BeliefNetworkEx(args[0]); BNDatabase db = new BNDatabase(new File(args[1])); try (PrintStream out = new PrintStream(new File(args[2]))) { out.println("/* Evidence */"); out.println(db.size()); for(Entry<String,String> entry : db.getEntries()) { String varName = entry.getKey(); int nodeIdx = bn.getNodeIndex(varName); if(nodeIdx == -1) throw new ProbCogException("Node " + varName + " not found in Bayesian network"); Domain dom = bn.getNode(varName).getDomain(); String value = entry.getValue(); int domIdx = -1; for(int i = 0; i < dom.getOrder(); i++) { if(dom.getName(i).equals(value)) { domIdx = i; break; } } if(domIdx == -1) throw new ProbCogException("Value " + value + " not found in domain of " + varName); out.println(String.format(" %d %d", nodeIdx, domIdx)); } } } }
gpl-3.0
blynkkk/blynk-server
server/utils/src/main/java/cc/blynk/utils/structure/TableLimitedQueue.java
395
package cc.blynk.utils.structure; /** * * FIFO limited array. * * The Blynk Project. * Created by Dmitriy Dumanskiy. * Created on 07.09.16. */ public class TableLimitedQueue<T> extends BaseLimitedQueue<T> { private static final int POOL_SIZE = Integer.parseInt(System.getProperty("table.rows.pool.size", "100")); public TableLimitedQueue() { super(POOL_SIZE); } }
gpl-3.0
FuzzyAvacado/ECommerce
src/main/java/com/fuzzy/repository/AccountRepository.java
1125
package com.fuzzy.repository; import com.fuzzy.model.account.Account; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * Created by fuzzyavacado on 10/16/16. */ @Repository public interface AccountRepository extends CrudRepository<Account, Long> { Account findOneByUserName(String name); Account findOneByEmail(String email); Account findOneByUserNameOrEmail(String username, String email); Account findOneByToken(String token); @Modifying @Transactional @Query("update Account u set u.email = :email " + "where u.userName = :userName") int updateAccount(@Param("userName") String userName, @Param("email") String email); @Modifying @Transactional @Query("update Account u set u.lastLogin = CURRENT_TIMESTAMP where u.userName = ?1") int updateLastLogin(String userName); }
gpl-3.0
relinc/SurePulseDataProcessor
src/net/relinc/processor/controllers/WorkingDirectoryPromptController.java
874
package net.relinc.processor.controllers; import java.io.File; import javafx.fxml.FXML; import javafx.scene.control.TextField; import javafx.stage.Stage; public class WorkingDirectoryPromptController { @FXML TextField directoryNameTF; public SplashPageController parent; public File workingDirectory; @FXML public void createNewDirectoryButtonFired(){ File newDir = new File(workingDirectory.getPath() + "/" + directoryNameTF.getText()); newDir.mkdir(); workingDirectory = newDir; Stage stage = (Stage) directoryNameTF.getScene().getWindow(); stage.close(); } @FXML public void useSelectedDirectoryFired(){ Stage stage = (Stage) directoryNameTF.getScene().getWindow(); stage.close(); } @FXML public void cancelButtonFired(){ workingDirectory = null; Stage stage = (Stage) directoryNameTF.getScene().getWindow(); stage.close(); } }
gpl-3.0
Chyrain/MCSS2.x-libraries
IMInputExtension_simple/src/com/v5kf/client/ui/keyboard/AutoHeightLayout.java
5515
package com.v5kf.client.ui.keyboard; import com.chyrain.utils.Logger; import android.content.Context; import android.content.res.Configuration; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; public class AutoHeightLayout extends ResizeLayout implements ResizeLayout.OnResizeListener { private static final int ID_CHILD = 1; /** * 不显示 */ public static final int KEYBOARD_STATE_NONE = 100; /** * 显示表情、多媒体功能 */ public static final int KEYBOARD_STATE_FUNC = 102; /** * 显示键盘(覆盖表情、多媒体界面) */ public static final int KEYBOARD_STATE_BOTH = 103; protected Context mContext; protected int mAutoHeightLayoutId; protected int mAutoViewHeight; // 单位dp protected View mAutoHeightLayoutView; protected int mKeyboardState = KEYBOARD_STATE_NONE; private int mOrientation = 0; // 当前状态横竖屏 public AutoHeightLayout(Context context, AttributeSet attrs) { super(context, attrs); this.mContext = context; if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { mAutoViewHeight = Utils.getDefKeyboardHeight(mContext); } else if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { mAutoViewHeight = Utils.px2dip(context, Utils.getDisplayHeightPixels(context)/2 - 50); } // Logger.d("AutoHeoghtLayout", "orientation mAutoViewHeight(dp):" + mAutoViewHeight); setOnResizeListener(this); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { int childSum = getChildCount(); if (getChildCount() > 1) { throw new IllegalStateException("can host only one direct child"); } super.addView(child, index, params); if (childSum == 0) { mAutoHeightLayoutId = child.getId(); if (mAutoHeightLayoutId < 0) { child.setId(ID_CHILD); mAutoHeightLayoutId = ID_CHILD; } RelativeLayout.LayoutParams paramsChild = (LayoutParams) child.getLayoutParams(); paramsChild.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); child.setLayoutParams(paramsChild); } else if (childSum == 1) { RelativeLayout.LayoutParams paramsChild = (LayoutParams) child.getLayoutParams(); paramsChild.addRule(RelativeLayout.ABOVE, mAutoHeightLayoutId); child.setLayoutParams(paramsChild); } } public int getKeyboardState() { return mKeyboardState; } public void setAutoHeightLayoutView(View view) { mAutoHeightLayoutView = view; } /** * px * @param height px */ public void setAutoViewHeight(final int height) { Logger.w("AutoHeightLayout", "orientation setAutoViewHeight(dp):" + Utils.px2dip(getContext(), height)); int heightDp = Utils.px2dip(mContext, height); if (heightDp > 0 && heightDp != mAutoViewHeight) { mAutoViewHeight = heightDp; // TODO if (mOrientation == Configuration.ORIENTATION_PORTRAIT) { // 竖屏 Utils.setDefKeyboardHeight(mContext, mAutoViewHeight); //dp } } if (mAutoHeightLayoutView != null) { mAutoHeightLayoutView.setVisibility(View.VISIBLE); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mAutoHeightLayoutView.getLayoutParams(); params.height = height; mAutoHeightLayoutView.setLayoutParams(params); } } public void hideAutoView(){ this.post(new Runnable() { @Override public void run() { Utils.closeSoftKeyboard(mContext); setAutoViewHeight(0); if (mAutoHeightLayoutView != null) { mAutoHeightLayoutView.setVisibility(View.GONE); } } }); mKeyboardState = KEYBOARD_STATE_NONE ; } public void showAutoView(){ if (mAutoHeightLayoutView != null) { mAutoHeightLayoutView.setVisibility(VISIBLE); setAutoViewHeight(Utils.dip2px(mContext, mAutoViewHeight)); } mKeyboardState = mKeyboardState == KEYBOARD_STATE_NONE ? KEYBOARD_STATE_FUNC : KEYBOARD_STATE_BOTH ; } @Override public void OnSoftPop(final int height) { mKeyboardState = KEYBOARD_STATE_BOTH; post(new Runnable() { @Override public void run() { setAutoViewHeight(height); } }); } @Override public void OnSoftClose(int height) { mKeyboardState = mKeyboardState == KEYBOARD_STATE_BOTH ? KEYBOARD_STATE_FUNC : KEYBOARD_STATE_NONE ; } @Override public void OnSoftChanegHeight(final int height) { post(new Runnable() { @Override public void run() { setAutoViewHeight(height); } }); } // TODO public void setOrientation(int orientation) { this.mOrientation = orientation; } public int getOrientation() { return mOrientation; } }
gpl-3.0
JavierNicolas/JadaMusic
core-library/src/main/java/org/opensilk/music/library/compare/ArtistCompare.java
2488
/* * Copyright (c) 2015 OpenSilk Productions LLC * * 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.opensilk.music.library.compare; import org.opensilk.music.library.sort.ArtistSortOrder; import org.opensilk.music.model.Artist; import java.util.Comparator; import rx.functions.Func2; /** * Created by drew on 4/26/15. */ public class ArtistCompare { public static Func2<Artist, Artist, Integer> func(final String sort) { return new Func2<Artist, Artist, Integer>() { @Override public Integer call(Artist artist, Artist artist2) { return comparator(sort).compare(artist, artist2); } }; } public static Comparator<Artist> comparator(String sort) { switch (sort) { case ArtistSortOrder.MOST_TRACKS: return new Comparator<Artist>() { @Override public int compare(Artist lhs, Artist rhs) { //reversed int c = rhs.trackCount - lhs.trackCount; if (c == 0) { return BundleableCompare.compareNameAZ(lhs, rhs); } return c; } }; case ArtistSortOrder.MOST_ALBUMS: return new Comparator<Artist>() { @Override public int compare(Artist lhs, Artist rhs) { //reversed int c = rhs.albumCount - lhs.albumCount; if (c == 0) { return BundleableCompare.compareNameAZ(lhs, rhs); } return c; } }; default: return BundleableCompare.comparator(sort); } } }
gpl-3.0
kite1988/famf
src/data/Tweet.java
2353
package data; import java.io.Serializable; import java.util.HashMap; import java.util.Map.Entry; public class Tweet implements Serializable { private static final long serialVersionUID = -476493665475018739L; public String tid = null; // twitter id public int id = -1; // internal id public int[] textUnique = null; public short[] visualUnique = null; public short[] visualFreq = null, textFreq = null; public int textLength = 0; public int visualLength = 0; public Tweet() { } public Tweet(Tweet t) { } public Tweet(String tid, int id, String[] textStr, String[] visualStr) { this(tid, id); setText(textStr); setVisual(visualStr); } public Tweet(String tid, int id) { this.tid = tid; this.id = id; } public void setText(String[] textStr) { HashMap<Integer, Short> textMap = new HashMap<Integer, Short>(); textLength = textStr.length; for (String w : textStr) { int wid = Integer.parseInt(w); Short count = textMap.get(wid); if (count == null) { count = 0; } count++; textMap.put(wid, count); } textUnique = new int[textMap.size()]; textFreq = new short[textMap.size()]; int idx = 0; for (Entry<Integer, Short> entry : textMap.entrySet()) { textUnique[idx] = entry.getKey(); textFreq[idx] = entry.getValue(); idx++; } } // for missing value public void setText(int wid) { HashMap<Integer, Short> textMap = new HashMap<Integer, Short>(); textLength = 1; textMap.put(Integer.valueOf(wid), Short.valueOf("1")); textUnique = new int[textMap.size()]; textFreq = new short[textMap.size()]; int idx = 0; for (Entry<Integer, Short> entry : textMap.entrySet()) { textUnique[idx] = entry.getKey(); textFreq[idx] = entry.getValue(); idx++; } } public void setVisual(String[] textStr) { HashMap<Short, Short> visualMap = new HashMap<Short, Short>(); visualLength = textStr.length; for (String w : textStr) { short wid = Short.parseShort(w); Short count = visualMap.get(wid); if (count == null) { count = 0; } count++; visualMap.put(wid, count); } visualUnique = new short[visualMap.size()]; visualFreq = new short[visualMap.size()]; int idx = 0; for (Entry<Short, Short> entry : visualMap.entrySet()) { visualUnique[idx] = entry.getKey(); visualFreq[idx] = entry.getValue(); idx++; } } }
gpl-3.0
Booksonic-Server/madsonic-main
src/main/java/org/madsonic/controller/GroupSettingsController.java
4598
/* This file is part of Madsonic. Madsonic 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. Madsonic 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 Madsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2009-2016 (C) Sindre Mehus, Martin Karel */ package org.madsonic.controller; import org.madsonic.domain.Group; import org.madsonic.domain.User; import org.madsonic.domain.UserSettings; import org.madsonic.service.SecurityService; import org.madsonic.service.SettingsService; import org.madsonic.util.CustomTheme; import org.apache.commons.lang.StringUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.ParameterizableViewController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Controller for the page used to administrate the set of internet radio/tv stations. * * @author Sindre Mehus, Martin Karel */ public class GroupSettingsController extends ParameterizableViewController { private SettingsService settingsService; private SecurityService securityService; @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); if (isFormSubmission(request)) { String error = handleParameters(request); map.put("error", error); if (error == null) { map.put("reload", true); map.put("toast", true); } } ModelAndView result = super.handleRequestInternal(request, response); map.put("groups", securityService.GetAllGroups()); User activeUser = securityService.getCurrentUser(request); UserSettings activeUserSettings = settingsService.getUserSettings(activeUser.getUsername()); map.put("customScrollbar", activeUserSettings.isCustomScrollbarEnabled()); map.put("customScrollbarTheme", CustomTheme.setCustomTheme(activeUserSettings.getThemeId() == null ? settingsService.getThemeId() : activeUserSettings.getThemeId())); result.addObject("model", map); return result; } /** * Determine if the given request represents a form submission. * * @param request current HTTP request * @return if the request represents a form submission */ private boolean isFormSubmission(HttpServletRequest request) { return "POST".equals(request.getMethod()); } private String handleParameters(HttpServletRequest request) { List<Group> groups = securityService.GetAllGroups(); for (Group group: groups) { Integer id = group.getId(); String name = getParameter(request, "name", id); boolean delete = getParameter(request, "delete", id) != null; // Integer audioDefaultBitrate = Integer.parseInt(getParameter(request, "audioDefaultBitrate", id)) ; // Integer videoDefaultBitrate = Integer.parseInt(getParameter(request, "videoDefaultBitrate", id)) ; // Integer audioMaxBitrate = Integer.parseInt(getParameter(request, "audioMaxBitrate", id)) ; // Integer videoMaxBitrate = Integer.parseInt(getParameter(request, "videoMaxBitrate", id)) ; if (delete) { try { securityService.deleteGroup(group); } catch (Exception e) { return " warning: constraint violation - group has member "; } } else { // securityService.updateGroup(new Group(id, name, audioDefaultBitrate, audioMaxBitrate, videoDefaultBitrate, videoMaxBitrate)); securityService.updateGroup(new Group(id, name, 0, 0, 1000, 5000)); } } String name = StringUtils.trimToNull(request.getParameter("name")); if (name != null) { securityService.createGroup(new Group(name)); } return null; } private String getParameter(HttpServletRequest request, String name, Integer id) { return StringUtils.trimToNull(request.getParameter(name + "[" + id + "]")); } public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } public void setSettingsService(SettingsService settingsService) { this.settingsService = settingsService; } }
gpl-3.0
totient/brief
src/main/java/totient/brief/util/KeyGeneratr.java
2071
package totient.brief.util; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public enum KeyGeneratr { KEY_GEN; public final char[] DIC_62 = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; private final long BASE = DIC_62.length; private final SecureRandom SEC_RAND = new SecureRandom(); public String generateKey() { long value = SEC_RAND.nextLong(); value *= (value < 0) ? -1 : 1; List<Character> seq = new ArrayList<>(); int exponent = 1; long remaining = value; while (remaining != 0L) { long a = (long) Math.pow(BASE, exponent); long b = remaining % a; long c = (long) Math.pow(BASE, exponent - 1); int d = (int) (b/c); seq.add(DIC_62[d]); remaining = remaining - b; exponent++; } return "_"+reverse(format(seq)); } private List<Character> format(List<Character> seq) { Random rand = ThreadLocalRandom.current(); int n; int[] inds = new int[3]; n = rand.nextInt((999 - 102) + 1) + 102; inds[0] = n / 100; int temp = n % 100; inds[1] = temp / 10; inds[2] = temp % 10; Arrays.sort(inds); char c = (seq.size()> inds[2]) ? seq.remove(inds[2]) : seq.remove(seq.size()-1); c = (seq.size()> inds[1]) ? seq.remove(inds[1]) : seq.remove(seq.size()-1); c = (seq.size()> inds[0]) ? seq.remove(inds[0]) : seq.remove(seq.size()-1); return seq; } private String reverse(List<Character> seq) { StringBuilder sb = new StringBuilder(); for (int i = seq.size() - 1; i >= 0; i--) { sb.append(seq.get(i)); } return sb.deleteCharAt(0).toString(); } }
gpl-3.0
psnc-dl/darceo
wrdz/wrdz-ms/entity/src/main/java/pl/psnc/synat/wrdz/ms/entity/messages/InternalMessage.java
3092
/** * Copyright 2015 Poznań Supercomputing and Networking Center * * Licensed under the GNU General Public License, Version 3.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/gpl-3.0.txt * * 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 pl.psnc.synat.wrdz.ms.entity.messages; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import pl.psnc.synat.wrdz.ms.types.InternalMessageType; /** * Represents a WRDZ internal message. */ @Entity @Table(name = "MS_INTERNAL_MESSAGES", schema = "darceo") public class InternalMessage implements Serializable { /** Serial version UID. */ private static final long serialVersionUID = -8096808523757148022L; /** Primary id. */ @Id @SequenceGenerator(name = "msInternalMessageSequenceGenerator", sequenceName = "darceo.MS_IM_ID_SEQ", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "msInternalMessageSequenceGenerator") @Column(name = "IM_ID", unique = true, nullable = false) private long id; /** Message origin. */ @Column(name = "IM_ORIGIN", length = 255, nullable = false) private String origin; /** The date the message was received on. */ @Temporal(TemporalType.TIMESTAMP) @Column(name = "IM_RECEIVED_ON", nullable = false) private Date receivedOn; /** Message type. */ @Enumerated(EnumType.STRING) @Column(name = "IM_TYPE", length = 35, nullable = false) private InternalMessageType type; /** Message data. */ @Column(name = "IM_DATA", length = 65535, nullable = false) private String data; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public Date getReceivedOn() { return receivedOn; } public void setReceivedOn(Date receivedOn) { this.receivedOn = receivedOn; } public InternalMessageType getType() { return type; } public void setType(InternalMessageType type) { this.type = type; } public String getData() { return data; } public void setData(String data) { this.data = data; } }
gpl-3.0
Mapleroid/cm-server
server-5.11.0.src/com/cloudera/enterprise/alertpublisher/InternalAlertPublisherAPIProxy.java
1722
package com.cloudera.enterprise.alertpublisher; import com.cloudera.enterprise.alertpublisher.avro.AvroInternalAlertPublisherAPI; import java.io.IOException; import java.net.URL; import org.apache.avro.ipc.HttpTransceiver; import org.apache.avro.ipc.specific.SpecificRequestor; import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class InternalAlertPublisherAPIProxy { private static final Logger LOG = LoggerFactory.getLogger(InternalAlertPublisherAPIProxy.class); private static final String DEFAULT_TIMEOUT = "alertpublisher.timeout"; private static final Duration timeout = Duration.standardSeconds(getSystemPropertyAsInt("alertpublisher.timeout", 5)); public final AvroInternalAlertPublisherAPI getClient(URL url) throws IOException { try { HttpTransceiver transceiver = new HttpTransceiver(url); SpecificRequestor requestor = new SpecificRequestor(AvroInternalAlertPublisherAPI.class, transceiver); AvroInternalAlertPublisherAPI client = (AvroInternalAlertPublisherAPI)SpecificRequestor.getClient(AvroInternalAlertPublisherAPI.class, requestor); LOG.debug("Opened connection to alert publisher: {}", url); return new TimeoutInternalAlertPublisherAPI(transceiver, client, timeout); } catch (IOException ioe) { LOG.error("Failed to connect to alert publisher: {}", url); }throw ioe; } private static int getSystemPropertyAsInt(String key, int defaultVal) { String val = System.getProperty(key); if (val != null) try { return Integer.parseInt(val); } catch (NumberFormatException ignored) { } return defaultVal; } }
gpl-3.0
Prasannasaraf/HadoopLab
Lab1/com.company.name/MaxMonthTemp.java
1262
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; public class MaxMonthTemp { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] programArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (programArgs.length != 2) { System.err.println("Usage: MaxTemp <in> <out>"); System.exit(2); } Job job = Job.getInstance(conf, "Monthly Max Temp"); job.setJarByClass(MaxMonthTemp.class); job.setMapperClass(MaxTempMapper.class); job.setCombinerClass(MaxTempReducer.class); job.setReducerClass(MaxTempReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(programArgs[0])); FileOutputFormat.setOutputPath(job, new Path(programArgs[1])); // Submit the job and wait for it to finish. System.exit(job.waitForCompletion(true) ? 0 : 1); } }
gpl-3.0
ursfassler/rizzly
src/ast/data/statement/CaseOpt.java
1266
/** * This file is part of Rizzly. * * Rizzly 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. * * Rizzly 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 Rizzly. If not, see <http://www.gnu.org/licenses/>. */ package ast.data.statement; import ast.data.AstBase; import ast.data.AstList; import ast.meta.SourcePosition; final public class CaseOpt extends AstBase { final public AstList<CaseOptEntry> value; public Block code; public CaseOpt(AstList<CaseOptEntry> value, Block code) { this.value = value; this.code = code; } @Deprecated public CaseOpt(SourcePosition info, AstList<CaseOptEntry> value, Block code) { metadata().add(info); this.value = value; this.code = code; } @Override public String toString() { return value.toString(); } }
gpl-3.0
TonyClark/ESL
src/ast/data/Int.java
1088
package ast.data; import java.util.HashSet; import ast.general.AST; import ast.types.Type; import compiler.DynamicVar; import compiler.FrameVar; import env.Env; import exp.BoaConstructor; import list.List; import runtime.functions.CodeBox; @BoaConstructor(fields = { "value" }) public class Int extends AST { public int value; public Int() { } public Int(int value) { super(); this.value = value; } public String toString() { return Integer.toString(value); } public void compile(List<FrameVar> locals, List<DynamicVar> dynamics, CodeBox code, boolean isLast) { code.add(new instrs.data.Int(getLineStart(), value), locals, dynamics); } public void FV(HashSet<String> vars) { } public void DV(HashSet<String> vars) { } public int maxLocals() { return 0; } public AST subst(AST ast, String name) { return this; } public void setPath(String path) { } public Type type(Env<String, Type> env) { setType(ast.types.Int.INT); return getType(); } public String getLabel() { return value + ""; } }
gpl-3.0
ACC-GIT/ACCAndroid
src/main/java/com/acc/android/util/scan/camera/CameraConfigurationManager.java
9236
/** * * ACCAndroid - ACC Android Development Platform * Copyright (c) 2014, AfirSraftGarrier, afirsraftgarrier@qq.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.acc.android.util.scan.camera; import java.util.regex.Pattern; import android.content.Context; import android.graphics.Point; import android.hardware.Camera; import android.os.Build; import android.util.Log; import android.view.Display; import android.view.WindowManager; final class CameraConfigurationManager { private static final String TAG = CameraConfigurationManager.class .getSimpleName(); private static final int TEN_DESIRED_ZOOM = 27; private static final int DESIRED_SHARPNESS = 30; private static final Pattern COMMA_PATTERN = Pattern.compile(","); private final Context context; private Point screenResolution; private Point cameraResolution; private int previewFormat; private String previewFormatString; CameraConfigurationManager(Context context) { this.context = context; } /** * Reads, one time, values from the camera that are needed by the app. */ void initFromCameraParameters(Camera camera) { Camera.Parameters parameters = camera.getParameters(); previewFormat = parameters.getPreviewFormat(); previewFormatString = parameters.get("preview-format"); Log.d(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString); WindowManager manager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); screenResolution = new Point(display.getWidth(), display.getHeight()); Log.d(TAG, "Screen resolution: " + screenResolution); cameraResolution = getCameraResolution(parameters, screenResolution); Log.d(TAG, "Camera resolution: " + screenResolution); } /** * Sets the camera up to take preview images which are used for both preview * and decoding. We detect the preview format here so that * buildLuminanceSource() can build an appropriate LuminanceSource subclass. * In the future we may want to force YUV420SP as it's the smallest, and the * planar Y can be used for barcode scanning without a copy in some cases. */ void setDesiredCameraParameters(Camera camera) { Camera.Parameters parameters = camera.getParameters(); Log.d(TAG, "Setting preview size: " + cameraResolution); parameters.setPreviewSize(cameraResolution.x, cameraResolution.y); setFlash(parameters); setZoom(parameters); // setSharpness(parameters); camera.setParameters(parameters); } Point getCameraResolution() { return cameraResolution; } Point getScreenResolution() { return screenResolution; } int getPreviewFormat() { return previewFormat; } String getPreviewFormatString() { return previewFormatString; } private static Point getCameraResolution(Camera.Parameters parameters, Point screenResolution) { String previewSizeValueString = parameters.get("preview-size-values"); // saw this on Xperia if (previewSizeValueString == null) { previewSizeValueString = parameters.get("preview-size-value"); } Point cameraResolution = null; if (previewSizeValueString != null) { Log.d(TAG, "preview-size-values parameter: " + previewSizeValueString); cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution); } if (cameraResolution == null) { // Ensure that the camera resolution is a multiple of 8, as the // screen may not be. cameraResolution = new Point((screenResolution.x >> 3) << 3, (screenResolution.y >> 3) << 3); } return cameraResolution; } private static Point findBestPreviewSizeValue( CharSequence previewSizeValueString, Point screenResolution) { int bestX = 0; int bestY = 0; int diff = Integer.MAX_VALUE; for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) { previewSize = previewSize.trim(); int dimPosition = previewSize.indexOf('x'); if (dimPosition < 0) { Log.w(TAG, "Bad preview-size: " + previewSize); continue; } int newX; int newY; try { newX = Integer.parseInt(previewSize.substring(0, dimPosition)); newY = Integer.parseInt(previewSize.substring(dimPosition + 1)); } catch (NumberFormatException nfe) { Log.w(TAG, "Bad preview-size: " + previewSize); continue; } int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y); if (newDiff == 0) { bestX = newX; bestY = newY; break; } else if (newDiff < diff) { bestX = newX; bestY = newY; diff = newDiff; } } if (bestX > 0 && bestY > 0) { return new Point(bestX, bestY); } return null; } private static int findBestMotZoomValue(CharSequence stringValues, int tenDesiredZoom) { int tenBestValue = 0; for (String stringValue : COMMA_PATTERN.split(stringValues)) { stringValue = stringValue.trim(); double value; try { value = Double.parseDouble(stringValue); } catch (NumberFormatException nfe) { return tenDesiredZoom; } int tenValue = (int) (10.0 * value); if (Math.abs(tenDesiredZoom - value) < Math.abs(tenDesiredZoom - tenBestValue)) { tenBestValue = tenValue; } } return tenBestValue; } private void setFlash(Camera.Parameters parameters) { // FIXME: This is a hack to turn the flash off on the Samsung Galaxy. // And this is a hack-hack to work around a different value on the // Behold II // Restrict Behold II check to Cupcake, per Samsung's advice // if (Build.MODEL.contains("Behold II") && // CameraManager.SDK_INT == Build.VERSION_CODES.CUPCAKE) { if (Build.MODEL.contains("Behold II") && CameraManager.SDK_INT == 3) { // 3 // = // Cupcake parameters.set("flash-value", 1); } else { parameters.set("flash-value", 2); } // This is the standard setting to turn the flash off that all devices // should honor. parameters.set("flash-mode", "off"); } private void setZoom(Camera.Parameters parameters) { String zoomSupportedString = parameters.get("zoom-supported"); if (zoomSupportedString != null && !Boolean.parseBoolean(zoomSupportedString)) { return; } int tenDesiredZoom = TEN_DESIRED_ZOOM; String maxZoomString = parameters.get("max-zoom"); if (maxZoomString != null) { try { int tenMaxZoom = (int) (10.0 * Double .parseDouble(maxZoomString)); if (tenDesiredZoom > tenMaxZoom) { tenDesiredZoom = tenMaxZoom; } } catch (NumberFormatException nfe) { Log.w(TAG, "Bad max-zoom: " + maxZoomString); } } String takingPictureZoomMaxString = parameters .get("taking-picture-zoom-max"); if (takingPictureZoomMaxString != null) { try { int tenMaxZoom = Integer.parseInt(takingPictureZoomMaxString); if (tenDesiredZoom > tenMaxZoom) { tenDesiredZoom = tenMaxZoom; } } catch (NumberFormatException nfe) { Log.w(TAG, "Bad taking-picture-zoom-max: " + takingPictureZoomMaxString); } } String motZoomValuesString = parameters.get("mot-zoom-values"); if (motZoomValuesString != null) { tenDesiredZoom = findBestMotZoomValue(motZoomValuesString, tenDesiredZoom); } String motZoomStepString = parameters.get("mot-zoom-step"); if (motZoomStepString != null) { try { double motZoomStep = Double.parseDouble(motZoomStepString .trim()); int tenZoomStep = (int) (10.0 * motZoomStep); if (tenZoomStep > 1) { tenDesiredZoom -= tenDesiredZoom % tenZoomStep; } } catch (NumberFormatException nfe) { // continue } } // Set zoom. This helps encourage the user to pull back. // Some devices like the Behold have a zoom parameter if (maxZoomString != null || motZoomValuesString != null) { parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0)); } // Most devices, like the Hero, appear to expose this zoom parameter. // It takes on values like "27" which appears to mean 2.7x zoom if (takingPictureZoomMaxString != null) { parameters.set("taking-picture-zoom", tenDesiredZoom); } } /* * private void setSharpness(Camera.Parameters parameters) { * * int desiredSharpness = DESIRED_SHARPNESS; * * String maxSharpnessString = parameters.get("sharpness-max"); if * (maxSharpnessString != null) { try { int maxSharpness = * Integer.parseInt(maxSharpnessString); if (desiredSharpness > * maxSharpness) { desiredSharpness = maxSharpness; } } catch * (NumberFormatException nfe) { Log.w(TAG, "Bad sharpness-max: " + * maxSharpnessString); } } * * parameters.set("sharpness", desiredSharpness); } */ }
gpl-3.0
DiscoveryGroup/bmvis2
src/main/java/biomine/nodeimportancecompression/ImportanceGraphWrapper.java
2372
/* * Copyright 2012 University of Helsinki. * * This file is part of BMVis². * * BMVis² is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * BMVis² is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BMVis². If not, see * <http://www.gnu.org/licenses/>. */ package biomine.nodeimportancecompression; import java.util.HashMap; import biomine.bmgraph.BMEdge; import biomine.bmgraph.BMGraph; import biomine.bmgraph.BMNode; public class ImportanceGraphWrapper { private BMGraph bmgraph; private ImportanceGraph importanceGraph; private BMNode[] iToNode; private HashMap<BMNode, Integer> nodeToI; public BMGraph getBMGraph(){ return bmgraph; } public ImportanceGraph getImportanceGraph(){ return importanceGraph; } public ImportanceGraphWrapper(BMGraph bm) { bmgraph = bm; iToNode = new BMNode[bm.getNodes().size()]; nodeToI = new HashMap<BMNode, Integer>(); importanceGraph = new ImportanceGraph(); int it = 0; for (BMNode n : bm.getNodes()) { nodeToI.put(n, it); iToNode[it++] = n; } for (BMEdge e : bm.getEdges()) { int u = nodeToI.get(e.getFrom()); int v = nodeToI.get(e.getTo()); String gs = e.get("goodness"); if(gs!=null){ double g = Double.parseDouble(gs); if(g > importanceGraph.getEdgeWeight(u,v)){ importanceGraph.addEdge(u, v, g); } } } } public void setImportance(int node,double imp){ importanceGraph.setImportance(node, imp); } public double getImportance(int node){ return importanceGraph.getImportance(node); } public int nodeToInt(BMNode nod){ return nodeToI.get(nod); } public BMNode intToNode(int i){ return iToNode[i]; } public void setImportance(BMNode nod,double imp){ setImportance(nodeToInt(nod), imp); } public double getImportance(BMNode nod){ return getImportance(nodeToInt(nod)); } }
gpl-3.0
Konloch/BitPlus
src/me/themallard/bitmmo/impl/analysis/DebugOverlayAnalyser.java
1273
package me.themallard.bitmmo.impl.analysis; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.MethodNode; import me.themallard.bitmmo.api.analysis.Builder; import me.themallard.bitmmo.api.analysis.ClassAnalyser; import me.themallard.bitmmo.api.analysis.IFieldAnalyser; import me.themallard.bitmmo.api.analysis.IMethodAnalyser; import me.themallard.bitmmo.api.analysis.SupportedHooks; @SupportedHooks(fields = {}, methods = {}) public class DebugOverlayAnalyser extends ClassAnalyser { private String className; public DebugOverlayAnalyser() { super("DebugOverlay"); } @Override protected boolean matches(ClassNode cn) { if (className == null) { for (MethodNode mn : cn.methods) { for (AbstractInsnNode ain : mn.instructions.toArray()) { if (ain instanceof LdcInsnNode) { if (((LdcInsnNode) ain).cst.toString() .equals(" / Ping: ")) { className = cn.name; return true; } } } } } return false; } @Override protected Builder<IFieldAnalyser> registerFieldAnalysers() { return null; } @Override protected Builder<IMethodAnalyser> registerMethodAnalysers() { return null; } }
gpl-3.0
PapenfussLab/PathOS
Tools/Hl7Tools/src/main/java/org/petermac/hl7/model/v251/message/ROR_ROR.java
11566
/* * This class is an auto-generated source file for a HAPI * HL7 v2.x standard structure class. * * For more information, visit: http://hl7api.sourceforge.net/ * * The contents of this file are subject to the Mozilla Public License Version 1.1 * (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.mozilla.org/MPL/ * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the * specific language governing rights and limitations under the License. * * The Original Code is "[file_name]". Description: * "[one_line_description]" * * The Initial Developer of the Original Code is University Health Network. Copyright (C) * 2012. All Rights Reserved. * * Contributor(s): ______________________________________. * * Alternatively, the contents of this file may be used under the terms of the * GNU General Public License (the "GPL"), in which case the provisions of the GPL are * applicable instead of those above. If you wish to allow use of your version of this * file only under the terms of the GPL and not to allow others to use your version * of this file under the MPL, indicate your decision by deleting the provisions above * and replace them with the notice and other provisions required by the GPL License. * If you do not delete the provisions above, a recipient may use your version of * this file under either the MPL or the GPL. * */ package org.petermac.hl7.model.v251.message; import org.petermac.hl7.model.v251.group.*; import org.petermac.hl7.model.v251.segment.*; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.parser.ModelClassFactory; import ca.uhn.hl7v2.parser.DefaultModelClassFactory; import ca.uhn.hl7v2.model.*; /** * <p>Represents a ROR_ROR message structure (see chapter 4.13.15). This structure contains the * following elements: </p> * <ul> * <li>1: MSH (Message Header) <b> </b> </li> * <li>2: MSA (Message Acknowledgment) <b> </b> </li> * <li>3: ERR (Error) <b>optional repeating</b> </li> * <li>4: SFT (Software Segment) <b>optional repeating</b> </li> * <li>5: ROR_ROR_DEFINITION (a Group object) <b> repeating</b> </li> * <li>6: DSC (Continuation Pointer) <b>optional </b> </li> * </ul> */ //@SuppressWarnings("unused") public class ROR_ROR extends AbstractMessage { /** * Creates a new ROR_ROR message with DefaultModelClassFactory. */ public ROR_ROR() { this(new DefaultModelClassFactory()); } /** * Creates a new ROR_ROR message with custom ModelClassFactory. */ public ROR_ROR(ModelClassFactory factory) { super(factory); init(factory); } private void init(ModelClassFactory factory) { try { this.add(MSH.class, true, false); this.add(MSA.class, true, false); this.add(ERR.class, false, true); this.add(SFT.class, false, true); this.add(ROR_ROR_DEFINITION.class, true, true); this.add(DSC.class, false, false); } catch(HL7Exception e) { log.error("Unexpected error creating ROR_ROR - this is probably a bug in the source code generator.", e); } } /** * Returns "2.5.1" */ public String getVersion() { return "2.5.1"; } /** * <p> * Returns * MSH (Message Header) - creates it if necessary * </p> * * */ public MSH getMSH() { return getTyped("MSH", MSH.class); } /** * <p> * Returns * MSA (Message Acknowledgment) - creates it if necessary * </p> * * */ public MSA getMSA() { return getTyped("MSA", MSA.class); } /** * <p> * Returns * the first repetition of * ERR (Error) - creates it if necessary * </p> * * */ public ERR getERR() { return getTyped("ERR", ERR.class); } /** * <p> * Returns a specific repetition of * ERR (Error) - creates it if necessary * </p> * * * @param rep The repetition index (0-indexed, i.e. the first repetition is at index 0) * @throws HL7Exception if the repetition requested is more than one * greater than the number of existing repetitions. */ public ERR getERR(int rep) { return getTyped("ERR", rep, ERR.class); } /** * <p> * Returns the number of existing repetitions of ERR * </p> * */ public int getERRReps() { return getReps("ERR"); } /** * <p> * Returns a non-modifiable List containing all current existing repetitions of ERR. * <p> * <p> * Note that unlike {@link #getERR()}, this method will not create any reps * if none are already present, so an empty list may be returned. * </p> * */ public java.util.List<ERR> getERRAll() throws HL7Exception { return getAllAsList("ERR", ERR.class); } /** * <p> * Inserts a specific repetition of ERR (Error) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public void insertERR(ERR structure, int rep) throws HL7Exception { super.insertRepetition( "ERR", structure, rep); } /** * <p> * Inserts a specific repetition of ERR (Error) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public ERR insertERR(int rep) throws HL7Exception { return (ERR)super.insertRepetition("ERR", rep); } /** * <p> * Removes a specific repetition of ERR (Error) * </p> * * * @see AbstractGroup#removeRepetition(String, int) */ public ERR removeERR(int rep) throws HL7Exception { return (ERR)super.removeRepetition("ERR", rep); } /** * <p> * Returns * the first repetition of * SFT (Software Segment) - creates it if necessary * </p> * * */ public SFT getSFT() { return getTyped("SFT", SFT.class); } /** * <p> * Returns a specific repetition of * SFT (Software Segment) - creates it if necessary * </p> * * * @param rep The repetition index (0-indexed, i.e. the first repetition is at index 0) * @throws HL7Exception if the repetition requested is more than one * greater than the number of existing repetitions. */ public SFT getSFT(int rep) { return getTyped("SFT", rep, SFT.class); } /** * <p> * Returns the number of existing repetitions of SFT * </p> * */ public int getSFTReps() { return getReps("SFT"); } /** * <p> * Returns a non-modifiable List containing all current existing repetitions of SFT. * <p> * <p> * Note that unlike {@link #getSFT()}, this method will not create any reps * if none are already present, so an empty list may be returned. * </p> * */ public java.util.List<SFT> getSFTAll() throws HL7Exception { return getAllAsList("SFT", SFT.class); } /** * <p> * Inserts a specific repetition of SFT (Software Segment) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public void insertSFT(SFT structure, int rep) throws HL7Exception { super.insertRepetition( "SFT", structure, rep); } /** * <p> * Inserts a specific repetition of SFT (Software Segment) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public SFT insertSFT(int rep) throws HL7Exception { return (SFT)super.insertRepetition("SFT", rep); } /** * <p> * Removes a specific repetition of SFT (Software Segment) * </p> * * * @see AbstractGroup#removeRepetition(String, int) */ public SFT removeSFT(int rep) throws HL7Exception { return (SFT)super.removeRepetition("SFT", rep); } /** * <p> * Returns * the first repetition of * DEFINITION (a Group object) - creates it if necessary * </p> * * */ public ROR_ROR_DEFINITION getDEFINITION() { return getTyped("DEFINITION", ROR_ROR_DEFINITION.class); } /** * <p> * Returns a specific repetition of * DEFINITION (a Group object) - creates it if necessary * </p> * * * @param rep The repetition index (0-indexed, i.e. the first repetition is at index 0) * @throws HL7Exception if the repetition requested is more than one * greater than the number of existing repetitions. */ public ROR_ROR_DEFINITION getDEFINITION(int rep) { return getTyped("DEFINITION", rep, ROR_ROR_DEFINITION.class); } /** * <p> * Returns the number of existing repetitions of DEFINITION * </p> * */ public int getDEFINITIONReps() { return getReps("DEFINITION"); } /** * <p> * Returns a non-modifiable List containing all current existing repetitions of DEFINITION. * <p> * <p> * Note that unlike {@link #getDEFINITION()}, this method will not create any reps * if none are already present, so an empty list may be returned. * </p> * */ public java.util.List<ROR_ROR_DEFINITION> getDEFINITIONAll() throws HL7Exception { return getAllAsList("DEFINITION", ROR_ROR_DEFINITION.class); } /** * <p> * Inserts a specific repetition of DEFINITION (a Group object) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public void insertDEFINITION(ROR_ROR_DEFINITION structure, int rep) throws HL7Exception { super.insertRepetition( "DEFINITION", structure, rep); } /** * <p> * Inserts a specific repetition of DEFINITION (a Group object) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public ROR_ROR_DEFINITION insertDEFINITION(int rep) throws HL7Exception { return (ROR_ROR_DEFINITION)super.insertRepetition("DEFINITION", rep); } /** * <p> * Removes a specific repetition of DEFINITION (a Group object) * </p> * * * @see AbstractGroup#removeRepetition(String, int) */ public ROR_ROR_DEFINITION removeDEFINITION(int rep) throws HL7Exception { return (ROR_ROR_DEFINITION)super.removeRepetition("DEFINITION", rep); } /** * <p> * Returns * DSC (Continuation Pointer) - creates it if necessary * </p> * * */ public DSC getDSC() { return getTyped("DSC", DSC.class); } }
gpl-3.0
Gabr1el94/FinanceiroWeb
ePaperWeb/src/java/MVC/classes/Movimentacao.java
3672
/* * 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 MVC.classes; import java.io.Serializable; import java.util.Calendar; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; /** * * @author gabriel */ @Entity public class Movimentacao implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Cascade(CascadeType.ALL) @Column(name = "idMovimentacao", insertable = true, updatable = true) private int id; private boolean status; @Temporal(TemporalType.DATE) @Column(insertable = true, updatable = true, nullable = false) private Calendar dataEmissao = Calendar.getInstance(); @Column(name = "Descricao", insertable = true, updatable = true, nullable = false, length = 40) private String descricao; @Column(name = "Categoria", insertable = true, updatable = true, nullable = false, length = 10) private String categoria; @Column(name = "Valor", insertable = true, updatable = true, nullable = false, scale = 2) private double valor; @Column(insertable = true, updatable = true, nullable = true) private String tipo; @ManyToOne @JoinColumn(name = "idGerente", referencedColumnName = "idPessoa", nullable = true, insertable = true, updatable = true, unique = false) @Cascade(CascadeType.ALL) private Gerente gerente; public Movimentacao() { } public Movimentacao(boolean status, Calendar dataEmissao, String descricao, String categoria, float valor) { this.status = status; this.dataEmissao = dataEmissao; this.descricao = descricao; this.categoria = categoria; this.valor = valor; this.gerente = gerente; } public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public Calendar getDataEmissao() { return dataEmissao; } public void setDataEmissao(Calendar dataEmissao) { this.dataEmissao = dataEmissao; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public String getCategoria() { return categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } public double getValor() { return valor; } public void setValor(float valor) { this.valor = valor; } public Gerente getGerente() { return gerente; } public void setGerente(Gerente gerente) { this.gerente = gerente; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } @Override public String toString() { return "Despesas{" + "status=" + status + ", dataEmissao=" + dataEmissao + ", descricao=" + descricao + ", categoria=" + categoria + ", valor=" + valor + ", gerente=" + gerente + '}'; } }
gpl-3.0
mrdev023/MMORPG_PROJECT
Unity Server Project/src/fr/technicalgames/data/World.java
3034
package fr.technicalgames.data; import java.io.*; import java.nio.file.*; import java.util.*; import java.util.Map.*; import javax.xml.bind.*; import fr.technicalgames.data.xml.WorldList; import fr.technicalgames.io.*; import fr.technicalgames.math.*; import fr.technicalgames.network.common.*; public class World { private int heightmapWidth,heightmapHeight; private float mapWidth,mapHeight; private float[][] heightsMap; private static Map<Integer,World> worlds = new HashMap<Integer,World>(); public World(String filename) throws IOException{ Path path = Paths.get("ressources/world/" + filename); byte[] data = Files.readAllBytes(path); DataBuffer d = new DataBuffer(data); heightmapWidth = d.getInt(); heightmapHeight = d.getInt(); mapWidth = d.getFloat(); mapHeight = d.getFloat(); heightsMap = new float[heightmapWidth][heightmapHeight]; for(int x = 0;x < heightmapWidth;x++){ for(int y = 0;y < heightmapHeight;y++){ heightsMap[x][y] = d.getFloat(); } } } public float getHeights(float x,float y){ float rx = (x * (float)heightmapWidth)/mapWidth; float ry = (y * (float)heightmapHeight)/mapHeight; int ix = (int)rx; int iy = (int)ry; float interpolate1 = Mathf.linearInterpolate(heightsMap[ix][iy],heightsMap[ix + 1][iy],rx - ix); float interpolate2 = Mathf.linearInterpolate(heightsMap[ix][iy + 1],heightsMap[ix + 1][iy + 1],rx - ix); return Mathf.linearInterpolate(interpolate1,interpolate2,ry - iy); } public static void loadWorlds(){ Log.println(Log.INFO, "Loading World ..."); try { JAXBContext jc = JAXBContext.newInstance(WorldList.class); Unmarshaller jaxbUnmarshaller = jc.createUnmarshaller(); WorldList worldList = (WorldList)jaxbUnmarshaller.unmarshal(new File("data/world/worldList.xml")); for(Entry<Integer, String> s : worldList.getWorlds().entrySet()){ try { World w = new World(s.getValue()); worlds.put(s.getKey(), w); } catch (IOException e) { e.printStackTrace(); } } } catch (JAXBException e) { e.printStackTrace(); } Log.println(Log.INFO, "World loaded !"); } public static Map<Integer, World> getWorlds() { return worlds; } public static void setWorlds(Map<Integer, World> worlds) { World.worlds = worlds; } public int getHeightmapWidth() { return heightmapWidth; } public void setHeightmapWidth(int heightmapWidth) { this.heightmapWidth = heightmapWidth; } public int getHeightmapHeight() { return heightmapHeight; } public void setHeightmapHeight(int heightmapHeight) { this.heightmapHeight = heightmapHeight; } public float getMapWidth() { return mapWidth; } public void setMapWidth(float mapWidth) { this.mapWidth = mapWidth; } public float getMapHeight() { return mapHeight; } public void setMapHeight(float mapHeight) { this.mapHeight = mapHeight; } public float[][] getHeightsMap() { return heightsMap; } public void setHeightsMap(float[][] heightsMap) { this.heightsMap = heightsMap; } }
gpl-3.0
ItakPC/Plasmatic-Revolution
src/com/ItakPC/plasmatic_rev/world/Map.java
1775
package com.ItakPC.plasmatic_rev.world; import com.ItakPC.plasmatic_rev.Game; import static com.ItakPC.plasmatic_rev.reference.Reference.*; import java.awt.*; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class Map { List<Chunk> loadedChunks = new CopyOnWriteArrayList<Chunk>(); public Map() { checkChunks(); } public void checkChunks() { int playerChunkX = Game.fastFloor(Game.instance.player.posX / (double) tileAmountX); int playerChunkY = Game.fastFloor(Game.instance.player.posY / (double)tileAmountY); /** Unload chunks */ unloadChunks(playerChunkX, playerChunkY); /** Load chunks */ loadChunks(playerChunkX, playerChunkY); } public void render(Graphics g) { for(Chunk chunk : loadedChunks) { chunk.render(g); } } private void unloadChunks(int playerChunkX, int playerChunkY) { for(Chunk chunk : loadedChunks) { if(chunk.chunkX > playerChunkX+(chunkAmountX-1)/2 || chunk.chunkX < playerChunkX-(chunkAmountX-1)/2 || chunk.chunkY > playerChunkY+(chunkAmountY-1)/2 || chunk.chunkY < playerChunkY-(chunkAmountY-1)/2) loadedChunks.remove(chunk); } } private void loadChunks(int playerChunkX, int playerChunkY) { for(int x = playerChunkX-(chunkAmountX-1)/2; x <= playerChunkX+(chunkAmountX-1)/2; x++) { for(int y = playerChunkY-(chunkAmountY-1)/2; y <= playerChunkY+(chunkAmountY-1)/2; y++) { if(!loadedChunks.contains(new Chunk(x, y))) { Chunk chunk = new Chunk(x, y); chunk.populate(); loadedChunks.add(chunk); } } } } }
gpl-3.0
autyzm-pg/friendly-plans
Friendly-plans/app/src/main/java/pg/autyzm/friendly_plans/asset/AssetsHelperModule.java
461
package pg.autyzm.friendly_plans.asset; import android.content.Context; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; @Module public class AssetsHelperModule { private AssetsHelper assetsHelper; public AssetsHelperModule(Context context) { this.assetsHelper = new AssetsHelper(context); } @Provides @Singleton public AssetsHelper getAssetsHelper() { return this.assetsHelper; } }
gpl-3.0
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/utils/ViewParsingUtils.java
15175
package com.appmatic.baseapp.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.text.method.LinkMovementMethod; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.appmatic.baseapp.R; import com.appmatic.baseapp.api.models.Content; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.google.android.youtube.player.YouTubeStandalonePlayer; import com.pixplicity.htmlcompat.HtmlCompat; import java.util.Arrays; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ public class ViewParsingUtils { private static int halfMargin = -1; private static int defaultMargin = -1; public static View parseContent(@NonNull final Context context, final Content content, boolean isFirstView, boolean isLastView) { String[] extras = content.getExtras().split(Content.EXTRA_DELIMITER); if (halfMargin == -1 || defaultMargin == -1) { halfMargin = (int) context.getResources().getDimension(R.dimen.half_default_margin); defaultMargin = (int) context.getResources().getDimension(R.dimen.default_margin); } switch (content.getType()) { case Content.TYPE_SEPARATOR: return inflateSeparator(context, isFirstView, isLastView); case Content.TYPE_TEXT: return inflateText(context, content.getContent(), isFirstView, isLastView); case Content.TYPE_IMAGE: return inflateImageView(context, content.getContent(), isFirstView, isLastView); case Content.TYPE_TABLE: return inflateTable(context, content.getContent(), extras, isFirstView, isLastView); case Content.TYPE_TITLE: return inflateTitle(context, content.getContent(), isFirstView, isLastView); case Content.TYPE_YOUTUBE: return inflateYouTubeVideo(context, content.getContent(), isFirstView, isLastView); default: return new View(context); } } private static View inflateSeparator(Context context, boolean isFirstView, boolean isLastView) { View separator = new View(context); separator.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1)); final TypedArray typedArray = context.obtainStyledAttributes(new int[]{android.R.attr.listDivider}); DeprecationUtils.setBackgroundDrawable(separator, typedArray.getDrawable(0)); typedArray.recycle(); if (isFirstView) setLinearViewMargins(separator, 0, defaultMargin, 0, halfMargin); else if (isLastView) setLinearViewMargins(separator, 0, halfMargin, 0, defaultMargin); else setLinearViewMargins(separator, 0, halfMargin, 0, halfMargin); return separator; } private static TextView inflateText(Context context, String text, boolean isFirstView, boolean isLastView) { TextView textView = new TextView(context); textView.setMovementMethod(LinkMovementMethod.getInstance()); textView.setText(HtmlCompat.fromHtml(context, text.replace("\n", "<br><br>").replace("</p>", "").replace("<p>", ""), 0)); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16.0f); textView.setTextColor(ContextCompat.getColor(context, R.color.mainTextColor)); textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); if (isFirstView) setLinearViewMargins(textView, defaultMargin, defaultMargin, defaultMargin, halfMargin); else if (isLastView) setLinearViewMargins(textView, defaultMargin, halfMargin, defaultMargin, defaultMargin); else setLinearViewMargins(textView, defaultMargin, halfMargin, defaultMargin, halfMargin); return textView; } private static ImageView inflateImageView(Context context, String url, boolean isFirstView, boolean isLastView) { ImageView image = new ImageView(context); image.setScaleType(ImageView.ScaleType.CENTER_CROP); image.setAdjustViewBounds(true); // As seen in http://stackoverflow.com/a/23550010 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER_HORIZONTAL; image.setLayoutParams(params); Glide.with(context) .load(url) .into(image); if (isFirstView && isLastView) setLinearViewMargins(image, 0, 0, 0, 0); if (isFirstView) setLinearViewMargins(image, 0, 0, 0, halfMargin); else if (isLastView) setLinearViewMargins(image, 0, halfMargin, 0, 0); else setLinearViewMargins(image, 0, halfMargin, 0, halfMargin); return image; } private static HorizontalScrollView inflateTable(Context context, String tableContent, String[] extras, boolean isFirstView, boolean isLastView) { HorizontalScrollView horizontalScrollView = new HorizontalScrollView(context); TableLayout tableLayout = new TableLayout(context); String[] rows = tableContent.split(Content.TABLE_ROW_DIVIDER); int primaryColor = ContextCompat.getColor(context, R.color.colorPrimary); int stripColor = Color.argb(35, Color.red(primaryColor), Color.green(primaryColor), Color.blue(primaryColor)); HorizontalScrollView.LayoutParams horizontalScrollViewParams = new HorizontalScrollView.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); TableRow.LayoutParams rowParams = new TableRow.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); horizontalScrollView.setLayoutParams(horizontalScrollViewParams); tableLayout.setLayoutParams(tableParams); tableLayout.setStretchAllColumns(true); for (int i = 0; i < rows.length; i++) { TableRow tableRow = new TableRow(context); tableRow.setLayoutParams(rowParams); if (Arrays.asList(extras).contains(Content.EXTRA_HAS_STRIPES) && i % 2 != 0) tableRow.setBackgroundColor(stripColor); if (Arrays.asList(extras).contains(Content.EXTRA_HAS_HEADER) && i == 0) tableRow.setBackgroundResource(R.drawable.bottom_tablerow_border); String[] rowCells = rows[i].split(Content.TABLE_COLUMN_DIVIDER); for (int j = 0; j < rowCells.length; j++) { TextView tvCell = new TextView(context); tvCell.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16.0f); tvCell.setText(HtmlCompat.fromHtml(context, rowCells[j], 0)); tvCell.setTextColor(ContextCompat.getColor(context, R.color.mainTextColor)); int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, context.getResources().getDisplayMetrics()); tvCell.setPadding(padding, i == 0 ? 0 : padding, padding, padding); if (Arrays.asList(extras).contains(Content.EXTRA_HAS_HEADER) && i == 0) { tableRow.setBackgroundResource(R.drawable.bottom_tablerow_border); tvCell.setTypeface(null, Typeface.BOLD); } if (j == rowCells.length - 1 && rowCells.length > 1) tvCell.setGravity(GravityCompat.END); tableRow.addView(tvCell); } tableLayout.addView(tableRow); } if (isFirstView && isLastView) setFrameViewMargins(horizontalScrollView, 0, defaultMargin, 0, 0); else if (isFirstView) setFrameViewMargins(horizontalScrollView, 0, defaultMargin, 0, halfMargin); else if (isLastView) setFrameViewMargins(horizontalScrollView, 0, halfMargin, 0, 0); else setFrameViewMargins(horizontalScrollView, 0, halfMargin, 0, halfMargin); horizontalScrollView.addView(tableLayout); return horizontalScrollView; } private static TextView inflateTitle(Context context, String title, boolean isFirstView, boolean isLastView) { TextView titleTextView = new TextView(context); titleTextView.setText(title); titleTextView.setTypeface(null, Typeface.BOLD); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24.0f); titleTextView.setTextColor(ContextCompat.getColor(context, R.color.mainTextColor)); titleTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); if (isFirstView) setLinearViewMargins(titleTextView, defaultMargin, defaultMargin, defaultMargin, halfMargin); else if (isLastView) setLinearViewMargins(titleTextView, defaultMargin, halfMargin, defaultMargin, defaultMargin); else setLinearViewMargins(titleTextView, defaultMargin, halfMargin, defaultMargin, halfMargin); return titleTextView; } private static FrameLayout inflateYouTubeVideo(final Context context, final String videoId, boolean isFirstView, boolean isLastView) { final FrameLayout videoLayout = new FrameLayout(context); TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true); videoLayout.setForeground(ContextCompat.getDrawable(context, outValue.resourceId)); final ImageView youTubeThumbnailView = new ImageView(context); final ImageView playLogo = new ImageView(context); playLogo.setVisibility(View.GONE); playLogo.setImageResource(R.drawable.youtube_play_logo); videoLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = YouTubeStandalonePlayer.createVideoIntent((Activity) context, context.getString(R.string.google_dev_api_key), videoId, 0, true, true); if (intent.resolveActivity(context.getPackageManager()) != null) context.startActivity(intent); else AppmaticUtils.openPlayStore(context, "com.google.android.youtube"); } }); Glide.with(context) .load("https://img.youtube.com/vi/" + videoId + "/0.jpg") .centerCrop() .into(new SimpleTarget<GlideDrawable>() { @Override public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) { youTubeThumbnailView.setImageDrawable(resource); playLogo.setVisibility(View.VISIBLE); } }); youTubeThumbnailView.setScaleType(ImageView.ScaleType.CENTER_CROP); LinearLayout.LayoutParams thumbnailParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int) context.getResources().getDimension(R.dimen.youtube_thumbnail)); thumbnailParams.gravity = Gravity.CENTER_HORIZONTAL; youTubeThumbnailView.setLayoutParams(thumbnailParams); FrameLayout.LayoutParams playLogoParams = new FrameLayout.LayoutParams( (int) TypedValue.applyDimension (TypedValue.COMPLEX_UNIT_DIP, 96, context.getResources().getDisplayMetrics()), (int) TypedValue.applyDimension (TypedValue.COMPLEX_UNIT_DIP, 96, context.getResources().getDisplayMetrics())); playLogoParams.gravity = Gravity.CENTER; playLogo.setLayoutParams(playLogoParams); LinearLayout.LayoutParams frameLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); videoLayout.addView(youTubeThumbnailView); videoLayout.addView(playLogo); if (isFirstView && isLastView) videoLayout.setLayoutParams(injectFrameLayoutMargins(frameLayoutParams, 0, 0, 0, 0)); else if (isFirstView) videoLayout.setLayoutParams(injectFrameLayoutMargins(frameLayoutParams, 0, 0, 0, halfMargin)); else if (isLastView) videoLayout.setLayoutParams(injectFrameLayoutMargins(frameLayoutParams, 0, halfMargin, 0, 0)); else videoLayout.setLayoutParams(injectFrameLayoutMargins(frameLayoutParams, 0, halfMargin, 0, halfMargin)); return videoLayout; } private static void setLinearViewMargins(View view, int start, int top, int end, int bottom) { ((LinearLayout.LayoutParams) view.getLayoutParams()).setMargins(start, top, end, bottom); } private static void setFrameViewMargins(View view, int start, int top, int end, int bottom) { ((FrameLayout.LayoutParams) view.getLayoutParams()).setMargins(start, top, end, bottom); } private static LinearLayout.LayoutParams injectFrameLayoutMargins(LinearLayout.LayoutParams layoutParams, int start, int top, int end, int bottom) { layoutParams.setMargins(start, top, end, bottom); return layoutParams; } }
gpl-3.0
grigoriev/betsapp
src/main/java/eu/grigoriev/config/PersistenceConfig.java
2788
package eu.grigoriev.config; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.util.Properties; @Configuration @EnableTransactionManagement @PropertySource({"classpath:persistence-mysql.properties"}) public class PersistenceConfig { @Autowired private Environment env; public Properties hibernateProperties() { return new Properties() { { setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); setProperty("hibernate.enable_lazy_load_no_trans", env.getProperty("hibernate.enable_lazy_load_no_trans")); } }; } @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan(new String[]{"eu.grigoriev.persistence.entity"}); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Autowired @Bean public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) { HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory); return transactionManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; } }
gpl-3.0
onli/userIdent
userIdent/Options.java
1682
package userIdent; import java.io.File; public class Options { public static String DBpath = System.getProperty("user.home") +File.separator+".userIdent"+File.separator; public static String userFile = System.getProperty("user.home") +File.separator+".userIdent"+File.separator+"users.ndx"; public static String mistralPath = System.getProperty("user.home") +File.separator+".userIdent"+File.separator+"bin"+File.separator+""; public static String mistralConfPath = System.getProperty("user.home") +File.separator+".userIdent"+File.separator+"cfg"+File.separator+""; public static String soundPath = System.getProperty("user.home") +File.separator+".userIdent"+File.separator+"data"+File.separator+"sounds"+File.separator+""; public static String prmPath = System.getProperty("user.home") +File.separator+".userIdent"+File.separator+"data"+File.separator+"prm"+File.separator+""; public static String lblPath = System.getProperty("user.home") +File.separator+".userIdent"+File.separator+"data"+File.separator+"lbl"+File.separator+""; public static String lstPath = System.getProperty("user.home") +File.separator+".userIdent"+File.separator+"data"+File.separator+"lst"+File.separator+""; public static String gmmPath = System.getProperty("user.home") +File.separator+".userIdent"+File.separator+"data"+File.separator+"gmm"+File.separator+""; public static String ndxPath = System.getProperty("user.home") +File.separator+".userIdent"+File.separator+"data"+File.separator+"ndx"+File.separator+""; public static String logPath = System.getProperty("user.home") +File.separator+".userIdent"+File.separator+"log"+File.separator+""; public static boolean demo = false; }
gpl-3.0
WikiDreams/timer
src/com/wikidreams/timertask/MyTask.java
225
package com.wikidreams.timertask; import java.util.TimerTask; public class MyTask extends TimerTask { public MyTask() { super(); } @Override public void run() { System.out.println("I run after 5 seconds."); } }
gpl-3.0
GUMGA/framework-backend
gumga-application/src/test/java/gumga/framework/application/Task.java
912
/* * 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 gumga.framework.application; import gumga.framework.domain.GumgaModel; import gumga.framework.domain.GumgaMultitenancy; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.SequenceGenerator; /** * * @author wlademir */ @Entity @SequenceGenerator(name = GumgaModel.SEQ_NAME, sequenceName = "SEQ_CAR") @GumgaMultitenancy public class Task extends GumgaModel<Long> implements Serializable{ String name; public Task() { } public Task(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
gpl-3.0
landryb/georchestra
extractorapp/src/main/java/org/georchestra/extractorapp/ws/extractor/ExtractorUpdatePriorityRequest.java
3039
/* * Copyright (C) 2009-2018 by the geOrchestra PSC * * This file is part of geOrchestra. * * geOrchestra 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. * * geOrchestra 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 * geOrchestra. If not, see <http://www.gnu.org/licenses/>. */ package org.georchestra.extractorapp.ws.extractor; import org.georchestra.extractorapp.ws.extractor.task.ExecutionPriority; import org.json.JSONException; import org.json.JSONObject; /** * Encapsulates the parameters required the priority of a task * * @author Mauricio Pazos * */ class ExtractorUpdatePriorityRequest { public final String _uuid; public final ExecutionPriority _priority; public ExtractorUpdatePriorityRequest(String uuid, ExecutionPriority priority) { assert uuid != null && priority != null; _uuid = uuid; _priority = priority; } /** * Makes a new instance of {@link ExtractorUpdatePriorityRequest} * * @param jsonData a {"uuid":value, "priority": value} * @return {@link ExtractorUpdatePriorityRequest} * @throws JSONException */ public static ExtractorUpdatePriorityRequest parseJson(String jsonData) throws JSONException { JSONObject jsonRequest = JSONUtil.parseStringToJSon(jsonData); final String uuid = jsonRequest.getString(TaskDescriptor.UUID_KEY); final String strPriority = jsonRequest.getString(TaskDescriptor.PRIORITY_KEY); ExecutionPriority priority = ExecutionPriority.valueOf(strPriority); ExtractorUpdatePriorityRequest request = new ExtractorUpdatePriorityRequest(uuid, priority); return request; } /** * New instance of {@link ExtractorUpdatePriorityRequest} * * @param uuid * @param intPriority it should be one of the enumerated values defined in * {@link ExecutionPriority}} * @return {@link ExtractorUpdatePriorityRequest} */ public static ExtractorUpdatePriorityRequest newInstance(final String uuid, final int intPriority) { ExecutionPriority priority = null; for (ExecutionPriority p : ExecutionPriority.values()) { if (p.ordinal() == intPriority) { priority = p; break; } } if (priority == null) { throw new IllegalArgumentException("the priority value: " + intPriority + " is not valid."); } ExtractorUpdatePriorityRequest request = new ExtractorUpdatePriorityRequest(uuid, priority); return request; } }
gpl-3.0
UnknownStudio/ChinaCraft
src/main/java/unstudio/chinacraft/item/ItemBuddhistCane.java
3637
package unstudio.chinacraft.item; import com.google.common.collect.Multimap; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.*; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import unstudio.chinacraft.api.EntityMethod; import unstudio.chinacraft.util.ItemLoreHelper; import java.util.List; /** * Created by trychen on 16/7/31. */ public class ItemBuddhistCane extends ItemCCStaff { public ItemBuddhistCane() { setUnlocalizedName("buddhist_cane"); setMaxDamage(730); } @Override public void onUsingTick(ItemStack stack, EntityPlayer player, int count) { if (player.ticksExisted % 6 != 0) return; if (!player.worldObj.isRemote) { List<EntityMob> mobs = EntityMethod.findNear(player, EntityMob.class, 8, 8); List<EntityPlayer> players = EntityMethod.findNear(player, EntityPlayer.class, 5, 5); boolean hasUnMaxhealthPlayer = false; float heal = 0.15f; int healCount = 6; for (EntityPlayer entityPlayer : players) { if (entityPlayer.getMaxHealth() != entityPlayer.getHealth()) { hasUnMaxhealthPlayer = true; } if (healCount < 1) break; entityPlayer.setHealth(entityPlayer.getHealth() + heal); healCount--; } if (mobs.size() == 0 && !hasUnMaxhealthPlayer) { hasAnimal(EntityMethod.findNear(player, EntityAnimal.class, 5, 5)); } } double x = player.posX + player.worldObj.rand.nextDouble() * (player.worldObj.rand.nextBoolean() ? 6 : -6); double y = player.posY + player.worldObj.rand.nextDouble() * (player.worldObj.rand.nextBoolean() ? 1 : -1); double z = player.posZ + player.worldObj.rand.nextDouble() * (player.worldObj.rand.nextBoolean() ? 6 : -6); player.worldObj.spawnParticle("happyVillager", x, y, z, 0, 0, 0); } public int hasAnimal(List<EntityAnimal> animals) { for (EntityAnimal animal : animals) { if (animal.getHealth() != animal.getMaxHealth()) { return 0; } } int count = animals.size() > 6 ? 6 : animals.size(); int add = count > 3 ? 3 : count; return add; } public boolean isDamageable() { return true; } public EnumAction getItemUseAction(ItemStack p_77661_1_) { return EnumAction.bow; } @SideOnly(Side.CLIENT) public void addInformation(ItemStack p_77624_1_, EntityPlayer p_77624_2_, List p_77624_3_, boolean p_77624_4_) { ItemLoreHelper.shiftLoreWithStat(p_77624_3_,getUnlocalizedName()); } @Override public Multimap getAttributeModifiers(ItemStack stack) { return super.getAttributeModifiers(stack); } public boolean onBlockDestroyed(ItemStack itemStack, World world, Block block, int x, int y, int z, EntityLivingBase p_150894_7_) { if (itemStack.getItemDamage() > 0&&(block instanceof BlockLeaves||block instanceof BlockMushroom||block instanceof BlockBush)&& world.rand.nextBoolean()){ itemStack.setItemDamage(itemStack.getItemDamage() - 1); world.spawnParticle("happyVillager", x, y, z, 0, 0, 0); } return false; } }
gpl-3.0
TGAC/miso-lims
miso-web/src/main/java/uk/ac/bbsrc/tgac/miso/webapp/controller/rest/RunRestController.java
26240
/* * Copyright (c) 2012. The Genome Analysis Centre, Norwich, UK * MISO project contacts: Robert Davey @ TGAC * ********************************************************************* * * This file is part of MISO. * * MISO 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. * * MISO 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 MISO. If not, see <http://www.gnu.org/licenses/>. * * ********************************************************************* */ package uk.ac.bbsrc.tgac.miso.webapp.controller.rest; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Response.Status; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.eaglegenomics.simlims.core.User; import uk.ac.bbsrc.tgac.miso.core.data.InstrumentModel; import uk.ac.bbsrc.tgac.miso.core.data.Library; import uk.ac.bbsrc.tgac.miso.core.data.Pair; import uk.ac.bbsrc.tgac.miso.core.data.Partition; import uk.ac.bbsrc.tgac.miso.core.data.PartitionQCType; import uk.ac.bbsrc.tgac.miso.core.data.Run; import uk.ac.bbsrc.tgac.miso.core.data.RunPartition; import uk.ac.bbsrc.tgac.miso.core.data.RunPartitionAliquot; import uk.ac.bbsrc.tgac.miso.core.data.SequencerPartitionContainer; import uk.ac.bbsrc.tgac.miso.core.data.impl.LibraryAliquot; import uk.ac.bbsrc.tgac.miso.core.data.impl.RunPosition; import uk.ac.bbsrc.tgac.miso.core.data.impl.RunPurpose; import uk.ac.bbsrc.tgac.miso.core.data.impl.view.PoolElement; import uk.ac.bbsrc.tgac.miso.core.data.impl.view.PoolableElementView; import uk.ac.bbsrc.tgac.miso.core.data.type.HealthType; import uk.ac.bbsrc.tgac.miso.core.data.type.PlatformType; import uk.ac.bbsrc.tgac.miso.core.security.AuthorizationManager; import uk.ac.bbsrc.tgac.miso.core.service.ContainerService; import uk.ac.bbsrc.tgac.miso.core.service.ExperimentService; import uk.ac.bbsrc.tgac.miso.core.service.LibraryAliquotService; import uk.ac.bbsrc.tgac.miso.core.service.LibraryService; import uk.ac.bbsrc.tgac.miso.core.service.PartitionQcTypeService; import uk.ac.bbsrc.tgac.miso.core.service.RunPartitionAliquotService; import uk.ac.bbsrc.tgac.miso.core.service.RunPartitionService; import uk.ac.bbsrc.tgac.miso.core.service.RunPurposeService; import uk.ac.bbsrc.tgac.miso.core.service.RunService; import uk.ac.bbsrc.tgac.miso.core.service.exception.ValidationException; import uk.ac.bbsrc.tgac.miso.core.util.IndexChecker; import uk.ac.bbsrc.tgac.miso.core.util.LimsUtils; import uk.ac.bbsrc.tgac.miso.core.util.PaginatedDataSource; import uk.ac.bbsrc.tgac.miso.core.util.PaginationFilter; import uk.ac.bbsrc.tgac.miso.core.util.SampleSheet; import uk.ac.bbsrc.tgac.miso.core.util.WhineyConsumer; import uk.ac.bbsrc.tgac.miso.core.util.WhineyFunction; import uk.ac.bbsrc.tgac.miso.dto.ContainerDto; import uk.ac.bbsrc.tgac.miso.dto.DataTablesResponseDto; import uk.ac.bbsrc.tgac.miso.dto.Dtos; import uk.ac.bbsrc.tgac.miso.dto.ExperimentDto; import uk.ac.bbsrc.tgac.miso.dto.ExperimentDto.RunPartitionDto; import uk.ac.bbsrc.tgac.miso.dto.InstrumentModelDto; import uk.ac.bbsrc.tgac.miso.dto.PartitionDto; import uk.ac.bbsrc.tgac.miso.dto.RunPartitionAliquotDto; import uk.ac.bbsrc.tgac.miso.dto.StudyDto; import uk.ac.bbsrc.tgac.miso.dto.request.DetailedQcStatusUpdateDto; import uk.ac.bbsrc.tgac.miso.dto.run.RunDto; import uk.ac.bbsrc.tgac.miso.webapp.controller.component.AdvancedSearchParser; import uk.ac.bbsrc.tgac.miso.webapp.controller.component.ServerErrorException; /** * A controller to handle all REST requests for Runs * * @author Rob Davey * @date 01-Sep-2011 * @since 0.1.0 */ @Controller @RequestMapping("/rest/runs") public class RunRestController extends RestController { public static class RunPartitionQCRequest { private List<Long> partitionIds; private Long qcTypeId; private String notes; public List<Long> getPartitionIds() { return partitionIds; } public void setPartitionIds(List<Long> partitionIds) { this.partitionIds = partitionIds; } public Long getQcTypeId() { return qcTypeId; } public void setQcTypeId(Long qcTypeId) { this.qcTypeId = qcTypeId; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } } public static class RunPartitionPurposeRequest { private List<Long> partitionIds; private Long runPurposeId; public List<Long> getPartitionIds() { return partitionIds; } public void setPartitionIds(List<Long> partitionIds) { this.partitionIds = partitionIds; } public Long getRunPurposeId() { return runPurposeId; } public void setRunPurposeId(Long runPurposeId) { this.runPurposeId = runPurposeId; } } public static class RunLibraryQcStatusUpdateRequest { private Boolean qcPassed; private String note; public Boolean getQcPassed() { return qcPassed; } public void setQcPassed(Boolean qcPassed) { this.qcPassed = qcPassed; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } } @Autowired private AuthorizationManager authorizationManager; @Autowired private RunService runService; @Autowired private ContainerService containerService; @Autowired private RunPartitionService runPartitionService; @Autowired private PartitionQcTypeService partitionQcTypeService; @Autowired private RunPartitionAliquotService runPartitionAliquotService; @Autowired private LibraryService libraryService; @Autowired private LibraryAliquotService libraryAliquotService; @Autowired private ExperimentService experimentService; @Autowired private RunPurposeService runPurposeService; @Autowired private IndexChecker indexChecker; @Autowired private AdvancedSearchParser advancedSearchParser; private final JQueryDataTableBackend<Run, RunDto> jQueryBackend = new JQueryDataTableBackend<Run, RunDto>() { @Override protected RunDto asDto(Run model) { return Dtos.asDto(model); } @Override protected PaginatedDataSource<Run> getSource() throws IOException { return runService; } }; @GetMapping(value = "/{runId}", produces = "application/json") public @ResponseBody RunDto getRunById(@PathVariable long runId) throws IOException { return RestUtils.getObject("Run", runId, runService, Dtos::asDto); } @GetMapping(value = "/{runId}/full", produces = "application/json") public @ResponseBody RunDto getRunByIdFull(@PathVariable Long runId) throws IOException { return RestUtils.getObject("Run", runId, runService, run -> Dtos.asDto(run, true, true, true)); } @GetMapping(value = "/{runId}/containers", produces = "application/json") public @ResponseBody List<ContainerDto> getContainersByRunId(@PathVariable Long runId) throws IOException { Collection<SequencerPartitionContainer> cc = containerService.listByRunId(runId); return Dtos.asContainerDtos(cc, true, true); } @GetMapping(value = "/alias/{runAlias}", produces = "application/json") public @ResponseBody RunDto getRunByAlias(@PathVariable String runAlias) throws IOException { Run r = runService.getRunByAlias(runAlias); if (r == null) { throw new RestException("No run found with alias: " + runAlias, Status.NOT_FOUND); } return Dtos.asDto(r); } @GetMapping(value = "/{runId}/samplesheet/{sheet}") public HttpEntity<String> getSampleSheetForRun(@PathVariable(name = "runId") Long runId, @PathVariable(name = "sheet") String sheet, HttpServletResponse response) throws IOException { Run run = runService.get(runId); return getSampleSheetForRun(run, SampleSheet.valueOf(sheet), response); } @GetMapping(value = "/alias/{runAlias}/samplesheet/{sheet}") public HttpEntity<String> getSampleSheetForRunByAlias(@PathVariable(name = "runAlias") String runAlias, @PathVariable(name = "sheet") String sheet, HttpServletResponse response) throws IOException { Run run = runService.getRunByAlias(runAlias); return getSampleSheetForRun(run, SampleSheet.valueOf(sheet), response); } private HttpEntity<String> getSampleSheetForRun(Run run, SampleSheet casavaVersion, HttpServletResponse response) throws IOException { if (run == null) { throw new RestException("Run does not exist.", Status.NOT_FOUND); } User user = authorizationManager.getCurrentUser(); if (run.getSequencerPartitionContainers().size() != 1) { throw new RestException( "Expected 1 sequencing container for run " + run.getAlias() + ", but found " + run.getSequencerPartitionContainers().size()); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(new MediaType("text", "csv")); response.setHeader("Content-Disposition", "attachment; filename=" + String.format("RUN%d-%s-SampleSheet.csv", run.getId(), casavaVersion.name())); return new HttpEntity<>(casavaVersion.createSampleSheet(run, user), headers); } @GetMapping(produces = "application/json") public @ResponseBody List<RunDto> listAllRuns() throws IOException { Collection<Run> lr = runService.list(); return Dtos.asRunDtos(lr); } @GetMapping(value = "/dt", produces = "application/json") @ResponseBody public DataTablesResponseDto<RunDto> dataTable(HttpServletRequest request) throws IOException { return jQueryBackend.get(request, advancedSearchParser); } @GetMapping(value = "/dt/project/{id}", produces = "application/json") @ResponseBody public DataTablesResponseDto<RunDto> dataTableByProject(@PathVariable("id") Long id, HttpServletRequest request) throws IOException { return jQueryBackend.get(request, advancedSearchParser, PaginationFilter.project(id)); } @GetMapping(value = "/dt/platform/{platform}", produces = "application/json") @ResponseBody public DataTablesResponseDto<RunDto> dataTableByPlatform(@PathVariable("platform") String platform, HttpServletRequest request) throws IOException { PlatformType platformType = PlatformType.valueOf(platform); if (platformType == null) { throw new RestException("Invalid platform type.", Status.BAD_REQUEST); } return jQueryBackend.get(request, advancedSearchParser, PaginationFilter.platformType(platformType)); } @GetMapping(value = "/dt/sequencer/{id}", produces = "application/json") @ResponseBody public DataTablesResponseDto<RunDto> dataTableBySequencer(@PathVariable("id") Long id, HttpServletRequest request) throws IOException { return jQueryBackend.get(request, advancedSearchParser, PaginationFilter.sequencer(id)); } @PostMapping(value = "{runId}/add", produces = "application/json") @ResponseStatus(code = HttpStatus.NO_CONTENT) public void addContainerByBarcode(@PathVariable Long runId, @RequestParam("position") String position, @RequestParam("barcode") String barcode) throws IOException { Run run = runService.get(runId); Collection<SequencerPartitionContainer> containers = containerService .listByBarcode(barcode); if (containers.isEmpty()) { throw new RestException("No containers with this barcode.", Status.BAD_REQUEST); } if (containers.size() > 1) { throw new RestException("Multiple containers with this barcode.", Status.BAD_REQUEST); } SequencerPartitionContainer container = containers.iterator().next(); InstrumentModel runPlatform = run.getSequencer().getInstrumentModel(); if (container.getModel().getInstrumentModels().stream() .noneMatch(platform -> platform.getId() == runPlatform.getId())) { throw new RestException(String.format("Container model '%s' (%s) is not compatible with %s (%s) run", container.getModel().getAlias(), container.getModel().getPlatformType(), run.getSequencer().getInstrumentModel().getAlias(), run.getSequencer().getInstrumentModel().getPlatformType()), Status.BAD_REQUEST); } RunPosition runPos = new RunPosition(); runPos.setRun(run); runPos.setContainer(container); if (!LimsUtils.isStringEmptyOrNull(position)) { runPos.setPosition(runPlatform.getPositions().stream() .filter(pos -> pos.getAlias().equals(position)) .findFirst().orElseThrow(() -> new ValidationException( String.format("Platform %s does not have a position %s", runPlatform.getAlias(), position)))); } run.getRunPositions().add(runPos); runService.update(run); } @PostMapping(value = "/{runId}/remove", produces = "application/json") @ResponseStatus(code = HttpStatus.NO_CONTENT) public void removeContainer(@PathVariable Long runId, @RequestBody List<Long> containerIds) throws IOException { Run run = runService.get(runId); run.getRunPositions().removeIf(rp -> containerIds.contains(rp.getContainer().getId())); runService.update(run); } @PostMapping(value = "/{runId}/qc", produces = "application/json") @ResponseStatus(code = HttpStatus.NO_CONTENT) public void setQc(@PathVariable Long runId, @RequestBody RunPartitionQCRequest request) throws IOException { Run run = RestUtils.retrieve("Run", runId, runService); PartitionQCType qcType = partitionQcTypeService.list().stream().filter(qt -> qt.getId() == request.getQcTypeId().longValue()).findAny() .orElseThrow( () -> new RestException(String.format("No partition QC type found with ID: %d", request.getQcTypeId()), Status.BAD_REQUEST)); run.getSequencerPartitionContainers().stream()// .flatMap(container -> container.getPartitions().stream())// .filter(partition -> request.partitionIds.contains(partition.getId()))// .map(WhineyFunction.rethrow(partition -> { RunPartition runPartition = runPartitionService.get(run, partition); if (runPartition == null) { runPartition = new RunPartition(); runPartition.setRun(run); runPartition.setPartition(partition); } runPartition.setQcType(qcType); runPartition.setNotes(request.notes); return runPartition; })).forEach(WhineyConsumer.rethrow(runPartitionService::save)); } @PutMapping("/{runId}/partition-purposes") @ResponseStatus(HttpStatus.NO_CONTENT) public void setPartitionPurposes(@PathVariable long runId, @RequestBody RunPartitionPurposeRequest request) throws IOException { Run run = RestUtils.retrieve("Run", runId, runService); RunPurpose purpose = RestUtils.retrieve("Run purpose", request.getRunPurposeId(), runPurposeService); List<Partition> partitions = run.getSequencerPartitionContainers().stream() .flatMap(container -> container.getPartitions().stream()) .filter(partition -> request.getPartitionIds().contains(partition.getId())) .collect(Collectors.toList()); for (Partition partition : partitions) { RunPartition runPartition = runPartitionService.get(run, partition); if (runPartition == null) { runPartition = new RunPartition(); runPartition.setRun(run); runPartition.setPartition(partition); } runPartition.setPurpose(purpose); runPartitionService.save(runPartition); } } @PutMapping("/{runId}/aliquots") @ResponseStatus(HttpStatus.NO_CONTENT) public void saveAliquots(@PathVariable long runId, @RequestBody List<RunPartitionAliquotDto> dtos) throws IOException { RestUtils.retrieve("Run", runId, runService); List<RunPartitionAliquot> runPartitionAliquots = dtos.stream().map(Dtos::to).collect(Collectors.toList()); runPartitionAliquotService.save(runPartitionAliquots); } public static class StudiesForExperiment { private ExperimentDto experiment; private List<StudyDto> studies; public ExperimentDto getExperiment() { return experiment; } public List<StudyDto> getStudies() { return studies; } public void setExperiment(ExperimentDto experiment) { this.experiment = experiment; } public void setStudies(List<StudyDto> studies) { this.studies = studies; } } @GetMapping("/{runId}/potentialExperiments") public @ResponseBody List<StudiesForExperiment> getPotentialExperiments(@PathVariable long runId) throws IOException { Run run = getRun(runId); RunDto runDto = Dtos.asDto(run); InstrumentModelDto instrumentModelDto = Dtos.asDto(run.getSequencer().getInstrumentModel()); Map<Library, List<Partition>> libraryGroups = getLibraryGroups(run); return libraryGroups.entrySet().stream().map(group -> new Pair<>(group.getKey(), group.getValue().stream().map(partition -> Dtos.asDto(partition, indexChecker)) .map(partitionDto -> new RunPartitionDto(runDto, partitionDto)) .collect(Collectors.toList()))) .map(group -> { StudiesForExperiment result = new StudiesForExperiment(); result.experiment = new ExperimentDto(); result.experiment.setLibrary(Dtos.asDto(group.getKey(), false)); result.experiment.setInstrumentModel(instrumentModelDto); result.experiment.setPartitions(group.getValue()); result.studies = group.getKey().getSample().getProject().getStudies().stream().map(Dtos::asDto).collect(Collectors.toList()); return result; }).collect(Collectors.toList()); } public static class AddRequest { private ExperimentDto experiment; private PartitionDto partition; public ExperimentDto getExperiment() { return experiment; } public PartitionDto getPartition() { return partition; } public void setExperiment(ExperimentDto experiment) { this.experiment = experiment; } public void setPartition(PartitionDto partition) { this.partition = partition; } } @GetMapping("/{runId}/potentialExperimentExpansions") public @ResponseBody List<AddRequest> getPotentialExperimentExpansions(@PathVariable long runId) throws IOException { Run run = getRun(runId); Map<Library, List<Partition>> libraryGroups = getLibraryGroups(run); return libraryGroups.entrySet().stream() .<AddRequest> flatMap(WhineyFunction.rethrow(group -> // experimentService.listAllByLibraryId(group.getKey().getId()).stream()// .filter(experiment -> experiment.getInstrumentModel().getId() == run.getSequencer().getInstrumentModel().getId()) .flatMap(experiment -> group.getValue().stream()// .filter(partition -> experiment.getRunPartitions().stream().noneMatch(rp -> rp.getPartition().equals(partition))) .map(partition -> { AddRequest request = new AddRequest(); request.experiment = Dtos.asDto(experiment); request.partition = Dtos.asDto(partition, indexChecker); return request; })))) .collect(Collectors.toList()); } private Map<Library, List<Partition>> getLibraryGroups(Run run) { return run.getSequencerPartitionContainers().stream()// .flatMap(container -> container.getPartitions().stream())// .filter(partition -> partition.getPool() != null)// .flatMap(partition -> partition.getPool().getPoolContents().stream()// .map(PoolElement::getPoolableElementView)// .map(PoolableElementView::getLibraryId)// .distinct() .map(libraryId -> new Pair<>(libraryId, partition)))// .collect(Collectors.groupingBy(Pair::getKey))// .entrySet().stream()// .collect(Collectors.toMap(// WhineyFunction .rethrow(entry -> libraryService.get(entry.getKey())), // entry -> entry.getValue().stream()// .map(Pair::getValue)// .collect(Collectors.toList()))); } @GetMapping("/search") public @ResponseBody List<RunDto> searchRuns(@RequestParam("q") String query) throws IOException { return runService.listBySearch(query).stream().map(Dtos::asDto).collect(Collectors.toList()); } @GetMapping("/recent") public @ResponseBody List<RunDto> listRecentRuns() throws IOException { return runService.list(0, 50, false, "startDate").stream().map(Dtos::asDto).collect(Collectors.toList()); } private Run getRun(long runId) throws IOException { Run run = runService.get(runId); if (run == null) { throw new RestException("Run not found", Status.NOT_FOUND); } return run; } @PostMapping public @ResponseBody RunDto createRun(@RequestBody RunDto dto) throws IOException { return RestUtils.createObject("Run", dto, Dtos::to, runService, Dtos::asDto); } @PutMapping("/{runId}") public @ResponseBody RunDto updateRun(@PathVariable long runId, @RequestBody RunDto dto) throws IOException { return RestUtils.updateObject("Run", runId, dto, WhineyFunction.rethrow(d -> { Run run = Dtos.to(d); // Containers cannot be updated in this way Run existing = runService.get(runId); run.getRunPositions().clear(); for (RunPosition pos : existing.getRunPositions()) { run.addSequencerPartitionContainer(pos.getContainer(), pos.getPosition()); } return run; }), runService, Dtos::asDto); } @PostMapping(value = "/bulk-delete") @ResponseBody @ResponseStatus(HttpStatus.NO_CONTENT) public void bulkDelete(@RequestBody(required = true) List<Long> ids) throws IOException { RestUtils.bulkDelete("Run", ids, runService); } @PutMapping("/{runId}/status") public @ResponseBody RunDto updateStatus(@PathVariable long runId, @RequestParam String status) throws IOException { Run run = RestUtils.retrieve("Run", runId, runService); HealthType health = HealthType.get(status); if (health == null) { throw new RestException("Invalid run status: " + status, Status.BAD_REQUEST); } run.setHealth(health); long savedId = runService.update(run); Run saved = runService.get(savedId); return Dtos.asDto(saved); } @PutMapping("/{runId}/partitions/{partitionId}/qc-status") @ResponseStatus(HttpStatus.NO_CONTENT) public @ResponseBody void updateRunPartitionQcStatus(@PathVariable long runId, @PathVariable long partitionId, @RequestBody DetailedQcStatusUpdateDto dto) throws IOException { Run run = RestUtils.retrieve("Run", runId, runService); Partition partition = findPartitionInRun(run, partitionId); PartitionQCType status = dto.getQcStatusId() == null ? null : RestUtils.retrieve("Partition QC status", dto.getQcStatusId(), partitionQcTypeService, Status.BAD_REQUEST); RunPartition runPartition = runPartitionService.get(run, partition); if (runPartition == null) { throw new ServerErrorException(String.format("No RunPartition found for run %d, partition %d", run.getId(), partition.getId())); } runPartition.setQcType(status); runPartition.setNotes(dto.getNote()); runPartitionService.save(runPartition); } private Partition findPartitionInRun(Run run, long partitionId) { Partition partition = run.getRunPositions().stream() .map(RunPosition::getContainer) .flatMap(x -> x.getPartitions().stream()) .filter(x -> x.getId() == partitionId) .findFirst().orElse(null); if (partition == null) { throw new RestException(String.format("Partition %d not found in run", partitionId), Status.NOT_FOUND); } return partition; } @PutMapping("/{runId}/partitions/{partitionId}/libraryaliquots/{aliquotId}/qc-status") @ResponseStatus(HttpStatus.NO_CONTENT) public @ResponseBody void updateRunLibraryQcStatus(@PathVariable long runId, @PathVariable long partitionId, @PathVariable long aliquotId, @RequestBody RunLibraryQcStatusUpdateRequest dto) throws IOException { Run run = RestUtils.retrieve("Run", runId, runService); Partition partition = findPartitionInRun(run, partitionId); PoolableElementView poolableElementView = partition.getPool().getPoolContents().stream() .map(PoolElement::getPoolableElementView) .filter(x -> x.getId() == aliquotId) .findFirst().orElse(null); if (poolableElementView == null) { throw new RestException(String.format("Library aliquot %d not found in partition", aliquotId), Status.NOT_FOUND); } LibraryAliquot aliquot = RestUtils.retrieve("Library aliquot", aliquotId, libraryAliquotService); RunPartitionAliquot runLib = runPartitionAliquotService.get(run, partition, aliquot); if (runLib == null) { runLib = new RunPartitionAliquot(); runLib.setRun(run); runLib.setPartition(partition); runLib.setAliquot(aliquot); } runLib.setQcPassed(dto.getQcPassed()); runLib.setQcNote(dto.getNote()); runPartitionAliquotService.save(runLib); } }
gpl-3.0
cberes/game
engine/src/main/java/net/seabears/game/terrains/HeightMap.java
715
package net.seabears.game.terrains; import java.awt.image.BufferedImage; public class HeightMap implements HeightGenerator { private static final double HALF_MAX_PIXEL_COLOR = Math.pow(2, 23); private final BufferedImage map; private final double maxHeight; public HeightMap(BufferedImage map, double maxHeight) { this.map = map; this.maxHeight = maxHeight; } @Override public float generate(int x, int z) { if (x < 0 || x >= map.getWidth() || z < 0 || z >= map.getHeight()) { return 0.0f; } return (float) ((map.getRGB(x, z) + HALF_MAX_PIXEL_COLOR) / HALF_MAX_PIXEL_COLOR * maxHeight); } @Override public int getVertexCount() { return map.getHeight(); } }
gpl-3.0
getir-hackathon-2016/locksmith-android
app/src/main/java/te/com/locksmith/tools/ServerResponseMessage.java
1443
package te.com.locksmith.tools; import android.app.Activity; import android.content.Context; import com.devspark.appmsg.AppMsg; import com.orhanobut.logger.Logger; import org.json.JSONException; import org.json.JSONObject; /** * Created by enes on 20/02/16. */ public class ServerResponseMessage { private static Activity activity; private static Context context; private static ServerResponseMessage serverResponseMessage = new ServerResponseMessage(); public static ServerResponseMessage getInstance(Context cxt) { context = cxt; try { activity = (Activity)cxt; }catch (Exception ex) { activity = null; Logger.e(ex, ex.toString()); } return serverResponseMessage; } public void execute(int statusCode, byte[] responseBody){ if (statusCode == 400 && activity != null){ try { String json = new String(responseBody); JSONObject jObj = new JSONObject(json); AppMsg.cancelAll(); AppMsg appMsg = AppMsg.makeText(activity,jObj.getString("responseDesc"),AppMsg.STYLE_ALERT); appMsg.setAnimation(android.R.anim.slide_in_left, android.R.anim.slide_out_right); appMsg.setDuration(4000); appMsg.show(); } catch (JSONException e) { e.printStackTrace(); } } } }
gpl-3.0
AlexSussex/Dissertation---ONE
src/core/GeoMessage.java
9989
/* * Copyright 2014 Aydin Rajaei, University of Sussex. * The Geo-One Simulator Project. */ package core; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * A message that is created at a node or passed between nodes. */ public class GeoMessage implements Comparable<Message> { /** Time-to-live (TTL) as seconds -setting id ({@value}). Boolean valued. * If set to true, the TTL is interpreted as seconds instead of minutes. * Default=false. */ public static final String TTL_SECONDS_S = "Scenario.ttlSeconds"; private static boolean ttlAsSeconds = false; /** Value for infinite TTL of message */ public static final int INFINITE_TTL = -1; private DTNHost from; /** Addressed Cast */ private Cast to; /** Identifier of the message */ private String id; /** Size of the message (bytes) */ private int size; /** List of nodes this message has passed */ private List<DTNHost> path; /** Next unique identifier to be given */ private static int nextUniqueId; /** Unique ID of this message */ private int uniqueId; /** The time this message was received */ private double timeReceived; /** The time when this message was created */ private double timeCreated; /** Initial TTL of the message */ private int initTtl; /** if a response to this message is required, this is the size of the * response message (or 0 if no response is requested) */ private int responseSize; /** if this message is a response message, this is set to the request msg*/ private Message requestMsg; /** Container for generic message properties. Note that all values * stored in the properties should be immutable because only a shallow * copy of the properties is made when replicating messages */ private Map<String, Object> properties; /** Application ID of the application that created the message */ private String appID; static { reset(); DTNSim.registerForReset(Message.class.getCanonicalName()); } /** * Creates a new Message. * @param from Who the message is (originally) from * @param to Who the message is (originally) to * @param id Message identifier (must be unique for message but * will be the same for all replicates of the message) * @param size Size of the message (in bytes) */ public GeoMessage(DTNHost from, Cast to, String id, int size) { this.from = from; this.to = to; this.id = id; this.size = size; this.path = new ArrayList<DTNHost>(); this.uniqueId = nextUniqueId; this.timeCreated = SimClock.getTime(); this.timeReceived = this.timeCreated; this.initTtl = INFINITE_TTL; this.responseSize = 0; this.requestMsg = null; this.properties = null; this.appID = null; GeoMessage.nextUniqueId++; addNodeOnPath(from); } /** * Returns the node this message is originally from * @return the node this message is originally from */ public DTNHost getFrom() { return this.from; } /** * Returns the node this message is originally to * @return the node this message is originally to */ public Cast getTo() { return this.to; } /** * Returns the ID of the message * @return The message id */ public String getId() { return this.id; } /** * Returns an ID that is unique per message instance * (different for replicates too) * @return The unique id */ public int getUniqueId() { return this.uniqueId; } /** * Returns the size of the message (in bytes) * @return the size of the message */ public int getSize() { return this.size; } /** * Adds a new node on the list of nodes this message has passed * @param node The node to add */ public void addNodeOnPath(DTNHost node) { this.path.add(node); } /** * Returns a list of nodes this message has passed so far * @return The list as vector */ public List<DTNHost> getHops() { return this.path; } /** * Returns the amount of hops this message has passed * @return the amount of hops this message has passed */ public int getHopCount() { return this.path.size() -1; } /** * Returns the time to live (in minutes or seconds, depending on the setting * {@link #TTL_SECONDS_S}) of the message or Integer.MAX_VALUE * if the TTL is infinite. Returned value can be negative if the TTL has * passed already. * @return The TTL */ public int getTtl() { if (this.initTtl == INFINITE_TTL) { return Integer.MAX_VALUE; } else { if (ttlAsSeconds) { return (int)(this.initTtl - (SimClock.getTime()-this.timeCreated) ); } else { return (int)( ((this.initTtl * 60) - (SimClock.getTime()-this.timeCreated)) /60.0 ); } } } /** * Sets the initial TTL (time-to-live) for this message. The initial * TTL is the TTL when the original message was created. The current TTL * is calculated based on the time of * @param ttl The time-to-live to set */ public void setTtl(int ttl) { this.initTtl = ttl; } /** * Sets the time when this message was received. * @param time The time to set */ public void setReceiveTime(double time) { this.timeReceived = time; } /** * Returns the time when this message was received * @return The time */ public double getReceiveTime() { return this.timeReceived; } /** * Returns the time when this message was created * @return the time when this message was created */ public double getCreationTime() { return this.timeCreated; } /** * If this message is a response to a request, sets the request message * @param request The request message */ public void setRequest(Message request) { this.requestMsg = request; } /** * Returns the message this message is response to or null if this is not * a response message * @return the message this message is response to */ public Message getRequest() { return this.requestMsg; } /** * Returns true if this message is a response message * @return true if this message is a response message */ public boolean isResponse() { return this.requestMsg != null; } /** * Sets the requested response message's size. If size == 0, no response * is requested (default) * @param size Size of the response message */ public void setResponseSize(int size) { this.responseSize = size; } /** * Returns the size of the requested response message or 0 if no response * is requested. * @return the size of the requested response message */ public int getResponseSize() { return responseSize; } /** * Returns a string representation of the message * @return a string representation of the message */ public String toString () { return id; } /** * Deep copies message data from other message. If new fields are * introduced to this class, most likely they should be copied here too * (unless done in constructor). * @param m The message where the data is copied */ protected void copyFrom(GeoMessage m) { this.path = new ArrayList<DTNHost>(m.path); this.timeCreated = m.timeCreated; this.responseSize = m.responseSize; this.requestMsg = m.requestMsg; this.initTtl = m.initTtl; this.appID = m.appID; if (m.properties != null) { Set<String> keys = m.properties.keySet(); for (String key : keys) { updateProperty(key, m.getProperty(key)); } } } /** * Adds a generic property for this message. The key can be any string but * it should be such that no other class accidently uses the same value. * The value can be any object but it's good idea to store only immutable * objects because when message is replicated, only a shallow copy of the * properties is made. * @param key The key which is used to lookup the value * @param value The value to store * @throws SimError if the message already has a value for the given key */ public void addProperty(String key, Object value) throws SimError { if (this.properties != null && this.properties.containsKey(key)) { /* check to prevent accidental name space collisions */ throw new SimError("Message " + this + " already contains value " + "for a key " + key); } this.updateProperty(key, value); } /** * Returns an object that was stored to this message using the given * key. If such object is not found, null is returned. * @param key The key used to lookup the object * @return The stored object or null if it isn't found */ public Object getProperty(String key) { if (this.properties == null) { return null; } return this.properties.get(key); } /** * Updates a value for an existing property. For storing the value first * time, {@link #addProperty(String, Object)} should be used which * checks for name space clashes. * @param key The key which is used to lookup the value * @param value The new value to store */ public void updateProperty(String key, Object value) throws SimError { if (this.properties == null) { /* lazy creation to prevent performance overhead for classes that don't use the property feature */ this.properties = new HashMap<String, Object>(); } this.properties.put(key, value); } /** * Returns a replicate of this message (identical except for the unique id) * @return A replicate of the message */ public GeoMessage replicate() { GeoMessage m = new GeoMessage(from, to, id, size); m.copyFrom(this); return m; } /** * Compares two messages by their ID (alphabetically). * @see String#compareTo(String) */ public int compareTo(Message m) { return toString().compareTo(m.toString()); } /** * Resets all static fields to default values */ public static void reset() { nextUniqueId = 0; Settings s = new Settings(); ttlAsSeconds = s.getBoolean(TTL_SECONDS_S, false); } /** * @return the appID */ public String getAppID() { return appID; } /** * @param appID the appID to set */ public void setAppID(String appID) { this.appID = appID; } }
gpl-3.0
SupaHam/SupaChatAPI
src/main/java/com/supaham/supachatapi/Parsers.java
278
package com.supaham.supachatapi; import com.supaham.supachatapi.xml.XmlParser; /** * Contains instances of built-in {@link Parser}s. */ public class Parsers { /** * Instance of {@link XmlParser}. */ public static final XmlParser XML = new XmlParser(); }
gpl-3.0
AkintudnesServer/essentials
Essentials/src/com/earth2me/essentials/commands/Commandeco.java
1545
package com.earth2me.essentials.commands; import org.bukkit.Server; import org.bukkit.command.CommandSender; import com.earth2me.essentials.Essentials; import org.bukkit.entity.Player; import com.earth2me.essentials.User; public class Commandeco extends EssentialsCommand { public Commandeco() { super("eco"); } @Override public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception { if (args.length < 2) { throw new NotEnoughArgumentsException(); } EcoCommands cmd; double amount; try { cmd = EcoCommands.valueOf(args[0].toUpperCase()); amount = Double.parseDouble(args[2].replaceAll("[^0-9\\.]", "")); } catch (Exception ex) { throw new NotEnoughArgumentsException(ex); } if (args[1].contentEquals("*")) { for (Player p : server.getOnlinePlayers()) { User u = ess.getUser(p); switch (cmd) { case GIVE: u.giveMoney(amount); break; case TAKE: u.takeMoney(amount); break; case RESET: u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount); break; } } } else { for (Player p : server.matchPlayer(args[1])) { User u = ess.getUser(p); switch (cmd) { case GIVE: u.giveMoney(amount); break; case TAKE: u.takeMoney(amount); break; case RESET: u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount); break; } } } } private enum EcoCommands { GIVE, TAKE, RESET } }
gpl-3.0
xxmicloxx/TSMusicBot
src/main/java/com/tsmusicbot/web/rest/package-info.java
73
/** * Spring MVC REST controllers. */ package com.tsmusicbot.web.rest;
gpl-3.0
federicoiosue/Omni-Notes
omniNotes/src/main/java/it/feio/android/omninotes/models/views/Fab.java
6668
/* * Copyright (C) 2013-2020 Federico Iosue (federico@iosue.it) * * 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 it.feio.android.omninotes.models.views; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static androidx.core.view.ViewCompat.animate; import static it.feio.android.omninotes.utils.ConstantsBase.FAB_ANIMATION_TIME; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.RelativeLayout; import androidx.annotation.NonNull; import androidx.core.view.ViewPropertyAnimatorListener; import androidx.recyclerview.widget.RecyclerView; import com.getbase.floatingactionbutton.AddFloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import it.feio.android.omninotes.OmniNotes; import it.feio.android.omninotes.R; import it.feio.android.omninotes.helpers.LogDelegate; import it.feio.android.omninotes.models.listeners.OnFabItemClickedListener; public class Fab { private final FloatingActionsMenu floatingActionsMenu; private final RecyclerView recyclerView; private final boolean expandOnLongClick; private boolean fabAllowed; private boolean fabHidden; private boolean fabExpanded; private View overlay; private OnFabItemClickedListener onFabItemClickedListener; public Fab(View fabView, RecyclerView recyclerView, boolean expandOnLongClick) { this.floatingActionsMenu = (FloatingActionsMenu) fabView; this.recyclerView = recyclerView; this.expandOnLongClick = expandOnLongClick; init(); } private void init() { this.fabHidden = true; this.fabExpanded = false; AddFloatingActionButton fabAddButton = floatingActionsMenu .findViewById(R.id.fab_expand_menu_button); fabAddButton.setOnClickListener(v -> { if (!isExpanded() && expandOnLongClick) { performAction(v); } else { performToggle(); } }); fabAddButton.setOnLongClickListener(v -> { if (!expandOnLongClick) { performAction(v); } else { performToggle(); } return true; }); recyclerView.addOnScrollListener( new RecyclerView.OnScrollListener() { public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { if (dy > 0) { hideFab(); } else if (dy < 0) { floatingActionsMenu.collapse(); showFab(); } else { LogDelegate.d("No Vertical Scrolled"); } } }); floatingActionsMenu.findViewById(R.id.fab_checklist).setOnClickListener(onClickListener); floatingActionsMenu.findViewById(R.id.fab_camera).setOnClickListener(onClickListener); if (!expandOnLongClick) { View noteBtn = floatingActionsMenu.findViewById(R.id.fab_note); noteBtn.setVisibility(View.VISIBLE); noteBtn.setOnClickListener(onClickListener); } } private final View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { onFabItemClickedListener.onFabItemClick(v.getId()); } }; public void performToggle() { fabExpanded = !fabExpanded; floatingActionsMenu.toggle(); } private void performAction(View v) { if (fabExpanded) { floatingActionsMenu.toggle(); fabExpanded = false; } else { onFabItemClickedListener.onFabItemClick(v.getId()); } } public void showFab() { if (floatingActionsMenu != null && fabAllowed && fabHidden) { animateFab(0, View.VISIBLE, View.VISIBLE); fabHidden = false; } } public void hideFab() { if (floatingActionsMenu != null && !fabHidden) { floatingActionsMenu.collapse(); animateFab(floatingActionsMenu.getHeight() + getMarginBottom(floatingActionsMenu), View.VISIBLE, View.INVISIBLE); fabHidden = true; fabExpanded = false; } } private void animateFab(int translationY, final int visibilityBefore, final int visibilityAfter) { animate(floatingActionsMenu).setInterpolator(new AccelerateDecelerateInterpolator()) .setDuration(FAB_ANIMATION_TIME) .translationY(translationY) .setListener(new ViewPropertyAnimatorListener() { @Override public void onAnimationStart(View view) { floatingActionsMenu.setVisibility(visibilityBefore); } @Override public void onAnimationEnd(View view) { floatingActionsMenu.setVisibility(visibilityAfter); } @Override public void onAnimationCancel(View view) { // Nothing to do } }); } public void setAllowed(boolean allowed) { fabAllowed = allowed; } private int getMarginBottom(View view) { int marginBottom = 0; final ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); if (layoutParams instanceof ViewGroup.MarginLayoutParams) { marginBottom = ((ViewGroup.MarginLayoutParams) layoutParams).bottomMargin; } return marginBottom; } public void setOnFabItemClickedListener(OnFabItemClickedListener onFabItemClickedListener) { this.onFabItemClickedListener = onFabItemClickedListener; } public void setOverlay(View overlay) { this.overlay = overlay; this.overlay.setOnClickListener(v -> performToggle()); } public void setOverlay(int colorResurce) { View overlayView = new View(OmniNotes.getAppContext()); overlayView.setBackgroundResource(colorResurce); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT); overlayView.setLayoutParams(params); overlayView.setVisibility(View.GONE); overlayView.setOnClickListener(v -> performToggle()); ViewGroup parent = ((ViewGroup) floatingActionsMenu.getParent()); parent.addView(overlayView, parent.indexOfChild(floatingActionsMenu)); this.overlay = overlayView; } public boolean isExpanded() { return fabExpanded; } }
gpl-3.0
rockon999/RockEngine
src/main/java/com/sci/engine/util/Vector2IPool.java
515
package com.sci.engine.util; /** * SciEngine * * @author sci4me * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) */ public class Vector2IPool extends ObjectPool<Vector2I> { private Vector2IPool(long expirationTime) { super(expirationTime); } @Override protected Vector2I create() { return new Vector2I(); } @Override protected boolean validate(Vector2I o) { o.setX(0); o.setY(0); return false; } @Override protected void expire(Vector2I o) { } }
gpl-3.0
StrimBagZ/StrimBagZ
app/src/main/java/net/lubot/strimbagzrewrite/data/model/Twitch/FollowedChannels.java
1474
/* * Copyright 2016 Nicola Fäßler * * This file is part of StrimBagZ. * * StrimBagZ 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.lubot.strimbagzrewrite.data.model.Twitch; import com.google.auto.value.AutoValue; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import java.util.List; @AutoValue public abstract class FollowedChannels { public abstract List<FollowedChannel> follows(); @AutoValue public static abstract class FollowedChannel { public abstract Channel channel(); public static JsonAdapter<FollowedChannel> jsonAdapter(Moshi moshi) { return new AutoValue_FollowedChannels_FollowedChannel.MoshiJsonAdapter(moshi); } } public static JsonAdapter<FollowedChannels> jsonAdapter(Moshi moshi) { return new AutoValue_FollowedChannels.MoshiJsonAdapter(moshi); } }
gpl-3.0
0be1/odm
src/test/java/fr/mtlx/odm/it/EmbeddedDS.java
8117
package fr.mtlx.odm.it; /* * #%L * fr.mtlx.odm * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2012 - 2013 Alexandre Mathieu <me@mtlx.fr> * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import java.io.File; import java.util.HashSet; import java.util.List; import javax.annotation.Nullable; import org.apache.directory.server.constants.ServerDNConstants; import org.apache.directory.server.core.DefaultDirectoryService; import org.apache.directory.server.core.DirectoryService; import org.apache.directory.server.core.partition.Partition; import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmIndex; import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition; import org.apache.directory.server.core.partition.ldif.LdifPartition; import org.apache.directory.server.core.schema.SchemaPartition; import org.apache.directory.server.ldap.LdapServer; import org.apache.directory.server.protocol.shared.transport.TcpTransport; import org.apache.directory.server.xdbm.Index; import org.apache.directory.shared.ldap.entry.ServerEntry; import org.apache.directory.shared.ldap.exception.LdapException; import org.apache.directory.shared.ldap.name.DN; import org.apache.directory.shared.ldap.schema.SchemaManager; import org.apache.directory.shared.ldap.schema.ldif.extractor.SchemaLdifExtractor; import org.apache.directory.shared.ldap.schema.ldif.extractor.impl.DefaultSchemaLdifExtractor; import org.apache.directory.shared.ldap.schema.loader.ldif.LdifSchemaLoader; import org.apache.directory.shared.ldap.schema.manager.impl.DefaultSchemaManager; import org.apache.directory.shared.ldap.schema.registries.SchemaLoader; public final class EmbeddedDS { public final static String PARTITION = "dc=mtlx,dc=fr"; /** The directory service */ private DirectoryService service; /** The LDAP server */ protected LdapServer server; /** * Add a new partition to the server * * @param partitionId The partition Id * @param partitionDn The partition DN * @return The newly added partition * @throws Exception If the partition can't be added */ private Partition addPartition( String partitionId, String partitionDn ) throws Exception { // Create a new partition named 'foo'. JdbmPartition partition = new JdbmPartition(); partition.setId( partitionId ); partition.setPartitionDir( new File( service.getWorkingDirectory(), partitionId ) ); partition.setSuffix( partitionDn ); service.addPartition( partition ); return partition; } /** * Add a new set of index on the given attributes * * @param partition The partition on which we want to add index * @param attrs The list of attributes to index */ private void addIndex( Partition partition, String... attrs ) { // Index some attributes on the apache partition HashSet<Index<?, ServerEntry, Long>> indexedAttributes = new HashSet<Index<?, ServerEntry, Long>>(); for ( String attribute : attrs ) { indexedAttributes.add( new JdbmIndex<String, ServerEntry>( attribute ) ); } ( ( JdbmPartition ) partition ).setIndexedAttributes( indexedAttributes ); } /** * initialize the schema manager and add the schema partition to directory service * * @throws Exception if the schema LDIF files are not found on the classpath */ private void initSchemaPartition() throws Exception { SchemaPartition schemaPartition = service.getSchemaService().getSchemaPartition(); // Init the LdifPartition LdifPartition ldifPartition = new LdifPartition(); String workingDirectory = service.getWorkingDirectory().getPath(); ldifPartition.setWorkingDirectory( workingDirectory + "/schema" ); // Extract the schema on disk (a brand new one) and load the registries File schemaRepository = new File( workingDirectory, "schema" ); SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor( new File( workingDirectory ) ); extractor.extractOrCopy( true ); schemaPartition.setWrappedPartition( ldifPartition ); SchemaLoader loader = new LdifSchemaLoader( schemaRepository ); SchemaManager schemaManager = new DefaultSchemaManager( loader ); service.setSchemaManager( schemaManager ); // We have to load the schema now, otherwise we won't be able // to initialize the Partitions, as we won't be able to parse // and normalize their suffix DN schemaManager.loadAllEnabled(); schemaPartition.setSchemaManager( schemaManager ); List<Throwable> errors = schemaManager.getErrors(); if ( errors.size() != 0 ) { throw new Exception( "Schema load failed : " + errors ); } } /** * Initialize the server. It creates the partition, adds the index, and * injects the context entries for the created partitions. * * @param workDir the directory to be used for storing the data * @throws Exception if there were some problems while initializing the system */ private void initDirectoryService( @Nullable File workDir ) throws Exception { // Initialize the LDAP service service = new DefaultDirectoryService(); if ( workDir != null ) { service.setWorkingDirectory( workDir ); } // first load the schema initSchemaPartition(); // then the system partition // this is a MANDATORY partition Partition systemPartition = addPartition( "system", ServerDNConstants.SYSTEM_DN ); service.setSystemPartition( systemPartition ); // Disable the ChangeLog system service.getChangeLog().setEnabled( false ); service.setDenormalizeOpAttrsEnabled( true ); Partition partition = addPartition( "mtlx", PARTITION ); // Index some attributes on the apache partition addIndex( partition, "objectClass", "ou", "uid" ); // And start the service service.startup(); // Inject the foo root entry if it does not already exist try { service.getAdminSession().lookup( partition.getSuffixDn() ); } catch ( LdapException lnnfe ) { DN dnFoo = new DN( PARTITION ); ServerEntry entryFoo = service.newEntry( dnFoo ); entryFoo.add( "objectClass", "top", "domain", "extensibleObject" ); entryFoo.add( "dc", "mtlx" ); service.getAdminSession().add( entryFoo ); } // We are all done ! } /** * starts the LdapServer * * @throws Exception */ public void startServer() throws Exception { server = new LdapServer(); int serverPort = 10389; server.setTransports( new TcpTransport( serverPort ) ); server.setDirectoryService( service ); server.start(); } public EmbeddedDS(@Nullable File workDir) throws Exception { if (workDir != null) { workDir = new File( System.getProperty( "java.io.tmpdir" ) + "/server-work" ); workDir.mkdirs(); } initDirectoryService( workDir ); startServer(); } public LdapServer getServer() { return server; } }
gpl-3.0
borboton13/sisk13
src/main/com/encens/khipus/service/employees/SalaryMovementServiceBean.java
13428
package com.encens.khipus.service.employees; import com.encens.khipus.exception.ConcurrencyException; import com.encens.khipus.exception.EntryDuplicatedException; import com.encens.khipus.exception.EntryNotFoundException; import com.encens.khipus.framework.service.GenericServiceBean; import com.encens.khipus.model.employees.*; import com.encens.khipus.model.employees.Currency; import com.encens.khipus.util.BigDecimalUtil; import com.encens.khipus.util.Constants; import com.encens.khipus.util.MessageUtils; import com.encens.khipus.util.ValidatorUtil; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.persistence.*; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import java.math.BigDecimal; import java.util.*; /** * SalaryMovementServiceBean * * @author */ @Name("salaryMovementService") @Stateless @AutoCreate @TransactionManagement(TransactionManagementType.BEAN) public class SalaryMovementServiceBean extends GenericServiceBean implements SalaryMovementService { @Resource private UserTransaction userTransaction; @PersistenceContext(unitName = "khipus") private EntityManager em; @In private SalaryMovementTypeService salaryMovementTypeService; @In private CurrencyService currencyService; @Override protected EntityManager getEntityManager() { return em; } @SuppressWarnings({"unchecked"}) public List<SalaryMovement> findByEmployeeAndInitDateEndDate(Employee employee, Date initDate, Date endDate) { return getEntityManager().createNamedQuery("SalaryMovement.findByEmployeeAndInitDateEndDate") .setParameter("employee", employee) .setParameter("initDate", initDate) .setParameter("endDate", endDate) .getResultList(); } @SuppressWarnings({"unchecked"}) public List<SalaryMovement> findByEmployeeAndGestionPayroll(Employee employee, GestionPayroll gestionPayroll) { return getEntityManager().createNamedQuery("SalaryMovement.findByEmployeeAndGestionPayroll") .setParameter("employee", employee) .setParameter("gestionPayroll", gestionPayroll) .getResultList(); } @SuppressWarnings({"unchecked"}) public Map<Long, List<SalaryMovement>> findByPayrollGenerationIdList(Class<? extends GenericPayroll> genericPayrollClass, List<Long> payrollGenerationIdList, GestionPayroll gestionPayroll) { Map<Long, List<SalaryMovement>> result = new HashMap<Long, List<SalaryMovement>>(); if (!ChristmasPayroll.class.equals(genericPayrollClass)) { List<SalaryMovement> salaryMovementList = new ArrayList<SalaryMovement>(0); if (ManagersPayroll.class.equals(genericPayrollClass)) { salaryMovementList = getEntityManager().createNamedQuery("SalaryMovement.findByManagersPayrollIdList") .setParameter("payrollGenerationIdList", payrollGenerationIdList) .setParameter("movementTypeList", MovementType.discountTypeGeneratedByPayrollGeneration()) .setParameter("gestionPayroll", gestionPayroll) .getResultList(); } else if (GeneralPayroll.class.equals(genericPayrollClass)) { salaryMovementList = getEntityManager().createNamedQuery("SalaryMovement.findByGeneralPayrollIdList") .setParameter("payrollGenerationIdList", payrollGenerationIdList) .setParameter("movementTypeList", MovementType.discountTypeGeneratedByPayrollGeneration()) .setParameter("gestionPayroll", gestionPayroll) .getResultList(); } else if (FiscalProfessorPayroll.class.equals(genericPayrollClass)) { salaryMovementList = getEntityManager().createNamedQuery("SalaryMovement.findByFiscalProfessorPayrollIdList") .setParameter("payrollGenerationIdList", payrollGenerationIdList) .setParameter("movementTypeList", MovementType.discountTypeGeneratedByPayrollGeneration()) .setParameter("gestionPayroll", gestionPayroll) .getResultList(); } for (SalaryMovement salaryMovement : salaryMovementList) { List<SalaryMovement> movementList = result.get(salaryMovement.getEmployee().getId()); if (movementList == null) { movementList = new ArrayList<SalaryMovement>(); movementList.add(salaryMovement); result.put(salaryMovement.getEmployee().getId(), movementList); } else { movementList.add(salaryMovement); } } } return result; } public SalaryMovement load(SalaryMovement salaryMovement) throws EntryNotFoundException { SalaryMovement result = null; try { result = (SalaryMovement) getEntityManager().createNamedQuery("SalaryMovement.loadSalaryMovement") .setParameter("id", salaryMovement.getId()).getSingleResult(); } catch (NoResultException ignored) { } if (result == null) { throw new EntryNotFoundException(); } return result; } public void matchGeneratedSalaryMovement(GeneratedPayroll generatedPayroll, List<? extends GenericPayroll> genericPayrollList) throws ConcurrencyException, EntryDuplicatedException { Map<MovementType, SalaryMovementType> defaultSalaryMovementTypeMap = new HashMap<MovementType, SalaryMovementType>(); Currency baseCurrency = null; try { userTransaction.setTransactionTimeout(genericPayrollList.size() * 60); userTransaction.begin(); for (GenericPayroll genericPayroll : genericPayrollList) { if (baseCurrency == null) { if (genericPayroll instanceof GeneralPayroll) { baseCurrency = currencyService.getCurrencyById(Constants.currencyIdSus); } else { baseCurrency = currencyService.findBaseCurrency(); } } createOrUpdate(generatedPayroll, genericPayroll.getEmployee(), defaultSalaryMovementTypeMap, MovementType.TARDINESS_MINUTES, baseCurrency, genericPayroll.getTardinessMinutesDiscount()); createOrUpdate(generatedPayroll, genericPayroll.getEmployee(), defaultSalaryMovementTypeMap, MovementType.LOAN, baseCurrency, genericPayroll.getLoanDiscount()); createOrUpdate(generatedPayroll, genericPayroll.getEmployee(), defaultSalaryMovementTypeMap, MovementType.ADVANCE_PAYMENT, baseCurrency, genericPayroll.getAdvanceDiscount()); createOrUpdate(generatedPayroll, genericPayroll.getEmployee(), defaultSalaryMovementTypeMap, MovementType.AFP, baseCurrency, genericPayroll.getAfp()); createOrUpdate(generatedPayroll, genericPayroll.getEmployee(), defaultSalaryMovementTypeMap, MovementType.RCIVA, baseCurrency, genericPayroll.getRciva()); createOrUpdate(generatedPayroll, genericPayroll.getEmployee(), defaultSalaryMovementTypeMap, MovementType.WIN, baseCurrency, genericPayroll.getWinDiscount()); createOrUpdate(generatedPayroll, genericPayroll.getEmployee(), defaultSalaryMovementTypeMap, MovementType.OTHER_DISCOUNT, baseCurrency, genericPayroll.getOtherDiscounts()); createOrUpdate(generatedPayroll, genericPayroll.getEmployee(), defaultSalaryMovementTypeMap, MovementType.DISCOUNT_OUT_OF_RETENTION, baseCurrency, genericPayroll.getDiscountsOutOfRetention()); } userTransaction.commit(); } catch (OptimisticLockException e) { e.printStackTrace(); try { userTransaction.rollback(); } catch (SystemException e1) { log.error("An unexpected error have happened rolling back", e1); } throw new ConcurrencyException(e); } catch (PersistenceException e) { e.printStackTrace(); try { userTransaction.rollback(); } catch (SystemException e1) { log.error("An unexpected error have happened rolling back", e1); } throw new EntryDuplicatedException(e); } catch (Exception e) { e.printStackTrace(); log.error("An unexpected error have happened ...", e); try { userTransaction.rollback(); } catch (SystemException e1) { log.error("An unexpected error have happened rolling back", e1); } throw new RuntimeException(e); } } @SuppressWarnings({"unchecked"}) private void createOrUpdate(GeneratedPayroll generatedPayroll, Employee employee, Map<MovementType, SalaryMovementType> defaultSalaryMovementTypeMap, MovementType movementType, Currency currency, BigDecimal amount) throws ConcurrencyException, EntryDuplicatedException { if (BigDecimalUtil.isPositive(amount)) { List<SalaryMovement> salaryMovementList = getEntityManager().createNamedQuery("SalaryMovement.findSalaryMovementByMovementTypeAndEmployeeAndGestionPayroll") .setParameter("gestionPayroll", generatedPayroll.getGestionPayroll()) .setParameter("employee", employee) .setParameter("movementType", movementType) .getResultList(); SalaryMovement salaryMovement = null; System.out.println("============> : " + ValidatorUtil.isEmptyOrNull(salaryMovementList) + " - " + employee.getFullName() + "movementType: " + movementType.toString() + " - " + amount); if (!ValidatorUtil.isEmptyOrNull(salaryMovementList)) { if (salaryMovementList.size() == 1) { salaryMovement = salaryMovementList.get(0); salaryMovement.setAmount(amount); salaryMovement.setCurrency(currency); } else { // delete all if exists more that 1 element deleteUnusedMovements(generatedPayroll.getGestionPayroll(), employee, movementType); } } if (salaryMovement != null) { update(salaryMovement); } else { String defaultDescription = generateDefaultDescription(generatedPayroll, movementType); salaryMovement = new SalaryMovement(generatedPayroll.getGestionPayroll().getEndDate(), defaultDescription, amount, generatedPayroll.getGestionPayroll(), currency, getDefaultMovementType(defaultSalaryMovementTypeMap, movementType), employee); System.out.println("======> movementType: " + movementType.toString()); System.out.println("======> defaultSalaryMovementTypeMap: " + defaultSalaryMovementTypeMap); System.out.println("======> getDefaultMovementType: " + getDefaultMovementType(defaultSalaryMovementTypeMap, movementType)); System.out.println(">>>>>>>> salaryMovement: " + salaryMovement); create(salaryMovement); } } else { deleteUnusedMovements(generatedPayroll.getGestionPayroll(), employee, movementType); } } private void deleteUnusedMovements(GestionPayroll gestionPayroll, Employee employee, MovementType movementType) { getEntityManager().createNamedQuery("SalaryMovement.deleteSalaryMovementByMovementTypeAndEmployeeAndGestionPayroll") .setParameter("gestionPayroll", gestionPayroll) .setParameter("employee", employee) .setParameter("movementType", movementType).executeUpdate(); getEntityManager().flush(); } private SalaryMovementType getDefaultMovementType(Map<MovementType, SalaryMovementType> defaultSalaryMovementTypeMap, MovementType movementType) { SalaryMovementType salaryMovementType = defaultSalaryMovementTypeMap.get(movementType); if (salaryMovementType == null) { salaryMovementType = salaryMovementTypeService.findDefaultByMovementType(movementType); defaultSalaryMovementTypeMap.put(movementType, salaryMovementType); } return salaryMovementType; } public String generateDefaultDescription(GeneratedPayroll generatedPayroll, MovementType movementType) { String defaultDescription = MessageUtils.getMessage("SalaryMovement.defaultDescription", generatedPayroll.getName(), MessageUtils.getMessage(movementType.getResourceKey())); if (defaultDescription.length() > 200) { defaultDescription = defaultDescription.substring(0, 199); } return defaultDescription; } }
gpl-3.0
daftano/dl-learner
protege/src/main/java/org/dllearner/tools/protege/SuggestClassPanel.java
2529
/** * Copyright (C) 2007-2009, Jens Lehmann * * This file is part of DL-Learner. * * DL-Learner 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. * * DL-Learner 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.dllearner.tools.protege; import java.awt.BorderLayout; import java.util.List; import javax.swing.JPanel; import javax.swing.JScrollPane; import org.dllearner.core.EvaluatedDescription; import org.dllearner.learningproblems.EvaluatedDescriptionClass; import org.protege.editor.owl.OWLEditorKit; /** * This class is the panel for the suggest list. It shows the descriptions made * by the DL-Learner. * * @author Christian Koetteritzsch * */ public class SuggestClassPanel extends JPanel { private static final long serialVersionUID = 724628423947230L; private final SuggestionsTable suggestionTable; private final JScrollPane suggestScroll; /** * This is the constructor for the suggest panel. It creates a new Scroll * panel and puts the Suggest List in it. * @param m model of the DL-Learner * @param v view of the DL-Learner */ public SuggestClassPanel(OWLEditorKit editorKit) { super(); this.setLayout(new BorderLayout()); // renders scroll bars if necessary suggestScroll = new JScrollPane( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); suggestionTable = new SuggestionsTable(editorKit); suggestionTable.setVisibleRowCount(6); suggestScroll.setViewportView(suggestionTable); add(BorderLayout.CENTER, suggestScroll); } @SuppressWarnings("unchecked") public void setSuggestions(List<? extends EvaluatedDescription> result){ suggestionTable.setSuggestions((List<EvaluatedDescriptionClass>)result); } public SuggestionsTable getSuggestionsTable() { return suggestionTable; } public EvaluatedDescriptionClass getSelectedSuggestion(){ return suggestionTable.getSelectedSuggestion(); } }
gpl-3.0
agent4788/Redis_Admin
src/main/java/net/kleditzsch/App/RedisAdmin/View/Dialog/Set/SetEntryEditDialogController.java
2517
package net.kleditzsch.App.RedisAdmin.View.Dialog.Set; /** * Created by oliver on 02.08.15. */ import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.stage.Stage; import net.kleditzsch.Ui.UiDialogHelper; public class SetEntryEditDialogController { protected String value = ""; protected boolean isSaveButtonClicked = false; @FXML // ResourceBundle that was given to the FXMLLoader private ResourceBundle resources; @FXML // URL location of the FXML file that was given to the FXMLLoader private URL location; @FXML // fx:id="valueTextField" private TextArea valueTextField; // Value injected by FXMLLoader @FXML // fx:id="cancleButton" private Button cancleButton; // Value injected by FXMLLoader @FXML void clickCancleButton(ActionEvent event) { Stage stage = (Stage) cancleButton.getScene().getWindow(); stage.close(); } @FXML void clickSaveButton(ActionEvent event) { String value = valueTextField.getText(); if(value != null && !value.isEmpty()) { this.isSaveButtonClicked = true; this.value = value; } else { UiDialogHelper.showErrorDialog("Fehlerhafte Eingaben", null, "Fehlerhafte Eingaben im Formular"); return; } Stage stage = (Stage) cancleButton.getScene().getWindow(); stage.close(); } @FXML // This method is called by the FXMLLoader when initialization is complete void initialize() { assert valueTextField != null : "fx:id=\"valueTextField\" was not injected: check your FXML file 'SetEntryEditDialogController.fxml'."; assert cancleButton != null : "fx:id=\"cancleButton\" was not injected: check your FXML file 'SetEntryEditDialogController.fxml'."; valueTextField.textProperty().addListener((observable, oldValue, newValue) -> { if(newValue == null || newValue.isEmpty()) { valueTextField.setStyle("-fx-border-color: red; -fx-border-width: 1px;"); } else { valueTextField.setStyle("-fx-border-width: 0px;"); } }); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public boolean isSaveButtonClicked() { return isSaveButtonClicked; } }
gpl-3.0
0xCMP/todo.txt-touch
src/com/todotxt/todotxttouch/TodoWidgetProvider.java
5651
/** * This file is part of Todo.txt Touch, an Android app for managing your todo.txt file (http://todotxt.com). * * Copyright (c) 2009-2012 Todo.txt contributors (http://todotxt.com) * * LICENSE: * * Todo.txt Touch 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. * * Todo.txt Touch 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 Todo.txt Touch. If not, see * <http://www.gnu.org/licenses/>. * * @author Todo.txt contributors <todotxt@yahoogroups.com> * @license http://www.gnu.org/licenses/gpl.html * @copyright 2009-2012 Todo.txt contributors (http://todotxt.com) */ package com.todotxt.todotxttouch; import java.util.List; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.res.Resources; import android.text.SpannableString; import android.util.Log; import android.view.View; import android.widget.RemoteViews; import com.todotxt.todotxttouch.task.Task; import com.todotxt.todotxttouch.task.TaskBag; public class TodoWidgetProvider extends AppWidgetProvider { private static final String TAG = TodoWidgetProvider.class.getName(); private static final int TASKS_TO_DISPLAY = 3; private static final int TASK_ID = 0; private static final int TASK_PRIO = 1; private static final int TASK_TEXT = 2; private final int[][] id = { { R.id.todoWidget_IdTask1, R.id.todoWidget_PrioTask1, R.id.todoWidget_TextTask1 }, { R.id.todoWidget_IdTask2, R.id.todoWidget_PrioTask2, R.id.todoWidget_TextTask2 }, { R.id.todoWidget_IdTask3, R.id.todoWidget_PrioTask3, R.id.todoWidget_TextTask3 } }; @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); // receive intent and update widget content if (Constants.INTENT_WIDGET_UPDATE.equals(intent.getAction())) { Log.d(TAG, "Update widget intent received "); updateWidgetContent(context, AppWidgetManager.getInstance(context), null, null); } } private void updateWidgetContent(Context context, AppWidgetManager appWidgetManager, int[] widgetIds, RemoteViews remoteViews) { Log.d(TAG, "Updating TodoWidgetProvider content."); // get widget ID's if not provided if (widgetIds == null) { widgetIds = appWidgetManager.getAppWidgetIds(new ComponentName( context, TodoWidgetProvider.class.getName())); } // get remoteViews if not provided if (remoteViews == null) { remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget); } // get taskBag from application TaskBag taskBag = ((TodoApplication) ((ContextWrapper) context) .getBaseContext()).getTaskBag(); List<Task> tasks = taskBag.getTasks(); int taskCount = tasks.size(); Resources resources = context.getResources(); for (int i = 0; i < TASKS_TO_DISPLAY; i++) { // get task to display if (i >= tasks.size()) { // no more tasks to display remoteViews.setViewVisibility(id[i][TASK_ID], View.GONE); remoteViews.setViewVisibility(id[i][TASK_PRIO], View.GONE); remoteViews.setViewVisibility(id[i][TASK_TEXT], View.GONE); continue; } Task task = tasks.get(i); if (!task.isCompleted()) { // don't show completed tasks // text String taskText; if (task.inScreenFormat().length() > 33) { taskText = task.inScreenFormat().substring(0, 33) + "..."; } else { taskText = task.inScreenFormat(); } SpannableString ss = new SpannableString(taskText); remoteViews.setTextViewText(id[i][TASK_TEXT], ss); remoteViews.setViewVisibility(id[i][TASK_TEXT], View.VISIBLE); // priority int color = R.color.white; switch (task.getPriority()) { case A: color = R.color.green; break; case B: color = R.color.blue; break; case C: color = R.color.orange; break; case D: color = R.color.gold; } remoteViews.setTextViewText(id[i][TASK_PRIO], task .getPriority().inListFormat()); remoteViews.setTextColor(id[i][TASK_PRIO], resources.getColor(color)); remoteViews.setViewVisibility(id[i][TASK_PRIO], View.VISIBLE); } } remoteViews.setViewVisibility(R.id.empty, taskCount == 0 ? View.VISIBLE : View.GONE); appWidgetManager.updateAppWidget(widgetIds, remoteViews); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget); Intent intent = new Intent(context, LoginScreen.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); remoteViews.setOnClickPendingIntent(R.id.widget_launchbutton, pendingIntent); intent = new Intent(context, AddTask.class); pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); remoteViews.setOnClickPendingIntent(R.id.widget_addbutton, pendingIntent); updateWidgetContent(context, appWidgetManager, appWidgetIds, remoteViews); } }
gpl-3.0
jcarvalho/fenixedu-commons
src/main/java/org/fenixedu/commons/spreadsheet/styles/CellStyle.java
515
package org.fenixedu.commons.spreadsheet.styles; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public abstract class CellStyle { public HSSFCellStyle getStyle(HSSFWorkbook book) { HSSFCellStyle style = book.createCellStyle(); appendToStyle(book, style, null); return style; } protected abstract void appendToStyle(HSSFWorkbook book, HSSFCellStyle style, HSSFFont font); }
gpl-3.0
alkafir/java-testsuit
src/wisedevil/test/TestCaseParser.java
5290
/* testsuit: Unit test framework for Java * Copyright (C) 2013 Alfredo Mungo * * 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 wisedevil.test; import static java.lang.reflect.Modifier.isPublic; import static java.lang.reflect.Modifier.isStatic; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedList; import java.util.LinkedHashSet; import java.util.Set; import wisedevil.test.annotation.*; import wisedevil.test.result.AbstractResultManager; import wisedevil.test.result.ConsoleResultManager; /** * This class is a parser for a test case class. * * <blockquote>Instances of this class are immutable</blockquote> */ public class TestCaseParser { /** * The test case class. */ private final Class<?> _cls; /** * The test case information. */ private TestCaseInfo _info; /** * Initializes a new instance of this class. * * @param c The test case class to parse * * @throws java.lang.NullPointerException If <code>c</code> is null */ public TestCaseParser(Class<?> c) throws NullPointerException { if(c == null) throw new NullPointerException(); _cls = c; _parseTestCaseInfo(); } /** * Returns the cleanup() method (if defined). * * @param inst The test case instance * * @return The cleanup() method of the test case, or null if none has been defined. */ public CleanupMethod getCleanup(Object inst) { try { return new CleanupMethod(inst, _cls.getMethod("cleanup")); } catch(Exception e) { return null; } } /** * Returns the setup() method (if defined). * * @param inst The test case instance * * @return The setup() method of the test case, or null if none has been defined. */ public SetupMethod getSetup(Object inst) { try { return new SetupMethod(inst, _cls.getMethod("setup")); } catch(Exception e) { return null; } } /** * Returns all the public non-static methods annotated with <code>@Test</code> * and not annotated with <code>@Ignore</code>, of type <code>void</code> * and with no arguments. * * @param instance The test case instance to retrieve the methods for * * @return The test methods */ public Set<TestMethod> getTestMethods(Object instance) { final Method[] all = _cls.getDeclaredMethods(); final LinkedHashSet<TestMethod> meths = new LinkedHashSet<TestMethod>(); Arrays.stream(all).forEach(m -> { final Test aTest = m.getAnnotation(Test.class); if(aTest != null) if(aTest.value() && m.getReturnType() == Void.TYPE && m.getParameterTypes().length == 0 && isPublic(m.getModifiers()) && !isStatic(m.getModifiers())) { final Timed time = m.getAnnotation(Timed.class); boolean timed; if(time != null) timed = time.value(); else timed = _info.isTimed(); meths.add(new TestMethod(instance, m, timed)); } }); return meths; } /** * Parses the test case metadata. */ private void _parseTestCaseInfo() { final Timed time = _cls.getAnnotation(Timed.class); // Timing information final Flows flows = _cls.getAnnotation(Flows.class); // Executin information final Name name = _cls.getAnnotation(Name.class); // Identification information final Description desc = _cls.getAnnotation(Description.class); // Description information final TestCaseInfoBuilder builder = new TestCaseInfoBuilder(); final ResultManager[] results = _cls.getAnnotationsByType(ResultManager.class); // The result manager information if(time != null) builder.isTimed(time.value()); if(flows != null) builder .setFlows(flows.value()) .setMaxLingerTime(flows.time()); if(name != null) builder.setName(name.value()); if(desc != null) builder.setDescription(desc.value()); if(results != null) { final LinkedList<Class<? extends AbstractResultManager>> r = new LinkedList<Class<? extends AbstractResultManager>>(); Arrays.stream(results).forEach(rm -> r.add(rm.value())); builder.setResultManagers(r); } builder.setTestCaseClass(_cls); _info = builder.build(); } /** * Returns the meta-information for the test case. * * <p><b>NOTE:</b> multiple calls to this method on the same instance, return the same object.</p> * * @return The meta-information for the test case */ public TestCaseInfo getTestCaseInfo() { return _info; } /** * Parses and returns a new test case. * * @param inst The test case instance * * @return A new TestCase instance */ public TestCase parseNew(Object inst) { return new TestCase(getTestCaseInfo(), getTestMethods(inst), getSetup(inst), getCleanup(inst)); } }
gpl-3.0
wild-swift/AndroidLibs
src/name/wildswift/android/libs/ui/creepingline/CreepingLineAdapter.java
971
/* * Copyright (c) 2013. * This file is part of Wild Swift Solutions For Android library. * * Wild Swift Solutions For Android 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. * * Wild Swift Solutions For Android 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 Android Interface Toolkit. If not, see <http://www.gnu.org/licenses/>. */ package name.wildswift.android.libs.ui.creepingline; import android.widget.Adapter; /** * @author Wild Swift */ public interface CreepingLineAdapter extends Adapter { }
gpl-3.0
rbuj/FreeRouting
src/main/java/net/freerouting/freeroute/board/ShapeTraceEntries.java
32060
/* * Copyright (C) 2014 Alfons Wirtz * website www.freerouting.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 at <http://www.gnu.org/licenses/> * for more details. */ package net.freerouting.freeroute.board; import java.util.Collection; import java.util.Iterator; import net.freerouting.freeroute.geometry.planar.ConvexShape; import net.freerouting.freeroute.geometry.planar.FloatPoint; import net.freerouting.freeroute.geometry.planar.Line; import net.freerouting.freeroute.geometry.planar.Point; import net.freerouting.freeroute.geometry.planar.Polyline; import net.freerouting.freeroute.geometry.planar.TileShape; /** * Auxiliary class used by the shove functions * * @author Alfons Wirtz */ public class ShapeTraceEntries { private static final double C_OFFSET_ADD = 1; public static void cutout_trace(PolylineTrace p_trace, ConvexShape p_shape, int p_cl_class) { if (!p_trace.is_on_the_board()) { System.out.println("ShapeTraceEntries.cutout_trace : trace is deleted"); return; } ConvexShape offset_shape; BasicBoard board = p_trace.board; ShapeSearchTree search_tree = board.search_tree_manager.get_default_tree(); if (search_tree.is_clearance_compensation_used()) { double curr_offset = p_trace.get_compensated_half_width(search_tree) + C_OFFSET_ADD; offset_shape = p_shape.offset(curr_offset); } else { // enlarge the shape in 2 steps for symmetry reasons double cl_offset = board.clearance_value(p_trace.clearance_class_no(), p_cl_class, p_trace.get_layer()) + C_OFFSET_ADD; offset_shape = p_shape.offset(p_trace.get_half_width()); offset_shape = offset_shape.offset(cl_offset); } Polyline trace_lines = p_trace.polyline(); Polyline[] pieces = offset_shape.cutout(trace_lines); if (pieces.length == 1 && pieces[0] == trace_lines) { // nothing cut off return; } if (pieces.length == 2 && offset_shape.is_outside(pieces[0].first_corner()) && offset_shape.is_outside(pieces[1].last_corner())) { fast_cutout_trace(p_trace, pieces[0], pieces[1]); } else { board.remove_item(p_trace); for (int i = 0; i < pieces.length; ++i) { board.insert_trace_without_cleaning(pieces[i], p_trace.get_layer(), p_trace.get_half_width(), p_trace.net_no_arr, p_trace.clearance_class_no(), FixedState.UNFIXED); } } } /** * Optimized function handling the performance critical standard cutout case */ private static void fast_cutout_trace(PolylineTrace p_trace, Polyline p_start_piece, Polyline p_end_piece) { BasicBoard board = p_trace.board; board.additional_update_after_change(p_trace); board.item_list.save_for_undo(p_trace); PolylineTrace start_piece = new PolylineTrace(p_start_piece, p_trace.get_layer(), p_trace.get_half_width(), p_trace.net_no_arr, p_trace.clearance_class_no(), 0, 0, FixedState.UNFIXED, board); start_piece.board = board; board.item_list.insert(start_piece); start_piece.set_on_the_board(true); PolylineTrace end_piece = new PolylineTrace(p_end_piece, p_trace.get_layer(), p_trace.get_half_width(), p_trace.net_no_arr, p_trace.clearance_class_no(), 0, 0, FixedState.UNFIXED, board); end_piece.board = board; board.item_list.insert(end_piece); end_piece.set_on_the_board(true); board.search_tree_manager.reuse_entries_after_cutout(p_trace, start_piece, end_piece); board.remove_item(p_trace); board.communication.observers.notify_new(start_piece); board.communication.observers.notify_new(end_piece); } private static boolean net_nos_equal(int[] p_net_nos_1, int[] p_net_nos_2) { if (p_net_nos_1.length != p_net_nos_2.length) { return false; } for (int curr_net_no_1 : p_net_nos_1) { boolean net_no_found = false; for (int curr_net_no_2 : p_net_nos_2) { if (curr_net_no_1 == curr_net_no_2) { net_no_found = true; } } if (!net_no_found) { return false; } } return true; } final Collection<Via> shove_via_list; private final TileShape shape; private final int layer; private final int[] own_net_nos; private final int cl_class; private CalcFromSide from_side; private final RoutingBoard board; private EntryPoint list_anchor; private int trace_piece_count; private int max_stack_level; private boolean shape_contains_trace_tails = false; private Item found_obstacle = null; /** * Used for shoving traces and vias out of the input shape. p_from_side.no * is the side of p_shape, from where the shove comes. if p_from_side.no < * 0, it will be calculated internally. */ ShapeTraceEntries(TileShape p_shape, int p_layer, int[] p_own_net_nos, int p_cl_type, CalcFromSide p_from_side, RoutingBoard p_board) { shape = p_shape; layer = p_layer; own_net_nos = p_own_net_nos; cl_class = p_cl_type; from_side = p_from_side; board = p_board; list_anchor = null; trace_piece_count = 0; max_stack_level = 0; shove_via_list = new java.util.LinkedList<>(); } /** * Stores traces and vias in p_item_list. Returns false, if p_item_list * contains obstacles, which cannot be shoved aside. If p_is_pad_check. the * check is for vias, otherwise it is for traces. If * p_copper_sharing_allowed, overlaps with traces or pads of the own net are * allowed. */ boolean store_items(Collection<Item> p_item_list, boolean p_is_pad_check, boolean p_copper_sharing_allowed) { Iterator<Item> it = p_item_list.iterator(); while (it.hasNext()) { Item curr_item = it.next(); if (!p_is_pad_check && curr_item instanceof ViaObstacleArea || curr_item instanceof ComponentObstacleArea) { continue; } boolean contains_own_net = curr_item.shares_net_no(this.own_net_nos); if (curr_item instanceof ConductionArea && (contains_own_net || !((ConductionArea) curr_item).get_is_obstacle())) { continue; } if (curr_item.is_shove_fixed() && !contains_own_net) { this.found_obstacle = curr_item; return false; } if (curr_item instanceof Via) { if (p_is_pad_check || !contains_own_net) { shove_via_list.add((Via) curr_item); } } else if (curr_item instanceof PolylineTrace) { PolylineTrace curr_trace = (PolylineTrace) curr_item; if (!store_trace(curr_trace)) { return false; } } else if (contains_own_net) { if (!p_copper_sharing_allowed) { this.found_obstacle = curr_item; return false; } if (p_is_pad_check && !((curr_item instanceof Pin) && ((Pin) curr_item).drill_allowed())) { this.found_obstacle = curr_item; return false; } } else { this.found_obstacle = curr_item; return false; } } search_from_side(); resort(); return calculate_stack_levels(); } /** * calculates the next substitute trace piece. Returns null at he end of the * substitute trace list. */ PolylineTrace next_substitute_trace_piece() { EntryPoint[] entries = pop_piece(); if (entries == null) { return null; } PolylineTrace curr_trace = entries[0].trace; TileShape offset_shape; ShapeSearchTree search_tree = this.board.search_tree_manager.get_default_tree(); if (search_tree.is_clearance_compensation_used()) { double curr_offset = curr_trace.get_compensated_half_width(search_tree) + C_OFFSET_ADD; offset_shape = (TileShape) shape.offset(curr_offset); } else { // enlarge the shape in 2 steps for symmetry reasons offset_shape = (TileShape) shape.offset(curr_trace.get_half_width()); double cl_offset = board.clearance_value(curr_trace.clearance_class_no(), cl_class, layer) + C_OFFSET_ADD; offset_shape = (TileShape) offset_shape.offset(cl_offset); } int edge_count = shape.border_line_count(); int edge_diff = entries[1].edge_no - entries[0].edge_no; // calculate the polyline of the substitute trace Line[] piece_lines = new Line[edge_diff + 3]; // start with the intersecting line of the trace at the start entry. piece_lines[0] = entries[0].trace.polyline().arr[entries[0].trace_line_no]; // end with the intersecting line of the trace at the end entry piece_lines[piece_lines.length - 1] = entries[1].trace.polyline().arr[entries[1].trace_line_no]; // fill the interiour lines of piece_lines with the appropriate edge // lines of the offset shape int curr_edge_no = entries[0].edge_no % edge_count; for (int i = 1; i < piece_lines.length - 1; ++i) { piece_lines[i] = offset_shape.border_line(curr_edge_no); if (curr_edge_no == edge_count - 1) { curr_edge_no = 0; } else { ++curr_edge_no; } } Polyline piece_polyline = new Polyline(piece_lines); if (piece_polyline.is_empty()) { // no valid trace piece, return the next one return next_substitute_trace_piece(); } return new PolylineTrace(piece_polyline, this.layer, curr_trace.get_half_width(), curr_trace.net_no_arr, curr_trace.clearance_class_no(), 0, 0, FixedState.UNFIXED, this.board); } /** * returns the maximum recursion depth for shoving the obstacle traces */ int stack_depth() { return max_stack_level; } /** * returns the number of substitute trace pieces. */ int substitute_trace_count() { return trace_piece_count; } /** * Looks if an unconnected endpoint of a trace of a foreign net is contained * in the interiour of the shape. */ public boolean trace_tails_in_shape() { return this.shape_contains_trace_tails; } /** * Cuts out all traces in p_item_list out of the stored shape. Traces with * net number p_except_net_no are ignored */ void cutout_traces(Collection<Item> p_item_list) { Iterator<Item> it = p_item_list.iterator(); while (it.hasNext()) { Item curr_item = it.next(); if (curr_item instanceof PolylineTrace && !curr_item.shares_net_no(this.own_net_nos)) { cutout_trace((PolylineTrace) curr_item, this.shape, this.cl_class); } } } /** * Returns the item responsible for the failing, if the shove algorithm * failed. */ Item get_found_obstacle() { return this.found_obstacle; } /** * Stores all intersection points of p_trace with the border of the internal * shape enlarged by the half width and the clearance of the corresponding * trace pen. */ private boolean store_trace(PolylineTrace p_trace) { ShapeSearchTree search_tree = this.board.search_tree_manager.get_default_tree(); TileShape offset_shape; if (search_tree.is_clearance_compensation_used()) { double curr_offset = p_trace.get_compensated_half_width(search_tree) + C_OFFSET_ADD; offset_shape = (TileShape) shape.offset(curr_offset); } else { // enlarge the shape in 2 steps for symmetry reasons double cl_offset = board.clearance_value(p_trace.clearance_class_no(), this.cl_class, p_trace.get_layer()) + C_OFFSET_ADD; offset_shape = (TileShape) shape.offset(p_trace.get_half_width()); offset_shape = (TileShape) offset_shape.offset(cl_offset); } // using enlarge here instead offset causes problems because of a // comparison in the constructor of class EntryPoint int[][] entries = offset_shape.entrance_points(p_trace.polyline()); for (int i = 0; i < entries.length; ++i) { int[] entry_tuple = entries[i]; FloatPoint entry_approx = p_trace.polyline().arr[entry_tuple[0]]. intersection_approx(offset_shape.border_line(entry_tuple[1])); insert_entry_point(p_trace, entry_tuple[0], entry_tuple[1], entry_approx); } // Look, if an end point of the trace lies in the interiour of // the shape. This may be the case, if a via touches the shape if (!p_trace.shares_net_no(own_net_nos)) { if (!(p_trace.nets_normal())) { return false; } Point end_corner = p_trace.first_corner(); Collection<Item> contact_list; for (int i = 0; i < 2; ++i) { if (offset_shape.contains(end_corner)) { if (i == 0) { contact_list = p_trace.get_start_contacts(); } else { contact_list = p_trace.get_end_contacts(); } int contact_count = 0; boolean store_end_corner = true; // check for contact object, which is not shovable Iterator<Item> it = contact_list.iterator(); while (it.hasNext()) { Item contact_item = it.next(); if (!contact_item.is_route()) { this.found_obstacle = contact_item; return false; } if (contact_item instanceof Trace) { if (contact_item.is_shove_fixed() || ((Trace) contact_item).get_half_width() != p_trace.get_half_width() || contact_item.clearance_class_no() != p_trace.clearance_class_no()) { if (offset_shape.contains_inside(end_corner)) { this.found_obstacle = contact_item; return false; } } } else if (contact_item instanceof Via) { TileShape via_shape = ((Via) contact_item).get_tile_shape_on_layer(layer); double via_trace_diff = via_shape.smallest_radius() - p_trace.get_compensated_half_width(search_tree); if (!search_tree.is_clearance_compensation_used()) { int via_clearance = board.clearance_value(contact_item.clearance_class_no(), this.cl_class, this.layer); int trace_clearance = board.clearance_value(p_trace.clearance_class_no(), this.cl_class, this.layer); if (trace_clearance > via_clearance) { via_trace_diff += via_clearance - trace_clearance; } } if (via_trace_diff < 0) { // the via is smaller than the trace this.found_obstacle = contact_item; return false; } if (via_trace_diff == 0 && !offset_shape.contains_inside(end_corner)) { // the via need not to be shoved store_end_corner = false; } } ++contact_count; } if (contact_count == 1 && store_end_corner) { Point projection = offset_shape.nearest_border_point(end_corner); { int projection_side = offset_shape.contains_on_border_line_no(projection); int trace_line_segment_no; // the following may not be correct because the trace may not conntain a suitable // line for the construction oof the end line of the substitute trace. if (i == 0) { trace_line_segment_no = 0; } else { trace_line_segment_no = p_trace.polyline().arr.length - 1; } if (projection_side >= 0) { insert_entry_point(p_trace, trace_line_segment_no, projection_side, projection.to_float()); } } } else if (contact_count == 0 && offset_shape.contains_inside(end_corner)) { shape_contains_trace_tails = true; } } end_corner = p_trace.last_corner(); } } this.found_obstacle = p_trace; return true; } private void search_from_side() { if (this.from_side != null && this.from_side.no >= 0) { return; // from side is already legal } EntryPoint curr_node = this.list_anchor; int curr_fromside_no = 0; FloatPoint curr_entry_approx = null; while (curr_node != null) { if (curr_node.trace.shares_net_no(this.own_net_nos)) { curr_fromside_no = curr_node.edge_no; curr_entry_approx = curr_node.entry_approx; break; } curr_node = curr_node.next; } this.from_side = new CalcFromSide(curr_fromside_no, curr_entry_approx); } /** * resorts the intersection points according to from_side_no and removes * redundant points */ private void resort() { int edge_count = this.shape.border_line_count(); if (this.from_side.no < 0 || from_side.no >= edge_count) { System.out.println("ShapeTraceEntries.resort: from side not calculated"); return; } // resort the intersection points, so that they start in the // middle of from_side. FloatPoint compare_corner_1 = shape.corner_approx(this.from_side.no); FloatPoint compare_corner_2; if (from_side.no == edge_count - 1) { compare_corner_2 = shape.corner_approx(0); } else { compare_corner_2 = shape.corner_approx(from_side.no + 1); } double from_point_dist = 0; FloatPoint from_point_projection = null; if (from_side.border_intersection != null) { from_point_projection = from_side.border_intersection.projection_approx(shape.border_line(from_side.no)); from_point_dist = from_point_projection.distance_square(compare_corner_1); if (from_point_dist >= compare_corner_1.distance_square(compare_corner_2)) { from_side = new CalcFromSide(from_side.no, null); } } // search the first intersection point between the side middle // and compare_corner_2 EntryPoint curr = list_anchor; EntryPoint prev = null; while (curr != null) { if (curr.edge_no > this.from_side.no) { break; } if (curr.edge_no == from_side.no) { if (from_side.border_intersection != null) { FloatPoint curr_projection = curr.entry_approx.projection_approx(shape.border_line(from_side.no)); if (curr_projection.distance_square(compare_corner_1) >= from_point_dist && curr_projection.distance_square(from_point_projection) <= curr_projection.distance_square(compare_corner_1)) { break; } } else if (curr.entry_approx.distance_square(compare_corner_2) <= curr.entry_approx.distance_square(compare_corner_1)) { break; } } prev = curr; curr = prev.next; } if (curr != null && curr != list_anchor) { EntryPoint new_anchor = curr; while (curr != null) { prev = curr; curr = prev.next; } prev.next = list_anchor; curr = list_anchor; while (curr != new_anchor) { // add edge_count to curr.side to differentiate points // before and after the middle of from_side curr.edge_no += edge_count; prev = curr; curr = prev.next; } prev.next = null; list_anchor = new_anchor; } // remove intersections between two other intersections of the same // connected set, so that only first and last intersection is kept. if (list_anchor == null) { return; } prev = list_anchor; int[] prev_net_nos = prev.trace.net_no_arr; curr = list_anchor.next; int[] curr_net_nos; EntryPoint next; if (curr != null) { curr_net_nos = curr.trace.net_no_arr; next = curr.next; } else { next = null; curr_net_nos = new int[0]; } EntryPoint before_prev = null; while (next != null) { int[] next_net_nos = next.trace.net_no_arr; if (net_nos_equal(prev_net_nos, curr_net_nos) && net_nos_equal(curr_net_nos, next_net_nos)) { prev.next = next; } else { before_prev = prev; prev = curr; prev_net_nos = curr_net_nos; } curr_net_nos = next_net_nos; curr = next; next = curr.next; } // remove nodes of own net at start and end of the list if (curr != null && net_nos_equal(curr_net_nos, own_net_nos)) { prev.next = null; if (net_nos_equal(prev_net_nos, own_net_nos)) { if (before_prev != null) { before_prev.next = null; } else { list_anchor = null; } } } if (list_anchor != null && list_anchor.trace.nets_equal(own_net_nos)) { list_anchor = list_anchor.next; if (list_anchor != null && list_anchor.trace.nets_equal(own_net_nos)) { list_anchor = list_anchor.next; } } } private boolean calculate_stack_levels() { if (list_anchor == null) { return true; } EntryPoint curr_entry = list_anchor; int[] curr_net_nos = curr_entry.trace.net_no_arr; int curr_level; if (net_nos_equal(curr_net_nos, this.own_net_nos)) { // ignore own net when calculating the stack level curr_level = 0; } else { curr_level = 1; } while (curr_entry != null) { if (curr_entry.stack_level < 0) // not yet calculated { ++trace_piece_count; curr_entry.stack_level = curr_level; if (curr_level > max_stack_level) { if (max_stack_level > 1) { this.found_obstacle = curr_entry.trace; } max_stack_level = curr_level; } } // set stack level for all entries of the current net; EntryPoint check_entry = curr_entry.next; int index_of_next_foreign_set = 0; int index_of_last_occurance_of_set = 0; int next_index = 0; EntryPoint last_own_entry = null; EntryPoint first_foreign_entry = null; while (check_entry != null) { ++next_index; int[] check_net_nos = check_entry.trace.net_no_arr; if (net_nos_equal(check_net_nos, curr_net_nos)) { index_of_last_occurance_of_set = next_index; last_own_entry = check_entry; check_entry.stack_level = curr_entry.stack_level; } else if (index_of_next_foreign_set == 0) { // first occurance of a foreign connected set index_of_next_foreign_set = next_index; first_foreign_entry = check_entry; } check_entry = check_entry.next; } EntryPoint next_entry; if (next_index != 0) { if (index_of_next_foreign_set != 0 && index_of_next_foreign_set < index_of_last_occurance_of_set) // raise level { next_entry = first_foreign_entry; if (next_entry.stack_level >= 0) // already calculated { // stack property failes return false; } ++curr_level; } else if (index_of_last_occurance_of_set != 0) { next_entry = last_own_entry; } else { next_entry = first_foreign_entry; if (next_entry.stack_level >= 0) // already calculated { --curr_level; if (next_entry.stack_level != curr_level) { return false; } } } curr_net_nos = next_entry.trace.net_no_arr; // remove all entries between curr_entry and next_entry, because // they are irrelevant; check_entry = curr_entry.next; while (check_entry != next_entry) { check_entry = check_entry.next; } curr_entry.next = next_entry; curr_entry = next_entry; } else { curr_entry = null; } } if (curr_level != 1) { System.out.println( "ShapeTraceEntries.calculate_stack_levels: curr_level inconsistent"); return false; } return true; } /** * Pops the next piece with minimal level from the imtersection list Returns * null, if the stack is empty. The returned array has 2 elements. The first * is the first entry point, and the second is the last entry point of the * minimal level. */ private EntryPoint[] pop_piece() { if (list_anchor == null) { if (this.trace_piece_count != 0) { System.out.println("ShapeTraceEntries: trace_piece_count is inconsistent"); } return null; } EntryPoint first = list_anchor; EntryPoint prev_first = null; while (first != null) { if (first.stack_level == this.max_stack_level) { break; } prev_first = first; first = first.next; } if (first == null) { System.out.println("ShapeTraceEntries: max_stack_level not found"); return null; } EntryPoint[] result = new EntryPoint[2]; result[0] = first; EntryPoint last = first; EntryPoint after_last = first.next; while (after_last != null) { if (after_last.stack_level != max_stack_level || !after_last.trace.nets_equal(first.trace)) { break; } last = after_last; after_last = last.next; } result[1] = last; // remove the nodes from first to last inclusive if (prev_first != null) { prev_first.next = after_last; } else { list_anchor = after_last; } // recalculate max_stack_level; max_stack_level = 0; EntryPoint curr = list_anchor; while (curr != null) { if (curr.stack_level > max_stack_level) { max_stack_level = curr.stack_level; } curr = curr.next; } --trace_piece_count; if (first.trace.nets_equal(this.own_net_nos)) { // own net is ignored and nay occur only at the lowest level result = pop_piece(); } return result; } private void insert_entry_point(PolylineTrace p_trace, int p_trace_line_no, int p_edge_no, FloatPoint p_entry_approx) { EntryPoint new_entry = new EntryPoint(p_trace, p_trace_line_no, p_edge_no, p_entry_approx); EntryPoint curr_prev = null; EntryPoint curr_next = list_anchor; // insert the new entry into the sorted list while (curr_next != null) { if (curr_next.edge_no > new_entry.edge_no) { break; } if (curr_next.edge_no == new_entry.edge_no) { FloatPoint prev_corner = shape.corner_approx(p_edge_no); FloatPoint next_corner; if (p_edge_no == shape.border_line_count() - 1) { next_corner = shape.corner_approx(0); } else { next_corner = shape.corner_approx(new_entry.edge_no + 1); } if (prev_corner.scalar_product(p_entry_approx, next_corner) <= prev_corner.scalar_product(curr_next.entry_approx, next_corner)) // the projection of the line from prev_corner to p_entry_approx // onto the line from prev_corner to next_corner is smaller // than the projection of the line from prev_corner to // next.entry_approx onto the same line. { break; } } curr_prev = curr_next; curr_next = curr_next.next; } new_entry.next = curr_next; if (curr_prev != null) { curr_prev.next = new_entry; } else { list_anchor = new_entry; } } private static class EntryPoint { final PolylineTrace trace; final int trace_line_no; int edge_no; final FloatPoint entry_approx; int stack_level; EntryPoint next; EntryPoint(PolylineTrace p_trace, int p_trace_line_no, int p_edge_no, FloatPoint p_entry_approx) { trace = p_trace; edge_no = p_edge_no; trace_line_no = p_trace_line_no; entry_approx = p_entry_approx; stack_level = -1; //not yet calculated } } }
gpl-3.0
DAT055-2/OpenFlisp
src/main/java/se/openflisp/sls/component/NandGate.java
2010
/* * Copyright (C) 2014- See AUTHORS file. * * 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 se.openflisp.sls.component; import se.openflisp.sls.*; import se.openflisp.sls.event.ComponentEventDelegator; import se.openflisp.sls.util.SignalCollection; /** * Class representing a logical NAND-gate. * * @author Pär Svedberg <rockkuf@gmail.com> * @version 1.0 */ public class NandGate extends Gate { /** * Creates a logical NAND-gate. * * @param identifier component identifier used for debugging and identifying within a Circuit */ public NandGate(String identifier) { super(identifier); } /** * Creates a logical NAND-gate. * * @param identifier component identifier used for debugging and identifying within a Circuit * @param delegator the event delegator used for notifying listeners of events within a Component */ public NandGate(String identifier, ComponentEventDelegator delegator) { super(identifier, delegator); } /** * {@inheritDoc} */ @Override protected Signal.State evaluateOutput() { if(this.getInputs().size() < 2) { return Signal.State.FLOATING; } if(SignalCollection.containsState(this.getInputs(), Signal.State.LOW)) { return Signal.State.HIGH; } if(SignalCollection.containsState(this.getInputs(), Signal.State.FLOATING)) { return Signal.State.FLOATING; } return Signal.State.LOW; } }
gpl-3.0
program-and-play/scenarios
src/base/main/java/Tasche.java
593
import util.LeereTascheException; import java.util.ArrayList; import java.util.Random; /** * Implementierung einer Tasche */ public class Tasche { private ArrayList<Schluessel> inhalt; public Tasche(ArrayList<Schluessel> inhalt) { this.inhalt = inhalt; } /** * * @return ein zufaelliger Schluessel */ public Schluessel greifeSchluessel() throws Exception { int anzahl = inhalt.size(); if(anzahl <= 0) { throw new LeereTascheException(); } return inhalt.remove(new Random().nextInt(anzahl)); } }
gpl-3.0
thvardhan/Youtuber-s-Lucky-Blocks
src/main/java/thvardhan/ytluckyblocks/entity/EntityTewity.java
3698
package thvardhan.ytluckyblocks.entity; import net.minecraft.entity.Entity; import net.minecraft.entity.IEntityLivingData; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.*; import net.minecraft.entity.monster.EntityIronGolem; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.monster.EntityPigZombie; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.util.DamageSource; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.World; public class EntityTewity extends EntityMob { boolean alwaysRenderNameTag = true; private String name = "Tewtiy"; public EntityTewity(World worldIn) { super(worldIn); ((PathNavigateGround) this.getNavigator()).setBreakDoors(true); this.tasks.addTask(0, new EntityAISwimming(this)); this.tasks.addTask(5, new EntityAIMoveTowardsRestriction(this, 1.0D)); this.tasks.addTask(7, new EntityAIWander(this, 1.0D)); this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); this.tasks.addTask(8, new EntityAILookIdle(this)); this.applyEntityAI(); this.setSize(0.6F, 2.0F); this.setAlwaysRenderNameTag(alwaysRenderNameTag); this.setCustomNameTag(name); } protected void applyEntityAI() { this.tasks.addTask(2, new EntityAIAttackMelee(this, 1.0D, false)); this.tasks.addTask(6, new EntityAIMoveThroughVillage(this, 1.0D, false)); this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true, EntityPigZombie.class)); this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); this.targetTasks.addTask(3, new EntityAINearestAttackableTarget(this, EntityVillager.class, false)); this.targetTasks.addTask(3, new EntityAINearestAttackableTarget(this, EntityIronGolem.class, true)); } protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.FOLLOW_RANGE).setBaseValue(10.0D); this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.3D); this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).setBaseValue(5.0D); this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(45D); this.getEntityAttribute(SharedMonsterAttributes.KNOCKBACK_RESISTANCE).setBaseValue(0.1D); } @Override public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, IEntityLivingData livingdata) { return livingdata; } @Override protected void setSize(float width, float height) { super.setSize(width, height); } @Override public void onLivingUpdate() { super.onLivingUpdate(); } @Override public void onUpdate() { super.onUpdate(); } @Override public boolean attackEntityFrom(DamageSource source, float amount) { return super.attackEntityFrom(source, amount); } @Override public boolean attackEntityAsMob(Entity entityIn) { return super.attackEntityAsMob(entityIn); } @Override protected boolean isValidLightLevel() { return super.isValidLightLevel(); } @Override public boolean getCanSpawnHere() { return super.getCanSpawnHere(); } @Override public void setAlwaysRenderNameTag(boolean alwaysRenderNameTag) { super.setAlwaysRenderNameTag(true); } }
gpl-3.0
brunsen/guinea-track
app/src/main/java/de/brunsen/guineatrack/model/GuineaPigOptionalData.java
5017
package de.brunsen.guineatrack.model; public class GuineaPigOptionalData { private int weight; private String lastBirth; private String dueDate; private String origin; private String limitations; private String castrationDate; private String picturePath; private String entry; private String departure; public GuineaPigOptionalData() { this(0, "", "", "", "", "", "", "", ""); } public GuineaPigOptionalData(int weight, String lastBirth, String dueDate, String origin, String limitations, String castrationDate, String picturePath, String entry, String departure) { this.setWeight(weight); this.setLastBirth(lastBirth); this.setDueDate(dueDate); this.setOrigin(origin); this.setLimitations(limitations); this.setCastrationDate(castrationDate); this.setPicturePath(picturePath); this.setEntry(entry); this.setDeparture(departure); } public GuineaPigOptionalData(GuineaPigOptionalData optionalData) { this(optionalData.getWeight(), optionalData.getLastBirth(), optionalData.getDueDate(), optionalData.getOrigin(), optionalData.getLimitations(), optionalData.getCastrationDate(), optionalData.getPicturePath(), optionalData.getEntry(), optionalData.getDeparture()); } public String getPicturePath() { return picturePath; } public void setPicturePath(String picturePath) { this.picturePath = picturePath; } public String getLastBirth() { return lastBirth; } public void setLastBirth(String lastBirth) { this.lastBirth = lastBirth; } public String getDueDate() { return dueDate; } public void setDueDate(String dueDate) { this.dueDate = dueDate; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public String getLimitations() { return limitations; } public void setLimitations(String limitations) { this.limitations = limitations; } public String getCastrationDate() { return castrationDate; } public void setCastrationDate(String castrationDate) { this.castrationDate = castrationDate; } public String getDeparture() { return departure; } public void setDeparture(String departure) { this.departure = departure; } public String getEntry() { return entry; } public void setEntry(String entry) { this.entry = entry; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof GuineaPigOptionalData)) return false; GuineaPigOptionalData that = (GuineaPigOptionalData) o; if (getWeight() != that.getWeight()) return false; if (getLastBirth() != null ? !getLastBirth().equals(that.getLastBirth()) : that.getLastBirth() != null) return false; if (getDueDate() != null ? !getDueDate().equals(that.getDueDate()) : that.getDueDate() != null) return false; if (getOrigin() != null ? !getOrigin().equals(that.getOrigin()) : that.getOrigin() != null) return false; if (getLimitations() != null ? !getLimitations().equals(that.getLimitations()) : that.getLimitations() != null) return false; if (getCastrationDate() != null ? !getCastrationDate().equals(that.getCastrationDate()) : that.getCastrationDate() != null) return false; if (getPicturePath() != null ? !getPicturePath().equals(that.getPicturePath()) : that.getPicturePath() != null) return false; if (getEntry() != null ? !getEntry().equals(that.getEntry()) : that.getEntry() != null) return false; return getDeparture() != null ? getDeparture().equals(that.getDeparture()) : that.getDeparture() == null; } @Override public int hashCode() { int result = getWeight(); result = 31 * result + (getLastBirth() != null ? getLastBirth().hashCode() : 0); result = 31 * result + (getDueDate() != null ? getDueDate().hashCode() : 0); result = 31 * result + (getOrigin() != null ? getOrigin().hashCode() : 0); result = 31 * result + (getLimitations() != null ? getLimitations().hashCode() : 0); result = 31 * result + (getCastrationDate() != null ? getCastrationDate().hashCode() : 0); result = 31 * result + (getPicturePath() != null ? getPicturePath().hashCode() : 0); result = 31 * result + (getEntry() != null ? getEntry().hashCode() : 0); result = 31 * result + (getDeparture() != null ? getDeparture().hashCode() : 0); return result; } }
gpl-3.0
hantsy/spring-reactive-sample
legacy/boot-data-r2dbc-mysql/src/main/java/com/example/demo/PostRepository.java
547
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.example.demo; import org.springframework.data.r2dbc.repository.Query; import org.springframework.data.r2dbc.repository.R2dbcRepository; import reactor.core.publisher.Flux; interface PostRepository extends R2dbcRepository<Post, Integer> { @Query("SELECT * FROM posts WHERE title like :name") Flux<Post> findByTitleContains(String name); }
gpl-3.0
William-Hai/Binary-Sort-Tree
src/main/java/bst/client/BTreeClient.java
679
package bst.client; import java.util.ArrayList; import bst.tree.NativeBTree; import bst.tree.Node; public class BTreeClient { public static void main(String[] args) { BTreeClient client = new BTreeClient(); client.nativeBTree(); } private void nativeBTree() { int[] nums = { 20, 80, 10, 30, 25, 8, 15, 35, 32, 27, 23, 40, 90 }; NativeBTree tree = NativeBTree.newInstance(50); for (int num : nums) { tree.insert(num); } tree.print(tree.getRoot(), new ArrayList<Node>()); System.out.println(); tree.remove(30); tree.print(tree.getRoot(), new ArrayList<Node>()); } }
gpl-3.0
dichen001/Go4Jobs
JerryLi/189_Rotate Array.java
879
/* Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. [show hint] Hint: Could you do it in-place with O(1) extra space? */ public class Solution { public void rotate(int[] nums, int k) { int moves = k % nums.length; # Rotation offset by length of array if (moves == 0) return; int[] tmp = new int[moves]; int lastIndex = nums.length-1; int t = moves; while(t>0){ tmp[t-1] = nums[lastIndex+t-moves]; t--; } for (int i=lastIndex; i>moves-1; i--){ nums[i] = nums[i-moves]; } for (int i=0; i<moves; i++){ nums[i] = tmp[i]; } } }
gpl-3.0
kopinits/spring-boot-mybatis
src/main/java/com/markus/app/rest/mapper/DealMapper.java
1350
package com.markus.app.rest.mapper; import java.util.List; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Options.FlushCachePolicy; import com.markus.app.rest.model.Deal; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectKey; import org.apache.ibatis.annotations.Update; @Mapper public interface DealMapper{ @Select("select * from deal where id = #{id}") @Options(flushCache=FlushCachePolicy.DEFAULT) Deal findById(@Param("id") Long id); @Select("select * from deal") @Options(flushCache=FlushCachePolicy.DEFAULT) List<Deal> findAll(); @Insert("INSERT into DEAL(id, name, startDate, version, creationTime) VALUES(#{id}, #{name}, #{startDate}, 0, CURRENT_TIMESTAMP)") @SelectKey(statement="SELECT DEAL_SEQUENCE.NEXTVAL FROM DUAL", keyProperty="id", before=true, resultType=Long.class) @Options(flushCache=FlushCachePolicy.DEFAULT) Long insert(Deal deal); @Update("UPDATE DEAL SET name=#{name}, startDate=#{startDate}, version=version+1, lastUpdateTime=CURRENT_TIMESTAMP WHERE id =#{id} and version=#{version}") @Options(flushCache=FlushCachePolicy.DEFAULT) int update(Deal deal); }
gpl-3.0
AKSW/DL-Learner
components-core/src/main/java/org/dllearner/algorithms/qtl/util/filters/PredicateExistenceFilter.java
4454
/** * Copyright (C) 2007 - 2016, Jens Lehmann * <p> * This file is part of DL-Learner. * <p> * DL-Learner is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * <p> * DL-Learner is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.dllearner.algorithms.qtl.util.filters; import org.apache.jena.graph.Node; import org.apache.jena.vocabulary.RDF; import org.dllearner.algorithms.qtl.QueryTreeUtils; import org.dllearner.algorithms.qtl.datastructures.NodeInv; import org.dllearner.algorithms.qtl.datastructures.impl.RDFResourceTree; import org.dllearner.algorithms.qtl.util.Entailment; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.SortedSet; /** * A query tree filter that removes edges whose existence is supposed to be * semantically meaningless from user perspective. * * @author Lorenz Buehmann * */ public class PredicateExistenceFilter extends AbstractTreeFilter<RDFResourceTree> { private Set<Node> existentialMeaninglessProperties = new HashSet<>(); public PredicateExistenceFilter() {} public PredicateExistenceFilter(Set<Node> existentialMeaninglessProperties) { this.existentialMeaninglessProperties = existentialMeaninglessProperties; } /** * @param existentialMeaninglessProperties the existential meaningless properties */ public void setExistentialMeaninglessProperties(Set<Node> existentialMeaninglessProperties) { this.existentialMeaninglessProperties = existentialMeaninglessProperties; } public boolean isMeaningless(Node predicate) { return existentialMeaninglessProperties.contains(predicate); } @Override public RDFResourceTree apply(RDFResourceTree tree) { RDFResourceTree newTree = new RDFResourceTree(tree, false); // if (tree.isLiteralNode() && !tree.isLiteralValueNode()) { // newTree = new RDFResourceTree(tree.getDatatype()); // } else { // newTree = new RDFResourceTree(0); // newTree.setData(tree.getData()); // } // newTree.setAnchorVar(tree.getAnchorVar()); for (Node edge : tree.getEdges()) { // get the label if it's an incoming edge Node edgeLabel = edge instanceof NodeInv ? ((NodeInv) edge).getNode() : edge; // properties that are marked as "meaningless" if (isMeaningless(edgeLabel)) { // if the edge is meaningless // 1. process all children for (RDFResourceTree child : tree.getChildren(edge)) { // add edge if child is resource, literal or a nodes that has to be kept if (child.isResourceNode() || child.isLiteralValueNode() || nodes2Keep.contains(child.getAnchorVar())) { RDFResourceTree newChild = apply(child); newTree.addChild(newChild, edge); } else { // else recursive call and then check if there is no more child attached, i.e. it's just a leaf with a variable as label RDFResourceTree newChild = apply(child); SortedSet<Node> childEdges = newChild.getEdges(); if (!childEdges.isEmpty() && !(childEdges.size() == 1 && childEdges.contains(RDF.type.asNode()))) { newTree.addChild(newChild, edge); } } } } else { // all other properties for (RDFResourceTree child : tree.getChildren(edge)) { RDFResourceTree newChild = apply(child); newTree.addChild(newChild, edge); } } } // we have to run the subsumption check one more time to prune the tree QueryTreeUtils.prune(newTree, null, Entailment.RDFS); return newTree; } }
gpl-3.0
SonTG/gama
msi.gama.lang.gaml/src-gen/msi/gama/lang/gaml/gaml/S_If.java
1338
/** */ package msi.gama.lang.gaml.gaml; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>SIf</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link msi.gama.lang.gaml.gaml.S_If#getElse <em>Else</em>}</li> * </ul> * * @see msi.gama.lang.gaml.gaml.GamlPackage#getS_If() * @model * @generated */ public interface S_If extends Statement { /** * Returns the value of the '<em><b>Else</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Else</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Else</em>' containment reference. * @see #setElse(EObject) * @see msi.gama.lang.gaml.gaml.GamlPackage#getS_If_Else() * @model containment="true" * @generated */ EObject getElse(); /** * Sets the value of the '{@link msi.gama.lang.gaml.gaml.S_If#getElse <em>Else</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Else</em>' containment reference. * @see #getElse() * @generated */ void setElse(EObject value); } // S_If
gpl-3.0
samysadi/acs
src/com/samysadi/acs/tracing/job/JobDownBwTotalProbe.java
1995
/* =============================================================================== Copyright (c) 2014-2015, Samy Sadi. All rights reserved. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. This file is part of ACS - Advanced Cloud Simulator. ACS is part of a research project undertaken by Samy Sadi (samy.sadi.contact@gmail.com) and supervised by Belabbas Yagoubi (byagoubi@gmail.com) in the University of Oran1 Ahmed Benbella, Algeria. ACS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. ACS 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 ACS. If not, see <http://www.gnu.org/licenses/>. =============================================================================== */ package com.samysadi.acs.tracing.job; import com.samysadi.acs.core.tracing.Probe; import com.samysadi.acs.core.tracing.Probed; import com.samysadi.acs.core.tracing.probetypes.DataSizeProbe; import com.samysadi.acs.tracing.AbstractLongIntegratorProbe; import com.samysadi.acs.virtualization.job.Job; /** * * @since 1.0 */ public class JobDownBwTotalProbe extends AbstractLongIntegratorProbe implements DataSizeProbe { public static final String KEY = JobDownBwTotalProbe.class.getSimpleName().substring(0, JobDownBwTotalProbe.class.getSimpleName().length() - 5); @Override public void setup(Probed parent) { if (!(parent instanceof Job)) throw new IllegalArgumentException("Illegal Parent"); super.setup(parent); } @Override protected Probe<?> getWatchedProbe() { return ((Job)JobDownBwTotalProbe.this.getParent()).getProbe(JobDownBwProbe.KEY); } @Override public String getKey() { return KEY; } }
gpl-3.0
Novanoid/Tourney
Application/src/usspg31/tourney/model/undo/ListChange.java
418
package usspg31.tourney.model.undo; import javafx.beans.Observable; import javafx.collections.ObservableList; abstract class ListChange<T> implements UndoAction { final ObservableList<T> list; final T value; ListChange(ObservableList<T> list, T value) { this.list = list; this.value = value; } @Override public Observable getObservable() { return this.list; } }
gpl-3.0
paffman/WBS-Project
src/main/java/de/fhbingen/wbs/calendar/Day.java
1968
/* * The WBS-Tool is a project management tool combining the Work Breakdown * Structure and Earned Value Analysis Copyright (C) 2013 FH-Bingen This * program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your * option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY;; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a * copy of the GNU General Public License along with this program. If not, * see <http://www.gnu.org/licenses/>. */ package de.fhbingen.wbs.calendar; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * Represents a day (without the time). */ public class Day extends Date { /** * Constructor. * @param date * Date to which the day is needed. */ public Day(final Date date) { this(date, false); } /** * Constructor. * @param date * Date to which the day is needed. * @param endOfDay * If true, the created date has the end time 23:59:59. */ public Day(final Date date, final boolean endOfDay) { Calendar cal = new GregorianCalendar(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); if (endOfDay) { cal.add(Calendar.HOUR, DateFunctions.MAX_HOUR_OF_DAY); cal.add(Calendar.MINUTE, DateFunctions.MAX_MINUTE_SECOND_OF_HOUR); cal.add(Calendar.SECOND, DateFunctions.MAX_MINUTE_SECOND_OF_HOUR); } super.setTime(cal.getTimeInMillis()); } }
gpl-3.0
hartwigmedical/hmftools
hmf-common/src/main/java/com/hartwig/hmftools/common/genome/region/GenomeRegionSelectorFactory.java
3389
package com.hartwig.hmftools.common.genome.region; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.hartwig.hmftools.common.genome.chromosome.Chromosome; import com.hartwig.hmftools.common.genome.chromosome.HumanChromosome; import com.hartwig.hmftools.common.genome.position.GenomePosition; import org.jetbrains.annotations.NotNull; public final class GenomeRegionSelectorFactory { private GenomeRegionSelectorFactory() { } @NotNull public static <R extends GenomeRegion> GenomeRegionSelector<R> create(@NotNull final Collection<R> regions) { return new GenomeRegionSelectorListImpl<>(regions); } @NotNull public static <R extends GenomeRegion> GenomeRegionSelector<R> create(@NotNull final Multimap<String, R> regions) { final GenomeRegionSelector<R> nullSelector = new NullGenomeRegionSelector<>(); final Map<String, GenomeRegionSelector<R>> chromosomeSelectors = Maps.newHashMap(); for (final String chromosome : regions.keySet()) { chromosomeSelectors.put(chromosome, new GenomeRegionSelectorListImpl<>(regions.get(chromosome))); } return new GenomeRegionSelector<R>() { @NotNull @Override public Optional<R> select(@NotNull final GenomePosition position) { return chromosomeSelectors.getOrDefault(position.chromosome(), nullSelector).select(position); } @Override public void select(@NotNull final GenomeRegion region, @NotNull final Consumer<R> handler) { chromosomeSelectors.getOrDefault(region.chromosome(), nullSelector).select(region, handler); } }; } @NotNull public static <R extends GenomeRegion> GenomeRegionSelector<R> createImproved(@NotNull final Multimap<Chromosome, R> regions) { final GenomeRegionSelector<R> nullSelector = new NullGenomeRegionSelector<>(); final Map<Chromosome, GenomeRegionSelector<R>> chromosomeSelectors = Maps.newHashMap(); for (final Chromosome chromosome : regions.keySet()) { chromosomeSelectors.put(chromosome, new GenomeRegionSelectorListImpl<>(regions.get(chromosome))); } return new GenomeRegionSelector<R>() { @NotNull @Override public Optional<R> select(@NotNull final GenomePosition position) { return chromosomeSelectors.getOrDefault(HumanChromosome.fromString(position.chromosome()), nullSelector).select(position); } @Override public void select(@NotNull final GenomeRegion region, @NotNull final Consumer<R> handler) { chromosomeSelectors.getOrDefault(HumanChromosome.fromString(region.chromosome()), nullSelector).select(region, handler); } }; } private static class NullGenomeRegionSelector<R extends GenomeRegion> implements GenomeRegionSelector<R> { @NotNull @Override public Optional<R> select(@NotNull final GenomePosition position) { return Optional.empty(); } @Override public void select(@NotNull final GenomeRegion region, @NotNull final Consumer<R> handler) { } } }
gpl-3.0
clementvillanueva/SimpleHDR
src/com/jidesoft/grouper/date/DateYearGrouper.java
1096
package com.jidesoft.grouper.date; import com.jidesoft.converter.ConverterContext; import com.jidesoft.converter.YearNameConverter; import com.jidesoft.grouper.GroupResources; import com.jidesoft.grouper.GrouperContext; import java.util.Calendar; import java.util.Locale; /** */ public class DateYearGrouper extends DateGrouper { public static GrouperContext CONTEXT = new GrouperContext("DateYear"); public Object getValue(Object value) { return getCalendarField(value, Calendar.YEAR); } public String getName() { return GroupResources.getResourceBundle(Locale.getDefault()).getString("Date.year"); } // public static void main(String[] args) { // ObjectGrouper grouper = new DateYearGrouper(); // Calendar calendar = Calendar.getInstance(); // for (int i = 0; i < 40; i++) { // System.out.println(grouper.getGroupValue(calendar)); // calendar.roll(Calendar.YEAR, 1); // } // } @Override public ConverterContext getConverterContext() { return YearNameConverter.CONTEXT; } }
gpl-3.0
dested/CraftbukkitMaps
src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java
1061
package org.bukkit.craftbukkit.entity; import net.minecraft.server.EntityTNTPrimed; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.entity.TNTPrimed; public class CraftTNTPrimed extends CraftEntity implements TNTPrimed { public CraftTNTPrimed(CraftServer server, EntityTNTPrimed entity) { super(server, entity); } @Override public String toString() { return "CraftTNTPrimed"; } public float getYield() { return ((EntityTNTPrimed) getHandle()).yield; } public boolean isIncendiary() { return ((EntityTNTPrimed) getHandle()).isIncendiary; } public void setIsIncendiary(boolean isIncendiary) { ((EntityTNTPrimed) getHandle()).isIncendiary = isIncendiary; } public void setYield(float yield) { ((EntityTNTPrimed) getHandle()).yield = yield; } public int getFuseTicks() { return ((EntityTNTPrimed) getHandle()).a; } public void setFuseTicks(int fuseTicks) { ((EntityTNTPrimed) getHandle()).a = fuseTicks; } }
gpl-3.0
automenta/adams-core
src/main/java/adams/parser/plugin/ParserFunction.java
1773
/* * 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/>. */ /** * ParserFunction.java * Copyright (C) 2013 University of Waikato, Hamilton, New Zealand */ package adams.parser.plugin; import java.io.Serializable; /** * Interface for functions to be used in parsers. * Functions must be stateless, as only a single instance is kept in memory. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 8400 $ */ public interface ParserFunction extends Serializable { /** * Returns the name of the function. * Can only consist of letters, underscores, numbers. * * @return the name */ public String getFunctionName(); /** * Returns the signature of the function. * * @return the signature */ public String getFunctionSignature(); /** * Returns the help string for the function. * * @return the help string */ public String getFunctionHelp(); /** * Gets called from the parser. * * @param params the parameters obtained through the parser * @return the result to be used further in the parser */ public Object callFunction(Object[] params); }
gpl-3.0
MartaVallejo/PhD_Code
Code/ClosestHeuristic/city/display/CellBiologicalValueStyle.java
507
package gi.city.display; import gi.city.Cell; import java.awt.Color; import java.awt.Font; import repast.simphony.visualizationOGL2D.DefaultStyleOGL2D; public class CellBiologicalValueStyle extends DefaultStyleOGL2D{ @Override public Color getColor(Object cell) { double value = Math.abs(((Cell) cell).getBioValue() + ((Cell) cell).getBioNeighbourValue()); if(value > 1){ value = 1; } /*if(value > 0.7) return new Color( 255, 0, 0);*/ return new Color( 0, (int)(value*255), 0); } }
gpl-3.0
craftercms/studio2
src/main/java/org/craftercms/studio/impl/v1/util/PathMacrosTransaltor.java
1744
/* * Copyright (C) 2007-2020 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.craftercms.studio.impl.v1.util; import org.apache.commons.lang3.StringUtils; import org.craftercms.studio.api.v1.constant.DmConstants; import org.craftercms.studio.api.v1.exception.ServiceLayerException; import java.util.Map; public class PathMacrosTransaltor { public static final String PAGEID = "{pageId}"; public static final String PAGE_GROUPID = "{pageGroupId}"; /** * Match the URL with the know patterns and translate them to actual value * * @param path */ public static String resolvePath(String path,Map<String,String> properties) throws ServiceLayerException { String pageId = properties.get(DmConstants.KEY_PAGE_ID); String groupId = properties.get(DmConstants.KEY_PAGE_GROUP_ID); if(StringUtils.isNotEmpty(pageId) && (path.contains(PAGEID))){ path = path.replace(PAGEID, pageId); } if(StringUtils.isNotEmpty(groupId) && (path.contains(PAGE_GROUPID))){ path = path.replace(PAGE_GROUPID, groupId); } return path; } }
gpl-3.0
KubaKaszycki/FreeCraft
src/main/java/kk/freecraft/tileentity/TileEntityBrewingStand.java
10749
/* * Copyright (C) Mojang AB * All rights reserved. */ package kk.freecraft.tileentity; import java.util.Arrays; import java.util.List; import kk.freecraft.block.BlockBrewingStand; import kk.freecraft.block.state.IBlockState; import kk.freecraft.entity.player.EntityPlayer; import kk.freecraft.entity.player.InventoryPlayer; import kk.freecraft.init.Items; import kk.freecraft.inventory.Container; import kk.freecraft.inventory.ContainerBrewingStand; import kk.freecraft.inventory.ISidedInventory; import kk.freecraft.item.Item; import kk.freecraft.item.ItemPotion; import kk.freecraft.item.ItemStack; import kk.freecraft.nbt.NBTTagCompound; import kk.freecraft.nbt.NBTTagList; import kk.freecraft.potion.PotionHelper; import kk.freecraft.server.gui.IUpdatePlayerListBox; import kk.freecraft.util.EnumFacing; public class TileEntityBrewingStand extends TileEntityLockable implements IUpdatePlayerListBox, ISidedInventory { /** * an array of the input slot indices */ private static final int[] inputSlots = new int[]{3}; /** * an array of the output slot indices */ private static final int[] outputSlots = new int[]{0, 1, 2}; /** * The ItemStacks currently placed in the slots of the brewing stand */ private ItemStack[] brewingItemStacks = new ItemStack[4]; private int brewTime; /** * an integer with each bit specifying whether that slot of the stand * contains a potion */ private boolean[] filledSlots; /** * used to check if the current ingredient has been removed from the brewing * stand during brewing */ private Item ingredientID; private String field_145942_n; /** * Gets the name of this command sender (usually username, but possibly * "Rcon") */ public String getName() { return this.hasCustomName() ? this.field_145942_n : "container.brewing"; } /** * Returns true if this thing is named */ public boolean hasCustomName() { return this.field_145942_n != null && this.field_145942_n.length() > 0; } public void func_145937_a(String p_145937_1_) { this.field_145942_n = p_145937_1_; } /** * Returns the number of slots in the inventory. */ public int getSizeInventory() { return this.brewingItemStacks.length; } /** * Updates the JList with a new model. */ public void update() { if (this.brewTime > 0) { --this.brewTime; if (this.brewTime == 0) { this.brewPotions(); this.markDirty(); } else if (!this.canBrew()) { this.brewTime = 0; this.markDirty(); } else if (this.ingredientID != this.brewingItemStacks[3].getItem()) { this.brewTime = 0; this.markDirty(); } } else if (this.canBrew()) { this.brewTime = 400; this.ingredientID = this.brewingItemStacks[3].getItem(); } if (!this.worldObj.isRemote) { boolean[] var1 = this.func_174902_m(); if (!Arrays.equals(var1, this.filledSlots)) { this.filledSlots = var1; IBlockState var2 = this.worldObj.getBlockState(this.getPos()); if (!(var2.getBlock() instanceof BlockBrewingStand)) { return; } for (int var3 = 0; var3 < BlockBrewingStand.BOTTLE_PROPS.length; ++var3) { var2 = var2.withProperty(BlockBrewingStand.BOTTLE_PROPS[var3], Boolean.valueOf(var1[var3])); } this.worldObj.setBlockState(this.pos, var2, 2); } } } private boolean canBrew() { if (this.brewingItemStacks[3] != null && this.brewingItemStacks[3].stackSize > 0) { ItemStack var1 = this.brewingItemStacks[3]; if (!var1.getItem().isPotionIngredient(var1)) { return false; } else { boolean var2 = false; for (int var3 = 0; var3 < 3; ++var3) { if (this.brewingItemStacks[var3] != null && this.brewingItemStacks[var3].getItem() == Items.potionitem) { int var4 = this.brewingItemStacks[var3].getMetadata(); int var5 = this.func_145936_c(var4, var1); if (!ItemPotion.isSplash(var4) && ItemPotion.isSplash(var5)) { var2 = true; break; } List var6 = Items.potionitem.getEffects(var4); List var7 = Items.potionitem.getEffects(var5); if ((var4 <= 0 || var6 != var7) && (var6 == null || !var6.equals(var7) && var7 != null) && var4 != var5) { var2 = true; break; } } } return var2; } } else { return false; } } private void brewPotions() { if (this.canBrew()) { ItemStack var1 = this.brewingItemStacks[3]; for (int var2 = 0; var2 < 3; ++var2) { if (this.brewingItemStacks[var2] != null && this.brewingItemStacks[var2].getItem() == Items.potionitem) { int var3 = this.brewingItemStacks[var2].getMetadata(); int var4 = this.func_145936_c(var3, var1); List var5 = Items.potionitem.getEffects(var3); List var6 = Items.potionitem.getEffects(var4); if ((var3 <= 0 || var5 != var6) && (var5 == null || !var5.equals(var6) && var6 != null)) { if (var3 != var4) { this.brewingItemStacks[var2].setItemDamage(var4); } } else if (!ItemPotion.isSplash(var3) && ItemPotion.isSplash(var4)) { this.brewingItemStacks[var2].setItemDamage(var4); } } } if (var1.getItem().hasContainerItem()) { this.brewingItemStacks[3] = new ItemStack(var1.getItem().getContainerItem()); } else { --this.brewingItemStacks[3].stackSize; if (this.brewingItemStacks[3].stackSize <= 0) { this.brewingItemStacks[3] = null; } } } } private int func_145936_c(int p_145936_1_, ItemStack p_145936_2_) { return p_145936_2_ == null ? p_145936_1_ : (p_145936_2_.getItem().isPotionIngredient(p_145936_2_) ? PotionHelper.applyIngredient(p_145936_1_, p_145936_2_.getItem().getPotionEffect(p_145936_2_)) : p_145936_1_); } public void readFromNBT(NBTTagCompound compound) { super.readFromNBT(compound); NBTTagList var2 = compound.getTagList("Items", 10); this.brewingItemStacks = new ItemStack[this.getSizeInventory()]; for (int var3 = 0; var3 < var2.tagCount(); ++var3) { NBTTagCompound var4 = var2.getCompoundTagAt(var3); byte var5 = var4.getByte("Slot"); if (var5 >= 0 && var5 < this.brewingItemStacks.length) { this.brewingItemStacks[var5] = ItemStack.loadItemStackFromNBT(var4); } } this.brewTime = compound.getShort("BrewTime"); if (compound.hasKey("CustomName", 8)) { this.field_145942_n = compound.getString("CustomName"); } } public void writeToNBT(NBTTagCompound compound) { super.writeToNBT(compound); compound.setShort("BrewTime", (short) this.brewTime); NBTTagList var2 = new NBTTagList(); for (int var3 = 0; var3 < this.brewingItemStacks.length; ++var3) { if (this.brewingItemStacks[var3] != null) { NBTTagCompound var4 = new NBTTagCompound(); var4.setByte("Slot", (byte) var3); this.brewingItemStacks[var3].writeToNBT(var4); var2.appendTag(var4); } } compound.setTag("Items", var2); if (this.hasCustomName()) { compound.setString("CustomName", this.field_145942_n); } } /** * Returns the stack in slot i */ public ItemStack getStackInSlot(int slotIn) { return slotIn >= 0 && slotIn < this.brewingItemStacks.length ? this.brewingItemStacks[slotIn] : null; } /** * Removes from an inventory slot (first arg) up to a specified number * (second arg) of items and returns them in a new stack. */ public ItemStack decrStackSize(int index, int count) { if (index >= 0 && index < this.brewingItemStacks.length) { ItemStack var3 = this.brewingItemStacks[index]; this.brewingItemStacks[index] = null; return var3; } else { return null; } } /** * When some containers are closed they call this on each slot, then drop * whatever it returns as an EntityItem - like when you close a workbench * GUI. */ public ItemStack getStackInSlotOnClosing(int index) { if (index >= 0 && index < this.brewingItemStacks.length) { ItemStack var2 = this.brewingItemStacks[index]; this.brewingItemStacks[index] = null; return var2; } else { return null; } } /** * Sets the given item stack to the specified slot in the inventory (can be * crafting or armor sections). */ public void setInventorySlotContents(int index, ItemStack stack) { if (index >= 0 && index < this.brewingItemStacks.length) { this.brewingItemStacks[index] = stack; } } /** * Returns the maximum stack size for a inventory slot. Seems to always be * 64, possibly will be extended. *Isn't this more of a set than a get?* */ public int getInventoryStackLimit() { return 64; } /** * Do not make give this method the name canInteractWith because it clashes * with Container */ public boolean isUseableByPlayer(EntityPlayer playerIn) { return this.worldObj.getTileEntity(this.pos) != this ? false : playerIn.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, (double) this.pos.getZ() + 0.5D) <= 64.0D; } public void openInventory(EntityPlayer playerIn) { } public void closeInventory(EntityPlayer playerIn) { } /** * Returns true if automation is allowed to insert the given stack (ignoring * stack size) into the given slot. */ public boolean isItemValidForSlot(int index, ItemStack stack) { return index == 3 ? stack.getItem().isPotionIngredient(stack) : stack.getItem() == Items.potionitem || stack.getItem() == Items.glass_bottle; } public boolean[] func_174902_m() { boolean[] var1 = new boolean[3]; for (int var2 = 0; var2 < 3; ++var2) { if (this.brewingItemStacks[var2] != null) { var1[var2] = true; } } return var1; } public int[] getSlotsForFace(EnumFacing side) { return side == EnumFacing.UP ? inputSlots : outputSlots; } /** * Returns true if automation can insert the given item in the given slot * from the given side. Args: slot, item, side */ public boolean canInsertItem(int slotIn, ItemStack itemStackIn, EnumFacing direction) { return this.isItemValidForSlot(slotIn, itemStackIn); } /** * Returns true if automation can extract the given item in the given slot * from the given side. Args: slot, item, side */ public boolean canExtractItem(int slotId, ItemStack stack, EnumFacing direction) { return true; } public String getGuiID() { return "minecraft:brewing_stand"; } public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) { return new ContainerBrewingStand(playerInventory, this); } public int getField(int id) { switch (id) { case 0: return this.brewTime; default: return 0; } } public void setField(int id, int value) { switch (id) { case 0: this.brewTime = value; default: } } public int getFieldCount() { return 1; } public void clearInventory() { for (int var1 = 0; var1 < this.brewingItemStacks.length; ++var1) { this.brewingItemStacks[var1] = null; } } }
gpl-3.0
woboq/p300
src/main/java/de/guruz/p300/utils/AePlayWave.java
2606
package de.guruz.p300.utils; /* * From http://www.anyexample.com/programming/java/java_play_wav_sound_file.xml * * Adapted by Markus Goetz */ import java.io.File; import java.io.IOException; import java.net.URL; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.FloatControl; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; public class AePlayWave extends Thread { protected static AePlayWave m_one; public static void playOneAtATime (URL u) { synchronized (AePlayWave.class) { if (m_one == null) { m_one = new AePlayWave (u); m_one.start(); } } } protected static void playOneAtATimeStopped () { synchronized (AePlayWave.class) { m_one = null; } } private URL m_url; private Position curPosition; private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb enum Position { LEFT, RIGHT, NORMAL }; protected AePlayWave(URL u) { m_url = u; curPosition = Position.NORMAL; } public void run() { try { AudioInputStream audioInputStream = null; try { audioInputStream = AudioSystem.getAudioInputStream(m_url); } catch (UnsupportedAudioFileException e1) { e1.printStackTrace(); return; } catch (IOException e1) { e1.printStackTrace(); return; } AudioFormat format = audioInputStream.getFormat(); SourceDataLine auline = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); try { auline = (SourceDataLine) AudioSystem.getLine(info); auline.open(format); } catch (LineUnavailableException e) { e.printStackTrace(); return; } catch (Exception e) { e.printStackTrace(); return; } if (auline.isControlSupported(FloatControl.Type.PAN)) { FloatControl pan = (FloatControl) auline .getControl(FloatControl.Type.PAN); if (curPosition == Position.RIGHT) pan.setValue(1.0f); else if (curPosition == Position.LEFT) pan.setValue(-1.0f); } auline.start(); int nBytesRead = 0; byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; try { while (nBytesRead != -1) { nBytesRead = audioInputStream.read(abData, 0, abData.length); if (nBytesRead >= 0) auline.write(abData, 0, nBytesRead); } } catch (IOException e) { e.printStackTrace(); return; } finally { auline.drain(); auline.close(); } } finally { playOneAtATimeStopped (); } } }
gpl-3.0
wandora-team/wandora
src/org/wandora/application/tools/CopyTopicPlayers.java
1690
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2016 Wandora Team * * 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/>. * * * CopyTopicPlayers.java * * Created on 13. huhtikuuta 2006, 11:58 * */ package org.wandora.application.tools; import org.wandora.topicmap.TopicMapException; import org.wandora.application.contexts.*; /** * Copies association player topics of associations in selected topics to clipboard. * * @author akivela */ public class CopyTopicPlayers extends CopyTopics { public CopyTopicPlayers() throws TopicMapException { } @Override public String getName() { return "Copy topic players"; } @Override public String getDescription() { return "Copies association player topics of associations in selected topics to clipboard."; } @Override public void initialize(int copyOrders, int includeOrders) { super.initialize(copyOrders, includeOrders); setContext(new PlayerContext()); } }
gpl-3.0
cosminrentea/roda
src/main/java/ro/roda/ddi/DocDscrType.java
5370
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 // 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: 2012.10.05 at 02:34:54 AM EEST // package ro.roda.ddi; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p> * Java class for docDscrType complex type. * * <p> * The following schema fragment specifies the expected content contained within * this class. * * <pre> * &lt;complexType name="docDscrType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="citation" type="{http://www.icpsr.umich.edu/DDI}citationType" minOccurs="0"/> * &lt;element name="guide" type="{http://www.icpsr.umich.edu/DDI}guideType" minOccurs="0"/> * &lt;element name="docStatus" type="{http://www.icpsr.umich.edu/DDI}docStatusType" minOccurs="0"/> * &lt;element name="docSrc" type="{http://www.icpsr.umich.edu/DDI}docSrcType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="notes" type="{http://www.icpsr.umich.edu/DDI}notesType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="ID" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;attribute name="xml-lang" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" /> * &lt;attribute name="source" default="producer"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="archive"/> * &lt;enumeration value="producer"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "docDscrType", propOrder = { "citation", "docSrc" }) @Entity @Table(schema = "ddi",name = "DocumentDescription") public class DocDscrType { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @XmlTransient private long id_; public long getId_() { return id_; } public void setId_(long id_) { this.id_ = id_; } @ManyToOne @JoinColumn(name = "Codebook_id") @XmlTransient private CodeBook codebook; public CodeBook getCodebook() { return codebook; } public void setCodebook(CodeBook codebook) { this.codebook = codebook; } @OneToOne(cascade = { CascadeType.ALL }) protected CitationType citation; @OneToMany(cascade = { CascadeType.ALL }, mappedBy = "docdscrtype") protected List<DocSrcType> docSrc; @XmlAttribute(name = "ID") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; // @XmlAttribute(name = "xml-lang") // @XmlJavaTypeAdapter(CollapsedStringAdapter.class) // @XmlSchemaType(name = "NMTOKEN") // protected String xmlLang; // @XmlAttribute // @XmlJavaTypeAdapter(CollapsedStringAdapter.class) // protected String source; /** * Gets the value of the citation property. * * @return possible object is {@link CitationType } * */ public CitationType getCitation() { return citation; } /** * Sets the value of the citation property. * * @param value * allowed object is {@link CitationType } * */ public void setCitation(CitationType value) { this.citation = value; } /** * Gets the value of the docSrc property. * * <p> * This accessor method returns a reference to the live List, not a * snapshot. Therefore any modification you make to the returned List will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the docSrc property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getDocSrc().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the List * {@link DocSrcType } * * */ public List<DocSrcType> getDocSrc() { if (docSrc == null) { docSrc = new ArrayList<DocSrcType>(); } return this.docSrc; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getID() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setID(String value) { this.id = value; } }
gpl-3.0
NoCheatPlus/NoCheatPlus
NCPCore/src/main/java/fr/neatmonster/nocheatplus/checks/moving/location/setback/MagicSetBack.java
907
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.neatmonster.nocheatplus.checks.moving.location.setback; /** * Default magic. * @author asofold * */ public class MagicSetBack { // TODO: Consider flags for type of set back locations, for fast inclusion+exclusion. }
gpl-3.0
Gspin96/blynk-server
server/core/src/main/java/cc/blynk/server/core/model/widgets/ui/Tabs.java
377
package cc.blynk.server.core.model.widgets.ui; import cc.blynk.server.core.model.widgets.NoPinWidget; /** * The Blynk Project. * Created by Dmitriy Dumanskiy. * Created on 07.02.16. */ public class Tabs extends NoPinWidget { public Tab[] tabs; public Tabs() { this.tabId = -1; } @Override public int getPrice() { return 0; } }
gpl-3.0
woopla/plantuml-server
src/main/java/net/sourceforge/plantuml/servlet/SvgServlet.java
1367
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ package net.sourceforge.plantuml.servlet; import net.sourceforge.plantuml.FileFormat; /* * SVG servlet of the webapp. * This servlet produces the UML diagram in SVG format. */ @SuppressWarnings("serial") public class SvgServlet extends UmlDiagramService { @Override public FileFormat getOutputFormat() { return FileFormat.SVG; } }
gpl-3.0
devent/prefdialog
prefdialog-misc-swing/src/main/java/com/anrisoftware/prefdialog/miscswing/multichart/freechart/FreechartXYChartFactory.java
1094
/* * Copyright 2013-2016 Erwin Müller <erwin.mueller@deventm.org> * * This file is part of prefdialog-misc-swing. * * prefdialog-misc-swing is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * prefdialog-misc-swing 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 Lesser General Public License * along with prefdialog-misc-swing. If not, see <http://www.gnu.org/licenses/>. */ package com.anrisoftware.prefdialog.miscswing.multichart.freechart; import org.jfree.chart.JFreeChart; import com.anrisoftware.prefdialog.miscswing.awtcheck.OnAwt; public interface FreechartXYChartFactory { @OnAwt FreechartXYChart create(String name, JFreeChart chart); }
gpl-3.0
imr/Electric8
com/sun/electric/tool/MultiTaskJob.java
7245
/* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: MultiTaskJob.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) 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. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool; import com.sun.electric.database.Environment; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; /** * This generic class supports map-reduce scheme of computation on Electric database. * Large computation has three stages: * 1) Large computation is splitted into smaller tasks. * Smaller tasks are identified by TaskKey class. * This stage is performed by prepareTasks method, which schedules each task by startTask method. * 2) Tasks run in parallel, each giving result of TaskResult type. * This stage is performed by runTask method for each instance of task. * 3) TaskResults are combinded into final result of Result type. * This stage is performed by mergeTaskResults method. * 4) Result is consumed on server. * This stage is performed by consumer.consume method. */ public abstract class MultiTaskJob<TaskKey,TaskResult,Result> extends Job { private transient LinkedHashMap<TaskKey,Task> tasks; private transient ArrayList<Task> allTasks; private transient int tasksDone; private transient Environment env; private transient EThread ownerThread; private transient int numberOfRunningThreads; private transient int numberOfFinishedThreads; private Consumer<Result> consumer; /** * Constructor creates a new instance of MultiTaskJob. * @param jobName a string that describes this MultiTaskJob. * @param t the Tool that originated this MultiTaskJob. * @param c interface which consumes the result on server */ public MultiTaskJob(String jobName, Tool t, Consumer<Result> c) { super(jobName, t, Job.Type.SERVER_EXAMINE, null, null, Job.Priority.USER); this.consumer = c; } /** * This abstract method split large computation into smaller task. * Smaller tasks are identified by TaskKey class. * Each task is scheduled by startTask method. * @throws com.sun.electric.tool.JobException */ public abstract void prepareTasks() throws JobException; /** * This abtract methods performs computation of each task. * @param taskKey task key which identifies the task * @return result of task computation * @throws com.sun.electric.tool.JobException */ public abstract TaskResult runTask(TaskKey taskKey) throws JobException; /** * This abtract method combines task results into final result. * @param taskResults map which contains result of each completed task. * @return final result which is obtained by merging task results. * @throws com.sun.electric.tool.JobException */ public abstract Result mergeTaskResults(Map<TaskKey,TaskResult> taskResults) throws JobException; // /** // * This method executes in the Client side after normal termination of full computation. // * This method should perform all needed termination actions. // * @param result result of full computation. // */ // public void terminateOK(Result result) {} /** * This method is not overriden by subclasses. * Override methods prepareTasks, runTask, mergeTaskResults instead. * @throws JobException */ @Override public final boolean doIt() throws JobException { tasks = new LinkedHashMap<TaskKey,Task>(); allTasks = new ArrayList<Task>(); prepareTasks(); env = Environment.getThreadEnvironment(); ownerThread = (EThread)Thread.currentThread(); numberOfRunningThreads = ServerJobManager.getMaxNumberOfThreads(); for (int id = 0; id < numberOfRunningThreads; id++) new WorkingThread(id).start(); waitTasks(); LinkedHashMap<TaskKey,TaskResult> taskResults = new LinkedHashMap<TaskKey,TaskResult>(); for (Task task: tasks.values()) { if (task.taskResult != null) taskResults.put(task.taskKey, task.taskResult); } Result result = mergeTaskResults(taskResults); if (consumer != null) consumer.consume(result); return true; } /** * Schedules task. Should be callled from prepareTasks or runTask methods only. * @param taskName task name which is appeared in Jobs Explorer Tree * @param taskKey task key which identifies the task. */ public synchronized void startTask(String taskName, TaskKey taskKey) { Task task = new Task(taskName, taskKey); if (tasks.containsKey(taskKey)) throw new IllegalArgumentException(); tasks.put(taskKey, task); allTasks.add(task); } private synchronized Task getTask() { if (tasksDone == allTasks.size()) { return null; } return allTasks.get(tasksDone++); } private synchronized void waitTasks() { try { while (numberOfFinishedThreads < numberOfRunningThreads) wait(); } catch (InterruptedException e) { e.printStackTrace(); } } private synchronized void finishWorkingThread() { numberOfFinishedThreads++; notify(); } private class Task { private final String taskName; private final TaskKey taskKey; private TaskResult taskResult; private Task(String taskName, TaskKey taskKey) { this.taskName = taskName; this.taskKey = taskKey; } } class WorkingThread extends EThread { private WorkingThread(int id) { super("WorkingThread-"+id); userInterface = new ServerJobManager.UserInterfaceRedirect(ownerThread.ejob.jobKey); ejob = ownerThread.ejob; isServerThread = ownerThread.isServerThread; database = ownerThread.database; } @Override public void run() { Environment.setThreadEnvironment(env); for (;;) { Task t = getTask(); if (t == null) { break; } try { t.taskResult = runTask(t.taskKey); } catch (Throwable e) { e.getStackTrace(); e.printStackTrace(System.out); e.printStackTrace(); } } finishWorkingThread(); } } }
gpl-3.0
anwilli5/coin-collection-android
app/src/main/java/com/spencerpages/UnitTests.java
27884
/* * Coin Collection, an Android app that helps users track the coins that they've collected * Copyright (C) 2010-2016 Andrew Williams * * This file is part of Coin Collection. * * Coin Collection 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. * * Coin Collection 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 Coin Collection. If not, see <http://www.gnu.org/licenses/>. */ package com.spencerpages; import java.util.ArrayList; import java.util.HashMap; import android.content.Context; import android.util.Log; import com.coincollection.CoinPageCreator; /** * Basic unit test suite - mainly just a way to sanity check that when adding new coins (for * instance, as the years progress and near coins are minted), we add in all the ones that we need * to. */ class UnitTests { private Context mContext = null; public boolean runTests(Context context) { mContext = context; // TODO Replace with better testing! boolean result = testAllMintMarks(); if(!result){ return false; } result = testPMintMarks(); if(!result){ return false; } result = testDMintMarks(); if(!result){ return false; } result = testSMintMarks(); if(!result){ return false; } result = testOMintMarks(); if(!result){ return false; } result = testCCMintMarks(); if(!result){ return false; } // All tests passed return true; } // TODO Replace with better tests private boolean testAllMintMarks() { CoinPageCreator creator = new CoinPageCreator(); creator.testSetContext(mContext); boolean showTerritories = true; boolean showMintMark = true; boolean showP = true; boolean showD = true; boolean showS = true; boolean showCC = true; boolean showO = true; boolean editDateRange = false; boolean showBurnished = false; HashMap<String,Integer> info = new HashMap<>(); info.put("Pennies", 273); // Typically increases by 2 info.put("Nickels", 181); // Typically increases by 2 info.put("Dimes", 155); // Typically increases by 2 info.put("Quarters", 146); info.put("State Quarters", 112); info.put("National Park Quarters", 100); // Typically increases by 10 info.put("Half-Dollars", 104); // Typically increases by 2 info.put("Eisenhower Dollars", 14); info.put("Susan B. Anthony Dollars", 11); info.put("Sacagawea/Native American Dollars", 40); // Typically increases by 2 info.put("Presidential Dollars", 78); // Typically increases by 4 info.put("Indian Head Cents", 55); info.put("Liberty Head Nickels", 33); info.put("Buffalo Nickels", 64); info.put("Mercury Dimes", 77); info.put("Barber Dimes", 74); info.put("Barber Quarters", 74); info.put("Standing Liberty Quarters", 37); info.put("Barber Half Dollars", 73); info.put("Walking Liberty Half Dollars", 65); info.put("Franklin Half Dollars", 35); info.put("Morgan Dollars", 96); info.put("Peace Dollars", 24); info.put("American Eagle Silver Dollars", 34); // Typically increases by 1 info.put("First Spouse Gold Coins", 41); // Typically increases by 4 info.put("American Innovation Dollars", 2); // Typically increases by 4 Object[] keys = info.keySet().toArray(); for(int i = 0; i < info.size(); i++){ String coinType = (String) keys[i]; Integer size = info.get(coinType); int j = 0; for( ; j < MainApplication.COLLECTION_TYPES.length; j++){ String coinName = MainApplication.COLLECTION_TYPES[j].getCoinType(); if(coinName.equals(coinType)){ break; } } HashMap<String, Object> parameters = new HashMap<>(); MainApplication.COLLECTION_TYPES[j].getCreationParameters(parameters); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARKS, showMintMark); parameters.put(CoinPageCreator.OPT_EDIT_DATE_RANGE, editDateRange); // TODO This only works for now because we make sure each collection // uses each option for the same things (but they don't have to) parameters.put(CoinPageCreator.OPT_CHECKBOX_1, showTerritories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2, showBurnished); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1, showP); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2, showD); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3, showS); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4, showO); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5, showCC); parameters.put(CoinPageCreator.OPT_CHECKBOX_1_STRING_ID, R.string.show_territories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2_STRING_ID, R.string.check_show_burnished_eagles); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1_STRING_ID, R.string.include_p); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2_STRING_ID, R.string.include_d); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3_STRING_ID, R.string.include_s); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4_STRING_ID, R.string.include_o); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5_STRING_ID, R.string.include_cc); creator.testSetInternalState(j, parameters); creator.populateCollectionArrays(); ArrayList<String> identifierList = creator.testGetIdentifierList(); ArrayList<String> mintList = creator.testGetMintList(); Integer size1 = identifierList.size(); Integer size2 = mintList.size(); if( !size1.equals(size) || !size2.equals(size) ){ for(int k = 0; k < size1; k++){ Log.e(MainApplication.APP_NAME, identifierList.get(k) + " " + mintList.get(k)); } Log.e(MainApplication.APP_NAME, "Failed sanity check - " + coinType + " - (" + String.valueOf(size1) + " : " + String.valueOf(size2) + ") != " + String.valueOf(size)); return false; } else { creator.testClearLists(); } } return true; } private boolean testPMintMarks() { CoinPageCreator creator = new CoinPageCreator(); creator.testSetContext(mContext); boolean showTerritories = true; boolean showMintMark = true; boolean showP = true; boolean showD = false; boolean showS = false; boolean showCC = false; boolean showO = false; boolean editDateRange = false; boolean showBurnished = false; HashMap<String,Integer> info = new HashMap<>(); // TODO Do these //info.put("Pennies", 261); //info.put("Nickels", 229); //info.put("Dimes", 143); //info.put("Quarters", 146); //info.put("State Quarters", 112); //info.put("National Park Quarters", 40); //info.put("Half-Dollars", 92); //info.put("Eisenhower Dollars", 14); //info.put("Susan B. Anthony Dollars", 11); //info.put("Sacagawea Dollars", 28); //info.put("Presidential Dollars", 56); //info.put("Indian Head Cents", 55); info.put("Liberty Head Nickels", 31); //info.put("Buffalo Nickels", 64); //info.put("Mercury Dimes", 77); //info.put("Barber Dimes", 74); info.put("Barber Quarters", 25); info.put("Standing Liberty Quarters", 15); info.put("Barber Half Dollars", 24); info.put("Walking Liberty Half Dollars", 20); info.put("Franklin Half Dollars", 16); info.put("Morgan Dollars", 28); info.put("Peace Dollars", 10); //info.put("First Spouse Gold Coins", 25); //info.put("American Innovation Dollars", 1); Object[] keys = info.keySet().toArray(); for(int i = 0; i < info.size(); i++){ String coinType = (String) keys[i]; Integer size = info.get(coinType); int j = 0; for( ; j < MainApplication.COLLECTION_TYPES.length; j++){ String coinName = MainApplication.COLLECTION_TYPES[j].getCoinType(); if(coinName.equals(coinType)){ break; } } HashMap<String, Object> parameters = new HashMap<>(); MainApplication.COLLECTION_TYPES[j].getCreationParameters(parameters); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARKS, showMintMark); parameters.put(CoinPageCreator.OPT_EDIT_DATE_RANGE, editDateRange); parameters.put(CoinPageCreator.OPT_CHECKBOX_1, showTerritories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2, showBurnished); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1, showP); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2, showD); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3, showS); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4, showO); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5, showCC); parameters.put(CoinPageCreator.OPT_CHECKBOX_1_STRING_ID, R.string.show_territories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2_STRING_ID, R.string.check_show_burnished_eagles); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1_STRING_ID, R.string.include_p); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2_STRING_ID, R.string.include_d); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3_STRING_ID, R.string.include_s); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4_STRING_ID, R.string.include_o); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5_STRING_ID, R.string.include_cc); creator.testSetInternalState(j, parameters); creator.populateCollectionArrays(); ArrayList<String> identifierList = creator.testGetIdentifierList(); ArrayList<String> mintList = creator.testGetMintList(); Integer size1 = identifierList.size(); Integer size2 = mintList.size(); if( !size1.equals(size) || !size2.equals(size) ){ for(int k = 0; k < size1; k++){ Log.e(MainApplication.APP_NAME, identifierList.get(k) + " " + mintList.get(k)); } Log.e(MainApplication.APP_NAME, "Failed sanity check - " + coinType + " - (" + String.valueOf(size1) + " : " + String.valueOf(size2) + ") != " + String.valueOf(size)); return false; } else { creator.testClearLists(); } } return true; } private boolean testDMintMarks() { CoinPageCreator creator = new CoinPageCreator(); creator.testSetContext(mContext); boolean showTerritories = true; boolean showMintMark = true; boolean showP = false; boolean showD = true; boolean showS = false; boolean showCC = false; boolean showO = false; boolean editDateRange = false; boolean showBurnished = false; HashMap<String,Integer> info = new HashMap<>(); // TODO Do these //info.put("Pennies", 261); //info.put("Nickels", 229); //info.put("Dimes", 143); //info.put("Quarters", 146); //info.put("State Quarters", 112); //info.put("National Park Quarters", 40); //info.put("Half-Dollars", 92); //info.put("Eisenhower Dollars", 14); //info.put("Susan B. Anthony Dollars", 11); //info.put("Sacagawea Dollars", 28); //info.put("Presidential Dollars", 56); //info.put("Indian Head Cents", 55); info.put("Liberty Head Nickels", 1); //info.put("Buffalo Nickels", 64); //info.put("Mercury Dimes", 77); //info.put("Barber Dimes", 74); info.put("Barber Quarters", 10); info.put("Standing Liberty Quarters", 10); info.put("Barber Half Dollars", 7); info.put("Walking Liberty Half Dollars", 21); info.put("Franklin Half Dollars", 14); info.put("Morgan Dollars", 1); info.put("Peace Dollars", 5); //info.put("First Spouse Gold Coins", 25); //info.put("American Innovation Dollars", 1); Object[] keys = info.keySet().toArray(); for(int i = 0; i < info.size(); i++){ String coinType = (String) keys[i]; Integer size = info.get(coinType); int j = 0; for( ; j < MainApplication.COLLECTION_TYPES.length; j++){ String coinName = MainApplication.COLLECTION_TYPES[j].getCoinType(); if(coinName.equals(coinType)){ break; } } HashMap<String, Object> parameters = new HashMap<>(); MainApplication.COLLECTION_TYPES[j].getCreationParameters(parameters); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARKS, showMintMark); parameters.put(CoinPageCreator.OPT_EDIT_DATE_RANGE, editDateRange); parameters.put(CoinPageCreator.OPT_CHECKBOX_1, showTerritories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2, showBurnished); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1, showP); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2, showD); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3, showS); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4, showO); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5, showCC); parameters.put(CoinPageCreator.OPT_CHECKBOX_1_STRING_ID, R.string.show_territories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2_STRING_ID, R.string.check_show_burnished_eagles); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1_STRING_ID, R.string.include_p); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2_STRING_ID, R.string.include_d); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3_STRING_ID, R.string.include_s); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4_STRING_ID, R.string.include_o); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5_STRING_ID, R.string.include_cc); creator.testSetInternalState(j, parameters); creator.populateCollectionArrays(); ArrayList<String> identifierList = creator.testGetIdentifierList(); ArrayList<String> mintList = creator.testGetMintList(); Integer size1 = identifierList.size(); Integer size2 = mintList.size(); if( !size1.equals(size) || !size2.equals(size) ){ for(int k = 0; k < size1; k++){ Log.e(MainApplication.APP_NAME, identifierList.get(k) + " " + mintList.get(k)); } Log.e(MainApplication.APP_NAME, "Failed sanity check - " + coinType + " - (" + String.valueOf(size1) + " : " + String.valueOf(size2) + ") != " + String.valueOf(size)); return false; } else { creator.testClearLists(); } } return true; } private boolean testSMintMarks() { CoinPageCreator creator = new CoinPageCreator(); creator.testSetContext(mContext); boolean showTerritories = true; boolean showMintMark = true; boolean showP = false; boolean showD = false; boolean showS = true; boolean showCC = false; boolean showO = false; boolean editDateRange = false; boolean showBurnished = false; HashMap<String,Integer> info = new HashMap<>(); // TODO Do these //info.put("Pennies", 261); //info.put("Nickels", 229); //info.put("Dimes", 143); //info.put("Quarters", 146); //info.put("State Quarters", 112); //info.put("National Park Quarters", 40); //info.put("Half-Dollars", 92); //info.put("Eisenhower Dollars", 14); //info.put("Susan B. Anthony Dollars", 11); //info.put("Sacagawea Dollars", 28); //info.put("Presidential Dollars", 56); //info.put("Indian Head Cents", 55); info.put("Liberty Head Nickels", 1); //info.put("Buffalo Nickels", 64); //info.put("Mercury Dimes", 77); info.put("Barber Dimes", 24); info.put("Barber Quarters", 21); info.put("Standing Liberty Quarters", 12); info.put("Barber Half Dollars", 24); info.put("Walking Liberty Half Dollars", 24); info.put("Franklin Half Dollars", 5); info.put("Morgan Dollars", 28); info.put("Peace Dollars", 9); //info.put("First Spouse Gold Coins", 25); //info.put("American Innovation Dollars", 1); Object[] keys = info.keySet().toArray(); for(int i = 0; i < info.size(); i++){ String coinType = (String) keys[i]; Integer size = info.get(coinType); int j = 0; for( ; j < MainApplication.COLLECTION_TYPES.length; j++){ String coinName = MainApplication.COLLECTION_TYPES[j].getCoinType(); if(coinName.equals(coinType)){ break; } } HashMap<String, Object> parameters = new HashMap<>(); MainApplication.COLLECTION_TYPES[j].getCreationParameters(parameters); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARKS, showMintMark); parameters.put(CoinPageCreator.OPT_EDIT_DATE_RANGE, editDateRange); parameters.put(CoinPageCreator.OPT_CHECKBOX_1, showTerritories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2, showBurnished); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1, showP); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2, showD); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3, showS); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4, showO); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5, showCC); parameters.put(CoinPageCreator.OPT_CHECKBOX_1_STRING_ID, R.string.show_territories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2_STRING_ID, R.string.check_show_burnished_eagles); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1_STRING_ID, R.string.include_p); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2_STRING_ID, R.string.include_d); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3_STRING_ID, R.string.include_s); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4_STRING_ID, R.string.include_o); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5_STRING_ID, R.string.include_cc); creator.testSetInternalState(j, parameters); creator.populateCollectionArrays(); ArrayList<String> identifierList = creator.testGetIdentifierList(); ArrayList<String> mintList = creator.testGetMintList(); Integer size1 = identifierList.size(); Integer size2 = mintList.size(); if( !size1.equals(size) || !size2.equals(size) ){ for(int k = 0; k < size1; k++){ Log.e(MainApplication.APP_NAME, identifierList.get(k) + " " + mintList.get(k)); } Log.e(MainApplication.APP_NAME, "Failed sanity check - " + coinType + " - (" + String.valueOf(size1) + " : " + String.valueOf(size2) + ") != " + String.valueOf(size)); return false; } else { creator.testClearLists(); } } return true; } private boolean testOMintMarks() { CoinPageCreator creator = new CoinPageCreator(); creator.testSetContext(mContext); boolean showTerritories = true; boolean showMintMark = true; boolean showP = false; boolean showD = false; boolean showS = false; boolean showCC = false; boolean showO = true; boolean editDateRange = false; boolean showBurnished = false; HashMap<String,Integer> info = new HashMap<>(); info.put("Barber Dimes", 17); info.put("Barber Quarters", 18); info.put("Barber Half Dollars", 18); info.put("Morgan Dollars", 26); Object[] keys = info.keySet().toArray(); for(int i = 0; i < info.size(); i++){ String coinType = (String) keys[i]; Integer size = info.get(coinType); int j = 0; for( ; j < MainApplication.COLLECTION_TYPES.length; j++){ String coinName = MainApplication.COLLECTION_TYPES[j].getCoinType(); if(coinName.equals(coinType)){ break; } } HashMap<String, Object> parameters = new HashMap<>(); MainApplication.COLLECTION_TYPES[j].getCreationParameters(parameters); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARKS, showMintMark); parameters.put(CoinPageCreator.OPT_EDIT_DATE_RANGE, editDateRange); parameters.put(CoinPageCreator.OPT_CHECKBOX_1, showTerritories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2, showBurnished); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1, showP); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2, showD); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3, showS); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4, showO); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5, showCC); parameters.put(CoinPageCreator.OPT_CHECKBOX_1_STRING_ID, R.string.show_territories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2_STRING_ID, R.string.check_show_burnished_eagles); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1_STRING_ID, R.string.include_p); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2_STRING_ID, R.string.include_d); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3_STRING_ID, R.string.include_s); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4_STRING_ID, R.string.include_o); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5_STRING_ID, R.string.include_cc); creator.testSetInternalState(j, parameters); creator.populateCollectionArrays(); ArrayList<String> identifierList = creator.testGetIdentifierList(); ArrayList<String> mintList = creator.testGetMintList(); Integer size1 = identifierList.size(); Integer size2 = mintList.size(); if( !size1.equals(size) || !size2.equals(size) ){ for(int k = 0; k < size1; k++){ Log.e(MainApplication.APP_NAME, identifierList.get(k) + " " + mintList.get(k)); } Log.e(MainApplication.APP_NAME, "Failed sanity check - " + coinType + " - (" + String.valueOf(size1) + " : " + String.valueOf(size2) + ") != " + String.valueOf(size)); return false; } else { creator.testClearLists(); } } return true; } private boolean testCCMintMarks() { CoinPageCreator creator = new CoinPageCreator(); creator.testSetContext(mContext); boolean showTerritories = true; boolean showMintMark = true; boolean showP = false; boolean showD = false; boolean showS = false; boolean showCC = true; boolean showO = false; boolean editDateRange = false; boolean showBurnished = false; HashMap<String,Integer> info = new HashMap<>(); info.put("Morgan Dollars", 13); Object[] keys = info.keySet().toArray(); for(int i = 0; i < info.size(); i++){ String coinType = (String) keys[i]; Integer size = info.get(coinType); int j = 0; for( ; j < MainApplication.COLLECTION_TYPES.length; j++){ String coinName = MainApplication.COLLECTION_TYPES[j].getCoinType(); if(coinName.equals(coinType)){ break; } } HashMap<String, Object> parameters = new HashMap<>(); MainApplication.COLLECTION_TYPES[j].getCreationParameters(parameters); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARKS, showMintMark); parameters.put(CoinPageCreator.OPT_EDIT_DATE_RANGE, editDateRange); parameters.put(CoinPageCreator.OPT_CHECKBOX_1, showTerritories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2, showBurnished); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1, showP); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2, showD); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3, showS); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4, showO); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5, showCC); parameters.put(CoinPageCreator.OPT_CHECKBOX_1_STRING_ID, R.string.show_territories); parameters.put(CoinPageCreator.OPT_CHECKBOX_2_STRING_ID, R.string.check_show_burnished_eagles); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_1_STRING_ID, R.string.include_p); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_2_STRING_ID, R.string.include_d); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_3_STRING_ID, R.string.include_s); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_4_STRING_ID, R.string.include_o); parameters.put(CoinPageCreator.OPT_SHOW_MINT_MARK_5_STRING_ID, R.string.include_cc); creator.testSetInternalState(j, parameters); creator.populateCollectionArrays(); ArrayList<String> identifierList = creator.testGetIdentifierList(); ArrayList<String> mintList = creator.testGetMintList(); Integer size1 = identifierList.size(); Integer size2 = mintList.size(); if( !size1.equals(size) || !size2.equals(size) ){ for(int k = 0; k < size1; k++){ Log.e(MainApplication.APP_NAME, identifierList.get(k) + " " + mintList.get(k)); } Log.e(MainApplication.APP_NAME, "Failed sanity check - " + coinType + " - (" + String.valueOf(size1) + " : " + String.valueOf(size2) + ") != " + String.valueOf(size)); return false; } else { creator.testClearLists(); } } return true; } }
gpl-3.0
241180/Oryx
oryx-client/client-ui/src/main/java/com/oryx/core/provider/typeByToken/model/system/ose/CodificationTypeByTokenProvider.java
790
package com.oryx.core.provider.typeByToken.model.system.ose; import com.oryx.core.provider.TypeByTokenProvider; import com.oryx.remote.webservice.element.model.system.ose.XmlCodification; import com.oryx.remote.webservices.service.codificationservice.CrudRequest; import com.oryx.remote.webservices.service.codificationservice.CrudResponse; /** * Created by 241180 on 16/01/2017. */ public final class CodificationTypeByTokenProvider extends TypeByTokenProvider { private static final Class<?> ENTITY_CLASS_TYPE = XmlCodification.class; private static final Class<?> XML_ENTITY_CLASS_TYPE = XmlCodification.class; private static final Class<?> CRUD_REQUEST_CLASS_TYPE = CrudRequest.class; private static final Class<?> CRUD_RESPONSE_CLASS_TYPE = CrudResponse.class; }
gpl-3.0
mars-sim/mars-sim
mars-sim-core/src/main/java/org/mars_sim/msp/core/environment/MeteoriteImpact.java
436
/** * Mars Simulation Project * MeteoriteImpactImpl.java * @version 3.2.0 2021-06-20 * @author Manny Kung */ package org.mars_sim.msp.core.environment; import org.mars_sim.msp.core.structure.building.BuildingManager; import com.google.inject.ImplementedBy; @ImplementedBy(MeteoriteImpactImpl.class) public interface MeteoriteImpact { void calculateMeteoriteProbability(BuildingManager buildingManager); }
gpl-3.0
Kloudtek/kloudmake
core/src/main/java/com/kloudtek/kloudmake/java/JavaTask.java
5440
/* * Copyright (c) 2015. Kelewan Technologies Ltd */ package com.kloudtek.kloudmake.java; import com.kloudtek.kloudmake.*; import com.kloudtek.kloudmake.annotation.Alternative; import com.kloudtek.kloudmake.exception.*; import com.kloudtek.kloudmake.inject.Injector; import com.kloudtek.kloudmake.util.ReflectionHelper; import com.kloudtek.util.validation.ValidationUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Method; import java.util.HashSet; import java.util.List; import java.util.Set; public class JavaTask extends AbstractTask { private Class<?> implClass; private final List<Injector> injectors; @NotNull private final Set<EnforceOnlyIf> onlyIf = new HashSet<>(); private Method method; private Method verifyMethod; public JavaTask(int order, Stage stage, boolean postChildren, Class<?> implClass, List<Injector> injectors, @NotNull Set<EnforceOnlyIf> onlyIf, Method method) throws InvalidResourceDefinitionException { this(order, stage, postChildren, implClass, injectors, onlyIf, method, null); } public JavaTask(int order, @NotNull Stage stage, boolean postChildren, @NotNull Class<?> implClass, @NotNull List<Injector> injectors, @NotNull Set<EnforceOnlyIf> onlyIf, @Nullable Method method, @Nullable Method verifyMethod) throws InvalidResourceDefinitionException { super(order, stage, postChildren); this.implClass = implClass; this.injectors = injectors; this.onlyIf.addAll(onlyIf); setMethod(method); setVerifyMethod(verifyMethod); } @Override public void execute(KMContextImpl context, Resource resource) throws KMRuntimeException { invoke(context, resource, method); } private Object invoke(KMContextImpl context, Resource resource, Method method) throws KMRuntimeException { Object javaImpl = resource.getJavaImpl(implClass); if (javaImpl == null) { try { javaImpl = implClass.newInstance(); ((ResourceImpl) resource).addJavaImpl(javaImpl); } catch (InstantiationException | IllegalAccessException e) { throw new KMRuntimeException("Unable to create class " + implClass.getName() + " " + e.getMessage(), e); } } assert javaImpl != null; injectAndValidate(resource, javaImpl, context); Object ret = ReflectionHelper.invoke(method, javaImpl); updateAttrs(resource, javaImpl); return ret; } @Override public boolean checkExecutionRequired(KMContextImpl context, Resource resource) throws KMRuntimeException { if (verifyMethod != null) { return (boolean) invoke(context, resource, verifyMethod); } return true; } @Override public boolean supports(KMContextImpl context, Resource resource) throws KMRuntimeException { if (onlyIf != null && !onlyIf.isEmpty()) { for (EnforceOnlyIf enforceOnlyIf : onlyIf) { if (!enforceOnlyIf.execAllowed(context, resource)) { return false; } } } return true; } protected void injectAndValidate(Resource resource, Object javaImpl, KMContextImpl ctx) throws FieldInjectionException, ResourceValidationException { for (Injector injector : injectors) { injector.inject(resource, javaImpl, ctx); } try { ValidationUtils.validate(javaImpl, ResourceValidationException.class); } catch (ResourceValidationException e) { throw new ResourceValidationException("Failed to validate '" + resource.toString() + "' " + e.getMessage()); } } protected void updateAttrs(Resource resource, Object javaImpl) throws InvalidAttributeException { for (Injector injector : injectors) { try { injector.updateAttr(resource, javaImpl); } catch (IllegalAccessException e) { throw new InvalidAttributeException("Unable to set field " + injector.getField().getName() + " of class " + implClass.getName()); } } } public Method getMethod() { return method; } public void setMethod(Method method) throws InvalidResourceDefinitionException { if (this.method != null) { throw new IllegalArgumentException("Cannot override method " + ReflectionHelper.toString(this.method)); } this.method = method; if (method != null) { this.onlyIf.addAll(EnforceOnlyIf.find(method)); Alternative altAnno = method.getAnnotation(Alternative.class); if (altAnno != null) { alternative = altAnno.value(); } } } public Method getVerifyMethod() { return verifyMethod; } public void setVerifyMethod(Method verifyMethod) throws InvalidResourceDefinitionException { if (this.verifyMethod != null) { throw new IllegalArgumentException("Cannot override method " + ReflectionHelper.toString(this.verifyMethod)); } this.verifyMethod = verifyMethod; } private void handleAlternativeAnnotation(Alternative annotation) { if (annotation != null) { alternative = annotation.value(); } } }
gpl-3.0
servalproject/ServalMapsDataMan
src/org/servalproject/maps/protobuf/PointOfInterestMessage.java
35150
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: PointOfInterestMessage.proto package org.servalproject.maps.protobuf; public final class PointOfInterestMessage { private PointOfInterestMessage() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface MessageOrBuilder extends com.google.protobuf.MessageOrBuilder { // optional string phoneNumber = 1; boolean hasPhoneNumber(); String getPhoneNumber(); // optional string subsciberId = 2; boolean hasSubsciberId(); String getSubsciberId(); // optional double latitude = 3; boolean hasLatitude(); double getLatitude(); // optional double longitude = 4; boolean hasLongitude(); double getLongitude(); // optional int64 timestamp = 5; boolean hasTimestamp(); long getTimestamp(); // optional string timeZone = 6; boolean hasTimeZone(); String getTimeZone(); // optional string title = 7; boolean hasTitle(); String getTitle(); // optional string description = 8; boolean hasDescription(); String getDescription(); // optional int64 category = 9; boolean hasCategory(); long getCategory(); } public static final class Message extends com.google.protobuf.GeneratedMessage implements MessageOrBuilder { // Use Message.newBuilder() to construct. private Message(Builder builder) { super(builder); } private Message(boolean noInit) {} private static final Message defaultInstance; public static Message getDefaultInstance() { return defaultInstance; } public Message getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.servalproject.maps.protobuf.PointOfInterestMessage.internal_static_Message_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.servalproject.maps.protobuf.PointOfInterestMessage.internal_static_Message_fieldAccessorTable; } private int bitField0_; // optional string phoneNumber = 1; public static final int PHONENUMBER_FIELD_NUMBER = 1; private java.lang.Object phoneNumber_; public boolean hasPhoneNumber() { return ((bitField0_ & 0x00000001) == 0x00000001); } public String getPhoneNumber() { java.lang.Object ref = phoneNumber_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (com.google.protobuf.Internal.isValidUtf8(bs)) { phoneNumber_ = s; } return s; } } private com.google.protobuf.ByteString getPhoneNumberBytes() { java.lang.Object ref = phoneNumber_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); phoneNumber_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional string subsciberId = 2; public static final int SUBSCIBERID_FIELD_NUMBER = 2; private java.lang.Object subsciberId_; public boolean hasSubsciberId() { return ((bitField0_ & 0x00000002) == 0x00000002); } public String getSubsciberId() { java.lang.Object ref = subsciberId_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (com.google.protobuf.Internal.isValidUtf8(bs)) { subsciberId_ = s; } return s; } } private com.google.protobuf.ByteString getSubsciberIdBytes() { java.lang.Object ref = subsciberId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); subsciberId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional double latitude = 3; public static final int LATITUDE_FIELD_NUMBER = 3; private double latitude_; public boolean hasLatitude() { return ((bitField0_ & 0x00000004) == 0x00000004); } public double getLatitude() { return latitude_; } // optional double longitude = 4; public static final int LONGITUDE_FIELD_NUMBER = 4; private double longitude_; public boolean hasLongitude() { return ((bitField0_ & 0x00000008) == 0x00000008); } public double getLongitude() { return longitude_; } // optional int64 timestamp = 5; public static final int TIMESTAMP_FIELD_NUMBER = 5; private long timestamp_; public boolean hasTimestamp() { return ((bitField0_ & 0x00000010) == 0x00000010); } public long getTimestamp() { return timestamp_; } // optional string timeZone = 6; public static final int TIMEZONE_FIELD_NUMBER = 6; private java.lang.Object timeZone_; public boolean hasTimeZone() { return ((bitField0_ & 0x00000020) == 0x00000020); } public String getTimeZone() { java.lang.Object ref = timeZone_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (com.google.protobuf.Internal.isValidUtf8(bs)) { timeZone_ = s; } return s; } } private com.google.protobuf.ByteString getTimeZoneBytes() { java.lang.Object ref = timeZone_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); timeZone_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional string title = 7; public static final int TITLE_FIELD_NUMBER = 7; private java.lang.Object title_; public boolean hasTitle() { return ((bitField0_ & 0x00000040) == 0x00000040); } public String getTitle() { java.lang.Object ref = title_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (com.google.protobuf.Internal.isValidUtf8(bs)) { title_ = s; } return s; } } private com.google.protobuf.ByteString getTitleBytes() { java.lang.Object ref = title_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); title_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional string description = 8; public static final int DESCRIPTION_FIELD_NUMBER = 8; private java.lang.Object description_; public boolean hasDescription() { return ((bitField0_ & 0x00000080) == 0x00000080); } public String getDescription() { java.lang.Object ref = description_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); if (com.google.protobuf.Internal.isValidUtf8(bs)) { description_ = s; } return s; } } private com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional int64 category = 9; public static final int CATEGORY_FIELD_NUMBER = 9; private long category_; public boolean hasCategory() { return ((bitField0_ & 0x00000100) == 0x00000100); } public long getCategory() { return category_; } private void initFields() { phoneNumber_ = ""; subsciberId_ = ""; latitude_ = 0D; longitude_ = 0D; timestamp_ = 0L; timeZone_ = ""; title_ = ""; description_ = ""; category_ = 0L; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getPhoneNumberBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getSubsciberIdBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeDouble(3, latitude_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeDouble(4, longitude_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeInt64(5, timestamp_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { output.writeBytes(6, getTimeZoneBytes()); } if (((bitField0_ & 0x00000040) == 0x00000040)) { output.writeBytes(7, getTitleBytes()); } if (((bitField0_ & 0x00000080) == 0x00000080)) { output.writeBytes(8, getDescriptionBytes()); } if (((bitField0_ & 0x00000100) == 0x00000100)) { output.writeInt64(9, category_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getPhoneNumberBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getSubsciberIdBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(3, latitude_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(4, longitude_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(5, timestamp_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(6, getTimeZoneBytes()); } if (((bitField0_ & 0x00000040) == 0x00000040)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(7, getTitleBytes()); } if (((bitField0_ & 0x00000080) == 0x00000080)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(8, getDescriptionBytes()); } if (((bitField0_ & 0x00000100) == 0x00000100)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(9, category_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.servalproject.maps.protobuf.PointOfInterestMessage.Message parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.servalproject.maps.protobuf.PointOfInterestMessage.Message parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.servalproject.maps.protobuf.PointOfInterestMessage.Message parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.servalproject.maps.protobuf.PointOfInterestMessage.Message parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.servalproject.maps.protobuf.PointOfInterestMessage.Message parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.servalproject.maps.protobuf.PointOfInterestMessage.Message parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.servalproject.maps.protobuf.PointOfInterestMessage.Message parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static org.servalproject.maps.protobuf.PointOfInterestMessage.Message parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static org.servalproject.maps.protobuf.PointOfInterestMessage.Message parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.servalproject.maps.protobuf.PointOfInterestMessage.Message parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.servalproject.maps.protobuf.PointOfInterestMessage.Message prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements org.servalproject.maps.protobuf.PointOfInterestMessage.MessageOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.servalproject.maps.protobuf.PointOfInterestMessage.internal_static_Message_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.servalproject.maps.protobuf.PointOfInterestMessage.internal_static_Message_fieldAccessorTable; } // Construct using org.servalproject.maps.protobuf.PointOfInterestMessage.Message.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); phoneNumber_ = ""; bitField0_ = (bitField0_ & ~0x00000001); subsciberId_ = ""; bitField0_ = (bitField0_ & ~0x00000002); latitude_ = 0D; bitField0_ = (bitField0_ & ~0x00000004); longitude_ = 0D; bitField0_ = (bitField0_ & ~0x00000008); timestamp_ = 0L; bitField0_ = (bitField0_ & ~0x00000010); timeZone_ = ""; bitField0_ = (bitField0_ & ~0x00000020); title_ = ""; bitField0_ = (bitField0_ & ~0x00000040); description_ = ""; bitField0_ = (bitField0_ & ~0x00000080); category_ = 0L; bitField0_ = (bitField0_ & ~0x00000100); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.servalproject.maps.protobuf.PointOfInterestMessage.Message.getDescriptor(); } public org.servalproject.maps.protobuf.PointOfInterestMessage.Message getDefaultInstanceForType() { return org.servalproject.maps.protobuf.PointOfInterestMessage.Message.getDefaultInstance(); } public org.servalproject.maps.protobuf.PointOfInterestMessage.Message build() { org.servalproject.maps.protobuf.PointOfInterestMessage.Message result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private org.servalproject.maps.protobuf.PointOfInterestMessage.Message buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { org.servalproject.maps.protobuf.PointOfInterestMessage.Message result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public org.servalproject.maps.protobuf.PointOfInterestMessage.Message buildPartial() { org.servalproject.maps.protobuf.PointOfInterestMessage.Message result = new org.servalproject.maps.protobuf.PointOfInterestMessage.Message(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.phoneNumber_ = phoneNumber_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.subsciberId_ = subsciberId_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.latitude_ = latitude_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.longitude_ = longitude_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } result.timestamp_ = timestamp_; if (((from_bitField0_ & 0x00000020) == 0x00000020)) { to_bitField0_ |= 0x00000020; } result.timeZone_ = timeZone_; if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000040; } result.title_ = title_; if (((from_bitField0_ & 0x00000080) == 0x00000080)) { to_bitField0_ |= 0x00000080; } result.description_ = description_; if (((from_bitField0_ & 0x00000100) == 0x00000100)) { to_bitField0_ |= 0x00000100; } result.category_ = category_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.servalproject.maps.protobuf.PointOfInterestMessage.Message) { return mergeFrom((org.servalproject.maps.protobuf.PointOfInterestMessage.Message)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.servalproject.maps.protobuf.PointOfInterestMessage.Message other) { if (other == org.servalproject.maps.protobuf.PointOfInterestMessage.Message.getDefaultInstance()) return this; if (other.hasPhoneNumber()) { setPhoneNumber(other.getPhoneNumber()); } if (other.hasSubsciberId()) { setSubsciberId(other.getSubsciberId()); } if (other.hasLatitude()) { setLatitude(other.getLatitude()); } if (other.hasLongitude()) { setLongitude(other.getLongitude()); } if (other.hasTimestamp()) { setTimestamp(other.getTimestamp()); } if (other.hasTimeZone()) { setTimeZone(other.getTimeZone()); } if (other.hasTitle()) { setTitle(other.getTitle()); } if (other.hasDescription()) { setDescription(other.getDescription()); } if (other.hasCategory()) { setCategory(other.getCategory()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 10: { bitField0_ |= 0x00000001; phoneNumber_ = input.readBytes(); break; } case 18: { bitField0_ |= 0x00000002; subsciberId_ = input.readBytes(); break; } case 25: { bitField0_ |= 0x00000004; latitude_ = input.readDouble(); break; } case 33: { bitField0_ |= 0x00000008; longitude_ = input.readDouble(); break; } case 40: { bitField0_ |= 0x00000010; timestamp_ = input.readInt64(); break; } case 50: { bitField0_ |= 0x00000020; timeZone_ = input.readBytes(); break; } case 58: { bitField0_ |= 0x00000040; title_ = input.readBytes(); break; } case 66: { bitField0_ |= 0x00000080; description_ = input.readBytes(); break; } case 72: { bitField0_ |= 0x00000100; category_ = input.readInt64(); break; } } } } private int bitField0_; // optional string phoneNumber = 1; private java.lang.Object phoneNumber_ = ""; public boolean hasPhoneNumber() { return ((bitField0_ & 0x00000001) == 0x00000001); } public String getPhoneNumber() { java.lang.Object ref = phoneNumber_; if (!(ref instanceof String)) { String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); phoneNumber_ = s; return s; } else { return (String) ref; } } public Builder setPhoneNumber(String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; phoneNumber_ = value; onChanged(); return this; } public Builder clearPhoneNumber() { bitField0_ = (bitField0_ & ~0x00000001); phoneNumber_ = getDefaultInstance().getPhoneNumber(); onChanged(); return this; } void setPhoneNumber(com.google.protobuf.ByteString value) { bitField0_ |= 0x00000001; phoneNumber_ = value; onChanged(); } // optional string subsciberId = 2; private java.lang.Object subsciberId_ = ""; public boolean hasSubsciberId() { return ((bitField0_ & 0x00000002) == 0x00000002); } public String getSubsciberId() { java.lang.Object ref = subsciberId_; if (!(ref instanceof String)) { String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); subsciberId_ = s; return s; } else { return (String) ref; } } public Builder setSubsciberId(String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; subsciberId_ = value; onChanged(); return this; } public Builder clearSubsciberId() { bitField0_ = (bitField0_ & ~0x00000002); subsciberId_ = getDefaultInstance().getSubsciberId(); onChanged(); return this; } void setSubsciberId(com.google.protobuf.ByteString value) { bitField0_ |= 0x00000002; subsciberId_ = value; onChanged(); } // optional double latitude = 3; private double latitude_ ; public boolean hasLatitude() { return ((bitField0_ & 0x00000004) == 0x00000004); } public double getLatitude() { return latitude_; } public Builder setLatitude(double value) { bitField0_ |= 0x00000004; latitude_ = value; onChanged(); return this; } public Builder clearLatitude() { bitField0_ = (bitField0_ & ~0x00000004); latitude_ = 0D; onChanged(); return this; } // optional double longitude = 4; private double longitude_ ; public boolean hasLongitude() { return ((bitField0_ & 0x00000008) == 0x00000008); } public double getLongitude() { return longitude_; } public Builder setLongitude(double value) { bitField0_ |= 0x00000008; longitude_ = value; onChanged(); return this; } public Builder clearLongitude() { bitField0_ = (bitField0_ & ~0x00000008); longitude_ = 0D; onChanged(); return this; } // optional int64 timestamp = 5; private long timestamp_ ; public boolean hasTimestamp() { return ((bitField0_ & 0x00000010) == 0x00000010); } public long getTimestamp() { return timestamp_; } public Builder setTimestamp(long value) { bitField0_ |= 0x00000010; timestamp_ = value; onChanged(); return this; } public Builder clearTimestamp() { bitField0_ = (bitField0_ & ~0x00000010); timestamp_ = 0L; onChanged(); return this; } // optional string timeZone = 6; private java.lang.Object timeZone_ = ""; public boolean hasTimeZone() { return ((bitField0_ & 0x00000020) == 0x00000020); } public String getTimeZone() { java.lang.Object ref = timeZone_; if (!(ref instanceof String)) { String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); timeZone_ = s; return s; } else { return (String) ref; } } public Builder setTimeZone(String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000020; timeZone_ = value; onChanged(); return this; } public Builder clearTimeZone() { bitField0_ = (bitField0_ & ~0x00000020); timeZone_ = getDefaultInstance().getTimeZone(); onChanged(); return this; } void setTimeZone(com.google.protobuf.ByteString value) { bitField0_ |= 0x00000020; timeZone_ = value; onChanged(); } // optional string title = 7; private java.lang.Object title_ = ""; public boolean hasTitle() { return ((bitField0_ & 0x00000040) == 0x00000040); } public String getTitle() { java.lang.Object ref = title_; if (!(ref instanceof String)) { String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); title_ = s; return s; } else { return (String) ref; } } public Builder setTitle(String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000040; title_ = value; onChanged(); return this; } public Builder clearTitle() { bitField0_ = (bitField0_ & ~0x00000040); title_ = getDefaultInstance().getTitle(); onChanged(); return this; } void setTitle(com.google.protobuf.ByteString value) { bitField0_ |= 0x00000040; title_ = value; onChanged(); } // optional string description = 8; private java.lang.Object description_ = ""; public boolean hasDescription() { return ((bitField0_ & 0x00000080) == 0x00000080); } public String getDescription() { java.lang.Object ref = description_; if (!(ref instanceof String)) { String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); description_ = s; return s; } else { return (String) ref; } } public Builder setDescription(String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000080; description_ = value; onChanged(); return this; } public Builder clearDescription() { bitField0_ = (bitField0_ & ~0x00000080); description_ = getDefaultInstance().getDescription(); onChanged(); return this; } void setDescription(com.google.protobuf.ByteString value) { bitField0_ |= 0x00000080; description_ = value; onChanged(); } // optional int64 category = 9; private long category_ ; public boolean hasCategory() { return ((bitField0_ & 0x00000100) == 0x00000100); } public long getCategory() { return category_; } public Builder setCategory(long value) { bitField0_ |= 0x00000100; category_ = value; onChanged(); return this; } public Builder clearCategory() { bitField0_ = (bitField0_ & ~0x00000100); category_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:Message) } static { defaultInstance = new Message(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:Message) } private static com.google.protobuf.Descriptors.Descriptor internal_static_Message_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_Message_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\034PointOfInterestMessage.proto\"\263\001\n\007Messa" + "ge\022\023\n\013phoneNumber\030\001 \001(\t\022\023\n\013subsciberId\030\002" + " \001(\t\022\020\n\010latitude\030\003 \001(\001\022\021\n\tlongitude\030\004 \001(" + "\001\022\021\n\ttimestamp\030\005 \001(\003\022\020\n\010timeZone\030\006 \001(\t\022\r" + "\n\005title\030\007 \001(\t\022\023\n\013description\030\010 \001(\t\022\020\n\010ca" + "tegory\030\t \001(\003B!\n\037org.servalproject.maps.p" + "rotobuf" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_Message_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_Message_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_Message_descriptor, new java.lang.String[] { "PhoneNumber", "SubsciberId", "Latitude", "Longitude", "Timestamp", "TimeZone", "Title", "Description", "Category", }, org.servalproject.maps.protobuf.PointOfInterestMessage.Message.class, org.servalproject.maps.protobuf.PointOfInterestMessage.Message.Builder.class); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
gpl-3.0
oxoooo/materialize
app/src/main/java/ooo/oxo/apps/materialize/graphics/ShapeDrawable.java
2840
/* * Materialize - Materialize all those not material * Copyright (C) 2015 XiNGRZ <xxx@oxo.ooo> * * 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 ooo.oxo.apps.materialize.graphics; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.ColorRes; import ooo.oxo.apps.materialize.R; public class ShapeDrawable extends CompositeDrawable { private boolean checked = false; private Drawable indicator; private Rect indicatorRegion = new Rect(); private int size; @SuppressWarnings("deprecation") public ShapeDrawable(Resources resources, Shape shape, @ColorRes int color) { super(resources); indicator = resources.getDrawable(R.drawable.ic_check_white_24dp); size = resources.getDimensionPixelSize(R.dimen.launcher_size); setShape(shape); setBackground(new ColorDrawable(resources.getColor(color))); } @Override public boolean isStateful() { return true; } @Override protected boolean onStateChange(int[] state) { if (state == null) { return false; } boolean checked = false; for (int i : state) { if (i == android.R.attr.state_checked) { checked = true; } } if (this.checked != checked) { this.checked = checked; invalidateSelf(); return true; } else { return false; } } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); indicatorRegion.set(bounds); indicatorRegion.inset(indicator.getIntrinsicWidth() / 2, indicator.getIntrinsicHeight() / 2); indicator.setBounds(indicatorRegion); } @Override public int getIntrinsicWidth() { return size; } @Override public int getIntrinsicHeight() { return size; } @Override public void draw(Canvas canvas) { super.draw(canvas); if (checked) { indicator.draw(canvas); } } }
gpl-3.0
PersoSim/de.persosim.rcp
de.persosim.rcp/src/de/persosim/rcp/handlers/AboutHandler.java
323
package de.persosim.rcp.handlers; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.swt.widgets.Shell; import de.persosim.rcp.dialogs.AboutDialog; public class AboutHandler { @Execute public void execute(Shell shell) { AboutDialog aboutDialog = new AboutDialog(shell); aboutDialog.open(); } }
gpl-3.0
Foo-Manroot/Time-Wanderer
Time-Wanderer/src/animations/BatAnimator.java
3800
package animations; import org.newdawn.slick.Animation; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.SpriteSheet; /** * * @author Pablo Peña */ public class BatAnimator { private Image spriteSheetImg; private SpriteSheet spriteSheet; private float scale; //Right private Animation idle1R; //Left private Animation idle1L; public BatAnimator(){ try { init(); } catch (SlickException ex) {System.err.println(ex);} } /**Set scale of the animations*/ public void setScale (float sc){ this.scale=sc; } /**Reset animatios that are not in a loop.*/ public void resetAnim(){ } /**Build all the animations from the spritesheet.*/ private void init() throws SlickException { //r1=new Rectangle(600,200,50,50); scale = 1.0f; spriteSheetImg = new Image("./src/resources/character/Murcielo final.png"); spriteSheet = new SpriteSheet(spriteSheetImg, 96, 96); //Right idle1R = new Animation(); createIdle1R(idle1R); //Left idle1L = new Animation(); createIdle1L(idle1L); } //----------------------------ANIM_CREATION------------------------------------- /*All these methods are the same, we choose a different row of the spriteSheet in each method, because each row corresponds to a different animation. We iterate through each row, adding the sprites to the animation. Animations may have a different number of frames than the rest, that is why the for inside each method might have a different number of iterations. R stands for right and L for left*/ /** * Create animation of idle right * * @param anim Animation where we will store the result */ public void createIdle1R(Animation anim) { for (int i = 0; i < spriteSheet.getHorizontalCount()-1; i++) { anim.addFrame(spriteSheet.getSprite(i, 0).getScaledCopy(this.scale), 250); } } //----------------------LEFT_ANIMATIONS----------------------------------------- /** * Create animation of idling left * * @param anim Animation where we will store the result */ public void createIdle1L(Animation anim) { for (int i = 0; i < spriteSheet.getHorizontalCount()-1; i++) { anim.addFrame(spriteSheet.getSprite(i, 0).getFlippedCopy(true, false).getScaledCopy(this.scale), 250); } } //****************************ANIM_CREATION************************************* //----------------------------ANIM_GETTER--------------------------------------- /*All these methods are the same, we choose a different row of the spriteSheet in each method, because each row corresponds to a different animation. We iterate through each row, adding the sprites to the animation. Animations may have a different number of frames than the rest, that is why the for inside each method might have a different number of iterations. R stands for right and L for left*/ //Right------------------------------------------------------------------------- /** * Obtain animation of idle right * * @return Animation where we will store the result */ public Animation getIdle1R() { return this.idle1R; } //LEFT-------------------------------------------------------------------------- /** * Obtain animation of idling left * * @return anim Animation where we will store the result */ public Animation getIdle1L() { return this.idle1L; } //****************************ANIM_GETTER*************************************** }
gpl-3.0
michaelsellers/stealthwatch
src/main/java/stealthwatch/problemone/GNodeWalker.java
1287
package stealthwatch.problemone; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import stealthwatch.GNode; /** * Observe that this GNode can be thought of as defining a graph. * In implementing the functions below, you can assume that: * 1) any graph defined by a GNode is acyclic (no cycles). * 2) when a GNode has no children, getChildren() returns a array of size 0, and *not* null. * 3) all children returned by getChildren() are not null. **/ //Implement a function with the following signature: // public ArrayList walkGraph(GNode); // //which should return a ArrayList containing every GNode in the //graph. Each node should appear in the ArrayList exactly once //(i.e. no duplicates). public class GNodeWalker { public ArrayList<GNode> walkGraph(GNode root) { List<GNode> flattened = Arrays.stream(root.getChildren()) .flatMap(GNodeWalker::flatten) .collect(Collectors.toList()); flattened.add(root); return new ArrayList<>(flattened); } private static Stream<GNode> flatten(GNode node) { return Stream.concat( Stream.of(node), Arrays.stream(node.getChildren()).flatMap(GNodeWalker::flatten)); } }
gpl-3.0
nkluge/asgbreezegui
src/main/java/de/uni_potsdam/hpi/asg/breezegui/BreezeGuiMain.java
3383
package de.uni_potsdam.hpi.asg.breezegui; /* * Copyright (C) 2015 Norman Kluge * * This file is part of ASGbreezeGui. * * ASGbreezeGui 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. * * ASGbreezeGui 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 ASGbreezeGui. If not, see <http://www.gnu.org/licenses/>. */ import java.util.Arrays; import org.apache.logging.log4j.Logger; import de.uni_potsdam.hpi.asg.breezegui.breezegraph.GuiMain; import de.uni_potsdam.hpi.asg.common.breeze.model.AbstractBreezeNetlist; import de.uni_potsdam.hpi.asg.common.breeze.model.BreezeProject; import de.uni_potsdam.hpi.asg.common.io.LoggerHelper; import de.uni_potsdam.hpi.asg.common.io.WorkingdirGenerator; public class BreezeGuiMain { private static Logger logger; private static BreezeGuiCommandlineOptions options; public static void main(String[] args) { int status = main2(args); System.exit(status); } public static int main2(String[] args) { try { long start = System.currentTimeMillis(); int status = -1; options = new BreezeGuiCommandlineOptions(); if(options.parseCmdLine(args)) { logger = LoggerHelper.initLogger(options.getOutputlevel(), options.getLogfile(), options.isDebug()); String version = BreezeGuiMain.class.getPackage().getImplementationVersion(); logger.info("ASGbreezeGui " + (version==null ? "Testmode" : "v" + version)); logger.debug("Args: " + Arrays.asList(args).toString()); WorkingdirGenerator.getInstance().create(null, null, "guitmp", null); status = execute(); WorkingdirGenerator.getInstance().delete(); } long end = System.currentTimeMillis(); if(logger != null) { logger.info("Runtime: " + LoggerHelper.formatRuntime(end - start, false)); } return status; } catch(Exception e) { System.out.println("An error occurred: " + e.getLocalizedMessage()); return 1; } } private static int execute() { BreezeProject proj = BreezeProject.create(options.getBrezeefile(), null, false, false); if(proj == null) { logger.error("Could not create Breeze project"); return -1; } AbstractBreezeNetlist netlist = null; for(AbstractBreezeNetlist n : proj.getSortedNetlists()) { netlist = n; } if(netlist == null) { logger.error("Breeze file did not contain a netlist"); return -1; } GuiMain gmain = new GuiMain(netlist, 1); switch(options.getMode()) { case "gui": gmain.show(); while(!gmain.isClosed()) { try { Thread.sleep(1000); } catch(InterruptedException e) { logger.error(e.getLocalizedMessage()); return -1; } } break; case "png": if(!gmain.exportPng(options.getOutfile())) { return -1; } break; case "svg": if(!gmain.exportSvg(options.getOutfile())) { return -1; } break; default: logger.error("Unknown mode: " + options.getMode()); return -1; } return 0; } }
gpl-3.0
YinYanfei/CadalWorkspace
CadalDLCAS/src/cn/edu/zju/cadal/sec/SecEstCountBolt.java
5118
package cn.edu.zju.cadal.sec; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Random; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; /** * Calculate the number of page, reading by single ip or single user in CADAL * web site, if the number is larger than THRESHOLD, then we can judge this IP * is unfriendly. * * @author CADAL */ public class SecEstCountBolt extends BaseRichBolt { private static final long serialVersionUID = 1L; private OutputCollector _collector = null; private Map<String, Integer> ipSigMap = null; private Map<Integer, Queue<Long>> sigTimeMap = null; private Random random = null; private static int RANDOM_MAX = 10000; private static int THRESHOLD = 60; // 指定时间间隔内的恶意IP阈值 private static int TIMELONGEST = 60000000; // 最长时间间隔 【1 min】 @SuppressWarnings("rawtypes") @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this._collector = collector; this.ipSigMap = new HashMap<String, Integer>(); this.sigTimeMap = new HashMap<Integer, Queue<Long>>(); this.random = new Random(); } @Override public void execute(Tuple input) { try { String msg = (String) input.getValue(0); // 10.15.62.110#$#hongxin#$#15023834#$#00000002#$#1386896488374218 String[] msgArr = msg.split("#\\$#"); // For ipSigMap String ipUser = msgArr[0] + "#$#" + msgArr[1]; Integer sigForIpUser = this.random.nextInt(this.RANDOM_MAX); // For sigTimeMap Long time = Long.valueOf(msgArr[4]); String resIpInfo = null; // 保存处理之后预测到的恶意IP信息 if (this.ipSigMap.containsKey(ipUser)) { sigForIpUser = this.ipSigMap.get(ipUser); Queue<Long> tmpQueue = this.sigTimeMap.get(sigForIpUser); tmpQueue.add(time); this.sigTimeMap.put(sigForIpUser, tmpQueue); resIpInfo = this.dealInSigTimeMap(); } else { this.ipSigMap.put(ipUser, sigForIpUser); Queue<Long> queueVal = new LinkedList<Long>(); queueVal.add(time); this.sigTimeMap.put(sigForIpUser, queueVal); } // emit if (resIpInfo != null) { this._collector.emit(new Values(resIpInfo)); } this._collector.ack(input); } catch (Exception e) { e.printStackTrace(); } } /** * 这个函数非常的关键,主要做了一下的几个事情: * -- 遍历两个Map数据结构 * -- 将sigTimeMap中离现在的时间超过N的queue记录删除 * -- 在sigTimeMap中找出超过指定次数的Sig记录,并在ipSigMap表中找出这个ip相关信息 * -- 删除恶意ip的Map结构信息 * -- 删除sigTimeMap中queue为空的记录信息,以及ipSigMap中对应的记录 * * @param ipUser * @return */ @SuppressWarnings({ "rawtypes", "unchecked", "static-access" }) private String dealInSigTimeMap() { Long curTime = System.currentTimeMillis() * 1000; String ipInfo = null; Iterator iter = this.sigTimeMap.entrySet().iterator(); while (iter.hasNext()) { Entry entry = (Entry) iter.next(); Integer key = (Integer) entry.getKey(); Queue<Long> val = (Queue<Long>) entry.getValue(); if (val.size() != 0) { // 这个地方之前写成了while循环 【重要】 Long timeInVal = val.peek(); if (timeInVal != null) { if (curTime - timeInVal > this.TIMELONGEST) { val.poll(); break; } } } // 判断是否为恶意 Iterator iter_ipSigMap = null; if (val.size() > this.THRESHOLD) { // 判断是否为恶意IP,通过value获得key【this.ipSigMap】 iter_ipSigMap = this.ipSigMap.entrySet().iterator(); while (iter_ipSigMap.hasNext()) { Entry entry_ipSigMap = (Entry) iter_ipSigMap.next(); String key_ipSigMap = (String) entry_ipSigMap.getKey(); Integer val_ipSigMap = (Integer) entry_ipSigMap.getValue(); if (val_ipSigMap == key) { ipInfo = key_ipSigMap; break; } } } // 清除相关数据 if(val.size() == 0) { String key_del = null; iter_ipSigMap = this.ipSigMap.entrySet().iterator(); while (iter_ipSigMap.hasNext()) { Entry entry_ipSigMap = (Entry) iter_ipSigMap.next(); String key_ipSigMap = (String) entry_ipSigMap.getKey(); Integer val_ipSigMap = (Integer) entry_ipSigMap.getValue(); if (val_ipSigMap == key) { key_del = key_ipSigMap; iter_ipSigMap.remove(); break; } } iter.remove(); // sigTimeMap中删除相应的字段 }else if (ipInfo != null) { // 清除两个Map的数据 iter_ipSigMap.remove(); iter.remove(); break; } } return ipInfo; } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("unfriendIP")); } }
gpl-3.0
shelllbw/workcraft
CpogPlugin/src/org/workcraft/plugins/cpog/tasks/PGMinerResultHandler.java
4532
package org.workcraft.plugins.cpog.tasks; import java.io.File; import java.lang.reflect.InvocationTargetException; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.workcraft.Framework; import org.workcraft.dom.VisualModelDescriptor; import org.workcraft.dom.math.MathModel; import org.workcraft.exceptions.VisualModelInstantiationException; import org.workcraft.gui.MainWindow; import org.workcraft.gui.ToolboxPanel; import org.workcraft.gui.graph.GraphEditorPanel; import org.workcraft.gui.workspace.Path; import org.workcraft.plugins.cpog.CpogDescriptor; import org.workcraft.plugins.cpog.VisualCpog; import org.workcraft.plugins.cpog.tools.CpogSelectionTool; import org.workcraft.plugins.shared.tasks.ExternalProcessResult; import org.workcraft.tasks.DummyProgressMonitor; import org.workcraft.tasks.Result; import org.workcraft.tasks.Result.Outcome; import org.workcraft.util.FileUtils; import org.workcraft.workspace.ModelEntry; import org.workcraft.workspace.Workspace; import org.workcraft.workspace.WorkspaceEntry; public class PGMinerResultHandler extends DummyProgressMonitor<ExternalProcessResult> { private VisualCpog visualCpog; private final WorkspaceEntry we; private final boolean createNewWindow; public PGMinerResultHandler(VisualCpog visualCpog, WorkspaceEntry we, boolean createNewWindow) { this.visualCpog = visualCpog; this.we = we; this.createNewWindow = createNewWindow; } public void finished(final Result<? extends ExternalProcessResult> result, String description) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { final Framework framework = Framework.getInstance(); MainWindow mainWindow = framework.getMainWindow(); final GraphEditorPanel editor = framework.getMainWindow().getCurrentEditor(); final ToolboxPanel toolbox = editor.getToolBox(); final CpogSelectionTool tool = toolbox.getToolInstance(CpogSelectionTool.class); if (result.getOutcome() == Outcome.FAILED) { JOptionPane.showMessageDialog(mainWindow, "PGMiner could not run", "Concurrency extraction failed", JOptionPane.ERROR_MESSAGE); } else { if (createNewWindow) { CpogDescriptor cpogModel = new CpogDescriptor(); MathModel mathModel = cpogModel.createMathModel(); Path<String> path = we.getWorkspacePath(); VisualModelDescriptor v = cpogModel.getVisualModelDescriptor(); try { if (v == null) { throw new VisualModelInstantiationException("visual model is not defined for \"" + cpogModel.getDisplayName() + "\"."); } visualCpog = (VisualCpog) v.create(mathModel); final Workspace workspace = framework.getWorkspace(); final Path<String> directory = workspace.getPath(we).getParent(); final String name = FileUtils.getFileNameWithoutExtension(new File(path.getNode())); final ModelEntry me = new ModelEntry(cpogModel, visualCpog); workspace.add(directory, name, me, true, true); } catch (VisualModelInstantiationException e) { e.printStackTrace(); } } String[] output = new String(result.getReturnValue().getOutput()).split("\n"); we.captureMemento(); try { for (int i = 0; i < output.length; i++) { String exp = output[i]; tool.insertExpression(exp, visualCpog, false, false, true, false); } we.saveMemento(); } catch (Exception e) { we.cancelMemento(); } } } }); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } }
gpl-3.0
mango-rpc/mango
core/src/main/java/org/mango/util/SeqId.java
402
package org.mango.util; import java.util.concurrent.atomic.AtomicLong; public class SeqId { private final static AtomicLong id = new AtomicLong(0); public static long nextLong() { while (true) { long oldId = id.get(); long newId = oldId + 1; if (id.compareAndSet(oldId, newId)) return newId; } } }
gpl-3.0
refreshingdev/SpringIntercSecur
src/main/java/com/example/ContextRunnerMain.java
3203
package com.example; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; /** * Technical demonstration of securing method invocations with spring-security */ public class ContextRunnerMain { public static void main(String[] args) { ClassPathXmlApplicationContext context; context = new ClassPathXmlApplicationContext("applicationContext.xml"); authenticate(context, "dev", "654321"); // intercept-methods is local to a bean, // even if it uses class name in method pattern //MyService myService = context.getBean("myUnprotectedService", MyService.class); MyService myService = context.getBean("myService", MyService.class); callService(myService); logout(); System.out.println("Logged out"); callService(myService); } private static void callService(MyService myService) { try { myService.breathe(); try { myService.useTheComputer(); } catch (AccessDeniedException e) { System.out.println("Access to the computer denied!"); } try { myService.formatDisk(); } catch (AccessDeniedException e) { System.out.println("Access to disk formatting denied!"); } try { myService.compile(); } catch (AccessDeniedException e) { System.out.println("Access to compilation denied!"); } } catch (AuthenticationCredentialsNotFoundException e) { System.out.println("You are not logged in. Cannot call any secured method!"); } } public static void authenticate(AbstractApplicationContext context, String user, String password) { AuthenticationManager authenticationManager = context.getBean("myAuthManager", AuthenticationManager.class); try { Authentication request = new UsernamePasswordAuthenticationToken(user, password); Authentication result = authenticationManager.authenticate(request); SecurityContextHolder.getContext().setAuthentication(result); } catch (AuthenticationException e) { // eg. BadCredentialsException: Bad credentials throw new RuntimeException(e); } System.out.println("Successfully authenticated. Security context contains: " + SecurityContextHolder.getContext().getAuthentication()); } private static void logout() { SecurityContextHolder.clearContext(); } }
gpl-3.0
hmraul/gpsPosition
src/main/java/com/rhm/controllers/Positions.java
3244
package com.rhm.controllers; import com.rhm.core.dto.GpsPositionRequest; import com.rhm.core.entities.GeoCoordinate; import com.rhm.core.entities.GpsPosition; import com.rhm.core.services.GeoCoordinateService; import com.rhm.core.services.GpsPositionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.annotation.PostConstruct; import java.util.List; @RestController @RequestMapping(value = "/positions") public class Positions { @Autowired GeoCoordinateService geoCoordinateService; @Autowired GpsPositionService gpsPositionService; @PostConstruct public void init() { gpsPositionService.save(new GpsPosition(new GeoCoordinate(0.0, 0.0), 0.0, 0.0, 0, "rhm")); gpsPositionService.save(new GpsPosition(new GeoCoordinate(0.0, 0.1), 0.0, 0.0, 0, "rhm")); gpsPositionService.save(new GpsPosition(new GeoCoordinate(0.0, 0.2), 0.0, 0.0, 0, "rhm")); gpsPositionService.save(new GpsPosition(new GeoCoordinate(41.527506, 2.363573), 0.0, 0.0, 0, "rhm")); gpsPositionService.save(new GpsPosition(new GeoCoordinate(0.0, 0.0), 0.0, 0.0, 0, "user")); gpsPositionService.save(new GpsPosition(new GeoCoordinate(0.0, 0.11), 0.0, 0.0, 0, "user")); gpsPositionService.save(new GpsPosition(new GeoCoordinate(0.0, 0.19), 0.0, 0.0, 0, "user")); gpsPositionService.save(new GpsPosition(new GeoCoordinate(41.527129, 2.363100), 0.0, 0.0, 0, "user")); } @RequestMapping(value = "/", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public List<GpsPosition> getPositions() { return gpsPositionService.findAll(); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public GpsPosition getPosition(@PathVariable long id) { // double distance = geoCoordinateService.calculateDistance( // getGpsPosition(4).getGeoCoordinate(), // getGpsPosition(8).getGeoCoordinate() // ); return getGpsPosition(id); } @RequestMapping(value = "/", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public GpsPosition createPosition(@RequestBody GpsPositionRequest request) { GpsPosition gpsPosition = new GpsPosition( new GeoCoordinate(request.getLatitude(), request.getLongitude()), request.getAltitude(), request.getSpeed(), request.getTime(), request.getUser() ); gpsPositionService.save(gpsPosition); return gpsPosition; } @RequestMapping(value = "/bulk", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public void createPositions(@RequestBody List<GpsPositionRequest> positions) { positions.forEach(gpsPositionRequest -> { GpsPosition gpsPosition = new GpsPosition( new GeoCoordinate( gpsPositionRequest.getLatitude(), gpsPositionRequest.getLongitude()), gpsPositionRequest.getAltitude(), gpsPositionRequest.getSpeed(), gpsPositionRequest.getTime(), gpsPositionRequest.getUser() ); gpsPositionService.save(gpsPosition); }); } private GpsPosition getGpsPosition(long id) { return gpsPositionService.findOne(id); } }
gpl-3.0
waikato-datamining/adams-base
adams-core/src/main/java/adams/gui/core/SortableAndSearchableTable.java
16988
/* * 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/>. */ /* * SortableAndSearchableTable.java * Copyright (C) 2010-2019 University of Waikato, Hamilton, New Zealand */ package adams.gui.core; import javax.swing.ListSelectionModel; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import java.util.Hashtable; import java.util.Vector; /** * A specialized JTable that allows double-clicking on header for resizing to * optimal width, as well as being searchable and sortable. * * @author fracpete (fracpete at waikato dot ac dot nz) */ public class SortableAndSearchableTable extends BaseTable implements SortableTable, SearchableTable, TableWithColumnFilters { /** for serialization. */ private static final long serialVersionUID = -3176811618121454828L; /** the key for the column width. */ public static final String KEY_COLWIDTH = "col width"; /** the key for the sort column setting. */ public static final String KEY_SORTCOL = "sort col"; /** the key for the sort order. */ public static final String KEY_SORTORDER = "sort order"; /** the key for case-sensitive. */ public static final String KEY_SORTCASESENSITIVE = "sort case-sensitive"; /** the key for the search string. */ public static final String KEY_SEARCHSTRING = "search string"; /** the key for the regular expression search flag. */ public static final String KEY_SEARCHREGEXP = "search reg exp"; /** the sortable/searchable model. */ protected SortableAndSearchableWrapperTableModel m_Model; /** whether to automatically sort table models that get set via setModel. */ protected boolean m_SortNewTableModel; /** * Constructs a default <code>SortedBaseTable</code> that is initialized with a default * data model, a default column model, and a default selection * model. */ public SortableAndSearchableTable() { super(); } /** * Constructs a <code>SortedBaseTable</code> with <code>numRows</code> * and <code>numColumns</code> of empty cells using * <code>DefaultTableModel</code>. The columns will have * names of the form "A", "B", "C", etc. * * @param numRows the number of rows the table holds * @param numColumns the number of columns the table holds */ public SortableAndSearchableTable(int numRows, int numColumns) { super(numRows, numColumns); } /** * Constructs a <code>SortedBaseTable</code> to display the values in the two dimensional array, * <code>rowData</code>, with column names, <code>columnNames</code>. * <code>rowData</code> is an array of rows, so the value of the cell at row 1, * column 5 can be obtained with the following code: * <p> * <pre> rowData[1][5]; </pre> * <p> * All rows must be of the same length as <code>columnNames</code>. * <p> * @param rowData the data for the new table * @param columnNames names of each column */ public SortableAndSearchableTable(final Object[][] rowData, final Object[] columnNames) { super(rowData, columnNames); } /** * Constructs a <code>SortedBaseTable</code> to display the values in the * <code>Vector</code> of <code>Vectors</code>, <code>rowData</code>, * with column names, <code>columnNames</code>. The * <code>Vectors</code> contained in <code>rowData</code> * should contain the values for that row. In other words, * the value of the cell at row 1, column 5 can be obtained * with the following code: * <p> * <pre>((Vector)rowData.elementAt(1)).elementAt(5);</pre> * <p> * @param rowData the data for the new table * @param columnNames names of each column */ public SortableAndSearchableTable(Vector rowData, Vector columnNames) { super(rowData, columnNames); } /** * Constructs a <code>SortedBaseTable</code> that is initialized with * <code>dm</code> as the data model, a default column model, * and a default selection model. * * @param dm the data model for the table */ public SortableAndSearchableTable(TableModel dm) { super(dm); } /** * Constructs a <code>SortedBaseTable</code> that is initialized with * <code>dm</code> as the data model, <code>cm</code> * as the column model, and a default selection model. * * @param dm the data model for the table * @param cm the column model for the table */ public SortableAndSearchableTable(TableModel dm, TableColumnModel cm) { super(dm, cm); } /** * Constructs a <code>SortedBaseTable</code> that is initialized with * <code>dm</code> as the data model, <code>cm</code> as the * column model, and <code>sm</code> as the selection model. * If any of the parameters are <code>null</code> this method * will initialize the table with the corresponding default model. * The <code>autoCreateColumnsFromModel</code> flag is set to false * if <code>cm</code> is non-null, otherwise it is set to true * and the column model is populated with suitable * <code>TableColumns</code> for the columns in <code>dm</code>. * * @param dm the data model for the table * @param cm the column model for the table * @param sm the row selection model for the table */ public SortableAndSearchableTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) { super(dm, cm, sm); } /** * Returns the initial setting of whether to sort new models. * Default implementation returns "false". * * @return true if new models need to be sorted */ protected boolean initialSortNewTableModel() { return false; } /** * Returns whether the initial sort is case-sensitive. * * @return true if case-sensitive */ protected boolean initialSortCaseSensitive() { return true; } /** * Sets whether to sort new models. * * @param value if true then new models get sorted */ public void setSortNewTableModel(boolean value) { m_SortNewTableModel = value; if (m_SortNewTableModel) sort(0); } /** * Returns whether to sort new models. * Default implementation is initialized with "false". * * @return true if new models get sorted */ public boolean getSortNewTableModel() { return m_SortNewTableModel; } /** * Initializes some GUI-related things. */ @Override protected void initGUI() { super.initGUI(); m_SortNewTableModel = initialSortNewTableModel(); setCaseSensitive(initialSortCaseSensitive()); m_Model.addMouseListenerToHeader(this); } /** * Finishes the initialization. */ @Override protected void finishInit() { if (getSortNewTableModel()) sort(0); super.finishInit(); } /** * Returns the class of the table model that the models need to be derived * from. The default implementation just returns TableModel.class * * @return the class the models must be derived from */ protected Class getTableModelClass() { return TableModel.class; } /** * Backs up the settings from the old model. * * @param model the old model (the model stored within the SortedModel) * @return the backed up settings */ protected Hashtable<String,Object> backupModelSettings(TableModel model) { Hashtable<String,Object> result; result = new Hashtable<>(); result.put(KEY_COLWIDTH, getColumnWidthApproach()); result.put(KEY_SORTCOL, m_Model.getSortColumn()); result.put(KEY_SORTORDER, m_Model.isAscending()); result.put(KEY_SORTCASESENSITIVE, m_Model.isCaseSensitive()); if (model instanceof SearchableTableModel) { if (((SearchableTableModel) model).getSeachString() != null) result.put(KEY_SEARCHSTRING, ((SearchableTableModel) model).getSeachString()); result.put(KEY_SEARCHREGEXP, ((SearchableTableModel) model).isRegExpSearch()); } return result; } /** * Restores the settings previously backed up. * * @param model the new model (the model stored within the SortedModel) * @param settings the old settings, null if no settings were available */ protected void restoreModelSettings(TableModel model, Hashtable<String,Object> settings) { int sortCol; boolean asc; boolean caseSensitive; String search; boolean regexp; ColumnWidthApproach colWidth; // default values sortCol = 0; asc = true; caseSensitive = true; search = null; regexp = false; colWidth = initialUseOptimalColumnWidths(); // get stored values if (settings != null) { colWidth = (ColumnWidthApproach) settings.get(KEY_COLWIDTH); sortCol = (Integer) settings.get(KEY_SORTCOL); asc = (Boolean) settings.get(KEY_SORTORDER); caseSensitive = (Boolean) settings.get(KEY_SORTCASESENSITIVE); if (model instanceof SearchableTableModel) { search = (String) settings.get(KEY_SEARCHSTRING); regexp = (Boolean) settings.get(KEY_SEARCHREGEXP); } } // restore sorting m_Model.setCaseSensitive(caseSensitive); if (getSortNewTableModel()) m_Model.sort(sortCol, asc); // restore search if (model instanceof SearchableTableModel) ((SearchableTableModel) model).search(search, regexp); // set optimal column widths setColumnWidthApproach(colWidth); } /** * Sets the model to display - only {@link #getTableModelClass()}. * * @param model the model to display */ @Override public synchronized void setModel(TableModel model) { Hashtable<String,Object> settings; if (!(getTableModelClass().isInstance(model))) model = createDefaultDataModel(); // backup current setup if (m_Model != null) { settings = backupModelSettings(m_Model); getTableHeader().removeMouseListener(m_Model.getHeaderMouseListener()); } else { settings = null; } m_Model = new SortableAndSearchableWrapperTableModel(model); super.setModel(m_Model); m_Model.addMouseListenerToHeader(this); // restore setup restoreModelSettings(m_Model, settings); } /** * Sets the base model to use. Discards any sorting. * * @param value the base model */ public synchronized void setUnsortedModel(TableModel value) { m_Model.setUnsortedModel(value); } /** * Sets the base model to use. * * @param value the base model * @param restoreSorting whether to restore the sorting */ public synchronized void setUnsortedModel(TableModel value, boolean restoreSorting) { m_Model.setUnsortedModel(value, restoreSorting); } /** * returns the underlying model, can be null. * * @return the current model */ public synchronized TableModel getUnsortedModel() { if (m_Model != null) return m_Model.getUnsortedModel(); else return null; } /** * Returns the actual underlying row the given visible one represents. Useful * for retrieving "non-visual" data that is also stored in a TableModel. * * @param visibleRow the displayed row to retrieve the original row for * @return the original row */ public synchronized int getActualRow(int visibleRow) { return m_Model.getActualRow(visibleRow); } /** * Returns the "visible" row derived from row in the actual table model. * * @param internalRow the row in the actual model * @return the row in the sorted model, -1 in case of an error */ public synchronized int getDisplayRow(int internalRow) { return m_Model.getDisplayRow(internalRow); } /** * returns whether the table was sorted. * * @return true if the table was sorted */ public synchronized boolean isSorted() { return m_Model.isSorted(); } /** * Returns the sort column. * * @return the sort column */ public synchronized int getSortColumn() { return m_Model.getSortColumn(); } /** * Returns whether sorting is ascending or not. * * @return true if ascending * @see #isSorted() * @see #getSortColumn() */ public synchronized boolean isAscending() { return m_Model.isAscending(); } /** * Sets whether the sorting is case-sensitive. * * @param value true if case-sensitive */ public void setCaseSensitive(boolean value) { m_Model.setCaseSensitive(value); } /** * Returns whether the sorting is case-sensitive. * * @return true if case-sensitive */ public boolean isCaseSensitive() { return m_Model.isCaseSensitive(); } /** * sorts the table over the given column (ascending). * * @param columnIndex the column to sort over */ public synchronized void sort(int columnIndex) { if (m_Model != null) m_Model.sort(columnIndex); } /** * sorts the table over the given column, either ascending or descending. * * @param columnIndex the column to sort over * @param ascending ascending if true, otherwise descending */ public synchronized void sort(int columnIndex, boolean ascending) { if (m_Model != null) m_Model.sort(columnIndex, ascending); } /** * Returns the actual row count in the model. * * @return the row count in the underlying data */ public synchronized int getActualRowCount() { return m_Model.getActualRowCount(); } /** * Performs a search for the given string. Limits the display of rows to * ones containing the search string. * * @param searchString the string to search for * @param regexp whether to perform regular expression matching * or just plain string comparison */ public synchronized void search(String searchString, boolean regexp) { int[] selected; int i; int index; // determine actual selected rows selected = getSelectedRows(); for (i = 0; i < selected.length; i++) selected[i] = getActualRow(selected[i]); m_Model.search(searchString, regexp); // re-select rows that are still in current search clearSelection(); for (i = 0; i < selected.length; i++) { index = getDisplayRow(selected[i]); if (index != -1) getSelectionModel().addSelectionInterval(index, index); } } /** * Returns the current search string. * * @return the search string, null if not filtered */ public synchronized String getSeachString() { return m_Model.getSeachString(); } /** * Returns whether the last search was a regular expression based one. * * @return true if last search was a reg exp one */ public synchronized boolean isRegExpSearch() { return m_Model.isRegExpSearch(); } /** * Sets the filter for the column. * * @param column the column to filter * @param filter the filter string * @param isRegExp whether the filter is a regular expression */ public void setColumnFilter(int column, String filter, boolean isRegExp) { m_Model.setColumnFilter(column, filter, isRegExp); } /** * Returns the filter for the column. * * @param column the column to query * @return the filter, null if none present */ public String getColumnFilter(int column) { return m_Model.getColumnFilter(column); } /** * Returns the whether the filter for the column is a regular expression. * * @param column the column to query * @return true if filter set and regular expression */ public boolean isColumnFilterRegExp(int column) { return m_Model.isColumnFilterRegExp(column); } /** * Returns the whether there is a filter active for the column. * * @param column the column to query * @return true if a filter is active */ public boolean isColumnFiltered(int column) { return m_Model.isColumnFiltered(column); } /** * Returns whether there is at least one filter active. * * @return true if at least one filter is active */ public boolean isAnyColumnFiltered() { return m_Model.isAnyColumnFiltered(); } /** * Removes any filter for the column. * * @param column the column to update */ public void removeColumnFilter(int column) { m_Model.removeColumnFilter(column); } /** * Removes all column filters */ public void removeAllColumnFilters() { m_Model.removeAllColumnFilters(); } }
gpl-3.0
stuartmscott/OpenFlame
Compiler/source/internalrep/assembly/arithmeticlogic/Add.java
1470
/* * The OpenFlame Project <http://stuartmscott.github.io/OpenFlame/>. * * Copyright (C) 2015 OpenFlame Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package internalrep.assembly.arithmeticlogic; import generator.Register; public class Add extends AluInst { public Add(String comment, boolean isFloat, Register source1, Register source2, Register destination) { // Adds source1 and source2 and puts result in destination super(comment, isFloat, ADD, source1, source2, destination); } public Add(String comment, boolean isFloat, int source1, int source2, int destination) { super(comment, isFloat, ADD, source1, source2, destination); } public String toString() { toIndexies(); return "add r" + mSourceIndex1 + " r" + mSourceIndex2 + " r" + mDestinationIndex + super.toString(); } }
gpl-3.0
Todkommt/Mass-Effect-Ships-Mod
lib/src/CoFHCore/src/main/java/cofh/repack/codechicken/lib/render/uv/UVTransformationList.java
2456
package cofh.repack.codechicken.lib.render.uv; import java.util.ArrayList; import java.util.Iterator; public class UVTransformationList extends UVTransformation { private ArrayList<UVTransformation> transformations = new ArrayList<UVTransformation>(); public UVTransformationList(UVTransformation... transforms) { for (UVTransformation t : transforms) { if (t instanceof UVTransformationList) { transformations.addAll(((UVTransformationList) t).transformations); } else { transformations.add(t); } } compact(); } @Override public void apply(UV uv) { for (int i = 0; i < transformations.size(); i++) { transformations.get(i).apply(uv); } } @Override public UVTransformationList with(UVTransformation t) { if (t.isRedundant()) { return this; } if (t instanceof UVTransformationList) { transformations.addAll(((UVTransformationList) t).transformations); } else { transformations.add(t); } compact(); return this; } public UVTransformationList prepend(UVTransformation t) { if (t.isRedundant()) { return this; } if (t instanceof UVTransformationList) { transformations.addAll(0, ((UVTransformationList) t).transformations); } else { transformations.add(0, t); } compact(); return this; } private void compact() { ArrayList<UVTransformation> newList = new ArrayList<UVTransformation>(transformations.size()); Iterator<UVTransformation> iterator = transformations.iterator(); UVTransformation prev = null; while (iterator.hasNext()) { UVTransformation t = iterator.next(); if (t.isRedundant()) { continue; } if (prev != null) { UVTransformation m = prev.merge(t); if (m == null) { newList.add(prev); } else if (m.isRedundant()) { t = null; } else { t = m; } } prev = t; } if (prev != null) { newList.add(prev); } if (newList.size() < transformations.size()) { transformations = newList; } } @Override public boolean isRedundant() { return transformations.size() == 0; } @Override public UVTransformation inverse() { UVTransformationList rev = new UVTransformationList(); for (int i = transformations.size() - 1; i >= 0; i--) { rev.with(transformations.get(i).inverse()); } return rev; } @Override public String toString() { String s = ""; for (UVTransformation t : transformations) { s += "\n" + t.toString(); } return s.trim(); } }
gpl-3.0
cosminrentea/roda
src/main/java/ro/roda/repository/RegionRepository.java
323
package ro.roda.repository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import ro.roda.domain.Region; @RepositoryRestResource public interface RegionRepository extends PagingAndSortingRepository<Region, Integer> { }
gpl-3.0
jpchanson/OpenDMS
src/tomoBay/model/services/emailErrorsService/EmailErrorsService.java
2874
package tomoBay.model.services.emailErrorsService; /** Copyright(C) 2015 Jan P.C. Hanson & Tomo Motor Parts Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.HashMap; import java.util.Map; import org.w3c.dom.NodeList; import tomoBay.exceptions.ServiceException; import tomoBay.helpers.XMLParser; import tomoBay.model.services.AbstractConfiguration; import tomoBay.model.services.AbstractService; /** * This service is responsible for generating a list of erroneous items that exist within the * database and emailing it to appropriate parties. * @author Jan P.C. Hanson * */ public class EmailErrorsService implements AbstractService { /****/ private Map<String, emailDataType> mailData_M; /****/ enum emailDataType { TO, CC, BCC, SUBJECT, MESSAGE } public EmailErrorsService() {super();} /* (non-Javadoc) * @see tomoBay.model.services.AbstractService#run() */ @Override public void run() throws ServiceException { //make sure the service has been configured if (this.mailData_M == null) {throw new ServiceException("no AbstractConfiguration object set");} ErrorsList errors = new ErrorsList(); if (errors.exist()) { EmailErrorsMailActions email = new EmailErrorsMailActions(); EmailErrorsDataFormat format = new EmailErrorsDataFormat(); email.loadData(this.mailData_M); String message = format.asHTML(errors.get()); email.addMessage(message); email.send(); } } /* (non-Javadoc) * @see tomoBay.model.services.AbstractService#setConfig(tomoBay.model.services.AbstractConfiguration) */ @Override public <E> void setConfig(AbstractConfiguration<E> config) { this.mailData_M = new HashMap<String, emailDataType>(); String xmlData = (String) config.configure(); for (emailDataType type : emailDataType.values()) { NodeList nodes = XMLParser.parseAll(type.toString(), xmlData); for(int i = 0 ; i < nodes.getLength() ; ++i) { if (this.mailData_M.containsKey(nodes.item(i).getTextContent())) {throw new ServiceException("\""+nodes.item(i).getTextContent()+"\" in \""+type+"\""+" is a duplicate of another field!!!" );} this.mailData_M.put(nodes.item(i).getTextContent(), type); } } } }
gpl-3.0
cosminrentea/roda
src/main/java/ro/roda/ddi/RspStmtType_.java
619
package ro.roda.ddi; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="Dali", date="2012-10-26T12:00:09.563+0300") @StaticMetamodel(RspStmtType.class) public class RspStmtType_ { public static volatile SingularAttribute<RspStmtType, Long> id_; public static volatile ListAttribute<RspStmtType, AuthEntyType> authEnty; public static volatile ListAttribute<RspStmtType, OthIdType> othId; public static volatile SingularAttribute<RspStmtType, String> id; }
gpl-3.0