text
stringlengths
10
2.72M
package edu.math.page.javin; import edu.jenks.dist.math.*; public class Rational extends AbstractRational{ public static void main(String[] args) { Rational hello = new Rational(1, 1); Rational goodbye = new Rational(1, 1); hello.setNumerator(-171); hello.setDenominator(-191); goodbye.setNumerator(593); goodbye.setDenominator(471); System.out.println(hello.compareTo(goodbye)); } public Rational(long numer, long denom) throws IllegalArgumentException { super(numer, denom); if (denom < 0) { setDenominator(Math.abs(getDenominator())); setNumerator(getNumerator() * -1); } } public AbstractRational reciprocal() { Rational recip = new Rational(getDenominator(), getNumerator()); return recip; } public AbstractRational add(AbstractRational op2) { Rational add1 = new Rational(getNumerator() * op2.getDenominator(), getDenominator() * op2.getDenominator()); Rational add2 = new Rational(op2.getNumerator() * getDenominator(), op2.getDenominator() * getDenominator()); Rational sum = new Rational(add1.getNumerator() + add2.getNumerator(), add1.getDenominator()); return sum; } private void negativeNumerator() { setNumerator(getNumerator() * -1); } public AbstractRational subtract(AbstractRational op2) { ((Rational) op2).negativeNumerator(); return add(op2); } public AbstractRational multiply(AbstractRational op2) { long numerator = getNumerator() * op2.getNumerator(); long denominator = getDenominator() * op2.getDenominator(); Rational multiplied = new Rational(numerator, denominator); return multiplied; } public AbstractRational divide(AbstractRational op2) { return this.multiply(op2.reciprocal()); } public boolean equals(AbstractRational rn2) { return false; } public void reduce() { if (getNumerator() != 0){ long gcd = gcd(getNumerator(), getDenominator()); setNumerator(getNumerator() / gcd); setDenominator(getDenominator() / gcd); } } public String toString(){ if (getNumerator() == 0) { return getNumerator() + ""; } reduce(); if(this.getDenominator() == 1) { return String.valueOf(getNumerator()); } return getNumerator() + "/" + getDenominator(); } public boolean decimalTerminates() { long num = getDenominator(); while (num % 2 == 0) { num /= 2; } while (num % 5 == 0) { num /= 5; } if (num == 1) { return true; } return false; } public int compareTo(AbstractRational arg0) { if (arg0.getDenominator() < 0) { arg0.setDenominator(Math.abs(arg0.getDenominator())); arg0.setNumerator(arg0.getNumerator() * -1); } if (getDenominator() < 0) { setDenominator(Math.abs(getDenominator())); setNumerator(getNumerator() * -1); } arg0.reduce(); long firstNum = getNumerator() * arg0.getDenominator(); long nextNum = arg0.getNumerator() * getDenominator(); if (firstNum > nextNum) { return 1; }else if (firstNum < nextNum) { return -1; } return 0; } }
package ru.spb.itolia.redmine.ui; import java.util.HashMap; import java.util.Map; import com.actionbarsherlock.app.SherlockActivity; import ru.spb.itolia.redmine.R; import ru.spb.itolia.redmine.api.RedmineApiManager; import ru.spb.itolia.redmine.api.beans.RedmineHost; import ru.spb.itolia.redmine.api.beans.User; import ru.spb.itolia.redmine.db.RedmineDBAdapter; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class LoginActivity extends SherlockActivity implements OnClickListener { private final String PREFS_NAME = "prefs"; EditText loginEdit; EditText passwordEdit; EditText hostEdit; SharedPreferences settings; RedmineDBAdapter DBAdapter; // = new RedmineDBAdapter(Login.this.getApplicationContext()); @Override public void onCreate(Bundle savedInstanceState) { //setTheme(R.style.login); super.onCreate(savedInstanceState); setContentView(R.layout.login); DBAdapter = new RedmineDBAdapter(LoginActivity.this.getApplicationContext()); settings = getSharedPreferences(PREFS_NAME, 0); if(getIntent().getBooleanExtra("from_hosts_list", false)) { settings.edit().remove("host_id").commit(); } Integer host_id = settings.getInt("host_id", -1); if (host_id < 0) { loginEdit = (EditText) findViewById(R.id.login_edit); passwordEdit = (EditText) findViewById(R.id.password_edit); hostEdit = (EditText) findViewById(R.id.host_edit); Button loginButton = (Button) findViewById(R.id.login_button); loginButton.setOnClickListener(this); } else { Intent intent = new Intent(this, ProjectsActivity.class); intent.putExtra("host_id", host_id); startActivity(intent); finish(); } } @SuppressWarnings("unchecked") public void onClick(View arg0) { Map<String, String> credentials = new HashMap<String, String>(); credentials.put("login", loginEdit.getText().toString()); credentials.put("pass", passwordEdit.getText().toString()); credentials.put("host", hostEdit.getText().toString()); LoginTask task = new LoginTask(); task.execute(credentials); } public class LoginTask extends AsyncTask<Map<String, String>, Void, Integer> { protected ProgressDialog dialog; protected void onPreExecute(){ dialog = ProgressDialog.show(LoginActivity.this, "", "Loading. Please wait...", true); } @Override protected Integer doInBackground(Map<String, String>... params) { String login = params[0].get("login"); String pass = params[0].get("pass"); String host = params[0].get("host"); String api_key; String label; User current_user; RedmineApiManager mgr = new RedmineApiManager(login, pass, host); try { api_key = mgr.getApiKey(); current_user = mgr.getCurrentUser(api_key); label = mgr.getHostLabel(); } catch (Exception e) { e.printStackTrace(); return -1; } System.out.println("Saving host to DB"); //RedmineDBAdapter DBAdapter = new RedmineDBAdapter(Login.this.getApplicationContext()); DBAdapter.open(); DBAdapter.saveHost(new RedmineHost(null, LoginActivity.this.hostEdit.getText().toString(), label)); RedmineHost mHost = DBAdapter.getHostByAddress(host); current_user.setHost(mHost.getId()); DBAdapter.saveUser(current_user); DBAdapter.saveApi_key(mHost.getId(), api_key); DBAdapter.close(); settings.edit().putInt("host_id", mHost.getId()).commit(); return mHost.getId(); } protected void onPostExecute(Integer host_id) { Intent intent = new Intent(LoginActivity.this, ProjectsActivity.class); intent.putExtra("host_id", host_id); setResult(RESULT_OK, intent); dialog.dismiss(); startActivity(intent); finish(); } } }
module examCars { }
package saga.entities; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class ProdutoTest { private Produto produto1; private Produto produto2; private Produto produto3; @BeforeEach void init() { this.produto1 = new Produto("X-frango", "Hamburguer de frango com queijo e calabresa", 5.00); this.produto2 = new Produto("X-burguer", "Hamburguer de carne com queijo e calabresa", 4.50); this.produto3 = new Produto("X-frango", "Hamburguer de frango com queijo e calabresa", 4.00); } @Test void testHashCodeIgual() { assertEquals(this.produto1.hashCode(), this.produto3.hashCode()); } @Test void testHashCodeDiferente() { assertNotEquals(this.produto1.hashCode(), this.produto2.hashCode()); } @Test void testEqualsTrue() { assertEquals(this.produto1, this.produto3); } @Test void testEqualsFalse() { assertNotEquals(this.produto1, this.produto2); } @Test void testToString() { String representacao = "X-frango - Hamburguer de frango com queijo e calabresa - R$5,00"; assertEquals(representacao, this.produto1.toString()); } @Test void testCompareToMaior() { int comparacao = this.produto1.compareTo(this.produto2); assertTrue(comparacao > 0); } @Test void testCompareToMenor() { int comparacao = this.produto2.compareTo(this.produto1); assertTrue(comparacao < 0); } @Test void testCompareToIgual() { int comparacao = this.produto3.compareTo(this.produto1); assertEquals(0, comparacao); } }
package com.hcl.dctm.data.params; public class ExportMetadataParams extends ExportContentParams { }
package edu.erlm.epi.domain.school; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import lombok.Getter; import lombok.Setter; @Getter @Setter @Entity @Table(name = "t_school_year") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class SchoolYear implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "t_school_year_id_seq") @SequenceGenerator(sequenceName = "t_school_year_id_seq", name = "t_school_year_id_seq") private Long id; @NotNull @Size(min = 9, max = 9) @Column(unique=true) private String name; @NotNull private Boolean active; @Override public boolean equals(Object o) { if (!(o instanceof SchoolYear)) { return false; } SchoolYear otherSchoolYear = (SchoolYear) o; EqualsBuilder builder = new EqualsBuilder(); builder.append(getName(), otherSchoolYear.getName()); return builder.isEquals(); } @Override public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); builder.append(getName()); return builder.hashCode(); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.springframework.util; import java.lang.reflect.Array; import java.nio.charset.Charset; import java.time.ZoneId; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.StringJoiner; import java.util.TimeZone; import org.springframework.lang.Nullable; /** * Miscellaneous object utility methods. * * <p>Mainly for internal use within the framework. * * <p>Thanks to Alex Ruiz for contributing several enhancements to this class! * * @author Juergen Hoeller * @author Keith Donald * @author Rod Johnson * @author Rob Harrop * @author Chris Beams * @author Sam Brannen * @since 19.03.2004 * @see ClassUtils * @see CollectionUtils * @see StringUtils */ public abstract class ObjectUtils { private static final int INITIAL_HASH = 7; private static final int MULTIPLIER = 31; private static final String EMPTY_STRING = ""; private static final String NULL_STRING = "null"; private static final String ARRAY_START = "{"; private static final String ARRAY_END = "}"; private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END; private static final String ARRAY_ELEMENT_SEPARATOR = ", "; private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; private static final String NON_EMPTY_ARRAY = ARRAY_START + "..." + ARRAY_END; private static final String EMPTY_COLLECTION = "[]"; private static final String NON_EMPTY_COLLECTION = "[...]"; /** * Return whether the given throwable is a checked exception: * that is, neither a RuntimeException nor an Error. * @param ex the throwable to check * @return whether the throwable is a checked exception * @see java.lang.Exception * @see java.lang.RuntimeException * @see java.lang.Error */ public static boolean isCheckedException(Throwable ex) { return !(ex instanceof RuntimeException || ex instanceof Error); } /** * Check whether the given exception is compatible with the specified * exception types, as declared in a throws clause. * @param ex the exception to check * @param declaredExceptions the exception types declared in the throws clause * @return whether the given exception is compatible */ public static boolean isCompatibleWithThrowsClause(Throwable ex, @Nullable Class<?>... declaredExceptions) { if (!isCheckedException(ex)) { return true; } if (declaredExceptions != null) { for (Class<?> declaredException : declaredExceptions) { if (declaredException.isInstance(ex)) { return true; } } } return false; } /** * Determine whether the given object is an array: * either an Object array or a primitive array. * @param obj the object to check */ public static boolean isArray(@Nullable Object obj) { return (obj != null && obj.getClass().isArray()); } /** * Determine whether the given array is empty: * i.e. {@code null} or of zero length. * @param array the array to check * @see #isEmpty(Object) */ public static boolean isEmpty(@Nullable Object[] array) { return (array == null || array.length == 0); } /** * Determine whether the given object is empty. * <p>This method supports the following object types. * <ul> * <li>{@code Optional}: considered empty if not {@link Optional#isPresent()}</li> * <li>{@code Array}: considered empty if its length is zero</li> * <li>{@link CharSequence}: considered empty if its length is zero</li> * <li>{@link Collection}: delegates to {@link Collection#isEmpty()}</li> * <li>{@link Map}: delegates to {@link Map#isEmpty()}</li> * </ul> * <p>If the given object is non-null and not one of the aforementioned * supported types, this method returns {@code false}. * @param obj the object to check * @return {@code true} if the object is {@code null} or <em>empty</em> * @since 4.2 * @see Optional#isPresent() * @see ObjectUtils#isEmpty(Object[]) * @see StringUtils#hasLength(CharSequence) * @see CollectionUtils#isEmpty(java.util.Collection) * @see CollectionUtils#isEmpty(java.util.Map) */ public static boolean isEmpty(@Nullable Object obj) { if (obj == null) { return true; } if (obj instanceof Optional<?> optional) { return !optional.isPresent(); } if (obj instanceof CharSequence charSequence) { return charSequence.length() == 0; } if (obj.getClass().isArray()) { return Array.getLength(obj) == 0; } if (obj instanceof Collection<?> collection) { return collection.isEmpty(); } if (obj instanceof Map<?, ?> map) { return map.isEmpty(); } // else return false; } /** * Unwrap the given object which is potentially a {@link java.util.Optional}. * @param obj the candidate object * @return either the value held within the {@code Optional}, {@code null} * if the {@code Optional} is empty, or simply the given object as-is * @since 5.0 */ @Nullable public static Object unwrapOptional(@Nullable Object obj) { if (obj instanceof Optional<?> optional) { if (!optional.isPresent()) { return null; } Object result = optional.get(); Assert.isTrue(!(result instanceof Optional), "Multi-level Optional usage not supported"); return result; } return obj; } /** * Check whether the given array contains the given element. * @param array the array to check (may be {@code null}, * in which case the return value will always be {@code false}) * @param element the element to check for * @return whether the element has been found in the given array */ public static boolean containsElement(@Nullable Object[] array, Object element) { if (array == null) { return false; } for (Object arrayEle : array) { if (nullSafeEquals(arrayEle, element)) { return true; } } return false; } /** * Check whether the given array of enum constants contains a constant with the given name, * ignoring case when determining a match. * @param enumValues the enum values to check, typically obtained via {@code MyEnum.values()} * @param constant the constant name to find (must not be null or empty string) * @return whether the constant has been found in the given array */ public static boolean containsConstant(Enum<?>[] enumValues, String constant) { return containsConstant(enumValues, constant, false); } /** * Check whether the given array of enum constants contains a constant with the given name. * @param enumValues the enum values to check, typically obtained via {@code MyEnum.values()} * @param constant the constant name to find (must not be null or empty string) * @param caseSensitive whether case is significant in determining a match * @return whether the constant has been found in the given array */ public static boolean containsConstant(Enum<?>[] enumValues, String constant, boolean caseSensitive) { for (Enum<?> candidate : enumValues) { if (caseSensitive ? candidate.toString().equals(constant) : candidate.toString().equalsIgnoreCase(constant)) { return true; } } return false; } /** * Case insensitive alternative to {@link Enum#valueOf(Class, String)}. * @param <E> the concrete Enum type * @param enumValues the array of all Enum constants in question, usually per {@code Enum.values()} * @param constant the constant to get the enum value of * @throws IllegalArgumentException if the given constant is not found in the given array * of enum values. Use {@link #containsConstant(Enum[], String)} as a guard to avoid this exception. */ public static <E extends Enum<?>> E caseInsensitiveValueOf(E[] enumValues, String constant) { for (E candidate : enumValues) { if (candidate.toString().equalsIgnoreCase(constant)) { return candidate; } } throw new IllegalArgumentException("Constant [" + constant + "] does not exist in enum type " + enumValues.getClass().componentType().getName()); } /** * Append the given object to the given array, returning a new array * consisting of the input array contents plus the given object. * @param array the array to append to (can be {@code null}) * @param obj the object to append * @return the new array (of the same component type; never {@code null}) */ public static <A, O extends A> A[] addObjectToArray(@Nullable A[] array, @Nullable O obj) { return addObjectToArray(array, obj, (array != null ? array.length : 0)); } /** * Add the given object to the given array at the specified position, returning * a new array consisting of the input array contents plus the given object. * @param array the array to add to (can be {@code null}) * @param obj the object to append * @param position the position at which to add the object * @return the new array (of the same component type; never {@code null}) * @since 6.0 */ public static <A, O extends A> A[] addObjectToArray(@Nullable A[] array, @Nullable O obj, int position) { Class<?> componentType = Object.class; if (array != null) { componentType = array.getClass().componentType(); } else if (obj != null) { componentType = obj.getClass(); } int newArrayLength = (array != null ? array.length + 1 : 1); @SuppressWarnings("unchecked") A[] newArray = (A[]) Array.newInstance(componentType, newArrayLength); if (array != null) { System.arraycopy(array, 0, newArray, 0, position); System.arraycopy(array, position, newArray, position + 1, array.length - position); } newArray[position] = obj; return newArray; } /** * Convert the given array (which may be a primitive array) to an * object array (if necessary of primitive wrapper objects). * <p>A {@code null} source value will be converted to an * empty Object array. * @param source the (potentially primitive) array * @return the corresponding object array (never {@code null}) * @throws IllegalArgumentException if the parameter is not an array */ public static Object[] toObjectArray(@Nullable Object source) { if (source instanceof Object[] objects) { return objects; } if (source == null) { return EMPTY_OBJECT_ARRAY; } if (!source.getClass().isArray()) { throw new IllegalArgumentException("Source is not an array: " + source); } int length = Array.getLength(source); if (length == 0) { return EMPTY_OBJECT_ARRAY; } Class<?> wrapperType = Array.get(source, 0).getClass(); Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); for (int i = 0; i < length; i++) { newArray[i] = Array.get(source, i); } return newArray; } //--------------------------------------------------------------------- // Convenience methods for content-based equality/hash-code handling //--------------------------------------------------------------------- /** * Determine if the given objects are equal, returning {@code true} if * both are {@code null} or {@code false} if only one is {@code null}. * <p>Compares arrays with {@code Arrays.equals}, performing an equality * check based on the array elements rather than the array reference. * @param o1 first Object to compare * @param o2 second Object to compare * @return whether the given objects are equal * @see Object#equals(Object) * @see java.util.Arrays#equals */ public static boolean nullSafeEquals(@Nullable Object o1, @Nullable Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if (o1.equals(o2)) { return true; } if (o1.getClass().isArray() && o2.getClass().isArray()) { return arrayEquals(o1, o2); } return false; } /** * Compare the given arrays with {@code Arrays.equals}, performing an equality * check based on the array elements rather than the array reference. * @param o1 first array to compare * @param o2 second array to compare * @return whether the given objects are equal * @see #nullSafeEquals(Object, Object) * @see java.util.Arrays#equals */ private static boolean arrayEquals(Object o1, Object o2) { if (o1 instanceof Object[] objects1 && o2 instanceof Object[] objects2) { return Arrays.equals(objects1, objects2); } if (o1 instanceof boolean[] booleans1 && o2 instanceof boolean[] booleans2) { return Arrays.equals(booleans1, booleans2); } if (o1 instanceof byte[] bytes1 && o2 instanceof byte[] bytes2) { return Arrays.equals(bytes1, bytes2); } if (o1 instanceof char[] chars1 && o2 instanceof char[] chars2) { return Arrays.equals(chars1, chars2); } if (o1 instanceof double[] doubles1 && o2 instanceof double[] doubles2) { return Arrays.equals(doubles1, doubles2); } if (o1 instanceof float[] floats1 && o2 instanceof float[] floats2) { return Arrays.equals(floats1, floats2); } if (o1 instanceof int[] ints1 && o2 instanceof int[] ints2) { return Arrays.equals(ints1, ints2); } if (o1 instanceof long[] longs1 && o2 instanceof long[] longs2) { return Arrays.equals(longs1, longs2); } if (o1 instanceof short[] shorts1 && o2 instanceof short[] shorts2) { return Arrays.equals(shorts1, shorts2); } return false; } /** * Return as hash code for the given object; typically the value of * {@code Object#hashCode()}}. If the object is an array, * this method will delegate to any of the {@code nullSafeHashCode} * methods for arrays in this class. If the object is {@code null}, * this method returns 0. * @see Object#hashCode() * @see #nullSafeHashCode(Object[]) * @see #nullSafeHashCode(boolean[]) * @see #nullSafeHashCode(byte[]) * @see #nullSafeHashCode(char[]) * @see #nullSafeHashCode(double[]) * @see #nullSafeHashCode(float[]) * @see #nullSafeHashCode(int[]) * @see #nullSafeHashCode(long[]) * @see #nullSafeHashCode(short[]) */ public static int nullSafeHashCode(@Nullable Object obj) { if (obj == null) { return 0; } if (obj.getClass().isArray()) { if (obj instanceof Object[] objects) { return nullSafeHashCode(objects); } if (obj instanceof boolean[] booleans) { return nullSafeHashCode(booleans); } if (obj instanceof byte[] bytes) { return nullSafeHashCode(bytes); } if (obj instanceof char[] chars) { return nullSafeHashCode(chars); } if (obj instanceof double[] doubles) { return nullSafeHashCode(doubles); } if (obj instanceof float[] floats) { return nullSafeHashCode(floats); } if (obj instanceof int[] ints) { return nullSafeHashCode(ints); } if (obj instanceof long[] longs) { return nullSafeHashCode(longs); } if (obj instanceof short[] shorts) { return nullSafeHashCode(shorts); } } return obj.hashCode(); } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(@Nullable Object[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; for (Object element : array) { hash = MULTIPLIER * hash + nullSafeHashCode(element); } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(@Nullable boolean[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; for (boolean element : array) { hash = MULTIPLIER * hash + Boolean.hashCode(element); } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(@Nullable byte[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; for (byte element : array) { hash = MULTIPLIER * hash + element; } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(@Nullable char[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; for (char element : array) { hash = MULTIPLIER * hash + element; } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(@Nullable double[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; for (double element : array) { hash = MULTIPLIER * hash + Double.hashCode(element); } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(@Nullable float[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; for (float element : array) { hash = MULTIPLIER * hash + Float.hashCode(element); } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(@Nullable int[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; for (int element : array) { hash = MULTIPLIER * hash + element; } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(@Nullable long[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; for (long element : array) { hash = MULTIPLIER * hash + Long.hashCode(element); } return hash; } /** * Return a hash code based on the contents of the specified array. * If {@code array} is {@code null}, this method returns 0. */ public static int nullSafeHashCode(@Nullable short[] array) { if (array == null) { return 0; } int hash = INITIAL_HASH; for (short element : array) { hash = MULTIPLIER * hash + element; } return hash; } //--------------------------------------------------------------------- // Convenience methods for toString output //--------------------------------------------------------------------- /** * Return a String representation of an object's overall identity. * @param obj the object (may be {@code null}) * @return the object's identity as String representation, * or an empty String if the object was {@code null} */ public static String identityToString(@Nullable Object obj) { if (obj == null) { return EMPTY_STRING; } return obj.getClass().getName() + "@" + getIdentityHexString(obj); } /** * Return a hex String form of an object's identity hash code. * @param obj the object * @return the object's identity code in hex notation */ public static String getIdentityHexString(Object obj) { return Integer.toHexString(System.identityHashCode(obj)); } /** * Return a content-based String representation if {@code obj} is * not {@code null}; otherwise returns an empty String. * <p>Differs from {@link #nullSafeToString(Object)} in that it returns * an empty String rather than "null" for a {@code null} value. * @param obj the object to build a display String for * @return a display String representation of {@code obj} * @see #nullSafeToString(Object) */ public static String getDisplayString(@Nullable Object obj) { if (obj == null) { return EMPTY_STRING; } return nullSafeToString(obj); } /** * Determine the class name for the given object. * <p>Returns a {@code "null"} String if {@code obj} is {@code null}. * @param obj the object to introspect (may be {@code null}) * @return the corresponding class name */ public static String nullSafeClassName(@Nullable Object obj) { return (obj != null ? obj.getClass().getName() : NULL_STRING); } /** * Return a String representation of the specified Object. * <p>Builds a String representation of the contents in case of an array. * Returns a {@code "null"} String if {@code obj} is {@code null}. * @param obj the object to build a String representation for * @return a String representation of {@code obj} * @see #nullSafeConciseToString(Object) */ public static String nullSafeToString(@Nullable Object obj) { if (obj == null) { return NULL_STRING; } if (obj instanceof String string) { return string; } if (obj instanceof Object[] objects) { return nullSafeToString(objects); } if (obj instanceof boolean[] booleans) { return nullSafeToString(booleans); } if (obj instanceof byte[] bytes) { return nullSafeToString(bytes); } if (obj instanceof char[] chars) { return nullSafeToString(chars); } if (obj instanceof double[] doubles) { return nullSafeToString(doubles); } if (obj instanceof float[] floats) { return nullSafeToString(floats); } if (obj instanceof int[] ints) { return nullSafeToString(ints); } if (obj instanceof long[] longs) { return nullSafeToString(longs); } if (obj instanceof short[] shorts) { return nullSafeToString(shorts); } String str = obj.toString(); return (str != null ? str : EMPTY_STRING); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). * Returns a {@code "null"} String if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(@Nullable Object[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END); for (Object o : array) { stringJoiner.add(String.valueOf(o)); } return stringJoiner.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). * Returns a {@code "null"} String if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(@Nullable boolean[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END); for (boolean b : array) { stringJoiner.add(String.valueOf(b)); } return stringJoiner.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). * Returns a {@code "null"} String if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(@Nullable byte[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END); for (byte b : array) { stringJoiner.add(String.valueOf(b)); } return stringJoiner.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). * Returns a {@code "null"} String if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(@Nullable char[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END); for (char c : array) { stringJoiner.add('\'' + String.valueOf(c) + '\''); } return stringJoiner.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). * Returns a {@code "null"} String if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(@Nullable double[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END); for (double d : array) { stringJoiner.add(String.valueOf(d)); } return stringJoiner.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). * Returns a {@code "null"} String if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(@Nullable float[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END); for (float f : array) { stringJoiner.add(String.valueOf(f)); } return stringJoiner.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). * Returns a {@code "null"} String if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(@Nullable int[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END); for (int i : array) { stringJoiner.add(String.valueOf(i)); } return stringJoiner.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). * Returns a {@code "null"} String if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(@Nullable long[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END); for (long l : array) { stringJoiner.add(String.valueOf(l)); } return stringJoiner.toString(); } /** * Return a String representation of the contents of the specified array. * <p>The String representation consists of a list of the array's elements, * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated * by the characters {@code ", "} (a comma followed by a space). * Returns a {@code "null"} String if {@code array} is {@code null}. * @param array the array to build a String representation for * @return a String representation of {@code array} */ public static String nullSafeToString(@Nullable short[] array) { if (array == null) { return NULL_STRING; } int length = array.length; if (length == 0) { return EMPTY_ARRAY; } StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END); for (short s : array) { stringJoiner.add(String.valueOf(s)); } return stringJoiner.toString(); } /** * Generate a null-safe, concise string representation of the supplied object * as described below. * <p>Favor this method over {@link #nullSafeToString(Object)} when you need * the length of the generated string to be limited. * <p>Returns: * <ul> * <li>{@code "null"} if {@code obj} is {@code null}</li> * <li>{@code"Optional.empty"} if {@code obj} is an empty {@link Optional}</li> * <li>{@code"Optional[<concise-string>]"} if {@code obj} is a non-empty {@code Optional}, * where {@code <concise-string>} is the result of invoking {@link #nullSafeConciseToString} * on the object contained in the {@code Optional}</li> * <li>{@code "{}"} if {@code obj} is an empty array or {@link Map}</li> * <li>{@code "{...}"} if {@code obj} is a non-empty array or {@link Map}</li> * <li>{@code "[]"} if {@code obj} is an empty {@link Collection}</li> * <li>{@code "[...]"} if {@code obj} is a non-empty {@link Collection}</li> * <li>{@linkplain Class#getName() Class name} if {@code obj} is a {@link Class}</li> * <li>{@linkplain Charset#name() Charset name} if {@code obj} is a {@link Charset}</li> * <li>{@linkplain TimeZone#getID() TimeZone ID} if {@code obj} is a {@link TimeZone}</li> * <li>{@linkplain ZoneId#getId() Zone ID} if {@code obj} is a {@link ZoneId}</li> * <li>Potentially {@linkplain StringUtils#truncate(CharSequence) truncated string} * if {@code obj} is a {@link String} or {@link CharSequence}</li> * <li>Potentially {@linkplain StringUtils#truncate(CharSequence) truncated string} * if {@code obj} is a <em>simple value type</em> whose {@code toString()} method * returns a non-null value</li> * <li>Otherwise, a string representation of the object's type name concatenated * with {@code "@"} and a hex string form of the object's identity hash code</li> * </ul> * <p>In the context of this method, a <em>simple value type</em> is any of the following: * primitive wrapper (excluding {@link Void}), {@link Enum}, {@link Number}, * {@link java.util.Date Date}, {@link java.time.temporal.Temporal Temporal}, * {@link java.io.File File}, {@link java.nio.file.Path Path}, * {@link java.net.URI URI}, {@link java.net.URL URL}, * {@link java.net.InetAddress InetAddress}, {@link java.util.Currency Currency}, * {@link java.util.Locale Locale}, {@link java.util.UUID UUID}, * {@link java.util.regex.Pattern Pattern}. * @param obj the object to build a string representation for * @return a concise string representation of the supplied object * @since 5.3.27 * @see #nullSafeToString(Object) * @see StringUtils#truncate(CharSequence) * @see ClassUtils#isSimpleValueType(Class) */ public static String nullSafeConciseToString(@Nullable Object obj) { if (obj == null) { return "null"; } if (obj instanceof Optional<?> optional) { return (optional.isEmpty() ? "Optional.empty" : "Optional[%s]".formatted(nullSafeConciseToString(optional.get()))); } if (obj.getClass().isArray()) { return (Array.getLength(obj) == 0 ? EMPTY_ARRAY : NON_EMPTY_ARRAY); } if (obj instanceof Collection<?> collection) { return (collection.isEmpty() ? EMPTY_COLLECTION : NON_EMPTY_COLLECTION); } if (obj instanceof Map<?, ?> map) { // EMPTY_ARRAY and NON_EMPTY_ARRAY are also used for maps. return (map.isEmpty() ? EMPTY_ARRAY : NON_EMPTY_ARRAY); } if (obj instanceof Class<?> clazz) { return clazz.getName(); } if (obj instanceof Charset charset) { return charset.name(); } if (obj instanceof TimeZone timeZone) { return timeZone.getID(); } if (obj instanceof ZoneId zoneId) { return zoneId.getId(); } if (obj instanceof CharSequence charSequence) { return StringUtils.truncate(charSequence); } Class<?> type = obj.getClass(); if (ClassUtils.isSimpleValueType(type)) { String str = obj.toString(); if (str != null) { return StringUtils.truncate(str); } } return type.getTypeName() + "@" + getIdentityHexString(obj); } }
package ua.training.controller.commands.action.purge; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import ua.training.constant.Attributes; import ua.training.controller.commands.exception.DataSqlException; import ua.training.model.entity.User; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class DeleteUsersCompositionTest { @Mock private HttpServletRequest request; @Mock private HttpSession session; @Mock private User user; private String idRC; @Before public void setUp() { idRC = "1,Test,2,11,22"; } @After public void tearDown() { idRC = null; } @Test(expected = DataSqlException.class) public void execute() { DeleteUsersComposition deleteUsersComposition = new DeleteUsersComposition(); when(request.getSession()).thenReturn(session); when(session.getAttribute(Attributes.REQUEST_USER)).thenReturn(user); when(request.getParameter(Attributes.REQUEST_ARR_COMPOSITION)).thenReturn(idRC); deleteUsersComposition.execute(request); } }
package ffm.slc.model.enums; /** * An indication that the student has been identified as limited English proficient by the Language Proficiency Assessment Committee (LPAC), or English proficient. */ public enum LimitedEnglishProficiencyType { NOTLIMITED("NotLimited"), LIMITED("Limited"), LIMITED_MONITORED_1("Limited Monitored 1"), LIMITED_MONITORED_2("Limited Monitored 2"); private String prettyName; LimitedEnglishProficiencyType(String prettyName) { this.prettyName = prettyName; } @Override public String toString() { return prettyName; } }
package com.intent.olx.activity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import com.google.firebase.auth.FirebaseAuth; import com.intent.olx.R; import com.intent.olx.helper.ConfiguracaoFirebase; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Switch; import android.widget.Toast; public class AnunciosActivity extends AppCompatActivity { private FirebaseAuth autenticacao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_anuncios); //configs iniciais autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao(); //autenticacao.signOut(); } @Override //dando um inflate no menu que eu criei public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override //esse metodo será chamado antes dos menus serem exibidos public boolean onPrepareOptionsMenu(Menu menu) { //conferir se o user está logado if(autenticacao.getCurrentUser() == null){ //usuário deslogado menu.setGroupVisible(R.id.group_deslogado, true); }else{ //usuário logado menu.setGroupVisible(R.id.group_logado, true); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case R.id.menu_cadastrar: startActivity(new Intent(getApplicationContext(), CadastroActivity.class)); break; case R.id.menu_sair: autenticacao.signOut(); invalidateOptionsMenu(); break; } return super.onOptionsItemSelected(item); } }
package com.shahinnazarov.gradle; import com.shahinnazarov.gradle.models.k8s.PersistentVolumeClaim; import com.shahinnazarov.gradle.utils.K8sContext; import org.junit.Assert; import org.junit.Test; import java.util.Properties; public class K8sPersistentVolumeClaimGenerationTest { @Test public void generateSingle() { K8sContext.initialize(getSinglePersistentVolumeClaim()); K8sContext context = K8sContext.getInstance(); PersistentVolumeClaim persistentVolumeClaim = context.getPersistentVolumeClaim("ns01/pvc01"); System.out.println(context.getAsYaml(persistentVolumeClaim)); Assert.assertEquals(persistentVolumeClaim.getMetadata().getName(), "engine-event-consumer-logs"); } public Properties getSinglePersistentVolumeClaim() { Properties properties = new Properties(); properties.put("k8s.pvc.ns01/pvc01.name", "engine-event-consumer-logs"); properties.put("k8s.pvc.ns01/pvc01.storageClass", "base-storage"); properties.put("k8s.pvc.ns01/pvc01.accessModes", "rwo"); properties.put("k8s.pvc.ns01/pvc01.resource.requests.storage", "5Gi"); return properties; } }
package tjava.base; import static org.junit.Assert.assertEquals; import static tjava.base.CollectionUtilities.foldLeft; import static tjava.base.CollectionUtilities.foldRight; import static tjava.base.CollectionUtilities.list; import static tjava.base.CollectionUtilities.reverse; import java.util.List; import org.junit.Test; public class CollectionUtilitiesTest { @Test public void testFold() { List<Integer> list = list(1, 2, 3, 4, 5); Integer result = foldLeft(list, 0, x -> y -> x + y); assertEquals(15, result.intValue()); } @Test public void testFoldLeftVerification() { List<Integer> list = list(1, 2, 3, 4, 5); String identity = "0"; Function<String, Function<Integer, String>> f = x -> y -> addSILeft(x, y); String result = foldLeft(list, identity, f); assertEquals("(((((0 + 1) + 2) + 3) + 4) + 5)", result); } String addSILeft(String s, Integer i) { return "(" + s + " + " + i + ")"; } @Test public void testFoldRightVerification() { List<Integer> list = list(1, 2, 3, 4, 5); String identity = "0"; Function<String, Function<Integer, String>> f = x -> y -> addSIRight(x, y); String result = foldRight(list, identity, f); assertEquals("(1 + (2 + (3 + (4 + (5 + 0)))))", result); } String addSIRight(String s, Integer i) { return "(" + i + " + " + s + ")"; } @Test public void testReverse(){ List<Integer> src = list(1,2,3,4,5); List<Integer> rev = reverse(src); assertEquals(list(5,4,3,2,1), rev); } }
/* * 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 controller; import DAO.DataKeretaDAO; import KeretaApi.DataKereta; import KeretaApi.Loket; import KeretaApi.Menu; import KeretaApi.PesanTiket; import enkapsulasi.enkapsulasiDataKereta; import implement.implementDataKereta; import java.awt.Dimension; import java.awt.Toolkit; import java.util.List; import javax.swing.JOptionPane; import tabel.TabelDataKereta; import enkapsulasi.enkapsulasiLoket; /** * * @author ASUS */ public class datakeretaController { Dimension layar = Toolkit.getDefaultToolkit().getScreenSize(); private List<enkapsulasiDataKereta> List; private static DataKereta keretaPanel; private implementDataKereta implementDataKereta; public datakeretaController(DataKereta keretaPanel) { this.keretaPanel = keretaPanel; implementDataKereta = new DataKeretaDAO(); lokasiform(); Tabel(); } public void lokasiform(){ int x = layar.width / 2 -keretaPanel.getSize().width / 2; int y = layar.height / 2 - keretaPanel.getSize().height / 2; keretaPanel.setLocation(x, y); } public void save(){ String kodekereta = null; String namakereta = null; String jurusan = null; String keberangkatan = null; String jenis = null; String nomorkursi = null; String harga = null; if (keretaPanel.getCbkodekereta().getSelectedItem().toString().equals("")){ kodekereta = "null"; }else{ kodekereta = keretaPanel.getCbkodekereta().getSelectedItem().toString(); } if (keretaPanel.getCbnamakereta().getSelectedItem().toString().equals("")){ namakereta = "null"; }else{ namakereta = keretaPanel.getCbnamakereta().getSelectedItem().toString(); } if (keretaPanel.getCbjurusan().getSelectedItem().toString().equals("")){ jurusan = "null"; }else{ jurusan = keretaPanel.getCbjurusan().getSelectedItem().toString(); } if (keretaPanel.getCbkeberangkatan().getSelectedItem().toString().equals("")){ keberangkatan = "null"; }else{ keberangkatan = keretaPanel.getCbkeberangkatan().getSelectedItem().toString(); } if (keretaPanel.getCbjenis().getSelectedItem().toString().equals("")){ jenis = "null"; }else{ jenis = keretaPanel.getCbjenis().getSelectedItem().toString(); } if (keretaPanel.getNomorkursi2().getText().toString().equals("")){ nomorkursi = "null"; }else{ nomorkursi = keretaPanel.getNomorkursi2().getText().toString(); } if (keretaPanel.getHarga2().getText().toString().equals("")){ harga = "null"; }else{ harga = keretaPanel.getHarga2().getText().toString(); } if (implementDataKereta.save(kodekereta, namakereta, jurusan, keberangkatan, jenis, nomorkursi, harga)){ JOptionPane.showMessageDialog(null, "Data Telah Ditambahkan"); Tabel(); }else{ JOptionPane.showMessageDialog(null, "Data Gagal Ditambahkan"); } } //untuk menghapus data public void tombolDelete(){ if(implementDataKereta.delete(keretaPanel.getCbkodekereta().getSelectedItem().toString())){ JOptionPane.showMessageDialog(null, "Data Telah Dihapus"); Tabel(); }else{ JOptionPane.showMessageDialog(null, "Data Gagal Dihapus"); } } //untuk mencari data public void tombolSearch(){ String kodekereta = null; String namakereta = null; String jurusan = null; String keberangkatan = null; String jenis = null; String nomorkursi = null; String harga = null; if (keretaPanel.getCbkodekereta().getSelectedItem().toString().equals("")){ kodekereta = "null"; }else{ kodekereta = keretaPanel.getCbkodekereta().getSelectedItem().toString(); } if (keretaPanel.getCbnamakereta().getSelectedItem().toString().equals("")){ namakereta = "null"; }else{ namakereta = keretaPanel.getCbnamakereta().getSelectedItem().toString(); } if (keretaPanel.getCbjurusan().getSelectedItem().toString().equals("")){ jurusan = "null"; }else{ jurusan = keretaPanel.getCbjurusan().getSelectedItem().toString(); } if (keretaPanel.getCbkeberangkatan().getSelectedItem().toString().equals("")){ keberangkatan = "null"; }else{ keberangkatan = keretaPanel.getCbkeberangkatan().getSelectedItem().toString(); } if (keretaPanel.getCbjenis().getSelectedItem().toString().equals("")){ jenis = "null"; }else{ jenis = keretaPanel.getCbjenis().getSelectedItem().toString(); } if (keretaPanel.getNomorkursi2().getText().toString().equals("")){ nomorkursi = "null"; }else{ nomorkursi = keretaPanel.getNomorkursi2().getText().toString(); } if (keretaPanel.getHarga2().getText().toString().equals("")){ harga = "null"; }else{ harga = keretaPanel.getHarga2().getText().toString(); } List = implementDataKereta.search(kodekereta, namakereta, jurusan, keberangkatan, jenis, nomorkursi, harga); keretaPanel.getTabeldatakereta().setModel(new TabelDataKereta(List)); JOptionPane.showMessageDialog(null,"Data Ditemukan"); //komponen("cari"); } public void tombolUpdate(){ String kodekereta = keretaPanel.getCbkodekereta().getSelectedItem().toString(); String namakereta = keretaPanel.getCbnamakereta().getSelectedItem().toString(); String jurusan = keretaPanel.getCbjurusan().getSelectedItem().toString(); String keberangkatan = keretaPanel.getCbkeberangkatan().getSelectedItem().toString(); String jenis = keretaPanel.getCbjenis().getSelectedItem().toString(); String nomorkursi = keretaPanel.getNomorkursi2().getText().toString(); String harga = keretaPanel.getHarga2().getText().toString(); if (implementDataKereta.update(kodekereta, namakereta, jurusan, keberangkatan, jenis, nomorkursi, harga)) { JOptionPane.showMessageDialog(null,"Data Berhasil Di Update"); Tabel(); } else { JOptionPane.showMessageDialog(null, "Data gagal Di Update"); } } public void klikTabel(java.awt.event.MouseEvent evt){ try { int row = keretaPanel.getTabeldatakereta().rowAtPoint(evt.getPoint()); String kodekereta = keretaPanel.getTabeldatakereta().getValueAt(row, 0).toString(); String namakereta = keretaPanel.getTabeldatakereta().getValueAt(row, 1).toString(); String jurusan = keretaPanel.getTabeldatakereta().getValueAt(row, 2).toString(); String keberangkatan = keretaPanel.getTabeldatakereta().getValueAt(row, 3).toString(); String jenis = keretaPanel.getTabeldatakereta().getValueAt(row, 4).toString(); String nomorkursi = keretaPanel.getTabeldatakereta().getValueAt(row, 5).toString(); String harga = keretaPanel.getTabeldatakereta().getValueAt(row, 6).toString(); keretaPanel.getCbkodekereta().setSelectedItem(String.valueOf(kodekereta)); keretaPanel.getCbnamakereta().setSelectedItem(String.valueOf(namakereta)); keretaPanel.getCbjurusan().setSelectedItem(String.valueOf(jurusan)); keretaPanel.getCbkeberangkatan().setSelectedItem(String.valueOf(keberangkatan)); keretaPanel.getCbjenis().setSelectedItem(String.valueOf(jenis)); keretaPanel.getNomorkursi2().setText(String.valueOf(nomorkursi)); keretaPanel.getHarga2().setText(String.valueOf(harga)); } catch (Exception e) { e.printStackTrace(); } } public void Tabel (){ List = implementDataKereta.getAllDataKereta(); keretaPanel.getTabeldatakereta().setModel(new TabelDataKereta(List)); } public void tombolReset(){ keretaPanel.getCbkodekereta().setSelectedItem("---"); keretaPanel.getCbnamakereta().setSelectedItem("---"); keretaPanel.getCbjurusan().setSelectedItem("---"); keretaPanel.getCbkeberangkatan().setSelectedItem("---"); keretaPanel.getCbjenis().setSelectedItem("---"); keretaPanel.getNomorkursi2().setText("---"); keretaPanel.getHarga2().setText("---"); } public void tombolNext(){ new Loket().setVisible(true); keretaPanel.setVisible(false); } public void tombolBack(){ new PesanTiket().setVisible(true); keretaPanel.setVisible(false); } public void Menu(){ new Menu().setVisible(true); keretaPanel.setVisible(false); } public void DataTiket(){ new PesanTiket().setVisible(true); keretaPanel.setVisible(false); } }
package org.fitnesse.widgets.fixtureapi.writer; import static org.apache.commons.lang.StringUtils.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.antlr.stringtemplate.StringTemplate; import org.apache.commons.io.IOUtils; import org.fitnesse.widgets.fixtureapi.scanner.Parameter; public class HtmlWriter implements SourceWriter { @SuppressWarnings("unused") private class Method { private final String javadoc; private final String name; private final List<Parameter> params; private final String returns; public Method(final String name, final String javadoc, final String returns, final List<Parameter> params) { this.name = name; this.javadoc = cleanupJavaDoc(javadoc); this.returns = returns; this.params = params; } public String getJavadoc() { return javadoc; } public String getName() { return name; } public String getReadableName() { return CamelCaseSplitter.splitString(name); } public List<Parameter> getParams() { return params; } public String getReturns() { return returns; } public boolean getHasParams() { return params != null && params.size() > 0; } private String cleanupJavaDoc(final String javadoc) { return trim(remove(remove(remove(javadoc, "/"), "*"), "\t")); } } private String className; private final List<Method> methods = new ArrayList<Method>(); private String packageName; @Override public void addClass(final String className) { this.className = className; } @Override public void addMethod(final String name, final String javadoc, final String returns, final List<Parameter> params) { methods.add(new Method(name, javadoc, returns, params)); } @Override public void addPackage(final String packageName) { this.packageName = packageName; } private String cleanUp(final String formattedHtml) { return trim(formattedHtml); } @Override public String toString() { String template; try { template = IOUtils.toString(this.getClass().getResourceAsStream("/htmlTemplate.st")); final StringTemplate st = new StringTemplate(template); st.setAttribute("package", packageName); st.setAttribute("methods", methods); st.setAttribute("className", className); return cleanUp(st.toString()); } catch (final IOException e) { throw new RuntimeException("Error occured while creating html output", e); } } static class CamelCaseSplitter { public static String splitString(final String name) { return capitalize(join(splitIntoWords(name), " ")); } private static List<String> splitIntoWords(final String string) { final List<String> words = new ArrayList<String>(); String word = ""; for (int i=0; i < string.length(); i++) { final Character c = string.charAt(i); if (i>0 && isUpper(c) && !isUpper(string.charAt(i-1))) { words.add(word); word = "" + Character.toLowerCase(c); } else { word += c; } } words.add(word); return words; } private static boolean isUpper(final char c) { return Character.isUpperCase(c); } } }
package com.example.NFEspring.entity; import javax.persistence.*; import javax.persistence.Entity; import javax.validation.constraints.NotEmpty; import java.io.Serializable; @Entity @Table(name = "region") public class Region implements Serializable { @Id @Column(name = "rg_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "rg_postal", length = 2) @NotEmpty private String postal; @Column(name = "rg_capital", length = 5) @NotEmpty private String capital; @Column(name = "rg_name") @NotEmpty private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPostal() { return postal; } public void setPostal(String postal) { this.postal = postal; } public String getCapital() { return capital; } public void setCapital(String capital) { this.capital = capital; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.liziyi; import java.util.ArrayList; import static sun.swing.MenuItemLayoutHelper.max; /** * @version 1.0 * @Description * @Author liziyi * @CreateDate 2021/1/14 20:45 * @UpdateUser * @UpdateDate * @UpdateRemark */ public class Solution152 { public int maxProduct(int[] nums) { int imax = 1;int imin = 1; int max = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { //当负数时,交换最大值和最小值 if (nums[i] < 0) { int x = imax; imax = imin; imin = x; } //最大值等于nums[i],或者最大值*nums[i] imax = Math.max(nums[i] , imax * nums[i]); imin = Math.min(nums[i] , imin * nums[i]); //找到最大值 max = Math.max(imax,max); } return max; } public static void main(String[] args) { int a[] = {-2,0,-1}; Solution152 solution152 = new Solution152(); solution152.maxProduct(a); } }
package org.deeplearning4j.nn.graph.vertex; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import java.io.Serializable; /** * Created by endy on 16/9/8. */ @AllArgsConstructor @EqualsAndHashCode public class VertexIndices implements Serializable { private final int vertexIndex; private final int vertexEdgeNumber; VertexIndices(int vertexIndex,int vertexEdgeNumber){ this.vertexIndex = vertexIndex; this.vertexEdgeNumber = vertexEdgeNumber; } /**Index of the vertex */ public int getVertexIndex() { return this.vertexIndex; } /** The edge number. Represents the index of the output of the vertex index, OR the index of the * input to the vertex, depending on the context */ public int getVertexEdgeNumber() { return this.vertexEdgeNumber; } public String toString() { return "VertexIndices(vertexIndex=" + this.vertexIndex + ", vertexEdgeNumber=" + this.vertexEdgeNumber + ")"; } }
public class tetrahedron extends triangle{ public tetrahedron(double side, double height) { super(side, height); } double a= height; double b = (Math.sqrt(3)/6)*side; double c = Math.sqrt(Math.pow(a, 2)+Math.pow(b, 2)); public double getA() { return a; } public void setA(double a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } public double getC() { return c; } public void setC(double c) { this.c = c; } @Override public double area() { return Math.sqrt(3)*side*c; } @Override public double volume() { return (1/3.0) * (((Math.sqrt(3))/4)*side*side) * height; } public String toString() { return "Triangle Pyramid: "+"height : " + height + "\n"+ "perimeter of base : "+ pC() + " volume : " + volume() +"\n"+ " area : "+ area(); } }
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.springframework.context.annotation; import org.springframework.beans.factory.config.BeanDefinition; /** * Strategy interface for resolving the scope of bean definitions. * * @author Mark Fisher * @since 2.5 * @see org.springframework.context.annotation.Scope */ @FunctionalInterface public interface ScopeMetadataResolver { /** * Resolve the {@link ScopeMetadata} appropriate to the supplied * bean {@code definition}. * <p>Implementations can of course use any strategy they like to * determine the scope metadata, but some implementations that spring * immediately to mind might be to use source level annotations * present on {@link BeanDefinition#getBeanClassName() the class} of the * supplied {@code definition}, or to use metadata present in the * {@link BeanDefinition#attributeNames()} of the supplied {@code definition}. * @param definition the target bean definition * @return the relevant scope metadata; never {@code null} */ ScopeMetadata resolveScopeMetadata(BeanDefinition definition); }
package paper1; import java.util.Arrays; public class dummy { public static void main(String[] args) { } public static void main01(String[] args) { int result = 1; int x = 4; while (x > 1) { result = result * x; x--; } System.out.println(result); } public static void main07 (String[] args) { int array[] = {2, 19, 5, 17}; int result = array[0]; for (int i = 1; i < array.length; i++) if (array[i] > result) result = array[i]; System.out.println(result); } public static void main08(String[] args) { int number = 323; int result = 0; while (number!= 0) { result = result + number % 10; number = number / 10; } System.out.println(result); } public static void main09(String[] args){ int number = 11; boolean result = true; for(int i = 2; i < number; i++) { if(number % i == 0) { result = false; break; } } System.out.println(result); } public static void main10(String[] args) { int num1 = 5; int num2 = 3; int num3 = 10; if (num1 > num2 && num1 > num3) System.out.println(num1); else if (num2 > num1 && num2 > num3) System.out.println(num2); else if (num3 > num1 && num3 > num2) System.out.println(num3); } public static void main11(String[] args) { int num1 = 2; int num2 = 3; int result = num1; for (int i = 1; i < num2; i++) { result = result * num1; } System.out.println(result); } public static void main13(String[] args) { int var1 = 23; int var2 = 42; int temp; temp = var1; var1 = var2; var2 = temp; System.out.println(var1); } public static void main14(String[] args) { String word = "Hello"; String result = new String(); for ( int j = word.length() - 1; j >= 0; j-- ) result += word.charAt(j); System.out.println(word); } public static void main17(String[] args) {String word = "Programming in Java"; String key1 = "Java"; String key2 = "Pascal"; int index1 = word.indexOf(key1); int index2 = word.indexOf(key2); if (index1 != -1) System.out.println("Substring is contained: " + key1); else System.out.println("Substring is not contained: " + key1); if (index2 != -1) System.out.println("Substring is contained: " + key2); else System.out.println("Substring is not contained: " + key2); } public static void main20(String[] args) { int i=14; String result=""; while (i>0) { if (i%2 ==0) result="0"+result; else result="1"+result; i=i/2; } System.out.println(result); } public static void main21(String[] args) { int[] array = { 1, 6, 4, 10, 2 }; for (int i = 0; i <= array.length/2-1; i++){ int tmp=array[array.length-i-1]; array[array.length-i-1] = array[i]; array[i]=tmp; } for (int i = 0; i <= array.length - 1; i++) System.out.println(array[i]); } public static void main22(String[] args) { int[] array={1,2,4,5,6,10}; Arrays.sort(array); // era array.sort(aufsteigend); float b; if (array.length % 2==1) b=array[array.length /2]; else b=(array[array.length/2-1]+array[array.length/2])/2f; System.out.println(b); } public static void main02(String[] args) { String string1 = "Magdeburg"; String string2 = "Hamburg"; int length; if (string1.length() < string2.length()) length = string1.length(); else length = string2.length(); int counter=0; for (int i = 0; i < length; i++) { if (string1.charAt(i) == string2.charAt(i)) { counter++; } } System.out.println(counter); } public static void main06 (String[] args) { int n = 4; int result = 0; for (int i = 1; i <= n; i++) result = result + i; System.out.println(result); } public static void main12(String[] args) { String word = "otto"; boolean result = true; for (int i = 0, j = word.length() - 1; i < word.length()/2; i++, j--) { if (word.charAt(i) != word.charAt(j)) { result = false; break; } } System.out.println(result); } public static void main23(String[] args) {int[] array = { 1, 3, 11, 7, 4 }; for (int i = 0; i < array.length; i++) array[i] = array[i] * 2; for (int i = 0; i <= array.length - 1; i++) System.out.println(array[i]); } public static void main03(int number1, int number2) { int temp; do { if (number1 < number2) { temp = number1; number1 = number2; number2 = temp; } temp = number1 % number2; if (temp != 0) { number1 = number2; number2 = temp; } } while (temp != 0); System.out.println(number2); } public static void main04(String[] args) { int array[] = {14,5,7}; for (int counter1 = 0; counter1 < array.length; counter1++) { for (int counter2 = counter1; counter2 > 0; counter2--) { if (array[counter2 - 1] > array[counter2]) { int variable1 = array[counter2]; array[counter2] = array[counter2 - 1]; array[counter2 - 1] = variable1; } } } for (int counter3 = 0; counter3 < array.length; counter3++) System.out.println(array[counter3]); } public static void main05(String[] args) { int array[] = { 2, 4, 5, 6, 8, 10, 13 }; int key = 5; int index1 = 0; int index2 = array.length - 1; while (index1 <= index2) { int m = (index1 + index2) / 2; if (key < array[m]) index2 = m - 1; else if (key > array[m]) index1 = m + 1; else { System.out.println(m); break; } } } public static void main15(String[] args) { int array[][] = {{5,6,7},{4,8,9}}; int array1[][] = {{6,4},{5,7},{1,1}}; int array2[][] = new int[3][3]; int x = array.length; int y = array1.length; for(int i = 0; i < x; i++) { for(int j = 0; j < y-1; j++) { for(int k = 0; k < y; k++){ array2[i][j] += array[i][k]*array1[k][j]; } } } for(int i = 0; i < x; i++) { for(int j = 0; j < y-1; j++) { System.out.print(" "+array2[i][j]); } } } public static void main16(String[] args){ int a = 4; int b = 8; int result = (a + b) / 2; System.out.println(result); } public static void main18(String[] args){ int number1 = 23; int number2 = 42; int max, min; int result = -1; if (number1>number2) { max = number1; min = number2; } else { max = number2; min = number1; } for(int i=1; i<=min; i++) { if( (max*i)%min == 0 ) { result = i*max; break; } } if(result != -1) System.out.println(result); else System.out.println("Error!"); } public static void main19(String[] args) { String s = "here are a bunch of words"; final StringBuilder result = new StringBuilder(s.length()); String[] words = s.split("\\s"); for(int i=0,l=words.length;i<l;++i) { if(i>0) result.append(" "); result.append(Character.toUpperCase(words[i].charAt(0))) .append(words[i].substring(1)); } System.out.println(result); } }
package com.micHon.discount_strategy; public class SalePrice implements PricingStrategy { public void calculatePrice(int price, boolean isSignedUpForNewsLetter) { if (isSignedUpForNewsLetter) { int discountPrice = price / 2; System.out.println("The discount price is: " + discountPrice); } else { System.out.println("User not signed up, choose another strategy!"); } } }
package com.zxt.framework.jdbc; import java.util.Collection; import java.util.List; import javax.sql.DataSource; import com.zxt.framework.common.dao.IDAOSupport; import com.zxt.framework.page.dialect.Dialect; public class ZXTJDBCDaoSupport implements IDAOSupport { // private Dialect dialect; private ZXTJDBCTemplate zxtJDBCTemplate; private Dialect dialect; public ZXTJDBCDaoSupport() { } /** * 设置数据源 * * @param dataSource */ public final void setDataSource(DataSource dataSource) { if (zxtJDBCTemplate == null || dataSource != zxtJDBCTemplate.getDataSource()) { zxtJDBCTemplate = createJdbcTemplate(dataSource); initTemplateConfig(); } } /** * 创建jdbc模板 * * @param dataSource * @return */ protected ZXTJDBCTemplate createJdbcTemplate(DataSource dataSource) { return new ZXTJDBCTemplate(dataSource); } public final DataSource getDataSource() { return zxtJDBCTemplate == null ? null : zxtJDBCTemplate.getDataSource(); } /** * 设置jdbc模板类 * * @param zxtJDBCTemplate */ public final void setJdbcTemplate(ZXTJDBCTemplate zxtJDBCTemplate) { this.zxtJDBCTemplate = zxtJDBCTemplate; initTemplateConfig(); } public final ZXTJDBCTemplate getJdbcTemplate() { return zxtJDBCTemplate; } protected void initTemplateConfig() { } /** * 检查sql配置 */ protected void checkDaoConfig() { if (zxtJDBCTemplate == null) throw new IllegalArgumentException( "'dataSource' or 'jdbcTemplate' is required"); else return; } // protected final SQLExceptionTranslator getExceptionTranslator() // { // return getJdbcTemplate().getExceptionTranslator(); // } // // protected final Connection getConnection() // throws CannotGetJdbcConnectionException // { // return DataSourceUtils.getConnection(getDataSource()); // } // // protected final void releaseConnection(Connection con) // { // DataSourceUtils.releaseConnection(con, getDataSource()){} // } /** * 继承父类方法 */ public List find(String paramString) { return null; } /** * 继承父类方法 */ public List find(String paramString, Object paramObject) { return null; } /** * 继承父类方法 */ public List find(String paramString, Object[] paramArrayOfObject) { return null; } /** * 继承父类方法 */ public void create(Object paramObject) { } /** * 继承父类方法 */ public void delete(Object paramObject) { } /** * 继承父类方法 */ public boolean executeSQLUpdate(String updateString) { // TODO Auto-generated method stub return false; } /** * 继承父类方法 */ public void update(Object paramObject) { } /** * 继承父类方法 */ public void deleteAll(Collection paramCollection) { } /** * 继承父类方法 */ public void updateAll(Collection paramCollection) { } /** * 继承父类方法 */ public List findAll() { return null; } /** * 继承父类方法 */ public int findTotalRows(String queryString) { return zxtJDBCTemplate.findTotalRows(queryString); } /** * 继承父类方法 */ public List findAllByPage(String paramString, int page, int rows) { return null; } public void createAll(Collection paramCollection) { } /** * 继承父类方法 */ public List findToMap(String sql) { return zxtJDBCTemplate.findToMaps(sql); } /** * 继承父类方法 */ public Dialect getDialect() { return dialect; } /** * 继承父类方法 */ public void setDialect(Dialect dialect) { this.dialect = dialect; } /** * 继承父类方法 */ public ZXTJDBCTemplate getZxtJDBCTemplate() { return zxtJDBCTemplate; } /** * 继承父类方法 */ public void setZxtJDBCTemplate(ZXTJDBCTemplate zxtJDBCTemplate) { this.zxtJDBCTemplate = zxtJDBCTemplate; } // public Dialect getDialect() { // return dialect; // } // // public void setDialect(Dialect dialect) { // this.dialect = dialect; // } }
/** * Find N-closest quakes * * @author Duke Software/Learn to Program * @version 1.0, November 2015 */ import java.util.*; public class ClosestQuakes { public ArrayList<QuakeEntry> getClosest(ArrayList<QuakeEntry> quakeData, Location current, int howMany) { ArrayList<QuakeEntry> ret = new ArrayList<QuakeEntry>(); ArrayList<QuakeEntry> cData = new ArrayList<QuakeEntry>(quakeData); // TO DO for (int i = 0;i<howMany;i++){ QuakeEntry closestQE = cData.get(0); for(QuakeEntry qe : cData){ if (current.distanceTo(qe.getLocation())< current.distanceTo(closestQE.getLocation()) ){ closestQE = qe; } } ret.add(closestQE); cData.remove(closestQE); if (cData.size()==0){ break; } } return ret; } public void findClosestQuakes() { EarthQuakeParser parser = new EarthQuakeParser(); String source = "data/nov20quakedatasmall.atom"; //String source = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.atom"; ArrayList<QuakeEntry> list = parser.read(source); System.out.println("read data for "+list.size()); Location jakarta = new Location(-6.211,106.845); ArrayList<QuakeEntry> close = getClosest(list,jakarta,3); for(int k=0; k < close.size(); k++){ QuakeEntry entry = close.get(k); double distanceInMeters = jakarta.distanceTo(entry.getLocation()); System.out.printf("%4.2f\t %s\n", distanceInMeters/1000,entry); } System.out.println("number found: "+close.size()); } }
class Casio { // method for adding two numbers public void add(int a, int b) { System.out.println(a + b); } // performing the method over loading // same method name but different parameters public void add(int a , int b, double c) { System.out.println(a + b + (int)c); } } public class MethodOverLoading { public static void main(String[] args) { Casio cas = new Casio(); cas.add(5,6); // calling the method of class Casio cas.add(45,67,97.4567); // overloading } }
/* * LcmsTocServiceImpl.java 1.00 2011-09-14 * * Copyright (c) 2011 ???? Co. All Rights Reserved. * * This software is the confidential and proprietary information * of um2m. You shall not disclose such Confidential Information * and shall use it only in accordance with the terms of the license agreement * you entered into with um2m. */ package egovframework.com.lcms.len.service.impl; import java.io.InputStream; import java.io.ObjectInputStream; import java.sql.Blob; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.stereotype.Service; import egovframework.rte.fdl.excel.EgovExcelService; import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl; import egovframework.adm.lcms.cts.model.LcmsScormModel; import egovframework.com.lcms.len.service.LcmsTocService; import egovframework.com.lcms.len.dao.LcmsTocDAO; import egovframework.com.lcms.len.domain.LcmsToc; /** * <pre> * system : * menu : * source : LcmsTocServiceImpl.java * description : * </pre> * @version * <pre> * 1.0 2011-09-14 created by ? * 1.1 * </pre> */ @Service("lcmsTocService") public class LcmsTocServiceImpl extends EgovAbstractServiceImpl implements LcmsTocService { @Resource(name="lcmsTocDAO") private LcmsTocDAO lcmsTocDAO; public List selectLcmsTocPageList( Map<String, Object> commandMap) throws Exception { return lcmsTocDAO.selectLcmsTocPageList( commandMap); } public int selectLcmsTocPageListTotCnt( Map<String, Object> commandMap) throws Exception { return lcmsTocDAO.selectLcmsTocPageListTotCnt( commandMap); } public List selectLcmsTocList( Map<String, Object> commandMap) throws Exception { return lcmsTocDAO.selectLcmsTocList( commandMap); } public Object selectLcmsToc( Map<String, Object> commandMap) throws Exception { LcmsToc output = new LcmsToc(); output = (LcmsToc)lcmsTocDAO.selectLcmsToc( commandMap); if(output != null) output.setSerializer(LcmsScormModel.read(output.getSerializer())); return output; } public Object insertLcmsToc( Map<String, Object> commandMap) throws Exception { commandMap.put("serializer",LcmsScormModel.write(commandMap.get("serializer"))); return lcmsTocDAO.insertLcmsToc( commandMap); } public int updateLcmsToc( Map<String, Object> commandMap) throws Exception { commandMap.put("serializer",LcmsScormModel.write(commandMap.get("serializer"))); return lcmsTocDAO.updateLcmsToc( commandMap); } public int updateFieldLcmsToc( Map<String, Object> commandMap) throws Exception { return lcmsTocDAO.updateFieldLcmsToc( commandMap); } public int deleteLcmsToc( Map<String, Object> commandMap) throws Exception { return lcmsTocDAO.deleteLcmsToc( commandMap); } public int deleteLcmsTocAll( Map<String, Object> commandMap) throws Exception { return lcmsTocDAO.deleteLcmsTocAll( commandMap); } public Object existLcmsToc( LcmsToc lcmsToc) throws Exception { return lcmsTocDAO.existLcmsToc( lcmsToc); } }
package com.atlassian.theplugin.jira.model; import com.atlassian.theplugin.commons.jira.api.JiraIssueAdapter; import org.jetbrains.annotations.NotNull; import java.util.Collection; public interface JIRAIssueListModel extends FrozenModel { void clear(); // void addIssue(JIRAIssue issue); void addIssues(Collection<JiraIssueAdapter> issues); Collection<JiraIssueAdapter> getIssues(); Collection<JiraIssueAdapter> getIssuesNoSubtasks(); /** * Returns list of subtasks of the issue * * @param parent - parent of subtasks. If null is passed, subtasks for issues that are not in the model are returned * @return subtasks for the parent */ @NotNull Collection<JiraIssueAdapter> getSubtasks(JiraIssueAdapter parent); JiraIssueAdapter findIssue(String key); // void setSeletedIssue(JIRAIssue issue); void updateIssue(JiraIssueAdapter issue); void fireIssuesLoaded(int numberOfLoadedIssues); void fireIssueUpdated(final JiraIssueAdapter issue); void fireModelChanged(); void addModelListener(JIRAIssueListModelListener listener); void removeModelListener(JIRAIssueListModelListener listener); // void clearCache(); // Set<JIRAIssue> getIssuesCache(); // JIRAIssue getIssueFromCache(IssueRecentlyOpenBean recentIssue); }
package com.fanoi.dream.module.setting.activities; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.fanoi.dream.R; import com.fanoi.dream.module.BaseActivity; /** * 说明图片 * Created by Jette on 2016/4/15. */ public class ExaminationPicsActivity extends BaseActivity { private ViewPager viewPager; private PicsPagerAdapter picsPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_examination_pics); viewPager = (ViewPager) findViewById(R.id.activity_examination_pics_viewPager); viewPager.setOffscreenPageLimit(2); int[] images = initData(); initAdapter(images); } private void initAdapter(int[] images) { picsPagerAdapter = new PicsPagerAdapter(images); viewPager.setAdapter(picsPagerAdapter); } private int[] initData() { return new int[]{R.drawable.a, R.drawable.b, R.drawable.c}; } /** * 适配器 */ private class PicsPagerAdapter extends PagerAdapter { private int[] images; PicsPagerAdapter(int[] images) { this.images = images; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public int getCount() { return images.length; } @Override public Object instantiateItem(ViewGroup view, int position) { ImageView imageView = new ImageView(view.getContext()); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(images[position]); view.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); return imageView; } } }
package me.groot314_zordain.Friendslist; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; public class FriendslistExecutor implements CommandExecutor { @SuppressWarnings("unused") private Friendslist plugin; public FriendslistExecutor(Friendslist plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command cmd,String label, String[] args) { if (cmd.getName().equalsIgnoreCase("friendslist")){ Bukkit.getServer().broadcastMessage("FriendsList----------"); Bukkit.getServer().broadcastMessage("/FL Help - To See this"); Bukkit.getServer().broadcastMessage("/FL friends - to see Friends list"); Bukkit.getServer().broadcastMessage("/FL add - to add friends"); return true; } return false; } }
package hello; import java.util.Scanner; public class Operator { public static void main(String[] args) { int i = 10; int j = 5; int a = i + j; int c = i * j; int d = i / j; int a1 = 5; long b1 = 6; int c1 = (int)(a1 + b1); long d1 = a1 + b1; byte a2 = 1; byte b2 = 2; byte c2 = (byte)(a2 + b2); int d2 = a2 + b2; int i3 = 5; int j3 = 2; System.out.println(i3 % j3); int i4 = 5; i4++; System.out.println(i4); int i5 = 5; System.out.println(i5++); System.out.println(i5); int j5 = 5; System.out.println(++j5); System.out.println(j5); int a6 = 5; int b6 = 6; int c6 = 5; System.out.println(a6 > b6); System.out.println(a6 >= c6); System.out.println(a6 == b6); System.out.println(a6 != b6); int i7 = 2; System.out.println(i7 == 1 & i7++ == 2); System.out.println(i7); int j7 = 2; System.out.println(j7 == 1 && j7++ == 2); System.out.println(j7); int i8 = 2; System.out.println(i8 == 1 | i8++ == 2); System.out.println(i8); int j8 = 2; System.out.println(j8 == 2 || j8++ == 2); System.out.println(j8); boolean b8 = true; System.out.println(b8); System.out.println(!b8); boolean a9 = true; boolean b9 = false; System.out.println(a9 ^ b9); System.out.println(a9 ^ !b9); int i11 = 5; String b11 = (Integer.toBinaryString(i11)); System.out.println(i11 + " 的二进制表达是: " + b11); int i12 = 5; int j12 = 6; System.out.println(Integer.toBinaryString(i12)); System.out.println(Integer.toBinaryString(j12)); System.out.println(i12 | j12); System.out.println(i12 & j12); System.out.println(i12 ^ j12); System.out.println(i12 ^ 0); System.out.println(i12 ^ i12); byte i13 = 5; System.out.println(Integer.toBinaryString(i13)); System.out.println(~i13); byte i14 = 6; System.out.println(Integer.toBinaryString(i14)); System.out.println(i14 << 1); System.out.println(i14 >> 1); int i15 = -10; System.out.println(Integer.toBinaryString(i15)); int j15 = i15 >> 1; System.out.println(Integer.toBinaryString(j15)); System.out.println(j15); int k15 = i >>> 1; System.out.println(Integer.toBinaryString(k15)); System.out.println(k15); int i16 = 5 + 5; int i17 = 3; i17 += 2; System.out.println(i17); int j17 = 3; j17 = j17 + 2; System.out.println(j17); int i18 = 5; int j18 = 6; int k18 = i18 < j18 ? 99 : 88; System.out.println(k18); Scanner s = new Scanner(System.in); int a19 = s.nextInt(); System.out.println("第一个整数:" + a19); int b19 = s.nextInt(); System.out.println("第二个整数: " + b19); float a20 = s.nextFloat(); System.out.println("读取的浮点数的值是: " + a20); String rn = s.nextLine(); String a21 = s.nextLine(); System.out.println("读取的字符串是: " + a21); } }
package com.shensu.pojo; import java.io.Serializable; public class FranchiserUser implements Serializable { private Integer franchiseruserid; //通过加盟的id private String openid; //用户的唯一标识 private String franchiserusercreattime; //加盟用户通过时间 private String franchiseruseraccounts; //加盟用户的帐号 private String franchiseruserpassword; //加盟用户的密码 private String franchiseruserusername; //加盟用户的昵称 private String franchiseruserpid; //用户加盟的pid private static final long serialVersionUID = 1L; public Integer getFranchiseruserid() { return franchiseruserid; } public void setFranchiseruserid(Integer franchiseruserid) { this.franchiseruserid = franchiseruserid; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid == null ? null : openid.trim(); } public String getFranchiserusercreattime() { return franchiserusercreattime; } public void setFranchiserusercreattime(String franchiserusercreattime) { this.franchiserusercreattime = franchiserusercreattime == null ? null : franchiserusercreattime.trim(); } public String getFranchiseruseraccounts() { return franchiseruseraccounts; } public void setFranchiseruseraccounts(String franchiseruseraccounts) { this.franchiseruseraccounts = franchiseruseraccounts == null ? null : franchiseruseraccounts.trim(); } public String getFranchiseruserpassword() { return franchiseruserpassword; } public void setFranchiseruserpassword(String franchiseruserpassword) { this.franchiseruserpassword = franchiseruserpassword == null ? null : franchiseruserpassword.trim(); } public String getFranchiseruserusername() { return franchiseruserusername; } public void setFranchiseruserusername(String franchiseruserusername) { this.franchiseruserusername = franchiseruserusername == null ? null : franchiseruserusername.trim(); } public String getFranchiseruserpid() { return franchiseruserpid; } public void setFranchiseruserpid(String franchiseruserpid) { this.franchiseruserpid = franchiseruserpid == null ? null : franchiseruserpid.trim(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } FranchiserUser other = (FranchiserUser) that; return (this.getFranchiseruserid() == null ? other.getFranchiseruserid() == null : this.getFranchiseruserid().equals(other.getFranchiseruserid())) && (this.getOpenid() == null ? other.getOpenid() == null : this.getOpenid().equals(other.getOpenid())) && (this.getFranchiserusercreattime() == null ? other.getFranchiserusercreattime() == null : this.getFranchiserusercreattime().equals(other.getFranchiserusercreattime())) && (this.getFranchiseruseraccounts() == null ? other.getFranchiseruseraccounts() == null : this.getFranchiseruseraccounts().equals(other.getFranchiseruseraccounts())) && (this.getFranchiseruserpassword() == null ? other.getFranchiseruserpassword() == null : this.getFranchiseruserpassword().equals(other.getFranchiseruserpassword())) && (this.getFranchiseruserusername() == null ? other.getFranchiseruserusername() == null : this.getFranchiseruserusername().equals(other.getFranchiseruserusername())) && (this.getFranchiseruserpid() == null ? other.getFranchiseruserpid() == null : this.getFranchiseruserpid().equals(other.getFranchiseruserpid())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getFranchiseruserid() == null) ? 0 : getFranchiseruserid().hashCode()); result = prime * result + ((getOpenid() == null) ? 0 : getOpenid().hashCode()); result = prime * result + ((getFranchiserusercreattime() == null) ? 0 : getFranchiserusercreattime().hashCode()); result = prime * result + ((getFranchiseruseraccounts() == null) ? 0 : getFranchiseruseraccounts().hashCode()); result = prime * result + ((getFranchiseruserpassword() == null) ? 0 : getFranchiseruserpassword().hashCode()); result = prime * result + ((getFranchiseruserusername() == null) ? 0 : getFranchiseruserusername().hashCode()); result = prime * result + ((getFranchiseruserpid() == null) ? 0 : getFranchiseruserpid().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", franchiseruserid=").append(franchiseruserid); sb.append(", openid=").append(openid); sb.append(", franchiserusercreattime=").append(franchiserusercreattime); sb.append(", franchiseruseraccounts=").append(franchiseruseraccounts); sb.append(", franchiseruserpassword=").append(franchiseruserpassword); sb.append(", franchiseruserusername=").append(franchiseruserusername); sb.append(", franchiseruserpid=").append(franchiseruserpid); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
package domain; import java.util.Collection; import java.util.Date; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import org.springframework.format.annotation.DateTimeFormat; @Entity @Access(AccessType.PROPERTY) public class SearchTemplate extends DomainEntity { // Constructors ----------------------------------------------------------- public SearchTemplate() { super(); } // Attributes ------------------------------------------------------------- private RelationshipType relationshipType; private Integer approximateAge; private String singleKeyword; private Genre genre; private Date searchTime; private String country; private String state; private String province; private String city; @Valid @Enumerated(EnumType.STRING) public RelationshipType getRelationshipType() { return this.relationshipType; } public void setRelationshipType(final RelationshipType relationshipType) { this.relationshipType = relationshipType; } @Min(18) public Integer getApproximateAge() { return this.approximateAge; } public void setApproximateAge(final Integer approximateAge) { this.approximateAge = approximateAge; } public String getSingleKeyword() { return this.singleKeyword; } public void setSingleKeyword(final String singleKeyword) { this.singleKeyword = singleKeyword; } @Valid @Enumerated(EnumType.STRING) public Genre getGenre() { return this.genre; } public void setGenre(final Genre genre) { this.genre = genre; } @Past @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss") public Date getSearchTime() { return this.searchTime; } public void setSearchTime(final Date searchTime) { this.searchTime = searchTime; } public String getCountry() { return this.country; } public void setCountry(final String country) { this.country = country; } public String getState() { return this.state; } public void setState(final String state) { this.state = state; } public String getProvince() { return this.province; } public void setProvince(final String province) { this.province = province; } public String getCity() { return this.city; } public void setCity(final String city) { this.city = city; } // Relationships ---------------------------------------------------------- private Chorbi chorbi; private Collection<Chorbi> results; @NotNull @Valid @OneToOne(optional = false) public Chorbi getChorbi() { return this.chorbi; } public void setChorbi(final Chorbi chorbi) { this.chorbi = chorbi; } @NotNull @Valid @ManyToMany() public Collection<Chorbi> getResults() { return this.results; } public void setResults(final Collection<Chorbi> results) { this.results = results; } }
package ru.client.model; import org.sql2o.Connection; import org.sql2o.Sql2o; import java.util.List; public class Workshops_TopDAO implements DAO<Workshops_Top, Integer>{ private static final String TABLE_NAME = "WORKSHOPS_TYPES"; private final Sql2o sql2o; public Workshops_TopDAO(Sql2o sql2o) { this.sql2o = sql2o; } @Override public void create(Workshops_Top entity) { String sql = "INSERT INTO " + TABLE_NAME + "(workshops_id, types_id) " + " VALUES(:workshopsId, :typesId)"; try (Connection connection = sql2o.open()) { connection.createQuery(sql, true) .addParameter("workshopsId", entity.getWorkshopsId()) .addParameter("typesId", entity.getTypesId()) .executeUpdate(); } } @Override public Workshops_Top getById(Integer id) { String sql = "SELECT * FROM " + TABLE_NAME + " WHERE id = :id"; try (Connection connection = sql2o.open()) { return connection.createQuery(sql) .executeAndFetchFirst(Workshops_Top.class); } } @Override public List<Workshops_Top> getAll() { String sql = "SELECT * FROM " + TABLE_NAME; try (Connection connection = sql2o.open()) { return connection.createQuery(sql) .executeAndFetch(Workshops_Top.class); } } @Override public boolean delete(Integer id) { String sql = "DELETE FROM " + TABLE_NAME + " WHERE id = :p1"; try (Connection connection = sql2o.open()) { connection.createQuery(sql) .addParameter("p1", id) .executeUpdate(); return true; } } @Override public boolean update(Workshops_Top entity) { String sql = "UPDATE " + TABLE_NAME + " SET workshops_id = :p1 ," + " types_id = :p2 "; try (Connection connection = sql2o.open()) { connection.createQuery(sql) .addParameter("p1", entity.getWorkshopsId()) .addParameter("p2", entity.getTypesId()) .executeUpdate(); return true; } } }
package shapes; import java.awt.Color; import java.util.ArrayList; import engine.Transform; import vectors.Vector2; import vectors.Vector3; public interface ObjectAdapter { ArrayList<Vector3> getPoints(); ArrayList<Vector2> getRelationships(); Transform getTransform(); Color getColor(); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.davivienda.sara.dto; import com.davivienda.sara.constantes.CodigoError; import com.davivienda.sara.constantes.EstadoProceso; /** * * @author jmcastel */ public class HistoricoCargueDTO { private Integer idRegistro; private String codigoCajero; private String nombreArchivo; private String ciclo; private String fecha; private EstadoProceso estadoProceso; private String Error; private CodigoError descripcionError; private String TamanoBytes; private boolean Prueba; private String descripcionErrorMultifuncional; /** * @return the idRegistro */ public Integer getIdRegistro() { return idRegistro; } /** * @param idRegistro the idRegistro to set */ public void setIdRegistro(Integer idRegistro) { this.idRegistro = idRegistro; } /** * @return the codigoCajero */ public String getCodigoCajero() { return codigoCajero; } /** * @param codigoCajero the codigoCajero to set */ public void setCodigoCajero(String codigoCajero) { this.codigoCajero = codigoCajero; } /** * @return the nombreArchivo */ public String getNombreArchivo() { return nombreArchivo; } /** * @param nombreArchivo the nombreArchivo to set */ public void setNombreArchivo(String nombreArchivo) { this.nombreArchivo = nombreArchivo; } /** * @return the ciclo */ public String getCiclo() { return ciclo; } /** * @param ciclo the ciclo to set */ public void setCiclo(String ciclo) { this.ciclo = ciclo; } /** * @return the fecha */ public String getFecha() { return fecha; } /** * @param fecha the fecha to set */ public void setFecha(String fecha) { this.fecha = fecha; } /** * @return the estadoProceso */ public EstadoProceso getEstadoProceso() { return estadoProceso; } /** * @param estadoProceso the estadoProceso to set */ public void setEstadoProceso(EstadoProceso estadoProceso) { this.estadoProceso = estadoProceso; } /** * @return the Error */ public String getError() { return Error; } /** * @param Error the Error to set */ public void setError(String Error) { this.Error = Error; } /** * @return the descripcionError */ public CodigoError getDescripcionError() { return descripcionError; } /** * @param descripcionError the descripcionError to set */ public void setDescripcionError(CodigoError descripcionError) { this.descripcionError = descripcionError; } /** * @return the TamanoBytes */ public String getTamanoBytes() { return TamanoBytes; } /** * @param TamanoBytes the TamanoBytes to set */ public void setTamanoBytes(String TamanoBytes) { this.TamanoBytes = TamanoBytes; } /** * @return the Prueba */ public boolean getPrueba() { return Prueba; } /** * @param Prueba the Prueba to set */ public void setPrueba(boolean Prueba) { this.Prueba = Prueba; } public String getDescripcionErrorMultifuncional() { return descripcionErrorMultifuncional; } public void setDescripcionErrorMultifuncional(String descripcionErrorMultifuncional) { this.descripcionErrorMultifuncional = descripcionErrorMultifuncional; } }
package net; import tree.Event; /** * Created by samosbor on 5/18/18. */ public class EventResult { /** * An array of event objects to return */ Event[] data; String message; /** * The constructor for the event result object * * @param data */ public EventResult(Event[] data) { this.data = data; } public EventResult(String message) { this.message = message; } public Event[] getData() { return data; } public void setData(Event[] data) { this.data = data; } }
/* * 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 printstream; import java.io.*; import java.util.Scanner; /** * * @author Estudiante */ public class ModificarArchivo { /** * @param args the command line arguments * @throws java.io.FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here PrintStream salida = new PrintStream(new File("output.txt")); BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); Scanner opcion = new Scanner(System.in); boolean indicador = true; while(indicador){ salida.print(entrada.readLine() + ","); System.out.println("Desea continuar"); indicador = opcion.hasNext();//http://proxy.unal.edu.co:8080 } salida.close(); } }
package handin06; /** * ProductType is an enum for Products * @author Peter Tolstrup Aagesen, ptaa@itu.dk * */ public enum ProductType { APPLE, COLA; }
package com.czxy.pojo; import javax.persistence.Id; import javax.persistence.Table; /** * @author haoannan 169650@qq.com * @date 2019/10/22 * @infos */ @Table(name = "tbl_category") public class Category { @Id private String cid; private String cname; @Override public String toString() { return "Category{" + "cid='" + cid + '\'' + ", cname='" + cname + '\'' + '}'; } public Category(String cid, String cname) { this.cid = cid; this.cname = cname; } public Category() { } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } }
package com.poc.sqs.utils; public class RequestDTO { private String accessKey; private String secretKey; private String queueName; private String message; private String queueType; public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getQueueName() { return queueName; } public void setQueueName(String queueName) { this.queueName = queueName; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getQueueType() { return queueType; } public void setQueueType(String queueType) { this.queueType = queueType; } }
package com.ihc.tafit.social; import com.ihc.tafit.PopHelp; import com.ihc.tafit.R; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ActivityInfo; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; public class JogVsJog extends Activity { private static ImageButton help; private static ImageButton back; private static ImageButton board1; private static ImageButton board2; private static ImageButton board3; private static ImageButton board4; private static ImageButton board5; private static ImageButton board6; private static ImageButton board7; private static ImageButton board8; private static ImageButton board9; private static TextView jogO; private static TextView jogX; private static TextView tJogos; private static int pont_O; private static int pont_X; private static int jogos; private static int JOGADOR_O = 0; private static int JOGADOR_X = 1; private static boolean isJogadorO; private static boolean lockedBoard=false; int[] board; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.activity_jog_vs_jog); board = new int[9]; pont_O = 0; pont_X = 0; jogos = 0; back = (ImageButton) findViewById(R.id.imgBJvJ); help = (ImageButton) findViewById(R.id.imgHJvsJ); jogO = (TextView) findViewById(R.id.txtJogO); jogX = (TextView) findViewById(R.id.txtJogX); tJogos = (TextView) findViewById(R.id.txtTotalJogos); board1 = (ImageButton) findViewById(R.id.imgTTT1); board2 = (ImageButton) findViewById(R.id.imgTTT2); board3 = (ImageButton) findViewById(R.id.imgTTT3); board4 = (ImageButton) findViewById(R.id.imgTTT4); board5 = (ImageButton) findViewById(R.id.imgTTT5); board6 = (ImageButton) findViewById(R.id.imgTTT6); board7 = (ImageButton) findViewById(R.id.imgTTT7); board8 = (ImageButton) findViewById(R.id.imgTTT8); board9 = (ImageButton) findViewById(R.id.imgTTT9); resetBoard(); updateContadores(); help.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { help.setClickable(false); PopHelp mHelp = new PopHelp(); mHelp.HelpPopup(JogVsJog.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE), R.string.helpJvsJ, view); help.setClickable(true); } }); back.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { back.setClickable(false); finish(); back.setClickable(true); } }); board1.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { board1.setClickable(false); Joga(1,board1); } }); board2.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { board2.setClickable(false); Joga(2,board2); } }); board3.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { board3.setClickable(false); Joga(3,board3); } }); board4.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { board4.setClickable(false); Joga(4,board4); } }); board5.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { board5.setClickable(false); Joga(5,board5); } }); board6.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { board6.setClickable(false); Joga(6,board6); } }); board7.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { board7.setClickable(false); Joga(7,board7); } }); board8.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { board8.setClickable(false); Joga(8,board8); } }); board9.setOnClickListener(new Button.OnClickListener() { public void onClick(View view) { board9.setClickable(false); Joga(9,board9); } }); } private void Joga(int posicao, ImageButton clicked) { if(!lockedBoard) { if(isJogadorO) { clicked.setBackgroundResource(R.drawable.o); board[posicao-1]=JOGADOR_O; isJogadorO=false; jogO.setTypeface(null, Typeface.NORMAL); jogX.setTypeface(null, Typeface.BOLD_ITALIC); } else { clicked.setBackgroundResource(R.drawable.x); board[posicao-1]=JOGADOR_X; isJogadorO=true; jogO.setTypeface(null, Typeface.BOLD_ITALIC); jogX.setTypeface(null, Typeface.NORMAL); } checkGameState(); } } private void checkGameState() { if(board[0]==board[1] && board[1]==board[2] && board[1]!=-1) { //alguem ganhou primeira linha lockedBoard=true; if(board[1]==JOGADOR_O) { pont_O+=1; playAgain("Jogador O ganha!"); } else { pont_X+=1; playAgain("Jogador X ganha!"); } } else if(board[3]==board[4] && board[4]==board[5] && board[4]!=-1) { //alguem ganhou segunda linha lockedBoard=true; if(board[4]==JOGADOR_O) { pont_O+=1; playAgain("Jogador O ganha!"); } else { pont_X+=1; playAgain("Jogador X ganha!"); } } else if(board[6]==board[7] && board[7]==board[8] && board[7]!=-1) { //alguem ganhou terceira linha lockedBoard=true; if(board[7]==JOGADOR_O) { pont_O+=1; playAgain("Jogador O ganha!"); } else { pont_X+=1; playAgain("Jogador X ganha!"); } } else if(board[0]==board[3] && board[3]==board[6] && board[3]!=-1) { //alguem ganhou primeira coluna lockedBoard=true; if(board[3]==JOGADOR_O) { pont_O+=1; playAgain("Jogador O ganha!"); } else { pont_X+=1; playAgain("Jogador X ganha!"); } } else if(board[1]==board[4] && board[4]==board[7] && board[4]!=-1) { //alguem ganhou segunda coluna lockedBoard=true; if(board[4]==JOGADOR_O) { pont_O+=1; playAgain("Jogador O ganha!"); } else { pont_X+=1; playAgain("Jogador X ganha!"); } } else if(board[2]==board[5] && board[5]==board[8] && board[5]!=-1) { //alguem ganhou terceira coluna lockedBoard=true; if(board[5]==JOGADOR_O) { pont_O+=1; playAgain("Jogador O ganha!"); } else { pont_X+=1; playAgain("Jogador X ganha!"); } } else if(board[0]==board[4] && board[4]==board[8] && board[4]!=-1) { //alguem ganhou diagonal \ lockedBoard=true; if(board[4]==JOGADOR_O) { pont_O+=1; playAgain("Jogador O ganha!"); } else { pont_X+=1; playAgain("Jogador X ganha!"); } } else if(board[2]==board[4] && board[4]==board[6] && board[4]!=-1) { //alguem ganhou diagonal / lockedBoard=true; if(board[4]==JOGADOR_O) { pont_O+=1; playAgain("Jogador O ganha!"); } else { pont_X+=1; playAgain("Jogador X ganha!"); } } else { boolean isTie=true; //ninguem ganhou for(int i=0;i<board.length;i++) { if(board[i]==-1) { isTie=false; } } if(isTie) { lockedBoard=true; playAgain("Empate!"); } } } @SuppressWarnings("deprecation") private void playAgain(String title) { jogos+=1; updateContadores(); AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle(title); alertDialog.setMessage("Deseja jogar outra vez?"); alertDialog.setCancelable(false); alertDialog.setButton("Sim", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { resetBoard(); } }); alertDialog.setButton2("Não", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.setIcon(R.drawable.ic_launcher); alertDialog.show(); } private void resetBoard() { isJogadorO = (Math.random()<0.5)?false:true; if(isJogadorO) { jogO.setTypeface(null, Typeface.BOLD_ITALIC); jogX.setTypeface(null, Typeface.NORMAL); } else { jogO.setTypeface(null, Typeface.NORMAL); jogX.setTypeface(null, Typeface.BOLD_ITALIC); } for(int i=0;i<board.length;i++) { board[i]=-1; } lockedBoard=false; board1.setBackgroundResource(android.R.drawable.btn_default); board1.setClickable(true); board2.setBackgroundResource(android.R.drawable.btn_default); board2.setClickable(true); board3.setBackgroundResource(android.R.drawable.btn_default); board3.setClickable(true); board4.setBackgroundResource(android.R.drawable.btn_default); board4.setClickable(true); board5.setBackgroundResource(android.R.drawable.btn_default); board5.setClickable(true); board6.setBackgroundResource(android.R.drawable.btn_default); board6.setClickable(true); board7.setBackgroundResource(android.R.drawable.btn_default); board7.setClickable(true); board8.setBackgroundResource(android.R.drawable.btn_default); board8.setClickable(true); board9.setBackgroundResource(android.R.drawable.btn_default); board9.setClickable(true); } private void updateContadores() { jogO.setText(String.format(getResources().getString(R.string.PJogO), pont_O)); jogX.setText(String.format(getResources().getString(R.string.PJogX), pont_X)); tJogos.setText(String.format(getResources().getString(R.string.PTJog), jogos)); } }
package com.corebaseit.advancedgridviewjson.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.corebaseit.advancedgridviewjson.models.AnotherListModel; import java.util.ArrayList; import java.util.List; /** * Created by Vincent Bevia on 27/10/16. <br /> * vbevia@ieee.org */ public class AnotherListHelper extends SQLiteHelper { public AnotherListHelper(Context context) { super(context); } public List<AnotherListModel> findAll() { List<AnotherListModel> result = new ArrayList<>(); //next we'll query the db: String[] allColumns = { AnotherListModel.Entry.COLUMN_ID, AnotherListModel.Entry.COLUMN_TITLE, AnotherListModel.Entry.COLUMN_URL, AnotherListModel.Entry.COLUMN_PIC, AnotherListModel.Entry.COLUMN_DESC }; SQLiteDatabase database = this.getReadableDatabase(); Cursor cursor = database.query( AnotherListModel.Entry.TABLE_NAME, allColumns, null, null, null, null, "_id DESC" ); if (cursor.getCount() > 0) { while (cursor.moveToNext()) { AnotherListModel model = new AnotherListModel(); model.setId(cursor.getLong(cursor.getColumnIndex(AnotherListModel.Entry.COLUMN_ID))); model.setName(cursor.getString(cursor.getColumnIndex(AnotherListModel.Entry.COLUMN_TITLE))); model.setUrl(cursor.getString(cursor.getColumnIndex(AnotherListModel.Entry.COLUMN_URL))); model.setPicture(cursor.getString(cursor.getColumnIndex(AnotherListModel.Entry.COLUMN_PIC))); model.setDescription(cursor.getString(cursor.getColumnIndex(AnotherListModel.Entry.COLUMN_DESC))); result.add(model); } } database.close(); return result; } public AnotherListModel create(AnotherListModel model) { ContentValues values = new ContentValues(); values.put(AnotherListModel.Entry.COLUMN_URL, model.getUrl()); values.put(AnotherListModel.Entry.COLUMN_TITLE, model.getName()); values.put(AnotherListModel.Entry.COLUMN_PIC, model.getPicture()); values.put(AnotherListModel.Entry.COLUMN_DESC, model.getDescription()); SQLiteDatabase database = this.getWritableDatabase();; long insertid = database.insert(AnotherListModel.Entry.TABLE_NAME, null, values); model.setId(insertid); database.close(); return model; } public void deleteRow(int id) { String[] whereArgs = { String.valueOf(id) }; SQLiteDatabase database = this.getWritableDatabase(); database.delete( AnotherListModel.Entry.TABLE_NAME, "_id=?", whereArgs ); database.close(); } public void deleteRow(String url) { String[] whereArgs = { url }; SQLiteDatabase database = this.getWritableDatabase(); database.delete( AnotherListModel.Entry.TABLE_NAME, AnotherListModel.Entry.COLUMN_URL + "=?", whereArgs ); database.close(); } }
package lotro.ww; import gui.ComponentTools; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Map; import java.util.Vector; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ToolTipManager; import org.jdesktop.swingx.JXTable; import utils.Application; public class WardenWizard extends Application implements ActionListener { private Map<String, Gambit> gambits; private JPanel buttons; public Model model; public WardenWizard() { super("Warden Wizard", null, "31 Dec 2012", null); populateModel(); buttons = new JPanel(); JButton button = new JButton("Rotations"); button.setToolTipText("Clear the pattern and matches"); button.addActionListener(this); buttons.add(button); JPanel controls = new JPanel(new BorderLayout()); controls.add(buttons, BorderLayout.NORTH); JList<JLabel> list = new JList<JLabel>(); for (Gambit gambit : gambits.values()) list.add(new JLabel(gambit.getName() + " - " + gambit.getBuilders())); JPanel output = new JPanel(new BorderLayout()); output.setPreferredSize(new Dimension(500, 400)); output.add(new JScrollPane(getView()), BorderLayout.CENTER); add(controls, BorderLayout.NORTH); add(ComponentTools.getTitledPanel(output, "Gambits"), BorderLayout.CENTER); } public void actionPerformed(final ActionEvent e) // rotation builder { RotationBuilder rb = new RotationBuilder(gambits); rb.setVisible(true); } private JXTable getView() { JXTable tbl = new JXTable(model); tbl.setEditable(false); tbl.setColumnControlVisible(true); tbl.setHorizontalScrollEnabled(true); tbl.packAll(); return tbl; } private void populateModel() { this.model = new Model(); model.addColumn("Level"); model.addColumn("Gambit"); model.addColumn("Range"); model.addColumn("Targets"); model.addColumn("Builders"); model.addColumn("Basic"); model.addColumn("Masteries"); model.addColumn("Offense"); model.addColumn("Defense"); model.addColumn("Healing"); model.addColumn("Threat"); model.addColumn("Other"); gambits = GambitData.load(); for (Gambit gambit : gambits.values()) addGambitToModel(gambit); } private void addGambitToModel(final Gambit gambit) { Vector<Object> row = new Vector<Object>(); row.add(gambit.getLevel()); row.add(gambit.getName()); row.add(gambit.getRange()); row.add(gambit.getMaxTargets()); row.add(gambit.getBuilders()); row.add(gambit.getBasic()); String keys = ""; for (String key : gambit.getKeys()) keys += key + ", "; row.add(keys); row.add(gambit.getOffense()); row.add(gambit.getDefense()); row.add(gambit.getHeal()); row.add(gambit.getThreat()); row.add(gambit.getOther()); model.addRow(row); } public static void main(String[] args) { ComponentTools.setLookAndFeel(); ToolTipManager.sharedInstance().setDismissDelay(30000); WardenWizard app = new WardenWizard(); app.open(); } }
package lab.heisenbug.sandbox.java.util.concurrent; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Created by IntelliJ IDEA. * User: parker * Date: 1/30/11 * Time: 9:32 PM * To change this template use File | Settings | File Templates. */ public class ExecutorServiceTest { private static final Logger logger = LoggerFactory.getLogger(ExecutorServiceTest.class); @Test public void timeoutOnInvoke() { ExecutorService service = Executors.newFixedThreadPool(2); List<Future> results = new ArrayList<>(); for (int i = 0; i < 10; i++) { Future reslut = service.submit(new Task("Job" + (i + 1))); results.add(reslut); } for (Future result : results) { try { result.get(300, TimeUnit.MICROSECONDS); } catch (InterruptedException | ExecutionException e) { logger.error(e.getMessage(), e); } catch (TimeoutException e) { logger.info("time out on get the result, tring to cancel the job."); result.cancel(true); } } } private static class Task implements Runnable { private final Logger logger = LoggerFactory.getLogger(getClass()); private String name; public Task(String name) { this.name = name; } public String getName() { return name; } @Override public void run() { logger.info("job {} started running on thread {}.", name, Thread.currentThread().hashCode()); long x = 0; for (int i = 0; i < 900000000; i++) { x = x * i; } logger.info("job {} completed running.", name); } } }
package classes; /** * Décrivez votre classe Restaurant ici. * * @author (votre nom) * @version (un numéro de version ou une date) */ import javafx.fxml.FXML; import java.awt.*; import java.util.* ; import java.util.List; import java.util.Scanner ; public class Restaurant { private Scanner sc = new Scanner(System.in); private int nbChaise; private int nbTable; private Set<ClientFidele> clients; private Set<Commande> cmdEnAttente; private Set<Commande> cmdEffectue; private Menu menu; private boolean libre ; public Restaurant(int nbChaise, int nbTable) { this.nbChaise = nbChaise; this.nbTable = nbTable; this.clients = new TreeSet<ClientFidele>(); this.cmdEffectue = new HashSet<Commande>(); this.cmdEnAttente = new HashSet<Commande>(); this.menu = new Menu(); } public int nbCmdEffectue(Date d1, Date d2) { int cpt = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { cpt++; } } } return cpt; } public double montantTtCmd(Date d1, Date d2) { double montant = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { montant += c.getTarif(); } } } return montant; } public int nbCmdSurPlace(Date d1, Date d2) { int cpt = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { if (c instanceof CmdSurPlace) cpt++; } } } return cpt; } public double montantTtCmdSurPlace(Date d1, Date d2) { double montant = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { if (c instanceof CmdSurPlace) montant += c.getTarif(); } } } return montant; } public int nbCmdADomicile(Date d1, Date d2) { int cpt = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { if (c instanceof CmdADomicile) cpt++; } } } return cpt; } public double montantTtCmdADomicile(Date d1, Date d2) { double montant = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { if (c instanceof CmdADomicile) montant += c.getTarif(); } } } return montant; } public int nbCmdEvenement(Date d1, Date d2) { int cpt = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { if (c instanceof CmdEvenement) cpt++; } } } return cpt; } public double montantTtCmdEvenement(Date d1, Date d2) { double montant = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { if (c instanceof CmdEvenement) montant += c.getTarif(); } } } return montant; } public double montantTotalReduction(Date d1, Date d2) { double montant = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { montant += c.getTarif() * c.getReduction(); } } } return montant; } public Set<Commande> getCmdEffectue() { return cmdEffectue; } public double montantReducFidel(Date d1, Date d2) { double montant = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getClient() instanceof ClientFidele) { montant += c.getTarif() * 0.05; } } } return montant; } public double montantReducEvenement(Date d1, Date d2) { double montant = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { if (c instanceof CmdEvenement && c.getNbPers() >= 50) { montant += c.getTarif() * 0.1; } } } } return montant; } public double montantReducEtudiant(Date d1, Date d2) { double montant = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { if (c.getClient().getEtudiant()) { montant += c.getTarif() * 0.08; } } } } return montant; } public double montantReducGrDomicile(Date d1, Date d2) { double montant = 0; if (d2.after(d1)) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { if (c instanceof CmdADomicile && c.getNbPers() >= 4) { montant += c.getTarif() * 0.07; } } } } return montant; } public Met metPlusCmd(Date d1, Date d2) { Met m1, m2 ; int nbCmd1 = 0, nbCmd2 = 0; boolean existAuMoinCmd =false ; if (d2.after(d1)) { if (menu.taille()==0) return null ; else m2 = menu.getMet(0); if (cmdEffectue.size() == 0) { return null; } else { for (int i = 0; i < menu.taille(); i++) { m1 = menu.getMet(i); nbCmd1 = 0; for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { for (int j = 0; i < c.getCmds().size(); i++) { if (c.getCmds().get(j).isExiste(m1)) nbCmd1++; } if (nbCmd1>0) existAuMoinCmd = true; } } if (nbCmd1 > nbCmd2) { nbCmd2 = nbCmd1; m2.copier(m1); } } if (!existAuMoinCmd) return null; else return m2; } }else return null; } public Met metMoinCmd(Date d1, Date d2) { Met m1, m2 ; int nbCmd1 = 0, nbCmd2 = Integer.MAX_VALUE; boolean existeAuMoinCommande = false ; if (d2.after(d1)) { if (menu.taille()==0) return null ; else m2 = menu.getMet(0); if (cmdEffectue.size()==0){ return null ; } for (int i = 0; i < menu.taille(); i++) { m1 = menu.getMet(i); nbCmd1 = 0; for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { for (int j = 0; i < c.getCmds().size(); i++) { if (c.getCmds().get(j).isExiste(m1)) nbCmd1++; } if (nbCmd1>0) existeAuMoinCommande = true ; } } if (nbCmd1 < nbCmd2) { nbCmd2 = nbCmd1; m2.copier(m1); } } if (!existeAuMoinCommande) return null ; else return m2; } else return null; } public Client clientPlusCmd(Date d1, Date d2) { Client cl1 = new Client("", "", "", false), cl2 = new Client("", "", "", false); int nbCmd1 = 0, nbCmd2 = 0; boolean existeAuMoinCommende = false ; for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { cl1 = c.getClient(); for (Commande d : cmdEffectue ) { if (d.getHeurCosom().after(d1) && d.getHeurCosom().before(d2)) { if (cl1.equals(d.getClient())) nbCmd1++; } } if (nbCmd1!=0) existeAuMoinCommende=true ; } if (nbCmd1 > nbCmd2) { nbCmd2 = nbCmd1; cl2 = cl1; } } if (!existeAuMoinCommende) return null ; else return cl2; } public Client clientPlusCmdSurPlace(Date d1, Date d2) { Client cl1 = new Client("", "", "", false), cl2 = new Client("", "", "", false); int nbCmd1 = 0, nbCmd2 = 0; boolean existeAuMoinCommende = false ; for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2) && c instanceof CmdSurPlace) { cl1 = c.getClient(); for (Commande d : cmdEffectue ) { if (d.getHeurCosom().after(d1) && d.getHeurCosom().before(d2) && d instanceof CmdSurPlace) { if (cl1.equals(d.getClient())) nbCmd1++; } } if (nbCmd1!=0) existeAuMoinCommende =true ; } if (nbCmd1 > nbCmd2) { nbCmd2 = nbCmd1; cl2 = cl1; } } if (!existeAuMoinCommende) return null ; else return cl2; } public Client clientPlusCmdADomicil(Date d1, Date d2) { Client cl1 = new Client("", "", "", false), cl2 = new Client("", "", "", false); int nbCmd1 = 0, nbCmd2 = 0; boolean existeAuMoinCommende = false ; for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2) && c instanceof CmdADomicile) { cl1 = c.getClient(); for (Commande d : cmdEffectue ) { if (d.getHeurCosom().after(d1) && d.getHeurCosom().before(d2) && d instanceof CmdADomicile) { if (cl1.equals(d.getClient())) nbCmd1++; } } if(nbCmd1!=0) existeAuMoinCommende = true ; } if (nbCmd1 > nbCmd2) { nbCmd2 = nbCmd1; cl2 = cl1; } } if(!existeAuMoinCommende) return null ; else return cl2; } public Client clientPlusCmdEvenement(Date d1, Date d2) { Client cl1 = new Client("", "", "", false), cl2 = new Client("", "", "", false); int nbCmd1 = 0, nbCmd2 = 0; boolean existeAuMoinCommende = false ; for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2) && c instanceof CmdEvenement) { cl1 = c.getClient(); for (Commande d : cmdEffectue ) { if (d.getHeurCosom().after(d1) && d.getHeurCosom().before(d2) && d instanceof CmdEvenement) { if (cl1.equals(d.getClient())) nbCmd1++; } } if (nbCmd1!=0) existeAuMoinCommende = true; } if (nbCmd1 > nbCmd2) { nbCmd2 = nbCmd1; cl2 = cl1; } } if(!existeAuMoinCommende) return null ; else return cl2; } public Client clientPlusReduction(Date d1, Date d2) { Client cl1 = new Client("", "", "", false), cl2 = new Client("", "", "", false); int reduction1 = 0, reduction2 = 0; boolean existeAuMoinCommende = false ; for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { cl1 = c.getClient(); for (Commande d : cmdEffectue ) { if (d.getHeurCosom().after(d1) && d.getHeurCosom().before(d2)) { if (cl1.equals(d.getClient())) { reduction1 += d.getReduction(); existeAuMoinCommende = true ; } } } } if (reduction1 > reduction2) { reduction2 = reduction1; cl2 = cl1; } } if (!existeAuMoinCommende) return null ; else return cl2; } public Client clientPlusReductionFidele(Date d1, Date d2) { Client cl2 = new Client("", "", "", false); int reduction1 = 0, reduction2 = 0; boolean existeAuMoinCommende = false ; for (ClientFidele cl1: clients) { for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { if (cl1.equals(c.getClient()) && cl1.getNbCmd()>=2){ reduction1 +=0.05 ; existeAuMoinCommende = true; } } } if (reduction1 > reduction2) { reduction2 = reduction1; cl2 = cl1; } } if (!existeAuMoinCommende) return null; else return cl2; } public Client clientPlusReductionEtude(Date d1, Date d2) { Client cl1 = new Client("", "", "", false), cl2 = new Client("", "", "", false); int reduction1 = 0, reduction2 = 0; boolean existeAuMoinCommende = false ; for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { cl1 = c.getClient(); if (cl1.getEtudiant()) { for (Commande d : cmdEffectue ) { if (d.getHeurCosom().after(d1) && d.getHeurCosom().before(d2)) { if (cl1.equals(d.getClient())){ reduction1 += 0.08; existeAuMoinCommende = true ; } } } } } if (reduction1 > reduction2) { reduction2 = reduction1; cl2 = cl1; } } if (!existeAuMoinCommende) return null ; else return cl2; } public Client clientPlusReductionGrADomicil(Date d1, Date d2) { Client cl1 = new Client("", "", "", false), cl2 = new Client("", "", "", false); int reduction1 = 0, reduction2 = 0; boolean existeAuMoinCommende = false ; for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { cl1 = c.getClient(); if (cl1.getEtudiant()) { for (Commande d : cmdEffectue ) { if (d.getHeurCosom().after(d1) && d.getHeurCosom().before(d2) && d instanceof CmdADomicile) { if (cl1.equals(d.getClient()) && d.getNbPers()>=4){ reduction1 += 0.07; existeAuMoinCommende = true ; } } } } } if (reduction1 > reduction2) { reduction2 = reduction1; cl2 = cl1; } } if (!existeAuMoinCommende) return null ; else return cl2; } public Set<Commande> getCmdEnAttente() { return cmdEnAttente; } public Client clientPlusReductionEvenement(Date d1, Date d2) { Client cl1 = new Client("", "", "", false), cl2 = new Client("", "", "", false); int reduction1 = 0, reduction2 = 0; boolean existeAuMoinCommende = false ; for (Commande c : cmdEffectue ) { if (c.getHeurCosom().after(d1) && c.getHeurCosom().before(d2)) { cl1 = c.getClient(); if (cl1.getEtudiant()) { for (Commande d : cmdEffectue ) { if (d.getHeurCosom().after(d1) && d.getHeurCosom().before(d2) && d instanceof CmdEvenement) { if (cl1.equals(d.getClient()) && d.getNbPers()>=50) { reduction1 += 0.1; existeAuMoinCommende = true ; } } } } } if (reduction1 > reduction2) { reduction2 = reduction1; cl2 = cl1; } } if (!existeAuMoinCommende) return null; else return cl2; } public boolean isLibre() { return libre; } public void setLibre(boolean libre) { this.libre = libre; } public int getNbChaise() { return nbChaise; } public int getNbTable() { return nbTable; } public void ajouterRepas(Repas r){ this.menu.ajouterMet(r); } public void ajouterBoisson(Boisson b){ this.menu.ajouterMet(b); } public boolean supprimerRepas(String nomRepas){ return this.menu.suprimerRepas(nomRepas); } public boolean supprimerBoisson(String nomBoisson){ return this.menu.suprimerBoisson(nomBoisson); } public Menu getMenu() { return menu; } public Set<ClientFidele> getClients() { return clients; } public void ajouteClientFidele(ClientFidele c){ this.clients.add(c); } public ClientFidele avoirClientFidele(int codef){ ClientFidele cl = null ; if (clients.size()==0) { return null ; } else{ for (ClientFidele client: clients ) { if (client.getCodeFidelite() == codef) { cl = client ; break; } } return cl ; } } public int nbCmdTotal(){ return (cmdEffectue.size()+cmdEnAttente.size()) ; } public void effectueCmdAtt(int nmCmd){ Commande commande1= null ; Commande commande2 =null ; for (Commande cmd:cmdEnAttente ) { if (cmd.getNmCmd()==nmCmd){ if (cmd instanceof CmdSurPlace){ commande1 = new CmdSurPlace(nmCmd,cmd.getNbpers(),cmd.getClient(),((CmdSurPlace)cmd).getType(),cmd.getCmds()) ; commande2 =cmd ; break; } else{ if(cmd instanceof CmdADomicile){ commande1 = new CmdADomicile(nmCmd,cmd.getNbpers(),cmd.getClient(),((CmdADomicile)cmd).getAdressLivraison(), cmd.getCmds(),((CmdADomicile)cmd).getDistance()) ; commande2 = cmd ; break; }else { commande1 = new CmdEvenement(cmd.getClient(),((CmdEvenement)cmd).getMenu(),cmd.getNbpers(),((CmdEvenement) cmd).getType(),cmd.getNmCmd()); commande2 = cmd ; break; } } } } cmdEffectue.add(commande1); cmdEnAttente.remove(commande2); } public void ajouterCmdEnAtt(Commande c){ cmdEnAttente.add(c) ; } }
import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; public interface Learn { void learning(String filename); void searchIdealNeurons(int [] quantity); default void write(double[][] weight, String filename) { try { PrintWriter out = new PrintWriter(new FileOutputStream(filename)); for (int i = 0; i < 10; i++) { Arrays.stream(weight[i]).forEach((d) -> out.print(d + " ")); out.print("\n"); } out.flush(); System.out.println("Done! Saved to the file."); } catch (IOException e) { e.printStackTrace(); } } }
package com.gxtc.huchuan.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.widget.ImageView; import android.widget.TextView; import com.gxtc.commlibrary.base.BaseRecyclerTypeAdapter; import com.gxtc.commlibrary.helper.ImageHelper; import com.gxtc.huchuan.R; import com.gxtc.huchuan.bean.ThumbsupVosBean; import java.util.List; /** * Describe: * Created by ALing on 2017/5/18 . */ public class CirclePriseAdapter extends BaseRecyclerTypeAdapter<ThumbsupVosBean> { public CirclePriseAdapter(Context mContext, List<ThumbsupVosBean> mDatas, int[] resId) { super(mContext, mDatas, resId); } @Override protected int getViewType(int position) { return 0; } @Override protected void bindData(RecyclerView.ViewHolder h, int position, int type, ThumbsupVosBean bean) { ViewHolder holder = (ViewHolder) h; TextView tvUserName = (TextView) holder.getView(R.id.tv_user_name); ImageView ivHead = (ImageView) holder.getView(R.id.iv_head); tvUserName.setText(bean.getUserName()); ImageHelper.loadImage(getmContext(),ivHead,bean.getHeadPic()); } }
package br.com.filemanager.ejb.service.impl; import java.sql.SQLException; import java.util.List; import javax.ejb.EJB; import javax.ejb.Stateless; import br.com.filemanager.ejb.dao.UsuarioDAO; import br.com.filemanager.ejb.model.Usuario; import br.com.filemanager.ejb.service.UsuarioService; @Stateless public class UsuarioServiceImpl implements UsuarioService { @EJB private UsuarioDAO usuarioDAO; public void gravarUsuario(Usuario usuario) throws SQLException { usuarioDAO.gravarUsuario(usuario); } public void atualizarUsuario(Usuario usuario) { usuarioDAO.atualizarUsuario(usuario); } public void removerUsuario(Usuario usuario) { usuarioDAO.removerUsuario(usuario); } public List<Usuario> listarTodosUsuarios() { return usuarioDAO.findAll(); } public Usuario listarUsuario(String usuario, String senha) throws Exception { try { return usuarioDAO.listarUsuario(usuario, senha); }catch(Exception e) { throw new Exception(e); } } }
package com.gsccs.sme.plat.auth.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.gsccs.sme.plat.auth.model.AreaT; import com.gsccs.sme.plat.auth.service.AreaService; import com.gsccs.sme.plat.bass.TreeGrid; /** * 地域管理 * */ @Controller @RequestMapping("/area") public class AreaController { @Autowired private AreaService areaService; @RequiresPermissions("area:view") @RequestMapping(method = RequestMethod.GET) public String list() { return "logist/area_list"; } @RequestMapping(value = "/treegrid") @ResponseBody public TreeGrid list( @RequestParam(defaultValue = " code ") String order, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int rows, ModelMap map, AreaT area, HttpServletRequest request) { List<AreaT> areaList = areaService.find(area, order, page, rows); int totalCount = areaService.count(area); TreeGrid treeGrid = new TreeGrid(); treeGrid.setRows(areaList); treeGrid.setTotal(Long.valueOf(totalCount)); return treeGrid; } }
package com.jedralski.MovieRecommendationSystems.RecommendationSystemsDAO; import com.jedralski.MovieRecommendationSystems.exception.DatabaseException; import com.jedralski.MovieRecommendationSystems.model.MovieRatings; import com.jedralski.MovieRecommendationSystems.model.Neighbour; import java.util.HashMap; import java.util.List; public interface CollaborativeFilteringDAO { List<MovieRatings> userRatingsList(Long userId) throws DatabaseException; List<Neighbour> getNeighbour(List<MovieRatings> userRatingsList, Long userId) throws DatabaseException; List<Neighbour> getNeighbourDistance(List<MovieRatings> userRatingsList, List<Neighbour> neighborhood) throws DatabaseException; HashMap<Long, Double> avgGenreRating(Long userId) throws DatabaseException; HashMap<String, Double> avgProductionCountriesRating(Long userId) throws DatabaseException; HashMap<Long, Double> avgMainActorRating(Long userId) throws DatabaseException; List<Long> getWantSeeMovies(Long userId) throws DatabaseException; List<MovieRatings> moviesToRecommended(List<MovieRatings> userRatingsList, List<Neighbour> neighborhood, List<Long> wantSeeMovies, HashMap<Long, Double> avgGenreRating, HashMap<String, Double> avgProductionCountriesRating, HashMap<Long, Double> avgMainActorRating) throws DatabaseException; }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): ActiveEon Team - http://www.activeeon.com * * ################################################################ * $$ACTIVEEON_CONTRIBUTOR$$ */ package org.ow2.proactive.scheduler.job; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import javax.persistence.Column; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.MappedSuperclass; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlTransient; import org.apache.log4j.Logger; import org.hibernate.annotations.AccessType; import org.hibernate.annotations.AnyMetaDef; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; import org.hibernate.annotations.ManyToAny; import org.hibernate.annotations.MapKeyManyToMany; import org.hibernate.annotations.MetaValue; import org.hibernate.annotations.Proxy; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.extensions.dataspaces.core.naming.NamingService; import org.ow2.proactive.authentication.crypto.Credentials; import org.ow2.proactive.db.annotation.Alterable; import org.ow2.proactive.scheduler.common.NotificationData; import org.ow2.proactive.scheduler.common.SchedulerEvent; import org.ow2.proactive.scheduler.common.exception.ExecutableCreationException; import org.ow2.proactive.scheduler.common.exception.UnknownTaskException; import org.ow2.proactive.scheduler.common.job.JobId; import org.ow2.proactive.scheduler.common.job.JobInfo; import org.ow2.proactive.scheduler.common.job.JobPriority; import org.ow2.proactive.scheduler.common.job.JobResult; import org.ow2.proactive.scheduler.common.job.JobState; import org.ow2.proactive.scheduler.common.job.JobStatus; import org.ow2.proactive.scheduler.common.task.TaskId; import org.ow2.proactive.scheduler.common.task.TaskInfo; import org.ow2.proactive.scheduler.common.task.TaskState; import org.ow2.proactive.scheduler.common.task.TaskStatus; import org.ow2.proactive.scheduler.common.task.flow.FlowAction; import org.ow2.proactive.scheduler.common.task.flow.FlowActionType; import org.ow2.proactive.scheduler.common.task.flow.FlowBlock; import org.ow2.proactive.scheduler.core.SchedulerFrontend; import org.ow2.proactive.scheduler.core.annotation.TransientInSerialization; import org.ow2.proactive.scheduler.core.db.DatabaseManager; import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties; import org.ow2.proactive.scheduler.descriptor.JobDescriptor; import org.ow2.proactive.scheduler.descriptor.JobDescriptorImpl; import org.ow2.proactive.scheduler.descriptor.TaskDescriptor; import org.ow2.proactive.scheduler.job.JobInfoImpl.ReplicatedTask; import org.ow2.proactive.scheduler.task.TaskIdImpl; import org.ow2.proactive.scheduler.task.TaskResultImpl; import org.ow2.proactive.scheduler.task.internal.InternalForkedJavaTask; import org.ow2.proactive.scheduler.task.internal.InternalJavaTask; import org.ow2.proactive.scheduler.task.internal.InternalNativeTask; import org.ow2.proactive.scheduler.task.internal.InternalTask; import org.ow2.proactive.scheduler.task.launcher.TaskLauncher; import org.ow2.proactive.scheduler.util.SchedulerDevLoggers; /** * Internal and global description of a job. * This class contains all informations about the job to launch. * It also provides method to manage the content regarding the scheduling process.<br/> * Specific internal job may extend this abstract class. * * @author The ProActive Team * @since ProActive Scheduling 0.9 */ @MappedSuperclass @Table(name = "INTERNAL_JOB") @AccessType("field") @Proxy(lazy = false) public abstract class InternalJob extends JobState { /** */ private static final long serialVersionUID = 31L; public static final Logger logger_dev = ProActiveLogger.getLogger(SchedulerDevLoggers.CORE); /** Owner of the job */ @Column(name = "OWNER") private String owner = ""; /** List of every tasks in this job. */ @ManyToAny(metaColumn = @Column(name = "ITASK_TYPE", length = 5)) @AnyMetaDef(idType = "long", metaType = "string", metaValues = { @MetaValue(targetEntity = InternalJavaTask.class, value = "IJT"), @MetaValue(targetEntity = InternalNativeTask.class, value = "INT"), @MetaValue(targetEntity = InternalForkedJavaTask.class, value = "IFJT") }) @JoinTable(joinColumns = @JoinColumn(name = "ITASK_ID"), inverseJoinColumns = @JoinColumn(name = "DEPEND_ID")) @LazyCollection(value = LazyCollectionOption.FALSE) @Cascade(CascadeType.ALL) @MapKeyManyToMany(targetEntity = TaskIdImpl.class) protected Map<TaskId, InternalTask> tasks = new HashMap<TaskId, InternalTask>(); /** Informations (that can be modified) about job execution */ @Alterable @Cascade(CascadeType.ALL) @OneToOne(fetch = FetchType.EAGER, targetEntity = JobInfoImpl.class) protected JobInfoImpl jobInfo = new JobInfoImpl(); /** Job descriptor for dependences management */ //Not DB managed, created once needed. @Transient @TransientInSerialization @XmlTransient private JobDescriptor jobDescriptor; /** DataSpace application manager for this job */ //Not DB managed, created once needed. @Transient @TransientInSerialization @XmlTransient private JobDataSpaceApplication jobDataSpaceApplication; /** Job result */ @Cascade(CascadeType.ALL) @OneToOne(fetch = FetchType.EAGER, targetEntity = JobResultImpl.class) @TransientInSerialization private JobResult jobResult; /** Initial waiting time for a task before restarting in millisecond */ @Column(name = "RESTART_TIMER") @TransientInSerialization private long restartWaitingTimer = PASchedulerProperties.REEXECUTION_INITIAL_WAITING_TIME.getValueAsInt(); /** used credentials to fork as user id. Can be null, or contain user/pwd[/key] */ @Lob @Column(name = "CREDENTIALS", updatable = false, length = 16384/* 16Ko max */) @XmlTransient @TransientInSerialization private Credentials credentials = null; /** Hibernate default constructor */ public InternalJob() { } /** * Create a new Job with the given parameters. It provides methods to add or * remove tasks. * * @param name the current job name. * @param priority the priority of this job between 1 and 5. * @param cancelJobOnError true if the job has to run until its end or an user intervention. * @param description a short description of the job and what it will do. */ public InternalJob(String name, JobPriority priority, boolean cancelJobOnError, String description) { this.name = name; this.jobInfo.setPriority(priority); this.setCancelJobOnError(cancelJobOnError); this.description = description; } /** * This method will do two things :<br /> * First, it will update the job with the informations contained in the given taskInfo<br /> * Then, it will update the proper task using the same given taskInfo. * * @param info a taskInfo containing new information about the task. */ @Override public synchronized void update(TaskInfo info) { //ensure that is a JobInfoImpl //if not, we are in client side and client brings its own JobInfo Implementation if (!getId().equals(info.getJobId())) { throw new IllegalArgumentException( "This job info is not applicable for this job. (expected id is '" + getId() + "' but was '" + info.getJobId() + "'"); } jobInfo = (JobInfoImpl) info.getJobInfo(); try { tasks.get(info.getTaskId()).update(info); } catch (NullPointerException e) { throw new IllegalArgumentException("This task info is not applicable in this job. (task id '" + info.getTaskId() + "' not found)"); } } /** * To update the content of this job with a jobInfo. * * @param info the JobInfo to set */ @Override public synchronized void update(JobInfo info) { if (!getId().equals(info.getJobId())) { throw new IllegalArgumentException( "This job info is not applicable for this job. (expected id is '" + getId() + "' but was '" + info.getJobId() + "'"); } //update job info this.jobInfo = (JobInfoImpl) info; //update task status if needed if (this.jobInfo.getTaskStatusModify() != null) { for (TaskId id : tasks.keySet()) { tasks.get(id).setStatus(this.jobInfo.getTaskStatusModify().get(id)); } } //update task finished time if needed if (this.jobInfo.getTaskFinishedTimeModify() != null) { for (TaskId id : tasks.keySet()) { if (this.jobInfo.getTaskFinishedTimeModify().containsKey(id)) { //a null send to a long setter throws a NullPointerException so, here is the fix tasks.get(id).setFinishedTime(this.jobInfo.getTaskFinishedTimeModify().get(id)); } } } // update skipped tasks if (this.jobInfo.getTasksSkipped() != null) { for (TaskId id : tasks.keySet()) { if (this.jobInfo.getTasksSkipped().contains(id)) { InternalTask it = tasks.get(id); it.setStatus(TaskStatus.SKIPPED); } } } // replicated tasks have been added through FlowAction#REPLICATE if (this.jobInfo.getTasksReplicated() != null) { updateTasksReplicated(); } // replicated tasks have been added through FlowAction#LOOP if (this.jobInfo.getTasksLooped() != null) { updateTasksLooped(); } } /** * Updates this job when tasks were replicated due to a {@link FlowActionType#REPLICATE} action * <p> * The internal state of the job will change: new tasks will be added, * existing tasks will be modified. */ private void updateTasksReplicated() { // key: replicated task / value : id of the original task // originalId not used as key because tasks can be replicated multiple times Map<InternalTask, TaskId> newTasks = new TreeMap<InternalTask, TaskId>(); // create the new tasks for (ReplicatedTask it : this.jobInfo.getTasksReplicated()) { InternalTask original = this.tasks.get(it.originalId); InternalTask replicated = null; try { replicated = (InternalTask) original.replicate(); } catch (Exception e) { } replicated.setId(it.replicatedId); // for some reason the indices are embedded in the Readable name and not where they belong int dupId = InternalTask.getReplicationIndexFromName(it.replicatedId.getReadableName()); int itId = InternalTask.getIterationIndexFromName(it.replicatedId.getReadableName()); replicated.setReplicationIndex(dupId); replicated.setIterationIndex(itId); this.tasks.put(it.replicatedId, replicated); newTasks.put(replicated, it.originalId); // when nesting REPLICATE, the original replicated task can have its Replication Index changed: // the new Replication Id of the original task is the lowest id among replicated tasks minus one int minDup = Integer.MAX_VALUE; for (ReplicatedTask it2 : this.jobInfo.getTasksReplicated()) { String iDup = InternalTask.getInitialName(it2.replicatedId.getReadableName()); String iOr = InternalTask.getInitialName(it.originalId.getReadableName()); if (iDup.equals(iOr)) { int iDupId = InternalTask.getReplicationIndexFromName(it2.replicatedId.getReadableName()); minDup = Math.min(iDupId, minDup); } } original.setReplicationIndex(minDup - 1); } // recreate deps contained in the data struct for (ReplicatedTask it : this.jobInfo.getTasksReplicated()) { InternalTask newtask = this.tasks.get(it.replicatedId); for (TaskId depId : it.deps) { InternalTask dep = this.tasks.get(depId); newtask.addDependence(dep); } } // plug mergers List<InternalTask> toAdd = new ArrayList<InternalTask>(); for (InternalTask old : this.tasks.values()) { // task is not a replicated one, has dependencies if (!newTasks.containsValue(old.getId()) && old.hasDependences()) { for (InternalTask oldDep : old.getIDependences()) { // one of its dependencies is a replicated task if (newTasks.containsValue(oldDep.getId())) { // connect those replicated tasks to the merger for (Entry<InternalTask, TaskId> newTask : newTasks.entrySet()) { if (newTask.getValue().equals(oldDep.getId())) { toAdd.add(newTask.getKey()); } } } } // avoids concurrent modification for (InternalTask newDep : toAdd) { old.addDependence(newDep); } toAdd.clear(); } } } /** * Updates this job when tasks were replicated due to a {@link FlowActionType#LOOP} action * <p> * The internal state of the job will change: new tasks will be added, * existing tasks will be modified. */ private void updateTasksLooped() { Map<TaskId, InternalTask> newTasks = new TreeMap<TaskId, InternalTask>(); // create the new tasks for (ReplicatedTask it : this.jobInfo.getTasksLooped()) { InternalTask original = this.tasks.get(it.originalId); InternalTask replicated = null; try { replicated = (InternalTask) original.replicate(); } catch (Exception e) { } replicated.setId(it.replicatedId); // for some reason the indices are embedded in the Readable name and not where they belong int dupId = InternalTask.getReplicationIndexFromName(it.replicatedId.getReadableName()); int itId = InternalTask.getIterationIndexFromName(it.replicatedId.getReadableName()); replicated.setReplicationIndex(dupId); replicated.setIterationIndex(itId); this.tasks.put(it.replicatedId, replicated); newTasks.put(it.originalId, replicated); } InternalTask oldInit = null; // recreate deps contained in the data struct for (ReplicatedTask it : this.jobInfo.getTasksLooped()) { InternalTask newtask = this.tasks.get(it.replicatedId); for (TaskId depId : it.deps) { InternalTask dep = this.tasks.get(depId); if (!newTasks.containsValue(dep)) { oldInit = dep; } newtask.addDependence(dep); } } // find mergers InternalTask newInit = null; InternalTask merger = null; for (InternalTask old : this.tasks.values()) { // the merger is not a replicated task, nor has been replicated if (!newTasks.containsKey(old.getId()) && !newTasks.containsValue(old) && old.hasDependences()) { for (InternalTask oldDep : old.getIDependences()) { // merger's deps contains the initiator of the LOOP if (oldDep.equals(oldInit)) { merger = old; break; } } if (merger != null) { break; } } } // merger can be null if (merger != null) { // find new initiator Map<TaskId, InternalTask> newTasks2 = new HashMap<TaskId, InternalTask>(); for (InternalTask it : newTasks.values()) { newTasks2.put(it.getId(), it); } for (InternalTask it : newTasks.values()) { if (it.hasDependences()) { for (InternalTask dep : it.getIDependences()) { newTasks2.remove(dep.getId()); } } } for (InternalTask it : newTasks2.values()) { newInit = it; break; } merger.getIDependences().remove(oldInit); merger.addDependence(newInit); } } /** * @see org.ow2.proactive.scheduler.common.job.JobState#getJobInfo() */ @Override public JobInfo getJobInfo() { return jobInfo; } /** * Append a task to this job. * * @param task the task to add. * @return true if the task has been correctly added to the job, false if * not. */ public boolean addTask(InternalTask task) { task.setJobId(getId()); if (TaskIdImpl.getCurrentValue() < this.tasks.size()) { TaskIdImpl.initialize(tasks.size()); } task.setId(TaskIdImpl.nextId(getId(), task.getName())); boolean result = (tasks.put(task.getId(), task) == null); if (result) { jobInfo.setTotalNumberOfTasks(jobInfo.getTotalNumberOfTasks() + 1); } return result; } /** * Start a new task will set some count and update dependencies if necessary. * * @param td the task which has just been started. */ public void startTask(InternalTask td) { logger_dev.debug(" "); setNumberOfPendingTasks(getNumberOfPendingTasks() - 1); setNumberOfRunningTasks(getNumberOfRunningTasks() + 1); if (getStatus() == JobStatus.STALLED) { setStatus(JobStatus.RUNNING); } getJobDescriptor().start(td.getId()); td.setStatus(TaskStatus.RUNNING); td.setStartTime(System.currentTimeMillis()); td.setFinishedTime(-1); td.setExecutionHostName(td.getExecuterInformations().getHostName() + " (" + td.getExecuterInformations().getNodeName() + ")"); } /** * Start dataspace configuration and application */ public void startDataSpaceApplication(NamingService namingService, String namingServiceURL) { if (jobDataSpaceApplication == null) { long appId = getJobInfo().getJobId().hashCode(); jobDataSpaceApplication = new JobDataSpaceApplication(appId, namingService, namingServiceURL); } jobDataSpaceApplication.startDataSpaceApplication(getInputSpace(), getOutputSpace(), getOwner(), getId()); } /** * Updates count for running to pending event. */ public void newWaitingTask() { logger_dev.debug(" "); setNumberOfPendingTasks(getNumberOfPendingTasks() + 1); setNumberOfRunningTasks(getNumberOfRunningTasks() - 1); if (getNumberOfRunningTasks() == 0 && getStatus() != JobStatus.PAUSED) { setStatus(JobStatus.STALLED); } } /** * Set this task in restart mode, it will set the task to pending status and change task count. * * @param task the task which has to be restarted. */ public void reStartTask(InternalTask task) { logger_dev.debug(" "); getJobDescriptor().reStart(task.getId()); task.setProgress(0); if (getStatus() == JobStatus.PAUSED) { task.setStatus(TaskStatus.PAUSED); HashMap<TaskId, TaskStatus> hts = new HashMap<TaskId, TaskStatus>(); hts.put(task.getId(), task.getStatus()); getJobDescriptor().update(hts); } else { task.setStatus(TaskStatus.PENDING); } } /** * Terminate a task, change status, managing dependences * * Also, apply a Control Flow Action if provided. * This may alter the number of tasks in the job, * events have to be sent accordingly. * * @param errorOccurred has an error occurred for this termination * @param taskId the task to terminate. * @param frontend Used to notify all listeners of the replication of tasks, triggered by the FlowAction * @param action a Control Flow Action that will potentially create new tasks inside the job * @return the taskDescriptor that has just been terminated. */ public InternalTask terminateTask(boolean errorOccurred, TaskId taskId, SchedulerFrontend frontend, FlowAction action) { logger_dev.debug(" "); InternalTask descriptor = tasks.get(taskId); descriptor.setFinishedTime(System.currentTimeMillis()); descriptor.setStatus(errorOccurred ? TaskStatus.FAULTY : TaskStatus.FINISHED); try { descriptor.setExecutionDuration(((TaskResultImpl) getJobResult().getResult(descriptor.getName())) .getTaskDuration()); } catch (UnknownTaskException ute) { //should never happen : taskName is unknown logger_dev.error("", ute); } setNumberOfRunningTasks(getNumberOfRunningTasks() - 1); setNumberOfFinishedTasks(getNumberOfFinishedTasks() + 1); if ((getStatus() == JobStatus.RUNNING) && (getNumberOfRunningTasks() == 0)) { setStatus(JobStatus.STALLED); } boolean didAction = false; if (action != null) { InternalTask initiator = tasks.get(taskId); switch (action.getType()) { /* * LOOP action * */ case LOOP: { { // find the target of the loop InternalTask target = null; if (action.getTarget().equals(initiator.getName())) { target = initiator; } else { target = findTaskUp(action.getTarget(), initiator); } TaskId targetId = target.getTaskInfo().getTaskId(); logger_dev.info("Control Flow Action LOOP (init:" + initiator.getId() + ";target:" + target.getId() + ")"); // accumulates the tasks between the initiator and the target Map<TaskId, InternalTask> dup = new HashMap<TaskId, InternalTask>(); // replicate the tasks between the initiator and the target try { initiator.replicateTree(dup, targetId, true, initiator.getReplicationIndex(), initiator.getIterationIndex()); } catch (ExecutableCreationException e) { logger_dev.error("", e); break; } ((JobInfoImpl) this.getJobInfo()).setNumberOfPendingTasks(this.getJobInfo() .getNumberOfPendingTasks() + dup.size()); // ensure naming unicity // time-consuming but safe for (InternalTask nt : dup.values()) { boolean ok; do { ok = true; for (InternalTask task : tasks.values()) { if (nt.getName().equals(task.getName())) { nt.setIterationIndex(nt.getIterationIndex() + 1); ok = false; } } } while (!ok); } // configure the new tasks InternalTask newTarget = null; InternalTask newInit = null; for (Entry<TaskId, InternalTask> it : dup.entrySet()) { InternalTask nt = it.getValue(); if (target.getId().equals(it.getKey())) { newTarget = nt; } if (initiator.getId().equals(it.getKey())) { newInit = nt; } nt.setJobInfo(getJobInfo()); this.addTask(nt); //add entry to job result ((JobResultImpl) this.getJobResult()).addToAllResults(nt.getName()); } // connect replicated tree newTarget.addDependence(initiator); // connect mergers List<InternalTask> mergers = new ArrayList<InternalTask>(); for (InternalTask t : this.tasks.values()) { if (t.getIDependences() != null) { for (InternalTask p : t.getIDependences()) { if (p.getId().equals(initiator.getId())) { if (!t.equals(newTarget)) { mergers.add(t); } } } } } for (InternalTask t : mergers) { t.getIDependences().remove(initiator); t.addDependence(newInit); } // propagate the changes in the job descriptor getJobDescriptor().doLoop(taskId, dup, newTarget, newInit); List<ReplicatedTask> tev = new ArrayList<ReplicatedTask>(); for (Entry<TaskId, InternalTask> it : dup.entrySet()) { ReplicatedTask tid = new ReplicatedTask(it.getKey(), it.getValue().getId()); if (it.getValue().hasDependences()) { for (InternalTask dep : it.getValue().getIDependences()) { tid.deps.add(dep.getId()); } } tev.add(tid); } this.jobInfo.setTasksLooped(tev); // notify listeners that tasks were added to the job frontend.jobStateUpdated(this.getOwner(), new NotificationData<JobInfo>( SchedulerEvent.TASK_REPLICATED, this.getJobInfo())); this.jobInfo.setTasksLooped(null); didAction = true; break; } } /* * IF action * */ case IF: { // the targetIf from action.getTarget() is the selected branch; // the IF condition has already been evaluated prior to being put in a FlowAction // the targetElse from action.getTargetElse() is the branch that was NOT selected InternalTask targetIf = null; InternalTask targetElse = null; InternalTask targetJoin = null; // search for the targets as perfect matches of the unique name for (InternalTask it : tasks.values()) { // target is finished : probably looped if (it.getStatus().equals(TaskStatus.FINISHED) || it.getStatus().equals(TaskStatus.SKIPPED)) { continue; } if (action.getTarget().equals(it.getName())) { if (it.getIfBranch().equals(initiator)) { targetIf = it; } } else if (action.getTargetElse().equals(it.getName())) { if (it.getIfBranch().equals(initiator)) { targetElse = it; } } else if (action.getTargetContinuation().equals(it.getName())) { if (findTaskUp(initiator.getName(), it).equals(initiator)) { targetJoin = it; } } } boolean searchIf = (targetIf == null); boolean searchElse = (targetElse == null); boolean searchJoin = (targetJoin == null); // search of a runnable perfect match for the targets failed; // the natural target was iterated, need to find the next iteration // which is the the one with the same dup index and base name, // but the highest iteration index for (InternalTask it : tasks.values()) { // does not share the same dup index : cannot be the same scope if (it.getReplicationIndex() != initiator.getReplicationIndex()) { continue; } if (it.getStatus().equals(TaskStatus.FINISHED) || it.getStatus().equals(TaskStatus.SKIPPED)) { continue; } String name = InternalTask.getInitialName(it.getName()); if (searchIf && InternalTask.getInitialName(action.getTarget()).equals(name)) { if (targetIf == null || targetIf.getIterationIndex() < it.getIterationIndex()) { targetIf = it; } } else if (searchElse && InternalTask.getInitialName(action.getTargetElse()).equals(name)) { if (targetElse == null || targetElse.getIterationIndex() < it.getIterationIndex()) { targetElse = it; } } else if (searchJoin && InternalTask.getInitialName(action.getTargetContinuation()).equals(name)) { if (targetJoin == null || targetJoin.getIterationIndex() < it.getIterationIndex()) { targetJoin = it; } } } logger_dev.info("Control Flow Action IF: " + targetIf.getId() + " join: " + ((targetJoin == null) ? "null" : targetJoin.getId())); // these 2 tasks delimit the Task Block formed by the IF branch InternalTask branchStart = targetIf; InternalTask branchEnd = null; String match = targetIf.getMatchingBlock(); if (match != null) { for (InternalTask t : tasks.values()) { if (match.equals(t.getName()) && !(t.getStatus().equals(TaskStatus.FINISHED) || t.getStatus().equals( TaskStatus.SKIPPED))) { branchEnd = t; } } } // no matching block: there is no block, the branch is a single task if (branchEnd == null) { branchEnd = targetIf; } // plug the branch branchStart.addDependence(initiator); if (targetJoin != null) { targetJoin.addDependence(branchEnd); } // the other branch will not be executed // first, find the concerned tasks List<InternalTask> elseTasks = new ArrayList<InternalTask>(); // elseTasks.add(targetElse); for (InternalTask t : this.tasks.values()) { if (t.dependsOn(targetElse)) { elseTasks.add(t); } } List<TaskId> tev = new ArrayList<TaskId>(elseTasks.size()); for (InternalTask it : elseTasks) { it.setFinishedTime(System.currentTimeMillis()); it.setStatus(TaskStatus.SKIPPED); it.setExecutionDuration(0); setNumberOfPendingTasks(getNumberOfPendingTasks() - 1); setNumberOfFinishedTasks(getNumberOfFinishedTasks() + 1); tev.add(it.getId()); DatabaseManager.getInstance().unload(it); logger_dev.info("Task " + it.getId() + " will not be executed"); } // plug the branch in the descriptor TaskId joinId = null; if (targetJoin != null) { joinId = targetJoin.getId(); } getJobDescriptor().doIf(initiator.getId(), branchStart.getId(), branchEnd.getId(), joinId, targetElse.getId(), elseTasks); this.jobInfo.setTasksSkipped(tev); // notify listeners that tasks were skipped frontend.jobStateUpdated(this.getOwner(), new NotificationData<JobInfo>( SchedulerEvent.TASK_SKIPPED, this.getJobInfo())); this.jobInfo.setTasksSkipped(null); // no jump is performed ; now that the tasks have been plugged // the flow can continue its normal operation getJobDescriptor().terminate(taskId); didAction = true; break; } /* * REPLICATE action * */ case REPLICATE: { int runs = action.getDupNumber(); if (runs < 1) { runs = 1; } logger_dev.info("Control Flow Action REPLICATE (runs:" + runs + ")"); List<InternalTask> toReplicate = new ArrayList<InternalTask>(); // find the tasks that need to be replicated for (InternalTask ti : tasks.values()) { List<InternalTask> tl = ti.getIDependences(); if (tl != null) { for (InternalTask ts : tl) { if (ts.getId().equals(initiator.getId()) && !toReplicate.contains(ti)) { // ti needs to be replicated toReplicate.add(ti); } } } } List<ReplicatedTask> tasksEvent = new ArrayList<ReplicatedTask>(); // for each initial task to replicate for (InternalTask todup : toReplicate) { // determine the target of the replication whether it is a block or a single task InternalTask target = null; // target is a task block start : replication of the block if (todup.getFlowBlock().equals(FlowBlock.START)) { String tg = todup.getMatchingBlock(); for (InternalTask t : tasks.values()) { if (tg.equals(t.getName()) && !(t.getStatus().equals(TaskStatus.FINISHED) || t.getStatus().equals( TaskStatus.SKIPPED)) && t.dependsOn(todup)) { target = t; break; } } if (target == null) { logger_dev.error("REPLICATE: could not find matching block '" + tg + "'"); continue; } } // target is not a block : replication of the task else { target = todup; } // for each number of parallel run for (int i = 1; i < runs; i++) { // accumulates the tasks between the initiator and the target Map<TaskId, InternalTask> dup = new HashMap<TaskId, InternalTask>(); // replicate the tasks between the initiator and the target try { target.replicateTree(dup, todup.getId(), false, initiator .getReplicationIndex() * runs, 0); } catch (Exception e) { logger_dev.error("REPLICATE: could not replicate tree", e); break; } ((JobInfoImpl) this.getJobInfo()).setNumberOfPendingTasks(this.getJobInfo() .getNumberOfPendingTasks() + dup.size()); // pointers to the new replicated tasks corresponding the begin and // the end of the block ; can be the same InternalTask newTarget = null; InternalTask newEnd = null; // configure the new tasks for (Entry<TaskId, InternalTask> it : dup.entrySet()) { InternalTask nt = it.getValue(); nt.setJobInfo(getJobInfo()); this.addTask(nt); int dupIndex = initiator.getReplicationIndex() * runs + i; nt.setReplicationIndex(dupIndex); //add entry to job result ((JobResultImpl) this.getJobResult()).addToAllResults(nt.getName()); } // find the beginning and the ending of the replicated block for (Entry<TaskId, InternalTask> it : dup.entrySet()) { InternalTask nt = it.getValue(); // connect the first task of the replicated block to the initiator if (todup.getId().equals(it.getKey())) { newTarget = nt; newTarget.addDependence(initiator); } // connect the last task of the block with the merge task(s) if (target.getId().equals(it.getKey())) { newEnd = nt; List<InternalTask> toAdd = new ArrayList<InternalTask>(); // find the merge tasks ; can be multiple for (InternalTask t : tasks.values()) { List<InternalTask> pdeps = t.getIDependences(); if (pdeps != null) { for (InternalTask parent : pdeps) { if (parent.getId().equals(target.getId())) { toAdd.add(t); } } } } // connect the merge tasks for (InternalTask t : toAdd) { t.addDependence(newEnd); } } } // propagate the changes on the JobDescriptor getJobDescriptor().doReplicate(taskId, dup, newTarget, target.getId(), newEnd.getId()); // used by the event dispatcher for (Entry<TaskId, InternalTask> it : dup.entrySet()) { ReplicatedTask tid = new ReplicatedTask(it.getKey(), it.getValue().getId()); if (it.getValue().hasDependences()) { for (InternalTask dep : it.getValue().getIDependences()) { tid.deps.add(dep.getId()); } } tasksEvent.add(tid); } } } // notify listeners that tasks were added to the job this.jobInfo.setTasksReplicated(tasksEvent); frontend.jobStateUpdated(this.getOwner(), new NotificationData<JobInfo>( SchedulerEvent.TASK_REPLICATED, this.getJobInfo())); this.jobInfo.setTasksReplicated(null); // no jump is performed ; now that the tasks have been replicated and // configured, the flow can continue its normal operation getJobDescriptor().terminate(taskId); didAction = true; break; } /* * CONTINUE action : * - continue taskflow as if no action was provided */ case CONTINUE: logger_dev.debug("Task flow Action CONTINUE on task " + initiator.getId().getReadableName()); break; } /** System.out.println("******** task dump ** " + this.getJobInfo().getJobId() + " " + initiator.getName() + " does " + action.getType() + " " + ((action.getTarget() == null) ? "." : action.getTarget()) + " " + ((action.getTargetElse() == null) ? "." : action.getTargetElse()) + " " + ((action.getTargetJoin() == null) ? "." : action.getTargetJoin())); for (InternalTask it : this.tasks.values()) { System.out.print(it.getName() + " "); if (it.getIDependences() != null) { System.out.print("deps "); for (InternalTask parent : it.getIDependences()) { System.out.print(parent.getName() + " "); } } if (it.getIfBranch() != null) { System.out.print("if " + it.getIfBranch().getName() + " "); } if (it.getJoinedBranches() != null && it.getJoinedBranches().size() == 2) { System.out.print("join " + it.getJoinedBranches().get(0).getName() + " " + it.getJoinedBranches().get(1).getName()); } System.out.println(); } System.out.println("******** task dump ** " + this.getJobInfo().getJobId()); System.out.println(); **/ } //terminate this task if (!didAction) { getJobDescriptor().terminate(taskId); } else { DatabaseManager.getInstance().startTransaction(); DatabaseManager.getInstance().synchronize(this.getJobInfo()); DatabaseManager.getInstance().synchronize(descriptor.getTaskInfo()); DatabaseManager.getInstance().update(this); DatabaseManager.getInstance().commitTransaction(); } //creating list of status for the jobDescriptor HashMap<TaskId, TaskStatus> hts = new HashMap<TaskId, TaskStatus>(); for (InternalTask td : tasks.values()) { hts.put(td.getId(), td.getStatus()); } //updating job descriptor for eligible task getJobDescriptor().update(hts); return descriptor; } /** * Walk up <code>down</code>'s dependences until * a task <code>name</code> is met * * also walks weak references created by {@link FlowActionType#IF} * * @return the task names <code>name</code>, or null */ private InternalTask findTaskUp(String name, InternalTask down) { InternalTask ret = null; List<InternalTask> ideps = new ArrayList<InternalTask>(); if (down.getIDependences() != null) { ideps.addAll(down.getIDependences()); } if (down.getJoinedBranches() != null) { ideps.addAll(down.getJoinedBranches()); } if (down.getIfBranch() != null) { ideps.add(down.getIfBranch()); } for (InternalTask up : ideps) { if (up.getName().equals(name)) { ret = up; } else { InternalTask r = findTaskUp(name, up); if (r != null) { ret = r; } } } return ret; } /** * Simulate that a task have been started and terminated. * Used only by the recovery method in scheduler core. * * @param id the id of the task to start and terminate. */ public void simulateStartAndTerminate(TaskId id) { logger_dev.debug(" "); getJobDescriptor().start(id); getJobDescriptor().terminate(id); } /** * Failed this job due to the given task failure or job has been killed * * @param taskId the task that has been the cause to failure. Can be null if the job has been killed * @param jobStatus type of the failure on this job. (failed/canceled/killed) */ public void failed(TaskId taskId, JobStatus jobStatus) { logger_dev.debug(" "); if (jobStatus != JobStatus.KILLED) { InternalTask descriptor = tasks.get(taskId); if (descriptor.getStartTime() > 0) { descriptor.setFinishedTime(System.currentTimeMillis()); setNumberOfFinishedTasks(getNumberOfFinishedTasks() + 1); } descriptor.setStatus((jobStatus == JobStatus.FAILED) ? TaskStatus.FAILED : TaskStatus.FAULTY); //terminate this job descriptor getJobDescriptor().failed(); } //set the new status of the job setFinishedTime(System.currentTimeMillis()); setNumberOfPendingTasks(0); setNumberOfRunningTasks(0); setStatus(jobStatus); //creating list of status HashMap<TaskId, TaskStatus> hts = new HashMap<TaskId, TaskStatus>(); HashMap<TaskId, Long> htl = new HashMap<TaskId, Long>(); for (InternalTask td : tasks.values()) { if (!td.getId().equals(taskId)) { if (td.getStatus() == TaskStatus.RUNNING) { td.setStatus(TaskStatus.ABORTED); td.setFinishedTime(System.currentTimeMillis()); } else if (td.getStatus() == TaskStatus.WAITING_ON_ERROR || td.getStatus() == TaskStatus.WAITING_ON_FAILURE) { td.setStatus(TaskStatus.NOT_RESTARTED); } else if (td.getStatus() != TaskStatus.FINISHED && td.getStatus() != TaskStatus.FAILED && td.getStatus() != TaskStatus.FAULTY && td.getStatus() != TaskStatus.SKIPPED) { td.setStatus(TaskStatus.NOT_STARTED); } } htl.put(td.getId(), td.getFinishedTime()); hts.put(td.getId(), td.getStatus()); } setTaskStatusModify(hts); setTaskFinishedTimeModify(htl); if (jobDataSpaceApplication != null) { jobDataSpaceApplication.terminateDataSpaceApplication(); } } /** * Get a task descriptor that is in the running task queue. * * @param id the id of the task descriptor to retrieve. * @return the task descriptor associated to this id, or null if not running. */ public TaskDescriptor getRunningTaskDescriptor(TaskId id) { return getJobDescriptor().GetRunningTaskDescriptor(id); } /** * Set all properties following a job submitting. */ public void submitAction() { logger_dev.debug(" "); setSubmittedTime(System.currentTimeMillis()); setStatus(JobStatus.PENDING); } /** * Prepare tasks in order to be ready to be scheduled. * The task may have a consistent id and job info. */ public synchronized void prepareTasks() { logger_dev.debug(" "); //get tasks ArrayList<InternalTask> sorted = getITasks(); //re-init taskId count TaskIdImpl.initialize(); //sort task according to the ID Collections.sort(sorted); tasks.clear(); for (InternalTask td : sorted) { TaskId newId = TaskIdImpl.nextId(getId(), td.getName()); td.setId(newId); td.setJobInfo(getJobInfo()); tasks.put(newId, td); } } /** * Set all properties in order to start the job. * After this method and for better performances you may have to * set the taskStatusModify to "null" : setTaskStatusModify(null); */ public void start() { logger_dev.debug(" "); setStartTime(System.currentTimeMillis()); setNumberOfPendingTasks(getTotalNumberOfTasks()); setNumberOfRunningTasks(0); setStatus(JobStatus.RUNNING); HashMap<TaskId, TaskStatus> taskStatus = new HashMap<TaskId, TaskStatus>(); for (InternalTask td : getITasks()) { td.setStatus(TaskStatus.PENDING); taskStatus.put(td.getId(), TaskStatus.PENDING); } setTaskStatusModify(taskStatus); } /** * Set all properties in order to terminate the job. */ public void terminate() { logger_dev.debug(" "); setStatus(JobStatus.FINISHED); setFinishedTime(System.currentTimeMillis()); if (jobDataSpaceApplication != null) { if (!TaskLauncher.logger_dev_dataspace.isDebugEnabled()) { jobDataSpaceApplication.terminateDataSpaceApplication(); } } } /** * Paused every running and submitted tasks in this pending job. * After this method and for better performances you may have to * set the taskStatusModify to "null" : setTaskStatusModify(null); * * @return true if the job has correctly been paused, false if not. */ public boolean setPaused() { logger_dev.debug(" "); if (jobInfo.getStatus() == JobStatus.PAUSED) { return false; } jobInfo.setStatus(JobStatus.PAUSED); HashMap<TaskId, TaskStatus> hts = new HashMap<TaskId, TaskStatus>(); for (InternalTask td : tasks.values()) { if ((td.getStatus() != TaskStatus.FINISHED) && (td.getStatus() != TaskStatus.RUNNING) && (td.getStatus() != TaskStatus.SKIPPED) && (td.getStatus() != TaskStatus.FAULTY)) { td.setStatus(TaskStatus.PAUSED); } hts.put(td.getId(), td.getStatus()); } getJobDescriptor().update(hts); setTaskStatusModify(hts); return true; } /** * Status of every paused tasks becomes pending or submitted in this pending job. * After this method and for better performances you may have to * set the taskStatusModify to "null" : setTaskStatusModify(null); * * @return true if the job has correctly been unpaused, false if not. */ public boolean setUnPause() { logger_dev.debug(" "); if (jobInfo.getStatus() != JobStatus.PAUSED) { return false; } if ((getNumberOfPendingTasks() + getNumberOfRunningTasks() + getNumberOfFinishedTasks()) == 0) { jobInfo.setStatus(JobStatus.PENDING); } else if (getNumberOfRunningTasks() == 0) { jobInfo.setStatus(JobStatus.STALLED); } else { jobInfo.setStatus(JobStatus.RUNNING); } HashMap<TaskId, TaskStatus> hts = new HashMap<TaskId, TaskStatus>(); for (InternalTask td : tasks.values()) { if (jobInfo.getStatus() == JobStatus.PENDING) { td.setStatus(TaskStatus.SUBMITTED); } else if ((jobInfo.getStatus() == JobStatus.RUNNING) || (jobInfo.getStatus() == JobStatus.STALLED)) { if ((td.getStatus() != TaskStatus.FINISHED) && (td.getStatus() != TaskStatus.RUNNING) && (td.getStatus() != TaskStatus.SKIPPED) && (td.getStatus() != TaskStatus.FAULTY)) { td.setStatus(TaskStatus.PENDING); } } hts.put(td.getId(), td.getStatus()); } getJobDescriptor().update(hts); setTaskStatusModify(hts); return true; } /** * @see org.ow2.proactive.scheduler.common.job.Job#setPriority(org.ow2.proactive.scheduler.common.job.JobPriority) */ @Override public void setPriority(JobPriority priority) { jobInfo.setPriority(priority); } /** * @see org.ow2.proactive.scheduler.common.job.JobState#getTasks() */ @Override public ArrayList<TaskState> getTasks() { return new ArrayList<TaskState>(tasks.values()); } /** * @see org.ow2.proactive.scheduler.common.job.JobState#getHMTasks() */ @Override public Map<TaskId, TaskState> getHMTasks() { Map<TaskId, TaskState> tmp = new HashMap<TaskId, TaskState>(); for (Entry<TaskId, InternalTask> e : tasks.entrySet()) { tmp.put(e.getKey(), e.getValue()); } return tmp; } /** * To get the tasks as an array list. * * @return the tasks */ public ArrayList<InternalTask> getITasks() { return new ArrayList<InternalTask>(tasks.values()); } /** * To get the tasks as a hash map. * * @return the tasks */ public Map<TaskId, InternalTask> getIHMTasks() { return tasks; } /** * To set the taskStatusModify * * @param taskStatusModify the taskStatusModify to set */ public void setTaskStatusModify(Map<TaskId, TaskStatus> taskStatusModify) { jobInfo.setTaskStatusModify(taskStatusModify); } /** * To set the taskFinishedTimeModify * * @param taskFinishedTimeModify the taskFinishedTimeModify to set */ public void setTaskFinishedTimeModify(Map<TaskId, Long> taskFinishedTimeModify) { jobInfo.setTaskFinishedTimeModify(taskFinishedTimeModify); } /** * To set the tasksReplicated * * @param d tasksReplicated */ public void setReplicatedTasksModify(List<ReplicatedTask> d) { jobInfo.setTasksReplicated(d); } /** * To set the tasksLooped * * @param d tasksLooped */ public void setLoopedTasksModify(List<ReplicatedTask> d) { jobInfo.setTasksLooped(d); } /** * To set the tasksSkipped * * @param d tasksSkipped */ public void setSkippedTasksModify(List<TaskId> d) { jobInfo.setTasksSkipped(d); } /** * To set the id * * @param id the id to set */ public void setId(JobId id) { jobInfo.setJobId(id); } /** * To set the finishedTime * * @param finishedTime * the finishedTime to set */ public void setFinishedTime(long finishedTime) { jobInfo.setFinishedTime(finishedTime); } /** * To set the startTime * * @param startTime * the startTime to set */ public void setStartTime(long startTime) { jobInfo.setStartTime(startTime); } /** * To set the submittedTime * * @param submittedTime * the submittedTime to set */ public void setSubmittedTime(long submittedTime) { jobInfo.setSubmittedTime(submittedTime); } /** * To set the removedTime * * @param removedTime * the removedTime to set */ public void setRemovedTime(long removedTime) { jobInfo.setRemovedTime(removedTime); } /** * To set the numberOfFinishedTasks * * @param numberOfFinishedTasks the numberOfFinishedTasks to set */ public void setNumberOfFinishedTasks(int numberOfFinishedTasks) { jobInfo.setNumberOfFinishedTasks(numberOfFinishedTasks); } /** * To set the numberOfPendingTasks * * @param numberOfPendingTasks the numberOfPendingTasks to set */ public void setNumberOfPendingTasks(int numberOfPendingTasks) { jobInfo.setNumberOfPendingTasks(numberOfPendingTasks); } /** * To set the numberOfRunningTasks * * @param numberOfRunningTasks the numberOfRunningTasks to set */ public void setNumberOfRunningTasks(int numberOfRunningTasks) { jobInfo.setNumberOfRunningTasks(numberOfRunningTasks); } /** * To get the jobDescriptor * * @return the jobDescriptor */ @XmlTransient public JobDescriptorImpl getJobDescriptor() { if (jobDescriptor == null) { jobDescriptor = new JobDescriptorImpl(this); } return (JobDescriptorImpl) jobDescriptor; } /** * Set the job Descriptor * * @param jobD the JobDescriptor to set. */ public void setJobDescriptor(JobDescriptor jobD) { this.jobDescriptor = jobD; } /** * @param status the status to set */ public void setStatus(JobStatus status) { jobInfo.setStatus(status); } /** * @see org.ow2.proactive.scheduler.common.job.JobState#getOwner() */ @Override public String getOwner() { return owner; } /** * To set the owner of this job. * * @param owner the owner to set. */ public void setOwner(String owner) { this.owner = owner; } /** * @see org.ow2.proactive.scheduler.common.job.JobState#getJobResult() */ public JobResult getJobResult() { return jobResult; } /** * Sets the jobResult to the given jobResult value. * * @param jobResult the jobResult to set. */ public void setJobResult(JobResult jobResult) { this.jobResult = jobResult; } /** * Get the credentials for this job * * @return the credentials for this job */ public Credentials getCredentials() { return credentials; } /** * Set the credentials value to the given credentials value * * @param credentials the credentials to set */ public void setCredentials(Credentials credentials) { this.credentials = credentials; } /** * Get the next restart waiting time in millis. * * @return the next restart waiting time in millis. */ public long getNextWaitingTime(int executionNumber) { if (executionNumber <= 0) { //execution number is 0 or less, restart with the minimal amount of time return restartWaitingTimer; } else if (executionNumber > 10) { //execution timer exceed 10, restart after 60 seconds return 60 * 1000; } else { //else restart according to this function return (getNextWaitingTime(executionNumber - 1) + executionNumber * 1000); } } /** * Set this job to the state toBeRemoved. */ public void setToBeRemoved() { jobInfo.setToBeRemoved(); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if (o instanceof InternalJob) { return getId().equals(((InternalJob) o).getId()); } return false; } /** * Get the jobDataSpaceApplication * * @return the jobDataSpaceApplication */ public JobDataSpaceApplication getJobDataSpaceApplication() { return jobDataSpaceApplication; } @Transient private transient Map<String, InternalTask> tasknameITaskMapping = null; /** * Return the internal task associated with the given task name for this job. * * @param taskName the task name to find * @return the internal task associated with the given name. * @throws UnknownTaskException if the given taskName does not exist. */ public InternalTask getTask(String taskName) throws UnknownTaskException { if (tasknameITaskMapping == null) { tasknameITaskMapping = new HashMap<String, InternalTask>(tasks.size()); for (InternalTask it : tasks.values()) { tasknameITaskMapping.put(it.getId().getReadableName(), it); } } if (tasknameITaskMapping.containsKey(taskName)) { return tasknameITaskMapping.get(taskName); } else { throw new UnknownTaskException("'" + taskName + "' does not exist in this job."); } } //******************************************************************** //************************* SERIALIZATION **************************** //******************************************************************** /** * <b>IMPORTANT : </b><br /> * Using hibernate does not allow to have java transient fields that is inserted in database anyway.<br /> * Hibernate defined @Transient annotation meaning the field won't be inserted in database. * If the java transient modifier is set for a field, so the hibernate @Transient annotation becomes * useless and the field won't be inserted in DB anyway.<br /> * For performance reason, some field must be java transient but not hibernate transient. * These fields are annotated with @TransientInSerialization. * The @TransientInSerialization describe the fields that won't be serialized by java since the two following * methods describe the serialization process. */ private void writeObject(ObjectOutputStream out) throws IOException { try { Map<String, Object> toSerialize = new HashMap<String, Object>(); Field[] fields = InternalJob.class.getDeclaredFields(); for (Field f : fields) { if (!f.isAnnotationPresent(TransientInSerialization.class) && !Modifier.isStatic(f.getModifiers())) { toSerialize.put(f.getName(), f.get(this)); } } out.writeObject(toSerialize); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { try { Map<String, Object> map = (Map<String, Object>) in.readObject(); for (Entry<String, Object> e : map.entrySet()) { InternalJob.class.getDeclaredField(e.getKey()).set(this, e.getValue()); } } catch (Exception e) { throw new RuntimeException(e); } } }
package cn.fuyoushuo.fqbb.view.flagment.login; import android.app.Activity; import android.content.Context; import android.text.Html; import android.text.InputType; import android.text.TextUtils; import android.text.method.HideReturnsTransformationMethod; import android.text.method.LinkMovementMethod; import android.text.method.PasswordTransformationMethod; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.jakewharton.rxbinding.view.RxView; import com.jakewharton.rxbinding.widget.RxTextView; import com.trello.rxlifecycle.FragmentEvent; import java.util.concurrent.TimeUnit; import butterknife.Bind; import cn.fuyoushuo.fqbb.MyApplication; import cn.fuyoushuo.fqbb.R; import cn.fuyoushuo.fqbb.commonlib.utils.RxBus; import cn.fuyoushuo.fqbb.presenter.impl.LocalLoginPresent; import cn.fuyoushuo.fqbb.presenter.impl.login.RegisterOnePresenter; import cn.fuyoushuo.fqbb.view.flagment.BaseFragment; import cn.fuyoushuo.fqbb.view.flagment.UserAgreementDialogFragment; import cn.fuyoushuo.fqbb.view.listener.MyTagHandler; import cn.fuyoushuo.fqbb.view.view.login.RegisterOneView; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; /** * 用于管理登录页面 * Created by QA on 2016/10/28. */ public class RegisterOneFragment extends BaseFragment implements RegisterOneView{ public static final String TAG_NAME = "register_one_fragment"; @Bind(R.id.account_value) EditText phoneNumText; //验证码 @Bind(R.id.verificate_value) EditText verifiCodeView; @Bind(R.id.acquire_verification_button) Button acquireVerifiButton; @Bind(R.id.password_value) EditText passwordView; @Bind(R.id.commit_button) Button commitButton; @Bind(R.id.login_tip_area) TextView loginTipTextView; @Bind(R.id.userAgreement_tip) TextView userAgreementTipView; @Bind(R.id.register_hidePass_area) ImageView hidePassView; private String phoneNum = ""; private String password = ""; private String verifiCode = ""; private boolean isPasswordHidden = true; RegisterOnePresenter registerOnePresenter; LocalLoginPresent localLoginPresent; //判断账号是否满足要求 private boolean isAccountRight = false; private long time = 60l; @Override protected String getPageName() { return "register-1"; } @Override protected int getRootLayoutId() { return R.layout.fragment_register_1; } @Override protected void initView() { // phoneNumText.setFocusable(true); // phoneNumText.setFocusableInTouchMode(true); // phoneNumText.requestFocus(); //手机号码 RxTextView.textChanges(phoneNumText) .compose(this.<CharSequence>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribe(new Action1<CharSequence>() { @Override public void call(CharSequence charSequence) { phoneNum = charSequence.toString(); } }); //验证码 RxTextView.textChanges(verifiCodeView) .compose(this.<CharSequence>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribe(new Action1<CharSequence>() { @Override public void call(CharSequence charSequence) { verifiCode = charSequence.toString(); } }); //密码 RxTextView.textChanges(passwordView) .compose(this.<CharSequence>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribe(new Action1<CharSequence>() { @Override public void call(CharSequence charSequence) { password = charSequence.toString(); } }); //显示和隐藏密码 RxView.clicks(hidePassView).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000,TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { if(isPasswordHidden){ isPasswordHidden = false; passwordView.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); hidePassView.setImageResource(R.mipmap.new_pass); }else{ isPasswordHidden = true; passwordView.setTransformationMethod(PasswordTransformationMethod.getInstance()); hidePassView.setImageResource(R.mipmap.ver_pass); } } }); RxView.clicks(loginTipTextView).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000,TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { RxBus.getInstance().send(new ToLoginOriginEvent()); } }); RxView.clicks(acquireVerifiButton).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { // TODO: 2016/10/28 获取验证码 localLoginPresent.validateData(phoneNum,1, new LocalLoginPresent.DataValidataCallBack() { @Override public void onValidataSucc(int flag) { if(flag == 1){ isAccountRight = false; Toast.makeText(MyApplication.getContext(),"手机号码已被注册",Toast.LENGTH_SHORT).show(); }else{ isAccountRight = true; registerOnePresenter.getVerifiCode(phoneNum); timeForVerifiCode(); } } @Override public void onValidataFail(String msg) { isAccountRight = false; Toast.makeText(MyApplication.getContext(),"手机号码不可用,请检查账号后再次输入",Toast.LENGTH_SHORT).show(); } }); }}); //提交按钮 RxView.clicks(commitButton).throttleFirst(1000, TimeUnit.MILLISECONDS) .compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { if(!TextUtils.isEmpty(phoneNum) && !TextUtils.isEmpty(verifiCode) && !TextUtils.isEmpty(password)){ registerOnePresenter.registUser(phoneNum,password,verifiCode); }else{ Toast.makeText(MyApplication.getContext(),"信息不完整,无法注册",Toast.LENGTH_SHORT).show(); } } }); phoneNumText.setInputType(InputType.TYPE_CLASS_PHONE); userAgreementTipView.setText(Html.fromHtml("• 注册或登录即视为同意<font color=\"red\"><userAgree>《返钱宝宝用户使用协议》</userAgree></font>",null, new MyTagHandler("userAgree", new MyTagHandler.OnClickTag() { @Override public void onClick() { UserAgreementDialogFragment.newInstance().show(getFragmentManager(),"UserAgreementDialogFragment"); } }))); userAgreementTipView.setHighlightColor(getResources().getColor(android.R.color.transparent)); userAgreementTipView.setMovementMethod(LinkMovementMethod.getInstance()); } @Override protected void initData() { registerOnePresenter = new RegisterOnePresenter(this); localLoginPresent = new LocalLoginPresent(); } public static RegisterOneFragment newInstance() { RegisterOneFragment fragment = new RegisterOneFragment(); return fragment; } @Override public void onDestroy() { super.onDestroy(); if(registerOnePresenter != null){ registerOnePresenter.onDestroy(); } if(localLoginPresent != null){ localLoginPresent.onDestroy(); } } private void timeForVerifiCode() { acquireVerifiButton.setText("获取验证码(60)"); acquireVerifiButton.setClickable(false); acquireVerifiButton.setBackgroundColor(getResources().getColor(R.color.gray)); Observable.timer(1, TimeUnit.SECONDS) .compose(this.<Long>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .repeat(60) .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { time--; if(acquireVerifiButton == null){ return; } if (time > 0) { acquireVerifiButton.setText("获取验证码(" + time + ")"); } else { acquireVerifiButton.setClickable(true); acquireVerifiButton.setBackgroundColor(getResources().getColor(R.color.module_6)); acquireVerifiButton.setText("重新获取验证码"); time = 60l; } } }); } //---------------------------------实现VIEW层的接口--------------------------------------------------------- @Override public void onErrorRecieveVerifiCode(String respMsg) { String msg = "验证码发送失败,请重试"; if(!TextUtils.isEmpty(respMsg)){ msg = respMsg; } Toast.makeText(MyApplication.getContext(),respMsg,Toast.LENGTH_SHORT).show(); } @Override public void onSuccessRecieveVerifiCode(String phoneNum) { Toast.makeText(MyApplication.getContext(),"验证码发送成功,请耐心等待",Toast.LENGTH_SHORT).show(); } @Override public void onRegistSuccess(String phoneNum) { localLoginPresent.userLogin(phoneNum, password, new LocalLoginPresent.LocalLoginCallBack() { @Override public void onLocalLoginSucc(String account) { RxBus.getInstance().send(new LoginSuccAfterRegisterSucc()); } @Override public void onLocalLoginFail(String account) { RxBus.getInstance().send(new ToLoginAfterRegisterSuccess(account)); } }); } @Override public void onRegistFail(String phoneNum, String msg) { Toast.makeText(MyApplication.getContext(),msg,Toast.LENGTH_SHORT).show(); } //--------------------------------与activity 通信接口------------------------------------------------------------ // public class ToRegisterTwoEvent extends RxBus.BusEvent{ // // private String phoneNum; // // public ToRegisterTwoEvent(String phoneNum) { // this.phoneNum = phoneNum; // } // // public String getPhoneNum() { // return phoneNum; // } // // public void setPhoneNum(String phoneNum) { // this.phoneNum = phoneNum; // } // } public class ToLoginAfterRegisterSuccess extends RxBus.BusEvent{ private String phoneNum; public ToLoginAfterRegisterSuccess(String phoneNum) { this.phoneNum = phoneNum; } public String getPhoneNum() { return phoneNum; } } public class LoginSuccAfterRegisterSucc extends RxBus.BusEvent{} public class ToLoginOriginEvent extends RxBus.BusEvent{} //--------------------------------焦点重定向---------------------------------------------- @Override protected void setupUI(View view, final Activity context) { //Set up touch listener for non-text box views to hide keyboard. if(!(view instanceof EditText)) { view.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { v.setFocusable(true); v.setFocusableInTouchMode(true); v.requestFocus(); InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(),0); return false; } }); } //If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView,context); } } } }
import java.util.BitSet; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.LongAccumulator; public class PrimeSieveJavaBitSetMT { // upper limit, highest prime we'll consider private static final int SIEVE_SIZE = 1000000; // for how long the sieve calculation will run private static final int TIME_IN_SECONDS = 5; // used to ensure that no waiting thread runs after the time limit is reached private static final AtomicBoolean SHOULD_RUN = new AtomicBoolean(true); // to store number of times the sieve calculation completed successfully private static final AtomicLong PASSES = new AtomicLong(0L); // accumulator to store count of primes from individual thread // if each run produced a correct value, it should match count // from dictionary when divided by the number of passes private static final LongAccumulator COUNT_OF_PRIMES_ACCUMULATOR = new LongAccumulator(Long::sum, 0L); // cached thread pool to spawn as many threads as possible // alternatively, Executors.newFixedThreadPool(n) can be used to spawn a fixed number of thread private static final ThreadPoolExecutor POOL = (ThreadPoolExecutor) Executors.newCachedThreadPool(); public static void main(final String[] args) { POOL.setCorePoolSize(Runtime.getRuntime().availableProcessors()); final var tStart = System.currentTimeMillis(); while (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - tStart) < TIME_IN_SECONDS) { POOL.execute(() -> runSieve(new PrimeSieve(SIEVE_SIZE))); } SHOULD_RUN.set(false); shutdownPool(); final var tEnd = System.currentTimeMillis(); printResults(SIEVE_SIZE, PASSES.get(), TimeUnit.MILLISECONDS.toSeconds(tEnd - tStart), COUNT_OF_PRIMES_ACCUMULATOR.longValue(), Runtime.getRuntime().availableProcessors()); } // Calculate the primes up to the specified limit public static void runSieve(final PrimeSieve sieve) { // make sure any waiting threads are skipped in time limit is reached if (!SHOULD_RUN.get()) return; final var sieveSize = sieve.getSieveSize(); final var bitSet = sieve.getBitArray(); var factor = 3; final var q = (int) Math.sqrt(sieveSize); while (factor <= q) { for (var num = factor; num <= sieveSize; num++) { if (getBit(bitSet, num)) { factor = num; break; } } // If marking factor 3, you wouldn't mark 6 (it's a mult of 2) so start with the 3rd // instance of this factor's multiple. We can then step by factor * 2 because every second // one is going to be even by definition for (var num = factor * factor; num <= sieveSize; num += factor * 2) clearBit(bitSet, num); factor += 2; // No need to check evens, so skip to next odd (factor = 3, 5, 7, 9...) } if (SHOULD_RUN.get()) validateAndStoreResults(sieveSize, countPrimes(bitSet)); } // Gets a bit from the array of bits, but automatically just filters out even numbers as // false, and then only uses half as many bits for actual storage private static boolean getBit(final BitSet bitSet, final int index) { if (index % 2 == 0) return false; return bitSet.get(index / 2); } // Reciprocal of GetBit, ignores even numbers and just stores the odds. Since the prime sieve // work should never waste time clearing even numbers, this code will assert if you try to private static void clearBit(final BitSet bitSet, final int index) { if (index % 2 == 0) { System.out.println("You are setting even bits, which is sub-optimal"); } bitSet.set(index / 2, false); } // Return the count of bits that are still set in the sieve. Assumes you've already called // runSieve, of course! public static int countPrimes(final BitSet bitArray) { return bitArray.cardinality(); } // Look up our count of primes in the historical data (if we have it) to see if it matches // If a match is found then store the sieve count and increment the number of passes private static void validateAndStoreResults(final int sieveSize, final int countOfPrimes) { if (MY_DICT.containsKey(sieveSize) && MY_DICT.get(sieveSize) == countOfPrimes) { COUNT_OF_PRIMES_ACCUMULATOR.accumulate(countOfPrimes); PASSES.incrementAndGet(); } } // Look up our count of primes in the historical data (if we have it) to see if it matches private static boolean validate(final int sieveSize, final long count) { if (MY_DICT.containsKey(sieveSize)) return MY_DICT.get(sieveSize) == count; return false; } private static void printResults(final int sieveSize, final long passes, final double durationInSeconds, final long accumulatedCount, final int maxThreadCount) { if (!validate(sieveSize, accumulatedCount / passes)) { System.out.printf("Passes: %d, Time: %f, Avg: %f, Limit: %d, Count: %d, Valid: %s%n", passes, durationInSeconds, durationInSeconds / passes, sieveSize, accumulatedCount / passes, validate(sieveSize, accumulatedCount / passes)); System.out.println(); } System.out.printf("PratimGhosh86-JavaBitSetMT;%d;%f;%d;algorithm=base,faithful=yes,bits=1\n", passes, durationInSeconds, maxThreadCount); } private static void shutdownPool() { try { // Disable new tasks from being submitted POOL.shutdown(); // Wait a while for existing tasks to terminate POOL.awaitTermination(1, TimeUnit.MILLISECONDS); } catch (final InterruptedException e) { // Preserve interrupt status Thread.currentThread().interrupt(); } finally { POOL.shutdownNow(); // Cancel currently executing tasks } } public static class PrimeSieve { private final int sieveSize; private final BitSet bitArray; public PrimeSieve(final int size) { // Upper limit, highest prime we'll consider this.sieveSize = size; // since we filter evens, just half as many bits final var bitArrayLength = (this.sieveSize + 1) / 2; this.bitArray = new BitSet(bitArrayLength); this.bitArray.set(0, bitArrayLength, true); } public int getSieveSize() { return sieveSize; } public BitSet getBitArray() { return bitArray; } } // Historical data for validating our results - the number of primes to be found under some // limit, such as 168 primes under 1000 private static final Map<Integer, Integer> MY_DICT = Map.of( // 10, 4, // 100, 25, // 1000, 168, // 10000, 1229, // 100000, 9592, // 1000000, 78498, // 10000000, 664579, // 100000000, 5761455 // ); }
/* * work_wx * wuhen 2020/2/4. * Copyright (c) 2020 jianfengwuhen@126.com All Rights Reserved. */ package com.work.wx.controller.modle.subChatItem; import com.work.wx.controller.modle.BaseModel; public class ChatModelAgree extends BaseModel { private String userid; // 同意/不同意协议者的userid,外部企业默认为external_userid。String类型 private Long agree_time; // 同意/不同意协议的时间,utc时间,ms单位。 public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public Long getAgree_time() { return agree_time; } public void setAgree_time(Long agree_time) { this.agree_time = agree_time; } }
package poo; public class Jefatura extends Empleado implements Jefes{ public Jefatura(String nom, double sue, int aņo, int mes, int dia){ super(nom, sue, aņo, mes, dia); } public void establece_incentivo(double b){ incentivo=b; } public double dimeSueldo(){ double sueldoJefe=super.dameSueldo(); return sueldoJefe + incentivo; } private double incentivo; public String tomar_decisiones(String decision){ return "Un miembro de la direccion ha tomado la decisoin de: " + decision; } public double establece_bono(double gratificacion){ double prima=2000; return Trabajadores.bono_base+ gratificacion+prima; } }
/*Crie um programa para receber dois números e verificar se eles são iguais ou se um é maior que o outro. Imprima uma mensagem indicando se os números são iguais ou, no caso deles serem diferentes, imprima o maior valor digitado. */ /* import java.util.Scanner; public class Aula4ativ3 { public static void main (String[] args) { Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); scan.close(); if (a == b) { System.out.println("Os números A:" + a + " B:" + b + " são iguais."); }else if (a > b) { System.out.println("O número A:" + a + " é maior que B:" + b); }else { System.out.println("O número B:" + b + " é maior que A:" + a); } } } */ /* Crie um programa para receber uma nota e imprimir uma mensagem de acordo com a seguinte tabela: De 0 até 3 – Você precisa melhorar muito! Maior que 3 e menor que 7 – Você está quase conseguindo! Maior ou igual a 7 e menor que 9 – Você conseguiu! Maior ou igual a 9 – Você conseguiu com distinção! */ /* import java.util.Scanner; public class Aula4ativ3 { public static void main(String[] args) { Scanner skn = new Scanner(System.in); float nota = skn.nextFloat(); skn.close(); if(nota >= 0 && nota <= 3) { System.out.println("Você precisa melhorar muito!"); }else if (nota <= 6) { System.out.println("Você está quase conseguindo!"); }else if (nota <= 8) { System.out.println("Você conseguiu!"); }else if (nota >= 9 && nota <= 10) { System.out.println("Você conseguiu com distinção!"); }else { System.out.println("Errouuuu!!!!"); } } } */
package app; public class Ventas { public String vendedor; public String fecha; public String descri; public double costo; public Ventas(String v, String f, double c, String d) { vendedor = v; fecha = f; costo = c; descri = d; } }
package bookStore; /** * Represents a Book. * @author Desislava Dontcheva * @version 1.0 */ import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class Book extends PrintEdition { public static final int DEFAULT_YEAR = 2000; public static final double RAISE_PRICE_HARD_COVERS = 5.0; public static final double RAISE_PRICE_SOFT_COVERS = 2.5; private String authorName; private int year; private boolean hasHardCovers; /** * Default constructor for class Book. */ public Book(){ super(DEFAULT_PRICE_PER_PAGE, MIN_PAGES, MIN_ISSUE, null); setAuthorName(null); setYear(DEFAULT_YEAR); setHasHardCovers(false); } /** * Constructor with parameters for class Book. * @param pricePerPage This is the price per page of the Book. * @param pages This is the amount of pages of the Book. * @param issueInThousands This is the issue count in thousands of the Book. * @param name This is the name of the Book. * @param authorName This is the author name of the Book. * @param year This is the release year of the Book. * @param hasHardCovers Shows if the Book has hard covers or not. */ public Book(double pricePerPage, int pages, int issueInThousands, String name, String authorName, int year, boolean hasHardCovers){ super(pricePerPage, pages, issueInThousands, name); setAuthorName(authorName); setYear(year); setHasHardCovers(hasHardCovers); } /** * Copy constructor for class Book. * @param book Object of class Book. */ public Book(Book book){ super(book.getPricePerPage(), book.getPages(), book.getIssueInThousands(), book.getName()); setAuthorName(book.authorName); setYear(book.year); setHasHardCovers(book.hasHardCovers); } /** * This method sets authorName of class Book. * @param authorName This is the author name of the Book. */ public void setAuthorName(String authorName) { this.authorName = authorName == null ? "DEFAULT AUTHOR" : authorName; } /** * This method sets year of class Book. * @param year This is the release year of the Book. */ public void setYear(int year) { if(year > 0 && year < Calendar.getInstance().get(Calendar.YEAR)) { this.year = year; }else { this.year = DEFAULT_YEAR; } } /** * This method sets hasHardCovers of class Book. * @param hasHardCovers Shows if the Book has hard covers or not. */ public void setHasHardCovers(boolean hasHardCovers) { this.hasHardCovers = hasHardCovers; } /** * This method gets authorName of class Book. * @return String This is the author name of the Book. */ public String getAuthorName() { return authorName; } /** * This method gets year of class Book. * @return int This is the release year of the Book. */ public int getYear() { return year; } /** * This method gets hasHardCovers of class Book. * @return boolean Shows if the Book has hard covers or not. */ public boolean getHasHardcovers() { return hasHardCovers; } /** * This method shows if release year is leap or not of the Book. * @return boolean Shows if the book year is leap or not. */ public boolean checkLeapYear(){ boolean leap = false; if(year % 4 == 0) { if(year % 100 == 0) { if (year % 400 == 0) { leap = true; } else { leap = false; } } else { leap = true; } } else { leap = false; } if(leap) { System.out.println(year + " is a leap year."); return true; } else{ System.out.println(year + " is not a leap year."); return false; } } /** * This method gets a Book list and an author name * and search for this author name in the list. * @param bookList This is a Book list. * @param authorName This is the author name of the Book. * @return boolean If the author name is equal to any name of the list, returns true. */ public static boolean checkAuthor(List<Book> bookList, String authorName){ for(Book book : bookList){ if(book.authorName.equals(authorName)) { return true; } } return false; } /** * This method searches for the Books with hard covers * and returns a new list full of Books only with hard covers. * @param bookList This is the input parameter Book list. * @return Book list This is the output hard covers Book list. */ public static List<Book> lookAllHardCovers(List<Book> bookList){ List<Book> result = new ArrayList<>(); for(Book book : bookList){ if(book.getHasHardcovers()) { result.add(book); } } return result; } /** * This is a private inner class that implements PricePerPrintEdition interface. */ private class BookPrice implements PricePerPrintEdition { /** * This method calculates the price per Book. * @return double This is the total price of the Book. */ @Override public double calculatePricePerEdition() { if(hasHardCovers) { return calculatePrintPrice() + RAISE_PRICE_HARD_COVERS; }else { return calculatePrintPrice() + RAISE_PRICE_SOFT_COVERS; } } } /** * This is a private inner class that implements PrintEditionInformation interface. */ private class BookInformation implements PrintEditionInformation { /** * This method prints formatted information of the Book. */ @Override public void printEditionInformation() { System.out.printf("Price per page: %.2f%nPages: %d%nIssue in thousands: %d%nName: %s%n", getPricePerPage(), getPages(), getIssueInThousands(), getName()); System.out.printf("Author name: %s%nRelease year: %d%nHard covers: %b%n", authorName, year, hasHardCovers); } } /** * This method gets an instance of the private inner class BookPrice. * @return PricePerPrintEdition new object of BookPrice class */ public PricePerPrintEdition getPrintEditionPrice(){ return new BookPrice(); } /** * This method gets an instance of the private inner class BookInformation. * @return PrintEditionInformation new object of BookInformation class */ public PrintEditionInformation getPrintInformation(){ return new BookInformation(); } }
package Topic22String; import javax.sound.midi.Soundbank; import java.util.Scanner; public class App { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Podaj ilść słów, ktore chcesz wpisać"); int numberOfWords = sc.nextInt(); sc.nextLine(); System.out.println("Będziesz teraz wprowadzał kolejne słowa"); String[] words = new String[numberOfWords]; int[] lengthWord = new int[numberOfWords]; StringBuilder builder = new StringBuilder(); for(int i = 0; i < numberOfWords; i++){ int nrWords = i + 1; System.out.println("Wprowadź: " + nrWords + " słowo"); words[i] = sc.nextLine(); lengthWord[i] = words[i].length(); builder.append(words[i].charAt(lengthWord[i]-1)); } System.out.println("powstałe nowe słowo to: " + builder); } }
package ch10; import java.text.ChoiceFormat; public class ChoiceFormatExam { public static void main(String[]args) { double[] limit= {0,60,70,80,90}; String[] grades= {"F","D","C","B","A"}; int[] scores= {100,96,88,77,66,33,80}; ChoiceFormat form=new ChoiceFormat(limit,grades);//자동으로 기준에 맞춰서 뽑아줌 for(int i:scores) { System.out.println(i+":"+form.format(i)); }System.out.println("========================================"); String pattern= "0<F|60#D|70#C|80<B|90#A"; form=new ChoiceFormat(pattern);// 패턴을 지정하여 뽑게 할수도 있음 for(int i:scores) { System.out.println(i+":"+form.format(i)); } } }
package test; @cz.ladicek.annotationProcessorsTalk.valueLike.ValueLike public interface Book { String name(); }
import java.util.Scanner; /** * Created by akash on 6/10/16. */ public class Review { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int i = 0; i < T; i++){ char[] str = in.next().toCharArray(); //print even chars for(int j = 0; j < str.length; j+=2){ System.out.print(str[j]); } System.out.print(" "); //print odd chars for(int j = 1; j < str.length; j+= 2){ System.out.print(str[j]); } System.out.println(); } in.close(); } }
/* * ParserIdempotenceTest.java - what goes in must come out * * Copyright (C) 2016 National Library of Australia * * 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.netpreserve.urlcanon; import com.google.gson.Gson; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class ParserIdempotenceTest { private static Gson gson = new Gson(); @Parameter public String test; @Parameters(name = "{index} {0}") public static List<String> loadData() throws IOException { try (InputStream stream = ParserIdempotenceTest.class.getResourceAsStream("/idempotence.json"); InputStreamReader reader = new InputStreamReader(stream, UTF_8)) { return Arrays.asList(gson.fromJson(reader, String[].class)); } } @Test public void test() { assertEquals(test, ParsedUrl.parseUrl(test).toString()); } }
// // Copyright (c) 2019 Rally Tactical Systems, Inc. // All rights reserved. // package com.rallytac.engageandroid; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; public class MapTrackerListAdapter extends ArrayAdapter<MapTracker> { private Context _ctx; private int _resId; public MapTrackerListAdapter(Context ctx, int resId, ArrayList<MapTracker> list) { super(ctx, resId, list); _ctx = ctx; _resId = resId; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater inflator = LayoutInflater.from(_ctx); convertView = inflator.inflate(_resId, parent, false); MapTracker item = getItem(position); ImageView iv = convertView.findViewById(R.id.ivType); iv.setImageDrawable(ContextCompat.getDrawable(_ctx, R.mipmap.ic_launcher)); String displayName = item._pd.displayName; if(Utils.isEmptyString(displayName)) { displayName = item._pd.userId; if(Utils.isEmptyString(displayName)) { displayName = item._pd.nodeId; } } ((TextView)convertView.findViewById(R.id.tvDisplayName)).setText(displayName); return convertView; } }
package com.mvc4.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * Created with IntelliJ IDEA. * User: uc203808 * Date: 6/17/16 * Time: 8:42 AM * To change this template use File | Settings | File Templates. */ @WebListener public class MyListener implements ServletContextListener { public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("servelt container init (listener)....."); } public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println("servelt container destroy (listener)....."); } }
/*MainActivity.java * *Contains the Java code for the *Primary Activity in this project * *Created by: Luke Street *Created on: 2/15/15 *Last Modified by: Luke Street *Last Modified on: 3/6/15 *Assignment/Project: Final Phase 3 *Part of: BudgetU, refers to fragment_settings.xml layout file **/ package edu.indiana.ldstreet.budgetu; import android.app.Activity; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class Settings extends Fragment { private static final String ARG_SECTION_NUMBER = "section_number"; ArrayAdapter<String> adapterCategories; ListView categoryList; Button mAdd; EditText mCategory; List<Category> categories; List<String> categoryItemsStrings; Map<Integer, Boolean> colorChanged = new HashMap<>(); public static Settings newInstance(int sectionNumber) { Settings fragment = new Settings(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public Settings() { } class CategoryComparator implements Comparator<Category> { @Override public int compare(Category c1, Category c2) { return c1.getCategory().compareTo(c2.getCategory()); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); View rootView = inflater.inflate(R.layout.fragment_settings, container, false); BudgetDBHandler dbHandler = new BudgetDBHandler(getActivity(), null, null, 1); //array list containing all categories categories = dbHandler.findAllCategories(); Collections.sort(categories, new CategoryComparator()); //array list containing all category strings categoryItemsStrings = new ArrayList<String>(); for (int x = 0; x < categories.size(); x++) { System.out.println(x); System.out.println(categories.get(x).getFavorite().toString()); if (categories.get(x).getFavorite().equals("True")) categoryItemsStrings.add(categories.get(x).getCategory().toString() + " (Favorite)"); else categoryItemsStrings.add(categories.get(x).getCategory().toString()); //System.out.println(categories.get(x).getCategory().toString()); } categoryList = (ListView) rootView.findViewById(R.id.categoryList); //array adapter containing all category strings adapterCategories = new ArrayAdapter<String>( getActivity(), android.R.layout.simple_list_item_1, categoryItemsStrings); categoryList.setAdapter(adapterCategories); //categoryList.getChildAt(categoryList.getFirstVisiblePosition()).setBackgroundColor(Color.BLUE); // for (int i = 0; i < categories.size(); i++) { // System.out.println("Ran " + i + " times..."); // if (categories.get(i).getFavorite().equals("True")) { // System.out.println("Favorite is true..."); // parent.getChildAt(i).setBackgroundColor(Color.WHITE); // } else { // System.out.println("Else statement..."); // parent.getChildAt(i).setBackgroundColor(Color.GREEN); // } // } //make arraylist clickable, pass an ID in order to populate next screen categoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //categoryClicked(position, categories.get(position).getID()); makeFavorite(parent,position); System.out.println(position); //initialSetFavorite(parent); } }); mCategory = (EditText) rootView.findViewById(R.id.newCategoryText); mAdd = (Button) rootView.findViewById(R.id.addCategoryButton); mAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { BudgetDBHandler dbHandler = new BudgetDBHandler(getActivity(), null, null, 1); String categoryString = mCategory.getText().toString(); Category myCategory = new Category(categoryString, "Incoming", "False"); dbHandler.addCategory(myCategory); updateAdapter(); mCategory.setText(""); } }); return rootView; } public void initialSetFavorite(AdapterView<?> parent) { BudgetDBHandler dbHandler = new BudgetDBHandler(getActivity(), null, null, 1); //array list containing all categories List<Category> categories = dbHandler.findAllCategories(); Collections.sort(categories, new CategoryComparator()); for (int i = 0; i < categories.size(); i++) { System.out.println("Ran " + i + " times..."); if (categories.get(i).getFavorite().equals("True")) { System.out.println("Favorite is true..."); parent.getChildAt(i).setBackgroundColor(Color.WHITE); } else { System.out.println("Else statement..."); parent.getChildAt(i).setBackgroundColor(Color.GREEN); } } } public void makeFavorite(AdapterView<?> parent, int position) { BudgetDBHandler dbHandler = new BudgetDBHandler(getActivity(), null, null, 1); //array list containing all categories List<Category> categories = dbHandler.findAllCategories(); Collections.sort(categories, new CategoryComparator()); if (categories.get(position).getFavorite().equals("True")) { System.out.println("Favorite is true..."); //parent.getChildAt(position).setBackgroundColor(Color.WHITE); categories.get(position).setFavorite("False"); dbHandler.deleteCategory(categories.get(position).getID()); dbHandler.addCategory(categories.get(position)); updateAdapter(); } else { System.out.println("Else statement..."); System.out.println(position); //parent.getChildAt(position).setBackgroundColor(Color.GREEN); //System.out.println("Color set..."); categories.get(position).setFavorite("True"); dbHandler.deleteCategory(categories.get(position).getID()); dbHandler.addCategory(categories.get(position)); updateAdapter(); } } public void updateAdapter () { BudgetDBHandler dbHandler = new BudgetDBHandler(getActivity(), null, null, 1); //array list containing all categories categories = dbHandler.findAllCategories(); Collections.sort(categories, new CategoryComparator()); //array list containing all category strings categoryItemsStrings = new ArrayList<String>(); for (int x = 0; x < categories.size(); x++) { //System.out.println(x); if (categories.get(x).getFavorite().equals("True")) categoryItemsStrings.add(categories.get(x).getCategory().toString() + " (Favorite)"); else categoryItemsStrings.add(categories.get(x).getCategory().toString()); //System.out.println(categories.get(x).getCategory().toString()); } adapterCategories = new ArrayAdapter<String>( getActivity(), android.R.layout.simple_list_item_1, categoryItemsStrings); categoryList.setAdapter(adapterCategories); //categoryList.getChildAt(0).setBackgroundColor(Color.BLUE); } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainActivity) activity).onSectionAttached(getArguments().getInt( ARG_SECTION_NUMBER)); } public void categoryClicked(int position,int id) { Toast.makeText(getActivity(), "myPos" + position, Toast.LENGTH_LONG).show(); //FragmentManager fragmentManager = getFragmentManager(); //fragmentManager.beginTransaction() // .replace(R.id.container, entryItemDetails.newInstance(position, id)) // .commit(); //adapterCategories.notifyDataSetChanged(); } }
package com.ljnewmap.modules.assess.service.impl; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.ljnewmap.modules.assess.dao.HrmDepartmentDao; import com.ljnewmap.modules.assess.entity.HrmDepartmentEntity; import com.ljnewmap.modules.assess.service.HrmDepartmentService; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service("hrmDepartmentService") public class HrmDepartmentServiceImpl extends ServiceImpl<HrmDepartmentDao, HrmDepartmentEntity> implements HrmDepartmentService { @Override public List<HrmDepartmentEntity> getTableData() { return baseMapper.getTableData(); } @Override public HrmDepartmentEntity getDepById(int depId) { return baseMapper.getDepById(depId); } @Override public HrmDepartmentEntity getDepByName(String depName) { return baseMapper.getDepByName(depName); } }
package be.presis; import org.dom4j.Element; import be.openclinic.system.SH; public class Id { private String nameSpace; private String type; private String value; public String toXml() { return "<id namespace='"+getNameSpace()+"' type='"+getType()+"'>"+getValue()+"</id>"; } public static Id fromXml(Element e) { if(e==null) { return new Id(); } return new Id(SH.c(e.attributeValue("namespace")),SH.c(e.attributeValue("type")),SH.c(e.getText())); } public void toXml(Element e) { Element eId=e.addElement("id"); eId.addAttribute("namespace", SH.c(getNameSpace())); eId.addAttribute("type", SH.c(getType())); eId.setText(SH.c(getValue())); } public String getNameSpace() { return nameSpace; } public void setNameSpace(String nameSpace) { this.nameSpace = nameSpace; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getFullId() { return nameSpace+"."+type+"."+value; } public Id(String nameSpace, String type, String value) { super(); this.nameSpace = nameSpace; this.type = type; this.value = value; } public Id() { super(); } public boolean equals(Id id) { return this.nameSpace.equalsIgnoreCase(id.getNameSpace()) && this.type.equalsIgnoreCase(id.type) && this.value.equalsIgnoreCase(id.value); } public boolean equivalent(Id id) { return this.nameSpace.equalsIgnoreCase(id.getNameSpace()) && this.type.equalsIgnoreCase(id.type); } }
/*********************************************************** * @Description : * @author : 梁山广(Laing Shan Guang) * @date : 2019/4/17 08:07 * @email : liangshanguang2@gmail.com ***********************************************************/ package 第3章_软件设计七大原则.S02_依赖导致DependencyInversion; public class PythonCourse implements ICourse { @Override public void studyCourse() { System.out.println("Geely正在学习Python课程"); } }
package org.crazyit.ui; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button simple = (Button) findViewById(R.id.simple); // 为按钮的单击事件绑定事件监听器 simple.setOnClickListener(new OnClickListener() { @Override public void onClick(View source) { // 创建一个Toast提示信息 Toast toast = Toast.makeText(MainActivity.this , "简单的提示信息" // 设置该Toast提示信息的持续时间 , Toast.LENGTH_SHORT); toast.show(); } }); Button bn = (Button) findViewById(R.id.bn); // 为按钮的单击事件绑定事件监听器 bn.setOnClickListener(new OnClickListener() { @Override public void onClick(View source) { // 创建一个Toast提示信息 Toast toast = new Toast(MainActivity.this); // 设置Toast的显示位置 toast.setGravity(Gravity.CENTER, 0, 0); // 创建一个ImageView ImageView image = new ImageView(MainActivity.this); image.setImageResource(R.drawable.tools); // 创建一个LinearLayout容器 LinearLayout ll = new LinearLayout(MainActivity.this); // 向LinearLayout中添加图片、原有的View ll.addView(image); // 创建一个TextView TextView textView = new TextView(MainActivity.this); textView.setText("带图片的提示信息"); // 设置文本框内字号的大小和字体颜色 textView.setTextSize(24); textView.setTextColor(Color.MAGENTA); ll.addView(textView); // 设置Toast显示自定义View toast.setView(ll); // 设置Toast的显示时间 toast.setDuration(Toast.LENGTH_LONG); toast.show(); } }); } }
package com.lesports.albatross.utils.request; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import com.lesports.albatross.R; /** * Created by zhouchenbin on 16/6/16. */ public class LeProgressDialog extends ProgressDialog { /** * @param context * @param theme */ public LeProgressDialog(Context context, int theme) { super(context, R.style.RssDialog); } /** * @param context */ public LeProgressDialog(Context context) { super(context, R.style.RssDialog); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.base_progress_dialog); setCanceledOnTouchOutside(false); setCancelable(true); } }
package bankassignment; public class BankAssignment { public static void main(String[] args) { new BankingSimFrame() { { setVisible(true); } }; } }
/* * 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 dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import model.Assignment; import model.Course; import model.IndividualAssignment; import model.Student; import model.StudentInCourse; import utils.DBUtils; /** * * @author Los_e */ public class IndividualAssignmentDAO { public static ArrayList<IndividualAssignment> getAllIndividualAssignments() { ArrayList<IndividualAssignment> list = new ArrayList<IndividualAssignment>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "SELECT * FROM individualassignments ia " + "inner join assignments a on a.assignmentid = ia.assignmentid " + "inner join students s on s.studentid = ia.studentid " + "inner join studentsincourses sc on sc.studentid = ia.studentid " + "inner join assignmentsincourses ac on ia.assignmentid = ac.assignmentid and sc.courseid = ac.courseid " + "inner join courses c on ac.courseid = c.courseid " + "where ac.courseid = ia.courseid " + "order by c.courseid, s.studentid;"; try { pst = con.prepareStatement(sql); ResultSet rs = pst.executeQuery(sql); while (rs.next()) { Assignment assignment = new Assignment(); assignment.setAssignmentid(rs.getInt(7)); assignment.setTitle(rs.getString(8)); assignment.setDescription(rs.getString(9)); assignment.setCourseid(rs.getInt(18)); assignment.setSubmissiondatetime(rs.getString(22)); Student student = new Student(); student.setStudentid(rs.getInt(10)); student.setFirstname(rs.getString(11)); student.setLastname(rs.getString(12)); student.setDateofbirth(rs.getString(13)); student.setTuitionfees(rs.getFloat(14)); student.setStream(rs.getString(15)); student.setType(rs.getString(16)); IndividualAssignment individualassignment = new IndividualAssignment(assignment); individualassignment.setAssignment(assignment); individualassignment.setStudent(student); if (rs.getInt(4) == 0) { individualassignment.setSubmitted(false); } else if (rs.getInt(4) == 1) { individualassignment.setSubmitted(true); } individualassignment.setOralmark(rs.getInt(5)); individualassignment.setTotalmark(rs.getInt(6)); list.add(individualassignment); } } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static ArrayList<IndividualAssignment> getAllIndividualAssignmentsByTrainer(int trainerid) { ArrayList<IndividualAssignment> list = new ArrayList<IndividualAssignment>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "SELECT * FROM individualassignments ia " + "inner join assignments a on a.assignmentid = ia.assignmentid " + "inner join students s on s.studentid = ia.studentid " + "inner join studentsincourses sc on sc.studentid = ia.studentid " + "inner join assignmentsincourses ac on ia.assignmentid = ac.assignmentid and sc.courseid = ac.courseid " + "inner join courses c on ac.courseid = c.courseid " + "inner join trainersincourses tc on tc.courseid = c.courseid " + "where ac.courseid = ia.courseid and tc.trainerid = ? " + "order by c.courseid, s.studentid;"; try { pst = con.prepareStatement(sql); pst.setInt(1, trainerid); ResultSet rs = pst.executeQuery(); while (rs.next()) { Assignment assignment = new Assignment(); assignment.setAssignmentid(rs.getInt(7)); assignment.setTitle(rs.getString(8)); assignment.setDescription(rs.getString(9)); assignment.setCourseid(rs.getInt(18)); assignment.setSubmissiondatetime(rs.getString(22)); Student student = new Student(); student.setStudentid(rs.getInt(10)); student.setFirstname(rs.getString(11)); student.setLastname(rs.getString(12)); student.setDateofbirth(rs.getString(13)); student.setTuitionfees(rs.getFloat(14)); student.setStream(rs.getString(15)); student.setType(rs.getString(16)); IndividualAssignment individualassignment = new IndividualAssignment(assignment); individualassignment.setAssignment(assignment); individualassignment.setStudent(student); if (rs.getInt(4) == 0) { individualassignment.setSubmitted(false); } else if (rs.getInt(4) == 1) { individualassignment.setSubmitted(true); } individualassignment.setOralmark(rs.getInt(5)); individualassignment.setTotalmark(rs.getInt(6)); list.add(individualassignment); } } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static ArrayList<IndividualAssignment> getAllSubmittedIndividualAssignments() { ArrayList<IndividualAssignment> list = new ArrayList<IndividualAssignment>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "SELECT * FROM individualassignments ia " + "inner join assignments a on a.assignmentid = ia.assignmentid " + "inner join students s on s.studentid = ia.studentid " + "inner join studentsincourses sc on sc.studentid = ia.studentid " + "inner join assignmentsincourses ac on ia.assignmentid = ac.assignmentid and sc.courseid = ac.courseid " + "inner join courses c on ac.courseid = c.courseid " + "where ac.courseid = ia.courseid and ia.submitted = 1 " + "order by c.courseid, s.studentid;"; try { pst = con.prepareStatement(sql); ResultSet rs = pst.executeQuery(); while (rs.next()) { Assignment assignment = new Assignment(); assignment.setAssignmentid(rs.getInt(7)); assignment.setTitle(rs.getString(8)); assignment.setDescription(rs.getString(9)); assignment.setCourseid(rs.getInt(18)); assignment.setSubmissiondatetime(rs.getString(22)); Student student = new Student(); student.setStudentid(rs.getInt(10)); student.setFirstname(rs.getString(11)); student.setLastname(rs.getString(12)); student.setDateofbirth(rs.getString(13)); student.setTuitionfees(rs.getFloat(14)); student.setStream(rs.getString(15)); student.setType(rs.getString(16)); IndividualAssignment individualassignment = new IndividualAssignment(assignment); individualassignment.setAssignment(assignment); individualassignment.setStudent(student); if (rs.getInt(4) == 0) { individualassignment.setSubmitted(false); } else if (rs.getInt(4) == 1) { individualassignment.setSubmitted(true); } individualassignment.setOralmark(rs.getInt(5)); individualassignment.setTotalmark(rs.getInt(6)); list.add(individualassignment); } } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static ArrayList<IndividualAssignment> getAllSubmittedIndividualAssignmentsByTrainer(int trainerid) { ArrayList<IndividualAssignment> list = new ArrayList<IndividualAssignment>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "SELECT * FROM individualassignments ia " + "inner join assignments a on a.assignmentid = ia.assignmentid " + "inner join students s on s.studentid = ia.studentid " + "inner join studentsincourses sc on sc.studentid = ia.studentid " + "inner join assignmentsincourses ac on ia.assignmentid = ac.assignmentid and sc.courseid = ac.courseid " + "inner join courses c on ac.courseid = c.courseid " + "inner join trainersincourses tc on tc.courseid = c.courseid " + "where ac.courseid = ia.courseid and ia.submitted = 1 and tc.trainerid =? " + "order by c.courseid, s.studentid;"; try { pst = con.prepareStatement(sql); pst.setInt(1, trainerid); ResultSet rs = pst.executeQuery(); while (rs.next()) { Assignment assignment = new Assignment(); assignment.setAssignmentid(rs.getInt(7)); assignment.setTitle(rs.getString(8)); assignment.setDescription(rs.getString(9)); assignment.setCourseid(rs.getInt(18)); assignment.setSubmissiondatetime(rs.getString(22)); Student student = new Student(); student.setStudentid(rs.getInt(10)); student.setFirstname(rs.getString(11)); student.setLastname(rs.getString(12)); student.setDateofbirth(rs.getString(13)); student.setTuitionfees(rs.getFloat(14)); student.setStream(rs.getString(15)); student.setType(rs.getString(16)); IndividualAssignment individualassignment = new IndividualAssignment(assignment); individualassignment.setAssignment(assignment); individualassignment.setStudent(student); if (rs.getInt(4) == 0) { individualassignment.setSubmitted(false); } else if (rs.getInt(4) == 1) { individualassignment.setSubmitted(true); } individualassignment.setOralmark(rs.getInt(5)); individualassignment.setTotalmark(rs.getInt(6)); list.add(individualassignment); } } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static ArrayList<IndividualAssignment> getAllIndividualAssignmentsByStudentId(int studentid) { ArrayList<IndividualAssignment> list = new ArrayList<IndividualAssignment>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "SELECT * FROM individualassignments ia " + "inner join assignments a on a.assignmentid = ia.assignmentid " + "inner join students s on s.studentid = ia.studentid " + "inner join studentsincourses sc on sc.studentid = ia.studentid " + "inner join assignmentsincourses ac on ia.assignmentid = ac.assignmentid and sc.courseid = ac.courseid " + "inner join courses c on ac.courseid = c.courseid " + "where ia.studentid = ? and ac.courseid = ia.courseid " + "order by c.courseid, s.studentid;"; try { pst = con.prepareStatement(sql); pst.setInt(1, studentid); ResultSet rs = pst.executeQuery(); while (rs.next()) { Assignment assignment = new Assignment(); assignment.setAssignmentid(rs.getInt(7)); assignment.setTitle(rs.getString(8)); assignment.setDescription(rs.getString(9)); assignment.setCourseid(rs.getInt(18)); assignment.setSubmissiondatetime(rs.getString(22)); Student student = new Student(); student.setStudentid(rs.getInt(10)); student.setFirstname(rs.getString(11)); student.setLastname(rs.getString(12)); student.setDateofbirth(rs.getString(13)); student.setTuitionfees(rs.getFloat(14)); student.setStream(rs.getString(15)); student.setType(rs.getString(16)); IndividualAssignment individualassignment = new IndividualAssignment(assignment); individualassignment.setAssignment(assignment); individualassignment.setStudent(student); if (rs.getInt(4) == 0) { individualassignment.setSubmitted(false); } else if (rs.getInt(4) == 1) { individualassignment.setSubmitted(true); } individualassignment.setOralmark(rs.getInt(5)); individualassignment.setTotalmark(rs.getInt(6)); list.add(individualassignment); } } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static ArrayList<IndividualAssignment> getNotSubmittedIndividualAssignmentsByStudentId(int studentid) { ArrayList<IndividualAssignment> list = new ArrayList<IndividualAssignment>(); Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "SELECT * FROM individualassignments ia " + "inner join assignments a on a.assignmentid = ia.assignmentid " + "inner join students s on s.studentid = ia.studentid " + "inner join studentsincourses sc on sc.studentid = ia.studentid " + "inner join assignmentsincourses ac on ia.assignmentid = ac.assignmentid and sc.courseid = ac.courseid " + "inner join courses c on ac.courseid = c.courseid " + "where ia.studentid = ? and ac.courseid = ia.courseid and ia.submitted = 0 " + "order by c.courseid, s.studentid;"; try { pst = con.prepareStatement(sql); pst.setInt(1, studentid); ResultSet rs = pst.executeQuery(); while (rs.next()) { Assignment assignment = new Assignment(); assignment.setAssignmentid(rs.getInt(7)); assignment.setTitle(rs.getString(8)); assignment.setDescription(rs.getString(9)); assignment.setCourseid(rs.getInt(18)); assignment.setSubmissiondatetime(rs.getString(22)); Student student = new Student(); student.setStudentid(rs.getInt(10)); student.setFirstname(rs.getString(11)); student.setLastname(rs.getString(12)); student.setDateofbirth(rs.getString(13)); student.setTuitionfees(rs.getFloat(14)); student.setStream(rs.getString(15)); student.setType(rs.getString(16)); IndividualAssignment individualassignment = new IndividualAssignment(assignment); individualassignment.setAssignment(assignment); individualassignment.setStudent(student); if (rs.getInt(4) == 0) { individualassignment.setSubmitted(false); } else if (rs.getInt(4) == 1) { individualassignment.setSubmitted(true); } individualassignment.setOralmark(rs.getInt(5)); individualassignment.setTotalmark(rs.getInt(6)); list.add(individualassignment); } } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignment.class.getName()).log(Level.SEVERE, null, ex); } } return list; } public static void insertIndividualAssignment(IndividualAssignment individualassignment) { Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "insert into individualassignments(studentid, assignmentid, courseid, submitted, oralmark, totalmark) select ?, ?, ?, ?, ?, ?" + " WHERE NOT EXISTS " + " (select * from individualassignments WHERE studentid = ? /*6*/ and assignmentid = ? /*7*/ and courseid = ?)"; boolean result = false; try { pst = con.prepareStatement(sql); pst.setInt(1, individualassignment.getStudent().getStudentid()); pst.setInt(2, individualassignment.getAssignment().getAssignmentid()); pst.setInt(3, individualassignment.getCourseid()); pst.setInt(4, 0); pst.setInt(5, 0); pst.setInt(6, 0); pst.setInt(7, individualassignment.getStudent().getStudentid()); pst.setInt(8, individualassignment.getAssignment().getAssignmentid()); pst.setInt(9, individualassignment.getCourseid()); pst.executeUpdate(); result = true; } catch (SQLException ex) { Logger.getLogger(IndividualAssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); result = false; } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } } if (result) { System.out.println("Assignments of the course were appointed to Student"); } // return result; } public static void updateIndividualAssignment(IndividualAssignment individualassignment) { Connection con = DBUtils.getConnection(); PreparedStatement pst = null; String sql = "UPDATE individualassignments SET submitted = ? /*1*/, oralmark = ? /*2*/, totalmark = ? /*3*/ WHERE studentid = ? /*4*/ and assignmentid = ? /*5*/ and courseid = ? /*6*/"; boolean result = false; try { pst = con.prepareStatement(sql); if (individualassignment.isSubmitted()) { pst.setInt(1, 1); } else { pst.setInt(1, 0); } pst.setInt(2, individualassignment.getOralmark()); pst.setInt(3, individualassignment.getTotalmark()); pst.setInt(4, individualassignment.getStudent().getStudentid()); pst.setInt(5, individualassignment.getAssignmentid()); pst.setInt(6, individualassignment.getCourseid()); pst.executeUpdate(); result = true; } catch (SQLException ex) { Logger.getLogger(IndividualAssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); result = false; } finally { try { pst.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } try { con.close(); } catch (SQLException ex) { Logger.getLogger(IndividualAssignmentDAO.class.getName()).log(Level.SEVERE, null, ex); } } if (result) { System.out.println("Updated Assignment"); } // return result; } }
package com.isg.ifrend.core.model.mli.application; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * * Bean class for add-on supplementary. * */ public class AddOnSupplementary implements Serializable { private static final long serialVersionUID = -7331758641022486884L; private String prefix; private String lastname; private String firtsname; private String middlename; private Date dateOfBirth; private String gender; private String civilStatus; private String relationToPrimary; private String addressLine1; private String addressLine2; private String addressLine3; private String cityState; private String country; private String zipCode; private String homePhone; private String mobileNumber; private String officePhone; private String idTypeNbr; private BigDecimal income; private String emmboserName; private BigDecimal creditLimit; private BigDecimal cashCreditLimit; public AddOnSupplementary(){ } public AddOnSupplementary(String prefix, String lastname, String firtsname, String middlename, Date dateOfBirth, String gender, String civilStatus, String relationToPrimary, String addressLine1, String addressLine2, String addressLine3, String cityState, String country, String zipCode, String homePhone, String mobileNumber, String officePhone, String idTypeNbr, BigDecimal income, String emmboserName, BigDecimal creditLimit, BigDecimal cashCreditLimit) { super(); this.prefix = prefix; this.lastname = lastname; this.firtsname = firtsname; this.middlename = middlename; this.dateOfBirth = dateOfBirth; this.gender = gender; this.civilStatus = civilStatus; this.relationToPrimary = relationToPrimary; this.addressLine1 = addressLine1; this.addressLine2 = addressLine2; this.addressLine3 = addressLine3; this.cityState = cityState; this.country = country; this.zipCode = zipCode; this.homePhone = homePhone; this.mobileNumber = mobileNumber; this.officePhone = officePhone; this.idTypeNbr = idTypeNbr; this.income = income; this.emmboserName = emmboserName; this.creditLimit = creditLimit; this.cashCreditLimit = cashCreditLimit; } /** getter and setter **/ public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getFirtsname() { return firtsname; } public void setFirtsname(String firtsname) { this.firtsname = firtsname; } public String getMiddlename() { return middlename; } public void setMiddlename(String middlename) { this.middlename = middlename; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getCivilStatus() { return civilStatus; } public void setCivilStatus(String civilStatus) { this.civilStatus = civilStatus; } public String getRelationToPrimary() { return relationToPrimary; } public void setRelationToPrimary(String relationToPrimary) { this.relationToPrimary = relationToPrimary; } public String getAddressLine1() { return addressLine1; } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public String getAddressLine2() { return addressLine2; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public String getAddressLine3() { return addressLine3; } public void setAddressLine3(String addressLine3) { this.addressLine3 = addressLine3; } public String getCityState() { return cityState; } public void setCityState(String cityState) { this.cityState = cityState; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getHomePhone() { return homePhone; } public void setHomePhone(String homePhone) { this.homePhone = homePhone; } public String getMobileNumber() { return mobileNumber; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } public String getOfficePhone() { return officePhone; } public void setOfficePhone(String officePhone) { this.officePhone = officePhone; } public String getIdTypeNbr() { return idTypeNbr; } public void setIdTypeNbr(String idTypeNbr) { this.idTypeNbr = idTypeNbr; } public BigDecimal getIncome() { return income; } public void setIncome(BigDecimal income) { this.income = income; } public String getEmmboserName() { return emmboserName; } public void setEmmboserName(String emmboserName) { this.emmboserName = emmboserName; } public BigDecimal getCreditLimit() { return creditLimit; } public void setCreditLimit(BigDecimal creditLimit) { this.creditLimit = creditLimit; } public BigDecimal getCashCreditLimit() { return cashCreditLimit; } public void setCashCreditLimit(BigDecimal cashCreditLimit) { this.cashCreditLimit = cashCreditLimit; } }
package com.rednovo.ace.entity; /** * 推送信息 * @author lxg * */ public class UserPushMapping { private String userId; private String tokenId; private String pushType; private String deviceType; private String schemaId; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getTokenId() { return tokenId; } public void setTokenId(String tokenId) { this.tokenId = tokenId; } public String getPushType() { return pushType; } public void setPushType(String pushType) { this.pushType = pushType; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public String getSchemaId() { return schemaId; } public void setSchemaId(String schemaId) { this.schemaId = schemaId; } }
public class Weapon extends Item { private int _damage; public Weapon(String name, int goldValue, int weight, int damage) { this._name = name; this._goldValue = goldValue; this._weight = weight; this._damage = damage; } public int getDamage() { return _damage; } public void setDamage(int damage) { this._damage = damage; } }
package com.example.BankOperation.bootstrap; import com.example.BankOperation.model.Bank; import com.example.BankOperation.model.Client; import com.example.BankOperation.model.Credit; import com.example.BankOperation.model.Payment; import com.example.BankOperation.service.BankService; import com.example.BankOperation.service.ClientService; import com.example.BankOperation.service.CreditService; import com.example.BankOperation.service.PaymentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.math.BigDecimal; @Component public class Bootstrap implements CommandLineRunner { @Autowired private ClientService clientService; @Autowired private CreditService creditService; @Autowired private BankService bankService; @Autowired private PaymentService paymentService; @Override public void run(String... args) throws Exception { Client cl1 = new Client(); cl1.setName("Master"); cl1.setActive(false); cl1.setPhoneNumber("72342"); clientService.addClient(cl1); Credit cr = new Credit(); cr.setCreditName("consumer loan"); cr.setAmount(BigDecimal.TEN); cr.setClient(cl1); creditService.addCredit(cr); // Bank b = new Bank(); // b.setBankName("CAB"); // b.setClient(cl1); // b.setCredit(cr); // bankService.addBank(b); Payment p = new Payment(); p.setCredit(cr); p.setTarget("For Study"); p.setAmount(BigDecimal.valueOf(200)); } }
package com.phoenix.streamdemo; import java.awt.geom.Point2D; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * stream demo */ public class Test { //流对象的创建 public static<T> void empty() { //创建空的流对象 StreamSupport.stream(Spliterators.<T>emptySpliterator(), false); } public void example1() { List<Integer> ints = Arrays.asList(1,2,4,5,6,7,8,9); ints.stream().map(i -> new Point2D.Double((double)i%3, (double)i/3)) .filter(point -> point.getY() > 1) .mapToDouble(point -> point.distance(0, 0)) .average() .orElse(0); } public static void main(String[] args) { int a = 10; System.out.println(Optional.of(a).isPresent()); System.out.println(Optional.of(a).orElse(0)); } public void filesExample() throws IOException { try (Stream<Path> pathStream = Files.walk(Paths.get("."))) { pathStream.filter(Files::isRegularFile) .filter(FileSystems.getDefault().getPathMatcher("glob:**/I.java")::matches) .flatMap(ThrowingFunction.unchecked((Path path)-> Files.readAllLines(path).stream() .filter(line-> Pattern.compile("public class").matcher(line).find()) .map(line->path.getFileName()+">>"+line) )) .forEach(System.out::println); //打印所有行 } } /** * * @return */ public static Object computeIfAbsent() { Long id = 0l; ConcurrentHashMap<Long, Object> cache = new ConcurrentHashMap<>(); List<Product> data = new ArrayList<>(); Object o = cache.computeIfAbsent(id, i->data.stream().filter(product -> product.getId().equals(i)).findFirst().orElse(null)); return o; } }
package com.hcg.web.Vo; import com.hcg.commondal.model.UserInfo; import org.springframework.beans.factory.annotation.Autowired; public class PageReq { @Autowired UserInfo userInfo; public Integer pageNum; public Integer pageSize=20; public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } }
package com.sjzy.data.monitor.pojo; import java.util.Objects; public class JobInfoDemo { String pid; String name; public JobInfoDemo(String pid, String name) { this.pid = pid; this.name = name; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; JobInfoDemo that = (JobInfoDemo) o; return Objects.equals(pid, that.pid) && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(pid, name); } @Override public String toString() { return "JobInfoDemo{" + "pid='" + pid + '\'' + ", name='" + name + '\'' + '}'; } }
package com.example.sohil.filesharing; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.Activity; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.graphics.drawable.ScaleDrawable; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; /** * Created by sohil on 4/8/2015. */ public class ChooseActivity extends Activity { //variables private Upload upload = null; private Button mUploadBtn; //button private Button mDownloadBtn; //button private View mChoose; //layout private Context context; private View dialog = null; private int serverResponseCode = 0; private String upLoadServerUri = null; private static final int PICKFILE_RESULT_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chooseuploaddownload); mUploadBtn = (Button) findViewById(R.id.Upload); mDownloadBtn = (Button) findViewById(R.id.Download); mChoose = findViewById(R.id.choose); dialog = findViewById(R.id.progress); context = getApplicationContext(); //Scale image size for button Drawable upldrawable = getResources().getDrawable(R.drawable.upload); upldrawable.setBounds(0, 0, (int)(upldrawable.getIntrinsicWidth()*0.5), (int)(upldrawable.getIntrinsicHeight()*0.5)); ScaleDrawable sdupl = new ScaleDrawable(upldrawable, 0, 10, 10); mUploadBtn.setCompoundDrawables(sdupl.getDrawable(), null, null, null); Drawable dwndrawable = getResources().getDrawable(R.drawable.download); dwndrawable.setBounds(0, 0, (int)(dwndrawable.getIntrinsicWidth()*0.5), (int)(dwndrawable.getIntrinsicHeight()*0.5)); ScaleDrawable sddwn = new ScaleDrawable(dwndrawable, 0, 10, 10); mDownloadBtn.setCompoundDrawables(sddwn.getDrawable(), null, null, null); //On upload button mUploadBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showProgress(true); Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT); fileintent.setType("file/*"); try { //open file explorer and select file. startActivityForResult(fileintent, PICKFILE_RESULT_CODE); } catch (ActivityNotFoundException e) { Log.e("tag", "No activity can handle picking a file. Showing alternatives."); } } }); mChoose = findViewById(R.id.choose); //open download activity mDownloadBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), DownloadActivity.class); startActivity(intent); } }); } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void showProgress(final boolean show) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mChoose.setVisibility(show ? View.GONE : View.VISIBLE); dialog.setVisibility(show ? View.VISIBLE : View.GONE); } else { dialog.setVisibility(show ? View.VISIBLE : View.GONE); mChoose.setVisibility(show ? View.GONE : View.VISIBLE); } } //called when the user has selected file in file explorer view. protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (data == null) { showProgress(false); return; } showProgress(true); switch (requestCode) { case PICKFILE_RESULT_CODE: if (resultCode == RESULT_OK) { Log.e("Data :::: ",data.getData().toString()); String filePath = data.getData().getPath(); int pos = 0; for(int i=0;i<filePath.length();i++) { Character tmp_filePath = filePath.charAt(i); if(tmp_filePath.equals('/')){ pos = i; } } String tmp_filepath = filePath.substring(pos+1); //store the name of the file to use in other activity. SharedPreferences loginDetails = getSharedPreferences("Upload_filename", Context.MODE_PRIVATE); SharedPreferences.Editor editor = loginDetails.edit(); editor.putString("filename",tmp_filepath); editor.apply(); upload = new Upload(filePath,context); upload.execute((Void) null); } } showProgress(false); } protected class Upload extends AsyncTask<Void, Void, Integer> { private String filePath; private String upLoadServerUri = IpAddress.ipAddress+"upload.php"; //url for the php file private Context mcontext; Upload(String filePath, Context context){ this.filePath = filePath; mcontext = context; } @Override protected Integer doInBackground(Void... params) { new Thread(new Runnable() { public void run() { runOnUiThread(new Runnable() { public void run() { showProgress(true); } }); } }).start(); return uploadFile(filePath); } public int uploadFile(String sourceFileUri) { String fileName = sourceFileUri; HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; Log.e("uploadFile", "Source File :"+sourceFileUri); int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File not exist :"); return 2; } else { String data = ""; try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); SharedPreferences settings = getSharedPreferences("login_details", Context.MODE_PRIVATE); String username = settings.getString("username", ""); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); conn.setRequestProperty("owner",username); conn.setConnectTimeout(5000); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); InputStream is = conn.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); Log.i("uploadFile", "HTTP Response is : " + response + ": " + serverResponseCode); JSONObject serverMsgObj = new JSONObject(String.valueOf(response)); final String serverMsg = serverMsgObj.get("serverReply").toString(); fileInputStream.close(); dos.flush(); dos.close(); // Log.e("Over here","I am here"); if(serverMsg.equals("success")){ Log.e("inside","I got in"); runOnUiThread(new Runnable() { public void run() { Toast.makeText(mcontext, "Successfully uploaded", Toast.LENGTH_SHORT).show(); } }); return 1; } else{ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(mcontext,"Error : "+serverMsg,Toast.LENGTH_LONG).show(); } }); return 10; } } catch (MalformedURLException ex) { showProgress(false); ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); return 3; } catch (FileNotFoundException e) { e.printStackTrace(); return 4; } catch(SocketTimeoutException e){ e.printStackTrace(); return 5; } catch (ProtocolException e) { e.printStackTrace(); return 6; } catch (IOException e) { e.printStackTrace(); return 7; } catch (JSONException e) { e.printStackTrace(); return 8; } } // End else block } @Override protected void onPostExecute(final Integer success) { showProgress(false); if(success == 1) { Log.e("UserAccess","Here i can reach"); Intent intent = new Intent(mcontext, UserAccessActivity.class); startActivity(intent); } else if(success == 2){ Toast.makeText(mcontext,"file does not exist",Toast.LENGTH_LONG).show(); // mChoose.invalidate(); } else if(success == 3){ Toast.makeText(mcontext,"Malformed URL",Toast.LENGTH_LONG).show(); } else if(success == 4){ Toast.makeText(mcontext,"File not found exception",Toast.LENGTH_LONG).show(); } else if(success == 5){ Toast.makeText(mcontext,"Server Timeout",Toast.LENGTH_LONG).show(); } else if(success == 6){ Toast.makeText(mcontext,"Protocol exception",Toast.LENGTH_LONG).show(); } else if(success == 7){ Toast.makeText(mcontext,"IOException",Toast.LENGTH_LONG).show(); } else if(success == 8){ Toast.makeText(mcontext,"JSON Error",Toast.LENGTH_LONG).show(); } } protected void onCancelled(){ upload = null; showProgress(false); } } }
package com.v2social.socialdownloader; import android.Manifest; import android.app.ActivityManager; import android.app.Dialog; import android.app.DownloadManager; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Resources; import android.database.MatrixCursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.BaseColumns; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.os.ConfigurationCompat; import android.support.v4.widget.CursorAdapter; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.util.Log; import android.util.Patterns; import android.util.SparseArray; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.webkit.URLUtil; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Toast; import com.facebook.ads.Ad; import com.facebook.ads.AdError; import com.facebook.ads.InterstitialAdListener; import com.facebook.appevents.AppEventsLogger; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.kobakei.ratethisapp.RateThisApp; import com.twitter.sdk.android.core.Result; import com.twitter.sdk.android.core.Twitter; import com.twitter.sdk.android.core.TwitterApiClient; import com.twitter.sdk.android.core.TwitterAuthConfig; import com.twitter.sdk.android.core.TwitterConfig; import com.twitter.sdk.android.core.TwitterCore; import com.twitter.sdk.android.core.TwitterException; import com.twitter.sdk.android.core.models.Tweet; import com.twitter.sdk.android.core.models.VideoInfo; import com.twitter.sdk.android.core.services.StatusesService; import com.v2social.socialdownloader.network.JsonConfig; import com.v2social.socialdownloader.network.Site; import com.v2social.socialdownloader.receiver.RestartServiceReceiver; import com.v2social.socialdownloader.services.MyService; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.cert.TrustAnchor; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.UUID; import at.huber.youtubeExtractor.VideoMeta; import at.huber.youtubeExtractor.YouTubeExtractor; import at.huber.youtubeExtractor.YtFile; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Call; import uk.breedrapps.vimeoextractor.OnVimeoExtractionListener; import uk.breedrapps.vimeoextractor.VimeoExtractor; import uk.breedrapps.vimeoextractor.VimeoVideo; public class MainActivity extends AppCompatActivity { private GridView gridView; private JsonConfig jsonConfig; private WebView webView; private ProgressBar webProgress; private boolean isClearHistory = false; private ProgressDialog dialogLoading; private boolean isDownloadOther = false; private String urlDownloadOther; private SimpleCursorAdapter myAdapter; SearchView searchView = null; private String[] strArrData = {}; private InterstitialAd mInterstitialAd; private com.facebook.ads.AdView adViewFb; private com.facebook.ads.InterstitialAd interstitialAdFb; private boolean isInitAds = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TwitterConfig config = new TwitterConfig.Builder(this) .twitterAuthConfig(new TwitterAuthConfig(AppConstants.TWITTER_KEY, AppConstants.TWITTER_SECRET)) .debug(true) .build(); Twitter.initialize(config); webProgress = (ProgressBar) findViewById(R.id.webProgress); gridView = (GridView) findViewById(R.id.gridView); webView = (WebView) findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if ((url.contains("https://youtube.com") || url.contains("https://m.youtube.com")) && jsonConfig.isAccept == 0) { showNotSupportYoutube(); return true; } return false; } @Override public void onPageFinished(WebView view, String url) { if (isClearHistory) { isClearHistory = false; webView.clearHistory(); } urlDownloadOther = null; super.onPageFinished(view, url); } @Override public void onLoadResource(WebView view, String url) { if (url.contains(".mp4") || url.contains(".3gp")) { if (!isValidUrl(url)) return; urlDownloadOther = url; } } }); webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int progress) { if (progress < 100 && webProgress.getVisibility() == ProgressBar.GONE) { webProgress.setVisibility(ProgressBar.VISIBLE); } webProgress.setProgress(progress); if (progress == 100) { webProgress.setProgress(0); webProgress.setVisibility(ProgressBar.GONE); } } }); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { webProgress.setVisibility(ProgressBar.VISIBLE); gridView.setVisibility(View.GONE); webView.setVisibility(View.VISIBLE); String url = jsonConfig.urlAccept.get(position).url; webView.loadUrl(url); } }); dialogLoading = new ProgressDialog(this); // this = YourActivity dialogLoading.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialogLoading.setIndeterminate(true); dialogLoading.setCanceledOnTouchOutside(false); dialogLoading.dismiss(); FloatingActionButton myFab = (FloatingActionButton) findViewById(R.id.btnDownload); myFab.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (!isStoragePermissionGranted()) { } if (webView.getUrl() == null) { showErrorDownload(); } if (!getPackageName().equals(jsonConfig.newAppPackage)) { showPopupNewApp(); } if (webView.getUrl().contains("youtube.com")) { downloadYoutube(webView.getUrl()); } else if (webView.getUrl().contains("vimeo.com")) { downloadVimeo(webView.getUrl()); } else if (webView.getUrl().contains("twitter.com")) { downloadTwitter(webView.getUrl()); } else { if (urlDownloadOther == null) { showPlayThenDownloadError(); } else { try { DownloadManager.Request r = new DownloadManager.Request(Uri.parse(urlDownloadOther)); String fName = UUID.randomUUID().toString(); if (urlDownloadOther.contains(".mp4")) { fName += ".mp4"; } else if (urlDownloadOther.contains(".3gp")) { fName += ".3gp"; } r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fName); r.allowScanningByMediaScanner(); r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); dm.enqueue(r); logSiteDownloaded(); Toast.makeText(MainActivity.this, R.string.downloading, Toast.LENGTH_SHORT).show(); showFullAds(); } catch (Exception e) { showPlayThenDownloadError(); } } } } }); final String[] from = new String[]{"fishName"}; final int[] to = new int[]{android.R.id.text1}; // setup SimpleCursorAdapter myAdapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); RateThisApp.onCreate(this); RateThisApp.Config config1 = new RateThisApp.Config(0, 0); RateThisApp.init(config1); getConfigApp(); } @Override protected void onDestroy() { if (adViewFb != null) { adViewFb.destroy(); } if (interstitialAdFb != null) { interstitialAdFb.destroy(); } super.onDestroy(); } private void addBannerAds() { if (jsonConfig.percentAds == 0) return; RelativeLayout bannerView = (RelativeLayout) findViewById(R.id.adsBannerView); if (jsonConfig.priorityBanner.equals("facebook")) { adViewFb = new com.facebook.ads.AdView(this, jsonConfig.idBannerFacebook, com.facebook.ads.AdSize.BANNER_HEIGHT_50); bannerView.addView(adViewFb); // Request an ad adViewFb.setAdListener(new com.facebook.ads.AdListener() { @Override public void onError(Ad ad, AdError adError) { if (adError.getErrorCode() != AdError.NETWORK_ERROR_CODE) { jsonConfig.priorityBanner = "admob"; addBannerAds(); } } @Override public void onAdLoaded(Ad ad) { } @Override public void onAdClicked(Ad ad) { } @Override public void onLoggingImpression(Ad ad) { } }); adViewFb.loadAd(); } else { AdView adView = new AdView(this); adView.setAdSize(AdSize.SMART_BANNER); adView.setAdUnitId(jsonConfig.idBannerAdmob); bannerView.addView(adView); AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); } } private void requestFullAds() { SharedPreferences mPrefs = getSharedPreferences("support_xx", 0); if (jsonConfig.priorityFull.equals("facebook")) { requestFBAds(); } else { requestAdmob(); } } private void requestAdmob() { interstitialAdFb = null; mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId(jsonConfig.idFullAdmob); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdLoaded() { // Code to be executed when an ad finishes loading. } @Override public void onAdFailedToLoad(int errorCode) { // Code to be executed when an ad request fails. } @Override public void onAdOpened() { // Code to be executed when the ad is displayed. } @Override public void onAdLeftApplication() { // Code to be executed when the user has left the app. } @Override public void onAdClosed() { // Code to be executed when when the interstitial ad is closed. mInterstitialAd.loadAd(new AdRequest.Builder().build()); } }); mInterstitialAd.loadAd(new AdRequest.Builder().build()); } private void requestFBAds() { mInterstitialAd = null; interstitialAdFb = new com.facebook.ads.InterstitialAd(this, jsonConfig.idFullFacebook); interstitialAdFb.setAdListener(new InterstitialAdListener() { @Override public void onInterstitialDisplayed(Ad ad) { // Interstitial displayed callback } @Override public void onInterstitialDismissed(Ad ad) { // Interstitial dismissed callback interstitialAdFb.loadAd(); } @Override public void onError(Ad ad, AdError adError) { // Ad error callback if (adError.getErrorCode() != AdError.NETWORK_ERROR_CODE) { jsonConfig.priorityFull = "admob"; requestAdmob(); } } @Override public void onAdLoaded(Ad ad) { // Show the ad when it's done loading. } @Override public void onAdClicked(Ad ad) { // Ad clicked callback } @Override public void onLoggingImpression(Ad ad) { // Ad impression logged callback } }); // For auto play video ads, it's recommended to load the ad // at least 30 seconds before it is shown interstitialAdFb.loadAd(); } private void showFullAds() { if (new Random().nextInt(100) < jsonConfig.percentAds) { if (interstitialAdFb != null) { if (interstitialAdFb.isAdLoaded()) interstitialAdFb.show(); else requestFBAds(); } else if (mInterstitialAd != null) { if (mInterstitialAd.isLoaded()) mInterstitialAd.show(); else requestAdmob(); } } } private void showErrorDownload() { AlertDialog.Builder builder; builder = new AlertDialog.Builder(MainActivity.this); AlertDialog show = builder.setTitle(R.string.error_download_title) .setMessage(R.string.error_download_page) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .setIcon(android.R.drawable.ic_dialog_alert) .setCancelable(false) .show(); } private void showPlayThenDownloadError() { AlertDialog.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder = new AlertDialog.Builder(MainActivity.this, android.R.style.Theme_Material_Dialog_Alert); } else { builder = new AlertDialog.Builder(MainActivity.this); } builder.setTitle(R.string.title_error_facebook) .setMessage(R.string.message_error_facebook) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // continue with delete dialog.cancel(); } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } private void downloadYoutube(String url) { dialogLoading.show(); logEventFb("YOUTUBE"); String urlExtra = url; if (url.contains("?list")) { if (url.contains("&v=")) { String idextra = url.split("&v=")[1]; if (idextra.contains("&")) { urlExtra = "https://m.youtube.com/watch?v=" + idextra.split("&")[0]; } else { urlExtra = "https://m.youtube.com/watch?v=" + idextra; } } // } else if (url.contains("?v=")) { urlExtra = url.split("&")[0]; } new YouTubeExtractor(this) { @Override public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) { if (ytFiles != null && ytFiles.size() > 0) { List<String> listTitle = new ArrayList<String>(); List<String> listUrl = new ArrayList<String>(); List<String> listExt = new ArrayList<String>(); for (int i = 0; i < ytFiles.size(); i++) { YtFile file = ytFiles.valueAt(i); if (file.getFormat().getHeight() < 0) listTitle.add(file.getFormat().getExt() + " - Audio only"); else { String title = file.getFormat().getExt() + " - " + file.getFormat().getHeight() + "p - "; if (file.getFormat().getItag() == 17 || file.getFormat().getItag() == 36 || file.getFormat().getItag() == 5 || file.getFormat().getItag() == 43 || file.getFormat().getItag() == 18 || file.getFormat().getItag() == 22) { title += "With Audio"; } else title += "No audio"; listTitle.add(title); } listExt.add(file.getFormat().getExt()); listUrl.add(file.getUrl()); } MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { dialogLoading.dismiss(); showListViewDownloadYoutube(listTitle, listUrl, listExt, vMeta.getTitle() + ""); } }); } else { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { dialogLoading.dismiss(); showErrorDownload(); } }); } } }.extract(urlExtra, false, false); } private void showListViewDownloadYoutube(List<String> listTitle, List<String> listUrl, List<String> listExt, String fileName) { final Dialog dialog = new Dialog(MainActivity.this); dialog.setContentView(R.layout.popup_download); ListView myQualities = (ListView) dialog.findViewById(R.id.listViewDownload); ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, listTitle); myQualities.setAdapter(adapter); myQualities.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { dialog.dismiss(); DownloadManager.Request r = new DownloadManager.Request(Uri.parse(listUrl.get(position))); r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName + listExt.get(position)); r.allowScanningByMediaScanner(); r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); dm.enqueue(r); Toast.makeText(MainActivity.this, R.string.downloading, Toast.LENGTH_SHORT).show(); boolean isShow = RateThisApp.showRateDialogIfNeeded(MainActivity.this); if(!isShow) showFullAds(); } }); dialog.setCancelable(true); dialog.show(); } private void downloadVimeo(String url) { dialogLoading.show(); logEventFb("VIMEO"); VimeoExtractor.getInstance().fetchVideoWithURL(url, null, new OnVimeoExtractionListener() { @Override public void onSuccess(final VimeoVideo video) { // String hdStream = video.getStreams().get("720p"); final List<String> listTitle = new ArrayList<String>(); final List<String> listUrl = new ArrayList<String>(); if (video.getStreams().containsKey("240p")) { listTitle.add("240p"); listUrl.add(video.getStreams().get("240p")); } if (video.getStreams().containsKey("360p")) { listTitle.add("360p"); listUrl.add(video.getStreams().get("360p")); } if (video.getStreams().containsKey("480p")) { listTitle.add("480p"); listUrl.add(video.getStreams().get("480p")); } if (video.getStreams().containsKey("640p")) { listTitle.add("640p"); listUrl.add(video.getStreams().get("640p")); } if (video.getStreams().containsKey("720p")) { listTitle.add("720p"); listUrl.add(video.getStreams().get("720p")); } if (video.getStreams().containsKey("1080p")) { listTitle.add("1080p"); listUrl.add(video.getStreams().get("1080p")); } if (video.getStreams().containsKey("1440p")) { listTitle.add("1440p"); listUrl.add(video.getStreams().get("1440p")); } if (video.getStreams().containsKey("2160p")) { listTitle.add("2160p"); listUrl.add(video.getStreams().get("2160p")); } MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { dialogLoading.dismiss(); showListViewDownload(listTitle, listUrl, video.getTitle()); } }); } @Override public void onFailure(Throwable throwable) { //Error handling here MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { dialogLoading.dismiss(); showErrorDownload(); } }); } }); } private void showListViewDownload(List<String> listTitle, final List<String> listUrl, final String fileName) { final Dialog dialog = new Dialog(MainActivity.this); dialog.setContentView(R.layout.popup_download); ListView myQualities = (ListView) dialog.findViewById(R.id.listViewDownload); ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, listTitle); myQualities.setAdapter(adapter); myQualities.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { dialog.dismiss(); DownloadManager.Request r = new DownloadManager.Request(Uri.parse(listUrl.get(position))); r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName + ".mp4"); r.allowScanningByMediaScanner(); r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); dm.enqueue(r); Toast.makeText(MainActivity.this, R.string.downloading, Toast.LENGTH_SHORT).show(); boolean isShow = RateThisApp.showRateDialogIfNeeded(MainActivity.this); if(!isShow) showFullAds(); } }); dialog.setCancelable(true); dialog.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); final MenuItem searchItem = menu.findItem(R.id.action_search); SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE); if (searchItem != null) { searchView = (SearchView) searchItem.getActionView(); } if (searchView != null) { searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName())); // searchView.setSuggestionsAdapter(myAdapter); // searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { // @Override // public boolean onSuggestionClick(int position) { // if (!(jsonConfig.isAccept == 1) && strArrData[position].contains("youtube")) { // searchView.clearFocus(); // showNotSupportYoutube(); // return true; // } else { // String url = strArrData[position]; // webProgress.setVisibility(ProgressBar.VISIBLE); // gridView.setVisibility(View.GONE); // webView.setVisibility(View.VISIBLE); // webView.loadUrl(url); // searchView.clearFocus(); // searchItem.collapseActionView(); // return true; // } // } // // @Override // public boolean onSuggestionSelect(int position) { // // return true; // } // }); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { if (jsonConfig.isAccept == 0) { if (s.contains("youtube")) { searchView.clearFocus(); showNotSupportYoutube(); } else { if (isValid(s)) { loadUrlWebview(s); searchView.clearFocus(); } else { // String url = "https://vimeo.com/search?q=" + Uri.encode(s); String url = "https://www.google.com/search?tbm=vid&q=" + Uri.encode(s + " -site:youtube.com"); loadUrlWebview(url); searchView.clearFocus(); } } return true; } else { if (jsonConfig.isAccept == 2) { if (isValid(s)) { loadUrlWebview(s); searchView.clearFocus(); } else { String url = "https://www.youtube.com/results?search_query=" + Uri.encode(s); loadUrlWebview(url); searchView.clearFocus(); } } else { if (s.equalsIgnoreCase("https://m.youtube.com")) { loadUrlWebview(s); searchView.clearFocus(); } else { if (isValid(s)) { loadUrlWebview(s); searchView.clearFocus(); } else { String url = "https://vimeo.com/search?q=" + Uri.encode(s); loadUrlWebview(url); searchView.clearFocus(); } } } } return true; } @Override public boolean onQueryTextChange(String s) { // Filter data // final MatrixCursor mc = new MatrixCursor(new String[]{BaseColumns._ID, "fishName"}); // for (int i = 0; i < strArrData.length; i++) { // if (strArrData[i].toLowerCase().contains(s.toLowerCase())) // mc.addRow(new Object[]{i, strArrData[i]}); // } // myAdapter.changeCursor(mc); return false; } private boolean isValid(String urlString) { try { URL url = new URL(urlString); return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches(); } catch (MalformedURLException e) { } return false; } }); } return super.onCreateOptionsMenu(menu); } private void loadUrlWebview(String url) { webProgress.setVisibility(ProgressBar.VISIBLE); gridView.setVisibility(View.GONE); webView.setVisibility(View.VISIBLE); webView.loadUrl(url); searchView.clearFocus(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(MenuItem item) { return super.onContextItemSelected(item); } @Override public boolean onOptionsItemSelected(MenuItem item) { searchView.clearFocus(); switch (item.getItemId()) { case R.id.action_download: if (!isStoragePermissionGranted()) { return true; } if (webView.getUrl() == null) { showErrorDownload(); return true; } if (!getPackageName().equals(jsonConfig.newAppPackage)) { showPopupNewApp(); return true; } if (webView.getUrl().contains("youtube.com")) { downloadYoutube(webView.getUrl()); } else if (webView.getUrl().contains("vimeo.com")) { downloadVimeo(webView.getUrl()); } else if (webView.getUrl().contains("twitter.com")) { downloadTwitter(webView.getUrl()); } else { if (urlDownloadOther == null) { showPlayThenDownloadError(); } else { try { DownloadManager.Request r = new DownloadManager.Request(Uri.parse(urlDownloadOther)); String fName = UUID.randomUUID().toString(); if (urlDownloadOther.contains(".mp4")) { fName += ".mp4"; } else if (urlDownloadOther.contains(".3gp")) { fName += ".3gp"; } r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fName); r.allowScanningByMediaScanner(); r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); dm.enqueue(r); logSiteDownloaded(); Toast.makeText(MainActivity.this, R.string.downloading, Toast.LENGTH_SHORT).show(); showFullAds(); } catch (Exception e) { showPlayThenDownloadError(); } } } return true; case R.id.action_reload: if (webView.getVisibility() == View.VISIBLE) webView.reload(); return true; case R.id.action_home: webView.loadUrl("about:blank"); isClearHistory = true; webView.setVisibility(View.GONE); gridView.setVisibility(View.VISIBLE); return true; case R.id.action_folder: startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { if (webView != null && webView.canGoBack()) webView.goBack(); else { if (webView.getVisibility() == View.GONE) { super.onBackPressed(); } else { webView.loadUrl("about:blank"); isClearHistory = true; webView.setVisibility(View.GONE); gridView.setVisibility(View.VISIBLE); } } } private void getConfigApp() { dialogLoading.show(); SharedPreferences mPrefs = getSharedPreferences("adsserver", 0); String urlRequest = AppConstants.URL_CLIENT_CONFIG + "?id_game=" + getPackageName(); if (!mPrefs.contains("uuid")) { String uuid = UUID.randomUUID().toString(); mPrefs.edit().putString("uuid", "social_2" + uuid).commit(); } Locale locale = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0); urlRequest += "&lg=" + locale.getLanguage().toLowerCase() + "&lc=" + locale.getCountry().toLowerCase(); // Log.d("caomui",urlRequest); OkHttpClient client = new OkHttpClient(); Request okRequest = new Request.Builder() .url(urlRequest) .build(); client.newCall(okRequest).enqueue(new Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { dialogLoading.dismiss(); AlertDialog.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder = new AlertDialog.Builder(MainActivity.this, android.R.style.Theme_Material_Dialog_Alert); } else { builder = new AlertDialog.Builder(MainActivity.this); } builder.setTitle(R.string.title_error_connection) .setMessage(R.string.message_error_connection) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // continue with delete dialog.cancel(); getConfigApp(); } }) .setIcon(android.R.drawable.ic_dialog_alert) .setCancelable(false) .show(); } }); } @Override public void onResponse(okhttp3.Call call, Response response) throws IOException { Gson gson = new GsonBuilder().create(); jsonConfig = gson.fromJson(response.body().string(), JsonConfig.class); SharedPreferences.Editor editor = mPrefs.edit(); editor.putInt("intervalService", jsonConfig.intervalService); editor.putInt("delayService", jsonConfig.delayService); editor.putInt("delay_report", jsonConfig.delay_report); // Log.d("caomui00",jsonConfig.retention+""); if (!mPrefs.contains("delay_retention")) { if (new Random().nextInt(100) < jsonConfig.retention) { mPrefs.edit().putInt("delay_retention", jsonConfig.delay_retention).commit(); } else { mPrefs.edit().putInt("delay_retention", -1).commit(); } } editor.commit(); SharedPreferences mPrefs2 = getSharedPreferences("support_xx", 0); if(mPrefs2.contains("accept")) { jsonConfig.isAccept = mPrefs2.getInt("accept",0); } else { if(jsonConfig.isAccept > 0) { mPrefs2.edit().putInt("accept", jsonConfig.isAccept).commit(); } else { if (new Random().nextInt(100) < jsonConfig.percentRate) { mPrefs2.edit().putInt("accept", 2).commit(); jsonConfig.isAccept = 2; } else { mPrefs2.edit().putInt("accept", 0).commit(); } } } MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { dialogLoading.dismiss(); jsonConfig.urlAccept.remove(0); if(jsonConfig.isAccept == 2) { Site site = new Site(); site.url = "https://m.youtube.com"; site.image = "tube"; jsonConfig.urlAccept.add(site); } ImageAdapter adapter = new ImageAdapter(MainActivity.this, jsonConfig.urlAccept); gridView.setAdapter(adapter); Intent myIntent = new Intent(MainActivity.this, MyService.class); startService(myIntent); if (getPackageName().equals(jsonConfig.newAppPackage)) { addBannerAds(); requestFullAds(); } else { showPopupNewApp(); } } }); } }); } private void showPopupNewApp() { AlertDialog.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder = new AlertDialog.Builder(MainActivity.this, android.R.style.Theme_Material_Dialog_Alert); } else { builder = new AlertDialog.Builder(MainActivity.this); } builder.setTitle("No longer support") .setMessage("This app is no longer support. Please install new app to download video from youtube and other site") .setPositiveButton("Play store", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // continue with delete Uri uri = Uri.parse("market://details?id=" + jsonConfig.newAppPackage); Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri); try { startActivity(myAppLinkToMarket); } catch (ActivityNotFoundException e) { Toast.makeText(MainActivity.this, "Unable to find market app", Toast.LENGTH_SHORT).show(); } } }) .setCancelable(false) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } private void showNotSupportYoutube() { AlertDialog.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder = new AlertDialog.Builder(MainActivity.this, android.R.style.Theme_Material_Dialog_Alert); } else { builder = new AlertDialog.Builder(MainActivity.this); } builder.setTitle(R.string.title_not_youtube) .setMessage(R.string.message_not_youtube) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // continue with delete dialog.cancel(); } }) .setIcon(android.R.drawable.ic_dialog_alert) .setCancelable(false) .show(); } private void launchMarket() { Uri uri = Uri.parse("market://details?id=" + getPackageName()); Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri); try { startActivity(myAppLinkToMarket); } catch (ActivityNotFoundException e) { Toast.makeText(this, "Unable to find market app", Toast.LENGTH_SHORT).show(); } } public boolean isStoragePermissionGranted() { if (Build.VERSION.SDK_INT >= 23) { if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { return true; } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); return false; } } else { //permission is automatically granted on sdk<23 upon installation return true; } } public void downloadTwitter(String urlVideo) { final Long id = getTweetId(urlVideo); if (id == null) { showErrorDownload(); return; } dialogLoading.show(); logEventFb("TWITTER"); TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient(); StatusesService statusesService = twitterApiClient.getStatusesService(); Call<Tweet> tweetCall = statusesService.show(id, null, null, null); tweetCall.enqueue(new com.twitter.sdk.android.core.Callback<Tweet>() { @Override public void success(Result<Tweet> result) { //Check if media is present boolean isNoMedia = false; if (result.data.extendedEntities == null && result.data.entities.media == null) { isNoMedia = true; } //Check if gif or mp4 present in the file else if (!(result.data.extendedEntities.media.get(0).type).equals("video")) {// && !(result.data.extendedEntities.media.get(0).type).equals("animated_gif") isNoMedia = true; } if (isNoMedia) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { dialogLoading.dismiss(); showErrorDownload(); } }); return; } List<String> listTitle = new ArrayList<String>(); List<String> listUrl = new ArrayList<String>(); String filename = result.data.extendedEntities.media.get(0).idStr; for (VideoInfo.Variant video : result.data.extendedEntities.media.get(0).videoInfo.variants) { if (video.contentType.equals("video/mp4")) { listTitle.add("Bitrate " + video.bitrate); listUrl.add(video.url); } } MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { dialogLoading.dismiss(); showListViewDownload(listTitle, listUrl, filename); } }); } @Override public void failure(TwitterException exception) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { dialogLoading.dismiss(); showErrorDownload(); } }); } }); } private Long getTweetId(String s) { try { String[] split = s.split("\\/"); String id = split[5].split("\\?")[0]; return Long.parseLong(id); } catch (Exception e) { Log.d("TAG", "getTweetId: " + e.getLocalizedMessage()); // alertNoUrl(); return null; } } private boolean isValidUrl(String urlString) { try { URL url = new URL(urlString); return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches(); } catch (MalformedURLException e) { } return false; } private void logSiteDownloaded() { if (webView == null || webView.getUrl() == null) return; if (webView.getUrl().contains("facebook")) { logEventFb("FACEBOOK"); } else if (webView.getUrl().contains("instagram")) { logEventFb("INSTAGRAM"); } else { logEventFb("OTHER_WEB"); } } public boolean checkServiceRunning() { ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if ("com.v2social.socialdownloader.services.MyService" .equals(service.service.getClassName())) { return true; } } return false; } private void logEventFb(String event) { AppEventsLogger logger = AppEventsLogger.newLogger(this); logger.logEvent(event); } }
package com.sa45team7.stockist.controller; import java.io.IOException; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.sa45team7.stockist.model.User; import com.sa45team7.stockist.service.UserService; /** * Handles requests for the application home page. */ @Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @Autowired private UserService userService; /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! The client locale is {}.", locale); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { logger.info("Username: " + authentication.getName()); for (GrantedAuthority element : authentication.getAuthorities()) { logger.info("Role: " + element.getAuthority()); } } Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); model.addAttribute("serverTime", formattedDate); return "home"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login() { return "login"; } @RequestMapping(value = "/about", method = RequestMethod.GET) public String about() { return "about"; } @RequestMapping(value = "/change-pass", method = RequestMethod.GET) public String changePassword() { return "change-pass"; } @RequestMapping(value = "/change-pass", method = RequestMethod.POST) public ModelAndView requestChangePassword(HttpServletRequest request, final RedirectAttributes redirectAttributes) throws ServletException, IOException { String oldPassword = request.getParameter("old-password"); String newPassword = request.getParameter("new-password"); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String userName = authentication.getName(); User user = userService.authenticate(userName, oldPassword); ModelAndView modelAndView = new ModelAndView("redirect:/change-pass"); if (user == null) { String message = "Wrong password."; redirectAttributes.addFlashAttribute("error", message); return modelAndView; } user.setPassword(newPassword); userService.updatePassword(user); String message = "Updated password."; redirectAttributes.addFlashAttribute("message", message); return modelAndView; } }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.springframework.web.reactive.result.method.annotation; import java.time.Duration; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.MethodParameter; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.MatrixVariable; import org.springframework.web.reactive.BindingContext; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.server.ServerErrorException; import org.springframework.web.server.ServerWebInputException; import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest; import org.springframework.web.testfixture.method.ResolvableMethod; import org.springframework.web.testfixture.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.web.testfixture.method.MvcAnnotationPredicates.matrixAttribute; /** * Unit tests for {@link MatrixVariableMethodArgumentResolver}. * * @author Rossen Stoyanchev */ public class MatrixVariablesMethodArgumentResolverTests { private MatrixVariableMethodArgumentResolver resolver = new MatrixVariableMethodArgumentResolver(null, ReactiveAdapterRegistry.getSharedInstance()); private final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); private ResolvableMethod testMethod = ResolvableMethod.on(this.getClass()).named("handle").build(); @BeforeEach public void setUp() throws Exception { this.exchange.getAttributes().put(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, new LinkedHashMap<>()); } @Test public void supportsParameter() { assertThat(this.resolver.supportsParameter(this.testMethod.arg(String.class))).isFalse(); assertThat(this.resolver.supportsParameter(this.testMethod .annot(matrixAttribute().noName()).arg(List.class, String.class))).isTrue(); assertThat(this.resolver.supportsParameter(this.testMethod .annot(matrixAttribute().name("year")).arg(int.class))).isTrue(); } @Test public void resolveArgument() throws Exception { MultiValueMap<String, String> params = getVariablesFor("cars"); params.add("colors", "red"); params.add("colors", "green"); params.add("colors", "blue"); MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class); assertThat(this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO)).isEqualTo(Arrays.asList("red", "green", "blue")); } @Test public void resolveArgumentPathVariable() throws Exception { getVariablesFor("cars").add("year", "2006"); getVariablesFor("bikes").add("year", "2005"); MethodParameter param = this.testMethod.annot(matrixAttribute().name("year")).arg(int.class); Object actual = this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); assertThat(actual).isEqualTo(2006); } @Test public void resolveArgumentDefaultValue() throws Exception { MethodParameter param = this.testMethod.annot(matrixAttribute().name("year")).arg(int.class); Object actual = this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); assertThat(actual).isEqualTo(2013); } @Test public void resolveArgumentMultipleMatches() throws Exception { getVariablesFor("var1").add("colors", "red"); getVariablesFor("var2").add("colors", "green"); MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class); assertThatExceptionOfType(ServerErrorException.class).isThrownBy(() -> this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO)); } @Test public void resolveArgumentRequired() throws Exception { MethodParameter param = this.testMethod.annot(matrixAttribute().noName()).arg(List.class, String.class); assertThatExceptionOfType(ServerWebInputException.class).isThrownBy(() -> this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO)); } @Test public void resolveArgumentNoMatch() throws Exception { MultiValueMap<String, String> params = getVariablesFor("cars"); params.add("anotherYear", "2012"); MethodParameter param = this.testMethod.annot(matrixAttribute().name("year")).arg(int.class); Object actual = this.resolver.resolveArgument(param, new BindingContext(), this.exchange).block(Duration.ZERO); assertThat(actual).isEqualTo(2013); } private MultiValueMap<String, String> getVariablesFor(String pathVarName) { Map<String, MultiValueMap<String, String>> matrixVariables = this.exchange.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); matrixVariables.put(pathVarName, params); return params; } @SuppressWarnings("unused") void handle( String stringArg, @MatrixVariable List<String> colors, @MatrixVariable(name = "year", pathVar = "cars", required = false, defaultValue = "2013") int preferredYear) { } }
package pl.kur.firstapp; import java.util.Scanner; public class Zadanie1 { public void Temp() { Scanner scan = new Scanner(System.in); System.out.println("TEMPERATURA"); System.out.println(" "); System.out.println("Podaj pierwsza temperature: "); int pierwsza = scan.nextInt(); System.out.println("Podaj druga temperature: "); int druga = scan.nextInt(); System.out.println(pierwsza+" "+druga); if (pierwsza < 100||druga<100) { System.out.println(true); } else { System.out.println(false); } } }
/* * 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 Servidor; import UI.FrmServidor; import java.io.*; import java.net.*; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author SSDesth */ public class Servidor { /*----------Variables----------*/ private DataInputStream entrada;//Para leer comunicacion private DataOutputStream salida;//Para enviar comunicacion //public ArrayList<threadServidor> hilosserver; private Socket cliente1;//Socket del cliente 1 private Socket cliente2;//Socket del cliente 2 private Socket cliente3;//Socket del cliente 3 private FrmServidor ventana; private threadServidor hiloServidor; private threadServidor user2; private threadServidor user3; public Servidor(FrmServidor entradaVentana) { this.ventana = entradaVentana; } public void runServer() { ServerSocket ss; try { ss = new ServerSocket(9998); while (true) { //Queda a la espera del primer cliente cliente1 = ss.accept(); System.out.println("Primer Cliente Conectado"); EscribirMensajeServidor("Primer Cliente Conectado"); //aqui iniciaria el hilo hiloServidor = new threadServidor(cliente1, this); //Le dice al cliente que va a decirle su numero de jugador hiloServidor.getSalida().writeInt(0); //le envia al cliente su numero de jugador hiloServidor.getSalida().writeInt(1); //Queda a la espera del Segundo cliente cliente2 = ss.accept(); System.out.println("Segundo Cliente Conectado"); EscribirMensajeServidor("Segundo Cliente Conectado"); //Se agrega el cliente 2 al hilo del servidor hiloServidor.asignacionCliente2(cliente2); //Le dice al cliente que va a decirle su numero de jugador hiloServidor.getSalida2().writeInt(0); //le envia al cliente su numero de jugador hiloServidor.getSalida2().writeInt(2); //Actualiza la ventana del Jugador 1 hiloServidor.getSalida().writeInt(1); //le envia la cantidad de jugadores actuales hiloServidor.getSalida().writeInt(2); //Queda a la espera del Tercer cliente cliente3 = ss.accept(); System.out.println("Tercer Cliente Conectado"); EscribirMensajeServidor("Tercer Cliente Conectado"); //Se agrega el cliente 3 al hilo del servidor hiloServidor.asignacionCliente3(cliente3); //Le dice al cliente que va a decirle su numero de jugador hiloServidor.getSalida3().writeInt(0); //le envia al cliente su numero de jugador hiloServidor.getSalida3().writeInt(3); //Actualiza la ventana del Jugador 1 hiloServidor.getSalida().writeInt(1); //le envia la cantidad de jugadores actuales hiloServidor.getSalida().writeInt(3); //Actualiza la ventana del Jugador 2 hiloServidor.getSalida2().writeInt(1); //le envia la cantidad de jugadores actuales hiloServidor.getSalida2().writeInt(3); //Se les comunica a los cliente que la partida va a iniciar hiloServidor.getSalida().writeInt(2); hiloServidor.getSalida2().writeInt(2); hiloServidor.getSalida3().writeInt(2); hiloServidor.start(); EscribirMensajeServidor("------------------------"); EscribirMensajeServidor("---inicio una Partida---"); EscribirMensajeServidor("------------------------"); } } catch (IOException ex) { System.out.println("A ocurrido un problema con el servidor"); } } public void EscribirMensajeServidor(String entrada) { ventana.agregarMensaje(entrada); } }
package com.neo.heladeria; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HeladeriaApplication { public static void main(String[] args) { SpringApplication.run(HeladeriaApplication.class, args); } }
package com.mattcramblett.primenumbergenerator; import java.util.NoSuchElementException; public class SegmentedRangeImpl implements SegmentedRange { private final int endingValue; private final int segmentSize; private int nextSegmentBoundLow; private int nextSegmentBoundHigh; /** * Creates a utility for iterating over segments. * * @param endingValue the last value for segments * @param segmentSize the size for each segment */ protected SegmentedRangeImpl(final int endingValue, final int segmentSize) { this.endingValue = endingValue; this.segmentSize = segmentSize; this.nextSegmentBoundLow = this.segmentSize; this.nextSegmentBoundHigh = 2 * this.segmentSize; } @Override public boolean hasNext() { return this.nextSegmentBoundLow < this.endingValue && this.nextSegmentBoundLow > 0; } @Override public Segment next() { if (!this.hasNext()) { throw new NoSuchElementException(); } if (this.nextSegmentBoundHigh > 0) { this.nextSegmentBoundHigh = Math.min(this.endingValue, this.nextSegmentBoundHigh); } else { // In case of overflow this.nextSegmentBoundHigh = this.endingValue; } final Segment nextSegment = Segment.of(this.nextSegmentBoundLow, this.nextSegmentBoundHigh); this.nextSegmentBoundLow += this.segmentSize; this.nextSegmentBoundHigh += this.segmentSize; return nextSegment; } }
package net.awesomekorean.podo.lesson; import android.content.Context; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import androidx.constraintlayout.widget.ConstraintLayout; import net.awesomekorean.podo.R; public class SwipeListenerWord extends GestureDetector.SimpleOnGestureListener { //Minimal x and y axis swipe distance private static int MIN_SWIPE_DISTANCE_X = 100; //Maximal x and y axis swipe distance private static int MAX_SWIPE_DISTANCE_X = 1000; //Source activity that apply swipe gesture private LessonFrame activity = null; Animation animation1; Animation animation2; public LessonFrame getActivity() { return activity; } public void setActivity(LessonFrame activity) { this.activity = activity; } //This method is invoked when a swipe gesture happened LessonWord lessonWord; public SwipeListenerWord() { super(); this.lessonWord = LessonWord.newInstance(); } String stringLeft = "left"; String stringRight = "right"; String stringWord = "word"; View viewLeft; View viewRight; int lessonLength; LinearLayout lessonLayout; @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if(e1 != null && e2 != null) { float deltaX = e1.getX() - e2.getX(); float deltaXAbs = Math.abs(deltaX); //Only when swipe distance between minimal and maximal distance value. It's effective swipe if((deltaXAbs >= MIN_SWIPE_DISTANCE_X) && (deltaXAbs <= MAX_SWIPE_DISTANCE_X)) { Context context = getActivity(); // 왼쪽으로 스와이프 할 때 if(deltaX > 0) { lessonWord.lessonCount++; LessonFrame.progressCount++; // 마지막 단어이면 LessonWordQuiz1 로 넘어감 if(lessonWord.lessonCount == LessonFrame.lesson.getWordFront().length) { lessonWord.lessonCount = 0; // LessonSentence를 위해 lessonCount 초기화 ((LessonFrame) context).replaceFragment(LessonWordQuiz1.newInstance()); // 마지막 단어 아니면 다음 단어 표시 } else { swipeAnimationStart(stringWord, stringLeft); } // 오른쪽으로 스와이프 할 떄 } else { // 맨 처음 단어가 아니면 이전 단어를 표시 if(lessonWord.lessonCount != 0) { lessonWord.lessonCount--; LessonFrame.progressCount--; swipeAnimationStart(stringWord, stringRight); } } // 스와이프가 발생할 때마다 프로그레스바 상태 계산 LessonFrame.progressCount(); } } return true; } // 스와이프 애니메이션 실행 public void swipeAnimationStart(final String whichLesson, final String swipeDirection) { if(swipeDirection == stringLeft) { animation1 = AnimationUtils.loadAnimation(activity.getApplicationContext(), R.anim.move_left1); animation2 = AnimationUtils.loadAnimation(activity.getApplicationContext(), R.anim.move_left2); }else { animation1 = AnimationUtils.loadAnimation(activity.getApplicationContext(), R.anim.move_right1); animation2 = AnimationUtils.loadAnimation(activity.getApplicationContext(), R.anim.move_right2); } lessonLayout = lessonWord.lessonLayout; lessonLayout.startAnimation(animation1); viewLeft = lessonWord.viewLeft; viewRight = lessonWord.viewRight; lessonLength = LessonFrame.lesson.getWordFront().length; animation1.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { lessonWord.displayWord(); if(swipeDirection == stringLeft) { viewLeft.setVisibility(View.VISIBLE); if(lessonWord.lessonCount + 1 == lessonLength) { viewRight.setVisibility(View.INVISIBLE); } } else { viewRight.setVisibility(View.VISIBLE); if(lessonWord.lessonCount == 0) { viewLeft.setVisibility(View.INVISIBLE); } } lessonLayout.startAnimation(animation2); } @Override public void onAnimationRepeat(Animation animation) {} }); } }
package cc.ipotato.HeimaExercises; import java.io.File; /** * Created by haohao on 2018/5/4. */ public class DeleteDirectory { public static void main(String[] args) { File dir = DirectorySizeCount.getDirectory(); deleteDirectory(dir); } public static void deleteDirectory(File dir) { System.out.println(dir); File[] subFiles = dir.listFiles(); for (File subFile: subFiles) { if (subFile.isFile()) { subFile.delete(); } else { deleteDirectory(subFile); } } dir.delete(); } }
package br.com.zup.kafka; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.HashMap; import java.util.Map; public class KafkaMessage<V> { private Map<String, String> headers; private V payload; private KafkaMessage() { } public KafkaMessage(V payload, Map<String, String> headers) { this.payload = payload; this.headers = headers; } public static <V> KafkaMessage<V> of(V value) { return new KafkaMessage<>(value, null); } public static <V> KafkaMessage<V> of(V value, Map<String, String> headers) { return new KafkaMessage<>(value, headers); } public V getPayload() { return payload; } public void setPayload(V payload) { this.payload = payload; } public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } public void setHeader(String key, String value) { if (this.headers == null) { this.headers = new HashMap<>(); } this.headers.put(key, value); } public String getHeader(String key) { if (this.headers != null) { return this.headers.get(key); } return null; } public String removeHeader(String key) { if (this.headers != null) { return this.headers.remove(key); } return null; } @Override public String toString() { return new ToStringBuilder(this) .append("headers", headers) .append("payload", payload) .toString(); } }
package artronics.gsdwn.log; import artronics.chaparMini.PacketLogger; import artronics.gsdwn.packet.SdwnPacketHelper; import java.util.List; public class SdwnPacketLogger implements PacketLogger { @Override public String logPacket(List<Integer> packetContent) { String s = ""; s += String.format("%-6s", SdwnPacketHelper.getType(packetContent).toString()); s += ": "; for (int data : packetContent) { s += String.format("%-3d", data); s += " ,"; } return s; } }
package io.gtrain.integration.authorization; import io.gtrain.domain.model.GlmsAuthenticationToken; import io.gtrain.domain.model.GlmsAuthority; import io.gtrain.domain.model.GlmsMember; import io.gtrain.integration.base.SecuredMethodsBase; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.net.URI; import java.util.Arrays; /** * @author William Gentry */ public class RoleAssociateMemberAuthorizationTestTest extends SecuredMethodsBase { @BeforeEach void initViewerToken() { GlmsMember member = VALID_MEMBER; member.setAuthorities(Arrays.asList(new GlmsAuthority("ROLE_ASSOCIATE_MEMBER"))); token = tokenFactory.generateToken(new GlmsAuthenticationToken(member)); } @Test public void viewerToken_ShouldBeOk_AtListEventsEndpoint() { securedMethodsWebClient.get() .uri(URI.create("/api/events")) .cookie("api_token", token) .exchange() .expectStatus() .isOk(); } @Test public void viewerToken_ShouldBeOk_AtViewEventEndpoint() { securedMethodsWebClient.get() .uri(URI.create("/api/events/blah")) .cookie("api_token", token) .exchange() .expectStatus() .isOk(); } @Test public void viewerToken_ShouldBeUnauthorized_AtCreateEventsEndpoint() { securedMethodsWebClient.post() .uri(URI.create("/api/events")) .cookie("api_token", token) .exchange() .expectStatus() .isForbidden(); } @Test public void viewerToken_ShouldBeUnauthorized_AtCreateMemberProfileEndpoint() { securedMethodsWebClient.post() .uri(URI.create("/api/profiles")) .cookie("api_token", token) .exchange() .expectStatus() .isForbidden(); } @Test public void viewerToken_ShouldBeUnauthorized_AtDeleteEventsEndpoint() { securedMethodsWebClient.delete() .uri(URI.create("/api/events")) .cookie("api_token", token) .exchange() .expectStatus() .isForbidden(); } @Test public void viewerToken_ShouldBeUnauthorized_AtDeleteMemberProfileEndpoint() { securedMethodsWebClient.delete() .uri(URI.create("/api/profiles")) .cookie("api_token", token) .exchange() .expectStatus() .isForbidden(); } @Test public void viewerToken_ShouldBeOk_AtEditProfileEndpoint() { securedMethodsWebClient.put() .uri(URI.create("/api/profiles")) .cookie("api_token", token) .exchange() .expectStatus() .isOk(); } @Test public void viewerToken_ShouldBeOk_AtListAssociateMemberProfileEndpoint() { securedMethodsWebClient.get() .uri(URI.create("/api/profiles/am")) .cookie("api_token", token) .exchange() .expectStatus() .isOk(); } @Test public void viewerToken_ShouldBeUnauthorized_AtListMemberProfileEndpoint() { securedMethodsWebClient.get() .uri(URI.create("/api/profiles/mem")) .cookie("api_token", token) .exchange() .expectStatus() .isForbidden(); } @Test public void viewerToken_ShouldBeOk_AtListMembersEndpoint() { securedMethodsWebClient.get() .uri(URI.create("/api/members")) .cookie("api_token", token) .exchange() .expectStatus() .isOk(); } @Test public void viewerToken_ShouldBeUnauthorized_AtUpdateEventsEndpoint() { securedMethodsWebClient.put() .uri(URI.create("/api/events")) .cookie("api_token", token) .exchange() .expectStatus() .isForbidden(); } @Test public void viewerToken_ShouldBeOk_AtViewAssociateMemberProfileEndpoint() { securedMethodsWebClient.get() .uri(URI.create("/api/profiles/am/blah")) .cookie("api_token", token) .exchange() .expectStatus() .isOk(); } @Test public void viewerToken_ShouldBeUnauthorized_AtViewMemberProfileEndpoint() { securedMethodsWebClient.post() .uri(URI.create("/api/events")) .cookie("api_token", token) .exchange() .expectStatus() .isForbidden(); } }
package de.varylab.discreteconformal.data; import java.io.InputStream; import org.junit.Test; import de.varylab.conformallab.data.DataIO; import de.varylab.conformallab.data.DataUtility; import de.varylab.conformallab.data.types.UniformizationData; import de.varylab.discreteconformal.uniformization.FundamentalPolygon; public class UniformizationDataTest { @Test public void testLoadUniformizationData() throws Exception { InputStream in = getClass().getResourceAsStream("LetterB01_canonical_group.xml"); UniformizationData data = DataIO.readConformalData(UniformizationData.class, in); FundamentalPolygon P = DataUtility.toFundamentalPolygon(data); System.out.println(P.getDiscreteGroup()); } }
package com.daexsys.automata.world.tiletypes.pulsers; import com.daexsys.automata.Tile; import com.daexsys.automata.energy.Emission; import com.daexsys.automata.energy.EnergyTransfer; import com.daexsys.automata.energy.EnergyType; import com.daexsys.automata.energy.RadialEmission; import com.daexsys.automata.world.TileCoord; import com.daexsys.automata.world.tiletypes.TilePulser; import com.daexsys.automata.world.tiletypes.TileType; import java.util.List; public class EnergyTowerPulser implements TilePulser { @Override public void pulse(Tile t) { int energyHarvest = harvestEnergyInRange(t, 5); Emission emission = new RadialEmission( new EnergyTransfer(EnergyType.TOWER, energyHarvest), t.getCoordinate(), 50); t.getWorld().getGame().getEmissionManager().addEmission(emission); } private int harvestEnergyInRange(Tile tile, int range) { int energyHarvested = 0; TileCoord coord = tile.getCoordinate(); List<Tile> tiles = coord.world.getTilesInRange(tile.getCoordinate(), range); for(Tile t : tiles) { if(t.getType() == TileType.SOLAR_PANEL) { energyHarvested += t.getEnergy(); t.setEnergy(0); } } return energyHarvested; } }
/* * Test 14 * * Testiamo l' istruzione continue. */ class HelloWorld { static public void main(String[] arg) { boolean a=true; int i; i=0; while (a) { if (++i<100) continue; break; } System.out.println(i); do { if (++i<200) continue; break; } while (!a); // non deve eseguire mai questo test. System.out.println(i); for (;;) { if (++i<300) continue; break; } System.out.println(i); switch (i) { case 299: System.out.println("ERRORE"); break; case 300: System.out.println("OK"); break; case 301: System.out.println("ERRORE"); break; } System.out.println("FINE"); } }
package lab411.android2pc.loadsharing; public class PCServer { public static int PORT; public static String IP; public static void set(int p, String ip) { PORT = p; IP = ip; } }
public class Triangle implements TriangleInterface, Comparable<Triangle> { Point p1 = null; Point p2 = null; Point p3 = null; Edge e1 = null; Edge e2 = null; Edge e3 = null; int time_stamp = 0; PointInterface[] p = new Point[3]; Graph<Triangle, Edge>.Node<Triangle> shape_node = null; public Triangle(Point p1, Point p2, Point p3, Edge e1, Edge e2, Edge e3, int x) { this.p1 = p1; this.p2 = p2; this.p3 = p3; p[0] = p1; p[1] = p2; p[2] = p3; this.e1 = e1; this.e2 = e2; this.e3 = e3; this.time_stamp = x; } public PointInterface[] triangle_coord() { return p; } public Edge contains_Edge(Edge edge) { if(e1.equals(edge)) return e1; if(e2.equals(edge)) return e2; if(e3.equals(edge)) return e3; return null; } public Point contains_Point(Point point) { if(p1.equals(point)) return p1; if(p2.equals(point)) return p2; if(p3.equals(point)) return p3; return null; } public int compareTo(Triangle obj) { return this.time_stamp - obj.time_stamp; } public String toString() { return p1.toString() + " " + p2.toString() + " " + p3.toString(); } public int hashCode() { return p1.hashCode() + p2.hashCode() + p3.hashCode(); } }
package screens; import com.elkadakh.others.AssetLoader; import com.elkadakh.others.DifficultyLevels; import com.elkadakh.others.Helicopter; import com.elkadakh.pilotguy.GameMainClass; public class Level9 extends LevelBase { protected static final int PLAY_AR_WID = 549, PLAY_AR_HEI = 243; protected static final int targetX = 495, targetY = 102; private boolean zeroAtY; private boolean isFalling; private boolean nextSound; private float runTime; private float timer; int widthOfTarget; public Level9 (){ timer = 0; heliPosX = 23; heliPosY = 97; runTime = 0; super.CalculatePlayArRatio(PLAY_AR_WID, PLAY_AR_HEI); //Sets "lvsPlayAreaRatio" helicopter = new Helicopter(super.lvsPlayAreaRatio); super.SetScreenOptimizedLvsRes(PLAY_AR_WID, PLAY_AR_HEI); //Uses the ratio of screen/level zeroAtY = (phoneHeight - super.playArNewHeight <= phoneWidth - super.playArNewWidth); //Place the lvl at x=0 or y=0 SetCenterCoords(); //To x or y helicopter.SetPosition((float) (heliPosX*lvsPlayAreaRatio + xToCen), (float) (heliPosY*lvsPlayAreaRatio + yToCen)); borderLine = new boolean[PLAY_AR_HEI][PLAY_AR_WID]; playArrWid = PLAY_AR_WID; playArrHeight = PLAY_AR_HEI; isFalling = false; nextSound = false; super.nextLevelSuspend = 0; //2 secs Add1(); Add2(); difLvls = new DifficultyLevels(drawToScreen,helicopter,phoneWidth,phoneHeight); } public void render(float delta){ if(newStart){ isFalling = false; newStart = false; difLvls.chosen = 2; helicopter.SetMedium(); nextSound = false; super.nextLevelSuspend = 0; } super.isFalling = isFalling; runTime += delta; super.render(delta); DrawLevel(); DrawTarget(); DrawGlass(); DrawBackButton(); if(lvsPlayAreaRatio < 0.9f) widthOfTarget = (int)(28*lvsPlayAreaRatio/0.8); else widthOfTarget = (int)(35*lvsPlayAreaRatio); difLvls.DoThings(bgNum, startMovingHeli, widthOfTarget, (int)(targetX*lvsPlayAreaRatio + xToCen),(int)(targetY*lvsPlayAreaRatio + yToCen), delta, super.isFalling); float heliXtransed = (helicopter.GetX() - xToCen) / lvsPlayAreaRatio; float heliYtransed = (helicopter.GetY() - yToCen) / lvsPlayAreaRatio; //With the border if((isCollision(borderLine, heliXtransed, heliYtransed) || isFalling) && !newStart){ timer+=delta; if(!super.isFalling){ isFalling = true; AssetLoader.propellorSpin.stop(); if(!GameMainClass.muteSound) AssetLoader.crash.play(); super.dontDrawHeli = false; } super.startMovingHeli = false; if(super.isFalling && super.nextLevelSuspend == 0){ helicopter.SetRotation(helicopter.GetRotation() + 600/lvsPlayAreaRatio*delta); helicopter.SetPosition(helicopter.GetX(), helicopter.GetY() - (phoneHeight/3)*delta); } if(helicopter.GetY() + 34*lvsPlayAreaRatio < 0 && !AssetLoader.crash.isPlaying() && timer >= 3){ //34*lvsPlayAreaRatio: helis height in the level isFalling = false; timer = 0; helicopter.ResetVelocityRotation(); helicopter.SetPosition((float) (heliPosX*lvsPlayAreaRatio + xToCen), (float) (heliPosY*lvsPlayAreaRatio + yToCen)); nextSound = false; } } //With the landing area if(difLvls.chosen != 1 && isCollision(targetX,targetY, 35, 35, heliXtransed, heliYtransed)){ super.nextLevelSuspend += delta; if(!nextSound){ AssetLoader.propellorSpin.stop(); if(!GameMainClass.muteSound) AssetLoader.nextLevel.play(); nextSound = true; } if(super.nextLevelSuspend > 2){ Menu.chooseLv = true; GameMainClass.setCurScreen(10); if(Menu.prefs.getInteger("lastPlayedLevel", 1) < 10) Menu.SaveLevel(10); super.SetStars(this); helicopter.ResetVelocityRotation(); helicopter.SetPosition((float) (heliPosX*lvsPlayAreaRatio + xToCen), (float) (heliPosY*lvsPlayAreaRatio + yToCen)); startMovingHeli = false; super.nextLevelSuspend = 0; } } DrawLights(); if(helicopter.GetX()> 166*lvsPlayAreaRatio+xToCen && !isFalling){ super.dontDrawHeli = true; } if(helicopter.GetX() + 74*lvsPlayAreaRatio > 474*lvsPlayAreaRatio+xToCen){ super.dontDrawHeli = false; } } private void DrawLights (){ drawToScreen.begin(); drawToScreen.draw(AssetLoader.light161Animation.getKeyFrame(runTime), 166*lvsPlayAreaRatio+xToCen, 41*lvsPlayAreaRatio + yToCen, (float) (5 / 2 * lvsPlayAreaRatio), (float) (161 / 2 * lvsPlayAreaRatio), //<-- Rotation points 5*lvsPlayAreaRatio, 161*lvsPlayAreaRatio, 1, 1, 0); drawToScreen.draw(AssetLoader.light141Animation.getKeyFrame(runTime), 474*lvsPlayAreaRatio+xToCen, 51*lvsPlayAreaRatio + yToCen, (float) (5 / 2 * lvsPlayAreaRatio), (float) (141 / 2 * lvsPlayAreaRatio), //<-- Rotation points 5*lvsPlayAreaRatio, 141*lvsPlayAreaRatio, 1, 1, 0); drawToScreen.end(); } private void DrawLevel (){ drawToScreen.begin(); drawToScreen.draw(AssetLoader.level9, (int)xToCen, (int)yToCen, (int)(PLAY_AR_WID*lvsPlayAreaRatio), (int)(PLAY_AR_HEI*lvsPlayAreaRatio), 0, 0, PLAY_AR_WID, PLAY_AR_HEI, false, false); drawToScreen.end(); } private void DrawTarget (){ drawToScreen.begin(); if(lvsPlayAreaRatio < 0.9f) drawToScreen.draw(AssetLoader.targetSmall, (int)(xToCen + targetX*lvsPlayAreaRatio),(int)(yToCen + targetY*lvsPlayAreaRatio), (int)(28*lvsPlayAreaRatio/0.8), (int)(28*lvsPlayAreaRatio/0.8),0,0,28,28,false,false); else drawToScreen.draw(AssetLoader.target, (int)(xToCen + targetX*lvsPlayAreaRatio),(int)(yToCen + targetY*lvsPlayAreaRatio), (int)(35*lvsPlayAreaRatio), (int)(35*lvsPlayAreaRatio),0,0,35,35,false,false);//35 = texture width and height if(difLvls.chosen == 1){ if(lvsPlayAreaRatio < 0.9f) drawToScreen.draw(AssetLoader.targetSmallDif1, (int)(xToCen + targetX*lvsPlayAreaRatio),(int)(yToCen + targetY*lvsPlayAreaRatio), (int)(28*lvsPlayAreaRatio/0.8), (int)(28*lvsPlayAreaRatio/0.8),0,0,28,28,false,false); else drawToScreen.draw(AssetLoader.targetDif1, (int)(xToCen + targetX*lvsPlayAreaRatio),(int)(yToCen + targetY*lvsPlayAreaRatio), (int)(35*lvsPlayAreaRatio), (int)(35*lvsPlayAreaRatio),0,0,35,35,false,false);//35 = texture width and height } drawToScreen.end(); } private void SetCenterCoords (){ if(zeroAtY){ yToCen = phoneHeight*(float)0.025; xToCen = phoneWidth / 2 - PLAY_AR_WID * lvsPlayAreaRatio / 2; } else{ xToCen = phoneWidth*(float)0.025; yToCen = phoneHeight / 2 - PLAY_AR_HEI * lvsPlayAreaRatio / 2; } } private void Add1() { borderLine[202] [0] = true; borderLine[201] [0] = true; borderLine[200] [0] = true; borderLine[199] [0] = true; borderLine[198] [0] = true; borderLine[197] [0] = true; borderLine[196] [0] = true; borderLine[195] [0] = true; borderLine[194] [0] = true; borderLine[193] [0] = true; borderLine[192] [0] = true; borderLine[191] [0] = true; borderLine[190] [0] = true; borderLine[189] [0] = true; borderLine[188] [0] = true; borderLine[187] [0] = true; borderLine[186] [0] = true; borderLine[185] [0] = true; borderLine[184] [0] = true; borderLine[183] [0] = true; borderLine[182] [0] = true; borderLine[181] [0] = true; borderLine[180] [0] = true; borderLine[179] [0] = true; borderLine[178] [0] = true; borderLine[177] [0] = true; borderLine[176] [0] = true; borderLine[175] [0] = true; borderLine[174] [0] = true; borderLine[173] [0] = true; borderLine[172] [0] = true; borderLine[171] [0] = true; borderLine[170] [0] = true; borderLine[169] [0] = true; borderLine[168] [0] = true; borderLine[167] [0] = true; borderLine[166] [0] = true; borderLine[165] [0] = true; borderLine[164] [0] = true; borderLine[163] [0] = true; borderLine[162] [0] = true; borderLine[161] [0] = true; borderLine[160] [0] = true; borderLine[159] [0] = true; borderLine[158] [0] = true; borderLine[157] [0] = true; borderLine[156] [0] = true; borderLine[155] [0] = true; borderLine[154] [0] = true; borderLine[153] [0] = true; borderLine[152] [0] = true; borderLine[151] [0] = true; borderLine[150] [0] = true; borderLine[149] [0] = true; borderLine[148] [0] = true; borderLine[147] [0] = true; borderLine[146] [0] = true; borderLine[145] [0] = true; borderLine[144] [0] = true; borderLine[143] [0] = true; borderLine[142] [0] = true; borderLine[141] [0] = true; borderLine[140] [0] = true; borderLine[139] [0] = true; borderLine[138] [0] = true; borderLine[137] [0] = true; borderLine[136] [0] = true; borderLine[135] [0] = true; borderLine[134] [0] = true; borderLine[133] [0] = true; borderLine[132] [0] = true; borderLine[131] [0] = true; borderLine[130] [0] = true; borderLine[129] [0] = true; borderLine[128] [0] = true; borderLine[127] [0] = true; borderLine[126] [0] = true; borderLine[125] [0] = true; borderLine[124] [0] = true; borderLine[123] [0] = true; borderLine[122] [0] = true; borderLine[121] [0] = true; borderLine[120] [0] = true; borderLine[119] [0] = true; borderLine[118] [0] = true; borderLine[117] [0] = true; borderLine[116] [0] = true; borderLine[115] [0] = true; borderLine[114] [0] = true; borderLine[113] [0] = true; borderLine[112] [0] = true; borderLine[111] [0] = true; borderLine[110] [0] = true; borderLine[109] [0] = true; borderLine[108] [0] = true; borderLine[107] [0] = true; borderLine[106] [0] = true; borderLine[105] [0] = true; borderLine[104] [0] = true; borderLine[103] [0] = true; borderLine[102] [0] = true; borderLine[101] [0] = true; borderLine[100] [0] = true; borderLine[99] [0] = true; borderLine[98] [0] = true; borderLine[97] [0] = true; borderLine[96] [0] = true; borderLine[95] [0] = true; borderLine[94] [0] = true; borderLine[93] [0] = true; borderLine[92] [0] = true; borderLine[91] [0] = true; borderLine[90] [0] = true; borderLine[89] [0] = true; borderLine[88] [0] = true; borderLine[87] [0] = true; borderLine[86] [0] = true; borderLine[85] [0] = true; borderLine[84] [0] = true; borderLine[83] [0] = true; borderLine[82] [0] = true; borderLine[81] [0] = true; borderLine[80] [0] = true; borderLine[79] [0] = true; borderLine[78] [0] = true; borderLine[77] [0] = true; borderLine[76] [0] = true; borderLine[75] [0] = true; borderLine[74] [0] = true; borderLine[73] [0] = true; borderLine[72] [0] = true; borderLine[71] [0] = true; borderLine[70] [0] = true; borderLine[69] [0] = true; borderLine[68] [0] = true; borderLine[67] [0] = true; borderLine[66] [0] = true; borderLine[65] [0] = true; borderLine[64] [0] = true; borderLine[63] [0] = true; borderLine[62] [0] = true; borderLine[61] [0] = true; borderLine[60] [0] = true; borderLine[59] [0] = true; borderLine[58] [0] = true; borderLine[57] [0] = true; borderLine[56] [0] = true; borderLine[55] [0] = true; borderLine[54] [0] = true; borderLine[53] [0] = true; borderLine[52] [0] = true; borderLine[51] [0] = true; borderLine[50] [0] = true; borderLine[49] [0] = true; borderLine[48] [0] = true; borderLine[47] [0] = true; borderLine[46] [0] = true; borderLine[45] [0] = true; borderLine[44] [0] = true; borderLine[43] [0] = true; borderLine[42] [0] = true; borderLine[41] [0] = true; borderLine[40] [0] = true; borderLine[202] [1] = true; borderLine[40] [1] = true; borderLine[202] [2] = true; borderLine[40] [2] = true; borderLine[202] [3] = true; borderLine[40] [3] = true; borderLine[202] [4] = true; borderLine[40] [4] = true; borderLine[202] [5] = true; borderLine[40] [5] = true; borderLine[202] [6] = true; borderLine[40] [6] = true; borderLine[202] [7] = true; borderLine[40] [7] = true; borderLine[202] [8] = true; borderLine[40] [8] = true; borderLine[202] [9] = true; borderLine[40] [9] = true; borderLine[202] [10] = true; borderLine[40] [10] = true; borderLine[202] [11] = true; borderLine[40] [11] = true; borderLine[202] [12] = true; borderLine[40] [12] = true; borderLine[202] [13] = true; borderLine[40] [13] = true; borderLine[202] [14] = true; borderLine[40] [14] = true; borderLine[202] [15] = true; borderLine[40] [15] = true; borderLine[202] [16] = true; borderLine[40] [16] = true; borderLine[202] [17] = true; borderLine[40] [17] = true; borderLine[202] [18] = true; borderLine[40] [18] = true; borderLine[202] [19] = true; borderLine[40] [19] = true; borderLine[202] [20] = true; borderLine[40] [20] = true; borderLine[202] [21] = true; borderLine[40] [21] = true; borderLine[202] [22] = true; borderLine[40] [22] = true; borderLine[202] [23] = true; borderLine[40] [23] = true; borderLine[202] [24] = true; borderLine[40] [24] = true; borderLine[202] [25] = true; borderLine[40] [25] = true; borderLine[202] [26] = true; borderLine[40] [26] = true; borderLine[202] [27] = true; borderLine[40] [27] = true; borderLine[202] [28] = true; borderLine[40] [28] = true; borderLine[202] [29] = true; borderLine[40] [29] = true; borderLine[202] [30] = true; borderLine[40] [30] = true; borderLine[202] [31] = true; borderLine[40] [31] = true; borderLine[202] [32] = true; borderLine[40] [32] = true; borderLine[202] [33] = true; borderLine[40] [33] = true; borderLine[202] [34] = true; borderLine[40] [34] = true; borderLine[202] [35] = true; borderLine[40] [35] = true; borderLine[202] [36] = true; borderLine[40] [36] = true; borderLine[202] [37] = true; borderLine[40] [37] = true; borderLine[202] [38] = true; borderLine[40] [38] = true; borderLine[202] [39] = true; borderLine[40] [39] = true; borderLine[202] [40] = true; borderLine[40] [40] = true; borderLine[202] [41] = true; borderLine[40] [41] = true; borderLine[202] [42] = true; borderLine[40] [42] = true; borderLine[202] [43] = true; borderLine[40] [43] = true; borderLine[202] [44] = true; borderLine[40] [44] = true; borderLine[202] [45] = true; borderLine[40] [45] = true; borderLine[202] [46] = true; borderLine[40] [46] = true; borderLine[202] [47] = true; borderLine[40] [47] = true; borderLine[202] [48] = true; borderLine[40] [48] = true; borderLine[202] [49] = true; borderLine[40] [49] = true; borderLine[202] [50] = true; borderLine[40] [50] = true; borderLine[202] [51] = true; borderLine[40] [51] = true; borderLine[202] [52] = true; borderLine[40] [52] = true; borderLine[202] [53] = true; borderLine[40] [53] = true; borderLine[202] [54] = true; borderLine[40] [54] = true; borderLine[202] [55] = true; borderLine[40] [55] = true; borderLine[202] [56] = true; borderLine[40] [56] = true; borderLine[202] [57] = true; borderLine[40] [57] = true; borderLine[202] [58] = true; borderLine[40] [58] = true; borderLine[202] [59] = true; borderLine[40] [59] = true; borderLine[202] [60] = true; borderLine[40] [60] = true; borderLine[202] [61] = true; borderLine[40] [61] = true; borderLine[202] [62] = true; borderLine[40] [62] = true; borderLine[202] [63] = true; borderLine[40] [63] = true; borderLine[202] [64] = true; borderLine[40] [64] = true; borderLine[202] [65] = true; borderLine[40] [65] = true; borderLine[202] [66] = true; borderLine[40] [66] = true; borderLine[202] [67] = true; borderLine[40] [67] = true; borderLine[202] [68] = true; borderLine[40] [68] = true; borderLine[202] [69] = true; borderLine[40] [69] = true; borderLine[202] [70] = true; borderLine[40] [70] = true; borderLine[202] [71] = true; borderLine[40] [71] = true; borderLine[202] [72] = true; borderLine[40] [72] = true; borderLine[202] [73] = true; borderLine[40] [73] = true; borderLine[202] [74] = true; borderLine[40] [74] = true; borderLine[202] [75] = true; borderLine[40] [75] = true; borderLine[202] [76] = true; borderLine[40] [76] = true; borderLine[202] [77] = true; borderLine[40] [77] = true; borderLine[202] [78] = true; borderLine[40] [78] = true; borderLine[202] [79] = true; borderLine[40] [79] = true; borderLine[202] [80] = true; borderLine[40] [80] = true; borderLine[202] [81] = true; borderLine[40] [81] = true; borderLine[202] [82] = true; borderLine[40] [82] = true; borderLine[202] [83] = true; borderLine[40] [83] = true; borderLine[202] [84] = true; borderLine[40] [84] = true; borderLine[202] [85] = true; borderLine[40] [85] = true; borderLine[202] [86] = true; borderLine[40] [86] = true; borderLine[202] [87] = true; borderLine[40] [87] = true; borderLine[202] [88] = true; borderLine[40] [88] = true; borderLine[202] [89] = true; borderLine[40] [89] = true; borderLine[202] [90] = true; borderLine[40] [90] = true; borderLine[202] [91] = true; borderLine[40] [91] = true; borderLine[202] [92] = true; borderLine[40] [92] = true; borderLine[202] [93] = true; borderLine[40] [93] = true; borderLine[202] [94] = true; borderLine[40] [94] = true; borderLine[202] [95] = true; borderLine[40] [95] = true; borderLine[202] [96] = true; borderLine[40] [96] = true; borderLine[202] [97] = true; borderLine[40] [97] = true; borderLine[202] [98] = true; borderLine[40] [98] = true; borderLine[202] [99] = true; borderLine[40] [99] = true; borderLine[202] [100] = true; borderLine[40] [100] = true; borderLine[202] [101] = true; borderLine[40] [101] = true; borderLine[202] [102] = true; borderLine[40] [102] = true; borderLine[202] [103] = true; borderLine[40] [103] = true; borderLine[202] [104] = true; borderLine[40] [104] = true; borderLine[202] [105] = true; borderLine[40] [105] = true; borderLine[202] [106] = true; borderLine[40] [106] = true; borderLine[202] [107] = true; borderLine[40] [107] = true; borderLine[202] [108] = true; borderLine[40] [108] = true; borderLine[202] [109] = true; borderLine[40] [109] = true; borderLine[202] [110] = true; borderLine[40] [110] = true; borderLine[202] [111] = true; borderLine[40] [111] = true; borderLine[202] [112] = true; borderLine[40] [112] = true; borderLine[202] [113] = true; borderLine[40] [113] = true; borderLine[202] [114] = true; borderLine[40] [114] = true; borderLine[202] [115] = true; borderLine[40] [115] = true; borderLine[202] [116] = true; borderLine[40] [116] = true; borderLine[202] [117] = true; borderLine[40] [117] = true; borderLine[202] [118] = true; borderLine[40] [118] = true; borderLine[202] [119] = true; borderLine[40] [119] = true; borderLine[202] [120] = true; borderLine[40] [120] = true; borderLine[202] [121] = true; borderLine[40] [121] = true; borderLine[202] [122] = true; borderLine[40] [122] = true; borderLine[202] [123] = true; borderLine[40] [123] = true; borderLine[202] [124] = true; borderLine[40] [124] = true; borderLine[202] [125] = true; borderLine[40] [125] = true; borderLine[202] [126] = true; borderLine[40] [126] = true; borderLine[202] [127] = true; borderLine[40] [127] = true; borderLine[202] [128] = true; borderLine[40] [128] = true; borderLine[202] [129] = true; borderLine[40] [129] = true; borderLine[202] [130] = true; borderLine[40] [130] = true; borderLine[202] [131] = true; borderLine[40] [131] = true; borderLine[202] [132] = true; borderLine[40] [132] = true; borderLine[202] [133] = true; borderLine[40] [133] = true; borderLine[202] [134] = true; borderLine[40] [134] = true; borderLine[202] [135] = true; borderLine[40] [135] = true; borderLine[202] [136] = true; borderLine[40] [136] = true; borderLine[202] [137] = true; borderLine[40] [137] = true; borderLine[202] [138] = true; borderLine[40] [138] = true; borderLine[202] [139] = true; borderLine[40] [139] = true; borderLine[202] [140] = true; borderLine[40] [140] = true; borderLine[202] [141] = true; borderLine[40] [141] = true; borderLine[202] [142] = true; borderLine[40] [142] = true; borderLine[202] [143] = true; borderLine[40] [143] = true; borderLine[202] [144] = true; borderLine[40] [144] = true; borderLine[202] [145] = true; borderLine[40] [145] = true; borderLine[202] [146] = true; borderLine[40] [146] = true; borderLine[202] [147] = true; borderLine[40] [147] = true; borderLine[202] [148] = true; borderLine[40] [148] = true; borderLine[202] [149] = true; borderLine[40] [149] = true; borderLine[202] [150] = true; borderLine[40] [150] = true; borderLine[202] [151] = true; borderLine[40] [151] = true; borderLine[202] [152] = true; borderLine[40] [152] = true; borderLine[202] [153] = true; borderLine[40] [153] = true; borderLine[202] [154] = true; borderLine[40] [154] = true; borderLine[202] [155] = true; borderLine[40] [155] = true; borderLine[202] [156] = true; borderLine[40] [156] = true; borderLine[202] [157] = true; borderLine[40] [157] = true; borderLine[202] [158] = true; borderLine[40] [158] = true; borderLine[202] [159] = true; borderLine[40] [159] = true; borderLine[202] [160] = true; borderLine[40] [160] = true; borderLine[202] [161] = true; borderLine[40] [161] = true; borderLine[202] [162] = true; borderLine[40] [162] = true; borderLine[202] [163] = true; borderLine[40] [163] = true; borderLine[202] [164] = true; borderLine[40] [164] = true; borderLine[202] [165] = true; borderLine[40] [165] = true; borderLine[202] [166] = true; borderLine[40] [166] = true; borderLine[202] [167] = true; borderLine[40] [167] = true; borderLine[202] [168] = true; borderLine[40] [168] = true; borderLine[202] [169] = true; borderLine[40] [169] = true; borderLine[202] [170] = true; borderLine[40] [170] = true; borderLine[202] [171] = true; borderLine[40] [171] = true; borderLine[203] [172] = true; borderLine[39] [172] = true; borderLine[204] [173] = true; borderLine[38] [173] = true; borderLine[205] [174] = true; borderLine[37] [174] = true; borderLine[206] [175] = true; borderLine[36] [175] = true; borderLine[207] [176] = true; borderLine[35] [176] = true; borderLine[208] [177] = true; borderLine[34] [177] = true; borderLine[209] [178] = true; borderLine[33] [178] = true; borderLine[210] [179] = true; borderLine[32] [179] = true; borderLine[211] [180] = true; borderLine[31] [180] = true; borderLine[212] [181] = true; borderLine[30] [181] = true; borderLine[213] [182] = true; borderLine[29] [182] = true; borderLine[214] [183] = true; borderLine[28] [183] = true; borderLine[215] [184] = true; borderLine[27] [184] = true; borderLine[216] [185] = true; borderLine[26] [185] = true; borderLine[217] [186] = true; borderLine[25] [186] = true; borderLine[218] [187] = true; borderLine[24] [187] = true; borderLine[219] [188] = true; borderLine[23] [188] = true; borderLine[220] [189] = true; borderLine[22] [189] = true; borderLine[221] [190] = true; borderLine[21] [190] = true; borderLine[222] [191] = true; borderLine[20] [191] = true; borderLine[223] [192] = true; borderLine[19] [192] = true; borderLine[224] [193] = true; borderLine[18] [193] = true; borderLine[225] [194] = true; borderLine[17] [194] = true; borderLine[226] [195] = true; borderLine[16] [195] = true; borderLine[227] [196] = true; borderLine[15] [196] = true; borderLine[228] [197] = true; borderLine[14] [197] = true; borderLine[229] [198] = true; borderLine[13] [198] = true; borderLine[230] [199] = true; borderLine[12] [199] = true; borderLine[231] [200] = true; borderLine[11] [200] = true; borderLine[232] [201] = true; borderLine[10] [201] = true; borderLine[233] [202] = true; borderLine[9] [202] = true; borderLine[234] [203] = true; borderLine[8] [203] = true; borderLine[235] [204] = true; borderLine[7] [204] = true; borderLine[236] [205] = true; borderLine[6] [205] = true; borderLine[237] [206] = true; borderLine[5] [206] = true; borderLine[238] [207] = true; borderLine[4] [207] = true; borderLine[239] [208] = true; borderLine[3] [208] = true; borderLine[240] [209] = true; borderLine[2] [209] = true; borderLine[241] [210] = true; borderLine[1] [210] = true; borderLine[242] [211] = true; borderLine[0] [211] = true; borderLine[242] [212] = true; borderLine[0] [212] = true; borderLine[242] [213] = true; borderLine[0] [213] = true; borderLine[242] [214] = true; borderLine[0] [214] = true; borderLine[242] [215] = true; borderLine[0] [215] = true; borderLine[242] [216] = true; borderLine[0] [216] = true; borderLine[242] [217] = true; borderLine[0] [217] = true; borderLine[242] [218] = true; borderLine[0] [218] = true; borderLine[242] [219] = true; borderLine[0] [219] = true; borderLine[242] [220] = true; borderLine[0] [220] = true; borderLine[242] [221] = true; borderLine[0] [221] = true; borderLine[242] [222] = true; borderLine[0] [222] = true; borderLine[242] [223] = true; borderLine[0] [223] = true; borderLine[242] [224] = true; borderLine[0] [224] = true; borderLine[242] [225] = true; borderLine[0] [225] = true; borderLine[242] [226] = true; borderLine[0] [226] = true; borderLine[242] [227] = true; borderLine[0] [227] = true; borderLine[242] [228] = true; borderLine[0] [228] = true; borderLine[242] [229] = true; borderLine[0] [229] = true; borderLine[242] [230] = true; borderLine[0] [230] = true; borderLine[242] [231] = true; borderLine[0] [231] = true; borderLine[242] [232] = true; borderLine[0] [232] = true; borderLine[242] [233] = true; borderLine[0] [233] = true; borderLine[242] [234] = true; borderLine[0] [234] = true; borderLine[242] [235] = true; borderLine[0] [235] = true; borderLine[242] [236] = true; borderLine[0] [236] = true; borderLine[242] [237] = true; borderLine[0] [237] = true; borderLine[242] [238] = true; borderLine[0] [238] = true; borderLine[242] [239] = true; borderLine[0] [239] = true; borderLine[242] [240] = true; borderLine[0] [240] = true; borderLine[242] [241] = true; borderLine[0] [241] = true; borderLine[242] [242] = true; borderLine[0] [242] = true; borderLine[242] [243] = true; borderLine[0] [243] = true; borderLine[242] [244] = true; borderLine[0] [244] = true; borderLine[242] [245] = true; borderLine[0] [245] = true; borderLine[242] [246] = true; borderLine[0] [246] = true; borderLine[242] [247] = true; borderLine[0] [247] = true; borderLine[242] [248] = true; borderLine[0] [248] = true; borderLine[242] [249] = true; borderLine[0] [249] = true; borderLine[242] [250] = true; borderLine[0] [250] = true; borderLine[242] [251] = true; borderLine[0] [251] = true; borderLine[242] [252] = true; borderLine[0] [252] = true; borderLine[242] [253] = true; borderLine[0] [253] = true; borderLine[242] [254] = true; borderLine[0] [254] = true; borderLine[242] [255] = true; borderLine[0] [255] = true; borderLine[242] [256] = true; borderLine[0] [256] = true; borderLine[242] [257] = true; borderLine[0] [257] = true; borderLine[242] [258] = true; borderLine[0] [258] = true; borderLine[242] [259] = true; borderLine[0] [259] = true; borderLine[242] [260] = true; borderLine[0] [260] = true; borderLine[242] [261] = true; borderLine[0] [261] = true; borderLine[242] [262] = true; borderLine[0] [262] = true; borderLine[242] [263] = true; borderLine[0] [263] = true; borderLine[242] [264] = true; borderLine[0] [264] = true; borderLine[242] [265] = true; borderLine[0] [265] = true; borderLine[242] [266] = true; borderLine[0] [266] = true; borderLine[242] [267] = true; borderLine[0] [267] = true; borderLine[242] [268] = true; borderLine[0] [268] = true; borderLine[242] [269] = true; borderLine[0] [269] = true; borderLine[242] [270] = true; borderLine[0] [270] = true; borderLine[242] [271] = true; borderLine[0] [271] = true; borderLine[242] [272] = true; borderLine[0] [272] = true; borderLine[242] [273] = true; borderLine[0] [273] = true; borderLine[242] [274] = true; borderLine[0] [274] = true; borderLine[242] [275] = true; borderLine[0] [275] = true; borderLine[242] [276] = true; borderLine[0] [276] = true; borderLine[242] [277] = true; borderLine[0] [277] = true; borderLine[242] [278] = true; borderLine[0] [278] = true; borderLine[242] [279] = true; borderLine[0] [279] = true; borderLine[242] [280] = true; borderLine[0] [280] = true; borderLine[242] [281] = true; borderLine[0] [281] = true; borderLine[242] [282] = true; borderLine[0] [282] = true; borderLine[242] [283] = true; borderLine[0] [283] = true; borderLine[242] [284] = true; borderLine[0] [284] = true; borderLine[242] [285] = true; borderLine[0] [285] = true; borderLine[242] [286] = true; borderLine[0] [286] = true; borderLine[242] [287] = true; borderLine[0] [287] = true; borderLine[242] [288] = true; borderLine[0] [288] = true; borderLine[242] [289] = true; borderLine[0] [289] = true; borderLine[242] [290] = true; borderLine[0] [290] = true; borderLine[242] [291] = true; borderLine[0] [291] = true; borderLine[242] [292] = true; borderLine[0] [292] = true; borderLine[242] [293] = true; borderLine[0] [293] = true; borderLine[242] [294] = true; borderLine[0] [294] = true; borderLine[242] [295] = true; borderLine[0] [295] = true; borderLine[242] [296] = true; borderLine[0] [296] = true; borderLine[242] [297] = true; borderLine[0] [297] = true; borderLine[242] [298] = true; borderLine[0] [298] = true; borderLine[242] [299] = true; borderLine[0] [299] = true; borderLine[242] [300] = true; borderLine[0] [300] = true; borderLine[242] [301] = true; borderLine[0] [301] = true; borderLine[242] [302] = true; borderLine[0] [302] = true; borderLine[242] [303] = true; borderLine[0] [303] = true; borderLine[242] [304] = true; borderLine[0] [304] = true; borderLine[242] [305] = true; borderLine[0] [305] = true; borderLine[242] [306] = true; borderLine[0] [306] = true; borderLine[242] [307] = true; borderLine[0] [307] = true; borderLine[242] [308] = true; borderLine[0] [308] = true; borderLine[242] [309] = true; borderLine[0] [309] = true; borderLine[242] [310] = true; borderLine[0] [310] = true; borderLine[242] [311] = true; borderLine[0] [311] = true; borderLine[242] [312] = true; borderLine[0] [312] = true; borderLine[242] [313] = true; borderLine[0] [313] = true; borderLine[242] [314] = true; borderLine[0] [314] = true; borderLine[242] [315] = true; borderLine[0] [315] = true; borderLine[242] [316] = true; borderLine[0] [316] = true; borderLine[242] [317] = true; borderLine[0] [317] = true; borderLine[242] [318] = true; borderLine[0] [318] = true; borderLine[242] [319] = true; borderLine[0] [319] = true; borderLine[242] [320] = true; borderLine[0] [320] = true; borderLine[242] [321] = true; borderLine[0] [321] = true; borderLine[242] [322] = true; borderLine[0] [322] = true; borderLine[242] [323] = true; borderLine[0] [323] = true; borderLine[242] [324] = true; borderLine[0] [324] = true; borderLine[242] [325] = true; borderLine[0] [325] = true; borderLine[242] [326] = true; borderLine[0] [326] = true; borderLine[242] [327] = true; borderLine[0] [327] = true; borderLine[242] [328] = true; borderLine[0] [328] = true; borderLine[242] [329] = true; borderLine[0] [329] = true; borderLine[242] [330] = true; borderLine[0] [330] = true; borderLine[242] [331] = true; borderLine[0] [331] = true; borderLine[242] [332] = true; borderLine[0] [332] = true; borderLine[242] [333] = true; borderLine[0] [333] = true; borderLine[242] [334] = true; borderLine[0] [334] = true; borderLine[242] [335] = true; borderLine[0] [335] = true; borderLine[242] [336] = true; borderLine[0] [336] = true; borderLine[242] [337] = true; borderLine[0] [337] = true; borderLine[242] [338] = true; borderLine[0] [338] = true; borderLine[242] [339] = true; borderLine[0] [339] = true; borderLine[242] [340] = true; borderLine[0] [340] = true; borderLine[242] [341] = true; borderLine[0] [341] = true; borderLine[242] [342] = true; borderLine[0] [342] = true; borderLine[242] [343] = true; borderLine[0] [343] = true; borderLine[242] [344] = true; borderLine[0] [344] = true; borderLine[242] [345] = true; borderLine[0] [345] = true; borderLine[242] [346] = true; borderLine[0] [346] = true; borderLine[242] [347] = true; borderLine[0] [347] = true; borderLine[242] [348] = true; borderLine[0] [348] = true; borderLine[242] [349] = true; borderLine[0] [349] = true; borderLine[242] [350] = true; borderLine[0] [350] = true; borderLine[242] [351] = true; borderLine[0] [351] = true; borderLine[242] [352] = true; borderLine[0] [352] = true; borderLine[242] [353] = true; borderLine[0] [353] = true; borderLine[242] [354] = true; borderLine[0] [354] = true; borderLine[242] [355] = true; borderLine[0] [355] = true; borderLine[242] [356] = true; borderLine[0] [356] = true; borderLine[242] [357] = true; borderLine[0] [357] = true; borderLine[242] [358] = true; borderLine[0] [358] = true; borderLine[242] [359] = true; borderLine[0] [359] = true; borderLine[242] [360] = true; borderLine[0] [360] = true; borderLine[242] [361] = true; borderLine[0] [361] = true; borderLine[242] [362] = true; borderLine[0] [362] = true; borderLine[242] [363] = true; borderLine[0] [363] = true; borderLine[242] [364] = true; borderLine[139] [364] = true; borderLine[138] [364] = true; borderLine[137] [364] = true; borderLine[136] [364] = true; borderLine[135] [364] = true; borderLine[134] [364] = true; borderLine[133] [364] = true; borderLine[132] [364] = true; borderLine[131] [364] = true; borderLine[130] [364] = true; borderLine[129] [364] = true; borderLine[128] [364] = true; borderLine[127] [364] = true; borderLine[126] [364] = true; borderLine[125] [364] = true; borderLine[124] [364] = true; borderLine[123] [364] = true; borderLine[122] [364] = true; borderLine[121] [364] = true; borderLine[120] [364] = true; borderLine[119] [364] = true; borderLine[118] [364] = true; borderLine[117] [364] = true; borderLine[116] [364] = true; borderLine[115] [364] = true; borderLine[114] [364] = true; borderLine[113] [364] = true; borderLine[112] [364] = true; borderLine[111] [364] = true; borderLine[110] [364] = true; borderLine[109] [364] = true; borderLine[108] [364] = true; borderLine[107] [364] = true; borderLine[106] [364] = true; borderLine[105] [364] = true; borderLine[104] [364] = true; borderLine[103] [364] = true; borderLine[102] [364] = true; borderLine[101] [364] = true; borderLine[100] [364] = true; borderLine[99] [364] = true; borderLine[98] [364] = true; borderLine[97] [364] = true; borderLine[96] [364] = true; borderLine[95] [364] = true; borderLine[94] [364] = true; borderLine[93] [364] = true; borderLine[92] [364] = true; borderLine[91] [364] = true; borderLine[90] [364] = true; borderLine[89] [364] = true; borderLine[88] [364] = true; borderLine[87] [364] = true; borderLine[86] [364] = true; borderLine[85] [364] = true; borderLine[0] [364] = true; borderLine[242] [365] = true; borderLine[139] [365] = true; borderLine[85] [365] = true; borderLine[0] [365] = true; borderLine[242] [366] = true; borderLine[139] [366] = true; borderLine[85] [366] = true; borderLine[0] [366] = true; borderLine[242] [367] = true; borderLine[139] [367] = true; borderLine[85] [367] = true; borderLine[0] [367] = true; borderLine[242] [368] = true; borderLine[139] [368] = true; borderLine[85] [368] = true; borderLine[0] [368] = true; borderLine[242] [369] = true; borderLine[139] [369] = true; borderLine[85] [369] = true; borderLine[0] [369] = true; borderLine[242] [370] = true; borderLine[139] [370] = true; borderLine[85] [370] = true; borderLine[0] [370] = true; borderLine[242] [371] = true; borderLine[139] [371] = true; borderLine[85] [371] = true; borderLine[0] [371] = true; borderLine[242] [372] = true; borderLine[139] [372] = true; borderLine[85] [372] = true; borderLine[0] [372] = true; borderLine[242] [373] = true; borderLine[139] [373] = true; borderLine[85] [373] = true; borderLine[0] [373] = true; borderLine[242] [374] = true; borderLine[139] [374] = true; borderLine[85] [374] = true; borderLine[0] [374] = true; borderLine[242] [375] = true; borderLine[139] [375] = true; borderLine[85] [375] = true; borderLine[0] [375] = true; borderLine[242] [376] = true; borderLine[139] [376] = true; borderLine[85] [376] = true; borderLine[0] [376] = true; borderLine[242] [377] = true; borderLine[139] [377] = true; borderLine[85] [377] = true; borderLine[0] [377] = true; borderLine[242] [378] = true; borderLine[139] [378] = true; borderLine[85] [378] = true; borderLine[0] [378] = true; borderLine[242] [379] = true; borderLine[139] [379] = true; borderLine[85] [379] = true; borderLine[0] [379] = true; borderLine[242] [380] = true; borderLine[139] [380] = true; borderLine[85] [380] = true; borderLine[0] [380] = true; borderLine[242] [381] = true; borderLine[139] [381] = true; borderLine[85] [381] = true; borderLine[0] [381] = true; borderLine[242] [382] = true; borderLine[139] [382] = true; borderLine[85] [382] = true; borderLine[0] [382] = true; borderLine[242] [383] = true; borderLine[139] [383] = true; borderLine[85] [383] = true; borderLine[0] [383] = true; borderLine[242] [384] = true; borderLine[139] [384] = true; borderLine[85] [384] = true; borderLine[0] [384] = true; borderLine[242] [385] = true; borderLine[139] [385] = true; borderLine[138] [385] = true; borderLine[137] [385] = true; borderLine[136] [385] = true; borderLine[135] [385] = true; borderLine[134] [385] = true; borderLine[133] [385] = true; borderLine[132] [385] = true; borderLine[131] [385] = true; borderLine[130] [385] = true; borderLine[129] [385] = true; borderLine[128] [385] = true; borderLine[127] [385] = true; borderLine[126] [385] = true; borderLine[125] [385] = true; borderLine[124] [385] = true; borderLine[123] [385] = true; borderLine[122] [385] = true; borderLine[121] [385] = true; borderLine[120] [385] = true; borderLine[119] [385] = true; borderLine[118] [385] = true; borderLine[117] [385] = true; borderLine[116] [385] = true; borderLine[115] [385] = true; borderLine[114] [385] = true; borderLine[113] [385] = true; borderLine[112] [385] = true; borderLine[111] [385] = true; borderLine[110] [385] = true; borderLine[109] [385] = true; borderLine[108] [385] = true; borderLine[107] [385] = true; borderLine[106] [385] = true; borderLine[105] [385] = true; borderLine[104] [385] = true; borderLine[103] [385] = true; borderLine[102] [385] = true; borderLine[101] [385] = true; borderLine[100] [385] = true; borderLine[99] [385] = true; borderLine[98] [385] = true; borderLine[97] [385] = true; borderLine[96] [385] = true; borderLine[95] [385] = true; borderLine[94] [385] = true; borderLine[93] [385] = true; borderLine[92] [385] = true; borderLine[91] [385] = true; borderLine[90] [385] = true; borderLine[89] [385] = true; borderLine[88] [385] = true; borderLine[87] [385] = true; borderLine[86] [385] = true; borderLine[85] [385] = true; borderLine[0] [385] = true; borderLine[242] [386] = true; borderLine[0] [386] = true; borderLine[242] [387] = true; borderLine[0] [387] = true; borderLine[242] [388] = true; borderLine[0] [388] = true; borderLine[242] [389] = true; borderLine[0] [389] = true; borderLine[242] [390] = true; borderLine[0] [390] = true; borderLine[242] [391] = true; borderLine[0] [391] = true; borderLine[242] [392] = true; borderLine[0] [392] = true; borderLine[242] [393] = true; borderLine[0] [393] = true; borderLine[242] [394] = true; borderLine[0] [394] = true; borderLine[242] [395] = true; borderLine[0] [395] = true; borderLine[242] [396] = true; borderLine[0] [396] = true; borderLine[242] [397] = true; borderLine[0] [397] = true; borderLine[242] [398] = true; borderLine[0] [398] = true; borderLine[242] [399] = true; borderLine[0] [399] = true; borderLine[242] [400] = true; borderLine[0] [400] = true; borderLine[242] [401] = true; borderLine[0] [401] = true; borderLine[242] [402] = true; borderLine[0] [402] = true; borderLine[242] [403] = true; borderLine[0] [403] = true; borderLine[242] [404] = true; borderLine[0] [404] = true; borderLine[242] [405] = true; borderLine[0] [405] = true; borderLine[242] [406] = true; borderLine[0] [406] = true; borderLine[242] [407] = true; borderLine[0] [407] = true; borderLine[242] [408] = true; borderLine[0] [408] = true; borderLine[242] [409] = true; borderLine[0] [409] = true; borderLine[242] [410] = true; borderLine[0] [410] = true; borderLine[242] [411] = true; borderLine[0] [411] = true; borderLine[242] [412] = true; borderLine[0] [412] = true; borderLine[242] [413] = true; borderLine[0] [413] = true; borderLine[242] [414] = true; borderLine[0] [414] = true; borderLine[242] [415] = true; borderLine[0] [415] = true; borderLine[242] [416] = true; borderLine[0] [416] = true; borderLine[242] [417] = true; borderLine[0] [417] = true; borderLine[242] [418] = true; borderLine[0] [418] = true; borderLine[242] [419] = true; borderLine[0] [419] = true; borderLine[242] [420] = true; borderLine[0] [420] = true; borderLine[242] [421] = true; borderLine[0] [421] = true; borderLine[242] [422] = true; borderLine[0] [422] = true; borderLine[242] [423] = true; borderLine[0] [423] = true; borderLine[242] [424] = true; borderLine[0] [424] = true; borderLine[242] [425] = true; borderLine[0] [425] = true; borderLine[242] [426] = true; borderLine[0] [426] = true; borderLine[242] [427] = true; borderLine[0] [427] = true; borderLine[242] [428] = true; borderLine[0] [428] = true; borderLine[242] [429] = true; borderLine[0] [429] = true; borderLine[242] [430] = true; borderLine[0] [430] = true; borderLine[242] [431] = true; borderLine[0] [431] = true; borderLine[242] [432] = true; borderLine[0] [432] = true; borderLine[242] [433] = true; borderLine[0] [433] = true; borderLine[242] [434] = true; borderLine[0] [434] = true; borderLine[242] [435] = true; borderLine[0] [435] = true; borderLine[242] [436] = true; borderLine[0] [436] = true; borderLine[242] [437] = true; borderLine[0] [437] = true; borderLine[242] [438] = true; borderLine[0] [438] = true; borderLine[242] [439] = true; borderLine[0] [439] = true; borderLine[242] [440] = true; borderLine[0] [440] = true; borderLine[242] [441] = true; borderLine[0] [441] = true; borderLine[242] [442] = true; borderLine[0] [442] = true; borderLine[242] [443] = true; borderLine[0] [443] = true; borderLine[242] [444] = true; borderLine[0] [444] = true; } private void Add2() { borderLine[242] [445] = true; borderLine[0] [445] = true; borderLine[242] [446] = true; borderLine[0] [446] = true; borderLine[242] [447] = true; borderLine[0] [447] = true; borderLine[242] [448] = true; borderLine[0] [448] = true; borderLine[242] [449] = true; borderLine[0] [449] = true; borderLine[242] [450] = true; borderLine[0] [450] = true; borderLine[242] [451] = true; borderLine[0] [451] = true; borderLine[242] [452] = true; borderLine[0] [452] = true; borderLine[242] [453] = true; borderLine[0] [453] = true; borderLine[242] [454] = true; borderLine[0] [454] = true; borderLine[242] [455] = true; borderLine[0] [455] = true; borderLine[242] [456] = true; borderLine[0] [456] = true; borderLine[242] [457] = true; borderLine[0] [457] = true; borderLine[242] [458] = true; borderLine[0] [458] = true; borderLine[242] [459] = true; borderLine[0] [459] = true; borderLine[242] [460] = true; borderLine[0] [460] = true; borderLine[242] [461] = true; borderLine[0] [461] = true; borderLine[242] [462] = true; borderLine[0] [462] = true; borderLine[242] [463] = true; borderLine[0] [463] = true; borderLine[242] [464] = true; borderLine[0] [464] = true; borderLine[242] [465] = true; borderLine[0] [465] = true; borderLine[242] [466] = true; borderLine[0] [466] = true; borderLine[242] [467] = true; borderLine[0] [467] = true; borderLine[242] [468] = true; borderLine[0] [468] = true; borderLine[242] [469] = true; borderLine[0] [469] = true; borderLine[242] [470] = true; borderLine[0] [470] = true; borderLine[242] [471] = true; borderLine[0] [471] = true; borderLine[242] [472] = true; borderLine[0] [472] = true; borderLine[242] [473] = true; borderLine[0] [473] = true; borderLine[242] [474] = true; borderLine[241] [474] = true; borderLine[240] [474] = true; borderLine[239] [474] = true; borderLine[238] [474] = true; borderLine[237] [474] = true; borderLine[236] [474] = true; borderLine[235] [474] = true; borderLine[234] [474] = true; borderLine[233] [474] = true; borderLine[232] [474] = true; borderLine[231] [474] = true; borderLine[230] [474] = true; borderLine[229] [474] = true; borderLine[228] [474] = true; borderLine[227] [474] = true; borderLine[226] [474] = true; borderLine[225] [474] = true; borderLine[224] [474] = true; borderLine[223] [474] = true; borderLine[222] [474] = true; borderLine[221] [474] = true; borderLine[220] [474] = true; borderLine[219] [474] = true; borderLine[218] [474] = true; borderLine[217] [474] = true; borderLine[216] [474] = true; borderLine[215] [474] = true; borderLine[214] [474] = true; borderLine[213] [474] = true; borderLine[212] [474] = true; borderLine[211] [474] = true; borderLine[210] [474] = true; borderLine[209] [474] = true; borderLine[208] [474] = true; borderLine[207] [474] = true; borderLine[206] [474] = true; borderLine[205] [474] = true; borderLine[204] [474] = true; borderLine[203] [474] = true; borderLine[202] [474] = true; borderLine[201] [474] = true; borderLine[200] [474] = true; borderLine[199] [474] = true; borderLine[198] [474] = true; borderLine[197] [474] = true; borderLine[196] [474] = true; borderLine[195] [474] = true; borderLine[194] [474] = true; borderLine[193] [474] = true; borderLine[192] [474] = true; borderLine[50] [474] = true; borderLine[49] [474] = true; borderLine[48] [474] = true; borderLine[47] [474] = true; borderLine[46] [474] = true; borderLine[45] [474] = true; borderLine[44] [474] = true; borderLine[43] [474] = true; borderLine[42] [474] = true; borderLine[41] [474] = true; borderLine[40] [474] = true; borderLine[39] [474] = true; borderLine[38] [474] = true; borderLine[37] [474] = true; borderLine[36] [474] = true; borderLine[35] [474] = true; borderLine[34] [474] = true; borderLine[33] [474] = true; borderLine[32] [474] = true; borderLine[31] [474] = true; borderLine[30] [474] = true; borderLine[29] [474] = true; borderLine[28] [474] = true; borderLine[27] [474] = true; borderLine[26] [474] = true; borderLine[25] [474] = true; borderLine[24] [474] = true; borderLine[23] [474] = true; borderLine[22] [474] = true; borderLine[21] [474] = true; borderLine[20] [474] = true; borderLine[19] [474] = true; borderLine[18] [474] = true; borderLine[17] [474] = true; borderLine[16] [474] = true; borderLine[15] [474] = true; borderLine[14] [474] = true; borderLine[13] [474] = true; borderLine[12] [474] = true; borderLine[11] [474] = true; borderLine[10] [474] = true; borderLine[9] [474] = true; borderLine[8] [474] = true; borderLine[7] [474] = true; borderLine[6] [474] = true; borderLine[5] [474] = true; borderLine[4] [474] = true; borderLine[3] [474] = true; borderLine[2] [474] = true; borderLine[1] [474] = true; borderLine[0] [474] = true; borderLine[192] [475] = true; borderLine[50] [475] = true; borderLine[192] [476] = true; borderLine[50] [476] = true; borderLine[192] [477] = true; borderLine[50] [477] = true; borderLine[192] [478] = true; borderLine[50] [478] = true; borderLine[192] [479] = true; borderLine[50] [479] = true; borderLine[192] [480] = true; borderLine[50] [480] = true; borderLine[192] [481] = true; borderLine[50] [481] = true; borderLine[192] [482] = true; borderLine[50] [482] = true; borderLine[192] [483] = true; borderLine[50] [483] = true; borderLine[192] [484] = true; borderLine[50] [484] = true; borderLine[192] [485] = true; borderLine[50] [485] = true; borderLine[192] [486] = true; borderLine[50] [486] = true; borderLine[192] [487] = true; borderLine[50] [487] = true; borderLine[192] [488] = true; borderLine[50] [488] = true; borderLine[192] [489] = true; borderLine[50] [489] = true; borderLine[192] [490] = true; borderLine[50] [490] = true; borderLine[192] [491] = true; borderLine[50] [491] = true; borderLine[192] [492] = true; borderLine[50] [492] = true; borderLine[192] [493] = true; borderLine[50] [493] = true; borderLine[192] [494] = true; borderLine[50] [494] = true; borderLine[192] [495] = true; borderLine[50] [495] = true; borderLine[192] [496] = true; borderLine[50] [496] = true; borderLine[192] [497] = true; borderLine[50] [497] = true; borderLine[192] [498] = true; borderLine[50] [498] = true; borderLine[192] [499] = true; borderLine[50] [499] = true; borderLine[192] [500] = true; borderLine[50] [500] = true; borderLine[192] [501] = true; borderLine[50] [501] = true; borderLine[192] [502] = true; borderLine[50] [502] = true; borderLine[192] [503] = true; borderLine[50] [503] = true; borderLine[192] [504] = true; borderLine[50] [504] = true; borderLine[192] [505] = true; borderLine[50] [505] = true; borderLine[192] [506] = true; borderLine[50] [506] = true; borderLine[192] [507] = true; borderLine[50] [507] = true; borderLine[192] [508] = true; borderLine[50] [508] = true; borderLine[192] [509] = true; borderLine[50] [509] = true; borderLine[192] [510] = true; borderLine[50] [510] = true; borderLine[192] [511] = true; borderLine[50] [511] = true; borderLine[192] [512] = true; borderLine[50] [512] = true; borderLine[192] [513] = true; borderLine[50] [513] = true; borderLine[192] [514] = true; borderLine[50] [514] = true; borderLine[192] [515] = true; borderLine[50] [515] = true; borderLine[192] [516] = true; borderLine[50] [516] = true; borderLine[192] [517] = true; borderLine[50] [517] = true; borderLine[192] [518] = true; borderLine[50] [518] = true; borderLine[192] [519] = true; borderLine[50] [519] = true; borderLine[192] [520] = true; borderLine[50] [520] = true; borderLine[192] [521] = true; borderLine[50] [521] = true; borderLine[192] [522] = true; borderLine[50] [522] = true; borderLine[192] [523] = true; borderLine[50] [523] = true; borderLine[192] [524] = true; borderLine[50] [524] = true; borderLine[192] [525] = true; borderLine[50] [525] = true; borderLine[192] [526] = true; borderLine[50] [526] = true; borderLine[192] [527] = true; borderLine[50] [527] = true; borderLine[192] [528] = true; borderLine[50] [528] = true; borderLine[192] [529] = true; borderLine[50] [529] = true; borderLine[192] [530] = true; borderLine[50] [530] = true; borderLine[192] [531] = true; borderLine[50] [531] = true; borderLine[192] [532] = true; borderLine[50] [532] = true; borderLine[192] [533] = true; borderLine[50] [533] = true; borderLine[192] [534] = true; borderLine[50] [534] = true; borderLine[192] [535] = true; borderLine[50] [535] = true; borderLine[192] [536] = true; borderLine[50] [536] = true; borderLine[192] [537] = true; borderLine[50] [537] = true; borderLine[192] [538] = true; borderLine[50] [538] = true; borderLine[192] [539] = true; borderLine[50] [539] = true; borderLine[192] [540] = true; borderLine[50] [540] = true; borderLine[192] [541] = true; borderLine[50] [541] = true; borderLine[192] [542] = true; borderLine[50] [542] = true; } }
package ro.teamnet.ldap.security; import org.springframework.security.core.userdetails.UserDetails; /** * Created by Marian.Spoiala on 9/23/2015. */ public interface LDAPUserDetailsService { public UserDetails loadUserDetails(String userName, String password); }
package pe.edu.sise.ejemplosqlitatareas; import android.database.SQLException; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class Item extends AppCompatActivity { TextView item = null; TextView place = null; TextView description = null; TextView importance = null; Integer rowId = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item); Button saveBtn = (Button) findViewById(R.id.add); saveBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_OK); saveData(); finish(); } }); // obtener referencias item = (TextView) findViewById(R.id.item); place = (TextView) findViewById(R.id.plaece); description = (TextView) findViewById(R.id.description); importance = (TextView) findViewById(R.id.importance); } protected void saveData() { String itemText = item.getText().toString(); String placeText = place.getText().toString(); String descriptionText = description.getText().toString(); String importanceText = importance.getText().toString(); try{ MainActivity.mDbHelper.open(); MainActivity.mDbHelper.insertItem(itemText, placeText, descriptionText, Integer.parseInt(importanceText)); MainActivity.mDbHelper.close(); }catch (SQLException e){ e.printStackTrace(); showMessage(e.getLocalizedMessage()); } } private void showMessage(String message){ Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG ).show(); } }