repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
sav007/apollo-android | apollo-api/src/main/java/com/apollographql/apollo/api/Mutation.java | 240 | package com.apollographql.apollo.api;
/**
* Represents a GraphQL mutation operation that will be sent to the server.
*/
public interface Mutation<D extends Operation.Data, T, V extends Operation.Variables> extends Operation<D, T, V> {
}
| mit |
NESCent/Phylontal | src/libsource/org/ethontos/phylontal/project/phylo/impl/PredicateHandlerImpl.java | 2529 | /*
* Phylontal - a tool for phylogenetic alignment of ontologies
* Copyright 2009-2011 Peter E. Midford
*
* This file is part of Phylontal.
*
* Phylontal is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Phylontal is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Phylontal. If not, see <http://www.gnu.org/licenses/>.
*
* Created on Oct 12, 2009
* Last updated on April 27, 2011
*
*/
package org.ethontos.phylontal.project.phylo.impl;
/**
* A callback for the NeXML reader - is this necessary?
* @author peter
* created Oct 12, 2009
*
*/
public class PredicateHandlerImpl extends PredicateHandler {
private String mPredicate;
private String mPrefix = "poa";
private boolean mPropertyIsRel;
private Object mValue;
private String mProperty;
private Object mSubject;
public PredicateHandlerImpl(Object subject, String predicate, Object value) {
super(subject, predicate, value);
}
@Override
void setPredicate(String predicate) {
mPredicate = predicate;
}
@Override
String getPredicate() {
return mPredicate;
}
@Override
void setPrefix(String prefix) {
mPrefix = prefix;
}
@Override
String getPrefix() {
return mPrefix;
}
@Override
void setPropertyIsRel(boolean propertyIsRel) {
mPropertyIsRel = propertyIsRel;
}
@Override
boolean getPropertyIsRel() {
return mPropertyIsRel;
}
@Override
String getURIString() {
return "http://ethontos.org#";
}
@Override
public
Object getValue() {
return mValue;
}
@Override
public
void setValue(Object value) {
mValue = value;
}
public String getRel() {
return getProperty();
}
public void setRel(String rel) {
setProperty(rel);
setPropertyIsRel(true);
}
public String getProperty() {
if ( null != mProperty ) {
return mProperty;
}
else {
return getPrefix() + ":" + getPredicate();
}
}
public void setProperty(String property) {
mProperty = property;
}
public Object getSubject() {
return mSubject;
}
public void setSubject(Object subject) {
mSubject = subject;
}
}
| mit |
ypxu87/listener | android/app/src/main/java/com/listener/MainActivity.java | 361 | package com.listener;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "listener";
}
}
| mit |
kercos/TreeGrammars | TreeGrammars/src/kernels/parallel/ted/ParallelSentenceAnnotationsAggregation.java | 5257 | package kernels.parallel.ted;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map.Entry;
import java.util.HashSet;
import java.util.TreeMap;
import java.util.Vector;
import kernels.algo.StringsAlignment;
import kernels.parallel.CheckGaps;
import kernels.parallel.ParallelSubstrings;
import util.IdentityArrayList;
import util.Utility;
/*
* 62 fields (76 if MWE8 is not filled)
*
* 0: SNT#
* 1: SOURCE (EN)
* 2: MANUAL
* 3: AUTO
* 4: DONE?
* 5-10: MWE1
* 5: SOURCE-TEXT
* 6: MANUAL-TEXT
* 7: MANUAL-CHECK
* 8: CORRECT
* 9: AUTO-TEXT
* 10: AUTO-CHECK
* 11-16: MWE2
* 17-22: MWE3
* 23-28: MWE4
* 29-44: MWE5
* 45-50: MWE6
* 51-56: MWE7
* 57-62: MWE8
*/
public class ParallelSentenceAnnotationsAggregation {
//sentenceNumber -> ParallelSentence
int sentenceNumber;
String sourceSentence;
String manualTranslation;
String autoTranslation;
Vector<AnnotatedMWE> annotations = new Vector<AnnotatedMWE>();
// annotatorNumber -> annotations
public class AnnotatedMWE {
boolean manualCheck;
String sourceSentenceMWE, manualTranslationMWE;
String manualCorrection; //if manualCheck==false
String autoTranslationMWE;
boolean autoCheck;
public int hashCode() {
return manualCorrection.hashCode();
}
public String toString() {
return sourceSentenceMWE + " -> " + manualTranslationMWE + "|" + autoCheck;
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(sourceSentence);
sb.append('\n');
sb.append(manualTranslation);
for(AnnotatedMWE a : annotations) {
sb.append("\n\t");
sb.append(a);
}
sb.append('\n');
return sb.toString();
}
public ParallelSentenceAnnotationsAggregation(String[] fields) {
sentenceNumber = Integer.parseInt(fields[0].trim());
sourceSentence = fields[1].trim();
manualTranslation = fields[2].trim();
autoTranslation = fields[3].trim();
addAnnotationLine(fields);
}
public boolean addAnnotationLine(String[] fields) {
boolean done = isYes(fields[4]);
if (!done) {
return false;
}
annotations = new Vector<ParallelSentenceAnnotationsAggregation.AnnotatedMWE>();
int fieldIndex = 5;
for(int i=0; i<8; i++) { //max 8 mwe per sentence
String mwe_sourceSentence = fields[fieldIndex].trim();
if (mwe_sourceSentence.isEmpty())
break;
ParallelSentenceAnnotationsAggregation.AnnotatedMWE an = new AnnotatedMWE();
an.sourceSentenceMWE = mwe_sourceSentence.toLowerCase(); //5
fieldIndex++;
an.manualTranslationMWE = fields[fieldIndex].trim().toLowerCase(); //6
fieldIndex++;
an.manualCheck = isYes(fields[fieldIndex]); //7
fieldIndex++;
if (!an.manualCheck) { //if manualCheck=="N"
an.manualCorrection = fields[fieldIndex].trim().toLowerCase(); //8
}
fieldIndex++;
an.autoTranslationMWE = fields[fieldIndex].trim().toLowerCase(); //9
fieldIndex++;
an.autoCheck = isYes(fields[fieldIndex]); //10
fieldIndex++;
annotations.add(an);
}
return true;
}
private static boolean isYes(String s) {
return s.trim().toUpperCase().startsWith("Y");
}
public void reportAllAnnotations(PrintWriter pw) {
pw.println();
pw.println("Sentence: " + this.sentenceNumber);
pw.println("\t" + "Source: " + this.sourceSentence);
pw.println("\t" + " MWE(s)" + "\t->\t" + annotations.size() + "\t" + annotations);
}
public HashMap<ArrayList<Integer>, int[]> buildCheckPresenceSourceReport(
PrintWriter pw, int[] counts, int[] sizes) {
// counts
// 0: present contiguous
// 1: present gaps
// 2: MT correct
// 3: total
HashMap<ArrayList<Integer>, int[]> mweFreq = new HashMap<ArrayList<Integer>, int[]>();
StringBuilder sb = new StringBuilder();
String[] snt = ParallelSubstrings.getInternedArrya(this.sourceSentence, "\\s+");
sb.append(this.sentenceNumber + "\n");
sb.append("\t" + "Source: " + this.sourceSentence + "\n");
boolean foundMistake = false;
for(AnnotatedMWE mwe : annotations) {
counts[3]++;
String expString = mwe.sourceSentenceMWE;
expString = expString.replaceAll("\\.\\.\\.", " ");
//expString = expString.replaceAll("'re", " 're");
//expString = expString.replaceAll("'s", " 's");
expString = expString.toLowerCase();
String[] expArray = expString.split("\\s+");
IdentityArrayList<String> exp = ParallelSubstrings.getIdentityArrayList(expString, "\\s+");
ArrayList<Integer> indexes = null;
if (CheckGaps.checkPresence(snt, exp)) {
if (CheckGaps.hasGap(snt, exp)) {
counts[1]++;
indexes = StringsAlignment.getBestIndexAlignemnt(expArray, snt);
}
else {
//contiguous
counts[0]++;
indexes = CheckGaps.getContiguousIndexes(snt,exp);
}
Utility.increaseInHashMap(mweFreq, indexes);
sizes[indexes.size()]++;
}
else {
foundMistake = true;
sb.append("\t\t" + mwe.sourceSentenceMWE + "\n");
}
if (mwe.autoCheck) {
// correctly translated by
counts[2]++;
}
}
if (foundMistake) {
pw.println(sb);
pw.println();
}
return mweFreq;
}
}
| mit |
networkdowntime/EmbeddableSearch | src/test/java/net/networkdowntime/search/text/processing/TextScrubberTest.java | 866 | package net.networkdowntime.search.text.processing;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import net.networkdowntime.search.text.processing.HtmlTagTextScrubber;
import net.networkdowntime.search.text.processing.TextScrubber;
public class TextScrubberTest {
TextScrubber textScrubber = new HtmlTagTextScrubber();
@Before
public void setUp() throws Exception {
}
@Test
public void testNoChange() {
String text = "The! [quick? brown] & fox. (3.1415) Jumps, {over; the:lazy} dog.";
assertEquals(text, textScrubber.scrubText(text));
}
@Test
public void testRemoveHtmlTag() {
String text = "The! [quick? <div class=\"foo\">brown</div>] & fox. (3.1415) Jumps, {over; the:lazy} dog.";
assertEquals("The! [quick? brown ] & fox. (3.1415) Jumps, {over; the:lazy} dog.", textScrubber.scrubText(text));
}
}
| mit |
bomrastreio/bomrastreio | api/src/main/java/br/com/bomrastreio/api/correios/trace/TraceStatus.java | 7853 | package br.com.bomrastreio.api.correios.trace;
import br.com.bomrastreio.api.object.ObjectStatus;
public enum TraceStatus {
UND_00(ObjectStatus.UNDEFINED),
BDE_00(ObjectStatus.DELIVERED),
BDE_01(ObjectStatus.DELIVERED),
BDE_02(ObjectStatus.ACTION_REQUIRED),
BDE_03(ObjectStatus.DELAYED),
BDE_04(ObjectStatus.DELAYED),
BDE_05(ObjectStatus.DELAYED),
BDE_06(ObjectStatus.DELAYED),
BDE_07(ObjectStatus.IN_TRANSIT),
BDE_08(ObjectStatus.DELAYED),
BDE_09(ObjectStatus.ACTION_REQUIRED),
BDE_10(ObjectStatus.DELAYED),
BDE_12(ObjectStatus.ACTION_REQUIRED),
BDE_19(ObjectStatus.DELAYED),
BDE_20(ObjectStatus.DELAYED),
BDE_21(ObjectStatus.DELAYED),
BDE_22(ObjectStatus.DELAYED),
BDE_23(ObjectStatus.DELAYED),
BDE_24(ObjectStatus.DELAYED),
BDE_25(ObjectStatus.DELAYED),
BDE_26(ObjectStatus.DELAYED),
BDE_28(ObjectStatus.ACTION_REQUIRED),
BDE_32(ObjectStatus.DELAYED),
BDE_33(ObjectStatus.DELAYED),
BDE_34(ObjectStatus.DELAYED),
BDE_35(ObjectStatus.DELAYED),
BDE_36(ObjectStatus.DELAYED),
BDE_37(ObjectStatus.ACTION_REQUIRED),
BDE_38(ObjectStatus.IN_TRANSIT),
BDE_40(ObjectStatus.DELAYED),
BDE_41(ObjectStatus.IN_TRANSIT),
BDE_42(ObjectStatus.DELAYED),
BDE_43(ObjectStatus.ACTION_REQUIRED),
BDE_45(ObjectStatus.IN_TRANSIT),
BDE_46(ObjectStatus.IN_TRANSIT),
BDE_47(ObjectStatus.IN_TRANSIT),
BDE_48(ObjectStatus.DELAYED),
BDE_49(ObjectStatus.DELAYED),
BDE_50(ObjectStatus.ACTION_REQUIRED),
BDE_51(ObjectStatus.ACTION_REQUIRED),
BDE_52(ObjectStatus.ACTION_REQUIRED),
BDE_53(ObjectStatus.IN_TRANSIT),
BDE_54(ObjectStatus.ACTION_REQUIRED),
BDE_55(ObjectStatus.IN_TRANSIT),
BDE_56(ObjectStatus.DELAYED),
BDE_57(ObjectStatus.IN_TRANSIT),
BDE_58(ObjectStatus.IN_TRANSIT),
BDE_59(ObjectStatus.IN_TRANSIT),
BDE_66(ObjectStatus.IN_TRANSIT),
BDE_69(ObjectStatus.IN_TRANSIT),
BDI_00(ObjectStatus.DELIVERED),
BDI_01(ObjectStatus.DELIVERED),
BDI_02(ObjectStatus.ACTION_REQUIRED),
BDI_03(ObjectStatus.DELAYED),
BDI_04(ObjectStatus.DELAYED),
BDI_05(ObjectStatus.DELAYED),
BDI_06(ObjectStatus.DELAYED),
BDI_07(ObjectStatus.IN_TRANSIT),
BDI_08(ObjectStatus.DELAYED),
BDI_09(ObjectStatus.ACTION_REQUIRED),
BDI_10(ObjectStatus.DELAYED),
BDI_12(ObjectStatus.ACTION_REQUIRED),
BDI_19(ObjectStatus.DELAYED),
BDI_20(ObjectStatus.DELAYED),
BDI_21(ObjectStatus.DELAYED),
BDI_22(ObjectStatus.DELAYED),
BDI_23(ObjectStatus.DELAYED),
BDI_24(ObjectStatus.DELAYED),
BDI_25(ObjectStatus.DELAYED),
BDI_26(ObjectStatus.DELAYED),
BDI_28(ObjectStatus.ACTION_REQUIRED),
BDI_32(ObjectStatus.DELAYED),
BDI_33(ObjectStatus.DELAYED),
BDI_34(ObjectStatus.DELAYED),
BDI_35(ObjectStatus.DELAYED),
BDI_36(ObjectStatus.DELAYED),
BDI_37(ObjectStatus.ACTION_REQUIRED),
BDI_38(ObjectStatus.IN_TRANSIT),
BDI_40(ObjectStatus.DELAYED),
BDI_41(ObjectStatus.IN_TRANSIT),
BDI_42(ObjectStatus.DELAYED),
BDI_43(ObjectStatus.ACTION_REQUIRED),
BDI_45(ObjectStatus.IN_TRANSIT),
BDI_46(ObjectStatus.IN_TRANSIT),
BDI_47(ObjectStatus.IN_TRANSIT),
BDI_48(ObjectStatus.DELAYED),
BDI_49(ObjectStatus.DELAYED),
BDI_50(ObjectStatus.ACTION_REQUIRED),
BDI_51(ObjectStatus.ACTION_REQUIRED),
BDI_52(ObjectStatus.ACTION_REQUIRED),
BDI_53(ObjectStatus.IN_TRANSIT),
BDI_54(ObjectStatus.ACTION_REQUIRED),
BDI_55(ObjectStatus.IN_TRANSIT),
BDI_56(ObjectStatus.DELAYED),
BDI_57(ObjectStatus.IN_TRANSIT),
BDI_58(ObjectStatus.IN_TRANSIT),
BDI_59(ObjectStatus.IN_TRANSIT),
BDI_66(ObjectStatus.IN_TRANSIT),
BDI_69(ObjectStatus.IN_TRANSIT),
BDR_00(ObjectStatus.DELIVERED),
BDR_01(ObjectStatus.DELIVERED),
BDR_02(ObjectStatus.ACTION_REQUIRED),
BDR_03(ObjectStatus.DELAYED),
BDR_04(ObjectStatus.DELAYED),
BDR_05(ObjectStatus.DELAYED),
BDR_06(ObjectStatus.DELAYED),
BDR_07(ObjectStatus.IN_TRANSIT),
BDR_08(ObjectStatus.DELAYED),
BDR_09(ObjectStatus.ACTION_REQUIRED),
BDR_10(ObjectStatus.DELAYED),
BDR_12(ObjectStatus.ACTION_REQUIRED),
BDR_19(ObjectStatus.DELAYED),
BDR_20(ObjectStatus.DELAYED),
BDR_21(ObjectStatus.DELAYED),
BDR_22(ObjectStatus.DELAYED),
BDR_23(ObjectStatus.DELAYED),
BDR_24(ObjectStatus.DELAYED),
BDR_25(ObjectStatus.DELAYED),
BDR_26(ObjectStatus.DELAYED),
BDR_28(ObjectStatus.ACTION_REQUIRED),
BDR_32(ObjectStatus.DELAYED),
BDR_33(ObjectStatus.DELAYED),
BDR_34(ObjectStatus.DELAYED),
BDR_35(ObjectStatus.DELAYED),
BDR_36(ObjectStatus.DELAYED),
BDR_37(ObjectStatus.ACTION_REQUIRED),
BDR_38(ObjectStatus.IN_TRANSIT),
BDR_40(ObjectStatus.DELAYED),
BDR_41(ObjectStatus.IN_TRANSIT),
BDR_42(ObjectStatus.DELAYED),
BDR_43(ObjectStatus.ACTION_REQUIRED),
BDR_45(ObjectStatus.IN_TRANSIT),
BDR_46(ObjectStatus.IN_TRANSIT),
BDR_47(ObjectStatus.IN_TRANSIT),
BDR_48(ObjectStatus.DELAYED),
BDR_49(ObjectStatus.DELAYED),
BDR_50(ObjectStatus.ACTION_REQUIRED),
BDR_51(ObjectStatus.ACTION_REQUIRED),
BDR_52(ObjectStatus.ACTION_REQUIRED),
BDR_53(ObjectStatus.IN_TRANSIT),
BDR_54(ObjectStatus.ACTION_REQUIRED),
BDR_55(ObjectStatus.IN_TRANSIT),
BDR_56(ObjectStatus.DELAYED),
BDR_57(ObjectStatus.IN_TRANSIT),
BDR_58(ObjectStatus.IN_TRANSIT),
BDR_59(ObjectStatus.IN_TRANSIT),
BDR_66(ObjectStatus.IN_TRANSIT),
BDR_69(ObjectStatus.IN_TRANSIT),
BLQ_01(ObjectStatus.IN_TRANSIT),
CD_00(ObjectStatus.IN_TRANSIT),
CD_01(ObjectStatus.IN_TRANSIT),
CD_02(ObjectStatus.IN_TRANSIT),
CD_03(ObjectStatus.IN_TRANSIT),
CMT_00(ObjectStatus.IN_TRANSIT),
CO_01(ObjectStatus.IN_TRANSIT),
CUN_00(ObjectStatus.IN_TRANSIT),
CUN_01(ObjectStatus.IN_TRANSIT),
DO_00(ObjectStatus.IN_TRANSIT),
DO_01(ObjectStatus.IN_TRANSIT),
DO_02(ObjectStatus.IN_TRANSIT),
EST_01(ObjectStatus.IN_TRANSIT),
EST_02(ObjectStatus.IN_TRANSIT),
EST_03(ObjectStatus.IN_TRANSIT),
EST_04(ObjectStatus.IN_TRANSIT),
EST_05(ObjectStatus.IN_TRANSIT),
EST_06(ObjectStatus.IN_TRANSIT),
EST_09(ObjectStatus.IN_TRANSIT),
FC_01(ObjectStatus.DELAYED),
FC_02(ObjectStatus.IN_TRANSIT),
FC_03(ObjectStatus.IN_TRANSIT),
FC_04(ObjectStatus.IN_TRANSIT),
FC_05(ObjectStatus.IN_TRANSIT),
FC_07(ObjectStatus.IN_TRANSIT),
IDC_01(ObjectStatus.IN_TRANSIT),
IDC_02(ObjectStatus.IN_TRANSIT),
IDC_03(ObjectStatus.IN_TRANSIT),
IDC_04(ObjectStatus.IN_TRANSIT),
IDC_05(ObjectStatus.IN_TRANSIT),
IDC_06(ObjectStatus.IN_TRANSIT),
IDC_07(ObjectStatus.IN_TRANSIT),
LDE_00(ObjectStatus.IN_TRANSIT),
LDI_00(ObjectStatus.ACTION_REQUIRED),
LDI_01(ObjectStatus.ACTION_REQUIRED),
LDI_02(ObjectStatus.ACTION_REQUIRED),
LDI_03(ObjectStatus.ACTION_REQUIRED),
LDI_14(ObjectStatus.ACTION_REQUIRED),
OEC_00(ObjectStatus.ACTION_REQUIRED),
OEC_01(ObjectStatus.IN_TRANSIT),
OEC_09(ObjectStatus.IN_TRANSIT),
PAR_15(ObjectStatus.IN_TRANSIT),
PAR_16(ObjectStatus.IN_TRANSIT),
PAR_17(ObjectStatus.IN_TRANSIT),
PAR_18(ObjectStatus.IN_TRANSIT),
PMT_01(ObjectStatus.IN_TRANSIT),
PO_00(ObjectStatus.IN_TRANSIT),
PO_01(ObjectStatus.IN_TRANSIT),
PO_09(ObjectStatus.IN_TRANSIT),
RO_00(ObjectStatus.IN_TRANSIT),
RO_01(ObjectStatus.IN_TRANSIT),
TRI_00(ObjectStatus.IN_TRANSIT);
private ObjectStatus objectStatus;
TraceStatus(ObjectStatus objectStatus) {
this.objectStatus = objectStatus;
}
public ObjectStatus getObjectStatus() {
return objectStatus;
}
/**
* Find a tracking object status from the joining of type and status.
* If wasn't found any status, the default will be {@link ObjectStatus#UNDEFINED}.
*
* @param type Trace response type
* @param status Trace status number
* @return ObjectStatus
*/
public static TraceStatus of(String type, String status) {
String traceStatusName = type + "_" + status;
TraceStatus traceStatus;
try {
traceStatus = TraceStatus.valueOf(traceStatusName);
} catch (Exception ex) {
traceStatus = TraceStatus.UND_00;
}
return traceStatus;
}
}
| mit |
SukruOzturk42/TeknoGarage | src/main/java/com/musu/repository/OrderDetailsRepository.java | 495 | package com.musu.repository;
import com.musu.model.OrderDetailsEntity;
import com.musu.model.OrdersEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface OrderDetailsRepository extends JpaRepository<OrderDetailsEntity, Long>{
@Query(value = "select d from OrderDetailsEntity d where d.ordersEntity.orderId=?1")
List<OrderDetailsEntity> findDetailsbyOrderID(int orderID);
}
| mit |
FlorisE/idMirror | app/src/main/java/tsukuba/emp/mirrorgl/util/Constants.java | 835 | package tsukuba.emp.mirrorgl.util;
public class Constants {
/**
* The amount of cells rendered per column and per row, e.g. BUFFER_NN = 40 implies a 40X40 grid
*/
public static final int BUFFER_NN = 40;
/**
* The time it takes for the effect to fade in and fade out
*/
public static final int FADE_TIME = 5000;
/**
* After how much time a picture will be taken
*/
public static final int PICTURE_TIME = 2000;
/**
* The duration of the interaction, excluding fade in/fade out time. Set to -1 for infinite
*/
public static final int INTERACTION_TIME = 10000;
/**
* Only draw cells which are located in an ellipse area, used when covering part of the screen with the
* idMirror shell
*/
public static final boolean DRAW_ELLIPSE = true;
}
| mit |
habibmasuro/XChange | xchange-openexchangerates/src/main/java/com/xeiam/xchange/oer/OER.java | 1626 | /**
* Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.xeiam.xchange.oer;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.xeiam.xchange.oer.dto.marketdata.OERTickers;
/**
* @author timmolter
*/
@Path("api")
@Produces(MediaType.APPLICATION_JSON)
public interface OER {
@GET
@Path("latest.json")
public OERTickers getTickers(@QueryParam("app_id") String appId) throws IOException;
}
| mit |
eug/imageio-pnm | src/main/java/eugfc/imageio/plugins/ppm/PPMImageReaderSpi.java | 1419 |
package eugfc.imageio.plugins.ppm;
import eugfc.imageio.plugins.AbstractImageReaderSpi;
import eugfc.imageio.plugins.PNMUtils;
import java.io.IOException;
import java.util.Locale;
import javax.imageio.ImageReader;
public class PPMImageReaderSpi extends AbstractImageReaderSpi {
private static final String[] MAGIC_NUMBER = {"P3", "P6"};
private static final String _vendorName = "Portable Pix Map";
private static final String _readerClassName = PNMUtils.BASE_CLASS_PATH + ".ppm.PPMImageReader";
private static final String[] _writerSpiNames = { PNMUtils.BASE_CLASS_PATH + ".ppm.PPMImageWriterSpi" };
private static final String[] _names = {"ppm", "pnm"};
private static final String[] _suffixes = {"ppm", "pnm"};
private static final String[] _MIMETypes = {
"image/x-portable-pixmap",
"image/x-portable-anymap"
};
public PPMImageReaderSpi() {
super(_vendorName, _names, _suffixes, _MIMETypes, _readerClassName, _writerSpiNames);
}
@Override
public boolean canDecodeInput(Object source) throws IOException {
return canDecodeInput(source, MAGIC_NUMBER);
}
@Override
public ImageReader createReaderInstance(Object extension) throws IOException {
return new PPMImageReader(this);
}
@Override
public String getDescription(Locale locale) {
return "Portable Pix Map";
}
}
| mit |
shengmin/coding-problem | leetcode/merge-two-sorted-list/Solution.java | 1455 | public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
ListNode n5 = new ListNode(5);
n1.next = n5;
n2.next = n3;
n3.next = n4;
print(s.mergeTwoLists(n1, n2));
}
private static void print(ListNode list) {
if (list != null) {
System.out.printf("%d ", list.val);
print(list.next);
} else {
System.out.println();
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) return null;
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode list = null;
ListNode i1 = l1;
ListNode i2 = l2;
if (i1.val <= i2.val) {
list = i1;
i1 = i1.next;
} else {
list = i2;
i2 = i2.next;
}
ListNode i = list;
while (i1 != null || i2 != null) {
if (i1 == null) {
i.next = i2;
break;
}
if (i2 == null) {
i.next = i1;
break;
}
if (i1.val <= i2.val) {
ListNode next = i1.next;
i.next = i1;
i1 = next;
} else {
ListNode next = i2.next;
i.next = i2;
i2 = next;
}
i = i.next;
}
return list;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
| mit |
trew/DisableMobs | src/se/samuelandersson/disablemobs/helpers/EntityHelper.java | 5612 | /*
* Copyright (c) 2013 Samuel Andersson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.samuelandersson.disablemobs.helpers;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.entity.EntityType;
/**
* Provides helper functions for Entities. Especially concerning names, since
* Bukkit gives some weird names when using EntityType.getName().
* EntityType.OCELOT.getName() returns "Ozelot", which is very confusing. This
* class also helps with separating hostile and neutral mobs, and also helps
* with sorting out what is a mob and what is an item i.e.
*
* @author Samuel Andersson
* @since 2013-07-20
*
*/
public class EntityHelper {
private static final List<EntityType> mobs;
private static final List<EntityType> hostile;
private static final List<EntityType> neutral;
static {
hostile = new ArrayList<EntityType>();
hostile.add(EntityType.BLAZE);
hostile.add(EntityType.CAVE_SPIDER);
hostile.add(EntityType.CREEPER);
hostile.add(EntityType.ENDER_DRAGON);
hostile.add(EntityType.ENDERMAN);
hostile.add(EntityType.GHAST);
hostile.add(EntityType.MAGMA_CUBE);
hostile.add(EntityType.PIG_ZOMBIE);
hostile.add(EntityType.SILVERFISH);
hostile.add(EntityType.SKELETON);
hostile.add(EntityType.SLIME);
hostile.add(EntityType.SPIDER);
hostile.add(EntityType.WITCH);
hostile.add(EntityType.WITHER);
hostile.add(EntityType.ZOMBIE);
neutral = new ArrayList<EntityType>();
neutral.add(EntityType.BAT);
neutral.add(EntityType.CHICKEN);
neutral.add(EntityType.COW);
neutral.add(EntityType.HORSE);
neutral.add(EntityType.IRON_GOLEM);
neutral.add(EntityType.MUSHROOM_COW);
neutral.add(EntityType.OCELOT);
neutral.add(EntityType.PIG);
neutral.add(EntityType.SHEEP);
neutral.add(EntityType.SNOWMAN);
neutral.add(EntityType.SQUID);
neutral.add(EntityType.VILLAGER);
neutral.add(EntityType.WOLF);
mobs = new ArrayList<EntityType>(hostile.size() + neutral.size());
mobs.addAll(hostile);
mobs.addAll(neutral);
}
/**
* Tries to retrieve the name from the mob using two methods. The first one
* uses <code>EntityType.name()</code> , the other one matches against
* <code>EntityType.getName()</code> , which sometimes returns weird results,
* like i.e. "Ozelot". Matches against the first one is preferred.
*
* @param name the name of the entity type
* @return An entity type matching the provided name, or
* <code>EntityType.UNKNOWN</code> otherwise.
* @see EntityType
*/
public static EntityType getTypeFromName(String name) {
name = name.toLowerCase();
for (EntityType t : mobs) {
if (t.name().toLowerCase().equals(name)) return t;
}
for (EntityType t : mobs) {
if (t.getName().toLowerCase().equals(name)) return t;
}
return EntityType.UNKNOWN;
}
/**
* Returns the lowercase entity name of this entity type in the following
* manner:
* <p>
* <code>return type.name().toLowerCase();</code>
* </p>
*
* @param type the type which we want the name of
* @return the name of the entity
*/
public static String getEntityName(EntityType type) {
return type.name().toLowerCase();
}
/**
* Returns a list of mobs where their name starts with the provided message.
* This is primarily used for tab completion.
*
* @param msg the beginning of the mobs' names.
* @return a list of mobs that starts with the provided message
*/
public static List<String> getMobsStartingWith(String msg) {
ArrayList<String> l = new ArrayList<String>(mobs.size());
for (EntityType e : mobs) {
String entityName = getEntityName(e);
if (entityName.startsWith(msg)) {
l.add(entityName);
}
}
return l;
}
/**
* Returns true if the entity type is a mob
*
* @param type the type which we want to know if it is a mob or not
* @return true if the entity type is a mob
*/
public static boolean isMob(EntityType type) {
return mobs.contains(type);
}
/**
* Returns true if the entity type is a hostile mob
*
* @param type the type which we want to know if it is a hostile mob or not
* @return true if the entity type is a hostile mob
*/
public static boolean isHostileMob(EntityType type) {
return hostile.contains(type);
}
/**
* Returns true if the entity type is a neutral mob
*
* @param type the type which we want to know if it is a neutral mob or not
* @return true if the entity type is a neutral mob
*/
public static boolean isNeutralMob(EntityType type) {
return neutral.contains(type);
}
/** Hidden constructor */
private EntityHelper() {
}
}
| mit |
Taskulu/realofit | app/src/main/java/com/taskulu/armanso/realofit/RealmObjects/Reddit/LastQuestionDataChildren.java | 705 | package com.taskulu.armanso.realofit.RealmObjects.Reddit;
import com.taskulu.armanso.realofit.annotion.Realofit;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class LastQuestionDataChildren extends RealmObject {
@PrimaryKey
private String id = "LastQuestionDataChildren";
@Realofit(LastQuestionDataChildrenData.class)
private LastQuestionDataChildrenData data;
public LastQuestionDataChildrenData getData() {
return data;
}
public void setData(LastQuestionDataChildrenData data) {
this.data = data;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| mit |
aisrael/swing-revival | src/test/java/swing/revival/util/BeanWrapperTest.java | 2805 | /**
* swing-revival:
* Swing Revival Toolkit
*
* Copyright (c) 2009 by Alistair A. Israel.
*
* This software is made available under the terms of the MIT License.
* See LICENSE.txt.
*
* Created Sep 30, 2009
*/
package swing.revival.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.lang.reflect.Field;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
* JUnit test for {@link BeanWrapper}.
*
* @author Alistair A. Israel
*/
public final class BeanWrapperTest {
/**
*
*/
@Ignore
public static final class Bean {
private long currentTimeMillis = System.currentTimeMillis();
private String name = Long.toString(currentTimeMillis);
/**
* @return the currentTimeMillis
*/
public long getCurrentTimeMillis() {
return currentTimeMillis;
}
/**
* @return the name
*/
public String getName() {
return name;
}
}
private Bean bean;
private BeanWrapper<Bean> wrapper;
/**
*
*/
@Before
public void setUp() {
bean = new Bean();
wrapper = BeanWrapper.wrap(bean);
}
/**
*
*/
@After
public void tearDown() {
wrapper = null;
bean = null;
}
/**
* Test for {@link BeanWrapper#getDeclaredFields()}.
*/
@Test
public void testGetDeclaredFields() {
final Field[] fields = wrapper.getDeclaredFields();
assertNotNull(fields);
assertEquals(2, fields.length);
}
/**
* Test for {@link BeanWrapper#getAnnotation(java.lang.Class)}.
*/
@Test
public void testGetAnnotation() {
assertNotNull(wrapper.getAnnotation(Ignore.class));
}
/**
* Test for {@link BeanWrapper#get(java.lang.reflect.Field)}.
*
* @throws Exception
* on exception
*/
@Test
public void testGet() throws Exception {
final Field ctmField = wrapper.getDeclaredField("currentTimeMillis");
assertEquals(bean.currentTimeMillis, wrapper.get(ctmField));
final Field nameField = wrapper.getDeclaredField("name");
assertSame(bean.name, wrapper.get(nameField));
}
/**
* Test for
* {@link BeanWrapper#set(java.lang.reflect.Field, java.lang.Object)} .
*
* @throws Exception
* on exception
*/
@Test
public void testSet() throws Exception {
final Field nameField = wrapper.getDeclaredField("name");
final String newValue = "new name";
wrapper.set(nameField, newValue);
assertSame(newValue, bean.name);
}
}
| mit |
chamakits/LinkingServer | src/main/java/edu/uprm/capstone/areatech/linkingserver/example/TimeServerHandler.java | 897 | package edu.uprm.capstone.areatech.linkingserver.example;
import java.util.Date;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
public class TimeServerHandler extends IoHandlerAdapter
{
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception
{
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception
{
String messageString = message.toString();
if(messageString.equalsIgnoreCase("quit"))
{
session.close(true);
}
else
{
session.write((new Date()).toString());
System.out.println("Message written...");
}
return;
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception
{
System.out.println("IDLE:"+session.getIdleCount(status));
}
}
| mit |
rentianhua/tsf_android | houseAd/Library/src/com/daimajia/slider/library/Tricks/ViewPagerEx.java | 112896 | package com.daimajia.slider.library.Tricks;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.v4.os.ParcelableCompat;
import android.support.v4.os.ParcelableCompatCreatorCallbacks;
import android.support.v4.view.AccessibilityDelegateCompat;
import android.support.v4.view.KeyEventCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.view.accessibility.AccessibilityRecordCompat;
import android.support.v4.widget.EdgeEffectCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.FocusFinder;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.Interpolator;
import android.widget.Scroller;
/**
* Layout manager that allows the user to flip left and right
* through pages of data. You supply an implementation of a
* {@link PagerAdapter} to generate the pages that the view shows.
*
* <p>Note this class is currently under early design and
* development. The API will likely change in later updates of
* the compatibility library, requiring changes to the source code
* of apps when they are compiled against the newer version.</p>
*
* <p>ViewPager is most often used in conjunction with {@link android.app.Fragment},
* which is a convenient way to supply and manage the lifecycle of each page.
* There are standard adapters implemented for using fragments with the ViewPager,
* which cover the most common use cases. These are
* {@link android.support.v4.app.FragmentPagerAdapter} and
* {@link android.support.v4.app.FragmentStatePagerAdapter}; each of these
* classes have simple code showing how to build a full user interface
* with them.
*
* <p>Here is a more complicated example of ViewPager, using it in conjuction
* with {@link android.app.ActionBar} tabs. You can find other examples of using
* ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code.
*
* {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/ActionBarTabsPager.java
* complete}
*/
/**
* @author daimajia : I just remove the if condition in setPageTransformer() to make it compatiable with Android 2.0+
* of course, with the help of the NineOldDroid.
* Thanks to JakeWharton.
* http://github.com/JakeWharton/NineOldAndroids
*/
public class ViewPagerEx extends ViewGroup{
private static final String TAG = "ViewPagerEx";
private static final boolean DEBUG = false;
private static final boolean USE_CACHE = false;
private static final int DEFAULT_OFFSCREEN_PAGES = 1;
private static final int MAX_SETTLE_DURATION = 600; // ms
private static final int MIN_DISTANCE_FOR_FLING = 25; // dips
private static final int DEFAULT_GUTTER_SIZE = 16; // dips
private static final int MIN_FLING_VELOCITY = 400; // dips
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.layout_gravity
};
/**
* Used to track what the expected number of items in the adapter should be.
* If the app changes this when we don't expect it, we'll throw a big obnoxious exception.
*/
private int mExpectedAdapterCount;
static class ItemInfo {
Object object;
int position;
boolean scrolling;
float widthFactor;
float offset;
}
private static final Comparator<ItemInfo> COMPARATOR = new Comparator<ItemInfo>(){
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
return lhs.position - rhs.position;
}
};
private static final Interpolator sInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
private final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
private final ItemInfo mTempItem = new ItemInfo();
private final Rect mTempRect = new Rect();
private PagerAdapter mAdapter;
private int mCurItem; // Index of currently displayed page.
private int mRestoredCurItem = -1;
private Parcelable mRestoredAdapterState = null;
private ClassLoader mRestoredClassLoader = null;
private Scroller mScroller;
private PagerObserver mObserver;
private int mPageMargin;
private Drawable mMarginDrawable;
private int mTopPageBounds;
private int mBottomPageBounds;
// Offsets of the first and last items, if known.
// Set during population, used to determine if we are at the beginning
// or end of the pager data set during touch scrolling.
private float mFirstOffset = -Float.MAX_VALUE;
private float mLastOffset = Float.MAX_VALUE;
private int mChildWidthMeasureSpec;
private int mChildHeightMeasureSpec;
private boolean mInLayout;
private boolean mScrollingCacheEnabled;
private boolean mPopulatePending;
private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES;
private boolean mIsBeingDragged;
private boolean mIsUnableToDrag;
private boolean mIgnoreGutter;
private int mDefaultGutterSize;
private int mGutterSize;
private int mTouchSlop;
/**
* Position of the last motion event.
*/
private float mLastMotionX;
private float mLastMotionY;
private float mInitialMotionX;
private float mInitialMotionY;
/**
* ID of the active pointer. This is used to retain consistency during
* drags/flings if multiple pointers are used.
*/
private int mActivePointerId = INVALID_POINTER;
/**
* Sentinel value for no current active pointer.
* Used by {@link #mActivePointerId}.
*/
private static final int INVALID_POINTER = -1;
/**
* Determines speed during touch scrolling
*/
private VelocityTracker mVelocityTracker;
private int mMinimumVelocity;
private int mMaximumVelocity;
private int mFlingDistance;
private int mCloseEnough;
// If the pager is at least this close to its final position, complete the scroll
// on touch down and let the user interact with the content inside instead of
// "catching" the flinging pager.
private static final int CLOSE_ENOUGH = 2; // dp
private boolean mFakeDragging;
private long mFakeDragBeginTime;
private EdgeEffectCompat mLeftEdge;
private EdgeEffectCompat mRightEdge;
private boolean mFirstLayout = true;
private boolean mNeedCalculatePageOffsets = false;
private boolean mCalledSuper;
private int mDecorChildCount;
private OnPageChangeListener mOnPageChangeListener;
private OnPageChangeListener mInternalPageChangeListener;
private OnAdapterChangeListener mAdapterChangeListener;
private PageTransformer mPageTransformer;
private Method mSetChildrenDrawingOrderEnabled;
private static final int DRAW_ORDER_DEFAULT = 0;
private static final int DRAW_ORDER_FORWARD = 1;
private static final int DRAW_ORDER_REVERSE = 2;
private int mDrawingOrder;
private ArrayList<View> mDrawingOrderedChildren;
private static final ViewPositionComparator sPositionComparator = new ViewPositionComparator();
/**
* Indicates that the pager is in an idle, settled state. The current page
* is fully in view and no animation is in progress.
*/
public static final int SCROLL_STATE_IDLE = 0;
/**
* Indicates that the pager is currently being dragged by the user.
*/
public static final int SCROLL_STATE_DRAGGING = 1;
/**
* Indicates that the pager is in the process of settling to a final position.
*/
public static final int SCROLL_STATE_SETTLING = 2;
private final Runnable mEndScrollRunnable = new Runnable() {
public void run() {
setScrollState(SCROLL_STATE_IDLE);
populate();
}
};
private int mScrollState = SCROLL_STATE_IDLE;
/**
* Callback interface for responding to changing state of the selected page.
*/
public interface OnPageChangeListener {
/**
* This method will be invoked when the current page is scrolled, either as part
* of a programmatically initiated smooth scroll or a user initiated touch scroll.
*
* @param position Position index of the first page currently being displayed.
* Page position+1 will be visible if positionOffset is nonzero.
* @param positionOffset Value from [0, 1) indicating the offset from the page at position.
* @param positionOffsetPixels Value in pixels indicating the offset from position.
*/
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
/**
* This method will be invoked when a new page becomes selected. Animation is not
* necessarily complete.
*
* @param position Position index of the new selected page.
*/
public void onPageSelected(int position);
/**
* Called when the scroll state changes. Useful for discovering when the user
* begins dragging, when the pager is automatically settling to the current page,
* or when it is fully stopped/idle.
*
* @param state The new scroll state.
* @see ViewPagerEx#SCROLL_STATE_IDLE
* @see ViewPagerEx#SCROLL_STATE_DRAGGING
* @see ViewPagerEx#SCROLL_STATE_SETTLING
*/
public void onPageScrollStateChanged(int state);
}
/**
* Simple implementation of the {@link OnPageChangeListener} interface with stub
* implementations of each method. Extend this if you do not intend to override
* every method of {@link OnPageChangeListener}.
*/
public static class SimpleOnPageChangeListener implements OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// This space for rent
}
@Override
public void onPageSelected(int position) {
// This space for rent
}
@Override
public void onPageScrollStateChanged(int state) {
// This space for rent
}
}
/**
* A PageTransformer is invoked whenever a visible/attached page is scrolled.
* This offers an opportunity for the application to apply a custom transformation
* to the page views using animation properties.
*
* <p>As property animation is only supported as of Android 3.0 and forward,
* setting a PageTransformer on a ViewPager on earlier platform versions will
* be ignored.</p>
*/
public interface PageTransformer {
/**
* Apply a property transformation to the given page.
*
* @param page Apply the transformation to this page
* @param position Position of page relative to the current front-and-center
* position of the pager. 0 is front and center. 1 is one full
* page position to the right, and -1 is one page position to the left.
*/
public void transformPage(View page, float position);
}
/**
* Used internally to monitor when adapters are switched.
*/
interface OnAdapterChangeListener {
public void onAdapterChanged(PagerAdapter oldAdapter, PagerAdapter newAdapter);
}
/**
* Used internally to tag special types of child views that should be added as
* pager decorations by default.
*/
interface Decor {}
public ViewPagerEx(Context context) {
super(context);
initViewPager();
}
public ViewPagerEx(Context context, AttributeSet attrs) {
super(context, attrs);
initViewPager();
}
void initViewPager() {
setWillNotDraw(false);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setFocusable(true);
final Context context = getContext();
mScroller = new Scroller(context, sInterpolator);
final ViewConfiguration configuration = ViewConfiguration.get(context);
final float density = context.getResources().getDisplayMetrics().density;
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density);
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
mLeftEdge = new EdgeEffectCompat(context);
mRightEdge = new EdgeEffectCompat(context);
mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);
mCloseEnough = (int) (CLOSE_ENOUGH * density);
mDefaultGutterSize = (int) (DEFAULT_GUTTER_SIZE * density);
ViewCompat.setAccessibilityDelegate(this, new MyAccessibilityDelegate());
if (ViewCompat.getImportantForAccessibility(this)
== ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(this,
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
}
@Override
protected void onDetachedFromWindow() {
removeCallbacks(mEndScrollRunnable);
super.onDetachedFromWindow();
}
private void setScrollState(int newState) {
if (mScrollState == newState) {
return;
}
mScrollState = newState;
if (mPageTransformer != null) {
// PageTransformers can do complex things that benefit from hardware layers.
enableLayers(newState != SCROLL_STATE_IDLE);
}
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageScrollStateChanged(newState);
}
}
/**
* Set a PagerAdapter that will supply views for this pager as needed.
*
* @param adapter Adapter to use
*/
public void setAdapter(PagerAdapter adapter) {
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mObserver);
mAdapter.startUpdate(this);
for (int i = 0; i < mItems.size(); i++) {
final ItemInfo ii = mItems.get(i);
mAdapter.destroyItem(this, ii.position, ii.object);
}
mAdapter.finishUpdate(this);
mItems.clear();
removeNonDecorViews();
mCurItem = 0;
scrollTo(0, 0);
}
final PagerAdapter oldAdapter = mAdapter;
mAdapter = adapter;
mExpectedAdapterCount = 0;
if (mAdapter != null) {
if (mObserver == null) {
mObserver = new PagerObserver();
}
mAdapter.registerDataSetObserver(mObserver);
mPopulatePending = false;
final boolean wasFirstLayout = mFirstLayout;
mFirstLayout = true;
mExpectedAdapterCount = mAdapter.getCount();
if (mRestoredCurItem >= 0) {
mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader);
setCurrentItemInternal(mRestoredCurItem, false, true);
mRestoredCurItem = -1;
mRestoredAdapterState = null;
mRestoredClassLoader = null;
} else if (!wasFirstLayout) {
populate();
} else {
requestLayout();
}
}
if (mAdapterChangeListener != null && oldAdapter != adapter) {
mAdapterChangeListener.onAdapterChanged(oldAdapter, adapter);
}
}
private void removeNonDecorViews() {
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.isDecor) {
removeViewAt(i);
i--;
}
}
}
/**
* Retrieve the current adapter supplying pages.
*
* @return The currently registered PagerAdapter
*/
public PagerAdapter getAdapter() {
return mAdapter;
}
void setOnAdapterChangeListener(OnAdapterChangeListener listener) {
mAdapterChangeListener = listener;
}
private int getClientWidth() {
return getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
}
/**
* Set the currently selected page. If the ViewPager has already been through its first
* layout with its current adapter there will be a smooth animated transition between
* the current item and the specified item.
*
* @param item Item index to select
*/
public void setCurrentItem(int item) {
mPopulatePending = false;
setCurrentItemInternal(item, !mFirstLayout, false);
}
/**
* Set the currently selected page.
*
* @param item Item index to select
* @param smoothScroll True to smoothly scroll to the new item, false to transition immediately
*/
public void setCurrentItem(int item, boolean smoothScroll) {
mPopulatePending = false;
setCurrentItemInternal(item, smoothScroll, false);
}
public int getCurrentItem() {
return mCurItem;
}
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) {
setCurrentItemInternal(item, smoothScroll, always, 0);
}
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) {
if (mAdapter == null || mAdapter.getCount() <= 0) {
setScrollingCacheEnabled(false);
return;
}
if (!always && mCurItem == item && mItems.size() != 0) {
setScrollingCacheEnabled(false);
return;
}
if (item < 0) {
item = 0;
} else if (item >= mAdapter.getCount()) {
item = mAdapter.getCount() - 1;
}
final int pageLimit = mOffscreenPageLimit;
if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) {
// We are doing a jump by more than one page. To avoid
// glitches, we want to keep all current pages in the view
// until the scroll ends.
for (int i=0; i<mItems.size(); i++) {
mItems.get(i).scrolling = true;
}
}
final boolean dispatchSelected = mCurItem != item;
if (mFirstLayout) {
// We don't have any idea how big we are yet and shouldn't have any pages either.
// Just set things up and let the pending layout handle things.
mCurItem = item;
if (dispatchSelected && mOnPageChangeListener != null) {
mOnPageChangeListener.onPageSelected(item);
}
if (dispatchSelected && mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageSelected(item);
}
requestLayout();
} else {
populate(item);
scrollToItem(item, smoothScroll, velocity, dispatchSelected);
}
}
private void scrollToItem(int item, boolean smoothScroll, int velocity,
boolean dispatchSelected) {
final ItemInfo curInfo = infoForPosition(item);
int destX = 0;
if (curInfo != null) {
final int width = getClientWidth();
destX = (int) (width * Math.max(mFirstOffset,
Math.min(curInfo.offset, mLastOffset)));
}
if (smoothScroll) {
smoothScrollTo(destX, 0, velocity);
if (dispatchSelected && mOnPageChangeListener != null) {
mOnPageChangeListener.onPageSelected(item);
}
if (dispatchSelected && mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageSelected(item);
}
} else {
if (dispatchSelected && mOnPageChangeListener != null) {
mOnPageChangeListener.onPageSelected(item);
}
if (dispatchSelected && mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageSelected(item);
}
completeScroll(false);
scrollTo(destX, 0);
pageScrolled(destX);
}
}
/**
* Set a listener that will be invoked whenever the page changes or is incrementally
* scrolled. See {@link OnPageChangeListener}.
*
* @param listener Listener to set
*/
public void setOnPageChangeListener(OnPageChangeListener listener) {
mOnPageChangeListener = listener;
}
/**
* Set a {@link PageTransformer} that will be called for each attached page whenever
* the scroll position is changed. This allows the application to apply custom property
* transformations to each page, overriding the default sliding look and feel.
*
* <p><em>Note:</em> Prior to Android 3.0 the property animation APIs did not exist.
* As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.</p>
*
* @param reverseDrawingOrder true if the supplied PageTransformer requires page views
* to be drawn from last to first instead of first to last.
* @param transformer PageTransformer that will modify each page's animation properties
*/
public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) {
final boolean hasTransformer = transformer != null;
final boolean needsPopulate = hasTransformer != (mPageTransformer != null);
mPageTransformer = transformer;
setChildrenDrawingOrderEnabledCompat(hasTransformer);
if (hasTransformer) {
mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD;
} else {
mDrawingOrder = DRAW_ORDER_DEFAULT;
}
if (needsPopulate) populate();
}
void setChildrenDrawingOrderEnabledCompat(boolean enable) {
if (Build.VERSION.SDK_INT >= 7) {
if (mSetChildrenDrawingOrderEnabled == null) {
try {
mSetChildrenDrawingOrderEnabled = ViewGroup.class.getDeclaredMethod(
"setChildrenDrawingOrderEnabled", new Class[] { Boolean.TYPE });
} catch (NoSuchMethodException e) {
Log.e(TAG, "Can't find setChildrenDrawingOrderEnabled", e);
}
}
try {
mSetChildrenDrawingOrderEnabled.invoke(this, enable);
} catch (Exception e) {
Log.e(TAG, "Error changing children drawing order", e);
}
}
}
@Override
protected int getChildDrawingOrder(int childCount, int i) {
final int index = mDrawingOrder == DRAW_ORDER_REVERSE ? childCount - 1 - i : i;
final int result = ((LayoutParams) mDrawingOrderedChildren.get(index).getLayoutParams()).childIndex;
return result;
}
/**
* Set a separate OnPageChangeListener for internal use by the support library.
*
* @param listener Listener to set
* @return The old listener that was set, if any.
*/
OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) {
OnPageChangeListener oldListener = mInternalPageChangeListener;
mInternalPageChangeListener = listener;
return oldListener;
}
/**
* Returns the number of pages that will be retained to either side of the
* current page in the view hierarchy in an idle state. Defaults to 1.
*
* @return How many pages will be kept offscreen on either side
* @see #setOffscreenPageLimit(int)
*/
public int getOffscreenPageLimit() {
return mOffscreenPageLimit;
}
/**
* Set the number of pages that should be retained to either side of the
* current page in the view hierarchy in an idle state. Pages beyond this
* limit will be recreated from the adapter when needed.
*
* <p>This is offered as an optimization. If you know in advance the number
* of pages you will need to support or have lazy-loading mechanisms in place
* on your pages, tweaking this setting can have benefits in perceived smoothness
* of paging animations and interaction. If you have a small number of pages (3-4)
* that you can keep active all at once, less time will be spent in layout for
* newly created view subtrees as the user pages back and forth.</p>
*
* <p>You should keep this limit low, especially if your pages have complex layouts.
* This setting defaults to 1.</p>
*
* @param limit How many pages will be kept offscreen in an idle state.
*/
public void setOffscreenPageLimit(int limit) {
if (limit < DEFAULT_OFFSCREEN_PAGES) {
Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " +
DEFAULT_OFFSCREEN_PAGES);
limit = DEFAULT_OFFSCREEN_PAGES;
}
if (limit != mOffscreenPageLimit) {
mOffscreenPageLimit = limit;
populate();
}
}
/**
* Set the margin between pages.
*
* @param marginPixels Distance between adjacent pages in pixels
* @see #getPageMargin()
* @see #setPageMarginDrawable(Drawable)
* @see #setPageMarginDrawable(int)
*/
public void setPageMargin(int marginPixels) {
final int oldMargin = mPageMargin;
mPageMargin = marginPixels;
final int width = getWidth();
recomputeScrollPosition(width, width, marginPixels, oldMargin);
requestLayout();
}
/**
* Return the margin between pages.
*
* @return The size of the margin in pixels
*/
public int getPageMargin() {
return mPageMargin;
}
/**
* Set a drawable that will be used to fill the margin between pages.
*
* @param d Drawable to display between pages
*/
public void setPageMarginDrawable(Drawable d) {
mMarginDrawable = d;
if (d != null) refreshDrawableState();
setWillNotDraw(d == null);
invalidate();
}
/**
* Set a drawable that will be used to fill the margin between pages.
*
* @param resId Resource ID of a drawable to display between pages
*/
public void setPageMarginDrawable(int resId) {
setPageMarginDrawable(getContext().getResources().getDrawable(resId));
}
@Override
protected boolean verifyDrawable(Drawable who) {
return super.verifyDrawable(who) || who == mMarginDrawable;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
final Drawable d = mMarginDrawable;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
}
// We want the duration of the page snap animation to be influenced by the distance that
// the screen has to travel, however, we don't want this duration to be effected in a
// purely linear fashion. Instead, we use this method to moderate the effect that the distance
// of travel has on the overall snap duration.
float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
return (float) Math.sin(f);
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x the number of pixels to scroll by on the X axis
* @param y the number of pixels to scroll by on the Y axis
*/
void smoothScrollTo(int x, int y) {
smoothScrollTo(x, y, 0);
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param x the number of pixels to scroll by on the X axis
* @param y the number of pixels to scroll by on the Y axis
* @param velocity the velocity associated with a fling, if applicable. (0 otherwise)
*/
void smoothScrollTo(int x, int y, int velocity) {
if (getChildCount() == 0) {
// Nothing to do.
setScrollingCacheEnabled(false);
return;
}
int sx = getScrollX();
int sy = getScrollY();
int dx = x - sx;
int dy = y - sy;
if (dx == 0 && dy == 0) {
completeScroll(false);
populate();
setScrollState(SCROLL_STATE_IDLE);
return;
}
setScrollingCacheEnabled(true);
setScrollState(SCROLL_STATE_SETTLING);
final int width = getClientWidth();
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth *
distanceInfluenceForSnapDuration(distanceRatio);
int duration = 0;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
final float pageWidth = width * mAdapter.getPageWidth(mCurItem);
final float pageDelta = (float) Math.abs(dx) / (pageWidth + mPageMargin);
duration = (int) ((pageDelta + 1) * 100);
}
duration = Math.min(duration, MAX_SETTLE_DURATION);
mScroller.startScroll(sx, sy, dx, dy, duration);
ViewCompat.postInvalidateOnAnimation(this);
}
ItemInfo addNewItem(int position, int index) {
ItemInfo ii = new ItemInfo();
ii.position = position;
ii.object = mAdapter.instantiateItem(this, position);
ii.widthFactor = mAdapter.getPageWidth(position);
if (index < 0 || index >= mItems.size()) {
mItems.add(ii);
} else {
mItems.add(index, ii);
}
return ii;
}
void dataSetChanged() {
// This method only gets called if our observer is attached, so mAdapter is non-null.
final int adapterCount = mAdapter.getCount();
mExpectedAdapterCount = adapterCount;
boolean needPopulate = mItems.size() < mOffscreenPageLimit * 2 + 1 &&
mItems.size() < adapterCount;
int newCurrItem = mCurItem;
boolean isUpdating = false;
for (int i = 0; i < mItems.size(); i++) {
final ItemInfo ii = mItems.get(i);
final int newPos = mAdapter.getItemPosition(ii.object);
if (newPos == PagerAdapter.POSITION_UNCHANGED) {
continue;
}
if (newPos == PagerAdapter.POSITION_NONE) {
mItems.remove(i);
i--;
if (!isUpdating) {
mAdapter.startUpdate(this);
isUpdating = true;
}
mAdapter.destroyItem(this, ii.position, ii.object);
needPopulate = true;
if (mCurItem == ii.position) {
// Keep the current item in the valid range
newCurrItem = Math.max(0, Math.min(mCurItem, adapterCount - 1));
needPopulate = true;
}
continue;
}
if (ii.position != newPos) {
if (ii.position == mCurItem) {
// Our current item changed position. Follow it.
newCurrItem = newPos;
}
ii.position = newPos;
needPopulate = true;
}
}
if (isUpdating) {
mAdapter.finishUpdate(this);
}
Collections.sort(mItems, COMPARATOR);
if (needPopulate) {
// Reset our known page widths; populate will recompute them.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.isDecor) {
lp.widthFactor = 0.f;
}
}
setCurrentItemInternal(newCurrItem, false, true);
requestLayout();
}
}
void populate() {
populate(mCurItem);
}
void populate(int newCurrentItem) {
ItemInfo oldCurInfo = null;
int focusDirection = View.FOCUS_FORWARD;
if (mCurItem != newCurrentItem) {
focusDirection = mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT;
oldCurInfo = infoForPosition(mCurItem);
mCurItem = newCurrentItem;
}
if (mAdapter == null) {
sortChildDrawingOrder();
return;
}
// Bail now if we are waiting to populate. This is to hold off
// on creating views from the time the user releases their finger to
// fling to a new position until we have finished the scroll to
// that position, avoiding glitches from happening at that point.
if (mPopulatePending) {
if (DEBUG) Log.i(TAG, "populate is pending, skipping for now...");
sortChildDrawingOrder();
return;
}
// Also, don't populate until we are attached to a window. This is to
// avoid trying to populate before we have restored our view hierarchy
// state and conflicting with what is restored.
if (getWindowToken() == null) {
return;
}
mAdapter.startUpdate(this);
final int pageLimit = mOffscreenPageLimit;
final int startPos = Math.max(0, mCurItem - pageLimit);
final int N = mAdapter.getCount();
final int endPos = Math.min(N-1, mCurItem + pageLimit);
if (N != mExpectedAdapterCount) {
String resName;
try {
resName = getResources().getResourceName(getId());
} catch (Resources.NotFoundException e) {
resName = Integer.toHexString(getId());
}
throw new IllegalStateException("The application's PagerAdapter changed the adapter's" +
" contents without calling PagerAdapter#notifyDataSetChanged!" +
" Expected adapter item count: " + mExpectedAdapterCount + ", found: " + N +
" Pager id: " + resName +
" Pager class: " + getClass() +
" Problematic adapter: " + mAdapter.getClass());
}
// Locate the currently focused item or add it if needed.
int curIndex = -1;
ItemInfo curItem = null;
for (curIndex = 0; curIndex < mItems.size(); curIndex++) {
final ItemInfo ii = mItems.get(curIndex);
if (ii.position >= mCurItem) {
if (ii.position == mCurItem) curItem = ii;
break;
}
}
if (curItem == null && N > 0) {
curItem = addNewItem(mCurItem, curIndex);
}
// Fill 3x the available width or up to the number of offscreen
// pages requested to either side, whichever is larger.
// If we have no current item we have no work to do.
if (curItem != null) {
float extraWidthLeft = 0.f;
int itemIndex = curIndex - 1;
ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
final int clientWidth = getClientWidth();
final float leftWidthNeeded = clientWidth <= 0 ? 0 :
2.f - curItem.widthFactor + (float) getPaddingLeft() / (float) clientWidth;
for (int pos = mCurItem - 1; pos >= 0; pos--) {
if (extraWidthLeft >= leftWidthNeeded && pos < startPos) {
if (ii == null) {
break;
}
if (pos == ii.position && !ii.scrolling) {
mItems.remove(itemIndex);
mAdapter.destroyItem(this, pos, ii.object);
if (DEBUG) {
Log.i(TAG, "populate() - destroyItem() with pos: " + pos +
" view: " + ((View) ii.object));
}
itemIndex--;
curIndex--;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
}
} else if (ii != null && pos == ii.position) {
extraWidthLeft += ii.widthFactor;
itemIndex--;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
} else {
ii = addNewItem(pos, itemIndex + 1);
extraWidthLeft += ii.widthFactor;
curIndex++;
ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
}
}
float extraWidthRight = curItem.widthFactor;
itemIndex = curIndex + 1;
if (extraWidthRight < 2.f) {
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
final float rightWidthNeeded = clientWidth <= 0 ? 0 :
(float) getPaddingRight() / (float) clientWidth + 2.f;
for (int pos = mCurItem + 1; pos < N; pos++) {
if (extraWidthRight >= rightWidthNeeded && pos > endPos) {
if (ii == null) {
break;
}
if (pos == ii.position && !ii.scrolling) {
mItems.remove(itemIndex);
mAdapter.destroyItem(this, pos, ii.object);
if (DEBUG) {
Log.i(TAG, "populate() - destroyItem() with pos: " + pos +
" view: " + ((View) ii.object));
}
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
}
} else if (ii != null && pos == ii.position) {
extraWidthRight += ii.widthFactor;
itemIndex++;
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
} else {
ii = addNewItem(pos, itemIndex);
itemIndex++;
extraWidthRight += ii.widthFactor;
ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
}
}
}
calculatePageOffsets(curItem, curIndex, oldCurInfo);
}
if (DEBUG) {
Log.i(TAG, "Current page list:");
for (int i=0; i<mItems.size(); i++) {
Log.i(TAG, "#" + i + ": page " + mItems.get(i).position);
}
}
mAdapter.setPrimaryItem(this, mCurItem, curItem != null ? curItem.object : null);
mAdapter.finishUpdate(this);
// Check width measurement of current pages and drawing sort order.
// Update LayoutParams as needed.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.childIndex = i;
if (!lp.isDecor && lp.widthFactor == 0.f) {
// 0 means requery the adapter for this, it doesn't have a valid width.
final ItemInfo ii = infoForChild(child);
if (ii != null) {
lp.widthFactor = ii.widthFactor;
lp.position = ii.position;
}
}
}
sortChildDrawingOrder();
if (hasFocus()) {
View currentFocused = findFocus();
ItemInfo ii = currentFocused != null ? infoForAnyChild(currentFocused) : null;
if (ii == null || ii.position != mCurItem) {
for (int i=0; i<getChildCount(); i++) {
View child = getChildAt(i);
ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(focusDirection)) {
break;
}
}
}
}
}
}
private void sortChildDrawingOrder() {
if (mDrawingOrder != DRAW_ORDER_DEFAULT) {
if (mDrawingOrderedChildren == null) {
mDrawingOrderedChildren = new ArrayList<View>();
} else {
mDrawingOrderedChildren.clear();
}
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
mDrawingOrderedChildren.add(child);
}
Collections.sort(mDrawingOrderedChildren, sPositionComparator);
}
}
private void calculatePageOffsets(ItemInfo curItem, int curIndex, ItemInfo oldCurInfo) {
final int N = mAdapter.getCount();
final int width = getClientWidth();
final float marginOffset = width > 0 ? (float) mPageMargin / width : 0;
// Fix up offsets for later layout.
if (oldCurInfo != null) {
final int oldCurPosition = oldCurInfo.position;
// Base offsets off of oldCurInfo.
if (oldCurPosition < curItem.position) {
int itemIndex = 0;
ItemInfo ii = null;
float offset = oldCurInfo.offset + oldCurInfo.widthFactor + marginOffset;
for (int pos = oldCurPosition + 1;
pos <= curItem.position && itemIndex < mItems.size(); pos++) {
ii = mItems.get(itemIndex);
while (pos > ii.position && itemIndex < mItems.size() - 1) {
itemIndex++;
ii = mItems.get(itemIndex);
}
while (pos < ii.position) {
// We don't have an item populated for this,
// ask the adapter for an offset.
offset += mAdapter.getPageWidth(pos) + marginOffset;
pos++;
}
ii.offset = offset;
offset += ii.widthFactor + marginOffset;
}
} else if (oldCurPosition > curItem.position) {
int itemIndex = mItems.size() - 1;
ItemInfo ii = null;
float offset = oldCurInfo.offset;
for (int pos = oldCurPosition - 1;
pos >= curItem.position && itemIndex >= 0; pos--) {
ii = mItems.get(itemIndex);
while (pos < ii.position && itemIndex > 0) {
itemIndex--;
ii = mItems.get(itemIndex);
}
while (pos > ii.position) {
// We don't have an item populated for this,
// ask the adapter for an offset.
offset -= mAdapter.getPageWidth(pos) + marginOffset;
pos--;
}
offset -= ii.widthFactor + marginOffset;
ii.offset = offset;
}
}
}
// Base all offsets off of curItem.
final int itemCount = mItems.size();
float offset = curItem.offset;
int pos = curItem.position - 1;
mFirstOffset = curItem.position == 0 ? curItem.offset : -Float.MAX_VALUE;
mLastOffset = curItem.position == N - 1 ?
curItem.offset + curItem.widthFactor - 1 : Float.MAX_VALUE;
// Previous pages
for (int i = curIndex - 1; i >= 0; i--, pos--) {
final ItemInfo ii = mItems.get(i);
while (pos > ii.position) {
offset -= mAdapter.getPageWidth(pos--) + marginOffset;
}
offset -= ii.widthFactor + marginOffset;
ii.offset = offset;
if (ii.position == 0) mFirstOffset = offset;
}
offset = curItem.offset + curItem.widthFactor + marginOffset;
pos = curItem.position + 1;
// Next pages
for (int i = curIndex + 1; i < itemCount; i++, pos++) {
final ItemInfo ii = mItems.get(i);
while (pos < ii.position) {
offset += mAdapter.getPageWidth(pos++) + marginOffset;
}
if (ii.position == N - 1) {
mLastOffset = offset + ii.widthFactor - 1;
}
ii.offset = offset;
offset += ii.widthFactor + marginOffset;
}
mNeedCalculatePageOffsets = false;
}
/**
* This is the persistent state that is saved by ViewPager. Only needed
* if you are creating a sublass of ViewPager that must save its own
* state, in which case it should implement a subclass of this which
* contains that state.
*/
public static class SavedState extends BaseSavedState {
int position;
Parcelable adapterState;
ClassLoader loader;
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(position);
out.writeParcelable(adapterState, flags);
}
@Override
public String toString() {
return "FragmentPager.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " position=" + position + "}";
}
public static final Parcelable.Creator<SavedState> CREATOR
= ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in, ClassLoader loader) {
return new SavedState(in, loader);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
});
SavedState(Parcel in, ClassLoader loader) {
super(in);
if (loader == null) {
loader = getClass().getClassLoader();
}
position = in.readInt();
adapterState = in.readParcelable(loader);
this.loader = loader;
}
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.position = mCurItem;
if (mAdapter != null) {
ss.adapterState = mAdapter.saveState();
}
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
if (mAdapter != null) {
mAdapter.restoreState(ss.adapterState, ss.loader);
setCurrentItemInternal(ss.position, false, true);
} else {
mRestoredCurItem = ss.position;
mRestoredAdapterState = ss.adapterState;
mRestoredClassLoader = ss.loader;
}
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (!checkLayoutParams(params)) {
params = generateLayoutParams(params);
}
final LayoutParams lp = (LayoutParams) params;
lp.isDecor |= child instanceof Decor;
if (mInLayout) {
if (lp != null && lp.isDecor) {
throw new IllegalStateException("Cannot add pager decor view during layout");
}
lp.needsMeasure = true;
addViewInLayout(child, index, params);
} else {
super.addView(child, index, params);
}
if (USE_CACHE) {
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(mScrollingCacheEnabled);
} else {
child.setDrawingCacheEnabled(false);
}
}
}
@Override
public void removeView(View view) {
if (mInLayout) {
removeViewInLayout(view);
} else {
super.removeView(view);
}
}
ItemInfo infoForChild(View child) {
for (int i=0; i<mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
if (mAdapter.isViewFromObject(child, ii.object)) {
return ii;
}
}
return null;
}
ItemInfo infoForAnyChild(View child) {
ViewParent parent;
while ((parent=child.getParent()) != this) {
if (parent == null || !(parent instanceof View)) {
return null;
}
child = (View)parent;
}
return infoForChild(child);
}
ItemInfo infoForPosition(int position) {
for (int i = 0; i < mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
if (ii.position == position) {
return ii;
}
}
return null;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mFirstLayout = true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// For simple implementation, our internal size is always 0.
// We depend on the container to specify the layout size of
// our view. We can't really know what it is since we will be
// adding and removing different arbitrary views and do not
// want the layout to change as this happens.
setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
getDefaultSize(0, heightMeasureSpec));
final int measuredWidth = getMeasuredWidth();
final int maxGutterSize = measuredWidth / 10;
mGutterSize = Math.min(maxGutterSize, mDefaultGutterSize);
// Children are just made to fill our space.
int childWidthSize = measuredWidth - getPaddingLeft() - getPaddingRight();
int childHeightSize = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
/*
* Make sure all children have been properly measured. Decor views first.
* Right now we cheat and make this less complicated by assuming decor
* views won't intersect. We will pin to edges based on gravity.
*/
int size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp != null && lp.isDecor) {
final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
int widthMode = MeasureSpec.AT_MOST;
int heightMode = MeasureSpec.AT_MOST;
boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM;
boolean consumeHorizontal = hgrav == Gravity.LEFT || hgrav == Gravity.RIGHT;
if (consumeVertical) {
widthMode = MeasureSpec.EXACTLY;
} else if (consumeHorizontal) {
heightMode = MeasureSpec.EXACTLY;
}
int widthSize = childWidthSize;
int heightSize = childHeightSize;
if (lp.width != LayoutParams.WRAP_CONTENT) {
widthMode = MeasureSpec.EXACTLY;
if (lp.width != LayoutParams.FILL_PARENT) {
widthSize = lp.width;
}
}
if (lp.height != LayoutParams.WRAP_CONTENT) {
heightMode = MeasureSpec.EXACTLY;
if (lp.height != LayoutParams.FILL_PARENT) {
heightSize = lp.height;
}
}
final int widthSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode);
final int heightSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode);
child.measure(widthSpec, heightSpec);
if (consumeVertical) {
childHeightSize -= child.getMeasuredHeight();
} else if (consumeHorizontal) {
childWidthSize -= child.getMeasuredWidth();
}
}
}
}
mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY);
// Make sure we have created all fragments that we need to have shown.
mInLayout = true;
populate();
mInLayout = false;
// Page views next.
size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
if (DEBUG) Log.v(TAG, "Measuring #" + i + " " + child
+ ": " + mChildWidthMeasureSpec);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp == null || !lp.isDecor) {
final int widthSpec = MeasureSpec.makeMeasureSpec(
(int) (childWidthSize * lp.widthFactor), MeasureSpec.EXACTLY);
child.measure(widthSpec, mChildHeightMeasureSpec);
}
}
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// Make sure scroll position is set correctly.
if (w != oldw) {
recomputeScrollPosition(w, oldw, mPageMargin, mPageMargin);
}
}
private void recomputeScrollPosition(int width, int oldWidth, int margin, int oldMargin) {
if (oldWidth > 0 && !mItems.isEmpty()) {
final int widthWithMargin = width - getPaddingLeft() - getPaddingRight() + margin;
final int oldWidthWithMargin = oldWidth - getPaddingLeft() - getPaddingRight()
+ oldMargin;
final int xpos = getScrollX();
final float pageOffset = (float) xpos / oldWidthWithMargin;
final int newOffsetPixels = (int) (pageOffset * widthWithMargin);
scrollTo(newOffsetPixels, getScrollY());
if (!mScroller.isFinished()) {
// We now return to your regularly scheduled scroll, already in progress.
final int newDuration = mScroller.getDuration() - mScroller.timePassed();
ItemInfo targetInfo = infoForPosition(mCurItem);
mScroller.startScroll(newOffsetPixels, 0,
(int) (targetInfo.offset * width), 0, newDuration);
}
} else {
final ItemInfo ii = infoForPosition(mCurItem);
final float scrollOffset = ii != null ? Math.min(ii.offset, mLastOffset) : 0;
final int scrollPos = (int) (scrollOffset *
(width - getPaddingLeft() - getPaddingRight()));
if (scrollPos != getScrollX()) {
completeScroll(false);
scrollTo(scrollPos, getScrollY());
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
int width = r - l;
int height = b - t;
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int paddingRight = getPaddingRight();
int paddingBottom = getPaddingBottom();
final int scrollX = getScrollX();
int decorCount = 0;
// First pass - decor views. We need to do this in two passes so that
// we have the proper offsets for non-decor views later.
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int childLeft = 0;
int childTop = 0;
if (lp.isDecor) {
final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (hgrav) {
default:
childLeft = paddingLeft;
break;
case Gravity.LEFT:
childLeft = paddingLeft;
paddingLeft += child.getMeasuredWidth();
break;
case Gravity.CENTER_HORIZONTAL:
childLeft = Math.max((width - child.getMeasuredWidth()) / 2,
paddingLeft);
break;
case Gravity.RIGHT:
childLeft = width - paddingRight - child.getMeasuredWidth();
paddingRight += child.getMeasuredWidth();
break;
}
switch (vgrav) {
default:
childTop = paddingTop;
break;
case Gravity.TOP:
childTop = paddingTop;
paddingTop += child.getMeasuredHeight();
break;
case Gravity.CENTER_VERTICAL:
childTop = Math.max((height - child.getMeasuredHeight()) / 2,
paddingTop);
break;
case Gravity.BOTTOM:
childTop = height - paddingBottom - child.getMeasuredHeight();
paddingBottom += child.getMeasuredHeight();
break;
}
childLeft += scrollX;
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
decorCount++;
}
}
}
final int childWidth = width - paddingLeft - paddingRight;
// Page views. Do this once we have the right padding offsets from above.
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
ItemInfo ii;
if (!lp.isDecor && (ii = infoForChild(child)) != null) {
int loff = (int) (childWidth * ii.offset);
int childLeft = paddingLeft + loff;
int childTop = paddingTop;
if (lp.needsMeasure) {
// This was added during layout and needs measurement.
// Do it now that we know what we're working with.
lp.needsMeasure = false;
final int widthSpec = MeasureSpec.makeMeasureSpec(
(int) (childWidth * lp.widthFactor),
MeasureSpec.EXACTLY);
final int heightSpec = MeasureSpec.makeMeasureSpec(
(int) (height - paddingTop - paddingBottom),
MeasureSpec.EXACTLY);
child.measure(widthSpec, heightSpec);
}
if (DEBUG) Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object
+ ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth()
+ "x" + child.getMeasuredHeight());
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
}
}
}
mTopPageBounds = paddingTop;
mBottomPageBounds = height - paddingBottom;
mDecorChildCount = decorCount;
if (mFirstLayout) {
scrollToItem(mCurItem, false, 0, false);
}
mFirstLayout = false;
}
@Override
public void computeScroll() {
if (!mScroller.isFinished() && mScroller.computeScrollOffset()) {
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
if (!pageScrolled(x)) {
mScroller.abortAnimation();
scrollTo(0, y);
}
}
// Keep on drawing until the animation has finished.
ViewCompat.postInvalidateOnAnimation(this);
return;
}
// Done with scroll, clean up state.
completeScroll(true);
}
private boolean pageScrolled(int xpos) {
if (mItems.size() == 0) {
mCalledSuper = false;
onPageScrolled(0, 0, 0);
if (!mCalledSuper) {
throw new IllegalStateException(
"onPageScrolled did not call superclass implementation");
}
return false;
}
final ItemInfo ii = infoForCurrentScrollPosition();
final int width = getClientWidth();
final int widthWithMargin = width + mPageMargin;
final float marginOffset = (float) mPageMargin / width;
final int currentPage = ii.position;
final float pageOffset = (((float) xpos / width) - ii.offset) /
(ii.widthFactor + marginOffset);
final int offsetPixels = (int) (pageOffset * widthWithMargin);
mCalledSuper = false;
onPageScrolled(currentPage, pageOffset, offsetPixels);
if (!mCalledSuper) {
throw new IllegalStateException(
"onPageScrolled did not call superclass implementation");
}
return true;
}
/**
* This method will be invoked when the current page is scrolled, either as part
* of a programmatically initiated smooth scroll or a user initiated touch scroll.
* If you override this method you must call through to the superclass implementation
* (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled
* returns.
*
* @param position Position index of the first page currently being displayed.
* Page position+1 will be visible if positionOffset is nonzero.
* @param offset Value from [0, 1) indicating the offset from the page at position.
* @param offsetPixels Value in pixels indicating the offset from position.
*/
protected void onPageScrolled(int position, float offset, int offsetPixels) {
// Offset any decor views if needed - keep them on-screen at all times.
if (mDecorChildCount > 0) {
final int scrollX = getScrollX();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
final int width = getWidth();
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.isDecor) continue;
final int hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
int childLeft = 0;
switch (hgrav) {
default:
childLeft = paddingLeft;
break;
case Gravity.LEFT:
childLeft = paddingLeft;
paddingLeft += child.getWidth();
break;
case Gravity.CENTER_HORIZONTAL:
childLeft = Math.max((width - child.getMeasuredWidth()) / 2,
paddingLeft);
break;
case Gravity.RIGHT:
childLeft = width - paddingRight - child.getMeasuredWidth();
paddingRight += child.getMeasuredWidth();
break;
}
childLeft += scrollX;
final int childOffset = childLeft - child.getLeft();
if (childOffset != 0) {
child.offsetLeftAndRight(childOffset);
}
}
}
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels);
}
if (mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels);
}
if (mPageTransformer != null) {
final int scrollX = getScrollX();
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.isDecor) continue;
final float transformPos = (float) (child.getLeft() - scrollX) / getClientWidth();
mPageTransformer.transformPage(child, transformPos);
}
}
mCalledSuper = true;
}
private void completeScroll(boolean postEvents) {
boolean needPopulate = mScrollState == SCROLL_STATE_SETTLING;
if (needPopulate) {
// Done with scroll, no longer want to cache view drawing.
setScrollingCacheEnabled(false);
mScroller.abortAnimation();
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
}
}
mPopulatePending = false;
for (int i=0; i<mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
if (ii.scrolling) {
needPopulate = true;
ii.scrolling = false;
}
}
if (needPopulate) {
if (postEvents) {
ViewCompat.postOnAnimation(this, mEndScrollRunnable);
} else {
mEndScrollRunnable.run();
}
}
}
private boolean isGutterDrag(float x, float dx) {
return (x < mGutterSize && dx > 0) || (x > getWidth() - mGutterSize && dx < 0);
}
private void enableLayers(boolean enable) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final int layerType = enable ?
ViewCompat.LAYER_TYPE_HARDWARE : ViewCompat.LAYER_TYPE_NONE;
ViewCompat.setLayerType(getChildAt(i), layerType, null);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onMotionEvent will be called and we do the actual
* scrolling there.
*/
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
// Always take care of the touch gesture being complete.
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Release the drag.
if (DEBUG) Log.v(TAG, "Intercept done!");
mIsBeingDragged = false;
mIsUnableToDrag = false;
mActivePointerId = INVALID_POINTER;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
return false;
}
// Nothing more to do here if we have decided whether or not we
// are dragging.
if (action != MotionEvent.ACTION_DOWN) {
if (mIsBeingDragged) {
if (DEBUG) Log.v(TAG, "Intercept returning true!");
return true;
}
if (mIsUnableToDrag) {
if (DEBUG) Log.v(TAG, "Intercept returning false!");
return false;
}
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
* whether the user has moved far enough from his original down touch.
*/
/*
* Locally do absolute value. mLastMotionY is set to the y value
* of the down event.
*/
final int activePointerId = mActivePointerId;
if (activePointerId == INVALID_POINTER) {
// If we don't have a valid id, the touch down wasn't on content.
break;
}
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId);
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float dx = x - mLastMotionX;
final float xDiff = Math.abs(dx);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mInitialMotionY);
if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
if (dx != 0 && !isGutterDrag(mLastMotionX, dx) &&
canScroll(this, false, (int) dx, (int) x, (int) y)) {
// Nested view has scrollable area under this point. Let it be handled there.
mLastMotionX = x;
mLastMotionY = y;
mIsUnableToDrag = true;
return false;
}
if (xDiff > mTouchSlop && xDiff * 0.5f > yDiff) {
if (DEBUG) Log.v(TAG, "Starting drag!");
mIsBeingDragged = true;
requestParentDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
mLastMotionX = dx > 0 ? mInitialMotionX + mTouchSlop :
mInitialMotionX - mTouchSlop;
mLastMotionY = y;
setScrollingCacheEnabled(true);
} else if (yDiff > mTouchSlop) {
// The finger has moved enough in the vertical
// direction to be counted as a drag... abort
// any attempt to drag horizontally, to work correctly
// with children that have scrolling containers.
if (DEBUG) Log.v(TAG, "Starting unable to drag!");
mIsUnableToDrag = true;
}
if (mIsBeingDragged) {
// Scroll to follow the motion event
if (performDrag(x)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
/*
* Remember location of down touch.
* ACTION_DOWN always refers to pointer index 0.
*/
mLastMotionX = mInitialMotionX = ev.getX();
mLastMotionY = mInitialMotionY = ev.getY();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsUnableToDrag = false;
mScroller.computeScrollOffset();
if (mScrollState == SCROLL_STATE_SETTLING &&
Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) > mCloseEnough) {
// Let the user 'catch' the pager as it animates.
mScroller.abortAnimation();
mPopulatePending = false;
populate();
mIsBeingDragged = true;
requestParentDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
} else {
completeScroll(false);
mIsBeingDragged = false;
}
if (DEBUG) Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY
+ " mIsBeingDragged=" + mIsBeingDragged
+ "mIsUnableToDrag=" + mIsUnableToDrag);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
/*
* The only time we want to intercept motion events is if we are in the
* drag mode.
*/
return mIsBeingDragged;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mFakeDragging) {
// A fake drag is in progress already, ignore this real one
// but still eat the touch events.
// (It is likely that the user is multi-touching the screen.)
return true;
}
if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
// Don't handle edge touches immediately -- they may actually belong to one of our
// descendants.
return false;
}
if (mAdapter == null || mAdapter.getCount() == 0) {
// Nothing to present or scroll; nothing to touch.
return false;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
final int action = ev.getAction();
boolean needsInvalidate = false;
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
mScroller.abortAnimation();
mPopulatePending = false;
populate();
// Remember where the motion event started
mLastMotionX = mInitialMotionX = ev.getX();
mLastMotionY = mInitialMotionY = ev.getY();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
break;
}
case MotionEvent.ACTION_MOVE:
if (!mIsBeingDragged) {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, pointerIndex);
final float xDiff = Math.abs(x - mLastMotionX);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mLastMotionY);
if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
if (xDiff > mTouchSlop && xDiff > yDiff) {
if (DEBUG) Log.v(TAG, "Starting drag!");
mIsBeingDragged = true;
requestParentDisallowInterceptTouchEvent(true);
mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop :
mInitialMotionX - mTouchSlop;
mLastMotionY = y;
setScrollState(SCROLL_STATE_DRAGGING);
setScrollingCacheEnabled(true);
// Disallow Parent Intercept, just in case
ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
}
// Not else! Note that mIsBeingDragged can be set above.
if (mIsBeingDragged) {
// Scroll to follow the motion event
final int activePointerIndex = MotionEventCompat.findPointerIndex(
ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
needsInvalidate |= performDrag(x);
}
break;
case MotionEvent.ACTION_UP:
if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
velocityTracker, mActivePointerId);
mPopulatePending = true;
final int width = getClientWidth();
final int scrollX = getScrollX();
final ItemInfo ii = infoForCurrentScrollPosition();
final int currentPage = ii.position;
final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;
final int activePointerIndex =
MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float x = MotionEventCompat.getX(ev, activePointerIndex);
final int totalDelta = (int) (x - mInitialMotionX);
int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity,
totalDelta);
setCurrentItemInternal(nextPage, true, true, initialVelocity);
mActivePointerId = INVALID_POINTER;
endDrag();
needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsBeingDragged) {
scrollToItem(mCurItem, true, 0, false);
mActivePointerId = INVALID_POINTER;
endDrag();
needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
final float x = MotionEventCompat.getX(ev, index);
mLastMotionX = x;
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastMotionX = MotionEventCompat.getX(ev,
MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
return true;
}
private void requestParentDisallowInterceptTouchEvent(boolean disallowIntercept) {
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
private boolean performDrag(float x) {
boolean needsInvalidate = false;
final float deltaX = mLastMotionX - x;
mLastMotionX = x;
float oldScrollX = getScrollX();
float scrollX = oldScrollX + deltaX;
final int width = getClientWidth();
float leftBound = width * mFirstOffset;
float rightBound = width * mLastOffset;
boolean leftAbsolute = true;
boolean rightAbsolute = true;
final ItemInfo firstItem = mItems.get(0);
final ItemInfo lastItem = mItems.get(mItems.size() - 1);
if (firstItem.position != 0) {
leftAbsolute = false;
leftBound = firstItem.offset * width;
}
if (lastItem.position != mAdapter.getCount() - 1) {
rightAbsolute = false;
rightBound = lastItem.offset * width;
}
if (scrollX < leftBound) {
if (leftAbsolute) {
float over = leftBound - scrollX;
needsInvalidate = mLeftEdge.onPull(Math.abs(over) / width);
}
scrollX = leftBound;
} else if (scrollX > rightBound) {
if (rightAbsolute) {
float over = scrollX - rightBound;
needsInvalidate = mRightEdge.onPull(Math.abs(over) / width);
}
scrollX = rightBound;
}
// Don't lose the rounded component
mLastMotionX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
pageScrolled((int) scrollX);
return needsInvalidate;
}
/**
* @return Info about the page at the current scroll position.
* This can be synthetic for a missing middle page; the 'object' field can be null.
*/
private ItemInfo infoForCurrentScrollPosition() {
final int width = getClientWidth();
final float scrollOffset = width > 0 ? (float) getScrollX() / width : 0;
final float marginOffset = width > 0 ? (float) mPageMargin / width : 0;
int lastPos = -1;
float lastOffset = 0.f;
float lastWidth = 0.f;
boolean first = true;
ItemInfo lastItem = null;
for (int i = 0; i < mItems.size(); i++) {
ItemInfo ii = mItems.get(i);
float offset;
if (!first && ii.position != lastPos + 1) {
// Create a synthetic item for a missing page.
ii = mTempItem;
ii.offset = lastOffset + lastWidth + marginOffset;
ii.position = lastPos + 1;
ii.widthFactor = mAdapter.getPageWidth(ii.position);
i--;
}
offset = ii.offset;
final float leftBound = offset;
final float rightBound = offset + ii.widthFactor + marginOffset;
if (first || scrollOffset >= leftBound) {
if (scrollOffset < rightBound || i == mItems.size() - 1) {
return ii;
}
} else {
return lastItem;
}
first = false;
lastPos = ii.position;
lastOffset = offset;
lastWidth = ii.widthFactor;
lastItem = ii;
}
return lastItem;
}
private int determineTargetPage(int currentPage, float pageOffset, int velocity, int deltaX) {
int targetPage;
if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) {
targetPage = velocity > 0 ? currentPage : currentPage + 1;
} else {
final float truncator = currentPage >= mCurItem ? 0.4f : 0.6f;
targetPage = (int) (currentPage + pageOffset + truncator);
}
if (mItems.size() > 0) {
final ItemInfo firstItem = mItems.get(0);
final ItemInfo lastItem = mItems.get(mItems.size() - 1);
// Only let the user target pages we have items for
targetPage = Math.max(firstItem.position, Math.min(targetPage, lastItem.position));
}
return targetPage;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
boolean needsInvalidate = false;
final int overScrollMode = ViewCompat.getOverScrollMode(this);
if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS ||
(overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS &&
mAdapter != null && mAdapter.getCount() > 1)) {
if (!mLeftEdge.isFinished()) {
final int restoreCount = canvas.save();
final int height = getHeight() - getPaddingTop() - getPaddingBottom();
final int width = getWidth();
canvas.rotate(270);
canvas.translate(-height + getPaddingTop(), mFirstOffset * width);
mLeftEdge.setSize(height, width);
needsInvalidate |= mLeftEdge.draw(canvas);
canvas.restoreToCount(restoreCount);
}
if (!mRightEdge.isFinished()) {
final int restoreCount = canvas.save();
final int width = getWidth();
final int height = getHeight() - getPaddingTop() - getPaddingBottom();
canvas.rotate(90);
canvas.translate(-getPaddingTop(), -(mLastOffset + 1) * width);
mRightEdge.setSize(height, width);
needsInvalidate |= mRightEdge.draw(canvas);
canvas.restoreToCount(restoreCount);
}
} else {
mLeftEdge.finish();
mRightEdge.finish();
}
if (needsInvalidate) {
// Keep animating
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the margin drawable between pages if needed.
if (mPageMargin > 0 && mMarginDrawable != null && mItems.size() > 0 && mAdapter != null) {
final int scrollX = getScrollX();
final int width = getWidth();
final float marginOffset = (float) mPageMargin / width;
int itemIndex = 0;
ItemInfo ii = mItems.get(0);
float offset = ii.offset;
final int itemCount = mItems.size();
final int firstPos = ii.position;
final int lastPos = mItems.get(itemCount - 1).position;
for (int pos = firstPos; pos < lastPos; pos++) {
while (pos > ii.position && itemIndex < itemCount) {
ii = mItems.get(++itemIndex);
}
float drawAt;
if (pos == ii.position) {
drawAt = (ii.offset + ii.widthFactor) * width;
offset = ii.offset + ii.widthFactor + marginOffset;
} else {
float widthFactor = mAdapter.getPageWidth(pos);
drawAt = (offset + widthFactor) * width;
offset += widthFactor + marginOffset;
}
if (drawAt + mPageMargin > scrollX) {
mMarginDrawable.setBounds((int) drawAt, mTopPageBounds,
(int) (drawAt + mPageMargin + 0.5f), mBottomPageBounds);
mMarginDrawable.draw(canvas);
}
if (drawAt > scrollX + width) {
break; // No more visible, no sense in continuing
}
}
}
}
/**
* Start a fake drag of the pager.
*
* <p>A fake drag can be useful if you want to synchronize the motion of the ViewPager
* with the touch scrolling of another view, while still letting the ViewPager
* control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.)
* Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call
* {@link #endFakeDrag()} to complete the fake drag and fling as necessary.
*
* <p>During a fake drag the ViewPager will ignore all touch events. If a real drag
* is already in progress, this method will return false.
*
* @return true if the fake drag began successfully, false if it could not be started.
*
* @see #fakeDragBy(float)
* @see #endFakeDrag()
*/
public boolean beginFakeDrag() {
if (mIsBeingDragged) {
return false;
}
mFakeDragging = true;
setScrollState(SCROLL_STATE_DRAGGING);
mInitialMotionX = mLastMotionX = 0;
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
} else {
mVelocityTracker.clear();
}
final long time = SystemClock.uptimeMillis();
final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0);
mVelocityTracker.addMovement(ev);
ev.recycle();
mFakeDragBeginTime = time;
return true;
}
/**
* End a fake drag of the pager.
*
* @see #beginFakeDrag()
* @see #fakeDragBy(float)
*/
public void endFakeDrag() {
if (!mFakeDragging) {
throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
}
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
velocityTracker, mActivePointerId);
mPopulatePending = true;
final int width = getClientWidth();
final int scrollX = getScrollX();
final ItemInfo ii = infoForCurrentScrollPosition();
final int currentPage = ii.position;
final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;
final int totalDelta = (int) (mLastMotionX - mInitialMotionX);
int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity,
totalDelta);
setCurrentItemInternal(nextPage, true, true, initialVelocity);
endDrag();
mFakeDragging = false;
}
/**
* Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first.
*
* @param xOffset Offset in pixels to drag by.
* @see #beginFakeDrag()
* @see #endFakeDrag()
*/
public void fakeDragBy(float xOffset) {
if (!mFakeDragging) {
throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
}
mLastMotionX += xOffset;
float oldScrollX = getScrollX();
float scrollX = oldScrollX - xOffset;
final int width = getClientWidth();
float leftBound = width * mFirstOffset;
float rightBound = width * mLastOffset;
final ItemInfo firstItem = mItems.get(0);
final ItemInfo lastItem = mItems.get(mItems.size() - 1);
if (firstItem.position != 0) {
leftBound = firstItem.offset * width;
}
if (lastItem.position != mAdapter.getCount() - 1) {
rightBound = lastItem.offset * width;
}
if (scrollX < leftBound) {
scrollX = leftBound;
} else if (scrollX > rightBound) {
scrollX = rightBound;
}
// Don't lose the rounded component
mLastMotionX += scrollX - (int) scrollX;
scrollTo((int) scrollX, getScrollY());
pageScrolled((int) scrollX);
// Synthesize an event for the VelocityTracker.
final long time = SystemClock.uptimeMillis();
final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE,
mLastMotionX, 0, 0);
mVelocityTracker.addMovement(ev);
ev.recycle();
}
/**
* Returns true if a fake drag is in progress.
*
* @return true if currently in a fake drag, false otherwise.
*
* @see #beginFakeDrag()
* @see #fakeDragBy(float)
* @see #endFakeDrag()
*/
public boolean isFakeDragging() {
return mFakeDragging;
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
private void endDrag() {
mIsBeingDragged = false;
mIsUnableToDrag = false;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
private void setScrollingCacheEnabled(boolean enabled) {
if (mScrollingCacheEnabled != enabled) {
mScrollingCacheEnabled = enabled;
if (USE_CACHE) {
final int size = getChildCount();
for (int i = 0; i < size; ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.setDrawingCacheEnabled(enabled);
}
}
}
}
}
public boolean canScrollHorizontally(int direction) {
if (mAdapter == null) {
return false;
}
final int width = getClientWidth();
final int scrollX = getScrollX();
if (direction < 0) {
return (scrollX > (int) (width * mFirstOffset));
} else if (direction > 0) {
return (scrollX < (int) (width * mLastOffset));
} else {
return false;
}
}
/**
* Tests scrollability within child views of v given a delta of dx.
*
* @param v View to test for horizontal scrollability
* @param checkV Whether the view v passed should itself be checked for scrollability (true),
* or just its children (false).
* @param dx Delta scrolled in pixels
* @param x X coordinate of the active touch point
* @param y Y coordinate of the active touch point
* @return true if child views of v can be scrolled by delta of dx.
*/
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
final int scrollY = v.getScrollY();
final int count = group.getChildCount();
// Count backwards - let topmost views consume scroll distance first.
for (int i = count - 1; i >= 0; i--) {
// TODO: Add versioned support here for transformed views.
// This will not work for transformed views in Honeycomb+
final View child = group.getChildAt(i);
if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() &&
y + scrollY >= child.getTop() && y + scrollY < child.getBottom() &&
canScroll(child, true, dx, x + scrollX - child.getLeft(),
y + scrollY - child.getTop())) {
return true;
}
}
}
return checkV && ViewCompat.canScrollHorizontally(v, -dx);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// Let the focused view and/or our descendants get the key first
return super.dispatchKeyEvent(event) || executeKeyEvent(event);
}
/**
* You can call this function yourself to have the scroll view perform
* scrolling from a key event, just as if the event had been dispatched to
* it by the view hierarchy.
*
* @param event The key event to execute.
* @return Return true if the event was handled, else false.
*/
public boolean executeKeyEvent(KeyEvent event) {
boolean handled = false;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_LEFT:
handled = arrowScroll(FOCUS_LEFT);
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
handled = arrowScroll(FOCUS_RIGHT);
break;
case KeyEvent.KEYCODE_TAB:
if (Build.VERSION.SDK_INT >= 11) {
// The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD
// before Android 3.0. Ignore the tab key on those devices.
if (KeyEventCompat.hasNoModifiers(event)) {
handled = arrowScroll(FOCUS_FORWARD);
} else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
handled = arrowScroll(FOCUS_BACKWARD);
}
}
break;
}
}
return handled;
}
public boolean arrowScroll(int direction) {
View currentFocused = findFocus();
if (currentFocused == this) {
currentFocused = null;
} else if (currentFocused != null) {
boolean isChild = false;
for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup;
parent = parent.getParent()) {
if (parent == this) {
isChild = true;
break;
}
}
if (!isChild) {
// This would cause the focus search down below to fail in fun ways.
final StringBuilder sb = new StringBuilder();
sb.append(currentFocused.getClass().getSimpleName());
for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup;
parent = parent.getParent()) {
sb.append(" => ").append(parent.getClass().getSimpleName());
}
Log.e(TAG, "arrowScroll tried to find focus based on non-child " +
"current focused view " + sb.toString());
currentFocused = null;
}
}
boolean handled = false;
View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused,
direction);
if (nextFocused != null && nextFocused != currentFocused) {
if (direction == View.FOCUS_LEFT) {
// If there is nothing to the left, or this is causing us to
// jump to the right, then what we really want to do is page left.
final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
if (currentFocused != null && nextLeft >= currLeft) {
handled = pageLeft();
} else {
handled = nextFocused.requestFocus();
}
} else if (direction == View.FOCUS_RIGHT) {
// If there is nothing to the right, or this is causing us to
// jump to the left, then what we really want to do is page right.
final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
if (currentFocused != null && nextLeft <= currLeft) {
handled = pageRight();
} else {
handled = nextFocused.requestFocus();
}
}
} else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {
// Trying to move left and nothing there; try to page.
handled = pageLeft();
} else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {
// Trying to move right and nothing there; try to page.
handled = pageRight();
}
if (handled) {
playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
}
return handled;
}
private Rect getChildRectInPagerCoordinates(Rect outRect, View child) {
if (outRect == null) {
outRect = new Rect();
}
if (child == null) {
outRect.set(0, 0, 0, 0);
return outRect;
}
outRect.left = child.getLeft();
outRect.right = child.getRight();
outRect.top = child.getTop();
outRect.bottom = child.getBottom();
ViewParent parent = child.getParent();
while (parent instanceof ViewGroup && parent != this) {
final ViewGroup group = (ViewGroup) parent;
outRect.left += group.getLeft();
outRect.right += group.getRight();
outRect.top += group.getTop();
outRect.bottom += group.getBottom();
parent = group.getParent();
}
return outRect;
}
boolean pageLeft() {
if (mCurItem > 0) {
setCurrentItem(mCurItem-1, true);
return true;
}
return false;
}
boolean pageRight() {
if (mAdapter != null && mCurItem < (mAdapter.getCount()-1)) {
setCurrentItem(mCurItem+1, true);
return true;
}
return false;
}
/**
* We only want the current page that is being shown to be focusable.
*/
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
final int focusableCount = views.size();
final int descendantFocusability = getDescendantFocusability();
if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
child.addFocusables(views, direction, focusableMode);
}
}
}
}
// we add ourselves (if focusable) in all cases except for when we are
// FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is
// to avoid the focus search finding layouts when a more precise search
// among the focusable children would be more interesting.
if (
descendantFocusability != FOCUS_AFTER_DESCENDANTS ||
// No focusable descendants
(focusableCount == views.size())) {
// Note that we can't call the superclass here, because it will
// add all views in. So we need to do the same thing View does.
if (!isFocusable()) {
return;
}
if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
isInTouchMode() && !isFocusableInTouchMode()) {
return;
}
if (views != null) {
views.add(this);
}
}
}
/**
* We only want the current page that is being shown to be touchable.
*/
@Override
public void addTouchables(ArrayList<View> views) {
// Note that we don't call super.addTouchables(), which means that
// we don't call View.addTouchables(). This is okay because a ViewPager
// is itself not touchable.
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
child.addTouchables(views);
}
}
}
}
/**
* We only want the current page that is being shown to be focusable.
*/
@Override
protected boolean onRequestFocusInDescendants(int direction,
Rect previouslyFocusedRect) {
int index;
int increment;
int end;
int count = getChildCount();
if ((direction & FOCUS_FORWARD) != 0) {
index = 0;
increment = 1;
end = count;
} else {
index = count - 1;
increment = -1;
end = -1;
}
for (int i = index; i != end; i += increment) {
View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(direction, previouslyFocusedRect)) {
return true;
}
}
}
}
return false;
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
// Dispatch scroll events from this ViewPager.
if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED) {
return super.dispatchPopulateAccessibilityEvent(event);
}
// Dispatch all other accessibility events from the current page.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
final ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem &&
child.dispatchPopulateAccessibilityEvent(event)) {
return true;
}
}
}
return false;
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams();
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return generateDefaultLayoutParams();
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
class MyAccessibilityDelegate extends AccessibilityDelegateCompat {
@Override
public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(host, event);
event.setClassName(ViewPagerEx.class.getName());
final AccessibilityRecordCompat recordCompat = AccessibilityRecordCompat.obtain();
recordCompat.setScrollable(canScroll());
if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED
&& mAdapter != null) {
recordCompat.setItemCount(mAdapter.getCount());
recordCompat.setFromIndex(mCurItem);
recordCompat.setToIndex(mCurItem);
}
}
@Override
public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
super.onInitializeAccessibilityNodeInfo(host, info);
info.setClassName(ViewPagerEx.class.getName());
info.setScrollable(canScroll());
if (canScrollHorizontally(1)) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
}
if (canScrollHorizontally(-1)) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
}
}
@Override
public boolean performAccessibilityAction(View host, int action, Bundle args) {
if (super.performAccessibilityAction(host, action, args)) {
return true;
}
switch (action) {
case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: {
if (canScrollHorizontally(1)) {
setCurrentItem(mCurItem + 1);
return true;
}
} return false;
case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: {
if (canScrollHorizontally(-1)) {
setCurrentItem(mCurItem - 1);
return true;
}
} return false;
}
return false;
}
private boolean canScroll() {
return (mAdapter != null) && (mAdapter.getCount() > 1);
}
}
private class PagerObserver extends DataSetObserver {
@Override
public void onChanged() {
dataSetChanged();
}
@Override
public void onInvalidated() {
dataSetChanged();
}
}
/**
* Layout parameters that should be supplied for views added to a
* ViewPager.
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
/**
* true if this view is a decoration on the pager itself and not
* a view supplied by the adapter.
*/
public boolean isDecor;
/**
* Gravity setting for use on decor views only:
* Where to position the view page within the overall ViewPager
* container; constants are defined in {@link android.view.Gravity}.
*/
public int gravity;
/**
* Width as a 0-1 multiplier of the measured pager width
*/
float widthFactor = 0.f;
/**
* true if this view was added during layout and needs to be measured
* before being positioned.
*/
boolean needsMeasure;
/**
* Adapter position this view is for if !isDecor
*/
int position;
/**
* Current child index within the ViewPager that this view occupies
*/
int childIndex;
public LayoutParams() {
super(FILL_PARENT, FILL_PARENT);
}
public LayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
gravity = a.getInteger(0, Gravity.TOP);
a.recycle();
}
}
static class ViewPositionComparator implements Comparator<View> {
@Override
public int compare(View lhs, View rhs) {
final LayoutParams llp = (LayoutParams) lhs.getLayoutParams();
final LayoutParams rlp = (LayoutParams) rhs.getLayoutParams();
if (llp.isDecor != rlp.isDecor) {
return llp.isDecor ? 1 : -1;
}
return llp.position - rlp.position;
}
}
}
| mit |
srecon/quartz-scheduler | src/main/java/com/blu/scheduler/AltynJob.java | 524 | package com.blu.scheduler;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by shamim on 07/12/15.
*/
public class AltynJob implements Job {
private Logger logger = LoggerFactory.getLogger(AltynJob.class);
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
logger.info("Do something useful!!", jobExecutionContext);
}
}
| mit |
bloodmc/StorageDrawers | packs/BiomesOPlenty/src/com/jaquadro/minecraft/storagedrawers/packs/bop/CommonProxy.java | 88 | package com.jaquadro.minecraft.storagedrawers.packs.bop;
public class CommonProxy
{
}
| mit |
haducloc/appslandia-plum | src/test/java/com/appslandia/plum/mocks/MockHttpSessionTest.java | 1451 | package com.appslandia.plum.mocks;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MockHttpSessionTest {
MockServletContext servletContext;
@Before
public void init() {
servletContext = new MockServletContext(new MockSessionCookieConfig());
}
@Test
public void testMockHttpSession() {
MockHttpSession session = new MockHttpSession(servletContext);
Assert.assertNotNull(session.getServletContext());
session.setMaxInactiveInterval(1800);
Assert.assertEquals(session.getMaxInactiveInterval(), 1800);
}
@Test
public void testSessionAttributes() {
MockHttpSession session = new MockHttpSession(servletContext);
session.setAttribute("attr1", "value1");
session.setAttribute("attr2", "value2");
Assert.assertEquals(session.getAttribute("attr1"), "value1");
Assert.assertNull(session.getAttribute("attr3"));
session.removeAttribute("attr2");
Assert.assertNull(session.getAttribute("attr2"));
}
@Test
public void testSessionInvalidate() {
MockHttpSession session = new MockHttpSession(servletContext);
// isInvalidated
Assert.assertFalse(session.isInvalidated());
session.invalidate();
Assert.assertTrue(session.isInvalidated());
}
@Test
public void testChangeSessionId() {
MockHttpSession session = new MockHttpSession(servletContext);
String oldId = session.getId();
session.changeSessionId();
Assert.assertNotEquals(session.getId(), oldId);
}
}
| mit |
iansoftdev/all-blockchain | src/main/java/io/iansoft/blockchain/repository/package-info.java | 83 | /**
* Spring Data JPA repositories.
*/
package io.iansoft.blockchain.repository;
| mit |
dblogcorp/dblog | sso/src/main/java/io/dblog/sso/rpc/PrivateLetterRpcService.java | 107 | package io.dblog.sso.rpc;
/**
* Created by Pelin on 17/8/1.
*/
public class PrivateLetterRpcService {
}
| mit |
gregemel/spaceglad | core/src/com/emelwerx/world/databags/World.java | 3280 | package com.emelwerx.world.databags;
import com.badlogic.ashley.core.Engine;
import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.physics.bullet.DebugDrawer;
import com.emelwerx.world.systems.PhysicsSystem;
import com.emelwerx.world.systems.PlayerSystem;
import com.emelwerx.world.systems.RenderSystem;
public class World {
private String name;
private boolean debug = false;
private DebugDrawer debugDrawer;
private Engine entityEngine;
private Entity entityCharacter;
private Entity entityPlayerItem;
private PhysicsSystem physicsSystem;
private PlayerSystem playerSystem;
private RenderSystem renderSystem;
private PerspectiveCamera worldPerspectiveCamera;
private Scene currentScene;
private String firstSceneName;
public PerspectiveCamera getWorldPerspectiveCamera() {
return worldPerspectiveCamera;
}
public void setWorldPerspectiveCamera(PerspectiveCamera worldPerspectiveCamera) {
this.worldPerspectiveCamera = worldPerspectiveCamera;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstSceneName() {
return firstSceneName;
}
public void setFirstSceneName(String firstSceneName) {
this.firstSceneName = firstSceneName;
}
public Scene getCurrentScene() {
return currentScene;
}
public void setCurrentScene(Scene currentScene) {
this.currentScene = currentScene;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public DebugDrawer getDebugDrawer() {
return debugDrawer;
}
public void setDebugDrawer(DebugDrawer debugDrawer) {
this.debugDrawer = debugDrawer;
}
public Engine getEntityEngine() {
return entityEngine;
}
public void setEntityEngine(Engine entityEngine) {
this.entityEngine = entityEngine;
}
public Entity getEntityCharacter() {
return entityCharacter;
}
public void setEntityCharacter(Entity entityCharacter) {
this.entityCharacter = entityCharacter;
}
public void setPlayer(Entity character) {
this.entityCharacter = character;
}
public Entity getEntityPlayerItem() {
return entityPlayerItem;
}
public void setEntityPlayerItem(Entity entityPlayerItem) {
this.entityPlayerItem = entityPlayerItem;
}
public PhysicsSystem getPhysicsSystem() {
return physicsSystem;
}
public void setPhysicsSystem(PhysicsSystem physicsSystem) {
this.physicsSystem = physicsSystem;
}
public PlayerSystem getPlayerSystem() {
return playerSystem;
}
public void setPlayerSystem(PlayerSystem playerSystem) {
this.playerSystem = playerSystem;
}
public RenderSystem getRenderSystem() {
return renderSystem;
}
public void setRenderSystem(RenderSystem renderSystem) {
this.renderSystem = renderSystem;
}
} | mit |
iwb-project/iwb-site | src/main/java/org/iwb/site/repository/UserDao.java | 360 | package org.iwb.site.repository;
import org.iwb.site.bo.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* Manages the users.
*
* @author Mathieu POUSSE <mathieu.pousse@zenika.com>
*/
public interface UserDao extends PagingAndSortingRepository<User, String> {
}
| mit |
sanosom/labs-gr7 | Lab4Weather/app/src/main/java/co/edu/udea/compumovil/lab4weather/MainActivity.java | 4388 | package co.edu.udea.compumovil.lab4weather;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import co.edu.udea.compumovil.lab4weather.POJO.Model;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MainActivity extends AppCompatActivity {
TextView city, press, status, humidity;
ImageView image;
AutoCompleteTextView query;
String key = "8cf7cf9202e00e5a08c2bfdab7eea988";
String url = "http://api.openweathermap.org/data/2.5";
String url_image = "http://openweathermap.org/img/w/";
RestInterface restInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
city = (TextView) findViewById(R.id.txt_city);
press = (TextView) findViewById(R.id.txt_press);
status = (TextView) findViewById(R.id.txt_status);
humidity = (TextView) findViewById(R.id.txt_humidity);
image = (ImageView) findViewById(R.id.image);
query = (AutoCompleteTextView) findViewById(R.id.txt_query);
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(url).build();
restInterface = adapter.create(RestInterface.class);
ArrayAdapter<CharSequence> capitals = ArrayAdapter.createFromResource(this,
R.array.capitals, android.R.layout.simple_spinner_dropdown_item);
query.setAdapter(capitals);
}
public void getWeatherReport(View view) {
restInterface.getWheatherReport(query.getText().toString(), key, "es", new Callback<Model>() {
@Override
public void success(Model model, Response response) {
city.setText(String.format(getString(R.string.city_text), model.getName()));
press.setText(String.format(getString(R.string.pressure_text), model.getMain().getPressure().toString()));
status.setText(String.format(getString(R.string.status_text), model.getWeather().get(0).getDescription()));
humidity.setText(String.format(getString(R.string.humidity_text), model.getMain().getHumidity().toString()));
String code = model.getWeather().get(0).getIcon();
ImageDownloader imageDownloader = new ImageDownloader();
imageDownloader.execute(code);
}
@Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
HttpURLConnection con = null;
Bitmap img = null;
InputStream is = null;
try {
con = (HttpURLConnection) (new URL(url_image + params[0] + ".png")).openConnection();
con.setRequestMethod("GET");
con.connect();
is = con.getInputStream();
img = BitmapFactory.decodeStream(new BufferedInputStream(is));
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Throwable t) {
t.printStackTrace();
}
try {
if (con != null) {
con.disconnect();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
return img;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
image.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 250, 250, true));
}
}
}
}
| mit |
fieldenms/tg | platform-gps-server/src/main/java/ua/com/fielden/platform/gis/gps/actors/ChangedModule.java | 274 | package ua.com.fielden.platform.gis.gps.actors;
import ua.com.fielden.platform.gis.gps.AbstractAvlModule;
public class ChangedModule<MODULE extends AbstractAvlModule> extends Changed<MODULE> {
public ChangedModule(final MODULE value) {
super(value);
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/appservice/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/appservice/v2019_08_01/implementation/VnetRouteImpl.java | 4322 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.appservice.v2019_08_01.implementation;
import com.microsoft.azure.management.appservice.v2019_08_01.VnetRoute;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import com.microsoft.azure.management.appservice.v2019_08_01.RouteType;
class VnetRouteImpl extends CreatableUpdatableImpl<VnetRoute, VnetRouteInner, VnetRouteImpl> implements VnetRoute, VnetRoute.Definition, VnetRoute.Update {
private final AppServiceManager manager;
private String resourceGroupName;
private String name;
private String vnetName;
private String routeName;
VnetRouteImpl(String name, AppServiceManager manager) {
super(name, new VnetRouteInner());
this.manager = manager;
// Set resource name
this.routeName = name;
//
}
VnetRouteImpl(VnetRouteInner inner, AppServiceManager manager) {
super(inner.name(), inner);
this.manager = manager;
// Set resource name
this.routeName = inner.name();
// set resource ancestor and positional variables
this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups");
this.name = IdParsingUtils.getValueFromIdByName(inner.id(), "serverfarms");
this.vnetName = IdParsingUtils.getValueFromIdByName(inner.id(), "virtualNetworkConnections");
this.routeName = IdParsingUtils.getValueFromIdByName(inner.id(), "routes");
//
}
@Override
public AppServiceManager manager() {
return this.manager;
}
@Override
public Observable<VnetRoute> createResourceAsync() {
AppServicePlansInner client = this.manager().inner().appServicePlans();
return client.createOrUpdateVnetRouteAsync(this.resourceGroupName, this.name, this.vnetName, this.routeName, this.inner())
.map(innerToFluentMap(this));
}
@Override
public Observable<VnetRoute> updateResourceAsync() {
AppServicePlansInner client = this.manager().inner().appServicePlans();
return client.updateVnetRouteAsync(this.resourceGroupName, this.name, this.vnetName, this.routeName, this.inner())
.map(innerToFluentMap(this));
}
@Override
protected Observable<VnetRouteInner> getInnerAsync() {
AppServicePlansInner client = this.manager().inner().appServicePlans();
return null; // NOP getInnerAsync implementation as get is not supported
}
@Override
public boolean isInCreateMode() {
return this.inner().id() == null;
}
@Override
public String endAddress() {
return this.inner().endAddress();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String kind() {
return this.inner().kind();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public RouteType routeType() {
return this.inner().routeType();
}
@Override
public String startAddress() {
return this.inner().startAddress();
}
@Override
public String type() {
return this.inner().type();
}
@Override
public VnetRouteImpl withExistingVirtualNetworkConnection(String resourceGroupName, String name, String vnetName) {
this.resourceGroupName = resourceGroupName;
this.name = name;
this.vnetName = vnetName;
return this;
}
@Override
public VnetRouteImpl withEndAddress(String endAddress) {
this.inner().withEndAddress(endAddress);
return this;
}
@Override
public VnetRouteImpl withKind(String kind) {
this.inner().withKind(kind);
return this;
}
@Override
public VnetRouteImpl withRouteType(RouteType routeType) {
this.inner().withRouteType(routeType);
return this;
}
@Override
public VnetRouteImpl withStartAddress(String startAddress) {
this.inner().withStartAddress(startAddress);
return this;
}
}
| mit |
manywho/metrics | src/main/java/com/manywho/metrics/api/snippets/entities/database/State.java | 914 | package com.manywho.metrics.api.snippets.entities.database;
import javax.persistence.*;
import java.io.Serializable;
import java.util.UUID;
@Entity
@Table(name = "StatesJson")
@IdClass(State.PrimaryKey.class)
public class State {
@Id
@Column(name = "id")
private UUID id;
@Id
@ManyToOne
@JoinColumn(name = "manywhotenant_id")
private ManyWhoTenant tenant;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public ManyWhoTenant getTenant() {
return tenant;
}
public void setTenant(ManyWhoTenant tenant) {
this.tenant = tenant;
}
public static class PrimaryKey implements Serializable {
private final UUID id;
private final UUID tenant;
public PrimaryKey(UUID id, UUID tenant) {
this.id = id;
this.tenant = tenant;
}
}
}
| mit |
nico01f/z-pec | ZimbraSoap/src/wsdl-test/generated/zcsclient/account/testUpdateProfileRequest.java | 1483 |
package generated.zcsclient.account;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for updateProfileRequest complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="updateProfileRequest">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="profile" type="{urn:zimbraAccount}profileInfo"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "updateProfileRequest", propOrder = {
"profile"
})
public class testUpdateProfileRequest {
@XmlElement(required = true)
protected testProfileInfo profile;
/**
* Gets the value of the profile property.
*
* @return
* possible object is
* {@link testProfileInfo }
*
*/
public testProfileInfo getProfile() {
return profile;
}
/**
* Sets the value of the profile property.
*
* @param value
* allowed object is
* {@link testProfileInfo }
*
*/
public void setProfile(testProfileInfo value) {
this.profile = value;
}
}
| mit |
WiQuery/wiquery | wiquery-core/src/test/java/org/odlabs/wiquery/tester/matchers/ModelMatcher.java | 501 | package org.odlabs.wiquery.tester.matchers;
import org.apache.wicket.Component;
public class ModelMatcher implements ComponentMatcher
{
private final Object modelObject;
public ModelMatcher(Object object)
{
this.modelObject = object;
}
@Override
public boolean matches(Component component)
{
return modelObject.equals(component.getDefaultModelObject());
}
@Override
public String toString()
{
return "model=='" + modelObject != null ? modelObject.toString() : "null" + "'";
}
}
| mit |
zeljko-bal/JWAF | src/main/java/org/jwaf/agent/annotations/LocalPlatformAid.java | 724 | package org.jwaf.agent.annotations;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
import org.jwaf.agent.persistence.entity.AgentIdentifier;
/**
* A qualifier for injecting the {@link AgentIdentifier} that represents the local platform.
*
* @author zeljko.bal
*/
@Target({TYPE, METHOD, FIELD, PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface LocalPlatformAid
{}
| mit |
nidhinvv/BubbleAlert | app/src/test/java/com/dkv/bubblealertview/ExampleUnitTest.java | 412 | package com.dkv.bubblealertview;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | mit |
StreamerSpectrum/BeamTeamDiscordBot | src/main/java/com/StreamerSpectrum/BeamTeamDiscordBot/beam/services/TeamMembershipExpandedSearchResponse.java | 304 | package com.StreamerSpectrum.BeamTeamDiscordBot.beam.services;
import java.util.ArrayList;
import com.StreamerSpectrum.BeamTeamDiscordBot.beam.resource.TeamMembershipExpanded;
@SuppressWarnings("serial")
public class TeamMembershipExpandedSearchResponse extends ArrayList<TeamMembershipExpanded> {
}
| mit |
RishiRaj22/ExerciseCounter | app/src/main/java/me/itsrishi/exercisecounter/listeners/RecyclerViewClickListener.java | 1550 | /*
* MIT License
*
* Copyright (c) 2017 Rishi Raj
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package me.itsrishi.exercisecounter.listeners;
import android.view.View;
/**
* @author Rishi Raj
*/
public interface RecyclerViewClickListener {
/**
* Used to communicate click events from recycler view to its listener
*
* @param position The position of the item clicked on the list
* @param view The view of the item clicked
*/
void onClick(int position, View view);
}
| mit |
shvets/cafebabe | classfile/src/main/java/org/sf/classfile/PoolEntry.java | 269 | // PoolEntry.java
package org.sf.classfile;
/**
* Basic interface for any entry that could be inserted into pool.
*
* @version 1.0 02/22/2000
* @author Alexander Shvets
*/
public abstract class PoolEntry extends Entry implements Tagged, Resolvable {}
| mit |
venkatramanm/reflection | src/main/java/com/venky/reflection/BeanIntrospector.java | 1820 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.venky.reflection;
import java.lang.reflect.Method;
import java.util.Date;
/**
*
* @author venky
*/
public class BeanIntrospector<B> {
private Class<B> beanClass;
protected Class<B> getBeanClass(){
return beanClass;
}
protected BeanIntrospector(Class<B> beanClass) {
this.beanClass = beanClass;
}
private static Class<?>[] primitiveNumericClasses = new Class[] { int.class, short.class, long.class, double.class, float.class };
protected static boolean isNumeric(Class<?> headingClass){
if (Number.class.isAssignableFrom(headingClass)){
return true;
}
if (headingClass.isPrimitive()){
for (Class<?> pc : primitiveNumericClasses){
if (pc.equals(headingClass)){
return true;
}
}
}
return false;
}
protected static boolean isDate(Class<?> headClass){
return Date.class.isAssignableFrom(headClass);
}
protected static boolean isBoolean(Class<?> headClass){
return boolean.class.equals(headClass) || Boolean.class.isAssignableFrom(headClass) ;
}
protected Method getMethod(String methodName,Class<?> ... parameterTypes) {
try {
return beanClass.getMethod(methodName, parameterTypes);
} catch (Exception ex) {
return null;
}
}
protected B createInstance(){
try {
return beanClass.newInstance();
}catch (Exception e){
throw new RuntimeException(e);
}
}
protected Method getGetter(String heading) {
return getMethod("get"+heading,new Class[]{});
}
}
| mit |
torcato/JDBCValidator | test/src/epfl/dias/sql/TestStatement.java | 5174 | package epfl.dias.sql;
import org.apache.log4j.Logger;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.sql.*;
import static org.junit.Assert.fail;
/**
* Created by torcato on 08.06.15.
* Test cases for statement queries
*/
public class TestStatement extends TestStatementAncestor {
protected static Logger log = Logger.getLogger( Properties.class );
/**
* Sets up the configuration for the tests
* @throws ClassNotFoundException
* @throws java.io.FileNotFoundException
* @throws java.io.UnsupportedEncodingException
*/
@BeforeClass
public static void setProperties() throws ClassNotFoundException, FileNotFoundException, UnsupportedEncodingException {
// will load only the postgres driver
System.setProperty("validator.auto.load.popular.drivers", "false");
System.setProperty("validator.extra.drivers", "org.postgresql.Driver");
System.setProperty("validator.default.filter.confFile","query.filter.chuv.yaml");
//Maybe create a different configuration file for the default config
System.setProperty("validator.default.filter.confFile","query.filter.chuv.yaml");
System.setProperty("validator.configurations", "chuv,hug");
System.setProperty("validator.chuv.filter.confFile", "query.filter.chuv.yaml");
System.setProperty("validator.hug.filter.confFile", "query.filter.hug.yaml");
Class.forName("epfl.dias.sql.DriverValidator");
Properties.reloadConfig();
}
protected Connection connect(String url) throws SQLException {
String user = "ipython";
String passwd="ipython4thewin";
return DriverManager.getConnection(url, user, passwd);
}
/**
* Runs a single query against our test DB
* @param url the url of the db t connect
* @param query the query to run
* @throws SQLException
*/
protected void runExecuteQuery( String url, String query) throws SQLException {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = connect(url);
st = con.createStatement();
rs = st.executeQuery(query);
if (rs.next())
{
log.debug("result of the query :" + rs.getString(1));
}
}
catch(SQLException e)
{
log.debug(e);
throw e;
}
finally {
if (con != null) con.close();
if (st != null) st.close();
if (rs != null) rs.close();
}
con.close();
}
protected void runExecute( String url, String query) throws SQLException
{
Connection con = null;
Statement st = null;
try {
con = connect(url);
st = con.createStatement();
st.execute( query);
}
catch(SQLException e)
{
log.debug(e);
throw e;
}
finally {
if (con != null) con.close();
if (st != null) st.close();
}
con.close();
}
protected void runBatch(String url, String[] queries) throws SQLException {
Connection con = null;
Statement st = null;
try {
con = connect(url);
st = con.createStatement();
for(String query: queries)
{
st.addBatch(query);
}
st.executeBatch();
}
catch(SQLException e)
{
log.debug(e);
log.debug(e.getNextException());
throw e;
}
finally {
if (con != null) con.close();
if (st != null) st.close();
}
con.close();
}
@Test
public void testBatch() throws SQLException {
// middle query should not pass in first configuration
String[] queries = {
"SELECT count(patient.year_of_birth) from patient where patient.year_of_birth = 0",
"SELECT patient.year_of_birth FROM patient where patient.year_of_birth = 0",
"SELECT count(patient.year_of_birth) from patient where patient.year_of_birth = 0"
};
String url1 = "validate:chuv:jdbc:postgresql://localhost/CHUV_MIPS";
try {
runBatch(url1, queries);
fail("query should not pass the filter");
} catch (SQLFilterException e) {
log.debug("Exception was thrown as it should");
log.debug(e);
}
String url2 = "validate:hug:jdbc:postgresql://localhost/CHUV_MIPS";
try {
//this query has to pass
// the limit for year_of_birth is not configured in query.filter.hug.yaml
runBatch(url2, queries);
}
// this exception is normal
catch( BatchUpdateException e)
{
log.debug("this exception will happen because we are making selects in a batch");
log.debug(e);
log.debug(e.getNextException());
}
}
}
| mit |
luodeng/test | frame/src/main/java/com/fasterxml/jackson/User.java | 3319 | package com.fasterxml.jackson;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
/**
* 用户模型
*/
//@JsonIgnoreProperties(ignoreUnknown=true)忽略所有未知元素
@JsonIgnoreProperties({"extra"})
public class User {
// 性别
private Gender gender;
// 姓名
private Name name;
private boolean isVerified;
// 用户头像
private byte[] userImage;
// 用户生日
@JsonSerialize(using = JacksonUtil.JsonLocalDateSerializer.class)
@JsonDeserialize(using = JacksonUtil.JsonLocalDateDeserializer.class)
private LocalDate birthday;
// 用户登录时间
@JsonSerialize(using = JacksonUtil.JsonLocalDateTimeSerializer.class)
@JsonDeserialize(using = JacksonUtil.JsonLocalDateTimeDeserializer.class)
private LocalDateTime loginTime;
// 不想输出此属性,使用此注解。
@JsonIgnore
private String note;
// 性别
public enum Gender {
MALE, FEMALE
}
// 姓名
public static class Name {
private String first;
// 别名
//@JsonProperty("LAST")
private String last;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
@Override
public String toString() {
return "Name{" +
"first='" + first + '\'' +
", last='" + last + '\'' +
'}';
}
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public LocalDateTime getLoginTime() {
return loginTime;
}
public void setLoginTime(LocalDateTime loginTime) {
this.loginTime = loginTime;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public boolean isVerified() {
return isVerified;
}
public void setVerified(boolean verified) {
this.isVerified = verified;
}
public byte[] getUserImage() {
return userImage;
}
public void setUserImage(byte[] userImage) {
this.userImage = userImage;
}
@Override
public String toString() {
return "User{" +
"gender=" + gender +
", name=" + name +
", isVerified=" + isVerified +
", userImage=" + Arrays.toString(userImage) +
'}';
}
} | mit |
sparber/CComprehensiveDatatypes | src/tree/symbols/TSXorAssign.java | 238 | package tree.symbols;
import tree.DefaultTreeNodeSymbol;
public class TSXorAssign extends DefaultTreeNodeSymbol {
public static int id = XOR_ASSIGN;
public static String text = "^=";
public TSXorAssign() {
super(text, id);
}
}
| mit |
kTT/dbunit-extractor | src/li/ktt/SQLInjector.java | 992 | package li.ktt;
import com.intellij.lang.Language;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.InjectedLanguagePlaces;
import com.intellij.psi.LanguageInjector;
import com.intellij.psi.PsiLanguageInjectionHost;
import org.jetbrains.annotations.NotNull;
public class SQLInjector implements LanguageInjector {
@Override
public void getLanguagesToInject(@NotNull final PsiLanguageInjectionHost host,
@NotNull final InjectedLanguagePlaces places) {
final boolean isSelectQuery = host.getText().trim().toUpperCase().startsWith("SELECT");
final boolean isDataSetFile = host.getContainingFile().getText().startsWith("<dataset>");
if (isDataSetFile && isSelectQuery) {
final Language language = Language.findLanguageByID("SQL");
if (language != null) {
places.addPlace(language, TextRange.from(0, host.getTextLength()), null, null);
}
}
}
}
| mit |
Deathnerd/CSC310 | src/main/com/gilleland/george/objects/Heap.java | 6585 | package com.gilleland.george.objects;
import com.gilleland.george.exceptions.ElementNotFoundException;
import com.gilleland.george.exceptions.EmptyHeapException;
import com.gilleland.george.interfaces.Container;
import java.util.Arrays;
import java.util.HashMap;
/**
* Created by Wes Gilleland on 11/23/2015.
*/
public class Heap<T extends Comparable<T>> implements Container {
protected T[] heap;
private int max_size = 10;
private int num_items = 0;
public Heap() {
this.heap = (T[]) new Comparable[max_size];
}
/**
* Insert at the bottom of the heap and perform
* a bubble up operation at the end to preserve correct
* order of the heap
*
* @param item The item to insert into the heap
*/
public void insert(T item) {
if (this.isFull()) {
this.heap = this.resize();
}
this.heap[this.num_items] = item;
this.bubbleUp();
this.num_items++;
}
/**
* Removes and returns the largest element in the heap (the head)
*
* @return The largest element in the heap (the head)
* @throws EmptyHeapException If the heap is empty
*/
public T remove() throws EmptyHeapException {
if (this.isEmpty()) {
throw new EmptyHeapException();
}
T temp = this.peek();
this.heap[0] = this.heap[this.num_items];
this.bubbleDown();
this.heap[this.num_items] = null;
this.num_items--;
return temp;
}
/**
* // TODO: 11/23/2015 Clean up the description
* Given a key to search for, do a linear search across the backing array
* for the heap.
*
* @param thing The thing to search for
* @return A {@link HashMap} with the keys "index" and "object" each containing
* the key's index and the object in the heap respectively
* @throws EmptyHeapException
* @throws ElementNotFoundException
*/
public HashMap<String, Object> search(T thing) throws EmptyHeapException, ElementNotFoundException {
if (this.isEmpty()) {
throw new EmptyHeapException();
}
for (int i = 0; i < this.heap.length; i++) {
if (this.heap[i].compareTo(thing) == 0) {
HashMap<String, Object> temp = new HashMap<>();
temp.put("index", i);
temp.put("object", this.heap[i]);
return temp;
}
}
throw new ElementNotFoundException();
}
/**
* Is the number of items in the heap zero?
*
* @return Is the heap empty?
*/
@Override
public boolean isEmpty() {
return num_items == 0;
}
/**
* Is the number of items in the heap equal to the length
* of the backing array?
*
* @return Is the heap full?
*/
@Override
public boolean isFull() {
return num_items == this.heap.length;
}
public T peek() throws EmptyHeapException {
if (this.isEmpty()) {
throw new EmptyHeapException();
}
return this.heap[0];
}
/**
* Returns the internal array representation of the heap as a string
*
* @return The internal array representation of the heap as a string
*/
@Override
public String toString() {
return Arrays.toString(this.heap);
}
/**
* Display the current contents of the heap in a breadth-first search pattern
*/
public void displayHeap() {
System.out.println("The current contents of the heap are: ");
String t = "[";
for (T aHeap : this.heap) {
if (aHeap != null) {
t += aHeap + ",";
}
}
System.out.printf("%s]\n", t.substring(0, t.lastIndexOf(',')));
}
/**
* Preserves the heap min structure upon insertion
*/
private void bubbleUp() {
int index = this.num_items;
while (index >= 0 && this.heap[index].compareTo(getParent(index)) > 0) {
this.swap(index, this.getParentIndex(index));
index = getParentIndex(index);
}
}
/**
* Preserves the heap min structure when a node is removed
*/
private void bubbleDown() {
int index = 0;
while (this.getLeftChildIndex(index) <= this.num_items) {
int smaller = getLeftChildIndex(index);
int comparison = this.heap[this.getLeftChildIndex(index)].compareTo(this.heap[this.getRightChildIndex(index)]);
if (this.getRightChildIndex(index) <= this.num_items && comparison > 0) {
smaller = this.getRightChildIndex(index);
}
comparison = this.heap[index].compareTo(this.heap[smaller]);
if (comparison > 0) {
swap(index, smaller);
} else {
return;
}
index = smaller;
}
}
private T getParent(int child_index) {
return this.heap[this.getParentIndex(child_index)];
}
private int getParentIndex(int child_index) {
return child_index / 2;
}
private T getLeftChild(int parent_index) {
return this.heap[this.getLeftChildIndex(parent_index)];
}
private int getLeftChildIndex(int parent_index) {
return (2 * parent_index) + 1;
}
private boolean hasLeftChild(int parent_index) {
return this.getRightChild(parent_index) != null;
}
private T getRightChild(int parent_index) {
return this.heap[this.getRightChildIndex(parent_index)];
}
private int getRightChildIndex(int parent_index) {
return (2 * parent_index) + 2;
}
private boolean hasRightChild(int parent_index) {
return this.getRightChild(parent_index) != null;
}
/**
* <p>Resizes the backing array of the heap to double its current size.</p>
* <p>Note: Size starts at 10 items</p>
* TODO: 11/23/2015 Figure out an algorithm to scale gracefully to predict large data sets
*
* @return The resized array for the heap
*/
private T[] resize() {
max_size = this.heap.length * 2;
return Arrays.copyOf(this.heap, this.max_size);
}
/**
* Internal convenience method to swap two array elements
*
* @param index_1 The index of the first element
* @param index_2 The index of the second element
*/
private void swap(int index_1, int index_2) {
T temp = this.heap[index_1];
this.heap[index_1] = this.heap[index_2];
this.heap[index_2] = temp;
}
}
| mit |
Microsoft/vso-httpclient-java | Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/testmanagement/webapi/TestPlanCloneRequest.java | 1396 | // @formatter:off
/*
* ---------------------------------------------------------
* Copyright(C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license. See License.txt in the project root.
* ---------------------------------------------------------
*
* ---------------------------------------------------------
* Generated file, DO NOT EDIT
* ---------------------------------------------------------
*
* See following wiki page for instructions on how to regenerate:
* https://vsowiki.com/index.php?title=Rest_Client_Generation
*/
package com.microsoft.alm.teamfoundation.testmanagement.webapi;
import java.util.ArrayList;
/**
*/
public class TestPlanCloneRequest {
private TestPlan destinationTestPlan;
private CloneOptions options;
private ArrayList<Integer> suiteIds;
public TestPlan getDestinationTestPlan() {
return destinationTestPlan;
}
public void setDestinationTestPlan(final TestPlan destinationTestPlan) {
this.destinationTestPlan = destinationTestPlan;
}
public CloneOptions getOptions() {
return options;
}
public void setOptions(final CloneOptions options) {
this.options = options;
}
public ArrayList<Integer> getSuiteIds() {
return suiteIds;
}
public void setSuiteIds(final ArrayList<Integer> suiteIds) {
this.suiteIds = suiteIds;
}
}
| mit |
CYDpeter/104021003 | 20150820swing/src/Swingtext2.java | 1580 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Swingtext2 extends JFrame {
private JButton jbtnExit = new JButton("Exit");// Exitªº«ö¶s
private JButton jbtnPush = new JButton("Push");// Pushªº«ö¶s
private JLabel jlb1 = new JLabel();// ¼ÐÅÒª«¥ó
private Container cp;// «Å§i¤@Óµøµ¡½L¤l(®e¾¹)
private String str = "«öPush«ö¶sªº¦¸¼Æ:";
private int count = 0;
public Swingtext2() {// µøµ¡Ãþ§Oªº«Øºc¤¸
initComp();// ©I¥sinitComp¨ç¦¡¥Hø»sµøµ¡ªº¼Ë¦¡
}
public void initComp() {
cp = this.getContentPane();// ¨ú±oµøµ¡ªº ½L¤l(®e¾¹) ¨Ó©ñ¸m¦UºØ¤¸¥ó
this.setBounds(150, 100, 600, 400);// ³]©wµøµ¡ªºªì©l¦ì¸m©M¤j¤p
this.setDefaultCloseOperation(EXIT_ON_CLOSE);// ³]©wµøµ¡«öX´Nµ²§ô°õ¦æ
cp.setLayout(null);// ¤£¨Ï¥Îµøµ¡¥¬§½Ãþ§O
// ³]©w¼ÐÅÒÅo~~
jlb1.setBounds(50, 70, 250, 25);// ³]©w¼ÐÅÒª«¥ó¦bµøµ¡¤Wªº¦ì¸m©M¤j¤p
jlb1.setText(str + count);// ³]©w¼ÐÅÒ¤WÅã¥Üªº¦r
cp.add(jlb1);// ±N¼ÐÅÒª«¥ó¥[¨ìµøµ¡®e¾¹¤¤
// ³]©wPush«ö¶s~~
jbtnPush.setBounds(50, 100, 80, 25);// ³]©wPush«ö¶s¦bµøµ¡ªº¦ì¸m©M¤j¤p
cp.add(jbtnPush);// ±NPush«ö¶s¥[¨ìµøµ¡¤¤
jbtnPush.addActionListener(new ActionListener() {// ¬°Push«ö¶s¥[¤J¨Æ¥ó³B²z
public void actionPerformed(ActionEvent ae) {
count++;
jlb1.setText(str + count);// §ó·s¼ÐÅÒ¤Wªº¦r
}
});
// ³]©wExit«ö¶s~~
jbtnExit.setBounds(50, 150, 80, 25);// ³]©wExit«ö¶s¦bµøµ¡ªº¦ì¸m©M¤j¤p
cp.add(jbtnExit);// ±NExit«ö¶s¥[¨ìµøµ¡¤¤
jbtnExit.addActionListener(new ActionListener() {// ¬°Exit«ö¶s¥[¤J¨Æ¥ó³B²z
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
}
}
| mit |
gauthiier/objects-and-simulations | day3/libs/teilchen/src/teilchen/util/Overlap.java | 3624 | /*
* Teilchen
*
* Copyright (C) 2013
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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
* {@link http://www.gnu.org/licenses/lgpl.html}
*
*/
package teilchen.util;
import mathematik.Vector3f;
import java.util.List;
public class Overlap {
public static Vector3f RESOLVE_SAME_PLACE = new Vector3f(1, 0, 0);
public static <E extends SpatialEntity> void resolveOverlap(E theEntityA,
E theEntityB) {
if (theEntityB == theEntityA) {
return;
}
if (theEntityA.radius() == 0 || theEntityB.radius() == 0) {
return;
}
final Vector3f mAB = mathematik.Util.sub(theEntityA.position(), theEntityB.position());
final float myDistance = mAB.length();
if (myDistance > 0) {
float myOverlap = theEntityB.radius() + theEntityA.radius() - myDistance;
if (myOverlap > 0) {
mAB.scale(0.5f * myOverlap / myDistance);
theEntityA.position().add(mAB);
theEntityB.position().sub(mAB);
}
} else {
if (RESOLVE_SAME_PLACE != null) {
final Vector3f myOffset = new Vector3f(RESOLVE_SAME_PLACE);
myOffset.scale(theEntityB.radius() + theEntityA.radius());
myOffset.scale(0.5f);
theEntityA.position().add(myOffset);
theEntityB.position().sub(myOffset);
}
}
}
public static <E extends SpatialEntity> void resolveOverlap(E theEntity,
E[] theEntities) {
if (theEntities == null || theEntities.length < 1) {
return;
}
for (int i = 0; i < theEntities.length; i++) {
resolveOverlap(theEntities[i], theEntity);
}
}
public static <E extends SpatialEntity> void resolveOverlap(E theEntity,
List<E> theEntities) {
if (theEntities == null || theEntities.size() < 1) {
return;
}
for (int i = 0; i < theEntities.size(); i++) {
resolveOverlap(theEntities.get(i), theEntity);
}
}
public static <E extends SpatialEntity> void resolveOverlap(List<E> theEntities) {
if (theEntities == null || theEntities.isEmpty()) {
return;
}
/**
* @todo room for improvement. there is some redundant testing going on
* here.
*/
for (int i = 0; i < theEntities.size(); i++) {
for (int j = 0; j < theEntities.size(); j++) {
if (i == j) {
continue;
}
// final SpatialEntity myOtherEntity = theEntities.get(j);
resolveOverlap(theEntities.get(i), theEntities.get(j));
}
}
}
}
| mit |
ictrobot/Open-Exchange | src/main/java/oe/block/BlockExtractor.java | 2336 | package oe.block;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import oe.OpenExchange;
import oe.block.tile.TileExtractor;
public class BlockExtractor extends BlockContainer {
public BlockExtractor() {
super(Material.iron);
setBlockTextureName(OEBlocks.Texture(this.getClass().getSimpleName().substring(5).trim()));
setBlockName(this.getClass().getSimpleName());
setHardness(3.0F);
setResistance(5.0F);
setStepSound(Block.soundTypeMetal);
setCreativeTab(CreativeTabs.tabBlock);
}
@Override
public TileEntity createNewTileEntity(World par1World, int var2) {
TileExtractor tileextractor = new TileExtractor();
return tileextractor;
}
@Override
public boolean onBlockActivated(World world, int i, int j, int k, EntityPlayer player, int i1, float f1, float f2, float f3) {
TileEntity te = world.getTileEntity(i, j, k);
if (te == null || !(te instanceof TileExtractor) || world.isRemote) {
return true;
}
player.openGui(OpenExchange.instance, 0, world, i, j, k);
return true;
}
@SideOnly(Side.CLIENT)
private IIcon[] icons;
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister par1IconRegister) {
icons = new IIcon[4];
icons[0] = par1IconRegister.registerIcon(OEBlocks.Texture("Extractor_Bottom"));
icons[1] = par1IconRegister.registerIcon(OEBlocks.Texture("Extractor_Top"));
icons[2] = par1IconRegister.registerIcon(OEBlocks.Texture("Extractor_Side"));
icons[3] = par1IconRegister.registerIcon(OEBlocks.Texture("Extractor_Side_Spin"));
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(int par1, int par2) {
switch (par1) {
case 1:
return icons[1];
case 0:
return icons[0];
default:
switch (par2) {
case 1:
return icons[3];
default:
return icons[2];
}
}
}
}
| mit |
saroad2/units | units_java/src/test/java/com/units/tests/length/DegreesOfLatitudeTests.java | 4595 | /* This file is auto generated.
* DO NOT EDIT IT MANUALLY!
*/
package com.units.tests.length;
import org.junit.Test;
import com.units.length.DegreesOfLatitude;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class DegreesOfLatitudeTests {
public void assertSameValue(double value1, double value2) {
assertTrue("unit value is " + value1 + " instead of " + value2, value1 == value2);
}
@Test
public void testConstructor() {
double actualValue = 3.1;
assertSameValue(new DegreesOfLatitude(actualValue).value(), actualValue);
}
@Test
public void testZero() {
DegreesOfLatitude zero = DegreesOfLatitude.zero();
assertSameValue(zero.value(), 0);
}
@Test
public void testOne() {
DegreesOfLatitude one = DegreesOfLatitude.one();
assertSameValue(one.value(), 1);
}
@Test
public void testComparisonToSmallerValue() {
DegreesOfLatitude unit = new DegreesOfLatitude(3.1);
DegreesOfLatitude comparedUnit = new DegreesOfLatitude(3.0);
assertFalse(unit.lessThan(comparedUnit));
assertFalse(unit.lessThanOrEquals(comparedUnit));
assertFalse(unit.equals(comparedUnit));
assertTrue(unit.greaterThan(comparedUnit));
assertTrue(unit.greaterThanOrEquals(comparedUnit));
}
@Test
public void testComparisonToEqualValue() {
DegreesOfLatitude unit = new DegreesOfLatitude(3.1);
DegreesOfLatitude comparedUnit = new DegreesOfLatitude(3.1);
assertFalse(unit.lessThan(comparedUnit));
assertTrue(unit.lessThanOrEquals(comparedUnit));
assertTrue(unit.equals(comparedUnit));
assertFalse(unit.greaterThan(comparedUnit));
assertTrue(unit.greaterThanOrEquals(comparedUnit));
}
@Test
public void testComparisonToBiggerValue() {
DegreesOfLatitude unit = new DegreesOfLatitude(3.1);
DegreesOfLatitude comparedUnit = new DegreesOfLatitude(3.2);
assertTrue(unit.lessThan(comparedUnit));
assertTrue(unit.lessThanOrEquals(comparedUnit));
assertFalse(unit.equals(comparedUnit));
assertFalse(unit.greaterThan(comparedUnit));
assertFalse(unit.greaterThanOrEquals(comparedUnit));
}
@Test
public void testEqualsNullFails() {
double actualValue = 3.1;
assertFalse("two units are equal, even though one of the is null",
new DegreesOfLatitude(actualValue).equals(null));
}
@Test
public void testPlus() {
double value1 = 3.1;
double value2 = 2.6;
double resultValue = 5.7;
DegreesOfLatitude unit1 = new DegreesOfLatitude(value1);
DegreesOfLatitude unit2 = new DegreesOfLatitude(value2);
DegreesOfLatitude result = unit1.plus(unit2);
assertSameValue(unit1.value(), value1);
assertSameValue(unit2.value(), value2);
assertSameValue(result.value(), resultValue);
}
@Test
public void testMinus() {
double value1 = 3.1;
double value2 = 2.6;
double resultValue = 0.5;
DegreesOfLatitude unit1 = new DegreesOfLatitude(value1);
DegreesOfLatitude unit2 = new DegreesOfLatitude(value2);
DegreesOfLatitude result = unit1.minus(unit2);
assertSameValue(unit1.value(), value1);
assertSameValue(unit2.value(), value2);
assertSameValue(result.value(), resultValue);
}
@Test
public void testOpposite() {
double value = 3.1;
DegreesOfLatitude unit = new DegreesOfLatitude(value);
DegreesOfLatitude result = unit.opposite();
assertSameValue(unit.value(), value);
assertSameValue(result.value(), -value);
}
@Test
public void testMultiplyByScalar() {
double value = 3.1;
double scalar = 5;
double resultValue = 15.5;
DegreesOfLatitude unit = new DegreesOfLatitude(value);
DegreesOfLatitude result = unit.multiplyByScalar(scalar);
assertSameValue(unit.value(), value);
assertSameValue(result.value(), resultValue);
}
@Test
public void testDivideByScalar() {
double value = 3.1;
double scalar = 5;
double resultValue = 0.62;
DegreesOfLatitude unit = new DegreesOfLatitude(value);
DegreesOfLatitude result = unit.divideByScalar(scalar);
assertSameValue(unit.value(), value);
assertSameValue(result.value(), resultValue);
}
@Test
public void testScalarRatio() {
double value1 = 3.1;
double value2 = 0.62;
double scalar = 5;
DegreesOfLatitude unit1 = new DegreesOfLatitude(value1);
DegreesOfLatitude unit2 = new DegreesOfLatitude(value2);
assertSameValue(unit1.scalarRatio(unit2), scalar);
}
@Test
public void testToString() {
double value = 3.1;
String stringValue = "3.1 degrees of latitude";
DegreesOfLatitude unit = new DegreesOfLatitude(value);
assertTrue("string value is \"" + unit.toString() + "\" instead of \"" + stringValue + "\"",
unit.toString().equals(stringValue));
}
} | mit |
terebesirobert/mockito | src/main/java/org/mockito/internal/junit/UniversalTestListener.java | 4238 | package org.mockito.internal.junit;
import org.mockito.internal.creation.settings.CreationSettings;
import org.mockito.internal.util.MockitoLogger;
import org.mockito.mock.MockCreationSettings;
import org.mockito.quality.Strictness;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* Universal test listener that behaves accordingly to current setting of strictness.
* Will come handy when we offer tweaking strictness at the method level with annotation.
* Should be relatively easy to improve and offer tweaking strictness per mock.
*/
public class UniversalTestListener implements MockitoTestListener {
private Strictness currentStrictness;
private final MockitoLogger logger;
private Map<Object, MockCreationSettings> mocks = new IdentityHashMap<Object, MockCreationSettings>();
private DefaultStubbingLookupListener stubbingLookupListener;
public UniversalTestListener(Strictness initialStrictness, MockitoLogger logger) {
this.currentStrictness = initialStrictness;
this.logger = logger;
//creating single stubbing lookup listener per junit rule instance / test method
//this way, when strictness is updated in the middle of the test it will affect the behavior of the stubbing listener
this.stubbingLookupListener = new DefaultStubbingLookupListener(currentStrictness);
}
@Override
public void testFinished(TestFinishedEvent event) {
Collection<Object> createdMocks = mocks.keySet();
//At this point, we don't need the mocks any more and we can mark all collected mocks for gc
//TODO make it better, it's easy to forget to clean up mocks and we still create new instance of list that nobody will read, it's also duplicated
//TODO clean up all other state, null out stubbingLookupListener
mocks = new IdentityHashMap<Object, MockCreationSettings>();
switch (currentStrictness) {
case WARN: emitWarnings(logger, event, createdMocks); break;
case STRICT_STUBS: reportUnusedStubs(event, createdMocks); break;
case LENIENT: break;
default: throw new IllegalStateException("Unknown strictness: " + currentStrictness);
}
}
private void reportUnusedStubs(TestFinishedEvent event, Collection<Object> mocks) {
//If there is some other failure (or mismatches were detected) don't report another exception to avoid confusion
if (event.getFailure() == null && !stubbingLookupListener.isMismatchesReported()) {
UnusedStubbings unused = new UnusedStubbingsFinder().getUnusedStubbings(mocks);
unused.reportUnused();
}
}
private static void emitWarnings(MockitoLogger logger, TestFinishedEvent event, Collection<Object> mocks) {
String testName = event.getTestClassInstance().getClass().getSimpleName() + "." + event.getTestMethodName();
if (event.getFailure() != null) {
//print stubbing mismatches only when there is a test failure
//to avoid false negatives. Give hint only when test fails.
new ArgMismatchFinder().getStubbingArgMismatches(mocks).format(testName, logger);
} else {
//print unused stubbings only when test succeeds to avoid reporting multiple problems and confusing users
new UnusedStubbingsFinder().getUnusedStubbings(mocks).format(testName, logger);
}
}
@Override
public void onMockCreated(Object mock, MockCreationSettings settings) {
this.mocks.put(mock, settings);
//It is not ideal that we modify the state of MockCreationSettings object
//MockCreationSettings is intended to be an immutable view of the creation settings
//In future, we should start passing MockSettings object to the creation listener
//TODO #793 - when completed, we should be able to get rid of the CreationSettings casting below
((CreationSettings) settings).getStubbingLookupListeners().add(stubbingLookupListener);
}
public void setStrictness(Strictness strictness) {
this.currentStrictness = strictness;
this.stubbingLookupListener.setCurrentStrictness(strictness);
}
}
| mit |
rafaelkyrdan/design-patterns | src/structural/patterns/adapter/LegacyImpl.java | 1552 | package structural.patterns.adapter;
/**
* It is a legacy implementation which inlcludes functionality which we want to re-use.
*/
public class LegacyImpl implements LegacyInterface {
private String creditCardNo;
private String customerName;
private String cardExpMonth;
private String cardExpYear;
private Short cardCVVNo;
private Double amount;
@Override
public void setCreditCardNo(String creditCardNo) {
this.creditCardNo = creditCardNo;
}
@Override
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
@Override
public void setCardExpMonth(String cardExpMonth) {
this.cardExpMonth = cardExpMonth;
}
@Override
public void setCardExpYear(String cardExpYear) {
this.cardExpYear = cardExpYear;
}
@Override
public void setCardCVVNo(Short cardCVVNo) {
this.cardCVVNo = cardCVVNo;
}
@Override
public void setAmount(Double amount) {
this.amount = amount;
}
@Override
public String getCreditCardNo() {
return creditCardNo;
}
@Override
public String getCustomerName() {
return customerName;
}
@Override
public String getCardExpMonth() {
return cardExpMonth;
}
@Override
public String getCardExpYear() {
return cardExpYear;
}
@Override
public Short getCardCVVNo() {
return cardCVVNo;
}
@Override
public Double getAmount() {
return amount;
}
}
| mit |
joshsh/twitlogic | twitlogic-core/src/main/java/net/fortytwo/twitlogic/proof/InferenceStep.java | 1933 | package net.fortytwo.twitlogic.proof;
import net.fortytwo.twitlogic.flow.Handler;
import net.fortytwo.twitlogic.services.twitter.HandlerException;
import net.fortytwo.twitlogic.vocabs.PMLJustification;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.vocabulary.RDF;
/**
* @author Joshua Shinavier (http://fortytwo.net).
*/
public class InferenceStep extends PMLConstruct {
private final Resource inferenceRule;
private final NodeSetList antecedentList;
public InferenceStep(final Resource inferenceRule,
final NodeSetList antecedentList,
final RDFizerContext context) {
super(context);
this.inferenceRule = inferenceRule;
this.antecedentList = antecedentList;
}
protected void handleStatements(final Handler<Statement> handler) throws HandlerException {
Resource g = context.getNamedGraph();
ValueFactory vf = context.getValueFactory();
handler.handle(vf.createStatement(
self,
RDF.TYPE,
vf.createURI(PMLJustification.INFERENCESTEP),
g));
handler.handle(vf.createStatement(
self,
vf.createURI(PMLJustification.HASINFERENCERULE),
inferenceRule,
g));
if (null == antecedentList) {
handler.handle(vf.createStatement(
self,
vf.createURI(PMLJustification.HASANTECEDENTLIST),
RDF.NIL,
g));
} else {
handler.handle(vf.createStatement(
self,
vf.createURI(PMLJustification.HASANTECEDENTLIST),
antecedentList.self,
g));
antecedentList.handleStatements(handler);
}
}
}
| mit |
kasperisager/kelvin-maps | src/main/java/dk/itu/kelvin/Main.java | 3457 | /**
* Copyright (C) 2015 The Authors.
*/
package dk.itu.kelvin;
// JavaFX utilities
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
// JavaFX text utilities
import javafx.scene.text.Font;
// FXML utilities
import javafx.fxml.FXMLLoader;
// Threading
import dk.itu.kelvin.thread.TaskQueue;
/**
* Main class.
*/
public final class Main extends Application {
/**
* The title of the application.
*
* This will be shown in the title bar of the application window.
*/
private static final String TITLE = "Kelvin Maps";
/**
* The minimum width of the application window.
*/
private static final int MIN_WIDTH = 500;
/**
* The minimum height of the application window.
*/
private static final int MIN_HEIGHT = 300;
/**
* The main view of the application.
*
* This view be loaded and used as the main entry point to the application.
*/
private static final String MAIN_VIEW = "view/Application.fxml";
/**
* Stylesheets to load in the application.
*/
private static final String[] STYLESHEETS = new String[] {
"stylesheet/Main.css"
};
/**
* Fonts to load in the application.
*/
private static final String[] FONTS = new String[] {
"font/ionicons.ttf"
};
/**
* The scene of the application.
*/
private Scene scene;
/**
* Load the main scene of the application.
*/
private void loadScene() {
// Bail out if the scene has already been loaded.
if (this.scene != null) {
return;
}
try {
this.scene = new Scene(
(new FXMLLoader(this.getClass().getResource(MAIN_VIEW))).load()
);
}
catch (Exception ex) {
// This should never happen so simply propagate the exception as a
// runtime exception.
throw new RuntimeException(ex);
}
}
/**
* Load all application stylesheets.
*/
private void loadStylesheets() {
// Attempt loading the scene if it hasn't already been loaded.
if (this.scene == null) {
this.loadScene();
}
for (String stylesheet: STYLESHEETS) {
this.scene.getStylesheets().add(
this.getClass().getResource(stylesheet).toExternalForm()
);
}
}
/**
* Load all application fonts.
*/
private void loadFonts() {
for (String font: FONTS) {
Font.loadFont(this.getClass().getResourceAsStream(font), 14);
}
}
/**
* Start the JavaFX thread and hand off control to the main view.
*
* @param stage The primary stage of the application.
*/
@Override
public void start(final Stage stage) {
// 1. Set the application title.
stage.setTitle(TITLE);
// 2. Set the minimum dimensions of the application window.
stage.setMinWidth(MIN_WIDTH);
stage.setMinHeight(MIN_HEIGHT);
// 3. Load the main scene of the application.
this.loadScene();
// 4. Load the application fonts.
this.loadFonts();
// 5. Load the application stylesheets.
this.loadStylesheets();
// 6. Set the scene of the primary stage.
stage.setScene(this.scene);
// 7. Show the primary stage. Eureka!
stage.show();
}
/**
* Stop the JavaFX thread and close the application.
*/
@Override
public void stop() {
TaskQueue.shutdown();
}
/**
* Launch the application.
*
* @param args Runtime arguments.
*/
public static void main(final String[] args) {
Main.launch(args);
}
}
| mit |
adonley/BitMesh | Sources/CloudServer/src/main/java/network/bitmesh/cloudserver/Servlets/LatestVersionServlet.java | 1659 | package network.bitmesh.cloudserver.Servlets;
import com.google.gson.Gson;
import network.bitmesh.cloudserver.ServerConfig;
import network.bitmesh.cloudserver.Utils.Versioning;
import network.bitmesh.utilities.Versioning.PackageInfo;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
public class LatestVersionServlet extends HttpServlet
{
private static final org.slf4j.Logger log = LoggerFactory.getLogger(LatestVersionServlet.class.getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
PackageInfo packageInfo = Versioning.latestReleaseInfo();
HashMap<String, Object> responseMap = new HashMap<String,Object>();
HashMap<String, Integer> versionMap = new HashMap<String, Integer>();
versionMap.put("major", packageInfo.getMajor());
versionMap.put("minor", packageInfo.getMinor());
versionMap.put("release", packageInfo.getRelease());
responseMap.put("version", versionMap);
responseMap.put("signature", packageInfo.getSignature());
Gson gson = new Gson();
resp.setStatus(resp.SC_OK);
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
out.print(gson.toJson(responseMap));
log.info("Version Response: " + gson.toJson(responseMap));
out.flush();
out.close();
}
}
| mit |
lahwran/pin | app/src/main/java/hamlah/pin/complice/CompliceTask.java | 3191 | package hamlah.pin.complice;
import android.content.Context;
import com.bluelinelabs.logansquare.LoganSquare;
import com.bluelinelabs.logansquare.annotation.JsonField;
import com.bluelinelabs.logansquare.annotation.JsonObject;
import java.io.IOException;
import hamlah.pin.HUSLColorConverter;
@JsonObject
public class CompliceTask {
@JsonField
int color;
@JsonField
String goText;
@JsonField
Integer recommendedTime;
@JsonField
String label;
CompliceTask() {
}
public CompliceTask(int color, String goText, Integer recommendedTime, String label) {
this.color = color;
this.goText = goText;
this.recommendedTime = recommendedTime;
this.label = label;
}
public int getColor() {
return color;
}
public String getGoText() {
return goText;
}
public Integer getRecommendedTime() {
return recommendedTime;
}
public String getLabel() {
return label;
}
public boolean startAction(Context context) {
return false;
}
public void endAction(boolean isComplete) {
}
public String toJson() throws IOException {
return LoganSquare.serialize(new CompliceTaskJsonWrapper(this));
}
public static CompliceTask fromJson(String input) throws IOException {
return LoganSquare.parse(input, CompliceTaskJsonWrapper.class).get();
}
/**
* Clamp values ranged 0-100 smoothly, with tanh.
* @param in starting value
* @param newcenter the original center is considered to be at 0.5; this will be the new center.
* @param curvature lower values produce sharper curves.
* @param scale simple multiplier for the resulting value. If this is 1 and newcenter is 0.5, the new range will be the same, just curved.
* @return
*/
private double smoothclamp(double in, double newcenter, double curvature, double scale) {
return Math.tanh((in - 50) / (50 * curvature)) * (scale * 50) + (100 * newcenter);
}
private int squashColor(int incolor, double brightness, double saturation) {
double brightnessScale = 0.2;
double saturationScale = 0.3;
if (!(brightness <= 1 - brightnessScale && brightness >= brightnessScale)) {
throw new AssertionError();
}
if (!(saturation <= 1 - saturationScale && saturation >= saturationScale)) {
throw new AssertionError();
}
double[] husl = HUSLColorConverter.rgbToHusl(HUSLColorConverter.intToRgb(incolor));
double[] clamped = {
husl[0],
smoothclamp(husl[1], saturation, 1, saturationScale),
smoothclamp(husl[2], brightness, 0.9, brightnessScale)
};
if (husl[1] < 1) {
// in case of zero saturation, let's not violently boost it.
clamped[1] = 0;
}
return HUSLColorConverter.rgbToInt(HUSLColorConverter.huslToRgb(clamped));
}
public int getDarkSquashedColor() {
return squashColor(getColor(), 0.3, 0.32);
}
public int getMidSquashedColor() {
return squashColor(getColor(), 0.65, 0.68);
}
}
| mit |
ligoj/bootstrap | bootstrap-business/src/test/java/org/ligoj/bootstrap/core/dao/RestRepositoryImplTest.java | 12961 | /*
* Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
*/
package org.ligoj.bootstrap.core.dao;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.criteria.JoinType;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.ligoj.bootstrap.dao.system.DialectRepository;
import org.ligoj.bootstrap.dao.system.SystemRoleAssignmentRepository;
import org.ligoj.bootstrap.dao.system.SystemRoleRepository;
import org.ligoj.bootstrap.model.system.SystemDialect;
import org.ligoj.bootstrap.model.system.SystemRole;
import org.ligoj.bootstrap.model.system.SystemRoleAssignment;
import org.ligoj.bootstrap.model.system.SystemUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.orm.jpa.JpaObjectRetrievalFailureException;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import de.svenjacobs.loremipsum.LoremIpsum;
/**
* {@link RestRepositoryImpl} class test.
*/
@ExtendWith(SpringExtension.class)
class RestRepositoryImplTest extends AbstractBootTest {
@Autowired
private DialectRepository repository;
@Autowired
private SystemRoleRepository roleRepository;
@Autowired
private SystemRoleAssignmentRepository roleAssignmentRepository;
/**
* Last know identifier.
*/
private int lastKnownEntity;
@BeforeEach
void setup() {
final var loremIpsum = new LoremIpsum();
var dial1 = new SystemDialect();
for (var i = 0; i < 10; i++) {
var dial2 = new SystemDialect();
dial2.setDialLong((long) i);
dial2.setDialChar(loremIpsum.getWords(1, i % 50));
dial2.setDialDate(new Date(System.currentTimeMillis() + i));
em.persist(dial2);
dial1 = new SystemDialect();
dial1.setDialLong((long) i);
dial1.setDialChar(loremIpsum.getWords(1, i % 50));
dial1.setDialDate(new Date(System.currentTimeMillis() + i));
dial1.setLink(dial2);
em.persist(dial1);
}
em.flush();
lastKnownEntity = dial1.getId();
em.clear();
}
/**
* Default find, and found.
*/
@Test
void findOne() {
final var dialect = repository.findOne(lastKnownEntity);
Assertions.assertNotNull(dialect);
Assertions.assertNotNull(dialect.getLink());
Assertions.assertFalse(isLazyInitialized(dialect.getLink().getChildren()));
}
/**
* Default find, and not found.
*/
@Test
void findOneNotFound() {
Assertions.assertNull(repository.findOne(-1));
}
/**
* Default find one with expected result.
*/
@Test
void findOneExpected() {
final var dialect = repository.findOneExpected(lastKnownEntity);
Assertions.assertNotNull(dialect);
Assertions.assertNotNull(dialect.getLink());
Assertions.assertFalse(isLazyInitialized(dialect.getLink().getChildren()));
}
/**
* Find one without expected result.
*/
@Test
void findOneExpectedError() {
Assertions.assertThrows(JpaObjectRetrievalFailureException.class, () -> repository.findOneExpected(-1));
}
/**
* Default find one with expected result and fetch association.
*/
@Test
void findOneExpectedFetch() {
final Map<String, JoinType> fetch = new HashMap<>();
fetch.put("link", JoinType.LEFT);
fetch.put("link.children", JoinType.LEFT);
final var dialect = repository.findOneExpected(lastKnownEntity, fetch);
Assertions.assertNotNull(dialect);
Assertions.assertNotNull(dialect.getLink());
Assertions.assertTrue(isLazyInitialized(dialect.getLink().getChildren()));
}
/**
* Default find one with expected result and empty fetch association.
*/
@Test
void findOneExpectedEmptyFetch() {
final var dialect = repository.findOneExpected(lastKnownEntity, null);
Assertions.assertNotNull(dialect);
Assertions.assertNotNull(dialect.getLink());
Assertions.assertFalse(isLazyInitialized(dialect.getLink().getChildren()));
}
/**
* Default find by name success.
*/
@Test
void findByName() {
var role = new SystemRole();
role.setName("name");
em.persist(role);
em.flush();
em.clear();
role = roleRepository.findByName("name");
Assertions.assertNotNull(role);
Assertions.assertEquals("name", role.getName());
}
@Test
void findByMoreProperties() {
var role = new SystemRole();
role.setName("role");
em.persist(role);
em.flush();
em.clear();
role = roleRepository.findBy("name", "role", new String[] { "id" }, role.getId());
Assertions.assertNotNull(role);
Assertions.assertEquals("role", role.getName());
}
@Test
void findByNull() {
final var dial1 = new SystemDialect();
dial1.setDialLong(1L);
em.persist(dial1);
final var dial2 = new SystemDialect();
dial2.setDialLong(2L);
dial2.setDialDate(new Date(System.currentTimeMillis()));
em.persist(dial2);
Assertions.assertEquals(1L, repository.findBy("dialDate", null).getDialLong().longValue());
Assertions.assertEquals(1, repository.findAllBy("dialDate", null).size());
Assertions.assertEquals(1, repository.deleteAllBy("dialDate", null));
Assertions.assertEquals(0, repository.findAllBy("dialDate", null).size());
}
@Test
void findByDeepPathMoreProperties() {
var role = new SystemRole();
role.setName("role");
em.persist(role);
var user = new SystemUser();
user.setLogin(DEFAULT_USER);
em.persist(user);
var assignment = new SystemRoleAssignment();
assignment.setRole(role);
assignment.setUser(user);
em.persist(assignment);
em.flush();
em.clear();
assignment = roleAssignmentRepository.findBy("role.name", "role", new String[] { "user.login" }, DEFAULT_USER);
Assertions.assertNotNull(assignment);
Assertions.assertEquals("role", assignment.getRole().getName());
}
@Test
void countBy() {
var role = new SystemRole();
role.setName("john");
em.persist(role);
em.flush();
em.clear();
Assertions.assertEquals(1, roleRepository.countBy("name", "john"));
Assertions.assertEquals(0, roleRepository.countBy("name", "any"));
}
/**
* Default find all by name success.
*/
@Test
void findAllByName() {
var role = new SystemRole();
role.setName("value2");
em.persist(role);
var role2 = new SystemRole();
role2.setName("value1");
em.persist(role2);
em.flush();
em.clear();
var roles = roleRepository.findAllBy("name", "value1");
Assertions.assertNotNull(roles);
Assertions.assertEquals(1, roles.size());
Assertions.assertEquals("value1", roles.get(0).getName());
}
/**
* Default find by name not found.
*/
@Test
void findByNameNull() {
Assertions.assertNull(roleRepository.findByName("any"));
}
/**
* Default find by name with expected result.
*/
@Test
void findByNameExpected() {
var role = new SystemRole();
role.setName("name");
em.persist(role);
em.flush();
em.clear();
role = roleRepository.findByNameExpected("name");
Assertions.assertNotNull(role);
Assertions.assertEquals("name", role.getName());
}
/**
* Find by name without expected result.
*/
@Test
void findByNameExpectedError() {
Assertions.assertThrows(JpaObjectRetrievalFailureException.class,
() -> roleRepository.findByNameExpected("any"));
}
@Test
void deleteAllNoFetch() {
var systemDialect = repository.findAll().get(1);
Assertions.assertFalse(repository.findAll().isEmpty());
Assertions.assertTrue(repository.deleteAllNoFetch() > 2);
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
em.flush();
em.clear();
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
Assertions.assertTrue(repository.findAll().isEmpty());
}
@Test
void deleteAllIdentifiers() {
var systemDialect = repository.findAll().get(1);
Assertions.assertFalse(repository.findAll().isEmpty());
final List<Integer> list = new ArrayList<>();
list.add(systemDialect.getId());
list.add(-1);
Assertions.assertEquals(1, repository.deleteAll(list));
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
em.flush();
em.clear();
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
}
@Test
void deleteAllBy() {
var systemDialect = repository.findAll().get(1);
Assertions.assertFalse(repository.findAll().isEmpty());
Assertions.assertEquals(1, repository.deleteAllBy("id", systemDialect.getId()));
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
em.flush();
em.clear();
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
}
@Test
void deleteAllByMoreProperties() {
var systemDialect = repository.findAll().get(1);
Assertions.assertFalse(repository.findAll().isEmpty());
Assertions.assertEquals(0,
repository.deleteAllBy("id", systemDialect.getId(), new String[] { "dialChar" }, "some"));
Assertions.assertEquals(1, repository.deleteAllBy("id", systemDialect.getId(), new String[] { "dialChar" },
systemDialect.getDialChar()));
Assertions.assertEquals(0, repository.deleteAllBy("id", systemDialect.getId(), new String[] { "dialChar" },
systemDialect.getDialChar()));
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
em.flush();
em.clear();
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
var role = new SystemRole();
role.setName("role");
em.persist(role);
em.flush();
em.clear();
role = roleRepository.findBy("name", "role", new String[] { "id" }, role.getId());
Assertions.assertNotNull(role);
Assertions.assertEquals("role", role.getName());
}
@Test
void deleteAllByDeepPathMoreProperties() {
var role = new SystemRole();
role.setName("role");
em.persist(role);
var user = new SystemUser();
user.setLogin(DEFAULT_USER);
em.persist(user);
var assignment = new SystemRoleAssignment();
assignment.setRole(role);
assignment.setUser(user);
em.persist(assignment);
em.flush();
em.clear();
final var nb = roleAssignmentRepository.deleteAllBy("role.id", role.getId(), new String[] { "user.login" },
DEFAULT_USER);
Assertions.assertNotNull(assignment);
Assertions.assertEquals(1, nb);
}
@Test
void deleteAllExpected() {
final var systemDialect = repository.findAll().get(1);
Assertions.assertFalse(repository.findAll().isEmpty());
final List<Integer> list = new ArrayList<>();
list.add(systemDialect.getId());
repository.deleteAllExpected(list);
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
em.flush();
em.clear();
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
}
@Test
void deleteAllExpectedFailed() {
final var systemDialect = repository.findAll().get(1);
Assertions.assertFalse(repository.findAll().isEmpty());
final List<Integer> list = new ArrayList<>();
list.add(systemDialect.getId());
list.add(-1);
Assertions.assertThrows(JpaObjectRetrievalFailureException.class, () -> repository.deleteAllExpected(list));
}
@Test
void deleteAllIdentifiersEmpty() {
var size = repository.findAll().size();
Assertions.assertEquals(0, repository.deleteAll(new ArrayList<Integer>()));
Assertions.assertEquals(size, repository.findAll().size());
em.flush();
em.clear();
Assertions.assertEquals(size, repository.findAll().size());
}
@Test
void deleteAllIdentifiersNull() {
var size = repository.findAll().size();
Assertions.assertEquals(0, repository.deleteAll((Collection<Integer>) null));
Assertions.assertEquals(size, repository.findAll().size());
em.flush();
em.clear();
Assertions.assertEquals(size, repository.findAll().size());
}
@Test
void deleteExpected() {
var systemDialect = repository.findAll().get(1);
repository.deleteById(systemDialect.getId());
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
em.flush();
em.clear();
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
}
@Test
void deleteExpectedError() {
Assertions.assertThrows(EmptyResultDataAccessException.class, () -> repository.deleteById(-1));
}
@Test
void deleteNoFetch() {
var systemDialect = repository.findAll().get(1);
repository.deleteNoFetch(systemDialect.getId());
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
em.flush();
em.clear();
Assertions.assertFalse(repository.existsById(systemDialect.getId()));
}
@Test
void deleteNoFetchError() {
var systemDialect = repository.findAll().get(1);
repository.deleteNoFetch(systemDialect.getId());
final var id = systemDialect.getId();
Assertions.assertThrows(JpaObjectRetrievalFailureException.class, () -> repository.deleteNoFetch(id));
}
@Test
void existExpected() {
var systemDialect = repository.findAll().get(1);
repository.existExpected(systemDialect.getId());
}
@Test
void existExpectedFail() {
Assertions.assertThrows(JpaObjectRetrievalFailureException.class, () -> repository.existExpected(-1));
}
}
| mit |
Rubentxu/entitas-java | codegenerator/plugins/src/main/java/ilargia/entitas/codeGeneration/plugins/dataProviders/components/providers/ShouldGenerateComponentDataProvider.java | 1377 | package ilargia.entitas.codeGeneration.plugins.dataProviders.components.providers;
import ilargia.entitas.api.IComponent;
import ilargia.entitas.codeGeneration.plugins.dataProviders.components.ComponentData;
import java.util.Arrays;
public class ShouldGenerateComponentDataProvider implements IComponentDataProvider {
public static String COMPONENT_GENERATE_COMPONENT = "component_generateComponent";
public static String COMPONENT_OBJECT_TYPE = "component_objectType";
public static boolean shouldGenerateComponent(ComponentData data) {
return (boolean) data.get(COMPONENT_GENERATE_COMPONENT);
}
public static void shouldGenerateComponent(ComponentData data, boolean generate) {
data.put(COMPONENT_GENERATE_COMPONENT, generate);
}
public static String getObjectType(ComponentData data) {
return (String) data.get(COMPONENT_OBJECT_TYPE);
}
public static void setObjectType(ComponentData data, String type) {
data.put(COMPONENT_OBJECT_TYPE, type);
}
@Override
public void provide(ComponentData data) {
boolean shouldGenerateComponent = !data.getSource().hasInterface(IComponent.class);
shouldGenerateComponent(data, shouldGenerateComponent);
if (shouldGenerateComponent) {
setObjectType(data, data.getSource().getCanonicalName());
}
}
}
| mit |
FAU-Inf2/rpgpack-android | src/de/fau/cs/mad/rpgpack/templatestore/ApiResponse.java | 558 | package de.fau.cs.mad.rpgpack.templatestore;
/**
* Representation of an ApiResponse
* @author Gregor Völkl
*
*/
public class ApiResponse {
public int resultCode;
public String reasonPhrase;
public String responseBody;
ApiResponse(int resultCode, String reasonPhrase, String responseBody) {
this.resultCode = resultCode;
this.reasonPhrase = reasonPhrase;
this.responseBody = responseBody;
}
public String toString() {
return "ResultCode: "+this.resultCode+" "+this.reasonPhrase+" \n\n " + this.responseBody;
}
}
| mit |
sdqali/kannel-java | sms/src/main/java/org/kannel/sms/SmsSender.java | 1538 | package org.kannel.sms;
import java.net.URL;
import java.nio.charset.Charset;
/**
* Base class for sending SMS messages to the smsbox.
*
* @author Garth Patil <garthpatil@gmail.com>
*/
public abstract class SmsSender
{
public SmsSender(URL smsbox)
{
this.smsbox = smsbox;
}
/**
* smsbox smsbox
*/
protected URL smsbox;
public URL getSmsbox() { return this.smsbox; }
public void setSmsbox(URL smsbox) { this.smsbox = smsbox; }
/**
* Send an SMS message.
* @param sms The SMS message to send.
* @return A SendStatus which includes status, message and the resulting HTTP status.
*/
public abstract SendStatus send(Sms sms) throws Exception;
/**
* Main method for testing.
* usage: SmsSender <from> <to> <text>
*/
public static void main(String[] argv)
{
if (argv.length != 3) {
System.err.println("usage: SmsSender <from> <to> <text>");
System.exit(1);
}
Sms sms = new Sms();
sms.setUsername("foo");
sms.setPassword("bar");
sms.setFrom(argv[0]);
sms.setTo(argv[1]);
sms.setText(argv[2]);
try {
// try HTTP
SmsSender s = new HttpSmsSender(new URL("http://localhost:13013/cgi-bin/sendsms"));
SendStatus status = s.send(sms);
System.out.println(status.toString());
// try XML
s = new XmlSmsSender(new URL("http://localhost:13013/cgi-bin/sendsms"));
status = s.send(sms);
System.out.println(status.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| mit |
emadhilo/capstone | SymptomChecker/src/org/coursera/androidcapstone/symptomapp/client/adapters/DoctorCheckInAdapter.java | 3611 | package org.coursera.androidcapstone.symptomapp.client.adapters;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.coursera.androidcapstone.symptomapp.api.CheckInDto;
import org.coursera.androidcapstone.symptomapp.client.Helper;
import org.coursera.androidcapstone.symptomapp.client.R;
import org.coursera.androidcapstone.symptomapp.client.R.id;
import org.coursera.androidcapstone.symptomapp.client.R.layout;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class DoctorCheckInAdapter extends BaseAdapter {
private static ArrayList<CheckInDto> checkinArrayList;
private LayoutInflater mInflater;
public DoctorCheckInAdapter(Context context, ArrayList<CheckInDto> list) {
checkinArrayList = list;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return checkinArrayList.size();
}
@Override
public Object getItem(int position) {
return checkinArrayList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.checkin_history_row, null);
holder = new ViewHolder();
holder.txtCheckedInAt = (TextView) convertView.findViewById(R.id.checkin_title);
holder.txtPain = (TextView) convertView.findViewById(R.id.checkin_pain_text);
holder.txtEat = (TextView) convertView.findViewById(R.id.checkin_eat_text);
holder.txtMedication = (TextView) convertView.findViewById(R.id.checkin_med_text);
holder.txtAlertText = (TextView) convertView.findViewById(R.id.listAlertText);
holder.imgAlert = (ImageView) convertView.findViewById(R.id.listAlertImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
SimpleDateFormat DATE_FORMAT_CHECKIN = new SimpleDateFormat("h:mma 'on' MMM, d yyyy", Locale.US);
String checkinText = "Checked in at "+DATE_FORMAT_CHECKIN.format(checkinArrayList.get(position).getCheckInTimeStamp());
holder.txtCheckedInAt.setText(Helper.replaceWithTodayYesterdayTomorrow(checkinText, "on "));
holder.txtPain.setText(checkinArrayList.get(position).getPainResponse().getResponse());
holder.txtEat.setText(checkinArrayList.get(position).getEatResponse().getResponse());
String meds = "";
for(String m: checkinArrayList.get(position).getMedicationTaken())
meds += Helper.replaceWithTodayYesterdayTomorrow(m, "on ") + "\n";
if(meds.equals(""))
meds = "none";
else
meds = meds.substring(0, meds.length()-1)+ "";
String alert = checkinArrayList.get(position).getAlertType();
if(alert == null || "".equals(alert)) {
holder.txtAlertText.setText("");
holder.txtAlertText.setVisibility(View.GONE);
holder.imgAlert.setVisibility(View.GONE);
}
else {
holder.txtAlertText.setText(Helper.alerts.get(alert));
holder.txtAlertText.setVisibility(View.VISIBLE);
holder.imgAlert.setVisibility(View.VISIBLE);
}
holder.txtMedication.setText(meds);
return convertView;
}
static class ViewHolder {
TextView txtCheckedInAt;
TextView txtPain;
TextView txtEat;
TextView txtMedication;
TextView txtAlertText;
ImageView imgAlert;
}
}
| mit |
chihane/Tumplar | app/src/main/java/mlxy/tumplar/view/activity/LoginActivity.java | 1654 | package mlxy.tumplar.view.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import mlxy.tumplar.R;
import mlxy.tumplar.view.fragment.LoginFragment;
public class LoginActivity extends BaseActivity {
private LoginFragment loginFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.normal_layout);
setTitle(R.string.title_login);
setupToolbar();
loginFragment = new LoginFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content, loginFragment).commit();
}
private void setupToolbar() {
Toolbar toolBar = getToolBar();
if (toolBar != null) {
toolBar.setNavigationIcon(R.mipmap.ic_close_white_24dp);
toolBar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
@Override
protected void onNewIntent(Intent intent) {
// Called on OAuth authorized. See https://www.tumblr.com/docs/en/api/v2#auth
Uri data = intent.getData();
if (data != null && data.getScheme().equals(getString(R.string.oauth_callback_scheme))) {
getSupportFragmentManager().beginTransaction().detach(loginFragment).commit();
String verifier = data.getQueryParameter("oauth_verifier");
loginFragment.onAuthorized(verifier);
}
}
}
| mit |
jgke/mapserver | src/main/java/fi/paivola/water/River.java | 5506 | package fi.paivola.water;
//import au.com.bytecode.opencsv.CSVWriter;
import fi.paivola.mapserver.utils.Color;
import fi.paivola.mapserver.core.DataFrame;
import fi.paivola.mapserver.core.Event;
import fi.paivola.mapserver.core.GameManager;
import fi.paivola.mapserver.core.ConnectionModel;
import fi.paivola.mapserver.core.Model;
import fi.paivola.mapserver.core.setting.SettingDouble;
import fi.paivola.mapserver.core.setting.SettingInt;
import fi.paivola.mapserver.core.setting.SettingList;
import fi.paivola.mapserver.core.setting.SettingMaster;
import fi.paivola.mapserver.utils.Icon;
import fi.paivola.mapserver.utils.RangeInt;
import fi.paivola.mapserver.utils.RangeDouble;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
/**
*
* @author Esa
*/
public class River extends ConnectionModel {
// CSVWriter writer;
// General (dimensions and stuff
double waterAmount = 0; // m^3
double width = 100; // m
double length = 1000000; // m
double startDepth = 0;
double floodDepth = 10;
double flowDepth = 0.5;
double slope = 45;
int order = 0;
public River(int id) {
super(id);
this.maxConnections = 20;
this.type = "River";
this.passthrough = false;
}
@Override
public void onTick(DataFrame last, DataFrame current) {
double flow = 0;
Boolean flood = false;
if (waterAmount > width*length*flowDepth) {
double currentDepth = waterAmount/(width*length);
double C = (double) (1 / 0.035f * Math.pow(currentDepth, 1 / 6));
double flowSpeed = (double) (C * Math.sqrt(currentDepth * slope));
flow = width * currentDepth * flowSpeed;
List<Model> lakes = new ArrayList<Model>();
for (Model m : this.connections) {
if ((m.type.equals("Lake")||m.type.equals("Sea")) && m.getInt("order") > this.order) {
lakes.add(m);
}
}
for (Model m : lakes) {
Event e = new Event("Flow", Event.Type.STRING, "" + flow);
this.addEventTo(m, current, e);
}
if (waterAmount - flow < 0) {
waterAmount = 0;
} else {
waterAmount -= flow;
}
Event e;
if(waterAmount > width*length*floodDepth)
{
flood = true;
e = new Event("Flood",Event.Type.OBJECT, flood);
this.addEventToAll(current, e);
}
}
/*
String[] entries = (waterAmount/1000000000 + "#" + flow/1000000+"#"+(flood?1:0)).split("#");
for (int i = 0; i < entries.length; i++) {
entries[i] = entries[i].trim();
}
if (writer != null) {
writer.writeNext(entries);
}
*/
}
@Override
public void onEvent(Event e, DataFrame current) {
if (e.name.equals("Flow") && e.sender.getInt("order") < this.order) {
waterAmount += Float.parseFloat(e.getString());
}
}
@Override
public void onRegisteration(GameManager gm, SettingMaster sm) {
sm.settings.put("order", new SettingInt("Position in the hydrodynamic chain", 0, new RangeInt(0, 100)));
sm.settings.put("width", new SettingDouble("Width of the river", 100, new RangeDouble(0,Double.MAX_VALUE)));
sm.settings.put("length", new SettingDouble("Length of the river", 10000, new RangeDouble(0,Double.MAX_VALUE)));
sm.settings.put("startDepth", new SettingDouble("Start water depth", 0.1, new RangeDouble(0,1)));
sm.settings.put("floodDepth", new SettingDouble("Flood water depth", 10, new RangeDouble(0,Double.MAX_VALUE)));
sm.settings.put("flowDepth", new SettingDouble("River starts to flow when over this", 0.5, new RangeDouble(0,1)));
sm.settings.put("slope", new SettingDouble("Width of the river", 20, new RangeDouble(0,90)));
sm.color = new Color(0, 0, 255);
sm.name = "River";
}
@Override
public void onGenerateDefaults(DataFrame df) {
waterAmount = width*length*startDepth;
}
@Override
public void onUpdateSettings(SettingMaster sm) {
this.order = Integer.parseInt(sm.settings.get("order").getValue());
this.width = Double.parseDouble(sm.settings.get("width").getValue());
this.length = Double.parseDouble(sm.settings.get("length").getValue());
this.startDepth = Double.parseDouble(sm.settings.get("startDepth").getValue());
this.floodDepth = Double.parseDouble(sm.settings.get("floodDepth").getValue());
this.flowDepth = Double.parseDouble(sm.settings.get("flowDepth").getValue());
this.slope = Double.parseDouble(sm.settings.get("slope").getValue());
this.saveInt("order", order);
this.saveDouble("width",width);
this.saveDouble("length",length);
this.saveDouble("startDepth",startDepth);
this.saveDouble("floodDepth",floodDepth);
this.saveDouble("flowDepth",flowDepth);
this.saveDouble("slope",slope);
/*
if (writer == null) {
try {
writer = new CSVWriter(new FileWriter(this.id + ".csv"), ',');
} catch (IOException e) {
System.out.println(e.toString());
}
}*/
}
}
| mit |
mediahackday/roadtracking | rt-util-credential/src/main/java/com/roadtracking/util/credential/ICredential.java | 204 | package com.roadtracking.util.credential;
/**
* Base to get saved password from user directory file.
*/
public interface ICredential {
String get(String key);
void set(String key, String value);
}
| mit |
tristanvda/SithAndroid | app/src/main/java/com/grietenenknapen/sithandroid/service/storage/tools/DbSqlHelperUtils.java | 3419 | package com.grietenenknapen.sithandroid.service.storage.tools;
import android.database.sqlite.SQLiteDatabase;
import com.grietenenknapen.sithandroid.model.database.Favourite;
import com.grietenenknapen.sithandroid.model.database.GamePlayer;
import com.grietenenknapen.sithandroid.model.database.Player;
import com.grietenenknapen.sithandroid.model.database.SithCard;
import com.grietenenknapen.sithandroid.model.database.relations.GamePlayerRelations;
import com.grietenenknapen.sithandroid.model.database.relations.PlayerFavourite;
import java.util.ArrayList;
import java.util.List;
import nl.qbusict.cupboard.Cupboard;
public class DbSqlHelperUtils {
public static List<SithCard> retrieveSithCardsForGamePlayer(final SQLiteDatabase db,
final Cupboard cupboard,
final long[] sithCardIds) {
final List<SithCard> sithCards = new ArrayList<>();
for (long id : sithCardIds) {
SithCard sithCard = cupboard.withDatabase(db).get(SithCard.class, id);
if (sithCard != null) {
sithCards.add(sithCard);
}
}
return sithCards;
}
public static Player retrievePlayerForGamePlayer(final SQLiteDatabase db,
final Cupboard cupboard,
final long playerId) {
Player player = cupboard.withDatabase(db).get(Player.class, playerId);
List<Favourite> favourites = retrieveFavouritesForPlayer(db, cupboard, playerId);
if (player != null) {
player.setFavourites(favourites);
}
return player;
}
public static GamePlayer retrieveGamePlayerForGamePlayerRelation(final SQLiteDatabase db,
final Cupboard cupboard,
final GamePlayerRelations gamePlayerRelations) {
GamePlayer gamePlayer = cupboard.withDatabase(db).get(GamePlayer.class, gamePlayerRelations.getGamePlayerId());
if (gamePlayer == null){
return null;
}
gamePlayer.setPlayer(retrievePlayerForGamePlayer(db, cupboard, gamePlayerRelations.getGamePlayerId()));
gamePlayer.setSithCards(retrieveSithCardsForGamePlayer(db, cupboard, gamePlayerRelations.getSithCardIds()));
return gamePlayer;
}
public static List<Favourite> retrieveFavouritesForPlayer(final SQLiteDatabase db,
final Cupboard cupboard,
final long playerId) {
final List<PlayerFavourite> existingPlayerFavourites = cupboard.withDatabase(db)
.query(PlayerFavourite.class)
.withSelection(PlayerFavourite.PLAYER_ID + " = ?", String.valueOf(playerId)).query().list();
final List<Favourite> favourites = new ArrayList<>();
for (PlayerFavourite playerFavourite : existingPlayerFavourites) {
Favourite favourite = cupboard.withDatabase(db).get(Favourite.class, playerFavourite.get_id());
if (favourite != null) {
favourites.add(favourite);
}
}
return favourites;
}
}
| mit |
micheljung/downlords-faf-client | src/main/java/com/faforever/client/mod/ModService.java | 2502 | package com.faforever.client.mod;
import com.faforever.client.task.CompletableTask;
import com.faforever.client.vault.search.SearchController.SearchConfig;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.scene.image.Image;
import org.apache.maven.artifact.versioning.ComparableVersion;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
public interface ModService {
void loadInstalledMods();
ObservableList<ModVersion> getInstalledModVersions();
CompletableFuture<Void> downloadAndInstallMod(String uid);
CompletableFuture<Void> downloadAndInstallMod(URL url);
CompletableFuture<Void> downloadAndInstallMod(URL url, DoubleProperty progressProperty, StringProperty titleProperty);
CompletableFuture<Void> downloadAndInstallMod(ModVersion modVersion, DoubleProperty progressProperty, StringProperty titleProperty);
Set<String> getInstalledModUids();
Set<String> getInstalledUiModsUids();
void enableSimMods(Set<String> simMods) throws IOException;
boolean isModInstalled(String uid);
CompletableFuture<Void> uninstallMod(ModVersion modVersion);
Path getPathForMod(ModVersion modVersion);
CompletableFuture<List<ModVersion>> getHighestRatedUiMods(int count, int page);
CompletableFuture<List<ModVersion>> getHighestRatedMods(int count, int page);
CompletableFuture<List<ModVersion>> getNewestMods(int count, int page);
@NotNull
ModVersion extractModInfo(Path path);
@NotNull
ModVersion extractModInfo(InputStream inputStream, Path basePath);
CompletableTask<Void> uploadMod(Path modPath);
Image loadThumbnail(ModVersion modVersion);
void evictModsCache();
/**
* Returns the download size of the specified modVersion in bytes.
*/
long getModSize(ModVersion modVersion);
ComparableVersion readModVersion(Path modDirectory);
CompletableFuture<List<FeaturedMod>> getFeaturedMods();
CompletableFuture<FeaturedMod> getFeaturedMod(String gameTypeBeanName);
List<ModVersion> getActivatedSimAndUIMods() throws IOException;
void overrideActivatedMods(List<ModVersion> modVersions) throws IOException;
CompletableFuture<List<ModVersion>> findByQuery(SearchConfig searchConfig, int page, int maxSearchResults);
void evictCache();
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/PatchInstallationDetail.java | 3204 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.compute.models;
import com.azure.core.annotation.Immutable;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** Information about a specific patch that was encountered during an installation action. */
@Immutable
public final class PatchInstallationDetail {
/*
* A unique identifier for the patch.
*/
@JsonProperty(value = "patchId", access = JsonProperty.Access.WRITE_ONLY)
private String patchId;
/*
* The friendly name of the patch.
*/
@JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY)
private String name;
/*
* The version string of the package. It may conform to Semantic
* Versioning. Only applies to Linux.
*/
@JsonProperty(value = "version", access = JsonProperty.Access.WRITE_ONLY)
private String version;
/*
* The KBID of the patch. Only applies to Windows patches.
*/
@JsonProperty(value = "kbId", access = JsonProperty.Access.WRITE_ONLY)
private String kbId;
/*
* The classification(s) of the patch as provided by the patch publisher.
*/
@JsonProperty(value = "classifications", access = JsonProperty.Access.WRITE_ONLY)
private List<String> classifications;
/*
* The state of the patch after the installation operation completed.
*/
@JsonProperty(value = "installationState", access = JsonProperty.Access.WRITE_ONLY)
private PatchInstallationState installationState;
/**
* Get the patchId property: A unique identifier for the patch.
*
* @return the patchId value.
*/
public String patchId() {
return this.patchId;
}
/**
* Get the name property: The friendly name of the patch.
*
* @return the name value.
*/
public String name() {
return this.name;
}
/**
* Get the version property: The version string of the package. It may conform to Semantic Versioning. Only applies
* to Linux.
*
* @return the version value.
*/
public String version() {
return this.version;
}
/**
* Get the kbId property: The KBID of the patch. Only applies to Windows patches.
*
* @return the kbId value.
*/
public String kbId() {
return this.kbId;
}
/**
* Get the classifications property: The classification(s) of the patch as provided by the patch publisher.
*
* @return the classifications value.
*/
public List<String> classifications() {
return this.classifications;
}
/**
* Get the installationState property: The state of the patch after the installation operation completed.
*
* @return the installationState value.
*/
public PatchInstallationState installationState() {
return this.installationState;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| mit |
rubenlagus/TelegramApi | src/main/java/org/telegram/mtproto/ServerException.java | 488 | package org.telegram.mtproto;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: Ruben Bermudez
* Date: 03.11.13
* Time: 6:47
*/
public class ServerException extends IOException {
public ServerException() {
}
public ServerException(String s) {
super(s);
}
public ServerException(String s, Throwable throwable) {
super(s, throwable);
}
public ServerException(Throwable throwable) {
super(throwable);
}
}
| mit |
juniormesquitadandao/report4all | lib/src/net/sf/jasperreports/engine/fill/JRYXComparator.java | 1548 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.engine.fill;
import java.util.Comparator;
import net.sf.jasperreports.engine.JRPrintElement;
/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
* @version $Id: JRYXComparator.java 7199 2014-08-27 13:58:10Z teodord $
*/
public class JRYXComparator implements Comparator<JRPrintElement>
{
/**
*
*/
public int compare(JRPrintElement elem1, JRPrintElement elem2)
{
if (elem1.getY() == elem2.getY())
{
return elem1.getX() - elem2.getX();
}
else
{
return elem1.getY() - elem2.getY();
}
}
}
| mit |
aureliano/e-docs | edocs-common/src/test/java/com/github/aureliano/edocs/common/persistence/PersistenceServiceTest.java | 943 | package com.github.aureliano.edocs.common.persistence;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class PersistenceServiceTest {
@Test
public void testInstance() {
PersistenceService ps = PersistenceService.instance();
assertNotNull(ps);
assertTrue(ps == PersistenceService.instance());
}
@Test
public void testRegisterPersistenceManager() {
PersistenceService ps = PersistenceService.instance();
CommonPersistenceManager pm = new CommonPersistenceManager();
ps.registerPersistenceManager(pm);
assertEquals(ps.getPersistenceManager(), pm);
}
@Test
public void testMappingEntity() {
PersistenceService ps = PersistenceService.instance();
assertTrue(ps == ps.mapEntity(CommonEntity.class, CommonDao.class));
assertTrue(ps.createDao(CommonEntity.class) instanceof CommonDao);
}
} | mit |
kelvinst/psf-def | src/main/java/org/kelvinst/psf_def/IScmInfo.java | 150 | package org.kelvinst.psf_def;
public interface IScmInfo {
String getName();
String getRepository();
String getBranch();
String getPath();
} | mit |
ruv-prog-so/BulletinGroupBlast | app/src/main/java/com/bulletingroupblast/bulletingroupblast/CreateOrganizationActivity.java | 1361 | /**
* Copyright © 2015 Ruben Piatnitsky
* This program is released under the "MIT license".
* Please see the file LICENSE in this distribution for
* license terms.
*
*/
package com.bulletingroupblast.bulletingroupblast;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class CreateOrganizationActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_organization);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_create_organization, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| mit |
ChainGangChase/cgc-game | core/src/com/percipient24/cgc/entities/Gate.java | 6106 | /*
* @(#)Gate.java 0.2 14/2/4
*
* Copyright 2014, MAGIC Spell Studios, LLC
*/
package com.percipient24.cgc.entities;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.utils.Array;
import com.percipient24.helpers.LayerHandler;
import com.percipient24.cgc.Data;
import com.percipient24.cgc.entities.players.Player;
import com.percipient24.cgc.entities.players.Prisoner;
import com.percipient24.cgc.entities.players.RookieCop;
import com.percipient24.enums.EntityType;
/*
* Handles the logic for a gate entity
*
* @version 0.2 14/2/4
* @author Christopher Rider
* @author Clayton Andrews
*/
public class Gate extends RotatableEntity
{
private Array<Sensor> sensors;
private boolean closed;
private short gateID;
public int sensorShapeID = -1;
public Color sensorColor;
/*
* Creates a new Gate object
*
* @param newLowAnimation The Animation for the bottom of this object
* @param newMidAnimation The Animation for the middle of this object
* @param newHighAnimation The Animation for the top of this object
* @param pEntityType The type of entity this object is
* @param attachedBody The Body object that represents this GameEntity in the world
* @param newGridX The grid X-position of this object
* @param newGridY The grid Y-position of this object
*/
public Gate(Animation newLowAnimation, Animation newMidAnimation,
Animation newHighAnimation, EntityType pEntityType,
Body attachedBody, int newGridX, int newGridY)
{
super(newLowAnimation, newMidAnimation, newHighAnimation, pEntityType, attachedBody);
closed = true;
sensors = new Array<Sensor>();
gateID = -1;
gridX = newGridX;
gridY = newGridY;
rotation = body.getAngle() * Data.RADDEG;
sensorColor = Color.WHITE;
// These numbers are calculated based on the texture dimensions of the associated art asset.
// The relationship is: 1.0f in world space is 96x96 in pixels (see art asset to get dimensions)
// By default, half-width and half-height are calculated based on the base image's dimensions
// when rotated/aligned horizontally.
//halfWidth = -0.5f;
//halfHeight = -0.104166667f;
}
/*
* Creates a new Gate object
*
* @param newLowAnimation The Animation for the bottom of this object
* @param newMidAnimation The Animation for the middle of this object
* @param newHighAnimation The Animation for the top of this object
* @param pEntityType The type of entity this object is
* @param attachedBody The Body object that represents this GameEntity in the world
* @param newGridX The grid X-position of this object
* @param newGridY The grid Y-position of this object
* @param startAlpha The starting alpha for this entity
*/
public Gate(Animation newLowAnimation, Animation newMidAnimation,
Animation newHighAnimation, EntityType pEntityType,
Body attachedBody, int newGridX, int newGridY, float startAlpha)
{
this(newLowAnimation, newMidAnimation, newHighAnimation, pEntityType,
attachedBody, newGridX, newGridY);
alpha = startAlpha;
}
/*
* Timestep-based update method
*
* @param deltaTime Seconds elapsed since the last frame
* @param layer The parallax layer to animate
*/
public void step(float deltaTime, int layer)
{
//update this Entity's animation state
if (!closed)
{
lowStateTime += deltaTime;
midStateTime += deltaTime;
highStateTime += deltaTime;
}
}
/*
* Gets whether or not this Gate is closed
*
* @return If closed, true
*/
public boolean isClosed()
{
return closed;
}
/*
* Adds a Sensor to this gate's Array of Sensors
*
* @param s The Sensor to add
*/
public void addSensor(Sensor s)
{
sensors.add(s);
}
/*
* Gets the Array of Sensors for this Gate
*
* @return This Gate's Sensors
*/
public Array<Sensor> gSensors()
{
return sensors;
}
/*
* Gets the ID of this Gate
*
* @return This Gate's ID
*/
public short gID()
{
return gateID;
}
/*
* Sets the ID of this Gate
*
* @param GID This Gate's new ID
*/
public void sID(short newID)
{
gateID = newID;
}
/*
* Tests if this Gate has all of its Sensors activated
*
* @return Whether or not the Gate opened
*/
public boolean test()
{
for(Sensor sensor : sensors)
{
if(sensor.getContacts() == 0)
{
return false;
}
}
open();
return true;
}
/*
* Opens this Gate
*/
private void open()
{
closed = false;
body.getFixtureList().get(0).setSensor(true);
for(Sensor sensor : sensors)
{
sensor.setOpenGateState();
}
}
/*
* Determines the first class type in a collision
*
* @param g The first entity colliding
*/
public void collide(GameEntity g)
{
g.collide(this);
}
/*
* Determines the second class type in a collision
*
* @param p The first entity colliding
*/
public void collide(Player p)
{
p.collide(this);
}
/*
* Determines the second class type in a collision
*
* @param p The first entity colliding
*/
public void collide(Prisoner p)
{
p.collide(this);
}
/*
* Determines the second class type in a collision
*
* @param rc The first entity colliding
*/
public void collide(RookieCop rc)
{
rc.collide(this);
}
/*
* @see com.percipient24.cgc.entities.GameEntity#addToWorldLayers(com.percipient24.helpers.BodyFactory)
*/
public void addToWorldLayers(LayerHandler lh)
{
rotation = body.getAngle() * Data.RADDEG;
lh.addEntityToGridLayer(gridX, gridY, this, LayerHandler.ground);
lh.addEntityToGridLayer(gridX, gridY, this, LayerHandler.fenceHigh);
}
/*
* @see com.percipient24.cgc.entities.GameEntity#removeFromWorldLayers(com.percipient24.helpers.BodyFactory)
*/
public void removeFromWorldLayers(LayerHandler lh)
{
lh.removeEntityFromGridLayer(gridX, gridY, this, LayerHandler.ground);
lh.removeEntityFromGridLayer(gridX, gridY, this, LayerHandler.fenceHigh);
}
} // End class
| mit |
microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/WorkbookFunctionsNumberValueRequest.java | 3020 | // Template Source: BaseMethodRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.models.WorkbookFunctionResult;
import com.microsoft.graph.models.WorkbookFunctions;
import com.microsoft.graph.requests.WorkbookFunctionsNumberValueRequest;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.models.WorkbookFunctionsNumberValueParameterSet;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Workbook Functions Number Value Request.
*/
public class WorkbookFunctionsNumberValueRequest extends BaseRequest<WorkbookFunctionResult> {
/**
* The request for this WorkbookFunctionsNumberValue
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public WorkbookFunctionsNumberValueRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, WorkbookFunctionResult.class);
}
/** The body for the method */
@Nullable
public WorkbookFunctionsNumberValueParameterSet body;
/**
* Invokes the method and returns a future with the result
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<WorkbookFunctionResult> postAsync() {
return sendAsync(HttpMethod.POST, body);
}
/**
* Invokes the method and returns the result
* @return result of the method invocation
* @throws ClientException an exception occurs if there was an error while the request was sent
*/
@Nullable
public WorkbookFunctionResult post() throws ClientException {
return send(HttpMethod.POST, body);
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
@Nonnull
public WorkbookFunctionsNumberValueRequest select(@Nonnull final String value) {
addSelectOption(value);
return this;
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
@Nonnull
public WorkbookFunctionsNumberValueRequest expand(@Nonnull final String value) {
addExpandOption(value);
return this;
}
}
| mit |
zbmatsu/iov | 2.Code/iov-common/src/main/java/com/zbmatsu/iov/common/web/Startup.java | 344 | package com.zbmatsu.iov.common.web;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
@Component
public class Startup {
@PostConstruct
void init() {
//1.注解解析
customAnnotationInit();
}
/**
*
*/
public void customAnnotationInit(){
System.out.println("test init......");
}
}
| mit |
martinjmares/studentsday2015 | moving-ball/src/main/java/org/glassfish/tyrus/ball/App.java | 973 | package org.glassfish.tyrus.ball;
import java.io.IOException;
import java.util.HashMap;
import javax.websocket.DeploymentException;
import org.glassfish.grizzly.http.server.CLStaticHttpHandler;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.tyrus.server.Server;
public class App {
public static void main(String... args) throws DeploymentException, IOException, InterruptedException {
Server server = new Server("0.0.0.0", 80, "/", new HashMap<>(), EventEndpoint.class, Sphero.SpheroEndpoint.class);
HttpServer staticContent = HttpServer.createSimpleServer("/", "0.0.0.0", 8080);
HttpHandler httpHandler = new CLStaticHttpHandler(HttpServer.class.getClassLoader(), "/web/");
staticContent.getServerConfiguration().addHttpHandler(httpHandler, "/");
staticContent.start();
server.start();
Thread.currentThread().join();
}
}
| mit |
Azure/azure-sdk-for-java | sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListSamples.java | 1948 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.applicationinsights.generated;
import com.azure.core.util.Context;
import com.azure.resourcemanager.applicationinsights.models.CategoryType;
/** Samples for Workbooks List. */
public final class WorkbooksListSamples {
/*
* x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-08-01/examples/WorkbooksManagedList.json
*/
/**
* Sample code: WorkbooksManagedList.
*
* @param manager Entry point to ApplicationInsightsManager.
*/
public static void workbooksManagedList(
com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) {
manager.workbooks().list(CategoryType.WORKBOOK, null, null, Context.NONE);
}
/*
* x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-08-01/examples/WorkbooksListSub.json
*/
/**
* Sample code: WorkbooksListSub.
*
* @param manager Entry point to ApplicationInsightsManager.
*/
public static void workbooksListSub(
com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) {
manager.workbooks().list(CategoryType.WORKBOOK, null, null, Context.NONE);
}
/*
* x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-08-01/examples/WorkbooksList2.json
*/
/**
* Sample code: WorkbooksList2.
*
* @param manager Entry point to ApplicationInsightsManager.
*/
public static void workbooksList2(
com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) {
manager.workbooks().list(CategoryType.WORKBOOK, null, null, Context.NONE);
}
}
| mit |
mlaux/mcmod | src/org/objectweb/asm/tree/InsnList.java | 17454 | /***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2007 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.objectweb.asm.tree;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import org.objectweb.asm.MethodVisitor;
/**
* A doubly linked list of {@link AbstractInsnNode} objects. <i>This
* implementation is not thread safe</i>.
*/
public class InsnList {
/**
* Indicates if preconditions of methods of this class must be checked.
* <i>Checking preconditions causes the {@link #indexOf indexOf},
* {@link #set set}, {@link #insert(AbstractInsnNode, AbstractInsnNode)},
* {@link #insert(AbstractInsnNode, InsnList)}, {@link #remove remove} and
* {@link #clear} methods to execute in O(n) time instead of O(1)</i>.
*/
public static boolean check;
/**
* The number of instructions in this list.
*/
private int size;
/**
* The first instruction in this list. May be <tt>null</tt>.
*/
private AbstractInsnNode first;
/**
* The last instruction in this list. May be <tt>null</tt>.
*/
private AbstractInsnNode last;
/**
* A cache of the instructions of this list. This cache is used to improve
* the performance of the {@link #get} method.
*/
AbstractInsnNode[] cache;
/**
* Returns the number of instructions in this list.
*
* @return the number of instructions in this list.
*/
public int size() {
return size;
}
/**
* Returns the first instruction in this list.
*
* @return the first instruction in this list, or <tt>null</tt> if the
* list is empty.
*/
public AbstractInsnNode getFirst() {
return first;
}
/**
* Returns the last instruction in this list.
*
* @return the last instruction in this list, or <tt>null</tt> if the list
* is empty.
*/
public AbstractInsnNode getLast() {
return last;
}
/**
* Returns the instruction whose index is given. This method builds a cache
* of the instructions in this list to avoid scanning the whole list each
* time it is called. Once the cache is built, this method run in constant
* time. This cache is invalidated by all the methods that modify the list.
*
* @param index the index of the instruction that must be returned.
* @return the instruction whose index is given.
* @throws IndexOutOfBoundsException if (index < 0 || index >= size()).
*/
public AbstractInsnNode get(final int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
if (cache == null) {
cache = toArray();
}
return cache[index];
}
/**
* Returns <tt>true</tt> if the given instruction belongs to this list.
* This method always scans the instructions of this list until it finds the
* given instruction or reaches the end of the list.
*
* @param insn an instruction.
* @return <tt>true</tt> if the given instruction belongs to this list.
*/
public boolean contains(final AbstractInsnNode insn) {
AbstractInsnNode i = first;
while (i != null && i != insn) {
i = i.next;
}
return i != null;
}
/**
* Returns the index of the given instruction in this list. This method
* builds a cache of the instruction indexes to avoid scanning the whole
* list each time it is called. Once the cache is built, this method run in
* constant time. The cache is invalidated by all the methods that modify
* the list.
*
* @param insn an instruction <i>of this list</i>.
* @return the index of the given instruction in this list. <i>The result of
* this method is undefined if the given instruction does not belong
* to this list</i>. Use {@link #contains contains} to test if an
* instruction belongs to an instruction list or not.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt> and
* if insn does not belong to this list.
*/
public int indexOf(final AbstractInsnNode insn) {
if (check && !contains(insn)) {
throw new IllegalArgumentException();
}
if (cache == null) {
cache = toArray();
}
return insn.index;
}
/**
* Makes the given visitor visit all of the instructions in this list.
*
* @param mv the method visitor that must visit the instructions.
*/
public void accept(final MethodVisitor mv) {
AbstractInsnNode insn = first;
while (insn != null) {
insn.accept(mv);
insn = insn.next;
}
}
/**
* Returns an iterator over the instructions in this list.
*
* @return an iterator over the instructions in this list.
*/
public ListIterator<?> iterator() {
return iterator(0);
}
/**
* Returns an iterator over the instructions in this list.
*
* @return an iterator over the instructions in this list.
*/
public ListIterator<?> iterator(int index) {
return new InsnListIterator(index);
}
/**
* Returns an array containing all of the instructions in this list.
*
* @return an array containing all of the instructions in this list.
*/
public AbstractInsnNode[] toArray() {
int i = 0;
AbstractInsnNode elem = first;
AbstractInsnNode[] insns = new AbstractInsnNode[size];
while (elem != null) {
insns[i] = elem;
elem.index = i++;
elem = elem.next;
}
return insns;
}
/**
* Replaces an instruction of this list with another instruction.
*
* @param location an instruction <i>of this list</i>.
* @param insn another instruction, <i>which must not belong to any
* {@link InsnList}</i>.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt>,
* and if i does not belong to this list or if insn belongs to an
* instruction list.
*/
public void set(final AbstractInsnNode location, final AbstractInsnNode insn) {
if (check && !(contains(location) && insn.index == -1)) {
throw new IllegalArgumentException();
}
AbstractInsnNode next = location.next;
insn.next = next;
if (next != null) {
next.prev = insn;
} else {
last = insn;
}
AbstractInsnNode prev = location.prev;
insn.prev = prev;
if (prev != null) {
prev.next = insn;
} else {
first = insn;
}
if (cache != null) {
int index = location.index;
cache[index] = insn;
insn.index = index;
} else {
insn.index = 0; // insn now belongs to an InsnList
}
location.index = -1; // i no longer belongs to an InsnList
location.prev = null;
location.next = null;
}
/**
* Adds the given instruction to the end of this list.
*
* @param insn an instruction, <i>which must not belong to any
* {@link InsnList}</i>.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt>,
* and if insn belongs to an instruction list.
*/
public void add(final AbstractInsnNode insn) {
if (check && insn.index != -1) {
throw new IllegalArgumentException();
}
++size;
if (last == null) {
first = insn;
last = insn;
} else {
last.next = insn;
insn.prev = last;
}
last = insn;
cache = null;
insn.index = 0; // insn now belongs to an InsnList
}
/**
* Adds the given instructions to the end of this list.
*
* @param insns an instruction list, which is cleared during the process.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt>,
* and if insn == this.
*/
public void add(final InsnList insns) {
if (check && insns == this) {
throw new IllegalArgumentException();
}
if (insns.size == 0) {
return;
}
size += insns.size;
if (last == null) {
first = insns.first;
last = insns.last;
} else {
AbstractInsnNode elem = insns.first;
last.next = elem;
elem.prev = last;
last = insns.last;
}
cache = null;
insns.removeAll(false);
}
/**
* Inserts the given instruction at the begining of this list.
*
* @param insn an instruction, <i>which must not belong to any
* {@link InsnList}</i>.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt>,
* and if insn belongs to an instruction list.
*/
public void insert(final AbstractInsnNode insn) {
if (check && insn.index != -1) {
throw new IllegalArgumentException();
}
++size;
if (first == null) {
first = insn;
last = insn;
} else {
first.prev = insn;
insn.next = first;
}
first = insn;
cache = null;
insn.index = 0; // insn now belongs to an InsnList
}
/**
* Inserts the given instructions at the begining of this list.
*
* @param insns an instruction list, which is cleared during the process.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt>,
* and if insn == this.
*/
public void insert(final InsnList insns) {
if (check && insns == this) {
throw new IllegalArgumentException();
}
if (insns.size == 0) {
return;
}
size += insns.size;
if (first == null) {
first = insns.first;
last = insns.last;
} else {
AbstractInsnNode elem = insns.last;
first.prev = elem;
elem.next = first;
first = insns.first;
}
cache = null;
insns.removeAll(false);
}
/**
* Inserts the given instruction after the specified instruction.
*
* @param location an instruction <i>of this list</i> after which insn must be
* inserted.
* @param insn the instruction to be inserted, <i>which must not belong to
* any {@link InsnList}</i>.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt>,
* and if i does not belong to this list or if insn belongs to an
* instruction list.
*/
public void insert(final AbstractInsnNode location, final AbstractInsnNode insn) {
if (check && !(contains(location) && insn.index == -1)) {
throw new IllegalArgumentException();
}
++size;
AbstractInsnNode next = location.next;
if (next == null) {
last = insn;
} else {
next.prev = insn;
}
location.next = insn;
insn.next = next;
insn.prev = location;
cache = null;
insn.index = 0; // insn now belongs to an InsnList
}
/**
* Inserts the given instructions after the specified instruction.
*
* @param location an instruction <i>of this list</i> after which the instructions
* must be inserted.
* @param insns the instruction list to be inserted, which is cleared during
* the process.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt>,
* and if i does not belong to this list or if insns == this.
*/
public void insert(final AbstractInsnNode location, final InsnList insns) {
if (check && !(contains(location) && insns != this)) {
throw new IllegalArgumentException();
}
if (insns.size == 0) {
return;
}
size += insns.size;
AbstractInsnNode ifirst = insns.first;
AbstractInsnNode ilast = insns.last;
AbstractInsnNode next = location.next;
if (next == null) {
last = ilast;
} else {
next.prev = ilast;
}
location.next = ifirst;
ilast.next = next;
ifirst.prev = location;
cache = null;
insns.removeAll(false);
}
/**
* Inserts the given instruction before the specified instruction.
*
* @param location an instruction <i>of this list</i> before which insn must be
* inserted.
* @param insn the instruction to be inserted, <i>which must not belong to
* any {@link InsnList}</i>.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt>,
* and if i does not belong to this list or if insn belongs to an
* instruction list.
*/
public void insertBefore(final AbstractInsnNode location, final AbstractInsnNode insn) {
if (check && !(contains(location) && insn.index == -1)) {
throw new IllegalArgumentException();
}
++size;
AbstractInsnNode prev = location.prev;
if (prev == null) {
first = insn;
} else {
prev.next = insn;
}
location.prev = insn;
insn.next = location;
insn.prev = prev;
cache = null;
insn.index = 0; // insn now belongs to an InsnList
}
/**
* Inserts the given instructions before the specified instruction.
*
* @param location an instruction <i>of this list</i> before which the instructions
* must be inserted.
* @param insns the instruction list to be inserted, which is cleared during
* the process.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt>,
* and if i does not belong to this list or if insns == this.
*/
public void insertBefore(final AbstractInsnNode location, final InsnList insns) {
if (check && !(contains(location) && insns != this)) {
throw new IllegalArgumentException();
}
if (insns.size == 0) {
return;
}
size += insns.size;
AbstractInsnNode ifirst = insns.first;
AbstractInsnNode ilast = insns.last;
AbstractInsnNode prev = location.prev;
if (prev == null) {
first = ifirst;
} else {
prev.next = ifirst;
}
location.prev = ilast;
ilast.next = location;
ifirst.prev = prev;
cache = null;
insns.removeAll(false);
}
/**
* Removes the given instruction from this list.
*
* @param insn the instruction <i>of this list</i> that must be removed.
* @throws IllegalArgumentException if {@link #check} is <tt>true</tt>,
* and if insn does not belong to this list.
*/
public void remove(final AbstractInsnNode insn) {
if (check && !contains(insn)) {
throw new IllegalArgumentException();
}
--size;
AbstractInsnNode next = insn.next;
AbstractInsnNode prev = insn.prev;
if (next == null) {
if (prev == null) {
first = null;
last = null;
} else {
prev.next = null;
last = prev;
}
} else {
if (prev == null) {
first = next;
next.prev = null;
} else {
prev.next = next;
next.prev = prev;
}
}
cache = null;
insn.index = -1; // insn no longer belongs to an InsnList
insn.prev = null;
insn.next = null;
}
/**
* Removes all of the instructions of this list.
*
* @param mark if the instructions must be marked as no longer belonging to
* any {@link InsnList}.
*/
private void removeAll(final boolean mark) {
if (mark) {
AbstractInsnNode insn = first;
while (insn != null) {
AbstractInsnNode next = insn.next;
insn.index = -1; // insn no longer belongs to an InsnList
insn.prev = null;
insn.next = null;
insn = next;
}
}
size = 0;
first = null;
last = null;
cache = null;
}
/**
* Removes all of the instructions of this list.
*/
public void clear() {
removeAll(check);
}
/**
* Reset all labels in the instruction list. This method should be called
* before reusing same instructions list between several
* <code>ClassWriter</code>s.
*/
public void resetLabels() {
AbstractInsnNode insn = first;
while (insn != null) {
if (insn instanceof LabelNode) {
((LabelNode) insn).resetLabel();
}
insn = insn.next;
}
}
private final class InsnListIterator implements ListIterator<Object> {
AbstractInsnNode next;
AbstractInsnNode prev;
InsnListIterator(int index) {
if (index == size()) {
next = null;
prev = getLast();
} else {
next = get(index);
prev = next.prev;
}
}
public boolean hasNext() {
return next != null;
}
public Object next() {
if (next == null) {
throw new NoSuchElementException();
}
AbstractInsnNode result = next;
prev = result;
next = result.next;
return result;
}
public void remove() {
InsnList.this.remove(prev);
prev = prev.prev;
}
public boolean hasPrevious() {
return prev != null;
}
public Object previous() {
AbstractInsnNode result = prev;
next = result;
prev = result.prev;
return result;
}
public int nextIndex() {
if (next == null) {
return size();
}
if (cache == null) {
cache = toArray();
}
return next.index;
}
public int previousIndex() {
if (prev == null) {
return -1;
}
if (cache == null) {
cache = toArray();
}
return prev.index;
}
public void add(Object o) {
InsnList.this.insertBefore(next, (AbstractInsnNode) o);
prev = (AbstractInsnNode) o;
}
public void set(Object o) {
InsnList.this.set(next.prev, (AbstractInsnNode) o);
prev = (AbstractInsnNode) o;
}
}
}
| mit |
Jaewan-Yun/Classical-Simulation | src/org/yoon_technology/engine/objects/Graph2D.java | 2233 | package org.yoon_technology.engine.objects;
/**
* Refer to LICENSE
*
* @author Jaewan Yun (jay50@pitt.edu)
*/
public class Graph2D extends World {
protected double xMax;
protected double xMin;
public Graph2D() {
this.restoreWorldSettings();
}
@Override
public void restoreWorldSettings() {
super.restoreWorldSettings();
// TODO
}
@Override
public double resized(int width, int height) {
this.width = width;
this.height = height;
this.xMax = (double)width/2.0;
this.xMin = (double)width/-2.0;
// createAxes(0, 0);
return 1.0;
}
// Screen coordinates X, Y at which to place the origin
protected void createAxes(int originX, int originY) {
// ArrayList<WorldObject> objects = new ArrayList<>();
//
// // X AXIS
// WorldObjectProperty xAxisProperty1 = new WorldObjectProperty();
// xAxisProperty1.addProperty(Color.LIGHT_GRAY);
// xAxisProperty1.setDrawMode(WorldObjectProperty.LINES);
// // Break continuum
// WorldObjectProperty xAxisProperty2 = new WorldObjectProperty();
// xAxisProperty2.addProperty(Color.LIGHT_GRAY);
// xAxisProperty2.setDrawMode(WorldObjectProperty.END_LINES);
//
// WorldObject lineObject = new WorldObject();
// lineObject.setPosition(new Vector3d(
// xMin,
// originY,
// 0.0));
// lineObject.setProperties(xAxisProperty1);
// objects.add(lineObject);
//
// lineObject = new WorldObject();
// lineObject.setPosition(new Vector3d(
// xMax,
// originY,
// 0.0));
// lineObject.setProperties(xAxisProperty2);
// objects.add(lineObject);
//
//
// // TODO Y Axis
//
// synchronized(this.objects) {
// for(int j = 0; j < objects.size(); j++) {
// this.addObject(objects.get(j));
// }
// }
// synchronized(this.texts) {
// for(int j = 0; j < texts.size(); j++) {
// this.addText(texts.get(j));
// }
// }
}
public void initialize() {
// ArrayList<WorldObject> objects = new ArrayList<>();
//
// synchronized(this.points) {
// this.clear();
// for(int j = 0; j < objects.size(); j++) {
// this.addPoint(objects.get(j));
// }
// createAxes(0, 0);
// }
}
@Override
public void sendSecondTick() {
}
}
| mit |
peterpaul/cli | src/main/java/net/kleinhaneveld/cli/exceptions/TooManyElementException.java | 308 | package net.kleinhaneveld.cli.exceptions;
import java.util.Set;
public class TooManyElementException extends RuntimeException {
private final Set items;
public <T> TooManyElementException(Set<T> items) {
this.items = items;
}
public Set getItems() {
return items;
}
}
| mit |
MobileSolution/android-lol-api | library/src/main/java/com/mobilesolutions/lolapi/models/match/MatchDetail.java | 2065 | package com.mobilesolutions.lolapi.models.match;
import com.google.gson.annotations.Expose;
import com.mobilesolutions.lolapi.models.common.Participant;
import com.mobilesolutions.lolapi.models.common.ParticipantIdentity;
import java.io.Serializable;
import java.util.List;
public class MatchDetail implements Serializable {
@Expose
private int mapId;
@Expose
private long matchCreation;
@Expose
private long matchDuration;
@Expose
private long matchId;
@Expose
private String matchMode;
@Expose
private String matchType;
@Expose
private String matchVersion;
@Expose
private List<ParticipantIdentity> participantIdentities;
@Expose
private List<Participant> participants;
@Expose
private String platformId;
@Expose
private String queueType;
@Expose
private String region;
@Expose
private String season;
@Expose
private List<Team> teams;
@Expose
private Timeline timeline;
public int getMapId() {
return mapId;
}
public long getMatchCreation() {
return matchCreation;
}
public long getMatchDuration() {
return matchDuration;
}
public long getMatchId() {
return matchId;
}
public String getMatchMode() {
return matchMode;
}
public String getMatchType() {
return matchType;
}
public String getMatchVersion() {
return matchVersion;
}
public List<ParticipantIdentity> getParticipantIdentities() {
return participantIdentities;
}
public List<Participant> getParticipants() {
return participants;
}
public String getPlatformId() {
return platformId;
}
public String getQueueType() {
return queueType;
}
public String getRegion() {
return region;
}
public String getSeason() {
return season;
}
public List<Team> getTeams() {
return teams;
}
public Timeline getTimeline() {
return timeline;
}
}
| mit |
joshiejack/Progression | src/main/java/joshie/progression/gui/buttons/ButtonJoinTeam.java | 1208 | package joshie.progression.gui.buttons;
import joshie.progression.gui.editors.GuiGroupEditor.Invite;
import joshie.progression.helpers.SplitHelper;
import joshie.progression.network.PacketChangeTeam;
import joshie.progression.network.PacketHandler;
import net.minecraft.client.gui.GuiScreen;
import static joshie.progression.gui.core.GuiList.GROUP_EDITOR;
import static joshie.progression.gui.core.GuiList.TOOLTIP;
import static joshie.progression.player.PlayerSavedData.TeamAction.JOIN;
import static net.minecraft.util.text.TextFormatting.BOLD;
public class ButtonJoinTeam extends ButtonBaseTeam {
private Invite invite;
public ButtonJoinTeam(Invite invite, int x, int y) {
super("Join " + invite.name, x, y);
this.invite = invite;
}
@Override
public void onClicked() {
if (!GuiScreen.isShiftKeyDown()) PacketHandler.sendToServer(new PacketChangeTeam(JOIN, invite.owner));
GROUP_EDITOR.removeInvite(invite); //Remove the invite always
}
@Override
public void addTooltip() {
TOOLTIP.add(BOLD + "Join Team");
TOOLTIP.add(SplitHelper.splitTooltip("If you want to join this team, click, if not shift click.", 40));
}
}
| mit |
laidig/siri-20-java | src/eu/datex2/schema/_2_0rc1/_2_0/SubjectTypeOfWorksEnum.java | 3919 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.11.30 at 08:24:17 PM JST
//
package eu.datex2.schema._2_0rc1._2_0;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SubjectTypeOfWorksEnum.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="SubjectTypeOfWorksEnum">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="bridge"/>
* <enumeration value="buriedCables"/>
* <enumeration value="buriedServices"/>
* <enumeration value="crashBarrier"/>
* <enumeration value="gallery"/>
* <enumeration value="gantry"/>
* <enumeration value="gasMainWork"/>
* <enumeration value="interchange"/>
* <enumeration value="junction"/>
* <enumeration value="levelCrossing"/>
* <enumeration value="lightingSystem"/>
* <enumeration value="measurementEquipment"/>
* <enumeration value="noiseProtection"/>
* <enumeration value="road"/>
* <enumeration value="roadsideDrains"/>
* <enumeration value="roadsideEmbankment"/>
* <enumeration value="roadsideEquipment"/>
* <enumeration value="roadSigns"/>
* <enumeration value="roundabout"/>
* <enumeration value="tollGate"/>
* <enumeration value="tunnel"/>
* <enumeration value="waterMain"/>
* <enumeration value="other"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "SubjectTypeOfWorksEnum")
@XmlEnum
public enum SubjectTypeOfWorksEnum {
@XmlEnumValue("bridge")
BRIDGE("bridge"),
@XmlEnumValue("buriedCables")
BURIED_CABLES("buriedCables"),
@XmlEnumValue("buriedServices")
BURIED_SERVICES("buriedServices"),
@XmlEnumValue("crashBarrier")
CRASH_BARRIER("crashBarrier"),
@XmlEnumValue("gallery")
GALLERY("gallery"),
@XmlEnumValue("gantry")
GANTRY("gantry"),
@XmlEnumValue("gasMainWork")
GAS_MAIN_WORK("gasMainWork"),
@XmlEnumValue("interchange")
INTERCHANGE("interchange"),
@XmlEnumValue("junction")
JUNCTION("junction"),
@XmlEnumValue("levelCrossing")
LEVEL_CROSSING("levelCrossing"),
@XmlEnumValue("lightingSystem")
LIGHTING_SYSTEM("lightingSystem"),
@XmlEnumValue("measurementEquipment")
MEASUREMENT_EQUIPMENT("measurementEquipment"),
@XmlEnumValue("noiseProtection")
NOISE_PROTECTION("noiseProtection"),
@XmlEnumValue("road")
ROAD("road"),
@XmlEnumValue("roadsideDrains")
ROADSIDE_DRAINS("roadsideDrains"),
@XmlEnumValue("roadsideEmbankment")
ROADSIDE_EMBANKMENT("roadsideEmbankment"),
@XmlEnumValue("roadsideEquipment")
ROADSIDE_EQUIPMENT("roadsideEquipment"),
@XmlEnumValue("roadSigns")
ROAD_SIGNS("roadSigns"),
@XmlEnumValue("roundabout")
ROUNDABOUT("roundabout"),
@XmlEnumValue("tollGate")
TOLL_GATE("tollGate"),
@XmlEnumValue("tunnel")
TUNNEL("tunnel"),
@XmlEnumValue("waterMain")
WATER_MAIN("waterMain"),
@XmlEnumValue("other")
OTHER("other");
private final String value;
SubjectTypeOfWorksEnum(String v) {
value = v;
}
public String value() {
return value;
}
public static SubjectTypeOfWorksEnum fromValue(String v) {
for (SubjectTypeOfWorksEnum c: SubjectTypeOfWorksEnum.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| mit |
narfman0/freeboot | src/main/java/com/blastedstudios/freeboot/ai/bt/actions/execution/Shoot.java | 4052 | // *******************************************************
// MACHINE GENERATED CODE
// MUST BE CAREFULLY COMPLETED
//
// ABSTRACT METHODS MUST BE IMPLEMENTED
//
// Generated on 01/25/2013 21:35:07
// *******************************************************
package com.blastedstudios.freeboot.ai.bt.actions.execution;
import com.badlogic.gdx.math.Vector2;
import com.blastedstudios.gdxworld.util.Log;
import com.blastedstudios.freeboot.world.WorldManager;
import com.blastedstudios.freeboot.world.being.Being;
import com.blastedstudios.freeboot.world.being.NPC;
import com.blastedstudios.freeboot.world.being.NPC.AIFieldEnum;
import com.blastedstudios.freeboot.world.weapon.Weapon;
/** ExecutionAction class created from MMPM action Shoot. */
public class Shoot extends jbt.execution.task.leaf.action.ExecutionAction {
/**
* Value of the parameter "target" in case its value is specified at
* construction time. null otherwise.
*/
private float[] target;
/**
* Location, in the context, of the parameter "target" in case its value is
* not specified at construction time. null otherwise.
*/
private java.lang.String targetLoc;
/**
* Constructor. Constructs an instance of Shoot that is able to run a
* com.blastedstudios.freeboot.ai.bt.actions.Shoot.
*
* @param target
* value of the parameter "target", or null in case it should be
* read from the context. If null,
* <code>targetLoc<code> cannot be null.
* @param targetLoc
* in case <code>target</code> is null, this variable represents
* the place in the context where the parameter's value will be
* retrieved from.
*/
public Shoot(jbt.model.core.ModelTask modelTask,
jbt.execution.core.BTExecutor executor,
jbt.execution.core.ExecutionTask parent, float[] target,
java.lang.String targetLoc) {
super(modelTask, executor, parent);
if (!(modelTask instanceof com.blastedstudios.freeboot.ai.bt.actions.Shoot)) {
throw new java.lang.RuntimeException(
"The ModelTask must subclass com.blastedstudios.freeboot.ai.bt.actions.Shoot");
}
this.target = target;
this.targetLoc = targetLoc;
}
/**
* Returns the value of the parameter "target", or null in case it has not
* been specified or it cannot be found in the context.
*/
public float[] getTarget() {
if (this.target != null) {
return this.target;
} else {
return (float[]) this.getContext().getVariable(this.targetLoc);
}
}
protected void internalSpawn() {
this.getExecutor().requestInsertionIntoList(
jbt.execution.core.BTExecutor.BTExecutorList.TICKABLE, this);
Log.debug(this.getClass().getCanonicalName(), "spawned");
}
protected jbt.execution.core.ExecutionTask.Status internalTick() {
Log.debug(this.getClass().getCanonicalName(), "ticked");
WorldManager world = (WorldManager) getContext().getVariable(AIFieldEnum.WORLD.name());
NPC self = (NPC) getContext().getVariable(AIFieldEnum.SELF.name());
if(!world.isPause()){
Vector2 target = new Vector2(getTarget()[0], getTarget()[1]);
Vector2 direction = target.cpy().sub(self.getPosition()).nor();
self.aim((float)Math.atan2(direction.y, direction.x));
Weapon equipped = self.getEquippedWeapon();
Being targetBeing = world.getClosestBeing(self, false, false);
int topLevel = Math.max(targetBeing == null ? 1 : targetBeing.getLevel(), self.getLevel());
if(equipped != null && equipped.getMSSinceAttack() > NPC.shootDelay(topLevel, self.getDifficulty()))
self.attack(direction, world);
}
return Status.SUCCESS;
}
protected void internalTerminate() {}
protected void restoreState(jbt.execution.core.ITaskState state) {}
protected jbt.execution.core.ITaskState storeState() {
return null;
}
protected jbt.execution.core.ITaskState storeTerminationState() {
return null;
}
} | mit |
DemigodsRPG/ErrorNoise | Standard/src/main/java/com/demigodsrpg/errornoise/ErrorNoiseRegistry.java | 1428 | package com.demigodsrpg.errornoise;
import org.bukkit.Bukkit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.stream.Collectors;
/**
* Registry for the error handlers and tasks.
*/
public class ErrorNoiseRegistry {
private final List<ErrorTask> TASKS = new ArrayList<>();
ErrorNoiseRegistry() {
}
public List<Handler> getErrorHandlers() {
// Get all of the handlers in a new ArrayList.
List<Handler> handlers = new ArrayList<>();
// Remove all non-relevant handlers from this list.
handlers.addAll(Arrays.asList(Bukkit.getServer().getLogger().getHandlers()).stream().
filter(handler -> handler instanceof ErrorHandler).collect(Collectors.toList()));
// Return the list of handlers.
return handlers;
}
public List<ErrorTask> getErrorTasks() {
return TASKS;
}
public void register(Level level) {
// Create and register an error handler for this log level.
Bukkit.getServer().getLogger().addHandler(new ErrorHandler(level));
// Create and register an error task for this log level.
TASKS.add(new ErrorTask(level));
}
public void alertErrorTasks(Level level) {
TASKS.stream().filter(task -> level.equals(task.getLevel())).forEach(ErrorTask::run);
}
}
| mit |
thahn0720/xml_checker | src/thahn/java/xmlchecker/MyConstants.java | 995 | package thahn.java.xmlchecker;
import thahn.java.xmlchecker.template.Flag;
public class MyConstants {
public static final String LOGO_PATH = "/icons/cloud.png";
public static final String TAG_PATH = "/icons/tag_generic_emphasized_obj.gif";
public static final String COMMENT_PATH = "/icons/tag-macro.gif";
public static final String ATTRIBUTE_PATH = "/icons/attribute.gif";
public static final String VARIABLE_PATH = "/icons/variable_view.gif";
/** "/descriptorchecker/template/init.xml" */
public static final String DESCRIPTOR_TEMPLATE_PATH
= "/" + Flag.class.getPackage().getName().replace(".", "/") + "/init.xml";
public static final String CMS_XML_CONTEXT = "thahn.java.descriptorchecker.context";
public static final String COMMAND_TOOLTIP_DES = "thahn.java.descriptorchecker.command.tooltip.des";
public static final String CMS_XML_EXTENSTION = "xml";
}
| mit |
overminder/YASIR | yasir-truffle/src/main/java/com/github/overmind/yasir/ast/ReadLocalNode.java | 1275 | package com.github.overmind.yasir.ast;
import com.oracle.truffle.api.dsl.NodeField;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.FrameSlotTypeException;
import com.oracle.truffle.api.frame.VirtualFrame;
// The specialization must match the write node's impl.
@NodeField(name = "slot", type = FrameSlot.class)
public abstract class ReadLocalNode extends Expr {
abstract FrameSlot getSlot();
@Specialization(rewriteOn = FrameSlotTypeException.class)
protected long readLong(VirtualFrame frame)
throws FrameSlotTypeException {
return frame.getLong(getSlot());
}
@Specialization(rewriteOn = FrameSlotTypeException.class)
protected boolean readBoolean(VirtualFrame frame)
throws FrameSlotTypeException {
return frame.getBoolean(getSlot());
}
@Specialization(rewriteOn = FrameSlotTypeException.class)
protected Object readObject(VirtualFrame frame)
throws FrameSlotTypeException {
return frame.getObject(getSlot());
}
@Specialization(contains = {"readLong", "readBoolean", "readObject"})
public Object read(VirtualFrame frame) {
return frame.getValue(getSlot());
}
}
| mit |
ppati000/visualDFA | Implementierung/visual-dfa/src/main/java/dfa/analyses/TaintJoin.java | 1740 | package dfa.analyses;
import java.util.Iterator;
import java.util.Set;
import dfa.analyses.TaintElement.TaintState;
import dfa.analyses.TaintElement.Value;
import dfa.framework.Join;
import soot.jimple.internal.JimpleLocal;
/**
* A {@code TaintJoin} performs the join for a {@code TaintAnalysis}.
*
* @author Sebastian Rauch
*/
public class TaintJoin implements Join<TaintElement> {
private JoinHelper joinHelper = new JoinHelper();
@Override
public TaintElement join(Set<TaintElement> elements) {
return joinHelper.performJoin(elements);
}
private static class JoinHelper extends LocalMapElementJoinHelper<Value, TaintElement> {
@Override
public Value doValueJoin(Set<TaintElement> elements, JimpleLocal local) {
Iterator<? extends LocalMapElement<Value>> elementIt = elements.iterator();
Value refVal = elementIt.next().getValue(local);
Value result = new Value(refVal.getTaintState(), refVal.wasViolated());
while (elementIt.hasNext()) {
Value currentVal = elementIt.next().getValue(local);
if (currentVal.wasViolated()) {
result.setViolated(true);
}
switch (currentVal.getTaintState()) {
case TAINTED:
result.setTaintState(TaintState.TAINTED);
break;
case CLEAN:
if (result.getTaintState().equals(TaintState.BOTTOM)) {
result.setTaintState(TaintState.CLEAN);
}
break;
default: // ignore bottom
}
}
return result;
}
}
}
| mit |
argyakrivos/eos-http-server | src/main/java/com/akrivos/eos/Main.java | 1848 | package com.akrivos.eos;
import com.akrivos.eos.config.Settings;
import com.akrivos.eos.http.FilesHandler;
import com.akrivos.eos.http.HttpServer;
import com.akrivos.eos.http.SocketConnector;
import org.apache.log4j.Logger;
/**
* Entry point of EOS
*/
public class Main {
private static final Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) {
// check if we are given a server configuration
if (args.length > 0) {
Settings.INSTANCE.loadSettings(args[0]);
}
// exit if the settings are not valid
if (!Settings.INSTANCE.areValid()) {
logger.error("Cannot start: server configuration is invalid.");
System.exit(1);
}
// get validated settings
String address = Settings.INSTANCE.getValueFor(Settings.SERVER_ADDRESS);
int port = Settings.INSTANCE.getValueAsIntegerFor(Settings.SERVER_PORT);
String root = Settings.INSTANCE.getValueFor(Settings.SERVER_ROOT);
// create the connector
Connector connector = new SocketConnector(10);
connector.setAddress(address);
connector.setPort(port);
Connector[] connectors = new Connector[]{connector};
// create the handler
Handler handler = new FilesHandler(root);
// create the server
Server server = new HttpServer();
server.setConnectors(connectors);
server.setHandler(handler);
// assign server to connector and handler
connector.setServer(server);
handler.setServer(server);
// start the server
try {
server.start();
} catch (Exception e) {
logger.error("Could not start the server on "
+ address + ":" + port);
System.exit(1);
}
}
} | mit |
dbunibas/BART | Bart_GUI/View/src/it/unibas/bartgui/view/panel/editor/ConfVioGenQ/ConfVioGenQEditPanel.java | 6269 | package it.unibas.bartgui.view.panel.editor.ConfVioGenQ;
import it.unibas.bartgui.resources.R;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import org.jdesktop.swingx.JXTitledSeparator;
import org.netbeans.validation.api.Problem;
import org.netbeans.validation.api.builtin.stringvalidation.StringValidators;
import org.netbeans.validation.api.ui.ValidationGroup;
import org.netbeans.validation.api.ui.swing.ValidationPanel;
import org.openide.util.ImageUtilities;
import org.openide.util.WeakListeners;
/**
*
* @author Grandinetti Giovanni <grandinetti.giovanni13@gmail.com>
*/
public class ConfVioGenQEditPanel extends JPanel{
private JButton okButton;
private JButton cancelButton;
private JXTitledSeparator title;
private ValidationPanel panelValAcc;
private ValidationGroup vg;
private ConfVioGenQPanel panel;
public ConfVioGenQEditPanel() {
setLayout(new BorderLayout());
//InitTitle();
InitButton();
initPanel();
//add(title,BorderLayout.NORTH);
add(panelValAcc,BorderLayout.CENTER);
}
private void initPanel() {
panelValAcc = new ValidationPanel();
getPanelValAcc().setBorder(new TitledBorder(new LineBorder(Color.BLACK), "VioGenQuery Configuration",
TitledBorder.CENTER,TitledBorder.TOP));
panel = new ConfVioGenQPanel();
getPanelValAcc().setInnerComponent(panel);
vg = getPanelValAcc().getValidationGroup();
vg.add(panel.getPercentagjTextField1(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getQueryExecutorjTextField1(), StringValidators.NO_WHITESPACE);
vg.add(panel.getMaxNumberOfRowsForSingleTupleQueriesjTextField1(),StringValidators.REQUIRE_VALID_INTEGER);
vg.add(panel.getSizeFactorForStandardQueriesTextField(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getSizeFactorForSymmetricQueriesTextField(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getSizeFactorForInequalityQueriesTextField(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getSizeFactorForSingleTupleQueriesTextField(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getProbabilityFactorForStandardQueriesTextField(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getProbabilityFactorForSymmetricQueriesTextField(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getProbabilityFactorForInequalityQueriesTextField(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getProbabilityFactorForSingleTupleQueriesTextField(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getWindowSizeFactorForStandardQueriesTextField(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getWindowSizeFactorForSymmetricQueriesjTextField1(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getWindowSizeFactorForInequalityQueriesjTextField1(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getWindowSizeFactorForSingleTupleQueriesjTextField1(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getOffsetFactorForStandardQueriesjTextField1(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getOffsetFactorForSymmetricQueriesjTextField1(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getOffsetFactorForInequalityQueriesjTextField1(), StringValidators.REQUIRE_VALID_NUMBER);
vg.add(panel.getOffsetFactorForSingleTupleQueriesjTextField1(), StringValidators.REQUIRE_VALID_NUMBER);
for(Document d : panel.getAllDocument()) {
d.addDocumentListener(WeakListeners.create(DocumentListener.class, new ValidDocListener(), panel));
}
}
/*private void InitTitle() {
title = new JXTitledSeparator();
getTitle().setIcon(ImageUtilities.image2Icon(ImageUtilities.loadImage(R.IMAGE_SETTINGS_Blu)));
getTitle().setHorizontalAlignment(SwingConstants.CENTER);
getTitle().setForeground(Color.BLUE.darker());
getTitle().setFont(new Font("Times New Roman", Font.ITALIC, 16));
getTitle().setTitle("VioGenQuery Configuration");
}*/
public Object[] getButtons() {
Object[] o = {getOkButton(),getCancelButton()};
return o;
}
private void InitButton() {
okButton = new JButton("OK");
getOkButton().setEnabled(false);
cancelButton = new JButton("Cancel");
}
/**
* @return the okButton
*/
public JButton getOkButton() {
return okButton;
}
/**
* @return the cancelButton
*/
public JButton getCancelButton() {
return cancelButton;
}
/**
* @return the title
*/
public JXTitledSeparator getTitle() {
return title;
}
/**
* @return the panelValAcc
*/
public ValidationPanel getPanelValAcc() {
return panelValAcc;
}
/**
* @return the vg
*/
public ValidationGroup getVg() {
return vg;
}
/**
* @return the panel
*/
public ConfVioGenQPanel getPanel() {
return panel;
}
private class ValidDocListener implements DocumentListener {
@Override
public void insertUpdate(DocumentEvent e) {
checkValidation();
}
@Override
public void removeUpdate(DocumentEvent e) {
checkValidation();
}
@Override
public void changedUpdate(DocumentEvent e) {
checkValidation();
}
private void checkValidation() {
Problem validateAll = vg.performValidation();
if (validateAll != null) {
okButton.setEnabled(false);
} else {
okButton.setEnabled(true);
}
}
}
}
| mit |
RCoon/CodingBat | Java/recursion2/Split53Test.java | 1368 | package recursion2;
/*
* Given an array of ints, is it possible to divide the ints into two groups,
* so that the sum of the two groups is the same, with these constraints:
* all the values that are multiple of 5 must be in one group, and all the
* values that are a multiple of 3 (and not a multiple of 5) must be in the
* other. (No loops needed.)
*
* split53({1,1}) --> true
* split53({1, 1, 1}) --> false
* split53({2, 4, 2}) --> true
*/
public class Split53Test {
public static void main(String[] args) {
Split53Test test = new Split53Test();
System.out.println(test.split53(new int[] {1, 1}));
System.out.println(test.split53(new int[] {1, 1, 1}));
System.out.println(test.split53(new int[] {2, 4, 2}));
}
public boolean split53(int[] nums) {
return helper(0, nums, 0, 0);
}
public boolean helper(int start, int[] nums, int sum5, int sum3) {
if (start >= nums.length) {
return sum5 == sum3;
} else if (nums[start] % 5 == 0) {
return helper(start + 1, nums, sum5 + nums[start], sum3);
} else if (nums[start] % 3 == 0) {
return helper(start + 1, nums, sum5, sum3 + nums[start]);
} else {
return helper(start + 1, nums, sum5 + nums[start], sum3)
|| helper(start + 1, nums, sum5, sum3 + nums[start]);
}
}
} | mit |
williancorrea/transport-api | src/main/java/br/com/wcorrea/transport/api/repository/financeiro/centroDeCusto/CentroDeCustoRepositoryQuery.java | 371 | package br.com.wcorrea.transport.api.repository.financeiro.centroDeCusto;
import br.com.wcorrea.transport.api.model.CentroDeCusto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface CentroDeCustoRepositoryQuery {
Page<CentroDeCusto> findAll(CentroDeCustoFiltro centroDeCustoFiltro, Pageable pageable);
}
| mit |
edralzar/wargolem | src/main/java/net/edralzar/wargolem/Brain.java | 556 | package net.edralzar.wargolem;
import net.edralzar.wargolem.model.Player;
import net.edralzar.wargolem.model.WarRoom;
public interface Brain {
/**
* Use this brain to save the state of the golem's WarRoom, ie in a file or a database
* @param room
*/
public void save(WarRoom room);
/**
* Use this brain to load a previously persisted WarRoom state, allowing the golem to reload it
* @param roomId
* @param owner
* @return the loaded WarRoom
*/
public WarRoom load(String roomId, Player owner);
}
| mit |
Pangaj/AndroidBasicProjectSetup | app/src/main/java/com/pangaj/shruthi/newprojectimportsetup/activities/NPNavigationActivity.java | 14204 | package com.pangaj.shruthi.newprojectimportsetup.activities;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Typeface;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.pangaj.shruthi.newprojectimportsetup.NPApplication;
import com.pangaj.shruthi.newprojectimportsetup.NPConstants;
import com.pangaj.shruthi.newprojectimportsetup.NPPreferences;
import com.pangaj.shruthi.newprojectimportsetup.R;
import com.pangaj.shruthi.newprojectimportsetup.fragments.NPFamilyFragment;
import com.pangaj.shruthi.newprojectimportsetup.fragments.NPHomeFragment;
import com.pangaj.shruthi.newprojectimportsetup.fragments.NPMapFragment;
import com.pangaj.shruthi.newprojectimportsetup.fragments.NPSettingsFragment;
import com.pangaj.shruthi.newprojectimportsetup.fragments.NPWorkFragment;
import com.pangaj.shruthi.newprojectimportsetup.utils.NPLog;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
/**
* Created by pangaj on 23/09/17.
*/
@RuntimePermissions
public class NPNavigationActivity extends NPBaseActivity implements NavigationView.OnNavigationItemSelectedListener, GoogleApiClient.ConnectionCallbacks {
final static int REQUEST_LOCATION = 199;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private int selectedMenuItemId;
private NPPreferences mPref;
private Context mContext;
private GoogleApiClient googleApiClient;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.np_activity_navigation);
setToolBar();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) { //may produce null pointer exception, if the actionBar is null
actionBar.setDisplayHomeAsUpEnabled(false); //hide the home icon - back button
}
mContext = getApplicationContext();
mPref = NPApplication.getInstance().getPrefs();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//set navigation header view
View headerView = navigationView.inflateHeaderView(R.layout.np_menu_header);
TextView tvUserEmail = headerView.findViewById(R.id.tv_email);
tvUserEmail.setText(mPref.getLoginEmail());
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, (Toolbar) findViewById(R.id.toolbar), R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
//initialise batch notification
TextView tvPressureMeter = (TextView) navigationView.getMenu().getItem(1).getActionView();
tvPressureMeter.setGravity(Gravity.CENTER_VERTICAL);
tvPressureMeter.setTypeface(null, Typeface.BOLD);
tvPressureMeter.setTextColor(ContextCompat.getColor(mContext, R.color.accent));
tvPressureMeter.setText(R.string.ninety_nine_plus);
navigationView.setNavigationItemSelectedListener(this);
loadInitialFragment();
}
private void loadInitialFragment() {
MenuItem navHome = navigationView.getMenu().getItem(0);
selectedMenuItemId = navHome.getItemId();
navHome.setChecked(true);
Fragment fragment = NPHomeFragment.newInstance();
replaceFragment(NPNavigationActivity.this, fragment, false, R.id.fragment_container);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
item.setChecked(true);
if (!(item.getItemId() == R.id.nav_logout || item.getItemId() == R.id.nav_maps)) {
selectedMenuItemId = item.getItemId();
drawerLayout.closeDrawers();
}
Fragment fragment;
switch (item.getItemId()) {
case R.id.nav_home:
fragment = new NPHomeFragment();
break;
case R.id.nav_work:
fragment = new NPWorkFragment();
break;
case R.id.nav_family:
fragment = new NPFamilyFragment();
break;
case R.id.nav_maps:
NPNavigationActivityPermissionsDispatcher.getLocationWithPermissionCheck(NPNavigationActivity.this);
return true;
case R.id.nav_settings:
fragment = new NPSettingsFragment();
break;
case R.id.nav_logout:
showAlertDialog(getString(R.string.logout), getString(R.string.logout_msg), true, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int id) {
mPref.clearData();
goToActivityAsNew(NPNavigationActivity.this, NPLoginScreenActivity.class);
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int id) {
navigationView.setCheckedItem(selectedMenuItemId);
}
});
return true;
default:
return true;
}
replaceFragment(NPNavigationActivity.this, fragment, false, R.id.fragment_container);
return true;
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (selectedMenuItemId != R.id.nav_home) {
if (selectedMenuItemId == R.id.nav_maps) {
if (NPMapFragment.checkOnBackPressListener()) {
loadInitialFragment();
}
} else {
loadInitialFragment();
}
} else {
super.onBackPressed();
}
}
//RunTime Permissions
@NeedsPermission(Manifest.permission.ACCESS_FINE_LOCATION)
void getLocation() {
//PermissionsDispatcher : Permission Granted
selectedMenuItemId = navigationView.getMenu().getItem(3).getItemId();
drawerLayout.closeDrawers();
replaceFragment(NPNavigationActivity.this, NPMapFragment.newInstance(), false, R.id.fragment_container);
// noLocation();
}
@OnPermissionDenied(Manifest.permission.ACCESS_FINE_LOCATION)
void onLocationDenied() {
// NOTE: Deal with a denied permission, e.g. by showing specific UI or disabling certain functionality
//PermissionsDispatcher : Permission Denied
navigationView.setCheckedItem(selectedMenuItemId);
Toast.makeText(mContext, R.string.need_location_permission_to_proceed_further, Toast.LENGTH_SHORT).show();
}
@OnShowRationale(Manifest.permission.ACCESS_FINE_LOCATION)
void showRationaleForLocation(@NonNull PermissionRequest request) {
showRationaleDialog(R.string.location_permission_fetch_current_location, request);
}
@OnNeverAskAgain(Manifest.permission.ACCESS_FINE_LOCATION)
void onLocationNeverAskAgain() {
//PermissionsDispatcher : Never Ask Again
showAlertDialog(getString(R.string.info), getString(R.string.location_permission_needed), true, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, NPConstants.REQUEST_CODE_LOCATION_PERMISSION);
Toast.makeText(NPNavigationActivity.this, getString(R.string.grant_location_permission), Toast.LENGTH_LONG).show();
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
navigationView.setCheckedItem(selectedMenuItemId);
}
});
}
// TODO: 10/1/2017 need to check the below
private void showRationaleDialog(@StringRes int messageResId, @NonNull final PermissionRequest request) {
showAlertDialog(getString(R.string.info), getString(messageResId), true, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int id) {
request.proceed();
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int id) {
request.cancel();
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// NOTE: delegate the permission handling to generated method
NPNavigationActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
// check whether gps is enabled
public boolean noLocation() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// buildAlertMessageNoGps();
enableLoc();
return true;
}
return false;
}
private void enableLoc() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
NPLog.v(TAG, "Location error " + connectionResult.getErrorCode());
}
}).build();
googleApiClient.connect();
}
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(@NonNull LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(NPNavigationActivity.this, REQUEST_LOCATION);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_LOCATION:
switch (resultCode) {
case Activity.RESULT_CANCELED: {
// The user was asked to change settings, but chose not to
finish();
break;
}
default: {
break;
}
}
break;
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
} | mit |
jeremyje/android-beryl | beryl/src/org/beryl/intents/IIntentBuilder.java | 524 | package org.beryl.intents;
import android.content.Context;
import android.content.Intent;
public interface IIntentBuilder {
/** Builds the intent using the parameters assigned to the object.
* NOTE: This operation can be expensive and should be performed on a background thread. This must be called before getIntent(). */
void prepareIntent(Context context);
/** Returns the Intent that represents the request. */
Intent getIntent();
boolean isValid();
boolean isChoosable();
CharSequence getChooserTitle();
}
| mit |
DevCrafters/SaveableSerializing | milkyway/SaveableSerializing/Parser/MinecraftParser_All.java | 2521 | package milkyway.SaveableSerializing.Parser;
import milkyway.SaveableSerializing.ItemStacks.Upper_1_7.DataTypes.ListRGB;
import milkyway.SaveableSerializing.ItemStacks.Upper_1_7.DataTypes.ListSaveable;
import milkyway.SaveableSerializing.ItemStacks.Upper_1_7.DataTypes.RGBColor;
import milkyway.SaveableSerializing.ItemStacks.Upper_1_7.ItemData.EnchantArray;
import milkyway.SaveableSerializing.ItemStacks.Upper_1_7.ItemData.Enchants;
import milkyway.SaveableSerializing.ItemStacks.Upper_1_7.ItemData.FireworkEffects;
import milkyway.SaveableSerializing.ItemStacks.Upper_1_7.ItemData.ItemMetas.*;
import milkyway.SaveableSerializing.ItemStacks.Upper_1_7.ItemData.ItemStacks;
import milkyway.SaveableSerializing.ItemStacks.Upper_1_7.PotionEffects;
/**
* Created by Developer_Unlocated on 2017-05-08.
*
* ÀÌ Å¬·¡½º´Â ¸¶ÀÎÅ©·¡ÇÁÆ® ¸ðµç ¹öÀüÀÇ ¾ÆÀÌÅÛÀ» ÀúÀåÇÕ´Ï´Ù.
*
* This class will be register instance of Minecraft ItemStack lower than 1.5.2.
*/
public class MinecraftParser_All implements ParserRegistry{
@Override
public void register() {
StaticSaveableDataRegistry.getHandle().registerSaveable(new ListRGB());
StaticSaveableDataRegistry.getHandle().registerSaveable(new ListSaveable());
StaticSaveableDataRegistry.getHandle().registerSaveable(new RGBColor());
StaticSaveableDataRegistry.getHandle().registerSaveable(new DefaultMeta());
StaticSaveableDataRegistry.getHandle().registerSaveable(new FireworkEffectsMeta());
StaticSaveableDataRegistry.getHandle().registerSaveable(new FireworksMeta());
StaticSaveableDataRegistry.getHandle().registerSaveable(new HeadMeta());
StaticSaveableDataRegistry.getHandle().registerSaveable(new LeatherArmoursMeta());
StaticSaveableDataRegistry.getHandle().registerSaveable(new PotionMeta());
StaticSaveableDataRegistry.getHandle().registerSaveable(new SaveableBookMeta());
StaticSaveableDataRegistry.getHandle().registerSaveable(new SaveableEnchantBook());
StaticSaveableDataRegistry.getHandle().registerSaveable(new EnchantArray());
StaticSaveableDataRegistry.getHandle().registerSaveable(new Enchants());
StaticSaveableDataRegistry.getHandle().registerSaveable(new FireworkEffects());
StaticSaveableDataRegistry.getHandle().registerSaveable(new ItemStacks());
StaticSaveableDataRegistry.getHandle().registerSaveable(new NullSaveableData());
StaticSaveableDataRegistry.getHandle().registerSaveable(new PotionEffects());
}
}
| mit |
asiermarzo/Ultraino | AcousticFieldSim/src/acousticfield3d/utils/TimerUtil.java | 1107 | package acousticfield3d.utils;
import java.util.HashMap;
/**
*
* @author Asier
*/
public class TimerUtil {
private static final TimerUtil _instance = new TimerUtil();
public static TimerUtil get() {
return _instance;
}
private final HashMap<String, Long> timers;
private TimerUtil(){
timers = new HashMap<>();
}
public void tick(String tag){
timers.put( tag , System.currentTimeMillis());
}
public double tack(String tag){
return tack(tag, true);
}
public double tack(String tag, final boolean newline){
Long start = timers.get(tag);
long end = System.currentTimeMillis();
if (start != null){
double time = (end - start) / 1000.0;
final String s = "Timer " + tag + " " + time;
if(newline){
System.out.println(s);
}else{
System.out.print(s);
}
return time;
}else{
return end / 1000.0;
}
}
}
| mit |
mcxtzhang/TJ-notes | src/com/mcxtzhang/TestMain.java | 545 | package com.mcxtzhang;
public class TestMain {
public static void main(String[] args){
hello();
}
public static void hello() {
String className = Thread.currentThread().getStackTrace()[2].getClassName();
String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
int lineNumber = Thread.currentThread().getStackTrace()[2].getLineNumber();
System.out.println(className);
System.out.println(methodName);
System.out.println(lineNumber);
}
} | mit |
ZagasTales/HistoriasdeZagas | src Graf/es/thesinsprods/zagastales/juegozagas/jugar/master/npc8/RevesesJugadores.java | 5868 | package es.thesinsprods.zagastales.juegozagas.jugar.master.npc8;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.border.BevelBorder;
import es.thesinsprods.resources.font.MorpheusFont;
import es.thesinsprods.zagastales.juegozagas.jugar.master.JugarOnline;
import javax.swing.ImageIcon;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class RevesesJugadores {
private JFrame frmHistoriasDeZagas;
public JFrame getFrame() {
return frmHistoriasDeZagas;
}
public void setFrame(JFrame frame) {
this.frmHistoriasDeZagas = frame;
}
MorpheusFont mf = new MorpheusFont ();
private final JLabel lblNewLabel_2 = new JLabel("");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RevesesJugadores window = new RevesesJugadores();
window.frmHistoriasDeZagas.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public RevesesJugadores() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHistoriasDeZagas = new JFrame();
frmHistoriasDeZagas.setResizable(false);
frmHistoriasDeZagas.setTitle("Historias de Zagas");
frmHistoriasDeZagas.setIconImage(Toolkit.getDefaultToolkit().getImage(RevesesJugadores.class.getResource("/images/Historias de Zagas, logo.png")));
frmHistoriasDeZagas.setBounds(100, 100, 348, 322);
frmHistoriasDeZagas.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frmHistoriasDeZagas.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Reveses");
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(mf.MyFont(0, 36));
lblNewLabel.setBounds(10, 11, 324, 60);
frmHistoriasDeZagas.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("");
if(!JugarOnline.npc8.getSetbacks().getReves().get(0).equals(null)){
if(!JugarOnline.npc8.getSetbacks().getReves().get(0).equals("null")){
lblNewLabel_1.setText(JugarOnline.npc8.getSetbacks().getReves().get(0)+"");
}
}
lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel_1.setForeground(Color.WHITE);
lblNewLabel_1.setFont(mf.MyFont(0,18));
lblNewLabel_1.setBounds(10, 82, 322, 30);
frmHistoriasDeZagas.getContentPane().add(lblNewLabel_1);
JLabel lblDestreza = new JLabel("");
if(!JugarOnline.npc8.getSetbacks().getReves().get(1).equals(null)){
if(!JugarOnline.npc8.getSetbacks().getReves().get(1).equals("null")){
lblDestreza.setText(JugarOnline.npc8.getSetbacks().getReves().get(1)+"");
}
}
lblDestreza.setHorizontalAlignment(SwingConstants.CENTER);
lblDestreza.setForeground(Color.WHITE);
lblDestreza.setFont(mf.MyFont(0,18));
lblDestreza.setBounds(10, 123, 322, 30);
frmHistoriasDeZagas.getContentPane().add(lblDestreza);
JLabel lblResistencia = new JLabel("");
if(!JugarOnline.npc8.getSetbacks().getReves().get(2).equals(null)){
if(!JugarOnline.npc8.getSetbacks().getReves().get(2).equals("null")){
lblResistencia.setText(JugarOnline.npc8.getSetbacks().getReves().get(2)+"");
}
}
lblResistencia.setHorizontalAlignment(SwingConstants.CENTER);
lblResistencia.setForeground(Color.WHITE);
lblResistencia.setFont(mf.MyFont(0,18));
lblResistencia.setBounds(10, 164, 322, 30);
frmHistoriasDeZagas.getContentPane().add(lblResistencia);
JLabel lblResistenciaMgica = new JLabel("");
if(!JugarOnline.npc8.getSetbacks().getReves().get(3).equals(null)){
if(!JugarOnline.npc8.getSetbacks().getReves().get(3).equals("null")){
lblResistenciaMgica.setText(JugarOnline.npc8.getSetbacks().getReves().get(3)+"");
}
}
lblResistenciaMgica.setHorizontalAlignment(SwingConstants.CENTER);
lblResistenciaMgica.setForeground(Color.WHITE);
lblResistenciaMgica.setFont(mf.MyFont(0,18));
lblResistenciaMgica.setBounds(10, 205, 322, 30);
frmHistoriasDeZagas.getContentPane().add(lblResistenciaMgica);
final JButton button = new JButton("");
button.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
button.setIcon(new ImageIcon(RevesesJugadores.class.getResource("/images/boton atras2.png")));
}
@Override
public void mouseReleased(MouseEvent e) {
button.setIcon(new ImageIcon(RevesesJugadores.class.getResource("/images/boton atras.png")));
}
});
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmHistoriasDeZagas.dispose();
}
});
button.setIcon(new ImageIcon(RevesesJugadores.class.getResource("/images/boton atras.png")));
button.setOpaque(false);
button.setForeground(Color.WHITE);
button.setFocusPainted(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setBorder(new BevelBorder(BevelBorder.RAISED, null, null,
null, null));
button.setBackground(new Color(139, 69, 19));
button.setBounds(10, 246, 105, 35);
frmHistoriasDeZagas.getContentPane().add(button);
lblNewLabel_2.setIcon(new ImageIcon(RevesesJugadores.class.getResource("/images/background-jugar.jpg")));
lblNewLabel_2.setBounds(0, 0, 344, 430);
frmHistoriasDeZagas.getContentPane().add(lblNewLabel_2);
}
}
| cc0-1.0 |
mikeb01/scratch | java/risk/src/main/java/org/sample/signalling/UnparkBenchmark.java | 902 | package org.sample.signalling;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
@State(Scope.Benchmark)
public class UnparkBenchmark
{
private volatile long value = 0;
private Thread t;
@Setup
public void setup()
{
t = new Thread(() ->
{
while (!Thread.currentThread().isInterrupted())
{
LockSupport.park();
long l = value;
}
});
t.setDaemon(true);
t.start();
}
@Benchmark
public void run()
{
value++;
LockSupport.unpark(t);
}
}
| cc0-1.0 |
CelsoLJunior/Projetos_LabProg2 | TrabalhoFinal/src/venda/view/MonetizacaoUI.java | 6064 | /*
* 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 venda.view;
import venda.util.Console;
import venda.view.menu.MonetizacaoMenu;
import java.util.InputMismatchException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import venda.dominio.Cliente;
import venda.negocio.ClienteNegocio;
import venda.negocio.NegocioException;
/**
*
* @author 691001155
*/
public class MonetizacaoUI {
private ClienteNegocio clienteNegocio;
public MonetizacaoUI() {
clienteNegocio = new ClienteNegocio();
}
public void menu() {
int opcao = -1;
do {
try {
System.out.println(MonetizacaoMenu.getOpcoes());
opcao = Console.scanInt("Digite sua opcao:");
switch (opcao) {
case MonetizacaoMenu.OP_DEPOSITO:
deposito();
break;
case MonetizacaoMenu.OP_TRANSFERENCIA:
transferencia();
break;
case MonetizacaoMenu.OP_VISUALIZASALDO:
vizualizarSaldo();
break;
case MonetizacaoMenu.OP_VOLTAR:
System.out.println("Retornando a aplicacao..");
break;
default:
System.out.println("Opcao invalida..");
}
} catch (InputMismatchException ex) {
UIUtil.mostrarErro("Somente numeros sao permitidos!");
}
} while (opcao != MonetizacaoMenu.OP_VOLTAR);
}
private void deposito() {
/*
if(clientes.size() < 1){
System.out.println("Sistema nao possui clientes!");
}
else{
testeSair = 0;
while (testeSair == 0) {
System.out.println("Digite o numero da conta do cliente: ");
int teste = e.nextInt();
for (Cliente cliente : clientes) {
if (cliente.getNumero_conta() == teste) {
System.out.println("Valor a ser depositado");
Double valor = e.nextDouble();
if (valor < 5) {
System.out.println("Valor negativo ou muito baixo!");
}
else{
cliente.deposito(valor);
System.out.println("R$ "+valor+" depositado!");
break;
}
*/
List<Cliente> listaClientes = clienteNegocio.listar();
if (listaClientes.isEmpty()) {
System.out.println("Clientes nao encontrados!");
} else {
int codigo = Console.scanInt("Numero da conta: ");
try {
Cliente teste = clienteNegocio.procurarPorCodigo(codigo);
this.mostrarCliente(teste);
double valor_depositar = Console.scanDouble("Valor a ser depositado: ");
if (valor_depositar > 0) {
double deposito = valor_depositar + teste.getSaldo();
teste.setSaldo(deposito);
clienteNegocio.atualizar(teste);
System.out.println("Cliente " + teste.getNome() + " depositou R$"+ valor_depositar +" com sucesso!");
}
else{
System.out.println("Impossível depositar R$"+ valor_depositar +"! Valor inválido ou negativo!");
}
} catch (NegocioException ex) {
UIUtil.mostrarErro(ex.getMessage());
}
}
}
public void transferencia() {
/*
case 2:
if(clientes.size() < 2){
System.out.println("Sistema nao possui clientes suficientes!");
}
else{
System.out.println("Digite o numero da conta do cliente: ");
int teste1 = e.nextInt();
for (Cliente cliente1 : clientes) {
if (cliente1.getNumero_conta() == teste1) {
while(true){
System.out.println("Valor a ser transferido");
Double valor1 = e.nextDouble();
if (valor1 < 0) {
System.out.println("Valor negativo!");
}
else{
cliente.deposito(-valor1);
cliente1.deposito(valor1);
System.out.println("R$ "+valor1+" transferido!");
testeSair=1;
break;
}
}
*/
}
private void vizualizarSaldo() {
//System.out.println("Seu saldo e de R$ "+cliente.getSaldo());
List<Cliente> listaClientes = clienteNegocio.listar();
if (listaClientes.isEmpty()) {
System.out.println("Clientes nao encontrados!");
} else {
int codigo = Console.scanInt("Numero da conta: ");
try {
Cliente teste = clienteNegocio.procurarPorCodigo(codigo);
this.mostrarCliente(teste);
} catch (NegocioException ex) {
UIUtil.mostrarErro(ex.getMessage());
}
}
}
private void mostrarCliente(Cliente p) {
System.out.println("-----------------------------");
System.out.println("Cliente");
System.out.println("CPF: " + p.getCpf());
System.out.println("Nome: " + p.getNome());
System.out.println("Email: " + p.getEmail());
System.out.println("Numero da conta: " + p.getNumconta());
System.out.println("Saldo: R$ " + p.getSaldo());
System.out.println("-----------------------------");
}
}
| cc0-1.0 |
pacohojaverde/fishackathonDroidApp | src/com/example/fishackathon/CustomOnItemSelectedListener.java | 490 | package com.example.fishackathon;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
}
@Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
}
| cc0-1.0 |
KurodaAkira/RPG-Hud | src/main/java/net/spellcraftgaming/rpghud/gui/hud/HudExtendedWidget.java | 1966 | package net.spellcraftgaming.rpghud.gui.hud;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.spellcraftgaming.rpghud.gui.hud.element.HudElement;
import net.spellcraftgaming.rpghud.gui.hud.element.extended.HudElementClockExtended;
import net.spellcraftgaming.rpghud.gui.hud.element.extended.HudElementDetailsExtended;
import net.spellcraftgaming.rpghud.gui.hud.element.extended.HudElementExperienceExtended;
import net.spellcraftgaming.rpghud.gui.hud.element.extended.HudElementFoodExtended;
import net.spellcraftgaming.rpghud.gui.hud.element.extended.HudElementHealthExtended;
import net.spellcraftgaming.rpghud.gui.hud.element.extended.HudElementHealthMountExtended;
import net.spellcraftgaming.rpghud.gui.hud.element.extended.HudElementLevelExtended;
import net.spellcraftgaming.rpghud.gui.hud.element.extended.HudElementWidgetExtended;
@Environment(EnvType.CLIENT)
public class HudExtendedWidget extends HudDefault {
public HudExtendedWidget(MinecraftClient mc, String hudKey, String hudName) {
super(mc, hudKey, hudName);
}
@Override
public HudElement setElementExperience() {
return new HudElementExperienceExtended();
}
@Override
public HudElement setElementHealthMount() {
return new HudElementHealthMountExtended();
}
@Override
public HudElement setElementHotbar() {
return null;
}
@Override
public HudElement setElementFood() {
return new HudElementFoodExtended();
}
@Override
public HudElement setElementHealth() {
return new HudElementHealthExtended();
}
@Override
public HudElement setElementWidget() {
return new HudElementWidgetExtended();
}
@Override
public HudElement setElementClock() {
return new HudElementClockExtended();
}
@Override
public HudElement setElementDetails() {
return new HudElementDetailsExtended();
}
@Override
public HudElement setElementLevel() {
return new HudElementLevelExtended();
}
}
| cc0-1.0 |
jenskastensson/openhab | bundles/io/org.openhab.io.habmin/src/main/java/org/openhab/io/habmin/services/designer/blocks/OpenhabStateOpenClosedBlock.java | 1404 | /**
* Copyright (c) 2010-2013, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.io.habmin.services.designer.blocks;
import org.openhab.io.habmin.services.designer.DesignerBlockBean;
import org.openhab.io.habmin.services.designer.DesignerFieldBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Chris Jackson
* @since 1.5.0
*
*/
public class OpenhabStateOpenClosedBlock extends DesignerRuleCreator {
private static final Logger logger = LoggerFactory.getLogger(OpenhabStateOpenClosedBlock.class);
String processBlock(RuleContext ruleContext, DesignerBlockBean block) {
String blockString = new String();
DesignerFieldBean operatorField = findField(block.fields, "STATE");
if(operatorField == null) {
logger.error("OPENHAB STATE OPENCLOSED contains no field STATE");
return null;
}
Operators op = Operators.valueOf(operatorField.value.toUpperCase());
if(op == null) {
logger.error("OPENHAB STATE OPENCLOSED contains invalid field STATE ({})", operatorField.name.toUpperCase());
return null;
}
blockString = op.toString();
return blockString;
}
enum Operators {
OPEN, CLOSED;
}
}
| epl-1.0 |
ELTE-Soft/xUML-RT-Executor | plugins/hu.eltesoft.modelexecution.m2m.metamodel/src-gen/hu/eltesoft/modelexecution/m2m/metamodel/classdef/ClReceptionSpec.java | 1348 | /**
*/
package hu.eltesoft.modelexecution.m2m.metamodel.classdef;
import hu.eltesoft.modelexecution.m2m.metamodel.base.Named;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Cl Reception Spec</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link hu.eltesoft.modelexecution.m2m.metamodel.classdef.ClReceptionSpec#getParameters <em>Parameters</em>}</li>
* </ul>
*
* @see hu.eltesoft.modelexecution.m2m.metamodel.classdef.ClassdefPackage#getClReceptionSpec()
* @model
* @generated
*/
public interface ClReceptionSpec extends Named {
/**
* Returns the value of the '<em><b>Parameters</b></em>' reference list.
* The list contents are of type {@link hu.eltesoft.modelexecution.m2m.metamodel.classdef.ClReceptionParameter}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Parameters</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Parameters</em>' reference list.
* @see hu.eltesoft.modelexecution.m2m.metamodel.classdef.ClassdefPackage#getClReceptionSpec_Parameters()
* @model
* @generated
*/
EList<ClReceptionParameter> getParameters();
} // ClReceptionSpec
| epl-1.0 |