blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
cf40f74b0bd4935f536541c27c496beccfe6edef
9ec173c503d07f227e5f29a000a88f95f71df0cb
/src/main/java/com/neuedu/controller/ProductUpdateServlet.java
26167defcf878288b9091da1ed103f86c5d24c22
[]
no_license
cyxdy930719/webManager
c3e8683f95ad062b359ad772004417a552e53501
7ad287a8df50676ff3cbada0eef7f312266a6f69
refs/heads/master
2020-04-12T18:43:55.962180
2018-12-31T12:12:12
2018-12-31T12:12:12
162,685,889
0
0
null
null
null
null
UTF-8
Java
false
false
858
java
package com.neuedu.controller; import com.neuedu.pojo.Product; import com.neuedu.service.ProductServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/update") public class ProductUpdateServlet extends HttpServlet { private ProductServiceImpl service = new ProductServiceImpl(); @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int id = Integer.parseInt(req.getParameter("product_id")); Product p = service.getOne(id); req.setAttribute("p",p); req.getRequestDispatcher("WEB-INF/pages/update.jsp").forward(req,resp); } }
c6a3fa75bb56caa215a27dcf45e2546342b11ec2
433c537366a1f52d00bfa652126e00b060ff7102
/src/java/util/Collections.java
4ed1db617ad7a6c35fa3356aa93df6fa76b51eae
[ "Apache-2.0" ]
permissive
xiaoguiguo/DDJDK
2e5046d901c612351101d892c6529fd991255dfe
6dfbda57d4df7c60a2e79eb3c58386ae0c074119
refs/heads/main
2023-08-30T03:36:44.887020
2021-11-15T07:48:13
2021-11-15T07:48:13
421,699,313
0
0
null
null
null
null
UTF-8
Java
false
false
220,162
java
/* * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Array; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import jdk.internal.access.SharedSecrets; /** * This class consists exclusively of static methods that operate on or return * collections. It contains polymorphic algorithms that operate on * collections, "wrappers", which return a new collection backed by a * specified collection, and a few other odds and ends. * * <p>The methods of this class all throw a {@code NullPointerException} * if the collections or class objects provided to them are null. * * <p>The documentation for the polymorphic algorithms contained in this class * generally includes a brief description of the <i>implementation</i>. Such * descriptions should be regarded as <i>implementation notes</i>, rather than * parts of the <i>specification</i>. Implementors should feel free to * substitute other algorithms, so long as the specification itself is adhered * to. (For example, the algorithm used by {@code sort} does not have to be * a mergesort, but it does have to be <i>stable</i>.) * * <p>The "destructive" algorithms contained in this class, that is, the * algorithms that modify the collection on which they operate, are specified * to throw {@code UnsupportedOperationException} if the collection does not * support the appropriate mutation primitive(s), such as the {@code set} * method. These algorithms may, but are not required to, throw this * exception if an invocation would have no effect on the collection. For * example, invoking the {@code sort} method on an unmodifiable list that is * already sorted may or may not throw {@code UnsupportedOperationException}. * * <p>This class is a member of the * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework"> * Java Collections Framework</a>. * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see Set * @see List * @see Map * @since 1.2 */ public class Collections { // Suppresses default constructor, ensuring non-instantiability. private Collections() { } // Algorithms /* * Tuning parameters for algorithms - Many of the List algorithms have * two implementations, one of which is appropriate for RandomAccess * lists, the other for "sequential." Often, the random access variant * yields better performance on small sequential access lists. The * tuning parameters below determine the cutoff point for what constitutes * a "small" sequential access list for each algorithm. The values below * were empirically determined to work well for LinkedList. Hopefully * they should be reasonable for other sequential access List * implementations. Those doing performance work on this code would * do well to validate the values of these parameters from time to time. * (The first word of each tuning parameter name is the algorithm to which * it applies.) */ private static final int BINARYSEARCH_THRESHOLD = 5000; private static final int REVERSE_THRESHOLD = 18; private static final int SHUFFLE_THRESHOLD = 5; private static final int FILL_THRESHOLD = 25; private static final int ROTATE_THRESHOLD = 100; private static final int COPY_THRESHOLD = 10; private static final int REPLACEALL_THRESHOLD = 11; private static final int INDEXOFSUBLIST_THRESHOLD = 35; /** * Sorts the specified list into ascending order, according to the * {@linkplain Comparable natural ordering} of its elements. * All elements in the list must implement the {@link Comparable} * interface. Furthermore, all elements in the list must be * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} * must not throw a {@code ClassCastException} for any elements * {@code e1} and {@code e2} in the list). * * <p>This sort is guaranteed to be <i>stable</i>: equal elements will * not be reordered as a result of the sort. * * <p>The specified list must be modifiable, but need not be resizable. * * @implNote * This implementation defers to the {@link List#sort(Comparator)} * method using the specified list and a {@code null} comparator. * * @param <T> the class of the objects in the list * @param list the list to be sorted. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> (for example, strings and integers). * @throws UnsupportedOperationException if the specified list's * list-iterator does not support the {@code set} operation. * @throws IllegalArgumentException (optional) if the implementation * detects that the natural ordering of the list elements is * found to violate the {@link Comparable} contract * @see List#sort(Comparator) */ @SuppressWarnings("unchecked") public static <T extends Comparable<? super T>> void sort(List<T> list) { list.sort(null); } /** * Sorts the specified list according to the order induced by the * specified comparator. All elements in the list must be <i>mutually * comparable</i> using the specified comparator (that is, * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException} * for any elements {@code e1} and {@code e2} in the list). * * <p>This sort is guaranteed to be <i>stable</i>: equal elements will * not be reordered as a result of the sort. * * <p>The specified list must be modifiable, but need not be resizable. * * @implNote * This implementation defers to the {@link List#sort(Comparator)} * method using the specified list and comparator. * * @param <T> the class of the objects in the list * @param list the list to be sorted. * @param c the comparator to determine the order of the list. A * {@code null} value indicates that the elements' <i>natural * ordering</i> should be used. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> using the specified comparator. * @throws UnsupportedOperationException if the specified list's * list-iterator does not support the {@code set} operation. * @throws IllegalArgumentException (optional) if the comparator is * found to violate the {@link Comparator} contract * @see List#sort(Comparator) */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> void sort(List<T> list, Comparator<? super T> c) { list.sort(c); } /** * Searches the specified list for the specified object using the binary * search algorithm. The list must be sorted into ascending order * according to the {@linkplain Comparable natural ordering} of its * elements (as by the {@link #sort(List)} method) prior to making this * call. If it is not sorted, the results are undefined. If the list * contains multiple elements equal to the specified object, there is no * guarantee which one will be found. * * <p>This method runs in log(n) time for a "random access" list (which * provides near-constant-time positional access). If the specified list * does not implement the {@link RandomAccess} interface and is large, * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. * * @param <T> the class of the objects in the list * @param list the list to be searched. * @param key the key to be searched for. * @return the index of the search key, if it is contained in the list; * otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the list: the index of the first * element greater than the key, or {@code list.size()} if all * elements in the list are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> (for example, strings and * integers), or the search key is not mutually comparable * with the elements of the list. */ public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) { if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) return Collections.indexedBinarySearch(list, key); else return Collections.iteratorBinarySearch(list, key); } private static <T> int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) { int low = 0; int high = list.size()-1; while (low <= high) { int mid = (low + high) >>> 1; Comparable<? super T> midVal = list.get(mid); int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } private static <T> int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key) { int low = 0; int high = list.size()-1; ListIterator<? extends Comparable<? super T>> i = list.listIterator(); while (low <= high) { int mid = (low + high) >>> 1; Comparable<? super T> midVal = get(i, mid); int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } /** * Gets the ith element from the given list by repositioning the specified * list listIterator. */ private static <T> T get(ListIterator<? extends T> i, int index) { T obj = null; int pos = i.nextIndex(); if (pos <= index) { do { obj = i.next(); } while (pos++ < index); } else { do { obj = i.previous(); } while (--pos > index); } return obj; } /** * Searches the specified list for the specified object using the binary * search algorithm. The list must be sorted into ascending order * according to the specified comparator (as by the * {@link #sort(List, Comparator) sort(List, Comparator)} * method), prior to making this call. If it is * not sorted, the results are undefined. If the list contains multiple * elements equal to the specified object, there is no guarantee which one * will be found. * * <p>This method runs in log(n) time for a "random access" list (which * provides near-constant-time positional access). If the specified list * does not implement the {@link RandomAccess} interface and is large, * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. * * @param <T> the class of the objects in the list * @param list the list to be searched. * @param key the key to be searched for. * @param c the comparator by which the list is ordered. * A {@code null} value indicates that the elements' * {@linkplain Comparable natural ordering} should be used. * @return the index of the search key, if it is contained in the list; * otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the list: the index of the first * element greater than the key, or {@code list.size()} if all * elements in the list are less than the specified key. Note * that this guarantees that the return value will be &gt;= 0 if * and only if the key is found. * @throws ClassCastException if the list contains elements that are not * <i>mutually comparable</i> using the specified comparator, * or the search key is not mutually comparable with the * elements of the list using this comparator. */ @SuppressWarnings("unchecked") public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) { if (c==null) return binarySearch((List<? extends Comparable<? super T>>) list, key); if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) return Collections.indexedBinarySearch(list, key, c); else return Collections.iteratorBinarySearch(list, key, c); } private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) { int low = 0; int high = l.size()-1; while (low <= high) { int mid = (low + high) >>> 1; T midVal = l.get(mid); int cmp = c.compare(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) { int low = 0; int high = l.size()-1; ListIterator<? extends T> i = l.listIterator(); while (low <= high) { int mid = (low + high) >>> 1; T midVal = get(i, mid); int cmp = c.compare(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } /** * Reverses the order of the elements in the specified list.<p> * * This method runs in linear time. * * @param list the list whose elements are to be reversed. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the {@code set} operation. */ @SuppressWarnings({"rawtypes", "unchecked"}) public static void reverse(List<?> list) { int size = list.size(); if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) { for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--) swap(list, i, j); } else { // instead of using a raw type here, it's possible to capture // the wildcard but it will require a call to a supplementary // private method ListIterator fwd = list.listIterator(); ListIterator rev = list.listIterator(size); for (int i=0, mid=list.size()>>1; i<mid; i++) { Object tmp = fwd.next(); fwd.set(rev.previous()); rev.set(tmp); } } } /** * Randomly permutes the specified list using a default source of * randomness. All permutations occur with approximately equal * likelihood. * * <p>The hedge "approximately" is used in the foregoing description because * default source of randomness is only approximately an unbiased source * of independently chosen bits. If it were a perfect source of randomly * chosen bits, then the algorithm would choose permutations with perfect * uniformity. * * <p>This implementation traverses the list backwards, from the last * element up to the second, repeatedly swapping a randomly selected element * into the "current position". Elements are randomly selected from the * portion of the list that runs from the first element to the current * position, inclusive. * * <p>This method runs in linear time. If the specified list does not * implement the {@link RandomAccess} interface and is large, this * implementation dumps the specified list into an array before shuffling * it, and dumps the shuffled array back into the list. This avoids the * quadratic behavior that would result from shuffling a "sequential * access" list in place. * * @param list the list to be shuffled. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the {@code set} operation. */ public static void shuffle(List<?> list) { Random rnd = r; if (rnd == null) r = rnd = new Random(); // harmless race. shuffle(list, rnd); } private static Random r; /** * Randomly permute the specified list using the specified source of * randomness. All permutations occur with equal likelihood * assuming that the source of randomness is fair.<p> * * This implementation traverses the list backwards, from the last element * up to the second, repeatedly swapping a randomly selected element into * the "current position". Elements are randomly selected from the * portion of the list that runs from the first element to the current * position, inclusive.<p> * * This method runs in linear time. If the specified list does not * implement the {@link RandomAccess} interface and is large, this * implementation dumps the specified list into an array before shuffling * it, and dumps the shuffled array back into the list. This avoids the * quadratic behavior that would result from shuffling a "sequential * access" list in place. * * @param list the list to be shuffled. * @param rnd the source of randomness to use to shuffle the list. * @throws UnsupportedOperationException if the specified list or its * list-iterator does not support the {@code set} operation. */ @SuppressWarnings({"rawtypes", "unchecked"}) public static void shuffle(List<?> list, Random rnd) { int size = list.size(); if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { for (int i=size; i>1; i--) swap(list, i-1, rnd.nextInt(i)); } else { Object[] arr = list.toArray(); // Shuffle array for (int i=size; i>1; i--) swap(arr, i-1, rnd.nextInt(i)); // Dump array back into list // instead of using a raw type here, it's possible to capture // the wildcard but it will require a call to a supplementary // private method ListIterator it = list.listIterator(); for (Object e : arr) { it.next(); it.set(e); } } } /** * Swaps the elements at the specified positions in the specified list. * (If the specified positions are equal, invoking this method leaves * the list unchanged.) * * @param list The list in which to swap elements. * @param i the index of one element to be swapped. * @param j the index of the other element to be swapped. * @throws IndexOutOfBoundsException if either {@code i} or {@code j} * is out of range (i &lt; 0 || i &gt;= list.size() * || j &lt; 0 || j &gt;= list.size()). * @since 1.4 */ @SuppressWarnings({"rawtypes", "unchecked"}) public static void swap(List<?> list, int i, int j) { // instead of using a raw type here, it's possible to capture // the wildcard but it will require a call to a supplementary // private method final List l = list; l.set(i, l.set(j, l.get(i))); } /** * Swaps the two specified elements in the specified array. */ private static void swap(Object[] arr, int i, int j) { Object tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } /** * Replaces all of the elements of the specified list with the specified * element. <p> * * This method runs in linear time. * * @param <T> the class of the objects in the list * @param list the list to be filled with the specified element. * @param obj The element with which to fill the specified list. * @throws UnsupportedOperationException if the specified list or its * list-iterator does not support the {@code set} operation. */ public static <T> void fill(List<? super T> list, T obj) { int size = list.size(); if (size < FILL_THRESHOLD || list instanceof RandomAccess) { for (int i=0; i<size; i++) list.set(i, obj); } else { ListIterator<? super T> itr = list.listIterator(); for (int i=0; i<size; i++) { itr.next(); itr.set(obj); } } } /** * Copies all of the elements from one list into another. After the * operation, the index of each copied element in the destination list * will be identical to its index in the source list. The destination * list's size must be greater than or equal to the source list's size. * If it is greater, the remaining elements in the destination list are * unaffected. <p> * * This method runs in linear time. * * @param <T> the class of the objects in the lists * @param dest The destination list. * @param src The source list. * @throws IndexOutOfBoundsException if the destination list is too small * to contain the entire source List. * @throws UnsupportedOperationException if the destination list's * list-iterator does not support the {@code set} operation. */ public static <T> void copy(List<? super T> dest, List<? extends T> src) { int srcSize = src.size(); if (srcSize > dest.size()) throw new IndexOutOfBoundsException("Source does not fit in dest"); if (srcSize < COPY_THRESHOLD || (src instanceof RandomAccess && dest instanceof RandomAccess)) { for (int i=0; i<srcSize; i++) dest.set(i, src.get(i)); } else { ListIterator<? super T> di=dest.listIterator(); ListIterator<? extends T> si=src.listIterator(); for (int i=0; i<srcSize; i++) { di.next(); di.set(si.next()); } } } /** * Returns the minimum element of the given collection, according to the * <i>natural ordering</i> of its elements. All elements in the * collection must implement the {@code Comparable} interface. * Furthermore, all elements in the collection must be <i>mutually * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and * {@code e2} in the collection).<p> * * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * * @param <T> the class of the objects in the collection * @param coll the collection whose minimum element is to be determined. * @return the minimum element of the given collection, according * to the <i>natural ordering</i> of its elements. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> (for example, strings and * integers). * @throws NoSuchElementException if the collection is empty. * @see Comparable */ public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) < 0) candidate = next; } return candidate; } /** * Returns the minimum element of the given collection, according to the * order induced by the specified comparator. All elements in the * collection must be <i>mutually comparable</i> by the specified * comparator (that is, {@code comp.compare(e1, e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and * {@code e2} in the collection).<p> * * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * * @param <T> the class of the objects in the collection * @param coll the collection whose minimum element is to be determined. * @param comp the comparator with which to determine the minimum element. * A {@code null} value indicates that the elements' <i>natural * ordering</i> should be used. * @return the minimum element of the given collection, according * to the specified comparator. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> using the specified comparator. * @throws NoSuchElementException if the collection is empty. * @see Comparable */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)min((Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) < 0) candidate = next; } return candidate; } /** * Returns the maximum element of the given collection, according to the * <i>natural ordering</i> of its elements. All elements in the * collection must implement the {@code Comparable} interface. * Furthermore, all elements in the collection must be <i>mutually * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and * {@code e2} in the collection).<p> * * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * * @param <T> the class of the objects in the collection * @param coll the collection whose maximum element is to be determined. * @return the maximum element of the given collection, according * to the <i>natural ordering</i> of its elements. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> (for example, strings and * integers). * @throws NoSuchElementException if the collection is empty. * @see Comparable */ public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) > 0) candidate = next; } return candidate; } /** * Returns the maximum element of the given collection, according to the * order induced by the specified comparator. All elements in the * collection must be <i>mutually comparable</i> by the specified * comparator (that is, {@code comp.compare(e1, e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and * {@code e2} in the collection).<p> * * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * * @param <T> the class of the objects in the collection * @param coll the collection whose maximum element is to be determined. * @param comp the comparator with which to determine the maximum element. * A {@code null} value indicates that the elements' <i>natural * ordering</i> should be used. * @return the maximum element of the given collection, according * to the specified comparator. * @throws ClassCastException if the collection contains elements that are * not <i>mutually comparable</i> using the specified comparator. * @throws NoSuchElementException if the collection is empty. * @see Comparable */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)max((Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) > 0) candidate = next; } return candidate; } /** * Rotates the elements in the specified list by the specified distance. * After calling this method, the element at index {@code i} will be * the element previously at index {@code (i - distance)} mod * {@code list.size()}, for all values of {@code i} between {@code 0} * and {@code list.size()-1}, inclusive. (This method has no effect on * the size of the list.) * * <p>For example, suppose {@code list} comprises{@code [t, a, n, k, s]}. * After invoking {@code Collections.rotate(list, 1)} (or * {@code Collections.rotate(list, -4)}), {@code list} will comprise * {@code [s, t, a, n, k]}. * * <p>Note that this method can usefully be applied to sublists to * move one or more elements within a list while preserving the * order of the remaining elements. For example, the following idiom * moves the element at index {@code j} forward to position * {@code k} (which must be greater than or equal to {@code j}): * <pre> * Collections.rotate(list.subList(j, k+1), -1); * </pre> * To make this concrete, suppose {@code list} comprises * {@code [a, b, c, d, e]}. To move the element at index {@code 1} * ({@code b}) forward two positions, perform the following invocation: * <pre> * Collections.rotate(l.subList(1, 4), -1); * </pre> * The resulting list is {@code [a, c, d, b, e]}. * * <p>To move more than one element forward, increase the absolute value * of the rotation distance. To move elements backward, use a positive * shift distance. * * <p>If the specified list is small or implements the {@link * RandomAccess} interface, this implementation exchanges the first * element into the location it should go, and then repeatedly exchanges * the displaced element into the location it should go until a displaced * element is swapped into the first element. If necessary, the process * is repeated on the second and successive elements, until the rotation * is complete. If the specified list is large and doesn't implement the * {@code RandomAccess} interface, this implementation breaks the * list into two sublist views around index {@code -distance mod size}. * Then the {@link #reverse(List)} method is invoked on each sublist view, * and finally it is invoked on the entire list. For a more complete * description of both algorithms, see Section 2.3 of Jon Bentley's * <i>Programming Pearls</i> (Addison-Wesley, 1986). * * @param list the list to be rotated. * @param distance the distance to rotate the list. There are no * constraints on this value; it may be zero, negative, or * greater than {@code list.size()}. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the {@code set} operation. * @since 1.4 */ public static void rotate(List<?> list, int distance) { if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD) rotate1(list, distance); else rotate2(list, distance); } private static <T> void rotate1(List<T> list, int distance) { int size = list.size(); if (size == 0) return; distance = distance % size; if (distance < 0) distance += size; if (distance == 0) return; for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) { T displaced = list.get(cycleStart); int i = cycleStart; do { i += distance; if (i >= size) i -= size; displaced = list.set(i, displaced); nMoved ++; } while (i != cycleStart); } } private static void rotate2(List<?> list, int distance) { int size = list.size(); if (size == 0) return; int mid = -distance % size; if (mid < 0) mid += size; if (mid == 0) return; reverse(list.subList(0, mid)); reverse(list.subList(mid, size)); reverse(list); } /** * Replaces all occurrences of one specified value in a list with another. * More formally, replaces with {@code newVal} each element {@code e} * in {@code list} such that * {@code (oldVal==null ? e==null : oldVal.equals(e))}. * (This method has no effect on the size of the list.) * * @param <T> the class of the objects in the list * @param list the list in which replacement is to occur. * @param oldVal the old value to be replaced. * @param newVal the new value with which {@code oldVal} is to be * replaced. * @return {@code true} if {@code list} contained one or more elements * {@code e} such that * {@code (oldVal==null ? e==null : oldVal.equals(e))}. * @throws UnsupportedOperationException if the specified list or * its list-iterator does not support the {@code set} operation. * @since 1.4 */ public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) { boolean result = false; int size = list.size(); if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) { if (oldVal==null) { for (int i=0; i<size; i++) { if (list.get(i)==null) { list.set(i, newVal); result = true; } } } else { for (int i=0; i<size; i++) { if (oldVal.equals(list.get(i))) { list.set(i, newVal); result = true; } } } } else { ListIterator<T> itr=list.listIterator(); if (oldVal==null) { for (int i=0; i<size; i++) { if (itr.next()==null) { itr.set(newVal); result = true; } } } else { for (int i=0; i<size; i++) { if (oldVal.equals(itr.next())) { itr.set(newVal); result = true; } } } } return result; } /** * Returns the starting position of the first occurrence of the specified * target list within the specified source list, or -1 if there is no * such occurrence. More formally, returns the lowest index {@code i} * such that {@code source.subList(i, i+target.size()).equals(target)}, * or -1 if there is no such index. (Returns -1 if * {@code target.size() > source.size()}) * * <p>This implementation uses the "brute force" technique of scanning * over the source list, looking for a match with the target at each * location in turn. * * @param source the list in which to search for the first occurrence * of {@code target}. * @param target the list to search for as a subList of {@code source}. * @return the starting position of the first occurrence of the specified * target list within the specified source list, or -1 if there * is no such occurrence. * @since 1.4 */ public static int indexOfSubList(List<?> source, List<?> target) { int sourceSize = source.size(); int targetSize = target.size(); int maxCandidate = sourceSize - targetSize; if (sourceSize < INDEXOFSUBLIST_THRESHOLD || (source instanceof RandomAccess&&target instanceof RandomAccess)) { nextCand: for (int candidate = 0; candidate <= maxCandidate; candidate++) { for (int i=0, j=candidate; i<targetSize; i++, j++) if (!eq(target.get(i), source.get(j))) continue nextCand; // Element mismatch, try next cand return candidate; // All elements of candidate matched target } } else { // Iterator version of above algorithm ListIterator<?> si = source.listIterator(); nextCand: for (int candidate = 0; candidate <= maxCandidate; candidate++) { ListIterator<?> ti = target.listIterator(); for (int i=0; i<targetSize; i++) { if (!eq(ti.next(), si.next())) { // Back up source iterator to next candidate for (int j=0; j<i; j++) si.previous(); continue nextCand; } } return candidate; } } return -1; // No candidate matched the target } /** * Returns the starting position of the last occurrence of the specified * target list within the specified source list, or -1 if there is no such * occurrence. More formally, returns the highest index {@code i} * such that {@code source.subList(i, i+target.size()).equals(target)}, * or -1 if there is no such index. (Returns -1 if * {@code target.size() > source.size()}) * * <p>This implementation uses the "brute force" technique of iterating * over the source list, looking for a match with the target at each * location in turn. * * @param source the list in which to search for the last occurrence * of {@code target}. * @param target the list to search for as a subList of {@code source}. * @return the starting position of the last occurrence of the specified * target list within the specified source list, or -1 if there * is no such occurrence. * @since 1.4 */ public static int lastIndexOfSubList(List<?> source, List<?> target) { int sourceSize = source.size(); int targetSize = target.size(); int maxCandidate = sourceSize - targetSize; if (sourceSize < INDEXOFSUBLIST_THRESHOLD || source instanceof RandomAccess) { // Index access version nextCand: for (int candidate = maxCandidate; candidate >= 0; candidate--) { for (int i=0, j=candidate; i<targetSize; i++, j++) if (!eq(target.get(i), source.get(j))) continue nextCand; // Element mismatch, try next cand return candidate; // All elements of candidate matched target } } else { // Iterator version of above algorithm if (maxCandidate < 0) return -1; ListIterator<?> si = source.listIterator(maxCandidate); nextCand: for (int candidate = maxCandidate; candidate >= 0; candidate--) { ListIterator<?> ti = target.listIterator(); for (int i=0; i<targetSize; i++) { if (!eq(ti.next(), si.next())) { if (candidate != 0) { // Back up source iterator to next candidate for (int j=0; j<=i+1; j++) si.previous(); } continue nextCand; } } return candidate; } } return -1; // No candidate matched the target } // Unmodifiable Wrappers /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified collection. Query operations on the returned collection "read through" * to the specified collection, and attempts to modify the returned * collection, whether direct or via its iterator, result in an * {@code UnsupportedOperationException}.<p> * * The returned collection does <i>not</i> pass the hashCode and equals * operations through to the backing collection, but relies on * {@code Object}'s {@code equals} and {@code hashCode} methods. This * is necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list.<p> * * The returned collection will be serializable if the specified collection * is serializable. * * @param <T> the class of the objects in the collection * @param c the collection for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified collection. */ public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) { return new UnmodifiableCollection<>(c); } /** * @serial include */ static class UnmodifiableCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 1820017752578914078L; final Collection<? extends E> c; UnmodifiableCollection(Collection<? extends E> c) { if (c==null) throw new NullPointerException(); this.c = c; } public int size() {return c.size();} public boolean isEmpty() {return c.isEmpty();} public boolean contains(Object o) {return c.contains(o);} public Object[] toArray() {return c.toArray();} public <T> T[] toArray(T[] a) {return c.toArray(a);} public <T> T[] toArray(IntFunction<T[]> f) {return c.toArray(f);} public String toString() {return c.toString();} public Iterator<E> iterator() { return new Iterator<E>() { private final Iterator<? extends E> i = c.iterator(); public boolean hasNext() {return i.hasNext();} public E next() {return i.next();} public void remove() { throw new UnsupportedOperationException(); } @Override public void forEachRemaining(Consumer<? super E> action) { // Use backing collection version i.forEachRemaining(action); } }; } public boolean add(E e) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean containsAll(Collection<?> coll) { return c.containsAll(coll); } public boolean addAll(Collection<? extends E> coll) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection<?> coll) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection<?> coll) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) { c.forEach(action); } @Override public boolean removeIf(Predicate<? super E> filter) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @Override public Spliterator<E> spliterator() { return (Spliterator<E>)c.spliterator(); } @SuppressWarnings("unchecked") @Override public Stream<E> stream() { return (Stream<E>)c.stream(); } @SuppressWarnings("unchecked") @Override public Stream<E> parallelStream() { return (Stream<E>)c.parallelStream(); } } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified set. Query operations on the returned set "read through" to the specified * set, and attempts to modify the returned set, whether direct or via its * iterator, result in an {@code UnsupportedOperationException}.<p> * * The returned set will be serializable if the specified set * is serializable. * * @param <T> the class of the objects in the set * @param s the set for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified set. */ public static <T> Set<T> unmodifiableSet(Set<? extends T> s) { return new UnmodifiableSet<>(s); } /** * @serial include */ static class UnmodifiableSet<E> extends UnmodifiableCollection<E> implements Set<E>, Serializable { private static final long serialVersionUID = -9215047833775013803L; UnmodifiableSet(Set<? extends E> s) {super(s);} public boolean equals(Object o) {return o == this || c.equals(o);} public int hashCode() {return c.hashCode();} } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified sorted set. Query operations on the returned sorted set "read * through" to the specified sorted set. Attempts to modify the returned * sorted set, whether direct, via its iterator, or via its * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in * an {@code UnsupportedOperationException}.<p> * * The returned sorted set will be serializable if the specified sorted set * is serializable. * * @param <T> the class of the objects in the set * @param s the sorted set for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified sorted set. */ public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) { return new UnmodifiableSortedSet<>(s); } /** * @serial include */ static class UnmodifiableSortedSet<E> extends UnmodifiableSet<E> implements SortedSet<E>, Serializable { private static final long serialVersionUID = -4929149591599911165L; private final SortedSet<E> ss; UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;} public Comparator<? super E> comparator() {return ss.comparator();} public SortedSet<E> subSet(E fromElement, E toElement) { return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement)); } public SortedSet<E> headSet(E toElement) { return new UnmodifiableSortedSet<>(ss.headSet(toElement)); } public SortedSet<E> tailSet(E fromElement) { return new UnmodifiableSortedSet<>(ss.tailSet(fromElement)); } public E first() {return ss.first();} public E last() {return ss.last();} } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified navigable set. Query operations on the returned navigable set "read * through" to the specified navigable set. Attempts to modify the returned * navigable set, whether direct, via its iterator, or via its * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in * an {@code UnsupportedOperationException}.<p> * * The returned navigable set will be serializable if the specified * navigable set is serializable. * * @param <T> the class of the objects in the set * @param s the navigable set for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified navigable set * @since 1.8 */ public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) { return new UnmodifiableNavigableSet<>(s); } /** * Wraps a navigable set and disables all of the mutative operations. * * @param <E> type of elements * @serial include */ static class UnmodifiableNavigableSet<E> extends UnmodifiableSortedSet<E> implements NavigableSet<E>, Serializable { private static final long serialVersionUID = -6027448201786391929L; /** * A singleton empty unmodifiable navigable set used for * {@link #emptyNavigableSet()}. * * @param <E> type of elements, if there were any, and bounds */ private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E> implements Serializable { private static final long serialVersionUID = -6291252904449939134L; public EmptyNavigableSet() { super(new TreeSet<>()); } private Object readResolve() { return EMPTY_NAVIGABLE_SET; } } @SuppressWarnings("rawtypes") private static final NavigableSet<?> EMPTY_NAVIGABLE_SET = new EmptyNavigableSet<>(); /** * The instance we are protecting. */ private final NavigableSet<E> ns; UnmodifiableNavigableSet(NavigableSet<E> s) {super(s); ns = s;} public E lower(E e) { return ns.lower(e); } public E floor(E e) { return ns.floor(e); } public E ceiling(E e) { return ns.ceiling(e); } public E higher(E e) { return ns.higher(e); } public E pollFirst() { throw new UnsupportedOperationException(); } public E pollLast() { throw new UnsupportedOperationException(); } public NavigableSet<E> descendingSet() { return new UnmodifiableNavigableSet<>(ns.descendingSet()); } public Iterator<E> descendingIterator() { return descendingSet().iterator(); } public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new UnmodifiableNavigableSet<>( ns.subSet(fromElement, fromInclusive, toElement, toInclusive)); } public NavigableSet<E> headSet(E toElement, boolean inclusive) { return new UnmodifiableNavigableSet<>( ns.headSet(toElement, inclusive)); } public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new UnmodifiableNavigableSet<>( ns.tailSet(fromElement, inclusive)); } } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified list. Query operations on the returned list "read through" to the * specified list, and attempts to modify the returned list, whether * direct or via its iterator, result in an * {@code UnsupportedOperationException}.<p> * * The returned list will be serializable if the specified list * is serializable. Similarly, the returned list will implement * {@link RandomAccess} if the specified list does. * * @param <T> the class of the objects in the list * @param list the list for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified list. */ public static <T> List<T> unmodifiableList(List<? extends T> list) { return (list instanceof RandomAccess ? new UnmodifiableRandomAccessList<>(list) : new UnmodifiableList<>(list)); } /** * @serial include */ static class UnmodifiableList<E> extends UnmodifiableCollection<E> implements List<E> { private static final long serialVersionUID = -283967356065247728L; final List<? extends E> list; UnmodifiableList(List<? extends E> list) { super(list); this.list = list; } public boolean equals(Object o) {return o == this || list.equals(o);} public int hashCode() {return list.hashCode();} public E get(int index) {return list.get(index);} public E set(int index, E element) { throw new UnsupportedOperationException(); } public void add(int index, E element) { throw new UnsupportedOperationException(); } public E remove(int index) { throw new UnsupportedOperationException(); } public int indexOf(Object o) {return list.indexOf(o);} public int lastIndexOf(Object o) {return list.lastIndexOf(o);} public boolean addAll(int index, Collection<? extends E> c) { throw new UnsupportedOperationException(); } @Override public void replaceAll(UnaryOperator<E> operator) { throw new UnsupportedOperationException(); } @Override public void sort(Comparator<? super E> c) { throw new UnsupportedOperationException(); } public ListIterator<E> listIterator() {return listIterator(0);} public ListIterator<E> listIterator(final int index) { return new ListIterator<E>() { private final ListIterator<? extends E> i = list.listIterator(index); public boolean hasNext() {return i.hasNext();} public E next() {return i.next();} public boolean hasPrevious() {return i.hasPrevious();} public E previous() {return i.previous();} public int nextIndex() {return i.nextIndex();} public int previousIndex() {return i.previousIndex();} public void remove() { throw new UnsupportedOperationException(); } public void set(E e) { throw new UnsupportedOperationException(); } public void add(E e) { throw new UnsupportedOperationException(); } @Override public void forEachRemaining(Consumer<? super E> action) { i.forEachRemaining(action); } }; } public List<E> subList(int fromIndex, int toIndex) { return new UnmodifiableList<>(list.subList(fromIndex, toIndex)); } /** * UnmodifiableRandomAccessList instances are serialized as * UnmodifiableList instances to allow them to be deserialized * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList). * This method inverts the transformation. As a beneficial * side-effect, it also grafts the RandomAccess marker onto * UnmodifiableList instances that were serialized in pre-1.4 JREs. * * Note: Unfortunately, UnmodifiableRandomAccessList instances * serialized in 1.4.1 and deserialized in 1.4 will become * UnmodifiableList instances, as this method was missing in 1.4. */ private Object readResolve() { return (list instanceof RandomAccess ? new UnmodifiableRandomAccessList<>(list) : this); } } /** * @serial include */ static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E> implements RandomAccess { UnmodifiableRandomAccessList(List<? extends E> list) { super(list); } public List<E> subList(int fromIndex, int toIndex) { return new UnmodifiableRandomAccessList<>( list.subList(fromIndex, toIndex)); } private static final long serialVersionUID = -2542308836966382001L; /** * Allows instances to be deserialized in pre-1.4 JREs (which do * not have UnmodifiableRandomAccessList). UnmodifiableList has * a readResolve method that inverts this transformation upon * deserialization. */ private Object writeReplace() { return new UnmodifiableList<>(list); } } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified map. Query operations on the returned map "read through" * to the specified map, and attempts to modify the returned * map, whether direct or via its collection views, result in an * {@code UnsupportedOperationException}.<p> * * The returned map will be serializable if the specified map * is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the map for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified map. */ public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) { return new UnmodifiableMap<>(m); } /** * @serial include */ private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable { private static final long serialVersionUID = -1034234728574286014L; private final Map<? extends K, ? extends V> m; UnmodifiableMap(Map<? extends K, ? extends V> m) { if (m==null) throw new NullPointerException(); this.m = m; } public int size() {return m.size();} public boolean isEmpty() {return m.isEmpty();} public boolean containsKey(Object key) {return m.containsKey(key);} public boolean containsValue(Object val) {return m.containsValue(val);} public V get(Object key) {return m.get(key);} public V put(K key, V value) { throw new UnsupportedOperationException(); } public V remove(Object key) { throw new UnsupportedOperationException(); } public void putAll(Map<? extends K, ? extends V> m) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } private transient Set<K> keySet; private transient Set<Entry<K,V>> entrySet; private transient Collection<V> values; public Set<K> keySet() { if (keySet==null) keySet = unmodifiableSet(m.keySet()); return keySet; } public Set<Entry<K,V>> entrySet() { if (entrySet==null) entrySet = new UnmodifiableEntrySet<>(m.entrySet()); return entrySet; } public Collection<V> values() { if (values==null) values = unmodifiableCollection(m.values()); return values; } public boolean equals(Object o) {return o == this || m.equals(o);} public int hashCode() {return m.hashCode();} public String toString() {return m.toString();} // Override default methods in Map @Override @SuppressWarnings("unchecked") public V getOrDefault(Object k, V defaultValue) { // Safe cast as we don't change the value return ((Map<K, V>)m).getOrDefault(k, defaultValue); } @Override public void forEach(BiConsumer<? super K, ? super V> action) { m.forEach(action); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { throw new UnsupportedOperationException(); } @Override public V putIfAbsent(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException(); } @Override public V replace(K key, V value) { throw new UnsupportedOperationException(); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException(); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } /** * We need this class in addition to UnmodifiableSet as * Map.Entries themselves permit modification of the backing Map * via their setValue operation. This class is subtle: there are * many possible attacks that must be thwarted. * * @serial include */ static class UnmodifiableEntrySet<K,V> extends UnmodifiableSet<Entry<K,V>> { private static final long serialVersionUID = 7854390611657943733L; @SuppressWarnings({"unchecked", "rawtypes"}) UnmodifiableEntrySet(Set<? extends Entry<? extends K, ? extends V>> s) { // Need to cast to raw in order to work around a limitation in the type system super((Set)s); } static <K, V> Consumer<Entry<? extends K, ? extends V>> entryConsumer( Consumer<? super Entry<K, V>> action) { return e -> action.accept(new UnmodifiableEntry<>(e)); } public void forEach(Consumer<? super Entry<K, V>> action) { Objects.requireNonNull(action); c.forEach(entryConsumer(action)); } static final class UnmodifiableEntrySetSpliterator<K, V> implements Spliterator<Entry<K,V>> { final Spliterator<Entry<K, V>> s; UnmodifiableEntrySetSpliterator(Spliterator<Entry<K, V>> s) { this.s = s; } @Override public boolean tryAdvance(Consumer<? super Entry<K, V>> action) { Objects.requireNonNull(action); return s.tryAdvance(entryConsumer(action)); } @Override public void forEachRemaining(Consumer<? super Entry<K, V>> action) { Objects.requireNonNull(action); s.forEachRemaining(entryConsumer(action)); } @Override public Spliterator<Entry<K, V>> trySplit() { Spliterator<Entry<K, V>> split = s.trySplit(); return split == null ? null : new UnmodifiableEntrySetSpliterator<>(split); } @Override public long estimateSize() { return s.estimateSize(); } @Override public long getExactSizeIfKnown() { return s.getExactSizeIfKnown(); } @Override public int characteristics() { return s.characteristics(); } @Override public boolean hasCharacteristics(int characteristics) { return s.hasCharacteristics(characteristics); } @Override public Comparator<? super Entry<K, V>> getComparator() { return s.getComparator(); } } @SuppressWarnings("unchecked") public Spliterator<Entry<K,V>> spliterator() { return new UnmodifiableEntrySetSpliterator<>( (Spliterator<Entry<K, V>>) c.spliterator()); } @Override public Stream<Entry<K,V>> stream() { return StreamSupport.stream(spliterator(), false); } @Override public Stream<Entry<K,V>> parallelStream() { return StreamSupport.stream(spliterator(), true); } public Iterator<Entry<K,V>> iterator() { return new Iterator<Entry<K,V>>() { private final Iterator<? extends Entry<? extends K, ? extends V>> i = c.iterator(); public boolean hasNext() { return i.hasNext(); } public Entry<K,V> next() { return new UnmodifiableEntry<>(i.next()); } public void remove() { throw new UnsupportedOperationException(); } public void forEachRemaining(Consumer<? super Entry<K, V>> action) { i.forEachRemaining(entryConsumer(action)); } }; } @SuppressWarnings("unchecked") public Object[] toArray() { Object[] a = c.toArray(); for (int i=0; i<a.length; i++) a[i] = new UnmodifiableEntry<>((Entry<? extends K, ? extends V>)a[i]); return a; } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { // We don't pass a to c.toArray, to avoid window of // vulnerability wherein an unscrupulous multithreaded client // could get his hands on raw (unwrapped) Entries from c. Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0)); for (int i=0; i<arr.length; i++) arr[i] = new UnmodifiableEntry<>((Entry<? extends K, ? extends V>)arr[i]); if (arr.length > a.length) return (T[])arr; System.arraycopy(arr, 0, a, 0, arr.length); if (a.length > arr.length) a[arr.length] = null; return a; } /** * This method is overridden to protect the backing set against * an object with a nefarious equals function that senses * that the equality-candidate is Map.Entry and calls its * setValue method. */ public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; return c.contains( new UnmodifiableEntry<>((Entry<?,?>) o)); } /** * The next two methods are overridden to protect against * an unscrupulous List whose contains(Object o) method senses * when o is a Map.Entry, and calls o.setValue. */ public boolean containsAll(Collection<?> coll) { for (Object e : coll) { if (!contains(e)) // Invokes safe contains() above return false; } return true; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Set<?> s = (Set<?>) o; if (s.size() != c.size()) return false; return containsAll(s); // Invokes safe containsAll() above } /** * This "wrapper class" serves two purposes: it prevents * the client from modifying the backing Map, by short-circuiting * the setValue method, and it protects the backing Map against * an ill-behaved Map.Entry that attempts to modify another * Map Entry when asked to perform an equality check. */ private static class UnmodifiableEntry<K,V> implements Entry<K,V> { private Entry<? extends K, ? extends V> e; UnmodifiableEntry(Entry<? extends K, ? extends V> e) {this.e = Objects.requireNonNull(e);} public K getKey() {return e.getKey();} public V getValue() {return e.getValue();} public V setValue(V value) { throw new UnsupportedOperationException(); } public int hashCode() {return e.hashCode();} public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Map.Entry)) return false; Entry<?,?> t = (Entry<?,?>)o; return eq(e.getKey(), t.getKey()) && eq(e.getValue(), t.getValue()); } public String toString() {return e.toString();} } } } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified sorted map. Query operations on the returned sorted map "read through" * to the specified sorted map. Attempts to modify the returned * sorted map, whether direct, via its collection views, or via its * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in * an {@code UnsupportedOperationException}.<p> * * The returned sorted map will be serializable if the specified sorted map * is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the sorted map for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified sorted map. */ public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) { return new UnmodifiableSortedMap<>(m); } /** * @serial include */ static class UnmodifiableSortedMap<K,V> extends UnmodifiableMap<K,V> implements SortedMap<K,V>, Serializable { private static final long serialVersionUID = -8806743815996713206L; private final SortedMap<K, ? extends V> sm; UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m; } public Comparator<? super K> comparator() { return sm.comparator(); } public SortedMap<K,V> subMap(K fromKey, K toKey) { return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); } public SortedMap<K,V> headMap(K toKey) { return new UnmodifiableSortedMap<>(sm.headMap(toKey)); } public SortedMap<K,V> tailMap(K fromKey) { return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); } public K firstKey() { return sm.firstKey(); } public K lastKey() { return sm.lastKey(); } } /** * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the * specified navigable map. Query operations on the returned navigable map "read * through" to the specified navigable map. Attempts to modify the returned * navigable map, whether direct, via its collection views, or via its * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in * an {@code UnsupportedOperationException}.<p> * * The returned navigable map will be serializable if the specified * navigable map is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the navigable map for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified navigable map * @since 1.8 */ public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) { return new UnmodifiableNavigableMap<>(m); } /** * @serial include */ static class UnmodifiableNavigableMap<K,V> extends UnmodifiableSortedMap<K,V> implements NavigableMap<K,V>, Serializable { private static final long serialVersionUID = -4858195264774772197L; /** * A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve * to preserve singleton property. * * @param <K> type of keys, if there were any, and of bounds * @param <V> type of values, if there were any */ private static class EmptyNavigableMap<K,V> extends UnmodifiableNavigableMap<K,V> implements Serializable { private static final long serialVersionUID = -2239321462712562324L; EmptyNavigableMap() { super(new TreeMap<>()); } @Override public NavigableSet<K> navigableKeySet() { return emptyNavigableSet(); } private Object readResolve() { return EMPTY_NAVIGABLE_MAP; } } /** * Singleton for {@link emptyNavigableMap()} which is also immutable. */ private static final EmptyNavigableMap<?,?> EMPTY_NAVIGABLE_MAP = new EmptyNavigableMap<>(); /** * The instance we wrap and protect. */ private final NavigableMap<K, ? extends V> nm; UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {super(m); nm = m;} public K lowerKey(K key) { return nm.lowerKey(key); } public K floorKey(K key) { return nm.floorKey(key); } public K ceilingKey(K key) { return nm.ceilingKey(key); } public K higherKey(K key) { return nm.higherKey(key); } @SuppressWarnings("unchecked") public Entry<K, V> lowerEntry(K key) { Entry<K,V> lower = (Entry<K, V>) nm.lowerEntry(key); return (null != lower) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(lower) : null; } @SuppressWarnings("unchecked") public Entry<K, V> floorEntry(K key) { Entry<K,V> floor = (Entry<K, V>) nm.floorEntry(key); return (null != floor) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(floor) : null; } @SuppressWarnings("unchecked") public Entry<K, V> ceilingEntry(K key) { Entry<K,V> ceiling = (Entry<K, V>) nm.ceilingEntry(key); return (null != ceiling) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(ceiling) : null; } @SuppressWarnings("unchecked") public Entry<K, V> higherEntry(K key) { Entry<K,V> higher = (Entry<K, V>) nm.higherEntry(key); return (null != higher) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(higher) : null; } @SuppressWarnings("unchecked") public Entry<K, V> firstEntry() { Entry<K,V> first = (Entry<K, V>) nm.firstEntry(); return (null != first) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(first) : null; } @SuppressWarnings("unchecked") public Entry<K, V> lastEntry() { Entry<K,V> last = (Entry<K, V>) nm.lastEntry(); return (null != last) ? new UnmodifiableEntrySet.UnmodifiableEntry<>(last) : null; } public Entry<K, V> pollFirstEntry() { throw new UnsupportedOperationException(); } public Entry<K, V> pollLastEntry() { throw new UnsupportedOperationException(); } public NavigableMap<K, V> descendingMap() { return unmodifiableNavigableMap(nm.descendingMap()); } public NavigableSet<K> navigableKeySet() { return unmodifiableNavigableSet(nm.navigableKeySet()); } public NavigableSet<K> descendingKeySet() { return unmodifiableNavigableSet(nm.descendingKeySet()); } public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return unmodifiableNavigableMap( nm.subMap(fromKey, fromInclusive, toKey, toInclusive)); } public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); } public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); } } // Synch Wrappers /** * Returns a synchronized (thread-safe) collection backed by the specified * collection. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing collection is accomplished * through the returned collection.<p> * * It is imperative that the user manually synchronize on the returned * collection when traversing it via {@link Iterator}, {@link Spliterator} * or {@link Stream}: * <pre> * Collection c = Collections.synchronizedCollection(myCollection); * ... * synchronized (c) { * Iterator i = c.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned collection does <i>not</i> pass the {@code hashCode} * and {@code equals} operations through to the backing collection, but * relies on {@code Object}'s equals and hashCode methods. This is * necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list.<p> * * The returned collection will be serializable if the specified collection * is serializable. * * @param <T> the class of the objects in the collection * @param c the collection to be "wrapped" in a synchronized collection. * @return a synchronized view of the specified collection. */ public static <T> Collection<T> synchronizedCollection(Collection<T> c) { return new SynchronizedCollection<>(c); } static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) { return new SynchronizedCollection<>(c, mutex); } /** * @serial include */ static class SynchronizedCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 3053995032091335093L; final Collection<E> c; // Backing Collection final Object mutex; // Object on which to synchronize SynchronizedCollection(Collection<E> c) { this.c = Objects.requireNonNull(c); mutex = this; } SynchronizedCollection(Collection<E> c, Object mutex) { this.c = Objects.requireNonNull(c); this.mutex = Objects.requireNonNull(mutex); } public int size() { synchronized (mutex) {return c.size();} } public boolean isEmpty() { synchronized (mutex) {return c.isEmpty();} } public boolean contains(Object o) { synchronized (mutex) {return c.contains(o);} } public Object[] toArray() { synchronized (mutex) {return c.toArray();} } public <T> T[] toArray(T[] a) { synchronized (mutex) {return c.toArray(a);} } public <T> T[] toArray(IntFunction<T[]> f) { synchronized (mutex) {return c.toArray(f);} } public Iterator<E> iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add(E e) { synchronized (mutex) {return c.add(e);} } public boolean remove(Object o) { synchronized (mutex) {return c.remove(o);} } public boolean containsAll(Collection<?> coll) { synchronized (mutex) {return c.containsAll(coll);} } public boolean addAll(Collection<? extends E> coll) { synchronized (mutex) {return c.addAll(coll);} } public boolean removeAll(Collection<?> coll) { synchronized (mutex) {return c.removeAll(coll);} } public boolean retainAll(Collection<?> coll) { synchronized (mutex) {return c.retainAll(coll);} } public void clear() { synchronized (mutex) {c.clear();} } public String toString() { synchronized (mutex) {return c.toString();} } // Override default methods in Collection @Override public void forEach(Consumer<? super E> consumer) { synchronized (mutex) {c.forEach(consumer);} } @Override public boolean removeIf(Predicate<? super E> filter) { synchronized (mutex) {return c.removeIf(filter);} } @Override public Spliterator<E> spliterator() { return c.spliterator(); // Must be manually synched by user! } @Override public Stream<E> stream() { return c.stream(); // Must be manually synched by user! } @Override public Stream<E> parallelStream() { return c.parallelStream(); // Must be manually synched by user! } private void writeObject(ObjectOutputStream s) throws IOException { synchronized (mutex) {s.defaultWriteObject();} } } /** * Returns a synchronized (thread-safe) set backed by the specified * set. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing set is accomplished * through the returned set.<p> * * It is imperative that the user manually synchronize on the returned * collection when traversing it via {@link Iterator}, {@link Spliterator} * or {@link Stream}: * <pre> * Set s = Collections.synchronizedSet(new HashSet()); * ... * synchronized (s) { * Iterator i = s.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned set will be serializable if the specified set is * serializable. * * @param <T> the class of the objects in the set * @param s the set to be "wrapped" in a synchronized set. * @return a synchronized view of the specified set. */ public static <T> Set<T> synchronizedSet(Set<T> s) { return new SynchronizedSet<>(s); } static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) { return new SynchronizedSet<>(s, mutex); } /** * @serial include */ static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> { private static final long serialVersionUID = 487447009682186044L; SynchronizedSet(Set<E> s) { super(s); } SynchronizedSet(Set<E> s, Object mutex) { super(s, mutex); } public boolean equals(Object o) { if (this == o) return true; synchronized (mutex) {return c.equals(o);} } public int hashCode() { synchronized (mutex) {return c.hashCode();} } } /** * Returns a synchronized (thread-safe) sorted set backed by the specified * sorted set. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing sorted set is accomplished * through the returned sorted set (or its views).<p> * * It is imperative that the user manually synchronize on the returned * sorted set when traversing it or any of its {@code subSet}, * {@code headSet}, or {@code tailSet} views via {@link Iterator}, * {@link Spliterator} or {@link Stream}: * <pre> * SortedSet s = Collections.synchronizedSortedSet(new TreeSet()); * ... * synchronized (s) { * Iterator i = s.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * or: * <pre> * SortedSet s = Collections.synchronizedSortedSet(new TreeSet()); * SortedSet s2 = s.headSet(foo); * ... * synchronized (s) { // Note: s, not s2!!! * Iterator i = s2.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned sorted set will be serializable if the specified * sorted set is serializable. * * @param <T> the class of the objects in the set * @param s the sorted set to be "wrapped" in a synchronized sorted set. * @return a synchronized view of the specified sorted set. */ public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) { return new SynchronizedSortedSet<>(s); } /** * @serial include */ static class SynchronizedSortedSet<E> extends SynchronizedSet<E> implements SortedSet<E> { private static final long serialVersionUID = 8695801310862127406L; private final SortedSet<E> ss; SynchronizedSortedSet(SortedSet<E> s) { super(s); ss = s; } SynchronizedSortedSet(SortedSet<E> s, Object mutex) { super(s, mutex); ss = s; } public Comparator<? super E> comparator() { synchronized (mutex) {return ss.comparator();} } public SortedSet<E> subSet(E fromElement, E toElement) { synchronized (mutex) { return new SynchronizedSortedSet<>( ss.subSet(fromElement, toElement), mutex); } } public SortedSet<E> headSet(E toElement) { synchronized (mutex) { return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex); } } public SortedSet<E> tailSet(E fromElement) { synchronized (mutex) { return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex); } } public E first() { synchronized (mutex) {return ss.first();} } public E last() { synchronized (mutex) {return ss.last();} } } /** * Returns a synchronized (thread-safe) navigable set backed by the * specified navigable set. In order to guarantee serial access, it is * critical that <strong>all</strong> access to the backing navigable set is * accomplished through the returned navigable set (or its views).<p> * * It is imperative that the user manually synchronize on the returned * navigable set when traversing it, or any of its {@code subSet}, * {@code headSet}, or {@code tailSet} views, via {@link Iterator}, * {@link Spliterator} or {@link Stream}: * <pre> * NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet()); * ... * synchronized (s) { * Iterator i = s.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * or: * <pre> * NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet()); * NavigableSet s2 = s.headSet(foo, true); * ... * synchronized (s) { // Note: s, not s2!!! * Iterator i = s2.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned navigable set will be serializable if the specified * navigable set is serializable. * * @param <T> the class of the objects in the set * @param s the navigable set to be "wrapped" in a synchronized navigable * set * @return a synchronized view of the specified navigable set * @since 1.8 */ public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) { return new SynchronizedNavigableSet<>(s); } /** * @serial include */ static class SynchronizedNavigableSet<E> extends SynchronizedSortedSet<E> implements NavigableSet<E> { private static final long serialVersionUID = -5505529816273629798L; private final NavigableSet<E> ns; SynchronizedNavigableSet(NavigableSet<E> s) { super(s); ns = s; } SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) { super(s, mutex); ns = s; } public E lower(E e) { synchronized (mutex) {return ns.lower(e);} } public E floor(E e) { synchronized (mutex) {return ns.floor(e);} } public E ceiling(E e) { synchronized (mutex) {return ns.ceiling(e);} } public E higher(E e) { synchronized (mutex) {return ns.higher(e);} } public E pollFirst() { synchronized (mutex) {return ns.pollFirst();} } public E pollLast() { synchronized (mutex) {return ns.pollLast();} } public NavigableSet<E> descendingSet() { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex); } } public Iterator<E> descendingIterator() { synchronized (mutex) { return descendingSet().iterator(); } } public NavigableSet<E> subSet(E fromElement, E toElement) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex); } } public NavigableSet<E> headSet(E toElement) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex); } } public NavigableSet<E> tailSet(E fromElement) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, true), mutex); } } public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); } } public NavigableSet<E> headSet(E toElement, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex); } } public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive), mutex); } } } /** * Returns a synchronized (thread-safe) list backed by the specified * list. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing list is accomplished * through the returned list.<p> * * It is imperative that the user manually synchronize on the returned * list when traversing it via {@link Iterator}, {@link Spliterator} * or {@link Stream}: * <pre> * List list = Collections.synchronizedList(new ArrayList()); * ... * synchronized (list) { * Iterator i = list.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned list will be serializable if the specified list is * serializable. * * @param <T> the class of the objects in the list * @param list the list to be "wrapped" in a synchronized list. * @return a synchronized view of the specified list. */ public static <T> List<T> synchronizedList(List<T> list) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : new SynchronizedList<>(list)); } static <T> List<T> synchronizedList(List<T> list, Object mutex) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list, mutex) : new SynchronizedList<>(list, mutex)); } /** * @serial include */ static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> { private static final long serialVersionUID = -7754090372962971524L; final List<E> list; SynchronizedList(List<E> list) { super(list); this.list = list; } SynchronizedList(List<E> list, Object mutex) { super(list, mutex); this.list = list; } public boolean equals(Object o) { if (this == o) return true; synchronized (mutex) {return list.equals(o);} } public int hashCode() { synchronized (mutex) {return list.hashCode();} } public E get(int index) { synchronized (mutex) {return list.get(index);} } public E set(int index, E element) { synchronized (mutex) {return list.set(index, element);} } public void add(int index, E element) { synchronized (mutex) {list.add(index, element);} } public E remove(int index) { synchronized (mutex) {return list.remove(index);} } public int indexOf(Object o) { synchronized (mutex) {return list.indexOf(o);} } public int lastIndexOf(Object o) { synchronized (mutex) {return list.lastIndexOf(o);} } public boolean addAll(int index, Collection<? extends E> c) { synchronized (mutex) {return list.addAll(index, c);} } public ListIterator<E> listIterator() { return list.listIterator(); // Must be manually synched by user } public ListIterator<E> listIterator(int index) { return list.listIterator(index); // Must be manually synched by user } public List<E> subList(int fromIndex, int toIndex) { synchronized (mutex) { return new SynchronizedList<>(list.subList(fromIndex, toIndex), mutex); } } @Override public void replaceAll(UnaryOperator<E> operator) { synchronized (mutex) {list.replaceAll(operator);} } @Override public void sort(Comparator<? super E> c) { synchronized (mutex) {list.sort(c);} } /** * SynchronizedRandomAccessList instances are serialized as * SynchronizedList instances to allow them to be deserialized * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList). * This method inverts the transformation. As a beneficial * side-effect, it also grafts the RandomAccess marker onto * SynchronizedList instances that were serialized in pre-1.4 JREs. * * Note: Unfortunately, SynchronizedRandomAccessList instances * serialized in 1.4.1 and deserialized in 1.4 will become * SynchronizedList instances, as this method was missing in 1.4. */ private Object readResolve() { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : this); } } /** * @serial include */ static class SynchronizedRandomAccessList<E> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list) { super(list); } SynchronizedRandomAccessList(List<E> list, Object mutex) { super(list, mutex); } public List<E> subList(int fromIndex, int toIndex) { synchronized (mutex) { return new SynchronizedRandomAccessList<>( list.subList(fromIndex, toIndex), mutex); } } private static final long serialVersionUID = 1530674583602358482L; /** * Allows instances to be deserialized in pre-1.4 JREs (which do * not have SynchronizedRandomAccessList). SynchronizedList has * a readResolve method that inverts this transformation upon * deserialization. */ private Object writeReplace() { return new SynchronizedList<>(list); } } /** * Returns a synchronized (thread-safe) map backed by the specified * map. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing map is accomplished * through the returned map.<p> * * It is imperative that the user manually synchronize on the returned * map when traversing any of its collection views via {@link Iterator}, * {@link Spliterator} or {@link Stream}: * <pre> * Map m = Collections.synchronizedMap(new HashMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned map will be serializable if the specified map is * serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the map to be "wrapped" in a synchronized map. * @return a synchronized view of the specified map. */ public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) { return new SynchronizedMap<>(m); } /** * @serial include */ private static class SynchronizedMap<K,V> implements Map<K,V>, Serializable { private static final long serialVersionUID = 1978198479659022715L; private final Map<K,V> m; // Backing Map final Object mutex; // Object on which to synchronize SynchronizedMap(Map<K,V> m) { this.m = Objects.requireNonNull(m); mutex = this; } SynchronizedMap(Map<K,V> m, Object mutex) { this.m = m; this.mutex = mutex; } public int size() { synchronized (mutex) {return m.size();} } public boolean isEmpty() { synchronized (mutex) {return m.isEmpty();} } public boolean containsKey(Object key) { synchronized (mutex) {return m.containsKey(key);} } public boolean containsValue(Object value) { synchronized (mutex) {return m.containsValue(value);} } public V get(Object key) { synchronized (mutex) {return m.get(key);} } public V put(K key, V value) { synchronized (mutex) {return m.put(key, value);} } public V remove(Object key) { synchronized (mutex) {return m.remove(key);} } public void putAll(Map<? extends K, ? extends V> map) { synchronized (mutex) {m.putAll(map);} } public void clear() { synchronized (mutex) {m.clear();} } private transient Set<K> keySet; private transient Set<Entry<K,V>> entrySet; private transient Collection<V> values; public Set<K> keySet() { synchronized (mutex) { if (keySet==null) keySet = new SynchronizedSet<>(m.keySet(), mutex); return keySet; } } public Set<Entry<K,V>> entrySet() { synchronized (mutex) { if (entrySet==null) entrySet = new SynchronizedSet<>(m.entrySet(), mutex); return entrySet; } } public Collection<V> values() { synchronized (mutex) { if (values==null) values = new SynchronizedCollection<>(m.values(), mutex); return values; } } public boolean equals(Object o) { if (this == o) return true; synchronized (mutex) {return m.equals(o);} } public int hashCode() { synchronized (mutex) {return m.hashCode();} } public String toString() { synchronized (mutex) {return m.toString();} } // Override default methods in Map @Override public V getOrDefault(Object k, V defaultValue) { synchronized (mutex) {return m.getOrDefault(k, defaultValue);} } @Override public void forEach(BiConsumer<? super K, ? super V> action) { synchronized (mutex) {m.forEach(action);} } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { synchronized (mutex) {m.replaceAll(function);} } @Override public V putIfAbsent(K key, V value) { synchronized (mutex) {return m.putIfAbsent(key, value);} } @Override public boolean remove(Object key, Object value) { synchronized (mutex) {return m.remove(key, value);} } @Override public boolean replace(K key, V oldValue, V newValue) { synchronized (mutex) {return m.replace(key, oldValue, newValue);} } @Override public V replace(K key, V value) { synchronized (mutex) {return m.replace(key, value);} } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { synchronized (mutex) {return m.computeIfAbsent(key, mappingFunction);} } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { synchronized (mutex) {return m.computeIfPresent(key, remappingFunction);} } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { synchronized (mutex) {return m.compute(key, remappingFunction);} } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { synchronized (mutex) {return m.merge(key, value, remappingFunction);} } private void writeObject(ObjectOutputStream s) throws IOException { synchronized (mutex) {s.defaultWriteObject();} } } /** * Returns a synchronized (thread-safe) sorted map backed by the specified * sorted map. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing sorted map is accomplished * through the returned sorted map (or its views).<p> * * It is imperative that the user manually synchronize on the returned * sorted map when traversing any of its collection views, or the * collections views of any of its {@code subMap}, {@code headMap} or * {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or * {@link Stream}: * <pre> * SortedMap m = Collections.synchronizedSortedMap(new TreeMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * or: * <pre> * SortedMap m = Collections.synchronizedSortedMap(new TreeMap()); * SortedMap m2 = m.subMap(foo, bar); * ... * Set s2 = m2.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not m2 or s2! * Iterator i = s2.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned sorted map will be serializable if the specified * sorted map is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the sorted map to be "wrapped" in a synchronized sorted map. * @return a synchronized view of the specified sorted map. */ public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) { return new SynchronizedSortedMap<>(m); } /** * @serial include */ static class SynchronizedSortedMap<K,V> extends SynchronizedMap<K,V> implements SortedMap<K,V> { private static final long serialVersionUID = -8798146769416483793L; private final SortedMap<K,V> sm; SynchronizedSortedMap(SortedMap<K,V> m) { super(m); sm = m; } SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) { super(m, mutex); sm = m; } public Comparator<? super K> comparator() { synchronized (mutex) {return sm.comparator();} } public SortedMap<K,V> subMap(K fromKey, K toKey) { synchronized (mutex) { return new SynchronizedSortedMap<>( sm.subMap(fromKey, toKey), mutex); } } public SortedMap<K,V> headMap(K toKey) { synchronized (mutex) { return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex); } } public SortedMap<K,V> tailMap(K fromKey) { synchronized (mutex) { return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex); } } public K firstKey() { synchronized (mutex) {return sm.firstKey();} } public K lastKey() { synchronized (mutex) {return sm.lastKey();} } } /** * Returns a synchronized (thread-safe) navigable map backed by the * specified navigable map. In order to guarantee serial access, it is * critical that <strong>all</strong> access to the backing navigable map is * accomplished through the returned navigable map (or its views).<p> * * It is imperative that the user manually synchronize on the returned * navigable map when traversing any of its collection views, or the * collections views of any of its {@code subMap}, {@code headMap} or * {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or * {@link Stream}: * <pre> * NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * or: * <pre> * NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap()); * NavigableMap m2 = m.subMap(foo, true, bar, false); * ... * Set s2 = m2.keySet(); // Needn't be in synchronized block * ... * synchronized (m) { // Synchronizing on m, not m2 or s2! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned navigable map will be serializable if the specified * navigable map is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the navigable map to be "wrapped" in a synchronized navigable * map * @return a synchronized view of the specified navigable map. * @since 1.8 */ public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) { return new SynchronizedNavigableMap<>(m); } /** * A synchronized NavigableMap. * * @serial include */ static class SynchronizedNavigableMap<K,V> extends SynchronizedSortedMap<K,V> implements NavigableMap<K,V> { private static final long serialVersionUID = 699392247599746807L; private final NavigableMap<K,V> nm; SynchronizedNavigableMap(NavigableMap<K,V> m) { super(m); nm = m; } SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) { super(m, mutex); nm = m; } public Entry<K, V> lowerEntry(K key) { synchronized (mutex) { return nm.lowerEntry(key); } } public K lowerKey(K key) { synchronized (mutex) { return nm.lowerKey(key); } } public Entry<K, V> floorEntry(K key) { synchronized (mutex) { return nm.floorEntry(key); } } public K floorKey(K key) { synchronized (mutex) { return nm.floorKey(key); } } public Entry<K, V> ceilingEntry(K key) { synchronized (mutex) { return nm.ceilingEntry(key); } } public K ceilingKey(K key) { synchronized (mutex) { return nm.ceilingKey(key); } } public Entry<K, V> higherEntry(K key) { synchronized (mutex) { return nm.higherEntry(key); } } public K higherKey(K key) { synchronized (mutex) { return nm.higherKey(key); } } public Entry<K, V> firstEntry() { synchronized (mutex) { return nm.firstEntry(); } } public Entry<K, V> lastEntry() { synchronized (mutex) { return nm.lastEntry(); } } public Entry<K, V> pollFirstEntry() { synchronized (mutex) { return nm.pollFirstEntry(); } } public Entry<K, V> pollLastEntry() { synchronized (mutex) { return nm.pollLastEntry(); } } public NavigableMap<K, V> descendingMap() { synchronized (mutex) { return new SynchronizedNavigableMap<>(nm.descendingMap(), mutex); } } public NavigableSet<K> keySet() { return navigableKeySet(); } public NavigableSet<K> navigableKeySet() { synchronized (mutex) { return new SynchronizedNavigableSet<>(nm.navigableKeySet(), mutex); } } public NavigableSet<K> descendingKeySet() { synchronized (mutex) { return new SynchronizedNavigableSet<>(nm.descendingKeySet(), mutex); } } public SortedMap<K,V> subMap(K fromKey, K toKey) { synchronized (mutex) { return new SynchronizedNavigableMap<>( nm.subMap(fromKey, true, toKey, false), mutex); } } public SortedMap<K,V> headMap(K toKey) { synchronized (mutex) { return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex); } } public SortedMap<K,V> tailMap(K fromKey) { synchronized (mutex) { return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex); } } public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { synchronized (mutex) { return new SynchronizedNavigableMap<>( nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableMap<>( nm.headMap(toKey, inclusive), mutex); } } public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { synchronized (mutex) { return new SynchronizedNavigableMap<>( nm.tailMap(fromKey, inclusive), mutex); } } } // Dynamically typesafe collection wrappers /** * Returns a dynamically typesafe view of the specified collection. * Any attempt to insert an element of the wrong type will result in an * immediate {@link ClassCastException}. Assuming a collection * contains no incorrectly typed elements prior to the time a * dynamically typesafe view is generated, and that all subsequent * access to the collection takes place through the view, it is * <i>guaranteed</i> that the collection cannot contain an incorrectly * typed element. * * <p>The generics mechanism in the language provides compile-time * (static) type checking, but it is possible to defeat this mechanism * with unchecked casts. Usually this is not a problem, as the compiler * issues warnings on all such unchecked operations. There are, however, * times when static type checking alone is not sufficient. For example, * suppose a collection is passed to a third-party library and it is * imperative that the library code not corrupt the collection by * inserting an element of the wrong type. * * <p>Another use of dynamically typesafe views is debugging. Suppose a * program fails with a {@code ClassCastException}, indicating that an * incorrectly typed element was put into a parameterized collection. * Unfortunately, the exception can occur at any time after the erroneous * element is inserted, so it typically provides little or no information * as to the real source of the problem. If the problem is reproducible, * one can quickly determine its source by temporarily modifying the * program to wrap the collection with a dynamically typesafe view. * For example, this declaration: * <pre> {@code * Collection<String> c = new HashSet<>(); * }</pre> * may be replaced temporarily by this one: * <pre> {@code * Collection<String> c = Collections.checkedCollection( * new HashSet<>(), String.class); * }</pre> * Running the program again will cause it to fail at the point where * an incorrectly typed element is inserted into the collection, clearly * identifying the source of the problem. Once the problem is fixed, the * modified declaration may be reverted back to the original. * * <p>The returned collection does <i>not</i> pass the hashCode and equals * operations through to the backing collection, but relies on * {@code Object}'s {@code equals} and {@code hashCode} methods. This * is necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list. * * <p>The returned collection will be serializable if the specified * collection is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned collection permits insertion of null elements * whenever the backing collection does. * * @param <E> the class of the objects in the collection * @param c the collection for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code c} is permitted to hold * @return a dynamically typesafe view of the specified collection * @since 1.5 */ public static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type) { return new CheckedCollection<>(c, type); } @SuppressWarnings("unchecked") static <T> T[] zeroLengthArray(Class<T> type) { return (T[]) Array.newInstance(type, 0); } /** * @serial include */ static class CheckedCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 1578914078182001775L; final Collection<E> c; final Class<E> type; @SuppressWarnings("unchecked") E typeCheck(Object o) { if (o != null && !type.isInstance(o)) throw new ClassCastException(badElementMsg(o)); return (E) o; } private String badElementMsg(Object o) { return "Attempt to insert " + o.getClass() + " element into collection with element type " + type; } CheckedCollection(Collection<E> c, Class<E> type) { this.c = Objects.requireNonNull(c, "c"); this.type = Objects.requireNonNull(type, "type"); } public int size() { return c.size(); } public boolean isEmpty() { return c.isEmpty(); } public boolean contains(Object o) { return c.contains(o); } public Object[] toArray() { return c.toArray(); } public <T> T[] toArray(T[] a) { return c.toArray(a); } public <T> T[] toArray(IntFunction<T[]> f) { return c.toArray(f); } public String toString() { return c.toString(); } public boolean remove(Object o) { return c.remove(o); } public void clear() { c.clear(); } public boolean containsAll(Collection<?> coll) { return c.containsAll(coll); } public boolean removeAll(Collection<?> coll) { return c.removeAll(coll); } public boolean retainAll(Collection<?> coll) { return c.retainAll(coll); } public Iterator<E> iterator() { // JDK-6363904 - unwrapped iterator could be typecast to // ListIterator with unsafe set() final Iterator<E> it = c.iterator(); return new Iterator<E>() { public boolean hasNext() { return it.hasNext(); } public E next() { return it.next(); } public void remove() { it.remove(); } public void forEachRemaining(Consumer<? super E> action) { it.forEachRemaining(action); } }; } public boolean add(E e) { return c.add(typeCheck(e)); } private E[] zeroLengthElementArray; // Lazily initialized private E[] zeroLengthElementArray() { return zeroLengthElementArray != null ? zeroLengthElementArray : (zeroLengthElementArray = zeroLengthArray(type)); } @SuppressWarnings("unchecked") Collection<E> checkedCopyOf(Collection<? extends E> coll) { Object[] a; try { E[] z = zeroLengthElementArray(); a = coll.toArray(z); // Defend against coll violating the toArray contract if (a.getClass() != z.getClass()) a = Arrays.copyOf(a, a.length, z.getClass()); } catch (ArrayStoreException ignore) { // To get better and consistent diagnostics, // we call typeCheck explicitly on each element. // We call clone() to defend against coll retaining a // reference to the returned array and storing a bad // element into it after it has been type checked. a = coll.toArray().clone(); for (Object o : a) typeCheck(o); } // A slight abuse of the type system, but safe here. return (Collection<E>) Arrays.asList(a); } public boolean addAll(Collection<? extends E> coll) { // Doing things this way insulates us from concurrent changes // in the contents of coll and provides all-or-nothing // semantics (which we wouldn't get if we type-checked each // element as we added it) return c.addAll(checkedCopyOf(coll)); } // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) {c.forEach(action);} @Override public boolean removeIf(Predicate<? super E> filter) { return c.removeIf(filter); } @Override public Spliterator<E> spliterator() {return c.spliterator();} @Override public Stream<E> stream() {return c.stream();} @Override public Stream<E> parallelStream() {return c.parallelStream();} } /** * Returns a dynamically typesafe view of the specified queue. * Any attempt to insert an element of the wrong type will result in * an immediate {@link ClassCastException}. Assuming a queue contains * no incorrectly typed elements prior to the time a dynamically typesafe * view is generated, and that all subsequent access to the queue * takes place through the view, it is <i>guaranteed</i> that the * queue cannot contain an incorrectly typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned queue will be serializable if the specified queue * is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned queue permits insertion of {@code null} elements * whenever the backing queue does. * * @param <E> the class of the objects in the queue * @param queue the queue for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code queue} is permitted to hold * @return a dynamically typesafe view of the specified queue * @since 1.8 */ public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type) { return new CheckedQueue<>(queue, type); } /** * @serial include */ static class CheckedQueue<E> extends CheckedCollection<E> implements Queue<E>, Serializable { private static final long serialVersionUID = 1433151992604707767L; final Queue<E> queue; CheckedQueue(Queue<E> queue, Class<E> elementType) { super(queue, elementType); this.queue = queue; } public E element() {return queue.element();} public boolean equals(Object o) {return o == this || c.equals(o);} public int hashCode() {return c.hashCode();} public E peek() {return queue.peek();} public E poll() {return queue.poll();} public E remove() {return queue.remove();} public boolean offer(E e) {return queue.offer(typeCheck(e));} } /** * Returns a dynamically typesafe view of the specified set. * Any attempt to insert an element of the wrong type will result in * an immediate {@link ClassCastException}. Assuming a set contains * no incorrectly typed elements prior to the time a dynamically typesafe * view is generated, and that all subsequent access to the set * takes place through the view, it is <i>guaranteed</i> that the * set cannot contain an incorrectly typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned set will be serializable if the specified set is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned set permits insertion of null elements whenever * the backing set does. * * @param <E> the class of the objects in the set * @param s the set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold * @return a dynamically typesafe view of the specified set * @since 1.5 */ public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) { return new CheckedSet<>(s, type); } /** * @serial include */ static class CheckedSet<E> extends CheckedCollection<E> implements Set<E>, Serializable { private static final long serialVersionUID = 4694047833775013803L; CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); } public boolean equals(Object o) { return o == this || c.equals(o); } public int hashCode() { return c.hashCode(); } } /** * Returns a dynamically typesafe view of the specified sorted set. * Any attempt to insert an element of the wrong type will result in an * immediate {@link ClassCastException}. Assuming a sorted set * contains no incorrectly typed elements prior to the time a * dynamically typesafe view is generated, and that all subsequent * access to the sorted set takes place through the view, it is * <i>guaranteed</i> that the sorted set cannot contain an incorrectly * typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned sorted set will be serializable if the specified sorted * set is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned sorted set permits insertion of null elements * whenever the backing sorted set does. * * @param <E> the class of the objects in the set * @param s the sorted set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold * @return a dynamically typesafe view of the specified sorted set * @since 1.5 */ public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s, Class<E> type) { return new CheckedSortedSet<>(s, type); } /** * @serial include */ static class CheckedSortedSet<E> extends CheckedSet<E> implements SortedSet<E>, Serializable { private static final long serialVersionUID = 1599911165492914959L; private final SortedSet<E> ss; CheckedSortedSet(SortedSet<E> s, Class<E> type) { super(s, type); ss = s; } public Comparator<? super E> comparator() { return ss.comparator(); } public E first() { return ss.first(); } public E last() { return ss.last(); } public SortedSet<E> subSet(E fromElement, E toElement) { return checkedSortedSet(ss.subSet(fromElement,toElement), type); } public SortedSet<E> headSet(E toElement) { return checkedSortedSet(ss.headSet(toElement), type); } public SortedSet<E> tailSet(E fromElement) { return checkedSortedSet(ss.tailSet(fromElement), type); } } /** * Returns a dynamically typesafe view of the specified navigable set. * Any attempt to insert an element of the wrong type will result in an * immediate {@link ClassCastException}. Assuming a navigable set * contains no incorrectly typed elements prior to the time a * dynamically typesafe view is generated, and that all subsequent * access to the navigable set takes place through the view, it is * <em>guaranteed</em> that the navigable set cannot contain an incorrectly * typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned navigable set will be serializable if the specified * navigable set is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned navigable set permits insertion of null elements * whenever the backing sorted set does. * * @param <E> the class of the objects in the set * @param s the navigable set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold * @return a dynamically typesafe view of the specified navigable set * @since 1.8 */ public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s, Class<E> type) { return new CheckedNavigableSet<>(s, type); } /** * @serial include */ static class CheckedNavigableSet<E> extends CheckedSortedSet<E> implements NavigableSet<E>, Serializable { private static final long serialVersionUID = -5429120189805438922L; private final NavigableSet<E> ns; CheckedNavigableSet(NavigableSet<E> s, Class<E> type) { super(s, type); ns = s; } public E lower(E e) { return ns.lower(e); } public E floor(E e) { return ns.floor(e); } public E ceiling(E e) { return ns.ceiling(e); } public E higher(E e) { return ns.higher(e); } public E pollFirst() { return ns.pollFirst(); } public E pollLast() {return ns.pollLast(); } public NavigableSet<E> descendingSet() { return checkedNavigableSet(ns.descendingSet(), type); } public Iterator<E> descendingIterator() {return checkedNavigableSet(ns.descendingSet(), type).iterator(); } public NavigableSet<E> subSet(E fromElement, E toElement) { return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type); } public NavigableSet<E> headSet(E toElement) { return checkedNavigableSet(ns.headSet(toElement, false), type); } public NavigableSet<E> tailSet(E fromElement) { return checkedNavigableSet(ns.tailSet(fromElement, true), type); } public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type); } public NavigableSet<E> headSet(E toElement, boolean inclusive) { return checkedNavigableSet(ns.headSet(toElement, inclusive), type); } public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type); } } /** * Returns a dynamically typesafe view of the specified list. * Any attempt to insert an element of the wrong type will result in * an immediate {@link ClassCastException}. Assuming a list contains * no incorrectly typed elements prior to the time a dynamically typesafe * view is generated, and that all subsequent access to the list * takes place through the view, it is <i>guaranteed</i> that the * list cannot contain an incorrectly typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned list will be serializable if the specified list * is serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned list permits insertion of null elements whenever * the backing list does. * * @param <E> the class of the objects in the list * @param list the list for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code list} is permitted to hold * @return a dynamically typesafe view of the specified list * @since 1.5 */ public static <E> List<E> checkedList(List<E> list, Class<E> type) { return (list instanceof RandomAccess ? new CheckedRandomAccessList<>(list, type) : new CheckedList<>(list, type)); } /** * @serial include */ static class CheckedList<E> extends CheckedCollection<E> implements List<E> { private static final long serialVersionUID = 65247728283967356L; final List<E> list; CheckedList(List<E> list, Class<E> type) { super(list, type); this.list = list; } public boolean equals(Object o) { return o == this || list.equals(o); } public int hashCode() { return list.hashCode(); } public E get(int index) { return list.get(index); } public E remove(int index) { return list.remove(index); } public int indexOf(Object o) { return list.indexOf(o); } public int lastIndexOf(Object o) { return list.lastIndexOf(o); } public E set(int index, E element) { return list.set(index, typeCheck(element)); } public void add(int index, E element) { list.add(index, typeCheck(element)); } public boolean addAll(int index, Collection<? extends E> c) { return list.addAll(index, checkedCopyOf(c)); } public ListIterator<E> listIterator() { return listIterator(0); } public ListIterator<E> listIterator(final int index) { final ListIterator<E> i = list.listIterator(index); return new ListIterator<E>() { public boolean hasNext() { return i.hasNext(); } public E next() { return i.next(); } public boolean hasPrevious() { return i.hasPrevious(); } public E previous() { return i.previous(); } public int nextIndex() { return i.nextIndex(); } public int previousIndex() { return i.previousIndex(); } public void remove() { i.remove(); } public void set(E e) { i.set(typeCheck(e)); } public void add(E e) { i.add(typeCheck(e)); } @Override public void forEachRemaining(Consumer<? super E> action) { i.forEachRemaining(action); } }; } public List<E> subList(int fromIndex, int toIndex) { return new CheckedList<>(list.subList(fromIndex, toIndex), type); } /** * {@inheritDoc} * * @throws ClassCastException if the class of an element returned by the * operator prevents it from being added to this collection. The * exception may be thrown after some elements of the list have * already been replaced. */ @Override public void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); list.replaceAll(e -> typeCheck(operator.apply(e))); } @Override public void sort(Comparator<? super E> c) { list.sort(c); } } /** * @serial include */ static class CheckedRandomAccessList<E> extends CheckedList<E> implements RandomAccess { private static final long serialVersionUID = 1638200125423088369L; CheckedRandomAccessList(List<E> list, Class<E> type) { super(list, type); } public List<E> subList(int fromIndex, int toIndex) { return new CheckedRandomAccessList<>( list.subList(fromIndex, toIndex), type); } } /** * Returns a dynamically typesafe view of the specified map. * Any attempt to insert a mapping whose key or value have the wrong * type will result in an immediate {@link ClassCastException}. * Similarly, any attempt to modify the value currently associated with * a key will result in an immediate {@link ClassCastException}, * whether the modification is attempted directly through the map * itself, or through a {@link Map.Entry} instance obtained from the * map's {@link Map#entrySet() entry set} view. * * <p>Assuming a map contains no incorrectly typed keys or values * prior to the time a dynamically typesafe view is generated, and * that all subsequent access to the map takes place through the view * (or one of its collection views), it is <i>guaranteed</i> that the * map cannot contain an incorrectly typed key or value. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned map will be serializable if the specified map is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned map permits insertion of null keys or values * whenever the backing map does. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold * @param valueType the type of value that {@code m} is permitted to hold * @return a dynamically typesafe view of the specified map * @since 1.5 */ public static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) { return new CheckedMap<>(m, keyType, valueType); } /** * @serial include */ private static class CheckedMap<K,V> implements Map<K,V>, Serializable { private static final long serialVersionUID = 5742860141034234728L; private final Map<K, V> m; final Class<K> keyType; final Class<V> valueType; private void typeCheck(Object key, Object value) { if (key != null && !keyType.isInstance(key)) throw new ClassCastException(badKeyMsg(key)); if (value != null && !valueType.isInstance(value)) throw new ClassCastException(badValueMsg(value)); } private BiFunction<? super K, ? super V, ? extends V> typeCheck( BiFunction<? super K, ? super V, ? extends V> func) { Objects.requireNonNull(func); return (k, v) -> { V newValue = func.apply(k, v); typeCheck(k, newValue); return newValue; }; } private String badKeyMsg(Object key) { return "Attempt to insert " + key.getClass() + " key into map with key type " + keyType; } private String badValueMsg(Object value) { return "Attempt to insert " + value.getClass() + " value into map with value type " + valueType; } CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) { this.m = Objects.requireNonNull(m); this.keyType = Objects.requireNonNull(keyType); this.valueType = Objects.requireNonNull(valueType); } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean containsKey(Object key) { return m.containsKey(key); } public boolean containsValue(Object v) { return m.containsValue(v); } public V get(Object key) { return m.get(key); } public V remove(Object key) { return m.remove(key); } public void clear() { m.clear(); } public Set<K> keySet() { return m.keySet(); } public Collection<V> values() { return m.values(); } public boolean equals(Object o) { return o == this || m.equals(o); } public int hashCode() { return m.hashCode(); } public String toString() { return m.toString(); } public V put(K key, V value) { typeCheck(key, value); return m.put(key, value); } @SuppressWarnings("unchecked") public void putAll(Map<? extends K, ? extends V> t) { // Satisfy the following goals: // - good diagnostics in case of type mismatch // - all-or-nothing semantics // - protection from malicious t // - correct behavior if t is a concurrent map Object[] entries = t.entrySet().toArray(); List<Entry<K,V>> checked = new ArrayList<>(entries.length); for (Object o : entries) { Entry<?,?> e = (Entry<?,?>) o; Object k = e.getKey(); Object v = e.getValue(); typeCheck(k, v); checked.add( new AbstractMap.SimpleImmutableEntry<>((K)k, (V)v)); } for (Entry<K,V> e : checked) m.put(e.getKey(), e.getValue()); } private transient Set<Entry<K,V>> entrySet; public Set<Entry<K,V>> entrySet() { if (entrySet==null) entrySet = new CheckedEntrySet<>(m.entrySet(), valueType); return entrySet; } // Override default methods in Map @Override public void forEach(BiConsumer<? super K, ? super V> action) { m.forEach(action); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { m.replaceAll(typeCheck(function)); } @Override public V putIfAbsent(K key, V value) { typeCheck(key, value); return m.putIfAbsent(key, value); } @Override public boolean remove(Object key, Object value) { return m.remove(key, value); } @Override public boolean replace(K key, V oldValue, V newValue) { typeCheck(key, newValue); return m.replace(key, oldValue, newValue); } @Override public V replace(K key, V value) { typeCheck(key, value); return m.replace(key, value); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { Objects.requireNonNull(mappingFunction); return m.computeIfAbsent(key, k -> { V value = mappingFunction.apply(k); typeCheck(k, value); return value; }); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return m.computeIfPresent(key, typeCheck(remappingFunction)); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return m.compute(key, typeCheck(remappingFunction)); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); return m.merge(key, value, (v1, v2) -> { V newValue = remappingFunction.apply(v1, v2); typeCheck(null, newValue); return newValue; }); } /** * We need this class in addition to CheckedSet as Map.Entry permits * modification of the backing Map via the setValue operation. This * class is subtle: there are many possible attacks that must be * thwarted. * * @serial exclude */ static class CheckedEntrySet<K,V> implements Set<Entry<K,V>> { private final Set<Entry<K,V>> s; private final Class<V> valueType; CheckedEntrySet(Set<Entry<K, V>> s, Class<V> valueType) { this.s = s; this.valueType = valueType; } public int size() { return s.size(); } public boolean isEmpty() { return s.isEmpty(); } public String toString() { return s.toString(); } public int hashCode() { return s.hashCode(); } public void clear() { s.clear(); } public boolean add(Entry<K, V> e) { throw new UnsupportedOperationException(); } public boolean addAll(Collection<? extends Entry<K, V>> coll) { throw new UnsupportedOperationException(); } public Iterator<Entry<K,V>> iterator() { final Iterator<Entry<K, V>> i = s.iterator(); return new Iterator<Entry<K,V>>() { public boolean hasNext() { return i.hasNext(); } public void remove() { i.remove(); } public Entry<K,V> next() { return checkedEntry(i.next(), valueType); } public void forEachRemaining(Consumer<? super Entry<K, V>> action) { i.forEachRemaining( e -> action.accept(checkedEntry(e, valueType))); } }; } @SuppressWarnings("unchecked") public Object[] toArray() { Object[] source = s.toArray(); /* * Ensure that we don't get an ArrayStoreException even if * s.toArray returns an array of something other than Object */ Object[] dest = (source.getClass() == Object[].class) ? source : new Object[source.length]; for (int i = 0; i < source.length; i++) dest[i] = checkedEntry((Entry<K,V>)source[i], valueType); return dest; } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { // We don't pass a to s.toArray, to avoid window of // vulnerability wherein an unscrupulous multithreaded client // could get his hands on raw (unwrapped) Entries from s. T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0)); for (int i=0; i<arr.length; i++) arr[i] = (T) checkedEntry((Entry<K,V>)arr[i], valueType); if (arr.length > a.length) return arr; System.arraycopy(arr, 0, a, 0, arr.length); if (a.length > arr.length) a[arr.length] = null; return a; } /** * This method is overridden to protect the backing set against * an object with a nefarious equals function that senses * that the equality-candidate is Map.Entry and calls its * setValue method. */ public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Entry<?,?> e = (Entry<?,?>) o; return s.contains( (e instanceof CheckedEntry) ? e : checkedEntry(e, valueType)); } /** * The bulk collection methods are overridden to protect * against an unscrupulous collection whose contains(Object o) * method senses when o is a Map.Entry, and calls o.setValue. */ public boolean containsAll(Collection<?> c) { for (Object o : c) if (!contains(o)) // Invokes safe contains() above return false; return true; } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; return s.remove(new AbstractMap.SimpleImmutableEntry <>((Entry<?,?>)o)); } public boolean removeAll(Collection<?> c) { return batchRemove(c, false); } public boolean retainAll(Collection<?> c) { return batchRemove(c, true); } private boolean batchRemove(Collection<?> c, boolean complement) { Objects.requireNonNull(c); boolean modified = false; Iterator<Entry<K,V>> it = iterator(); while (it.hasNext()) { if (c.contains(it.next()) != complement) { it.remove(); modified = true; } } return modified; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Set<?> that = (Set<?>) o; return that.size() == s.size() && containsAll(that); // Invokes safe containsAll() above } static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Entry<K,V> e, Class<T> valueType) { return new CheckedEntry<>(e, valueType); } /** * This "wrapper class" serves two purposes: it prevents * the client from modifying the backing Map, by short-circuiting * the setValue method, and it protects the backing Map against * an ill-behaved Map.Entry that attempts to modify another * Map.Entry when asked to perform an equality check. */ private static class CheckedEntry<K,V,T> implements Entry<K,V> { private final Entry<K, V> e; private final Class<T> valueType; CheckedEntry(Entry<K, V> e, Class<T> valueType) { this.e = Objects.requireNonNull(e); this.valueType = Objects.requireNonNull(valueType); } public K getKey() { return e.getKey(); } public V getValue() { return e.getValue(); } public int hashCode() { return e.hashCode(); } public String toString() { return e.toString(); } public V setValue(V value) { if (value != null && !valueType.isInstance(value)) throw new ClassCastException(badValueMsg(value)); return e.setValue(value); } private String badValueMsg(Object value) { return "Attempt to insert " + value.getClass() + " value into map with value type " + valueType; } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map.Entry)) return false; return e.equals(new AbstractMap.SimpleImmutableEntry <>((Entry<?,?>)o)); } } } } /** * Returns a dynamically typesafe view of the specified sorted map. * Any attempt to insert a mapping whose key or value have the wrong * type will result in an immediate {@link ClassCastException}. * Similarly, any attempt to modify the value currently associated with * a key will result in an immediate {@link ClassCastException}, * whether the modification is attempted directly through the map * itself, or through a {@link Map.Entry} instance obtained from the * map's {@link Map#entrySet() entry set} view. * * <p>Assuming a map contains no incorrectly typed keys or values * prior to the time a dynamically typesafe view is generated, and * that all subsequent access to the map takes place through the view * (or one of its collection views), it is <i>guaranteed</i> that the * map cannot contain an incorrectly typed key or value. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned map will be serializable if the specified map is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned map permits insertion of null keys or values * whenever the backing map does. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold * @param valueType the type of value that {@code m} is permitted to hold * @return a dynamically typesafe view of the specified map * @since 1.5 */ public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m, Class<K> keyType, Class<V> valueType) { return new CheckedSortedMap<>(m, keyType, valueType); } /** * @serial include */ static class CheckedSortedMap<K,V> extends CheckedMap<K,V> implements SortedMap<K,V>, Serializable { private static final long serialVersionUID = 1599671320688067438L; private final SortedMap<K, V> sm; CheckedSortedMap(SortedMap<K, V> m, Class<K> keyType, Class<V> valueType) { super(m, keyType, valueType); sm = m; } public Comparator<? super K> comparator() { return sm.comparator(); } public K firstKey() { return sm.firstKey(); } public K lastKey() { return sm.lastKey(); } public SortedMap<K,V> subMap(K fromKey, K toKey) { return checkedSortedMap(sm.subMap(fromKey, toKey), keyType, valueType); } public SortedMap<K,V> headMap(K toKey) { return checkedSortedMap(sm.headMap(toKey), keyType, valueType); } public SortedMap<K,V> tailMap(K fromKey) { return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType); } } /** * Returns a dynamically typesafe view of the specified navigable map. * Any attempt to insert a mapping whose key or value have the wrong * type will result in an immediate {@link ClassCastException}. * Similarly, any attempt to modify the value currently associated with * a key will result in an immediate {@link ClassCastException}, * whether the modification is attempted directly through the map * itself, or through a {@link Map.Entry} instance obtained from the * map's {@link Map#entrySet() entry set} view. * * <p>Assuming a map contains no incorrectly typed keys or values * prior to the time a dynamically typesafe view is generated, and * that all subsequent access to the map takes place through the view * (or one of its collection views), it is <em>guaranteed</em> that the * map cannot contain an incorrectly typed key or value. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned map will be serializable if the specified map is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned map permits insertion of null keys or values * whenever the backing map does. * * @param <K> type of map keys * @param <V> type of map values * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold * @param valueType the type of value that {@code m} is permitted to hold * @return a dynamically typesafe view of the specified map * @since 1.8 */ public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m, Class<K> keyType, Class<V> valueType) { return new CheckedNavigableMap<>(m, keyType, valueType); } /** * @serial include */ static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V> implements NavigableMap<K,V>, Serializable { private static final long serialVersionUID = -4852462692372534096L; private final NavigableMap<K, V> nm; CheckedNavigableMap(NavigableMap<K, V> m, Class<K> keyType, Class<V> valueType) { super(m, keyType, valueType); nm = m; } public Comparator<? super K> comparator() { return nm.comparator(); } public K firstKey() { return nm.firstKey(); } public K lastKey() { return nm.lastKey(); } public Entry<K, V> lowerEntry(K key) { Entry<K,V> lower = nm.lowerEntry(key); return (null != lower) ? new CheckedEntrySet.CheckedEntry<>(lower, valueType) : null; } public K lowerKey(K key) { return nm.lowerKey(key); } public Entry<K, V> floorEntry(K key) { Entry<K,V> floor = nm.floorEntry(key); return (null != floor) ? new CheckedEntrySet.CheckedEntry<>(floor, valueType) : null; } public K floorKey(K key) { return nm.floorKey(key); } public Entry<K, V> ceilingEntry(K key) { Entry<K,V> ceiling = nm.ceilingEntry(key); return (null != ceiling) ? new CheckedEntrySet.CheckedEntry<>(ceiling, valueType) : null; } public K ceilingKey(K key) { return nm.ceilingKey(key); } public Entry<K, V> higherEntry(K key) { Entry<K,V> higher = nm.higherEntry(key); return (null != higher) ? new CheckedEntrySet.CheckedEntry<>(higher, valueType) : null; } public K higherKey(K key) { return nm.higherKey(key); } public Entry<K, V> firstEntry() { Entry<K,V> first = nm.firstEntry(); return (null != first) ? new CheckedEntrySet.CheckedEntry<>(first, valueType) : null; } public Entry<K, V> lastEntry() { Entry<K,V> last = nm.lastEntry(); return (null != last) ? new CheckedEntrySet.CheckedEntry<>(last, valueType) : null; } public Entry<K, V> pollFirstEntry() { Entry<K,V> entry = nm.pollFirstEntry(); return (null == entry) ? null : new CheckedEntrySet.CheckedEntry<>(entry, valueType); } public Entry<K, V> pollLastEntry() { Entry<K,V> entry = nm.pollLastEntry(); return (null == entry) ? null : new CheckedEntrySet.CheckedEntry<>(entry, valueType); } public NavigableMap<K, V> descendingMap() { return checkedNavigableMap(nm.descendingMap(), keyType, valueType); } public NavigableSet<K> keySet() { return navigableKeySet(); } public NavigableSet<K> navigableKeySet() { return checkedNavigableSet(nm.navigableKeySet(), keyType); } public NavigableSet<K> descendingKeySet() { return checkedNavigableSet(nm.descendingKeySet(), keyType); } @Override public NavigableMap<K,V> subMap(K fromKey, K toKey) { return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false), keyType, valueType); } @Override public NavigableMap<K,V> headMap(K toKey) { return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType); } @Override public NavigableMap<K,V> tailMap(K fromKey) { return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType); } public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType); } public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType); } public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType); } } // Empty collections /** * Returns an iterator that has no elements. More precisely, * * <ul> * <li>{@link Iterator#hasNext hasNext} always returns {@code * false}.</li> * <li>{@link Iterator#next next} always throws {@link * NoSuchElementException}.</li> * <li>{@link Iterator#remove remove} always throws {@link * IllegalStateException}.</li> * </ul> * * <p>Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * * @param <T> type of elements, if there were any, in the iterator * @return an empty iterator * @since 1.7 */ @SuppressWarnings("unchecked") public static <T> Iterator<T> emptyIterator() { return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR; } private static class EmptyIterator<E> implements Iterator<E> { static final EmptyIterator<Object> EMPTY_ITERATOR = new EmptyIterator<>(); public boolean hasNext() { return false; } public E next() { throw new NoSuchElementException(); } public void remove() { throw new IllegalStateException(); } @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); } } /** * Returns a list iterator that has no elements. More precisely, * * <ul> * <li>{@link Iterator#hasNext hasNext} and {@link * ListIterator#hasPrevious hasPrevious} always return {@code * false}.</li> * <li>{@link Iterator#next next} and {@link ListIterator#previous * previous} always throw {@link NoSuchElementException}.</li> * <li>{@link Iterator#remove remove} and {@link ListIterator#set * set} always throw {@link IllegalStateException}.</li> * <li>{@link ListIterator#add add} always throws {@link * UnsupportedOperationException}.</li> * <li>{@link ListIterator#nextIndex nextIndex} always returns * {@code 0}.</li> * <li>{@link ListIterator#previousIndex previousIndex} always * returns {@code -1}.</li> * </ul> * * <p>Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * * @param <T> type of elements, if there were any, in the iterator * @return an empty list iterator * @since 1.7 */ @SuppressWarnings("unchecked") public static <T> ListIterator<T> emptyListIterator() { return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR; } private static class EmptyListIterator<E> extends EmptyIterator<E> implements ListIterator<E> { static final EmptyListIterator<Object> EMPTY_ITERATOR = new EmptyListIterator<>(); public boolean hasPrevious() { return false; } public E previous() { throw new NoSuchElementException(); } public int nextIndex() { return 0; } public int previousIndex() { return -1; } public void set(E e) { throw new IllegalStateException(); } public void add(E e) { throw new UnsupportedOperationException(); } } /** * Returns an enumeration that has no elements. More precisely, * * <ul> * <li>{@link Enumeration#hasMoreElements hasMoreElements} always * returns {@code false}.</li> * <li> {@link Enumeration#nextElement nextElement} always throws * {@link NoSuchElementException}.</li> * </ul> * * <p>Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * * @param <T> the class of the objects in the enumeration * @return an empty enumeration * @since 1.7 */ @SuppressWarnings("unchecked") public static <T> Enumeration<T> emptyEnumeration() { return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION; } private static class EmptyEnumeration<E> implements Enumeration<E> { static final EmptyEnumeration<Object> EMPTY_ENUMERATION = new EmptyEnumeration<>(); public boolean hasMoreElements() { return false; } public E nextElement() { throw new NoSuchElementException(); } public Iterator<E> asIterator() { return emptyIterator(); } } /** * The empty set (immutable). This set is serializable. * * @see #emptySet() */ @SuppressWarnings("rawtypes") public static final Set EMPTY_SET = new EmptySet<>(); /** * Returns an empty set (immutable). This set is serializable. * Unlike the like-named field, this method is parameterized. * * <p>This example illustrates the type-safe way to obtain an empty set: * <pre> * Set&lt;String&gt; s = Collections.emptySet(); * </pre> * @implNote Implementations of this method need not create a separate * {@code Set} object for each call. Using this method is likely to have * comparable cost to using the like-named field. (Unlike this method, the * field does not provide type safety.) * * @param <T> the class of the objects in the set * @return the empty set * * @see #EMPTY_SET * @since 1.5 */ @SuppressWarnings("unchecked") public static final <T> Set<T> emptySet() { return (Set<T>) EMPTY_SET; } /** * @serial include */ private static class EmptySet<E> extends AbstractSet<E> implements Serializable { private static final long serialVersionUID = 1582296315990362920L; public Iterator<E> iterator() { return emptyIterator(); } public int size() {return 0;} public boolean isEmpty() {return true;} public void clear() {} public boolean contains(Object obj) {return false;} public boolean containsAll(Collection<?> c) { return c.isEmpty(); } public Object[] toArray() { return new Object[0]; } public <T> T[] toArray(T[] a) { if (a.length > 0) a[0] = null; return a; } // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); } @Override public boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); return false; } @Override public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); } // Preserves singleton property private Object readResolve() { return EMPTY_SET; } @Override public int hashCode() { return 0; } } /** * Returns an empty sorted set (immutable). This set is serializable. * * <p>This example illustrates the type-safe way to obtain an empty * sorted set: * <pre> {@code * SortedSet<String> s = Collections.emptySortedSet(); * }</pre> * * @implNote Implementations of this method need not create a separate * {@code SortedSet} object for each call. * * @param <E> type of elements, if there were any, in the set * @return the empty sorted set * @since 1.8 */ @SuppressWarnings("unchecked") public static <E> SortedSet<E> emptySortedSet() { return (SortedSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET; } /** * Returns an empty navigable set (immutable). This set is serializable. * * <p>This example illustrates the type-safe way to obtain an empty * navigable set: * <pre> {@code * NavigableSet<String> s = Collections.emptyNavigableSet(); * }</pre> * * @implNote Implementations of this method need not * create a separate {@code NavigableSet} object for each call. * * @param <E> type of elements, if there were any, in the set * @return the empty navigable set * @since 1.8 */ @SuppressWarnings("unchecked") public static <E> NavigableSet<E> emptyNavigableSet() { return (NavigableSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET; } /** * The empty list (immutable). This list is serializable. * * @see #emptyList() */ @SuppressWarnings("rawtypes") public static final List EMPTY_LIST = new EmptyList<>(); /** * Returns an empty list (immutable). This list is serializable. * * <p>This example illustrates the type-safe way to obtain an empty list: * <pre> * List&lt;String&gt; s = Collections.emptyList(); * </pre> * * @implNote * Implementations of this method need not create a separate {@code List} * object for each call. Using this method is likely to have comparable * cost to using the like-named field. (Unlike this method, the field does * not provide type safety.) * * @param <T> type of elements, if there were any, in the list * @return an empty immutable list * * @see #EMPTY_LIST * @since 1.5 */ @SuppressWarnings("unchecked") public static final <T> List<T> emptyList() { return (List<T>) EMPTY_LIST; } /** * @serial include */ private static class EmptyList<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 8842843931221139166L; public Iterator<E> iterator() { return emptyIterator(); } public ListIterator<E> listIterator() { return emptyListIterator(); } public int size() {return 0;} public boolean isEmpty() {return true;} public void clear() {} public boolean contains(Object obj) {return false;} public boolean containsAll(Collection<?> c) { return c.isEmpty(); } public Object[] toArray() { return new Object[0]; } public <T> T[] toArray(T[] a) { if (a.length > 0) a[0] = null; return a; } public E get(int index) { throw new IndexOutOfBoundsException("Index: "+index); } public boolean equals(Object o) { return (o instanceof List) && ((List<?>)o).isEmpty(); } public int hashCode() { return 1; } @Override public boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); return false; } @Override public void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); } @Override public void sort(Comparator<? super E> c) { } // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); } @Override public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); } // Preserves singleton property private Object readResolve() { return EMPTY_LIST; } } /** * The empty map (immutable). This map is serializable. * * @see #emptyMap() * @since 1.3 */ @SuppressWarnings("rawtypes") public static final Map EMPTY_MAP = new EmptyMap<>(); /** * Returns an empty map (immutable). This map is serializable. * * <p>This example illustrates the type-safe way to obtain an empty map: * <pre> * Map&lt;String, Date&gt; s = Collections.emptyMap(); * </pre> * @implNote Implementations of this method need not create a separate * {@code Map} object for each call. Using this method is likely to have * comparable cost to using the like-named field. (Unlike this method, the * field does not provide type safety.) * * @param <K> the class of the map keys * @param <V> the class of the map values * @return an empty map * @see #EMPTY_MAP * @since 1.5 */ @SuppressWarnings("unchecked") public static final <K,V> Map<K,V> emptyMap() { return (Map<K,V>) EMPTY_MAP; } /** * Returns an empty sorted map (immutable). This map is serializable. * * <p>This example illustrates the type-safe way to obtain an empty map: * <pre> {@code * SortedMap<String, Date> s = Collections.emptySortedMap(); * }</pre> * * @implNote Implementations of this method need not create a separate * {@code SortedMap} object for each call. * * @param <K> the class of the map keys * @param <V> the class of the map values * @return an empty sorted map * @since 1.8 */ @SuppressWarnings("unchecked") public static final <K,V> SortedMap<K,V> emptySortedMap() { return (SortedMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP; } /** * Returns an empty navigable map (immutable). This map is serializable. * * <p>This example illustrates the type-safe way to obtain an empty map: * <pre> {@code * NavigableMap<String, Date> s = Collections.emptyNavigableMap(); * }</pre> * * @implNote Implementations of this method need not create a separate * {@code NavigableMap} object for each call. * * @param <K> the class of the map keys * @param <V> the class of the map values * @return an empty navigable map * @since 1.8 */ @SuppressWarnings("unchecked") public static final <K,V> NavigableMap<K,V> emptyNavigableMap() { return (NavigableMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP; } /** * @serial include */ private static class EmptyMap<K,V> extends AbstractMap<K,V> implements Serializable { private static final long serialVersionUID = 6428348081105594320L; public int size() {return 0;} public boolean isEmpty() {return true;} public void clear() {} public boolean containsKey(Object key) {return false;} public boolean containsValue(Object value) {return false;} public V get(Object key) {return null;} public Set<K> keySet() {return emptySet();} public Collection<V> values() {return emptySet();} public Set<Entry<K,V>> entrySet() {return emptySet();} public boolean equals(Object o) { return (o instanceof Map) && ((Map<?,?>)o).isEmpty(); } public int hashCode() {return 0;} // Override default methods in Map @Override @SuppressWarnings("unchecked") public V getOrDefault(Object k, V defaultValue) { return defaultValue; } @Override public void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { Objects.requireNonNull(function); } @Override public V putIfAbsent(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException(); } @Override public V replace(K key, V value) { throw new UnsupportedOperationException(); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException(); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } // Preserves singleton property private Object readResolve() { return EMPTY_MAP; } } // Singleton collections /** * Returns an immutable set containing only the specified object. * The returned set is serializable. * * @param <T> the class of the objects in the set * @param o the sole object to be stored in the returned set. * @return an immutable set containing only the specified object. */ public static <T> Set<T> singleton(T o) { return new SingletonSet<>(o); } static <E> Iterator<E> singletonIterator(final E e) { return new Iterator<E>() { private boolean hasNext = true; public boolean hasNext() { return hasNext; } public E next() { if (hasNext) { hasNext = false; return e; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); if (hasNext) { hasNext = false; action.accept(e); } } }; } /** * Creates a {@code Spliterator} with only the specified element * * @param <T> Type of elements * @return A singleton {@code Spliterator} */ static <T> Spliterator<T> singletonSpliterator(final T element) { return new Spliterator<T>() { long est = 1; @Override public Spliterator<T> trySplit() { return null; } @Override public boolean tryAdvance(Consumer<? super T> consumer) { Objects.requireNonNull(consumer); if (est > 0) { est--; consumer.accept(element); return true; } return false; } @Override public void forEachRemaining(Consumer<? super T> consumer) { tryAdvance(consumer); } @Override public long estimateSize() { return est; } @Override public int characteristics() { int value = (element != null) ? Spliterator.NONNULL : 0; return value | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE | Spliterator.DISTINCT | Spliterator.ORDERED; } }; } /** * @serial include */ private static class SingletonSet<E> extends AbstractSet<E> implements Serializable { private static final long serialVersionUID = 3193687207550431679L; private final E element; SingletonSet(E e) {element = e;} public Iterator<E> iterator() { return singletonIterator(element); } public int size() {return 1;} public boolean contains(Object o) {return eq(o, element);} // Override default methods for Collection @Override public void forEach(Consumer<? super E> action) { action.accept(element); } @Override public Spliterator<E> spliterator() { return singletonSpliterator(element); } @Override public boolean removeIf(Predicate<? super E> filter) { throw new UnsupportedOperationException(); } @Override public int hashCode() { return Objects.hashCode(element); } } /** * Returns an immutable list containing only the specified object. * The returned list is serializable. * * @param <T> the class of the objects in the list * @param o the sole object to be stored in the returned list. * @return an immutable list containing only the specified object. * @since 1.3 */ public static <T> List<T> singletonList(T o) { return new SingletonList<>(o); } /** * @serial include */ private static class SingletonList<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 3093736618740652951L; private final E element; SingletonList(E obj) {element = obj;} public Iterator<E> iterator() { return singletonIterator(element); } public int size() {return 1;} public boolean contains(Object obj) {return eq(obj, element);} public E get(int index) { if (index != 0) throw new IndexOutOfBoundsException("Index: "+index+", Size: 1"); return element; } // Override default methods for Collection @Override public void forEach(Consumer<? super E> action) { action.accept(element); } @Override public boolean removeIf(Predicate<? super E> filter) { throw new UnsupportedOperationException(); } @Override public void replaceAll(UnaryOperator<E> operator) { throw new UnsupportedOperationException(); } @Override public void sort(Comparator<? super E> c) { } @Override public Spliterator<E> spliterator() { return singletonSpliterator(element); } @Override public int hashCode() { return 31 + Objects.hashCode(element); } } /** * Returns an immutable map, mapping only the specified key to the * specified value. The returned map is serializable. * * @param <K> the class of the map keys * @param <V> the class of the map values * @param key the sole key to be stored in the returned map. * @param value the value to which the returned map maps {@code key}. * @return an immutable map containing only the specified key-value * mapping. * @since 1.3 */ public static <K,V> Map<K,V> singletonMap(K key, V value) { return new SingletonMap<>(key, value); } /** * @serial include */ private static class SingletonMap<K,V> extends AbstractMap<K,V> implements Serializable { private static final long serialVersionUID = -6979724477215052911L; private final K k; private final V v; SingletonMap(K key, V value) { k = key; v = value; } public int size() {return 1;} public boolean isEmpty() {return false;} public boolean containsKey(Object key) {return eq(key, k);} public boolean containsValue(Object value) {return eq(value, v);} public V get(Object key) {return (eq(key, k) ? v : null);} private transient Set<K> keySet; private transient Set<Entry<K,V>> entrySet; private transient Collection<V> values; public Set<K> keySet() { if (keySet==null) keySet = singleton(k); return keySet; } public Set<Entry<K,V>> entrySet() { if (entrySet==null) entrySet = Collections.<Entry<K,V>>singleton( new SimpleImmutableEntry<>(k, v)); return entrySet; } public Collection<V> values() { if (values==null) values = singleton(v); return values; } // Override default methods in Map @Override public V getOrDefault(Object key, V defaultValue) { return eq(key, k) ? v : defaultValue; } @Override public void forEach(BiConsumer<? super K, ? super V> action) { action.accept(k, v); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { throw new UnsupportedOperationException(); } @Override public V putIfAbsent(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException(); } @Override public V replace(K key, V value) { throw new UnsupportedOperationException(); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException(); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException(); } @Override public int hashCode() { return Objects.hashCode(k) ^ Objects.hashCode(v); } } // Miscellaneous /** * Returns an immutable list consisting of {@code n} copies of the * specified object. The newly allocated data object is tiny (it contains * a single reference to the data object). This method is useful in * combination with the {@code List.addAll} method to grow lists. * The returned list is serializable. * * @param <T> the class of the object to copy and of the objects * in the returned list. * @param n the number of elements in the returned list. * @param o the element to appear repeatedly in the returned list. * @return an immutable list consisting of {@code n} copies of the * specified object. * @throws IllegalArgumentException if {@code n < 0} * @see List#addAll(Collection) * @see List#addAll(int, Collection) */ public static <T> List<T> nCopies(int n, T o) { if (n < 0) throw new IllegalArgumentException("List length = " + n); return new CopiesList<>(n, o); } /** * @serial include */ private static class CopiesList<E> extends AbstractList<E> implements RandomAccess, Serializable { private static final long serialVersionUID = 2739099268398711800L; final int n; final E element; CopiesList(int n, E e) { assert n >= 0; this.n = n; element = e; } public int size() { return n; } public boolean contains(Object obj) { return n != 0 && eq(obj, element); } public int indexOf(Object o) { return contains(o) ? 0 : -1; } public int lastIndexOf(Object o) { return contains(o) ? n - 1 : -1; } public E get(int index) { if (index < 0 || index >= n) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+n); return element; } public Object[] toArray() { final Object[] a = new Object[n]; if (element != null) Arrays.fill(a, 0, n, element); return a; } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { final int n = this.n; if (a.length < n) { a = (T[]) Array .newInstance(a.getClass().getComponentType(), n); if (element != null) Arrays.fill(a, 0, n, element); } else { Arrays.fill(a, 0, n, element); if (a.length > n) a[n] = null; } return a; } public List<E> subList(int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > n) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); return new CopiesList<>(toIndex - fromIndex, element); } @Override public int hashCode() { if (n == 0) return 1; // hashCode of n repeating elements is 31^n + elementHash * Sum(31^k, k = 0..n-1) // this implementation completes in O(log(n)) steps taking advantage of // 31^(2*n) = (31^n)^2 and Sum(31^k, k = 0..(2*n-1)) = Sum(31^k, k = 0..n-1) * (31^n + 1) int pow = 31; int sum = 1; for (int i = Integer.numberOfLeadingZeros(n) + 1; i < Integer.SIZE; i++) { sum *= pow + 1; pow *= pow; if ((n << i) < 0) { pow *= 31; sum = sum * 31 + 1; } } return pow + sum * (element == null ? 0 : element.hashCode()); } @Override public boolean equals(Object o) { if (o == this) return true; if (o instanceof CopiesList) { CopiesList<?> other = (CopiesList<?>) o; return n == other.n && (n == 0 || eq(element, other.element)); } if (!(o instanceof List)) return false; int remaining = n; E e = element; Iterator<?> itr = ((List<?>) o).iterator(); if (e == null) { while (itr.hasNext() && remaining-- > 0) { if (itr.next() != null) return false; } } else { while (itr.hasNext() && remaining-- > 0) { if (!e.equals(itr.next())) return false; } } return remaining == 0 && !itr.hasNext(); } // Override default methods in Collection @Override public Stream<E> stream() { return IntStream.range(0, n).mapToObj(i -> element); } @Override public Stream<E> parallelStream() { return IntStream.range(0, n).parallel().mapToObj(i -> element); } @Override public Spliterator<E> spliterator() { return stream().spliterator(); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); SharedSecrets.getJavaObjectInputStreamAccess().checkArray(ois, Object[].class, n); } } /** * Returns a comparator that imposes the reverse of the <em>natural * ordering</em> on a collection of objects that implement the * {@code Comparable} interface. (The natural ordering is the ordering * imposed by the objects' own {@code compareTo} method.) This enables a * simple idiom for sorting (or maintaining) collections (or arrays) of * objects that implement the {@code Comparable} interface in * reverse-natural-order. For example, suppose {@code a} is an array of * strings. Then: <pre> * Arrays.sort(a, Collections.reverseOrder()); * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p> * * The returned comparator is serializable. * * @param <T> the class of the objects compared by the comparator * @return A comparator that imposes the reverse of the <i>natural * ordering</i> on a collection of objects that implement * the {@code Comparable} interface. * @see Comparable */ @SuppressWarnings("unchecked") public static <T> Comparator<T> reverseOrder() { return (Comparator<T>) ReverseComparator.REVERSE_ORDER; } /** * @serial include */ private static class ReverseComparator implements Comparator<Comparable<Object>>, Serializable { private static final long serialVersionUID = 7207038068494060240L; static final ReverseComparator REVERSE_ORDER = new ReverseComparator(); public int compare(Comparable<Object> c1, Comparable<Object> c2) { return c2.compareTo(c1); } private Object readResolve() { return Collections.reverseOrder(); } @Override public Comparator<Comparable<Object>> reversed() { return Comparator.naturalOrder(); } } /** * Returns a comparator that imposes the reverse ordering of the specified * comparator. If the specified comparator is {@code null}, this method is * equivalent to {@link #reverseOrder()} (in other words, it returns a * comparator that imposes the reverse of the <em>natural ordering</em> on * a collection of objects that implement the Comparable interface). * * <p>The returned comparator is serializable (assuming the specified * comparator is also serializable or {@code null}). * * @param <T> the class of the objects compared by the comparator * @param cmp a comparator who's ordering is to be reversed by the returned * comparator or {@code null} * @return A comparator that imposes the reverse ordering of the * specified comparator. * @since 1.5 */ @SuppressWarnings("unchecked") public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) { if (cmp == null) { return (Comparator<T>) ReverseComparator.REVERSE_ORDER; } else if (cmp == ReverseComparator.REVERSE_ORDER) { return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE; } else if (cmp == Comparators.NaturalOrderComparator.INSTANCE) { return (Comparator<T>) ReverseComparator.REVERSE_ORDER; } else if (cmp instanceof ReverseComparator2) { return ((ReverseComparator2<T>) cmp).cmp; } else { return new ReverseComparator2<>(cmp); } } /** * @serial include */ private static class ReverseComparator2<T> implements Comparator<T>, Serializable { private static final long serialVersionUID = 4374092139857L; /** * The comparator specified in the static factory. This will never * be null, as the static factory returns a ReverseComparator * instance if its argument is null. * * @serial */ final Comparator<T> cmp; ReverseComparator2(Comparator<T> cmp) { assert cmp != null; this.cmp = cmp; } public int compare(T t1, T t2) { return cmp.compare(t2, t1); } public boolean equals(Object o) { return (o == this) || (o instanceof ReverseComparator2 && cmp.equals(((ReverseComparator2)o).cmp)); } public int hashCode() { return cmp.hashCode() ^ Integer.MIN_VALUE; } @Override public Comparator<T> reversed() { return cmp; } } /** * Returns an enumeration over the specified collection. This provides * interoperability with legacy APIs that require an enumeration * as input. * * <p>The iterator returned from a call to {@link Enumeration#asIterator()} * does not support removal of elements from the specified collection. This * is necessary to avoid unintentionally increasing the capabilities of the * returned enumeration. * * @param <T> the class of the objects in the collection * @param c the collection for which an enumeration is to be returned. * @return an enumeration over the specified collection. * @see Enumeration */ public static <T> Enumeration<T> enumeration(final Collection<T> c) { return new Enumeration<T>() { private final Iterator<T> i = c.iterator(); public boolean hasMoreElements() { return i.hasNext(); } public T nextElement() { return i.next(); } }; } /** * Returns an array list containing the elements returned by the * specified enumeration in the order they are returned by the * enumeration. This method provides interoperability between * legacy APIs that return enumerations and new APIs that require * collections. * * @param <T> the class of the objects returned by the enumeration * @param e enumeration providing elements for the returned * array list * @return an array list containing the elements returned * by the specified enumeration. * @since 1.4 * @see Enumeration * @see ArrayList */ public static <T> ArrayList<T> list(Enumeration<T> e) { ArrayList<T> l = new ArrayList<>(); while (e.hasMoreElements()) l.add(e.nextElement()); return l; } /** * Returns true if the specified arguments are equal, or both null. * * NB: Do not replace with Object.equals until JDK-8015417 is resolved. */ static boolean eq(Object o1, Object o2) { return o1==null ? o2==null : o1.equals(o2); } /** * Returns the number of elements in the specified collection equal to the * specified object. More formally, returns the number of elements * {@code e} in the collection such that * {@code Objects.equals(o, e)}. * * @param c the collection in which to determine the frequency * of {@code o} * @param o the object whose frequency is to be determined * @return the number of elements in {@code c} equal to {@code o} * @throws NullPointerException if {@code c} is null * @since 1.5 */ public static int frequency(Collection<?> c, Object o) { int result = 0; if (o == null) { for (Object e : c) if (e == null) result++; } else { for (Object e : c) if (o.equals(e)) result++; } return result; } /** * Returns {@code true} if the two specified collections have no * elements in common. * * <p>Care must be exercised if this method is used on collections that * do not comply with the general contract for {@code Collection}. * Implementations may elect to iterate over either collection and test * for containment in the other collection (or to perform any equivalent * computation). If either collection uses a nonstandard equality test * (as does a {@link SortedSet} whose ordering is not <em>compatible with * equals</em>, or the key set of an {@link IdentityHashMap}), both * collections must use the same nonstandard equality test, or the * result of this method is undefined. * * <p>Care must also be exercised when using collections that have * restrictions on the elements that they may contain. Collection * implementations are allowed to throw exceptions for any operation * involving elements they deem ineligible. For absolute safety the * specified collections should contain only elements which are * eligible elements for both collections. * * <p>Note that it is permissible to pass the same collection in both * parameters, in which case the method will return {@code true} if and * only if the collection is empty. * * @param c1 a collection * @param c2 a collection * @return {@code true} if the two specified collections have no * elements in common. * @throws NullPointerException if either collection is {@code null}. * @throws NullPointerException if one collection contains a {@code null} * element and {@code null} is not an eligible element for the other collection. * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws ClassCastException if one collection contains an element that is * of a type which is ineligible for the other collection. * (<a href="Collection.html#optional-restrictions">optional</a>) * @since 1.5 */ public static boolean disjoint(Collection<?> c1, Collection<?> c2) { // The collection to be used for contains(). Preference is given to // the collection who's contains() has lower O() complexity. Collection<?> contains = c2; // The collection to be iterated. If the collections' contains() impl // are of different O() complexity, the collection with slower // contains() will be used for iteration. For collections who's // contains() are of the same complexity then best performance is // achieved by iterating the smaller collection. Collection<?> iterate = c1; // Performance optimization cases. The heuristics: // 1. Generally iterate over c1. // 2. If c1 is a Set then iterate over c2. // 3. If either collection is empty then result is always true. // 4. Iterate over the smaller Collection. if (c1 instanceof Set) { // Use c1 for contains as a Set's contains() is expected to perform // better than O(N/2) iterate = c2; contains = c1; } else if (!(c2 instanceof Set)) { // Both are mere Collections. Iterate over smaller collection. // Example: If c1 contains 3 elements and c2 contains 50 elements and // assuming contains() requires ceiling(N/2) comparisons then // checking for all c1 elements in c2 would require 75 comparisons // (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring // 100 comparisons (50 * ceiling(3/2)). int c1size = c1.size(); int c2size = c2.size(); if (c1size == 0 || c2size == 0) { // At least one collection is empty. Nothing will match. return true; } if (c1size > c2size) { iterate = c2; contains = c1; } } for (Object e : iterate) { if (contains.contains(e)) { // Found a common element. Collections are not disjoint. return false; } } // No common elements were found. return true; } /** * Adds all of the specified elements to the specified collection. * Elements to be added may be specified individually or as an array. * The behavior of this convenience method is identical to that of * {@code c.addAll(Arrays.asList(elements))}, but this method is likely * to run significantly faster under most implementations. * * <p>When elements are specified individually, this method provides a * convenient way to add a few elements to an existing collection: * <pre> * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon"); * </pre> * * @param <T> the class of the elements to add and of the collection * @param c the collection into which {@code elements} are to be inserted * @param elements the elements to insert into {@code c} * @return {@code true} if the collection changed as a result of the call * @throws UnsupportedOperationException if {@code c} does not support * the {@code add} operation * @throws NullPointerException if {@code elements} contains one or more * null values and {@code c} does not permit null elements, or * if {@code c} or {@code elements} are {@code null} * @throws IllegalArgumentException if some property of a value in * {@code elements} prevents it from being added to {@code c} * @see Collection#addAll(Collection) * @since 1.5 */ @SafeVarargs public static <T> boolean addAll(Collection<? super T> c, T... elements) { boolean result = false; for (T element : elements) result |= c.add(element); return result; } /** * Returns a set backed by the specified map. The resulting set displays * the same ordering, concurrency, and performance characteristics as the * backing map. In essence, this factory method provides a {@link Set} * implementation corresponding to any {@link Map} implementation. There * is no need to use this method on a {@link Map} implementation that * already has a corresponding {@link Set} implementation (such as {@link * HashMap} or {@link TreeMap}). * * <p>Each method invocation on the set returned by this method results in * exactly one method invocation on the backing map or its {@code keySet} * view, with one exception. The {@code addAll} method is implemented * as a sequence of {@code put} invocations on the backing map. * * <p>The specified map must be empty at the time this method is invoked, * and should not be accessed directly after this method returns. These * conditions are ensured if the map is created empty, passed directly * to this method, and no reference to the map is retained, as illustrated * in the following code fragment: * <pre> * Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap( * new WeakHashMap&lt;Object, Boolean&gt;()); * </pre> * * @param <E> the class of the map keys and of the objects in the * returned set * @param map the backing map * @return the set backed by the map * @throws IllegalArgumentException if {@code map} is not empty * @since 1.6 */ public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) { return new SetFromMap<>(map); } /** * @serial include */ private static class SetFromMap<E> extends AbstractSet<E> implements Set<E>, Serializable { private final Map<E, Boolean> m; // The backing map private transient Set<E> s; // Its keySet SetFromMap(Map<E, Boolean> map) { if (!map.isEmpty()) throw new IllegalArgumentException("Map is non-empty"); m = map; s = map.keySet(); } public void clear() { m.clear(); } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean contains(Object o) { return m.containsKey(o); } public boolean remove(Object o) { return m.remove(o) != null; } public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; } public Iterator<E> iterator() { return s.iterator(); } public Object[] toArray() { return s.toArray(); } public <T> T[] toArray(T[] a) { return s.toArray(a); } public String toString() { return s.toString(); } public int hashCode() { return s.hashCode(); } public boolean equals(Object o) { return o == this || s.equals(o); } public boolean containsAll(Collection<?> c) {return s.containsAll(c);} public boolean removeAll(Collection<?> c) {return s.removeAll(c);} public boolean retainAll(Collection<?> c) {return s.retainAll(c);} // addAll is the only inherited implementation // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) { s.forEach(action); } @Override public boolean removeIf(Predicate<? super E> filter) { return s.removeIf(filter); } @Override public Spliterator<E> spliterator() {return s.spliterator();} @Override public Stream<E> stream() {return s.stream();} @Override public Stream<E> parallelStream() {return s.parallelStream();} private static final long serialVersionUID = 2454657854757543876L; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); s = m.keySet(); } } /** * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo) * {@link Queue}. Method {@code add} is mapped to {@code push}, * {@code remove} is mapped to {@code pop} and so on. This * view can be useful when you would like to use a method * requiring a {@code Queue} but you need Lifo ordering. * * <p>Each method invocation on the queue returned by this method * results in exactly one method invocation on the backing deque, with * one exception. The {@link Queue#addAll addAll} method is * implemented as a sequence of {@link Deque#addFirst addFirst} * invocations on the backing deque. * * @param <T> the class of the objects in the deque * @param deque the deque * @return the queue * @since 1.6 */ public static <T> Queue<T> asLifoQueue(Deque<T> deque) { return new AsLIFOQueue<>(Objects.requireNonNull(deque)); } /** * @serial include */ static class AsLIFOQueue<E> extends AbstractQueue<E> implements Queue<E>, Serializable { private static final long serialVersionUID = 1802017725587941708L; private final Deque<E> q; AsLIFOQueue(Deque<E> q) { this.q = q; } public boolean add(E e) { q.addFirst(e); return true; } public boolean offer(E e) { return q.offerFirst(e); } public E poll() { return q.pollFirst(); } public E remove() { return q.removeFirst(); } public E peek() { return q.peekFirst(); } public E element() { return q.getFirst(); } public void clear() { q.clear(); } public int size() { return q.size(); } public boolean isEmpty() { return q.isEmpty(); } public boolean contains(Object o) { return q.contains(o); } public boolean remove(Object o) { return q.remove(o); } public Iterator<E> iterator() { return q.iterator(); } public Object[] toArray() { return q.toArray(); } public <T> T[] toArray(T[] a) { return q.toArray(a); } public <T> T[] toArray(IntFunction<T[]> f) { return q.toArray(f); } public String toString() { return q.toString(); } public boolean containsAll(Collection<?> c) { return q.containsAll(c); } public boolean removeAll(Collection<?> c) { return q.removeAll(c); } public boolean retainAll(Collection<?> c) { return q.retainAll(c); } // We use inherited addAll; forwarding addAll would be wrong // Override default methods in Collection @Override public void forEach(Consumer<? super E> action) {q.forEach(action);} @Override public boolean removeIf(Predicate<? super E> filter) { return q.removeIf(filter); } @Override public Spliterator<E> spliterator() {return q.spliterator();} @Override public Stream<E> stream() {return q.stream();} @Override public Stream<E> parallelStream() {return q.parallelStream();} } }
135ede5e4b2b48d23c1add825d13ccd1f854ecf6
eb97ee5d4f19d7bf028ae9a400642a8c644f8fe3
/tags/2011-12-23/seasar2-2.4.45/seasar2/s2-framework/src/main/java/org/seasar/framework/util/SerializeUtil.java
65e4e95b5a5ae6da2efbfc30686185427acf0e46
[ "Apache-2.0" ]
permissive
svn2github/s2container
54ca27cf0c1200a93e1cb88884eb8226a9be677d
625adc6c4e1396654a7297d00ec206c077a78696
refs/heads/master
2020-06-04T17:15:02.140847
2013-08-09T09:38:15
2013-08-09T09:38:15
10,850,644
0
1
null
null
null
null
UTF-8
Java
false
false
3,096
java
/* * Copyright 2004-2011 the Seasar Foundation and the Others. * * 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.seasar.framework.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.seasar.framework.exception.ClassNotFoundRuntimeException; import org.seasar.framework.exception.IORuntimeException; /** * オブジェクトをシリアライズするためのユーティリティです。 * * @author higa * */ public class SerializeUtil { private static final int BYTE_ARRAY_SIZE = 8 * 1024; /** * インスタンスを構築します。 */ protected SerializeUtil() { } /** * オブジェクトをシリアライズできるかテストします。 * * @param o * @return * @throws IORuntimeException * @throws ClassNotFoundRuntimeException */ public static Object serialize(final Object o) throws IORuntimeException, ClassNotFoundRuntimeException { byte[] binary = fromObjectToBinary(o); return fromBinaryToObject(binary); } /** * オブジェクトをbyteの配列に変換します。 * * @param o * @return */ public static byte[] fromObjectToBinary(Object o) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream( BYTE_ARRAY_SIZE); ObjectOutputStream oos = new ObjectOutputStream(baos); try { oos.writeObject(o); } finally { oos.close(); } return baos.toByteArray(); } catch (IOException ex) { throw new IORuntimeException(ex); } } /** * byteの配列をオブジェクトに変換します。 * * @param binary * @return */ public static Object fromBinaryToObject(byte[] binary) { try { ByteArrayInputStream bais = new ByteArrayInputStream(binary); ObjectInputStream ois = new ObjectInputStream(bais); try { return ois.readObject(); } finally { ois.close(); } } catch (IOException ex) { throw new IORuntimeException(ex); } catch (ClassNotFoundException ex) { throw new ClassNotFoundRuntimeException(ex); } } }
[ "koichik@319488c0-e101-0410-93bc-b5e51f62721a" ]
koichik@319488c0-e101-0410-93bc-b5e51f62721a
ec62ffd550e931dab3d8d27cbde7b113df0746ca
750186b94b8f631bf05a54000542e60be85ce127
/Scheme Interpreter/src/intermediate/Node.java
bf2330e2ec986d10b4886e35b2c7775ad8803bc7
[]
no_license
crrenteria/Scheme_Interpreter
70bae87962c0be0467bde01c1e747a0adb935eb1
b091aaa7e36d5aca94fe0fcc71b65e501ff4fb11
refs/heads/master
2020-05-29T09:07:57.748036
2014-04-17T06:59:32
2014-04-17T06:59:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
568
java
package intermediate; public class Node { String value; Node leftChild; Node rightChild; Node parent; public Node(String s) { value = s; leftChild = null; rightChild = null; parent = null; } public boolean hasLeftChild() { return (leftChild != null); } public boolean hasRightChild() { return (rightChild != null); } public String getValue() { return value; } public Node getParent() { return parent; } public Node getLeftChild() { return leftChild; } public Node getRightChild() { return rightChild; } }
690086d0e1d5a77136ccdfe379560559af8f588e
20c3000e7fe508533eaeb53d55c8b3d50abb10fa
/src/main/java/com/shaoyuanhu/chapter/one/t4/Run.java
4341e2cdf1dcf4dadfb8524e5a46aeeb9a7203ef
[]
no_license
shaoyuanhu/core-technology-of-java-multithread-programming
e23681356e33e79b15b51d32ba3b2717ab9b9997
df7b71acc25dcbf609ad2ac638849013a3d561a9
refs/heads/master
2021-05-10T17:00:00.434657
2018-01-30T06:26:45
2018-01-30T06:26:45
118,594,913
0
0
null
null
null
null
UTF-8
Java
false
false
879
java
package com.shaoyuanhu.chapter.one.t4; /** * @Author: ShaoYuanHu * @Description: 测试MyThread * @Date: Create in 2018-01-23 17:33 */ public class Run { public static void main(String[] args) { shardVariable(); } /** * 创建1个线程对象,将这个MyThread对象作为参数传递给五个Thread的构造,并分配不通的线程名称 * 因为只有一个MyThread对象,所以count变量对5个Thread线程是共享的 */ private static void shardVariable() { MyThread thread = new MyThread(); Thread a = new Thread(thread,"A"); Thread b = new Thread(thread,"B"); Thread c = new Thread(thread,"C"); Thread d = new Thread(thread,"D"); Thread e = new Thread(thread,"E"); a.start(); b.start(); c.start(); d.start(); e.start(); } }
61ef9338f5c9907db8207ffe52619e968d88fc61
1842bb0f3b60ed08b12def9159eb3033cf7283a3
/jmvp/src/main/java/com/soubw/jmvp/BaseUICallBackI.java
d6a63bf6bec3c1b48e12a9182043351f8521656e
[]
no_license
WX-JIN/JMvpDemo
1dd08ed908f396e75409e4866430df971e415c03
7230c297b4c7219beaf851b8375189bffde3928e
refs/heads/master
2020-04-06T07:10:29.895542
2016-08-27T08:02:51
2016-08-27T08:02:51
65,342,576
1
0
null
null
null
null
UTF-8
Java
false
false
1,098
java
package com.soubw.jmvp; import android.os.Handler; import android.os.Looper; /** * @author WX_JIN * @email [email protected] * @link http://soubw.com */ public abstract class BaseUICallBackI<T> implements BaseCallBackI<T> { private BaseViewI baseViewI; private Handler handler; public BaseUICallBackI(BaseViewI baseViewI) { this.baseViewI = baseViewI; handler = new Handler(Looper.getMainLooper()); } public void postUISuccess(final T t) { handler.post(new Runnable() { @Override public void run() { try { onSuccess(t); } catch (Exception e) { e.printStackTrace(); } } }); } public void postUIFail(final String msg) { handler.post(new Runnable() { @Override public void run() { try { onFail(msg); } catch (Exception e) { e.printStackTrace(); } } }); } }
397aff03c83d12d3c12f98358b081aa6de7f2c2f
2086231845095c5b789d718edd6e916d617d6fad
/HuJunMQ/src/demo05/Broker.java
df98e490ed36b818b2fcad5ecb7bcb6e0cb32afd
[ "MIT" ]
permissive
hujunchina/java-learning
86463d78f2b6c237c2789eaab4f312edccb1fd31
4051cf07f3c81e0b84953e182c4d6202050d8e50
refs/heads/master
2021-07-22T23:24:42.963504
2019-12-11T03:27:43
2019-12-11T03:27:43
224,174,966
0
0
MIT
2020-10-13T17:46:23
2019-11-26T11:23:27
Java
UTF-8
Java
false
false
3,688
java
package demo05; import java.io.IOException; import java.net.ServerSocket; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class Broker { private final static int MAX_SIZE = 100000; //保存消息的数据容器 protected final static BlockingQueue<byte[]> messageQueue = new ArrayBlockingQueue<byte[]>(MAX_SIZE); // 两个socket private ServerSocket publish_socket; private ServerSocket subscribe_socket; // 存储注册订阅者 public List<Topic> getTopicList() { return topicList; } public void setTopicList(List<Topic> topicList) { this.topicList = topicList; } // 存储主题和信息 private List<Topic> topicList = new ArrayList<Topic>(); private void log(String logs){ System.out.println("Broker: "+logs); } private static Set<String> topicName = new HashSet<String>(); private static Map<String, Topic> topicMap = new HashMap<String, Topic>(); public void publishSocket(){ try{ publish_socket = new ServerSocket(BrokerServer.PUBLISH_SERVICE_PORT); log("create publish socket server succeeded"); } catch (IOException e) { log("create publish socket failed"); e.printStackTrace(); } } public void subscribeSocket(){ try{ subscribe_socket = new ServerSocket(BrokerServer.SUBSCRIBE_SERVICE_PORT); log("create subscribe socket server succeeded"); } catch (IOException e) { log("create subscribe socket server failed"); e.printStackTrace(); } } // 保存消息,目前存储在内存中,后期持久化优化到文件中 public static void msgHandler(List<Topic> topics){ System.out.println("invoke"); for(Topic topic: topics){ TopicHandler.getTopics().add(topic.getTopic()); topicName.add(topic.getTopic()); System.out.println(topic.getTopic()); TopicHandler.addMap(topic.getTopic(), topic); topicMap.put(topic.getTopic(), topic); } } public static boolean hasTopic(String name){ if(topicName.contains(name)){ return true; }else{ return false; } } public static List<Topic> getTopicList(List<String> tnames){ List<Topic> rtTopic = null; for(String name : tnames){ if(hasTopic(name)){ Topic topic = topicMap.get(name); rtTopic.add(topic); } } return rtTopic; } public static Topic getTopic(String name){ return topicMap.get(name); } public static void setTopic(String name){ Topic topic = new Topic(); topic.setTopic(name); topicName.add(name); topicMap.put(name, topic); } // test run server public static void main(String[] args) { Broker broker = new Broker(); broker.publishSocket(); broker.subscribeSocket(); try{ while(true){ // 一个线程作为发布者socket server BrokerServer server = new BrokerServer(broker.publish_socket.accept()); new Thread(server).start(); // 另一个线程作为订阅者 socket server BrokerConsumer consumerServer = new BrokerConsumer(broker.subscribe_socket.accept()); new Thread(consumerServer).start(); } }catch (IOException e){ broker.log("socket server stopped"); e.printStackTrace(); } } }
[ "hujunchina@outlook" ]
hujunchina@outlook
34ce33475df5a5ca10d0e58db64baf8c1ea136dc
385142095beea3d06266a1895cb0266bc4ce236b
/src/main/java/com/groovybot/persistence/PMF.java
73a23bbbb57081c323d9f22dd52d92986fbde447
[ "Apache-2.0" ]
permissive
cretzel/groovybot
ac81d744d45797c5153ee8b1b7aa798fe073b4bd
47c46ccd7d1fbfd51d577a184dc71d83360c9602
refs/heads/master
2020-04-20T20:34:37.066372
2009-11-25T20:30:51
2009-11-25T20:30:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
546
java
package com.groovybot.persistence; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; public final class PMF { private static final PersistenceManagerFactory pmfInstance = JDOHelper .getPersistenceManagerFactory("transactions-optional"); private PMF() { } public static PersistenceManagerFactory get() { return pmfInstance; } public static PersistenceManager getPersistanceManager() { return get().getPersistenceManager(); } }
7d52f185a70f0a5d1a1e731848974a05635d9570
fc561a50cef3d4ac4bc9967160c71328e8677c83
/src/main/java/datastructures/trees/FindIfTreeisBST.java
64c942c81b2e3e6d2aadf8ff85d55d55d7770075
[]
no_license
Nemo24/algorithms
9108169dcf0712c7caf99892af143ce498d91c4d
3e67760fcaae5ea3bd267bd70f55cf9f739c731e
refs/heads/master
2021-01-17T09:14:02.183835
2019-09-29T10:09:41
2019-09-29T10:09:41
62,985,651
0
0
null
null
null
null
UTF-8
Java
false
false
2,064
java
package datastructures.trees; /** * Created by mm on 1/3/16. */ public class FindIfTreeisBST { int prev = Integer.MIN_VALUE; public boolean isBSTWrongApproach(BinaryTree tree){ if (tree == null) return false; return isBSTWrongApproach(tree.root); } private boolean isBSTWrongApproach(BinaryTreeNode root){ if (root == null) return true; if ((root.getLeft()!=null) && (root.getLeft().getData() > root.getData())) return false; if ((root.getRight()!=null) && (root.getRight().getData() < root.getData())) return false; return isBSTWrongApproach(root.getLeft()) && isBSTWrongApproach(root.getRight()); } public boolean isBST(BinaryTree tree){ if (tree == null) return false; prev = Integer.MIN_VALUE; return isBST(tree.root); } private boolean isBST(BinaryTreeNode root){ if (root == null) return true; boolean leftIsTrue = isBST(root.getLeft()); if (!leftIsTrue) return false; if (root.getData() < prev) return false; prev = root.getData(); return isBST(root.getRight()); } public static void main(String[] args) { BinaryTree tree1 = BinaryTreeCreatorHelper.getBinarySearchTreeWrong(); BinaryTree tree2 = BinaryTreeCreatorHelper.getBinarySearchTreeCorrect(); BinaryTree tree3 = BinaryTreeCreatorHelper.getBinarySearchTreeVeryWrong(); FindIfTreeisBST mm = new FindIfTreeisBST(); System.out.println("wrong approach"); System.out.println(mm.isBSTWrongApproach(tree1) + ":this should be false"); System.out.println(mm.isBSTWrongApproach(tree2) + ":this could be true"); System.out.println(mm.isBSTWrongApproach(tree3) + ":this should be false"); System.out.println(); System.out.println("right approach"); System.out.println(mm.isBST(tree1) + ":this should be false"); System.out.println(mm.isBST(tree2) + ":this could be true"); System.out.println(mm.isBST(tree3) + ":this should be false"); } }
16705f1a835242424dfe879d4c3e5125900c8743
91feacfea6bbcadd634dde42681dbba317e31f75
/src/main/java/com/creditharmony/fortune/utils/FileUtil.java
1d6314bf711d732406a67f7a0a3696202811b1e9
[]
no_license
sengeiou/chp-fortune
0d5ccc9b40568a622fa162dc609bd4ccfc358a9f
ac676cb5d8502269d2d44bf395206034f26b4e49
refs/heads/master
2020-05-16T02:53:13.475287
2017-07-06T07:31:26
2017-07-06T07:31:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
16,367
java
package com.creditharmony.fortune.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLConnection; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.FileCopyUtils; import org.springframework.web.multipart.MultipartFile; import com.creditharmony.common.util.FileUtils; import com.creditharmony.core.config.Global; import com.creditharmony.core.excel.util.ExportExcel; import com.creditharmony.core.fortune.type.ReportType; import com.creditharmony.core.users.util.UserUtils; import com.creditharmony.dm.bean.DocumentBean; import com.creditharmony.dm.file.util.Zip; import com.creditharmony.dm.service.DmService; import com.creditharmony.fortune.common.FileManagement; import com.creditharmony.fortune.common.ThreadPool; import com.creditharmony.fortune.common.entity.Attachment; import com.creditharmony.fortune.deduct.common.Constant; import com.creditharmony.fortune.deduct.service.DocumentSynthesis; import com.google.common.collect.Lists; /** * 文件操作工具类 * @Class Name FileUtil * @author zhujie * @Create In 2015年11月27日 */ public class FileUtil { /** * 日志对象 */ protected static Logger logger = LoggerFactory.getLogger(FileUtil.class); /** * 保存文件 * * @param file * 上传的文件 * @param fileType * 上传的文件类型 * @return Attachment:文件名,新文件名,存放根路径 * @throws IOException * @throws IllegalStateException */ public static Attachment saveFiles(MultipartFile file,String customerFile) throws IllegalStateException, IOException { Attachment attachment = FileUtil.saveFiles(file, customerFile, "tmp"); return attachment; } /** * 保存文件 * * @param file * 上传的文件 * @param fileType * 上传的文件类型 * @return Attachment:文件名,新文件名,存放根路径 * @throws IOException * @throws IllegalStateException */ public static Attachment saveFiles(MultipartFile file,String customerFile, String subFile) throws IllegalStateException, IOException { // 返回值,记录文件的原文件名和新文件名 Attachment savedFile = new Attachment(); // 上传文件名 String fileName = file.getOriginalFilename(); InputStream is = file.getInputStream(); savedFile.setAttaFilename(fileName);// 文件名 savedFile.setAttaNewfilename(fileName);// 新文件名 try { DocumentBean docbean = null; String user = UserUtils.getUserId(); DmService dmService = DmService.getInstance(); docbean = dmService.createDocument(fileName,is , DmService.BUSI_TYPE_FORTUNE, customerFile, subFile,user ); savedFile.setAttaFilepath(docbean.getDocId());// 存放根路径 } catch(RuntimeException e){ logger.error("[Fortune---->FileUtil:saveFiles()] exception: "+e.getMessage()); } catch (Exception e1) { e1.printStackTrace(); return savedFile; } return savedFile; } /** * * 2016年2月24日 * By 刘雄武 * @param response * @param seletive * @param type */ public static void fileDownloadby(HttpServletResponse response,Attachment seletive,String type) { // 根据附件ID检索附件信息 logger.info("fileDownload文件下载......"); DmService dmService = DmService.getInstance(); OutputStream os; try { response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + new String( seletive.getAttaFilename().getBytes("gb2312"), "ISO8859-1" ) +"\"")); os = response.getOutputStream(); dmService.download(os, seletive.getAttaFilepath()); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 从网盘读取并下载 * 2016年5月16日 * By 周俊 * @param response * @param strZipPath * @param strZipname */ public static void downFileToNetdisk(HttpServletResponse response, String filePath,String fileName) { try { // 放到缓冲流里面 InputStream ins = new FileInputStream(filePath); BufferedInputStream bins = new BufferedInputStream(ins); // 获取文件输出IO流 OutputStream outs = response.getOutputStream(); BufferedOutputStream bouts = new BufferedOutputStream(outs); // 设置response内容的类型 response.setContentType("application/x-msdownload"); // 设置头部信息 response.setHeader("Content-disposition","attachment;filename="+ new String( fileName.getBytes("GBK"), "ISO8859-1" )); int bytesRead = 0; byte[] buffer = new byte[1024]; // 开始向网络传输文件流 while ((bytesRead = bins.read(buffer, 0, 1024)) != -1) { bouts.write(buffer, 0, bytesRead); } //调用flush()方法 bouts.flush(); ins.close(); bins.close(); outs.close(); bouts.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 文件下载 * 2015年12月9日 * By 韩龙 * @param response * @param seletive Attachment实体类 * @param type 预览:preview 下载:download */ public static void fileDownload(HttpServletResponse response,Attachment seletive,String type) { // 根据附件ID检索附件信息 logger.info("fileDownload文件下载......"); File file = null; file = new File(FileUtils.path(Global.getConfig("uploadFilePath")+ "/" + seletive.getAttaFilepath())); if(!file.exists()){ String errorMessage; if(type.equalsIgnoreCase("preview")){ logger.info("没有文件预览"); errorMessage = "没有文件预览"; }else{ logger.info("没有文件下载"); errorMessage = "没有文件下载"; } try { // 文字回写 OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-16"))); outputStream.flush(); outputStream.close(); } catch (IOException e) { logger.error("文件读定错误"+e.getLocalizedMessage(),e); } return; } // 确定下载文件类型 String mimeType= URLConnection.guessContentTypeFromName(file.getName()); if(mimeType==null){ // 默认类型 mimeType = "application/octet-stream"; } response.setContentType(mimeType); if(type.equalsIgnoreCase("preview")){ // 预览模式 response.setHeader("Content-Disposition", String.format("inline; filename=\"" + seletive.getAttaFilename() +"\"")); }else{ // 其他模式:下载 response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + seletive.getAttaFilename() +"\"")); } response.setContentLength((int)file.length()); try { InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); // 文件转换成数据流输出,最后关闭输入,输出数据流 FileCopyUtils.copy(inputStream, response.getOutputStream()); } catch (IOException e) { logger.error("文件转换数据流出错"+e.getLocalizedMessage(),e); } } /** * 导出excel * 2015年12月9日 * By 韩龙 * @param dataList 导出数据列表 * @param cla 导出模板实体类 * @param fileName 导出文件名字 * @param response */ public static void exportExcel(List<?> dataList, Class<?> cla, String fileName, HttpServletResponse response) { // 构建导出excel对象 ExportExcel exportExcel = new ExportExcel(null, cla); // 设置导出数据源 exportExcel.setDataList(dataList); try { logger.info("写出文件到客户端" + fileName + ".xlsx"); // 写出文件到客户端 exportExcel.write(response, fileName + ".xlsx"); exportExcel.dispose(); } catch (IOException e) { e.printStackTrace(); logger.error("列表导出失败", e); } } /** * 批量下载文件zip * 2015年12月9日 * By 韩龙 * @param subs 文件列表 * @param fileName Global.USERFILES_BASE_URL路径 * @param type 文件类型 * @param response */ public static void zipFileDownload(File[] subs, String fileName,HttpServletResponse response){ ZipOutputStream zos=null; FileInputStream fis=null; try { // 设置Header信息 response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", "attachment; filename=" + getZipFilename(fileName) + ";filename*=UTF-8''" + getZipFilename(fileName)); zos = new ZipOutputStream(response.getOutputStream()); // 遍历文件 for (int i=0;i<subs.length;i++) { File f=subs[i]; try { zos.putNextEntry(new ZipEntry(f.getName())); fis = new FileInputStream(f); byte[] buffer = new byte[1024]; int r = 0; while ((r = fis.read(buffer)) != -1) { zos.write(buffer, 0, r); } fis.close(); } catch (IOException e) { logger.error("压缩文件"+f.getName()+"错误:"+e.getLocalizedMessage(),e); } } zos.flush(); zos.close(); } catch (IOException e1) { logger.error("压缩文件错误:"+e1.getLocalizedMessage(),e1); } } /** * 批量从文件服务器下载zip文件 * 2015年12月29日 * By 韩龙 * @param fileName * @param response * @param listAttachment */ public static void zipFileDownload(String fileName,HttpServletResponse response,List<Attachment> listAttachment){ OutputStream os = null; // 封装 List<String> docIds = Lists.newArrayList(); List<Attachment> docIdFiles = Lists.newArrayList(); for (Attachment a : listAttachment) { // 斜杠开头的是chp2.0的数据, if(a.getAttaFilepath().startsWith("/")){ docIdFiles.add(a); }else{ docIds.add(a.getAttaFilepath()); } } try { // response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + seletive.getAttaFilename() +"\"")); // 设置Header信息 // response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=" + getZipFilename(fileName) + ";filename*=UTF-8''" + getZipFilename(fileName)); os = response.getOutputStream(); Map<String,InputStream> map = new HashMap<String,InputStream>(); Map<String,InputStream> fileMap = new HashMap<String,InputStream>(); // 2.0文件是从网盘上下载 if(docIdFiles != null && docIdFiles.size() > 0){ for (Attachment attachment : docIdFiles) { // 放到缓冲流里面 InputStream ins = new FileInputStream(attachment.getAttaFilepath() + "."+attachment.getAttaFileType()); fileMap.put(attachment.getAttaNewfilename(), ins); } } if(docIds != null && docIds.size() > 0){ DmService dmService = DmService.getInstance(); // dmService.download(os, docIds); map = dmService.downloadDocuments(docIds); } map.putAll(fileMap); Zip.zipFiles(os, map); } catch (IOException e1) { logger.error("压缩文件错误:"+e1.getLocalizedMessage(),e1); }finally{ // 关闭流 // try { // os.flush(); // os.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } } /** * 下载压缩包文件名 * 2015年12月10日 * By 韩龙 * @return * @throws UnsupportedEncodingException */ private static String getZipFilename(String baseName) throws UnsupportedEncodingException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd_HH-mm-dd"); Date date = new Date(); String s = baseName +"_"+ sdf.format(date) + ".zip"; return java.net.URLEncoder.encode(s, "utf-8"); } /** * 合成文件 * 2016年1月11日 * By 韩龙 * @param filters * Map key:templateName模板名称 * :parameter 需要参数 * :lendCode 出借编号 * :attaTableId 所属表ID * :attaFlag 文件标识(cjxy:出借合同;bg:变更申请;zr:赎回申请;hkxy:委托划扣;zrsq:债权转让等等) * :attaFileOwner 所属表表名[可选] * :fileName 文件名[可选] * @return * @throws IOException */ public static int compositeFile(Map<String, Object> filters){ int result = 0; String makeFileName = filters.get("fileName")==null?"1":filters.get("fileName").toString(); String httpUrl = Constant.getProperties.get("template_cpt_url"); String signType = filters.get("signType")==null?"":filters.get("signType").toString(); // 获取参数模板Url if(filters.get("templateName") !=null ){ String fileName = Constant.getProperties.get(filters.get("templateName")); httpUrl = httpUrl.replace("reportlet=", "reportlet="+fileName); }else{ // 默认值:收款确认书 String fileName = Constant.getProperties.get(ReportType.SKQRS_HK.getCode()); httpUrl = httpUrl.replace("reportlet=", "reportlet="+fileName); } // 获取每个模板需要的参数,并拼接 String parameter = (String) (filters.get("parameter")==null ? "":filters.get("parameter")); httpUrl = httpUrl +"&"+parameter; //文件类型 String[] flieTypes; if(StringUtils.isNotBlank(StringExUtil.getTrimString(filters.get("flieType")))){ flieTypes = new String[]{filters.get("flieType").toString()}; }else{ // 获取配置要生成文件类型 flieTypes = Constant.getProperties.get("file_type").split(","); } ThreadPool threadPool =ThreadPool.getInstance(); List<Attachment> attachmentLst = new ArrayList<Attachment>(); List<HashMap<String, String>> rehttpList = new ArrayList<HashMap<String, String>>(); for (String flieType : flieTypes) { String rehttpUrl =""; // 获取线程池 String fileName = makeFileName + "." + flieType; Attachment attachment = new Attachment(); attachment.preInsert(); attachment.setAttaId(attachment.getId()); attachment.setAttaFilename(fileName); attachment.setAttaNewfilename(fileName); //出借编号或者客户编号,都存在此字段 attachment.setLoanCode(StringExUtil.getTrimString(filters.get("lendCode"))); attachment.setAttaFileType(flieType); attachment.setDictAttaFlag(StringExUtil.getTrimString(filters.get("attaFlag"))); attachment.setAttaTableId(StringExUtil.getTrimString(filters.get("attaTableId"))); attachment.setAttaFileOwner(StringExUtil.getTrimString(filters.get("attaFileOwner"))); //attachment.setFrom(StringExUtil.getTrimString(filters.get("from"))); attachment.setCreateTime(new Date()); attachment.setCreateBy(UserUtils.getUserId()); String reType = flieType; if(reType.equals("pdf")){ if(filters.containsKey("sendFlag") && filters.get("sendFlag").equals(com.creditharmony.fortune.creditor.matching.constant.Constant.SEND_FLAG_YES)){ attachment.setSendFlag(com.creditharmony.fortune.creditor.matching.constant.Constant.SEND_FLAG_YES); attachment.setTemplateType(filters.get("templateType").toString()); } } if(reType.equals("doc")){ reType = "word"; } attachmentLst.add(attachment); rehttpUrl = httpUrl + "&format="+reType; HashMap<String, String> fileParam = new HashMap<String, String>(); fileParam.put("rehttpUrl", rehttpUrl); fileParam.put("fileName", fileName); rehttpList.add(fileParam); result++; } // 文件合成用, Attachment discardAttachment = filters.get("attachment")==null ? null : (Attachment)filters.get("attachment"); // 放入线程 FileManagement fileManagement = new FileManagement(); DocumentSynthesis DocumentSynthesis = new DocumentSynthesis(attachmentLst,StringExUtil.getTrimString(filters.get("attaTableId")),discardAttachment,StringExUtil.getTrimString(filters.get("from")) ); fileManagement.before(rehttpList,signType,null,filters.get("customerCode").toString(),filters.get("lendCode").toString(), DocumentSynthesis); threadPool.addTask(fileManagement); return result; } }
a4be61fe13a0140b258afb6bc1b8c646ccdad255
dcf8f9283093f16e79686d083f4496d1e7ae24d1
/build/dist/jpaint/src/main/java/model/persistence/ApplicationState.java
b1ea1b529671edd5f4112f09b71bfb7e95260031
[]
no_license
sljiang93/jpaint
85f41b409003a4ca832a7f29a05a9117f244afe8
113d49f7761eef5e97999b03a685a131005ea50b
refs/heads/master
2023-07-10T19:27:08.387068
2021-08-22T21:14:09
2021-08-22T21:14:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,500
java
package model.persistence; import model.*; import model.dialogs.DialogProvider; import model.interfaces.IApplicationState; import model.interfaces.IDialogProvider; import view.interfaces.IUiModule; import java.awt.Point; import java.io.Serializable; import controller.MouseClick; public class ApplicationState implements IApplicationState, Serializable { //private static final long serialVersionUID = -5545483996576839007L; private final IUiModule uiModule; private final IDialogProvider dialogProvider; private ShapeType activeShapeType; private ShapeColor activePrimaryColor; private ShapeColor activeSecondaryColor; private ShapeShadingType activeShapeShadingType; private StartAndEndPointMode activeStartAndEndPointMode; private Point startPoint; private Point endPoint; public ApplicationState(IUiModule uiModule) { this.uiModule = uiModule; this.dialogProvider = new DialogProvider(this); setDefaults(); } @Override public void setActiveShape() { activeShapeType = uiModule.getDialogResponse(dialogProvider.getChooseShapeDialog()); } @Override public void setActivePrimaryColor() { activePrimaryColor = uiModule.getDialogResponse(dialogProvider.getChoosePrimaryColorDialog()); } @Override public void setActiveSecondaryColor() { activeSecondaryColor = uiModule.getDialogResponse(dialogProvider.getChooseSecondaryColorDialog()); } @Override public void setActiveShadingType() { activeShapeShadingType = uiModule.getDialogResponse(dialogProvider.getChooseShadingTypeDialog()); } @Override public void setActiveStartAndEndPointMode() { activeStartAndEndPointMode = uiModule.getDialogResponse(dialogProvider.getChooseStartAndEndPointModeDialog()); } @Override public void CopyCommand() { } /*@Override public void DeleteCommand() { } @Override public void PasteCommand() { }*/ @Override public void UndoCommand() { } @Override public void RedoCommand() { } @Override public ShapeType getActiveShapeType() { return activeShapeType; } @Override public ShapeColor getActivePrimaryColor() { return activePrimaryColor; } @Override public ShapeColor getActiveSecondaryColor() { return activeSecondaryColor; } @Override public ShapeShadingType getActiveShapeShadingType() { return activeShapeShadingType; } @Override public StartAndEndPointMode getActiveStartAndEndPointMode() { return activeStartAndEndPointMode; } public Point getStartPoint(){ return startPoint; } public Point getEndPoint(){ return endPoint; } public Point getAdjustedStart(){ double startX = Math.min(startPoint.getX(), endPoint.getX()); double startY = Math.min(startPoint.getY(), endPoint.getY()); return new Point(); } public Point getAdjustedEnd(){ double endX = Math.max(startPoint.getX(), endPoint.getX()); double endY = Math.max(startPoint.getY(), endPoint.getY()); return new Point(); } private void setDefaults() { activeShapeType = ShapeType.ELLIPSE; activePrimaryColor = ShapeColor.BLUE; activeSecondaryColor = ShapeColor.GREEN; activeShapeShadingType = ShapeShadingType.FILLED_IN; activeStartAndEndPointMode = StartAndEndPointMode.DRAW; } }
1f4632402d0da0ce2123d4d84623ee7cc3aae24a
529149c9cb2135f3bc81874b753bd2c12d5a589b
/src/org/openrdf/query/algebra/evaluation/function/postgis/geometry/attribute/IsRectangle.java
2c88c00461c708520149cd9e5ed75592308d23c4
[ "Apache-2.0" ]
permissive
i3mainz/kiwi-postgis
5ce7a6794267e03044bcbda2d50e7c9ecc4c50bf
8b287fd3424c53892f945a7db21b590811bf20d4
refs/heads/master
2021-07-05T15:30:08.983530
2020-11-03T20:49:45
2020-11-03T20:49:45
200,048,925
1
0
null
null
null
null
UTF-8
Java
false
false
546
java
package org.openrdf.query.algebra.evaluation.function.postgis.geometry.attribute; import org.openrdf.model.vocabulary.POSTGIS; import org.locationtech.jts.geom.Geometry; import org.openrdf.query.algebra.evaluation.function.postgis.geometry.base.GeometricBinaryAttributeFunction; public class IsRectangle extends GeometricBinaryAttributeFunction { @Override public String getURI() { return POSTGIS.st_isRectangle.stringValue(); } @Override public boolean attribute(Geometry geom) { return geom.isRectangle(); } }
d10c850c934b662ccd37a278fac08f177df62700
f4051f7e6e36dfced76a5d53ad24e8b69902adf4
/health_parent/health_common/src/main/java/com/cwj/health/constant/RedisMessageConstant.java
834b2b14e54bd6168614266af74cab66c656b33a
[]
no_license
cwj584062461/health102
36ad0daff7473ec59e4c84caa0a34c8b01fbab60
5a48e47709a1923b6f90d9b9e2da8ee85a9c4ab3
refs/heads/master
2023-01-05T15:53:48.024084
2020-11-03T15:30:26
2020-11-03T15:30:26
306,558,916
0
0
null
null
null
null
UTF-8
Java
false
false
370
java
package com.cwj.health.constant; public interface RedisMessageConstant { static final String SENDTYPE_ORDER = "001";//用于缓存体检预约时发送的验证码 static final String SENDTYPE_LOGIN = "002";//用于缓存手机号快速登录时发送的验证码 static final String SENDTYPE_GETPWD = "003";//用于缓存找回密码时发送的验证码 }
e3bb6b46bc4068d76d188ad08e3b3dd2bfaf0680
09f245c2fe54c1d21230e5f95136f140cca19552
/app/src/test/java/com/example/lesson6ps/ExampleUnitTest.java
57f3a67a1970d5ff59bdfc61f186ed4fb4697bfd
[]
no_license
cheerful4ever/lesson6Ps
d9619ddf8b1b0065ab6de9a1e4e93cac6d16fbaa
59397d8962714ac0831ae1689fe1737cdf65d2c1
refs/heads/master
2022-09-22T19:41:06.381825
2020-05-28T15:28:14
2020-05-28T15:28:14
267,531,492
0
0
null
null
null
null
UTF-8
Java
false
false
382
java
package com.example.lesson6ps; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
4c020cca0df8a2988ab0614639dcef967e8dcc94
802801a14aa6a3059e4a870458bbf7d9531a89a3
/src/test/java/thread/Animal/Tortoise.java
336987a4f2ef8d5d71fbf4f4485bf7e80b9b240c
[]
no_license
myselfmjs/com-book-web
0fc629858a1a17ef80ab945428bae6e50222f04e
949d19a4f472e62b0b50b6c02d15aa89840ec8b9
refs/heads/master
2021-01-19T02:27:10.171257
2018-12-14T08:07:50
2018-12-14T08:07:50
84,404,031
0
0
null
null
null
null
UTF-8
Java
false
false
904
java
package thread.Animal; /** * @Author: majunsheng * @Date: 2018/4/9 **/ public class Tortoise extends Animal { public Tortoise() { setName("乌龟");// Thread的方法,给线程赋值名字 } // 重写running方法,编写乌龟的奔跑操作 @Override public void runing() { // 跑的距离 double dis = 0.1; length -= dis; if (length <= 0) { length = 0; System.out.println("乌龟获得了胜利"); // 让兔子不要在跑了 if (calltoback != null) { calltoback.win(); } }else{ System.out.println("乌龟跑了" + dis + "米,距离终点还有" + (double)Math.round(length*100)/100 + "米"); } try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }
c531c899f34721d1fc4c3b875ca7fcaef97eeb3c
ef695a2d7ec188fd0f237b7647ac3c2c319ab9d2
/app/src/main/java/com/academy/shoplist/data/SingletonShopList.java
f9378aac35bc76339129541fcd5c65e27c106ef7
[]
no_license
JheromeSamson/Shoplist
0d50810a2ce9e9856089847f7b476c001aa9d435
369e25f30752a738bb27b6e62b2659b70b54ec5c
refs/heads/master
2021-03-25T22:14:22.979792
2020-04-02T15:07:38
2020-04-02T15:07:38
247,649,528
1
0
null
null
null
null
UTF-8
Java
false
false
953
java
package com.academy.shoplist.data; import com.academy.shoplist.bean.Prodotto; import java.util.ArrayList; public class SingletonShopList { public ArrayList<Prodotto> prodotto = new ArrayList<>(); private static SingletonShopList instance; public SingletonShopList(){} public static synchronized SingletonShopList getInstance() { if (instance == null){ synchronized (SingletonShopList.class){ if (instance == null) instance = new SingletonShopList(); } } return instance; } public void setProdotto(Prodotto prodotto) { this.prodotto.add(prodotto); } public Prodotto getProdottoByPosition(int position){ return prodotto.get(position); } public void removeProdotto(int position){ this.prodotto.remove(position); } public void setEdit(String toString, String toString1, int position) { } }
b65465a640c0515529298beabc3311290df9cd4d
014986fe5cb02a9b84a395d1125aa83e7f384206
/src/main/java/app/bank/service/TestService.java
f664eaedea63d07a865580d934860ee8e55df733
[]
no_license
wysockikacper98/backend-bank
92a44b721941e25e789cd698d028458ed17fe7b5
4cda8841f60e4fe02219a3c8e029dc46ac7832d2
refs/heads/master
2023-02-27T08:45:35.636272
2021-02-01T13:43:06
2021-02-01T13:43:06
330,437,151
0
0
null
null
null
null
UTF-8
Java
false
false
1,779
java
package app.bank.service; import app.bank.dto.DataFromServer; import app.bank.dto.HerokuSendPayments; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.math.BigDecimal; import java.util.Arrays; @Service public class TestService { public void getDataTest() { RestTemplate restTemplate = new RestTemplate(); String fooResourceURL = "https://jednroz.herokuapp.com/get?id=12121212"; ResponseEntity<DataFromServer[]> response = restTemplate.getForEntity(fooResourceURL, DataFromServer[].class); DataFromServer[] data = response.getBody(); Arrays.stream(data).forEach(temp -> System.out.println(temp.getBankno())); if (response.getStatusCode() == HttpStatus.OK) { System.out.println("OK"); } } //TODO: Nie działa 503 Service Unavailable public void postDataTest() { String fooResourceUrl = "https://jednroz.herokuapp.com/send"; RestTemplate restTemplate = new RestTemplate(); HttpEntity<HerokuSendPayments> request = new HttpEntity<>(new HerokuSendPayments( BigDecimal.valueOf(66.00), "11 1111 1111 1111 1111 1111 1111", "Debited Test Address", "22 1212 1212 2222 2222 2222 2222", "Credited test Address", BigDecimal.valueOf(65.23), "Pierszy testowy przelew")); System.out.println("Przed heroku"); String heroku = restTemplate.postForObject(fooResourceUrl, request, String.class); System.out.println(heroku); } }
1b0cbdc5cb25a7d2b66b94147eae26dd0f49450e
520ad8116be1df8b1f900afc631bc78c7f442482
/course/src/util/Calculator.java
add85605b2862f6ffeed7bce4019931f2546c31a
[]
no_license
igorney/javacourse
21a50d36874b6321ab31b87367cf5b87b981a5b7
4fefc4b3e58143fd6abf0ad691c4603f16aefd49
refs/heads/master
2021-05-21T17:08:34.192638
2020-04-29T03:37:51
2020-04-29T03:37:51
252,729,740
1
0
null
null
null
null
UTF-8
Java
false
false
250
java
package util; public class Calculator { public static final double PI = 3.14139; public static double circunference(double radius) { return 2*PI*radius; } public static double volume(double radius) { return 4*PI*radius*radius*radius/3; } }
6e24dfead9ad7e5d1b7a233a1c4fc54b946153e0
652efc4cdd206b77c5d5dccbdabd290a408a3ddd
/app/src/main/java/app/sunshine/juanjo/views/MyView.java
9800b650e744667be175ad0b671305acfea015d3
[ "Apache-2.0" ]
permissive
sasij/Weather-app
fb7658df9fe39d242330dfce61863d105e2e3b1a
cf03a6d8f7df47b7c31f68eda32a77fb9c9d6c8a
refs/heads/master
2016-09-06T17:43:20.293786
2015-02-01T15:57:26
2015-02-01T15:57:26
22,812,616
0
0
null
null
null
null
UTF-8
Java
false
false
530
java
package app.sunshine.juanjo.views; import android.content.Context; import android.util.AttributeSet; import android.view.View; /** * Created by juanjo on 28/08/14. */ public class MyView extends View { public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defaultStyle) { super(context, attrs, defaultStyle); } protected void onMeasure(int wMeasureSpec, int hMeasureSpec) { } }
9009f72daf419bc21eef09ed8b76a717eb2d10e8
ed9138bc0d1291163a386124fa467d52e0fb7f3f
/Pos2Books/src/se/budohoor/economics/pos2books/plugins/books/economic/types/CashBookGetData.java
1ba2885195c1e2ee7ae0c5194d4bf44cb659ec60
[]
no_license
odie37/pos-2-books
56a06439e9e072d8bea2e747d65ef3dad3349709
cbec64fef1d7abb48d948b3adc2f8be36e09cf19
refs/heads/master
2016-09-10T10:37:04.105489
2015-01-04T19:11:32
2015-01-04T19:11:32
28,779,078
0
0
null
null
null
null
UTF-8
Java
false
false
1,522
java
package se.budohoor.economics.pos2books.plugins.books.economic.types; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entityHandle" type="{http://e-conomic.com}CashBookHandle" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "entityHandle" }) @XmlRootElement(name = "CashBook_GetData") public class CashBookGetData { protected CashBookHandle entityHandle; /** * Gets the value of the entityHandle property. * * @return * possible object is * {@link CashBookHandle } * */ public CashBookHandle getEntityHandle() { return entityHandle; } /** * Sets the value of the entityHandle property. * * @param value * allowed object is * {@link CashBookHandle } * */ public void setEntityHandle(CashBookHandle value) { this.entityHandle = value; } }
a78c18cd3e92eeecb8f8218661c82408bc61b899
4877a49854457aa2495d470a5a0f38e4ba9a07d0
/src/main/java/com/restaurant/client/feign/MealFallback.java
52acdf02c3dc671ca3fbc7998ad474372d9afce9
[]
no_license
TulyakovYasha/restaurantclient
f5ae82fad34568759beb1fdc942bc4d211c1bc64
2c2200115608bfdea2122d0c09dac9fedfdbaa92
refs/heads/master
2020-08-20T02:14:39.929457
2019-10-18T08:17:01
2019-10-18T08:17:01
215,975,028
1
0
null
null
null
null
UTF-8
Java
false
false
614
java
package com.restaurant.client.feign; import api.dto.MealDTO; import com.restaurant.client.feign.client.RestaurantFeignClient; import org.springframework.stereotype.Component; @Component public class MealFallback implements RestaurantFeignClient { @Override public MealDTO save(MealDTO mealDTO) { return new MealDTO(); } @Override public MealDTO update(MealDTO mealDTO) { return new MealDTO(); } @Override public MealDTO get(String uuid) { return new MealDTO(); } @Override public boolean delete(String uuid) { return false; } }
48c705f3b57973821d1920eccd44f17b432389be
b17e8b87a21877e2c0208065b0303de7cbec4a04
/OOPC/2102 Examples/dec01/BoxingTimingExample.java
43d642c09a4b93963728bc54ba2b7f7aa6eb3f01
[]
no_license
jaithakai91/egreer-wpi
63b799c7fc54cd638c35b8086d6cc71beb37e8f9
628122efb2b717c3906cafffdd1ba0f9ecea3136
refs/heads/master
2023-04-18T14:31:35.452030
2011-03-06T06:31:39
2011-03-06T06:31:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,014
java
package dec01; /** * Show timing issues for boxing/unboxing * * @author heineman */ public class BoxingTimingExample { /** * @param args */ public static void main(String[] args) { // What is the only visible difference here? Integer x, y; int a, b; long start, end; start = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { a = 99; b = 137; a = a + b; } end = System.currentTimeMillis(); System.out.println ("Time required for int arithmetic: " + (end - start)); // Is there any reason why it is 20x slower? Yes! start = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { x = 99; // equivalent to x = new Integer(99); y = 137; // equivalent to y = new Integer(137); x = x + y; // equivalent to x = new Integer (x.intValue() + y.intValue()); } end = System.currentTimeMillis(); System.out.println ("Time required for Integer arithmetic: " + (end - start)); } }
443e5038db77d85d0780fbc210dacbd7a0bee40b
95e944448000c08dd3d6915abb468767c9f29d3c
/sources/com/p280ss/android/ugc/aweme/i18n/language/initial/C30486f.java
23a8f4f5b41234c3225695b3e82dbbad796f4bdf
[]
no_license
xrealm/tiktok-src
261b1faaf7b39d64bb7cb4106dc1a35963bd6868
90f305b5f981d39cfb313d75ab231326c9fca597
refs/heads/master
2022-11-12T06:43:07.401661
2020-07-04T20:21:12
2020-07-04T20:21:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
715
java
package com.p280ss.android.ugc.aweme.i18n.language.initial; import android.content.Context; import java.util.concurrent.Callable; /* renamed from: com.ss.android.ugc.aweme.i18n.language.initial.f */ final /* synthetic */ class C30486f implements Callable { /* renamed from: a */ private final C30483e f80095a; /* renamed from: b */ private final Context f80096b; /* renamed from: c */ private final String[] f80097c; C30486f(C30483e eVar, Context context, String[] strArr) { this.f80095a = eVar; this.f80096b = context; this.f80097c = strArr; } public final Object call() { return this.f80095a.mo80160a(this.f80096b, this.f80097c); } }
b69e0fb47426583cf4ee3584580e9070f990dc5c
30b86c7a3fe6513a8003b5157dffd1f5dda08b38
/core/src/main/java/org/openstack4j/model/storage/block/builder/VolumeTypeBuilder.java
b5cee84239d0602de0e43c3c8de3c43c4ec09358
[ "Apache-2.0" ]
permissive
tanjin861117/openstack4j
c098a25529398855a1391f4d51fc28b687cb8cb6
b58da68654fc7570a3aee3f1eabdf9aef499a607
refs/heads/master
2020-04-06T17:29:04.079837
2018-11-13T13:17:20
2018-11-13T13:17:20
157,660,728
0
0
null
null
null
null
UTF-8
Java
false
false
765
java
package org.openstack4j.model.storage.block.builder; import java.util.Map; import org.openstack4j.common.Buildable.Builder; import org.openstack4j.model.storage.block.VolumeType; public interface VolumeTypeBuilder extends Builder<VolumeTypeBuilder, VolumeType> { /** * See {@link VolumeType#getName()} * * @param name the name of the volume type * @return VolumeTypeBuilder */ VolumeTypeBuilder name(String name); VolumeTypeBuilder description(String Description); /** * See {@link VolumeType#getExtraSpecs()} <b>Optional</b> * * @param extraSpecs Defining extra specs for the volume type as a key-value map. * @return VolumeTypeBuilder */ VolumeTypeBuilder extraSpecs(Map<String, String> extraSpecs); }
4fe690f22cd73e8c32520355663716682747c6c9
71cf31218c77bae6cfb5e9633bb68972410f3f9e
/Test/de/hawhamburg/hibernate/tests/UniversityDaoTest.java
d41b7c7593ca793bb03f3b3e20c5ff577196790a
[ "Apache-2.0" ]
permissive
serious6/HibernateSimpleProject
aeabe6d167a63bc0669d9a500aca54e1bdf1380a
1a2bd10a87187e61b158fbd029008decf964c313
refs/heads/master
2021-01-02T08:51:46.310842
2014-03-26T20:29:01
2014-03-26T20:29:01
null
0
0
null
null
null
null
ISO-8859-1
Java
false
false
1,481
java
package de.hawhamburg.hibernate.tests; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import de.hawhamburg.hibernate.dao.UniversityDao; import de.hawhamburg.tables.Adress; import de.hawhamburg.tables.Student; import de.hawhamburg.tables.University; public class UniversityDaoTest { private UniversityDao universityDao; @Before public void setUp() throws Exception { this.universityDao = new UniversityDao(); } @After public void tearDown() throws Exception { } @Test public void addUniversity() { University university = new University(); university.setName("TUHH"); university.setAdress(new Adress("Schwarzenbergstraße", "93", "21073", "Hamburg")); universityDao.add(university); Assert.assertNotNull(university.getId()); } @Test public void populateUniversity() { University haw = new University(); haw.setName("HAW Hamburg"); haw.setAdress(new Adress("Berliner Tor", "5", "20099", "Hamburg")); Adress wg1 = new Adress("Jungfernstieg", "1", "20099", "Hamburg"); Student student1 = new Student(); student1.setAdress(wg1); student1.setFirstName("Paul"); student1.setLastName("Paulsen"); student1.setUniversity(haw); Student student2 = new Student(); student2.setAdress(wg1); student2.setFirstName("Paulina"); student2.setLastName("Paulinsen"); student2.setUniversity(haw); haw.addStudent(student1); haw.addStudent(student2); universityDao.add(haw); } }
e0e4f7b990c9898e86ad13fd49bd72b05e7a01d4
ffab662510188b94ef74acf32463ed5d8ea192ee
/com.work.tour/src/com/tour/work/dao/DAO.java
3fcd8c19f7a1e129e699ac41448a0e92c19409cd
[]
no_license
better-space/first-jsp-project
fb6b3bc9ec58b0229a4ea96c778180e9f58801dc
5c769a01f58e21e22f66cbec8f8245ede9ff1895
refs/heads/master
2021-07-02T21:49:43.457732
2017-09-25T05:33:51
2017-09-25T05:33:51
104,705,413
1
0
null
null
null
null
GB18030
Java
false
false
1,065
java
/** package com.tour.work.dao; import java.sql.Connection; import java.sql.DriverManager; public class DAO { private Connection conn = null; public Connection getConn(){ try { Class.forName("com.hxtt.sql.access.AccessDriver"); String url = "jdbc:Access:/d:/Database/Database1.mdb"; conn = DriverManager.getConnection(url,"",""); } catch (Exception e) { e.printStackTrace(); } return conn; } } **/ //连接mysql package com.tour.work.dao; import java.sql.Connection; import java.sql.DriverManager; public class DAO { private Connection conn = null; public Connection getConn(){ String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/com.tour.work?useUnicode=true&characterEncoding=utf-8&useSSL=false"; String password = "suhe5059"; String user = "root"; try{ Class.forName(driver); conn = DriverManager.getConnection(url, user, password); if(conn!=null){ System.out.println("成功连接mysql数据库"); } }catch(Exception e){ e.printStackTrace(); } return conn; } }
f5a91c6b9483d354721c12899a80a351b8ddc35d
f7cb92ab608774e7384878cc591ddccd0bc46105
/EDA2/eda2/Bebida.java
35692c8efb2cf8bc4086f4ff5593d8bb7d0a54a3
[]
no_license
IgnacioCharlin/proyectoRestaurant
cca192b741d53c6dfeb2a2b9f50b8ad29a63d8a3
853cfa0ef25f5f3f3cc5a695b1326d877961fbbd
refs/heads/main
2023-03-12T22:37:55.414786
2021-03-08T18:59:28
2021-03-08T18:59:28
309,466,111
0
0
null
2020-11-07T20:35:56
2020-11-02T18:54:05
Java
UTF-8
Java
false
false
507
java
package eda2; public class Bebida extends Pedido { private String descripcion; private Double precio; public Bebida(String descripcion, Double precio) { super(); this.descripcion = descripcion; this.precio = precio; } protected String getDescripcion() { return descripcion; } protected void setDescripcion(String descripcion) { this.descripcion = descripcion; } protected Double getPrecio() { return precio; } protected void setPrecio(Double precio) { this.precio = precio; } }
3f78163239b134dee1a65d38d15666f25825f2a6
9a5636d97342cac48ba02ca424195c7aaed1d599
/DreamUp/src/com/dreamup/project/actions/SupportProList.java
022a14a61c45e4750dd3021fdba91f6485b49610
[]
no_license
plandosee14/DreamUp
bc38b1189c0542cc53cbeb57d89b933222d0bb87
16aabd6d057b356a702a4419d58e55fa3a66dd84
refs/heads/master
2021-01-12T18:10:08.986624
2016-11-07T09:28:04
2016-11-07T09:28:04
71,339,846
1
2
null
null
null
null
UHC
Java
false
false
1,203
java
package com.dreamup.project.actions; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.dreamup.project.dao.ProjectDAO; import com.dreamup.project.dto.ProjectDTO; public class SupportProList extends Action{ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("들어오나"); String m_id = request.getParameter("m_id"); System.out.println("m_id " + m_id ); ProjectDAO dao = new ProjectDAO(); List<ProjectDTO> supportProList; supportProList = dao.selectProjectById(m_id); for (int i = 0; i < supportProList.size(); i++) { System.out.println("여기라고 "); ProjectDTO project = new ProjectDTO(); project = supportProList.get(i); System.out.println(project.toString()); } request.setAttribute("supportProList", supportProList); return mapping.findForward("scs"); } }
c2fcf3b4fb6bd9e8e93e98a75875b43c666911c0
e8f1aa2776ea471c8857f13d579aef27a55ba2c8
/src/main/java/pl/kamilpchelka/codecool/datastructures/exceptions/StackOverflow.java
aa13ffc4bcc6fd00326325ccbcde53c5c604ab91
[]
no_license
KamilPchelka/Data-Structures-in-Java
8a35cbfca7595ab985bc175f8d89623f8c36c4ef
2703a2b3a10e0f2411db9aa2e6d2eef511260271
refs/heads/master
2020-03-13T00:07:42.530673
2018-04-26T11:36:01
2018-04-26T11:36:01
130,880,602
0
0
null
null
null
null
UTF-8
Java
false
false
111
java
package pl.kamilpchelka.codecool.datastructures.exceptions; public class StackOverflow extends Exception { }
35bca990a368f1fcfe52827bab00fde44563ebac
975bb97bb3ef51a53f2850b633fc0ab6efa27707
/src/main/java/net/kear/recipeorganizer/persistence/dto/RecipeMessageDto.java
cbdf95e192e7aea2215c0393047c907a2eccf38f
[]
no_license
lwkear/recipeorganizer
3fa06cca5a64125b80792cea2d4829296ea2f25e
c7e28dc7a70d482f4b86b1b396786b690f562b99
refs/heads/master
2020-04-05T13:15:27.455233
2018-11-19T15:12:50
2018-11-19T15:12:50
154,981,796
0
0
null
null
null
null
UTF-8
Java
false
false
2,725
java
package net.kear.recipeorganizer.persistence.dto; import java.io.Serializable; import java.util.Arrays; import net.kear.recipeorganizer.enums.ApprovalAction; import net.kear.recipeorganizer.enums.ApprovalReason; public class RecipeMessageDto implements Serializable { private static final long serialVersionUID = 1L; private long toUserId; private long recipeId; private String recipeName; private ApprovalAction action; private ApprovalReason[] reasons; private String message; public RecipeMessageDto() {} public RecipeMessageDto(long toUserId, long recipeId, String recipeName, ApprovalAction action, ApprovalReason[] reasons, String message) { super(); this.toUserId = toUserId; this.recipeId = recipeId; this.recipeName = recipeName; this.action = action; this.reasons = reasons; this.message = message; } public long getToUserId() { return toUserId; } public void setToUserId(long toUserId) { this.toUserId = toUserId; } public long getRecipeId() { return recipeId; } public void setRecipeId(long recipeId) { this.recipeId = recipeId; } public String getRecipeName() { return recipeName; } public void setRecipeName(String recipeName) { this.recipeName = recipeName; } public ApprovalAction getAction() { return action; } public void setAction(ApprovalAction action) { this.action = action; } public ApprovalReason[] getReasons() { return reasons; } public void setReasons(ApprovalReason[] reasons) { this.reasons = reasons; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((action == null) ? 0 : action.hashCode()); result = prime * result + (int) (recipeId ^ (recipeId >>> 32)); result = prime * result + (int) (toUserId ^ (toUserId >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RecipeMessageDto other = (RecipeMessageDto) obj; if (action != other.action) return false; if (recipeId != other.recipeId) return false; if (toUserId != other.toUserId) return false; return true; } @Override public String toString() { return "RecipeMessageDto [toUserId=" + toUserId + ", recipeId=" + recipeId + ", recipeName=" + recipeName + ", action=" + action + ", reasons=" + Arrays.toString(reasons) + ", message=" + message + "]"; } }
ac9a453c01c57270d269cd4d12cb91d96d033644
d0760db729e7fe9e3839a5e432182f65dd654a0c
/JSF_OMS/src/java/consumo/campanasListar.java
2b573f9484727c14a6662d47074b2278946a7277
[]
no_license
PICA-2016/PICA_OMS
33220967ca3614c5c586c8e84048e000bd500d39
cf48b936301e604b0fb7140c89bfaad5ed191a41
refs/heads/master
2021-01-18T21:40:19.220002
2016-06-01T07:08:37
2016-06-01T07:08:37
52,056,977
0
0
null
null
null
null
UTF-8
Java
false
false
3,186
java
/* * 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 consumo; import com.pica.dss.campanas.AdministrarCampanas; import com.pica.dss.campanas.CampanaCons; import com.pica.dss.campanas.DataServiceFault; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.xml.ws.WebServiceRef; /** * * @author GermanO */ @ManagedBean(name="beanListarCampanas") //@Named(value = "beanConsultaProductos") @ViewScoped public class campanasListar implements java.io.Serializable { @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/10.85.0.100_9766/services/administrarCampanas.wsdl") private AdministrarCampanas service; private List<CampanaCons> listaCampanas; private String estado; private String campana; private String IDCAMPANA; @PostConstruct public void init() { listaCampanas = this.listaCampanas(); } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public List<CampanaCons> listaCampanas() { System.out.println("hola"); try { List<CampanaCons> lista = new ArrayList<>(); listaCampanas = wsConsultaCampana("A"); for (CampanaCons campanaCons : listaCampanas) { System.out.println("Campanas : " + campanaCons.getNOMBRE()); } } catch (DataServiceFault ex) { System.out.println("error"); } return listaCampanas; } private java.util.List<com.pica.dss.campanas.CampanaCons> wsConsultaCampana(java.lang.String estado) throws DataServiceFault { // Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe. // If the calling of port operations may lead to race condition some synchronization is required. com.pica.dss.campanas.AdministrarCampanasPortType port = service.getSOAP11Endpoint(); return port.wsConsultaCampana(estado); } public List<CampanaCons> getListaCampanas() { return listaCampanas; } public void setListaCampanas(List<CampanaCons> listaCampanas) { this.listaCampanas = listaCampanas; } public void action(String IDCAMPANA) { try { System.out.println("germano - "+IDCAMPANA); FacesContext.getCurrentInstance().getExternalContext().redirect("registrar_campanhias_productos.xhtml"); } catch (IOException ex) { // do something here } } public String getCampana() { return campana; } public void setCampana(String IDCAMPANA) { System.out.println("2 - IDCAMPANA "+IDCAMPANA); this.campana = IDCAMPANA; } }
958656e506044a24304652d4a654094f54668fbd
704ac47a7ecd2b9f226c5d1b138822f1fcb5c65e
/app/src/androidTest/java/com/abhishek/listview/ExampleInstrumentedTest.java
eff8b616529b366e733ae8a63c43f38ffb7d2743
[]
no_license
abhishekhugetech/Listview-a
1e600b800025e8d9909cef70b94c908989f570fc
237073de8e44260060f4a2b57cb1bf2ca1c982c8
refs/heads/master
2020-03-16T15:29:47.791653
2018-05-09T11:59:25
2018-05-09T11:59:25
132,745,956
0
0
null
null
null
null
UTF-8
Java
false
false
726
java
package com.abhishek.listview; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.abhishek.listview", appContext.getPackageName()); } }
31fdf0cf886018e78898e6a5b01c6f3273889fa2
d26f11c1611b299e169e6a027f551a3deeecb534
/core/filesystem/org/fdesigner/filesystem/provider/FileInfo.java
dc5e844706afdd43119a7a4995058edaafd3dcf1
[]
no_license
WeControlTheFuture/fdesigner-ui
1bc401fd71a57985544220b9f9e42cf18db6491d
62efb51e57e5d7f25654e67ef8b2762311b766b6
refs/heads/master
2020-11-24T15:00:24.450846
2019-12-27T08:47:23
2019-12-27T08:47:23
228,199,674
0
0
null
null
null
null
UTF-8
Java
false
false
6,810
java
/******************************************************************************* * Copyright (c) 2005, 2015 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation * Martin Oberhuber (Wind River) - [170317] add symbolic link support to API *******************************************************************************/ package org.fdesigner.filesystem.provider; import org.fdesigner.filesystem.EFS; import org.fdesigner.filesystem.IFileInfo; import org.fdesigner.filesystem.internal.filesystem.local.LocalFileNativesManager; /** * This class should be used by file system providers in their implementation * of API methods that return {@link IFileInfo} objects. * * @since org.eclipse.core.filesystem 1.0 * @noextend This class is not intended to be subclassed by clients. */ public class FileInfo implements IFileInfo { /** * Internal attribute indicating if the file is a directory */ private static final int ATTRIBUTE_DIRECTORY = 1 << 0; /** * Internal attribute indicating if the file exists. */ private static final int ATTRIBUTE_EXISTS = 1 << 16; /** * Bit field of file attributes. Initialized to specify a writable resource. */ private int attributes = EFS.ATTRIBUTE_OWNER_WRITE | EFS.ATTRIBUTE_OWNER_READ; private int errorCode = NONE; /** * The last modified time. */ private long lastModified = EFS.NONE; /** * The file length. */ private long length = EFS.NONE; /** * The file name. */ private String name = ""; //$NON-NLS-1$ /** * The target file name if this is a symbolic link */ private String linkTarget = null; /** * Creates a new file information object with default values. */ public FileInfo() { super(); } /** * Creates a new file information object. All values except the file name * will have default values. * * @param name The name of this file */ public FileInfo(String name) { super(); this.name = name; } /** * Convenience method to clear a masked region of the attributes bit field. * * @param mask The mask to be cleared */ private void clear(int mask) { attributes &= ~mask; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { // We know this object is cloneable. return null; } } /** * @since 1.5 */ @Override public int compareTo(IFileInfo o) { return name.compareTo(o.getName()); } @Override public boolean exists() { return getAttribute(ATTRIBUTE_EXISTS); } /** * @since 1.4 */ @Override public int getError() { return errorCode; } @Override public boolean getAttribute(int attribute) { if (attribute == EFS.ATTRIBUTE_READ_ONLY && isAttributeSuported(EFS.ATTRIBUTE_OWNER_WRITE)) return (!isSet(EFS.ATTRIBUTE_OWNER_WRITE)) || isSet(EFS.ATTRIBUTE_IMMUTABLE); else if (attribute == EFS.ATTRIBUTE_EXECUTABLE && isAttributeSuported(EFS.ATTRIBUTE_OWNER_EXECUTE)) return isSet(EFS.ATTRIBUTE_OWNER_EXECUTE); else return isSet(attribute); } @Override public String getStringAttribute(int attribute) { if (attribute == EFS.ATTRIBUTE_LINK_TARGET) return this.linkTarget; return null; } @Override public long getLastModified() { return lastModified; } @Override public long getLength() { return length; } @Override public String getName() { return name; } @Override public boolean isDirectory() { return isSet(ATTRIBUTE_DIRECTORY); } private boolean isSet(long mask) { return (attributes & mask) != 0; } private void set(int mask) { attributes |= mask; } @Override public void setAttribute(int attribute, boolean value) { if (attribute == EFS.ATTRIBUTE_READ_ONLY && isAttributeSuported(EFS.ATTRIBUTE_OWNER_WRITE)) { if (value) { clear(EFS.ATTRIBUTE_OWNER_WRITE | EFS.ATTRIBUTE_OTHER_WRITE | EFS.ATTRIBUTE_GROUP_WRITE); set(EFS.ATTRIBUTE_IMMUTABLE); } else { set(EFS.ATTRIBUTE_OWNER_WRITE | EFS.ATTRIBUTE_OWNER_READ); clear(EFS.ATTRIBUTE_IMMUTABLE); } } else if (attribute == EFS.ATTRIBUTE_EXECUTABLE && isAttributeSuported(EFS.ATTRIBUTE_OWNER_EXECUTE)) { if (value) set(EFS.ATTRIBUTE_OWNER_EXECUTE); else clear(EFS.ATTRIBUTE_OWNER_EXECUTE | EFS.ATTRIBUTE_GROUP_EXECUTE | EFS.ATTRIBUTE_OTHER_EXECUTE); } else { if (value) set(attribute); else clear(attribute); } } private static boolean isAttributeSuported(int value) { return (LocalFileNativesManager.getSupportedAttributes() & value) != 0; } /** * Sets whether this is a file or directory. * * @param value <code>true</code> if this is a directory, and <code>false</code> * if this is a file. */ public void setDirectory(boolean value) { if (value) set(ATTRIBUTE_DIRECTORY); else clear(ATTRIBUTE_DIRECTORY); } /** * Sets whether this file or directory exists. * * @param value <code>true</code> if this file exists, and <code>false</code> * otherwise. */ public void setExists(boolean value) { if (value) set(ATTRIBUTE_EXISTS); else clear(ATTRIBUTE_EXISTS); } /** * Sets the error code indicating whether an I/O error was encountered when accessing the file. * * @param errorCode {@link IFileInfo#IO_ERROR} if this file has an I/O error, * and {@link IFileInfo#NONE} otherwise. * @since 1.4 */ public void setError(int errorCode) { this.errorCode = errorCode; } @Override public void setLastModified(long value) { lastModified = value; } /** * Sets the length of this file. A value of {@link EFS#NONE} * indicates the file does not exist, is a directory, or the length could not be computed. * * @param value the length of this file, or {@link EFS#NONE} */ public void setLength(long value) { this.length = value; } /** * Sets the name of this file. * * @param name The file name */ public void setName(String name) { if (name == null) throw new IllegalArgumentException(); this.name = name; } /** * Sets or clears a String attribute, e.g. symbolic link target. * * @param attribute The kind of attribute to set. Currently only * {@link EFS#ATTRIBUTE_LINK_TARGET} is supported. * @param value The String attribute, or <code>null</code> to clear * the attribute * @since org.eclipse.core.filesystem 1.1 */ public void setStringAttribute(int attribute, String value) { if (attribute == EFS.ATTRIBUTE_LINK_TARGET) this.linkTarget = value; } /** * For debugging purposes only. */ @Override public String toString() { return name; } }
c07386e3a0545c1df63c8bdd9010ddc248885524
85da22331a0a84b8caeedc63759085cb7f47a2bc
/src/by/tc/nb/bean/FindNoteByContentResponse.java
0ad4cd77e283729faa068ad8face204a82453e19
[]
no_license
davudmurtazin/Task3
17b41d4324ff3fd25da341a1bb2486154fbab614
45d923485d75d82193345047457544abf3459cdc
refs/heads/master
2021-01-11T04:55:20.146185
2016-10-06T08:40:39
2016-10-06T08:40:39
69,977,816
0
0
null
null
null
null
UTF-8
Java
false
false
348
java
package by.tc.nb.bean; import java.util.ArrayList; import by.tc.nb.bean.entity.Note; public class FindNoteByContentResponse extends Response { private ArrayList<Note> foundNotes; public ArrayList<Note> getFoundNotes() { return foundNotes; } public void setFoundNotes(ArrayList<Note> foundNotes) { this.foundNotes = foundNotes; } }
336cc94ec30ad3eb15e53c47fdad65d77ecb13be
658596c850cc065b962dd7ff54c556f67fc60f95
/src/test/java/com/spencerwi/either/EitherTest.java
ad41b3909b09fa71c3b81eaca181b08830dba113
[ "MIT" ]
permissive
nokok/Either.java
d0f76936e0e376b6ac697fe5b84536fe3606b296
b54cf5941e62239bca542f8de484c57f203cb3ba
refs/heads/master
2020-12-20T19:57:28.367508
2019-06-27T12:54:40
2019-06-27T12:54:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,164
java
package com.spencerwi.either; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.util.NoSuchElementException; import static org.assertj.core.api.Assertions.assertThat; public class EitherTest { @Test public void canDecideWhichSideToBuild_givenSupplierMethods(){ Either<String, Integer> leftSupplied = Either.either(()->"test", ()->null); assertThat(leftSupplied).isInstanceOf(Either.Left.class); assertThat(leftSupplied.getLeft()).isEqualTo("test"); Either<String, Integer> rightSupplied = Either.either(()->null, ()->42); assertThat(rightSupplied).isInstanceOf(Either.Right.class); assertThat(rightSupplied.getRight()).isEqualTo(42); } @Test public void isRightBiased(){ Either<String,Integer> bothSupplied = Either.either(()->"test", ()->42); assertThat(bothSupplied).isInstanceOf(Either.Right.class); } @Nested @DisplayName("Either.Left") public class EitherLeftTest { @Test public void canBeBuiltAsLeft(){ Either<String, Integer> leftOnly = Either.left("test"); assertThat(leftOnly).isInstanceOf(Either.Left.class); } @Test public void returnsLeftValueWhenAsked(){ Either<String, Integer> leftOnly = Either.left("test"); assertThat(leftOnly.getLeft()).isEqualTo("test"); } @Test public void throwsWhenAskedForRight(){ Either<String, Integer> leftOnly = Either.left("test"); try { leftOnly.getRight(); } catch(NoSuchElementException e){ assertThat(e).hasMessageContaining("Tried to getRight from a Left"); } } @Test public void identifiesAsLeftAndNotAsRight(){ Either<String, Integer> leftOnly = Either.left("test"); assertThat(leftOnly.isLeft()).isTrue(); assertThat(leftOnly.isRight()).isFalse(); } @Test public void executesLeftTransformation_whenFolded(){ Either<String, Integer> leftOnly = Either.left("test"); String result = leftOnly.fold( (leftSide) -> leftSide.toUpperCase(), (rightSide) -> rightSide.toString() ); assertThat(result).isEqualTo("TEST"); } @Test public void executesLeftTransformation_whenMapped(){ Either<String, Integer> leftOnly = Either.left("test"); Either<String, Integer> result = leftOnly.map( (leftSide) -> leftSide.toUpperCase(), (rightSide) -> rightSide * 2 ); assertThat(result).isInstanceOf(Either.Left.class); assertThat(result.getLeft()).isEqualTo("TEST"); } @Test public void runsLeftConsumer_WhenRunIsCalled(){ Either<String, Integer> leftOnly = Either.left("test"); WrapperAroundBoolean leftHasBeenRun = new WrapperAroundBoolean(false); leftOnly.run( left -> { leftHasBeenRun.set(true); }, right -> { /* no-op */ } ); assertThat(leftHasBeenRun.get()).isEqualTo(true); } @Test public void isEqualToOtherLeftsHavingTheSameLeftValue(){ Either<String,Integer> leftIsTest = Either.left("test"); Either<String,Object> leftIsAlsoTest = Either.left("test"); assertThat(leftIsTest).isEqualTo(leftIsAlsoTest); } @Test public void isNotEqualToOtherLeftsHavingDifferentValues(){ Either<String,Integer> leftIsHello = Either.left("hello"); Either<String,Integer> leftIsWorld = Either.left("world"); assertThat(leftIsHello).isNotEqualTo(leftIsWorld); } @Test public void isNotEqualToObjectsOfOtherClasses_obviously(){ String hello = "hello"; Either<String,Integer> leftIsHello = Either.left(hello); assertThat(leftIsHello).isNotEqualTo(hello); } @Test public void hasSameHashCodeAsWrappedLeftValue(){ Either<String, Integer> leftOnly = Either.left("Test"); assertThat(leftOnly.hashCode()).isEqualTo(leftOnly.getLeft().hashCode()); } } @Nested @DisplayName("Either.Right") public class EitherRightTest { @Test public void canBeBuiltAsRight(){ Either<String, Integer> rightOnly = Either.right(42); assertThat(rightOnly).isInstanceOf(Either.Right.class); } @Test public void returnsRightValueWhenAsked(){ Either<String, Integer> rightOnly = Either.right(42); assertThat(rightOnly.getRight()).isEqualTo(42); } @Test public void throwsWhenAskedForLeft(){ Either<String, Integer> rightOnly = Either.right(42); try { rightOnly.getLeft(); }catch(NoSuchElementException e){ assertThat(e).hasMessageContaining("Tried to getLeft from a Right"); } } @Test public void identifiesAsRightAndNotAsLeft(){ Either<String, Integer> rightOnly = Either.right(42); assertThat(rightOnly.isRight()).isTrue(); assertThat(rightOnly.isLeft()).isFalse(); } @Test public void executesRightTransformation_whenFolded(){ Either<String, Integer> rightOnly = Either.right(42); String result = rightOnly.fold( (leftSide) -> leftSide.toUpperCase(), (rightSide) -> rightSide.toString() ); assertThat(result).isEqualTo("42"); } @Test public void executesRightTransformation_whenMapped(){ Either<String, Integer> rightOnly = Either.right(42); Either<String, Integer> result = rightOnly.map( (leftSide) -> leftSide.toUpperCase(), (rightSide) -> rightSide * 2 ); assertThat(result).isInstanceOf(Either.Right.class); assertThat(result.getRight()).isEqualTo(42*2); } @Test public void runsRightConsumer_WhenRunIsCalled(){ Either<String, Integer> rightOnly = Either.right(42); WrapperAroundBoolean rightHasBeenRun = new WrapperAroundBoolean(false); rightOnly.run( left -> { /* no-op */ }, right -> { rightHasBeenRun.set(true); } ); assertThat(rightHasBeenRun.get()).isEqualTo(true); } @Test public void isEqualToOtherRightsHavingTheSameRightValue(){ Either<String,Integer> rightIs42 = Either.right(42); Either<Object,Integer> rightIsAlso42 = Either.right(42); assertThat(rightIs42).isEqualTo(rightIsAlso42); } @Test public void isNotEqualToOtherRightsHavingDifferentValues(){ Either<String,Integer> rightIs42 = Either.right(42); Either<String,Integer> rightIs9001 = Either.right(9001); assertThat(rightIs42).isNotEqualTo(rightIs9001); } @Test public void isNotEqualToObjectsOfOtherClasses_obviously(){ Integer fortyTwo = 42; Either<String,Integer> rightIs42 = Either.right(fortyTwo); assertThat(rightIs42).isNotEqualTo(fortyTwo); } @Test public void hasSameHashCodeAsWrappedRightValue(){ Either<String, Integer> rightOnly = Either.right(42); assertThat(rightOnly.hashCode()).isEqualTo(rightOnly.getRight().hashCode()); } } public static class WrapperAroundBoolean { private boolean value; public WrapperAroundBoolean(){ this.value = false; } public WrapperAroundBoolean(boolean value) { this.value = value; } public void set(boolean value){ this.value = value; } public boolean get(){ return this.value; } } }
20473388ab6bebfe47143dea72bad7b3b1a0bb62
8016a44f22755c0f9a6624d36683832eb76649f8
/StubProgram.java
b15a579cca2732544fc76b92a46a13adb6a7f6b4
[]
no_license
BenHilderman/ISC4U-Unit-2-01
b83c54449f69ec165e795f300be151c9afb2ecf0
20d0c583437efa594642e56e78800ef76c4c940e
refs/heads/master
2022-04-10T02:20:23.731570
2020-03-24T17:26:12
2020-03-24T17:26:12
249,771,819
0
0
null
null
null
null
UTF-8
Java
false
false
987
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class StubProgram { /** * StubProgram uses MrCoxallStack. */ public static void main(String[] args) { // program lets users add items to the MrCoxallStack MrCoxallStack anStack = new MrCoxallStack(); String anItem; InputStreamReader r = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(r); Scanner input = new Scanner(System.in); System.out.println("Enter the amount of items you want in the stack:"); int stackNumber = input.nextInt(); for (int lockNumber = 0; lockNumber < stackNumber; lockNumber++) { System.out.println("Enter an item to the stack"); try { anItem = br.readLine(); anStack.push(anItem); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
b3863374539fbdccc262dad495adc52fd20540cd
d72e8fe1730a4028c4f14a1892875c281df435cb
/app/src/main/java/test/com/badman/masque/UnpaidFragment.java
2fb21020fdff41b6fd4ba7c0dfd72757749ea601
[]
no_license
asifbu/Masque
4f29f66e4d83334340a719ce685cdf76f35085b1
70c5b2aa932c7e9fe350f7f9f09bccc7b9361a85
refs/heads/master
2020-12-23T14:01:09.106669
2020-03-03T22:29:27
2020-03-03T22:29:27
237,174,010
0
0
null
null
null
null
UTF-8
Java
false
false
123
java
package test.com.badman.masque; import android.support.v4.app.Fragment; public class UnpaidFragment extends Fragment { }
c59d0fc446bc9055c3288c2074880cba6af6fe99
753f5a8f1d49cadbbab13aeb5c3a84df26b62a19
/app/src/main/java/com/geniuskid/accidentdetector/customViews/NoSwipeViewPager.java
9530d94365b0d74500c04a959d2a00f8178c1107
[]
no_license
itsgeniuS/AccidentDetector
1d81d8c9fe4c9c3434606901dee21a7fbd62525e
cdaf903612da113218d6cac8e88bf5b24d080e10
refs/heads/master
2022-01-28T12:34:31.484467
2019-06-25T16:36:45
2019-06-25T16:36:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,506
java
package com.geniuskid.accidentdetector.customViews; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.Scroller; import java.lang.reflect.Field; public class NoSwipeViewPager extends ViewPager { private String name = "mScroller"; private Context context; public NoSwipeViewPager(Context context) { super(context); this.context = context; setUpScroller(); } public NoSwipeViewPager(Context context, AttributeSet attributeSet) { super(context, attributeSet); setUpScroller(); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return false; } @Override public boolean onTouchEvent(MotionEvent ev) { return false; } private void setUpScroller() { try { Class<?> viewpager = ViewPager.class; Field scroller = viewpager.getDeclaredField(name); scroller.setAccessible(true); scroller.set(this, new MyScroller(context)); } catch (Exception e) { e.printStackTrace(); } } public class MyScroller extends Scroller { MyScroller(Context context) { super(context); } @Override public void startScroll(int startX, int startY, int dx, int dy, int duration) { super.startScroll(startX, startY, dx, dy, 350); } } }
7f4e95078a9093c7813f4e9e6c3785fb75cd7989
87d7af899071528435f16f6e9fa7273f2379ede4
/hibernate/src/com/bookstore/domain/Chapter.java
ee40089826af9d503a1f5c942e7cce242236fff1
[]
no_license
sanket2599/HibernateAssignment
67f2997a0cbcd0f4a4219b84b12b6b4ed38d4b71
56f3a21922f960e6ab759d37f2230c8bb0896bb3
refs/heads/main
2023-08-01T11:24:18.701553
2021-09-18T08:53:37
2021-09-18T08:53:37
407,807,669
0
0
null
null
null
null
UTF-8
Java
false
false
1,005
java
package com.bookstore.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table//(name = "chapter") public class Chapter implements Serializable{ /** * */ private static final long serialVersionUID = -3161146984865936553L; @Id private ChapterPK chapterPK; //@Column(name = "title") private String title; public Chapter() {} public Chapter(ChapterPK chapterPK, String title) { super(); this.chapterPK = chapterPK; this.title = title; } public ChapterPK getChapterPK() { return chapterPK; } public void setChapterPK(ChapterPK chapterPK) { this.chapterPK = chapterPK; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public String toString() { return "Chapter [chapterPK=" + chapterPK + ", title=" + title + "]"; } }
29c250f32a1df789a56ccce31059eeac33923ff5
0874d515fb8c23ae10bf140ee5336853bceafe0b
/l2j-universe-lindvior/Lindvior Source/gameserver/src/main/java/l2p/gameserver/model/base/EnchantSkillLearn.java
9f393b6c52d5400575b8d2c0aa5e09071d5187f7
[]
no_license
NotorionN/l2j-universe
8dfe529c4c1ecf0010faead9e74a07d0bc7fa380
4d05cbd54f5586bf13e248e9c853068d941f8e57
refs/heads/master
2020-12-24T16:15:10.425510
2013-11-23T19:35:35
2013-11-23T19:35:35
37,354,291
0
1
null
null
null
null
UTF-8
Java
false
false
11,164
java
package l2p.gameserver.model.base; import l2p.gameserver.model.Player; import l2p.gameserver.tables.SkillTable; public final class EnchantSkillLearn { // these two build the primary key private final int _id; private final int _level; // not needed, just for easier debug private final String _name; private final String _type; private final int _baseLvl; private final int _maxLvl; private final int _minSkillLevel; private int _costMul; public EnchantSkillLearn(int id, int lvl, String name, String type, int minSkillLvl, int baseLvl, int maxLvl) { _id = id; _level = lvl; _baseLvl = baseLvl; _maxLvl = maxLvl; _minSkillLevel = minSkillLvl; _name = name.intern(); _type = type.intern(); _costMul = _maxLvl == 15 ? 5 : 1; } /** * @return Returns the id. */ public int getId() { return _id; } /** * @return Returns the level. */ public int getLevel() { return _level; } /** * @return Returns the minLevel. */ public int getBaseLevel() { return _baseLvl; } /** * @return Returns the minSkillLevel. */ public int getMinSkillLevel() { return _minSkillLevel; } /** * @return Returns the name. */ public String getName() { return _name; } public int getCostMult() { return _costMul; } /** * @return Returns the spCost. */ /** * @return Returns the spCost. */ public int[] getCost() { if (_maxLvl == 10) return SkillTable.getInstance().getInfo(_id, 1).isOffensive() ? _priceAwakening[_level % 100] : _priceAwakening[_level % 100]; else return SkillTable.getInstance().getInfo(_id, 1).isOffensive() ? _priceCombat[_level % 100] : _priceBuff[_level % 100]; } /** * Шанс заточки скилов 2й профы */ private static final int[][] _chance = {{}, //76 77 78 79 80 81 82 83 84 85 {82, 92, 97, 97, 97, 97, 97, 97, 97, 97}, // 1 {80, 90, 95, 95, 95, 95, 95, 95, 95, 95}, // 2 {78, 88, 93, 93, 93, 93, 93, 93, 93, 93}, // 3 {52, 76, 86, 91, 91, 91, 91, 91, 91, 91}, // 4 {50, 74, 84, 89, 89, 89, 89, 89, 89, 89}, // 5 {48, 72, 82, 87, 87, 87, 87, 87, 87, 87}, // 6 {01, 46, 70, 80, 85, 85, 85, 85, 85, 85}, // 7 {01, 44, 68, 78, 83, 83, 83, 83, 83, 83}, // 8 {01, 42, 66, 76, 81, 81, 81, 81, 81, 81}, // 9 {01, 01, 40, 64, 74, 79, 79, 79, 79, 79}, // 10 {01, 01, 38, 62, 72, 77, 77, 77, 77, 77}, // 11 {01, 01, 36, 60, 70, 75, 75, 75, 75, 75}, // 12 {01, 01, 01, 34, 58, 68, 73, 73, 73, 73}, // 13 {01, 01, 01, 32, 56, 66, 71, 71, 71, 71}, // 14 {01, 01, 01, 30, 54, 64, 69, 69, 69, 69}, // 15 {01, 01, 01, 01, 28, 52, 62, 67, 67, 67}, // 16 {01, 01, 01, 01, 26, 50, 60, 65, 65, 65}, // 17 {01, 01, 01, 01, 24, 48, 58, 63, 63, 63}, // 18 {01, 01, 01, 01, 01, 22, 46, 56, 61, 61}, // 19 {01, 01, 01, 01, 01, 20, 44, 54, 59, 59}, // 20 {01, 01, 01, 01, 01, 18, 42, 52, 57, 57}, // 21 {01, 01, 01, 01, 01, 01, 16, 40, 50, 55}, // 22 {01, 01, 01, 01, 01, 01, 14, 38, 48, 53}, // 23 {01, 01, 01, 01, 01, 01, 12, 36, 46, 51}, // 24 {01, 01, 01, 01, 01, 01, 01, 10, 34, 44}, // 25 {01, 01, 01, 01, 01, 01, 01, 8, 32, 42}, // 26 {01, 01, 01, 01, 01, 01, 01, 06, 30, 40}, // 27 {01, 01, 01, 01, 01, 01, 01, 01, 04, 28}, // 28 {01, 01, 01, 01, 01, 01, 01, 01, 02, 26}, // 29 {01, 01, 01, 01, 01, 01, 01, 01, 02, 24}, // 30 }; /** * Шанс заточки скилов 3ей профы */ private static final int[][] _chance15 = {{}, //76 77 78 79 80 81 82 83 84 85 {18, 28, 38, 48, 58, 82, 92, 97, 97, 97}, // 1 {01, 01, 01, 46, 56, 80, 90, 95, 95, 95}, // 2 {01, 01, 01, 01, 54, 78, 88, 93, 93, 93}, // 3 {01, 01, 01, 01, 42, 52, 76, 86, 91, 91}, // 4 {01, 01, 01, 01, 01, 50, 74, 84, 89, 89}, // 5 {01, 01, 01, 01, 01, 48, 72, 82, 87, 87}, // 6 {01, 01, 01, 01, 01, 01, 46, 70, 80, 85}, // 7 {01, 01, 01, 01, 01, 01, 44, 68, 78, 83}, // 8 {01, 01, 01, 01, 01, 01, 42, 66, 76, 81}, // 9 {01, 01, 01, 01, 01, 01, 01, 40, 64, 74}, // 10 {01, 01, 01, 01, 01, 01, 01, 38, 62, 72}, // 11 {01, 01, 01, 01, 01, 01, 01, 36, 60, 70}, // 12 {01, 01, 01, 01, 01, 01, 01, 01, 34, 58}, // 13 {01, 01, 01, 01, 01, 01, 01, 01, 32, 56}, // 14 {01, 01, 01, 01, 01, 01, 01, 01, 30, 54}, // 15 }; /** * Шанс заточки скилов 4ей профы */ private static final int[][] _chance10 = {{}, //85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 {85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99},//1 {80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94},//2 {75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89},//3 {70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84},//4 {65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79},//5 {60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74},//6 {30, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69},//7 {25, 26, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64},//8 {20, 21, 22, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59},//9 {15, 16, 17, 18, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54},//10 }; /*TODO: Вынести в ХМЛ, на оффе около 10 видов комбанаций цен.*/ /** * Цена заточки скиллов 3й профессии */ private static final int[][] _priceBuff = {{}, // {51975, 352786}, // 1 {51975, 352786}, // 2 {51975, 352786}, // 3 {78435, 370279}, // 4 {78435, 370279}, // 5 {78435, 370279}, // 6 {105210, 388290}, // 7 {105210, 388290}, // 8 {105210, 388290}, // 9 {132300, 416514}, // 10 {132300, 416514}, // 11 {132300, 416514}, // 12 {159705, 435466}, // 13 {159705, 435466}, // 14 {159705, 435466}, // 15 {187425, 466445}, // 16 {187425, 466445}, // 17 {187425, 466445}, // 18 {215460, 487483}, // 19 {215460, 487483}, // 20 {215460, 487483}, // 21 {243810, 520215}, // 22 {243810, 520215}, // 23 {243810, 520215}, // 24 {272475, 542829}, // 25 {272475, 542829}, // 26 {272475, 542829}, // 27 {304500, 566426}, // 28, цифра неточная {304500, 566426}, // 29, цифра неточная {304500, 566426}, // 30, цифра неточная }; /*TODO: Вынести в ХМЛ, на оффе около 10 видов комбанаций цен.*/ /** * Цена заточки атакующих скиллов */ private static final int[][] _priceCombat = {{}, // {93555, 635014}, // 1 {93555, 635014}, // 2 {93555, 635014}, // 3 {141183, 666502}, // 4 {141183, 666502}, // 5 {141183, 666502}, // 6 {189378, 699010}, // 7 {189378, 699010}, // 8 {189378, 699010}, // 9 {238140, 749725}, // 10 {238140, 749725}, // 11 {238140, 749725}, // 12 {287469, 896981}, // 13 {287469, 896981}, // 14 {287469, 896981}, // 15 {337365, 959540}, // 16 {337365, 959540}, // 17 {337365, 959540}, // 18 {387828, 1002821}, // 19 {387828, 1002821}, // 20 {387828, 1002821}, // 21 {438858, 1070155}, // 22 {438858, 1070155}, // 23 {438858, 1070155}, // 24 {496601, 1142010}, // 25, цифра неточная {496601, 1142010}, // 26, цифра неточная {496601, 1142010}, // 27, цифра неточная {561939, 1218690}, // 28, цифра неточная {561939, 1218690}, // 29, цифра неточная {561939, 1218690}, // 30, цифра неточная }; /** * Цена заточки скилов 4ей профы */ private static final int[][] _priceAwakening = {{}, // {1332450, 2091345}, // 1 {3997349, 6274037}, // 2 {6662250, 10456729}, // 3 {9327150, 14639421}, // 4 {11992050, 18822133}, // 5 {14656950, 23004804}, // 6 {17321850, 27187496}, // 7 {19986750, 31370188}, // 8 {22651650, 35552880}, // 9 {25316550, 39735572}, // 10 }; /** * Шанс успешной заточки */ public int getRate(Player ply) { int level = _level % 100; int chance; switch (_maxLvl) { case 10: { chance = Math.min(_chance10[level].length - 1, ply.getLevel() - 85); return _chance10[level][chance]; } case 15: { chance = Math.min(_chance15[level].length - 1, ply.getLevel() - 76); return _chance15[level][chance]; } default: { chance = Math.min(_chance[level].length - 1, ply.getLevel() - 76); } } return _chance[level][chance]; } public int getMaxLevel() { return _maxLvl; } public String getType() { return _type; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + _id; result = PRIME * result + _level; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; if (!(obj instanceof EnchantSkillLearn)) return false; EnchantSkillLearn other = (EnchantSkillLearn) obj; return getId() == other.getId() && getLevel() == other.getLevel(); } }
ae30019aaad3e9b5cfef1eec4d6e1df42119c9b0
7cb0d799781dee02c1653041fb71283593084c28
/app/src/main/java/com/kongtiaoapp/xxhj/adapter/MyZhenduanAdapter.java
46b32990e4952d1a5111183a280997c054685d18
[]
no_license
guochengabc/xxhj_project
2a7a41f000dc7c6512d93c83a641e6dd7a531a87
b6588be8e5c9436f88873e085a76c3241193a8c1
refs/heads/master
2020-09-21T13:09:44.562591
2020-01-19T09:17:05
2020-01-19T09:17:05
224,797,254
0
0
null
null
null
null
UTF-8
Java
false
false
2,031
java
package com.kongtiaoapp.xxhj.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.kongtiaoapp.xxhj.R; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by 桂飞 on 2016/11/4. */ public class MyZhenduanAdapter extends BaseAdapter { private List<String> list; private Context context; private List<Integer> list_image; public MyZhenduanAdapter( Context context) { this.context = context; notifyDataSetChanged(); } public void setList(List<String> list, List<Integer> list_image) { this.list = list; this.list_image = list_image; notifyDataSetChanged(); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolers viewholers = null; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.item_zhenduan, parent, false); viewholers = new ViewHolers(convertView); convertView.setTag(viewholers); } else { viewholers = (ViewHolers) convertView.getTag(); } viewholers.txt_zhenduan.setText(list.get(position).toString()); viewholers.image_summer.setImageResource(list_image.get(position)); return convertView; } class ViewHolers { @BindView(R.id.txt_zhenduan) TextView txt_zhenduan; @BindView(R.id.image_summer) ImageView image_summer; public ViewHolers(View view) { ButterKnife.bind(this, view); } } }
7906d09fd7e14d65e96211bf3ae73c3d35635b16
c8be6f80fdf7dcc2a71e29c9ae82d845a7a6eb88
/Algorithm/七大排序算法/SelectSort.java
ed11435646dbba85b86575f98d2359016f99dc4a
[]
no_license
cloudy-liu/BDSA
35be50ab83c39b86d2d213cfbcb9f5d23513d01f
af0ccbbe61e943cc60918f36e276a7e368105cf9
refs/heads/master
2021-06-11T07:08:30.724833
2021-03-21T15:12:16
2021-03-21T15:12:16
137,571,843
1
0
null
null
null
null
UTF-8
Java
false
false
1,206
java
/** * Author: cloudy * Date : 2018-6-14 */ package com.my.test; public class SelectSort extends BaseSort{ public void selectSort(int[] data) {//升序排序 int len = data.length; for (int i = 0; i < len; i++) { int minIndex = i; //初始化假定i为最小值的索引 for (int j = i + 1; j < len; j++) {//从 i+1处,开始寻找最小值的索引 if (data[minIndex] > data[j]) { minIndex = j; } } if (minIndex != i) { //比较一轮下来后,minIndex位置若发生变化,交换 swap(data, minIndex, i); } } } public static void main(String[] args) { for (int i = 0; i < BaseSort.data.length; i++) { BaseSort.beforeSort(BaseSort.data[i]); SelectSort sort = new SelectSort(); sort.selectSort(BaseSort.data[i]); BaseSort.afterSort(BaseSort.data[i]); } } } /* Before Sort 10 9 8 7 6 5 5 4 3 2 1 0 After Sort 0 1 2 3 4 5 5 6 7 8 9 10 Before Sort 1 2 3 4 5 5 6 7 After Sort 1 2 3 4 5 5 6 7 Before Sort 1 7 3 5 0 0 2 4 8 6 After Sort 0 0 1 2 3 4 5 6 7 8 */
09f2e60928f26e741a2197112ab804e008a0ef2f
0679d8f3c153ef1413385466f7d0c7ef7ec401b6
/src/test/java/com/entel/pageInterface/ILoginPage.java
e350037d62dbbbac56150cd54ff58457bac4c6ea
[]
no_license
Anand-qaselenium/entalProject
5d4f3239ed1d7bfef5738e15f4724ab1a6a10456
3a7c0d0e5985c5f48db69e8c97cf564eaeb27aec
refs/heads/master
2022-07-06T08:53:28.475959
2019-12-18T19:01:04
2019-12-18T19:01:04
219,269,046
0
0
null
2022-06-29T17:45:15
2019-11-03T09:00:55
HTML
UTF-8
Java
false
false
72
java
package com.entel.pageInterface; public interface ILoginPage { }
75c8d0c0f6f8f9898a363b91b65510ee591359dd
e56afd6c2bcc8d11524909aabeee200155bade02
/app03_library/app/src/main/java/com/choay/library/model/NaverBookDTO.java
f05302d2a5f062bf22251affe46e1b5ab3415deb
[ "Apache-2.0" ]
permissive
dkdud8140/Android
8ee93d000c77d0073add185ef30bb3fb3ce2b9f5
911a77afe19d21ee50f9f47de4e7fdebc62bb5c8
refs/heads/main
2023-07-28T03:26:52.972875
2021-08-23T04:57:57
2021-08-23T04:57:57
389,844,199
0
0
null
null
null
null
UTF-8
Java
false
false
1,851
java
package com.choay.library.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; /** * { * rss : "rss정보", * channer : "컨테이너", * . * . * . * items : [ * { * title : "title", * link : "link", * . * . * . * * } * ] * } */ @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor @Builder public class NaverBookDTO { private String title; // string 검색 결과 문서의 제목을 나타낸다. 제목에서 검색어와 일치하는 부분은 태그로 감싸져 있다. private String link; // string 검색 결과 문서의 하이퍼텍스트 link를 나타낸다. private String image; // string 썸네일 이미지의 URL이다. 이미지가 있는 경우만 나타납난다. private String author; // string 저자 정보이다. private String price; // integer 정가 정보이다. 절판도서 등으로 가격이 없으면 나타나지 않는다. private String discount; // integer 할인 가격 정보이다. 절판도서 등으로 가격이 없으면 나타나지 않는다. private String publisher; // string 출판사 정보이다. private String isbn; // integer ISBN 넘버이다. private String description; // string 검색 결과 문서의 내용을 요약한 패시지 정보이다. 문서 전체의 내용은 link를 따라가면 읽을 수 있다. 패시지에서 검색어와 일치하는 부분은 태그로 감싸져 있다. private String pubdate; // datetime 출간일 정보이다. }
6a6628a10cdef8922a84fe7b8dd9b681cf0b81b8
f5f779a1ec8d003ad7ccdb287659c1af97dbb1b5
/common_utils/src/main/java/com/nobodyhub/transcendence/common/domain/DataExcerpt.java
fcdd6ce9c4910a8d0eb354250ba6df0084d3de48
[]
no_license
yan-hai/transcendence
38b4d6e932e28b914ce1a5e3f1a0c733c9c28949
b48d7994b6027fb7b578008c3837df5a4a00830e
refs/heads/master
2020-04-15T12:17:26.413217
2019-02-06T04:41:19
2019-02-06T04:41:19
164,667,783
0
1
null
null
null
null
UTF-8
Java
false
false
558
java
package com.nobodyhub.transcendence.common.domain; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; /** * An excerpt of data that used for retrieving from database * * @param <T> the type enumeration of target data */ @Data @EqualsAndHashCode @AllArgsConstructor(access = AccessLevel.PROTECTED) public abstract class DataExcerpt<T> { /** * type of data */ protected T type; /** * the unique for data of given {@link #type} */ protected String id; }
6be5b83ff944c0abff326a3d2b3008116b765861
15400fe0b8a7f7e3b4fb368bae6d94b56f49d2f7
/src/com/sanushi/junit/basics/BankAccountTest.java
dc2a16794b41db515d8b45804f37b7bc961dd919
[]
no_license
Sanushi-Salgado/Java-Unit-Testing-With-JUnit
80a686a4d7b65f381c7c2d6d1c9fe06e1f18d7b4
381cd2baab0474cadb22567b4393ae8d9ee06535
refs/heads/master
2022-10-09T09:47:31.299979
2020-06-08T06:19:23
2020-06-08T06:19:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,328
java
package com.sanushi.junit.basics; import org.junit.*; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.fail; public class BankAccountTest { private static int count; private BankAccount bankAccount; @BeforeClass public static void beforeClass() { System.out.println("Starting to execute BankAccountTest. Count: " + count); } @Before public void setup() { bankAccount = new BankAccount("San", "Sal", 1000.00, BankAccount.CHECKING); System.out.println("Running Utilities test..."); } @Test public void deposit() throws Exception { // fail("This method has not yet been implemented"); double balance = bankAccount.deposit(200.00, true); assertEquals(1200.00, balance, 0); } @Test public void withdraw_branch() throws Exception { double balance = bankAccount.withdraw(600.00, true); assertEquals(400, balance, 0); } @Test (expected = IllegalArgumentException.class) public void withdraw_notBranch() throws Exception { // The test actually passes. We want the method to throw an IllegalArgumentException. bankAccount.withdraw(600.00, false); // In older versions of JUnit the following was done // try { // bankAccount.withdraw(600.00, true); // fail("Invalid withdrawal"); // }catch (IllegalArgumentException e){ // // } } @Test public void getBalance_deposit() throws Exception { bankAccount.deposit(200.00, true); assertEquals(1200.00, bankAccount.getBalance(), 0); } @Test public void getBalance_withdraw() throws Exception { bankAccount.withdraw(200.00, true); assertEquals(800.00, bankAccount.getBalance(), 0); } @Test public void isChecking_true() throws Exception { // assertEquals(true, bankAccount.isChecking()); assertTrue("This account is not Utilities checking account", bankAccount.isChecking()); } @After public void tearDown() { System.out.println("Count: " + count++); } @AfterClass public static void afterClass() { System.out.println("Completed executing BankAccountTest. Count: " + count); } }
8fa7dc7b6479fa8a426959f8e351ec8703541a95
69fd67c1ce860bfe1b92d655fb43083f01f41aa1
/src/TestIO/TestWriter.java
abcd9db045533c4d9f045d2757fe8240d1d28fbf
[]
no_license
maxomnis/java2
f53474e0c381608a3525a790a113dc13f90ffde4
741766c426fa0923e77bc93a9111a3ecf7152897
refs/heads/master
2021-04-09T12:01:59.796504
2020-12-02T07:12:18
2020-12-02T07:12:18
125,476,105
0
0
null
null
null
null
UTF-8
Java
false
false
542
java
package TestIO; import java.io.FileWriter; import java.io.IOException; public class TestWriter { public static void main(String[] args) throws IOException { try { FileWriter fw = new FileWriter("E:/java2/src/TestIO/popm.txt"); fw.write("李商隐\n"); fw.write("李商隐\n"); fw.write("李商隐\n"); fw.write("李商隐\n"); fw.write("李商隐\n"); }catch (Exception e) { e.printStackTrace(); } } }
f23cc9b695492b458ea6a6b24b98e5e3cafd2734
34ed6e0a773dd53c4a06cf4e8f0663418df6bb38
/src/main/java/de/herrlock/mfd/elements/Constant.java
d2bcfda9c61b26f145d7adb86f8cf6ff112698cc
[]
no_license
herrlock/MFDParser
f00ae1a4cf8c7c65f6069dfd9c5f27c0e3467dd4
71f692d27c7f578dc1aac2b8f55e269fcfc074d9
refs/heads/master
2016-09-05T16:06:32.578738
2015-12-06T23:29:09
2015-12-06T23:29:09
42,447,889
1
0
null
null
null
null
UTF-8
Java
false
false
1,864
java
package de.herrlock.mfd.elements; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jsoup.nodes.Element; import com.google.common.collect.ImmutableList; /** * A Constant has a type and a value. * * @author HerrLock */ public class Constant extends Component { private static final Logger logger = LogManager.getLogger(); private final String value; private final String datatype; private final List<Target> targets; /** * @param element */ public Constant( final Element element ) { super( element ); logger.entry(); Element constant = element.select( "> data > constant" ).first(); if ( constant == null ) { this.value = ""; this.datatype = ""; } else { this.value = element.attr( "value" ); this.datatype = element.attr( "datatype" ); } List<Target> targets = new ArrayList<>(); for ( Element target : element.select( " > targets > datapoint " ) ) { targets.add( new Target( target ) ); } this.targets = ImmutableList.copyOf( targets ); } public String getValue() { return this.value; } public String getDatatype() { return this.datatype; } public List<Target> getTargets() { return this.targets; } public static final class Target { private final int pos; private final int key; public Target( final Element e ) { this.pos = Integer.parseInt( e.attr( "pos" ) ); this.key = Integer.parseInt( e.attr( "key" ) ); } public int getPos() { return this.pos; } public int getKey() { return this.key; } } }
5b13c9d7a1a8566c5483cf172e192652be484047
969a1bc148af6b2eebdef2a08ada9cef1fb460d4
/app/src/main/java/ashley/todolist/MainActivity.java
5e2ddbee05d8f6576a32fb66738a7551d6299412
[]
no_license
ashleylau/cs193a-homework-2
7086dd523c19bb7330abc5e1a1f248a46915c986
22729841fd8baae218f937a1c2d6f2281323dbe1
refs/heads/master
2021-01-10T13:58:39.893299
2016-01-25T02:01:46
2016-01-25T02:01:46
50,319,194
0
0
null
null
null
null
UTF-8
Java
false
false
3,398
java
package ashley.todolist; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener { private ArrayList<String> taskItems; private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Restores array list from previous state (if it exists), otherwise creates a new one if (savedInstanceState != null && savedInstanceState.containsKey("savedTasks")){ taskItems = savedInstanceState.getStringArrayList("savedTasks"); } else { taskItems = new ArrayList<>(); } //Initializes the adapter for the listview and the array list adapter = new ArrayAdapter<>( this, R.layout.tasklayout, R.id.task_Item, taskItems ); ListView taskList = (ListView) findViewById(R.id.task_List); taskList.setOnItemLongClickListener(this); taskList.setAdapter(adapter); } /* On pressing the add button, the text is gotten from the EditText field and that text is added to the array list of strings. */ public void addTask(View view) { EditText toDoField = (EditText) findViewById(R.id.userTask); String toDoTask = toDoField.getText().toString(); if (toDoTask.equals("")){ Toast.makeText(MainActivity.this, "Enter some text!", Toast.LENGTH_SHORT).show(); } else { taskItems.add(toDoTask); adapter.notifyDataSetChanged(); toDoField.setText(""); } } /* On a long click, the to-do task is deleted. A message is shown to indicate that to the user. */ @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, "Deleted: " + taskItems.get(position), Toast.LENGTH_SHORT).show(); taskItems.remove(position); adapter.notifyDataSetChanged(); return false; } /* Saves the tasks with the key "savedTasks" */ @Override protected void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putStringArrayList("savedTasks", taskItems); } /*Restores the to-do tasks upon restoration of the activity. This method * also recreates the adapter and list view. */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState){ super.onRestoreInstanceState(savedInstanceState); taskItems = savedInstanceState.getStringArrayList("savedTasks"); adapter = new ArrayAdapter<>( this, R.layout.tasklayout, R.id.task_Item, taskItems ); ListView taskList = (ListView) findViewById(R.id.task_List); taskList.setOnItemLongClickListener(this); taskList.setAdapter(adapter); } }
387b39022f5702b482005bbc325675b96e3821c5
7aa02f902ad330c70b0b34ec2d4eb3454c7a3fc1
/com/google/api/client/googleapis/auth/oauth2/GoogleClientSecrets.java
a164bf1a4b20ad996f1545f34e54c3696cae70cc
[]
no_license
hisabimbola/andexpensecal
5e42c7e687296fae478dfd39abee45fae362bc5b
c47e6f0a1a6e24fe1377d35381b7e7e37f1730ee
refs/heads/master
2021-01-19T15:20:25.262893
2016-08-11T16:00:49
2016-08-11T16:00:49
100,962,347
1
0
null
2017-08-21T14:48:33
2017-08-21T14:48:33
null
UTF-8
Java
false
false
3,062
java
package com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.json.C0657b; import com.google.api.client.json.C0771d; import com.google.api.client.p050d.ab; import com.google.api.client.p050d.am; import java.io.InputStream; import java.util.List; public final class GoogleClientSecrets extends C0657b { @ab private Details installed; @ab private Details web; public final class Details extends C0657b { @ab(a = "auth_uri") private String authUri; @ab(a = "client_id") private String clientId; @ab(a = "client_secret") private String clientSecret; @ab(a = "redirect_uris") private List<String> redirectUris; @ab(a = "token_uri") private String tokenUri; public Details clone() { return (Details) super.clone(); } public String getAuthUri() { return this.authUri; } public String getClientId() { return this.clientId; } public String getClientSecret() { return this.clientSecret; } public List<String> getRedirectUris() { return this.redirectUris; } public String getTokenUri() { return this.tokenUri; } public Details set(String str, Object obj) { return (Details) super.set(str, obj); } public Details setAuthUri(String str) { this.authUri = str; return this; } public Details setClientId(String str) { this.clientId = str; return this; } public Details setClientSecret(String str) { this.clientSecret = str; return this; } public Details setRedirectUris(List<String> list) { this.redirectUris = list; return this; } public Details setTokenUri(String str) { this.tokenUri = str; return this; } } public static GoogleClientSecrets load(C0771d c0771d, InputStream inputStream) { return (GoogleClientSecrets) c0771d.m7056a(inputStream, GoogleClientSecrets.class); } public GoogleClientSecrets clone() { return (GoogleClientSecrets) super.clone(); } public Details getDetails() { boolean z = true; if ((this.web == null) == (this.installed == null)) { z = false; } am.m6914a(z); return this.web == null ? this.installed : this.web; } public Details getInstalled() { return this.installed; } public Details getWeb() { return this.web; } public GoogleClientSecrets set(String str, Object obj) { return (GoogleClientSecrets) super.set(str, obj); } public GoogleClientSecrets setInstalled(Details details) { this.installed = details; return this; } public GoogleClientSecrets setWeb(Details details) { this.web = details; return this; } }
22236ae35924b3b8e89e0e7bc0fc0f15aa3403d1
5f75cab8e7daf127e84fb7ac2cf4d2b77a232333
/src/main/java/com/OtherFunctionality/PreparedStatementDemo.java
da777f9377f35492415c83b67ba8e9695f272e5a
[]
no_license
qaamishra/Jdbc
cd931d2280fc4831e6ee8abb92f3c6473d6e87d8
a622bfcd20a81632ed584f05f763e74c48b578ec
refs/heads/master
2020-05-31T20:02:15.544700
2017-06-12T02:25:46
2017-06-12T02:25:46
94,046,851
0
0
null
null
null
null
UTF-8
Java
false
false
1,153
java
package com.OtherFunctionality; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; class PreparedStatementDemo { public static void main(String args[]) throws SQLException { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url="jdbc:odbc:mydsn1"; Properties p=new Properties(); p.put("user", "Rohit"); p.put("password","Kumar"); Connection con=DriverManager.getConnection(url,p); System.out.print("Connection Established...."); PreparedStatement ps= con.prepareStatement("insert into Employee (eid,ename,esal,edesg) values(?,?,?,?)"); System.out.println("hiii"); ps.setInt(1,109); ps.setString(2, "KIRRAANNN"); ps.setInt(3, 500000); ps.setString(4, "DIRECTOR"); System.out.println(" hiiiiiiiiiii"); int count = ps.executeUpdate(); System.out.println(" hiiiiiiiiiii"); System.out.println(count +"row(s) inserted"); //ps.close(); // stmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } }
5aaa662fb247cc7e3c0f35c9d3fec1bdc65cabe7
b9c3b3cb54032ccf795bbabe4885b12f9f2a3a5e
/src/com/vins/tab/ReportBillsAdapter.java
04c73b0e74e788befa06e496809f9c0149cc2a9c
[]
no_license
vakeeel/BillShareApp
d343fb3054f48abc0ab1986d4e0bfc26bcf97168
766478e48fd51688d4d7746bf36b853bcb6124cf
refs/heads/master
2020-12-25T18:18:32.566478
2012-06-17T09:31:17
2012-06-17T09:31:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,413
java
package com.vins.tab; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.kumulos.android.jsonclient.Kumulos; import com.kumulos.android.jsonclient.ResponseHandler; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; public class ReportBillsAdapter extends BaseAdapter { private Context context; private List<FriendsInfo> friendsInfo; private EditText amount; private TextView sharedAmount; public ArrayList<String> sharedPeople; int friendsParticipated = 0; public ReportBillsAdapter(Context context, List<FriendsInfo> friendsInfo, EditText amountTV, TextView sharedAmount) { this.context = context; this.friendsInfo = friendsInfo; this.amount = amountTV; this.sharedAmount = sharedAmount; sharedPeople = new ArrayList<String>(); } @Override public int getCount() { return friendsInfo.size(); } @Override public Object getItem(int position) { return friendsInfo.get(position); } @Override public long getItemId(int position) { return position; } public int pos = 0; @Override public View getView(int position, View convertView, ViewGroup parent) { FriendsInfo info = friendsInfo.get(position); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.reportbills_lv, null); } TextView userName = (TextView) convertView.findViewById(R.id.selectWhoParticipatedTVID); userName.setText(info.getUserEmail()); // Set the onClick Listener on this button final Button btnRemove = (Button) convertView.findViewById(R.id.addRemoveButton); btnRemove.setFocusableInTouchMode(false); btnRemove.setFocusable(false); btnRemove.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("on click"); System.out.println("amount on clicking = " + amount.getText().toString()); LinearLayout layout = (LinearLayout)v.getParent(); TextView tv = (TextView)layout.getChildAt(0); if(btnRemove.getText().toString().equalsIgnoreCase("add")) { friendsParticipated++; double sharedAmountValue = Double.valueOf(amount.getText().toString())/(double)friendsParticipated; sharedAmount.setText(new Double(Math.round(sharedAmountValue*100.0)/100.0).toString()); System.out.println("Add : " + tv.getText().toString()); System.out.println("selected item : " + ((ReportBillsActivity)context).selectedItem); sharedPeople.add(tv.getText().toString()); HashMap<String, String> params = new HashMap<String, String>(); params.put("billid", "xxx"); params.put("email", tv.getText().toString()); params.put("whopaid", ((ReportBillsActivity)context).selectedItem); params.put("amount", "0.0"); Kumulos.call("createShareRecord", params, new ResponseHandler() { @Override public void didCompleteWithResult(Object result) { btnRemove.setText("Remove"); } } ); } else { friendsParticipated--; btnRemove.setText("Add"); double sharedAmountValue = (friendsParticipated <= 0)? 0.0 : Double.valueOf(amount.getText().toString())/(double)friendsParticipated; sharedAmount.setText(new Double(Math.round(sharedAmountValue*100.0)/100.0).toString()); System.out.println("Remove : " + tv.getText().toString()); System.out.println("selected item : " + ((ReportBillsActivity)context).selectedItem); sharedPeople.remove(tv.getText().toString()); HashMap<String, String> params = new HashMap<String, String>(); params.put("billid", "xxx"); params.put("email", tv.getText().toString()); params.put("whopaid", ((ReportBillsActivity)context).selectedItem); Kumulos.call("deleteShareRecord", params, new ResponseHandler() { @Override public void didCompleteWithResult(Object result) { btnRemove.setText("Add"); } } ); } } }); btnRemove.setTag(info); return convertView; } }
50fab60319807dba71739158a3e9b34c6cb42007
798f8e3a90e39c55eeebae251e0dc497c2ca8d91
/src/main/java/com/ss/editor/tree/generator/tree/node/BranchesParametersTreeNode.java
1ff29f6d3b8b3065733d6e0927cac1d2436ecd3b
[ "Apache-2.0" ]
permissive
JavaSaBr/jmb-tree-generator
39166cffc4dee38a986ee15aff259843059f6266
94ccb18b4824ccc9e1fa7bcb5bf243db6e1926ba
refs/heads/master
2021-01-20T06:47:07.781072
2018-05-21T03:41:46
2018-05-21T03:41:46
101,517,524
3
1
Apache-2.0
2018-05-21T03:39:18
2017-08-26T22:53:52
Java
UTF-8
Java
false
false
2,227
java
package com.ss.editor.tree.generator.tree.node; import com.ss.editor.annotation.FromAnyThread; import com.ss.editor.annotation.FxThread; import com.ss.editor.tree.generator.PluginMessages; import com.ss.editor.tree.generator.parameters.BranchesParameters; import com.ss.editor.tree.generator.tree.action.CreateBranchAction; import com.ss.editor.ui.control.tree.NodeTree; import com.ss.editor.ui.control.tree.node.TreeNode; import com.ss.rlib.common.util.array.Array; import com.ss.rlib.common.util.array.ArrayFactory; import javafx.collections.ObservableList; import javafx.scene.control.MenuItem; import org.jetbrains.annotations.NotNull; /** * The implementation of presentation branches parameters node in the {@link ParametersTreeNode} * * @author JavaSaBr */ public class BranchesParametersTreeNode extends ParametersTreeNode<BranchesParameters> { public BranchesParametersTreeNode(@NotNull BranchesParameters element, long objectId) { super(element, objectId); } @Override @FromAnyThread public @NotNull String getName() { return PluginMessages.TREE_GENERATOR_EDITOR_NODE_BRANCHES; } @Override @FxThread public @NotNull Array<TreeNode<?>> getChildren(@NotNull NodeTree<?> nodeTree) { var branchesParameters = getElement(); var treeParameters = branchesParameters.getTreeParameters(); var children = ArrayFactory.<TreeNode<?>>newArray(TreeNode.class); var branches = treeParameters.getBranches(); for (var branch : branches) { children.add(FACTORY_REGISTRY.createFor(branch)); } for (var i = 0; i < children.size(); i++) { var node = (BranchParametersTreeNode) children.get(i); node.setName(PluginMessages.TREE_GENERATOR_EDITOR_NODE_BRANCH + " #" + i); } return children; } @Override @FxThread public void fillContextMenu(@NotNull NodeTree<?> nodeTree, @NotNull ObservableList<MenuItem> items) { super.fillContextMenu(nodeTree, items); items.add(new CreateBranchAction(nodeTree, this)); } @Override @FxThread public boolean hasChildren(@NotNull NodeTree<?> nodeTree) { return true; } }
57d0ae02b00dbe7304895333e4affc2641a4ee60
176bea464e9fbf6b1b29e0104b13985f38784d95
/by-language/java/java-basics/1-installing-basics/workshop/Workshop05.java
c27a91f73a84f7ab4d4a2576874eebc16f78363b
[]
no_license
Manuel1426/my-teaching-materials
f9accd21d7545168b5f91a7d11ec40a78e78b109
c3ccf92160b711c4e1754426a7df93f966a27f74
refs/heads/master
2023-03-18T21:51:14.046956
2017-10-03T20:12:09
2017-10-03T20:12:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
150
java
public class Workshop05{ public static void main(String[] args) { int e = 8; // please cube of e's value System.out.println(e); } }
e5d8d7da4dcb9b95d666a9ad34e8c7c4a9ee1d41
d2cb1f4f186238ed3075c2748552e9325763a1cb
/methods_all/nonstatic_methods/javax_swing_plaf_metal_MetalScrollBarUI_wait_long.java
1cac61d9fd71d4ac14c1dacc25c627384d78ba98
[]
no_license
Adabot1/data
9e5c64021261bf181b51b4141aab2e2877b9054a
352b77eaebd8efdb4d343b642c71cdbfec35054e
refs/heads/master
2020-05-16T14:22:19.491115
2019-05-25T04:35:00
2019-05-25T04:35:00
183,001,929
4
0
null
null
null
null
UTF-8
Java
false
false
213
java
class javax_swing_plaf_metal_MetalScrollBarUI_wait_long{ public static void function() {javax.swing.plaf.metal.MetalScrollBarUI obj = new javax.swing.plaf.metal.MetalScrollBarUI();obj.wait(-2155073088023908753);}}
c24246e0887a43e87d871f883852bbadf0094c67
d121774d5f6c1baccf1cd580746b8c5da863d9a7
/src/com/LHS/digitalimagebasics/ColorSwapper.java
3a8c2809f6ef1f8a2275ba210aa15da7b52f4ab8
[]
no_license
GlobalSystemsScience/Digital-Image-Basics-Applet
4bf4a7fe331c8cdcc7c7fab4dc599d8cf65ec0ce
acddab3613d0c89d1553ce8fa233580bcc69ed0e
refs/heads/master
2020-04-17T00:59:07.105554
2013-04-26T20:13:36
2013-04-26T20:13:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,416
java
package com.LHS.digitalimagebasics; import java.awt.image.RGBImageFilter; public class ColorSwapper extends RGBImageFilter { private static int RED = 0xFF0000; private static int GREEN = 0x00FF00; private static int BLUE = 0x0000FF; private int redDisplayColor; private int greenDisplayColor; private int blueDisplayColor; private int[] redColorShift; private int[] greenColorShift; private int[] blueColorShift; private boolean[] hideRed; private boolean[] hideGreen; private boolean[] hideBlue; private int count = 0; private boolean[] greenLeftShift; @Override public int filterRGB(int x, int y, int rgb) { int red=0, green = 0, blue=0; for (int i=0; i < greenColorShift.length; i++) { if (!hideGreen[i]) { if (greenColorShift[i] != -1) { if (greenLeftShift[i]) { green += (rgb & GREEN) << greenColorShift[i]; } else { green += (rgb & GREEN) >> greenColorShift[i]; } } } } for (int i=0; i < redColorShift.length; i++) { if (!hideRed[i]) { if (redColorShift[i] != -1) red += ((rgb & RED) >> redColorShift[i]); } } for (int i=0; i < blueColorShift.length; i++) { if (!hideBlue[i]) { if (blueColorShift[i] != -1) blue += ((rgb & BLUE) << blueColorShift[i]); } } if (count % 1000 == 0) { System.out.println(red + " " + green + " " + blue); } count++; return ( red | green | blue | (rgb & 0xFF000000)); } public void setRedDisplayColor(int redDisplayColor) { this.redDisplayColor = redDisplayColor; } public void setGreenDisplayColor(int greenDisplayColor) { this.greenDisplayColor = greenDisplayColor; } public void setBlueDisplayColor(int blueDisplayColor) { this.blueDisplayColor = blueDisplayColor; } public void setRedColorShift(int[] redColorShift) { this.redColorShift = redColorShift; } public void setGreenColorShift(int[] greenColorShift) { this.greenColorShift = greenColorShift; } public void setBlueColorShift(int[] blueColorShift) { this.blueColorShift = blueColorShift; } public void setGreenLeftShift(boolean[] greenLeftShift) { this.greenLeftShift = greenLeftShift; } public void setHideRed(boolean[] hideRed) { this.hideRed = hideRed; } public void setHideGreen(boolean[] hideGreen) { this.hideGreen = hideGreen; } public void setHideBlue(boolean[] hideBlue) { this.hideBlue = hideBlue; } }
87049475f1bd5e3b3e2234317f75b3e12bfdd135
b6a1e0d93f51b037375beaf81975e255400cf1f8
/wear/src/main/java/com/kimjio/mealviewer/widget/SelectMenuAdapter.java
7bcf8fb77bf384dd3453bf149d5a9efcc1f092be
[]
no_license
Kimjio/MealViewer
ddb361bd337c552406efdba2b405a5b0d395363e
8c7704fce85a813b9ab2595d0a25fc6d2dd11f51
refs/heads/master
2021-07-06T06:05:45.231539
2020-09-20T09:23:54
2020-09-20T09:23:54
184,378,135
1
0
null
null
null
null
UTF-8
Java
false
false
9,424
java
package com.kimjio.mealviewer.widget; import android.app.Activity; import android.content.Intent; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Observer; import androidx.recyclerview.widget.RecyclerView; import androidx.wear.widget.WearableRecyclerView; import com.kimjio.handwritingfix.HandwritingHelper; import com.kimjio.mealviewer.R; import com.kimjio.mealviewer.activity.SchoolSearchActivity; import com.kimjio.mealviewer.activity.SubSelectActivity; public class SelectMenuAdapter extends WearableRecyclerView.Adapter<SelectMenuViewHolder> { private static final int REQ_COUNTRY = 2; private static final int REQ_SCHOOL_TYPE = 3; public static final int REQ_SEARCH = 4; private static final int TYPE_TITLE = 0; private static final int TYPE_EDITABLE = 1; private OpenSearchListener searchListener; private OpenSubMenuListener menuListener; private OnOpenOnPhoneClickListener oopListener; private MutableLiveData<CharSequence> countryData = new MutableLiveData<>(); private MutableLiveData<CharSequence> schoolTypeData = new MutableLiveData<>(); private Observer<CharSequence> countryObserver; private Observer<CharSequence> schoolTypeObserver; private Observer<CharSequence> searchObserver; private CharSequence country; private CharSequence schoolType = "0"; private CharSequence schoolName = ""; @Override @ViewType public int getItemViewType(int position) { if (position == 2) return TYPE_EDITABLE; return TYPE_TITLE; } @NonNull @Override public SelectMenuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, @ViewType int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.select_menu, parent, false); if (viewType == TYPE_EDITABLE) return new SelectMenuViewHolder(view, true); return new SelectMenuViewHolder(view); } @Override public void onBindViewHolder(@NonNull SelectMenuViewHolder holder, final int position) { holder.binding.title.setEnabled(true); holder.binding.wrapper.setEnabled(true); holder.binding.wrapper.setOnClickListener(null); switch (position) { case 0: holder.binding.title.setText(R.string.select_menu_country); countryData.observeForever(countryObserver = sequence -> { holder.binding.subTitle.setText(sequence); holder.binding.subTitle.setVisibility(View.VISIBLE); }); holder.binding.image.setImageResource(R.drawable.ic_rounded_location); holder.binding.wrapper.setOnClickListener(v -> { Intent intent = new Intent(v.getContext(), SubSelectActivity.class); intent.putExtra(SubSelectActivity.EXTRA_CURRENT_VALUE, country) .putExtra(SubSelectActivity.EXTRA_MENU_ICON, R.drawable.ic_rounded_location) .putExtra(SubSelectActivity.EXTRA_MENUS, R.array.country_educations) .putExtra(SubSelectActivity.EXTRA_MENU_VALUES, R.array.country_education_urls); if (menuListener != null) menuListener.openSubMenu(intent, REQ_COUNTRY); }); break; case 1: holder.binding.title.setText(R.string.select_menu_type); schoolTypeData.observeForever(schoolTypeObserver = sequence -> { holder.binding.subTitle.setText(sequence); holder.binding.subTitle.setVisibility(View.VISIBLE); }); if (schoolTypeData.getValue() == null) schoolTypeData.setValue(holder.itemView.getContext().getText(R.string.all)); holder.binding.image.setImageResource(R.drawable.ic_rounded_school); holder.binding.wrapper.setOnClickListener(v -> { Intent intent = new Intent(v.getContext(), SubSelectActivity.class); intent.putExtra(SubSelectActivity.EXTRA_CURRENT_VALUE, schoolType) .putExtra(SubSelectActivity.EXTRA_MENU_ICON, R.drawable.ic_rounded_school) .putExtra(SubSelectActivity.EXTRA_MENUS, R.array.school_type) .putExtra(SubSelectActivity.EXTRA_MENU_VALUES, SubSelectActivity.VALUE_IS_INDEX); if (menuListener != null) menuListener.openSubMenu(intent, REQ_SCHOOL_TYPE); }); break; case 2: holder.binding.titleEditable.setHint(R.string.hint_school_name); holder.binding.titleEditable.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { schoolName = s; } @Override public void afterTextChanged(Editable s) { } }); holder.binding.subTitle.setVisibility(View.GONE); new HandwritingHelper().attachToTextView(holder.binding.titleEditable); holder.binding.image.setImageResource(R.drawable.ic_rounded_school_name); break; case 3: holder.binding.title.setText(android.R.string.search_go); holder.binding.title.setEnabled(false); holder.binding.wrapper.setEnabled(false); countryData.observeForever(searchObserver = sequence -> { holder.binding.title.setEnabled(true); holder.binding.wrapper.setEnabled(true); }); holder.binding.subTitle.setVisibility(View.GONE); holder.binding.image.setImageResource(R.drawable.ic_rounded_search); holder.binding.wrapper.setOnClickListener(v -> { Intent intent = new Intent(v.getContext(), SchoolSearchActivity.class); intent.putExtra(SchoolSearchActivity.EXTRA_LOCAL_DOMAIN, country) .putExtra(SchoolSearchActivity.EXTRA_SCHOOL_TYPE, schoolType) .putExtra(SchoolSearchActivity.EXTRA_SCHOOL_NAME, schoolName); if (searchListener != null) searchListener.openSearch(intent, REQ_SEARCH); }); break; case 4: holder.binding.title.setText(R.string.common_open_on_phone); holder.binding.subTitle.setVisibility(View.GONE); holder.binding.image.setImageResource(R.drawable.ic_rounded_open_on_phone); holder.binding.wrapper.setOnClickListener(v -> { if (oopListener != null) oopListener.onOpenOnPhoneClick(); }); break; default: break; } } public void setOpenSubMenuListener(OpenSubMenuListener menuListener) { this.menuListener = menuListener; } public void setOpenSearchListener(OpenSearchListener searchListener) { this.searchListener = searchListener; } public void setOnOpenOnPhoneClickListener(OnOpenOnPhoneClickListener oopListener) { this.oopListener = oopListener; } @Override public int getItemCount() { /* 지역 타입 이름 Edit 검색 Butt OOP Butt */ return 5; } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { CharSequence title = data.getCharSequenceExtra(SubSelectActivity.RESULT_MENU_TITLE); CharSequence value = data.getCharSequenceExtra(SubSelectActivity.RESULT_MENU_VALUE); switch (requestCode) { case REQ_COUNTRY: country = value; countryData.setValue(title); break; case REQ_SCHOOL_TYPE: schoolType = value; schoolTypeData.setValue(title); break; } } } @Override public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) { super.onDetachedFromRecyclerView(recyclerView); countryData.removeObserver(countryObserver); schoolTypeData.removeObserver(schoolTypeObserver); } public interface OpenSearchListener { void openSearch(Intent data, int requestCode); } public interface OpenSubMenuListener { void openSubMenu(Intent data, int requestCode); } public interface OnOpenOnPhoneClickListener { void onOpenOnPhoneClick(); } @IntDef({TYPE_TITLE, TYPE_EDITABLE}) private @interface ViewType { } }
dd71b452f09539ad25e0f47b2b568542b92a4ba2
500f87ac5a998010a9712d131c23578f62cce763
/app/src/main/java/com/example/sqlcipherexample/LogUtils.java
9661dde6692a158c19d17759f93d661265ed338d
[]
no_license
YogeshD25/Keystore-Demo
e8121b74770bdfb6394b868505f111141eb79d03
3d5319a6d9e0b16e450b1cd8220bc81d0f2bf19f
refs/heads/master
2020-12-13T21:25:25.455496
2020-01-21T10:57:25
2020-01-21T10:57:25
234,534,139
0
0
null
null
null
null
UTF-8
Java
false
false
282
java
package com.example.sqlcipherexample; import android.util.Log; public class LogUtils { public static final String tag = "Keystore API Android"; public static void debug( String message) { if (BuildConfig.DEBUG) { Log.d(tag, message); } } }
82f19f04f360144456008e28d4a4754ffb2f3d84
873c15976805f3296d9e3d7d8861edab5593f676
/src/integration-test/java/io/jay/tddspringbootorderinsideout/authentication/EndpointAccessTests.java
f5026331cb30069337e72795ce5fcb636b760cca
[]
no_license
shub8968/tdd-spring-boot-order
85e22f1ee8c678c1b788b8f86587f849437e0728
0bf610fdc12bd2e84403bd6214241e8cbe0d2954
refs/heads/master
2023-06-05T10:40:56.538678
2021-06-20T23:54:02
2021-06-20T23:54:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,697
java
package io.jay.tddspringbootorderinsideout.authentication; import io.jay.tddspringbootorderinsideout.authentication.rest.dto.TokenResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.web.servlet.MockMvc; import javax.transaction.Transactional; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @DirtiesContext public class EndpointAccessTests { @Autowired private MockMvc mockMvc; private AuthenticationTestHelper testHelper; @BeforeEach void setUp() { testHelper = new AuthenticationTestHelper(mockMvc); } @Test @Transactional void test_signup_isAccessible() throws Exception { testHelper.signUp("[email protected]", "password") .andExpect(status().isOk()); } @Test @Transactional void test_login_isAccessible() throws Exception { testHelper.signUp("[email protected]", "password"); testHelper.login("[email protected]", "password") .andExpect(status().isOk()); } @Test void test_getOrders_returnsForbidden() throws Exception { mockMvc.perform(get("/orders")) .andExpect(status().isForbidden()); } @Test void test_getUsers_returnsForbidden() throws Exception { mockMvc.perform(get("/users")) .andExpect(status().isForbidden()); } @Test @Transactional void test_getOrdersWithAccessToken_returnsOk() throws Exception { testHelper.signUp("[email protected]", "password"); TokenResponse tokenResponse = testHelper.loginAndReturnToken("[email protected]", "password"); mockMvc.perform(get("/orders") .header("Authorization", "Bearer " + tokenResponse.getAccessToken())) .andExpect(status().isOk()); } @Test @Transactional void test_getOrdersWithRefreshToken_returnsOk() throws Exception { testHelper.signUp("[email protected]", "password"); TokenResponse tokenResponse = testHelper.loginAndReturnToken("[email protected]", "password"); mockMvc.perform(get("/orders") .header("Authorization", "Bearer " + tokenResponse.getRefreshToken())) .andExpect(status().isOk()); } }
145583f342e251ac64509d20458e5c322e59e2d1
a65190d4900ec5404023879089d00bd81f86b2c6
/src/main/java/com/hmt/carga/config/locale/package-info.java
c8edb3b5641bb7ce47562fe30af501680f057cfe
[]
no_license
Darguelles/hmt-carga
f3f8edf8c1915d6ce1466cdac61615b03753edee
a73f353851ee549b748c3b1edb3e69862d7d7f6e
refs/heads/master
2020-11-24T21:30:00.732499
2017-09-05T06:23:51
2017-09-05T06:23:51
73,507,643
1
0
null
null
null
null
UTF-8
Java
false
false
70
java
/** * Locale specific code. */ package com.hmt.carga.config.locale;
24074af56e49f6ed84625d2b2777f73e46f30cbb
4688d19282b2b3b46fc7911d5d67eac0e87bbe24
/aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisanalytics/model/transform/DeleteApplicationInputProcessingConfigurationResultJsonUnmarshaller.java
cd1fc77d9c468010c56bb00fe7cc7008580699b3
[ "Apache-2.0" ]
permissive
emilva/aws-sdk-java
c123009b816963a8dc86469405b7e687602579ba
8fdbdbacdb289fdc0ede057015722b8f7a0d89dc
refs/heads/master
2021-05-13T17:39:35.101322
2018-12-12T13:11:42
2018-12-12T13:11:42
116,821,450
1
0
Apache-2.0
2018-09-19T04:17:41
2018-01-09T13:45:39
Java
UTF-8
Java
false
false
1,979
java
/* * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.kinesisanalytics.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.kinesisanalytics.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import static com.fasterxml.jackson.core.JsonToken.*; /** * DeleteApplicationInputProcessingConfigurationResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteApplicationInputProcessingConfigurationResultJsonUnmarshaller implements Unmarshaller<DeleteApplicationInputProcessingConfigurationResult, JsonUnmarshallerContext> { public DeleteApplicationInputProcessingConfigurationResult unmarshall(JsonUnmarshallerContext context) throws Exception { DeleteApplicationInputProcessingConfigurationResult deleteApplicationInputProcessingConfigurationResult = new DeleteApplicationInputProcessingConfigurationResult(); return deleteApplicationInputProcessingConfigurationResult; } private static DeleteApplicationInputProcessingConfigurationResultJsonUnmarshaller instance; public static DeleteApplicationInputProcessingConfigurationResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DeleteApplicationInputProcessingConfigurationResultJsonUnmarshaller(); return instance; } }
[ "" ]
95e32d96423bb3c174a31c459d1da499aa1c8e67
bdef6ed9107028902af5b4dfd02fa141ea3cb8ee
/src/main/java/lesson04/locks/LockDemo.java
9ad311c5d4854f8d61e86001f2d80436d24366bb
[]
no_license
yunzhongfan/corejava
02b7520ec8c266068f9f9f0f93e7a57cf100ce0a
bed86dcffb69e1b8fe9402ad824f26968b467656
refs/heads/master
2020-04-18T11:42:26.413093
2019-01-25T11:57:37
2019-01-25T11:57:37
167,510,434
0
0
null
null
null
null
UTF-8
Java
false
false
1,109
java
package lesson04.locks; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockDemo { public static int count; public static Lock countLock = new ReentrantLock(); public static void main(String[] args) throws InterruptedException { ExecutorService executor = Executors.newCachedThreadPool(); for (int i = 1; i <= 100; i++) { Runnable task = () -> { for (int k = 1; k <= 1000; k++) { countLock.lock(); try { count++; // Critical section } finally { countLock.unlock(); // Make sure the lock is unlocked } } }; executor.execute(task); } executor.shutdown(); executor.awaitTermination(10, TimeUnit.MINUTES); System.out.println("Final value: " + count); } }
a0e36934b9d14f30bc84f88e2b76e0f5c35bf8c4
13c3f8328e5da34c1c906e78a71037dd6c5ae03e
/Mslawin-notes-Server/src/main/java/pl/mslawin/notes/domain/notes/Task.java
971c98c3f578417f05f281ccb1bde89d0729735b
[]
no_license
mslawin/Notes
06f10784c8c67ac143f9fb7977fb0f32be81f7fe
5fabfad9fde65c7c90c7984c25ac306047951b32
refs/heads/master
2021-01-19T03:55:10.380832
2016-07-19T13:14:29
2016-07-19T13:14:29
43,203,813
0
0
null
null
null
null
UTF-8
Java
false
false
1,917
java
package pl.mslawin.notes.domain.notes; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import org.joda.time.LocalDateTime; @Entity public class Task { @Id @GeneratedValue private Long id; @Column(name = "text", nullable = false) private String text; @Column(name = "author", nullable = false) private String author; @Column(name = "creation_time", nullable = false) private LocalDateTime creationTime; @Column(name = "completed") private boolean completed = false; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "list_id") private TasksList tasksList; public Task() { } public Task(String text, String author) { this.text = text; this.author = author; this.creationTime = LocalDateTime.now(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public LocalDateTime getCreationTime() { return creationTime; } public void setCreationTime(LocalDateTime creationTime) { this.creationTime = creationTime; } public boolean isCompleted() { return completed; } public void setCompleted(boolean completed) { this.completed = completed; } public TasksList getTasksList() { return tasksList; } public void setTasksList(TasksList tasksList) { this.tasksList = tasksList; } }
40506012083347b5dd488ff574ba1f87e7d8867a
9e8ede50afd012f36ada2d8af9ccc16357223b2b
/app/src/main/java/com/openxu/libdemo/view/bean/PieBean.java
784491cf0a660e40f91390db50f8cb3336f00725
[]
no_license
openXu/OXAndroid
92e796e630cabeae11c411948f0496f16df9d2f1
87870d74ed18edcdd3c9a4661ef673d6a2508629
refs/heads/master
2021-01-17T12:05:30.237610
2019-03-20T10:09:43
2019-03-20T10:09:43
84,056,482
0
1
null
null
null
null
UTF-8
Java
false
false
644
java
package com.openxu.libdemo.view.bean; /** * autour : openXu * date : 2018/6/8 9:40 * className : PieBean * version : 1.0 * description : 请添加类说明 */ public class PieBean { private float Numner; private String Name; public PieBean() { } public PieBean(float Numner, String Name) { this.Numner = Numner; this.Name = Name; } public float getNumner() { return Numner; } public void setNumner(float numner) { Numner = numner; } public String getName() { return Name; } public void setName(String name) { Name = name; } }
1c62a5926d3074c9125cf8f8a82f1560a3395621
6a6f252b726ef92f67657875104b0993113017eb
/ms-gestion-alumno/src/main/java/pe/edu/galaxy/training/java/sb/ms/gestion/alumnos/controller/commons/ObjectResponse.java
f03711875a218d336eca64bf93b07067557e07b8
[]
no_license
renzoku147/ms-spring-cloud
3d62bc8f2180b64d4784e5102fc1027613c4a32f
215036628f24d8e90f0adec6486d7e40bdb1c94e
refs/heads/master
2023-06-12T04:38:30.828174
2021-07-09T02:12:29
2021-07-09T02:12:29
383,461,635
0
0
null
null
null
null
UTF-8
Java
false
false
232
java
package pe.edu.galaxy.training.java.sb.ms.gestion.alumnos.controller.commons; import lombok.Builder; import lombok.Data; @Data @Builder public class ObjectResponse { private ObjectMessage message; private Object data; }
d9f471d1af7b80308e236e7f4a2d30bdd847a2a8
d410836fc545fce7745d4c2142fa79abdc9f0611
/src/main/java/bandit/ThompsonSampling.java
57b0f8bc2c77c71ddf21a2ead2d04222af54b26b
[]
no_license
takun2s/bandit
038fb30d444e79b0e3f7b2db4943897b97911b10
8a8911422e67322bd5fd8b6d3608ba8855d4c9c0
refs/heads/master
2020-03-11T17:41:48.461565
2018-04-19T09:53:40
2018-04-19T09:53:40
130,154,492
1
0
null
null
null
null
UTF-8
Java
false
false
737
java
package bandit; import org.apache.commons.math3.distribution.BetaDistribution; /** * Created by takun on 17/04/2018. */ public class ThompsonSampling extends AbstractBandit { public ThompsonSampling(int k) { super(k); } public ThompsonSampling(int k, long seed) { super(k, seed); } protected double[] expections() { double x = random.nextDouble() ; double[] y = new double[k] ; for(int i = 0; i < k; i++) { double a = 1 + cumulateScore(i) ; double b = 1 + trial(i) - cumulateScore(i) ; BetaDistribution beta = new BetaDistribution(a, b) ; y[i] = beta.inverseCumulativeProbability(x) ; } return y ; } }
1002c4e118a7201f7feb1d70e24bbc13c7856920
65bd4bee5777fcd9cb1cbebcdc6ece29228c936a
/src/main/java/io/github/cottonmc/witchcraft/block/SpellCircleBlock.java
169f857e80c18d339b7f6cf9642d2b7ba9b26daf
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive" ]
permissive
CottonMC/PracticalWitchcraft
3fb0c2c4d881bb351ca6c72ab673b4da454a05a2
c8b663ed44bd7176da78bfa2b107417f3a5e038c
refs/heads/master
2020-05-07T12:30:44.368747
2020-03-02T00:44:41
2020-03-02T00:44:41
180,507,474
1
1
null
null
null
null
UTF-8
Java
false
false
3,660
java
package io.github.cottonmc.witchcraft.block; import io.github.cottonmc.witchcraft.block.entity.SpellCircleEntity; import io.github.cottonmc.witchcraft.effect.WitchcraftEffects; import io.github.cottonmc.witchcraft.item.WitchcraftItems; import io.github.cottonmc.witchcraft.spell.Spell; import net.fabricmc.fabric.api.block.FabricBlockSettings; import net.fabricmc.fabric.api.util.NbtType; import net.minecraft.block.Block; import net.minecraft.block.BlockEntityProvider; import net.minecraft.block.BlockState; import net.minecraft.block.Material; import net.minecraft.block.entity.BlockEntity; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.BlockView; import net.minecraft.world.World; import net.minecraft.world.explosion.Explosion; import java.util.Random; public class SpellCircleBlock extends Block implements BlockEntityProvider { public SpellCircleBlock() { super(FabricBlockSettings.of(Material.CARPET).noCollision().build()); } @Override public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (!world.isClient && (world.getBlockEntity(pos) instanceof SpellCircleEntity)) { if (world.getBlockTickScheduler().isScheduled(pos, WitchcraftBlocks.SPELL_CIRCLE) || world.getBlockTickScheduler().isTicking(pos, WitchcraftBlocks.SPELL_CIRCLE)) return ActionResult.SUCCESS; ItemStack stack = player.getStackInHand(hand); SpellCircleEntity be = (SpellCircleEntity) world.getBlockEntity(pos); if (be.hasPixie() && stack.getItem() == WitchcraftItems.BROOMSTICK) { if (player.hasStatusEffect(WitchcraftEffects.FIZZLE)) { int level = player.getStatusEffect(WitchcraftEffects.FIZZLE).getAmplifier() + 1; if (world.getRandom().nextInt(20) <= level) { world.createExplosion(null, DamageSource.MAGIC, pos.getX(), pos.getY(), pos.getZ(), 3f, true, Explosion.DestructionType.NONE); world.breakBlock(pos, false); return ActionResult.SUCCESS; } } be.beginSpell(player); } else if (stack.getItem() == WitchcraftItems.BOTTLED_PIXIE) { ItemStack bottle = new ItemStack(Items.GLASS_BOTTLE); if (!player.isCreative()) { if (stack.getCount() == 1) player.setStackInHand(hand, bottle); else if (!player.inventory.insertStack(bottle)) { ItemEntity entity = player.dropItem(bottle, false); world.spawnEntity(entity); } } be.addPixie(); } } return ActionResult.SUCCESS; } @Override public void scheduledTick(BlockState state, ServerWorld world, BlockPos pos, Random rad) { if (world.getBlockEntity(pos) instanceof SpellCircleEntity) { ((SpellCircleEntity)world.getBlockEntity(pos)).performSpell(); } } @Override public void onPlaced(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) { BlockEntity be = world.getBlockEntity(pos); if (be instanceof SpellCircleEntity && stack.getOrCreateTag().contains("Spell", NbtType.COMPOUND)) { SpellCircleEntity circle = (SpellCircleEntity)be; Spell spell = Spell.fromTag(stack.getTag().getCompound("Spell")); circle.setSpell(spell); } } @Override public BlockEntity createBlockEntity(BlockView view) { return new SpellCircleEntity(); } }
7af16953871ba1c844dae58c3d9146b5891dc5ba
ed53c4d93e851d46e963cafb26cb6a3f468dd47c
/extensions/ecs/ecs-weaver/src/arc/ecs/weaver/impl/template/UniEntityLink.java
c53251767e6a14407a428416c7e4f7d5b89e3d8c
[]
no_license
zonesgame/Arc
0a4ea8cf1c44066e85ffd95cfe52eb1ece1488e7
ea8a0be1642befa535fba717e94c4fc03bd6f8a0
refs/heads/main
2023-06-28T04:21:06.146553
2021-07-26T14:02:35
2021-07-26T14:02:35
384,278,749
0
0
null
null
null
null
UTF-8
Java
false
false
750
java
package arc.ecs.weaver.impl.template; import arc.ecs.*; import arc.ecs.link.*; import java.lang.reflect.*; public class UniEntityLink extends Component{ public Entity field; public static class Mutator implements UniFieldMutator{ private Base base; @Override public int read(Component c, Field f){ Entity e = ((UniEntityLink)c).field; return (e != null) ? e.getId() : -1; } @Override public void write(int value, Component c, Field f){ Entity e = (value != -1) ? base.getEntity(value) : null; ((UniEntityLink)c).field = e; } @Override public void setBase(Base base){ this.base = base; } } }
a56839f4499df8d510b52f4c68947b5f6b88d164
b70d13cba15e185ad0c67807b3bac83dc711debf
/app/src/main/java/com/mylaneza/jamarte/entities/Secuencia.java
ae14dfb9efd49819c0a8a1673d9d53669ec4a31e
[]
no_license
mylaneza/jamenarte
60b716719f2c5286a59a59d854888e7066a1d5f4
740dbb8b3d3a9b0271afcb66d5449bb2a9c8ad1e
refs/heads/master
2023-04-02T05:13:33.793267
2021-04-16T02:59:19
2021-04-16T02:59:19
358,452,410
0
0
null
null
null
null
UTF-8
Java
false
false
215
java
package com.mylaneza.jamarte.entities; import java.util.Vector; /** * Created by mylaneza on 08/08/2018. */ public class Secuencia { public long leccion; public long id; public String name; }
9bd832a3ab11ee74334d664d1449c29d5aefc3ee
0772d207e53d266659ae337893d2840b05b2babe
/src/main/java/com/thundermoose/bio/controllers/ExceptionAdvice.java
bc60ac8538dfc22c58c2b0f4a4028c5ef7458575
[]
no_license
monitorjbl/brbbio
839ee5bb34f53e8a19e78c67bb05dfbfb97f50a0
72e3f23c01421d42d4a91fef5792309cf69d7842
refs/heads/master
2023-06-09T05:57:32.837159
2015-01-27T23:08:20
2015-01-27T23:11:56
10,519,619
0
0
null
null
null
null
UTF-8
Java
false
false
1,249
java
package com.thundermoose.bio.controllers; import com.thundermoose.bio.exceptions.UserNotFoundException; import com.thundermoose.bio.model.ExceptionResponse; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.log4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; /** * Created by tayjones on 3/10/14. */ @ControllerAdvice public class ExceptionAdvice { private static final Logger logger = Logger.getLogger(ExceptionAdvice.class); @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public ExceptionResponse handleAllException(Exception ex) { if (ex instanceof UserNotFoundException) { logger.debug(ex.getMessage(), ex); } else { logger.error(ex.getMessage(), ex); } ExceptionResponse r = new ExceptionResponse(); r.setMessage(ex.getMessage()); r.setType(ex.getClass().getCanonicalName()); r.setStacktrace(ExceptionUtils.getFullStackTrace(ex)); return r; } }
a9214cfb757f3c1f59d5a9828b98099b2bc21ae4
7612119fcbc5c951ccd993cce17a08a1b7cbb1bb
/src/java/apiview-java-processor/src/main/java/com/azure/tools/apiview/processor/diagnostics/rules/ConsiderFinalClassDiagnosticRule.java
31b5471a3a9c81c294e297fd177042020615ccd8
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
jitendriyag2/azure-sdk-tools
8248da7c0914a5e2dd638a6caea0c8b746914467
1ea2117fad56bb34cfe1cc5b090a0c58ef7b18c2
refs/heads/master
2022-12-22T20:26:31.856255
2020-09-24T23:41:24
2020-09-24T23:41:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,266
java
package com.azure.tools.apiview.processor.diagnostics.rules; import com.azure.tools.apiview.processor.diagnostics.DiagnosticRule; import com.azure.tools.apiview.processor.model.APIListing; import com.azure.tools.apiview.processor.model.Diagnostic; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Modifier; import static com.azure.tools.apiview.processor.analysers.util.ASTUtils.makeId; import static com.azure.tools.apiview.processor.model.DiagnosticKind.*; public class ConsiderFinalClassDiagnosticRule implements DiagnosticRule { @Override public void scan(final CompilationUnit cu, final APIListing listing) { cu.getTypes().forEach(type -> { if (type.isEnumDeclaration()) return; if (type.hasModifier(Modifier.Keyword.ABSTRACT)) return; if (type.isClassOrInterfaceDeclaration() && type.asClassOrInterfaceDeclaration().isInterface()) return; if (!type.hasModifier(Modifier.Keyword.FINAL)) { listing.addDiagnostic(new Diagnostic( INFO, makeId(type), "Consider making all classes final by default - only make non-final if subclassing is supported.")); } }); } }
bd83ad04990fb3acd5df36ec183575e32bc7894e
689e8a3ccd884c4c9c92975b24c637d2d55b9b1a
/src/main/java/br/com/caelum/ingresso/dao/SessaoDao.java
ecc858a22eda4ffdd946f34298645673266bd2e2
[]
no_license
GIDSC/fj22-ingressos
6e9ed9854b3265e30a27977a6d5988cba56f4e11
5ddf2cc8c8aef905854405a3ff28c22cc0d9dd9b
refs/heads/master
2020-09-04T00:47:07.651323
2019-11-14T00:50:59
2019-11-14T00:50:59
219,621,557
0
0
null
2019-11-05T00:16:55
2019-11-05T00:16:54
null
UTF-8
Java
false
false
971
java
package br.com.caelum.ingresso.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import br.com.caelum.ingresso.model.Filme; import br.com.caelum.ingresso.model.Sala; import br.com.caelum.ingresso.model.Sessao; @Repository public class SessaoDao { @PersistenceContext private EntityManager manager; public void save(Sessao sessao) { manager.persist(sessao); } public List<Sessao> buscaSessoesDaSala(Sala sala) { return manager.createQuery("select s from Sessao s where s.sala = :sala", Sessao.class) .setParameter("sala", sala).getResultList(); } public List<Sessao> buscaSessoesDoFilme(Filme filme) { return manager.createQuery("select s from Sessao s where s.filme = :filme", Sessao.class) .setParameter("filme", filme).getResultList(); } public Sessao findOne(Integer id) { return manager.find(Sessao.class, id); } }
11a7c51104297f5de600ca9718be27e34087e280
b3127d54bfc2cb4e4e4ebe7d6b547f0fb36cf852
/src/main/java/us/kochlabs/tools/life360/Life360Client.java
b9a0bd8774fc6d7e1ebab318159cf46251faa786
[]
no_license
denniskoch/java-life360
e407e6d26346e66569e63bf3b2fc4d02789778b6
f56ec2318cb45d01847c6d784714bcc5607ab3ce
refs/heads/master
2023-04-11T12:02:41.477858
2021-04-24T14:32:28
2021-04-24T14:32:28
359,970,469
0
0
null
null
null
null
UTF-8
Java
false
false
5,974
java
package us.kochlabs.tools.life360; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import us.kochlabs.tools.life360.auth.Bearer; import us.kochlabs.tools.life360.circles.Circle; import us.kochlabs.tools.life360.circles.Circles; import java.io.IOException; import java.util.ArrayList; /** * Life360 Client class */ public class Life360Client { static final String AUTH_CONSTANT = "cFJFcXVnYWJSZXRyZTRFc3RldGhlcnVmcmVQdW1hbUV4dWNyRUh1YzptM2ZydXBSZXRSZXN3ZXJFQ2hBUHJFOTZxYWtFZHI0Vg=="; static final String API_BASE_URL = "https://api.life360.com/v3/"; static final String TOKEN_PATH = "oauth2/token.json"; static final String CIRCLES_PATH = "circles.json"; static final String CIRCLE_PATH = "circles/"; private String username; private String password; private String bearerToken; private HttpClient httpClient; private ObjectMapper objectMapper; /** * * @param username Life360 username * @param password Life 360 password */ public Life360Client(String username, String password) { this.username = username; this.password = password; this.bearerToken = null; this.httpClient = HttpClientBuilder.create().build(); this.objectMapper = new ObjectMapper(); } /** * Authenticates to Life360's API and obtains the bearer token for all future API calls. * * @return The result of the logon process */ public boolean authenticate() { String uri = API_BASE_URL + TOKEN_PATH; HttpPost httpPost = new HttpPost(uri); String authorization = "Basic " + AUTH_CONSTANT; httpPost.addHeader("Authorization",authorization); ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("grant_type", "password")); postParameters.add(new BasicNameValuePair("username", username)); postParameters.add(new BasicNameValuePair("password", password)); try { httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8")); HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity, "UTF-8"); if (response.getStatusLine().getStatusCode() == 200) { Bearer bearer = objectMapper.readValue(responseString, Bearer.class); this.bearerToken = "Bearer " + bearer.access_token; return true; } } catch (ClientProtocolException cpe) { System.out.println(cpe.getMessage()); } catch (ParseException pe) { System.out.println(pe.getMessage()); } catch (JsonProcessingException jpe) { System.out.println(jpe.getMessage()); } catch (IOException ioe) { System.out.println(ioe.getMessage()); } return false; } /** * Performs the HTTP request with given URI, constructs headers for Life360 authentication * * @param uri URI to send the the request to * @return JSON respons string from the request */ public String apiHttpGet(String uri) { try { HttpGet httpGet = new HttpGet(uri); httpGet.addHeader("Authorization", this.bearerToken); HttpResponse response = httpClient.execute(httpGet); HttpEntity responseEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200) { String responseString = EntityUtils.toString(responseEntity, "UTF-8"); return responseString; } else { return null; } } catch (ClientProtocolException cpe) { System.out.println(cpe.getMessage()); } catch (IOException ioe) { System.out.println(ioe.getMessage()); } return null; } /** * Get all Life360 Circles for the account * * @return All circles the subscription is a member/owner of */ public Circles getAllCircles() { String uri = API_BASE_URL + CIRCLES_PATH; String responseString = apiHttpGet(uri); Circles circles = null; if (responseString != null) { //System.out.println(responseString); try { circles = objectMapper.readValue(responseString, Circles.class); } catch (Exception e) { System.out.println(e.getMessage()); } } return circles; } /** * Retrieve a Life360 from the API * * @param circleId * @return Requested Life360 circle */ public Circle getCircleById(String circleId) { String uri = API_BASE_URL + CIRCLE_PATH + circleId; String responseString = apiHttpGet(uri); Circle circle = null; if (responseString != null) { //System.out.println(responseString); try { circle = objectMapper.readValue(responseString, Circle.class); } catch (Exception e) { System.out.println(e.getMessage()); } } return circle; } }
721f5a5fb90c1e99214fee86ac1c3d9504f33f20
23749b673ff50cfb3bd09eb9662715e09da17dc8
/src/main/java/com/citrix/netscaler/nitro/resource/config/cache/cacheobject_args.java
e2bfc0dbb6d3852ec25dda277a01cd23013d8e8a
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
netscaler/nitro
20f0499200478b971f6c11a8f77ab44113bfe1a5
2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4
refs/heads/master
2016-08-04T20:02:53.344531
2013-11-22T04:04:18
2013-11-22T04:04:18
8,279,932
0
0
null
null
null
null
UTF-8
Java
false
false
6,555
java
/* * Copyright (c) 2008-2015 Citrix Systems, Inc. * * 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.citrix.netscaler.nitro.resource.config.cache; /** * Provides additional arguments required for fetching the cacheobject resource. */ public class cacheobject_args { private String url; private Long locator; private Long httpstatus; private String host; private Integer port; private String groupname; private String httpmethod; private String group; private String ignoremarkerobjects; private String includenotreadyobjects; /** * <pre> * URL of the particular object whose details is required. Parameter "host" must be specified along with the URL.<br> Minimum length = 1 * </pre> */ public void set_url(String url) throws Exception{ this.url = url; } /** * <pre> * URL of the particular object whose details is required. Parameter "host" must be specified along with the URL.<br> Minimum length = 1 * </pre> */ public String get_url() throws Exception { return this.url; } /** * <pre> * ID of the cached object. * </pre> */ public void set_locator(long locator) throws Exception { this.locator = new Long(locator); } /** * <pre> * ID of the cached object. * </pre> */ public void set_locator(Long locator) throws Exception{ this.locator = locator; } /** * <pre> * ID of the cached object. * </pre> */ public Long get_locator() throws Exception { return this.locator; } /** * <pre> * HTTP status of the object. * </pre> */ public void set_httpstatus(long httpstatus) throws Exception { this.httpstatus = new Long(httpstatus); } /** * <pre> * HTTP status of the object. * </pre> */ public void set_httpstatus(Long httpstatus) throws Exception{ this.httpstatus = httpstatus; } /** * <pre> * HTTP status of the object. * </pre> */ public Long get_httpstatus() throws Exception { return this.httpstatus; } /** * <pre> * Host name of the object. Parameter "url" must be specified.<br> Minimum length = 1 * </pre> */ public void set_host(String host) throws Exception{ this.host = host; } /** * <pre> * Host name of the object. Parameter "url" must be specified.<br> Minimum length = 1 * </pre> */ public String get_host() throws Exception { return this.host; } /** * <pre> * Host port of the object. You must also set the Host parameter.<br> Default value: 80<br> Minimum value = 1 * </pre> */ public void set_port(int port) throws Exception { this.port = new Integer(port); } /** * <pre> * Host port of the object. You must also set the Host parameter.<br> Default value: 80<br> Minimum value = 1 * </pre> */ public void set_port(Integer port) throws Exception{ this.port = port; } /** * <pre> * Host port of the object. You must also set the Host parameter.<br> Default value: 80<br> Minimum value = 1 * </pre> */ public Integer get_port() throws Exception { return this.port; } /** * <pre> * Name of the content group to which the object belongs. It will display only the objects belonging to the specified content group. You must also set the Host parameter. * </pre> */ public void set_groupname(String groupname) throws Exception{ this.groupname = groupname; } /** * <pre> * Name of the content group to which the object belongs. It will display only the objects belonging to the specified content group. You must also set the Host parameter. * </pre> */ public String get_groupname() throws Exception { return this.groupname; } /** * <pre> * HTTP request method that caused the object to be stored.<br> Default value: GET<br> Possible values = GET, POST * </pre> */ public void set_httpmethod(String httpmethod) throws Exception{ this.httpmethod = httpmethod; } /** * <pre> * HTTP request method that caused the object to be stored.<br> Default value: GET<br> Possible values = GET, POST * </pre> */ public String get_httpmethod() throws Exception { return this.httpmethod; } /** * <pre> * Name of the content group whose objects should be listed. * </pre> */ public void set_group(String group) throws Exception{ this.group = group; } /** * <pre> * Name of the content group whose objects should be listed. * </pre> */ public String get_group() throws Exception { return this.group; } /** * <pre> * Ignore marker objects. Marker objects are created when a response exceeds the maximum or minimum response size for the content group or has not yet received the minimum number of hits for the content group.<br> Possible values = ON, OFF * </pre> */ public void set_ignoremarkerobjects(String ignoremarkerobjects) throws Exception{ this.ignoremarkerobjects = ignoremarkerobjects; } /** * <pre> * Ignore marker objects. Marker objects are created when a response exceeds the maximum or minimum response size for the content group or has not yet received the minimum number of hits for the content group.<br> Possible values = ON, OFF * </pre> */ public String get_ignoremarkerobjects() throws Exception { return this.ignoremarkerobjects; } /** * <pre> * Include responses that have not yet reached a minimum number of hits before being cached.<br> Possible values = ON, OFF * </pre> */ public void set_includenotreadyobjects(String includenotreadyobjects) throws Exception{ this.includenotreadyobjects = includenotreadyobjects; } /** * <pre> * Include responses that have not yet reached a minimum number of hits before being cached.<br> Possible values = ON, OFF * </pre> */ public String get_includenotreadyobjects() throws Exception { return this.includenotreadyobjects; } public static class includenotreadyobjectsEnum { public static final String ON = "ON"; public static final String OFF = "OFF"; } public static class httpmethodEnum { public static final String GET = "GET"; public static final String POST = "POST"; } public static class ignoremarkerobjectsEnum { public static final String ON = "ON"; public static final String OFF = "OFF"; } }
4ac5e88dc149a725ecab50360a967b25c7c4e82c
1cbdb6ae2cc99aaae136f64c14a9e0f368b872db
/src/com/eric/dao/AdminDAO.java
4ba9f250a86885d05d60caa0987b97059fedc710
[ "Apache-2.0" ]
permissive
zhouhh2017/termonline
09b799c967b00b2469a9e72d3353b2ad281e1ce4
849e75d443f89038cd89b4e15b67f256071d8cc7
refs/heads/master
2021-01-23T12:57:54.035683
2017-06-03T01:33:23
2017-06-03T01:33:23
93,214,032
2
0
null
null
null
null
UTF-8
Java
false
false
6,551
java
package com.eric.dao; import java.util.List; import javax.annotation.Resource; import org.hibernate.Session; import org.springframework.orm.hibernate4.HibernateTemplate; import org.springframework.stereotype.Component; import com.eric.model.Admin; import com.eric.model.Dictionary; import com.eric.model.Item; import com.eric.model.User; import com.eric.model.Word; @Component public class AdminDAO { private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } @Resource public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } //��֤��¼ public boolean loginValid(Admin admin) { // TODO Auto-generated method stub String adminName = admin.getAdminname(); String password = admin.getPassword(); List<Admin> result = (List<Admin>)(hibernateTemplate .find("from t_admin where adminname = ? and password = ?", new String[]{adminName,password})); if(result.size()>0){ return true; }else{ return false; } } //�´ʲ�ѯ public List<String[]> searchNewWord() { // TODO Auto-generated method stub Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); return (List<String[]>)session.createSQLQuery("select name,sum(times) as times from t_newword where status =0 group by name").list(); } public List<String[]> searchNewWord(int page, int rows) { // TODO Auto-generated method stub Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); return (List<String[]>)session.createSQLQuery( "select name,sum(times) as times from t_newword where status =0 group by name order by times desc limit " + rows*(page-1) + "," + rows).list(); } public int getNewWordTotal() { Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); return session.createSQLQuery( "select name,sum(times) as times from t_newword where status =0 group by name order by times desc").list().size(); } public void delNewItem(String ids) { // TODO Auto-generated method stub Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); String[] tmp = ids.split(","); for (int i = 0; i < tmp.length; i++) { session.createSQLQuery( "update t_newword set status = 1 where name = " + "\"" + tmp[i] + "\"").executeUpdate(); } } public void insertOneItem(Item item) { // TODO Auto-generated method stub hibernateTemplate.save(item); } public void changeNewWordStatus(String itemName) { // TODO Auto-generated method stub Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); session.createSQLQuery( "update t_newword set status = 1 where name = " + "\"" + itemName + "\"").executeUpdate(); } //�õ��û��б� public List<User> getUserList(int page, int rows) { // TODO Auto-generated method stub Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); return session.createQuery("from t_user").setFirstResult((page-1)*rows).setMaxResults(rows).list(); } public int getUserTotal() { // TODO Auto-generated method stub return hibernateTemplate.find("from t_user").size(); } public void delUser(String ids) { // TODO Auto-generated method stub Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); String[] tmp = ids.split(","); for (int i = 0; i < tmp.length; i++) { session.createSQLQuery( "delete from t_user where id = " + "\"" + tmp[i] + "\"").executeUpdate(); } } /*public void updateNewWord(String userName) { // TODO Auto-generated method stub String name = userName; Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); session.createSQLQuery( "update t_newword set userName = " + name +" where userName = " + "\"" + name + "\"").executeUpdate(); }*/ public List<String[]> searchHotWord(int page, int rows) { Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); return (List<String[]>)session.createSQLQuery( "select id,name,times from t_hotword order by times desc limit " + rows*(page-1) + "," + rows).list(); } public int getHotWordTotal() { // TODO Auto-generated method stub return hibernateTemplate.find("from t_hotword").size(); } // 词汇列表 public List<Word> getWordList(int page, int rows) { Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); return session.createQuery("from t_word").setFirstResult((page-1)*rows).setMaxResults(rows).list(); } // 词汇统计量 public int getWordTotal() { // TODO Auto-generated method stub return hibernateTemplate.find("from t_word").size(); } // 添加词汇 public void add(Word w) { // TODO Auto-generated method stub hibernateTemplate.save(w); } // 修改词汇 public void update(Word word) { // TODO Auto-generated method stub hibernateTemplate.update(word); } // 删除词汇 public void wordDel(String ids) { // TODO Auto-generated method stub Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); String[] tmp = ids.split(","); for (int i = 0; i < tmp.length; i++) { session.createSQLQuery( "delete from t_word where id = " + "\"" + tmp[i] + "\"").executeUpdate(); } } // 添加字典 public void add(Dictionary d) { // TODO Auto-generated method stub hibernateTemplate.save(d); } // 修改字典 public void update(Dictionary dic) { // TODO Auto-generated method stub hibernateTemplate.update(dic); } // 删除字典 public void dicDel(String ids) { // TODO Auto-generated method stub Session session = hibernateTemplate.getSessionFactory() .getCurrentSession(); String[] tmp = ids.split(","); for (int i = 0; i < tmp.length; i++) { session.createSQLQuery( "delete from t_dictionary where id = " + "\"" + tmp[i] + "\"") .executeUpdate(); } } // 字典列表 public List<Dictionary> getDicList(int page, int rows) { Session session = hibernateTemplate.getSessionFactory().getCurrentSession(); return session.createQuery("from t_dictionary").setFirstResult((page-1)*rows).setMaxResults(rows).list(); } // 字典统计量 public int getDicTotal() { // TODO Auto-generated method stub return hibernateTemplate.find("from t_dictionary").size(); } }
53d07c3516f2164d5729115045d21c2ad1075d93
e6cc873e4fc15f819fccb3dd9a37edc07691fb6f
/E-com/src/main/java/com/comtrade/entiteti/Stavke.java
3f40c892accf47b1c8c88d66ee097e2620ba43e3
[]
no_license
ztrampic/E-comm
d98cbd4e84e09988fde9a83a22779561965e0c7d
3714170db1dc8dcd3e642bd30e29aee1930d9e63
refs/heads/master
2021-11-13T04:48:30.749820
2021-10-30T12:59:06
2021-10-30T12:59:06
196,863,000
0
0
null
null
null
null
UTF-8
Java
false
false
1,203
java
package com.comtrade.entiteti; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Stavke { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private int kolicina; private int brStavke; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_racun") private Racun racun; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_proizvoda") private Proizvod proizvod; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getKolicina() { return kolicina; } public void setKolicina(int kolicina) { this.kolicina = kolicina; } public int getBrStavke() { return brStavke; } public void setBrStavke(int brStavke) { this.brStavke = brStavke; } public Racun getRacun() { return racun; } public void setRacun(Racun racun) { this.racun = racun; } public Proizvod getProizvod() { return proizvod; } public void setProizvod(Proizvod proizvod) { this.proizvod = proizvod; } }
b79f481d9d45b989f2ec0affa9a0f7f73f5a73cd
8b41fc644c8716ff9634927fadf15a8f20dcec01
/src/main/java/util/ListIterator.java
9eb7a1a71dd3e926e02e742ce790ca81c99f56cd
[]
no_license
frametianhe/java-1.8
c1791a6a3e460b1f2f1a9f974947f1413a8c5869
e4ccc5ec38f0c70b8fbe979bc49cbef9cdb2327f
refs/heads/master
2021-08-06T01:05:24.756325
2019-12-04T10:38:04
2019-12-04T10:38:04
225,837,910
0
0
null
2020-10-13T17:57:47
2019-12-04T10:15:24
Java
UTF-8
Java
false
false
10,098
java
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.util; /** * An iterator for lists that allows the programmer * to traverse the list in either direction, modify * the list during iteration, and obtain the iterator's * current position in the list. A {@code ListIterator} * has no current element; its <I>cursor position</I> always * lies between the element that would be returned by a call * to {@code previous()} and the element that would be * returned by a call to {@code next()}. * An iterator for a list of length {@code n} has {@code n+1} possible * cursor positions, as illustrated by the carets ({@code ^}) below: * <PRE> * Element(0) Element(1) Element(2) ... Element(n-1) * cursor positions: ^ ^ ^ ^ ^ * </PRE> * Note that the {@link #remove} and {@link #set(Object)} methods are * <i>not</i> defined in terms of the cursor position; they are defined to * operate on the last element returned by a call to {@link #next} or * {@link #previous()}. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @author Josh Bloch * @see Collection * @see List * @see Iterator * @see Enumeration * @see List#listIterator() * @since 1.2 * 用于列表的迭代器,它允许程序员向任意方向遍历列表,在迭代期间修改列表,并获取列表中的迭代器当前位置。ListIterator无当前元素;它的光标位置总是位于调用previous()返回的元素和调用next()返回的元素之间。迭代器的长度n n + 1可能光标位置,在图中以克拉(^)如下: 元素元素(0)(1)(2)……元素(n - 1) 光标位置:^ ^ ^ ^ ^ 注意,删除和设置(对象)方法没有根据光标位置定义;它们被定义为对通过调用next或previous()返回的最后一个元素进行操作。 这个接口是Java集合框架的一个成员。 */ public interface ListIterator<E> extends Iterator<E> { // Query Operations /** * Returns {@code true} if this list iterator has more elements when * traversing the list in the forward direction. (In other words, * returns {@code true} if {@link #next} would return an element rather * than throwing an exception.)如果此列表迭代器在正向遍历列表时具有更多元素,则返回true。(换句话说,如果next返回一个元素而不是抛出一个异常,则返回true。) * * @return {@code true} if the list iterator has more elements when * traversing the list in the forward direction */ boolean hasNext(); /** * Returns the next element in the list and advances the cursor position. * This method may be called repeatedly to iterate through the list, * or intermixed with calls to {@link #previous} to go back and forth. * (Note that alternating calls to {@code next} and {@code previous} * will return the same element repeatedly.)返回列表中的下一个元素并推进光标位置。这个方法可以被反复调用以遍历列表,或者与前一个方法的调用混合,以便来回执行。(注意,对next和previous的交替调用将重复返回相同的元素。) * * @return the next element in the list * @throws NoSuchElementException if the iteration has no next element */ E next(); /** * Returns {@code true} if this list iterator has more elements when * traversing the list in the reverse direction. (In other words, * returns {@code true} if {@link #previous} would return an element * rather than throwing an exception.)如果这个列表迭代器在反方向遍历列表时具有更多元素,则返回true。(换句话说,如果先前返回的是元素而不是抛出异常,则返回true。) * * @return {@code true} if the list iterator has more elements when * traversing the list in the reverse direction */ boolean hasPrevious(); /** * Returns the previous element in the list and moves the cursor * position backwards. This method may be called repeatedly to * iterate through the list backwards, or intermixed with calls to * {@link #next} to go back and forth. (Note that alternating calls * to {@code next} and {@code previous} will return the same * element repeatedly.)返回列表中的前一个元素并将光标位置向后移动。可以反复调用此方法以向后遍历列表,或与相邻的调用相互混合。(注意,对next和previous的交替调用将重复返回相同的元素。) * * @return the previous element in the list * @throws NoSuchElementException if the iteration has no previous * element */ E previous(); /** * Returns the index of the element that would be returned by a * subsequent call to {@link #next}. (Returns list size if the list * iterator is at the end of the list.)返回元素的索引,该索引将由后续对next的调用返回。(如果列表迭代器位于列表末尾,则返回列表大小。) * * @return the index of the element that would be returned by a * subsequent call to {@code next}, or list size if the list * iterator is at the end of the list */ int nextIndex(); /** * Returns the index of the element that would be returned by a * subsequent call to {@link #previous}. (Returns -1 if the list * iterator is at the beginning of the list.)返回元素的索引,该索引将由后续对previous的调用返回。(如果列表迭代器位于列表的开头,则返回-1。) * * @return the index of the element that would be returned by a * subsequent call to {@code previous}, or -1 if the list * iterator is at the beginning of the list */ int previousIndex(); // Modification Operations /** * Removes from the list the last element that was returned by {@link * #next} or {@link #previous} (optional operation). This call can * only be made once per call to {@code next} or {@code previous}. * It can be made only if {@link #add} has not been * called after the last call to {@code next} or {@code previous}.从列表中移除下一个或之前返回的元素(可选操作)。这个调用只能在下一次调用或之前调用一次。只有在对next或previous的最后一次调用之后没有调用add时,才可以进行此操作。 * * @throws UnsupportedOperationException if the {@code remove} * operation is not supported by this list iterator * @throws IllegalStateException if neither {@code next} nor * {@code previous} have been called, or {@code remove} or * {@code add} have been called after the last call to * {@code next} or {@code previous} */ void remove(); /** * Replaces the last element returned by {@link #next} or * {@link #previous} with the specified element (optional operation). * This call can be made only if neither {@link #remove} nor {@link * #add} have been called after the last call to {@code next} or * {@code previous}.用指定的元素(可选操作)替换next或previous返回的最后一个元素。只有在对next或previous的最后一次调用之后没有调用remove或add,才可以进行此调用。 * * @param e the element with which to replace the last element returned by * {@code next} or {@code previous} * @throws UnsupportedOperationException if the {@code set} operation * is not supported by this list iterator * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list * @throws IllegalStateException if neither {@code next} nor * {@code previous} have been called, or {@code remove} or * {@code add} have been called after the last call to * {@code next} or {@code previous} */ void set(E e); /** * Inserts the specified element into the list (optional operation). * The element is inserted immediately before the element that * would be returned by {@link #next}, if any, and after the element * that would be returned by {@link #previous}, if any. (If the * list contains no elements, the new element becomes the sole element * on the list.) The new element is inserted before the implicit * cursor: a subsequent call to {@code next} would be unaffected, and a * subsequent call to {@code previous} would return the new element. * (This call increases by one the value that would be returned by a * call to {@code nextIndex} or {@code previousIndex}.) * * @param e the element to insert * @throws UnsupportedOperationException if the {@code add} method is * not supported by this list iterator * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws IllegalArgumentException if some aspect of this element * prevents it from being added to this list * 将指定的元素插入到列表中(可选操作)。元素会在next(如果有的话)返回的元素之前以及之前(如果有的话)返回的元素之后插入。(如果列表不包含元素,则新元素将成为列表中的唯一元素。)在隐式游标之前插入新元素:对next的后续调用不受影响,随后调用之前的调用将返回新元素。(这个调用增加了一个调用nextIndex或previousIndex的值。) */ void add(E e); }
7ee336d62f40ec1365c01050e51c08d5ed6a25b7
12b24632ef98ca6bd68f1e85a9b1ffdeff24022d
/SunFlowerJava/app/src/main/java/com/example/sunflower_java/adapters/BindingAdapters.java
e0cdceff58587b00324b4049500f6c6c5f996d49
[]
no_license
han1254/Sunflower-Java
04f4a6a575b0bb71bc0350aac6f15cd31ce550ee
1c61a806f097be003747d2b13fff730fb75a666a
refs/heads/master
2020-12-14T12:39:49.833591
2020-01-18T14:33:51
2020-01-18T14:33:51
234,746,936
0
0
null
null
null
null
UTF-8
Java
false
false
405
java
package com.example.sunflower_java.adapters; import android.view.View; import androidx.databinding.BindingAdapter; /** * Time:2020/1/14 21:42 * Author: han1254 * Email: [email protected] * Function: */ public class BindingAdapters { @BindingAdapter("isGone") public static void bindIsGone(View view, boolean isGone) { view.setVisibility(isGone ? View.GONE : View.VISIBLE); } }
28d39c6d5b15717af14ed183465013ae97fccd0e
0270874c82ae338d279f62b83692acddd38dc554
/src/main/java/com/lzk/spring/boot/config/MyBatisConfig.java
c109ff3063c55c70374e0a210fddb84753c66c3e
[]
no_license
TheHelloWorld/SpringBootDemo
0a4ed5a7c9de716c2963c19a81b89f64c90c98f2
33d1ee2b600b37db0af67173209ef4aa96cdb99b
refs/heads/master
2021-08-28T05:31:09.937838
2017-12-11T09:23:08
2017-12-11T09:23:08
113,833,767
0
0
null
null
null
null
UTF-8
Java
false
false
1,917
java
package com.lzk.spring.boot.config; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; /** * @author lzk * */ @Configuration //加上这个注解,使得支持事务 @EnableTransactionManagement public class MyBatisConfig implements TransactionManagementConfigurer { @Autowired private DataSource dataSource; @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactoryBean() { try { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); bean.setDataSource(dataSource); bean.setMapperLocations(resolver.getResources("classpath:mybatis-contexts/*.xml")); return bean.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Bean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } }
bf75b1ef1554a13a8cdb1585891262ace5a2a264
416ba65d73e1da2a46963235c5c945ad172168f3
/web/src/main/java/com/zrlog/web/controller/BaseController.java
bf1c52bd3046822d54628435631c678569b7e534
[ "Apache-2.0" ]
permissive
dragcszh/java
b2cf76c6bec8f02c17884c5a81ed114163320d11
a43374b00a64173abc7f4eedde75a083bca31f44
refs/heads/main
2022-12-27T13:49:10.992372
2020-10-04T07:15:17
2020-10-04T07:15:17
301,061,785
0
0
null
null
null
null
UTF-8
Java
false
false
3,577
java
package com.zrlog.web.controller; import com.google.gson.Gson; import com.jfinal.core.Controller; import com.jfinal.kit.PathKit; import com.zrlog.common.Constants; import com.zrlog.common.request.PageableRequest; import com.zrlog.web.interceptor.TemplateHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.Map; /** * 提供一些基础的工具类,方便其子类调用 */ public class BaseController extends Controller { private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class); /** * 获取主题的相对于程序的路径,当Cookie中有值的情况下,优先使用Cookie里面的数据(仅当主题存在的情况下,否则返回默认的主题), * * @return */ public String getTemplatePath() { String templatePath = Constants.WEB_SITE.get("template").toString(); templatePath = templatePath == null ? Constants.DEFAULT_TEMPLATE_PATH : templatePath; String previewTheme = TemplateHelper.getTemplatePathByCookie(getRequest().getCookies()); if (previewTheme != null) { templatePath = previewTheme; } if (!new File(PathKit.getWebRootPath() + templatePath).exists()) { templatePath = Constants.DEFAULT_TEMPLATE_PATH; } return templatePath; } public Integer getDefaultRows() { return Integer.valueOf(Constants.WEB_SITE.get("rows").toString()); } public boolean isNotNullOrNotEmptyStr(Object... args) { for (Object arg : args) { if (arg == null || "".equals(arg)) { return false; } } return true; } /** * 用于转化 GET 的中文乱码 * * @param param * @return */ public String convertRequestParam(String param) { if (param != null) { //如果可以正常读取到中文的情况,直接跳过转换 if (containsHanScript(param)) { return param; } try { return URLDecoder.decode(new String(param.getBytes(StandardCharsets.ISO_8859_1)), "UTF-8"); } catch (UnsupportedEncodingException e) { LOGGER.error("request convert to UTF-8 error ", e); } } return ""; } private static boolean containsHanScript(String s) { return s.codePoints().anyMatch( codepoint -> Character.UnicodeScript.of(codepoint) == Character.UnicodeScript.HAN); } public void fullTemplateSetting(Object jsonStr) { if (isNotNullOrNotEmptyStr(jsonStr)) { Map<String, Object> res = getAttr("_res"); res.putAll(new Gson().fromJson(jsonStr.toString(), Map.class)); } } public void fullTemplateSetting() { Object jsonStr = Constants.WEB_SITE.get(getTemplatePath() + Constants.TEMPLATE_CONFIG_SUFFIX); fullTemplateSetting(jsonStr); } /** * 封装Jqgrid的分页参数 * * @return */ public PageableRequest getPageable() { PageableRequest pageableRequest = new PageableRequest(); pageableRequest.setRows(getParaToInt("rows", 10)); pageableRequest.setSort(getPara("sidx")); pageableRequest.setOrder(getPara("sord")); pageableRequest.setPage(getParaToInt("page", 1)); return pageableRequest; } }
a0b5c877db0d0df78cd8bfcc810c6866601f6798
16d92a044f4ad63c6ac0c0d1f4d279abf161e607
/SummerWinter Coding(2019)/멀쩡한 사각형/Solution.java
a8ae5b2e00db2a63d458d6ebdc1f2d7148d54616
[]
no_license
nh0317/Programers
6c94e9e32c1217e5f092c4b5f6e1f67d42bae0c5
c6dccc879a8b70c77278d6be1d3c31b00fa16253
refs/heads/main
2023-03-16T22:59:08.206584
2021-03-05T15:21:21
2021-03-05T15:21:21
325,028,973
0
0
null
null
null
null
UTF-8
Java
false
false
630
java
import java.util.*; class Solution { public long solution(int w, int h) { long total=(long)w*h; int n=0; //최대 공약수 n 구하기 for(int i=1;i<=Math.min(w,h);i++){ if(w%i==0 && h%i==0){ n=i; } } //w*h을 같은 비율로 최대한 축소한 직사각형에서 //대각선이 지나는 블록의 수 long minRemove= w/n + h/n -1; return total-(long)minRemove*n; } } /* COMMENT 동일한 폴더의 COMEMNT.hwp 참고 (표를 첨부하기 위해 한글로 작성함) */
d884de91ea597ef3c43a598735f48941d30a6f05
efa72336b8246b53b0469ee338ac8c96901c8e5b
/zookeeper/src/main/java/com/kaka/jtest/zookeeper/zkclient/ZooKeeperTest.java
8cdc951045f1c17c094b21b4b0a15b03f9263af7
[]
no_license
jkaka/jtest
3b31cfc8c6fd170963d07ba72a759c2d76429d1f
07e901b2a7814ed62164f3dd61d398c42c60677d
refs/heads/master
2022-12-22T11:27:41.536904
2020-04-13T06:33:01
2020-04-13T06:33:01
133,806,729
1
0
null
2022-12-16T00:42:41
2018-05-17T11:57:15
Java
UTF-8
Java
false
false
1,518
java
package com.kaka.jtest.zookeeper.zkclient; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.junit.Before; import org.junit.Test; import java.util.List; /** * zookeeper原生api * 只能监听一次 * * @author jsk * @Date 2019/3/1 15:55 */ public class ZooKeeperTest { private String zkUrl = "localhost:2181"; private int sessionTimeout = 20000; private int connectTimeout = 20000; ZooKeeper zkClient = null; @Before public void init() throws Exception { zkClient = new ZooKeeper(zkUrl, sessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { //收到事件通知后的回调函数(应该是我们自己的事件处理逻辑) System.out.println(event.getType() + "----" + event.getPath()); try { zkClient.getChildren("/", true);//再次触发监听 } catch (Exception e) { } } }); } /** * 获取子节点 * * @throwsException */ @Test public void getChildren() throws Exception { List<String> children = zkClient.getChildren("/", true); for (String child : children) { System.out.println(child); } // Thread.sleep(Long.MAX_VALUE);//让程序一直运行,在CRT终端里 ls / watch ;create /appe www ;观察控制台打印情况 } }
8df4cf2b363b99deca23a0cfce79dda16e7cc7b9
2e84c611a7443189d2225d6edb77ca8a7c1f2854
/src/main/java/ua/lviv/lgs/utils/ConnectionUtils.java
d8f30cdcbe067901de984838decbcdfeaa706475
[]
no_license
pavlivmykola/Java_Advanced_lesson10
f4c78a52e0367d963451f30cd9fadd69ee341ae2
ab029116b76de87f5380c6212dd59a6a1f979c18
refs/heads/master
2020-04-29T05:53:18.923168
2019-03-15T22:23:55
2019-03-15T22:23:55
175,897,959
0
0
null
null
null
null
UTF-8
Java
false
false
901
java
package ua.lviv.lgs.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.apache.log4j.xml.DOMConfigurator; import ua.lviv.lgs.service.UsersService; public class ConnectionUtils { private static String USER_NAME = "root"; private static String USER_PASSWORD = "gfhfdjp"; private static String URL = "jdbc:mysql://localhost:3306/project1?useLegacyDatetimeCode=false&serverTimezone=UTC"; public static Connection openConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { java.net.URL u = UsersService.class.getClassLoader().getResource("ua/lviv/lgs/logger/loggerConfig.xml"); DOMConfigurator.configure("loggerConfig.xml"); Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); return DriverManager.getConnection(URL, USER_NAME, USER_PASSWORD); } }
528028043bad879cf6d6c5e58eff1a6107599d3f
3df27b037c878b7d980b5c068d3663682c09b0b3
/src/com/jbf/workflow/dao/SysWorkflowTaskPageUrlDao.java
6cd8c099d7080baeb715a7fe354c5541d22567ae
[]
no_license
shinow/tjec
82fbd67886bc1f60c63af3e6054d1e4c16df2a0d
0b2f4de2eda13acf351dfc04faceea508c9dd4b0
refs/heads/master
2021-09-24T15:45:42.212349
2018-10-11T06:13:55
2018-10-11T06:13:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
797
java
/************************************************************ * 类名:SysWorkflowTaskPageUrl * * 类别:Dao * 功能:任务对应的处理页面Dao * * Ver 変更日 部门 担当者 変更内容 * ────────────────────────────────────────────── * V1.00 2014-07-23 CFIT-PG HYF 初版 * * Copyright (c) 2014 CFIT-Weifang Company All Rights Reserved. ************************************************************/ package com.jbf.workflow.dao; import com.jbf.common.dao.IGenericDao; import com.jbf.workflow.po.SysWorkflowTaskPageUrl; public interface SysWorkflowTaskPageUrlDao extends IGenericDao<SysWorkflowTaskPageUrl, Long> { }
[ "lin521lh" ]
lin521lh
fddf32e57cb10d44c68a2dab458d6fda297e8238
a4696b3db18e3ed943fe00c1ba7fb38086c28b30
/app/src/main/java/br/com/aluras/algum/data/AlgumContract.java
16f2226a40c64a10a66e7a0d11385548d08331b9
[]
no_license
aluras/Algum
2a0da310bd1cf429406a00cf6a009968ff6fbf68
e6e691e543c3c7ff30502b625a70218fbdc5be47
refs/heads/master
2016-08-12T05:51:04.363839
2015-12-30T14:44:36
2015-12-30T14:44:36
35,623,334
0
0
null
null
null
null
UTF-8
Java
false
false
2,788
java
package br.com.aluras.algum.data; import android.content.ContentResolver; import android.content.ContentUris; import android.net.Uri; import android.provider.BaseColumns; import android.text.format.Time; public class AlgumContract { // The "Content authority" is a name for the entire content provider, similar to the // relationship between a domain name and its website. A convenient string to use for the // content authority is the package name for the app, which is guaranteed to be unique on the // device. public static final String CONTENT_AUTHORITY = "br.com.aluras.algum"; // Use CONTENT_AUTHORITY to create the base of all URI's which apps will use to contact // the content provider. public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); // Possible paths (appended to base content URI for possible URI's) // For instance, content://com.example.android.sunshine.app/weather/ is a valid path for // looking at weather data. content://com.example.android.sunshine.app/givemeroot/ will fail, // as the ContentProvider hasn't been given any information on what to do with "givemeroot". // At least, let's hope not. Don't be that dev, reader. Don't be that dev. public static final String PATH_CONTA = "conta"; public static final String PATH_LANCAMENTOS = "lancamentos"; // To make it easy to query for the exact date, we normalize all dates that go into // the database to the start of the the Julian day at UTC. public static long normalizeDate(long startDate) { // normalize the start date to the beginning of the (UTC) day Time time = new Time(); time.set(startDate); int julianDay = Time.getJulianDay(startDate, time.gmtoff); return time.setJulianDay(julianDay); } /* Inner class that defines the table contents of the location table Students: This is where you will add the strings. (Similar to what has been done for WeatherEntry) */ public static final class ContaEntry implements BaseColumns{ public static final String TABLE_NAME = "contas"; public static final String COLUMN_NOME = "nome"; public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_CONTA).build(); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CONTA; public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CONTA; public static Uri buildContaUri(long id) { return ContentUris.withAppendedId(CONTENT_URI, id); } } }
2a74df8b914420623ee0489ea6ffd23578f42475
3a165d9594c3fdeb4b7b8bc54a478ad453cfe180
/app/src/main/java/com/android/frkrny/teamworkpro/custom/RoundedDrawable.java
7055f84e21246efa5b5d6b154485a52ab66deeac
[]
no_license
frank-rooney/teamworkpro
bcd63064c750bfdc93257a53e685ff204d7a652f
6c585bf4293d40dfd256e0c8171949bdbaf1aa88
refs/heads/master
2021-01-16T00:03:16.889333
2017-08-13T20:15:05
2017-08-13T20:15:05
99,951,114
0
0
null
null
null
null
UTF-8
Java
false
false
12,332
java
package com.android.frkrny.teamworkpro.custom; import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.widget.ImageView; /** * Credit below: * https://github.com/vinc3m1/RoundedImageView */ class RoundedDrawable extends Drawable { private static final String TAG = "RoundedDrawable"; static final int DEFAULT_BORDER_COLOR = Color.BLACK; private final RectF mBounds = new RectF(); private final RectF mDrawableRect = new RectF(); private final RectF mBitmapRect = new RectF(); private final BitmapShader mBitmapShader; private final Paint mBitmapPaint; private final int mBitmapWidth; private final int mBitmapHeight; private final RectF mBorderRect = new RectF(); private final Paint mBorderPaint; private final Matrix mShaderMatrix = new Matrix(); private float mCornerRadius = 0; private boolean mOval = false; private float mBorderWidth = 0; private ColorStateList mBorderColor = ColorStateList.valueOf(DEFAULT_BORDER_COLOR); private ImageView.ScaleType mScaleType = ImageView.ScaleType.FIT_CENTER; private RoundedDrawable(Bitmap bitmap) { mBitmapWidth = bitmap.getWidth(); mBitmapHeight = bitmap.getHeight(); mBitmapRect.set(0, 0, mBitmapWidth, mBitmapHeight); mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mBitmapShader.setLocalMatrix(mShaderMatrix); mBitmapPaint = new Paint(); mBitmapPaint.setStyle(Paint.Style.FILL); mBitmapPaint.setAntiAlias(true); mBitmapPaint.setShader(mBitmapShader); mBorderPaint = new Paint(); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setAntiAlias(true); mBorderPaint.setColor(mBorderColor.getColorForState(getState(), DEFAULT_BORDER_COLOR)); mBorderPaint.setStrokeWidth(mBorderWidth); } @Nullable static RoundedDrawable fromBitmap(Bitmap bitmap) { if (bitmap != null) { return new RoundedDrawable(bitmap); } else { return null; } } private static Drawable fromDrawable(Drawable drawable) { if (drawable != null) { if (drawable instanceof RoundedDrawable) { // just return if it's already a RoundedDrawable return drawable; } else if (drawable instanceof LayerDrawable) { LayerDrawable ld = (LayerDrawable) drawable; int num = ld.getNumberOfLayers(); // loop through layers to and change to RoundedDrawables if possible for (int i = 0; i < num; i++) { Drawable d = ld.getDrawable(i); ld.setDrawableByLayerId(ld.getId(i), fromDrawable(d)); } return ld; } // try to get a bitmap from the drawable and Bitmap bm = drawableToBitmap(drawable); if (bm != null) { return new RoundedDrawable(bm); } else { Log.w(TAG, "Failed to create bitmap from drawable!"); } } return drawable; } private static Bitmap drawableToBitmap(Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } Bitmap bitmap; int width = Math.max(drawable.getIntrinsicWidth(), 1); int height = Math.max(drawable.getIntrinsicHeight(), 1); try { bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); } catch (Exception e) { e.printStackTrace(); bitmap = null; } return bitmap; } @Override public boolean isStateful() { return mBorderColor.isStateful(); } @Override protected boolean onStateChange(int[] state) { int newColor = mBorderColor.getColorForState(state, 0); if (mBorderPaint.getColor() != newColor) { mBorderPaint.setColor(newColor); return true; } else { return super.onStateChange(state); } } private void updateShaderMatrix() { float scale; float dx; float dy; switch (mScaleType) { case CENTER: mBorderRect.set(mBounds); mBorderRect.inset((mBorderWidth) / 2, (mBorderWidth) / 2); mShaderMatrix.set(null); mShaderMatrix.setTranslate((int) ((mBorderRect.width() - mBitmapWidth) * 0.5f + 0.5f), (int) ((mBorderRect.height() - mBitmapHeight) * 0.5f + 0.5f)); break; case CENTER_CROP: mBorderRect.set(mBounds); mBorderRect.inset((mBorderWidth) / 2, (mBorderWidth) / 2); mShaderMatrix.set(null); dx = 0; dy = 0; if (mBitmapWidth * mBorderRect.height() > mBorderRect.width() * mBitmapHeight) { scale = mBorderRect.height() / (float) mBitmapHeight; dx = (mBorderRect.width() - mBitmapWidth * scale) * 0.5f; } else { scale = mBorderRect.width() / (float) mBitmapWidth; dy = (mBorderRect.height() - mBitmapHeight * scale) * 0.5f; } mShaderMatrix.setScale(scale, scale); mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth, (int) (dy + 0.5f) + mBorderWidth); break; case CENTER_INSIDE: mShaderMatrix.set(null); if (mBitmapWidth <= mBounds.width() && mBitmapHeight <= mBounds.height()) { scale = 1.0f; } else { scale = Math.min(mBounds.width() / (float) mBitmapWidth, mBounds.height() / (float) mBitmapHeight); } dx = (int) ((mBounds.width() - mBitmapWidth * scale) * 0.5f + 0.5f); dy = (int) ((mBounds.height() - mBitmapHeight * scale) * 0.5f + 0.5f); mShaderMatrix.setScale(scale, scale); mShaderMatrix.postTranslate(dx, dy); mBorderRect.set(mBitmapRect); mShaderMatrix.mapRect(mBorderRect); mBorderRect.inset((mBorderWidth) / 2, (mBorderWidth) / 2); mShaderMatrix.setRectToRect(mBitmapRect, mBorderRect, Matrix.ScaleToFit.FILL); break; default: case FIT_CENTER: mBorderRect.set(mBitmapRect); mShaderMatrix.setRectToRect(mBitmapRect, mBounds, Matrix.ScaleToFit.CENTER); mShaderMatrix.mapRect(mBorderRect); mBorderRect.inset((mBorderWidth) / 2, (mBorderWidth) / 2); mShaderMatrix.setRectToRect(mBitmapRect, mBorderRect, Matrix.ScaleToFit.FILL); break; case FIT_END: mBorderRect.set(mBitmapRect); mShaderMatrix.setRectToRect(mBitmapRect, mBounds, Matrix.ScaleToFit.END); mShaderMatrix.mapRect(mBorderRect); mBorderRect.inset((mBorderWidth) / 2, (mBorderWidth) / 2); mShaderMatrix.setRectToRect(mBitmapRect, mBorderRect, Matrix.ScaleToFit.FILL); break; case FIT_START: mBorderRect.set(mBitmapRect); mShaderMatrix.setRectToRect(mBitmapRect, mBounds, Matrix.ScaleToFit.START); mShaderMatrix.mapRect(mBorderRect); mBorderRect.inset((mBorderWidth) / 2, (mBorderWidth) / 2); mShaderMatrix.setRectToRect(mBitmapRect, mBorderRect, Matrix.ScaleToFit.FILL); break; case FIT_XY: mBorderRect.set(mBounds); mBorderRect.inset((mBorderWidth) / 2, (mBorderWidth) / 2); mShaderMatrix.set(null); mShaderMatrix.setRectToRect(mBitmapRect, mBorderRect, Matrix.ScaleToFit.FILL); break; } mDrawableRect.set(mBorderRect); mBitmapShader.setLocalMatrix(mShaderMatrix); } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); mBounds.set(bounds); updateShaderMatrix(); } @Override public void draw(@NonNull Canvas canvas) { if (mOval) { if (mBorderWidth > 0) { canvas.drawOval(mDrawableRect, mBitmapPaint); canvas.drawOval(mBorderRect, mBorderPaint); } else { canvas.drawOval(mDrawableRect, mBitmapPaint); } } else { if (mBorderWidth > 0) { canvas.drawRoundRect(mDrawableRect, Math.max(mCornerRadius, 0), Math.max(mCornerRadius, 0), mBitmapPaint); canvas.drawRoundRect(mBorderRect, mCornerRadius, mCornerRadius, mBorderPaint); } else { canvas.drawRoundRect(mDrawableRect, mCornerRadius, mCornerRadius, mBitmapPaint); } } } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void setAlpha(int alpha) { mBitmapPaint.setAlpha(alpha); invalidateSelf(); } @Override public void setColorFilter(ColorFilter cf) { mBitmapPaint.setColorFilter(cf); invalidateSelf(); } @Override public void setDither(boolean dither) { mBitmapPaint.setDither(dither); invalidateSelf(); } @Override public void setFilterBitmap(boolean filter) { mBitmapPaint.setFilterBitmap(filter); invalidateSelf(); } @Override public int getIntrinsicWidth() { return mBitmapWidth; } @Override public int getIntrinsicHeight() { return mBitmapHeight; } public float getCornerRadius() { return mCornerRadius; } RoundedDrawable setCornerRadius(float radius) { mCornerRadius = radius; return this; } public float getBorderWidth() { return mBorderWidth; } RoundedDrawable setBorderWidth(float width) { mBorderWidth = width; mBorderPaint.setStrokeWidth(mBorderWidth); return this; } public int getBorderColor() { return mBorderColor.getDefaultColor(); } RoundedDrawable setBorderColor(ColorStateList colors) { mBorderColor = colors != null ? colors : ColorStateList.valueOf(0); mBorderPaint.setColor(mBorderColor.getColorForState(getState(), DEFAULT_BORDER_COLOR)); return this; } public RoundedDrawable setBorderColor(int color) { return setBorderColor(ColorStateList.valueOf(color)); } public ColorStateList getBorderColors() { return mBorderColor; } public boolean isOval() { return mOval; } RoundedDrawable setOval(boolean oval) { mOval = oval; return this; } public ImageView.ScaleType getScaleType() { return mScaleType; } public RoundedDrawable setScaleType(ImageView.ScaleType scaleType) { if (scaleType == null) { scaleType = ImageView.ScaleType.FIT_CENTER; } if (mScaleType != scaleType) { mScaleType = scaleType; updateShaderMatrix(); } return this; } Bitmap toBitmap() { return drawableToBitmap(this); } }
bbd4d6b927a0a7d65909a4a54fb5383841e1725b
4c6adf0ce6ef3f02dcef9c345e0e5e4ff139d886
/Common/FO/fo-jar/fo-order/src/main/java/com/pay/fo/order/dto/batchpayment/BatchPaymentReqBaseInfoDTO.java
732efd4f68724ebd1af6a488419db32d125b946c
[]
no_license
happyjianguo/pay-1
8631906be62707316f0ed3eb6b2337c90d213bc0
40ae79738cfe4e5d199ca66468f3a33e9d8f2007
refs/heads/master
2020-07-27T19:51:54.958859
2016-12-19T07:34:24
2016-12-19T07:34:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,288
java
package com.pay.fo.order.dto.batchpayment; import java.util.Date; import java.util.List; public class BatchPaymentReqBaseInfoDTO { /** * 请求流水号 */ private Long requestSeq; /** * 请求类型 */ private Integer requestType; /** * 业务批次号 */ private String businessBatchNo; /** * 付款方名称 */ private String payerName; /** * 付款方登录标识 */ private String payerLoginName; /** * 付款方会员号 */ private Long payerMemberCode; /** * 付款方会员类型 */ private Integer payerMemberType; /** * 付款方账号 */ private String payerAcctCode; /** * 付款方账号类型 */ private Integer payerAcctType; /** * 创建者 */ private String creator; /** * 创建日期 */ private Date createDate; /** * 更新日期 */ private Date updateDate; /** * 审核状态 */ private Integer status; /** * 审核员 */ private String auditor; /** * 请求付款金额 */ private Long requestAmount; /** * 请求付款次数 */ private Integer requestCount; /** * 有效金额 */ private Long validAmount; /** * 有效笔数 */ private Integer validCount; /** * 是否是付款方付手续费 */ private Integer isPayerPayFee; /** * 手续费 */ private Long fee; /** * 总手续费 */ private Long totalFee; /** * 收款方手续费 */ private Long payeeFee; /** * 付款方手续费 */ private Long payerFee; /** * 实际付款金额 */ private Long realpayAmount; /** * 实际出款金额 */ private Long realoutAmount; /** * 请求来源 */ private String requestSrc; /** * 审核备注 */ private String auditRemark; /** * 请求明细信息 */ private List<RequestDetail> requestDetails; /** * 错误信息 */ private String errorMsg; /** * 处理类型 0 默认 1 定期 */ private Integer processType; /** * 执行时间 */ private Date excuteDate; private String payerCurrencyCode; public Long getTotalFee() { return totalFee; } public void setTotalFee(Long totalFee) { this.totalFee = totalFee; } public Long getPayeeFee() { return payeeFee; } public void setPayeeFee(Long payeeFee) { this.payeeFee = payeeFee; } public Long getPayerFee() { return payerFee; } public void setPayerFee(Long payerFee) { this.payerFee = payerFee; } private Integer payeeAcctType ; private String payeeCurrencyCode ; /** * @return the requestSeq */ public Long getRequestSeq() { return requestSeq; } /** * @param requestSeq * the requestSeq to set */ public void setRequestSeq(Long requestSeq) { this.requestSeq = requestSeq; } /** * @return the requestType */ public Integer getRequestType() { return requestType; } /** * @param requestType * the requestType to set */ public void setRequestType(Integer requestType) { this.requestType = requestType; } /** * @return the businessBatchNo */ public String getBusinessBatchNo() { return businessBatchNo; } /** * @param businessBatchNo * the businessBatchNo to set */ public void setBusinessBatchNo(String businessBatchNo) { this.businessBatchNo = businessBatchNo; } /** * @return the payerName */ public String getPayerName() { return payerName; } /** * @param payerName * the payerName to set */ public void setPayerName(String payerName) { this.payerName = payerName; } /** * @return the payerLoginName */ public String getPayerLoginName() { return payerLoginName; } /** * @param payerLoginName * the payerLoginName to set */ public void setPayerLoginName(String payerLoginName) { this.payerLoginName = payerLoginName; } /** * @return the payerMemberCode */ public Long getPayerMemberCode() { return payerMemberCode; } /** * @param payerMemberCode * the payerMemberCode to set */ public void setPayerMemberCode(Long payerMemberCode) { this.payerMemberCode = payerMemberCode; } /** * @return the payerMemberType */ public Integer getPayerMemberType() { return payerMemberType; } /** * @param payerMemberType * the payerMemberType to set */ public void setPayerMemberType(Integer payerMemberType) { this.payerMemberType = payerMemberType; } /** * @return the payerAcctCode */ public String getPayerAcctCode() { return payerAcctCode; } /** * @param payerAcctCode * the payerAcctCode to set */ public void setPayerAcctCode(String payerAcctCode) { this.payerAcctCode = payerAcctCode; } /** * @return the payerAcctType */ public Integer getPayerAcctType() { return payerAcctType; } /** * @param payerAcctType * the payerAcctType to set */ public void setPayerAcctType(Integer payerAcctType) { this.payerAcctType = payerAcctType; } /** * @return the creator */ public String getCreator() { return creator; } /** * @param creator * the creator to set */ public void setCreator(String creator) { this.creator = creator; } /** * @return the createDate */ public Date getCreateDate() { return createDate; } /** * @param createDate * the createDate to set */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * @return the updateDate */ public Date getUpdateDate() { return updateDate; } /** * @param updateDate * the updateDate to set */ public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } /** * @return the status */ public Integer getStatus() { return status; } /** * @param status * the status to set */ public void setStatus(Integer status) { this.status = status; } /** * @return the auditor */ public String getAuditor() { return auditor; } /** * @param auditor * the auditor to set */ public void setAuditor(String auditor) { this.auditor = auditor; } /** * @return the requestAmount */ public Long getRequestAmount() { return requestAmount; } /** * @param requestAmount * the requestAmount to set */ public void setRequestAmount(Long requestAmount) { this.requestAmount = requestAmount; } /** * @return the requestCount */ public Integer getRequestCount() { return requestCount; } /** * @param requestCount * the requestCount to set */ public void setRequestCount(Integer requestCount) { this.requestCount = requestCount; } /** * @return the validAmount */ public Long getValidAmount() { return validAmount; } /** * @param validAmount * the validAmount to set */ public void setValidAmount(Long validAmount) { this.validAmount = validAmount; } /** * @return the validCount */ public Integer getValidCount() { return validCount; } /** * @param validCount * the validCount to set */ public void setValidCount(Integer validCount) { this.validCount = validCount; } /** * @return the isPayerPayFee */ public Integer getIsPayerPayFee() { return isPayerPayFee; } /** * @param isPayerPayFee * the isPayerPayFee to set */ public void setIsPayerPayFee(Integer isPayerPayFee) { this.isPayerPayFee = isPayerPayFee; } /** * @return the fee */ public Long getFee() { return fee; } /** * @param fee * the fee to set */ public void setFee(Long fee) { this.fee = fee; } /** * @return the realpayAmount */ public Long getRealpayAmount() { return realpayAmount; } /** * @param realpayAmount * the realpayAmount to set */ public void setRealpayAmount(Long realpayAmount) { this.realpayAmount = realpayAmount; } /** * @return the realoutAmount */ public Long getRealoutAmount() { return realoutAmount; } /** * @param realoutAmount * the realoutAmount to set */ public void setRealoutAmount(Long realoutAmount) { this.realoutAmount = realoutAmount; } /** * @return the requestSrc */ public String getRequestSrc() { return requestSrc; } /** * @param requestSrc * the requestSrc to set */ public void setRequestSrc(String requestSrc) { this.requestSrc = requestSrc; } /** * @return the auditRemark */ public String getAuditRemark() { return auditRemark; } /** * @param auditRemark * the auditRemark to set */ public void setAuditRemark(String auditRemark) { this.auditRemark = auditRemark; } /** * @return the requestDetails */ public List<RequestDetail> getRequestDetails() { return requestDetails; } /** * @param requestDetails * the requestDetails to set */ public void setRequestDetails(List<RequestDetail> requestDetails) { this.requestDetails = requestDetails; } /** * @return the errorMsg */ public String getErrorMsg() { return errorMsg; } /** * @param errorMsg * the errorMsg to set */ public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public Integer getProcessType() { return processType; } public void setProcessType(Integer processType) { this.processType = processType; } public Date getExcuteDate() { return excuteDate; } public void setExcuteDate(Date excuteDate) { this.excuteDate = excuteDate; } public String getPayeeCurrencyCode() { return payeeCurrencyCode; } public void setPayeeCurrencyCode(String payeeCurrencyCode) { this.payeeCurrencyCode = payeeCurrencyCode; } public Integer getPayeeAcctType() { return payeeAcctType; } public void setPayeeAcctType(Integer payeeAcctType) { this.payeeAcctType = payeeAcctType; } public String getPayerCurrencyCode() { return payerCurrencyCode; } public void setPayerCurrencyCode(String payerCurrencyCode) { this.payerCurrencyCode = payerCurrencyCode; } @Override public String toString() { return "BatchPaymentReqBaseInfoDTO [requestSeq=" + requestSeq + ", requestType=" + requestType + ", businessBatchNo=" + businessBatchNo + ", payerName=" + payerName + ", payerLoginName=" + payerLoginName + ", payerMemberCode=" + payerMemberCode + ", payerMemberType=" + payerMemberType + ", payerAcctCode=" + payerAcctCode + ", payerAcctType=" + payerAcctType + ", creator=" + creator + ", createDate=" + createDate + ", updateDate=" + updateDate + ", status=" + status + ", auditor=" + auditor + ", requestAmount=" + requestAmount + ", requestCount=" + requestCount + ", validAmount=" + validAmount + ", validCount=" + validCount + ", isPayerPayFee=" + isPayerPayFee + ", fee=" + fee + ", totalFee=" + totalFee + ", payeeFee=" + payeeFee + ", payerFee=" + payerFee + ", realpayAmount=" + realpayAmount + ", realoutAmount=" + realoutAmount + ", requestSrc=" + requestSrc + ", auditRemark=" + auditRemark + ", requestDetails=" + requestDetails + ", errorMsg=" + errorMsg + ", processType=" + processType + ", excuteDate=" + excuteDate + ", payerCurrencyCode=" + payerCurrencyCode + ", payeeAcctType=" + payeeAcctType + ", payeeCurrencyCode=" + payeeCurrencyCode + "]"; } }
3d59bde8a7c164a9113ec92ba9bbcab9c45ca192
eb79d9558896f4d144a5acf98de4f7571d8ae673
/app/src/main/java/com/jc/model/CalModel.java
2396536f67b94a6b3d1edda06580f936f5272759
[]
no_license
strangerjj/calculator
f7a4abb796f3eb30d1db6300e7274116a1f1048a
e1a7837fd1ae771ebe32c2a868e37c9eca7a3c0e
refs/heads/master
2021-01-10T03:26:55.251551
2016-02-26T09:16:35
2016-02-26T09:16:35
52,514,126
0
0
null
null
null
null
UTF-8
Java
false
false
2,764
java
package com.jc.model; import com.jc.interfaces.ICalculator; import java.util.Stack; /** * Created by YJZJB0051 on 2016-02-26. */ public class CalModel implements ICalculator { //计算器算法 public static double popOpOffStack(Stack<String> stack) { double result = 0; //从栈中获取运算数,由于运算数以字符串的形式储存 //在用作计算时需转型为可计算类型,这里用double //pop()函数为移除栈顶的元素,并返回此元素 double operand = Double.valueOf(stack.pop()); //从栈中移除元素后如果栈已为空,则直接返回operand if (stack.isEmpty()) { return operand; } //继续从栈中获取操作符,根据操作符类型继续递归调用 String operate = stack.pop(); if (operate.equals("+")) { result = CalModel.popOpOffStack(stack) + operand; } else if (operate.equals("-")) { result = CalModel.popOpOffStack(stack) - operand; } else if (operate.equals("*")) { result = CalModel.popOpOffStack(stack) * operand; } else if (operate.equals("/")) { result = CalModel.popOpOffStack(stack) / operand; } return result; } //记录输入的运算数和操作符的栈 private Stack<String> dataStack = new Stack<>(); //是否在输入操作符,对连续输入操作符的情况则视为操作符的替换 private boolean isOperate = false; @Override public void pushOperand(String operand) { //当输入运算数时直接压入stack,不会触发计算 dataStack.add(operand); isOperate = false; } @Override public double pushOperate(String operate) { //当操作符时"+-*/"时,输入会继续 //所以copy一份当前栈的数据作为参数传入进行计算并返回 //当操作符时"="号时,则直接使用当前栈作为参数 //因为"="是意味之后需要重新开始 double result; if (isOperate) { dataStack.pop();//如果前一个是操作符,则将它替换 } if (operate.equals("=")) { result = CalModel.popOpOffStack(dataStack); } else { @SuppressWarnings("unchecked") Stack<String> tmpStack = (Stack<String>) dataStack.clone(); result = CalModel.popOpOffStack(tmpStack); //计算完前面结果后把输入的运算符压入栈 dataStack.add(operate); isOperate = true; } return result; } @Override public void reset() { dataStack.removeAllElements(); isOperate = false; } }
efe7fa9c72e8eab7c5e74423ae76b5597e36bcdb
eeda52b0903a6a9884171fd6efd92b01aba25058
/etl-kettle-mbg/src/main/java/com/caixin/data/middle/etl/kettle/mbg/model/RJobExample.java
60df97c72ad9c9d630328b9373c16f2413685411
[]
no_license
v5coder/etl-kettle-web
485ec69e0af7796d1b77a3da8fb22f04893a3d52
c9814c37d0f2fb079342fbcc9a081259764a2b4b
refs/heads/master
2023-05-28T00:27:24.438832
2020-03-03T01:13:07
2020-03-03T01:13:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
40,363
java
package com.caixin.data.middle.etl.kettle.mbg.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class RJobExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public RJobExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdJobIsNull() { addCriterion("ID_JOB is null"); return (Criteria) this; } public Criteria andIdJobIsNotNull() { addCriterion("ID_JOB is not null"); return (Criteria) this; } public Criteria andIdJobEqualTo(Long value) { addCriterion("ID_JOB =", value, "idJob"); return (Criteria) this; } public Criteria andIdJobNotEqualTo(Long value) { addCriterion("ID_JOB <>", value, "idJob"); return (Criteria) this; } public Criteria andIdJobGreaterThan(Long value) { addCriterion("ID_JOB >", value, "idJob"); return (Criteria) this; } public Criteria andIdJobGreaterThanOrEqualTo(Long value) { addCriterion("ID_JOB >=", value, "idJob"); return (Criteria) this; } public Criteria andIdJobLessThan(Long value) { addCriterion("ID_JOB <", value, "idJob"); return (Criteria) this; } public Criteria andIdJobLessThanOrEqualTo(Long value) { addCriterion("ID_JOB <=", value, "idJob"); return (Criteria) this; } public Criteria andIdJobIn(List<Long> values) { addCriterion("ID_JOB in", values, "idJob"); return (Criteria) this; } public Criteria andIdJobNotIn(List<Long> values) { addCriterion("ID_JOB not in", values, "idJob"); return (Criteria) this; } public Criteria andIdJobBetween(Long value1, Long value2) { addCriterion("ID_JOB between", value1, value2, "idJob"); return (Criteria) this; } public Criteria andIdJobNotBetween(Long value1, Long value2) { addCriterion("ID_JOB not between", value1, value2, "idJob"); return (Criteria) this; } public Criteria andIdDirectoryIsNull() { addCriterion("ID_DIRECTORY is null"); return (Criteria) this; } public Criteria andIdDirectoryIsNotNull() { addCriterion("ID_DIRECTORY is not null"); return (Criteria) this; } public Criteria andIdDirectoryEqualTo(Integer value) { addCriterion("ID_DIRECTORY =", value, "idDirectory"); return (Criteria) this; } public Criteria andIdDirectoryNotEqualTo(Integer value) { addCriterion("ID_DIRECTORY <>", value, "idDirectory"); return (Criteria) this; } public Criteria andIdDirectoryGreaterThan(Integer value) { addCriterion("ID_DIRECTORY >", value, "idDirectory"); return (Criteria) this; } public Criteria andIdDirectoryGreaterThanOrEqualTo(Integer value) { addCriterion("ID_DIRECTORY >=", value, "idDirectory"); return (Criteria) this; } public Criteria andIdDirectoryLessThan(Integer value) { addCriterion("ID_DIRECTORY <", value, "idDirectory"); return (Criteria) this; } public Criteria andIdDirectoryLessThanOrEqualTo(Integer value) { addCriterion("ID_DIRECTORY <=", value, "idDirectory"); return (Criteria) this; } public Criteria andIdDirectoryIn(List<Integer> values) { addCriterion("ID_DIRECTORY in", values, "idDirectory"); return (Criteria) this; } public Criteria andIdDirectoryNotIn(List<Integer> values) { addCriterion("ID_DIRECTORY not in", values, "idDirectory"); return (Criteria) this; } public Criteria andIdDirectoryBetween(Integer value1, Integer value2) { addCriterion("ID_DIRECTORY between", value1, value2, "idDirectory"); return (Criteria) this; } public Criteria andIdDirectoryNotBetween(Integer value1, Integer value2) { addCriterion("ID_DIRECTORY not between", value1, value2, "idDirectory"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("NAME is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("NAME is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("NAME =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("NAME <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("NAME >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("NAME >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("NAME <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("NAME <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("NAME like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("NAME not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("NAME in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("NAME not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("NAME between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("NAME not between", value1, value2, "name"); return (Criteria) this; } public Criteria andJobVersionIsNull() { addCriterion("JOB_VERSION is null"); return (Criteria) this; } public Criteria andJobVersionIsNotNull() { addCriterion("JOB_VERSION is not null"); return (Criteria) this; } public Criteria andJobVersionEqualTo(String value) { addCriterion("JOB_VERSION =", value, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionNotEqualTo(String value) { addCriterion("JOB_VERSION <>", value, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionGreaterThan(String value) { addCriterion("JOB_VERSION >", value, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionGreaterThanOrEqualTo(String value) { addCriterion("JOB_VERSION >=", value, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionLessThan(String value) { addCriterion("JOB_VERSION <", value, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionLessThanOrEqualTo(String value) { addCriterion("JOB_VERSION <=", value, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionLike(String value) { addCriterion("JOB_VERSION like", value, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionNotLike(String value) { addCriterion("JOB_VERSION not like", value, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionIn(List<String> values) { addCriterion("JOB_VERSION in", values, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionNotIn(List<String> values) { addCriterion("JOB_VERSION not in", values, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionBetween(String value1, String value2) { addCriterion("JOB_VERSION between", value1, value2, "jobVersion"); return (Criteria) this; } public Criteria andJobVersionNotBetween(String value1, String value2) { addCriterion("JOB_VERSION not between", value1, value2, "jobVersion"); return (Criteria) this; } public Criteria andJobStatusIsNull() { addCriterion("JOB_STATUS is null"); return (Criteria) this; } public Criteria andJobStatusIsNotNull() { addCriterion("JOB_STATUS is not null"); return (Criteria) this; } public Criteria andJobStatusEqualTo(Integer value) { addCriterion("JOB_STATUS =", value, "jobStatus"); return (Criteria) this; } public Criteria andJobStatusNotEqualTo(Integer value) { addCriterion("JOB_STATUS <>", value, "jobStatus"); return (Criteria) this; } public Criteria andJobStatusGreaterThan(Integer value) { addCriterion("JOB_STATUS >", value, "jobStatus"); return (Criteria) this; } public Criteria andJobStatusGreaterThanOrEqualTo(Integer value) { addCriterion("JOB_STATUS >=", value, "jobStatus"); return (Criteria) this; } public Criteria andJobStatusLessThan(Integer value) { addCriterion("JOB_STATUS <", value, "jobStatus"); return (Criteria) this; } public Criteria andJobStatusLessThanOrEqualTo(Integer value) { addCriterion("JOB_STATUS <=", value, "jobStatus"); return (Criteria) this; } public Criteria andJobStatusIn(List<Integer> values) { addCriterion("JOB_STATUS in", values, "jobStatus"); return (Criteria) this; } public Criteria andJobStatusNotIn(List<Integer> values) { addCriterion("JOB_STATUS not in", values, "jobStatus"); return (Criteria) this; } public Criteria andJobStatusBetween(Integer value1, Integer value2) { addCriterion("JOB_STATUS between", value1, value2, "jobStatus"); return (Criteria) this; } public Criteria andJobStatusNotBetween(Integer value1, Integer value2) { addCriterion("JOB_STATUS not between", value1, value2, "jobStatus"); return (Criteria) this; } public Criteria andIdDatabaseLogIsNull() { addCriterion("ID_DATABASE_LOG is null"); return (Criteria) this; } public Criteria andIdDatabaseLogIsNotNull() { addCriterion("ID_DATABASE_LOG is not null"); return (Criteria) this; } public Criteria andIdDatabaseLogEqualTo(Integer value) { addCriterion("ID_DATABASE_LOG =", value, "idDatabaseLog"); return (Criteria) this; } public Criteria andIdDatabaseLogNotEqualTo(Integer value) { addCriterion("ID_DATABASE_LOG <>", value, "idDatabaseLog"); return (Criteria) this; } public Criteria andIdDatabaseLogGreaterThan(Integer value) { addCriterion("ID_DATABASE_LOG >", value, "idDatabaseLog"); return (Criteria) this; } public Criteria andIdDatabaseLogGreaterThanOrEqualTo(Integer value) { addCriterion("ID_DATABASE_LOG >=", value, "idDatabaseLog"); return (Criteria) this; } public Criteria andIdDatabaseLogLessThan(Integer value) { addCriterion("ID_DATABASE_LOG <", value, "idDatabaseLog"); return (Criteria) this; } public Criteria andIdDatabaseLogLessThanOrEqualTo(Integer value) { addCriterion("ID_DATABASE_LOG <=", value, "idDatabaseLog"); return (Criteria) this; } public Criteria andIdDatabaseLogIn(List<Integer> values) { addCriterion("ID_DATABASE_LOG in", values, "idDatabaseLog"); return (Criteria) this; } public Criteria andIdDatabaseLogNotIn(List<Integer> values) { addCriterion("ID_DATABASE_LOG not in", values, "idDatabaseLog"); return (Criteria) this; } public Criteria andIdDatabaseLogBetween(Integer value1, Integer value2) { addCriterion("ID_DATABASE_LOG between", value1, value2, "idDatabaseLog"); return (Criteria) this; } public Criteria andIdDatabaseLogNotBetween(Integer value1, Integer value2) { addCriterion("ID_DATABASE_LOG not between", value1, value2, "idDatabaseLog"); return (Criteria) this; } public Criteria andTableNameLogIsNull() { addCriterion("TABLE_NAME_LOG is null"); return (Criteria) this; } public Criteria andTableNameLogIsNotNull() { addCriterion("TABLE_NAME_LOG is not null"); return (Criteria) this; } public Criteria andTableNameLogEqualTo(String value) { addCriterion("TABLE_NAME_LOG =", value, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogNotEqualTo(String value) { addCriterion("TABLE_NAME_LOG <>", value, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogGreaterThan(String value) { addCriterion("TABLE_NAME_LOG >", value, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogGreaterThanOrEqualTo(String value) { addCriterion("TABLE_NAME_LOG >=", value, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogLessThan(String value) { addCriterion("TABLE_NAME_LOG <", value, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogLessThanOrEqualTo(String value) { addCriterion("TABLE_NAME_LOG <=", value, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogLike(String value) { addCriterion("TABLE_NAME_LOG like", value, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogNotLike(String value) { addCriterion("TABLE_NAME_LOG not like", value, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogIn(List<String> values) { addCriterion("TABLE_NAME_LOG in", values, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogNotIn(List<String> values) { addCriterion("TABLE_NAME_LOG not in", values, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogBetween(String value1, String value2) { addCriterion("TABLE_NAME_LOG between", value1, value2, "tableNameLog"); return (Criteria) this; } public Criteria andTableNameLogNotBetween(String value1, String value2) { addCriterion("TABLE_NAME_LOG not between", value1, value2, "tableNameLog"); return (Criteria) this; } public Criteria andCreatedUserIsNull() { addCriterion("CREATED_USER is null"); return (Criteria) this; } public Criteria andCreatedUserIsNotNull() { addCriterion("CREATED_USER is not null"); return (Criteria) this; } public Criteria andCreatedUserEqualTo(String value) { addCriterion("CREATED_USER =", value, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserNotEqualTo(String value) { addCriterion("CREATED_USER <>", value, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserGreaterThan(String value) { addCriterion("CREATED_USER >", value, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserGreaterThanOrEqualTo(String value) { addCriterion("CREATED_USER >=", value, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserLessThan(String value) { addCriterion("CREATED_USER <", value, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserLessThanOrEqualTo(String value) { addCriterion("CREATED_USER <=", value, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserLike(String value) { addCriterion("CREATED_USER like", value, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserNotLike(String value) { addCriterion("CREATED_USER not like", value, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserIn(List<String> values) { addCriterion("CREATED_USER in", values, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserNotIn(List<String> values) { addCriterion("CREATED_USER not in", values, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserBetween(String value1, String value2) { addCriterion("CREATED_USER between", value1, value2, "createdUser"); return (Criteria) this; } public Criteria andCreatedUserNotBetween(String value1, String value2) { addCriterion("CREATED_USER not between", value1, value2, "createdUser"); return (Criteria) this; } public Criteria andCreatedDateIsNull() { addCriterion("CREATED_DATE is null"); return (Criteria) this; } public Criteria andCreatedDateIsNotNull() { addCriterion("CREATED_DATE is not null"); return (Criteria) this; } public Criteria andCreatedDateEqualTo(Date value) { addCriterion("CREATED_DATE =", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateNotEqualTo(Date value) { addCriterion("CREATED_DATE <>", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateGreaterThan(Date value) { addCriterion("CREATED_DATE >", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateGreaterThanOrEqualTo(Date value) { addCriterion("CREATED_DATE >=", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateLessThan(Date value) { addCriterion("CREATED_DATE <", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateLessThanOrEqualTo(Date value) { addCriterion("CREATED_DATE <=", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateIn(List<Date> values) { addCriterion("CREATED_DATE in", values, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateNotIn(List<Date> values) { addCriterion("CREATED_DATE not in", values, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateBetween(Date value1, Date value2) { addCriterion("CREATED_DATE between", value1, value2, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateNotBetween(Date value1, Date value2) { addCriterion("CREATED_DATE not between", value1, value2, "createdDate"); return (Criteria) this; } public Criteria andModifiedUserIsNull() { addCriterion("MODIFIED_USER is null"); return (Criteria) this; } public Criteria andModifiedUserIsNotNull() { addCriterion("MODIFIED_USER is not null"); return (Criteria) this; } public Criteria andModifiedUserEqualTo(String value) { addCriterion("MODIFIED_USER =", value, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserNotEqualTo(String value) { addCriterion("MODIFIED_USER <>", value, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserGreaterThan(String value) { addCriterion("MODIFIED_USER >", value, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserGreaterThanOrEqualTo(String value) { addCriterion("MODIFIED_USER >=", value, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserLessThan(String value) { addCriterion("MODIFIED_USER <", value, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserLessThanOrEqualTo(String value) { addCriterion("MODIFIED_USER <=", value, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserLike(String value) { addCriterion("MODIFIED_USER like", value, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserNotLike(String value) { addCriterion("MODIFIED_USER not like", value, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserIn(List<String> values) { addCriterion("MODIFIED_USER in", values, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserNotIn(List<String> values) { addCriterion("MODIFIED_USER not in", values, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserBetween(String value1, String value2) { addCriterion("MODIFIED_USER between", value1, value2, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedUserNotBetween(String value1, String value2) { addCriterion("MODIFIED_USER not between", value1, value2, "modifiedUser"); return (Criteria) this; } public Criteria andModifiedDateIsNull() { addCriterion("MODIFIED_DATE is null"); return (Criteria) this; } public Criteria andModifiedDateIsNotNull() { addCriterion("MODIFIED_DATE is not null"); return (Criteria) this; } public Criteria andModifiedDateEqualTo(Date value) { addCriterion("MODIFIED_DATE =", value, "modifiedDate"); return (Criteria) this; } public Criteria andModifiedDateNotEqualTo(Date value) { addCriterion("MODIFIED_DATE <>", value, "modifiedDate"); return (Criteria) this; } public Criteria andModifiedDateGreaterThan(Date value) { addCriterion("MODIFIED_DATE >", value, "modifiedDate"); return (Criteria) this; } public Criteria andModifiedDateGreaterThanOrEqualTo(Date value) { addCriterion("MODIFIED_DATE >=", value, "modifiedDate"); return (Criteria) this; } public Criteria andModifiedDateLessThan(Date value) { addCriterion("MODIFIED_DATE <", value, "modifiedDate"); return (Criteria) this; } public Criteria andModifiedDateLessThanOrEqualTo(Date value) { addCriterion("MODIFIED_DATE <=", value, "modifiedDate"); return (Criteria) this; } public Criteria andModifiedDateIn(List<Date> values) { addCriterion("MODIFIED_DATE in", values, "modifiedDate"); return (Criteria) this; } public Criteria andModifiedDateNotIn(List<Date> values) { addCriterion("MODIFIED_DATE not in", values, "modifiedDate"); return (Criteria) this; } public Criteria andModifiedDateBetween(Date value1, Date value2) { addCriterion("MODIFIED_DATE between", value1, value2, "modifiedDate"); return (Criteria) this; } public Criteria andModifiedDateNotBetween(Date value1, Date value2) { addCriterion("MODIFIED_DATE not between", value1, value2, "modifiedDate"); return (Criteria) this; } public Criteria andUseBatchIdIsNull() { addCriterion("USE_BATCH_ID is null"); return (Criteria) this; } public Criteria andUseBatchIdIsNotNull() { addCriterion("USE_BATCH_ID is not null"); return (Criteria) this; } public Criteria andUseBatchIdEqualTo(String value) { addCriterion("USE_BATCH_ID =", value, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdNotEqualTo(String value) { addCriterion("USE_BATCH_ID <>", value, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdGreaterThan(String value) { addCriterion("USE_BATCH_ID >", value, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdGreaterThanOrEqualTo(String value) { addCriterion("USE_BATCH_ID >=", value, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdLessThan(String value) { addCriterion("USE_BATCH_ID <", value, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdLessThanOrEqualTo(String value) { addCriterion("USE_BATCH_ID <=", value, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdLike(String value) { addCriterion("USE_BATCH_ID like", value, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdNotLike(String value) { addCriterion("USE_BATCH_ID not like", value, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdIn(List<String> values) { addCriterion("USE_BATCH_ID in", values, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdNotIn(List<String> values) { addCriterion("USE_BATCH_ID not in", values, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdBetween(String value1, String value2) { addCriterion("USE_BATCH_ID between", value1, value2, "useBatchId"); return (Criteria) this; } public Criteria andUseBatchIdNotBetween(String value1, String value2) { addCriterion("USE_BATCH_ID not between", value1, value2, "useBatchId"); return (Criteria) this; } public Criteria andPassBatchIdIsNull() { addCriterion("PASS_BATCH_ID is null"); return (Criteria) this; } public Criteria andPassBatchIdIsNotNull() { addCriterion("PASS_BATCH_ID is not null"); return (Criteria) this; } public Criteria andPassBatchIdEqualTo(String value) { addCriterion("PASS_BATCH_ID =", value, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdNotEqualTo(String value) { addCriterion("PASS_BATCH_ID <>", value, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdGreaterThan(String value) { addCriterion("PASS_BATCH_ID >", value, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdGreaterThanOrEqualTo(String value) { addCriterion("PASS_BATCH_ID >=", value, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdLessThan(String value) { addCriterion("PASS_BATCH_ID <", value, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdLessThanOrEqualTo(String value) { addCriterion("PASS_BATCH_ID <=", value, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdLike(String value) { addCriterion("PASS_BATCH_ID like", value, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdNotLike(String value) { addCriterion("PASS_BATCH_ID not like", value, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdIn(List<String> values) { addCriterion("PASS_BATCH_ID in", values, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdNotIn(List<String> values) { addCriterion("PASS_BATCH_ID not in", values, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdBetween(String value1, String value2) { addCriterion("PASS_BATCH_ID between", value1, value2, "passBatchId"); return (Criteria) this; } public Criteria andPassBatchIdNotBetween(String value1, String value2) { addCriterion("PASS_BATCH_ID not between", value1, value2, "passBatchId"); return (Criteria) this; } public Criteria andUseLogfieldIsNull() { addCriterion("USE_LOGFIELD is null"); return (Criteria) this; } public Criteria andUseLogfieldIsNotNull() { addCriterion("USE_LOGFIELD is not null"); return (Criteria) this; } public Criteria andUseLogfieldEqualTo(String value) { addCriterion("USE_LOGFIELD =", value, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldNotEqualTo(String value) { addCriterion("USE_LOGFIELD <>", value, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldGreaterThan(String value) { addCriterion("USE_LOGFIELD >", value, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldGreaterThanOrEqualTo(String value) { addCriterion("USE_LOGFIELD >=", value, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldLessThan(String value) { addCriterion("USE_LOGFIELD <", value, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldLessThanOrEqualTo(String value) { addCriterion("USE_LOGFIELD <=", value, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldLike(String value) { addCriterion("USE_LOGFIELD like", value, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldNotLike(String value) { addCriterion("USE_LOGFIELD not like", value, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldIn(List<String> values) { addCriterion("USE_LOGFIELD in", values, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldNotIn(List<String> values) { addCriterion("USE_LOGFIELD not in", values, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldBetween(String value1, String value2) { addCriterion("USE_LOGFIELD between", value1, value2, "useLogfield"); return (Criteria) this; } public Criteria andUseLogfieldNotBetween(String value1, String value2) { addCriterion("USE_LOGFIELD not between", value1, value2, "useLogfield"); return (Criteria) this; } public Criteria andSharedFileIsNull() { addCriterion("SHARED_FILE is null"); return (Criteria) this; } public Criteria andSharedFileIsNotNull() { addCriterion("SHARED_FILE is not null"); return (Criteria) this; } public Criteria andSharedFileEqualTo(String value) { addCriterion("SHARED_FILE =", value, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileNotEqualTo(String value) { addCriterion("SHARED_FILE <>", value, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileGreaterThan(String value) { addCriterion("SHARED_FILE >", value, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileGreaterThanOrEqualTo(String value) { addCriterion("SHARED_FILE >=", value, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileLessThan(String value) { addCriterion("SHARED_FILE <", value, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileLessThanOrEqualTo(String value) { addCriterion("SHARED_FILE <=", value, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileLike(String value) { addCriterion("SHARED_FILE like", value, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileNotLike(String value) { addCriterion("SHARED_FILE not like", value, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileIn(List<String> values) { addCriterion("SHARED_FILE in", values, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileNotIn(List<String> values) { addCriterion("SHARED_FILE not in", values, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileBetween(String value1, String value2) { addCriterion("SHARED_FILE between", value1, value2, "sharedFile"); return (Criteria) this; } public Criteria andSharedFileNotBetween(String value1, String value2) { addCriterion("SHARED_FILE not between", value1, value2, "sharedFile"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
b7ad3d648d9fe6f6b6211ce9b1a54c24f60fd5c5
96a7161f31fb3e2b309006c3e0ba914bb3d93216
/src/main/java/org/mattrr78/passwordgenenv/GeneratePasswordRequest.java
05ae00ec24183e748734d589c4b92c4da2af6d2b
[]
no_license
mattrr78/passwordgenenv
c36626d5806ae32d03d9073606082cfff8f29987
cef7c8c3d26fb90d3774add62dee3cc9ccd7e5b3
refs/heads/master
2023-02-21T10:11:07.872203
2021-01-08T01:46:12
2021-01-08T01:46:12
324,277,030
0
0
null
null
null
null
UTF-8
Java
false
false
1,460
java
package org.mattrr78.passwordgenenv; public class GeneratePasswordRequest { private int count = 1; private int minimumLength = 6; private int maximumLength = 50; private CharacterType[] allowedTypes = CharacterType.values(); private CharacterType[] atLeastOneTypes = { CharacterType.LOWER, CharacterType.UPPER, CharacterType.NUMBER }; private int hogCpuValue = 0; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getMinimumLength() { return minimumLength; } public void setMinimumLength(int minimumLength) { this.minimumLength = minimumLength; } public int getMaximumLength() { return maximumLength; } public void setMaximumLength(int maximumLength) { this.maximumLength = maximumLength; } public CharacterType[] getAllowedTypes() { return allowedTypes; } public void setAllowedTypes(CharacterType[] allowedTypes) { this.allowedTypes = allowedTypes; } public CharacterType[] getAtLeastOneTypes() { return atLeastOneTypes; } public void setAtLeastOneTypes(CharacterType[] atLeastOneTypes) { this.atLeastOneTypes = atLeastOneTypes; } public int getHogCpuValue() { return hogCpuValue; } public void setHogCpuValue(int hogCpuValue) { this.hogCpuValue = hogCpuValue; } }
93573561e32c9c5b26906b5dbfd3914fad6c22e6
f0ad7e39af29fcf69d233ff12436dc8b49174840
/test/trinaglePuzzle/model/TestModelType.java
9746047ed9f26bc7d9ce81796ba9cb253d6f84b6
[]
no_license
sameermalikjmi/puzzle
338a3df6af62a3afb86ecac0a33d9339095b0369
a88248a697c810fab233b5f3b6a7bcf8b2e92e0f
refs/heads/main
2023-08-12T05:04:23.808812
2021-10-09T00:59:53
2021-10-09T00:59:53
415,160,242
0
0
null
null
null
null
UTF-8
Java
false
false
2,274
java
package trinaglePuzzle.model; import org.junit.Before; import org.junit.jupiter.api.BeforeEach; import trianglePuzzle.model.Edge; import trianglePuzzle.model.Model; import trianglePuzzle.model.Node; import trianglePuzzle.model.TrianglePuzzle; public abstract class TestModelType { protected Model model; @BeforeEach public void setUp() { model = new Model(); TrianglePuzzle p = new TrianglePuzzle(); p.addNode(new Node(155, 34, 0, false)); p.addNode(new Node(115, 112, 1, false)); p.addNode(new Node( 200, 112, 2, false)); p.addNode(new Node(78, 180, 3, false)); p.addNode(new Node(162, 180, 4, false)); p.addNode(new Node(250, 180, 5, false)); p.addNode(new Node(40, 240, 6, false)); p.addNode(new Node(115, 240, 7, false)); p.addNode(new Node(200, 240, 8, false)); p.addNode(new Node(290, 240, 9, false)); p.addEdge(new Edge("red",1,p.getNodes().get(0),p.getNodes().get(1))); p.addEdge(new Edge("green",2,p.getNodes().get(1),p.getNodes().get(2))); p.addEdge(new Edge("red",3,p.getNodes().get(0),p.getNodes().get(2))); p.addEdge(new Edge("red",4,p.getNodes().get(1),p.getNodes().get(3))); p.addEdge(new Edge("green",5,p.getNodes().get(3),p.getNodes().get(4))); p.addEdge(new Edge("blue",6,p.getNodes().get(1),p.getNodes().get(4))); p.addEdge(new Edge("blue",7,p.getNodes().get(2),p.getNodes().get(4))); p.addEdge(new Edge("green",8,p.getNodes().get(4),p.getNodes().get(5))); p.addEdge(new Edge("red",9,p.getNodes().get(2),p.getNodes().get(5))); p.addEdge(new Edge("red",10,p.getNodes().get(3),p.getNodes().get(6))); p.addEdge(new Edge("green",11,p.getNodes().get(6),p.getNodes().get(7))); p.addEdge(new Edge("blue",12,p.getNodes().get(3),p.getNodes().get(7))); p.addEdge(new Edge("blue",13,p.getNodes().get(7),p.getNodes().get(4))); p.addEdge(new Edge("green",14,p.getNodes().get(7),p.getNodes().get(8))); p.addEdge(new Edge("blue",15,p.getNodes().get(4),p.getNodes().get(8))); p.addEdge(new Edge("blue",16,p.getNodes().get(5),p.getNodes().get(8))); p.addEdge(new Edge("green",17,p.getNodes().get(8),p.getNodes().get(9))); p.addEdge(new Edge("red",18,p.getNodes().get(5),p.getNodes().get(9))); p.setTriangle(p.getEdges()); model.setPuzzle(p); } }
c5de0130dc9cb5ff0fd8d6e0e8dfe2630e3646df
e6d4afa67078b9040fb6c302d2712314da9c9fd3
/rx/src/test/java/com/github/sioncheng/springs/rx/FluxTests.java
2b9bf0e1174525c090c5cf800c23a87544a917e1
[]
no_license
sioncheng/springs
56a94c310a6905bc0b1031a9c87fe7c4a26736ae
08e4a5e4bdd8fcc9f6387697cd06b09556bf45ab
refs/heads/master
2020-05-22T05:45:44.857841
2019-05-15T16:16:08
2019-05-15T16:16:08
186,241,015
0
0
null
null
null
null
UTF-8
Java
false
false
2,071
java
package com.github.sioncheng.springs.rx; import org.junit.Assert; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.util.Arrays; import java.util.List; public class FluxTests { @Test public void testCreateFlux() { Flux<String> stringFlux = Flux.just("a", "b", "c", "d", "e"); Assert.assertNotNull(stringFlux); StepVerifier.create(stringFlux) .expectNext("a") .expectNext("b") .expectNext("c") .expectNext("d") .expectNext("e") .verifyComplete(); } @Test public void testMergeFlux() { Flux<String> stringFlux1 = Flux.just("a", "b"); Flux<String> stringFlux2 = Flux.just("c", "d", "e"); StepVerifier.create(stringFlux1.mergeWith(stringFlux2)) .expectNext("a") .expectNext("b") .expectNext("c") .expectNext("d") .expectNext("e") .verifyComplete(); } @Test public void collectList() { Flux<String> fruitFlux = Flux.just( "apple", "orange", "banana", "kiwi", "strawberry"); Mono<List<String>> fruitListMono = fruitFlux.collectList(); StepVerifier .create(fruitListMono) .expectNext(Arrays.asList( "apple", "orange", "banana", "kiwi", "strawberry")) .verifyComplete(); } @Test public void all() { Flux<String> animalFlux = Flux.just( "aardvark", "elephant", "koala", "eagle", "kangaroo"); Mono<Boolean> hasAMono = animalFlux.all(a -> a.contains("a")); StepVerifier.create(hasAMono) .expectNext(true) .verifyComplete(); Mono<Boolean> hasKMono = animalFlux.all(a -> a.contains("k")); StepVerifier.create(hasKMono) .expectNext(false) .verifyComplete(); } }
e403a2b66ac3dfd4575cfff288651fa0965da5a5
21a5ab10a4309922346a4cbef108e88efa331efd
/Coursera Java 1/StringSecondAssignment/part1.java
c961b016c59011b77f9a175d78ae9b69e88735ce
[]
no_license
roypj/Coursera-OOP-1
4b37d7c76d19bc16b0ca7ee4eca2d4fd889e1bea
83be721be93734a92ae922d8014700be8477232d
refs/heads/master
2021-01-20T15:57:48.137822
2017-12-30T19:11:23
2017-12-30T19:11:23
90,803,405
0
0
null
2017-12-30T19:11:25
2017-05-10T00:18:44
Java
UTF-8
Java
false
false
2,429
java
/** * Write a description of part1 here. * * @author (your name) * @version (a version number or a date) */ public class part1 { public int findStopCodon(String dna, int startIdx, String stopCodon){ int currIdx = dna.indexOf(stopCodon,startIdx+3); while(currIdx!=-1){ if((currIdx-startIdx)%3==0){ return currIdx; } else{ currIdx = dna.indexOf(stopCodon,currIdx+1); } } return dna.length(); } public String findGene(String dna){ int startIdx = dna.indexOf("ATG"); //System.out.println(dna); //System.out.println(startIdx); if (startIdx==-1){ return ""; } int atgIdx = findStopCodon(dna,startIdx,"TAA"); //System.out.println(atgIdx); int tagIdx = findStopCodon(dna,startIdx,"TAG"); //System.out.println(tagIdx); int tgaIdx = findStopCodon(dna,startIdx,"TGA"); //System.out.println(tagIdx); int minIdx = Math.min(Math.max(0,atgIdx),Math.min(Math.max(0,tagIdx),Math.max(0,tgaIdx))); //System.out.println(minIdx); if (minIdx==0||minIdx==dna.length()){ return ""; }else{ return dna.substring(startIdx,minIdx+3); } } public void printAllGenes(String dna){ int ocur =0; while (true){ String Gene = findGene(dna); if(!Gene.isEmpty()){ System.out.println(Gene); dna = dna.substring(dna.indexOf(Gene)+Gene.length()); //System.out.println("new dna"+dna); ocur+=1; } if(Gene.isEmpty()){ break; } } System.out.println("The number of Genes found is : "+ocur); } public void testStopCodon(){ System.out.println(findStopCodon("ATGGGSAAATAA",0,"TAA")); System.out.println(findStopCodon("ATGGGAAATAA",0,"TAA")); } public void testFindGene(){ System.out.println(findGene("xxxATGXXXXXXTAA")); System.out.println(findGene("xxxATGYYYTAG")); System.out.println(findGene("xxxATGZZZTGA")); System.out.println(findGene("xxxATGZZGA")); System.out.println(findGene("xxxTGZZGA")); System.out.println(findGene("xxxATGSSSTGAZZZTAGAAAAAATGA")); } public void testPrintallGenes(){ printAllGenes("xxxATGXXXXXXTAAxxxATGYYYYYYTAGxxxATGZZZZZZTGAxxxATZZZZZZTAAxxxATZZZZZZTAxxxATGZZZTAA"); printAllGenes("ATGTAAGATGCCCTAGT"); } }
4f1e248e7b756e7625fbd9732a679851834cc14a
0d8225751dd9e1396c9018fc33189efa1bac89d2
/Java & Scala/java/superkeyword/SA.java
638ae2e8b0c3f0cfc55eec15a03e715a3922b4f5
[]
no_license
potato17/Java-Scala
682cc961edd0be709dc7c35ebb41defed34acb44
888c2ca4e381f394755971b0f77cca547c1f69d6
refs/heads/master
2020-06-27T14:22:50.046527
2019-08-01T05:59:51
2019-08-01T05:59:51
199,975,479
0
0
null
null
null
null
UTF-8
Java
false
false
167
java
package superkeyword; public class SA { public static void main(String[] args) { SC d=new SC(); d.printColor(); // TODO Auto-generated method stub } }
a8a4f8245b2450d1688d882bcb522597ec864c6b
3ec181de57f014603bb36b8d667a8223875f5ee8
/jcommon/prometheus/prometheus-client/src/main/java/com/xiaomi/youpin/prometheus/client/PrometheusGauge.java
ce7ac3becb5b79bcff47f0881056d047b9af5d7e
[ "Apache-2.0" ]
permissive
XiaoMi/mone
41af3b636ecabd7134b53a54c782ed59cec09b9e
576cea4e6cb54e5bb7c37328f1cb452cda32f953
refs/heads/master
2023-08-31T08:47:40.632419
2023-08-31T08:09:35
2023-08-31T08:09:35
331,844,632
1,148
152
Apache-2.0
2023-09-14T07:33:13
2021-01-22T05:20:18
Java
UTF-8
Java
false
false
2,158
java
package com.xiaomi.youpin.prometheus.client; import io.prometheus.client.Gauge; import lombok.extern.slf4j.Slf4j; import org.slf4j.MDC; import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author zhangxiaowei */ @Slf4j public class PrometheusGauge implements XmGauge { public Gauge myGauge; public String[] labelNames; public String[] labelValues; public PrometheusGauge() { } @Override public void set(double delta,String ...labelValues) { try { List<String> mylist = new ArrayList<>(Arrays.asList(labelValues)); mylist.add(Prometheus.constLabels.get(Metrics.SERVICE)); String[] finalValue = mylist.toArray(new String[mylist.size()]); this.myGauge.labels(finalValue).set(delta); } catch (Throwable throwable) { //log.warn(throwable.getMessage()); } } public PrometheusGauge(Gauge cb, String[] lns, String[] lvs) { this.myGauge = cb; this.labelNames = lns; this.labelValues = lvs; } @Override public XmGauge with(String... labelValue) { /*String traceId = MDC.get("tid"); if (StringUtils.isEmpty(traceId)) { traceId = "no traceId"; }*/ try { if (this.labelNames.length != labelValue.length) { log.warn("Incorrect numbers of labels : " + myGauge.describe().get(0).name); return new PrometheusGauge(); } return this; } catch (Throwable throwable) { log.warn(throwable.getMessage()); return null; } } @Override public void add(double delta,String... labelValue) { List<String> mylist = new ArrayList<>(Arrays.asList(labelValues)); mylist.add(Prometheus.constLabels.get(Metrics.SERVICE)); String[] finalValue = mylist.toArray(new String[mylist.size()]); try { this.myGauge.labels(finalValue).inc(delta); } catch (Throwable throwable) { //log.warn(throwable.getMessage()); } } }
9b66ac1aaa101f3c8cb9d92d6520505f107892b2
7467dc2c8aaa82caa88a817b19786566cddf0e48
/src/org/driver/util/CoachUtil.java
69ba8d5804fe1cacbc8269eb9421532c34bf7618
[]
no_license
Nightcxd/DriverManagerSystem
018b6c240d8e6f47edaaa22e9bc2d729bc88956b
792759ef5c2cffc7c67df959ddb93398efb6a33b
refs/heads/master
2020-06-25T05:25:57.862505
2017-07-12T03:34:37
2017-07-12T03:34:37
96,960,612
1
0
null
null
null
null
UTF-8
Java
false
false
4,156
java
package org.driver.util; import java.util.List; import org.apache.log4j.Logger; import org.driver.bean.Coach; import org.driver.bean.Trainee; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class CoachUtil { private static final Logger logger = Logger.getLogger(CoachUtil.class); private static SessionFactory sessionFactory; static { Configuration cfg = new Configuration(); cfg.configure("org/driver/util/hibernate.cfg.xml"); sessionFactory = cfg.buildSessionFactory(); } /* *保存教练 */ public void save(Coach m) { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.save(m);//保存 tx.commit(); } catch (RuntimeException e) { tx.rollback(); throw e; } finally { session.close(); } } /* 删除指定id的教练 */ public void delete(int c_id) { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Coach st = (Coach) session.get(Coach.class, c_id); session.delete(st); tx.commit(); } catch (RuntimeException e) { tx.rollback(); throw e; } finally { session.close(); } } /* 更新教练 */ public void update(Coach m) { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.update(m);//保存 tx.commit(); } catch (RuntimeException e) { tx.rollback(); throw e; } finally { session.close(); } } /* 通过id获取一个教练 */ public Coach getById(String c_id) { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Coach m = (Coach) session.get(Coach.class, c_id);//获取 tx.commit(); return m; } catch (RuntimeException e) { tx.rollback(); throw e; } finally { session.close(); } } /* 查询全部教练 */ public List<Coach> findAll() { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); List<Coach> list = session.createQuery("From Coach").list(); tx.commit(); return list; } catch (RuntimeException e) { tx.rollback(); throw e; } finally { session.close(); } } /* 分页的查询 */ public QueryResult<Coach> getCoachList(int firstResult, int maxResult) { Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); //查询总记录数量 Long count = (Long) session.createQuery( "select count(*) from Coach") .uniqueResult();//执行查询 //查询一段数据 Query query = session.createQuery("From Coach"); query.setFirstResult(firstResult); query.setMaxResults(maxResult); List<Coach> list = query.list(); tx.commit(); return new QueryResult<Coach>(list, count); } catch (RuntimeException e) { tx.rollback(); throw e; } finally { session.close(); } } public static void main(String[] args) { } }
[ "root@hadoop1.(none)" ]
root@hadoop1.(none)
83b5f8f9c36c8eddd347d22051cadf8e56327e54
083de3b2cea03af63bbe31f5318be34fb08fa559
/src/factory_pattern/RiffleFactory.java
2b2b0b2e5cb0d6dc4a218f8ea65d78e0b47a72b4
[ "MIT" ]
permissive
anibalfuentesjara/design-patterns
54a99d36cde53bacd255944a1459d8b53e77f866
0dca27cc5ac45a3b2e5c04c4f6070144fa3d84e2
refs/heads/main
2023-06-16T19:12:15.013865
2021-07-04T19:48:32
2021-07-04T19:48:32
379,041,984
0
0
null
null
null
null
UTF-8
Java
false
false
156
java
package factory_pattern; public class RiffleFactory implements ShellFactory { @Override public Shell createShell() { return new RiffleShell(); } }
d38435a150d77c0183ea38c21db5814b3913f50c
a965c716243baeb9f23b320e7107c7c421ee4f53
/src/com/quiz0121/Ex004_Hap.java
ab50c9059e8e681b807c9b2d6173d451ec29e9ad
[]
no_license
EnuShalisha/coding-preJAVA
dbcb97f2794dbf8d1764e87d2c107946a741e072
405826ad782ffb378d4921c5adbf2c07e5164a77
refs/heads/main
2023-03-21T23:45:58.282363
2021-02-13T04:14:26
2021-02-13T04:14:26
331,312,458
0
0
null
null
null
null
UHC
Java
false
false
485
java
package com.quiz0121; public class Ex004_Hap { public static void main(String[] args) { /* 1~100 까지 정수의 합을 계산하여 출력하는 프로그램 */ int s, n; s=0; n=0; while(n<100) { n++; s+=n; } System.out.println("결과 : "+s); // 5050 /* int s, n; s=n=0; while(n++<100) { s+=n; } System.out.println("결과 : "+s); */ /* int s, n; s=n=0; while(++n<=100) { s+=n; } System.out.println("결과 : "+s); */ } }
359d506a1eda4d70ea85b6696dd5871a479a82e0
c2227ab39a41107646e1048a6fa5e3cc30c7e8df
/DataStructure/Graph/WeightedQuickUnionUF.java
2b346e5ceee1d0647592baf5def31d1b1136e4af
[]
no_license
TylerYang/algorithm
56d0ae35e34710ec472c0cbbd8cc1efa586346be
742a40abf0eca3014218bcfa2589affe524ca077
refs/heads/master
2020-05-16T13:42:23.716529
2016-02-15T11:19:50
2016-02-15T11:19:50
33,816,520
0
0
null
null
null
null
UTF-8
Java
false
false
805
java
public class WeightedQuickUnionUF{ int count; int[] sz, id; public WeightedQuickUnionUF(int N) { count = N; sz = new int[N]; id = new int[N]; for(int i = 0; i < id.length; i++) { id[i] = i; } } private int count() { return count; } private boolean connected(int p, int q) { return find(p) == find(q); } private int find(int p) { while(p != id[p]) p = id[p]; return p; } private void union(int p, int q){ int pId = id[p], qId = id[q]; if(pId == qId) return; if(sz[pId] < sz[qId]) { id[pId] = qId; sz[qId] += sz[pId]; } else { id[qId] = pId; sz[pId] += sz[qId]; } count--; } }
ce19032a9b746f8383af9d14bae8477cb55a2540
adb073a93ec2ceae65756d9e6f2f04478d6c74aa
/advance-java/week5/23.Behavioral-design-pattern/exercise/test-module-2/src/UI.java
847ed219f0a3d541197e5b7c8c1855e5647d14ab
[]
no_license
nhlong9697/codegym
0ae20f19360a337448e206137d703c5c2056a17b
38e105272fca0aecc0e737277b3a0a47b8cc0702
refs/heads/master
2023-05-12T17:18:14.570378
2022-07-13T09:07:52
2022-07-13T09:07:52
250,012,451
0
0
null
2023-05-09T05:40:08
2020-03-25T15:12:34
JavaScript
UTF-8
Java
false
false
544
java
public class UI { public void initialize() { System.out.println("---- CHUONG TRINH QUAN LY DANH BA ----"); System.out.println("Chon chuc nang theo so (de tiep tuc):"); System.out.println("1. Xem danh sach"); System.out.println("2. Them moi"); System.out.println("3. Cap nhat"); System.out.println("4. Xoa"); System.out.println("5. Tim kiem"); System.out.println("6. Doc tu file"); System.out.println("7. Ghi vao file"); System.out.println("8. Thoat"); } }