hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
30187e5c8fa2a8053433d9a2b81fc371a05f8cef
5,710
/* Copyright (c) 2016 OpenJAX * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * You should have received a copy of The MIT License (MIT) along with this * program. If not, see <http://opensource.org/licenses/MIT/>. */ package org.openjax.jjb.runtime; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.openjax.standard.net.URIComponent; import org.openjax.standard.util.FastCollections; import org.openjax.standard.util.Numbers; import org.openjax.jjb.runtime.decoder.StringDecoder; public class Property<T> { @SuppressWarnings("unchecked") private static <T>T encode(final T value, final JSObject jsObject, final Binding<T> binding) { if (value != null && !binding.type.isAssignableFrom(value.getClass())) throw new EncodeException("\"" + binding.name + "\": " + value.getClass().getName() + " cannot be encoded as " + binding.type.getName(), jsObject); if (value instanceof String) { final String escaped = StringDecoder.escapeString((String)value); return (T)(binding.urlEncode ? URIComponent.encode(escaped) : escaped); } return value; } @SuppressWarnings("unchecked") private static <T>T decode(final T value, final JSObject jsObject, final Binding<T> binding) { return value instanceof String && binding.urlDecode ? (T)URIComponent.decode(((String)value)) : value; } private final JSObject jsObject; protected final Binding<T> binding; private Required required; private boolean present = false; private T value; public Property(final JSObject jsObject, final Binding<T> binding) { this.jsObject = jsObject; this.binding = binding; this.required = binding.required; } protected void clone(final Property<T> clone) { this.present = clone.present; this.value = clone.value; } protected boolean isTypeAssignable(final T value) { final Class<?> type; return value == null || (binding.array ? value instanceof List && ((type = FastCollections.getComponentType((List<?>)value)) == null || binding.type.isAssignableFrom(type)) : binding.type.isAssignableFrom(type = value.getClass())); } public void set(final T value) { // FIXME: This check is not necessary in the real world, as the only way it // FIXME: is possible call set() with an incorrectly typed object is with // FIXME: raw or missing (thus unchecked) generics, or thru reflection. // if (!isTypeAssignable(value)) // throw new ClassCastException(binding.type.getName() + " incompatible with " + (binding.array ? List.class.getName() + "<" + value.getClass().getName() + ">" : value.getClass().getName())); this.present = true; this.value = value; } public T get() { return value; } public void clear() { this.present = false; this.value = null; } protected Required required() { return required; } public boolean present() { return present; } protected String getPath() { return jsObject._getPath() + "." + binding.name; } @SuppressWarnings("unchecked") protected T encode() throws EncodeException { final String error = binding.validate(this, value); if (error != null) throw new EncodeException(error, jsObject); if (!binding.isAssignable(value)) throw new EncodeException("\"" + binding.name + "\": " + value.getClass().getName() + " cannot be encoded as " + (binding.array ? List.class.getName() + "<" + value.getClass().getName() + ">" : value.getClass().getName()), jsObject); if (value instanceof Collection<?>) { final Collection<T> collection = (Collection<T>)value; final Collection<T> encoded = new JSArray<>(collection.size()); for (final T member : collection) encoded.add(encode(member, jsObject, binding)); return (T)encoded; } return encode(value, jsObject, binding); } @SuppressWarnings("unchecked") protected void decode(final JsonReader reader) throws DecodeException, IOException { final String error = binding.validate(this, value); if (error != null) throw new DecodeException(error, reader); if (value instanceof Collection<?>) { final Collection<T> collection = (Collection<T>)value; final Collection<T> decoded = new ArrayList<>(collection.size()); for (final T member : collection) decoded.add(decode(member, jsObject, binding)); this.value = (T)decoded; } else { this.value = decode(value, jsObject, binding); } } @Override public int hashCode() { final int hashCode = 1917841483; return value == null ? hashCode : hashCode ^ 31 * value.hashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) return true; if (!(obj instanceof Property)) return false; final Property<?> that = (Property<?>)obj; if (that.value instanceof Number) return Numbers.equivalent((Number)value, (Number)that.value, 10 * Math.max(Math.ulp(((Number)value).doubleValue()), Math.ulp(((Number)that.value).doubleValue()))); return that.value != null ? that.value.equals(value) : value == null; } }
35.246914
239
0.686865
ac3b839caad1f1461d8998d4097927cad97044b5
1,590
package fwcd.sketch.view.tools; import java.util.function.Consumer; import javax.swing.ImageIcon; import fwcd.fructose.EventListenerList; import fwcd.fructose.Option; import fwcd.fructose.function.Subscription; import fwcd.fructose.geometry.LineSeg2D; import fwcd.fructose.geometry.Vector2D; import fwcd.fructose.swing.ResourceImage; import fwcd.sketch.model.BrushProperties; import fwcd.sketch.model.items.ColoredLine; import fwcd.sketch.model.items.ColoredPath; import fwcd.sketch.model.items.SketchItem; public class Brush extends DrawTool<ColoredPath> { private static final ImageIcon ICON = new ResourceImage("/brushIcon.png").getAsIcon(); private final EventListenerList<SketchItem> partListeners = new EventListenerList<>(); private int precision = 0; public void setPrecision(int precision) { this.precision = precision; } @Override public ImageIcon getIcon() { return ICON; } @Override protected ColoredPath getSketchItem(Vector2D startPos, BrushProperties props) { return new ColoredPath(props); } @Override protected ColoredPath updateItem(ColoredPath item, Vector2D start, Vector2D last, Vector2D pos) { if (pos.sub(last).length() > precision) { LineSeg2D part = new LineSeg2D(last, pos); if (partListeners.size() > 0) { partListeners.fire(new ColoredLine(part, item.getColor(), item.getThickness())); } return item.withLine(part); } else { return item; } } @Override public Option<Subscription> subscribeToAddedParts(Consumer<? super SketchItem> listener) { return Option.of(partListeners.subscribe(listener)); } }
28.909091
98
0.769811
8807ae2496566d7eb2bc1711d4d560b268ff618a
8,527
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.repository.viewer.filter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jdt.internal.ui.util.StringMatcher; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.talend.core.model.properties.BusinessProcessItem; import org.talend.core.model.properties.Item; import org.talend.core.model.properties.JobDocumentationItem; import org.talend.core.model.properties.Property; import org.talend.core.model.properties.RoutineItem; import org.talend.core.model.properties.SQLPatternItem; import org.talend.core.model.properties.User; import org.talend.core.model.properties.impl.JobletDocumentationItemImpl; import org.talend.core.model.repository.ERepositoryObjectType; import org.talend.core.model.repository.IRepositoryPrefConstants; import org.talend.core.model.repository.RepositoryManager; import org.talend.repository.RepositoryViewPlugin; import org.talend.repository.model.IRepositoryNode; import org.talend.repository.model.IRepositoryNode.ENodeType; import org.talend.repository.model.IRepositoryNode.EProperties; import org.talend.repository.model.RepositoryConstants; import org.talend.repository.model.RepositoryNode; /** * DOC ggu class global comment. Detailled comment * * filter by status, users and label for repository element and folder * * FIXME, later, it's better to split for each functions. */ public class RepositoryCommonViewerFilter extends ViewerFilter { /** * DOC ggu RepositoryViewerFilter constructor comment. */ public RepositoryCommonViewerFilter() { } protected IPreferenceStore getPreferenceStore() { return RepositoryViewPlugin.getDefault().getPreferenceStore(); } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, * java.lang.Object) */ @Override public boolean select(Viewer viewer, Object parentElement, Object element) { if (!getPreferenceStore().getBoolean(IRepositoryPrefConstants.USE_FILTER)) { return true; } boolean visible = true; if (element instanceof RepositoryNode) { RepositoryNode node = (RepositoryNode) element; if (ENodeType.REPOSITORY_ELEMENT.equals(node.getType()) || ENodeType.SIMPLE_FOLDER.equals(node.getType())) { visible = filterByUserStatusName(node); } } return visible; } private boolean filterByUserStatusName(RepositoryNode node) { String[] statusFilter = RepositoryNodeFilterHelper.getFiltersByPreferenceKey(IRepositoryPrefConstants.FILTER_BY_STATUS); String[] userFilter = RepositoryNodeFilterHelper.getFiltersByPreferenceKey(IRepositoryPrefConstants.FILTER_BY_USER); boolean enableNameFilter = getPreferenceStore().getBoolean(IRepositoryPrefConstants.TAG_USER_DEFINED_PATTERNS_ENABLED); if (statusFilter == null && userFilter == null && !enableNameFilter) { return true; } boolean visible = true; if (ENodeType.SIMPLE_FOLDER.equals(node.getType())) { visible = isStableItem(node); if (visible) { return true; } for (IRepositoryNode childNode : node.getChildren()) { visible = visible || filterByUserStatusName((RepositoryNode) childNode); if (visible) { return true; } } return visible; } List items = new ArrayList(); if (statusFilter != null && statusFilter.length > 0) { items.addAll(Arrays.asList(statusFilter)); } if (userFilter != null && userFilter.length > 0) { items.addAll(Arrays.asList(userFilter)); } if (node.getObject() != null) { Property property = node.getObject().getProperty(); String statusCode = ""; if (property != null) { statusCode = property.getStatusCode(); } User author = node.getObject().getAuthor(); String user = ""; if (author != null) { user = author.getLogin(); } if ((items.contains(statusCode) || items.contains(user)) && !isStableItem(node)) { visible = false; } else if (items.contains(RepositoryConstants.NOT_SET_STATUS) && (statusCode == null || "".equals(statusCode))) { visible = false; if (property != null) { Item item = property.getItem(); if (item instanceof RoutineItem && ((RoutineItem) item).isBuiltIn() || item instanceof SQLPatternItem && ((SQLPatternItem) item).isSystem() || item instanceof BusinessProcessItem || item instanceof JobDocumentationItem || item instanceof JobletDocumentationItemImpl) { visible = true; } } } } // filter by name String label = (String) node.getProperties(EProperties.LABEL); if (visible && isMatchNameFilterPattern(label)) { visible = true; } else { if (enableNameFilter && !isStableItem(node)) { visible = false; } } return visible; } private boolean isMatchNameFilterPattern(String label) { boolean enable = getPreferenceStore().getBoolean(IRepositoryPrefConstants.TAG_USER_DEFINED_PATTERNS_ENABLED); if (!enable) { return false; } if (label != null && label.length() > 0) { StringMatcher[] testMatchers = getMatchers(); if (testMatchers != null) { for (StringMatcher testMatcher : testMatchers) { if (testMatcher.match(label)) { return true; } } } } return false; } private StringMatcher[] getMatchers() { String userFilterPattern = getPreferenceStore().getString(IRepositoryPrefConstants.FILTER_BY_NAME); String[] newPatterns = null; if (userFilterPattern != null && !"".equals(userFilterPattern)) { newPatterns = RepositoryNodeFilterHelper.convertFromString(userFilterPattern, RepositoryManager.PATTERNS_SEPARATOR); } StringMatcher[] matchers = null; if (newPatterns != null) { matchers = new StringMatcher[newPatterns.length]; for (int i = 0; i < newPatterns.length; i++) { matchers[i] = new StringMatcher(newPatterns[i], true, false); } } return matchers; } private boolean isStableItem(RepositoryNode node) { Object label = node.getProperties(EProperties.LABEL); if (ENodeType.SIMPLE_FOLDER.equals(node.getType()) && ERepositoryObjectType.SQLPATTERNS.equals(node.getContentType()) && (label.equals("Generic") || label.equals("UserDefined") || label.equals("MySQL") || label.equals("Netezza") || label.equals("Oracle") || label.equals("ParAccel") || label.equals("Teradata")) || label.equals("Hive")) { return true; } else if (ENodeType.REPOSITORY_ELEMENT.equals(node.getType()) && node.getObject() != null) { Item item = node.getObject().getProperty().getItem(); if (item instanceof SQLPatternItem) { if (((SQLPatternItem) item).isSystem()) { return true; } } else if (item instanceof RoutineItem) { if (((RoutineItem) item).isBuiltIn()) { return true; } } } return false; } }
39.294931
128
0.611939
1ce8b17e9307776deff4b23e79b9f5f8467b62de
2,308
package de.icw.util.collect; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Default implementation of {@link PartialCollection} based on {@link ArrayList}. * <h3>Usage</h3> * <p> * See {@link PartialArrayList#of(List, int)} * </p> * * @param <T> */ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class PartialArrayList<T extends Serializable> extends ArrayList<T> implements PartialCollection<T> { private static final long serialVersionUID = -7548645400982124555L; private final boolean moreAvailable; /** * Default constructor. * * @param list the list of entities to store. * @param moreAvailable the flag to store. */ public PartialArrayList(Collection<T> list, boolean moreAvailable) { super(list); this.moreAvailable = moreAvailable; } @Override public boolean isMoreAvailable() { return moreAvailable; } /** * Static constructor for an empty instance. * * @param <T> * @return an empty {@link PartialArrayList}. */ public static <T extends Serializable> PartialArrayList<T> emptyList() { return new PartialArrayList<>(Collections.emptyList(), false); } /** * Convenience method for creating a {@link PartialArrayList} as sublist for the given * collection with setting the {@link PartialCollection#isMoreAvailable()} automatically * * @param full the complete List to be wrapped, may be larger than the limit. If so, a sublist * will be used. * @param limit to be checked against * * @param <T> identifying the type of contained elements * @return an newly created {@link PartialArrayList}. */ public static <T extends Serializable> PartialArrayList<T> of(List<T> full, int limit) { if (null == full || full.isEmpty()) { return emptyList(); } int actualSize = full.size(); if (actualSize <= limit) { return new PartialArrayList<>(full, false); } else { return new PartialArrayList<>(full.subList(0, limit), true); } } }
29.21519
108
0.652946
85da1230f857bc451ef34a20162a1a370172eb0e
5,108
import java.util.HashSet; import java.util.Set; import java.util.Stack; /** * The class is used for recording the status of the player, * including the current location, the caught Poke�ons, the number of Poke balls and the path visited. * @author SNYMac * */ public class Player implements Cloneable{ private Cell baseCell; private Stack<Pokemon> caughtPoke; private Stack<Coordinate> path; private int numPokeBall = 0; private int numStep = 0; private int[][] score; //debug public void printAllScore(){ for (int i=0;i<score.length; i++){ for (int j=0;j<score[0].length; j++){ System.out.print(score[i][j] + " "); } System.out.println(); } } public Player(){ caughtPoke = new Stack<>(); path = new Stack<>(); } public Player(int rows, int cols, Cell base){ this(); baseCell = base; Coordinate c = baseCell.getCoor(); path.push(c); //initialize score at each cell score = new int[rows][cols]; for (int i=0; i<score.length; i++){ for (int j=0; j<score[0].length; j++) score[i][j] = Integer.MIN_VALUE; } //initialize score at base cell score[c.getRow()][c.getCol()] = 0; } public Stack<Coordinate> getPath(){ return path; } public int getScore(Coordinate c){ return score[c.getRow()][c.getCol()]; } public Cell getBaseCell(){ return baseCell; } /** * @return the formatted current necessary properties of the player for output in String */ public String formattedPlayerInfo(){ return (numPokeBall + ":" + caughtPoke.size() + ":" + numDistinctPokeType() + ":" + maxPokeCp()); } /** * Calculate the score based on the state of the player * @return the calculated score */ public int calcScore(){ return numPokeBall + (5 * caughtPoke.size()) + (10 * numDistinctPokeType()) + maxPokeCp() - numStep; } /** * Update the score at a specific cell if the new score is better * @param coor the coordinate of the cell to be updated * @param newScore the calculated new score * @return true if the score is updated */ public boolean updateCellScore(Coordinate coor, int newScore){ int currScore = score[coor.getRow()][coor.getCol()]; if (newScore > currScore){ score[coor.getRow()][coor.getCol()] = newScore; return true; } return false; } /** * change the score of a specific cell, this should be used only when the previous value is known * @param c the coordinate of the cell * @param oldScore previous version of the score stored outside the Player class */ public void revertScore(Coordinate c, int oldScore){ score[c.getRow()][c.getCol()] = oldScore; } /** * Try to catch the pokemon and deactivate the pokemon if needed * @param poke the pokemon object * @return true if pokemon is caught successfully */ public boolean catchPokemon(Pokemon poke){ if (numPokeBall >= poke.getReqBall()/* && poke.isActive()*/){ caughtPoke.push(poke); numPokeBall -= poke.getReqBall(); poke.setActive(false); // System.out.println("caught" + poke.name); return true; } return false; } /** * Collect the pokeballs in the station and deactivate the station if needed * @param stn the station that the player stepped on * @return true if pokeballs are successfully collected */ public void collectStation(Station stn){ // System.out.println("get " + stn.getnumBall()); numPokeBall += stn.getnumBall(); stn.setActive(false); } /** * revert the state of the player * @param gobj the GameObject that holds the information to revert the player */ public void rollback(GameObject gobj){ gobj.setActive(true); if (gobj instanceof Pokemon){ // System.out.println("release " + ((Pokemon)gobj).name); numPokeBall += caughtPoke.pop().getReqBall(); } else if (gobj instanceof Station){ // System.out.println("release " + ((Station)gobj).getnumBall()); numPokeBall -= ((Station)gobj).getnumBall(); } } /** * Store the path and increment the step counter * @param coor */ public void recordPath(Coordinate coor){ // System.out.println("push " + coor); path.push(coor); numStep++; } /** * remove the latest cell coordinate of the path stored */ public void revertPath(){ // System.out.println("pop"); path.pop(); numStep--; } /** * Overridden clone method for Player */ @Override protected Player clone(){ Player p; try { p = (Player) super.clone(); p.caughtPoke = (Stack<Pokemon>) this.caughtPoke.clone(); p.path = (Stack<Coordinate>) this.path.clone(); return p; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * @return number of distinct type of pokemons caught */ private int numDistinctPokeType(){ Set<String> distinctType = new HashSet<>(); for (Pokemon p: caughtPoke){ distinctType.add(p.getType()); } return distinctType.size(); } /** * @return the maximum CP of pokemons caught */ private int maxPokeCp(){ int maxCp = 0; for (Pokemon p: caughtPoke){ if (maxCp < p.getCp()) maxCp = p.getCp(); } return maxCp; } }
24.557692
103
0.659945
afd6b99be07e0f9c62fc57e72cb438aee9391065
2,195
package com.lixuemin.mock.event; /** * @program: bwol-icll * * @description: 学习详情 * * @author: lixuemin * * @create: 2021-05-07 **/ public class LearningDetailEvent { private String resCode;//资源编码 private Integer resType;//资源类型 private Long optTime;//操作时间 private String ansOption;//作答选项 private Integer result;//作答结果 private Integer eventType;//事件类型 private Long recordStartTime; //跟读开始 private Long recordEndTime;//跟读结束 private String recordAudioCode;//跟读音频标识 private Double recordScore;//跟读分值 public String getResCode() { return resCode; } public void setResCode(String resCode) { this.resCode = resCode; } public Integer getResType() { return resType; } public void setResType(Integer resType) { this.resType = resType; } public String getAnsOption() { return ansOption; } public void setAnsOption(String ansOption) { this.ansOption = ansOption; } public Integer getResult() { return result; } public void setResult(Integer result) { this.result = result; } public Integer getEventType() { return eventType; } public void setEventType(Integer eventType) { this.eventType = eventType; } public Long getOptTime() { return optTime; } public void setOptTime(Long optTime) { this.optTime = optTime; } public Long getRecordStartTime() { return recordStartTime; } public void setRecordStartTime(Long recordStartTime) { this.recordStartTime = recordStartTime; } public Long getRecordEndTime() { return recordEndTime; } public void setRecordEndTime(Long recordEndTime) { this.recordEndTime = recordEndTime; } public String getRecordAudioCode() { return recordAudioCode; } public void setRecordAudioCode(String recordAudioCode) { this.recordAudioCode = recordAudioCode; } public Double getRecordScore() { return recordScore; } public void setRecordScore(Double recordScore) { this.recordScore = recordScore; } }
21.105769
60
0.642825
048ae5f73b10432da864d62f390b5c4a421a1bab
415
package com.loveplusplus.update.sample; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; public class ExitActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_exit); int pid=android.os.Process.myPid(); android.os.Process.killProcess(pid); finish();; } }
23.055556
53
0.783133
367c53fb1b0e73e929cd8c7d778a64a397841861
1,441
/** * */ package august_leetcode_challenges; /** * @author PRATAP LeetCode 303 * */ public class Day16_RangeSumQueryImmutable { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } } class NumArray { int tree[]; int newArr[]; public NumArray(int[] nums) { this.newArr = nums; tree = new int[4 * nums.length]; build(1, 0, nums.length - 1); } private void build(int node, int start, int end) { // TODO Auto-generated method stub if (start == end) { tree[node] = this.newArr[start]; return; } int mid = (start + end) / 2; int left = 2 * node; int right = 2 * node + 1; build(left, start, mid); build(right, mid + 1, end); tree[node] = tree[left] + tree[right]; } public int sumRange(int l, int r) { int start = 0, end = this.newArr.length - 1; int ans = find(1, start, end, l, r); return ans; } private int find(int node, int start, int end, int l, int r) { // TODO Auto-generated method stub if (start > r || end < l) return Integer.MIN_VALUE; if (start == end) return tree[node]; else if (start >= l && end <= r) { return tree[node]; } else { int mid = (start + end) / 2; int left = find(2 * node, start, mid, l, r); int right = find(2 * node + 1, mid + 1, end, l, r); int sum = (left == Integer.MIN_VALUE) ? 0 : left; sum += (right == Integer.MIN_VALUE) ? 0 : right; return sum; } } }
20.295775
63
0.590562
f53b69af19eab25fb3db3e07c552a0e7792b1070
2,031
package onethreeseven.common.util; import org.junit.Assert; import org.junit.Test; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; /** * Testing parsing date/time using {@link TimeUtil}. * @author Luke Bermingham */ public class TimeUtilTest { @Test public void parseDate1() throws Exception { LocalDateTime expected = LocalDateTime.of(1994, 6, 17, 13, 0, 2); LocalDateTime actual = TimeUtil.parseDate("17/06/1994 13:00:02"); Assert.assertTrue(ChronoUnit.SECONDS.between(expected, actual) == 0); } @Test public void parseDate2() throws Exception { LocalDateTime expected = LocalDateTime.of(2012, 8, 16, 14, 0, 0); LocalDateTime actual = TimeUtil.parseDate("16/08/2012 2:00 PM"); Assert.assertTrue(ChronoUnit.SECONDS.between(expected, actual) == 0); } @Test public void parseDate3() throws Exception { LocalDateTime expected = LocalDateTime.of(2007, 4, 12, 16, 39, 48); LocalDateTime actual = TimeUtil.parseDate("2007-04-12 16:39:48"); Assert.assertTrue(ChronoUnit.SECONDS.between(expected, actual) == 0); } @Test public void parseDate4() throws Exception { LocalDateTime expected = LocalDateTime.of(1993, 5, 13, 16, 39, 48); LocalDateTime actual = TimeUtil.parseDate("19930513 16:39:48"); Assert.assertTrue(ChronoUnit.SECONDS.between(expected, actual) == 0); } @Test public void parseDate5() throws Exception { LocalDateTime expected = LocalDateTime.of(2011, 12, 3, 10, 15, 30); LocalDateTime actual = TimeUtil.parseDate("2011-12-03T10:15:30+01:00"); Assert.assertTrue(ChronoUnit.SECONDS.between(expected, actual) == 0); } @Test public void parseDate6() throws Exception { LocalDateTime expected = LocalDateTime.of(2012, 11, 9, 21, 51, 2); LocalDateTime actual = TimeUtil.parseDate("2012-11-09T21:51:02Z"); Assert.assertTrue(ChronoUnit.SECONDS.between(expected, actual) == 0); } }
35.631579
79
0.67356
9ea0169ff6884c33a945edd60ebb1e8c67b2cc69
4,635
package android.preference; import android.MobialiaUtil; import android.Res; import android.content.Context; import android.content.SharedPreferences; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.InputElement; import com.google.gwt.dom.client.SelectElement; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.EventListener; public class PreferencesBuilder { public static void addGroupLabel(Element panel, int labelText) { addGroupLabel(panel, Context.resources.getString(labelText)); } public static void addGroupLabel(Element panel, String labelText) { Element labelE = DOM.createDiv(); labelE.setInnerHTML(labelText); labelE.addClassName(Res.R.style().dialogTitle()); panel.appendChild(labelE); } public static void addListPreference(Element panel, final SharedPreferences sharedPrefs, final String key, int label, int summary, final int values, int labels, String defaultValue) { addListPreference(panel, sharedPrefs, key, Context.resources.getString(label), Context.resources.getString(summary), Context.resources.getStringArray(values), Context.resources.getStringArray(labels), defaultValue); } public static void addListPreference(Element panel, final SharedPreferences sharedPrefs, final String key, String label, String summary, final String[] values, String[] labels, String defaultValue) { String value = sharedPrefs.getString(key, defaultValue); Element inputLabel = DOM.createLabel(); inputLabel.addClassName(Res.R.style().preferencesElement()); final Element listBoxE = DOM.createSelect(); listBoxE.addClassName(Res.R.style().preferencesListBox()); listBoxE.addClassName(Res.R.style().materialSelect()); int selectedPosition = MobialiaUtil.arrayPosition(values, value); int i = 0; for (String text : labels) { Element optionE = DOM.createOption(); optionE.setInnerHTML(text); if (i++ == selectedPosition) { optionE.setPropertyString("selected", "selected"); } listBoxE.appendChild(optionE); } Event.setEventListener(listBoxE, new EventListener() { @Override public void onBrowserEvent(Event event) { SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString(key, values[((SelectElement) listBoxE).getSelectedIndex()]); editor.commit(); } }); Event.sinkEvents(listBoxE, Event.ONCHANGE); inputLabel.appendChild(listBoxE); Element labelG = DOM.createDiv(); labelG.addClassName(Res.R.style().preferencesLabel()); labelG.setInnerHTML(label); inputLabel.appendChild(labelG); Element summaryG = DOM.createDiv(); summaryG.addClassName(Res.R.style().preferencesSummary()); summaryG.setInnerHTML(summary); inputLabel.appendChild(summaryG); panel.appendChild(inputLabel); } public static void addBooleanPreference(Element panel, final SharedPreferences sharedPrefs, final String key, int label, int summary, boolean defaultValue) { addBooleanPreference(panel, sharedPrefs, key, Context.resources.getString(label), Context.resources.getString(summary), defaultValue); } public static void addBooleanPreference(Element panel, final SharedPreferences sharedPrefs, final String key, String label, String summary, boolean defaultValue) { Boolean value = sharedPrefs.getBoolean(key, defaultValue); Element inputLabel = DOM.createLabel(); inputLabel.addClassName(Res.R.style().materialLabel()); inputLabel.addClassName(Res.R.style().preferencesElement()); final Element checkBox = DOM.createInputCheck(); if (value) { checkBox.setPropertyString("checked", "true"); } inputLabel.appendChild(checkBox); final Element checkboxSymbol = DOM.createDiv(); checkboxSymbol.addClassName(Res.R.style().materialCheckbox()); checkboxSymbol.addClassName(Res.R.style().preferencesCheckBox()); inputLabel.appendChild(checkboxSymbol); Element labelG = DOM.createDiv(); labelG.addClassName(Res.R.style().preferencesLabel()); labelG.setInnerHTML(label); inputLabel.appendChild(labelG); Element summaryG = DOM.createDiv(); summaryG.addClassName(Res.R.style().preferencesSummary()); summaryG.setInnerHTML(summary); inputLabel.appendChild(summaryG); Event.setEventListener(inputLabel, new EventListener() { @Override public void onBrowserEvent(Event event) { SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean(key, ((InputElement) checkBox).isChecked()); editor.commit(); } }); Event.sinkEvents(inputLabel, Event.ONCLICK | Event.ONTOUCHEND); panel.appendChild(inputLabel); } }
37.08
140
0.759008
9db481ba01c3e83cba317404f796127fe365a995
739
package dev.utils.app.assist.floating; import android.app.Activity; import android.view.View; import android.view.ViewGroup; /** * detail: 悬浮窗辅助类接口 * @author Ttt * <pre> * {@link FloatingWindowManagerAssist2} 所需接口方法 * </pre> */ public interface IFloatingActivity { /** * 获取悬浮窗依附的 Activity * @return {@link Activity} */ Activity getAttachActivity(); /** * 获取悬浮窗 Map Key * @return 悬浮窗 Map Key */ String getMapFloatingKey(); /** * 获取悬浮窗 Map Value View * @return 悬浮窗 Map Value View */ View getMapFloatingView(); /** * 获取悬浮窗 View LayoutParams * @return 悬浮窗 View LayoutParams */ ViewGroup.LayoutParams getMapFloatingViewLayoutParams(); }
18.948718
60
0.631935
d0dde68a1d5d17ac47f1626988b384908ab36eb6
600
package com.baidu.beidou.navi.server.processor; import com.baidu.beidou.navi.server.callback.Callback; import com.baidu.beidou.navi.server.vo.NaviRpcRequest; import com.baidu.beidou.navi.server.vo.NaviRpcResponse; /** * ClassName: NaviRpcProcessor <br/> * Function: Navi Rpc处理单元接口 * * @author Zhang Xu */ public interface NaviRpcProcessor { /** * 处理请求并且响应结果 * * @param request * 请求 * @param callback * 结果Callback */ public void service(NaviRpcRequest request, Callback<NaviRpcResponse> callback); }
23.076923
85
0.645
6b5aeced26cf509e066ffdeac2543bdb848203d8
386
package com.google.android.gms.internal.ads; import android.webkit.JavascriptInterface; /* compiled from: com.google.android.gms:play-services-ads@@19.4.0 */ final class zzajx { private final zzake zzdgp; private zzajx(zzake zzake) { this.zzdgp = zzake; } @JavascriptInterface public final void notify(String str) { this.zzdgp.zzdg(str); } }
21.444444
69
0.681347
fb3c4ffbc93ad0b47b5be5dbb68fbca835f95d9f
1,702
package com.ibcio; import java.io.IOException; import java.nio.CharBuffer; import java.util.HashMap; import java.util.Map; import java.util.Set; public class WebSocketMessageInboundPool { //保存连接的MAP容器 private static final Map<String,WebSocketMessageInbound > connections = new HashMap<String,WebSocketMessageInbound>(); //向连接池中添加连接 public static void addMessageInbound(WebSocketMessageInbound inbound){ //添加连接 System.out.println("user : " + inbound.getUser() + " join.."); connections.put(inbound.getUser(), inbound); } //获取所有的在线用户 public static Set<String> getOnlineUser(){ return connections.keySet(); } public static void removeMessageInbound(WebSocketMessageInbound inbound){ //移除连接 System.out.println("user : " + inbound.getUser() + " exit.."); connections.remove(inbound.getUser()); } public static void sendMessageToUser(String user,String message){ try { //向特定的用户发送数据 System.out.println("send message to user : " + user + " ,message content : " + message); WebSocketMessageInbound inbound = connections.get(user); if(inbound != null){ inbound.getWsOutbound().writeTextMessage(CharBuffer.wrap(message)); } } catch (IOException e) { e.printStackTrace(); } } //向所有的用户发送消息 public static void sendMessage(String message){ try { Set<String> keySet = connections.keySet(); for (String key : keySet) { WebSocketMessageInbound inbound = connections.get(key); if(inbound != null){ System.out.println("send message to user : " + key + " ,message content : " + message); inbound.getWsOutbound().writeTextMessage(CharBuffer.wrap(message)); } } } catch (IOException e) { e.printStackTrace(); } } }
27.901639
119
0.708578
dadd1e9a4f7a2d072e4fee84793e1ad533cc78b3
564
package cn.yuanye1818.func4a.test; import android.Manifest; import cn.yuanye1818.func4a.core.hero.Hero; import cn.yuanye1818.func4a.core.permission.PermissionFunc; public class PermissonChecker { public static final int CHECK_STORE_FILE = 0; public static final String CACHE_CHECK_STORE_FILE = "permission_check_store_file"; public static void checkStoreFile(Hero hero) { PermissionFunc.check(hero, CACHE_CHECK_STORE_FILE, CHECK_STORE_FILE, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}); } }
28.2
87
0.748227
eb28d8e279c102eb213538a0c2d5fb8c1961f7db
1,008
/* * Copyright 2015-2018 Micro Focus or one of its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hpe.caf.util.rabbitmq; /** * A general event trigger with a target. * * @param <T> the class or interface of the target the Event applies to */ @FunctionalInterface public interface Event<T> { /** * Trigger the action represented by this Event. * * @param target the class to perform an action on */ void handleEvent(final T target); }
30.545455
75
0.712302
17f996d3fae39abc2dd0fac77a61a229e79faff3
413
package edu.uniandes.tsdl.mutapk.selector; public class SelectorAmountMutants extends SelectorType{ private final int amountMutants; public SelectorAmountMutants(boolean isConfidenceInterval, boolean isAPK, int totalMutants, int amountMutants) { super(isConfidenceInterval, isAPK, totalMutants); this.amountMutants = amountMutants; } public int getAmountMutants() { return amountMutants; } }
22.944444
113
0.794189
c66f78f0d7ca56fb568013294bea8e091510f0fa
1,640
/* * Copyright 2007 skynamics AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openbp.guiclient.model.item.itemfinder; import java.util.ArrayList; import java.util.List; import org.openbp.core.model.Model; import org.openbp.core.model.ModelObject; import org.openbp.core.model.item.process.Node; import org.openbp.core.model.item.process.SubprocessNode; /** * Finder implementation for process items. * * @author Baumgartner Michael */ public class ProcessFinder extends NodeFinder { /** * @copy org.openbp.guiclient.model.item.itemfinder.NodeFinder.findModelObjectInNode */ protected List findModelObjectInNode(Node node, ModelObject item) { List list = new ArrayList(); if (node instanceof SubprocessNode) { addIfMatch(node, ((SubprocessNode) node).getSubprocess(), item, list); } return list; } /** * @copy org.openbp.guiclient.model.item.itemfinder.NodeFinder.scanModel */ protected List scanModel(Model model, ModelObject core) { List found = super.scanModel(model, core); return found; } }
29.818182
86
0.712805
241a0ef722a55bfe0892c96f474eff80f1e92c71
3,479
package com.example.musicplayerdome.main.other; import android.util.Log; import com.example.musicplayerdome.abstractclass.MvContract; import com.example.musicplayerdome.bean.BannerBean; import com.example.musicplayerdome.main.bean.MvSublistBean; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import yuncun.bean.YuncunReviewBean; public class MvPresenter extends MvContract.Presenter{ private static final String TAG = "MvPresenter"; public MvPresenter(MvContract.View view) { this.mView = view; this.mModel = new MvModel(); } @Override public void getRecommendMV() { mModel.getRecommendMV() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<MvSublistBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(MvSublistBean mvSublistBean) { mView.onGetRecommendMVSuccess(mvSublistBean); } @Override public void onError(Throwable e) { Log.e(TAG, "MVonError: "+e.getMessage()); } @Override public void onComplete() { } }); } @Override public void getYuncun() { mModel.getYuncun() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<YuncunReviewBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(YuncunReviewBean yuncunReviewBean) { mView.onGetYuncunSuccess(yuncunReviewBean); } @Override public void onError(Throwable e) { Log.e(TAG, "云村热评onError: "+e.getMessage()); mView.onGetYuncunFail(e.getMessage()); } @Override public void onComplete() { } }); } @Override public void getYuncunAgain() { mModel.getYuncun() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<YuncunReviewBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(YuncunReviewBean bean) { mView.onGetgetYuncunAgainSuccess(bean); } @Override public void onError(Throwable e) { mView.onGetYuncunAgainFail(e.getMessage()); } @Override public void onComplete() { } }); } }
32.212963
79
0.479736
8261068770b62907814406dfb7a8fcaed3216ccb
6,942
/* * #%L * SCIFIO fork of the Java Advanced Imaging Image I/O Tools API Core. * %% * Copyright (C) 2008 - 2016 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ /* * $RCSfile: CBlkInfo.java,v $ * $Revision: 1.1 $ * $Date: 2005/02/11 05:02:01 $ * $State: Exp $ * * Class: CBlkInfo * * Description: Object containing code-block informations. * * * * COPYRIGHT: * * This software module was originally developed by Rapha�l Grosbois and * Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel * Askel�f (Ericsson Radio Systems AB); and Bertrand Berthelot, David * Bouchard, F�lix Henry, Gerard Mozelle and Patrice Onno (Canon Research * Centre France S.A) in the course of development of the JPEG2000 * standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This * software module is an implementation of a part of the JPEG 2000 * Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio * Systems AB and Canon Research Centre France S.A (collectively JJ2000 * Partners) agree not to assert against ISO/IEC and users of the JPEG * 2000 Standard (Users) any of their rights under the copyright, not * including other intellectual property rights, for this software module * with respect to the usage by ISO/IEC and Users of this software module * or modifications thereof for use in hardware or software products * claiming conformance to the JPEG 2000 Standard. Those intending to use * this software module in hardware or software products are advised that * their use may infringe existing patents. The original developers of * this software module, JJ2000 Partners and ISO/IEC assume no liability * for use of this software module or modifications thereof. No license * or right to this software module is granted for non JPEG 2000 Standard * conforming products. JJ2000 Partners have full right to use this * software module for his/her own purpose, assign or donate this * software module to any third party and to inhibit third parties from * using this software module for non JPEG 2000 Standard conforming * products. This copyright notice must be included in all copies or * derivative works of this software module. * * Copyright (c) 1999/2000 JJ2000 Partners. * * * */ package io.scif.jj2000.j2k.codestream.reader; import java.util.*; /** * This class contains location of code-blocks' piece of codewords * (there is one piece per layer) and some other information. * * */ public class CBlkInfo{ /** Upper-left x-coordinate of the code-block (relative to the tile) */ public int ulx; /** Upper-left y-coordinate of the code-block (relative to the tile) */ public int uly; /** Width of the code-block */ public int w; /** Height of the code-block */ public int h; /** The number of most significant bits which are skipped for this * code-block (= Mb-1-bitDepth). See VM text */ public int msbSkipped; /** Length of each piece of code-block's codewords */ public int[] len; /** Offset of each piece of code-block's codewords in the file */ public int[] off; /** The number of truncation point for each layer */ public int[] ntp; /** The cumulative number of truncation points */ public int ctp; /** The length of each segment (used with regular termination or * in selective arithmetic bypass coding mode) */ public int[][] segLen; /** Index of the packet where each layer has been found */ public int[] pktIdx; /** * Constructs a new instance with specified number of layers and * code-block coordinates. The number corresponds to the maximum * piece of codeword for one code-block. * * @param ulx The uper-left x-coordinate * * @param uly The uper-left y-coordinate * * @param w Width of the code-block * * @param h Height of the code-block * * @param nl The number of layers * */ public CBlkInfo(int ulx,int uly,int w,int h,int nl){ this.ulx = ulx; this.uly = uly; this.w = w; this.h = h; off = new int[nl]; len = new int[nl]; ntp = new int[nl]; segLen = new int[nl][]; pktIdx = new int[nl]; for(int i=nl-1;i>=0;i--) pktIdx[i] = -1; } /** * Adds the number of new truncation for specified layer. * * @param l layer index * * @param newtp Number of new truncation points * */ public void addNTP(int l,int newtp){ ntp[l] = newtp; ctp = 0; for(int lIdx=0; lIdx<=l; lIdx++){ ctp += ntp[lIdx]; } } /** * Object information in a string. * * @return Object information * */ public String toString(){ String string = "(ulx,uly,w,h)= "+ulx+","+uly+","+w+","+h; string += ", "+msbSkipped+" MSB bit(s) skipped\n"; if( len!=null ) for(int i=0; i<len.length; i++){ string += "\tl:"+i+", start:"+off[i]+ ", len:"+len[i]+", ntp:"+ntp[i]+", pktIdx="+ pktIdx[i]; if(segLen!=null && segLen[i]!=null){ string += " { "; for(int j=0; j<segLen[i].length; j++) string += segLen[i][j]+" "; string += "}"; } string += "\n"; } string += "\tctp="+ctp; return string; } }
34.71
79
0.648228
1895add96fadcbe167cf96ed6ff7160bf6048dc5
587
package com.google.android.gms.internal.ads; public final class zzbjs implements zzdti<zzcjz<zzams, zzcla>> { /* renamed from: a */ private final zzbjn f25424a; /* renamed from: b */ private final zzdtu<zzclc> f25425b; public zzbjs(zzbjn zzbjn, zzdtu<zzclc> zzdtu) { this.f25424a = zzbjn; this.f25425b = zzdtu; } public final /* synthetic */ Object get() { zzclv zzclv = new zzclv((zzclc) this.f25425b.get()); zzdto.m30114a(zzclv, "Cannot return null from a non-@Nullable @Provides method"); return zzclv; } }
26.681818
89
0.635434
0ca196d1f36d2867afd39fa18273190272ad8993
4,692
/* * 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 model.character.skill; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javax.xml.bind.annotation.*; /** * * @author Dr.Chase */ @XmlAccessorType (XmlAccessType.FIELD) @XmlRootElement(name = "skill") //@XmlAccessorType (XmlAccessType.FIELD) /** * This class represents active skills. * Each skill is tied to an attribute. When a character's skill level reaches * the level of the attribute, improving that skill will cost more. * At character generation the user can buy a skill with skill points * but when the character finsihed generation, skills can be bought with * good charma points. * Active skills are used for example when the character shoots with a firearm. * Shooting a pistol uses the pistol skill. Shooting an assault rifle uses the * assault rifle skill and so on. * Characters can specialize their active skills. For example if one character * wants to specialize to "Ares Predator" pistol, he can do that. His * specialization level will be added to the level of the skill when he or she * is using the Ares Predator pistol, but the specialization level will be * subtracted from the level of the skill, when he is using any other type * of pistol. * Example: character has level 4 pistol skill, and level 1 specialization to * Ares Predator. When he is using the Ares Predator, his pistol skill will be * level 5, but when he is using a Glock his pistol skill will be 3. * At character generation, only one specialization is allowed. * When a character "level ups" by spending good charma, he or she can * get another specialization. In game specializations don't have skill penalty * so the specialization's level will not be subtracted from the skill level. * Other constraints: * Specialization level can't exceed the level of the base skill. * For example: * With level 3 pistol skill, Ares Predator specialization can't be more than * level 3. * The character can't have more specialization than the level of the attribute * tied to the actual skill. * For example: * Character has agility level 4, then he can havea maximum of * 4 specializations for pistol skill. */ public class Skill { private String nameOfSkill; SkillAttrEnum attrOfSkill; ActiveSkillCategoryEnum skillCategoryEnum; private int levelOfSkill; private String description; private boolean isSpecialized; private String specialization; public String getNameOfSkill() { return nameOfSkill; } public void setNameOfSkill(String nameOfSkill) { this.nameOfSkill = nameOfSkill; } public SkillAttrEnum getAttrOfSkill() { return attrOfSkill; } public void setAttrOfSkill(SkillAttrEnum attrOfSkill) { this.attrOfSkill = attrOfSkill; } public int getLevelOfSkill() { return levelOfSkill; } public void setLevelOfSkill(int levelOfSkill) { this.levelOfSkill = levelOfSkill; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isIsSpecialized() { return isSpecialized; } public void setIsSpecialized(boolean isSpecialized) { this.isSpecialized = isSpecialized; } public String getSpecialization() { return specialization; } public void setSpecialization(String specialization) { this.specialization = specialization; } // public SimpleStringProperty getNameOfSkillProperty() { // return new SimpleStringProperty(nameOfSkill); // } // // public void setNameOfSkill(SimpleStringProperty nameOfSkill) { // this.nameOfSkill = nameOfSkill.getValue(); // } // // // // // public SimpleIntegerProperty getLevelOfSkillProperty() { // return new SimpleIntegerProperty(levelOfSkill); // } // // public void setLevelOfSkill(SimpleIntegerProperty levelOfSkill) { // this.levelOfSkill = levelOfSkill.getValue(); // } // // public SimpleStringProperty getDescriptionProperty() { // return new SimpleStringProperty(description); // } // // public void setDescription(SimpleStringProperty description) { // this.description = description.getValue(); // } }
33.514286
80
0.696718
5dc037184fdafc7066629442dc0ce76f732b1eab
303
package com.robinjonsson.dwquartz.triggers; import com.robinjonsson.dwquartz.AbstractJob; import java.util.Set; import org.quartz.Trigger; public interface CustomTriggerBuilder { boolean canBuildTrigger(final AbstractJob job); Set<? extends Trigger> buildTriggers(final AbstractJob job); }
21.642857
64
0.79868
69e099b146f6916671847ea6942f5b62241d6bd3
2,885
package com.wix.restaurants.availability; import java.util.Calendar; import java.util.Iterator; class TimeWindowsIterator implements Iterator<Status> { private final WeeklyTimeWindowsIterator regularIt; private final DateTimeWindowsIterator exceptionsIt; private Status regularStatus; private Status exceptionStatus; private boolean hasNext = true; public TimeWindowsIterator(Calendar cal, Availability availability) { this.regularIt = new WeeklyTimeWindowsIterator(cal, availability.weekly); this.exceptionsIt = new DateTimeWindowsIterator(cal, availability.exceptions); // TimeWindow iterators always return at least one element regularStatus = regularIt.next(); exceptionStatus = exceptionsIt.next(); } @Override public boolean hasNext() { return hasNext; } @Override public Status next() { // Future has no exceptions? if ((Status.STATUS_UNKNOWN.equals(exceptionStatus.status)) && (exceptionStatus.until == null)) { // Continue with regular statuses final Status lastRegularStatus = regularStatus; if (regularIt.hasNext()) { regularStatus = regularIt.next(); } else { hasNext = false; } return lastRegularStatus; } // So we do have real exceptions to deal with // Real exceptions take precedent if (!Status.STATUS_UNKNOWN.equals(exceptionStatus.status)) { // If the exception is indefinite, it trumps everything else if (exceptionStatus.until == null) { hasNext = false; return exceptionStatus; } final Status lastExceptionStatus = exceptionStatus; exceptionStatus = exceptionsIt.next(); // we know there are still real exceptions later while ((regularStatus.until != null) && (!regularStatus.until().after(lastExceptionStatus.until()))) { regularStatus = regularIt.next(); } return lastExceptionStatus; } // No real exception this time if ((regularStatus.until == null) || (regularStatus.until().after(exceptionStatus.until()))) { final Status lastExceptionStatus = exceptionStatus; exceptionStatus = exceptionsIt.next(); // we know there are still real exceptions later return new Status(regularStatus.status, lastExceptionStatus.until()); } else if (regularStatus.until().before(exceptionStatus.until())) { final Status lastRegularStatus = regularStatus; regularStatus = regularIt.next(); // we know there are still regular statuses later return lastRegularStatus; } else { exceptionStatus = exceptionsIt.next(); // we know there are still real exceptions later final Status lastRegularStatus = regularStatus; regularStatus = regularIt.next(); // we know there are still regular statuses later return lastRegularStatus; } } @Override public void remove() { throw new UnsupportedOperationException("Remove unsupported"); } }
33.546512
99
0.721317
247914dcbaeca6187bc92d26e42b96ca427d6eca
690
package com.bdccryptotrader; import android.os.Bundle; // required for onCreate parameter import org.devio.rn.splashscreen.SplashScreen; // required for react-native-splash-screen >= 0.3.1 import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { @Override protected void onCreate(Bundle savedInstanceState) { SplashScreen.show(this, R.style.SplashStatusBarTheme); super.onCreate(savedInstanceState); } /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ @Override protected String getMainComponentName() { return "BdcCryptoTrader"; } }
28.75
98
0.756522
4329bde3334f67a8817ac617750a79c3b1afd434
2,278
//package com.springboot.aop.aspect; // // //import org.aspectj.lang.JoinPoint; //import org.aspectj.lang.ProceedingJoinPoint; //import org.aspectj.lang.annotation.After; //import org.aspectj.lang.annotation.AfterReturning; //import org.aspectj.lang.annotation.AfterThrowing; //import org.aspectj.lang.annotation.Around; //import org.aspectj.lang.annotation.Aspect; //import org.aspectj.lang.annotation.Before; //import org.aspectj.lang.annotation.Pointcut; //import org.springframework.stereotype.Component; // ///** // * Annotation版Aspect切面Bean // * @author Tom // */ ////声明这是一个组件 //@Component ////声明这是一个切面Bean,AnnotaionAspect是一个面,由框架实现的 //@Aspect //public class AnnotaionAspect { // //// private final static Logger log = Logger.getLogger(AnnotaionAspect.class); // // //配置切入点,该方法无方法体,主要为方便同类中其他方法使用此处配置的切入点 // //切点的集合,这个表达式所描述的是一个虚拟面(规则) // //就是为了Annotation扫描时能够拿到注解中的内容 // @Pointcut("execution(* com.springboot.aop..*(..))") // public void aspect(){} // // /* // * 配置前置通知,使用在方法aspect()上注册的切入点 // * 同时接受JoinPoint切入点对象,可以没有该参数 // */ // @Before("aspect()") // public void before(JoinPoint joinPoint){ // System.out.println("before " + joinPoint); // } // // //配置后置通知,使用在方法aspect()上注册的切入点 // @After("aspect()") // public void after(JoinPoint joinPoint){ // System.out.println("after " + joinPoint); // } // // //配置环绕通知,使用在方法aspect()上注册的切入点 // @Around("aspect()") // public void around(JoinPoint joinPoint){ // long start = System.currentTimeMillis(); // try { // ((ProceedingJoinPoint) joinPoint).proceed(); // long end = System.currentTimeMillis(); // System.out.println("around " + joinPoint + "\tUse time : " + (end - start) + " ms!"); // } catch (Throwable e) { // long end = System.currentTimeMillis(); // System.out.println("around " + joinPoint + "\tUse time : " + (end - start) + " ms with exception : " + e.getMessage()); // } // } // // //配置后置返回通知,使用在方法aspect()上注册的切入点 // @AfterReturning("aspect()") // public void afterReturn(JoinPoint joinPoint){ // System.out.println("afterReturn " + joinPoint); // } // // //配置抛出异常后通知,使用在方法aspect()上注册的切入点 // @AfterThrowing(pointcut="aspect()", throwing="ex") // public void afterThrow(JoinPoint joinPoint, Exception ex){ // System.out.println("afterThrow " + joinPoint + "\t" + ex.getMessage()); // } // //}
30.783784
124
0.686128
6bf0a4344ec92536df4d63aca4788509328d579b
1,958
/** * */ package cn.ancono.math.geometry.analytic.space; import cn.ancono.math.numberModels.Calculators; import cn.ancono.math.numberModels.api.RealCalculator; /** * A tool for spaceAG. * @author liyicheng * */ public final class SpaceAgUtils { /** * Returns the angle of {@code ��AOB} * @param A * @param O * @param B * @return */ public static <T> T angleCos(SPoint<T> A, SPoint<T> O, SPoint<T> B) { return SVector.vector(O, A).angleCos(SVector.vector(O, B)); } /** * Returns the angle between two planes: <i>ABC</i> and <i>BCD</i>, or * say {@code ��A-BC-D}. * @param A a point * @param B a point * @param C a point * @param D a point * @return */ public static <T> T angleCos(SPoint<T> A, SPoint<T> B, SPoint<T> C, SPoint<T> D) { return null; } /** * Compares the two parallel vector(if they are not parallel, then the result is {@code -1}). Considering {@code v1} is * the direct toward which is positive, compares the two vector of their length. Returns {@code -1} if {@code v1<v2}, * {@code 0} if {@code v1==v2}, and {@code 1} if {@code v1>v2}. If the two vectors are of different direction, then * {@code -1} will always be returned. * @param v1 * @param v2 * @return */ public static <T> int compareVector(SVector<T> v1, SVector<T> v2) { RealCalculator<T> mc = (RealCalculator<T>) v1.getCalculator(); T t1 = v1.x, t2 = v2.x; if (mc.isZero(t1)) { if (mc.isZero(v2.y)) { t1 = v1.z; t2 = v2.z; } else { t1 = v1.y; t2 = v2.y; } } if (!Calculators.isSameSign(t1, t2, mc)) { return -1; } int comp = mc.compare(t1, t2); int signum = Calculators.signum(t1, mc); return signum > 0 ? comp : -comp; } }
28.794118
123
0.538304
994004adacad3d68cec25eabfcd34dfb350ae0db
11,217
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.starlark; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.runtime.StarlarkOptionsParser; import com.google.devtools.build.lib.starlark.util.StarlarkOptionsTestCase; import com.google.devtools.build.lib.util.Pair; import com.google.devtools.common.options.OptionsParsingException; import com.google.devtools.common.options.OptionsParsingResult; import net.starlark.java.eval.StarlarkInt; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit test for the {@code StarlarkOptionsParser}. */ @RunWith(JUnit4.class) public class StarlarkOptionsParsingTest extends StarlarkOptionsTestCase { // test --flag=value @Test public void testFlagEqualsValueForm() throws Exception { writeBasicIntFlag(); OptionsParsingResult result = parseStarlarkOptions("--//test:my_int_setting=666"); assertThat(result.getStarlarkOptions()).hasSize(1); assertThat(result.getStarlarkOptions().get("//test:my_int_setting")) .isEqualTo(StarlarkInt.of(666)); assertThat(result.getResidue()).isEmpty(); } // test --@workspace//flag=value @Test public void testFlagNameWithWorkspace() throws Exception { writeBasicIntFlag(); rewriteWorkspace("workspace(name = 'starlark_options_test')"); OptionsParsingResult result = parseStarlarkOptions("--@starlark_options_test//test:my_int_setting=666"); assertThat(result.getStarlarkOptions()).hasSize(1); assertThat(result.getStarlarkOptions().get("@starlark_options_test//test:my_int_setting")) .isEqualTo(StarlarkInt.of(666)); assertThat(result.getResidue()).isEmpty(); } // test --fake_flag=value @Test public void testBadFlag_equalsForm() throws Exception { scratch.file("test/BUILD"); reporter.removeHandler(failFastHandler); OptionsParsingException e = assertThrows( OptionsParsingException.class, () -> parseStarlarkOptions("--//fake_flag=blahblahblah")); assertThat(e).hasMessageThat().contains("Error loading option //fake_flag"); assertThat(e.getInvalidArgument()).isEqualTo("//fake_flag"); } // test --fake_flag @Test public void testBadFlag_boolForm() throws Exception { scratch.file("test/BUILD"); reporter.removeHandler(failFastHandler); OptionsParsingException e = assertThrows(OptionsParsingException.class, () -> parseStarlarkOptions("--//fake_flag")); assertThat(e).hasMessageThat().contains("Error loading option //fake_flag"); assertThat(e.getInvalidArgument()).isEqualTo("//fake_flag"); } @Test public void testSingleDash_notAllowed() throws Exception { writeBasicIntFlag(); OptionsParsingResult result = parseStarlarkOptions("-//test:my_int_setting=666"); assertThat(result.getStarlarkOptions()).isEmpty(); assertThat(result.getResidue()).containsExactly("-//test:my_int_setting=666"); } // test --non_flag_setting=value @Test public void testNonFlagParsing() throws Exception { scratch.file( "test/build_setting.bzl", "def _build_setting_impl(ctx):", " return []", "int_flag = rule(", " implementation = _build_setting_impl,", " build_setting = config.int(flag=False)", ")"); scratch.file( "test/BUILD", "load('//test:build_setting.bzl', 'int_flag')", "int_flag(name = 'my_int_setting', build_setting_default = 42)"); OptionsParsingException e = assertThrows( OptionsParsingException.class, () -> parseStarlarkOptions("--//test:my_int_setting=666")); assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: //test:my_int_setting=666"); } // test --bool_flag @Test public void testBooleanFlag() throws Exception { writeBasicBoolFlag(); OptionsParsingResult result = parseStarlarkOptions("--//test:my_bool_setting=false"); assertThat(result.getStarlarkOptions()).hasSize(1); assertThat(result.getStarlarkOptions().get("//test:my_bool_setting")).isEqualTo(false); assertThat(result.getResidue()).isEmpty(); } // test --nobool_flag @Test public void testNoPrefixedBooleanFlag() throws Exception { writeBasicBoolFlag(); OptionsParsingResult result = parseStarlarkOptions("--no//test:my_bool_setting"); assertThat(result.getStarlarkOptions()).hasSize(1); assertThat(result.getStarlarkOptions().get("//test:my_bool_setting")).isEqualTo(false); assertThat(result.getResidue()).isEmpty(); } // test --noint_flag @Test public void testNoPrefixedNonBooleanFlag() throws Exception { writeBasicIntFlag(); OptionsParsingException e = assertThrows( OptionsParsingException.class, () -> parseStarlarkOptions("--no//test:my_int_setting")); assertThat(e) .hasMessageThat() .isEqualTo("Illegal use of 'no' prefix on non-boolean option: //test:my_int_setting"); } // test --int_flag @Test public void testFlagWithoutValue() throws Exception { writeBasicIntFlag(); OptionsParsingException e = assertThrows( OptionsParsingException.class, () -> parseStarlarkOptions("--//test:my_int_setting")); assertThat(e).hasMessageThat().isEqualTo("Expected value after --//test:my_int_setting"); } // test --flag --flag @Test public void testRepeatFlagLastOneWins() throws Exception { writeBasicIntFlag(); OptionsParsingResult result = parseStarlarkOptions("--//test:my_int_setting=4 --//test:my_int_setting=7"); assertThat(result.getStarlarkOptions()).hasSize(1); assertThat(result.getStarlarkOptions().get("//test:my_int_setting")) .isEqualTo(StarlarkInt.of(7)); assertThat(result.getResidue()).isEmpty(); } // test --flagA=valueA --flagB=valueB @Test public void testMultipleFlags() throws Exception { scratch.file( "test/build_setting.bzl", "def _build_setting_impl(ctx):", " return []", "int_flag = rule(", " implementation = _build_setting_impl,", " build_setting = config.int(flag=True)", ")"); scratch.file( "test/BUILD", "load('//test:build_setting.bzl', 'int_flag')", "int_flag(name = 'my_int_setting', build_setting_default = 42)", "int_flag(name = 'my_other_int_setting', build_setting_default = 77)"); OptionsParsingResult result = parseStarlarkOptions("--//test:my_int_setting=0 --//test:my_other_int_setting=0"); assertThat(result.getResidue()).isEmpty(); assertThat(result.getStarlarkOptions()).hasSize(2); assertThat(result.getStarlarkOptions().get("//test:my_int_setting")) .isEqualTo(StarlarkInt.of(0)); assertThat(result.getStarlarkOptions().get("//test:my_other_int_setting")) .isEqualTo(StarlarkInt.of(0)); } // test --non_build_setting @Test public void testNonBuildSetting() throws Exception { scratch.file( "test/rules.bzl", "def _impl(ctx):", " return []", "my_rule = rule(", " implementation = _impl,", ")"); scratch.file("test/BUILD", "load('//test:rules.bzl', 'my_rule')", "my_rule(name = 'my_rule')"); OptionsParsingException e = assertThrows(OptionsParsingException.class, () -> parseStarlarkOptions("--//test:my_rule")); assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: //test:my_rule"); } // test --non_rule_configured_target @Test public void testNonRuleConfiguredTarget() throws Exception { scratch.file( "test/BUILD", "genrule(", " name = 'my_gen',", " srcs = ['x.in'],", " outs = ['x.cc'],", " cmd = '$(locations :tool) $< >$@',", " tools = [':tool'],", ")", "cc_library(name = 'tool-dep')"); OptionsParsingException e = assertThrows(OptionsParsingException.class, () -> parseStarlarkOptions("--//test:x.in")); assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: //test:x.in"); } // test --int_flag=non_int_value @Test public void testWrongValueType_int() throws Exception { writeBasicIntFlag(); OptionsParsingException e = assertThrows( OptionsParsingException.class, () -> parseStarlarkOptions("--//test:my_int_setting=woohoo")); assertThat(e) .hasMessageThat() .isEqualTo("While parsing option //test:my_int_setting=woohoo: 'woohoo' is not a int"); } // test --bool_flag=non_bool_value @Test public void testWrongValueType_bool() throws Exception { writeBasicBoolFlag(); OptionsParsingException e = assertThrows( OptionsParsingException.class, () -> parseStarlarkOptions("--//test:my_bool_setting=woohoo")); assertThat(e) .hasMessageThat() .isEqualTo("While parsing option //test:my_bool_setting=woohoo: 'woohoo' is not a boolean"); } // test --int-flag=same value as default @Test public void testDontStoreDefaultValue() throws Exception { // build_setting_default = 42 writeBasicIntFlag(); OptionsParsingResult result = parseStarlarkOptions("--//test:my_int_setting=42"); assertThat(result.getStarlarkOptions()).isEmpty(); } @Test public void testOptionsAreParsedWithBuildTestsOnly() throws Exception { writeBasicIntFlag(); optionsParser.parse("--build_tests_only"); OptionsParsingResult result = parseStarlarkOptions("--//test:my_int_setting=15"); assertThat(result.getStarlarkOptions().get("//test:my_int_setting")) .isEqualTo(StarlarkInt.of(15)); } @Test public void testRemoveStarlarkOptionsWorks() throws Exception { Pair<ImmutableList<String>, ImmutableList<String>> residueAndStarlarkOptions = StarlarkOptionsParser.removeStarlarkOptions( ImmutableList.of( "--//local/starlark/option", "--@some_repo//external/starlark/option", "--@//main/repo/option", "some-random-residue", "--mangled//external/starlark/option")); assertThat(residueAndStarlarkOptions.getFirst()) .containsExactly( "--//local/starlark/option", "--@some_repo//external/starlark/option", "--@//main/repo/option"); assertThat(residueAndStarlarkOptions.getSecond()) .containsExactly("some-random-residue", "--mangled//external/starlark/option"); } }
34.835404
100
0.683338
1b5e3160ddf3159d34c369da8ef7f0b94e660316
12,533
package com.yyl.service; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.transform.Transformers; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; //import sun.net.www.content.text.plain; import com.yyl.common.UtiltyHelper; import com.yyl.modal.PagerInfo; import com.yyl.thirdpart.SMSHelper; @Service public class UsersService extends BaseService{ @Transactional public List LoadUsersList() { Session db = getCurrentSession(); String sql = "select * from UserInfos"; Query q = db.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); q.setMaxResults(10); q.setFirstResult(0); return q.list(); } @Transactional public void ForgetPassword(String phoneNumber) { Session db = getCurrentSession(); String rand = UtiltyHelper.CreateRandomNumber(); String sql = "update UserInfos set UserPass='"+rand+"' where PhoneNumber='"+phoneNumber+"'"; db.createSQLQuery(sql).executeUpdate(); sql = "insert into SMSPost(Body,PhoneNumber,CreateTime, PostState, SMSType)"+ " values(:BODY,:PN,:TIME,:PS,:TYPE)"; SQLQuery q = db.createSQLQuery(sql); q.setParameter("BODY", rand); q.setParameter("TIME", UtiltyHelper.GetNowDate()); q.setParameter("PN", phoneNumber); q.setParameter("PS", 0); q.setParameter("TYPE", 2); q.executeUpdate(); SMSHelper.SendSMS_Pass(phoneNumber, rand); } @Transactional public void CreateVerifyNumber(String phoneNumber,String code) { Session db = getCurrentSession(); String sql = "insert into VerifyCode(Code,CreateTime,PhoneNumber,State)"+ " values(:CODE,:TIME,:PN,:STATE)"; SQLQuery q = db.createSQLQuery(sql); q.setParameter("CODE", code); q.setParameter("TIME", UtiltyHelper.GetNowDate()); q.setParameter("PN", phoneNumber); q.setParameter("STATE", 1); q.executeUpdate(); sql = "insert into SMSPost(Body,PhoneNumber,CreateTime, PostState, SMSType)"+ " values(:BODY,:PN,:TIME,:PS,:TYPE)"; q = db.createSQLQuery(sql); q.setParameter("BODY", code); q.setParameter("TIME", UtiltyHelper.GetNowDate()); q.setParameter("PN", phoneNumber); q.setParameter("PS", 0); q.setParameter("TYPE", 1); q.executeUpdate(); SMSHelper.SendSMS_Reg(phoneNumber, code); } @Transactional public boolean VerifyCode(String phoneNumber,String code) { Session db = getCurrentSession(); String sql = "select * from VerifyCode where PhoneNumber='"+phoneNumber+"' and Code='"+code+"' and State=1"; Object result = db.createSQLQuery(sql).uniqueResult(); if(result == null) return false; return true; } @Transactional public boolean RegistUser( String phoneNumber, String userPass, String nickName, String gender, String brithday, String signText, int salaryID, int areaID, int jobID, String userPic, String hxUser, String hxPass) { Session db = getCurrentSession(); String sql = "select * from UserInfos where PhoneNumber='"+phoneNumber+"'"; Object result = db.createSQLQuery(sql).uniqueResult(); if(result != null) return false; sql = "insert into UserInfos(PhoneNumber,UserPass, hxUser, hxPass,NickName, Gender, Brithday,signtext, SalaryID,AreaID, JobID,MyCoin, UserPic,CreateTime,Age)"+ " values(:PN,:UP,:hxUser,:hxPass,:NICK,:G,:B,:SIGN,:SALARY,:AREA,:JOB,:COIN,:UPIC,:TIME,:AGE)"; SQLQuery q = db.createSQLQuery(sql); q.setParameter("PN", phoneNumber); q.setParameter("UP", userPass); q.setParameter("hxUser", hxUser); q.setParameter("hxPass", hxPass); q.setParameter("NICK", nickName); q.setParameter("G", gender); q.setParameter("B", brithday); q.setParameter("SIGN", signText); q.setParameter("SALARY", salaryID); q.setParameter("AREA", areaID); q.setParameter("JOB", jobID); q.setParameter("COIN", 0); q.setParameter("UPIC", userPic); q.setParameter("TIME", UtiltyHelper.GetNowDate()); q.setParameter("AGE", UtiltyHelper.getAgeByBirthday(brithday)); q.executeUpdate(); return true; } @Transactional public void UpdateUserInfo(int uid, String userPass, String nickName, String gender, String brithday, String signText, String salaryId, String areaId, String jobId, String userPic, String email, String hobbies) { Session db = getCurrentSession(); String sql = "update UserInfos set"; if(userPass != null && !userPass.isEmpty()) { sql += " UserPass='"+userPass+"',"; } if(nickName != null && !nickName.isEmpty()) { sql += " NickName='"+nickName+"',"; } if(gender != null && !gender.isEmpty()) { sql += " Gender='"+gender+"',"; } if(brithday != null && !brithday.isEmpty()) { sql += " Brithday='"+brithday+"',"; int age = UtiltyHelper.getAgeByBirthday(brithday); sql += " Age="+age+","; } if(signText != null && !signText.isEmpty()) { sql += " signtext='"+signText+"',"; } if(userPic != null && !userPic.isEmpty()) { sql += " UserPic='"+userPic+"',"; } if(email != null && !email.isEmpty()) { sql += " EMail='"+email+"',"; } if(hobbies != null && !hobbies.isEmpty()) { sql += " Hobbies='"+hobbies+"',"; } if(areaId != null && !areaId.isEmpty()) { sql += " AreaID='"+areaId+"',"; } if(jobId != null && !jobId.isEmpty()) { sql += " JobID='"+jobId+"',"; } if(salaryId != null && !salaryId.isEmpty()) { sql += " SalaryID='"+salaryId+"',"; } if(sql.endsWith(",")) sql = sql.substring(0,sql.length()-1); sql += " where UID="+uid; db.createSQLQuery(sql).executeUpdate(); } @Transactional public boolean RegistUser2( String phoneNumber, String userPass, String hxUser, String hxPass) { Session db = getCurrentSession(); String sql = "select * from UserInfos where PhoneNumber='"+phoneNumber+"'"; Object result = db.createSQLQuery(sql).uniqueResult(); if(result != null) return false; sql = "insert into UserInfos(PhoneNumber,UserPass, hxUser, hxPass,CreateTime,MyCoin,CreditPoint,UserLevel,Gender,UserPic,BuddyRequest,NickName)"+ " values(:PN,:UP,:hxUser,:hxPass,:TIME,0,100,1,1,'default.jpg',1,'')"; SQLQuery q = db.createSQLQuery(sql); q.setParameter("PN", phoneNumber); q.setParameter("UP", userPass); q.setParameter("hxUser", hxUser); q.setParameter("hxPass", hxPass); q.setParameter("TIME", UtiltyHelper.GetNowDate()); q.executeUpdate(); return true; } @Transactional public Map UserLogon(String phoneNumber,String password) { Session db = getCurrentSession(); String sql = "select * from UserInfos where PhoneNumber='"+phoneNumber+"'"; Object result = db.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).uniqueResult(); if(result == null) return null; Map userInfo = (Map)result; String UserPass = userInfo.get("UserPass").toString(); if(!UserPass.equals(password)) { return null; } return userInfo; } @Transactional public void UpdateUserIcon(int uid,String picFile) { Session db = getCurrentSession(); String sql = "update UserInfos set UserPic='"+picFile+"' where UID="+uid; db.createSQLQuery(sql).executeUpdate(); } @Transactional public Object GetUserInfoByUID(int uid) { Session db = getCurrentSession(); String sql = "select UID,hxUser,NickName,Gender,Brithday,signtext,UserPic,Age,CreditPoint,UserLevel,AreaName,AreaID,SalaryName,JobName,JobID,Email,Hobbies,BuddyRequest,x1.myEventCnt,x2.myJoinCnt from userInfo_view,(select count(*) myEventCnt from Events_view where UID="+uid+") x1,(select count(*) myJoinCnt from Events_view a,EventJoin b where a.EID=b.EID and b.UID="+uid+") x2 where UID="+uid; Query q = db.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); return q.uniqueResult(); } @Transactional public int IsPendingBuddy(int uid,int buddyId) { Session db = getCurrentSession(); String sql = "select * from UserBuddys where UID="+uid+" and BuddyID="+buddyId; int cnt = db.createSQLQuery(sql).list().size(); if(cnt>0) return 2; sql = "select * from BuddyRequest where Status=0 and FromUID="+uid+" and ToUID="+buddyId; cnt = db.createSQLQuery(sql).list().size(); if(cnt>0) return 1; return 0; } @Transactional public Object GetUserInfoByHXID(String username) { Session db = getCurrentSession(); String sql = "select UID from UserInfos where hxUser='"+username+"'"; Map userInfo = (Map)db.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).uniqueResult(); int uid = Integer.parseInt(userInfo.get("UID").toString()); return GetUserInfoByUID(uid); } @Transactional public List SearchUsers( String phoneNumber, String nickName, String Gender, String Area, String JobName, String age, int page) { Session db = getCurrentSession(); String sql = "select UID,hxUser,NickName,Gender,Brithday,signtext,UserPic,Age,CreditPoint,UserLevel,AreaName,SalaryName,JobName from userInfo_view where 1=1"; if(phoneNumber!=null && !phoneNumber.isEmpty()) { sql += " and PhoneNumber='"+phoneNumber+"'"; } if(nickName!=null && !nickName.isEmpty()) { sql += " and NickName like '%"+nickName+"%'"; } if(Gender!=null && !Gender.isEmpty()) { sql += " and Gender="+Gender; } if(JobName!=null && !JobName.isEmpty()) { sql += " and JobID="+JobName; } if(Area!=null && !Area.isEmpty()) { sql += " and AreaID="+Area; } if(age!=null && !age.isEmpty()) { sql += " and Age<"+age; } Query q = db.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); q.setMaxResults(PageSize); q.setFirstResult((page-1)*PageSize); return q.list(); } @Transactional public PagerInfo SearchUsers2( String phoneNumber, String nickName, String Gender, String Area, String JobName, String Salary, int page) { Session db = getCurrentSession(); String sql = "select count(*) from userInfo_view where 1=1"; String where = ""; if(phoneNumber!=null && !phoneNumber.isEmpty()) { where += " and PhoneNumber like '%"+phoneNumber+"%'"; } if(nickName!=null && !nickName.isEmpty()) { where += " and NickName like '%"+nickName+"%'"; } if(Gender!=null && !Gender.isEmpty() && !Gender.equals("0")) { where += " and Gender="+Gender; } if(JobName!=null && !JobName.isEmpty() && !JobName.equals("0")) { where += " and JobID="+JobName; } if(Area!=null && !Area.isEmpty() && !Area.equals("0")) { where += " and AreaID="+Area; } if(Salary!=null && !Salary.isEmpty() && !Salary.equals("0")) { where += " and SalaryID="+Salary; } int total = Integer.parseInt(db.createSQLQuery(sql+where).uniqueResult().toString()); PagerInfo pi = new PagerInfo(); pi.CaclePager(total, PageSize, page); sql = "select * from userInfo_view where 1=1"; Query q = db.createSQLQuery(sql+where).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); q.setMaxResults(PageSize); q.setFirstResult((pi.getCurrentPage()-1)*PageSize); pi.setDataList(q.list()); return pi; } @Transactional public void UpdateLocatedUser(int uid,String latitude,String longitude) { Session db = getCurrentSession(); String sql = "delete from UserLocation where UID="+uid; db.createSQLQuery(sql).executeUpdate(); sql = "insert into UserLocation(latitude,longitude,UID,CreateTime) "+ "values(:LA,:LO,:UID,:TIME)"; SQLQuery q = db.createSQLQuery(sql); q.setParameter("LA", latitude); q.setParameter("LO", longitude); q.setParameter("UID", uid); q.setParameter("TIME", UtiltyHelper.GetNowDate()); q.executeUpdate(); } @Transactional public List UserListNearBy(int page,String latitude,String longitude) { Session db = getCurrentSession(); String sql = "select a.UID,a.NickName,a.hxUser,a.UserPic,a.Gender,a.CreditPoint,a.UserLevel,a.Brithday,a.signtext,round(6378.138*2*asin(sqrt(pow(sin( ("+latitude+"*pi()/180-b.Latitude*pi()/180)/2),2)+cos("+latitude+"*pi()/180)*cos(b.Latitude*pi()/180)* pow(sin( ("+longitude+"*pi()/180-b.Longitude*pi()/180)/2),2)))*1000) distance from UserLocation b,userInfo_view a where a.UID=b.UID order by distance"; Query q = db.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); q.setMaxResults(PageSize); q.setFirstResult((page-1) * PageSize); return q.list(); } }
28.484091
406
0.680124
2f5810c991bbd7bfd7f8f1b9c7d5e7c230394189
2,176
package daikon.inv.filter; import daikon.VarInfo; import daikon.inv.Invariant; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.regex.qual.Regex; /** * A filter that filters out invariants that contain derived variables of a specified derivation. If * the derivation class name contains the regular expression in dkconfig_class_re, the invariant is * filtered out. By default, no derived variables are matched. */ public class DerivedVariableFilter extends InvariantFilter { @Override public String getDescription() { return "Derived Variable filter on '" + dkconfig_class_re + "'"; } /** * Regular expression to match against the class name of derived variables. Invariants that * contain derived variables that match will be filtered out. If null, nothing will be filtered * out. */ // dkconfig_* means a configuration option, set from command line or file public static @Nullable @Regex String dkconfig_class_re = null; public static @Nullable Pattern class_re = null; @SuppressWarnings("StaticAssignmentInConstructor") public DerivedVariableFilter() { isOn = dkconfig_class_re != null; if (isOn) { assert dkconfig_class_re != null : "@AssumeAssertion(nullness): dependent: nullness is indicated by boolean variable isOn"; class_re = Pattern.compile(dkconfig_class_re); } } public @Nullable @Regex String get_derivation_class_re() { return dkconfig_class_re; } @Override boolean shouldDiscardInvariant(Invariant invariant) { assert class_re != null : "@AssumeAssertion(nullness): only called when filter is active"; for (VarInfo vi : invariant.ppt.var_infos) { if (vi.derived == null) { continue; } // System.out.printf("Comparing %s to %s%n", // vi.derived.getClass().getName(), class_re); assert class_re != null : "@AssumeAssertion(nullness): limited side effects don't affect this field"; if (class_re.matcher(vi.derived.getClass().getName()).find()) { return true; } } return false; } }
33.476923
101
0.705882
df5fb2556ec84002a252b1cd4ba35b91305af0d2
1,275
package fs.command; import fs.App; import fs.Disk; import fs.util.StringUtils; import java.io.IOException; /** * * @author José Andrés García Sáenz <[email protected]> */ public class PrintFileContentCommand extends Command { public static final String COMMAND = "cat"; @Override public void execute(String[] args) { if (args.length != 2) { reportSyntaxError(); return; } App app = App.getInstance(); Disk disk = app.getDisk(); String file = args[1]; try { String content = disk.getFileContent(file); int block = 80; int ceil = (int) Math.ceil((double) content.length() / block); for (int i = 0; i < ceil; i++) { System.out.println(StringUtils.substring(content, i*block, (i+1)*block)); } } catch (IOException ex) { reportError(ex); } } @Override protected String getName() { return PrintFileContentCommand.COMMAND; } @Override protected String getDescription() { return "Print the content of a file"; } @Override protected String getSyntax() { return getName() + " FILE"; } }
22.767857
89
0.552157
fc7c7451b03741d5aff0b6d232c0e1f8f6d6e929
2,582
/* * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package heng.shi.controller; import heng.shi.entity.InstantMessage; import heng.shi.entity.User; import heng.shi.repository.ActiveWebSocketUserRepository; import heng.shi.service.CurrentUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.messaging.simp.annotation.SubscribeMapping; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; /** * Controller for managing {@link Message} instances. * * @author Rob Winch */ @Controller @RequestMapping("/") public class MessageController { private SimpMessageSendingOperations messagingTemplate; private ActiveWebSocketUserRepository activeUserRepository; @Autowired public MessageController(ActiveWebSocketUserRepository activeUserRepository, SimpMessageSendingOperations messagingTemplate) { this.activeUserRepository = activeUserRepository; this.messagingTemplate = messagingTemplate; } @MessageMapping("/im") public void im(InstantMessage im, @CurrentUser User currentUser) { if (currentUser==null){ System.out.println("fuck null!"); } System.out.println("/im "+currentUser); im.setFrom(currentUser.getUsername()); this.messagingTemplate.convertAndSendToUser(im.getTo(), "/queue/messages", im); this.messagingTemplate.convertAndSendToUser(im.getFrom(), "/queue/messages", im); System.out.println(im); } @SubscribeMapping("/users") public List<String> subscribeMessages() throws Exception { List<String> users = this.activeUserRepository.findAllActiveUsers(); System.out.println(users); return users; } }
36.366197
89
0.745159
bd01aca1fec18c99cecfd3a76dcadb126df0cc7a
258
package com.hjg.base.util.log.file; import java.io.File; /** * Created by pengwei on 2017/3/30. */ public interface LogFileEngine { void writeToFile(File logFile, String logContent, LogFileParam params); void flushAsync(); void release(); }
18.428571
75
0.705426
19081f003416700d797929610b02685fdc9b68b3
1,543
package eu.sanjin.kurelic.cbc.view.aspect; import eu.sanjin.kurelic.cbc.business.services.CartService; import eu.sanjin.kurelic.cbc.business.viewmodel.cart.CartItems; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpSession; @Aspect @Component public class SessionAspect { private final CartService service; public SessionAspect(CartService service) { this.service = service; } // Advices @Before("@annotation(readFromSession)") public void loadFromSession(ReadFromSession readFromSession) { var session = getSession(); if (session.getAttribute(readFromSession.value()) == null) { session.setAttribute(readFromSession.value(), new CartItems()); } service.loadCartItems((CartItems) session.getAttribute(readFromSession.value())); } @AfterReturning("@annotation(saveToSession)") public void saveToSession(SaveToSession saveToSession) { var session = getSession(); session.setAttribute(saveToSession.value(), service.getCartItems()); } // Utility private HttpSession getSession() { return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession(true); } }
34.288889
122
0.747894
06234c8585452373f85586eabc5e3a6c78010de7
1,552
package org.springframework.remoting.caucho; import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.lang.Nullable; /** * {@link FactoryBean} for Hessian proxies. Exposes the proxied service * for use as a bean reference, using the specified service interface. * * Hessian is a slim, binary RPC protocol. * For information on Hessian, see the * <a href="http://hessian.caucho.com">Hessian website</a> * <b>Note: As of Spring 4.0, this proxy factory requires Hessian 4.0 or above.</b> * * The service URL must be an HTTP URL exposing a Hessian service. * For details, see the {@link HessianClientInterceptor} javadoc. * * @since 13.05.2003 * @see #setServiceInterface * @see #setServiceUrl * @see HessianClientInterceptor * @see HessianServiceExporter * @see org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean * @see org.springframework.remoting.rmi.RmiProxyFactoryBean */ public class HessianProxyFactoryBean extends HessianClientInterceptor implements FactoryBean<Object> { @Nullable private Object serviceProxy; @Override public void afterPropertiesSet() { super.afterPropertiesSet(); this.serviceProxy = new ProxyFactory(getServiceInterface(), this).getProxy(getBeanClassLoader()); } @Override @Nullable public Object getObject() { return this.serviceProxy; } @Override public Class<?> getObjectType() { return getServiceInterface(); } @Override public boolean isSingleton() { return true; } }
25.866667
102
0.762887
c80770c5f1387d4805355bfbfb29e6b817dd3810
2,982
package com.java.parkme.controller; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; 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.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.java.parkme.dto.UploadFileDTO; import com.java.parkme.service.FileStorageService; @RestController public class FileController { private static final Logger logger = LoggerFactory.getLogger(FileController.class); @Autowired private FileStorageService fileStorageService; @PostMapping("/uploadFile") public UploadFileDTO uploadFile(@RequestHeader(name = "filename", required = true) String value, @RequestParam("image") MultipartFile file) { logger.info("Server storing resource "+value); String fileName = fileStorageService.storeFile(file, value); String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath() .path("/downloadFile/") .path(fileName) .toUriString(); return new UploadFileDTO(fileName, fileDownloadUri, file.getContentType(), file.getSize()); } @GetMapping("/downloadFile/{fileName:.+}") public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) { logger.info("Server returning resource"+fileName); Resource resource = null; try { resource = fileStorageService.loadFileAsResource(fileName); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // Try to determine file's content type String contentType = null; try { contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); } catch (IOException ex) { logger.info("Could not determine file type."); } // Fallback to the default content type if type could not be determined if(contentType == null) { contentType = "application/octet-stream"; } return ResponseEntity.ok() .contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } }
37.746835
145
0.726023
c5c02c7b06bdd677327bc0d058b6ecf434952e6c
849
package cy.agorise.graphenej; import org.junit.Assert; import org.junit.Test; public class HtlcTest { private final Htlc htlc = new Htlc("1.16.124"); @Test public void testByteSerialization(){ Htlc htlc1 = new Htlc("1.16.1"); Htlc htlc2 = new Htlc("1.16.100"); Htlc htlc3 = new Htlc("1.16.500"); Htlc htlc4 = new Htlc("1.16.1000"); byte[] expected_1 = Util.hexToBytes("01"); byte[] expected_2 = Util.hexToBytes("64"); byte[] expected_3 = Util.hexToBytes("f403"); byte[] expected_4 = Util.hexToBytes("e807"); Assert.assertArrayEquals(expected_1, htlc1.toBytes()); Assert.assertArrayEquals(expected_2, htlc2.toBytes()); Assert.assertArrayEquals(expected_3, htlc3.toBytes()); Assert.assertArrayEquals(expected_4, htlc4.toBytes()); } }
31.444444
62
0.63722
d29877ea800620196a892f877177fc4a4a1f2e51
901
//$Id$ package org.hibernate.test.annotations.various; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Version; import org.hibernate.annotations.Index; import org.hibernate.annotations.OptimisticLock; /** * @author Emmanuel Bernard */ @Entity public class Conductor { @Id @GeneratedValue private Integer id; @Column(name = "cond_name") @Index(name = "cond_name") @OptimisticLock(excluded = true) private String name; @Version private Long version; public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
16.685185
48
0.72919
55c57d6c53c413c64a997666cb27a3c12e66fbb2
1,324
import java.util.*; public class Bipartite { public int[] color; public boolean[] marked; public LinkedList<Integer>queue = new LinkedList<Integer>(); Bipartite(Graph g,int s) { color = new int[g.V()]; marked = new boolean[g.V()]; for ( int i = 0 ; i<g.V(); i++) { color[i] = -1; } color[s] = 0; // 0 is white color and 1 is RED. Intially source vertex is given white color. } boolean findingBipartite(Graph g, int s) { queue.add(s); while(!queue.isEmpty()) { int ss = queue.remove(); marked[ss] = true; for(int w: g.adj(ss)) { if(color[w] == -1 && !marked[w]) { color[w] = 1 - color[ss]; queue.add(w); } else if ( color[w] == color[ss]) return false; } } return true; } public static void main (String args[]) { Graph g = new Graph(6); g.addEdge(0, 1); g.addEdge(0, 2); //g.addEdge(0, 3); g.addEdge(3, 2); g.addEdge(4, 5); Bipartite b = new Bipartite(g, 0); boolean res = b.findingBipartite(g, 0); System.out.println(res + ", Bipartatie"); } }
23.642857
100
0.457704
6137d8146f4effba5e7c95f77069e93c610c7361
1,672
package llvmmop.output.combinedaspect.event.advice; import llvmmop.output.MOPVariable; import llvmmop.parser.ast.mopspec.MOPParameters; import llvmmop.parser.ast.type.PrimitiveType; import llvmmop.parser.ast.type.Type; import llvmmop.parser.ast.type.VoidType; public class AroundAdviceReturn { MOPVariable skipAroundAdvice; MOPParameters parameters; Type type; public AroundAdviceReturn(Type type, MOPParameters parameters) { skipAroundAdvice = new MOPVariable("MOP_skipAroundAdvice"); this.parameters = parameters; this.type = type; } public String toString() { String ret = ""; if(type instanceof VoidType){ ret += "if(" + skipAroundAdvice + "){\n"; ret += "return;\n"; ret += "} else {\n"; ret += "proceed(" + parameters.parameterString() + ");\n"; ret += "}\n"; }else if(type instanceof PrimitiveType){ PrimitiveType pType = (PrimitiveType)type; ret += "if(" + skipAroundAdvice + "){\n"; switch(pType.getType()){ case Int: case Byte: case Short: case Char: ret += "return 0;\n"; break; case Long: ret += "return 0L;\n"; break; case Float: ret += "return 0.0f;\n"; break; case Double: ret += "return 0.0d;\n"; break; case Boolean: ret += "return false;\n"; break; default: ret += "return null;\n"; break; } ret += "} else {\n"; ret += "return proceed(" + parameters.parameterString() + ");\n"; ret += "}\n"; } else { ret += "if(" + skipAroundAdvice + "){\n"; ret += "return null;\n"; ret += "} else {\n"; ret += "return proceed(" + parameters.parameterString() + ");\n"; ret += "}\n"; } return ret; } }
23.222222
68
0.616627
5279e4875b3a992ae69ca237e00900af24abb2c0
4,306
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.test.modules.search; import java.util.Hashtable; import java.util.Iterator; import junit.framework.Test; import org.netbeans.jellytools.JellyTestCase; import org.netbeans.jellytools.NbDialogOperator; import org.netbeans.jemmy.operators.JComboBoxOperator; import org.netbeans.junit.NbModuleSuite; /** * Some search tests * @author Max Sauer */ public class BasicSearchTest extends JellyTestCase { public String DATA_PROJECT_NAME = "UtilitiesTestProject"; @Override protected void setUp() throws Exception { openDataProjects("projects/" + DATA_PROJECT_NAME); } /** path to sample files */ private static final String TEST_PACKAGE_PATH = "org.netbeans.test.utilities.basicsearch"; /** Creates a new instance of BasicSearchTest */ public BasicSearchTest(String testName) { super(testName); } /** * Adds tests to suite * @return created suite */ public static Test suite() { return NbModuleSuite.create( NbModuleSuite.createConfiguration(BasicSearchTest.class).addTest("testSearchForClass", "testRememberSearchesInsideComboBox").enableModules(".*").clusters(".*")); } public void testSearchForClass() { NbDialogOperator ndo = Utilities.getFindDialogMainMenu(); JComboBoxOperator jcbo = new JComboBoxOperator(ndo, new JComboBoxOperator.JComboBoxFinder()); jcbo.enterText("class"); //enter 'class' in search comboBox and press [Enter] SearchResultsOperator sro = new SearchResultsOperator(); assertTrue("Junit Output window should be visible", sro.isVisible()); System.out.println("## Search output opened"); Utilities.takeANap(1000); sro.close(); assertFalse("Search window is visible," + "should be closed", sro.isShowing()); } /** * Test if searched items are remembered inside combobox */ public void testRememberSearchesInsideComboBox() { //setup ten searches for (int i = 0; i < 10; i++) { NbDialogOperator ndo = Utilities.getFindDialogMainMenu(); JComboBoxOperator jcbo = new JComboBoxOperator(ndo, new JComboBoxOperator.JComboBoxFinder()); jcbo.enterText("a" + i); Utilities.takeANap(500); } //check NbDialogOperator ndo = Utilities.getFindDialogMainMenu(); JComboBoxOperator jcbo = new JComboBoxOperator(ndo, new JComboBoxOperator.JComboBoxFinder()); for (int i = 0; i < jcbo.getItemCount() - 1; i++) { assertEquals("Found " + jcbo.getItemAt(i).toString() +" in search combo" + "expected" + new Integer(9-i).toString() + ".", jcbo.getItemAt(i).toString(), "a" + new Integer(9-i).toString()); } assertEquals("Expected 'class', found: " + jcbo.getItemAt(jcbo.getItemCount()-1), jcbo.getItemAt(jcbo.getItemCount()-1), "class"); } private String soutHashTable(Hashtable ht) { StringBuffer sb = new StringBuffer(); Iterator itv = ht.values().iterator(); for (Iterator it = ht.keySet().iterator(); it.hasNext();) { sb.append("KEY: " + it.next() + " Value: " + itv.next() + "\n"); } return sb.toString(); } }
36.184874
177
0.63725
05334df273888d89c286f39bfb4c6a6711e61875
989
/* * @Description: * @Author: you-know-who-2017 * @Github: https://github.com/you-know-who-2017 * @Date: 2019-12-21 01:25:31 * @LastEditors: you-know-who-2017 * @LastEditTime: 2019-12-21 01:25:31 */ import java.util.*; public class Example15_2 { public static void main(String args[]){ List<String> list=new LinkedList<String>(); for(int i=0;i<=60096;i++){ list.add("speed"+i); } Iterator<String> iter=list.iterator(); long starttime=System.currentTimeMillis(); while(iter.hasNext()){ String te=iter.next(); } long endTime=System.currentTimeMillis(); long result=endTime-starttime; System.out.println("使用迭代器遍历集合所用时间:"+result+"毫秒"); starttime=System.currentTimeMillis(); for(int i=0;i<list.size();i++){ String te=list.get(i); } endTime=System.currentTimeMillis(); result=endTime-starttime; System.out.println("使用get方法遍历集合所用时间:"+result+"毫秒"); } }
29.969697
57
0.619818
604949f35ecef5667d769bccd8b3ce4508d67b4c
1,532
package org.springframework.samples.petclinic.ui.view.owner; import com.vaadin.flow.component.ClickEvent; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.data.binder.ValidationException; import com.vaadin.flow.router.BeforeEnterEvent; import com.vaadin.flow.router.BeforeEnterObserver; import com.vaadin.flow.router.Route; import org.springframework.samples.petclinic.ui.view.MainContentLayout; @Route(value = "owners/:ownerId([0-9]+)/pets/:petId([0-9]+)/edit", layout = MainContentLayout.class) public class PetEditView extends PetFormView implements BeforeEnterObserver { private final PetEditPresenter presenter; PetEditView(PetEditPresenter presenter) { super(presenter); this.presenter = presenter; presenter.setView(this); } @Override protected String formTitle() { return getTranslation("pet"); } @Override protected String actionButtonLabel() { return getTranslation("updatePet"); } @Override protected void actionButtonListener(ClickEvent<Button> event) { try { binder.writeBean(presenter.getModel()); presenter.save(); } catch (ValidationException ex) { } } @Override public void beforeEnter(BeforeEnterEvent event) { Integer ownerId = event.getRouteParameters().getInteger("ownerId").orElse(null); Integer petId = event.getRouteParameters().getInteger("petId").orElse(null); presenter.initModel(ownerId, petId); } }
30.64
100
0.708877
62aac60aebce58728c88acc251116a7f2c4eaacb
3,660
package features.domain.builders; import features.domain.ParentD; import features.domain.ParentDChildC; import features.domain.ParentDToChildC; import java.util.List; import joist.domain.builders.AbstractBuilder; import joist.domain.builders.DefaultsContext; import joist.domain.uow.UoW; @SuppressWarnings("all") public abstract class ParentDToChildCBuilderCodegen extends AbstractBuilder<ParentDToChildC> { public ParentDToChildCBuilderCodegen(ParentDToChildC instance) { super(instance); } @Override public ParentDToChildCBuilder defaults() { return (ParentDToChildCBuilder) super.defaults(); } @Override protected void defaults(DefaultsContext c) { super.defaults(c); c.rememberIfSet(parentDChildC()); c.rememberIfSet(parentD()); if (parentDChildC() == null) { parentDChildC(c.getIfAvailable(ParentDChildC.class)); if (parentDChildC() == null) { parentDChildC(defaultParentDChildC()); c.rememberIfSet(parentDChildC()); } } if (parentD() == null) { parentD(c.getIfAvailable(ParentD.class)); if (parentD() == null) { parentD(defaultParentD()); c.rememberIfSet(parentD()); } } } public Long id() { if (UoW.isOpen() && get().getId() == null) { UoW.flush(); } return get().getId(); } public ParentDToChildCBuilder id(Long id) { get().setId(id); return (ParentDToChildCBuilder) this; } public ParentDChildCBuilder parentDChildC() { if (get().getParentDChildC() == null) { return null; } return Builders.existing(get().getParentDChildC()); } public ParentDToChildCBuilder parentDChildC(ParentDChildC parentDChildC) { get().setParentDChildC(parentDChildC); return (ParentDToChildCBuilder) this; } public ParentDToChildCBuilder with(ParentDChildC parentDChildC) { return parentDChildC(parentDChildC); } public ParentDToChildCBuilder parentDChildC(ParentDChildCBuilder parentDChildC) { return parentDChildC(parentDChildC == null ? null : parentDChildC.get()); } public ParentDToChildCBuilder with(ParentDChildCBuilder parentDChildC) { return parentDChildC(parentDChildC); } protected ParentDChildCBuilder defaultParentDChildC() { return Builders.aParentDChildC().defaults(); } public ParentDBuilder parentD() { if (get().getParentD() == null) { return null; } return Builders.existing(get().getParentD()); } public ParentDToChildCBuilder parentD(ParentD parentD) { get().setParentD(parentD); return (ParentDToChildCBuilder) this; } public ParentDToChildCBuilder with(ParentD parentD) { return parentD(parentD); } public ParentDToChildCBuilder parentD(ParentDBuilder parentD) { return parentD(parentD == null ? null : parentD.get()); } public ParentDToChildCBuilder with(ParentDBuilder parentD) { return parentD(parentD); } protected ParentDBuilder defaultParentD() { return Builders.aParentD().defaults(); } public ParentDToChildC get() { return (features.domain.ParentDToChildC) super.get(); } @Override public ParentDToChildCBuilder ensureSaved() { doEnsureSaved(); return (ParentDToChildCBuilder) this; } @Override public ParentDToChildCBuilder use(AbstractBuilder<?> builder) { return (ParentDToChildCBuilder) super.use(builder); } @Override public void delete() { ParentDToChildC.queries.delete(get()); } public static void deleteAll() { List<Long> ids = ParentDToChildC.queries.findAllIds(); for (Long id : ids) { ParentDToChildC.queries.delete(ParentDToChildC.queries.find(id)); } } }
26.142857
94
0.706831
a8fad6b17f279cef04dabd091f1d87dd4c2d1866
1,767
package com.xxx.pri.domain; import lombok.Data; import cn.hutool.core.bean.BeanUtil; import io.swagger.annotations.ApiModelProperty; import cn.hutool.core.bean.copier.CopyOptions; import javax.persistence.*; import javax.validation.constraints.*; import java.sql.Timestamp; import com.xxx.pri.base.PriBaseEntity; /** * @website https://el-admin.vip * @description / * @author xslong * @date 2020-12-16 **/ @Entity @Data @Table(name="pri_member") @org.hibernate.annotations.GenericGenerator(name = "jpa-uuid", strategy = "uuid") public class Member extends PriBaseEntity<String> { @Id @GeneratedValue(generator = "jpa-uuid") @Column(name = "id") @ApiModelProperty(value = "ID") private String id; @Column(name = "username",unique = true) @ApiModelProperty(value = "用户名") private String username; @Column(name = "nick_name") @ApiModelProperty(value = "昵称") private String nickName; @Column(name = "gender") @ApiModelProperty(value = "性别") private String gender; @Column(name = "phone") @ApiModelProperty(value = "手机号码") private String phone; @Column(name = "email",unique = true) @ApiModelProperty(value = "邮箱") private String email; @Column(name = "avatar_path") @ApiModelProperty(value = "头像真实路径") private String avatarPath; @Column(name = "password") @ApiModelProperty(value = "密码") private String password; @Column(name = "enabled") @ApiModelProperty(value = "状态:1启用、0禁用") private Long enabled; @Column(name = "pwd_reset_time") @ApiModelProperty(value = "修改密码的时间") private Timestamp pwdResetTime; public void copy(Member source){ BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); } }
29.949153
92
0.691568
930b8dad4222aa23bc729e795ccc08360ec0aac7
2,181
package q450; import org.junit.runner.RunWith; import util.runner.Answer; import util.runner.LeetCodeRunner; import util.runner.TestData; import util.runner.data.DataExpectation; /** * https://leetcode.com/problems/battleships-in-a-board/ * * Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are * represented with '.'s. You may assume the following rules: * * You receive a valid board, made of only battleships or empty slots. * Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape * 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size. * At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships. * * Example: * * X..X * ...X * ...X * * In the above board there are 2 battleships. * * Invalid Example: * * ...X * XXXX * ...X * * This is an invalid board that you will not receive - as battleships will always have a cell separating between them. * * Follow up: * Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board? */ @RunWith(LeetCodeRunner.class) public class Q419_BattleshipsInABoard { @Answer public int countBattleships(char[][] board) { if (board.length == 0 || board[0].length == 0) { return 0; } final int m = board.length, n = board[0].length; int res = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'X') { if (i > 0 && board[i - 1][j] == 'X' || j > 0 && board[i][j - 1] == 'X') { // 之前已经找到过它的端点了 continue; } else { res++; } } } } return res; } @TestData public DataExpectation exmple = DataExpectation.create(new char[][]{ {'X', '.', '.', '.'}, {'.', '.', '.', 'X'}, {'.', '.', '.', 'X'} }).expect(2); }
29.876712
119
0.55204
e6eff475cce28df21bded50607191750b1f8bd58
592
package genepi.io.linkage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class DatFileWriter { private BufferedWriter bw; private boolean first = true; public DatFileWriter(String filename) throws IOException { bw = new BufferedWriter(new FileWriter(new File(filename), false)); first = true; } public void write(Marker snp) throws IOException { if (first) { first = false; } else { bw.newLine(); } bw.write("M " + snp.getId()); } public void close() throws IOException { bw.close(); } }
17.939394
69
0.702703
1eb8b907c2ac806ee96860e158c3019a728a92d4
527
package com.nainai.mobile; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @MapperScan("com.nainai.mobile.mapper") @ServletComponentScan("com.nainai.mobile.config") public class MobileApplication { public static void main(String[] args) { SpringApplication.run(MobileApplication.class, args); } }
29.277778
68
0.808349
3989133a596ed85a579c367ab65dd126a2691efb
2,618
package pl.agh.wd; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.security.test.context.support.WithMockUser; import pl.agh.wd.controller.FieldOfStudyController; import pl.agh.wd.model.*; import pl.agh.wd.repository.*; import java.util.List; import java.util.Optional; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class FieldOfStudyTests { @Autowired private FieldOfStudyRepository fieldOfStudyRepository; @Autowired private FacultyRepository facultyRepository; @Autowired private FieldOfStudyController fieldOfStudyController; @Test @WithMockUser(username = "admin", roles={"ADMIN"}) void testGetFaculties() { Faculty newFaculty = new Faculty(); newFaculty.setName("FOStestFaculty"); Optional <Faculty> optionalFaculty = facultyRepository.findByName("FOStestFaculty"); assert(optionalFaculty.isEmpty()); facultyRepository.save(newFaculty); optionalFaculty = facultyRepository.findByName("FOStestFaculty"); assert(optionalFaculty.isPresent()); FieldOfStudy newFOS = new FieldOfStudy(); newFOS.setFaculty(newFaculty); newFOS.setName("FOStestFOS"); Optional<FieldOfStudy> optionalFOS = fieldOfStudyRepository.findByName("FOStestFOS"); assert(optionalFOS.isEmpty()); fieldOfStudyRepository.save(newFOS); optionalFOS = fieldOfStudyRepository.findByName("FOStestFOS"); assert(optionalFOS.isPresent()); List<FieldOfStudy> FOSList = fieldOfStudyRepository.findAll(); assert(!FOSList.isEmpty()); boolean found = false; for (FieldOfStudy fos : FOSList) { if (fos.getName().equals("FOStestFOS")) { found = true; break; } } assert(found); found = false; ResponseEntity<?> responseEntity = fieldOfStudyController.getFaculties(); List<FieldOfStudy> lista = (List<FieldOfStudy>) responseEntity.getBody(); assert(lista != null); assert(!lista.isEmpty()); for (FieldOfStudy fos : lista) { System.out.println(fos.getName()); if (fos.getName().equals("FOStestFOS")) { found = true; break; } } assert(found); assert(responseEntity.getStatusCode().toString().equals("200 OK")); } }
29.41573
93
0.669213
eaf9beacdb1be17732e51297fd43fab0c110ddc0
3,015
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer 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 ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package hmi.graphics.opengl.state; import hmi.graphics.opengl.GLRenderContext; /** * A GLCapability is a wrapper for some OpenGL capability. * The capability will be enabled or disabled when the * glInit() or glRender() method is called, depending on the current state of the GLCapability object. * @author Job Zwiers */ public class GLCapability implements GLStateComponent { private boolean enabled; // enabled or disabled private int glId; // OpenGL variable id private int scId; // GLStateComponent id /** * Create a new capability (i.e. a boolean valued GLStateComponent) */ public GLCapability(int glId, boolean enabled) { this.glId = glId; this.enabled = enabled; scId = GLState.getSCId(glId); } /** * Sets the state of this GLCapability to the specified boolean value. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Returns the state of this GLCapability. */ public boolean isEnabled() { return enabled; } /** * Equality test based upon GLStateComponent id and boolean value */ public boolean equals(Object obj) { if (obj instanceof GLCapability) { GLCapability glcap = (GLCapability) obj; return glcap.scId == this.scId && glcap.enabled == this.enabled; } else { return false; } } /** * hash code consistent with equals. */ public int hashCode() { return scId; } public void glInit(GLRenderContext gl) { glRender(gl); } public final void glRender(GLRenderContext glc) { if (enabled) { glc.gl.glEnable(glId); } else { glc.gl.glDisable(glId); } } public final int getSCId() { return scId; } public String toString() { return("<" + GLState.getGLName(glId) + " = " + enabled + ">"); } }
29.851485
102
0.610282
f35a4adb4789a05f2bb58c9c8496eadccc83ce2b
1,107
package com.dotmarketing.business.cache.provider.hazelcast; import java.text.DecimalFormat; import java.text.NumberFormat; import com.dotcms.cluster.business.HazelcastUtil.HazelcastInstanceType; import com.dotmarketing.business.cache.provider.CacheStats; public class HazelcastCacheProviderClient extends AbstractHazelcastCacheProvider { private static final long serialVersionUID = 1L; @Override public String getName() { return "Hazelcast Client Provider"; } @Override public String getKey() { return "HazelcastCacheProviderClient"; } @Override protected HazelcastInstanceType getHazelcastInstanceType() { return HazelcastInstanceType.CLIENT; } @Override protected CacheStats getStats(String group) { NumberFormat nf = DecimalFormat.getInstance(); long size = getHazelcastInstance().getMap(group).keySet().size(); CacheStats result = new CacheStats(); result.addStat(CacheStats.REGION, group); result.addStat(CacheStats.REGION_SIZE, nf.format(size)); return result; } }
25.744186
82
0.724481
c7ace456ddfa326401b9339c0f945927416c69f4
7,804
package it.unisa.c03.myPersonalTrainer.parameters.service; import it.unisa.c03.myPersonalTrainer.parameters.dao.ParametersDAO; import it.unisa.c03.myPersonalTrainer.parameters.bean.Parameters; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; class ParametersServiceImplTest { ParametersDAO parametersDAO = Mockito.mock(ParametersDAO.class); ParametersService pservice = new ParametersServiceImpl(parametersDAO); //TC_1.2_1 @Test void lenghtWeightNotValid() throws IOException { String weight = "2"; String fatMass = "30%"; String leanMass = "55%"; String email = "[email protected]"; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("lunghezza peso non valida", exception.getMessage()); } @Test void lenghtWeightNotValidMax() throws IOException { String weight = "180"; String fatMass = "30%"; String leanMass = "55%"; String email = "[email protected]"; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("valore peso non valido", exception.getMessage()); } @Test void lenghtWeightNotValidMin() throws IOException { String weight = "20"; String fatMass = "30%"; String leanMass = "55%"; String email = "[email protected]"; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("valore peso non valido", exception.getMessage()); } @Test void valuesNull() throws IOException { String weight = null; String fatMass = null; String leanMass = null; String email = "[email protected]"; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("valori mancanti", exception.getMessage()); } //TC_1.2_2 @Test void formatWeightNotValid() throws IOException { String weight = "5X"; String fatMass = "30%"; String email = "[email protected]"; String leanMass = "55%"; NumberFormatException exception = assertThrows(NumberFormatException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("formato peso non valido", exception.getMessage()); } //TC_1.2_4 @Test void lenghtFatMassNotValid() throws IOException { String weight = "50"; String fatMass = "3%"; String email = "[email protected]"; String leanMass = "45%"; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("lunghezza massa grassa non valida", exception.getMessage()); } //TC_1.2_5 @Test void lenghtFatMassNotValidMax() throws IOException { String weight = "50"; String fatMass = "99%"; String email = "[email protected]"; String leanMass = "55%"; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("lunghezza massa grassa non valida", exception.getMessage()); } @Test void formatfatMassNotValid() throws IOException { String weight = "50"; String fatMass = "30X%"; String leanMass = "55%"; String email = "[email protected]"; NumberFormatException exception = assertThrows(NumberFormatException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("formato massa grassa non valido", exception.getMessage()); } @Test void formatleanMassNotValid() throws IOException { String weight = "50"; String fatMass = "30%"; String leanMass = "55X%"; String email = "[email protected]"; NumberFormatException exception = assertThrows(NumberFormatException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("formato massa magra non valido", exception.getMessage()); } //TC_1.2_3 @Test void lenghtleanMassNotValid() throws IOException { String weight = "50"; String fatMass = "30%"; String email = "[email protected]"; String leanMass = "5%"; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("lunghezza massa magra non valida", exception.getMessage()); } @Test void lenghtleanMassNotValidMax() throws IOException { String weight = "50"; String fatMass = "30%"; String email = "[email protected]"; String leanMass = "99%"; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { pservice.createParameters(weight, leanMass, fatMass, email); }); assertEquals("lunghezza massa magra non valida", exception.getMessage()); } @Test void finalTest() throws IOException { String weight = "50"; String fatMass = "30%"; String leanMass = "50%"; String email = "[email protected]"; assertEquals(Parameters.class, pservice.createParameters(weight, leanMass, fatMass, email).getClass()); } @Test void testServiceInsert() throws IOException { Mockito.when(parametersDAO.insertParameters(any())).thenReturn(true); assertEquals(true, pservice.saveParameters(any())); } @Test void testServiceInsertFalse() throws IOException { Mockito.when(parametersDAO.insertParameters(any())).thenReturn(false); assertEquals(false, pservice.saveParameters(any())); } @Test void testFindByEmailNull() { String email = null; IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { pservice.getByMail(email); }); assertEquals("Email non valida", exception.getMessage()); } @Test void mailNonExist() throws InterruptedException, ExecutionException, IOException { ArrayList<Parameters> list = new ArrayList<>(); Mockito.when(parametersDAO.selectByMail(anyString())).thenReturn(list); assertEquals(0, pservice.getByMail(anyString()).size()); } @Test void mailExist() throws InterruptedException, ExecutionException, IOException { Parameters p1 = new Parameters(80, 48, 40, "[email protected]"); ArrayList<Parameters> list = new ArrayList<>(); list.add(p1); Mockito.when(parametersDAO.selectByMail(anyString())).thenReturn(list); assertEquals(1, pservice.getByMail(anyString()).size()); } }
36.297674
112
0.631855
1fbf4cd4c512ba7126f4b6239addc4479aa271aa
1,254
package com.psddev.dari.db; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.shyiko.mysql.binlog.BinaryLogClient; import com.github.shyiko.mysql.binlog.BinaryLogClient.AbstractLifecycleListener; import com.google.common.cache.Cache; class MySQLBinaryLogLifecycleListener extends AbstractLifecycleListener { private static final Logger LOGGER = LoggerFactory.getLogger(MySQLBinaryLogLifecycleListener.class); private final Cache<UUID, Object[]> cache; private volatile boolean connected; public MySQLBinaryLogLifecycleListener(Cache<UUID, Object[]> cache) { this.cache = cache; } public boolean isConnected() { return connected; } @Override public void onConnect(BinaryLogClient client) { LOGGER.info("Connected to MySQL as a slave"); connected = true; } @Override public void onCommunicationFailure(BinaryLogClient client, Exception error) { LOGGER.warn("Can't communicate with MySQL as a slave!", error); } @Override public void onDisconnect(BinaryLogClient client) { LOGGER.info("Disconnected from MySQL as a slave"); connected = false; cache.invalidateAll(); } }
27.866667
104
0.721691
1a1f3aaa1d9413d0fdbd3508db12766a8dd9d282
2,861
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.samples.litho.textinput; import android.view.View; import com.facebook.litho.ClickEvent; import com.facebook.litho.Column; import com.facebook.litho.Component; import com.facebook.litho.ComponentContext; import com.facebook.litho.Handle; import com.facebook.litho.Row; import com.facebook.litho.StateValue; import com.facebook.litho.annotations.FromEvent; import com.facebook.litho.annotations.LayoutSpec; import com.facebook.litho.annotations.OnCreateInitialState; import com.facebook.litho.annotations.OnCreateLayout; import com.facebook.litho.annotations.OnEvent; import com.facebook.litho.annotations.State; import com.facebook.litho.widget.Text; import com.facebook.litho.widget.TextInput; import com.facebook.yoga.YogaEdge; /** Demo to show how to request/clear focus programmatically. */ @LayoutSpec class TextInputRequestAndClearFocusSpec { @OnCreateInitialState static void onCreateInitialState(ComponentContext c, StateValue<Handle> textInputHandle) { textInputHandle.set(new Handle()); } @OnCreateLayout static Component onCreateLayout(ComponentContext c, @State Handle textInputHandle) { return Column.create(c) .child(TextInput.create(c).handle(textInputHandle)) .child( Row.create(c) .child( Text.create(c) .text("Request Focus") .clickHandler(TextInputRequestAndClearFocus.onRequestFocusClick(c)) .paddingDip(YogaEdge.ALL, 16) .marginDip(YogaEdge.RIGHT, 16)) .child( Text.create(c) .text("Clear Focus") .clickHandler(TextInputRequestAndClearFocus.onClearFocusClick(c)) .paddingDip(YogaEdge.ALL, 16))) .build(); } @OnEvent(ClickEvent.class) static void onRequestFocusClick( ComponentContext c, @FromEvent View view, @State Handle textInputHandle) { TextInput.requestFocus(c, textInputHandle); } @OnEvent(ClickEvent.class) static void onClearFocusClick( ComponentContext c, @FromEvent View view, @State Handle textInputHandle) { TextInput.clearFocus(c, textInputHandle); } }
36.679487
92
0.706047
cef350208a5d259eb85f4574bcf380cdbb6d439c
192
package net.cuddlebat.skygrid.world; import net.minecraft.world.gen.chunk.OverworldChunkGeneratorConfig; public class SkygridChunkGeneratorConfig extends OverworldChunkGeneratorConfig { }
21.333333
78
0.859375
2cc646a5484d56252fb6c934db1a3adad1da9d58
1,098
/* * Copyright 2017 Artear S.A. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.artear.thumbnailkit; import com.artear.thumbnailkit.image.CDNThumbnail; /** * Created by sergiobanares. */ public interface CDNThumbnailInterface { /** * @param imageUrl base image url * @return true if can be handled */ boolean validate(String imageUrl); /** * @param imageUrl base image url * @param thumbnail Strategy to reformat url * @return image url modified */ String thumbnail(String imageUrl, CDNThumbnail thumbnail); }
27.45
75
0.70765
7c49d183a7600d0575575896474c3044f2d7ee48
5,340
package advent.twenty_seventeen; import advent.common.DailyProblem; import advent.utilities.FileUtilities; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class Day20ParticleSwarm implements DailyProblem<Integer, Integer> { private final int part1Answer; private final int part2Answer; static class Particle { long x; long y; long z; long vx; long vy; long vz; long ax; long ay; long az; @Override public String toString() { return "(" + x + "," + y + "," + z + ")"; } } public Day20ParticleSwarm(String filename) { List<String> lines = FileUtilities.readLines(filename, String::trim); this.part1Answer = runPart1(getParticlesFromInput(lines)); this.part2Answer = runPart2(getParticlesFromInput(lines)); } private int runPart1(Particle[] particles) { int step = 0; Map<Integer, Integer> nearest = new HashMap<>(); while (step != 100000) { long minD = Long.MAX_VALUE; int pIdx = -1; for (int p = 0; p != particles.length; p++) { updateParticlePosition(particles, p); long d = Math.abs(particles[p].x) + Math.abs(particles[p].y) + Math.abs(particles[p].z); if (d < minD) { minD = d; pIdx = p; } } nearest.put(pIdx, nearest.getOrDefault(pIdx, 0) + 1); step++; } int nIdx = -1; int maxCount = -1; for (Map.Entry<Integer, Integer> entry : nearest.entrySet()) { if (entry.getValue() > maxCount) { maxCount = entry.getValue(); nIdx = entry.getKey(); } } return nIdx; } private void updateParticlePosition(Particle[] particles, int p) { particles[p].vx += particles[p].ax; particles[p].vy += particles[p].ay; particles[p].vz += particles[p].az; particles[p].x += particles[p].vx; particles[p].y += particles[p].vy; particles[p].z += particles[p].vz; } private int runPart2(Particle[] particles) { Map<Integer, Integer> nearest = new HashMap<>(); int step = 0; int alive = particles.length; int previous = 0; while (alive > 0 && step < 10000) { previous = alive; for (int p = 0; p != particles.length; p++) { if (particles[p] == null) { continue; } updateParticlePosition(particles, p); } for (int a = 0; a != particles.length - 1; a++) { if (particles[a] != null) { boolean aMatched = false; for (int b = a+1; b != particles.length; b++) { if (particles[b] != null) { boolean samePos = particles[a].x == particles[b].x; samePos = samePos && particles[a].y == particles[b].y; samePos = samePos && particles[a].z == particles[b].z; if (samePos) { particles[b] = null; aMatched = true; alive--; } } } if (aMatched) { particles[a] = null; alive--; } } } if (previous == alive) { step++; } else { step = 0; } } return alive; } private Particle[] getParticlesFromInput(List<String> lines) { Particle[] particles = new Particle[lines.size()]; for (int p = 0; p != particles.length; p++) { // p=< 3,0,0>, v=< 2,0,0>, a=<-1,0,0> particles[p] = new Particle(); String line = lines.get(p); int i = line.indexOf("<"); int j = line.indexOf(">", i); String[] bits = line.substring(i+1,j).split(","); particles[p].x = Integer.parseInt(bits[0].trim()); particles[p].y = Integer.parseInt(bits[1].trim()); particles[p].z = Integer.parseInt(bits[2].trim()); i = line.indexOf("<", j); j = line.indexOf(">", i); bits = line.substring(i+1,j).split(","); particles[p].vx = Integer.parseInt(bits[0].trim()); particles[p].vy = Integer.parseInt(bits[1].trim()); particles[p].vz = Integer.parseInt(bits[2].trim()); i = line.indexOf("<", j); j = line.indexOf(">", i); bits = line.substring(i+1,j).split(","); particles[p].ax = Integer.parseInt(bits[0].trim()); particles[p].ay = Integer.parseInt(bits[1].trim()); particles[p].az = Integer.parseInt(bits[2].trim()); } return particles; } @Override public Integer getPart1Answer() { return part1Answer; } @Override public Integer getPart2Answer() { return part2Answer; } }
31.785714
104
0.472846
d727958a35d128d4efbc184b610660f76a4ef078
2,667
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package groovy.transform.stc; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.SourceUnit; import java.util.List; /** * If multiple candidate signatures are found after applying type hints, * a conflict resolver can attempt to resolve the ambiguity. * * @since 2.5.0 */ public class ClosureSignatureConflictResolver { /** * * @param candidates the list of signatures as determined after applying type hints and performing initial inference calculations * @param receiver the receiver the method is being called on * @param arguments the arguments for the closure * @param closure the closure expression under analysis * @param methodNode the method for which a {@link groovy.lang.Closure} parameter was annotated with {@link ClosureParams} * @param sourceUnit the source unit of the file being compiled * @param compilationUnit the compilation unit of the file being compiled * @param options the options, corresponding to the {@link ClosureParams#options()} found on the annotation * @return a non-null list of signatures, where a signature corresponds to an array of class nodes, each of them matching a parameter. A list with more than one element indicates that all ambiguities haven't yet been resolved. */ public List<ClassNode[]> resolve(List<ClassNode[]> candidates, ClassNode receiver, Expression arguments, ClosureExpression closure, MethodNode methodNode, SourceUnit sourceUnit, CompilationUnit compilationUnit, String[] options) { // do nothing by default return candidates; } }
48.490909
230
0.745407
1e86900418b9318a0161c881df8c69348c1d0a19
8,464
/* * Copyright 2016 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.util; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import static io.netty.util.internal.ObjectUtil.checkNotNull; /** * Builder for immutable {@link DomainNameMapping} instances. * * @param <V> concrete type of value objects * @deprecated Use {@link DomainWildcardMappingBuilder} */ @Deprecated public final class DomainNameMappingBuilder<V> { private final V defaultValue; private final Map<String, V> map; /** * Constructor with default initial capacity of the map holding the mappings * * @param defaultValue the default value for {@link DomainNameMapping#map(String)} to return * when nothing matches the input */ public DomainNameMappingBuilder(V defaultValue) { this(4, defaultValue); } /** * Constructor with initial capacity of the map holding the mappings * * @param initialCapacity initial capacity for the internal map * @param defaultValue the default value for {@link DomainNameMapping#map(String)} to return * when nothing matches the input */ public DomainNameMappingBuilder(int initialCapacity, V defaultValue) { this.defaultValue = checkNotNull(defaultValue, "defaultValue"); map = new LinkedHashMap<String, V>(initialCapacity); } /** * Adds a mapping that maps the specified (optionally wildcard) host name to the specified output value. * Null values are forbidden for both hostnames and values. * <p> * <a href="http://en.wikipedia.org/wiki/Wildcard_DNS_record">DNS wildcard</a> is supported as hostname. * For example, you can use {@code *.netty.io} to match {@code netty.io} and {@code downloads.netty.io}. * </p> * * @param hostname the host name (optionally wildcard) * @param output the output value that will be returned by {@link DomainNameMapping#map(String)} * when the specified host name matches the specified input host name */ public DomainNameMappingBuilder<V> add(String hostname, V output) { map.put(checkNotNull(hostname, "hostname"), checkNotNull(output, "output")); return this; } /** * Creates a new instance of immutable {@link DomainNameMapping} * Attempts to add new mappings to the result object will cause {@link UnsupportedOperationException} to be thrown * * @return new {@link DomainNameMapping} instance */ public DomainNameMapping<V> build() { return new ImmutableDomainNameMapping<V>(defaultValue, map); } /** * Immutable mapping from domain name pattern to its associated value object. * Mapping is represented by two arrays: keys and values. Key domainNamePatterns[i] is associated with values[i]. * * @param <V> concrete type of value objects */ private static final class ImmutableDomainNameMapping<V> extends DomainNameMapping<V> { private static final String REPR_HEADER = "ImmutableDomainNameMapping(default: "; private static final String REPR_MAP_OPENING = ", map: {"; private static final String REPR_MAP_CLOSING = "})"; private static final int REPR_CONST_PART_LENGTH = REPR_HEADER.length() + REPR_MAP_OPENING.length() + REPR_MAP_CLOSING.length(); private final String[] domainNamePatterns; private final V[] values; private final Map<String, V> map; @SuppressWarnings("unchecked") private ImmutableDomainNameMapping(V defaultValue, Map<String, V> map) { super(null, defaultValue); Set<Map.Entry<String, V>> mappings = map.entrySet(); int numberOfMappings = mappings.size(); domainNamePatterns = new String[numberOfMappings]; values = (V[]) new Object[numberOfMappings]; final Map<String, V> mapCopy = new LinkedHashMap<String, V>(map.size()); int index = 0; for (Map.Entry<String, V> mapping : mappings) { final String hostname = normalizeHostname(mapping.getKey()); final V value = mapping.getValue(); domainNamePatterns[index] = hostname; values[index] = value; mapCopy.put(hostname, value); ++index; } this.map = Collections.unmodifiableMap(mapCopy); } @Override @Deprecated public DomainNameMapping<V> add(String hostname, V output) { throw new UnsupportedOperationException( "Immutable DomainNameMapping does not support modification after initial creation"); } @Override public V map(String hostname) { if (hostname != null) { hostname = normalizeHostname(hostname); int length = domainNamePatterns.length; for (int index = 0; index < length; ++index) { if (matches(domainNamePatterns[index], hostname)) { return values[index]; } } } return defaultValue; } @Override public Map<String, V> asMap() { return map; } @Override public String toString() { String defaultValueStr = defaultValue.toString(); int numberOfMappings = domainNamePatterns.length; if (numberOfMappings == 0) { return REPR_HEADER + defaultValueStr + REPR_MAP_OPENING + REPR_MAP_CLOSING; } String pattern0 = domainNamePatterns[0]; String value0 = values[0].toString(); int oneMappingLength = pattern0.length() + value0.length() + 3; // 2 for separator ", " and 1 for '=' int estimatedBufferSize = estimateBufferSize(defaultValueStr.length(), numberOfMappings, oneMappingLength); StringBuilder sb = new StringBuilder(estimatedBufferSize) .append(REPR_HEADER).append(defaultValueStr).append(REPR_MAP_OPENING); appendMapping(sb, pattern0, value0); for (int index = 1; index < numberOfMappings; ++index) { sb.append(", "); appendMapping(sb, index); } return sb.append(REPR_MAP_CLOSING).toString(); } /** * Estimates the length of string representation of the given instance: * est = lengthOfConstantComponents + defaultValueLength + (estimatedMappingLength * numOfMappings) * 1.10 * * @param defaultValueLength length of string representation of {@link #defaultValue} * @param numberOfMappings number of mappings the given instance holds, * e.g. {@link #domainNamePatterns#length} * @param estimatedMappingLength estimated size taken by one mapping * @return estimated length of string returned by {@link #toString()} */ private static int estimateBufferSize(int defaultValueLength, int numberOfMappings, int estimatedMappingLength) { return REPR_CONST_PART_LENGTH + defaultValueLength + (int) (estimatedMappingLength * numberOfMappings * 1.10); } private StringBuilder appendMapping(StringBuilder sb, int mappingIndex) { return appendMapping(sb, domainNamePatterns[mappingIndex], values[mappingIndex].toString()); } private static StringBuilder appendMapping(StringBuilder sb, String domainNamePattern, String value) { return sb.append(domainNamePattern).append('=').append(value); } } }
40.888889
119
0.633625
291f0cbfd95c69c107cdd959ab6a5e6a482af8cf
574
package view; import com.arellomobile.mvp.MvpView; import com.arellomobile.mvp.presenter.InjectPresenter; import com.arellomobile.mvp.view.CounterTestView; import com.arellomobile.mvp.view.TestView; import com.arellomobile.mvp.view.TestViewChild2; import presenter.WithViewGenericPresenter; /** * Date: 04.03.2016 * Time: 11:27 * * @author Savin Mikhail */ public class InjectPresenterWithGenericView extends CounterTestView { @InjectPresenter WithViewGenericPresenter<InjectPresenterWithGenericView, CounterTestView> mPresenter; public void testEvent() { } }
22.96
86
0.808362
6d0f8f207db782cc3830a08395972d0c9874d8f1
597
package com.github.sql.builder.criteria; import com.github.sql.builder.model.Column; /** * Represents a <code>is null</code> predicate. * * @author Medhi * */ public class IsNullCriteria implements Criteria { /** * The column to apply the predicate to. */ private final Column column; /** * Constructor of {@link IsNullCriteria}. * * @param column * the {@link Column} */ public IsNullCriteria(Column column) { this.column = column; } @Override public void output(StringBuilder builder) { column.output(builder); builder.append(" is null"); } }
17.057143
49
0.664992
a8c8b1813935a889700e5ef82dbbdcd5537dc0cf
8,594
package com.comcast.pop.handler.executor.impl.progress.agenda; import com.comcast.pop.api.progress.AgendaProgress; import com.comcast.pop.api.progress.CompleteStateMessage; import com.comcast.pop.api.progress.OperationProgress; import com.comcast.pop.api.progress.ProcessingState; import com.comast.pop.handler.base.progress.reporter.BaseReporterThread; import org.apache.commons.lang3.StringUtils; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * Agenda progress threaded reporter */ public class AgendaProgressThread extends BaseReporterThread<AgendaProgressThreadConfig> implements AgendaProgressConsumer { // reporter thread fields (not to be used in other threads without adjusting the use of synchronized in this class) private AgendaProgressThreadConfig agendaProgressThreadConfig; private List<OperationProgress> operationProgressToReport = new LinkedList<>(); private boolean completeProgressSent = false; // cross thread fields private Set<OperationProgressProvider> operationProgressProviders = new HashSet<>(); private AgendaProgress agendaProgress; // operation percent completion tracking private int totalProgressOperationCount = 0; private int completedProgressOperationCount = 0; private double overallProgressPercentComplete = 0d; public AgendaProgressThread(AgendaProgressThreadConfig agendaProgressThreadConfig) { super(agendaProgressThreadConfig); this.agendaProgressThreadConfig = agendaProgressThreadConfig; } @Override protected boolean isThereProgressToReport() { return operationProgressToReport.size() > 0 || !completeProgressSent; } protected void resetOperationProgressToReport() { operationProgressToReport.clear(); } private synchronized AgendaProgress getAgendaProgress() { return agendaProgress; } @Override public synchronized void setAgendaProgress(AgendaProgress agendaProgress) { this.agendaProgress = agendaProgress; } @Override public synchronized void registerOperationProgressProvider(OperationProgressProvider operationProgressProvder) { this.operationProgressProviders.add(operationProgressProvder); } protected synchronized Set<OperationProgressProvider> getOperationProgressProviders() { return operationProgressProviders; } protected synchronized void setOperationProgressProviders(Set<OperationProgressProvider> operationProgressProviders) { this.operationProgressProviders = operationProgressProviders; } protected List<OperationProgress> getOperationProgressToReport() { return operationProgressToReport; } protected void setOperationProgressToReport(List<OperationProgress> operationProgressToReport) { this.operationProgressToReport = operationProgressToReport; } @Override protected synchronized void updateProgressItemsToReport() { if(operationProgressProviders == null || operationProgressProviders.size() == 0) return; List<OperationProgressProvider> operationProgressRetrieversToRemove = new LinkedList<>(); double incompleteOperationPercentTotal = 0; for(OperationProgressProvider opr : operationProgressProviders) { OperationProgress operationProgress = opr.retrieveOperationProgress(); if(operationProgress != null && operationProgress.getProcessingState() != null) { switch (operationProgress.getProcessingState()) { case EXECUTING: // remove any existing progress for the same op operationProgressToReport.removeIf(op -> StringUtils.equals(operationProgress.getOperation(), op.getOperation())); if(operationProgress.getPercentComplete() != null) { // protect against handlers saying percents over 100 incompleteOperationPercentTotal += Math.min(100d, operationProgress.getPercentComplete()); } operationProgressToReport.add(operationProgress); break; case COMPLETE: processCompleteOperationProgress(operationProgress); completedProgressOperationCount++; operationProgressToReport.removeIf(op -> StringUtils.equals(operationProgress.getOperation(), op.getOperation())); operationProgressToReport.add(operationProgress); // completed operations have no further progress to report operationProgressRetrieversToRemove.add(opr); break; } } } overallProgressPercentComplete = calculatePercentComplete(completedProgressOperationCount, totalProgressOperationCount, incompleteOperationPercentTotal); operationProgressRetrieversToRemove.forEach(opr -> operationProgressProviders.remove(opr)); } protected void processCompleteOperationProgress(OperationProgress operationProgress) { // complete + succeeded is always pushed to 100% if(StringUtils.equalsIgnoreCase(CompleteStateMessage.SUCCEEDED.toString(), operationProgress.getProcessingStateMessage())) { operationProgress.setPercentComplete(100d); } } // if this becomes any more complex break it into its own class protected static double calculatePercentComplete(int completedOperationCount, int totalOperationCount, double incompleteOperationPercentTotal) { return (totalOperationCount > 0) ? ((completedOperationCount * 100d) + incompleteOperationPercentTotal) / totalOperationCount : 0d; } @Override protected void reportProgress() { AgendaProgress agendaProgress = getAgendaProgress(); if(agendaProgress == null) return; // attach the latest progress value based on the operations agendaProgress.setPercentComplete(overallProgressPercentComplete); if(operationProgressToReport.size() > 0) { // TODO: do not set the agendaProgressId on the ops progress, make the progress endpoint deal with that agendaProgress.setOperationProgress(operationProgressToReport.toArray(new OperationProgress[0])); } if(agendaProgressThreadConfig.getRequireProgressId() && agendaProgress.getId() == null) { logger.warn("The AgendaProgress is unset. No update is being sent."); } else { logger.trace("Reporting progress here. LinkId:[" + agendaProgress.getLinkId() + "], agendaId: [" + agendaProgress.getAgendaId() + "], Id: [" + agendaProgress.getId() + "], Cid: [" + agendaProgress.getCid() + "]"); agendaProgressThreadConfig.getReporter().reportProgress(agendaProgress); } logger.debug( "Reported progress {} {}% for: {} with progress updates for ops: {}", agendaProgress.getProcessingState(), agendaProgress.getPercentComplete(), agendaProgress.getId(), operationProgressToReport == null ? null : operationProgressToReport.stream().map(OperationProgress::getOperation).collect(Collectors.joining(",")) ); if(agendaProgress.getProcessingState() == ProcessingState.COMPLETE) { completeProgressSent = true; } logger.debug("Clearing progress to report"); // on success we clear the op progress to report resetOperationProgressToReport(); } @Override public synchronized void setTotalProgressOperationCount(int totalProgressOperationCount) { this.totalProgressOperationCount = totalProgressOperationCount; } @Override public synchronized void adjustTotalProgressOperationCount(int operationTotalCountAdjustment) { setTotalProgressOperationCount(totalProgressOperationCount + operationTotalCountAdjustment); } @Override public synchronized void incrementCompletedOperationCount(int incrementAmount) { completedProgressOperationCount += incrementAmount; } @Override protected String getThreadName() { return "AgendaProgressThread"; } }
38.711712
161
0.691878
a5f1c48faff5016585eaa3b2febf6e057ce19ab2
12,235
/* * Copyright 2014-2015 Daniel Pedraza-Arcega * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.grayfox.server.dao; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Locale; import javax.inject.Inject; import com.grayfox.server.domain.Category; import com.grayfox.server.domain.Credential; import com.grayfox.server.domain.Location; import com.grayfox.server.domain.Poi; import com.grayfox.server.domain.Recommendation; import com.grayfox.server.domain.User; import com.grayfox.server.test.config.TestConfig; import com.grayfox.server.test.dao.jdbc.UtilJdbcDao; import com.grayfox.server.util.Messages; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; @Rollback @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestConfig.class) public class RecommendationDaoTest { @Inject private UtilJdbcDao utilJdbcDao; @Inject private CredentialDao credentialDao; @Inject private UserDao userDao; @Inject private RecommendationDao recommendationDao; @Before public void setUp() { assertThat(utilJdbcDao).isNotNull(); assertThat(credentialDao).isNotNull(); assertThat(userDao).isNotNull(); assertThat(recommendationDao).isNotNull(); } @Test @Transactional public void testFetchNearestByRating() { loadMockDataForFetchNearestByRating(); Category c = new Category(); c.setFoursquareId("1"); c.setIconUrl("url"); c.setName("CAT_1"); Poi p1 = new Poi(); p1.setFoursquareId("1"); p1.setFoursquareRating(9.2); p1.setLocation(Location.parse("19.044,-98.197753")); p1.setName("POI_1"); p1.setCategories(new HashSet<>(Arrays.asList(c))); Recommendation r1 = new Recommendation(); r1.setPoi(p1); r1.setType(Recommendation.Type.GLOBAL); r1.setReason(Messages.get("recommendation.global.reason")); List<Recommendation> expectedRecommendations = Arrays.asList(r1); List<Recommendation> actualRecommendations = recommendationDao.findNearestWithHighRating(Location.parse("19.043635,-98.197947"), 100, Locale.ROOT); assertThat(actualRecommendations).isNotNull().isNotEmpty().doesNotContainNull().hasSameSizeAs(expectedRecommendations).containsExactlyElementsOf(expectedRecommendations); } @Test @Transactional public void testFetchNearestByCategoriesLiked() { loadMockDataForFetchNearestByCategoriesLiked(); Category c1 = new Category(); c1.setFoursquareId("1"); c1.setIconUrl("url1"); c1.setName("CAT_1"); Category c3 = new Category(); c3.setFoursquareId("3"); c3.setIconUrl("url3"); c3.setName("CAT_3"); Poi p1 = new Poi(); p1.setFoursquareId("1"); p1.setFoursquareRating(9.2); p1.setLocation(Location.parse("19.044,-98.197753")); p1.setName("POI_1"); p1.setCategories(new HashSet<>(Arrays.asList(c1))); Poi p2 = new Poi(); p2.setFoursquareId("2"); p2.setFoursquareRating(8.5); p2.setLocation(Location.parse("19.043148,-98.198354")); p2.setName("POI_2"); p2.setCategories(new HashSet<>(Arrays.asList(c3))); Recommendation r1 = new Recommendation(); r1.setPoi(p1); r1.setType(Recommendation.Type.SELF); r1.setReason(Messages.get("recommendation.self.reason", c1.getName())); Recommendation r2 = new Recommendation(); r2.setPoi(p2); r2.setType(Recommendation.Type.SELF); r2.setReason(Messages.get("recommendation.self.reason", c3.getName())); List<Recommendation> expectedRecommendations = Arrays.asList(r1, r2); List<Recommendation> actualRecommendations = recommendationDao.findNearestByCategoriesLiked("fakeToken", Location.parse("19.043635,-98.197947"), 100, Locale.ROOT); assertThat(actualRecommendations).isNotNull().isNotEmpty().doesNotContainNull().hasSameSizeAs(expectedRecommendations).containsExactlyElementsOf(expectedRecommendations); } @Test @Transactional public void testFetchNearestByCategoriesLikedByFriends() { loadMockDataFetchNearestByCategoriesLikedByFriends(); Category c1 = new Category(); c1.setFoursquareId("1"); c1.setIconUrl("url1"); c1.setName("CAT_1"); Category c2 = new Category(); c2.setFoursquareId("2"); c2.setIconUrl("url2"); c2.setName("CAT_2"); Poi p1 = new Poi(); p1.setFoursquareId("1"); p1.setFoursquareRating(9.2); p1.setLocation(Location.parse("19.044,-98.197753")); p1.setName("POI_1"); p1.setCategories(new HashSet<>(Arrays.asList(c1))); Poi p3 = new Poi(); p3.setFoursquareId("3"); p3.setFoursquareRating(9d); p3.setLocation(Location.parse("19.04329,-98.197432")); p3.setName("POI_3"); p3.setCategories(new HashSet<>(Arrays.asList(c2))); Recommendation r1 = new Recommendation(); r1.setPoi(p1); r1.setType(Recommendation.Type.SOCIAL); r1.setReason(Messages.get("recommendation.social.reason", "John2 Doe2", c1.getName())); Recommendation r2 = new Recommendation(); r2.setPoi(p3); r2.setType(Recommendation.Type.SOCIAL); r2.setReason(Messages.get("recommendation.social.reason", "John3 Doe3", c2.getName())); List<Recommendation> expectedRecommendations = Arrays.asList(r1, r2); List<Recommendation> actualRecommendations = recommendationDao.findNearestByCategoriesLikedByFriends("fakeToken", Location.parse("19.043635,-98.197947"), 100, Locale.ROOT); assertThat(actualRecommendations).isNotNull().isNotEmpty().doesNotContainNull().hasSameSizeAs(expectedRecommendations).containsExactlyElementsOf(expectedRecommendations); } private void loadMockDataForFetchNearestByRating() { Category c = new Category(); c.setFoursquareId("1"); c.setIconUrl("url"); c.setName("CAT_1"); Poi p1 = new Poi(); p1.setFoursquareId("1"); p1.setFoursquareRating(9.2); p1.setLocation(Location.parse("19.044,-98.197753")); p1.setName("POI_1"); p1.setCategories(new HashSet<>(Arrays.asList(c))); Poi p2 = new Poi(); p2.setFoursquareId("2"); p2.setFoursquareRating(8.5); p2.setLocation(Location.parse("19.043148,-98.198354")); p2.setName("POI_2"); p2.setCategories(new HashSet<>(Arrays.asList(c))); Poi p3 = new Poi(); p3.setFoursquareId("3"); p3.setFoursquareRating(9d); p3.setLocation(Location.parse("19.04258,-98.190608")); p3.setName("POI_3"); p3.setCategories(new HashSet<>(Arrays.asList(c))); utilJdbcDao.saveCategory(c); utilJdbcDao.savePois(Arrays.asList(p1, p2, p3)); } private void loadMockDataForFetchNearestByCategoriesLiked() { Category c1 = new Category(); c1.setFoursquareId("1"); c1.setIconUrl("url1"); c1.setName("CAT_1"); Category c2 = new Category(); c2.setFoursquareId("2"); c2.setIconUrl("url2"); c2.setName("CAT_2"); Category c3 = new Category(); c3.setFoursquareId("3"); c3.setIconUrl("url3"); c3.setName("CAT_3"); Poi p1 = new Poi(); p1.setFoursquareId("1"); p1.setFoursquareRating(9.2); p1.setLocation(Location.parse("19.044,-98.197753")); p1.setName("POI_1"); p1.setCategories(new HashSet<>(Arrays.asList(c1))); Poi p2 = new Poi(); p2.setFoursquareId("2"); p2.setFoursquareRating(8.5); p2.setLocation(Location.parse("19.043148,-98.198354")); p2.setName("POI_2"); p2.setCategories(new HashSet<>(Arrays.asList(c3))); Poi p3 = new Poi(); p3.setFoursquareId("3"); p3.setFoursquareRating(9d); p3.setLocation(Location.parse("19.04258,-98.190608")); p3.setName("POI_3"); p3.setCategories(new HashSet<>(Arrays.asList(c2))); Poi p4 = new Poi(); p4.setFoursquareId("4"); p4.setFoursquareRating(9d); p4.setLocation(Location.parse("19.043983,-98.198805")); p4.setName("POI_4"); p4.setCategories(new HashSet<>(Arrays.asList(c1))); Credential c = new Credential(); c.setAccessToken("fakeToken"); User u = new User(); u.setFoursquareId("1"); u.setName("John"); u.setLastName("Doe"); u.setPhotoUrl("url"); u.setCredential(c); u.setLikes(new HashSet<>(Arrays.asList(c1, c2, c3))); utilJdbcDao.saveCategories(Arrays.asList(c1, c2, c3)); utilJdbcDao.savePois(Arrays.asList(p1, p2, p3, p4)); credentialDao.save(c); userDao.save(u); } private void loadMockDataFetchNearestByCategoriesLikedByFriends() { Category c1 = new Category(); c1.setFoursquareId("1"); c1.setIconUrl("url1"); c1.setName("CAT_1"); Category c2 = new Category(); c2.setFoursquareId("2"); c2.setIconUrl("url2"); c2.setName("CAT_2"); Category c3 = new Category(); c3.setFoursquareId("3"); c3.setIconUrl("url3"); c3.setName("CAT_3"); Poi p1 = new Poi(); p1.setFoursquareId("1"); p1.setFoursquareRating(9.2); p1.setLocation(Location.parse("19.044,-98.197753")); p1.setName("POI_1"); p1.setCategories(new HashSet<>(Arrays.asList(c1))); Poi p2 = new Poi(); p2.setFoursquareId("2"); p2.setFoursquareRating(8.5); p2.setLocation(Location.parse("19.043148,-98.198354")); p2.setName("POI_2"); p2.setCategories(new HashSet<>(Arrays.asList(c3))); Poi p3 = new Poi(); p3.setFoursquareId("3"); p3.setFoursquareRating(9d); p3.setLocation(Location.parse("19.04329,-98.197432")); p3.setName("POI_3"); p3.setCategories(new HashSet<>(Arrays.asList(c2))); Poi p4 = new Poi(); p4.setFoursquareId("4"); p4.setFoursquareRating(9d); p4.setLocation(Location.parse("19.043983,-98.198805")); p4.setName("POI_4"); p4.setCategories(new HashSet<>(Arrays.asList(c1))); Credential c = new Credential(); c.setAccessToken("fakeToken"); User f1 = new User(); f1.setFoursquareId("2"); f1.setName("John2"); f1.setLastName("Doe2"); f1.setPhotoUrl("url2"); f1.setLikes(new HashSet<>(Arrays.asList(c1, c2))); User f2 = new User(); f2.setFoursquareId("3"); f2.setName("John3"); f2.setLastName("Doe3"); f2.setPhotoUrl("url3"); f2.setLikes(new HashSet<>(Arrays.asList(c2))); User u = new User(); u.setFoursquareId("1"); u.setName("John1"); u.setLastName("Doe1"); u.setPhotoUrl("url1"); u.setCredential(c); u.setLikes(new HashSet<>(Arrays.asList(c3))); u.setFriends(new HashSet<>(Arrays.asList(f1, f2))); utilJdbcDao.saveCategories(Arrays.asList(c1, c2, c3)); utilJdbcDao.savePois(Arrays.asList(p1, p2, p3, p4)); credentialDao.save(c); userDao.save(u); } }
35.057307
180
0.642501
ee2e3eee8481e3fc8b3ff9bedb733f75f1f9c361
30,721
/** * Copyright (C) 2010-2012 eBusiness Information, Excilys Group * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed To in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.androidannotations; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Map; import java.util.Set; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import org.androidannotations.annotationprocessor.AnnotatedAbstractProcessor; import org.androidannotations.annotationprocessor.SupportedAnnotationClasses; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.AfterTextChange; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.App; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.BeforeTextChange; import org.androidannotations.annotations.Click; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.EApplication; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.EProvider; import org.androidannotations.annotations.EReceiver; import org.androidannotations.annotations.EService; import org.androidannotations.annotations.EView; import org.androidannotations.annotations.EViewGroup; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.FragmentArg; import org.androidannotations.annotations.FragmentById; import org.androidannotations.annotations.FragmentByTag; import org.androidannotations.annotations.FromHtml; import org.androidannotations.annotations.Fullscreen; import org.androidannotations.annotations.HttpsClient; import org.androidannotations.annotations.InstanceState; import org.androidannotations.annotations.ItemClick; import org.androidannotations.annotations.ItemLongClick; import org.androidannotations.annotations.ItemSelect; import org.androidannotations.annotations.LongClick; import org.androidannotations.annotations.NoTitle; import org.androidannotations.annotations.NonConfigurationInstance; import org.androidannotations.annotations.OnActivityResult; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.OptionsMenu; import org.androidannotations.annotations.OrmLiteDao; import org.androidannotations.annotations.RoboGuice; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.SeekBarProgressChange; import org.androidannotations.annotations.SeekBarTouchStart; import org.androidannotations.annotations.SeekBarTouchStop; import org.androidannotations.annotations.SystemService; import org.androidannotations.annotations.TextChange; import org.androidannotations.annotations.Touch; import org.androidannotations.annotations.Trace; import org.androidannotations.annotations.Transactional; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import org.androidannotations.annotations.res.AnimationRes; import org.androidannotations.annotations.res.BooleanRes; import org.androidannotations.annotations.res.ColorRes; import org.androidannotations.annotations.res.ColorStateListRes; import org.androidannotations.annotations.res.DimensionPixelOffsetRes; import org.androidannotations.annotations.res.DimensionPixelSizeRes; import org.androidannotations.annotations.res.DimensionRes; import org.androidannotations.annotations.res.DrawableRes; import org.androidannotations.annotations.res.HtmlRes; import org.androidannotations.annotations.res.IntArrayRes; import org.androidannotations.annotations.res.IntegerRes; import org.androidannotations.annotations.res.LayoutRes; import org.androidannotations.annotations.res.MovieRes; import org.androidannotations.annotations.res.StringArrayRes; import org.androidannotations.annotations.res.StringRes; import org.androidannotations.annotations.res.TextArrayRes; import org.androidannotations.annotations.res.TextRes; import org.androidannotations.annotations.rest.Accept; import org.androidannotations.annotations.rest.Delete; import org.androidannotations.annotations.rest.Get; import org.androidannotations.annotations.rest.Head; import org.androidannotations.annotations.rest.Options; import org.androidannotations.annotations.rest.Post; import org.androidannotations.annotations.rest.Put; import org.androidannotations.annotations.rest.Rest; import org.androidannotations.annotations.rest.RestService; import org.androidannotations.annotations.sharedpreferences.Pref; import org.androidannotations.annotations.sharedpreferences.SharedPref; import org.androidannotations.generation.CodeModelGenerator; import org.androidannotations.helper.AndroidManifest; import org.androidannotations.helper.AndroidManifestFinder; import org.androidannotations.helper.Option; import org.androidannotations.helper.TimeStats; import org.androidannotations.model.AndroidRes; import org.androidannotations.model.AndroidSystemServices; import org.androidannotations.model.AnnotationElements; import org.androidannotations.model.AnnotationElementsHolder; import org.androidannotations.model.ModelExtractor; import org.androidannotations.processing.AfterInjectProcessor; import org.androidannotations.processing.AfterTextChangeProcessor; import org.androidannotations.processing.AfterViewsProcessor; import org.androidannotations.processing.AppProcessor; import org.androidannotations.processing.BackgroundProcessor; import org.androidannotations.processing.BeanProcessor; import org.androidannotations.processing.BeforeTextChangeProcessor; import org.androidannotations.processing.ClickProcessor; import org.androidannotations.processing.EActivityProcessor; import org.androidannotations.processing.EApplicationProcessor; import org.androidannotations.processing.EBeanProcessor; import org.androidannotations.processing.EFragmentProcessor; import org.androidannotations.processing.EProviderProcessor; import org.androidannotations.processing.EReceiverProcessor; import org.androidannotations.processing.EServiceProcessor; import org.androidannotations.processing.EViewGroupProcessor; import org.androidannotations.processing.EViewProcessor; import org.androidannotations.processing.ExtraProcessor; import org.androidannotations.processing.FragmentArgProcessor; import org.androidannotations.processing.FragmentByIdProcessor; import org.androidannotations.processing.FragmentByTagProcessor; import org.androidannotations.processing.FromHtmlProcessor; import org.androidannotations.processing.FullscreenProcessor; import org.androidannotations.processing.HttpsClientProcessor; import org.androidannotations.processing.InstanceStateProcessor; import org.androidannotations.processing.ItemClickProcessor; import org.androidannotations.processing.ItemLongClickProcessor; import org.androidannotations.processing.ItemSelectedProcessor; import org.androidannotations.processing.LongClickProcessor; import org.androidannotations.processing.ModelProcessor; import org.androidannotations.processing.ModelProcessor.ProcessResult; import org.androidannotations.processing.NoTitleProcessor; import org.androidannotations.processing.NonConfigurationInstanceProcessor; import org.androidannotations.processing.OnActivityResultProcessor; import org.androidannotations.processing.OptionsItemProcessor; import org.androidannotations.processing.OptionsMenuProcessor; import org.androidannotations.processing.OrmLiteDaoProcessor; import org.androidannotations.processing.PrefProcessor; import org.androidannotations.processing.ResProcessor; import org.androidannotations.processing.RestServiceProcessor; import org.androidannotations.processing.RoboGuiceProcessor; import org.androidannotations.processing.RootContextProcessor; import org.androidannotations.processing.SeekBarProgressChangeProcessor; import org.androidannotations.processing.SeekBarTouchStartProcessor; import org.androidannotations.processing.SeekBarTouchStopProcessor; import org.androidannotations.processing.SharedPrefProcessor; import org.androidannotations.processing.SystemServiceProcessor; import org.androidannotations.processing.TextChangeProcessor; import org.androidannotations.processing.TouchProcessor; import org.androidannotations.processing.TraceProcessor; import org.androidannotations.processing.TransactionalProcessor; import org.androidannotations.processing.UiThreadProcessor; import org.androidannotations.processing.ViewByIdProcessor; import org.androidannotations.processing.rest.DeleteProcessor; import org.androidannotations.processing.rest.GetProcessor; import org.androidannotations.processing.rest.HeadProcessor; import org.androidannotations.processing.rest.OptionsProcessor; import org.androidannotations.processing.rest.PostProcessor; import org.androidannotations.processing.rest.PutProcessor; import org.androidannotations.processing.rest.RestImplementationsHolder; import org.androidannotations.processing.rest.RestProcessor; import org.androidannotations.rclass.AndroidRClassFinder; import org.androidannotations.rclass.CoumpoundRClass; import org.androidannotations.rclass.IRClass; import org.androidannotations.rclass.ProjectRClassFinder; import org.androidannotations.validation.AfterInjectValidator; import org.androidannotations.validation.AfterTextChangeValidator; import org.androidannotations.validation.AfterViewsValidator; import org.androidannotations.validation.AppValidator; import org.androidannotations.validation.BeanValidator; import org.androidannotations.validation.BeforeTextChangeValidator; import org.androidannotations.validation.ClickValidator; import org.androidannotations.validation.EActivityValidator; import org.androidannotations.validation.EApplicationValidator; import org.androidannotations.validation.EBeanValidator; import org.androidannotations.validation.EFragmentValidator; import org.androidannotations.validation.EProviderValidator; import org.androidannotations.validation.EReceiverValidator; import org.androidannotations.validation.EServiceValidator; import org.androidannotations.validation.EViewGroupValidator; import org.androidannotations.validation.EViewValidator; import org.androidannotations.validation.ExtraValidator; import org.androidannotations.validation.FragmentArgValidator; import org.androidannotations.validation.FragmentByIdValidator; import org.androidannotations.validation.FragmentByTagValidator; import org.androidannotations.validation.FromHtmlValidator; import org.androidannotations.validation.FullscreenValidator; import org.androidannotations.validation.HttpsClientValidator; import org.androidannotations.validation.InstanceStateValidator; import org.androidannotations.validation.ItemClickValidator; import org.androidannotations.validation.ItemLongClickValidator; import org.androidannotations.validation.ItemSelectedValidator; import org.androidannotations.validation.LongClickValidator; import org.androidannotations.validation.ModelValidator; import org.androidannotations.validation.NoTitleValidator; import org.androidannotations.validation.NonConfigurationInstanceValidator; import org.androidannotations.validation.OnActivityResultValidator; import org.androidannotations.validation.OptionsItemValidator; import org.androidannotations.validation.OptionsMenuValidator; import org.androidannotations.validation.OrmLiteDaoValidator; import org.androidannotations.validation.PrefValidator; import org.androidannotations.validation.ResValidator; import org.androidannotations.validation.RestServiceValidator; import org.androidannotations.validation.RoboGuiceValidator; import org.androidannotations.validation.RootContextValidator; import org.androidannotations.validation.RunnableValidator; import org.androidannotations.validation.SeekBarProgressChangeValidator; import org.androidannotations.validation.SeekBarTouchStartValidator; import org.androidannotations.validation.SeekBarTouchStopValidator; import org.androidannotations.validation.SharedPrefValidator; import org.androidannotations.validation.SystemServiceValidator; import org.androidannotations.validation.TextChangeValidator; import org.androidannotations.validation.TouchValidator; import org.androidannotations.validation.TraceValidator; import org.androidannotations.validation.TransactionalValidator; import org.androidannotations.validation.ViewByIdValidator; import org.androidannotations.validation.rest.AcceptValidator; import org.androidannotations.validation.rest.DeleteValidator; import org.androidannotations.validation.rest.GetValidator; import org.androidannotations.validation.rest.HeadValidator; import org.androidannotations.validation.rest.OptionsValidator; import org.androidannotations.validation.rest.PostValidator; import org.androidannotations.validation.rest.PutValidator; import org.androidannotations.validation.rest.RestValidator; @SupportedAnnotationClasses({ EActivity.class, // App.class, // EViewGroup.class, // EView.class, // AfterViews.class, // RoboGuice.class, // ViewById.class, // Click.class, // LongClick.class, // ItemClick.class, // ItemLongClick.class, // Touch.class, // ItemSelect.class, // UiThread.class, // Transactional.class, // Background.class, // Extra.class, // SystemService.class, // SharedPref.class, // Pref.class, // StringRes.class, // ColorRes.class, // AnimationRes.class, // BooleanRes.class, // ColorStateListRes.class, // DimensionRes.class, // DimensionPixelOffsetRes.class, // DimensionPixelSizeRes.class, // DrawableRes.class, // IntArrayRes.class, // IntegerRes.class, // LayoutRes.class, // MovieRes.class, // TextRes.class, // TextArrayRes.class, // StringArrayRes.class, // Rest.class, // Get.class, // Head.class, // Options.class, // Post.class, // Put.class, // Delete.class, // Accept.class, // FromHtml.class, // OptionsMenu.class, // OptionsItem.class, // HtmlRes.class, // NoTitle.class, // Fullscreen.class, // RestService.class, // EBean.class, // RootContext.class, // Bean.class, // AfterInject.class, // EService.class, // EReceiver.class, // EProvider.class, // Trace.class, // InstanceState.class, // NonConfigurationInstance.class, // EApplication.class, // EFragment.class, // FragmentById.class, // FragmentByTag.class, // BeforeTextChange.class, // TextChange.class, // SeekBarProgressChange.class, // SeekBarTouchStart.class, // SeekBarTouchStop.class, // AfterTextChange.class, // OrmLiteDao.class, // HttpsClient.class, // FragmentArg.class, // OnActivityResult.class // }) @SupportedSourceVersion(SourceVersion.RELEASE_6) public class AndroidAnnotationProcessor extends AnnotatedAbstractProcessor { private final TimeStats timeStats = new TimeStats(); @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); Messager messager = processingEnv.getMessager(); timeStats.setMessager(messager); messager.printMessage(Diagnostic.Kind.NOTE, "Starting AndroidAnnotations annotation processing"); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { timeStats.clear(); timeStats.start("Whole Processing"); try { processThrowing(annotations, roundEnv); } catch (Exception e) { handleException(annotations, roundEnv, e); } timeStats.stop("Whole Processing"); timeStats.logStats(); return true; } private void processThrowing(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws Exception { if (nothingToDo(annotations, roundEnv)) { return; } AnnotationElementsHolder extractedModel = extractAnnotations(annotations, roundEnv); Option<AndroidManifest> androidManifestOption = extractAndroidManifest(); if (androidManifestOption.isAbsent()) { return; } AndroidManifest androidManifest = androidManifestOption.get(); Option<IRClass> rClassOption = findRClasses(androidManifest); if (rClassOption.isAbsent()) { return; } IRClass rClass = rClassOption.get(); AndroidSystemServices androidSystemServices = new AndroidSystemServices(); AnnotationElements validatedModel = validateAnnotations(extractedModel, rClass, androidSystemServices, androidManifest); ProcessResult processResult = processAnnotations(validatedModel, rClass, androidSystemServices, androidManifest); generateSources(processResult); } private boolean nothingToDo(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { return roundEnv.processingOver() || annotations.size() == 0; } private AnnotationElementsHolder extractAnnotations(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { timeStats.start("Extract Annotations"); ModelExtractor modelExtractor = new ModelExtractor(processingEnv, getSupportedAnnotationClasses()); AnnotationElementsHolder extractedModel = modelExtractor.extract(annotations, roundEnv); timeStats.stop("Extract Annotations"); return extractedModel; } private Option<AndroidManifest> extractAndroidManifest() { timeStats.start("Extract Manifest"); AndroidManifestFinder finder = new AndroidManifestFinder(processingEnv); Option<AndroidManifest> manifest = finder.extractAndroidManifest(); timeStats.stop("Extract Manifest"); return manifest; } private Option<IRClass> findRClasses(AndroidManifest androidManifest) throws IOException { timeStats.start("Find R Classes"); ProjectRClassFinder rClassFinder = new ProjectRClassFinder(processingEnv); Option<IRClass> rClass = rClassFinder.find(androidManifest); AndroidRClassFinder androidRClassFinder = new AndroidRClassFinder(processingEnv); Option<IRClass> androidRClass = androidRClassFinder.find(); if (rClass.isAbsent() || androidRClass.isAbsent()) { return Option.absent(); } IRClass coumpoundRClass = new CoumpoundRClass(rClass.get(), androidRClass.get()); timeStats.stop("Find R Classes"); return Option.of(coumpoundRClass); } private AnnotationElements validateAnnotations(AnnotationElementsHolder extractedModel, IRClass rClass, AndroidSystemServices androidSystemServices, AndroidManifest androidManifest) { timeStats.start("Validate Annotations"); ModelValidator modelValidator = buildModelValidator(rClass, androidSystemServices, androidManifest); AnnotationElements validatedAnnotations = modelValidator.validate(extractedModel); timeStats.stop("Validate Annotations"); return validatedAnnotations; } private ModelValidator buildModelValidator(IRClass rClass, AndroidSystemServices androidSystemServices, AndroidManifest androidManifest) { ModelValidator modelValidator = new ModelValidator(); modelValidator.register(new EApplicationValidator(processingEnv, androidManifest)); modelValidator.register(new EActivityValidator(processingEnv, rClass, androidManifest)); modelValidator.register(new EServiceValidator(processingEnv, androidManifest)); modelValidator.register(new EReceiverValidator(processingEnv, androidManifest)); modelValidator.register(new EProviderValidator(processingEnv, androidManifest)); modelValidator.register(new EFragmentValidator(processingEnv, rClass)); modelValidator.register(new EViewGroupValidator(processingEnv, rClass)); modelValidator.register(new EViewValidator(processingEnv)); modelValidator.register(new EBeanValidator(processingEnv)); modelValidator.register(new RoboGuiceValidator(processingEnv)); modelValidator.register(new ViewByIdValidator(processingEnv, rClass)); modelValidator.register(new FragmentByIdValidator(processingEnv, rClass)); modelValidator.register(new FragmentByTagValidator(processingEnv)); modelValidator.register(new FromHtmlValidator(processingEnv, rClass)); modelValidator.register(new ClickValidator(processingEnv, rClass)); modelValidator.register(new LongClickValidator(processingEnv, rClass)); modelValidator.register(new TouchValidator(processingEnv, rClass)); modelValidator.register(new ItemClickValidator(processingEnv, rClass)); modelValidator.register(new ItemSelectedValidator(processingEnv, rClass)); modelValidator.register(new ItemLongClickValidator(processingEnv, rClass)); for (AndroidRes androidRes : AndroidRes.values()) { modelValidator.register(new ResValidator(androidRes, processingEnv, rClass)); } modelValidator.register(new TransactionalValidator(processingEnv)); modelValidator.register(new ExtraValidator(processingEnv)); modelValidator.register(new FragmentArgValidator(processingEnv)); modelValidator.register(new SystemServiceValidator(processingEnv, androidSystemServices)); modelValidator.register(new SharedPrefValidator(processingEnv)); modelValidator.register(new PrefValidator(processingEnv)); modelValidator.register(new RestValidator(processingEnv)); modelValidator.register(new DeleteValidator(processingEnv)); modelValidator.register(new GetValidator(processingEnv)); modelValidator.register(new HeadValidator(processingEnv)); modelValidator.register(new OptionsValidator(processingEnv)); modelValidator.register(new PostValidator(processingEnv)); modelValidator.register(new PutValidator(processingEnv)); modelValidator.register(new AcceptValidator(processingEnv)); modelValidator.register(new AppValidator(processingEnv, androidManifest)); modelValidator.register(new OptionsMenuValidator(processingEnv, rClass)); modelValidator.register(new OptionsItemValidator(processingEnv, rClass)); modelValidator.register(new NoTitleValidator(processingEnv)); modelValidator.register(new FullscreenValidator(processingEnv)); modelValidator.register(new RestServiceValidator(processingEnv)); modelValidator.register(new RootContextValidator(processingEnv)); modelValidator.register(new NonConfigurationInstanceValidator(processingEnv)); modelValidator.register(new BeanValidator(processingEnv)); modelValidator.register(new AfterInjectValidator(processingEnv)); modelValidator.register(new BeforeTextChangeValidator(processingEnv, rClass)); modelValidator.register(new TextChangeValidator(processingEnv, rClass)); modelValidator.register(new AfterTextChangeValidator(processingEnv, rClass)); modelValidator.register(new SeekBarProgressChangeValidator(processingEnv, rClass)); modelValidator.register(new SeekBarTouchStartValidator(processingEnv, rClass)); modelValidator.register(new SeekBarTouchStopValidator(processingEnv, rClass)); /* * Any view injection or listener binding should occur before * AfterViewsValidator */ modelValidator.register(new AfterViewsValidator(processingEnv)); modelValidator.register(new TraceValidator(processingEnv)); modelValidator.register(new RunnableValidator(UiThread.class, processingEnv)); modelValidator.register(new RunnableValidator(Background.class, processingEnv)); modelValidator.register(new InstanceStateValidator(processingEnv)); modelValidator.register(new OrmLiteDaoValidator(processingEnv, rClass)); modelValidator.register(new HttpsClientValidator(processingEnv, rClass)); modelValidator.register(new OnActivityResultValidator(processingEnv, rClass)); return modelValidator; } private boolean traceActivated() { Map<String, String> options = processingEnv.getOptions(); if (options.containsKey("trace")) { String trace = options.get("trace"); return !"false".equals(trace); } else { return true; } } private ProcessResult processAnnotations(AnnotationElements validatedModel, IRClass rClass, AndroidSystemServices androidSystemServices, AndroidManifest androidManifest) throws Exception { timeStats.start("Process Annotations"); ModelProcessor modelProcessor = buildModelProcessor(rClass, androidSystemServices, androidManifest, validatedModel); ProcessResult processResult = modelProcessor.process(validatedModel); timeStats.stop("Process Annotations"); return processResult; } private ModelProcessor buildModelProcessor(IRClass rClass, AndroidSystemServices androidSystemServices, AndroidManifest androidManifest, AnnotationElements validatedModel) { ModelProcessor modelProcessor = new ModelProcessor(); modelProcessor.register(new EApplicationProcessor()); modelProcessor.register(new EActivityProcessor(processingEnv, rClass)); modelProcessor.register(new EServiceProcessor()); modelProcessor.register(new EReceiverProcessor()); modelProcessor.register(new EProviderProcessor()); modelProcessor.register(new EFragmentProcessor(processingEnv, rClass)); modelProcessor.register(new EViewGroupProcessor(processingEnv, rClass)); modelProcessor.register(new EViewProcessor()); modelProcessor.register(new EBeanProcessor()); modelProcessor.register(new SharedPrefProcessor()); modelProcessor.register(new PrefProcessor(validatedModel)); modelProcessor.register(new RoboGuiceProcessor()); modelProcessor.register(new ViewByIdProcessor(processingEnv, rClass)); modelProcessor.register(new FragmentByIdProcessor(processingEnv, rClass)); modelProcessor.register(new FragmentByTagProcessor(processingEnv)); modelProcessor.register(new FromHtmlProcessor(processingEnv, rClass)); modelProcessor.register(new ClickProcessor(processingEnv, rClass)); modelProcessor.register(new LongClickProcessor(processingEnv, rClass)); modelProcessor.register(new TouchProcessor(processingEnv, rClass)); modelProcessor.register(new ItemClickProcessor(processingEnv, rClass)); modelProcessor.register(new ItemSelectedProcessor(processingEnv, rClass)); modelProcessor.register(new ItemLongClickProcessor(processingEnv, rClass)); for (AndroidRes androidRes : AndroidRes.values()) { modelProcessor.register(new ResProcessor(processingEnv, androidRes, rClass)); } modelProcessor.register(new TransactionalProcessor()); modelProcessor.register(new ExtraProcessor(processingEnv)); modelProcessor.register(new FragmentArgProcessor(processingEnv)); modelProcessor.register(new SystemServiceProcessor(androidSystemServices)); RestImplementationsHolder restImplementationHolder = new RestImplementationsHolder(); modelProcessor.register(new RestProcessor(processingEnv, restImplementationHolder)); modelProcessor.register(new GetProcessor(processingEnv, restImplementationHolder)); modelProcessor.register(new PostProcessor(processingEnv, restImplementationHolder)); modelProcessor.register(new PutProcessor(processingEnv, restImplementationHolder)); modelProcessor.register(new DeleteProcessor(processingEnv, restImplementationHolder)); modelProcessor.register(new HeadProcessor(processingEnv, restImplementationHolder)); modelProcessor.register(new OptionsProcessor(processingEnv, restImplementationHolder)); modelProcessor.register(new AppProcessor()); modelProcessor.register(new OptionsMenuProcessor(processingEnv, rClass)); modelProcessor.register(new OptionsItemProcessor(processingEnv, rClass)); modelProcessor.register(new NoTitleProcessor()); modelProcessor.register(new FullscreenProcessor()); modelProcessor.register(new RestServiceProcessor()); modelProcessor.register(new OrmLiteDaoProcessor(processingEnv)); modelProcessor.register(new RootContextProcessor()); modelProcessor.register(new NonConfigurationInstanceProcessor(processingEnv)); modelProcessor.register(new BeanProcessor(processingEnv)); modelProcessor.register(new BeforeTextChangeProcessor(processingEnv, rClass)); modelProcessor.register(new TextChangeProcessor(processingEnv, rClass)); modelProcessor.register(new AfterTextChangeProcessor(processingEnv, rClass)); modelProcessor.register(new SeekBarProgressChangeProcessor(processingEnv, rClass)); modelProcessor.register(new SeekBarTouchStartProcessor(processingEnv, rClass)); modelProcessor.register(new SeekBarTouchStopProcessor(processingEnv, rClass)); /* * Any view injection or listener binding should occur before * AfterViewsProcessor */ modelProcessor.register(new AfterViewsProcessor()); if (traceActivated()) { modelProcessor.register(new TraceProcessor()); } modelProcessor.register(new UiThreadProcessor()); modelProcessor.register(new BackgroundProcessor()); modelProcessor.register(new AfterInjectProcessor()); modelProcessor.register(new InstanceStateProcessor(processingEnv)); modelProcessor.register(new HttpsClientProcessor(rClass)); modelProcessor.register(new OnActivityResultProcessor(processingEnv, rClass)); return modelProcessor; } private void generateSources(ProcessResult processResult) throws IOException { timeStats.start("Generate Sources"); Messager messager = processingEnv.getMessager(); messager.printMessage(Diagnostic.Kind.NOTE, "Number of files generated by AndroidAnnotations: " + processResult.codeModel.countArtifacts()); CodeModelGenerator modelGenerator = new CodeModelGenerator(processingEnv.getFiler(), messager); modelGenerator.generate(processResult); timeStats.stop("Generate Sources"); } private void handleException(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv, Exception e) { String errorMessage = "Unexpected error. Please report an issue on AndroidAnnotations, with the following content: " + stackTraceToString(e); Messager messager = processingEnv.getMessager(); messager.printMessage(Diagnostic.Kind.ERROR, errorMessage); /* * Printing exception as an error on a random element. The exception is * not related to this element, but otherwise it wouldn't show up in * eclipse. */ Element element = roundEnv.getElementsAnnotatedWith(annotations.iterator().next()).iterator().next(); messager.printMessage(Diagnostic.Kind.ERROR, errorMessage, element); } private String stackTraceToString(Throwable e) { StringWriter writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); e.printStackTrace(pw); return writer.toString(); } }
49.1536
189
0.839589
b026a552a82ab0edb29e7169a3c090c823540229
2,297
import arc.util.*; import mindustry.Vars; import mindustry.game.Team; import mindustry.gen.*; import mindustry.mod.Mod; import mindustry.world.*; public class blockPlace extends Mod { @Override public void registerClientCommands(CommandHandler handler){ handler.<Player>register( "place", "<block> <team> <x> <y>", "Place blocks", (args, player) ->{ if(!player.admin){ player.sendMessage("[red]You are not admin"); return; } Block sblock = Vars.content.blocks(). find(b -> b.name.equals(args[0])); int xx; int yy; try { xx = Integer.parseInt(args[2]); } catch (NumberFormatException e) { player.sendMessage("[red]X must be number!"); return; } try { yy = Integer.parseInt(args[3]); } catch (NumberFormatException e) { player.sendMessage("[red]Y must be number!"); return; } Team tteam; switch (args[1]) { case "sharded": tteam = Team.sharded; break; case "blue": tteam = Team.blue; break; case "crux": tteam = Team.crux; break; case "derelict": tteam = Team.derelict; break; case "green": tteam = Team.green; break; case "purple": tteam = Team.purple; break; default: player.sendMessage("[accent]Teams: [yellow]sharded[], [blue]blue[], [red]crux[], [gray]derelict[], [green]green[], [purple]purple[]."); return; } if (sblock != null) { Vars.world.tile(xx,yy).setNet(sblock,tteam,0); player.sendMessage("[royal]You are placing" + " " +"[accent]"+sblock + " " + "[green]for" + " " +"[accent]"+tteam + " " + "[royal]team at "+xx+","+yy); } else { player.sendMessage("[red]You may select a Block."); } }); } }
32.814286
167
0.447105
013c8501e53b12f5ca27a35a1a9567f60334f338
2,542
// Copyright (C) 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.pgm; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.gerrit.pgm.init.InitPlugins.JAR; import static com.google.gerrit.pgm.init.InitPlugins.PLUGIN_DIR; import com.google.common.flogger.FluentLogger; import com.google.gerrit.launcher.GerritLauncher; import com.google.gerrit.pgm.init.PluginsDistribution; import com.google.inject.Singleton; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @Singleton public class WarDistribution implements PluginsDistribution { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Override public void foreach(Processor processor) throws IOException { File myWar = GerritLauncher.getDistributionArchive(); if (myWar.isFile()) { try (ZipFile zf = new ZipFile(myWar)) { for (ZipEntry ze : entriesOf(zf)) { if (ze.isDirectory()) { continue; } if (ze.getName().startsWith(PLUGIN_DIR) && ze.getName().endsWith(JAR)) { String pluginJarName = new File(ze.getName()).getName(); String pluginName = pluginJarName.substring(0, pluginJarName.length() - JAR.length()); try (InputStream in = zf.getInputStream(ze)) { processor.process(pluginName, in); } catch (IOException ioe) { logger.atSevere().log("Error opening plugin %s: %s", ze.getName(), ioe.getMessage()); } } } } } } @Override public List<String> listPluginNames() throws FileNotFoundException { // not yet used throw new UnsupportedOperationException(); } private static Iterable<? extends ZipEntry> entriesOf(ZipFile zipFile) { return zipFile.stream().collect(toImmutableList()); } }
35.802817
99
0.709284
c8fa216eb5d6407b228077a4cd548cbe8d427920
774
/* Copyright © 2021, SAS Institute Inc., Cary, NC, USA. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.sas.ci360.agent.errors; import org.json.JSONObject; public class FailedEvent { private JSONObject event; private int retryCount; public FailedEvent(JSONObject jsonEvent, int retryCount) { this.event = jsonEvent; this.retryCount = retryCount; } public FailedEvent(JSONObject event) { this(event, 0); } public JSONObject getEvent() { return event; } public void setEvent(JSONObject event) { this.event = event; } public int getRetryCount() { return retryCount; } public void setRetryCount(int retryCount) { this.retryCount = retryCount; } public void incrementRetryCount() { this.retryCount++; } }
18.428571
77
0.717054
3ed8a4bc1ca72b8b22f265b453ab4101f91b6054
8,134
/******************************************************************************* * Copyright 2012-2019 Phil Glover and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package org.pitest.pitclipse.launch; import static org.pitest.pitclipse.core.PitCoreActivator.getDefault; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jdt.core.IClasspathAttribute; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.junit.JUnitCore; import org.eclipse.jdt.launching.JavaLaunchDelegate; import org.pitest.pitclipse.core.extension.handler.ExtensionPointHandler; import org.pitest.pitclipse.core.extension.point.PitRuntimeOptions; import org.pitest.pitclipse.launch.config.ClassFinder; import org.pitest.pitclipse.launch.config.LaunchConfigurationWrapper; import org.pitest.pitclipse.launch.config.PackageFinder; import org.pitest.pitclipse.launch.config.ProjectFinder; import org.pitest.pitclipse.launch.config.SourceDirFinder; import org.pitest.pitclipse.runner.PitOptions; import org.pitest.pitclipse.runner.PitOptions.PitOptionsBuilder; import org.pitest.pitclipse.runner.PitRunner; import org.pitest.pitclipse.runner.config.PitConfiguration; import org.pitest.pitclipse.runner.io.SocketProvider; import com.google.common.collect.ImmutableList; /** * <p>Abstract launch configuration used to execute PIT in a background VM.</p> * * <p>Pitest is executed by calling {@link PitRunner#main(String[])}.</p> * * <p>Right after the VM has been launched, contributions to the {@code results} * extension points are notified thanks to {@link ExtensionPointHandler}.</p> */ public abstract class AbstractPitLaunchDelegate extends JavaLaunchDelegate { private static final String EXTENSION_POINT_ID = "org.pitest.pitclipse.core.executePit"; private static final String PIT_RUNNER = PitRunner.class.getCanonicalName(); private int portNumber; private final PitConfiguration pitConfiguration; private boolean projectUsesJunit5 = false; public AbstractPitLaunchDelegate(PitConfiguration pitConfiguration) { this.pitConfiguration = pitConfiguration; } protected void generatePortNumber() { portNumber = new SocketProvider().getFreePort(); } @Override public String getMainTypeName(ILaunchConfiguration launchConfig) throws CoreException { return PIT_RUNNER; } @Override public String[] getClasspath(ILaunchConfiguration launchConfig) throws CoreException { ImmutableList.Builder<String> builder = ImmutableList.<String>builder() .addAll(getDefault().getPitClasspath()); builder.addAll(ImmutableList.copyOf(super.getClasspath(launchConfig))); if (projectUsesJunit5) { // Allow Pitest to detect Junit5 tests builder.addAll(getDefault().getPitestJunit5PluginClasspath()); } List<String> newClasspath = builder.build(); return newClasspath.toArray(new String[newClasspath.size()]); } @Override public String getProgramArguments(ILaunchConfiguration launchConfig) throws CoreException { return new StringBuilder(super.getProgramArguments(launchConfig)).append(' ').append(portNumber).toString(); } @Override public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { generatePortNumber(); LaunchConfigurationWrapper configWrapper = LaunchConfigurationWrapper.builder() .withLaunchConfiguration(configuration).withProjectFinder(getProjectFinder()) .withPackageFinder(getPackageFinder()).withClassFinder(getClassFinder()) .withSourceDirFinder(getSourceDirFinder()).withPitConfiguration(pitConfiguration).build(); projectUsesJunit5 = isJUnit5InClasspathOf(configWrapper.getProject()); PitOptionsBuilder optionsBuilder = configWrapper.getPitOptionsBuilder(); PitOptions options = optionsBuilder.withUseJUnit5(projectUsesJunit5) .build(); super.launch(configuration, mode, launch, monitor); IExtensionRegistry registry = Platform.getExtensionRegistry(); new ExtensionPointHandler<PitRuntimeOptions>(EXTENSION_POINT_ID).execute(registry, new PitRuntimeOptions( portNumber, options, configWrapper.getMutatedProjects())); } private static boolean isJUnit5InClasspathOf(IJavaProject project) throws JavaModelException { // FIXME Naive implementation, won't handle every case (e.g. JUnit 5 provided through a junit5.jar archive) // A better implementation may rely on JDT to scan the classpath / source files for definition / use // of JUnit 5 Test annotation // // See also https://github.com/redhat-developer/vscode-java/issues/204 for (IClasspathEntry classpathEntry : project.getRawClasspath()) { if (JUnitCore.JUNIT5_CONTAINER_PATH.equals(classpathEntry.getPath())) { return true; } } for (IClasspathEntry classpathEntry : project.getResolvedClasspath(true)) { Map<String, Object> attributes = Arrays.stream(classpathEntry.getExtraAttributes()).collect(Collectors.toMap(IClasspathAttribute::getName, IClasspathAttribute::getValue, (value1, value2) -> value1)); if (isJUnit5FromMaven(attributes)) { return true; } if (isJUnit5FromGradle(classpathEntry, attributes)) { return true; } if (pointsToJunitJupiterEngineJar(classpathEntry)) { return true; } } return false; } private static boolean isJUnit5FromMaven(Map<String, Object> attributes) { if (!attributes.containsKey("maven.pomderived") || !attributes.containsKey("maven.groupId") || !attributes.containsKey("maven.artifactId")) { return false; } return "true".equals(attributes.get("maven.pomderived")) && "org.junit.jupiter".equals(attributes.get("maven.groupId")) && "junit-jupiter-engine".equals(attributes.get("maven.artifactId")); } private static boolean isJUnit5FromGradle(IClasspathEntry classpathEntry, Map<String, Object> attributes) { if (!attributes.containsKey("gradle_use_by_scope")) { return false; } return pointsToJunitJupiterEngineJar(classpathEntry); } private static boolean pointsToJunitJupiterEngineJar(IClasspathEntry classpathEntry) { try { String[] pathElements = classpathEntry.getPath().toString().split("/"); String file = pathElements[pathElements.length - 1]; return file.startsWith("junit-jupiter-engine") && file.endsWith(".jar"); } catch (IndexOutOfBoundsException e) { // path doesn't have expected format, never mind } return false; } protected abstract ProjectFinder getProjectFinder(); protected abstract SourceDirFinder getSourceDirFinder(); protected abstract PackageFinder getPackageFinder(); protected abstract ClassFinder getClassFinder(); }
43.265957
208
0.719818
1e472d8440061c2e5cd4ee6a7e31f09e4155979b
1,638
package com.societegenerale.commons.plugin.rules; import java.util.Collection; import java.util.List; import java.util.Set; import javax.annotation.Nonnull; import com.societegenerale.commons.plugin.service.ScopePathProvider; import com.societegenerale.commons.plugin.utils.ArchUtils; import com.tngtech.archunit.lang.ArchRule; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; /** * Returning null collections (List, Set) forces the caller to always perform a null check, which hinders readability. It's much better to never return a null Collection, and instead return an empty one. * This rule enforces that all methods returning a Collection must be annotated with @Nonnull * * @see: there is no agreed standard for notNull annotation, see <a href= "https://stackoverflow.com/questions/4963300/which-notnull-java-annotation-should-i-use/">here</a> * * */ public class DontReturnNullCollectionTest implements ArchRuleTest { protected static final String NO_NULL_COLLECTION_MESSAGE = "we don't want callers to perform null check every time. Return an empty collection, not null. Please annotate the method with "+Nonnull.class.getCanonicalName(); @Override public void execute(String packagePath, ScopePathProvider scopePathProvider, Collection<String> excludedPaths) { ArchRule rule = methods().that().haveRawReturnType(List.class).or().haveRawReturnType(Set.class).should().beAnnotatedWith(Nonnull.class) .because(NO_NULL_COLLECTION_MESSAGE); rule.check(ArchUtils.importAllClassesInPackage(scopePathProvider.getMainClassesPath(), packagePath, excludedPaths)); } }
44.27027
223
0.795482
53e3cb695469a90a6aa411f7d5ffa4ace39affe6
522
package PackageBusinesses; import java.io.Serializable; import java.util.Set; /** * Interface dos businesses */ public interface IBusiness extends Serializable, Comparable<IBusiness>{ public String getBusID(); public String getName(); public String getCity(); public String getState(); public Set<String> getCategories(); public IBusiness clone(); /** * Calcula o hash value do Business * @return hash value do Business */ @Override public int hashCode(); }
21.75
75
0.67433
bb01c09ca854eb4e5be5580910cd7bc2e1d218b1
2,081
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.policyinsights.generated; import com.azure.resourcemanager.policyinsights.models.AttestationEvidence; import com.azure.resourcemanager.policyinsights.models.ComplianceState; import java.time.OffsetDateTime; import java.util.Arrays; /** Samples for Attestations CreateOrUpdateAtResourceGroup. */ public final class AttestationsCreateOrUpdateAtResourceGroupSamples { /* * x-ms-original-file: specification/policyinsights/resource-manager/Microsoft.PolicyInsights/stable/2021-01-01/examples/Attestations_CreateResourceGroupScope.json */ /** * Sample code: Create attestation at resource group scope. * * @param manager Entry point to PolicyInsightsManager. */ public static void createAttestationAtResourceGroupScope( com.azure.resourcemanager.policyinsights.PolicyInsightsManager manager) { manager .attestations() .define("790996e6-9871-4b1f-9cd9-ec42cd6ced1e") .withExistingResourceGroup("myRg") .withPolicyAssignmentId( "/subscriptions/35ee058e-5fa0-414c-8145-3ebb8d09b6e2/providers/microsoft.authorization/policyassignments/b101830944f246d8a14088c5") .withPolicyDefinitionReferenceId("0b158b46-ff42-4799-8e39-08a5c23b4551") .withComplianceState(ComplianceState.COMPLIANT) .withExpiresOn(OffsetDateTime.parse("2021-06-15T00:00:00Z")) .withOwner("55a32e28-3aa5-4eea-9b5a-4cd85153b966") .withComments("This subscription has passed a security audit.") .withEvidence( Arrays .asList( new AttestationEvidence() .withDescription("The results of the security audit.") .withSourceUri("https://gist.github.com/contoso/9573e238762c60166c090ae16b814011"))) .create(); } }
47.295455
167
0.699664
a1f61bc1835d6404b756142a034620077b974ae5
792
package br.com.zup.livraria.livraria.controller.form; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import br.com.zup.livraria.livraria.entity.Country; import br.com.zup.livraria.livraria.entity.State; import br.com.zup.livraria.livraria.notation.ItExist; public class StateForm { @NotBlank private String name; @NotNull @ItExist(domainClass = Country.class, fieldName = "id") private Long country; public StateForm() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getCountry() { return country; } public void setCountry(Long country) { this.country = country; } public State converter(Country country) { return new State(name, country); } }
18.857143
56
0.742424
43ba93ee5c9d458cf32e65a4335d1ef100651bfb
2,540
/* * Java port of Bullet (c) 2008 Martin Dvorak <[email protected]> * * Bullet Continuous Collision Detection and Physics Library * Copyright (c) 2003-2008 Erwin Coumans http://www.bulletphysics.com/ * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ package com.bulletphysics.collision.broadphase; import com.bulletphysics.collision.dispatch.CollisionAlgorithmCreateFunc; import com.bulletphysics.collision.dispatch.CollisionObject; import com.bulletphysics.collision.dispatch.ManifoldResult; import com.bulletphysics.collision.narrowphase.PersistentManifold; import com.bulletphysics.util.ObjectArrayList; /** * Collision algorithm for handling narrowphase or midphase collision detection * between two collision object types. * * @author jezek2 */ public abstract class CollisionAlgorithm { //protected final BulletStack stack = BulletStack.get(); // JAVA NOTE: added private CollisionAlgorithmCreateFunc createFunc; protected Dispatcher dispatcher; public void init() { } public void init(CollisionAlgorithmConstructionInfo ci) { dispatcher = ci.dispatcher1; } public abstract void destroy(); public abstract void processCollision(CollisionObject body0, CollisionObject body1, DispatcherInfo dispatchInfo, ManifoldResult resultOut); public abstract float calculateTimeOfImpact(CollisionObject body0, CollisionObject body1, DispatcherInfo dispatchInfo, ManifoldResult resultOut); public abstract void getAllContactManifolds(ObjectArrayList<PersistentManifold> manifoldArray); public final void internalSetCreateFunc(CollisionAlgorithmCreateFunc func) { createFunc = func; } public final CollisionAlgorithmCreateFunc internalGetCreateFunc() { return createFunc; } }
35.774648
146
0.78937
a5d39384bef6ac5e5b74764c829e9a96d36871e4
395
package market_store.cards; import market_store.cardholders.Cardholder; public class SilverCard extends Card { public SilverCard(Cardholder cardHolder) { super(cardHolder, CardType.SILVER, 2); } @Override public double finalDiscountRate() { if(this.getTurnover() > 300){ return 3.5; } return this.getInitialDiscountRate(); } }
20.789474
46
0.653165
26a321b66aaff7f5cbe4ae4b77524ee3b2f7ac57
353
package com.example.powerincode.popularmovies.network.services; import com.example.powerincode.popularmovies.network.models.genre.GenreList; import retrofit2.Call; import retrofit2.http.GET; /** * Created by powerman23rus on 31.10.17. * Enjoy ;) */ public interface GenreService { @GET("genre/movie/list") Call<GenreList> listGenres(); }
20.764706
76
0.753541
101b28b836ee3e8178cc12ae75c65df0922bb208
8,227
package es.deusto.deustotech.capabilities; import android.os.Parcel; import android.os.Parcelable; public class UserMinimumPreferences implements Parcelable { private int layoutBackgroundColor; private float buttonWidth; private float buttonHeight; private int buttonBackgroundColor; private int buttonTextColor; private float buttonTextSize; private float editTextTextSize; private int editTextBackgroundColor; private int editTextTextColor; private float brightness; private float volume; private int textViewBackgroundColor; private int textViewTextColor; private float textViewTextSize; private int editTextWidth; private int textViewWidth; private int editTextHeight; private int textViewHeight; private int luxes; private int displayHasApplicable = 0; //false private int audioHasApplicable = 0; private String contextAuxLight; public UserMinimumPreferences() { super(); } public UserMinimumPreferences(int layoutBackgroundColor, float buttonWidth, float buttonHeight, int buttonBackgroundColor, int buttonTextColor, float buttonTextSize, float editTextTextSize, int editTextBackgroundColor, int editTextTextColor, int textViewBackgroundColor, int textViewTextColor, float textViewTextSize, int editTextWidth, int textViewWidth, int editTextHeight, int textViewHeight, int displayHasApplicable, int audioHasApplicable, int luxes, String contextAuxLight) { super(); this.layoutBackgroundColor = layoutBackgroundColor; this.buttonWidth = buttonWidth; this.buttonHeight = buttonHeight; this.buttonBackgroundColor = buttonBackgroundColor; this.buttonTextColor = buttonTextColor; this.buttonTextSize = buttonTextSize; this.editTextTextSize = editTextTextSize; this.editTextBackgroundColor = editTextBackgroundColor; this.editTextTextColor = editTextTextColor; this.textViewBackgroundColor = textViewBackgroundColor; this.textViewTextColor = textViewTextColor; this.textViewTextSize = textViewTextSize; this.editTextWidth = editTextWidth; this.textViewWidth = textViewWidth; this.editTextHeight = editTextHeight; this.textViewHeight = textViewHeight; this.displayHasApplicable = displayHasApplicable; this.audioHasApplicable = audioHasApplicable; this.luxes = luxes; this.contextAuxLight = contextAuxLight; } public UserMinimumPreferences(Parcel in) { readFromParcel(in); } public int getLayoutBackgroundColor() { return layoutBackgroundColor; } public void setLayoutBackgroundColor(int backgroundColor) { this.layoutBackgroundColor = backgroundColor; } public float getButtonWidth() { return buttonWidth; } public void setButtonWidth(float buttonWidth) { this.buttonWidth = buttonWidth; } public float getButtonHeight() { return buttonHeight; } public void setButtonHeight(float buttonHeight) { this.buttonHeight = buttonHeight; } public int getButtonBackgroundColor() { return buttonBackgroundColor; } public void setButtonBackgroundColor(int buttonBackgroundColor) { this.buttonBackgroundColor = buttonBackgroundColor; } public int getButtonTextColor() { return buttonTextColor; } public void setButtonTextColor(int buttonTextColor) { this.buttonTextColor = buttonTextColor; } public float getButtonTextSize() { return buttonTextSize; } public void setButtonTextSize(float buttonTextSize) { this.buttonTextSize = buttonTextSize; } public float getEditTextTextSize() { return editTextTextSize; } public void setEditTextTextSize(float editTextTextSize) { this.editTextTextSize = editTextTextSize; } public int getEditTextBackgroundColor() { return editTextBackgroundColor; } public void setEditTextBackgroundColor(int editTextBackgroundColor) { this.editTextBackgroundColor = editTextBackgroundColor; } public int getEditTextTextColor() { return editTextTextColor; } public void setEditTextTextColor(int editTextTextColor) { this.editTextTextColor = editTextTextColor; } public float getBrightness() { return brightness; } public void setBrightness(float brightness) { this.brightness = brightness; } public float getVolume() { return volume; } public void setVolume(float volume) { this.volume = volume; } public int getDisplayHasApplicable() { return displayHasApplicable; } public void setDisplayHasApplicable(int isApplicable) { this.displayHasApplicable = isApplicable; } public int getAudioHasApplicable() { return audioHasApplicable; } public void setAudioHasApplicable(int isApplicable) { this.audioHasApplicable = isApplicable; } public void setTextViewBackgroundColor(int textViewBackgroundColor) { this.textViewBackgroundColor = textViewBackgroundColor; } public void setTextViewTextColor(int textViewTextColor) { this.textViewTextColor = textViewTextColor; } public void setTextViewTextSize(float textViewTextSize) { this.textViewTextSize = textViewTextSize; } public int getTextViewBackgroundColor() { return textViewBackgroundColor; } public int getTextViewTextColor() { return textViewTextColor; } public float getTextViewTextSize() { return textViewTextSize; } public int getEditTextWidth() { return editTextWidth; } public void setEditTextWidth(int editTextWidth) { this.editTextWidth = editTextWidth; } public int getTextViewWidth() { return textViewWidth; } public void setTextViewWidth(int textViewWidth) { this.textViewWidth = textViewWidth; } public int getEditTextHeight() { return editTextHeight; } public void setEditTextHeight(int editTextHeight) { this.editTextHeight = editTextHeight; } public int getTextViewHeight() { return textViewHeight; } public void setTextViewHeight(int textViewHeight) { this.textViewHeight = textViewHeight; } public int getLuxes() { return luxes; } public void setLuxes(int luxes) { this.luxes = luxes; } public String getContextAuxLight() { return contextAuxLight; } public void setContextAuxLight(String contextAuxLight) { this.contextAuxLight = contextAuxLight; } public static Parcelable.Creator<UserMinimumPreferences> getCreator() { return CREATOR; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(layoutBackgroundColor); dest.writeFloat(buttonWidth); dest.writeFloat(buttonHeight); dest.writeInt(buttonBackgroundColor); dest.writeInt(buttonTextColor); dest.writeFloat(buttonTextSize); dest.writeFloat(editTextTextSize); dest.writeInt(editTextBackgroundColor); dest.writeInt(editTextTextColor); dest.writeFloat(brightness); dest.writeFloat(volume); dest.writeInt(displayHasApplicable); dest.writeInt(audioHasApplicable); dest.writeInt(textViewBackgroundColor); dest.writeInt(textViewTextColor); dest.writeFloat(textViewTextSize); dest.writeInt(editTextWidth); dest.writeInt(textViewWidth); dest.writeInt(editTextHeight); dest.writeInt(textViewHeight); dest.writeInt(luxes); dest.writeString(contextAuxLight); } private void readFromParcel(Parcel in) { layoutBackgroundColor = in.readInt(); buttonWidth = in.readFloat(); buttonHeight = in.readFloat(); buttonBackgroundColor = in.readInt(); buttonTextColor = in.readInt(); buttonTextSize = in.readFloat(); editTextTextSize = in.readFloat(); editTextBackgroundColor = in.readInt(); editTextTextColor = in.readInt(); brightness = in.readFloat(); volume = in.readFloat(); displayHasApplicable = in.readInt(); audioHasApplicable = in.readInt(); textViewBackgroundColor = in.readInt(); textViewTextColor = in.readInt(); textViewTextSize = in.readFloat(); editTextWidth = in.readInt(); textViewWidth = in.readInt(); editTextHeight = in.readInt(); textViewHeight = in.readInt(); luxes = in.readInt(); contextAuxLight = in.readString(); } public static final Parcelable.Creator<UserMinimumPreferences> CREATOR = new Parcelable.Creator<UserMinimumPreferences>() { public UserMinimumPreferences createFromParcel(Parcel in) { return new UserMinimumPreferences(in); } public UserMinimumPreferences[] newArray(int size) { return new UserMinimumPreferences[size]; } }; }
25.871069
125
0.778048
f759de445903d0c2b968dea93e1714f1615e546e
9,118
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work.impl.background.gcm; import android.content.Context; import android.os.PowerManager; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.work.Logger; import androidx.work.WorkInfo; import androidx.work.impl.ExecutionListener; import androidx.work.impl.Processor; import androidx.work.impl.Schedulers; import androidx.work.impl.WorkDatabase; import androidx.work.impl.WorkManagerImpl; import androidx.work.impl.model.WorkSpec; import androidx.work.impl.utils.WakeLocks; import androidx.work.impl.utils.WorkTimer; import com.google.android.gms.gcm.GcmNetworkManager; import com.google.android.gms.gcm.TaskParams; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Handles requests for executing {@link androidx.work.WorkRequest}s on behalf of * {@link WorkManagerGcmService}. */ public class WorkManagerGcmDispatcher { // Synthetic access static final String TAG = Logger.tagWithPrefix("WrkMgrGcmDispatcher"); private static final long AWAIT_TIME_IN_MINUTES = 10; private static final long AWAIT_TIME_IN_MILLISECONDS = AWAIT_TIME_IN_MINUTES * 60 * 1000; private final Context mContext; private final WorkTimer mWorkTimer; // Synthetic access WorkManagerImpl mWorkManagerImpl; public WorkManagerGcmDispatcher(@NonNull Context context, @NonNull WorkTimer workTimer) { mContext = context.getApplicationContext(); mWorkTimer = workTimer; mWorkManagerImpl = WorkManagerImpl.getInstance(context); } /** * Handles {@link WorkManagerGcmService#onInitializeTasks()}. */ @MainThread public void onInitializeTasks() { // Reschedule all eligible work, as all tasks have been cleared in GCMNetworkManager. // This typically happens after an upgrade. mWorkManagerImpl.getWorkTaskExecutor().executeOnBackgroundThread(new Runnable() { @Override public void run() { Logger.get().debug(TAG, "onInitializeTasks(): Rescheduling work"); mWorkManagerImpl.rescheduleEligibleWork(); } }); } /** * Handles {@link WorkManagerGcmService#onRunTask(TaskParams)}. */ public int onRunTask(@NonNull TaskParams taskParams) { // Tasks may be executed concurrently but every Task will be executed in a unique thread // per tag, which in our case is a workSpecId. Therefore its safe to block here with // a latch because there is 1 thread per workSpecId. Logger.get().debug(TAG, String.format("Handling task %s", taskParams)); String workSpecId = taskParams.getTag(); if (workSpecId == null || workSpecId.isEmpty()) { // Bad request. No WorkSpec id. Logger.get().debug(TAG, "Bad request. No workSpecId."); return GcmNetworkManager.RESULT_FAILURE; } WorkSpecExecutionListener listener = new WorkSpecExecutionListener(workSpecId); WorkSpecTimeLimitExceededListener timeLimitExceededListener = new WorkSpecTimeLimitExceededListener(mWorkManagerImpl); Processor processor = mWorkManagerImpl.getProcessor(); processor.addExecutionListener(listener); String wakeLockTag = String.format("WorkGcm-onRunTask (%s)", workSpecId); PowerManager.WakeLock wakeLock = WakeLocks.newWakeLock(mContext, wakeLockTag); mWorkManagerImpl.startWork(workSpecId); mWorkTimer.startTimer(workSpecId, AWAIT_TIME_IN_MILLISECONDS, timeLimitExceededListener); try { wakeLock.acquire(); listener.getLatch().await(AWAIT_TIME_IN_MINUTES, TimeUnit.MINUTES); } catch (InterruptedException exception) { Logger.get().debug(TAG, String.format("Rescheduling WorkSpec %s", workSpecId)); return reschedule(workSpecId); } finally { processor.removeExecutionListener(listener); mWorkTimer.stopTimer(workSpecId); wakeLock.release(); } if (listener.needsReschedule()) { Logger.get().debug(TAG, String.format("Rescheduling WorkSpec %s", workSpecId)); return reschedule(workSpecId); } WorkDatabase workDatabase = mWorkManagerImpl.getWorkDatabase(); WorkSpec workSpec = workDatabase.workSpecDao().getWorkSpec(workSpecId); WorkInfo.State state = workSpec != null ? workSpec.state : null; if (state == null) { Logger.get().debug(TAG, String.format("WorkSpec %s does not exist", workSpecId)); return GcmNetworkManager.RESULT_FAILURE; } else { switch (state) { case SUCCEEDED: case CANCELLED: Logger.get().debug(TAG, String.format("Returning RESULT_SUCCESS for WorkSpec %s", workSpecId)); return GcmNetworkManager.RESULT_SUCCESS; case FAILED: Logger.get().debug(TAG, String.format("Returning RESULT_FAILURE for WorkSpec %s", workSpecId)); return GcmNetworkManager.RESULT_FAILURE; default: Logger.get().debug(TAG, "Rescheduling eligible work."); return reschedule(workSpecId); } } } /** * Cleans up resources when the {@link WorkManagerGcmDispatcher} is no longer in use. */ public void onDestroy() { mWorkTimer.onDestroy(); } private int reschedule(@NonNull final String workSpecId) { final WorkDatabase workDatabase = mWorkManagerImpl.getWorkDatabase(); workDatabase.runInTransaction(new Runnable() { @Override public void run() { // Mark the workSpec as unscheduled. We are doing this explicitly here because // there are many cases where WorkerWrapper may not have had a chance to update this // flag. For e.g. this will happen if the Worker took longer than 10 minutes. workDatabase.workSpecDao() .markWorkSpecScheduled(workSpecId, WorkSpec.SCHEDULE_NOT_REQUESTED_YET); // We reschedule on our own to apply our own backoff policy. Schedulers.schedule( mWorkManagerImpl.getConfiguration(), mWorkManagerImpl.getWorkDatabase(), mWorkManagerImpl.getSchedulers()); } }); Logger.get().debug(TAG, String.format("Returning RESULT_SUCCESS for WorkSpec %s", workSpecId)); return GcmNetworkManager.RESULT_SUCCESS; } static class WorkSpecTimeLimitExceededListener implements WorkTimer.TimeLimitExceededListener { private static final String TAG = Logger.tagWithPrefix("WrkTimeLimitExceededLstnr"); private final WorkManagerImpl mWorkManager; WorkSpecTimeLimitExceededListener(@NonNull WorkManagerImpl workManager) { mWorkManager = workManager; } @Override public void onTimeLimitExceeded(@NonNull String workSpecId) { Logger.get().debug(TAG, String.format("WorkSpec time limit exceeded %s", workSpecId)); mWorkManager.stopWork(workSpecId); } } static class WorkSpecExecutionListener implements ExecutionListener { private static final String TAG = Logger.tagWithPrefix("WorkSpecExecutionListener"); private final String mWorkSpecId; private final CountDownLatch mLatch; private boolean mNeedsReschedule; WorkSpecExecutionListener(@NonNull String workSpecId) { mWorkSpecId = workSpecId; mLatch = new CountDownLatch(1); mNeedsReschedule = false; } boolean needsReschedule() { return mNeedsReschedule; } CountDownLatch getLatch() { return mLatch; } @Override public void onExecuted(@NonNull String workSpecId, boolean needsReschedule) { if (!mWorkSpecId.equals(workSpecId)) { Logger.get().warning(TAG, String.format("Notified for %s, but was looking for %s", workSpecId, mWorkSpecId)); } else { mNeedsReschedule = needsReschedule; mLatch.countDown(); } } } }
39.301724
100
0.655297
ce0b3cb1861a28700bed2e872b925f49710f6682
12,462
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.functions; import org.apache.flink.configuration.Configuration; import org.apache.flink.table.api.ValidationException; import org.apache.flink.table.catalog.CatalogFunction; import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.util.Collector; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import javax.annotation.Nullable; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import static org.apache.flink.core.testutils.FlinkAssertions.anyCauseMatches; import static org.apache.flink.table.functions.UserDefinedFunctionHelper.instantiateFunction; import static org.apache.flink.table.functions.UserDefinedFunctionHelper.isClassNameSerializable; import static org.apache.flink.table.functions.UserDefinedFunctionHelper.prepareInstance; import static org.apache.flink.table.functions.UserDefinedFunctionHelper.validateClass; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Tests for {@link UserDefinedFunctionHelper}. */ @SuppressWarnings("unused") class UserDefinedFunctionHelperTest { @ParameterizedTest @MethodSource("testSpecs") void testInstantiation(TestSpec testSpec) { final Supplier<UserDefinedFunction> supplier; if (testSpec.functionClass != null) { supplier = () -> instantiateFunction(testSpec.functionClass); } else if (testSpec.catalogFunction != null) { supplier = () -> instantiateFunction( UserDefinedFunctionHelperTest.class.getClassLoader(), new Configuration(), "f", testSpec.catalogFunction); } else { return; } if (testSpec.expectedErrorMessage != null) { assertThatThrownBy(supplier::get) .satisfies( anyCauseMatches( ValidationException.class, testSpec.expectedErrorMessage)); } else { assertThat(supplier.get()).isNotNull(); } } @ParameterizedTest @MethodSource("testSpecs") void testValidation(TestSpec testSpec) { final Runnable runnable; if (testSpec.functionClass != null) { runnable = () -> validateClass(testSpec.functionClass); } else if (testSpec.functionInstance != null) { runnable = () -> prepareInstance(new Configuration(), testSpec.functionInstance); } else { return; } if (testSpec.expectedErrorMessage != null) { assertThatThrownBy(runnable::run) .satisfies( anyCauseMatches( ValidationException.class, testSpec.expectedErrorMessage)); } else { runnable.run(); } } @Test void testSerialization() { assertThat(isClassNameSerializable(new ValidTableFunction())).isTrue(); assertThat(isClassNameSerializable(new ValidScalarFunction())).isTrue(); assertThat(isClassNameSerializable(new ParameterizedTableFunction(12))).isFalse(); assertThat(isClassNameSerializable(new StatefulScalarFunction())).isFalse(); } // -------------------------------------------------------------------------------------------- // Test utilities // -------------------------------------------------------------------------------------------- private static List<TestSpec> testSpecs() { return Arrays.asList( TestSpec.forClass(ValidScalarFunction.class).expectSuccess(), TestSpec.forInstance(new ValidScalarFunction()).expectSuccess(), TestSpec.forClass(PrivateScalarFunction.class) .expectErrorMessage( "Function class '" + PrivateScalarFunction.class.getName() + "' is not public."), TestSpec.forClass(MissingImplementationScalarFunction.class) .expectErrorMessage( "Function class '" + MissingImplementationScalarFunction.class.getName() + "' does not implement a method named 'eval'."), TestSpec.forClass(PrivateMethodScalarFunction.class) .expectErrorMessage( "Method 'eval' of function class '" + PrivateMethodScalarFunction.class.getName() + "' is not public."), TestSpec.forInstance(new ValidTableAggregateFunction()).expectSuccess(), TestSpec.forInstance(new MissingEmitTableAggregateFunction()) .expectErrorMessage( "Function class '" + MissingEmitTableAggregateFunction.class.getName() + "' does not implement a method named 'emitUpdateWithRetract' or 'emitValue'."), TestSpec.forInstance(new ValidTableFunction()).expectSuccess(), TestSpec.forInstance(new ParameterizedTableFunction(12)).expectSuccess(), TestSpec.forClass(ParameterizedTableFunction.class) .expectErrorMessage( "Function class '" + ParameterizedTableFunction.class.getName() + "' must have a public default constructor."), TestSpec.forClass(HierarchicalTableAggregateFunction.class).expectSuccess(), TestSpec.forCatalogFunction(ValidScalarFunction.class.getName()).expectSuccess(), TestSpec.forCatalogFunction("I don't exist.") .expectErrorMessage("Cannot instantiate user-defined function 'f'.")); } private static class TestSpec { final @Nullable Class<? extends UserDefinedFunction> functionClass; final @Nullable UserDefinedFunction functionInstance; final @Nullable CatalogFunction catalogFunction; @Nullable String expectedErrorMessage; TestSpec( @Nullable Class<? extends UserDefinedFunction> functionClass, @Nullable UserDefinedFunction functionInstance, @Nullable CatalogFunction catalogFunction) { this.functionClass = functionClass; this.functionInstance = functionInstance; this.catalogFunction = catalogFunction; } static TestSpec forClass(Class<? extends UserDefinedFunction> function) { return new TestSpec(function, null, null); } static TestSpec forInstance(UserDefinedFunction function) { return new TestSpec(null, function, null); } static TestSpec forCatalogFunction(String className) { return new TestSpec(null, null, new CatalogFunctionMock(className)); } TestSpec expectErrorMessage(String expectedErrorMessage) { this.expectedErrorMessage = expectedErrorMessage; return this; } TestSpec expectSuccess() { this.expectedErrorMessage = null; return this; } } private static class CatalogFunctionMock implements CatalogFunction { private final String className; CatalogFunctionMock(String className) { this.className = className; } @Override public String getClassName() { return className; } @Override public CatalogFunction copy() { return null; } @Override public Optional<String> getDescription() { return Optional.empty(); } @Override public Optional<String> getDetailedDescription() { return Optional.empty(); } @Override public boolean isGeneric() { return false; } @Override public FunctionLanguage getFunctionLanguage() { return FunctionLanguage.JAVA; } } // -------------------------------------------------------------------------------------------- // Test classes for validation // -------------------------------------------------------------------------------------------- /** Valid scalar function. */ public static class ValidScalarFunction extends ScalarFunction { public String eval(int i) { return null; } } private static class PrivateScalarFunction extends ScalarFunction { public String eval(int i) { return null; } } /** No implementation method. */ public static class MissingImplementationScalarFunction extends ScalarFunction { // nothing to do } /** Implementation method is private. */ public static class PrivateMethodScalarFunction extends ScalarFunction { private String eval(int i) { return null; } } /** Valid table aggregate function. */ public static class ValidTableAggregateFunction extends TableAggregateFunction<String, String> { public void accumulate(String acc, String in) { // nothing to do } public void emitValue(String acc, Collector<String> out) { // nothing to do } @Override public String createAccumulator() { return null; } } /** No emitting method implementation. */ public static class MissingEmitTableAggregateFunction extends TableAggregateFunction<String, String> { public void accumulate(String acc, String in) { // nothing to do } @Override public String createAccumulator() { return null; } } /** Valid table function. */ public static class ValidTableFunction extends TableFunction<String> { public void eval(String i) { // nothing to do } } /** Table function with parameters in constructor. */ public static class ParameterizedTableFunction extends TableFunction<String> { public ParameterizedTableFunction(int param) { // nothing to do } public void eval(String i) { // nothing to do } } private abstract static class AbstractTableAggregateFunction extends TableAggregateFunction<String, String> { public void accumulate(String acc, String in) { // nothing to do } } /** Hierarchy that is implementing different methods. */ public static class HierarchicalTableAggregateFunction extends AbstractTableAggregateFunction { public void emitValue(String acc, Collector<String> out) { // nothing to do } @Override public String createAccumulator() { return null; } } /** Function with state. */ public static class StatefulScalarFunction extends ScalarFunction { public String state; public String eval() { return state; } } }
36.438596
121
0.5922
a85f5bf39e50c1cc88ee257391b72106d96454bf
11,854
/** * Copyright 2011-2012 eBusiness Information, Groupe Excilys (www.excilys.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.excilys.ebi.spring.dbunit.config; import static org.springframework.util.StringUtils.tokenizeToStringArray; import java.io.IOException; import java.util.List; import org.dbunit.database.DatabaseConfig; import org.dbunit.dataset.CompositeDataSet; import org.dbunit.dataset.DataSetException; import org.dbunit.dataset.IDataSet; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.util.Assert; import com.excilys.ebi.spring.dbunit.config.Constants.ConfigurationDefaults; import com.excilys.ebi.spring.dbunit.dataset.DataSetDecorator; /** * @author <a href="mailto:[email protected]">Stephane LANDELLE</a> */ public class DataSetConfiguration implements DatabaseConnectionConfigurer { private boolean disabled; private String dataSourceSpringName; private DBOperation setUpOperation[] = new DBOperation[] { ConfigurationDefaults.DEFAULT_SETUP_OPERATION }; private DBOperation tearDownOperation[] = new DBOperation[] { ConfigurationDefaults.DEFAULT_TEARDOWN_OPERATION }; private DBType dbType = ConfigurationDefaults.DEFAULT_DB_TYPE; private String[] dataSetResourceLocations = new String[] { "classpath:dataSet.xml" }; private DataSetFormat format = ConfigurationDefaults.DEFAULT_DB_FORMAT; private DataSetFormatOptions formatOptions = new DataSetFormatOptions(); private String escapePattern = ConfigurationDefaults.DEFAULT_ESCAPE_PATTERN; private int batchSize = ConfigurationDefaults.DEFAULT_BATCH_SIZE; private int fetchSize = ConfigurationDefaults.DEFAULT_FETCH_SIZE; private boolean qualifiedTableNames = ConfigurationDefaults.DEFAULT_QUALIFIED_TABLE_NAMES; private boolean batchedStatements = ConfigurationDefaults.DEFAULT_BATCHED_STATEMENTS; private boolean skipOracleRecycleBinTables = ConfigurationDefaults.DEFAULT_SKIP_ORACLE_RECYCLEBIN_TABLES; private String[] tableType = ConfigurationDefaults.DEFAULT_TABLE_TYPE; private String schema = ConfigurationDefaults.DEFAULT_SCHEMA; private Class<? extends DataSetDecorator>[] decorators = null; public IDataSet getDataSet() throws DataSetException, IOException { List<IDataSet> dataSets = format.loadMultiple(formatOptions, dataSetResourceLocations); return dataSets.size() == 1 ? dataSets.get(0) : new CompositeDataSet(dataSets.toArray(new IDataSet[dataSets.size()])); } @Override public void configure(DatabaseConfig databaseConfig) { Assert.notNull(dbType, "dbType is required"); databaseConfig.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, dbType.getDataTypeFactory()); databaseConfig.setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, dbType.getMetadataHandler()); databaseConfig.setProperty(DatabaseConfig.PROPERTY_ESCAPE_PATTERN, escapePattern); databaseConfig.setProperty(DatabaseConfig.PROPERTY_BATCH_SIZE, batchSize); databaseConfig.setProperty(DatabaseConfig.PROPERTY_FETCH_SIZE, fetchSize); databaseConfig.setProperty(DatabaseConfig.FEATURE_CASE_SENSITIVE_TABLE_NAMES, formatOptions.isCaseSensitiveTableNames()); databaseConfig.setProperty(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, qualifiedTableNames); databaseConfig.setProperty(DatabaseConfig.FEATURE_BATCHED_STATEMENTS, batchedStatements); databaseConfig.setProperty(DatabaseConfig.FEATURE_SKIP_ORACLE_RECYCLEBIN_TABLES, skipOracleRecycleBinTables); databaseConfig.setProperty(DatabaseConfig.PROPERTY_TABLE_TYPE, tableType); } public static Builder newDataSetConfiguration() { return new Builder(); } public static class Builder { private DataSetConfiguration dataSetConfiguration = new DataSetConfiguration(); private Builder() { } public Builder withDisabled(boolean disabled) { dataSetConfiguration.disabled = disabled; return this; } public Builder withDataSourceSpringName(String dataSourceSpringName) { dataSetConfiguration.dataSourceSpringName = dataSourceSpringName; return this; } public Builder withSetUpOp(DBOperation[] setUpOp) { dataSetConfiguration.setUpOperation = setUpOp; return this; } public Builder withTearDownOp(DBOperation[] tearDownOp) { dataSetConfiguration.tearDownOperation = tearDownOp; return this; } public Builder withDbType(DBType dbType) { if (dbType != null) dataSetConfiguration.dbType = dbType; return this; } public Builder withDataSetResourceLocations(String[] dataSetResourceLocations) { dataSetConfiguration.dataSetResourceLocations = dataSetResourceLocations; return this; } public Builder withFormat(DataSetFormat format) { dataSetConfiguration.format = format; return this; } public Builder withFormatOptions(DataSetFormatOptions formatOptions) { dataSetConfiguration.formatOptions = formatOptions; return this; } public Builder withEscapePattern(String escapePattern) { escapePattern = escapePattern.trim(); dataSetConfiguration.escapePattern = escapePattern.isEmpty() ? null : escapePattern; return this; } public Builder withBatchSize(int batchSize) { dataSetConfiguration.batchSize = batchSize; return this; } public Builder withFetchSize(int fetchSize) { dataSetConfiguration.fetchSize = fetchSize; return this; } public Builder withQualifiedTableNames(boolean qualifiedTableNames) { dataSetConfiguration.qualifiedTableNames = qualifiedTableNames; return this; } public Builder withBatchedStatements(boolean batchedStatements) { dataSetConfiguration.batchedStatements = batchedStatements; return this; } public Builder withSkipOracleRecycleBinTables(boolean skipOracleRecycleBinTables) { dataSetConfiguration.skipOracleRecycleBinTables = skipOracleRecycleBinTables; return this; } public Builder withTableType(String[] tableType) { if (tableType != null) dataSetConfiguration.tableType = tableType; return this; } public Builder withSchema(String schema) { schema = schema.trim(); if (!schema.isEmpty()) dataSetConfiguration.schema = schema; return this; } public Builder withDecorators(Class<? extends DataSetDecorator>[] decorators) { if (decorators != null) dataSetConfiguration.decorators = decorators; return this; } public DataSetConfiguration build() { Assert.notNull(dataSetConfiguration.dataSetResourceLocations, "dataSetResourceLocations is required"); Assert.notNull(dataSetConfiguration.setUpOperation, "setUpOperation is required"); Assert.notNull(dataSetConfiguration.tearDownOperation, "tearDownOperation is required"); Assert.notNull(dataSetConfiguration.dbType, "dbType is required"); Assert.notNull(dataSetConfiguration.format, "format is required"); Assert.notNull(dataSetConfiguration.formatOptions, "formatOptions are required"); return dataSetConfiguration; } } public String getDataSetResourceLocation() { throw new UnsupportedOperationException(); } public void setDataSetResourceLocation(String dataSetResourceLocation) { this.dataSetResourceLocations = tokenizeToStringArray(dataSetResourceLocation, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); } public boolean isDisabled() { return disabled; } public String getDataSourceSpringName() { return dataSourceSpringName; } public DBOperation[] getSetUpOperation() { return setUpOperation; } public DBOperation[] getTearDownOperation() { return tearDownOperation; } public DBType getDbType() { return dbType; } public String[] getDataSetResourceLocations() { return dataSetResourceLocations; } public DataSetFormat getFormat() { return format; } public DataSetFormatOptions getFormatOptions() { return formatOptions; } public String getEscapePattern() { return escapePattern; } public int getBatchSize() { return batchSize; } public int getFetchSize() { return fetchSize; } public boolean isQualifiedTableNames() { return qualifiedTableNames; } public boolean isBatchedStatements() { return batchedStatements; } public boolean isSkipOracleRecycleBinTables() { return skipOracleRecycleBinTables; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public void setDataSourceSpringName(String dataSourceSpringName) { this.dataSourceSpringName = dataSourceSpringName; } public void setSetUpOperation(DBOperation[] setUpOperation) { this.setUpOperation = setUpOperation; } public void setTearDownOperation(DBOperation[] tearDownOperation) { this.tearDownOperation = tearDownOperation; } public void setDbType(DBType dbType) { this.dbType = dbType; } public void setDataSetResourceLocations(String[] dataSetResourceLocations) { this.dataSetResourceLocations = dataSetResourceLocations; } public void setFormat(DataSetFormat format) { this.format = format; } public void setFormatOptions(DataSetFormatOptions formatOptions) { this.formatOptions = formatOptions; } public void setEscapePattern(String escapePattern) { this.escapePattern = escapePattern; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } public void setFetchSize(int fetchSize) { this.fetchSize = fetchSize; } public void setQualifiedTableNames(boolean qualifiedTableNames) { this.qualifiedTableNames = qualifiedTableNames; } public void setBatchedStatements(boolean batchedStatements) { this.batchedStatements = batchedStatements; } public void setSkipOracleRecycleBinTables(boolean skipOracleRecycleBinTables) { this.skipOracleRecycleBinTables = skipOracleRecycleBinTables; } public String[] getTableType() { return tableType; } public void setTableType(String[] tableType) { this.tableType = tableType; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public Class<? extends DataSetDecorator>[] getDecorators() { return decorators; } public void setDecorators(Class<? extends DataSetDecorator>[] decorators) { this.decorators = decorators; } }
33.485876
146
0.708537
fcfd97ed598519dd5e03f0784b4b7d170d77e854
8,141
/* Copyright (c) 2018, University of North Carolina at Chapel Hill */ /* Copyright (c) 2015-2017, Dell EMC */ package com.emc.metalnx.services.configuration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.irods.jargon.core.connection.AuthScheme; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; import com.emc.metalnx.services.interfaces.ConfigService; /** * Class that will load all all configurable parameters from *.properties files. */ @Service @Transactional @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.INTERFACES) public class ConfigServiceImpl implements ConfigService { public final static Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class); @Value("${msi.api.version}") private String msiAPIVersionSupported; @Value("${msi.metalnx.list}") private String mlxMSIsExpected; @Value("${msi.irods.list}") private String irods41MSIsExpected; @Value("${msi.irods.42.list}") private String irods42MSIsExpected; @Value("${msi.other.list}") private String otherMSIsExpected; @Value("${irods.host}") private String irodsHost; @Value("${irods.port}") private String irodsPort; @Value("${irods.zoneName}") private String irodsZone; @Value("${irods.auth.scheme}") private String defaultIrodsAuthScheme; @Value("${jobs.irods.username}") private String irodsJobUser; @Value("${jobs.irods.password}") private String irodsJobPassword; @Value("${jobs.irods.auth.scheme}") private String irodsAuthScheme; @Value("${populate.msi.enabled}") private boolean populateMsiEnabled; @Value("${metalnx.enable.tickets}") private boolean ticketsEnabled; @Value("${metalnx.enable.dashboard}") private boolean dashboardEnabled; @Value("${metalnx.enable.upload.rules}") private boolean uploadRulesEnabled; @Value("${metalnx.download.limit}") private long downloadLimit; /** * This is a string representation of AuthType mappings in the form * iRODType:userFriendlyType| (bar delimited) This is parsed from the * metalnx.properties and can be accessed as a parsed mapping via * {@code ConfigService.listAuthTypeMappings()} */ @Value("${metalnx.authtype.mappings}") private String authtypeMappings; @Override public GlobalConfig getGlobalConfig() { logger.info("getGlobalConfig()"); GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setTicketsEnabled(this.isTicketsEnabled()); globalConfig.setUploadRulesEnabled(isUploadRulesEnabled()); globalConfig.setDashboardEnabled(dashboardEnabled); logger.debug("globalConfig:{}", globalConfig); return globalConfig; } @Override public String getMsiAPIVersionSupported() { if (msiAPIVersionSupported == null) return ""; return msiAPIVersionSupported; } @Override public List<String> getMlxMSIsExpected() { if (mlxMSIsExpected == null) return Collections.emptyList(); return Arrays.asList(mlxMSIsExpected.split(",")); } @Override public List<String> getIrods41MSIsExpected() { if (irods41MSIsExpected == null) return Collections.emptyList(); return Arrays.asList(irods41MSIsExpected.split(",")); } @Override public List<String> getIrods42MSIsExpected() { if (irods42MSIsExpected == null) return Collections.emptyList(); return Arrays.asList(irods42MSIsExpected.split(",")); } @Override public List<String> getOtherMSIsExpected() { if (otherMSIsExpected == null) return Collections.emptyList(); return Arrays.asList(otherMSIsExpected.split(",")); } @Override public String getIrodsHost() { return irodsHost; } @Override public String getIrodsPort() { return irodsPort; } @Override public String getIrodsZone() { return irodsZone; } @Override public String getIrodsJobUser() { return irodsJobUser; } @Override public String getIrodsJobPassword() { return irodsJobPassword; } @Override public String getIrodsAuthScheme() { return irodsAuthScheme; } @Override public long getDownloadLimit() { return downloadLimit; } @Override public boolean isPopulateMsiEnabled() { return populateMsiEnabled; } public boolean isTicketsEnabled() { return ticketsEnabled; } public void setTicketsEnabled(boolean ticketsEnabled) { this.ticketsEnabled = ticketsEnabled; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ConfigServiceImpl ["); if (msiAPIVersionSupported != null) { builder.append("msiAPIVersionSupported=").append(msiAPIVersionSupported).append(", "); } if (mlxMSIsExpected != null) { builder.append("mlxMSIsExpected=").append(mlxMSIsExpected).append(", "); } if (irods41MSIsExpected != null) { builder.append("irods41MSIsExpected=").append(irods41MSIsExpected).append(", "); } if (irods42MSIsExpected != null) { builder.append("irods42MSIsExpected=").append(irods42MSIsExpected).append(", "); } if (otherMSIsExpected != null) { builder.append("otherMSIsExpected=").append(otherMSIsExpected).append(", "); } if (irodsHost != null) { builder.append("irodsHost=").append(irodsHost).append(", "); } if (irodsPort != null) { builder.append("irodsPort=").append(irodsPort).append(", "); } if (irodsZone != null) { builder.append("irodsZone=").append(irodsZone).append(", "); } if (defaultIrodsAuthScheme != null) { builder.append("defaultIrodsAuthScheme=").append(defaultIrodsAuthScheme).append(", "); } if (irodsJobUser != null) { builder.append("irodsJobUser=").append(irodsJobUser).append(", "); } if (irodsJobPassword != null) { builder.append("irodsJobPassword=").append(irodsJobPassword).append(", "); } if (irodsAuthScheme != null) { builder.append("irodsAuthScheme=").append(irodsAuthScheme).append(", "); } builder.append("populateMsiEnabled=").append(populateMsiEnabled).append(", ticketsEnabled=") .append(ticketsEnabled).append(", dashboardEnabled=").append(dashboardEnabled) .append(", uploadRulesEnabled=").append(uploadRulesEnabled).append(", downloadLimit=") .append(downloadLimit).append("]"); return builder.toString(); } @Override public boolean isUploadRulesEnabled() { return uploadRulesEnabled; } public void setUploadRulesEnabled(boolean uploadRulesEnabled) { this.uploadRulesEnabled = uploadRulesEnabled; } @Override public String getDefaultIrodsAuthScheme() { return defaultIrodsAuthScheme; } public void setDefaultIrodsAuthScheme(String defaultIrodsAuthScheme) { this.defaultIrodsAuthScheme = defaultIrodsAuthScheme; } @Override public boolean isDashboardEnabled() { return dashboardEnabled; } public void setDashboardEnabled(boolean dashboardEnabled) { this.dashboardEnabled = dashboardEnabled; } @Override public List<AuthTypeMapping> listAuthTypeMappings() { List<AuthTypeMapping> authTypeList = new ArrayList<AuthTypeMapping>(); if (this.getAuthtypeMappings() == null || this.getAuthtypeMappings().isEmpty() || this.getAuthtypeMappings().equals("${metalnx.authtype.mappings}")) { for (String scheme : AuthScheme.getAuthSchemeList()) { authTypeList.add(new AuthTypeMapping(scheme, scheme)); } } else { String[] entries; // parse and create a custom auth type list entries = this.getAuthtypeMappings().split("\\|"); for (String entry : entries) { String[] parsedEntry = entry.split(":"); if (parsedEntry.length != 2) { throw new IllegalArgumentException("unparsable authTypeMapping"); } authTypeList.add(new AuthTypeMapping(parsedEntry[0], parsedEntry[1])); } } return authTypeList; } public String getAuthtypeMappings() { return authtypeMappings; } public void setAuthtypeMappings(String authtypeMappings) { this.authtypeMappings = authtypeMappings; } }
27.784983
94
0.742169
58cdb888c12277ce11a2c714001a5bf6c6634d15
1,059
package mobile.madridchange.buhon.adapters.beans; import android.widget.ImageView; import android.widget.TextView; /** * Created by omar on 13/11/16. */ public class EventsBaseAdapterBean { private TextView txtName; private TextView txtDescription; private ImageView imagenEvento; public ImageView getImagenEvento() { return imagenEvento; } public void setImagenEvento(ImageView imagenEvento) { this.imagenEvento = imagenEvento; } public EventsBaseAdapterBean(TextView txtName, TextView txtDescription, ImageView imagenEvento) { this.txtName = txtName; this.txtDescription = txtDescription; this.imagenEvento = imagenEvento; } public TextView getTxtName() { return txtName; } public void setTxtName(TextView txtName) { this.txtName = txtName; } public TextView getTxtDescription() { return txtDescription; } public void setTxtDescription(TextView txtDescription) { this.txtDescription = txtDescription; } }
23.533333
101
0.69594
cb33d773aca71ff2821d50fc2266457354ba97ca
327
package ch.hsr.sai14sa12.blogmicroservice.blog; import ch.hsr.sai14sa12.blogmicroservice.blog.dto.BlogDto; import java.util.List; import java.util.UUID; public interface BlogService { void createBlog(String title, String description, UUID userId); List<BlogDto> getAllBlogs(); BlogDto getBlogById(long id); }
20.4375
67
0.767584
f62e6700c41226604d8deb3e0f617551624e5576
1,339
package webflux.cassandra.example.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.cassandra.core.ReactiveCassandraOperations; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.client.WebClient; import webflux.cassandra.example.event.OnReadyEvent; import webflux.cassandra.example.http.HackerNewsClient; import webflux.cassandra.example.repository.ArticleRepository; @Configuration public class HttpConfig { @Value("${hackernews.url}") private String hackernewsUrl; @Bean public OnReadyEvent initializeDatabase(HackerNewsClient hackerNewsClient, ArticleRepository articleRepository) { return new OnReadyEvent(hackerNewsClient, articleRepository); } @Bean public HackerNewsClient hackerNewsClient(WebClient hackerNewsWebClient) { return new HackerNewsClient(hackerNewsWebClient); } @Bean public WebClient hackerNewsWebClient() { return WebClient.builder() .baseUrl(hackernewsUrl) .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON.toString()) .build(); } }
35.236842
116
0.775952
88a2172c48158434883ae19fa4df944194c069da
7,244
package com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.domain; import java.util.Date; import javax.annotation.Generated; public class DataName { @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.979+08:00", comments="Source field: data_name.id") private Long id; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.979+08:00", comments="Source field: data_name.data_name") private String dataName; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.display_name") private String displayName; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.data_source_id") private Long dataSourceId; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.datasource_type") private String datasourceType; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.timestamp_field") private String timestampField; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.properties") private String properties; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.creator") private String creator; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.create_at") private Date createAt; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.modifier") private String modifier; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.modify_at") private Date modifyAt; @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.979+08:00", comments="Source field: data_name.id") public Long getId() { return id; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.979+08:00", comments="Source field: data_name.id") public void setId(Long id) { this.id = id; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.979+08:00", comments="Source field: data_name.data_name") public String getDataName() { return dataName; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.979+08:00", comments="Source field: data_name.data_name") public void setDataName(String dataName) { this.dataName = dataName; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.display_name") public String getDisplayName() { return displayName; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.display_name") public void setDisplayName(String displayName) { this.displayName = displayName; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.data_source_id") public Long getDataSourceId() { return dataSourceId; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.data_source_id") public void setDataSourceId(Long dataSourceId) { this.dataSourceId = dataSourceId; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.datasource_type") public String getDatasourceType() { return datasourceType; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.datasource_type") public void setDatasourceType(String datasourceType) { this.datasourceType = datasourceType; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.timestamp_field") public String getTimestampField() { return timestampField; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.timestamp_field") public void setTimestampField(String timestampField) { this.timestampField = timestampField; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.properties") public String getProperties() { return properties; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.properties") public void setProperties(String properties) { this.properties = properties; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.creator") public String getCreator() { return creator; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.creator") public void setCreator(String creator) { this.creator = creator; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.create_at") public Date getCreateAt() { return createAt; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.create_at") public void setCreateAt(Date createAt) { this.createAt = createAt; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.modifier") public String getModifier() { return modifier; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.modifier") public void setModifier(String modifier) { this.modifier = modifier; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.modify_at") public Date getModifyAt() { return modifyAt; } @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-09-07T18:59:32.98+08:00", comments="Source field: data_name.modify_at") public void setModifyAt(Date modifyAt) { this.modifyAt = modifyAt; } }
48.61745
155
0.724462
c67fc8febb517df4d5cd8e08e8dba691869f1245
2,049
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.test.check.registrycenter.initializer; import org.apache.dubbo.test.check.exception.DubboTestException; import org.apache.dubbo.test.check.registrycenter.Context; import org.apache.dubbo.test.check.registrycenter.Initializer; import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext; import java.util.concurrent.atomic.AtomicBoolean; /** * The implementation of {@link Initializer} to initialize zookeeper. */ public abstract class ZookeeperInitializer implements Initializer { /** * The {@link #INITIALIZED} for checking the {@link #initialize(Context)} method is called or not. */ private final AtomicBoolean INITIALIZED = new AtomicBoolean(false); @Override public void initialize(Context context) throws DubboTestException { if (!this.INITIALIZED.compareAndSet(false, true)) { return; } this.doInitialize((ZookeeperContext) context); } /** * Initialize the global context for zookeeper. * * @param context the global context for zookeeper. * @throws DubboTestException when any exception occurred. */ protected abstract void doInitialize(ZookeeperContext context) throws DubboTestException; }
39.403846
102
0.747194
e9cf3980ea952786778871417af3ae7dabba43b3
2,505
package org.semanticweb.elk.reasoner.saturation.conclusions.classes; /* * #%L * ELK Reasoner * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2011 - 2016 Department of Computer Science, University of Oxford * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.semanticweb.elk.Reference; import org.semanticweb.elk.reasoner.saturation.conclusions.model.ClassConclusion; import org.semanticweb.elk.reasoner.saturation.context.ClassConclusionSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A {@link ClassConclusion.Visitor} that checks if visited * {@link ClassConclusion} is contained the {@link ClassConclusionSet} value of * the given {@link Reference}. The visit method returns {@code true} if the * {@link ClassConclusion} occurs in the {@link ClassConclusionSet} and * {@code false} otherwise. * * @see ClassConclusionInsertionVisitor * @see ClassConclusionDeletionVisitor * @see ClassConclusionOccurrenceCheckingVisitor * * @author "Yevgeny Kazakov" */ public class ClassConclusionOccurrenceCheckingVisitor extends DummyClassConclusionVisitor<Boolean> { // logger for events private static final Logger LOGGER_ = LoggerFactory .getLogger(ClassConclusionOccurrenceCheckingVisitor.class); private final Reference<? extends ClassConclusionSet> conclusionsRef_; public ClassConclusionOccurrenceCheckingVisitor(Reference<? extends ClassConclusionSet> conclusions) { this.conclusionsRef_ = conclusions; } // TODO: make this by combining the visitor in order to avoid overheads when // logging is switched off @Override protected Boolean defaultVisit(ClassConclusion conclusion) { ClassConclusionSet conclusions = conclusionsRef_.get(); boolean result = conclusions == null ? false : conclusions.containsConclusion(conclusion); if (LOGGER_.isTraceEnabled()) { LOGGER_.trace("{}: check occurrence of {}: {}", conclusions, conclusion, result ? "success" : "failure"); } return result; } }
34.315068
103
0.756886
67d8a937b61bc2cfdd6408ed985e4cc2737b51b1
749
package nl.certificate; import java.io.FileOutputStream; import java.io.PrintStream; import java.security.cert.X509Certificate; import java.util.Base64; public class CertificateWriter { public static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; public static final String END_CERT = "-----END CERTIFICATE-----"; public static void write(X509Certificate x509Certificate) { try { FileOutputStream out= new FileOutputStream( "mdentree_prod.pem"); PrintStream pos= new PrintStream( out); pos.println( BEGIN_CERT); pos.write( Base64.getEncoder().encode(x509Certificate.getEncoded())); pos.println( ); pos.println( END_CERT); out.close(); } catch (Exception e) { throw new RuntimeException(e); } } }
28.807692
75
0.720961
65640d27206c4e47f1dcdeba558d46f068b8f180
191
package uk.gov.companieshouse.exception; public class DocumentRenderException extends RuntimeException { public DocumentRenderException(String message) { super(message); } }
23.875
63
0.764398
e12ce3f3bad63a94307e65d1d236b5756f2cad35
728
package exam.model.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.Table; @Entity @Table(name = "categories") public class Category extends BaseEntity { private CategoryName category; private String description; @Enumerated public CategoryName getCategory() { return category; } public void setCategory(CategoryName category) { this.category = category; } @Column(name = "description", columnDefinition = "TEXT") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
22.060606
60
0.706044
580eda0cdd5c34e3846c0205e2d2b579bf5c9c6f
388
package cn.qumiandan.web.frontServer.games.entity.request; import java.math.BigDecimal; import javax.validation.constraints.NotNull; import lombok.Data; @Data public class AddShareGameOrderParams { @NotNull(message = "订单id不能为空") private String orderId; @NotNull(message = "游戏单价price不能为空") private BigDecimal price; @NotNull(message = "游戏倍数不能为空") private Integer times; }
18.47619
58
0.770619
f754e5dc603163b2ae473d6f69cdbb4d5d6465ed
22,975
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tom_roush.pdfbox.util; import android.graphics.PointF; import java.util.Arrays; import com.tom_roush.harmony.awt.geom.AffineTransform; import com.tom_roush.pdfbox.cos.COSArray; import com.tom_roush.pdfbox.cos.COSBase; import com.tom_roush.pdfbox.cos.COSFloat; import com.tom_roush.pdfbox.cos.COSNumber; /** * This class will be used for matrix manipulation. * * @author Ben Litchfield */ public final class Matrix implements Cloneable { static final float[] DEFAULT_SINGLE = { 1,0,0, // a b 0 sx hy 0 note: hx and hy are reversed vs. the PDF spec as we use 0,1,0, // c d 0 = hx sy 0 AffineTransform's definition x and y shear 0,0,1 // tx ty 1 tx ty 1 }; private final float[] single; /** * Constructor. This produces an identity matrix. */ public Matrix() { single = new float[DEFAULT_SINGLE.length]; System.arraycopy(DEFAULT_SINGLE, 0, single, 0, DEFAULT_SINGLE.length); } /** * Creates a matrix from a 6-element (a b c d e f) COS array. * * @param array */ public Matrix(COSArray array) { single = new float[DEFAULT_SINGLE.length]; single[0] = ((COSNumber)array.getObject(0)).floatValue(); single[1] = ((COSNumber)array.getObject(1)).floatValue(); single[3] = ((COSNumber)array.getObject(2)).floatValue(); single[4] = ((COSNumber)array.getObject(3)).floatValue(); single[6] = ((COSNumber)array.getObject(4)).floatValue(); single[7] = ((COSNumber)array.getObject(5)).floatValue(); single[8] = 1; } /** * Creates a transformation matrix with the given 6 elements. Transformation matrices are * discussed in 8.3.3, "Common Transformations" and 8.3.4, "Transformation Matrices" of the PDF * specification. For simple purposes (rotate, scale, translate) it is recommended to use the * static methods below. * * @see Matrix#getRotateInstance(double, float, float) * @see Matrix#getScaleInstance(float, float) * @see Matrix#getTranslateInstance(float, float) * * @param a the X coordinate scaling element (m00) of the 3x3 matrix * @param b the Y coordinate shearing element (m10) of the 3x3 matrix * @param c the X coordinate shearing element (m01) of the 3x3 matrix * @param d the Y coordinate scaling element (m11) of the 3x3 matrix * @param e the X coordinate translation element (m02) of the 3x3 matrix * @param f the Y coordinate translation element (m12) of the 3x3 matrix */ public Matrix(float a, float b, float c, float d, float e, float f) { single = new float[DEFAULT_SINGLE.length]; single[0] = a; single[1] = b; single[3] = c; single[4] = d; single[6] = e; single[7] = f; single[8] = 1; } /** * Creates a matrix with the same elements as the given AffineTransform. * @param at */ public Matrix(AffineTransform at) { single = new float[DEFAULT_SINGLE.length]; System.arraycopy(DEFAULT_SINGLE, 0, single, 0, DEFAULT_SINGLE.length); single[0] = (float)at.getScaleX(); single[1] = (float)at.getShearY(); single[3] = (float)at.getShearX(); single[4] = (float)at.getScaleY(); single[6] = (float)at.getTranslateX(); single[7] = (float)at.getTranslateY(); } /** * Convenience method to be used when creating a matrix from unverified data. If the parameter * is a COSArray with at least six numbers, a Matrix object is created from the first six * numbers and returned. If not, then the identity Matrix is returned. * * @param base a COS object, preferably a COSArray with six numbers. * * @return a Matrix object. */ public static Matrix createMatrix(COSBase base) { if (!(base instanceof COSArray)) { return new Matrix(); } COSArray array = (COSArray) base; if (array.size() < 6) { return new Matrix(); } for (int i = 0; i < 6; ++i) { if (!(array.getObject(i) instanceof COSNumber)) { return new Matrix(); } } return new Matrix(array); } /** * This method resets the numbers in this Matrix to the original values, which are * the values that a newly constructed Matrix would have. * * @deprecated This method will be removed. */ @Deprecated public void reset() { System.arraycopy(DEFAULT_SINGLE, 0, single, 0, DEFAULT_SINGLE.length); } /** * Create an affine transform from this matrix's values. * * @return An affine transform with this matrix's values. */ public AffineTransform createAffineTransform() { return new AffineTransform( single[0], single[1], // m00 m10 = scaleX shearY single[3], single[4], // m01 m11 = shearX scaleY single[6], single[7] ); // m02 m12 = tx ty } /** * Set the values of the matrix from the AffineTransform. * * @param af The transform to get the values from. * @deprecated Use the {@link #Matrix(AffineTransform)} constructor instead. */ @Deprecated public void setFromAffineTransform( AffineTransform af ) { single[0] = (float)af.getScaleX(); single[1] = (float)af.getShearY(); single[3] = (float)af.getShearX(); single[4] = (float)af.getScaleY(); single[6] = (float)af.getTranslateX(); single[7] = (float)af.getTranslateY(); } /** * This will get a matrix value at some point. * * @param row The row to get the value from. * @param column The column to get the value from. * * @return The value at the row/column position. */ public float getValue( int row, int column ) { return single[row*3+column]; } /** * This will set a value at a position. * * @param row The row to set the value at. * @param column the column to set the value at. * @param value The value to set at the position. */ public void setValue( int row, int column, float value ) { single[row*3+column] = value; } /** * Return a single dimension array of all values in the matrix. * * @return The values of this matrix. */ public float[][] getValues() { float[][] retval = new float[3][3]; retval[0][0] = single[0]; retval[0][1] = single[1]; retval[0][2] = single[2]; retval[1][0] = single[3]; retval[1][1] = single[4]; retval[1][2] = single[5]; retval[2][0] = single[6]; retval[2][1] = single[7]; retval[2][2] = single[8]; return retval; } /** * Return a single dimension array of all values in the matrix. * * @return The values ot this matrix. * @deprecated Use {@link #getValues()} instead. */ @Deprecated public double[][] getValuesAsDouble() { double[][] retval = new double[3][3]; retval[0][0] = single[0]; retval[0][1] = single[1]; retval[0][2] = single[2]; retval[1][0] = single[3]; retval[1][1] = single[4]; retval[1][2] = single[5]; retval[2][0] = single[6]; retval[2][1] = single[7]; retval[2][2] = single[8]; return retval; } /** * Concatenates (premultiplies) the given matrix to this matrix. * * @param matrix The matrix to concatenate. */ public void concatenate(Matrix matrix) { matrix.multiply(this, this); } /** * Translates this matrix by the given vector. * * @param vector 2D vector */ public void translate(Vector vector) { Matrix m = Matrix.getTranslateInstance(vector.getX(), vector.getY()); concatenate(m); } /** * Translates this matrix by the given amount. * * @param tx x-translation * @param ty y-translation */ public void translate(float tx, float ty) { Matrix m = Matrix.getTranslateInstance(tx, ty); concatenate(m); } /** * Scales this matrix by the given factors. * * @param sx x-scale * @param sy y-scale */ public void scale(float sx, float sy) { Matrix m = Matrix.getScaleInstance(sx, sy); concatenate(m); } /** * Rotares this matrix by the given factors. * * @param theta The angle of rotation measured in radians */ public void rotate(double theta) { Matrix m = Matrix.getRotateInstance(theta, 0, 0); concatenate(m); } /** * This will take the current matrix and multiply it with a matrix that is passed in. * * @param b The matrix to multiply by. * * @return The result of the two multiplied matrices. */ public Matrix multiply( Matrix b ) { return this.multiply(b, new Matrix()); } /** * This method multiplies this Matrix with the specified other Matrix, storing the product in the specified * result Matrix. By reusing Matrix instances like this, multiplication chains can be executed without having * to create many temporary Matrix objects. * <p> * It is allowed to have (other == this) or (result == this) or indeed (other == result) but if this is done, * the backing float[] matrix values may be copied in order to ensure a correct product. * * @param other the second operand Matrix in the multiplication * @param result the Matrix instance into which the result should be stored. If result is null, a new Matrix * instance is created. * @return the product of the two matrices. */ public Matrix multiply( Matrix other, Matrix result ) { if (result == null) { result = new Matrix(); } if (other != null && other.single != null) { // the operands float[] thisOperand = this.single; float[] otherOperand = other.single; // We're multiplying 2 sets of floats together to produce a third, but we allow // any of these float[] instances to be the same objects. // There is the possibility then to overwrite one of the operands with result values // and therefore corrupt the result. // If either of these operands are the same float[] instance as the result, then // they need to be copied. if (this == result) { final float[] thisOrigVals = new float[this.single.length]; System.arraycopy(this.single, 0, thisOrigVals, 0, this.single.length); thisOperand = thisOrigVals; } if (other == result) { final float[] otherOrigVals = new float[other.single.length]; System.arraycopy(other.single, 0, otherOrigVals, 0, other.single.length); otherOperand = otherOrigVals; } result.single[0] = thisOperand[0] * otherOperand[0] + thisOperand[1] * otherOperand[3] + thisOperand[2] * otherOperand[6]; result.single[1] = thisOperand[0] * otherOperand[1] + thisOperand[1] * otherOperand[4] + thisOperand[2] * otherOperand[7]; result.single[2] = thisOperand[0] * otherOperand[2] + thisOperand[1] * otherOperand[5] + thisOperand[2] * otherOperand[8]; result.single[3] = thisOperand[3] * otherOperand[0] + thisOperand[4] * otherOperand[3] + thisOperand[5] * otherOperand[6]; result.single[4] = thisOperand[3] * otherOperand[1] + thisOperand[4] * otherOperand[4] + thisOperand[5] * otherOperand[7]; result.single[5] = thisOperand[3] * otherOperand[2] + thisOperand[4] * otherOperand[5] + thisOperand[5] * otherOperand[8]; result.single[6] = thisOperand[6] * otherOperand[0] + thisOperand[7] * otherOperand[3] + thisOperand[8] * otherOperand[6]; result.single[7] = thisOperand[6] * otherOperand[1] + thisOperand[7] * otherOperand[4] + thisOperand[8] * otherOperand[7]; result.single[8] = thisOperand[6] * otherOperand[2] + thisOperand[7] * otherOperand[5] + thisOperand[8] * otherOperand[8]; } return result; } /** * Transforms the given point by this matrix. * * @param point point to transform */ public void transform(PointF point) { float x = (float)point.x; float y = (float)point.y; float a = single[0]; float b = single[1]; float c = single[3]; float d = single[4]; float e = single[6]; float f = single[7]; point.set(x * a + y * c + e, x * b + y * d + f); } /** * Transforms the given point by this matrix. * * @param x x-coordinate * @param y y-coordinate */ public PointF transformPoint(float x, float y) { float a = single[0]; float b = single[1]; float c = single[3]; float d = single[4]; float e = single[6]; float f = single[7]; return new PointF(x * a + y * c + e, x * b + y * d + f); } /** * Transforms the given point by this matrix. * * @param vector 2D vector */ public Vector transform(Vector vector) { float a = single[0]; float b = single[1]; float c = single[3]; float d = single[4]; float e = single[6]; float f = single[7]; float x = vector.getX(); float y = vector.getY(); return new Vector(x * a + y * c + e, x * b + y * d + f); } /** * Create a new matrix with just the scaling operators. * * @return A new matrix with just the scaling operators. * @deprecated This method is due to be removed, please contact us if you make use of it. */ @Deprecated public Matrix extractScaling() { Matrix matrix = new Matrix(); matrix.single[0] = this.single[0]; matrix.single[4] = this.single[4]; return matrix; } /** * Convenience method to create a scaled instance. * * @param sx The xscale operator. * @param sy The yscale operator. * @return A new matrix with just the x/y scaling */ public static Matrix getScaleInstance(float sx, float sy) { Matrix matrix = new Matrix(); matrix.single[0] = sx; matrix.single[4] = sy; return matrix; } /** * Create a new matrix with just the translating operators. * * @return A new matrix with just the translating operators. * @deprecated This method is due to be removed, please contact us if you make use of it. */ @Deprecated public Matrix extractTranslating() { Matrix matrix = new Matrix(); matrix.single[6] = this.single[6]; matrix.single[7] = this.single[7]; return matrix; } /** * Convenience method to create a translating instance. * * @param tx The x translating operator. * @param ty The y translating operator. * @return A new matrix with just the x/y translating. * @deprecated Use {@link #getTranslateInstance} instead. */ @Deprecated public static Matrix getTranslatingInstance(float tx, float ty) { return getTranslateInstance(tx, ty); } /** * Convenience method to create a translating instance. * * @param tx The x translating operator. * @param ty The y translating operator. * @return A new matrix with just the x/y translating. */ public static Matrix getTranslateInstance(float tx, float ty) { Matrix matrix = new Matrix(); matrix.single[6] = tx; matrix.single[7] = ty; return matrix; } /** * Convenience method to create a rotated instance. * * @param theta The angle of rotation measured in radians * @param tx The x translation. * @param ty The y translation. * @return A new matrix with the rotation and the x/y translating. */ public static Matrix getRotateInstance(double theta, float tx, float ty) { float cosTheta = (float)Math.cos(theta); float sinTheta = (float)Math.sin(theta); Matrix matrix = new Matrix(); matrix.single[0] = cosTheta; matrix.single[1] = sinTheta; matrix.single[3] = -sinTheta; matrix.single[4] = cosTheta; matrix.single[6] = tx; matrix.single[7] = ty; return matrix; } /** * Produces a copy of the first matrix, with the second matrix concatenated. * * @param a The matrix to copy. * @param b The matrix to concatenate. */ public static Matrix concatenate(Matrix a, Matrix b) { Matrix copy = a.clone(); copy.concatenate(b); return copy; } /** * Clones this object. * @return cloned matrix as an object. */ @Override public Matrix clone() { Matrix clone = new Matrix(); System.arraycopy( single, 0, clone.single, 0, 9 ); return clone; } /** * Returns the x-scaling factor of this matrix. This is calculated from the scale and shear. * * @return The x-scaling factor. */ public float getScalingFactorX() { float xScale = single[0]; /** * BM: if the trm is rotated, the calculation is a little more complicated * * The rotation matrix multiplied with the scaling matrix is: * ( x 0 0) ( cos sin 0) ( x*cos x*sin 0) * ( 0 y 0) * (-sin cos 0) = (-y*sin y*cos 0) * ( 0 0 1) ( 0 0 1) ( 0 0 1) * * So, if you want to deduce x from the matrix you take * M(0,0) = x*cos and M(0,1) = x*sin and use the theorem of Pythagoras * * sqrt(M(0,0)^2+M(0,1)^2) = * sqrt(x2*cos2+x2*sin2) = * sqrt(x2*(cos2+sin2)) = <- here is the trick cos2+sin2 is one * sqrt(x2) = * abs(x) */ if( !(single[1]==0.0f && single[3]==0.0f) ) { xScale = (float)Math.sqrt(Math.pow(single[0], 2)+ Math.pow(single[1], 2)); } return xScale; } /** * Returns the y-scaling factor of this matrix. This is calculated from the scale and shear. * * @return The y-scaling factor. */ public float getScalingFactorY() { float yScale = single[4]; if( !(single[1]==0.0f && single[3]==0.0f) ) { yScale = (float)Math.sqrt(Math.pow(single[3], 2)+ Math.pow(single[4], 2)); } return yScale; } /** * Returns the x-scaling element of this matrix. * * @see #getScalingFactorX() */ public float getScaleX() { return single[0]; } /** * Returns the y-shear element of this matrix. */ public float getShearY() { return single[1]; } /** * Returns the x-shear element of this matrix. */ public float getShearX() { return single[3]; } /** * Returns the y-scaling element of this matrix. * * @see #getScalingFactorY() */ public float getScaleY() { return single[4]; } /** * Returns the x-translation element of this matrix. */ public float getTranslateX() { return single[6]; } /** * Returns the y-translation element of this matrix. */ public float getTranslateY() { return single[7]; } /** * Get the x position in the matrix. This method is deprecated as it is incorrectly named. * * @return The x-position. * @deprecated Use {@link #getTranslateX} instead */ @Deprecated public float getXPosition() { return single[6]; } /** * Get the y position. This method is deprecated as it is incorrectly named. * * @return The y position. * @deprecated Use {@link #getTranslateY} instead */ @Deprecated public float getYPosition() { return single[7]; } /** * Returns a COS array which represent the geometric relevant * components of the matrix. The last column of the matrix is ignored, * only the first two columns are returned. This is analog to the * Matrix(COSArray) constructor. */ public COSArray toCOSArray() { COSArray array = new COSArray(); array.add(new COSFloat(single[0])); array.add(new COSFloat(single[1])); array.add(new COSFloat(single[3])); array.add(new COSFloat(single[4])); array.add(new COSFloat(single[6])); array.add(new COSFloat(single[7])); return array; } @Override public String toString() { return "[" + single[0] + "," + single[1] + "," + single[3] + "," + single[4] + "," + single[6] + "," + single[7] + "]"; } @Override public int hashCode() { return Arrays.hashCode(single); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return Arrays.equals(this.single, ((Matrix) obj).single); } }
30.270092
113
0.566877
cb94ca022ee37136d770ffd67f64702141d1e991
18,318
package ui.custom.fx; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javafx.geometry.Rectangle2D; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; /** * A line chart depicting various data points across multiple series. Abstract to force consolidation of the logic behind implementations for various template types. * @param <T> The type of object which is contained within the graph. * @param <TX> The type for the X axis. * @param <TY> The type for the Y axis. */ public abstract class Chart<T, TX extends Comparable<TX>, TY extends Comparable<TY>> extends Canvas { public final static Rectangle2D DEFAULT_VIEWPORT = new Rectangle2D(-0.05, 0.0, 1.1, 1.05); private static final Color[] colors = new Color[] {Color.RED, Color.BLUE, Color.GREEN, Color.PURPLE, Color.ORANGE, Color.YELLOW, Color.LIGHTGREEN, Color.DARKCYAN, Color.DARKGREEN, Color.MAGENTA, Color.LIGHTBLUE, Color.DARKBLUE}; private static int idx = 0; public static class Series<T> { private String name; private final List<T> data; private Color color; private final SimpleBooleanProperty visible; public Series() { this.name = null; this.data = new ArrayList<>(); this.color = colors[Chart.idx++ % Chart.colors.length]; this.visible = new SimpleBooleanProperty(true); } public List<T> getData() { return data; } public void setName(String name) { this.name = name; } public String getName() { return name; } public Color getColor() { return color; } public BooleanProperty visibleProperty() { return visible; } } public static class Range<T extends Comparable<T>> { private final T min; private final T max; public Range(T min, T max) { this.min = min; this.max = max; } public T getMin() { return min; } public T getMax() { return max; } public boolean contains(T val) { if(val == null) { return false; } if(min != null) { if(min.compareTo(val) > 0) { return false; } } if(max != null) { if(max.compareTo(val) < 0) { return false; } } return true; } @Override public String toString() { return "<" + min + ", " + max + ">"; } } @FunctionalInterface public interface Normalizer<T extends Comparable<T>> { double normalize(Range<T> bounds, T value); } @FunctionalInterface public interface GenerateTicks<T extends Comparable<T>> { List<T> generateTicks(Range<T> base, double low, double high); } protected static class Point<T, TX, TY> { private Point2D location; private TX x; private TY y; private T datum; private Color color; public Point(T datum, TX x, TY y, Point2D location, Color color) { this.location = location; this.x = x; this.y = y; this.datum = datum; this.color = color; } public T getDatum() { return datum; } } private final List<Series<T>> series; private final AtomicBoolean redrawPending = new AtomicBoolean(false); private final AtomicBoolean redrawSuspended = new AtomicBoolean(false); private final Function<T, TX> fnXValue; private final Function<T, TY> fnYValue; private final Normalizer<TX> fnNormalizerX; private final Normalizer<TY> fnNormalizerY; private final GenerateTicks<TX> fnTicksX; private final GenerateTicks<TY> fnTicksY; private final Function<TX, String> fnFormatX; private final Function<TY, String> fnFormatY; private Range<TX> rangeX; private Range<TY> rangeY; private double pxTickLength = 5.0; private Rectangle2D viewport; private final Text textForMeasuring = new Text(); protected double pointRadius = 5.0; protected double interactRadius = 15.0; protected final List<Point<T, TX, TY>> renderedPoints = new ArrayList<>(); protected Chart(Function<T, TX> fnX, Function<T, TY> fnY, Normalizer<TX> fnNormalizerX, Normalizer<TY> fnNormalizerY, GenerateTicks<TX> fnTicksX, GenerateTicks<TY> fnTicksY, Function<TX, String> fnFormatX, Function<TY, String> fnFormatY) { this.series = new LinkedList<>(); this.fnXValue = fnX; this.fnYValue = fnY; this.fnNormalizerX = fnNormalizerX; this.fnNormalizerY = fnNormalizerY; this.fnTicksX = fnTicksX; this.fnTicksY = fnTicksY; this.fnFormatX = fnFormatX; this.fnFormatY = fnFormatY; this.viewport = DEFAULT_VIEWPORT; this.textForMeasuring.setFont(Font.font("MONOSPACE", 12.0)); setHeight(200.0); setWidth(200.0); widthProperty().addListener((observable, oldValue, newValue) -> redraw()); heightProperty().addListener((observable, oldValue, newValue) -> redraw()); } @Override public boolean isResizable() { return true; } @Override public double minHeight(double width) { return 0.0; } @Override public double maxHeight(double width) { return 10000.0; } @Override public double minWidth(double height) { return 0.0; } @Override public double maxWidth(double height) { return 10000.0; } @Override public double prefWidth(double height) { return 0.0; } @Override public double prefHeight(double width) { return 0.0; } @Override public void resize(double width, double height) { setWidth(width); setHeight(height); } public void clearSeries() { this.series.clear(); redraw(); } public void addSeries(Series<T> series) { this.series.add(series); redraw(); } public void removeSeries(Series<T> series) { this.series.remove(series); redraw(); } public void setXRange(Range<TX> range) { rangeX = range; redraw(); } public void setYRange(Range<TY> range) { rangeY = range; redraw(); } public void suspendLayout(boolean state) { if(state) { redrawSuspended.set(true); } else { if(redrawSuspended.getAndSet(false) && redrawPending.get()) { redraw(); } } } public void zoom(Rectangle2D viewport) { this.viewport = viewport; redraw(); } public double viewportXForControlX(final double pxX) { //Prevent tearing if used multithreaded. final Rectangle2D rect = rectChart; return (pxX - rect.getMinX()) / rect.getWidth() * viewport.getWidth() + viewport.getMinX(); } public boolean pointInsideViewport(final Point2D pt) { return rectChart.contains(pt); } //Used in the paint method, stored for use in viewportXForControlX and pointInsideViewport methods. private Rectangle2D rectChart = new Rectangle2D(0, 0, 0, 0); protected double chartXFromDataX(Range<TX> axisX, TX x) { if(axisX.getMin().equals(axisX.getMax())) { return 0.5 * rectChart.getWidth() + rectChart.getMinX(); } else { final double normalizedX = fnNormalizerX.normalize(axisX, x); return (normalizedX - viewport.getMinX()) / viewport.getWidth() * rectChart.getWidth() + rectChart.getMinX(); } } protected double chartYFromDataY(Range<TY> axisY, TY y) { return (1 - (fnNormalizerY.normalize(axisY, y) - viewport.getMinY()) / viewport.getHeight()) * rectChart.getHeight() + rectChart.getMinY(); } /** * Trigger a redraw in the Fx Application Thread. If called from the app thread it will be called directly, otherwise it will be scheduled to run later. */ protected final void redraw() { redrawPending.set(true); if(!Platform.isFxApplicationThread()) { Platform.runLater(this::redraw); return; } //If we haven't requested a redraw since the last draw, we can skip this redraw because nothing will have changed. if(!redrawSuspended.get()) { if (redrawPending.getAndSet(false)) { GraphicsContext gc = this.getGraphicsContext2D(); gc.clearRect(0.0, 0.0, getWidth(), getHeight()); paint(gc); } } } protected void paint(GraphicsContext gc) { // Get a sorted copy of the series data. Once we have this we can release locks. Rectangle2D rectViewport = viewport; HashMap<Series, LinkedList<T>> data = new HashMap<>(); for(Series<T> series : this.series) { LinkedList<T> seriesData = new LinkedList<>(series.getData()); seriesData.sort((o1, o2) -> fnXValue.apply(o1).compareTo(fnXValue.apply(o2))); data.put(series, seriesData); } //Make sure we have data before continuing. if(data.size() == 0) { return; } if(data.values().stream().flatMap(LinkedList::stream).count() == 0) { return; } // Calculate the range on each axis. Range<TX> axisX; Range<TY> axisY; //TODO: Since we just sorted by X, we can optimize this a bit. if(rangeX != null) { axisX = new Range<>( rangeX.min == null ? data.values().stream().flatMap(LinkedList::stream).map(fnXValue).min(TX::compareTo).get() : rangeX.min, rangeX.max == null ? data.values().stream().flatMap(LinkedList::stream).map(fnXValue).max(TX::compareTo).get() : rangeX.max ); } else { axisX = new Range<>( data.values().stream().flatMap(LinkedList::stream).map(fnXValue).min(TX::compareTo).get(), data.values().stream().flatMap(LinkedList::stream).map(fnXValue).max(TX::compareTo).get() ); } if(rangeY != null) { axisY = new Range<>( rangeY.min == null ? data.values().stream().flatMap(LinkedList::stream).map(fnYValue).min(TY::compareTo).get() : rangeY.min, rangeY.max == null ? data.values().stream().flatMap(LinkedList::stream).map(fnYValue).max(TY::compareTo).get() : rangeY.max ); } else { axisY = new Range<>( data.values().stream().flatMap(LinkedList::stream).map(fnYValue).min(TY::compareTo).get(), data.values().stream().flatMap(LinkedList::stream).map(fnYValue).max(TY::compareTo).get() ); } final List<TX> ticksX = fnTicksX.generateTicks(axisX, viewport.getMinX(), viewport.getMaxX()); //axisX = new Range<>(ticksX.get(0), ticksX.get(ticksX.size() - 1)); //rangeXRendered = axisX; final List<TY> ticksY = fnTicksY.generateTicks(axisY, viewport.getMinY(), viewport.getMaxY()); //axisY = new Range<>(ticksY.get(0), ticksY.get(ticksY.size() - 1)); // Calculate the width of the widest Y-axis label and the height of the tallest X-axis label. double maxWidth = 0.0; double pxMinSpacingBetweenTicks = 0.0; for(TY tickY : ticksY) { textForMeasuring.setText(fnFormatY.apply(tickY)); maxWidth = Math.max(maxWidth, textForMeasuring.getLayoutBounds().getWidth()); pxMinSpacingBetweenTicks = Math.max(pxMinSpacingBetweenTicks, 2.0 * textForMeasuring.getLayoutBounds().getHeight()); } double maxHeight = 0.0; for(TX tickX : ticksX) { //X-labels are displayed at a 30-degree incline. //The approximate width of the rotated text is 0.87*{width} //The distance from the top of the bounding to the origin from which text should be drawn is 0.5*{length} + 0.87*{height} textForMeasuring.setText(fnFormatX.apply(tickX)); final Bounds boundsText = textForMeasuring.getLayoutBounds(); maxHeight = Math.max(maxHeight, 0.5 * boundsText.getWidth() + 0.87 * boundsText.getHeight()); //TODO: Also check maxWidth against the amount by which this would underflow the X=0 line } final Rectangle2D sizeAxisLabel = new Rectangle2D(0.0, 0.0, maxWidth, maxHeight); if(getWidth() <= sizeAxisLabel.getWidth() || getHeight() <= sizeAxisLabel.getHeight()) { return; } rectChart = new Rectangle2D(sizeAxisLabel.getWidth() + pxTickLength, 0.0, getWidth() - sizeAxisLabel.getWidth() - pxTickLength, getHeight() - sizeAxisLabel.getHeight() - pxTickLength); // Render series data, build tooltip cache renderedPoints.clear(); for(Map.Entry<Series, LinkedList<T>> entry : data.entrySet()) { Point2D ptPrev = null; gc.setStroke(entry.getKey().getColor()); //TODO: Make this customizable gc.setLineWidth(2.0); for(T value : entry.getValue()) { TX x = fnXValue.apply(value); TY y = fnYValue.apply(value); // Add rectViewport.getMinY() instead of subtracting because we're mirroring the Y coordinate around the X-axis. Point2D ptNew = new Point2D( chartXFromDataX(axisX, x), chartYFromDataY(axisY, y)); Point<T, TX, TY> pt = new Point<>( value, x, y, ptNew, entry.getKey().getColor() ); renderedPoints.add(pt); if(ptPrev != null) { gc.strokeLine(ptPrev.getX(), ptPrev.getY(), ptNew.getX(), ptNew.getY()); } gc.strokeOval(ptNew.getX() - pointRadius, ptNew.getY() - pointRadius, pointRadius * 2, pointRadius * 2); ptPrev = ptNew; } } // Render axes (last so it overwrites any values near an axis) //Clear the axis area gc.clearRect(0.0, 0.0, sizeAxisLabel.getWidth() + pxTickLength, getHeight()); gc.clearRect(0.0, getHeight() - sizeAxisLabel.getHeight() - pxTickLength, getWidth(), sizeAxisLabel.getHeight()); //Draw the axes gc.setStroke(Color.BLACK); gc.setLineWidth(0.5); gc.strokeLine(rectChart.getMinX(), 0.0, rectChart.getMinX(), rectChart.getMaxY()); gc.strokeLine(rectChart.getMinX(), rectChart.getMaxY(), rectChart.getMaxX(), rectChart.getMaxY()); Font font = Font.font("MONOSPACE", 12.0); gc.setFont(font); //ticksX and ticksY are lists of the corresponding values; they need to be handed of to the corresponding fnNormalize and then scaled for display. double pxLast = -pxMinSpacingBetweenTicks; for(TX tickX : ticksX) { final double pxX = chartXFromDataX(axisX, tickX); if(pxLast + pxMinSpacingBetweenTicks > pxX) { continue; } pxLast = pxX; gc.strokeLine(pxX, rectChart.getMaxY(), pxX, rectChart.getMaxY() + pxTickLength); final String textLabel = fnFormatX.apply(tickX); textForMeasuring.setText(textLabel); final Bounds boundsText = textForMeasuring.getLayoutBounds(); double offsetY = 0.5 * boundsText.getWidth() + 0.87 * boundsText.getHeight(); double offsetX = -0.87 * boundsText.getWidth(); gc.save(); // Translate then rotate to rotate text around local origin rather than rotating around the canvas origin. // Rotating and drawing at an offset results in a rotation around the origin. gc.translate(pxX + offsetX, rectChart.getMaxY() + offsetY); gc.rotate(-30.0); gc.strokeText(textLabel, 0.0, 0.0); gc.restore(); } for(TY tickY : ticksY) { final double pxY = chartYFromDataY(axisY, tickY); gc.strokeLine(rectChart.getMinX() - pxTickLength, pxY, rectChart.getMinX(), pxY); final String textLabel = fnFormatY.apply(tickY); textForMeasuring.setText(textLabel); gc.strokeText(fnFormatY.apply(tickY), 0.0, pxY + textForMeasuring.getLayoutBounds().getHeight()); } } protected List<T> pointsNearLocation(final Point2D screenNear) { final Point2D ptNear = this.screenToLocal(screenNear); return renderedPoints.stream() .filter(point -> point.location.distance(ptNear) < interactRadius) .sorted((o1, o2) -> Double.compare(o1.location.distance(ptNear), o2.location.distance(ptNear))) .limit(50) //Completely arbitrary number; drawing thousands of menu items causes performance issues, the 50 closest should be sufficient. .map(point -> point.getDatum()) .collect(Collectors.toList()); } protected T pointNearestLocation(final Point2D screenNear) { final Point2D ptNear = this.screenToLocal(screenNear); final Optional<T> result = renderedPoints.stream() .filter(point -> point.location.distance(ptNear) < interactRadius) .sorted((o1, o2) -> Double.compare(o1.location.distance(ptNear), o2.location.distance(ptNear))) .map(point -> point.getDatum()) .findFirst(); return result.isPresent() ? result.get() : null; } }
39.224839
232
0.597281
8b89dc470da2ff1a182e6e978f4b02bd98810778
142
/** * Package that contains all the classes for the UI portion of the export * dialog. */ package io.opensphere.analysis.export.view;
23.666667
74
0.711268
43bc2a21664f9c2d7a75b218cfc3d4fb27c79f35
2,433
package apps.lightrays.raytracer.scene; /** * The Class OpticalProperties. */ public class OpticalProperties { /** The colour. */ public Colour colour; /** The diffusion. */ public double diffusion; /** The luminous. */ public boolean luminous; /** The reflectiveness. */ public double reflectiveness; /** The refractiveness. */ public double refractiveness; /** The transparency. */ public double transparency; /** * Instantiates a new optical properties. */ public OpticalProperties() { } /** * Instantiates a new optical properties. * * @param c * the c * @param refra * the refra * @param transp * the transp * @param refle * the refle * @param diffu * the diffu * @param lumin * the lumin */ public OpticalProperties(Colour c, double refra, double transp, double refle, double diffu, boolean lumin) { set(c, refra, transp, refle, diffu, lumin); } /** * Sets the. * * @param c * the c * @param refra * the refra * @param transp * the transp * @param refle * the refle * @param diffu * the diffu * @param lumin * the lumin */ public void set(Colour c, double refra, double transp, double refle, double diffu, boolean lumin) { this.colour = c; this.refractiveness = refra; this.transparency = transp; this.reflectiveness = refle; this.diffusion = diffu; this.luminous = lumin; } /** * Sets the colour. * * @param c * the new colour */ public void setColour(Colour c) { this.colour = c; } /** * Sets the values. * * @param refra * the refra * @param transp * the transp * @param refle * the refle * @param diffu * the diffu * @param lumin * the lumin */ public void setValues(double refra, double transp, double refle, double diffu, boolean lumin) { this.refractiveness = refra; this.transparency = transp; this.reflectiveness = refle; this.diffusion = diffu; this.luminous = lumin; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return "optics[" + colour + "refr:" + refractiveness + ",transp:" + transparency + ",refl:" + reflectiveness + ",dif:" + diffusion + " lumin:" + luminous + "]"; } }
19.780488
69
0.581998
eeafe120296fb5f06db83bef9b5b600029bb64d9
2,716
package javax.persistence.async; import javax.persistence.FlushModeType; import javax.persistence.LockModeType; import javax.persistence.Parameter; import javax.persistence.TemporalType; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; /** * Asynchronous version of {@link javax.persistence.TypedQuery}. * * @author Jakob Korherr */ public interface AsyncQuery<ResultType> { CompletableFuture<List<ResultType>> getResultList(); CompletableFuture<ResultType> getSingleResult(); CompletableFuture<Integer> executeUpdate(); AsyncQuery<ResultType> setMaxResults(int maxResult); int getMaxResults(); AsyncQuery<ResultType> setFirstResult(int startPosition); int getFirstResult(); AsyncQuery<ResultType> setHint(String hintName, Object value); Map<String, Object> getHints(); <T> AsyncQuery<ResultType> setParameter(Parameter<T> param, T value); AsyncQuery<ResultType> setParameter(Parameter<Calendar> param, Calendar value, TemporalType temporalType); AsyncQuery<ResultType> setParameter(Parameter<Date> param, Date value, TemporalType temporalType); AsyncQuery<ResultType> setParameter(String name, Object value); AsyncQuery<ResultType> setParameter(String name, Calendar value, TemporalType temporalType); AsyncQuery<ResultType> setParameter(String name, Date value, TemporalType temporalType); AsyncQuery<ResultType> setParameter(int position, Object value); AsyncQuery<ResultType> setParameter(int position, Calendar value, TemporalType temporalType); AsyncQuery<ResultType> setParameter(int position, Date value, TemporalType temporalType); Set<Parameter<?>> getParameters(); Parameter<?> getParameter(String name); <T> Parameter<T> getParameter(String name, Class<T> type); Parameter<?> getParameter(int position); <T> Parameter<T> getParameter(int position, Class<T> type); boolean isBound(Parameter<?> param); <T> T getParameterValue(Parameter<T> param); Object getParameterValue(String name); Object getParameterValue(int position); AsyncQuery<ResultType> setFlushMode(FlushModeType flushMode); FlushModeType getFlushMode(); AsyncQuery<ResultType> setLockMode(LockModeType lockMode); LockModeType getLockMode(); }
29.204301
73
0.67268
af0b9bada66872673899aa38ffc69fc5cb37fb02
968
package designs.UniqueEmails; import java.util.HashSet; import java.util.Set; public class uniqueEmails { public static int numUniqueEmails(String[] emails) { Set<String> uniqueEmails = new HashSet<>(); for(String s:emails){ int indexAt = s.indexOf('@')<0?s.length():s.indexOf('@'); String local = s.substring(0,indexAt); String domain = s.substring(indexAt); local= local.replaceAll("\\.",""); local=local.substring(0,local.indexOf('+')<0?local.length():local.indexOf('+')); uniqueEmails.add(local+domain); String g = "abc"; g.startsWith(""); } return uniqueEmails.size(); } public static void main(String[] args) { String[] emails = new String[]{"[email protected]","[email protected]","[email protected]"}; System.out.println(numUniqueEmails(emails)); } }
29.333333
140
0.597107
c66a80f0e1d88534cd2d737183df11003929cfca
2,651
package com.mcy.define; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; /** * @ProjectName: DefineStudyDemo * @Package: com.mcy.define * @ClassName: DataBaseUtil * @Description: java类作用描述 * @Author: macy * @CreateDate: 2020/4/28 21:17 * @UpdateUser: 更新者 * @UpdateDate: 2020/4/28 21:17 * @UpdateRemark: 更新说明 * @Version: 1.0 */ public class DataBaseUtil { private static DataBaseUtil mInstance; private SQLiteManager mSqLiteManager; private DataBaseUtil(Context context) { init(context); } public static synchronized DataBaseUtil getInstance(Context context) { if (mInstance == null) { mInstance = new DataBaseUtil(context); } return mInstance; } private void init(Context context) { if (mSqLiteManager == null) { mSqLiteManager = SQLiteManager.getInstance(context); } } public long insertDB(ContentValues contentValues) { SQLiteDatabase writeableDB = mSqLiteManager.getWriteableDB(); long insert = writeableDB.insert(SQLiteHelper.TABLE_NAME, null, contentValues); mSqLiteManager.releaseWriteableDB(); return insert; } public int deleteDB(String[] conditions) { SQLiteDatabase writeableDB = mSqLiteManager.getWriteableDB(); int delete = writeableDB.delete(SQLiteHelper.TABLE_NAME, "name = ? AND age = ?", conditions); mSqLiteManager.releaseWriteableDB(); return delete; } public int updateDB(ContentValues contentValues, String[] conditions) { SQLiteDatabase writeableDB = mSqLiteManager.getWriteableDB(); int update = writeableDB.update(SQLiteHelper.TABLE_NAME, contentValues, "name = ? AND age = ?", conditions); mSqLiteManager.releaseWriteableDB(); return update; } public List<Student> queryDB() { List<Student> list = new ArrayList<>(); SQLiteDatabase readableDB = mSqLiteManager.getReadableDB(); Cursor cursor = readableDB.query(SQLiteHelper.TABLE_NAME, null, null, null, null, null, null); while (cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); Student student = new Student(); student.setName(name); student.setAge(age); list.add(student); } cursor.close(); mSqLiteManager.releaseReadableDB(); return list; } }
32.329268
116
0.666541
702da1bf504c2cb0cf24f892a1f98c6a1e447f2d
1,221
package com.packtpub.springrest.inventory.web; import com.packtpub.springrest.inventory.InventoryService; import com.packtpub.springrest.model.Room; import com.packtpub.springrest.model.RoomCategory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; /** * Resource (controller) class for {@link Room}s. * * @author Ludovic Dewailly */ @RestController @RequestMapping("/rooms") public class RoomsResource { @Autowired private InventoryService inventoryService; public RoomsResource() {} @RequestMapping(value = "/{roomId}", method = RequestMethod.GET) public RoomDTO getRoom(@PathVariable("roomId") long id) { Room room = inventoryService.getRoom(id); return new RoomDTO(room); } @RequestMapping( method = RequestMethod.GET) public List<RoomDTO> getRoomsInCategory(@RequestParam("categoryId") long categoryId) { RoomCategory category = inventoryService.getRoomCategory(categoryId); return inventoryService.getAllRoomsWithCategory(category) .stream().map(RoomDTO::new).collect(Collectors.toList()); } }
31.307692
90
0.739558
cec50f60f9e859be4f63b418836cc35019bf2121
3,283
package de.unikoblenz.west.reveal.stackexchange; import java.util.ArrayList; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class StackUserParser extends DefaultHandler { public static final String ELT_ROW = "row"; public static final String ATT_ID = "Id"; public static final String ATT_REPUT = "Reputation"; public static final String ATT_CREATION = "CreationDate"; public static final String ATT_DISP_NAME = "DisplayName"; public static final String ATT_LAST_ACCESS = "LastAccessDate"; public static final String ATT_VIEWS = "Views"; public static final String ATT_UP_VOTES = "UpVotes"; public static final String ATT_DOWN_VOTES = "DownVotes"; public static final String ATT_ACCOUNT_ID = "AccountId"; public static final String ATT_LOCATION = "Location"; public static final String ATT_AGE = "Age"; public static final String ATT_ABOUT = "AboutMe"; public static final String ATT_WEBSITE = "WebsiteUrl"; public ArrayList<SERawUser> users = new ArrayList<SERawUser>(); @Override public void startDocument() throws SAXException { this.users = new ArrayList<SERawUser>(); } @Override public void endDocument() throws SAXException { } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals(ELT_ROW)) { // <row Id="10" Reputation="412" CreationDate="2013-02-19T21:06:55.953" // DisplayName="charles" LastAccessDate="2014-05-02T21:27:29.540" Views="3" // UpVotes="30" DownVotes="0" AccountId="1895162" /> SERawUser user = new SERawUser(); if (attributes.getIndex(ATT_ID)>=0) { user.id = Integer.parseInt(attributes.getValue(ATT_ID)); } if (attributes.getIndex(ATT_REPUT)>=0) { user.reputation = Integer.parseInt(attributes.getValue(ATT_REPUT)); } if (attributes.getIndex(ATT_CREATION)>=0) { user.creationDate = StackExchangeCommunityFactory.parseDate(attributes.getValue(ATT_CREATION)); } if (attributes.getIndex(ATT_DISP_NAME)>=0) { user.displayName = attributes.getValue(ATT_DISP_NAME); } if (attributes.getIndex(ATT_LAST_ACCESS)>=0) { user.lastAccessDate = StackExchangeCommunityFactory.parseDate(attributes.getValue(ATT_LAST_ACCESS)); } if (attributes.getIndex(ATT_VIEWS)>=0) { user.views = Integer.parseInt(attributes.getValue(ATT_VIEWS)); } if (attributes.getIndex(ATT_UP_VOTES)>=0) { user.upVotes = Integer.parseInt(attributes.getValue(ATT_UP_VOTES)); } if (attributes.getIndex(ATT_DOWN_VOTES)>=0) { user.downVotes = Integer.parseInt(attributes.getValue(ATT_DOWN_VOTES)); } if (attributes.getIndex(ATT_ACCOUNT_ID)>=0) { user.accountId = Integer.parseInt(attributes.getValue(ATT_ACCOUNT_ID)); } if (attributes.getIndex(ATT_LOCATION)>=0) { user.location = attributes.getValue(ATT_LOCATION); } if (attributes.getIndex(ATT_AGE)>=0) { user.age = Integer.parseInt(attributes.getValue(ATT_AGE)); } if (attributes.getIndex(ATT_ABOUT)>=0) { user.aboutMe = attributes.getValue(ATT_ABOUT); } if (attributes.getIndex(ATT_WEBSITE)>=0) { user.websiteUrl = attributes.getValue(ATT_WEBSITE); } this.users.add(user); } } }
34.557895
104
0.731039
fc18ec0e132c4d7c744652b649830515190fae21
2,273
package com.coveo.feign.hierarchy; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.core.type.filter.AssignableTypeFilter; public class CachedSpringClassHierarchySupplier implements ClassHierarchySupplier { private static final Logger logger = LoggerFactory.getLogger(CachedSpringClassHierarchySupplier.class); private static Map<Class<?>, Set<Class<?>>> baseClassSubClassesCache = new HashMap<>(); private Set<Class<?>> subClasses; public CachedSpringClassHierarchySupplier(Class<?> baseClass, String basePackage) { if (!baseClassSubClassesCache.containsKey(baseClass)) { logger.debug( "Cache miss for the SpringClassHierarchySupplier using key '{}' and base package '{}'.", baseClass, basePackage); ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AssignableTypeFilter(baseClass)); Set<Class<?>> subClasses = new HashSet<>(); for (BeanDefinition beanDefinition : provider.findCandidateComponents(basePackage)) { try { subClasses.add(Class.forName(beanDefinition.getBeanClassName())); } catch (ClassNotFoundException e) { throw new IllegalStateException( String.format("Could not load child class '%s'.", beanDefinition.getBeanClassName()), e); } } baseClassSubClassesCache.put(baseClass, subClasses); logger.debug("Found '{}' subClasses.", subClasses.size()); } else { logger.debug("Cache hit for the SpringClassHierarchySupplier using key '{}'.", baseClass); } subClasses = baseClassSubClassesCache.get(baseClass); } @Override public Set<Class<?>> getSubClasses(Class<?> clazz, String basePackage) { return subClasses .stream() .filter(subClass -> clazz.isAssignableFrom(subClass)) .collect(Collectors.toSet()); } }
38.525424
99
0.723273