blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
14c1c49ededa1488b326d0dc3df02e9a22d0f791
01b46f74ad96ad3c7ce4850f48bf9e4ef206dc1f
/app/src/main/java/com/javis/ab/view/AbOnChangeListener.java
2a9b74747e23da9fa7999e0b3423db2c56ca27af
[]
no_license
HHaobin/TulaodaLayoutDemo
e9607519c987ade69bf04a489c69e8b17203b74a
3c84941af588deacb8abe8711f25261147b8fa13
refs/heads/master
2020-05-21T11:29:56.007826
2019-01-19T08:39:01
2019-01-19T08:39:01
46,936,634
3
0
null
null
null
null
UTF-8
Java
false
false
607
java
package com.javis.ab.view; /** * The listener interface for receiving abOnChange events. * The class that is interested in processing a abOnChange * event implements this interface, and the object created * with that class is registered with a component using the * component's <code>addAbOnChangeListener<code> method. When * the abOnChange event occurs, that object's appropriate * method is invoked. * * @see AbOnChangeEvent */ public interface AbOnChangeListener { /** * On change. * * @param position the position */ public void onChange(int position); }
[ "zhxfl@fuan.lan" ]
zhxfl@fuan.lan
74520c403434ebd32811b206adad5022da15aea9
2a3f19a4a2b91d9d715378aadb0b1557997ffafe
/sources/com/google/android/gms/location/internal/zzm.java
9c2ffbeffaf3d692f8b1108a254ed3d44fc58673
[]
no_license
amelieko/McDonalds-java
ce5062f863f7f1cbe2677938a67db940c379d0a9
2fe00d672caaa7b97c4ff3acdb0e1678669b0300
refs/heads/master
2022-01-09T22:10:40.360630
2019-04-21T14:47:20
2019-04-21T14:47:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,557
java
package com.google.android.gms.location.internal; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.internal.safeparcel.zza; import com.google.android.gms.common.internal.safeparcel.zzb; import com.google.android.gms.location.LocationRequest; import java.util.List; public class zzm implements Creator<LocationRequestInternal> { static void zza(LocationRequestInternal locationRequestInternal, Parcel parcel, int i) { int zzar = zzb.zzar(parcel); zzb.zza(parcel, 1, locationRequestInternal.zzaIc, i, false); zzb.zza(parcel, 4, locationRequestInternal.zzaUF); zzb.zzc(parcel, 5, locationRequestInternal.zzaWf, false); zzb.zza(parcel, 6, locationRequestInternal.mTag, false); zzb.zza(parcel, 7, locationRequestInternal.zzaWg); zzb.zzc(parcel, 1000, locationRequestInternal.getVersionCode()); zzb.zzJ(parcel, zzar); } /* renamed from: zzfc */ public LocationRequestInternal createFromParcel(Parcel parcel) { String str = null; boolean z = false; int zzaq = zza.zzaq(parcel); boolean z2 = true; List list = LocationRequestInternal.zzaWe; LocationRequest locationRequest = null; int i = 0; while (parcel.dataPosition() < zzaq) { int zzap = zza.zzap(parcel); switch (zza.zzcj(zzap)) { case 1: locationRequest = (LocationRequest) zza.zza(parcel, zzap, LocationRequest.CREATOR); break; case 4: z2 = zza.zzc(parcel, zzap); break; case 5: list = zza.zzc(parcel, zzap, ClientIdentity.CREATOR); break; case 6: str = zza.zzq(parcel, zzap); break; case 7: z = zza.zzc(parcel, zzap); break; case 1000: i = zza.zzg(parcel, zzap); break; default: zza.zzb(parcel, zzap); break; } } if (parcel.dataPosition() == zzaq) { return new LocationRequestInternal(i, locationRequest, z2, list, str, z); } throw new zza.zza("Overread allowed size end=" + zzaq, parcel); } /* renamed from: zzig */ public LocationRequestInternal[] newArray(int i) { return new LocationRequestInternal[i]; } }
[ "makfc1234@gmail.com" ]
makfc1234@gmail.com
7239d8de1e3d49c07b9ca6b5d713393460633211
13b54fc8118c5bdb3afafc6d3d67d9713c08dd95
/21-10-06/람다식(Lambda Expressions)과 스트림(Stream)/람다식예제/StreamEx01_2.java
9c9cbdfa568a2b5bd0603e685afebeffaf99714c
[]
no_license
suyeonChoi7807/ojt
c2079af6d260882bf1ab4f8377089f89d8cd3309
11c9f3166f234c80fad426ec2735ee1002f1a5f6
refs/heads/main
2023-08-17T21:37:35.955047
2021-10-28T00:21:55
2021-10-28T00:21:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
597
java
import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class StreamEx01_2 { public static void main(String[] args) { /* * 자바 8에 람다식과 스트림(내부 반복자)를 적용하여 코딩 * [결론] Stream 내부 반복자는 컬렉션 내부에서 요소들을 반복 * 개발자는 요소당 처리해야 할 코드만 제공하는 코드 패턴을 말한다. */ List<Integer> list= (List)Arrays.asList(10,20,30,40,50); Stream<Integer> stream= list.stream(); stream.forEach(value->{ System.out.print(value+" "); }); } }
[ "noreply@github.com" ]
suyeonChoi7807.noreply@github.com
6c67c4e1234b85c641d7b552a6a40107310e3731
14fa9f6356f8b5824eab6e596238631afa5cd9d6
/src/main/java/com/fliker/Repository/FileContent.java
834e1a78e884b0a73fc7ac5ea116be1bf9950876
[]
no_license
Somashis/FlikerGit
73931802e5c361d5103fdb36b70b2513b0d9ac4d
7a000d3c5b515cc5e44eeae20474545e0f0cce5e
refs/heads/master
2020-04-02T23:32:55.018729
2017-10-02T22:08:16
2017-10-02T22:08:16
61,175,618
1
1
null
2016-06-17T06:57:14
2016-06-15T03:45:40
HTML
UTF-8
Java
false
false
871
java
package com.fliker.Repository; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="FileContent") public class FileContent { @Id private String filecontentid; private String fileid; private String fileContent; private String fileurl; public String getFilecontentid() { return filecontentid; } public void setFilecontentid(String filecontentid) { this.filecontentid = filecontentid; } public String getFileid() { return fileid; } public void setFileid(String fileid) { this.fileid = fileid; } public String getFileContent() { return fileContent; } public void setFileContent(String fileContent) { this.fileContent = fileContent; } public String getFileurl() { return fileurl; } public void setFileurl(String fileurl) { this.fileurl = fileurl; } }
[ "somashis.nath@gmail.com" ]
somashis.nath@gmail.com
77e6b291a5dcaf6058d0e63d47cfd49974f6a574
a601597c0ccc49846cc557dca406e74a1dbe73a0
/api/src/main/java/com/iotpack/api/entity/device/DeviceEntity.java
c16a173d5fe7db64d17a1af4d5f10e1b8efe4c88
[]
no_license
anviod/iotpack
00184a6b40a1cf6653b4ede3fd46111e9d618598
6fbb8ef63cd0cfe106cce8e968ee8cfe96b29c1f
refs/heads/master
2022-11-30T18:18:05.614443
2020-08-20T01:41:20
2020-08-20T01:41:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,411
java
package com.iotpack.api.entity.device; import com.iotpack.api.entity.converter.HashMapConverter; import lombok.Data; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.Where; import org.springframework.data.redis.core.RedisHash; import javax.persistence.*; import java.util.HashMap; /** * 设备表 */ @Data @SQLDelete(sql = "update `device` SET deleted_at = unix_timestamp(now()) WHERE id = ?") @Entity @Table(name = "device") @Where(clause = "deleted_at is null") @DynamicUpdate @Cacheable public class DeviceEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; String name; /** * 设备位置 */ String location; /** * 经度 */ Double lon=113.62; /** * 纬度 */ Double lat=34.75; /** * 高度 */ Double ele=0.0; /** * 设备id */ String deviceId; /** * 设备类型 */ Long deviceType; /** * 设备清单id */ Integer deviceCheckListId; /** * 产品id */ Long productId; /** * 产品id */ Long gatewayId; /** * 设备缩水组织 */ Long organizationId; /** * 上级设备 */ Long superiorDeviceId; @Convert(converter = HashMapConverter.class) HashMap<String,Object> meta; }
[ "945627077@qq.com" ]
945627077@qq.com
b15619c030ddc2de15e80a1ad037a40122ae4550
671c3d2c9da0451908703b23c7691d8de3528106
/WP3/os-robust-behaviour-analysis-service-ws/src/main/java/eu/project/robust/behaviour/analysis/prediction/HealthClassifierResult.java
081604ee0de623b642e8658e1ce263ab1b85f26a
[ "Apache-2.0" ]
permissive
robust-project/platform
0ee4d163a57f4cae8ef8b760aa04dcac5e2e6254
020d98b4277e897892d5c02fb0a1cce7125e6c76
refs/heads/master
2021-01-01T05:50:09.636856
2013-12-10T14:01:50
2013-12-10T14:01:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,250
java
/** *Copyright 2013 Knowledge Media Institute * *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package eu.project.robust.behaviour.analysis.prediction; import java.util.Date; public class HealthClassifierResult { private boolean healthIndicatorIncrease; private int healthIndicator; private String communityID; private Date date; public HealthClassifierResult(boolean healthChange, int healthIndicator, String communityID, Date date) { this.healthIndicatorIncrease = healthChange; this.healthIndicator = healthIndicator; this.communityID = communityID; this.date = date; } public HealthClassifierResult() { } public boolean isHealthIndicatorIncrease() { return healthIndicatorIncrease; } public void setHealthIndicatorIncrease(boolean healthIndicatorIncrease) { this.healthIndicatorIncrease = healthIndicatorIncrease; } public int getHealthIndicator() { return healthIndicator; } public void setHealthIndicator(int healthIndicator) { this.healthIndicator = healthIndicator; } public String getCommunityID() { return communityID; } public void setCommunityID(String communityID) { this.communityID = communityID; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public String toString() { return "HealthClassifierResult{" + "healthIndicatorIncrease=" + healthIndicatorIncrease + ", healthIndicator=" + healthIndicator + ", communityID='" + communityID + '\'' + ", date=" + date + '}'; } }
[ "rajn@softwaremind.pl" ]
rajn@softwaremind.pl
3aa92987ae7716e71f0cb9cd9f78f5749cc23dd7
812194c4e888d3a191134d97923d21624bb80e78
/AStar/src/org/ploxie/pathfinding/AStar.java
a52434990c088094bbfaf5629e22aa7c3087e879
[]
no_license
Ploxie/AStar-Test
d92f30e20ea874dcb6925ab59234f080516a4418
6d08a8ca488c27b2db5e0e1c34801e46b360501c
refs/heads/master
2021-03-30T03:06:02.191960
2020-03-27T13:30:56
2020-03-27T13:30:56
248,009,903
0
0
null
null
null
null
UTF-8
Java
false
false
8,193
java
package org.ploxie.pathfinding; import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Set; public class AStar { private static int DEFAULT_HV_COST = 10; private static int DEFAULT_DIAGONAL_COST = 14; private int hvCost; private int diagonalCost; private Node[][] searchArea; private PriorityQueue<Node> openList; private Set<Node> closedSet; private Node initialNode; private Node finalNode; private List<Node> blockedNodes = new ArrayList<Node>(); public AStar(int rows, int cols, Node initialNode, Node finalNode, int hvCost, int diagonalCost) { this.hvCost = hvCost; this.diagonalCost = diagonalCost; setInitialNode(initialNode); setFinalNode(finalNode); this.searchArea = new Node[rows][cols]; this.openList = new PriorityQueue<Node>(new Comparator<Node>() { @Override public int compare(Node node0, Node node1) { return Integer.compare(node0.getF(), node1.getF()); } }); setNodes(); this.closedSet = new HashSet<>(); } public AStar(int rows, int cols, Node initialNode, Node finalNode) { this(rows, cols, initialNode, finalNode, DEFAULT_HV_COST, DEFAULT_DIAGONAL_COST); } public AStar(int rows, int cols) { this.hvCost = DEFAULT_HV_COST; this.diagonalCost = DEFAULT_DIAGONAL_COST; this.searchArea = new Node[rows][cols]; this.openList = new PriorityQueue<Node>(new Comparator<Node>() { @Override public int compare(Node node0, Node node1) { return Integer.compare(node0.getF(), node1.getF()); } }); this.closedSet = new HashSet<>(); for (int i = 0; i < searchArea.length; i++) { for (int j = 0; j < searchArea[0].length; j++) { Node node = new Node(i, j); this.searchArea[i][j] = node; } } } private void setNodes() { for (int i = 0; i < searchArea.length; i++) { for (int j = 0; j < searchArea[0].length; j++) { Node node = new Node(i, j); node.calculateHeuristic(getFinalNode()); this.searchArea[i][j] = node; } } } public void addBlock(int column, int row) { setBlock(row, column); } public void setBlocks(int[][] blocksArray) { for (int i = 0; i < blocksArray.length; i++) { int row = blocksArray[i][0]; int col = blocksArray[i][1]; setBlock(row, col); } } public List<Node> findPath() { openList.clear(); closedSet.clear(); setNodes(); openList.add(initialNode); while (!isEmpty(openList)) { Node currentNode = openList.poll(); closedSet.add(currentNode); if(blockedNodes.contains(currentNode)) { continue; } if (isFinalNode(currentNode)) { return getPath(currentNode); } else { addAdjacentNodes(currentNode); } } return new ArrayList<Node>(); } private List<Node> getPath(Node currentNode) { List<Node> path = new ArrayList<Node>(); path.add(currentNode); Node parent; while ((parent = currentNode.getParent()) != null) { path.add(0, parent); currentNode = parent; } return path; } private void addAdjacentNodes(Node currentNode) { addAdjacentUpperRow(currentNode); addAdjacentMiddleRow(currentNode); addAdjacentLowerRow(currentNode); } private void addAdjacentLowerRow(Node currentNode) { int row = currentNode.getRow(); int col = currentNode.getColumn(); int lowerRow = row + 1; if (lowerRow < getSearchArea().length) { if (col - 1 >= 0) { checkNode(currentNode, col - 1, lowerRow, getDiagonalCost()); // Comment this line if diagonal movements are not allowed } if (col + 1 < getSearchArea()[0].length) { checkNode(currentNode, col + 1, lowerRow, getDiagonalCost()); // Comment this line if diagonal movements are not allowed } checkNode(currentNode, col, lowerRow, getHvCost()); } } private void addAdjacentMiddleRow(Node currentNode) { int row = currentNode.getRow(); int col = currentNode.getColumn(); int middleRow = row; if (col - 1 >= 0) { checkNode(currentNode, col - 1, middleRow, getHvCost()); } if (col + 1 < getSearchArea()[0].length) { checkNode(currentNode, col + 1, middleRow, getHvCost()); } } private void addAdjacentUpperRow(Node currentNode) { int row = currentNode.getRow(); int col = currentNode.getColumn(); int upperRow = row - 1; if (upperRow >= 0) { if (col - 1 >= 0) { checkNode(currentNode, col - 1, upperRow, getDiagonalCost()); // Comment this if diagonal movements are not allowed } if (col + 1 < getSearchArea()[0].length) { checkNode(currentNode, col + 1, upperRow, getDiagonalCost()); // Comment this if diagonal movements are not allowed } checkNode(currentNode, col, upperRow, getHvCost()); } } private void checkNode(Node currentNode, int col, int row, int cost) { Node adjacentNode = getSearchArea()[row][col]; if (!adjacentNode.isBlocked() && !getClosedSet().contains(adjacentNode)) { if (!getOpenList().contains(adjacentNode)) { adjacentNode.setNodeData(currentNode, cost); getOpenList().add(adjacentNode); } else { boolean changed = adjacentNode.checkBetterPath(currentNode, cost); if (changed) { // Remove and Add the changed node, so that the PriorityQueue can sort again its // contents with the modified "finalCost" value of the modified node getOpenList().remove(adjacentNode); getOpenList().add(adjacentNode); } } } } private boolean isFinalNode(Node currentNode) { return currentNode.equals(finalNode); } private boolean isEmpty(PriorityQueue<Node> openList) { return openList.size() == 0; } private void setBlock(int row, int col) { this.searchArea[row][col].setBlocked(true); this.closedSet.add(this.searchArea[row][col]); this.blockedNodes.add(this.searchArea[row][col]); } public Node getInitialNode() { return initialNode; } public void setInitialNode(Node initialNode) { this.initialNode = initialNode; } public Node getFinalNode() { return finalNode; } public void setFinalNode(Node finalNode) { this.finalNode = finalNode; } public Node[][] getSearchArea() { return searchArea; } public void setSearchArea(Node[][] searchArea) { this.searchArea = searchArea; } public PriorityQueue<Node> getOpenList() { return openList; } public void setOpenList(PriorityQueue<Node> openList) { this.openList = openList; } public Set<Node> getClosedSet() { return closedSet; } public List<Node> getBlockedNodes(){ return blockedNodes; } public void setClosedSet(Set<Node> closedSet) { this.closedSet = closedSet; } public int getHvCost() { return hvCost; } public void setHvCost(int hvCost) { this.hvCost = hvCost; } private int getDiagonalCost() { return diagonalCost; } private void setDiagonalCost(int diagonalCost) { this.diagonalCost = diagonalCost; } }
[ "joakim.ekbladh@gmail.com" ]
joakim.ekbladh@gmail.com
ac43ab76b5bb72fbcc6e6f9dfcdcde133f281343
e8fbca7a6851b82c9ae3f805234c840e11f7c261
/modules/thirdparty/batik/sources/org/apache/flex/forks/batik/gvt/event/GraphicsNodeFocusEvent.java
33e886d752b60e1129a7fdcfdebb89ed09501f07
[ "Apache-2.0", "W3C", "LicenseRef-scancode-proprietary-license", "MPL-1.1", "MPL-1.0", "BSD-3-Clause" ]
permissive
teramura/flex-sdk
6772f7c729bb5fde5a080f5bed4df53280043024
c281c4f248f9adc8f10910be5e070149477d9216
refs/heads/develop
2023-05-13T21:26:18.785749
2023-04-28T15:10:59
2023-04-28T15:10:59
91,769,399
0
0
Apache-2.0
2018-06-27T10:44:03
2017-05-19T05:38:06
ActionScript
UTF-8
Java
false
false
2,012
java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.flex.forks.batik.gvt.event; import org.apache.flex.forks.batik.gvt.GraphicsNode; /** * A low-level event which indicates that a graphics node has gained or * lost the keyboard focus. * * @author <a href="mailto:Thierry.Kormann@sophia.inria.fr">Thierry Kormann</a> * @version $Id: GraphicsNodeFocusEvent.java 475477 2006-11-15 22:44:28Z cam $ */ public class GraphicsNodeFocusEvent extends GraphicsNodeEvent { /** * The first number in the range of ids used for focus events. */ static final int FOCUS_FIRST = 1004; /** * The id for the "focusGained" event. This event indicates that * the component gained the keyboard focus. */ public static final int FOCUS_GAINED = FOCUS_FIRST; /** * The id for the "focusLoses" event. This event indicates that * the component lost the keyboard focus. */ public static final int FOCUS_LOST = FOCUS_FIRST + 1; /** * Constructs a new graphics node focus event. * @param source the graphics node where the event originated * @param id the id of this event */ public GraphicsNodeFocusEvent(GraphicsNode source, int id) { super(source, id); } }
[ "cframpton@apache.org" ]
cframpton@apache.org
9781e73b462676c4f8cc7bfdab2bfd8ae4fdba9e
c9e51564babf7de532fb65886b7ac435a4c03446
/src/main/java/com/gestankbratwurst/ferocore/util/tasks/TaskManager.java
578d4544b5f710b56bbf736ebb2e887e34c622d4
[]
no_license
Projekt-Sidusgames/FeroCore
0a1ab30440f55b11019a955bbfd85d9372f4aa26
ed291a741cf04dd6a9f30e39f2f810057230aee8
refs/heads/master
2023-03-10T01:06:59.819138
2021-02-27T09:27:37
2021-02-27T09:27:37
340,214,490
0
0
null
null
null
null
UTF-8
Java
false
false
5,530
java
package com.gestankbratwurst.ferocore.util.tasks; import com.gestankbratwurst.ferocore.FeroCore; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.Consumer; import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; public class TaskManager { private static final TaskManager instance = TaskManager.getInstance(); public static TaskManager getInstance() { return TaskManager.instance == null ? new TaskManager(JavaPlugin.getPlugin(FeroCore.class)) : TaskManager.instance; } @Getter private final ScheduledExecutorService scheduler; private final BukkitScheduler bukkitScheduler; private final JavaPlugin plugin; public TaskManager(final FeroCore plugin) { final int threadPoolSize = plugin.getFeroIO().getConfig().getSchedulerThreadPoolSize(); this.bukkitScheduler = Bukkit.getScheduler(); this.scheduler = Executors.newScheduledThreadPool(threadPoolSize); this.plugin = plugin; } public <U> Consumer<U> consumeBukkitSync(final Consumer<U> asyncAction) { return (u) -> this.bukkitScheduler.runTask(this.plugin, () -> asyncAction.accept(u)); } public <U, V> BiConsumer<U, V> biConsumeBukkitSync(final BiConsumer<U, V> asyncAction) { return (u, v) -> this.bukkitScheduler.runTask(this.plugin, () -> asyncAction.accept(u, v)); } /** * Repeatedly executes a Runnable at a fixed rate. - Thread Async * * @param runnable the Runnable that is going to be executed. * @param delay the delay before the first execution. * @param repeat the delay between each repeated execution. * @param timeUnit the time units. * @return a ScheduledFuture */ public ScheduledFuture<?> executeScheduledTask(final Runnable runnable, final long delay, final long repeat, final TimeUnit timeUnit) { return this.scheduler.scheduleAtFixedRate(runnable, delay, repeat, timeUnit); } // Replaces everything but 0-9 private String extractNumber(final String input) { return input.replaceAll("[^0-9]", ""); } // Strips color codes private String stripColor(final String input) { return ChatColor.stripColor(input); } /** * Executes a Runnable Task Async once. - Thread Async * * @param runnable the runnable to execute. */ public void executeTask(final Runnable runnable) { this.scheduler.execute(runnable); } /** * Executes a Runnable. - Bukkit Sync * * @param runnable the runnable to execute. * @return */ public BukkitTask runBukkitSync(final Runnable runnable) { return this.bukkitScheduler.runTask(this.plugin, runnable); } public int runBukkitSyncDelayed(final Runnable runnable, final long delyTicks) { return this.bukkitScheduler.scheduleSyncDelayedTask(this.plugin, runnable, delyTicks); } /** * Executes a Runnable. - Bukkit Async * * @param runnable the runnable to execute. * @return */ public BukkitTask runBukkitAsync(final Runnable runnable) { return this.bukkitScheduler.runTaskAsynchronously(this.plugin, runnable); } /** * Repeatedly executes a Runnable. - Bukkit Sync - Delays in Ticks * * @param runnable the runnable to execute. * @param delayTicks the delay before the first execution. * @param repeatTicks the dealy between each repeated execution. * @return a BukkitTask */ public BukkitTask runRepeatedBukkit(final Runnable runnable, final long delayTicks, final long repeatTicks) { return this.bukkitScheduler.runTaskTimer(this.plugin, runnable, delayTicks, repeatTicks); } /** * Repeatedly executes a Runnable. - Bukkit Async - Delays in Ticks * * @param runnable the runnable to execute. * @param delayTicks the delay before the first execution. * @param repeatTicks the dealy between each repeated execution. * @return a BukkitTask */ public BukkitTask runRepeatedBukkitAsync(final Runnable runnable, final long delayTicks, final long repeatTicks) { return this.bukkitScheduler .runTaskTimerAsynchronously(this.plugin, runnable, delayTicks, repeatTicks); } /** * Repeats a Runnable a fixed amount of times. - BukkitSync - Delays in Ticks * * @param runnable the runnable to execute. * @param delayTicks the delay before the first execution. * @param repeatDelay the delay between each further execution. * @param repeatAmount the amount of repeats. */ public void runFixedTimesBukkitSync(final Runnable runnable, final long delayTicks, final long repeatDelay, final int repeatAmount) { TickedRunnable.start(runnable, delayTicks, repeatDelay, repeatAmount, this.plugin, true); } /** * Repeats a Runnable a fixed amount of times. - BukkitSync - Delays in Ticks * * @param runnable the runnable to execute. * @param delayTicks the delay before the first execution. * @param repeatDelay the delay between each further execution. * @param repeatAmount the amount of repeats. */ public void runFixedTimesBukkitAsync(final Runnable runnable, final long delayTicks, final long repeatDelay, final int repeatAmount) { TickedRunnable.start(runnable, delayTicks, repeatDelay, repeatAmount, this.plugin, false); } }
[ "unconfigured@null.spigotmc.org" ]
unconfigured@null.spigotmc.org
6d99c702d53073cb02be6978bf2676ad2dd7b2af
4edd008ed8cb2b578cd3e81997dd964a353d5665
/src/main/java/org/example/SuperMarioBros/Model/MushroomGrowth.java
8a87f43a617b38196bca14bc890411b2cef60447
[]
no_license
neginhsobhani/Super-Mario
2669b66260dd2c0365d9a128dc903378f7bb13b9
e9e4bcc43b1fe95292e7e665f156354a3be9b8b7
refs/heads/main
2023-06-03T10:40:53.199741
2021-06-16T15:29:57
2021-06-16T15:29:57
377,543,121
6
0
null
null
null
null
UTF-8
Java
false
false
2,025
java
package org.example.SuperMarioBros.Model; import java.awt.*; /** * MushroomGrowth class represents a power up which helps mario * increase in size and also gives him more abilities. * It holds the class details relevant in our context. */ public class MushroomGrowth extends FixedGameObject { private int yAxisAnimation; private boolean isRight; private final int speed; private Wall bumpingWall; public MushroomGrowth(int startX, int startY) { super(startX, startY, "objects.png", new Rectangle(0, 0, 16, 16)); yAxisAnimation = 0; isRight = true; //moves faster than mario speed = 3; setGravityMagnitude(0.8f); } @Override public void update() { if (yAxisAnimation < getHeight()) { yAxisAnimation += 1; move(0, -1); } else { enableGravity(); if (isRight) move(speed, 0); else move(-speed, 0); } super.update(); } @Override public void onCollision(GameObject other) { super.onCollision(other); if (other.equals(bumpingWall)) { while (collide(other)) move(0, -1); return; } //the method is actually only called when other is instance of Wall if (other instanceof Wall) { //on side collisions (no need to check isUnder as the mushroom doesn't jump) if (!isAbove(other) && !other.equals(bumpingWall)) isRight = !isRight; } } /** * on collision to a bumping wall, this is called */ public void jumpFlip(Wall other) { if (bumpingWall != null) return; bumpingWall = other; isRight = !isRight; jump(5); } // called by wall public void clearBumpingWall() { bumpingWall = null; } }
[ "neginhsobhani@gmail.com" ]
neginhsobhani@gmail.com
4ade6a870c7851cb1b7b6b535c5e434d6a4fd69f
4df0b90673c434042fac6f1dae460c5391ada2fe
/app/src/main/java/inesc_id/gsd/bibtrek/app/dblp/parsing/AuthorJSONParser.java
0970315f235a8a6d9719f9ca4335ed712ed6d2c9
[]
no_license
inesc-id/BibTrek
e210502799de4a5a59aaa630834426e8bcca0374
2d4e597fd1a0b432d10b2ef32e4c585e013e4392
refs/heads/master
2023-04-27T04:52:14.049360
2020-06-13T10:52:06
2020-06-13T10:52:06
194,652,175
1
1
null
null
null
null
UTF-8
Java
false
false
676
java
package inesc_id.gsd.bibtrek.app.dblp.parsing; import org.json.JSONObject; public class AuthorJSONParser extends JSONParser { private static final String AUTHOR = "author"; private static final String URL = "url"; public AuthorJSONParser() { } @Override Object[] displayInfo(JSONObject info, int counter) { Object[] tuple; String author, url; author = (String) info.get(AUTHOR); url = (String) info.get(URL); System.out.println("(" + (counter+1) + ")"); System.out.print("- Author: "); System.out.println(author); System.out.print("- URL: "); System.out.println(url); tuple = new Object[]{author, url}; return tuple; } }
[ "jose.bras@tecnico.ulisboa.pt" ]
jose.bras@tecnico.ulisboa.pt
8442c3c61d6b310b7a45bc4296944739f50bc206
803f56f92c66456be55fbb53512e9881ab7259f0
/src/main/java/com/guonl/factory/test01/ReflecTionUtil.java
4bcb1daf2823a62ef0178f0756c6de0f01c55c02
[ "Apache-2.0" ]
permissive
guonl/springboot-dbmanager
97d2eabbe80dfb2ae25712064079fdfc61e9fdfc
d04ffa76d9c9a91db63e65c28b4660dee88dec35
refs/heads/master
2020-04-06T16:57:07.694403
2019-05-13T02:38:08
2019-05-13T02:38:08
157,640,657
0
0
null
null
null
null
UTF-8
Java
false
false
5,363
java
package com.guonl.factory.test01; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.SortedMap; import javax.servlet.jsp.jstl.sql.Result; /** * Created by guonl * Date 2018/11/27 4:06 PM * Description: */ public class ReflecTionUtil { /** * 反射工具类 * 封装数据结果到集合 * 传入result 实体和 实体类具体url */ private String[] classMethods = new String[20];// set方法数组 private Class[] classParams = new Class[20];// set方法参数类型 private int classMethodsNum = 0;// 实体类属性个数 private Class cs = null;// 会话管理器 private List list = null;// 实体类属性字段名的集合 public void getStandardManager(String url) throws ClassNotFoundException { cs = Class.forName(url); } public void getProtect(String url) throws ClassNotFoundException { // 实体类变量字段 list = new ArrayList(); this.getStandardManager(url); Field[] fields = cs.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { list.add(fields[i].getName()); } } public void getConsructor(String url) throws ClassNotFoundException { // set方法和参数类型 this.getStandardManager(url); Method[] methods = cs.getMethods(); int count = 0; for (Method m : methods) { if (m.getName().substring(0, 3).equals("set")) { Class[] parms = m.getParameterTypes(); classMethods[count] = m.getName(); classParams[count] = parms[0];// count++; } } classMethodsNum = count; } public Object getObject(String url) throws SecurityException, NoSuchMethodException, ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { /** * 创建类对象 */ this.getStandardManager(url); Constructor constructor = cs.getConstructor(); Object object = constructor.newInstance(); return object; } public Result checkResult(Result rs) { /** * 验证数据库中的数据 */ for (int i = 0; i < rs.getRowCount(); i++) { SortedMap map = rs.getRows()[i]; for (int j = 0; j < list.size(); j++) { Object value = map.get(list.get(j));//testtest if(value==null){ System.out.println("数据验证失败,检查实体类与数据表规范!"); try { throw new Exception("数据验证失败,检查实体类与数据表规范!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ map.put(list.get(j), value); } } } return rs; } public List getValue(String url, Result rs) { /** * list列表 value */ List resultlist = new ArrayList(); try { this.getConsructor(url); this.getProtect(url); rs = checkResult(rs); for (int i = 0; i < rs.getRowCount(); i++) { Object object = this.getObject(url); for (int j = 0; j < classMethodsNum; j++) { Method method = cs.getMethod(classMethods[j], classParams[j]); //System.out.println("当前调用set方法:"+method); //System.out.println("表字段名:"+classMethods[j] // .substring(3).toLowerCase());//表字段名 String tstr = classMethods[j] .substring(3).toLowerCase(); ///System.out.println("表字段值:"+rs.getRows()[i].get(tstr)); //表字段值 method.invoke(object, rs.getRows()[i].get(tstr));//动态设值 //System.out.println((Nr_users)object); } resultlist.add(object); } } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return resultlist; } }
[ "983220871@qq.com" ]
983220871@qq.com
db5411e526921713235aa4544dacc442454dbacb
39bef83f3a903f49344b907870feb10a3302e6e4
/Android Studio Projects/bf.io.openshop/src/com/google/gson/internal/bind/TimeTypeAdapter.java
45712ce67fe2f137dc8d4ee474e8d6faf0f5f544
[]
no_license
Killaker/Android
456acf38bc79030aff7610f5b7f5c1334a49f334
52a1a709a80778ec11b42dfe9dc1a4e755593812
refs/heads/master
2021-08-19T06:20:26.551947
2017-11-24T22:27:19
2017-11-24T22:27:19
111,960,738
0
0
null
null
null
null
UTF-8
Java
false
false
2,049
java
package com.google.gson.internal.bind; import java.sql.*; import com.google.gson.reflect.*; import java.io.*; import com.google.gson.*; import java.text.*; import com.google.gson.stream.*; import java.util.*; public final class TimeTypeAdapter extends TypeAdapter<Time> { public static final TypeAdapterFactory FACTORY; private final DateFormat format; static { FACTORY = new TypeAdapterFactory() { @Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) { if (typeToken.getRawType() == Time.class) { return (TypeAdapter<T>)new TimeTypeAdapter(); } return null; } }; } public TimeTypeAdapter() { this.format = new SimpleDateFormat("hh:mm:ss a"); } @Override public Time read(final JsonReader jsonReader) throws IOException { synchronized (this) { Time time; if (jsonReader.peek() == JsonToken.NULL) { jsonReader.nextNull(); time = null; } else { try { time = new Time(this.format.parse(jsonReader.nextString()).getTime()); } catch (ParseException ex) { throw new JsonSyntaxException(ex); } } return time; } } @Override public void write(final JsonWriter jsonWriter, final Time time) throws IOException { // monitorenter(this) Label_0019: { if (time != null) { break Label_0019; } String format = null; try { while (true) { jsonWriter.value(format); return; format = this.format.format(time); continue; } } finally { } // monitorexit(this) } } }
[ "ema1986ct@gmail.com" ]
ema1986ct@gmail.com
84ef0d172cc401d736f2a6b63f319675cda44d63
82ef671f636898bc39192f26f156e0a18930d6ed
/AndroidCEFX_Common/src/de/hdm/cefx/concurrency/operations/OperationIDComparator.java
d989468828e100ebc6589d0aaa42d09d927d14ff
[]
no_license
ubuntudroid/WatchMyPhone
5bfe105a1d6bd9e0956b86e0bb4d1b6f226a410d
ce95d016615291f4983ce73ec718805ee1e4583f
refs/heads/master
2018-12-29T21:02:20.276298
2013-09-11T11:48:05
2013-09-11T11:48:05
1,772,089
1
1
null
null
null
null
UTF-8
Java
false
false
2,390
java
/******************************************************************************* * Copyright (C) 2010 Ansgar Gerlicher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Stuttgart, Hochschule der Medien: http://www.mi.hdm-stuttgart.de/mmb/ * Collaborative Editing Framework or XML: * http://sourceforge.net/projects/cefx/ * * Dresden, University of Technology, Faculty of Computer Science * Computer Networks Group: http://www.rn.inf.tu-dresden.de * mobilis project: http://mobilisplatform.sourceforge.net ******************************************************************************/ /** * This sourcecode is part of the Collaborative Editing Framework for XML (CEFX). * @author Michael Voigt */ package de.hdm.cefx.concurrency.operations; import java.util.Comparator; public class OperationIDComparator implements Comparator { public int compare(Object arg0, Object arg1) { OperationID o1=((Operation)arg0).getOperationID(); OperationID o2=((Operation)arg1).getOperationID(); StateVector s1=((Operation)arg0).getStateVector(); StateVector s2=((Operation)arg1).getStateVector(); boolean b1=UpdateOperationsProcessor.isTransformationNeeded(s1, s2); boolean b2=UpdateOperationsProcessor.isTransformationNeeded(s2, s1); if ((b1==true) && (b2==false)) { return 1; } if ((b1==false) && (b2==true)) { return -1; } int tmp; tmp=o1.getOperationPriority()-o2.getOperationPriority(); if (tmp!=0) { return tmp; } if (o1.getOp().getType()==Operation.UPDATE) { tmp=o1.getUpdateOperationPriority()-o2.getUpdateOperationPriority(); if (tmp!=0) { return tmp; } } else if (o1.getOp().getType()==Operation.DELETE) { tmp=o2.getDOMLevel()-o1.getDOMLevel(); if (tmp!=0) { return tmp; } } tmp=o1.getSVSum()-o2.getSVSum(); if (tmp!=0) { return tmp; } return o1.getClientID()-o2.getClientID(); } }
[ "ubuntudroid@googlemail.com" ]
ubuntudroid@googlemail.com
610c02b245f7669af0988c559be3b0aa23d3bc12
293af93207a07cea4c437478322f032d04ef5f5d
/app/src/main/java/com/eshop/mvp/ui/activity/set/HelpDetailActivity.java
1fac8b25149bf0c664b32eede297f3eef372c393
[]
no_license
thinking123/yiqi-android-pro
1918f861678ea64a90fab63d0532a7df85c0af09
7c67c1fe1c28699565abd75ef0918810d8587c65
refs/heads/master
2020-06-24T11:47:17.849026
2019-04-24T02:25:19
2019-04-24T02:25:19
198,954,139
1
0
null
null
null
null
UTF-8
Java
false
false
2,556
java
package com.eshop.mvp.ui.activity.set; import android.content.Intent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.eshop.R; import com.eshop.app.base.BaseApp; import com.eshop.app.base.BaseSupportActivity; import com.eshop.di.component.DaggerHelpComponent; import com.eshop.di.module.HelpModule; import com.eshop.mvp.contract.HelpContract; import com.eshop.mvp.http.entity.store.HelpBean; import com.eshop.mvp.presenter.HelpPresenter; import com.jess.arms.base.BaseActivity; import com.jess.arms.di.component.AppComponent; import java.util.List; import butterknife.BindView; public class HelpDetailActivity extends BaseSupportActivity<HelpPresenter> implements HelpContract.View { @BindView(R.id.toolbar_title) TextView toolbarTitle; @BindView(R.id.title_top) TextView title_top; @BindView(R.id.content_sub) TextView content_sub; private String Title = ""; @Override public void setupActivityComponent(@NonNull AppComponent appComponent) { DaggerHelpComponent //如找不到该类,请编译一下项目 .builder() .appComponent(appComponent) .helpModule(new HelpModule(this)) .build() .inject(this); } @Override public int initView(@Nullable Bundle savedInstanceState) { return R.layout.activity_help_detail; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0 } @Override public void initData(@Nullable Bundle savedInstanceState) { toolbarTitle.setText("常见问题"); String title = getIntent().getStringExtra("q"); String content = getIntent().getStringExtra("a"); Title = getIntent().getStringExtra("title"); setData(title,content); } private void setData(String title_txt,String content_txt){ title_top.setText(title_txt); content_sub.setText(content_txt); if(Title!=null) toolbarTitle.setText(Title); } @Override public void myHelpResult(List<HelpBean> list) { } @Override public void showLoading() { } @Override public void hideLoading() { } @Override public void showMessage(@NonNull String message) { } @Override public void launchActivity(@NonNull Intent intent) { } @Override public void killMyself() { } }
[ "1294873004@qq.com" ]
1294873004@qq.com
c6ea0f3fb0f6f5dbb8f1ba41bd125fd6a32f0610
e92742cc1d5a5c10ae06ef4e306f54abb0e97744
/src/main/java/top/osfun/ext/MyApplicationListener.java
675c576aaa595eb73730e7919e5ea9341a85f1b0
[]
no_license
funing90919/spring-annotation
02a6caa6b20f5c13d4346a149ea1d4bb0d68d18a
775ba8c18e64a39b406301e378068460583a4da5
refs/heads/master
2021-06-14T17:03:28.675965
2019-05-27T08:18:46
2019-05-27T08:18:46
187,196,923
0
0
null
2020-10-13T13:17:53
2019-05-17T10:28:14
Java
UTF-8
Java
false
false
486
java
package top.osfun.ext; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * Created by Jacky on 2019-05-13 21:12. */ @Component public class MyApplicationListener implements ApplicationListener { // 容器中发布事件后触发 @Override public void onApplicationEvent(ApplicationEvent event) { System.out.println("收到事件" + event); } }
[ "funing90919@outlook.com" ]
funing90919@outlook.com
5de44606176f576e9459f60e702a51dfefab13e8
08046556c01e6fd814e5fc9634e7c4df1d94398b
/src/main/java/me/vzhilin/dbrow/adapter/conv/BooleanConverter.java
d060fd776644cab3c12596760f5e6998512281f1
[]
no_license
db-tree/db-row
bb945c9b2f1a7eba368a9e77e856c98352037fef
2e6041a3eabb8ec418afc6773063ba2bd854d6e7
refs/heads/master
2023-06-24T02:04:38.263789
2022-08-10T10:45:21
2022-08-10T10:45:21
216,020,445
1
0
null
2023-06-14T22:24:52
2019-10-18T12:36:03
Java
UTF-8
Java
false
false
544
java
package me.vzhilin.dbrow.adapter.conv; import me.vzhilin.dbrow.adapter.Converter; public final class BooleanConverter implements Converter { public final static BooleanConverter INSTANCE = new BooleanConverter(); @Override public Object fromString(String text) { if ("true".equals(text)) { return true; } if ("false".equals(text)) { return false; } return null; } @Override public String toString(Object o) { return String.valueOf(o); } }
[ "zhilin.vladimir.nic@gmail.com" ]
zhilin.vladimir.nic@gmail.com
cbb66ce0af75bc173ee3296de2f89391a3f367b1
ea08792b304fed21f96f78a4753bcdb85b16f67f
/ContextModuleClient/src/main/java/itti/com/pl/arena/cm/client/ui/Messages.java
7e341705ea2aeaefe0e32fb2bc7395f94894a86a
[]
no_license
mwach/ContextModule
1096fa4c2401413e31a104568df87174bb271802
53c605cb2b0fb91b489e632e78a97795ad6f4f95
refs/heads/master
2021-03-12T21:43:11.388160
2014-06-14T19:32:51
2014-06-14T19:32:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
591
java
package itti.com.pl.arena.cm.client.ui; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Messages { private static final String BUNDLE_NAME = "itti.com.pl.arena.cm.client.ui.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
[ "mwach@wp.pl" ]
mwach@wp.pl
b230913e7821ce371d79a37cae596fdbff808d09
0205999a193bf670cd9d6e5b37e342b75f4e15b8
/spring-core/src/test/java/org/springframework/core/codec/AbstractEncoderTestCase.java
ab80c953646920816ede0e41a1b3afab0d660155
[ "Apache-2.0" ]
permissive
leaderli/spring-source
18aa9a8c7c5e22d6faa6167e999ff88ffa211ba0
0edd75b2cedb00ad1357e7455a4fe9474b3284da
refs/heads/master
2022-02-18T16:34:19.625966
2022-01-29T08:56:48
2022-01-29T08:56:48
204,468,286
0
0
null
null
null
null
UTF-8
Java
false
false
11,169
java
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.codec; import org.junit.Test; import org.reactivestreams.Publisher; import org.springframework.core.ResolvableType; import org.springframework.core.io.buffer.AbstractLeakCheckingTestCase; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.MimeType; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import java.util.Map; import java.util.function.Consumer; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.core.io.buffer.DataBufferUtils.release; /** * Abstract base class for {@link Encoder} unit tests. Subclasses need to implement * {@link #canEncode()} and {@link #encode()}, possibly using the wide * * variety of helper methods like {@link #testEncodeAll}. * * @author Arjen Poutsma * @since 5.1.3 */ @SuppressWarnings("ProtectedField") public abstract class AbstractEncoderTestCase<E extends Encoder<?>> extends AbstractLeakCheckingTestCase { /** * The encoder to test. */ protected final E encoder; /** * Construct a new {@code AbstractEncoderTestCase} for the given parameters. * * @param encoder the encoder */ protected AbstractEncoderTestCase(E encoder) { Assert.notNull(encoder, "Encoder must not be null"); this.encoder = encoder; } /** * Subclasses should implement this method to test {@link Encoder#canEncode}. */ @Test public abstract void canEncode() throws Exception; /** * Subclasses should implement this method to test {@link Encoder#encode}, possibly using * {@link #testEncodeAll} or other helper methods. */ @Test public abstract void encode() throws Exception; /** * Helper methods that tests for a variety of encoding scenarios. This methods * invokes: * <ul> * <li>{@link #testEncode(Publisher, ResolvableType, Consumer, MimeType, Map)}</li> * <li>{@link #testEncodeError(Publisher, ResolvableType, MimeType, Map)}</li> * <li>{@link #testEncodeCancel(Publisher, ResolvableType, MimeType, Map)}</li> * <li>{@link #testEncodeEmpty(ResolvableType, MimeType, Map)}</li> * </ul> * * @param input the input to be provided to the encoder * @param inputClass the input class * @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output * @param <T> the output type */ protected <T> void testEncodeAll(Publisher<? extends T> input, Class<? extends T> inputClass, Consumer<StepVerifier.FirstStep<DataBuffer>> stepConsumer) { testEncodeAll(input, ResolvableType.forClass(inputClass), stepConsumer, null, null); } /** * Helper methods that tests for a variety of decoding scenarios. This methods * invokes: * <ul> * <li>{@link #testEncode(Publisher, ResolvableType, Consumer, MimeType, Map)}</li> * <li>{@link #testEncodeError(Publisher, ResolvableType, MimeType, Map)}</li> * <li>{@link #testEncodeCancel(Publisher, ResolvableType, MimeType, Map)}</li> * <li>{@link #testEncodeEmpty(ResolvableType, MimeType, Map)}</li> * </ul> * * @param input the input to be provided to the encoder * @param inputType the input type * @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output * @param mimeType the mime type to use for decoding. May be {@code null}. * @param hints the hints used for decoding. May be {@code null}. * @param <T> the output type */ protected <T> void testEncodeAll(Publisher<? extends T> input, ResolvableType inputType, Consumer<StepVerifier.FirstStep<DataBuffer>> stepConsumer, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { testEncode(input, inputType, stepConsumer, mimeType, hints); testEncodeError(input, inputType, mimeType, hints); testEncodeCancel(input, inputType, mimeType, hints); testEncodeEmpty(inputType, mimeType, hints); } /** * Test a standard {@link Encoder#encode encode} scenario. * * @param input the input to be provided to the encoder * @param inputClass the input class * @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output * @param <T> the output type */ protected <T> void testEncode(Publisher<? extends T> input, Class<? extends T> inputClass, Consumer<StepVerifier.FirstStep<DataBuffer>> stepConsumer) { testEncode(input, ResolvableType.forClass(inputClass), stepConsumer, null, null); } /** * Test a standard {@link Encoder#encode encode} scenario. * * @param input the input to be provided to the encoder * @param inputType the input type * @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output * @param mimeType the mime type to use for decoding. May be {@code null}. * @param hints the hints used for decoding. May be {@code null}. * @param <T> the output type */ protected <T> void testEncode(Publisher<? extends T> input, ResolvableType inputType, Consumer<StepVerifier.FirstStep<DataBuffer>> stepConsumer, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { Flux<DataBuffer> result = encoder().encode(input, this.bufferFactory, inputType, mimeType, hints); StepVerifier.FirstStep<DataBuffer> step = StepVerifier.create(result); stepConsumer.accept(step); } /** * Test a {@link Encoder#encode encode} scenario where the input stream contains an error. * This test method will feed the first element of the {@code input} stream to the encoder, * followed by an {@link InputException}. * The result is expected to contain one "normal" element, followed by the error. * * @param input the input to be provided to the encoder * @param inputType the input type * @param mimeType the mime type to use for decoding. May be {@code null}. * @param hints the hints used for decoding. May be {@code null}. * @see InputException */ protected void testEncodeError(Publisher<?> input, ResolvableType inputType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { input = Flux.concat( Flux.from(input).take(1), Flux.error(new InputException())); Flux<DataBuffer> result = encoder().encode(input, this.bufferFactory, inputType, mimeType, hints); StepVerifier.create(result) .consumeNextWith(DataBufferUtils::release) .expectError(InputException.class) .verify(); } /** * Test a {@link Encoder#encode encode} scenario where the input stream is canceled. * This test method will feed the first element of the {@code input} stream to the decoder, * followed by a cancel signal. * The result is expected to contain one "normal" element. * * @param input the input to be provided to the encoder * @param inputType the input type * @param mimeType the mime type to use for decoding. May be {@code null}. * @param hints the hints used for decoding. May be {@code null}. */ protected void testEncodeCancel(Publisher<?> input, ResolvableType inputType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { Flux<DataBuffer> result = encoder().encode(input, this.bufferFactory, inputType, mimeType, hints); StepVerifier.create(result) .consumeNextWith(DataBufferUtils::release) .thenCancel() .verify(); } /** * Test a {@link Encoder#encode encode} scenario where the input stream is empty. * The output is expected to be empty as well. * * @param inputType the input type * @param mimeType the mime type to use for decoding. May be {@code null}. * @param hints the hints used for decoding. May be {@code null}. */ protected void testEncodeEmpty(ResolvableType inputType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { Flux<?> input = Flux.empty(); Flux<DataBuffer> result = encoder().encode(input, this.bufferFactory, inputType, mimeType, hints); StepVerifier.create(result) .verifyComplete(); } /** * Create a result consumer that expects the given bytes. * * @param expected the expected bytes * @return a consumer that expects the given data buffer to be equal to {@code expected} */ protected final Consumer<DataBuffer> expectBytes(byte[] expected) { return dataBuffer -> { byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(resultBytes); release(dataBuffer); assertThat(resultBytes).isEqualTo(expected); }; } /** * Create a result consumer that expects the given string, using the UTF-8 encoding. * * @param expected the expected string * @return a consumer that expects the given data buffer to be equal to {@code expected} */ protected Consumer<DataBuffer> expectString(String expected) { return dataBuffer -> { byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(resultBytes); release(dataBuffer); String actual = new String(resultBytes, UTF_8); assertThat(actual).isEqualTo(expected); }; } @SuppressWarnings("unchecked") private <T> Encoder<T> encoder() { return (Encoder<T>) this.encoder; } /** * Exception used in {@link #testEncodeError}. */ @SuppressWarnings("serial") public static class InputException extends RuntimeException { } }
[ "429243408@qq.com" ]
429243408@qq.com
47b9f152671f9abb72e8bcc3fe9c40739cc76071
26c959606e3815135a3e915ba151214beaf35c62
/src/main/java/collection/MultiDimensionalArrayIterator.java
b77507f183d12c39d40792e8cd782c3b21ee4b0b
[]
no_license
Bisonq/018_DynamicMultiDimensionalArray
3536eb18bb68a92a69d7724ca5461c0e48e65ff2
934b1b8be65b6527c7c0c3a622e00dc12d65d7f0
refs/heads/master
2022-11-24T01:21:56.443608
2020-07-24T10:04:52
2020-07-24T10:04:52
281,759,442
0
0
null
null
null
null
UTF-8
Java
false
false
517
java
package collection; import java.util.Iterator; import java.util.List; public class MultiDimensionalArrayIterator<E> implements Iterator<E> { private Iterator<E> arrayElementsIterator; public MultiDimensionalArrayIterator(List<E> arrayElements) { this.arrayElementsIterator = arrayElements.iterator(); } @Override public boolean hasNext() { return arrayElementsIterator.hasNext(); } @Override public E next() { return arrayElementsIterator.next(); } }
[ "tsosnowski666@gmail.com" ]
tsosnowski666@gmail.com
12e00ec87ea80edf9f9d630f18c89a75a310f0b0
900fb8f4e6d2fc4885849ec0ecb21c54465427a3
/src/main/java/af/props/ValidatedProperties.java
4bfd0551cda79c70139d5a2b7df961cc322c3a3a
[ "Apache-2.0" ]
permissive
AlexFalappa/nb-cfgprops
c9362fd19c24f22c0eaf243f66dbd02feac12e17
b93e39b9d3eccfaa7302e37b56a7a4330a226ece
refs/heads/master
2021-01-18T11:30:54.464998
2020-07-27T17:18:21
2020-07-27T17:18:21
84,326,576
0
0
null
null
null
null
UTF-8
Java
false
false
1,372
java
package af.props; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; import org.hibernate.validator.constraints.URL; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import lombok.Getter; import lombok.Setter; /** * A set of JSR-303 validated properties. * * @author Alessandro Falappa */ @ConfigurationProperties(prefix = "validated") @Validated @Getter @Setter public class ValidatedProperties { /** * Non empty string. */ @NotEmpty private String notEmpty; /** * Non null character. */ @NotNull private Character notNull; /** * Integer in the [0-10] inclusive range. */ @Range(min = 0, max = 10) private Integer inRange; /** * Non null string with length from 4 to 8. */ @NotNull @Length(min = 4, max = 8) private String lengthInRange; /** * Non null string representing an URL. */ @URL @NotNull private String urlString; /** * A point as an array of exactly two double numbers. */ @Size(min = 2, max = 2) @NotNull private double[] point; }
[ "alex.falappa@gmail.com" ]
alex.falappa@gmail.com
59b2498f58c5ff0c0eab09ebfda75e7871d3e7bc
0cdbb3ba924b62fd3dfbec3aae59724a01c71cea
/src/main/edu/testdome/java/RoutePlanner/RoutePlannerRecursive.java
a7a57e261a15524af29a9210e42fd9b593fe95e1
[ "MIT" ]
permissive
AlvinLaiPro/TestDomeJavaPractice
a80357916d2703b9a7ed82411f63355bf0ee9127
e36cb9605b99f74c6304e8cccebcff1f58b75507
refs/heads/master
2023-03-18T00:40:50.372625
2021-01-27T16:01:10
2021-01-27T16:01:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,195
java
package main.edu.testdome.java.RoutePlanner; public class RoutePlannerRecursive { public static boolean routeExists(int fromRow, int fromColumn, int toRow, int toColumn, boolean[][] mapMatrix) { int rowCount = mapMatrix.length; int columnCount = mapMatrix[0].length; boolean visited[][] = new boolean[rowCount][columnCount]; boolean flag = false; for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { if (i==fromRow && j == fromColumn && !visited[i][j]) { if (isPath(toRow, toColumn, mapMatrix, i, j, visited)) { flag = true; break; } } } } return flag; } public static boolean isSafe(int i, int j, boolean matrix[][]) { if (i >= 0 && i < matrix.length && j >= 0 && j < matrix[0].length) return true; return false; } public static boolean isPath(int toRow, int toColumn,boolean matrix[][], int i, int j, boolean visited[][]) { if (isSafe(i, j, matrix) && matrix[i][j] && !visited[i][j]) { visited[i][j] = true; if (i==toRow && j == toColumn) return true; // traverse up boolean up = isPath(toRow, toColumn, matrix, i - 1, j, visited); if (up) return true; // traverse left boolean left = isPath(toRow, toColumn, matrix, i, j - 1, visited); if (left) return true; // traverse down boolean down = isPath(toRow, toColumn, matrix, i + 1, j, visited); if (down) return true; // traverse right boolean right = isPath(toRow, toColumn, matrix, i, j + 1, visited); if (right) return true; } // no path has been found return false; } public static void main(String[] args) { boolean[][] mapMatrix = { {true, false, false}, {true, true, false}, {false, true, true}, }; System.out.println(routeExists(0, 0, 2, 2, mapMatrix)); } }
[ "himashirodrigo23@gmail.com" ]
himashirodrigo23@gmail.com
7a3d04580e35387990418a4f79d79eb762e55ae6
8520276d9992877380598fccbd8d44fee8684895
/app/src/main/java/com/ppb/kalkulatorfirestore/MainActivity.java
dbdf2f7dc2280f82f7400b9b2a2dc9231e0232ce
[]
no_license
uliarizki/Kalkulator_Firestore
04338b3ccc2e4b1eaddd5a5a6672050b84fa37fd
26e17f5958978d93644019ca9d6b62399b4922a9
refs/heads/master
2020-09-29T23:47:30.706577
2019-12-10T15:43:01
2019-12-10T15:43:01
227,150,237
0
0
null
null
null
null
UTF-8
Java
false
false
341
java
package com.ppb.kalkulatorfirestore; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
[ "uliarizki@gmail.com" ]
uliarizki@gmail.com
73b501e43332503f0222ff5dfa1c87862d0ee4a0
4643b14df45c7cf84efdaeacd4544837d1781958
/src/main/java/com/fasterxml/jackson/perf/json/JsonNoInternReadVanilla.java
1874d6a00297b3233e1af8db1414dd11621d1a20
[]
no_license
isabella232/jackson-benchmarks
b8cde0682d1bd820108c3eaabfb13fcaef80aa40
85ac76df6932ce1349d9fd66936453cad1744c4f
refs/heads/master
2023-01-22T08:35:12.366022
2020-11-25T00:12:40
2020-11-25T00:12:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,406
java
package com.fasterxml.jackson.perf.json; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Scope; import com.fasterxml.jackson.core.json.JsonFactory; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.perf.ReadPerfBaseFullJackson; import com.fasterxml.jackson.perf.data.InputConverter; import com.fasterxml.jackson.perf.model.MediaItem; // 11-Apr-2018, tatu: Note that this test should NOT have different performance // in 3.0.0, as intern()ing is not enabled by default any more. @State(Scope.Thread) @OutputTimeUnit(TimeUnit.SECONDS) public class JsonNoInternReadVanilla extends ReadPerfBaseFullJackson<MediaItem> { private static final ObjectMapper MAPPER = JsonMapper.builder(JsonFactory.builder() .disable(JsonFactory.Feature.INTERN_FIELD_NAMES) .build()) .build(); // pass non-null ObjectMapper: will remove whitespace, if any private final static InputConverter JSON_CONV = InputConverter.stdConverter(MAPPER); // NOTE: to _RETAIN_ whitespace, we'd use: // private final static InputConverter JSON_CONV = InputConverter.nopConverter(MAPPER); public JsonNoInternReadVanilla() { super(MediaItem.class, JSON_CONV, MAPPER); } }
[ "tatu.saloranta@iki.fi" ]
tatu.saloranta@iki.fi
f8235d389ec86f5de5ec4ec714d23f4f5560b70f
2a3840e528f6809fe9571fccd8f249cd0ca903f6
/src/offline/FindPeak.java
e78dbe29031ca2a44ca9f6ec9deae3be02c14d25
[]
no_license
1992dux/Titan
1c31e79d3487e7bbae739fba46d8ca2a8527e566
c33d3f03b28abb04a2eefee897721407baba601c
refs/heads/master
2021-04-08T07:04:49.012862
2018-03-19T04:20:56
2018-03-19T04:20:56
125,313,736
0
0
null
null
null
null
UTF-8
Java
false
false
3,650
java
package offline; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.bson.Document; import com.mongodb.Block; import com.mongodb.MongoClient; import com.mongodb.client.MapReduceIterable; import com.mongodb.client.MongoDatabase; import db.mongodb.MongoDBUtil; public class FindPeak { private static final String COLLECTION_NAME = "logs"; private static final String TIME = "time"; private static final String URL_PREFIX = "/Titan"; private static List<LocalTime> buckets = initBuckets(); public static void main(String[] args) { MongoClient mongoClient = new MongoClient(); MongoDatabase db = mongoClient.getDatabase(MongoDBUtil.DB_NAME); // contstruct mapper function // function() { // if (this.url.startsWith("/Titan")) { // emit(this.time.substring(0, 5), 1); // } // } StringBuilder sb = new StringBuilder(); sb.append("function() {"); sb.append("if (this.url.startsWith(\""); sb.append(URL_PREFIX); sb.append("\")) { emit(this."); sb.append(TIME); sb.append(".substring(0, 5), 1); }"); sb.append("}"); String map = sb.toString(); // Construct reduce function //function(key, values) { // return Arrays.sum(values) //} String reduce = "function(key, values) {return Array.sum(values);}"; // MapReduce MapReduceIterable<Document> results = db.getCollection(COLLECTION_NAME).mapReduce(map, reduce); //Save total count to each bucket Map<String, Double> timeMap = new HashMap<>(); results.forEach(new Block<Document>() { @Override public void apply(final Document document) { String time = findBucket(document.getString("_id")); Double count = document.getDouble("value"); if (timeMap.containsKey(time)) { timeMap.put(time, timeMap.get(time) + count); } else { timeMap.put(time, count); } } }); // Sort the list List<Map.Entry<String, Double>> timeList = new ArrayList<>(timeMap.entrySet()); Collections.sort(timeList, new Comparator<Map.Entry<String, Double>>() { @Override public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) { if (o1.getValue().compareTo(o2.getValue()) > 0) { return 1; } else { return -1; } } }); printList(timeList); mongoClient.close(); } private static void printList(List<Map.Entry<String, Double>> timeList) { for (Map.Entry<String, Double> entry : timeList) { System.out.println("time : " + entry.getKey() + " count : " + entry.getValue()); } } private static List<LocalTime> initBuckets() { List<LocalTime> buckets = new ArrayList<>(); LocalTime time = LocalTime.parse("00:00"); // expand the granularity, set every 15 minute as time zone for (int i = 0; i < 96; i++) { buckets.add(time); time = time.plusMinutes(15); } return buckets; } private static String findBucket(String currentTime) { String[] time = currentTime.split(":"); int timeNum = Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1]); int index = timeNum / 15; return buckets.get(index).toString(); // LocalTime curr = LocalTime.parse(currentTime); // int left = 0, right = buckets.size() - 1; // while (left < right - 1) { // int mid = (left + right) / 2; // if (buckets.get(mid).isAfter(curr)) { // right = mid - 1; // } else { // left = mid; // } // } // if (buckets.get(right).isAfter(curr)) { // return buckets.get(left).toString(); // } // return buckets.get(right).toString(); } }
[ "1992dux@gmail.com" ]
1992dux@gmail.com
6d101fb302b55b905f5040f1519bd7ce16ac56ff
7a060989f0f655f1fa2beefaaf51061b06218f72
/client/src/edu/indiana/d2i/seqmining/webservice/client/ClientConstants.java
6e792aa276d436e739a1e5d3f624368f054d8162
[ "Apache-2.0" ]
permissive
guangchen/sequential-pattern-miner-webservice
b321a5e3e5885ed910a47e67be55e6a05ebb263d
f76719809aa775a5b25e667bdefe8ef3eb4e1e9c
refs/heads/master
2020-05-19T11:46:56.748936
2014-08-25T17:51:29
2014-08-25T17:51:29
12,471,033
0
2
null
null
null
null
UTF-8
Java
false
false
570
java
package edu.indiana.d2i.seqmining.webservice.client; public class ClientConstants { public static String CLIENT_PROPERTY_FNAME = "seqminer-client.properties"; public static String SEQ_PATTERN_MINER_PROPERTY_FNAME = "seqminer-algo.properties"; public static String SEQ_PATTERN_MINER_WS_EPR = "seq.pattern.miner.ws.epr"; public static String CLIENT_CALLBACK_PORT = "client.callback.port"; public static String CLIENT_FIGURE_OUTPUT_DIR = "client.figure.output.dir"; public static String SEQ_PATTERN_MINER_WS_TYPE = "seq.pattern.miner.ws.type"; }
[ "gruan@umail.iu.edu" ]
gruan@umail.iu.edu
7579d095b665697bec7eadc1ccb0d54b2989169f
df9bae82cec5be5c324f40ed39fff41401f91494
/Exercise/Polymorphism/src/WildFarm/animals/Tiger.java
0fd39c62f74cdbae16823d4eedfabc5d84ab12b6
[]
no_license
valentin-stojanov/Java-OOP
f0a1c712dcbc61749ef6d1e46947ce1de0d68d88
bf06b4f9de76a64d29c442abbe1de5d4b8376067
refs/heads/main
2023-08-09T10:20:59.790446
2021-09-12T08:47:04
2021-09-12T08:47:04
382,868,593
0
0
null
null
null
null
UTF-8
Java
false
false
654
java
package WildFarm.animals; import WildFarm.foods.Food; import WildFarm.foods.Meat; import WildFarm.foods.Vegetable; public class Tiger extends Felime { public Tiger(String animalName, String animalType, double animalWeight, String livingRegion) { super(animalName, animalType, animalWeight, livingRegion); } @Override public void makeSound() { System.out.println("ROAAR!!!"); } @Override public void eat(Food food){ if (food instanceof Meat){ super.eat(food); }else { throw new IllegalArgumentException("Tigers are not eating that type of food!"); } } }
[ "valentin_stojanov@abv.bg" ]
valentin_stojanov@abv.bg
647abf4538bea69ba9b3c74f26d191230fe4f9e8
c29e3ef810b96d24a82feb074724b475cda8ebf6
/FileSearch/src/main/java/task/FileScanner.java
d0f6f2ce4cee7f59d2d690be87388ee5ce858db5
[]
no_license
Moo-lavender/File-Search
fe24c9f5492cf60e6b087a3ce7a0756544a5882e
6794f1334e707989d65713c4cd0121b4ca51a173
refs/heads/master
2023-05-26T14:05:14.370580
2020-05-23T13:55:18
2020-05-23T13:55:18
240,254,951
0
0
null
2023-05-23T20:12:12
2020-02-13T12:27:19
Java
UTF-8
Java
false
false
4,002
java
package task; import java.io.File; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; public class FileScanner { //1.核心线程数:始终运行的线程数量 //2.最大的线程数:有新任务,并且当前运行的线程数小于最大线程数,会创建新的线程来处理任务(正式工 + 零时工) //3、4.超过3这个数量,4这个时间单位,2-1(最大线程数-核心线程数)这些线程(零时工)就会关闭 //5.工作的阻塞队列 //6.如果超出工作队列的长度,任务要处理的方式(4种策略需要知道) private ThreadPoolExecutor pool = new ThreadPoolExecutor( 3,3,0, TimeUnit.MICROSECONDS, new LinkedBlockingDeque<>(),new ThreadPoolExecutor.AbortPolicy() ); //这是一种快捷创建的方式 //private ExecutorService exe = Executors.newFixedThreadPool(4); //计数器,不传入数值表示初始化为0 private volatile AtomicInteger count = new AtomicInteger(); //线程等待的锁对象 private Object lock = new Object();//第一种:synchronized private ScanCallback callback; public FileScanner(ScanCallback callback) { this.callback = callback; } // private CountDownLatch latch = new CountDownLatch(1);//第二种:await阻塞等待 // private Semaphore semaphore = new Semaphore(0);//第三章acquire()阻塞等待 /** * 扫描文件目录 * @param path */ public void scan(String path) { count.incrementAndGet();//启动根目录扫描任务计数器i++ doScan(new File(path)); } private void doScan(File dir) { pool.execute(new Runnable() { @Override public void run() { try { callback.callback(dir); File[] children = dir.listFiles(); //下级文件和文件夹 if (children != null) { for (File child : children) { if (child.isDirectory()) {//如果是文件夹,递归处理 count.incrementAndGet();//启动子文件夹扫描任务计数器i++ System.out.println("当前任务数:"+count.get()); doScan(child); } } } }finally { //保证线程计数不管是否出现异常都能进行-1操作 int r = count.decrementAndGet(); if (r == 0) { synchronized (lock) { lock.notify(); } } } } }); } /** * 等待扫瞄任务结束scan方法 * 多线程的任务等待 thread.start * 1.join():需要使用线程Thread类的引用对象 * 2.wait()线程间通信 */ public void waitFinish() throws InterruptedException { try { synchronized (lock){ lock.wait(); } } finally { //阻塞等待直到任务完成,完成需要关闭线程池 System.out.println("关闭线程池"); //内部实现原理,是通过内部的Thread.interrupt()来中断 pool.shutdownNow(); } } public static void main(String[] args) throws InterruptedException { Thread t = new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()); synchronized (FileScanner.class) { FileScanner.class.notifyAll(); } } }); t.start(); synchronized (FileScanner.class) { FileScanner.class.wait(); } System.out.println(Thread.currentThread().getName()); } }
[ "1820545434@qq.com" ]
1820545434@qq.com
1edb0323358b45bc71cd50372d3014e1b61d4cd1
5a8ad42d735ff72d9cb70f6818786d7b3f669ad9
/16장_스프링부트_액츄에이터_사용하기/src/main/java/me/june/spring/Note.java
cf1e905a89f38ea39d46f02413cdfa1a903a2b18
[]
no_license
ces518/Spring_In_Action_Study
3c3e43660b0c22c97d774033f15a715bac1c37cf
115150652ec14ca41ccc08a0eb85ff5cdbe47500
refs/heads/master
2023-03-01T21:08:36.179652
2021-02-06T14:07:46
2021-02-06T14:07:46
322,320,303
0
0
null
null
null
null
UTF-8
Java
false
false
479
java
package me.june.spring; import java.util.Date; public class Note { private Date time = new Date(); private String text; public Note() { } public Note(String text) { this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }
[ "ncucu.me@kakaocommerce.com" ]
ncucu.me@kakaocommerce.com
91baf85e5abb7b8a267e82ea815586cf345edbaf
8b5cdda28454b0aab451a4b3216a58ca87517c41
/AL-Game/data/scripts/system/database/mysql5/MySQL5PortalCooldownsDAO.java
6cb9fec26f52536204e91d795688d1bad24cf7fe
[]
no_license
flroexus/aelp
ac36cd96963bd12847e37118531b68953f9e8440
4f6cca6b462419accf53b58c454be0cf6abe39c0
refs/heads/master
2023-05-28T18:36:47.919387
2020-09-05T07:27:49
2020-09-05T07:27:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,208
java
package mysql5; import com.aionemu.commons.database.DatabaseFactory; import com.aionemu.gameserver.dao.MySQL5DAOUtils; import com.aionemu.gameserver.dao.PortalCooldownsDAO; import com.aionemu.gameserver.model.gameobjects.player.Player; import javolution.util.FastMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; public class MySQL5PortalCooldownsDAO extends PortalCooldownsDAO { private static final Logger log = LoggerFactory.getLogger(MySQL5PortalCooldownsDAO.class); public static final String INSERT_QUERY = "INSERT INTO `portal_cooldowns` (`player_id`, `world_id`, `reuse_time`) VALUES (?,?,?)"; public static final String DELETE_QUERY = "DELETE FROM `portal_cooldowns` WHERE `player_id`=?"; public static final String SELECT_QUERY = "SELECT `world_id`, `reuse_time` FROM `portal_cooldowns` WHERE `player_id`=?"; @Override public void loadPortalCooldowns(final Player player) { Connection con = null; FastMap<Integer, Long> portalCoolDowns = new FastMap<Integer, Long>(); PreparedStatement stmt = null; try { con = DatabaseFactory.getConnection(); stmt = con.prepareStatement(SELECT_QUERY); stmt.setInt(1, player.getObjectId()); ResultSet rset = stmt.executeQuery(); while (rset.next()) { int worldId = rset.getInt("world_id"); long reuseTime = rset.getLong("reuse_time"); if (reuseTime > System.currentTimeMillis()) { portalCoolDowns.put(worldId, reuseTime); } } player.getPortalCooldownList().setPortalCoolDowns(portalCoolDowns); rset.close(); } catch (SQLException e) { log.error("LoadPortalCooldowns", e); } finally { DatabaseFactory.close(stmt, con); } } @Override public void storePortalCooldowns(final Player player) { deletePortalCooldowns(player); Map<Integer, Long> portalCoolDowns = player.getPortalCooldownList().getPortalCoolDowns(); if (portalCoolDowns == null) return; for (Map.Entry<Integer, Long> entry : portalCoolDowns.entrySet()) { final int worldId = entry.getKey(); final long reuseTime = entry.getValue(); if (reuseTime < System.currentTimeMillis()) continue; Connection con = null; PreparedStatement stmt = null; try { con = DatabaseFactory.getConnection(); stmt = con.prepareStatement(INSERT_QUERY); stmt.setInt(1, player.getObjectId()); stmt.setInt(2, worldId); stmt.setLong(3, reuseTime); stmt.execute(); } catch (SQLException e) { log.error("storePortalCooldowns", e); } finally { DatabaseFactory.close(stmt, con); } } } private void deletePortalCooldowns(final Player player) { Connection con = null; PreparedStatement stmt = null; try { con = DatabaseFactory.getConnection(); stmt = con.prepareStatement(DELETE_QUERY); stmt.setInt(1, player.getObjectId()); stmt.execute(); } catch (SQLException e) { log.error("deletePortalCooldowns", e); } finally { DatabaseFactory.close(stmt, con); } } @Override public boolean supports(String arg0, int arg1, int arg2) { return MySQL5DAOUtils.supports(arg0, arg1, arg2); } }
[ "luiz.philip@amedigital.com" ]
luiz.philip@amedigital.com
aab6452085579de242db9ad0a0340a4e5bf104ed
e775e660d0f68c7e51d93c6888689ccb39d1f1db
/JAVA/prj_jee/org.jsonstleary/src/main/java/Property.java
8281a0da5ecac53fd314f2bc260616de3b45cb3b
[ "JSON" ]
permissive
genose/progmatic_things
5b95f7e90dbe5a14e0c819c7e076d626444e349a
ff256b1fcae30e3b06b9dbddfa81439c1c4adb8e
refs/heads/master
2022-07-08T04:42:13.810913
2021-03-05T09:37:47
2021-03-05T09:37:47
114,885,484
3
0
null
2022-06-29T18:23:34
2017-12-20T12:33:48
Java
UTF-8
Java
false
false
2,867
java
/* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.util.Enumeration; import java.util.Properties; /** * Converts a Property file data into JSONObject and back. * @author JSON.org * @version 2015-05-05 */ public class Property { /** * Converts a property file object into a JSONObject. The property file object is a table of name value pairs. * @param properties java.util.Properties * @return JSONObject * @throws JSONException */ public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException { // can't use the new constructor for Android support // JSONObject jo = new JSONObject(properties == null ? 0 : properties.size()); JSONObject jo = new JSONObject(); if (properties != null && !properties.isEmpty()) { Enumeration<?> enumProperties = properties.propertyNames(); while(enumProperties.hasMoreElements()) { String name = (String)enumProperties.nextElement(); jo.put(name, properties.getProperty(name)); } } return jo; } /** * Converts the JSONObject into a property file object. * @param jo JSONObject * @return java.util.Properties * @throws JSONException */ public static Properties toProperties(JSONObject jo) throws JSONException { Properties properties = new Properties(); if (jo != null) { // Don't use the new entrySet API to maintain Android support for (final String key : jo.keySet()) { Object value = jo.opt(key); if (!JSONObject.NULL.equals(value)) { properties.put(key, value.toString()); } } } return properties; } }
[ "devel@genose.org" ]
devel@genose.org
8194dc22e4818b08f31f0c75d946633573569db1
437d05c037e938f36969cb96e2c7ad42b960ac15
/apps/app10e/src/app10e/dao/DAO.java
a3df3b25dab70fd967f0cd394cd3e231a0c698f2
[]
no_license
Sunnie-Y/servlet-and-JSP
31a30ebc5a0d8f393e11f0feedf6ca72975f4d09
82d2058e6a790d9a71b7bb6da10aea641e30d80f
refs/heads/master
2022-03-19T15:54:37.587203
2019-12-12T12:06:44
2019-12-12T12:06:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
200
java
package app10e.dao; import java.sql.Connection; import javax.sql.DataSource; public interface DAO { void setDataSource(DataSource dataSource); Connection getConnection() throws DAOException; }
[ "18225542927@163.com" ]
18225542927@163.com
e604e5cb5380129c68f36ebe10be0a3f502afb4c
cdceb209b7838b6641dad994e114c4ea55dfdfe7
/fmall-search/src/main/java/com/suse/fmall/search/service/impl/ProductSaveServiceImpl.java
7061be379365e89038ade3a635bc7f9cedc9ee60
[ "Apache-2.0" ]
permissive
garethhk/Fmall
4c648b784b11d045778f486af773102b78be1d56
f8da2149d2cf5279b62cfa477c8bcd865231e322
refs/heads/master
2023-05-12T18:06:29.101201
2021-05-17T06:10:07
2021-05-17T06:10:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,255
java
package com.suse.fmall.search.service.impl; import com.alibaba.fastjson.JSON; import com.suse.common.to.es.SkuEsModel; import com.suse.fmall.search.config.FmallElasticSearchConfig; import com.suse.fmall.search.constant.EsConstant; import com.suse.fmall.search.service.ProductSaveService; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @Author LiuJing * @Date: 2021/03/21/ 22:01 * @Description */ @Slf4j @Service public class ProductSaveServiceImpl implements ProductSaveService { @Autowired private RestHighLevelClient restHighLevelClient; @Override public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException { //保存到es //1.给es建立索引,product //2.给es保存数据 //BulkRequest bulkRequest, RequestOptions options BulkRequest bulkRequest = new BulkRequest(); for (SkuEsModel skuEsModel : skuEsModels) { //构造保存请求 IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX); indexRequest.id(skuEsModel.getSkuId().toString()); String modelStr = JSON.toJSONString(skuEsModel); indexRequest.source(modelStr, XContentType.JSON); bulkRequest.add(indexRequest); } BulkResponse bulkRes = restHighLevelClient.bulk(bulkRequest, FmallElasticSearchConfig.COMMON_OPTIONS); //TODO 如果批量错误 boolean success = !bulkRes.hasFailures(); List<String> collect = Arrays.stream(bulkRes.getItems()) .map(BulkItemResponse::getId).collect(Collectors.toList()); log.info("商品上架完成:{},返回数据:{}",collect,bulkRes.toString()); return success; } }
[ "18384623913@l63.com" ]
18384623913@l63.com
aca258629fd76457cb35ca0391afa54adf14fcbd
839e76aa1dd86f1c7b1d5f5602dd3d4629310830
/src/com/blackhole/database/jdbc/MongoDBImpl.java
8a68ce16a6d04f839fe6a534210ec1b1d0ca4b68
[]
no_license
jarpi/todo-rest
733fadd78975da6a5d1344dabb77181a8baaa1f2
0bdd9cb5c913b494b696f9e208607507265b7b6b
refs/heads/master
2020-06-05T16:59:23.290245
2015-01-14T19:45:42
2015-01-14T19:45:42
20,780,469
0
0
null
null
null
null
UTF-8
Java
false
false
7,586
java
package com.blackhole.database.jdbc; import java.net.UnknownHostException; import java.util.ArrayList; import org.bson.types.ObjectId; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.WriteResult; /* * Specific database connection layer * * It's uses singleton pattern, if instances is created, return instances, create it otherwise */ public class MongoDBImpl { private static MongoClient mMongoClient; private static DB mDb; boolean mAuth; public MongoDBImpl(String ip) throws UnknownHostException { if (mMongoClient == null) { try { mMongoClient = new MongoClient(ip, 27017); mDb = mMongoClient.getDB("tictactoe"); // auth = db.authenticate(username, password); // TODO } catch (UnknownHostException e) { throw e; } } } /* * Given a @collection and @id get single document from database */ public DBObject getDocumentById(String collection, String id) throws Exception { BasicDBObject bdb = new BasicDBObject("_id",new ObjectId(id)); DBObject result = null; if (mDb.collectionExists(collection)) { DBCollection coll = mDb.getCollection(collection); result = coll.findOne(bdb); } else { throw new Exception("Collection doesn't exist"); } return result; } /* * Given a @collection get single document by @field and @value of that field (like sql query SELECT * FROM TABLE WHERE field=value) */ public DBObject getDocumentByField(String collection, String field, String value) throws Exception { BasicDBObject bdb = new BasicDBObject(); if (field.equals("_id")) { bdb.put(field, new ObjectId(value)); } else { bdb.put(field, value); } DBObject result = null; if (existsCollection(collection)) { DBCollection coll = mDb.getCollection(collection); result = coll.findOne(bdb); } else { throw new Exception("Collection doesn't exist"); } return result; } /* * Given a @collection get multiple documents by @field and a @value */ public ArrayList<String> getDocumentsByField(String collection, String field, String value) throws Exception { BasicDBObject bdb = new BasicDBObject(); if (field.equals("_id")) { bdb.put(field, new ObjectId(value)); } else { bdb.put(field, value); } ArrayList<String> result = new ArrayList<String>(); DBCursor dbc; if (existsCollection(collection)) { DBCollection coll = mDb.getCollection(collection); dbc = coll.find(bdb); while (dbc.hasNext()) { DBObject dbo = dbc.next(); result.add(dbo.get("_id").toString()); } } else { throw new Exception("Collection doesn't exist"); } return result; } /* * Given a @collection and list of @fields and @values, get an array of documents */ public ArrayList<String> getDocumentsByFields(String collection, Object[] fields, Object[] values) throws Exception { BasicDBObject bdb = new BasicDBObject(); for (int i=0; i<fields.length; i++) { String field = (String)fields[i]; String value = (String)values[i]; if (field.equals("_id")){ // if filter field is ID, then convert it to "ObjectId" type bdb.put(field,new ObjectId(value)); } else { // if filter field is boolean type, convert the value to boolean if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) { bdb.put(field,Boolean.valueOf(value)); } else { // if filter field is string or number, simply add (for later revisions it will be need to add any type that database have) bdb.put(field,value); } } } // Add all documents ID to array list ArrayList<String> result = new ArrayList<String>(); DBCursor dbc; if (existsCollection(collection)) { DBCollection coll = mDb.getCollection(collection); dbc = coll.find(bdb); while (dbc.hasNext()) { DBObject dbo = dbc.next(); result.add(dbo.get("_id").toString()); } } else { throw new Exception("Collection doesn't exist"); } return result; } /* * Given a @collection and list of @fields and @values, get a single document */ public DBObject getDocumentByFields(String collection, Object[] fields, Object[] values) throws Exception { BasicDBObject bdb = new BasicDBObject(); for (int i=0; i<fields.length; i++) { String field = (String)fields[i]; String value = (String)values[i]; if (field.equals("_id")){ bdb.put(field,new ObjectId(value)); } else { bdb.put(field,value); } } DBObject result = null; if (existsCollection(collection)) { DBCollection coll = mDb.getCollection(collection); result = coll.findOne(bdb); } else { throw new Exception("Collection doesn't exist"); } return result; } /* * Given a @collection and a document of type DBObject, insert to database */ public boolean insertDocument(String collection, BasicDBObject document) throws Exception { WriteResult result = null; if (existsCollection(collection)) { DBCollection coll = mDb.getCollection(collection); result = coll.insert(document); } else { throw new Exception("Collection doesn't exist"); } return result.getLastError().ok(); } /* * Given a @collection and a DB Object @document, update it * * @document has and _id field, that is used to perform query of update */ public boolean updateDocumentById(String collection, BasicDBObject document) throws Exception { WriteResult result = null; BasicDBObject query = new BasicDBObject("_id",document.get("_id")); if (existsCollection(collection)){ DBCollection coll = mDb.getCollection(collection); result = coll.update(query, document); } else { throw new Exception("Collection doesn't exist"); } return result.getLastError().ok(); } /* * Given a @collection and a DB Object @document, delete it from database */ public boolean deleteDocumentById(String collection, BasicDBObject document) throws Exception { WriteResult result = null; if (existsCollection(collection)){ DBCollection coll = mDb.getCollection(collection); result = coll.remove(document); } else { throw new Exception("Collection doesn't exist"); } return result.getLastError().ok(); } /* * Given a @collection and a DB Object @document, delete it from database by @field and @value */ public boolean deleteDocumentByField(String collection, String field, String value) throws Exception{ BasicDBObject bdb = new BasicDBObject(); if (field.equals("_id")) { bdb.put(field, new ObjectId(value)); } else { bdb.put(field, value); } WriteResult result = null; if (existsCollection(collection)) { DBCollection coll = mDb.getCollection(collection); result = coll.remove(bdb); } else { throw new Exception("Collection doesn't exist"); } return result.getLastError().ok(); } /* * Given a @collection check if it exists */ public boolean existsCollection(String collection) throws Exception { try { if (mDb.collectionExists(collection)) { return true; } return false; } catch (Exception e) { throw e; } } public boolean deleteAllDocumentsByCollection(String collection) throws Exception { try { if (mDb.collectionExists(collection)){ DBCollection coll = mDb.getCollection(collection); coll.remove(new BasicDBObject()); return true; } } catch (Exception e) { throw e; } return false; } }
[ "ebls123@gmail.com" ]
ebls123@gmail.com
32a6435cea4fb5c3db706df0219f319231d51650
e3d7ccbc512c58fbe46bb58c8580e446b60675f0
/src/gamePanel.java
0ac1855df234d27ce89772660f2306dccf514ec6
[]
no_license
aliseyfi75/AP-Project
15e92cfe9bd52537f2fa715460f569985233f6dd
71cba419bff397d9838e4e03d2a4eebc73f99703
refs/heads/master
2020-05-04T20:36:29.367487
2019-04-09T11:18:48
2019-04-09T11:18:48
179,444,694
0
0
null
null
null
null
UTF-8
Java
false
false
616
java
import javax.swing.*; import java.awt.*; class gamePanel extends JPanel { private Image[] images; private int currentBG; gamePanel(Image image) { images = new Image[1]; images[0] = image; } gamePanel(Image[] images) { this.images = images; currentBG = 0; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); drawBG(g); } private void drawBG(Graphics g) { g.drawImage(images[currentBG], 0, 0, this); } void nextBG() { currentBG = (currentBG + 1) % images.length; } }
[ "ali.seyfi@tum.de" ]
ali.seyfi@tum.de
e1a68a00d99c4c2f087921207ae6920f870c886f
6a1cce3e73ea2819070d233f4f42351d07640bb0
/spl3/Server/src/main/java/bgu/spl/net/api/MessageEncoderDecoder.java
91495050044baf26378336820944effdf93e9411
[]
no_license
alijbareen/SPL-Systems_Programming_Assignments
a1b06e5b883ca95f94381028ae47af8d22acdaf5
149dad107200e06268a733eecf43846ef0b207d4
refs/heads/master
2022-12-15T04:24:09.911053
2020-09-08T11:15:32
2020-09-08T11:15:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
546
java
package bgu.spl.net.api; public interface MessageEncoderDecoder<T> { /** * add the next byte to the decoding process * * @param nextByte the next byte to consider for the currently decoded * message * @return a message if this byte completes one or null if it doesnt. */ T decodeNextByte(byte nextByte); /** * encodes the given message to bytes array * * @param message the message to encode * @return the encoded bytes */ byte[] encode(String message); }
[ "noreply@github.com" ]
alijbareen.noreply@github.com
d9f9b6caa2e0caa911c4c48a7b34a3f85a5b1e1e
ec8aa131e1067fe4f43d0cf37f7a0406bf4a7326
/src/main/java/com/supriyanta/interviewprep/service/EmailService.java
92fe0c676bb4d7ceb4282844e3582094524b4217
[]
no_license
adavijit/interview-prep
847cfdcd38829873860eb1ddc6b3a747e56fa010
4a6674ac196b0aee0215bdf3145fe03cfef8bbb7
refs/heads/master
2022-11-23T18:54:06.857992
2020-07-29T15:36:25
2020-07-29T15:36:25
284,116,205
0
0
null
2020-07-31T19:41:46
2020-07-31T19:41:46
null
UTF-8
Java
false
false
771
java
package com.supriyanta.interviewprep.service; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.MailMessage; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service @Slf4j public class EmailService { @Autowired private JavaMailSender mailSender; public void sendSimpleMail(SimpleMailMessage email) { try { mailSender.send(email); } catch (Exception exception) { log.warn(exception.toString()); // TODO: Create new Exception class throw new IllegalStateException("Error sending mail!"); } } }
[ "supriyanta34@gmail.com" ]
supriyanta34@gmail.com
4299dcb954e9002363e19f376991fa1da27aac95
d5959ae1bc2dd7b468193a2f32a191e42d1cd761
/src/main/java/com/feihuwang/pc/model/EntityItem.java
3986e2bf06ba0137d8a73d9cccfc5fe303b5bb8b
[]
no_license
liveqmock/ab_common_vo
55218f2b42268bcb7130bfd66f3d7bd8f0eff566
0a6f60dee5571ea2e7a55eb16a7cbe18f7affe31
refs/heads/master
2021-01-20T11:18:55.705321
2014-11-15T04:55:36
2014-11-15T04:55:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
148
java
package com.feihuwang.pc.model; import java.io.Serializable; public interface EntityItem extends Serializable { public Serializable getMyId(); }
[ "baoyinli@sohu-inc.com" ]
baoyinli@sohu-inc.com
e5efed34e106cf2bb7c4c4d75411da070d1f8114
963599f6f1f376ba94cbb504e8b324bcce5de7a3
/sources/p035ru/unicorn/ujin/view/fragments/makearecord/RecordRep.java
2b39999f4986e8217be998d7e88ebf4bf5dc3850
[]
no_license
NikiHard/cuddly-pancake
563718cb73fdc4b7b12c6233d9bf44f381dd6759
3a5aa80d25d12da08fd621dc3a15fbd536d0b3d4
refs/heads/main
2023-04-09T06:58:04.403056
2021-04-20T00:45:08
2021-04-20T00:45:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,143
java
package p035ru.unicorn.ujin.view.fragments.makearecord; import java.util.List; import kotlin.Metadata; import kotlin.jvm.internal.Intrinsics; import p035ru.unicorn.ujin.data.profile.repository.ProfileLocalRepository; import p035ru.unicorn.ujin.data.realm.Resource; import p035ru.unicorn.ujin.data.realm.profile.User; import p035ru.unicorn.ujin.data.repository.BaseRemoteRepository; import p035ru.unicorn.ujin.view.activity.navigation.repository.LocalRepository; import p035ru.unicorn.ujin.view.fragments.makearecord.model.Appointment; import p035ru.unicorn.ujin.view.fragments.makearecord.model.CreateRecordOut; import p035ru.unicorn.ujin.view.fragments.makearecord.model.ExecutorsIn; import p035ru.unicorn.ujin.view.fragments.makearecord.model.OpenDatesIn; import p035ru.unicorn.ujin.view.fragments.makearecord.model.RevokeIn; import p035ru.unicorn.ujin.view.fragments.makearecord.model.ScheduleListIn; import p046io.reactivex.Flowable; import p046io.reactivex.Observable; import p046io.reactivex.schedulers.Schedulers; import p046io.realm.RealmModel; @Metadata(mo51341bv = {1, 0, 3}, mo51342d1 = {"\u0000n\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0010\b\n\u0002\b\u0005\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u0002\n\u0002\b\u0002\n\u0002\u0010 \n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0004\b\u0016\u0018\u00002\u00020\u0001B\u0005¢\u0006\u0002\u0010\u0002J\u001a\u0010\u0011\u001a\u000e\u0012\n\u0012\b\u0012\u0004\u0012\u00020\u00140\u00130\u00122\u0006\u0010\u0015\u001a\u00020\fJ\u001a\u0010\u0016\u001a\u000e\u0012\n\u0012\b\u0012\u0004\u0012\u00020\u00170\u00130\u00122\u0006\u0010\u0018\u001a\u00020\u0019J\u000e\u0010\u001a\u001a\u00020\u001b2\u0006\u0010\u001c\u001a\u00020\fJ\u0012\u0010\u001d\u001a\u000e\u0012\n\u0012\b\u0012\u0004\u0012\u00020\u00170\u001e0\u0012J\u0012\u0010\u001f\u001a\u000e\u0012\n\u0012\b\u0012\u0004\u0012\u00020 0\u001e0\u0012J\u0006\u0010!\u001a\u00020\"J\u0018\u0010#\u001a\u0014\u0012\u0010\u0012\u000e\u0012\n\u0012\b\u0012\u0004\u0012\u00020$0\u001e0\u00130\u0012J\u001a\u0010%\u001a\u000e\u0012\n\u0012\b\u0012\u0004\u0012\u00020&0\u00130\u00122\u0006\u0010'\u001a\u00020(J\u0010\u0010)\u001a\u00020\u001b2\b\u0010*\u001a\u0004\u0018\u00010 J\u000e\u0010+\u001a\u00020\u001b2\u0006\u0010\u001c\u001a\u00020\fR\u0011\u0010\u0003\u001a\u00020\u0004¢\u0006\b\n\u0000\u001a\u0004\b\u0005\u0010\u0006R\u0011\u0010\u0007\u001a\u00020\b¢\u0006\b\n\u0000\u001a\u0004\b\t\u0010\nR\u001a\u0010\u000b\u001a\u00020\fX†\u000e¢\u0006\u000e\n\u0000\u001a\u0004\b\r\u0010\u000e\"\u0004\b\u000f\u0010\u0010¨\u0006,"}, mo51343d2 = {"Lru/unicorn/ujin/view/fragments/makearecord/RecordRep;", "Lru/unicorn/ujin/data/repository/BaseRemoteRepository;", "()V", "localRep", "Lru/unicorn/ujin/view/activity/navigation/repository/LocalRepository;", "getLocalRep", "()Lru/unicorn/ujin/view/activity/navigation/repository/LocalRepository;", "profileRep", "Lru/unicorn/ujin/data/profile/repository/ProfileLocalRepository;", "getProfileRep", "()Lru/unicorn/ujin/data/profile/repository/ProfileLocalRepository;", "toUserId", "", "getToUserId", "()I", "setToUserId", "(I)V", "cancelRecord", "Lio/reactivex/Observable;", "Lru/unicorn/ujin/data/realm/Resource;", "Lru/unicorn/ujin/view/fragments/makearecord/model/RevokeIn;", "recordId", "createRecord", "Lru/unicorn/ujin/view/fragments/makearecord/model/Appointment;", "record", "Lru/unicorn/ujin/view/fragments/makearecord/model/CreateRecordOut;", "deleteRecordLocally", "", "id", "getAllRecords", "", "getExecutorsList", "Lru/unicorn/ujin/view/fragments/makearecord/model/ExecutorsIn;", "getUserInfo", "Lru/unicorn/ujin/data/realm/profile/User;", "loadAvailableDatesByExecutorId", "Lru/unicorn/ujin/view/fragments/makearecord/model/OpenDatesIn;", "loadSchedule", "Lru/unicorn/ujin/view/fragments/makearecord/model/ScheduleListIn;", "date", "", "setExecutor", "executor", "setUserId", "app_kortrosRelease"}, mo51344k = 1, mo51345mv = {1, 4, 1}) /* renamed from: ru.unicorn.ujin.view.fragments.makearecord.RecordRep */ /* compiled from: RecordRep.kt */ public class RecordRep extends BaseRemoteRepository { private final LocalRepository localRep; private final ProfileLocalRepository profileRep = ProfileLocalRepository.Companion.getInstance(); private int toUserId; public RecordRep() { LocalRepository instance = LocalRepository.getInstance(); Intrinsics.checkNotNullExpressionValue(instance, "LocalRepository.getInstance()"); this.localRep = instance; } public final LocalRepository getLocalRep() { return this.localRep; } public final ProfileLocalRepository getProfileRep() { return this.profileRep; } public final int getToUserId() { return this.toUserId; } public final void setToUserId(int i) { this.toUserId = i; } public final void setUserId(int i) { this.toUserId = i; } /* JADX WARNING: Code restructure failed: missing block: B:1:0x0002, code lost: r1 = r1.getId(); */ /* Code decompiled incorrectly, please refer to instructions dump. */ public final void setExecutor(p035ru.unicorn.ujin.view.fragments.makearecord.model.ExecutorsIn r1) { /* r0 = this; if (r1 == 0) goto L_0x000d java.lang.Integer r1 = r1.getId() if (r1 == 0) goto L_0x000d int r1 = r1.intValue() goto L_0x000e L_0x000d: r1 = -1 L_0x000e: r0.setUserId(r1) return */ throw new UnsupportedOperationException("Method not decompiled: p035ru.unicorn.ujin.view.fragments.makearecord.RecordRep.setExecutor(ru.unicorn.ujin.view.fragments.makearecord.model.ExecutorsIn):void"); } public final Observable<List<Appointment>> getAllRecords() { Flowable<List<U>> flowable = this.localRep.getDataSortedByField(Appointment.class, "id").filter(RecordRep$getAllRecords$localData$1.INSTANCE).flatMapIterable(RecordRep$getAllRecords$localData$2.INSTANCE).cast(Appointment.class).toList().toFlowable(); Intrinsics.checkNotNullExpressionValue(flowable, "localRep.getDataSortedBy… .toFlowable()"); Observable<List<U>> subscribeOn = flowable.toObservable().mergeWith(getApi().getAllRecords(getToken()).map(RecordRep$getAllRecords$remoteData$1.INSTANCE).filter(RecordRep$getAllRecords$remoteData$2.INSTANCE).doOnNext(new RecordRep$getAllRecords$remoteData$3(this)).onErrorReturn(RecordRep$getAllRecords$remoteData$4.INSTANCE).filter(RecordRep$getAllRecords$1.INSTANCE)).subscribeOn(Schedulers.m6765io()); Intrinsics.checkNotNullExpressionValue(subscribeOn, "localData.toObservable()…scribeOn(Schedulers.io())"); return subscribeOn; } public final User getUserInfo() { return this.profileRep.getUser(); } public final Observable<List<ExecutorsIn>> getExecutorsList() { Observable<List<? extends RealmModel>> observable = this.localRep.getData(ExecutorsIn.class).toObservable(); if (observable != null) { Observable<R> onErrorResumeNext = getApi().getExecutors(getToken()).map(RecordRep$getExecutorsList$remoteData$1.INSTANCE).doOnNext(new RecordRep$getExecutorsList$remoteData$2(this)).onErrorResumeNext(observable); Intrinsics.checkNotNullExpressionValue(onErrorResumeNext, "api.getExecutors(getToke…rrorResumeNext(localData)"); Observable<R> concatMap = observable.concatMap(new RecordRep$getExecutorsList$1(onErrorResumeNext)); Intrinsics.checkNotNullExpressionValue(concatMap, "localData\n .concatMap {remoteData}"); return concatMap; } throw new NullPointerException("null cannot be cast to non-null type io.reactivex.Observable<kotlin.collections.List<ru.unicorn.ujin.view.fragments.makearecord.model.ExecutorsIn>>"); } public final Observable<Resource<ScheduleListIn>> loadSchedule(String str) { Intrinsics.checkNotNullParameter(str, "date"); Observable<R> onErrorReturn = getApi().loadScheduleForExecutor(getToken(), this.toUserId, str).map(RecordRep$loadSchedule$1.INSTANCE).onErrorReturn(RecordRep$loadSchedule$2.INSTANCE); Intrinsics.checkNotNullExpressionValue(onErrorReturn, "api.loadScheduleForExecu…source.error(t.message) }"); return onErrorReturn; } public final Observable<Resource<List<OpenDatesIn>>> loadAvailableDatesByExecutorId() { Observable<R> onErrorReturn = getApi().loadOpenDatesForExecutor(getToken(), this.toUserId).map(RecordRep$loadAvailableDatesByExecutorId$1.INSTANCE).onErrorReturn(RecordRep$loadAvailableDatesByExecutorId$2.INSTANCE); Intrinsics.checkNotNullExpressionValue(onErrorReturn, "api.loadOpenDatesForExec…source.error(t.message) }"); return onErrorReturn; } public final Observable<Resource<Appointment>> createRecord(CreateRecordOut createRecordOut) { Intrinsics.checkNotNullParameter(createRecordOut, "record"); Observable<R> onErrorReturn = getApi().makeAppoinment(getToken(), createRecordOut).map(RecordRep$createRecord$1.INSTANCE).onErrorReturn(RecordRep$createRecord$2.INSTANCE); Intrinsics.checkNotNullExpressionValue(onErrorReturn, "api.makeAppoinment(getTo…source.error(t.message) }"); return onErrorReturn; } public final Observable<Resource<RevokeIn>> cancelRecord(int i) { Observable<R> onErrorReturn = getApi().revokeRecord(getToken(), i).map(RecordRep$cancelRecord$1.INSTANCE).onErrorReturn(RecordRep$cancelRecord$2.INSTANCE); Intrinsics.checkNotNullExpressionValue(onErrorReturn, "api.revokeRecord(getToke…source.error(t.message) }"); return onErrorReturn; } public final void deleteRecordLocally(int i) { this.localRep.deleteById(Appointment.class, "id", i); } }
[ "a.amirovv@mail.ru" ]
a.amirovv@mail.ru
c755e183be2cffd08f80cd0d9a4c4950c90d34f0
9412557f4c471960067c0ae1929d009322f8158b
/brightcove-exoplayer/OfflinePlaybackSampleApp/src/main/java/com/brightcove/player/samples/offlineplayback/VideoListAdapter.java
05ea0a67b70187c4adaf524b07ec36310b3958e1
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
rahulyhg/android-player-samples
86d35ab34f199092772e9d6daea02f8a1b90c297
6f8609573fa306fc9b492f74f12e96d950f2f4a8
refs/heads/master
2021-04-30T05:49:28.407786
2018-02-12T18:39:39
2018-02-12T18:40:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
17,229
java
package com.brightcove.player.samples.offlineplayback; import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.widget.ContentLoadingProgressBar; import android.support.v7.widget.RecyclerView; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.brightcove.player.edge.OfflineCatalog; import com.brightcove.player.model.Video; import com.brightcove.player.network.DownloadStatus; import com.brightcove.player.samples.offlineplayback.utils.ViewUtil; import com.squareup.picasso.Picasso; import java.net.URI; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Video list adapter can be used to show a list of videos on a {@link RecyclerView}. */ public class VideoListAdapter extends RecyclerView.Adapter<VideoListAdapter.ViewHolder> { /** * The current list of videos. */ private List<Video> videoList; /** * A map of video identifiers and position of video in the list. */ private Map<String, Integer> indexMap = new HashMap<>(); /** * A view holder that hold references to the UI components in a list item. */ public class ViewHolder extends RecyclerView.ViewHolder { /** * Reference the item view context */ public final Context context; /** * Reference to the thumbnail image view. */ public final ImageView videoThumbnailImage; /** * Reference to the video title view. */ public final TextView videoTitleText; /** * Reference to the video status information text view. */ public final TextView videoStatusText; /** * Reference to the video license information text view. */ public final TextView videoLicenseText; /** * Reference to the video duration view. */ public final TextView videoDurationText; /** * Reference to the rent video button. */ public final Button rentButton; /** * Reference to the buy video button. */ public final Button buyButton; /** * Reference to the download video button. */ public final ImageButton downloadButton; /** * Reference to the delete video button. */ public final ImageButton deleteButton; /** * Reference to the download progress bar. */ public final ContentLoadingProgressBar downloadProgressBar; /** * The currently linked video. */ public Video video; /** * Constructs a new view holder for the given item view. * * @param itemView reference to the item. */ public ViewHolder(@NonNull View itemView) { super(itemView); context = itemView.getContext(); videoThumbnailImage = ViewUtil.findView(itemView, R.id.video_thumbnail_image); videoTitleText = ViewUtil.findView(itemView, R.id.video_title_text); videoStatusText = ViewUtil.findView(itemView, R.id.video_status_text); videoLicenseText = ViewUtil.findView(itemView, R.id.video_license_text); videoDurationText = ViewUtil.findView(itemView, R.id.video_duration_text); rentButton = ViewUtil.findView(itemView, R.id.rent_button); buyButton = ViewUtil.findView(itemView, R.id.buy_button); downloadButton = ViewUtil.findView(itemView, R.id.download_button); deleteButton = ViewUtil.findView(itemView, R.id.delete_button); downloadProgressBar = ViewUtil.findView(itemView, R.id.download_progress_bar); downloadProgressBar.getProgressDrawable().setColorFilter(Color.DKGRAY, PorterDuff.Mode.SRC_IN); } @NonNull public Video getVideo() { Video result = video; if (video.isOfflinePlaybackAllowed()) { Video offlineVideo = catalog.findOfflineVideoById(video.getId()); if (offlineVideo != null) { result = offlineVideo; } } return result; } } /** * The catalog where the video in this list can be found. */ private final OfflineCatalog catalog; /** * The listener that can handle user interactions on a video item display. */ private final VideoListListener listener; /** * Constructors a new video list adapter. * * @param catalog reference to the offline catalog. * @param listener reference to a listener * @throws IllegalArgumentException if the catalog or listener is null. */ public VideoListAdapter(@NonNull OfflineCatalog catalog, @NonNull VideoListListener listener) { if (listener == catalog) { throw new IllegalArgumentException("Catalog is null!"); } if (listener == null) { throw new IllegalArgumentException("Video list listener is null!"); } this.catalog = catalog; this.listener = listener; } /** * Sets the list of videos to be shown. If this value is null, then the list will be empty. * * @param videoList list of {@link Video} objects. */ public void setVideoList(@Nullable List<Video> videoList) { this.videoList = videoList; buildIndexMap(); } /** * Build the index map. */ private void buildIndexMap() { indexMap.clear(); if (videoList != null) { int index = 0; for (Video video : videoList) { indexMap.put(video.getId(), index++); } } notifyDataSetChanged(); } /** * Causes item display for the specified video to be updated. * * @param video the video that changed */ public void notifyVideoChanged(@NonNull Video video) { notifyVideoChanged(video, null); } /** * Causes item display for the specified video to be updated. * * @param video the video that changed * @param status optional current download status. */ public void notifyVideoChanged(@NonNull Video video, @Nullable DownloadStatus status) { String videoId = video.getId(); if (indexMap.containsKey(videoId)) { int index = indexMap.get(videoId); videoList.set(index, video); notifyItemChanged(index, status); } } /** * Removes a video from the list. * * @param video the video to be removed. */ public void removeVideo(Video video) { String videoId = video.getId(); if (indexMap.containsKey(videoId)) { int index = indexMap.remove(videoId); videoList.remove(index); buildIndexMap(); } } /** * The current list of {@link Video} objects. * * @return null or a list of list of {@link Video} objects. */ @Nullable public List<Video> getVideoList() { return videoList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_item_view, parent, false); return new ViewHolder(view); } /** * Updates the row at the given position to reflect the changes in the underlying data. * * @param holder reference to the view holder. * @param position the position of the row that should be updated. * @param status optional current download status. */ public void updateView(@NonNull final ViewHolder holder, int position, @Nullable DownloadStatus status) { holder.video = videoList.get(position); final Video video = holder.getVideo(); if (video.isOfflinePlaybackAllowed()) { final Date expiryDate = video.getLicenseExpiryDate(); if (expiryDate == null) { holder.videoLicenseText.setText("Buy or rent for offline playback"); holder.videoStatusText.setVisibility(View.GONE); holder.rentButton.setVisibility(View.VISIBLE); holder.buyButton.setVisibility(View.VISIBLE); holder.deleteButton.setVisibility(View.GONE); holder.downloadButton.setVisibility(View.GONE); holder.downloadProgressBar.setVisibility(View.GONE); } else { holder.rentButton.setVisibility(View.GONE); holder.buyButton.setVisibility(View.GONE); if (video.isOwned()) { holder.videoLicenseText.setText("Owned"); } else { holder.videoLicenseText.setText(String.format("Rental Expires: %s %s", DateFormat.getMediumDateFormat(holder.context).format(expiryDate), DateFormat.getTimeFormat(holder.context).format(expiryDate))); } if (status == null) { holder.videoStatusText.setText("Checking download status..."); holder.videoStatusText.setVisibility(View.VISIBLE); holder.deleteButton.setVisibility(View.GONE); holder.downloadButton.setVisibility(View.GONE); holder.downloadProgressBar.setVisibility(View.GONE); new Thread(new Runnable() { @Override public void run() { final DownloadStatus status = catalog.getVideoDownloadStatus(holder.video); holder.itemView.post(new Runnable() { @Override public void run() { updateDownloadStatus(holder, status); } }); } }).start(); } else { updateDownloadStatus(holder, status); } } } else { holder.videoLicenseText.setVisibility(View.GONE); holder.videoStatusText.setText("Online Only"); holder.videoStatusText.setVisibility(View.VISIBLE); holder.rentButton.setVisibility(View.GONE); holder.buyButton.setVisibility(View.GONE); holder.downloadButton.setVisibility(View.GONE); holder.deleteButton.setVisibility(View.GONE); holder.downloadProgressBar.setVisibility(View.GONE); } holder.videoTitleText.setText(video.getName()); URI imageUri = video.getStillImageUri(); if (imageUri == null) { holder.videoThumbnailImage.setImageResource(R.drawable.movie); } else { Picasso.with(holder.context).load(imageUri.toASCIIString()).into(holder.videoThumbnailImage); } int duration = video.getDuration(); if (duration > 0) { holder.videoDurationText.setText(millisecondsToString(duration)); holder.videoDurationText.setVisibility(View.VISIBLE); } else { holder.videoDurationText.setText(null); holder.videoDurationText.setVisibility(View.GONE); } } /** * Updates the view held by the specified holder with the current status of the download. * * @param holder reference to the view holder. * @param status optional current download status. */ private void updateDownloadStatus(@NonNull ViewHolder holder, DownloadStatus status) { int statusCode = status.getCode(); if (statusCode == DownloadStatus.STATUS_NOT_QUEUED) { holder.videoStatusText.setText("Press download to save video"); holder.downloadButton.setVisibility(View.VISIBLE); holder.downloadProgressBar.setVisibility(View.GONE); } else { holder.videoStatusText.setText(status.getStatusMessage()); holder.downloadButton.setVisibility(View.GONE); if (statusCode == DownloadStatus.STATUS_DOWNLOADING) { holder.downloadProgressBar.setVisibility(View.VISIBLE); holder.downloadProgressBar.setProgress((int) status.getProgress()); } else { holder.downloadProgressBar.setVisibility(View.GONE); if (statusCode == DownloadStatus.STATUS_DELETING) { holder.videoLicenseText.setVisibility(View.GONE); holder.rentButton.setVisibility(View.GONE); holder.buyButton.setVisibility(View.GONE); holder.downloadButton.setVisibility(View.GONE); holder.deleteButton.setVisibility(View.GONE); } } } holder.videoStatusText.setVisibility(View.VISIBLE); holder.deleteButton.setVisibility(View.VISIBLE); } @Override public void onBindViewHolder(final ViewHolder holder, int position, List<Object> payloads) { if (payloads.size() == 0) { super.onBindViewHolder(holder, position, payloads); } else { updateView(holder, position, (DownloadStatus) payloads.get(0)); } } @Override public void onBindViewHolder(final ViewHolder holder, int position) { updateView(holder, position, null); // Setup listeners to handle user interactions holder.videoThumbnailImage.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { boolean consumed = false; if (event.getAction() == MotionEvent.ACTION_DOWN) { consumed = true; } if(event.getAction() == MotionEvent.ACTION_UP) { listener.playVideo(holder.getVideo()); consumed = true; } return consumed; } }); holder.rentButton.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { listener.rentVideo(holder.video); } return false; } }); holder.buyButton.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { listener.buyVideo(holder.video); } return false; } }); holder.downloadButton.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { listener.downloadVideo(holder.video); } return false; } }); holder.deleteButton.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { holder.videoStatusText.setText("Deleting video..."); listener.deleteVideo(holder.video); } return false; } }); } @Override public int getItemCount() { return videoList == null ? 0 : videoList.size(); } /** * Converts the given duration into a time span string. * * @param duration elapsed time as number of milliseconds. * @return the formatted time span string. */ @NonNull public static String millisecondsToString(long duration) { final TimeUnit scale = TimeUnit.MILLISECONDS; StringBuilder builder = new StringBuilder(); long days = scale.toDays(duration); duration -= TimeUnit.DAYS.toMillis(days); if (days > 0) { builder.append(days); builder.append(days > 1 ? " days " : " day "); } long hours = scale.toHours(duration); duration -= TimeUnit.HOURS.toMillis(hours); if (hours > 0) { builder.append(String.format("%02d:", hours)); } long minutes = scale.toMinutes(duration); duration -= TimeUnit.MINUTES.toMillis(minutes); long seconds = scale.toSeconds(duration); builder.append(String.format("%02d:%02d", minutes, seconds)); return builder.toString(); } }
[ "smartinez@brightcove.com" ]
smartinez@brightcove.com
fab561a3b071803f4bdaae81c0ba91a27bdc632f
47b6b002d64c170a1978457cf43edb9098f76b43
/atcrowdfunding-bean/src/main/java/com/gentle/atcrowdfunding/bean/TRole.java
4cd91261873544b8f2fe68c00c01aa8534f4687b
[]
no_license
gentleBreezeX/SCW
7b21afa87988777b8477e68b09b6cf1360b52cc8
c9bd89274a22db38c9a834a3c7767a3be79d6ada
refs/heads/master
2022-12-22T06:41:58.098517
2019-12-28T14:25:35
2019-12-28T14:25:35
230,618,589
0
0
null
2022-12-16T11:54:46
2019-12-28T14:11:07
JavaScript
UTF-8
Java
false
false
515
java
package com.gentle.atcrowdfunding.bean; public class TRole { private Integer id; private String name; @Override public String toString() { return "TRole [id=" + id + ", name=" + name + "]"; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } }
[ "819974025@qq.com" ]
819974025@qq.com
41103d54035516c4a625cc1b539f0f64c759a08a
9eebd3dd3b5ca0400c7f8ff96eff82c6a4f2c27d
/elasticSearch6.4.3/src/main/java/com/example/demo/service/SchoolService.java
6579ec3114eb9cea7d60ceb498ee353f5cbba23b
[]
no_license
zhangcc1988/ES-DEMO
8d6b304e596f5366403c1289971a28c330ec00ba
3f921c6d38b78327071cd5d521cad595fa962770
refs/heads/master
2023-04-03T04:38:44.488563
2020-12-17T09:57:24
2020-12-17T09:57:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
414
java
package com.example.demo.service; import com.example.demo.document.School; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; /** * created by zc 2020/11/18 13:52 */ public interface SchoolService { School getById(String id); Page<School> listSchool(PageRequest pageRequest); void removeSchoolById(String id); School save(School school); }
[ "1277188108@qq.com" ]
1277188108@qq.com
43cc4dfda6418423b55c4fee8468ddd7ca57ca45
493c0966537c4d48ea05324c2d00f0602061b146
/src/main/java/app/dao/interfaces/DAO.java
3d4c539c5c795e09e79bf396aa88830ecc3c8048
[]
no_license
VGolomoz/NewsParserTestTask
192e3b482c3e28ab34fc37a8ca9e3701f77b08c3
b0d06e3bb7bdce3b041e2e5465f7a42feb013f14
refs/heads/master
2022-09-17T22:37:39.550491
2019-12-15T10:30:41
2019-12-15T10:30:41
227,050,383
0
0
null
null
null
null
UTF-8
Java
false
false
172
java
package app.dao.interfaces; public interface DAO<T> extends AutoCloseable { Boolean create(T entity); Boolean delete(Long id); @Override void close(); }
[ "gworkout@ukr.net" ]
gworkout@ukr.net
c59b528079fa2b059c5e7d1c01fe01215e83df71
093858efe851bd3919fc3986a8edec317e81d816
/unittests/UnitTest_GetAvailableBalance.java
de22197fdf566137acbc5d3e9d3f5bdda1a21582
[ "MIT" ]
permissive
bdrhoa/TangoCard_Java_SDK
30a65e0ff8818c18f7d4bd18043ee78ba36990e0
268b954896121f8f646650f1e1ddd5c9816c6b92
refs/heads/master
2020-04-11T09:12:00.737574
2012-12-02T07:08:38
2012-12-02T07:08:38
7,290,916
1
1
null
null
null
null
UTF-8
Java
false
false
5,555
java
/** * * UnitTest_GetAvailableBalance.java * TangoCard_Java_SDK * * Tango Card SDK JUnit Test * * Copyright (c) 2012 Tango Card, Inc * All rights reserved. * * 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. */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Properties; import tangocard.sdk.TangoCardServiceApi; import tangocard.sdk.common.TangoCardSdkException; import tangocard.sdk.response.ServiceResponseEnum; import tangocard.sdk.response.success.GetAvailableBalanceResponse; import tangocard.sdk.service.TangoCardServiceApiEnum; import tangocard.sdk.service.TangoCardServiceException; import junit.framework.TestCase; /** * The Class UnitTest_GetAvailableBalance. */ public class UnitTest_GetAvailableBalance extends TestCase { public static void main(String args[]) { } /** The _app_username. */ private String _app_username = null; /** The _app_password. */ private String _app_password = null; /** The _enum Tango Card service api. */ private TangoCardServiceApiEnum _enumTangoCardServiceApi = TangoCardServiceApiEnum.UNDEFINED; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() { Properties prop = new Properties(); try { prop.load(new FileInputStream("config/app_config.properties")); } catch ( FileNotFoundException ex ) { TestCase.fail("FileNotFoundException: " + ex.getMessage()); } catch ( Exception ex ) { TestCase.fail("Exception: " + ex.getMessage()); } this._app_username = prop.getProperty("app_username"); this._app_password = prop.getProperty("app_password"); String app_tango_card_service_api = prop.getProperty("app_tango_card_service_api"); this._enumTangoCardServiceApi = TangoCardServiceApiEnum.valueOf(app_tango_card_service_api); } /** * Instantiates a new unit test_ get available balance. * * @param method the method */ public UnitTest_GetAvailableBalance(String method) { super(method); } /** * Test get available balance. */ public void test_GetAvailableBalance() { boolean isSuccess = false; GetAvailableBalanceResponse responseAvailableBalance = new GetAvailableBalanceResponse(); try { isSuccess = TangoCardServiceApi.GetAvailableBalance( this._enumTangoCardServiceApi, this._app_username, this._app_password, responseAvailableBalance ); } catch (TangoCardServiceException ex) { TestCase.fail("TangoCardServiceException: " + ex.getMessage()); } catch (TangoCardSdkException ex) { TestCase.fail("TangoCardSdkException: " + ex.getMessage()); } catch (Exception ex) { TestCase.fail("Exception: " + ex.getMessage()); } TestCase.assertTrue(isSuccess); TestCase.assertNotNull(responseAvailableBalance); int tango_cents_available_balance = responseAvailableBalance.getAvailableBalance(); TestCase.assertTrue(tango_cents_available_balance >= 100); } /** * Test_ get available balance_ invalid credentials. */ public void test_GetAvailableBalance_InvalidCredentials() { String username = "burt@example.com"; String password = "password"; boolean isSuccess = false; GetAvailableBalanceResponse responseAvailableBalance = new GetAvailableBalanceResponse(); try { isSuccess = TangoCardServiceApi.GetAvailableBalance( this._enumTangoCardServiceApi, username, password, responseAvailableBalance ); TestCase.fail("Expected 'TangoCardServiceException' to be thrown"); } catch (TangoCardServiceException ex) { TestCase.assertTrue( ex.getResponseType().equals(ServiceResponseEnum.INV_CREDENTIAL.toString()) ); } catch (TangoCardSdkException ex) { TestCase.fail("TangoCardSdkException: " + ex.getMessage()); } catch (Exception ex) { TestCase.fail("Exception: " + ex.getMessage()); } TestCase.assertFalse(isSuccess); } }
[ "jeff@tangocard.com" ]
jeff@tangocard.com
8d243a2ccd6854825d60fcebbac511968a9caffe
fad219ceac0faf4e405469345970245f7f85103a
/Proof of life/Android/Code/app/src/main/java/com/proofofLife/Encryption/EncryptionHelper.java
97ed80b4df55afb7d1a30c41798e3b06508bb2ec
[]
no_license
VinayTShetty/ProjectsWorked_2019-2021
f092e8b01e1707c82058acad572a6bfce77421d7
70c80b9ad681b099c6de9a718e103d362e9f453d
refs/heads/main
2023-06-02T17:26:34.669354
2021-06-26T02:06:23
2021-06-26T02:06:23
380,391,756
0
0
null
null
null
null
UTF-8
Java
false
false
2,057
java
package com.proofofLife.Encryption; import android.util.Base64; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; public class EncryptionHelper { // private static final byte[] KeyBytes = {0x39, 0x55, 0x17, 0x12, 0x13, (byte) 0x88, (byte) 0x98, 0x47, (byte) 0x90, 0x08, 0x49, 0x21, 0x12, (byte) 0xd4, 0x11, 0x29}; private static final byte[] KeyBytes ={ 0x3A, 0x09, 0x44, 0x62, (byte) 0xFD, 0x62, 0x10, (byte) 0xCD, (byte) 0xE8, 0x74, 0x42, (byte) 0xCA, (byte)0xA9, (byte)0xD7, 0x18, (byte)0xF9 }; public static byte[] decryptData(byte[] encryptedData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // Decrypt the text // Create key and cipher Key aesKey = new SecretKeySpec(KeyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); // Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding ");//PKCS5Padding cipher.init(Cipher.DECRYPT_MODE, aesKey); byte[] decrypted = cipher.doFinal(encryptedData); // byte[] decrypted = cipher.doFinal(Base64.decode(new String(encryptedData, StandardCharsets.UTF_8), Base64.NO_WRAP)); return decrypted; } public static byte[] encryptData(byte[] inputData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // Create key and cipher Key aesKey = new SecretKeySpec(KeyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); // AES/ECB/NoPadding // AES/CBC/PKCS5Padding // encrypt the text cipher.init(Cipher.ENCRYPT_MODE, aesKey); byte[] encrypted = cipher.doFinal(inputData); return encrypted; } }
[ "vinay@succorfish.com" ]
vinay@succorfish.com
6294dad5052c9a36519ca1032555ff744db3f9a4
6e2afe29a13cddd79680b49662c636a42da2cd93
/service-feign/src/main/java/com/zzp/HelloController.java
07aea97996375eb9e9194f7a4c455d9fbc9ba864
[]
no_license
angryz/spring-cloud-practice
d4e3f52306c9321fd824b3f9e2996dc2e9966777
8c583bbfa5a2fe45dcbac11fb4694ccbe8145387
refs/heads/master
2021-01-19T11:58:06.521256
2017-04-12T06:28:21
2017-04-12T06:28:21
88,006,957
0
0
null
null
null
null
UTF-8
Java
false
false
667
java
package com.zzp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author Zheng Zhipeng */ @RestController public class HelloController { @Autowired SchedualServiceHelllo schedualServiceHelllo; @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello(@RequestParam String name) { return schedualServiceHelllo.sayHiFromClientOne(name); } }
[ "angryzorro@gmail.com" ]
angryzorro@gmail.com
18705ea0b93bc78c2361f0ec4be2415940503d87
c10766ea8ffa040cb2f088ad573f32fc6640076e
/demos/GUI/JPaintShaderDemos/TestDrawingView/gen/org/lamw/testdrawingview/BuildConfig.java
1c7c49a38bd9aeb0a1494646255fc6742fd2570c
[]
no_license
dev-cristianobarbosa/lazandroidmodulewizard
a557ded8c8884151652b8b9a37ebd83abcf1a946
702d198f273df21c348241414c980ccc56a513ee
refs/heads/master
2022-06-23T04:23:27.995672
2020-05-06T17:14:49
2020-05-06T17:14:49
261,815,421
1
1
null
2020-05-06T16:21:36
2020-05-06T16:21:36
null
UTF-8
Java
false
false
166
java
/** Automatically generated file. DO NOT MODIFY */ package org.lamw.testdrawingview; public final class BuildConfig { public final static boolean DEBUG = true; }
[ "jmpessoa_hotmail.com" ]
jmpessoa_hotmail.com
2e41b9e7d12b926e69444dbf35a96f55a929f90c
8e35269d128fd6655d52ad1a378dce669ae7de3c
/src/main/java/edu/fiuba/algo3/controlador/Test.java
f7b5660202924c4acaa26864027142c4b2885eab
[ "MIT" ]
permissive
seblaz/DungeonCards
7928b572eec6efffc85db97b8007833c68f47c41
d1b99a6ac9961e234a302c451ddc2be3e56ac3cc
refs/heads/master
2023-07-29T19:19:00.737860
2021-09-05T18:03:58
2021-09-05T18:03:58
379,449,241
0
0
null
null
null
null
UTF-8
Java
false
false
60
java
package edu.fiuba.algo3.controlador; public class Test { }
[ "sebastian.blazquez96@gmail.com" ]
sebastian.blazquez96@gmail.com
4fb951b55f70585d00bd9016c0f544d0b8e6c2ae
bbffb4dee4fd8e5b9b0e985369d2c12bf47853d8
/Stranicenje/src/hr/java/stranicenje/entiteti/Stranica.java
23bebf101b9bf5d18cf7030849fadb177320dbfb
[]
no_license
kzdelarec/JavaProjects
367edc7a18a98b979383ba8df29faf1c1cc28b4b
df00b62b6fc2a22d85f28fbc4c68405acbfb4430
refs/heads/master
2022-01-23T00:26:52.729255
2019-11-26T17:02:10
2019-11-26T17:02:10
152,137,823
0
0
null
2022-01-21T23:22:18
2018-10-08T19:53:40
HTML
UTF-8
Java
false
false
743
java
package hr.java.stranicenje.entiteti; public class Stranica { Integer korak; Integer ulaz; String sto; String izlaz; String memorija; public Integer getKorak() { return korak; } public void setKorak(Integer korak) { this.korak = korak; } public Integer getUlaz() { return ulaz; } public void setUlaz(Integer ulaz) { this.ulaz = ulaz; } public String getSto() { return sto; } public void setSto(String sto) { this.sto = sto; } public String getIzlaz() { return izlaz; } public void setIzlaz(String izlaz) { this.izlaz = izlaz; } public String getMemorija() { return memorija; } public void setMemorija(String memorija) { this.memorija = memorija; } }
[ "Kiki@Kristijan" ]
Kiki@Kristijan
bdc3c457e791c5942d044e57a731c86ced9a02bc
12b14b30fcaf3da3f6e9dc3cb3e717346a35870a
/examples/commons-math3/mutations/mutants-Dfp/2519/org/apache/commons/math3/dfp/Dfp.java
a8d8795efea3d9e36b287cfa86be0c83cc4713f6
[ "BSD-3-Clause", "Minpack", "Apache-2.0" ]
permissive
SmartTests/smartTest
b1de326998857e715dcd5075ee322482e4b34fb6
b30e8ec7d571e83e9f38cd003476a6842c06ef39
refs/heads/main
2023-01-03T01:27:05.262904
2020-10-27T20:24:48
2020-10-27T20:24:48
305,502,060
0
0
null
null
null
null
UTF-8
Java
false
false
85,772
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.dfp; import java.util.Arrays; import org.apache.commons.math3.RealFieldElement; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.util.FastMath; /** * Decimal floating point library for Java * * <p>Another floating point class. This one is built using radix 10000 * which is 10<sup>4</sup>, so its almost decimal.</p> * * <p>The design goals here are: * <ol> * <li>Decimal math, or close to it</li> * <li>Settable precision (but no mix between numbers using different settings)</li> * <li>Portability. Code should be kept as portable as possible.</li> * <li>Performance</li> * <li>Accuracy - Results should always be +/- 1 ULP for basic * algebraic operation</li> * <li>Comply with IEEE 854-1987 as much as possible. * (See IEEE 854-1987 notes below)</li> * </ol></p> * * <p>Trade offs: * <ol> * <li>Memory foot print. I'm using more memory than necessary to * represent numbers to get better performance.</li> * <li>Digits are bigger, so rounding is a greater loss. So, if you * really need 12 decimal digits, better use 4 base 10000 digits * there can be one partially filled.</li> * </ol></p> * * <p>Numbers are represented in the following form: * <pre> * n = sign &times; mant &times; (radix)<sup>exp</sup>;</p> * </pre> * where sign is &plusmn;1, mantissa represents a fractional number between * zero and one. mant[0] is the least significant digit. * exp is in the range of -32767 to 32768</p> * * <p>IEEE 854-1987 Notes and differences</p> * * <p>IEEE 854 requires the radix to be either 2 or 10. The radix here is * 10000, so that requirement is not met, but it is possible that a * subclassed can be made to make it behave as a radix 10 * number. It is my opinion that if it looks and behaves as a radix * 10 number then it is one and that requirement would be met.</p> * * <p>The radix of 10000 was chosen because it should be faster to operate * on 4 decimal digits at once instead of one at a time. Radix 10 behavior * can be realized by adding an additional rounding step to ensure that * the number of decimal digits represented is constant.</p> * * <p>The IEEE standard specifically leaves out internal data encoding, * so it is reasonable to conclude that such a subclass of this radix * 10000 system is merely an encoding of a radix 10 system.</p> * * <p>IEEE 854 also specifies the existence of "sub-normal" numbers. This * class does not contain any such entities. The most significant radix * 10000 digit is always non-zero. Instead, we support "gradual underflow" * by raising the underflow flag for numbers less with exponent less than * expMin, but don't flush to zero until the exponent reaches MIN_EXP-digits. * Thus the smallest number we can represent would be: * 1E(-(MIN_EXP-digits-1)*4), eg, for digits=5, MIN_EXP=-32767, that would * be 1e-131092.</p> * * <p>IEEE 854 defines that the implied radix point lies just to the right * of the most significant digit and to the left of the remaining digits. * This implementation puts the implied radix point to the left of all * digits including the most significant one. The most significant digit * here is the one just to the right of the radix point. This is a fine * detail and is really only a matter of definition. Any side effects of * this can be rendered invisible by a subclass.</p> * @see DfpField * @version $Id$ * @since 2.2 */ public class Dfp implements RealFieldElement<Dfp> { /** The radix, or base of this system. Set to 10000 */ public static final int RADIX = 10000; /** The minimum exponent before underflow is signaled. Flush to zero * occurs at minExp-DIGITS */ public static final int MIN_EXP = -32767; /** The maximum exponent before overflow is signaled and results flushed * to infinity */ public static final int MAX_EXP = 32768; /** The amount under/overflows are scaled by before going to trap handler */ public static final int ERR_SCALE = 32760; /** Indicator value for normal finite numbers. */ public static final byte FINITE = 0; /** Indicator value for Infinity. */ public static final byte INFINITE = 1; /** Indicator value for signaling NaN. */ public static final byte SNAN = 2; /** Indicator value for quiet NaN. */ public static final byte QNAN = 3; /** String for NaN representation. */ private static final String NAN_STRING = "NaN"; /** String for positive infinity representation. */ private static final String POS_INFINITY_STRING = "Infinity"; /** String for negative infinity representation. */ private static final String NEG_INFINITY_STRING = "-Infinity"; /** Name for traps triggered by addition. */ private static final String ADD_TRAP = "add"; /** Name for traps triggered by multiplication. */ private static final String MULTIPLY_TRAP = "multiply"; /** Name for traps triggered by division. */ private static final String DIVIDE_TRAP = "divide"; /** Name for traps triggered by square root. */ private static final String SQRT_TRAP = "sqrt"; /** Name for traps triggered by alignment. */ private static final String ALIGN_TRAP = "align"; /** Name for traps triggered by truncation. */ private static final String TRUNC_TRAP = "trunc"; /** Name for traps triggered by nextAfter. */ private static final String NEXT_AFTER_TRAP = "nextAfter"; /** Name for traps triggered by lessThan. */ private static final String LESS_THAN_TRAP = "lessThan"; /** Name for traps triggered by greaterThan. */ private static final String GREATER_THAN_TRAP = "greaterThan"; /** Name for traps triggered by newInstance. */ private static final String NEW_INSTANCE_TRAP = "newInstance"; /** Mantissa. */ protected int[] mant; /** Sign bit: 1 for positive, -1 for negative. */ protected byte sign; /** Exponent. */ protected int exp; /** Indicator for non-finite / non-number values. */ protected byte nans; /** Factory building similar Dfp's. */ private final DfpField field; /** Makes an instance with a value of zero. * @param field field to which this instance belongs */ protected Dfp(final DfpField field) { mant = new int[field.getRadixDigits()]; sign = 1; exp = 0; nans = FINITE; this.field = field; } /** Create an instance from a byte value. * @param field field to which this instance belongs * @param x value to convert to an instance */ protected Dfp(final DfpField field, byte x) { this(field, (long) x); } /** Create an instance from an int value. * @param field field to which this instance belongs * @param x value to convert to an instance */ protected Dfp(final DfpField field, int x) { this(field, (long) x); } /** Create an instance from a long value. * @param field field to which this instance belongs * @param x value to convert to an instance */ protected Dfp(final DfpField field, long x) { // initialize as if 0 mant = new int[field.getRadixDigits()]; nans = FINITE; this.field = field; boolean isLongMin = false; if (x == Long.MIN_VALUE) { // special case for Long.MIN_VALUE (-9223372036854775808) // we must shift it before taking its absolute value isLongMin = true; ++x; } // set the sign if (x < 0) { sign = -1; x = -x; } else { sign = 1; } exp = 0; while (x != 0) { System.arraycopy(mant, mant.length - exp, mant, mant.length - 1 - exp, exp); mant[mant.length - 1] = (int) (x % RADIX); x /= RADIX; exp++; } if (isLongMin) { // remove the shift added for Long.MIN_VALUE // we know in this case that fixing the last digit is sufficient for (int i = 0; i < mant.length - 1; i++) { if (mant[i] != 0) { mant[i]++; break; } } } } /** Create an instance from a double value. * @param field field to which this instance belongs * @param x value to convert to an instance */ protected Dfp(final DfpField field, double x) { // initialize as if 0 mant = new int[field.getRadixDigits()]; sign = 1; exp = 0; nans = FINITE; this.field = field; long bits = Double.doubleToLongBits(x); long mantissa = bits & 0x000fffffffffffffL; int exponent = (int) ((bits & 0x7ff0000000000000L) >> 52) - 1023; if (exponent == -1023) { // Zero or sub-normal if (x == 0) { // make sure 0 has the right sign if ((bits & 0x8000000000000000L) != 0) { sign = -1; } return; } exponent++; // Normalize the subnormal number while ( (mantissa & 0x0010000000000000L) == 0) { exponent--; mantissa <<= 1; } mantissa &= 0x000fffffffffffffL; } if (exponent == 1024) { // infinity or NAN if (x != x) { sign = (byte) 1; nans = QNAN; } else if (x < 0) { sign = (byte) -1; nans = INFINITE; } else { sign = (byte) 1; nans = INFINITE; } return; } Dfp xdfp = new Dfp(field, mantissa); xdfp = xdfp.divide(new Dfp(field, 4503599627370496l)).add(field.getOne()); // Divide by 2^52, then add one xdfp = xdfp.multiply(DfpMath.pow(field.getTwo(), exponent)); if ((bits & 0x8000000000000000L) != 0) { xdfp = xdfp.negate(); } System.arraycopy(xdfp.mant, 0, mant, 0, mant.length); sign = xdfp.sign; exp = xdfp.exp; nans = xdfp.nans; } /** Copy constructor. * @param d instance to copy */ public Dfp(final Dfp d) { mant = d.mant.clone(); sign = d.sign; exp = d.exp; nans = d.nans; field = d.field; } /** Create an instance from a String representation. * @param field field to which this instance belongs * @param s string representation of the instance */ protected Dfp(final DfpField field, final String s) { // initialize as if 0 mant = new int[field.getRadixDigits()]; sign = 1; exp = 0; nans = FINITE; this.field = field; boolean decimalFound = false; final int rsize = 4; // size of radix in decimal digits final int offset = 4; // Starting offset into Striped final char[] striped = new char[getRadixDigits() * rsize + offset * 2]; // Check some special cases if (s.equals(POS_INFINITY_STRING)) { sign = (byte) 1; nans = INFINITE; return; } if (s.equals(NEG_INFINITY_STRING)) { sign = (byte) -1; nans = INFINITE; return; } if (s.equals(NAN_STRING)) { sign = (byte) 1; nans = QNAN; return; } // Check for scientific notation int p = s.indexOf("e"); if (p == -1) { // try upper case? p = s.indexOf("E"); } final String fpdecimal; int sciexp = 0; if (p != -1) { // scientific notation fpdecimal = s.substring(0, p); String fpexp = s.substring(p+1); boolean negative = false; for (int i=0; i<fpexp.length(); i++) { if (fpexp.charAt(i) == '-') { negative = true; continue; } if (fpexp.charAt(i) >= '0' && fpexp.charAt(i) <= '9') { sciexp = sciexp * 10 + fpexp.charAt(i) - '0'; } } if (negative) { sciexp = -sciexp; } } else { // normal case fpdecimal = s; } // If there is a minus sign in the number then it is negative if (fpdecimal.indexOf("-") != -1) { sign = -1; } // First off, find all of the leading zeros, trailing zeros, and significant digits p = 0; // Move p to first significant digit int decimalPos = 0; for (;;) { if (fpdecimal.charAt(p) >= '1' && fpdecimal.charAt(p) <= '9') { break; } if (decimalFound && fpdecimal.charAt(p) == '0') { decimalPos--; } if (fpdecimal.charAt(p) == '.') { decimalFound = true; } p++; if (p == fpdecimal.length()) { break; } } // Copy the string onto Stripped int q = offset; striped[0] = '0'; striped[1] = '0'; striped[2] = '0'; striped[3] = '0'; int significantDigits=0; for(;;) { if (p == (fpdecimal.length())) { break; } // Don't want to run pass the end of the array if (q == mant.length*rsize+offset+1) { break; } if (fpdecimal.charAt(p) == '.') { decimalFound = true; decimalPos = significantDigits; p++; continue; } if (fpdecimal.charAt(p) < '0' || fpdecimal.charAt(p) > '9') { p++; continue; } striped[q] = fpdecimal.charAt(p); q++; p++; significantDigits++; } // If the decimal point has been found then get rid of trailing zeros. if (decimalFound && q != offset) { for (;;) { q--; if (q == offset) { break; } if (striped[q] == '0') { significantDigits--; } else { break; } } } // special case of numbers like "0.00000" if (decimalFound && significantDigits == 0) { decimalPos = 0; } // Implicit decimal point at end of number if not present if (!decimalFound) { decimalPos = q-offset; } // Find the number of significant trailing zeros q = offset; // set q to point to first sig digit p = significantDigits-1+offset; while (p > q) { if (striped[p] != '0') { break; } p--; } // Make sure the decimal is on a mod 10000 boundary int i = ((rsize * 100) - decimalPos - sciexp % rsize) % rsize; q -= i; decimalPos += i; // Make the mantissa length right by adding zeros at the end if necessary while ((p - q) < (mant.length * rsize)) { for ( i = 0; i < rsize; i++) { striped[++p] = '0'; } } // Ok, now we know how many trailing zeros there are, // and where the least significant digit is for (i = mant.length - 1; i >= 0; i--) { mant[i] = (striped[q] - '0') * 1000 + (striped[q+1] - '0') * 100 + (striped[q+2] - '0') * 10 + (striped[q+3] - '0'); q += 4; } exp = (decimalPos+sciexp) / rsize; if (q < striped.length) { // Is there possible another digit? round((striped[q] - '0')*1000); } } /** Creates an instance with a non-finite value. * @param field field to which this instance belongs * @param sign sign of the Dfp to create * @param nans code of the value, must be one of {@link #INFINITE}, * {@link #SNAN}, {@link #QNAN} */ protected Dfp(final DfpField field, final byte sign, final byte nans) { this.field = field; this.mant = new int[field.getRadixDigits()]; this.sign = sign; this.exp = 0; this.nans = nans; } /** Create an instance with a value of 0. * Use this internally in preference to constructors to facilitate subclasses * @return a new instance with a value of 0 */ public Dfp newInstance() { return new Dfp(getField()); } /** Create an instance from a byte value. * @param x value to convert to an instance * @return a new instance with value x */ public Dfp newInstance(final byte x) { return new Dfp(getField(), x); } /** Create an instance from an int value. * @param x value to convert to an instance * @return a new instance with value x */ public Dfp newInstance(final int x) { return new Dfp(getField(), x); } /** Create an instance from a long value. * @param x value to convert to an instance * @return a new instance with value x */ public Dfp newInstance(final long x) { return new Dfp(getField(), x); } /** Create an instance from a double value. * @param x value to convert to an instance * @return a new instance with value x */ public Dfp newInstance(final double x) { return new Dfp(getField(), x); } /** Create an instance by copying an existing one. * Use this internally in preference to constructors to facilitate subclasses. * @param d instance to copy * @return a new instance with the same value as d */ public Dfp newInstance(final Dfp d) { // make sure we don't mix number with different precision if (field.getRadixDigits() != d.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; return dotrap(DfpField.FLAG_INVALID, NEW_INSTANCE_TRAP, d, result); } return new Dfp(d); } /** Create an instance from a String representation. * Use this internally in preference to constructors to facilitate subclasses. * @param s string representation of the instance * @return a new instance parsed from specified string */ public Dfp newInstance(final String s) { return new Dfp(field, s); } /** Creates an instance with a non-finite value. * @param sig sign of the Dfp to create * @param code code of the value, must be one of {@link #INFINITE}, * {@link #SNAN}, {@link #QNAN} * @return a new instance with a non-finite value */ public Dfp newInstance(final byte sig, final byte code) { return field.newDfp(sig, code); } /** Get the {@link org.apache.commons.math3.Field Field} (really a {@link DfpField}) to which the instance belongs. * <p> * The field is linked to the number of digits and acts as a factory * for {@link Dfp} instances. * </p> * @return {@link org.apache.commons.math3.Field Field} (really a {@link DfpField}) to which the instance belongs */ public DfpField getField() { return field; } /** Get the number of radix digits of the instance. * @return number of radix digits */ public int getRadixDigits() { return field.getRadixDigits(); } /** Get the constant 0. * @return a Dfp with value zero */ public Dfp getZero() { return field.getZero(); } /** Get the constant 1. * @return a Dfp with value one */ public Dfp getOne() { return field.getOne(); } /** Get the constant 2. * @return a Dfp with value two */ public Dfp getTwo() { return field.getTwo(); } /** Shift the mantissa left, and adjust the exponent to compensate. */ protected void shiftLeft() { for (int i = mant.length - 1; i > 0; i--) { mant[i] = mant[i-1]; } mant[0] = 0; exp--; } /* Note that shiftRight() does not call round() as that round() itself uses shiftRight() */ /** Shift the mantissa right, and adjust the exponent to compensate. */ protected void shiftRight() { for (int i = 0; i < mant.length - 1; i++) { mant[i] = mant[i+1]; } mant[mant.length - 1] = 0; exp++; } /** Make our exp equal to the supplied one, this may cause rounding. * Also causes de-normalized numbers. These numbers are generally * dangerous because most routines assume normalized numbers. * Align doesn't round, so it will return the last digit destroyed * by shifting right. * @param e desired exponent * @return last digit destroyed by shifting right */ protected int align(int e) { int lostdigit = 0; boolean inexact = false; int diff = exp - e; int adiff = diff; if (adiff < 0) { adiff = -adiff; } if (diff == 0) { return 0; } if (adiff > (mant.length + 1)) { // Special case Arrays.fill(mant, 0); exp = e; field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); dotrap(DfpField.FLAG_INEXACT, ALIGN_TRAP, this, this); return 0; } for (int i = 0; i < adiff; i++) { if (diff < 0) { /* Keep track of loss -- only signal inexact after losing 2 digits. * the first lost digit is returned to add() and may be incorporated * into the result. */ if (lostdigit != 0) { inexact = true; } lostdigit = mant[0]; shiftRight(); } else { shiftLeft(); } } if (inexact) { field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); dotrap(DfpField.FLAG_INEXACT, ALIGN_TRAP, this, this); } return lostdigit; } /** Check if instance is less than x. * @param x number to check instance against * @return true if instance is less than x and neither are NaN, false otherwise */ public boolean lessThan(final Dfp x) { // make sure we don't mix number with different precision if (field.getRadixDigits() != x.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, x, result); return false; } /* if a nan is involved, signal invalid and return false */ if (isNaN() || x.isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, x, newInstance(getZero())); return false; } return compare(this, x) < 0; } /** Check if instance is greater than x. * @param x number to check instance against * @return true if instance is greater than x and neither are NaN, false otherwise */ public boolean greaterThan(final Dfp x) { // make sure we don't mix number with different precision if (field.getRadixDigits() != x.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; dotrap(DfpField.FLAG_INVALID, GREATER_THAN_TRAP, x, result); return false; } /* if a nan is involved, signal invalid and return false */ if (isNaN() || x.isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, GREATER_THAN_TRAP, x, newInstance(getZero())); return false; } return compare(this, x) > 0; } /** Check if instance is less than or equal to 0. * @return true if instance is not NaN and less than or equal to 0, false otherwise */ public boolean negativeOrNull() { if (isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, this, newInstance(getZero())); return false; } return (sign < 0) || ((mant[mant.length - 1] == 0) && !isInfinite()); } /** Check if instance is strictly less than 0. * @return true if instance is not NaN and less than or equal to 0, false otherwise */ public boolean strictlyNegative() { if (isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, this, newInstance(getZero())); return false; } return (sign < 0) && ((mant[mant.length - 1] != 0) || isInfinite()); } /** Check if instance is greater than or equal to 0. * @return true if instance is not NaN and greater than or equal to 0, false otherwise */ public boolean positiveOrNull() { if (isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, this, newInstance(getZero())); return false; } return (sign > 0) || ((mant[mant.length - 1] == 0) && !isInfinite()); } /** Check if instance is strictly greater than 0. * @return true if instance is not NaN and greater than or equal to 0, false otherwise */ public boolean strictlyPositive() { if (isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, this, newInstance(getZero())); return false; } return (sign > 0) && ((mant[mant.length - 1] != 0) || isInfinite()); } /** Get the absolute value of instance. * @return absolute value of instance * @since 3.2 */ public Dfp abs() { Dfp result = newInstance(this); result.sign = 1; return result; } /** Check if instance is infinite. * @return true if instance is infinite */ public boolean isInfinite() { return nans == INFINITE; } /** Check if instance is not a number. * @return true if instance is not a number */ public boolean isNaN() { return (nans == QNAN) || (nans == SNAN); } /** Check if instance is equal to zero. * @return true if instance is equal to zero */ public boolean isZero() { if (isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, this, newInstance(getZero())); return false; } return (mant[mant.length - 1] == 0) && !isInfinite(); } /** Check if instance is equal to x. * @param other object to check instance against * @return true if instance is equal to x and neither are NaN, false otherwise */ @Override public boolean equals(final Object other) { if (other instanceof Dfp) { final Dfp x = (Dfp) other; if (isNaN() || x.isNaN() || field.getRadixDigits() != x.field.getRadixDigits()) { return false; } return compare(this, x) == 0; } return false; } /** * Gets a hashCode for the instance. * @return a hash code value for this object */ @Override public int hashCode() { return 17 + (sign << 8) + (nans << 16) + exp + Arrays.hashCode(mant); } /** Check if instance is not equal to x. * @param x number to check instance against * @return true if instance is not equal to x and neither are NaN, false otherwise */ public boolean unequal(final Dfp x) { if (isNaN() || x.isNaN() || field.getRadixDigits() != x.field.getRadixDigits()) { return false; } return greaterThan(x) || lessThan(x); } /** Compare two instances. * @param a first instance in comparison * @param b second instance in comparison * @return -1 if a<b, 1 if a>b and 0 if a==b * Note this method does not properly handle NaNs or numbers with different precision. */ private static int compare(final Dfp a, final Dfp b) { // Ignore the sign of zero if (a.mant[a.mant.length - 1] == 0 && b.mant[b.mant.length - 1] == 0 && a.nans == FINITE && b.nans == FINITE) { return 0; } if (a.sign != b.sign) { if (a.sign == -1) { return -1; } else { return 1; } } // deal with the infinities if (a.nans == INFINITE && b.nans == FINITE) { return a.sign; } if (a.nans == FINITE && b.nans == INFINITE) { return -b.sign; } if (a.nans == INFINITE && b.nans == INFINITE) { return 0; } // Handle special case when a or b is zero, by ignoring the exponents if (b.mant[b.mant.length-1] != 0 && a.mant[b.mant.length-1] != 0) { if (a.exp < b.exp) { return -a.sign; } if (a.exp > b.exp) { return a.sign; } } // compare the mantissas for (int i = a.mant.length - 1; i >= 0; i--) { if (a.mant[i] > b.mant[i]) { return a.sign; } if (a.mant[i] < b.mant[i]) { return -a.sign; } } return 0; } /** Round to nearest integer using the round-half-even method. * That is round to nearest integer unless both are equidistant. * In which case round to the even one. * @return rounded value * @since 3.2 */ public Dfp rint() { return trunc(DfpField.RoundingMode.ROUND_HALF_EVEN); } /** Round to an integer using the round floor mode. * That is, round toward -Infinity * @return rounded value * @since 3.2 */ public Dfp floor() { return trunc(DfpField.RoundingMode.ROUND_FLOOR); } /** Round to an integer using the round ceil mode. * That is, round toward +Infinity * @return rounded value * @since 3.2 */ public Dfp ceil() { return trunc(DfpField.RoundingMode.ROUND_CEIL); } /** Returns the IEEE remainder. * @param d divisor * @return this less n &times; d, where n is the integer closest to this/d * @since 3.2 */ public Dfp remainder(final Dfp d) { final Dfp result = this.subtract(this.divide(d).rint().multiply(d)); // IEEE 854-1987 says that if the result is zero, then it carries the sign of this if (result.mant[mant.length-1] == 0) { result.sign = sign; } return result; } /** Does the integer conversions with the specified rounding. * @param rmode rounding mode to use * @return truncated value */ protected Dfp trunc(final DfpField.RoundingMode rmode) { boolean changed = false; if (isNaN()) { return newInstance(this); } if (nans == INFINITE) { return newInstance(this); } if (mant[mant.length-1] == 0) { // a is zero return newInstance(this); } /* If the exponent is less than zero then we can certainly * return zero */ if (exp < 0) { field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); Dfp result = newInstance(getZero()); result = dotrap(DfpField.FLAG_INEXACT, TRUNC_TRAP, this, result); return result; } /* If the exponent is greater than or equal to digits, then it * must already be an integer since there is no precision left * for any fractional part */ if (exp >= mant.length) { return newInstance(this); } /* General case: create another dfp, result, that contains the * a with the fractional part lopped off. */ Dfp result = newInstance(this); for (int i = 0; i < mant.length-result.exp; i++) { changed |= result.mant[i] != 0; result.mant[i] = 0; } if (changed) { switch (rmode) { case ROUND_FLOOR: if (result.sign == -1) { // then we must increment the mantissa by one result = result.add(newInstance(-1)); } break; case ROUND_CEIL: if (result.sign == 1) { // then we must increment the mantissa by one result = result.add(getOne()); } break; case ROUND_HALF_EVEN: default: final Dfp half = newInstance("0.5"); Dfp a = subtract(result); // difference between this and result a.sign = 1; // force positive (take abs) if (a.greaterThan(half)) { a = newInstance(getOne()); a.sign = sign; result = result.add(a); } /** If exactly equal to 1/2 and odd then increment */ if (a.equals(half) && result.exp > 0 && (result.mant[mant.length-result.exp]&1) != 0) { a = newInstance(getOne()); a.sign = sign; result = result.add(a); } break; } field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); // signal inexact result = dotrap(DfpField.FLAG_INEXACT, TRUNC_TRAP, this, result); return result; } return result; } /** Convert this to an integer. * If greater than 2147483647, it returns 2147483647. If less than -2147483648 it returns -2147483648. * @return converted number */ public int intValue() { Dfp rounded; int result = 0; rounded = rint(); if (rounded.greaterThan(newInstance(2147483647))) { return 2147483647; } if (rounded.lessThan(newInstance(-2147483648))) { return -2147483648; } for (int i = mant.length - 1; i >= mant.length - rounded.exp; i--) { result = result * RADIX + rounded.mant[i]; } if (rounded.sign == -1) { result = -result; } return result; } /** Get the exponent of the greatest power of 10000 that is * less than or equal to the absolute value of this. I.E. if * this is 10<sup>6</sup> then log10K would return 1. * @return integer base 10000 logarithm */ public int log10K() { return exp - 1; } /** Get the specified power of 10000. * @param e desired power * @return 10000<sup>e</sup> */ public Dfp power10K(final int e) { Dfp d = newInstance(getOne()); d.exp = e + 1; return d; } /** Get the exponent of the greatest power of 10 that is less than or equal to abs(this). * @return integer base 10 logarithm * @since 3.2 */ public int intLog10() { if (mant[mant.length-1] > 1000) { return exp * 4 - 1; } if (mant[mant.length-1] > 100) { return exp * 4 - 2; } if (mant[mant.length-1] > 10) { return exp * 4 - 3; } return exp * 4 - 4; } /** Return the specified power of 10. * @param e desired power * @return 10<sup>e</sup> */ public Dfp power10(final int e) { Dfp d = newInstance(getOne()); if (e >= 0) { d.exp = e / 4 + 1; } else { d.exp = (e + 1) / 4; } switch ((e % 4 + 4) % 4) { case 0: break; case 1: d = d.multiply(10); break; case 2: d = d.multiply(100); break; default: d = d.multiply(1000); } return d; } /** Negate the mantissa of this by computing the complement. * Leaves the sign bit unchanged, used internally by add. * Denormalized numbers are handled properly here. * @param extra ??? * @return ??? */ protected int complement(int extra) { extra = RADIX-extra; for (int i = 0; i < mant.length; i++) { mant[i] = RADIX-mant[i]-1; } int rh = extra / RADIX; extra = extra - rh * RADIX; for (int i = 0; i < mant.length; i++) { final int r = mant[i] + rh; rh = r / RADIX; mant[i] = r - rh * RADIX; } return extra; } /** Add x to this. * @param x number to add * @return sum of this and x */ public Dfp add(final Dfp x) { // make sure we don't mix number with different precision if (field.getRadixDigits() != x.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; return dotrap(DfpField.FLAG_INVALID, ADD_TRAP, x, result); } /* handle special cases */ if (nans != FINITE || x.nans != FINITE) { if (isNaN()) { return this; } if (x.isNaN()) { return x; } if (nans == INFINITE && x.nans == FINITE) { return this; } if (x.nans == INFINITE && nans == FINITE) { return x; } if (x.nans == INFINITE && nans == INFINITE && sign == x.sign) { return x; } if (x.nans == INFINITE && nans == INFINITE && sign != x.sign) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); Dfp result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, ADD_TRAP, x, result); return result; } } /* copy this and the arg */ Dfp a = newInstance(this); Dfp b = newInstance(x); /* initialize the result object */ Dfp result = newInstance(getZero()); /* Make all numbers positive, but remember their sign */ final byte asign = a.sign; final byte bsign = b.sign; a.sign = 1; b.sign = 1; /* The result will be signed like the arg with greatest magnitude */ byte rsign = bsign; if (compare(a, b) > 0) { rsign = asign; } /* Handle special case when a or b is zero, by setting the exponent of the zero number equal to the other one. This avoids an alignment which would cause catastropic loss of precision */ if (b.mant[mant.length-1] == 0) { b.exp = a.exp; } if (a.mant[mant.length-1] == 0) { a.exp = b.exp; } /* align number with the smaller exponent */ int aextradigit = 0; int bextradigit = 0; if (a.exp < b.exp) { aextradigit = a.align(b.exp); } else { bextradigit = b.align(a.exp); } /* complement the smaller of the two if the signs are different */ if (asign != bsign) { if (asign == rsign) { bextradigit = b.complement(bextradigit); } else { aextradigit = a.complement(aextradigit); } } /* add the mantissas */ int rh = 0; /* acts as a carry */ for (int i = 0; i < mant.length; i++) { final int r = a.mant[i]+b.mant[i]+rh; rh = r / RADIX; result.mant[i] = r - rh * RADIX; } result.exp = a.exp; result.sign = rsign; /* handle overflow -- note, when asign!=bsign an overflow is * normal and should be ignored. */ if (rh != 0 && (asign == bsign)) { final int lostdigit = result.mant[0]; result.shiftRight(); result.mant[mant.length-1] = rh; final int excp = result.round(lostdigit); if (excp != 0) { result = dotrap(excp, ADD_TRAP, x, result); } } /* normalize the result */ for (int i = 0; i < mant.length; i++) { if (result.mant[mant.length-1] != 0) { break; } result.shiftLeft(); if (i == 0) { result.mant[0] = aextradigit+bextradigit; aextradigit = 0; bextradigit = 0; } } /* result is zero if after normalization the most sig. digit is zero */ if (result.mant[mant.length-1] == 0) { result.exp = 0; if (asign != bsign) { // Unless adding 2 negative zeros, sign is positive result.sign = 1; // Per IEEE 854-1987 Section 6.3 } } /* Call round to test for over/under flows */ final int excp = result.round(aextradigit + bextradigit); if (excp != 0) { result = dotrap(excp, ADD_TRAP, x, result); } return result; } /** Returns a number that is this number with the sign bit reversed. * @return the opposite of this */ public Dfp negate() { Dfp result = newInstance(this); result.sign = (byte) - result.sign; return result; } /** Subtract x from this. * @param x number to subtract * @return difference of this and a */ public Dfp subtract(final Dfp x) { return add(x.negate()); } /** Round this given the next digit n using the current rounding mode. * @param n ??? * @return the IEEE flag if an exception occurred */ protected int round(int n) { boolean inc = false; switch (field.getRoundingMode()) { case ROUND_DOWN: inc = false; break; case ROUND_UP: inc = n != 0; // round up if n!=0 break; case ROUND_HALF_UP: inc = n >= 5000; // round half up break; case ROUND_HALF_DOWN: inc = n > 5000; // round half down break; case ROUND_HALF_EVEN: inc = n > 5000 || (n == 5000 && (mant[0] & 1) == 1); // round half-even break; case ROUND_HALF_ODD: inc = n > 5000 || (n == 5000 && (mant[0] & 1) == 0); // round half-odd break; case ROUND_CEIL: inc = sign == 1 && n != 0; // round ceil break; case ROUND_FLOOR: default: inc = sign == -1 && n != 0; // round floor break; } if (inc) { // increment if necessary int rh = 1; for (int i = 0; i < mant.length; i++) { final int r = mant[i] + rh; rh = r / RADIX; mant[i] = r - rh * RADIX; } if (rh != 0) { shiftRight(); mant[mant.length-1] = rh; } } // check for exceptional cases and raise signals if necessary if (exp < MIN_EXP) { // Gradual Underflow field.setIEEEFlagsBits(DfpField.FLAG_UNDERFLOW); return DfpField.FLAG_UNDERFLOW; } if (exp > MAX_EXP) { // Overflow field.setIEEEFlagsBits(DfpField.FLAG_OVERFLOW); return DfpField.FLAG_OVERFLOW; } if (n != 0) { // Inexact field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); return DfpField.FLAG_INEXACT; } return 0; } /** Multiply this by x. * @param x multiplicand * @return product of this and x */ public Dfp multiply(final Dfp x) { // make sure we don't mix number with different precision if (field.getRadixDigits() != x.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; return dotrap(DfpField.FLAG_INVALID, MULTIPLY_TRAP, x, result); } Dfp result = newInstance(getZero()); /* handle special cases */ if (nans != FINITE || x.nans != FINITE) { if (isNaN()) { return this; } if (x.isNaN()) { return x; } if (nans == INFINITE && x.nans == FINITE && x.mant[mant.length-1] != 0) { result = newInstance(this); result.sign = (byte) (sign * x.sign); return result; } if (x.nans == INFINITE && nans == FINITE && mant[mant.length-1] != 0) { result = newInstance(x); result.sign = (byte) (sign * x.sign); return result; } if (x.nans == INFINITE && nans == INFINITE) { result = newInstance(this); result.sign = (byte) (sign * x.sign); return result; } if ( (x.nans == INFINITE && nans == FINITE && mant[mant.length-1] == 0) || (nans == INFINITE && x.nans == FINITE && x.mant[mant.length-1] == 0) ) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, MULTIPLY_TRAP, x, result); return result; } } int[] product = new int[mant.length*2]; // Big enough to hold even the largest result for (int i = 0; i < mant.length; i++) { int rh = 0; // acts as a carry for (int j=0; j<mant.length; j++) { int r = mant[i] * x.mant[j]; // multiply the 2 digits r = r + product[i+j] + rh; // add to the product digit with carry in rh = r / RADIX; product[i+j] = r - rh * RADIX; } product[i+mant.length] = rh; } // Find the most sig digit int md = mant.length * 2 - 1; // default, in case result is zero for (int i = mant.length * 2 - 1; i >= 0; i--) { if (product[i] != 0) { md = i; break; } } // Copy the digits into the result for (int i = 0; i < mant.length; i++) { result.mant[mant.length - i - 1] = product[md - i]; } // Fixup the exponent. result.exp = exp + x.exp + md - 2 * mant.length + 1; result.sign = (byte)((sign == x.sign)?1:-1); if (result.mant[mant.length-1] == 0) { // if result is zero, set exp to zero result.exp = 0; } final int excp; if (md > (mant.length-1)) { excp = result.round(product[md-mant.length]); } else { excp = result.round(0); // has no effect except to check status } if (excp != 0) { result = dotrap(excp, MULTIPLY_TRAP, x, result); } return result; } /** Multiply this by a single digit x. * @param x multiplicand * @return product of this and x */ public Dfp multiply(final int x) { if (x >= 0 && x < RADIX) { return multiplyFast(x); } else { return multiply(newInstance(x)); } } /** Multiply this by a single digit 0&lt;=x&lt;radix. * There are speed advantages in this special case. * @param x multiplicand * @return product of this and x */ private Dfp multiplyFast(final int x) { Dfp result = newInstance(this); /* handle special cases */ if (nans != FINITE) { if (isNaN()) { return this; } if (nans == INFINITE && x != 0) { result = newInstance(this); return result; } if (nans == INFINITE && x == 0) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, MULTIPLY_TRAP, newInstance(getZero()), result); return result; } } /* range check x */ if (x < 0 || x >= RADIX) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, MULTIPLY_TRAP, result, result); return result; } int rh = 0; for (int i = 0; i < mant.length; i++) { final int r = mant[i] * x + rh; rh = r / RADIX; result.mant[i] = r - rh * RADIX; } int lostdigit = 0; if (rh != 0) { lostdigit = result.mant[0]; result.shiftRight(); result.mant[mant.length-1] = rh; } if (result.mant[mant.length - 1] <= 0) { // if result is zero, set exp to zero result.exp = 0; } final int excp = result.round(lostdigit); if (excp != 0) { result = dotrap(excp, MULTIPLY_TRAP, result, result); } return result; } /** Divide this by divisor. * @param divisor divisor * @return quotient of this by divisor */ public Dfp divide(Dfp divisor) { int dividend[]; // current status of the dividend int quotient[]; // quotient int remainder[];// remainder int qd; // current quotient digit we're working with int nsqd; // number of significant quotient digits we have int trial=0; // trial quotient digit int minadj; // minimum adjustment boolean trialgood; // Flag to indicate a good trail digit int md=0; // most sig digit in result int excp; // exceptions // make sure we don't mix number with different precision if (field.getRadixDigits() != divisor.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; return dotrap(DfpField.FLAG_INVALID, DIVIDE_TRAP, divisor, result); } Dfp result = newInstance(getZero()); /* handle special cases */ if (nans != FINITE || divisor.nans != FINITE) { if (isNaN()) { return this; } if (divisor.isNaN()) { return divisor; } if (nans == INFINITE && divisor.nans == FINITE) { result = newInstance(this); result.sign = (byte) (sign * divisor.sign); return result; } if (divisor.nans == INFINITE && nans == FINITE) { result = newInstance(getZero()); result.sign = (byte) (sign * divisor.sign); return result; } if (divisor.nans == INFINITE && nans == INFINITE) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, DIVIDE_TRAP, divisor, result); return result; } } /* Test for divide by zero */ if (divisor.mant[mant.length-1] == 0) { field.setIEEEFlagsBits(DfpField.FLAG_DIV_ZERO); result = newInstance(getZero()); result.sign = (byte) (sign * divisor.sign); result.nans = INFINITE; result = dotrap(DfpField.FLAG_DIV_ZERO, DIVIDE_TRAP, divisor, result); return result; } dividend = new int[mant.length+1]; // one extra digit needed quotient = new int[mant.length+2]; // two extra digits needed 1 for overflow, 1 for rounding remainder = new int[mant.length+1]; // one extra digit needed /* Initialize our most significant digits to zero */ dividend[mant.length] = 0; quotient[mant.length] = 0; quotient[mant.length+1] = 0; remainder[mant.length] = 0; /* copy our mantissa into the dividend, initialize the quotient while we are at it */ for (int i = 0; i < mant.length; i++) { dividend[i] = mant[i]; quotient[i] = 0; remainder[i] = 0; } /* outer loop. Once per quotient digit */ nsqd = 0; for (qd = mant.length+1; qd >= 0; qd--) { /* Determine outer limits of our quotient digit */ // r = most sig 2 digits of dividend final int divMsb = dividend[mant.length]*RADIX+dividend[mant.length-1]; int min = divMsb / (divisor.mant[mant.length-1]+1); int max = (divMsb + 1) / divisor.mant[mant.length-1]; trialgood = false; while (!trialgood) { // try the mean trial = (min+max)/2; /* Multiply by divisor and store as remainder */ int rh = 0; for (int i = 0; i < mant.length + 1; i++) { int dm = (i<mant.length)?divisor.mant[i]:0; final int r = (dm * trial) + rh; rh = r / RADIX; remainder[i] = r - rh * RADIX; } /* subtract the remainder from the dividend */ rh = 1; // carry in to aid the subtraction for (int i = 0; i < mant.length + 1; i++) { final int r = ((RADIX-1) - remainder[i]) + dividend[i] + rh; rh = r / RADIX; remainder[i] = r - rh * RADIX; } /* Lets analyze what we have here */ if (rh == 0) { // trial is too big -- negative remainder max = trial-1; continue; } /* find out how far off the remainder is telling us we are */ minadj = (remainder[mant.length] * RADIX)+remainder[mant.length-1]; minadj = minadj / (divisor.mant[mant.length-1]+1); if (minadj >= 2) { min = trial+minadj; // update the minimum continue; } /* May have a good one here, check more thoroughly. Basically its a good one if it is less than the divisor */ trialgood = false; // assume false for (int i = mant.length - 1; i >= 0; i--) { if (divisor.mant[i] > remainder[i]) { trialgood = true; } if (divisor.mant[i] < remainder[i]) { break; } } if (remainder[mant.length] != 0) { trialgood = false; } if (trialgood == false) { min = trial+1; } } /* Great we have a digit! */ quotient[qd] = trial; if (trial != 0 || nsqd != 0) { nsqd++; } if (field.getRoundingMode() == DfpField.RoundingMode.ROUND_DOWN && nsqd == mant.length) { // We have enough for this mode break; } if (nsqd > mant.length) { // We have enough digits break; } /* move the remainder into the dividend while left shifting */ dividend[0] = 0; for (int i = 0; i < mant.length; i++) { dividend[i + 1] = remainder[i]; } } /* Find the most sig digit */ md = mant.length; // default for (int i = mant.length + 1; i >= 0; i--) { if (quotient[i] != 0) { md = i; break; } } /* Copy the digits into the result */ for (int i=0; i<mant.length; i++) { result.mant[mant.length-i-1] = quotient[md-i]; } /* Fixup the exponent. */ result.exp = exp - divisor.exp + md - mant.length; result.sign = (byte) ((sign == divisor.sign) ? 1 : -1); if (result.mant[mant.length-1] == 0) { // if result is zero, set exp to zero result.exp = 0; } if (md > (mant.length-1)) { excp = result.round(quotient[md-mant.length]); } else { excp = result.round(0); } if (excp != 0) { result = dotrap(excp, DIVIDE_TRAP, divisor, result); } return result; } /** Divide by a single digit less than radix. * Special case, so there are speed advantages. 0 &lt;= divisor &lt; radix * @param divisor divisor * @return quotient of this by divisor */ public Dfp divide(int divisor) { // Handle special cases if (nans != FINITE) { if (isNaN()) { return this; } if (nans == INFINITE) { return newInstance(this); } } // Test for divide by zero if (divisor == 0) { field.setIEEEFlagsBits(DfpField.FLAG_DIV_ZERO); Dfp result = newInstance(getZero()); result.sign = sign; result.nans = INFINITE; result = dotrap(DfpField.FLAG_DIV_ZERO, DIVIDE_TRAP, getZero(), result); return result; } // range check divisor if (divisor < 0 || divisor >= RADIX) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); Dfp result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, DIVIDE_TRAP, result, result); return result; } Dfp result = newInstance(this); int rl = 0; for (int i = mant.length-1; i >= 0; i--) { final int r = rl*RADIX + result.mant[i]; final int rh = r / divisor; rl = r - rh * divisor; result.mant[i] = rh; } if (result.mant[mant.length-1] == 0) { // normalize result.shiftLeft(); final int r = rl * RADIX; // compute the next digit and put it in final int rh = r / divisor; rl = r - rh * divisor; result.mant[0] = rh; } final int excp = result.round(rl * RADIX / divisor); // do the rounding if (excp != 0) { result = dotrap(excp, DIVIDE_TRAP, result, result); } return result; } /** {@inheritDoc} */ public Dfp reciprocal() { return field.getOne().divide(this); } /** Compute the square root. * @return square root of the instance * @since 3.2 */ public Dfp sqrt() { // check for unusual cases if (nans == FINITE && mant[mant.length-1] == 0) { // if zero return newInstance(this); } if (nans != FINITE) { if (nans == INFINITE && sign == 1) { // if positive infinity return newInstance(this); } if (nans == QNAN) { return newInstance(this); } if (nans == SNAN) { Dfp result; field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(this); result = dotrap(DfpField.FLAG_INVALID, SQRT_TRAP, null, result); return result; } } if (sign == -1) { // if negative Dfp result; field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(this); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, SQRT_TRAP, null, result); return result; } Dfp x = newInstance(this); /* Lets make a reasonable guess as to the size of the square root */ if (x.exp < -1 || x.exp > 1) { x.exp = this.exp / 2; } /* Coarsely estimate the mantissa */ switch (x.mant[mant.length-1] / 2000) { case 0: x.mant[mant.length-1] = x.mant[mant.length-1]/2+1; break; case 2: x.mant[mant.length-1] = 1500; break; case 3: x.mant[mant.length-1] = 2200; break; default: x.mant[mant.length-1] = 3000; } Dfp dx = newInstance(x); /* Now that we have the first pass estimate, compute the rest by the formula dx = (y - x*x) / (2x); */ Dfp px = getZero(); Dfp ppx = getZero(); while (x.unequal(px)) { dx = newInstance(x); dx.sign = -1; dx = dx.add(this.divide(x)); dx = dx.divide(2); ppx = px; px = x; x = x.add(dx); if (x.equals(ppx)) { // alternating between two values break; } // if dx is zero, break. Note testing the most sig digit // is a sufficient test since dx is normalized if (dx.mant[mant.length-1] == 0) { break; } } return x; } /** Get a string representation of the instance. * @return string representation of the instance */ @Override public String toString() { if (nans != FINITE) { // if non-finite exceptional cases if (nans == INFINITE) { return (sign < 0) ? NEG_INFINITY_STRING : POS_INFINITY_STRING; } else { return NAN_STRING; } } if (exp > mant.length || exp < -1) { return dfp2sci(); } return dfp2string(); } /** Convert an instance to a string using scientific notation. * @return string representation of the instance in scientific notation */ protected String dfp2sci() { char rawdigits[] = new char[mant.length * 4]; char outputbuffer[] = new char[mant.length * 4 + 20]; int p; int q; int e; int ae; int shf; // Get all the digits p = 0; for (int i = mant.length - 1; i >= 0; i--) { rawdigits[p++] = (char) ((mant[i] / 1000) + '0'); rawdigits[p++] = (char) (((mant[i] / 100) %10) + '0'); rawdigits[p++] = (char) (((mant[i] / 10) % 10) + '0'); rawdigits[p++] = (char) (((mant[i]) % 10) + '0'); } // Find the first non-zero one for (p = 0; p < rawdigits.length; p++) { if (rawdigits[p] != '0') { break; } } shf = p; // Now do the conversion q = 0; if (sign == -1) { outputbuffer[q++] = '-'; } if (p != rawdigits.length) { // there are non zero digits... outputbuffer[q++] = rawdigits[p++]; outputbuffer[q++] = '.'; while (p<rawdigits.length) { outputbuffer[q++] = rawdigits[p++]; } } else { outputbuffer[q++] = '0'; outputbuffer[q++] = '.'; outputbuffer[q++] = '0'; outputbuffer[q++] = 'e'; outputbuffer[q++] = '0'; return new String(outputbuffer, 0, 5); } outputbuffer[q++] = 'e'; // Find the msd of the exponent e = exp * 4 - shf - 1; ae = e; if (e < 0) { ae = -e; } // Find the largest p such that p < e for (p = 1000000000; p > ae; p /= 10) { // nothing to do } if (e < 0) { outputbuffer[q++] = '-'; } while (p > 0) { outputbuffer[q++] = (char)(ae / p + '0'); ae = ae % p; p = p / 10; } return new String(outputbuffer, 0, q); } /** Convert an instance to a string using normal notation. * @return string representation of the instance in normal notation */ protected String dfp2string() { char buffer[] = new char[mant.length*4 + 20]; int p = 1; int q; int e = exp; boolean pointInserted = false; buffer[0] = ' '; if (e <= 0) { buffer[p++] = '0'; buffer[p++] = '.'; pointInserted = true; } while (e < 0) { buffer[p++] = '0'; buffer[p++] = '0'; buffer[p++] = '0'; buffer[p++] = '0'; e++; } for (int i = mant.length - 1; i >= 0; i--) { buffer[p++] = (char) ((mant[i] / 1000) + '0'); buffer[p++] = (char) (((mant[i] / 100) % 10) + '0'); buffer[p++] = (char) (((mant[i] / 10) % 10) + '0'); buffer[p++] = (char) (((mant[i]) % 10) + '0'); if (--e == 0) { buffer[p++] = '.'; pointInserted = true; } } while (e > 0) { buffer[p++] = '0'; buffer[p++] = '0'; buffer[p++] = '0'; buffer[p++] = '0'; e--; } if (!pointInserted) { // Ensure we have a radix point! buffer[p++] = '.'; } // Suppress leading zeros q = 1; while (buffer[q] == '0') { q++; } if (buffer[q] == '.') { q--; } // Suppress trailing zeros while (buffer[p-1] == '0') { p--; } // Insert sign if (sign < 0) { buffer[--q] = '-'; } return new String(buffer, q, p - q); } /** Raises a trap. This does not set the corresponding flag however. * @param type the trap type * @param what - name of routine trap occurred in * @param oper - input operator to function * @param result - the result computed prior to the trap * @return The suggested return value from the trap handler */ public Dfp dotrap(int type, String what, Dfp oper, Dfp result) { Dfp def = result; switch (type) { case DfpField.FLAG_INVALID: def = newInstance(getZero()); def.sign = result.sign; def.nans = QNAN; break; case DfpField.FLAG_DIV_ZERO: if (nans == FINITE && mant[mant.length-1] != 0) { // normal case, we are finite, non-zero def = newInstance(getZero()); def.sign = (byte)(sign*oper.sign); def.nans = INFINITE; } if (nans == FINITE && mant[mant.length-1] == 0) { // 0/0 def = newInstance(getZero()); def.nans = QNAN; } if (nans == INFINITE || nans == QNAN) { def = newInstance(getZero()); def.nans = QNAN; } if (nans == INFINITE || nans == SNAN) { def = newInstance(getZero()); def.nans = QNAN; } break; case DfpField.FLAG_UNDERFLOW: if ( (result.exp+mant.length) < MIN_EXP) { def = newInstance(getZero()); def.sign = result.sign; } else { def = newInstance(result); // gradual underflow } result.exp = result.exp + ERR_SCALE; break; case DfpField.FLAG_OVERFLOW: result.exp = result.exp - ERR_SCALE; def = newInstance(getZero()); def.sign = result.sign; def.nans = INFINITE; break; default: def = result; break; } return trap(type, what, oper, def, result); } /** Trap handler. Subclasses may override this to provide trap * functionality per IEEE 854-1987. * * @param type The exception type - e.g. FLAG_OVERFLOW * @param what The name of the routine we were in e.g. divide() * @param oper An operand to this function if any * @param def The default return value if trap not enabled * @param result The result that is specified to be delivered per * IEEE 854, if any * @return the value that should be return by the operation triggering the trap */ protected Dfp trap(int type, String what, Dfp oper, Dfp def, Dfp result) { return def; } /** Returns the type - one of FINITE, INFINITE, SNAN, QNAN. * @return type of the number */ public int classify() { return nans; } /** Creates an instance that is the same as x except that it has the sign of y. * abs(x) = dfp.copysign(x, dfp.one) * @param x number to get the value from * @param y number to get the sign from * @return a number with the value of x and the sign of y */ public static Dfp copysign(final Dfp x, final Dfp y) { Dfp result = x.newInstance(x); result.sign = y.sign; return result; } /** Returns the next number greater than this one in the direction of x. * If this==x then simply returns this. * @param x direction where to look at * @return closest number next to instance in the direction of x */ public Dfp nextAfter(final Dfp x) { // make sure we don't mix number with different precision if (field.getRadixDigits() != x.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; return dotrap(DfpField.FLAG_INVALID, NEXT_AFTER_TRAP, x, result); } // if this is greater than x boolean up = false; if (this.lessThan(x)) { up = true; } if (compare(this, x) == 0) { return newInstance(x); } if (lessThan(getZero())) { up = !up; } final Dfp inc; Dfp result; if (up) { inc = newInstance(getOne()); inc.exp = this.exp-mant.length+1; inc.sign = this.sign; if (this.equals(getZero())) { inc.exp = MIN_EXP-mant.length; } result = add(inc); } else { inc = newInstance(getOne()); inc.exp = this.exp; inc.sign = this.sign; if (this.equals(inc)) { inc.exp = this.exp-mant.length; } else { inc.exp = this.exp-mant.length+1; } if (this.equals(getZero())) { inc.exp = MIN_EXP-mant.length; } result = this.subtract(inc); } if (result.classify() == INFINITE && this.classify() != INFINITE) { field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); result = dotrap(DfpField.FLAG_INEXACT, NEXT_AFTER_TRAP, x, result); } if (result.equals(getZero()) && this.equals(getZero()) == false) { field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); result = dotrap(DfpField.FLAG_INEXACT, NEXT_AFTER_TRAP, x, result); } return result; } /** Convert the instance into a double. * @return a double approximating the instance * @see #toSplitDouble() */ public double toDouble() { if (isInfinite()) { if (lessThan(getZero())) { return Double.NEGATIVE_INFINITY; } else { return Double.POSITIVE_INFINITY; } } if (isNaN()) { return Double.NaN; } Dfp y = this; boolean negate = false; int cmp0 = compare(this, getZero()); if (cmp0 == 0) { return sign < 0 ? -0.0 : +0.0; } else if (cmp0 < 0) { y = negate(); negate = true; } /* Find the exponent, first estimate by integer log10, then adjust. Should be faster than doing a natural logarithm. */ int exponent = (int)(y.intLog10() * 3.32); if (exponent < 0) { exponent--; } Dfp tempDfp = DfpMath.pow(getTwo(), exponent); while (tempDfp.lessThan(y) || tempDfp.equals(y)) { tempDfp = tempDfp.multiply(2); exponent++; } exponent--; /* We have the exponent, now work on the mantissa */ y = y.divide(DfpMath.pow(getTwo(), exponent)); if (exponent > -1023) { y = y.subtract(getOne()); } if (exponent < -1074) { return 0; } if (exponent > 1023) { return negate ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } y = y.multiply(newInstance(4503599627370496l)).rint(); String str = y.toString(); str = str.substring(0, str.length()-1); long mantissa = Long.parseLong(str); if (mantissa == 4503599627370496L) { // Handle special case where we round up to next power of two mantissa = 0; exponent++; } /* Its going to be subnormal, so make adjustments */ if (exponent <= -1023) { exponent--; } while (exponent < -1023) { exponent++; mantissa >>>= 1; } long bits = mantissa | ((exponent + 1023L) << 52); double x = Double.longBitsToDouble(bits); if (negate) { x = -x; } return x; } /** Convert the instance into a split double. * @return an array of two doubles which sum represent the instance * @see #toDouble() */ public double[] toSplitDouble() { double split[] = new double[2]; long mask = 0xffffffffc0000000L; split[0] = Double.longBitsToDouble(Double.doubleToLongBits(toDouble()) & mask); split[1] = subtract(newInstance(split[0])).toDouble(); return split; } /** {@inheritDoc} * @since 3.2 */ public double getReal() { return toDouble(); } /** {@inheritDoc} * @since 3.2 */ public Dfp add(final double a) { return add(newInstance(a)); } /** {@inheritDoc} * @since 3.2 */ public Dfp subtract(final double a) { return subtract(newInstance(a)); } /** {@inheritDoc} * @since 3.2 */ public Dfp multiply(final double a) { return multiply(newInstance(a)); } /** {@inheritDoc} * @since 3.2 */ public Dfp divide(final double a) { return divide(newInstance(a)); } /** {@inheritDoc} * @since 3.2 */ public Dfp remainder(final double a) { return remainder(newInstance(a)); } /** {@inheritDoc} * @since 3.2 */ public long round() { return FastMath.round(toDouble()); } /** {@inheritDoc} * @since 3.2 */ public Dfp signum() { if (isNaN() || isZero()) { return this; } else { return newInstance(sign > 0 ? +1 : -1); } } /** {@inheritDoc} * @since 3.2 */ public Dfp copySign(final Dfp s) { if ((sign >= 0 && s.sign >= 0) || (sign < 0 && s.sign < 0)) { // Sign is currently OK return this; } return negate(); // flip sign } /** {@inheritDoc} * @since 3.2 */ public Dfp copySign(final double s) { long sb = Double.doubleToLongBits(s); if ((sign >= 0 && sb >= 0) || (sign < 0 && sb < 0)) { // Sign is currently OK return this; } return negate(); // flip sign } /** {@inheritDoc} * @since 3.2 */ public Dfp scalb(final int n) { return multiply(DfpMath.pow(getTwo(), n)); } /** {@inheritDoc} * @since 3.2 */ public Dfp hypot(final Dfp y) { return multiply(this).add(y.multiply(y)).sqrt(); } /** {@inheritDoc} * @since 3.2 */ public Dfp cbrt() { return rootN(3); } /** {@inheritDoc} * @since 3.2 */ public Dfp rootN(final int n) { return (sign >= 0) ? DfpMath.pow(this, getOne().divide(n)) : DfpMath.pow(negate(), getOne().divide(n)).negate(); } /** {@inheritDoc} * @since 3.2 */ public Dfp pow(final double p) { return DfpMath.pow(this, newInstance(p)); } /** {@inheritDoc} * @since 3.2 */ public Dfp pow(final int n) { return DfpMath.pow(this, n); } /** {@inheritDoc} * @since 3.2 */ public Dfp pow(final Dfp e) { return DfpMath.pow(this, e); } /** {@inheritDoc} * @since 3.2 */ public Dfp exp() { return DfpMath.exp(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp expm1() { return DfpMath.exp(this).subtract(getOne()); } /** {@inheritDoc} * @since 3.2 */ public Dfp log() { return DfpMath.log(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp log1p() { return DfpMath.log(this.add(getOne())); } // TODO: deactivate this implementation (and return type) in 4.0 /** Get the exponent of the greatest power of 10 that is less than or equal to abs(this). * @return integer base 10 logarithm * @deprecated as of 3.2, replaced by {@link #intLog10()}, in 4.0 the return type * will be changed to Dfp */ @Deprecated public int log10() { return intLog10(); } // TODO: activate this implementation (and return type) in 4.0 // /** {@inheritDoc} // * @since 3.2 // */ // public Dfp log10() { // return DfpMath.log(this).divide(DfpMath.log(newInstance(10))); // } /** {@inheritDoc} * @since 3.2 */ public Dfp cos() { return DfpMath.cos(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp sin() { return DfpMath.sin(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp tan() { return DfpMath.tan(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp acos() { return DfpMath.acos(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp asin() { return DfpMath.asin(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp atan() { return DfpMath.atan(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp atan2(final Dfp x) throws DimensionMismatchException { // compute r = sqrt(x^2+y^2) final Dfp r = x.multiply(x).add(multiply(this)).sqrt(); if (x.sign >= 0) { // compute atan2(y, x) = 2 atan(y / (r + x)) return getTwo().multiply(divide(r.add(x)).atan()); } else { // compute atan2(y, x) = +/- pi - 2 atan(y / (r - x)) final Dfp tmp = getTwo().multiply(divide(r.subtract(x)).atan()); final Dfp pmPi = newInstance((tmp.sign <= 0) ? -FastMath.PI : FastMath.PI); return pmPi.subtract(tmp); } } /** {@inheritDoc} * @since 3.2 */ public Dfp cosh() { return DfpMath.exp(this).add(DfpMath.exp(negate())).divide(2); } /** {@inheritDoc} * @since 3.2 */ public Dfp sinh() { return DfpMath.exp(this).subtract(DfpMath.exp(negate())).divide(2); } /** {@inheritDoc} * @since 3.2 */ public Dfp tanh() { final Dfp ePlus = DfpMath.exp(this); final Dfp eMinus = DfpMath.exp(negate()); return ePlus.subtract(eMinus).divide(ePlus.add(eMinus)); } /** {@inheritDoc} * @since 3.2 */ public Dfp acosh() { return multiply(this).subtract(getOne()).sqrt().add(this).log(); } /** {@inheritDoc} * @since 3.2 */ public Dfp asinh() { return multiply(this).add(getOne()).sqrt().add(this).log(); } /** {@inheritDoc} * @since 3.2 */ public Dfp atanh() { return getOne().add(this).divide(getOne().subtract(this)).log().divide(2); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final Dfp[] a, final Dfp[] b) throws DimensionMismatchException { if (a.length != b.length) { throw new DimensionMismatchException(a.length, b.length); } Dfp r = getZero(); for (int i = 0; i < a.length; ++i) { r = r.add(a[i].multiply(b[i])); } return r; } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final double[] a, final Dfp[] b) throws DimensionMismatchException { if (a.length != b.length) { throw new DimensionMismatchException(a.length, b.length); } Dfp r = getZero(); for (int i = 0; i < a.length; ++i) { r = r.add(b[i].multiply(a[i])); } return r; } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final Dfp a1, final Dfp b1, final Dfp a2, final Dfp b2) { return a1.multiply(b1).add(a2.multiply(b2)); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final double a1, final Dfp b1, final double a2, final Dfp b2) { return b1.multiply(a1).add(b2.multiply(a2)); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final Dfp a1, final Dfp b1, final Dfp a2, final Dfp b2, final Dfp a3, final Dfp b3) { return a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3)); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final double a1, final Dfp b1, final double a2, final Dfp b2, final double a3, final Dfp b3) { return b1.multiply(a1).add(b2.multiply(a2)).add(b3.multiply(a3)); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final Dfp a1, final Dfp b1, final Dfp a2, final Dfp b2, final Dfp a3, final Dfp b3, final Dfp a4, final Dfp b4) { return a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3)).add(a4.multiply(b4)); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final double a1, final Dfp b1, final double a2, final Dfp b2, final double a3, final Dfp b3, final double a4, final Dfp b4) { return b1.multiply(a1).add(b2.multiply(a2)).add(b3.multiply(a3)).add(b4.multiply(a4)); } }
[ "kesina@Kesinas-MBP.lan" ]
kesina@Kesinas-MBP.lan
c5acdde9cbf308171f1ba0b10f333e40f209dc04
74d992a2fa73bd6695c2eb7decc11d7b0896f087
/robotframework-selenium2library-java-master/src/main/java/com/github/markusbernhardt/selenium2library/keywords/TableElement.java
f8755a89abf84ca7d7b0eff9365cbb20e9c45219
[ "Apache-2.0" ]
permissive
lakshmi592/robotframework-project
931cd2f6f2c677fdfb49c8403b87f1b90cfe760d
ca18aa36011b46726d75cf8bdcb5a5ee03d39f61
refs/heads/master
2020-06-21T00:02:33.661428
2019-07-17T01:48:40
2019-07-17T01:48:40
197,294,221
0
0
null
null
null
null
UTF-8
Java
false
false
11,752
java
package com.github.markusbernhardt.selenium2library.keywords; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.Autowired; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords; import com.github.markusbernhardt.selenium2library.RunOnFailureKeywordsAdapter; import com.github.markusbernhardt.selenium2library.Selenium2LibraryNonFatalException; import com.github.markusbernhardt.selenium2library.locators.TableElementFinder; @RobotKeywords public class TableElement extends RunOnFailureKeywordsAdapter { /** * Instantiated BrowserManagement keyword bean */ @Autowired protected BrowserManagement browserManagement; /** * Instantiated Logging keyword bean */ @Autowired protected Logging logging; // ############################## // Keywords // ############################## @RobotKeywordOverload public String getTableCell(String tableLocator, int row, int column) { return getTableCell(tableLocator, row, column, "INFO"); } /** * Returns the content of the table cell at the coordinates <b>row</b> and * <b>column</b> of the table identified by <b>tableLocator</b>.<br> * <br> * Row and column number start from 1. Header and footer rows are included * in the count. That way also cell content from header or footer rows can * be obtained with this keyword.<br> * <br> * Key attributes for tables are id and name. See `Introduction` for details * about locators and log levels.<br> * * @param tableLocator * The locator to locate the table. * @param row * The table row. * @param column * The table column. * @param logLevel * Default=INFO. Optional log level. * @return The table cell content. */ @RobotKeyword @ArgumentNames({ "tableLocator", "row", "column", "logLevel=INFO" }) public String getTableCell(String tableLocator, int row, int column, String logLevel) { int rowIndex = row - 1; int columnIndex = column - 1; WebElement table = TableElementFinder.find(browserManagement.getCurrentWebDriver(), tableLocator); if (table != null) { List<WebElement> rows = table.findElements(By.xpath("./thead/tr")); if (rowIndex >= rows.size()) { rows.addAll(table.findElements(By.xpath("./tbody/tr"))); } if (rowIndex >= rows.size()) { rows.addAll(table.findElements(By.xpath("./tfoot/tr"))); } if (rowIndex < rows.size()) { List<WebElement> columns = rows.get(rowIndex).findElements(By.tagName("th")); if (columnIndex >= columns.size()) { columns.addAll(rows.get(rowIndex).findElements(By.tagName("td"))); } if (columnIndex < columns.size()) { return columns.get(columnIndex).getText(); } } } logging.logSource(logLevel); throw new Selenium2LibraryNonFatalException(String.format( "Cell in table %s in row #%d and column #%d could not be found.", tableLocator, row, column)); } @RobotKeywordOverload public void tableCellShouldContain(String tableLocator, int row, int column, String text) { tableCellShouldContain(tableLocator, row, column, text, "INFO"); } /** * Verify the content of the table cell at the coordinates <b>row</b> and * <b>column</b> of the table identified by <b>tableLocator</b> contains * <b>text</b>.<br> * <br> * Row and column number start from 1. Header and footer rows are included * in the count. That way also cell content from header or footer rows can * be obtained with this keyword.<br> * <br> * Key attributes for tables are id and name. See `Introduction` for details * about locators and log levels.<br> * * @param tableLocator * The locator to locate the table. * @param row * The table row. * @param column * The table column. * @param text * The text to verify. * @param logLevel * Default=INFO. Optional log level. */ @RobotKeyword @ArgumentNames({ "tableLocator", "row", "column", "text", "logLevel=INFO" }) public void tableCellShouldContain(String tableLocator, int row, int column, String text, String logLevel) { String message = String.format("Cell in table '%s' in row #%d and column #%d should have contained text '%s'.", tableLocator, row, column, text); String content = ""; try { content = getTableCell(tableLocator, row, column, logLevel); } catch (AssertionError err) { logging.info(err.getMessage()); throw new Selenium2LibraryNonFatalException(message); } logging.info(String.format("Cell contains %s.", content)); if (!content.contains(text)) { logging.logSource(logLevel); throw new Selenium2LibraryNonFatalException(message); } } @RobotKeywordOverload public void tableColumnShouldContain(String tableLocator, int col, String text) { tableColumnShouldContain(tableLocator, col, text, "INFO"); } /** * Verify the content of any table cells of the table <b>column</b> of the * table identified by <b>tableLocator</b> contains <b>text</b>.<br> * <br> * Key attributes for tables are id and name. See `Introduction` for details * about locators and log levels.<br> * <br> * The first leftmost column is column number 1. If the table contains cells * that span multiple columns, those merged cells count as a single column. * For example both tests below work, if in one row columns A and B are * merged with colspan="2", and the logical third column contains "C".<br> * <br> * Example: * <table border="1" cellspacing="0"> * <tr> * <td>Table Column Should Contain</td> * <td>tableId</td> * <td>3</td> * <td>C</td> * </tr> * <tr> * <td>Table Column Should Contain</td> * <td>tableId</td> * <td>2</td> * <td>C</td> * </tr> * </table> * * @param tableLocator * The locator to locate the table. * @param col * The table column. * @param text * The text to verify. * @param logLevel * Default=INFO. Optional log level. */ @RobotKeyword @ArgumentNames({ "tableLocator", "col", "text", "logLevel=INFO" }) public void tableColumnShouldContain(String tableLocator, int col, String text, String logLevel) { WebElement element = TableElementFinder.findByCol(browserManagement.getCurrentWebDriver(), tableLocator, col, text); if (element == null) { logging.logSource(logLevel); throw new Selenium2LibraryNonFatalException(String.format( "Column #%d in table identified by '%s' should have contained text '%s'.", col, tableLocator, text)); } } @RobotKeywordOverload public void tableFooterShouldContain(String tableLocator, String text) { tableFooterShouldContain(tableLocator, text, "INFO"); } /** * Verify the content of any table footer cells of the table identified by * <b>tableLocator</b> contains <b>text</b>.<br> * <br> * Key attributes for tables are id and name. See `Introduction` for details * about locators and log levels.<br> * * @param tableLocator * The locator to locate the table. * @param text * The text to verify. * @param logLevel * Default=INFO. Optional log level. */ @RobotKeyword @ArgumentNames({ "tableLocator", "text", "logLevel=INFO" }) public void tableFooterShouldContain(String tableLocator, String text, String logLevel) { WebElement element = TableElementFinder.findByFooter(browserManagement.getCurrentWebDriver(), tableLocator, text); if (element == null) { logging.logSource(logLevel); throw new Selenium2LibraryNonFatalException(String.format( "Footer in table identified by '%s' should have contained text '%s'.", tableLocator, text)); } } @RobotKeywordOverload public void tableHeaderShouldContain(String tableLocator, String text) { tableHeaderShouldContain(tableLocator, text, "INFO"); } /** * Verify the content of any table header cells of the table identified by * <b>tableLocator</b> contains <b>text</b>.<br> * <br> * Key attributes for tables are id and name. See `Introduction` for details * about locators and log levels.<br> * * @param tableLocator * The locator to locate the table. * @param text * The text to verify. * @param logLevel * Default=INFO. Optional log level. */ @RobotKeyword @ArgumentNames({ "tableLocator", "text", "logLevel=INFO" }) public void tableHeaderShouldContain(String tableLocator, String text, String logLevel) { WebElement element = TableElementFinder.findByHeader(browserManagement.getCurrentWebDriver(), tableLocator, text); if (element == null) { logging.logSource(logLevel); throw new Selenium2LibraryNonFatalException(String.format( "Header in table identified by '%s' should have contained text '%s'.", tableLocator, text)); } } @RobotKeywordOverload public void tableRowShouldContain(String tableLocator, int row, String text) { tableRowShouldContain(tableLocator, row, text, "INFO"); } /** * Verify the content of any table cells of the table <b>row</b> of the * table identified by <b>tableLocator</b> contains <b>text</b>.<br> * <br> * Key attributes for tables are id and name. See `Introduction` for details * about locators and log levels.<br> * <br> * The uppermost row is row number 1. For tables that are structured with * thead, tbody and tfoot, only the tbody section is searched. Please use * Table Header Should Contain or Table Footer Should Contain for tests * against the header or footer content.<br> * <br> * If the table contains cells that span multiple rows, a match only occurs * for the uppermost row of those merged cells.<br> * * @param tableLocator * The locator to locate the table. * @param row * The table row. * @param text * The text to verify. * @param logLevel * Default=INFO. Optional log level. */ @RobotKeyword @ArgumentNames({ "tableLocator", "row", "text", "logLevel=INFO" }) public void tableRowShouldContain(String tableLocator, int row, String text, String logLevel) { WebElement element = TableElementFinder.findByRow(browserManagement.getCurrentWebDriver(), tableLocator, row, text); if (element == null) { logging.logSource(logLevel); throw new Selenium2LibraryNonFatalException(String.format( "Row #%d in table identified by '%s' should have contained text '%s'.", row, tableLocator, text)); } } @RobotKeywordOverload public void tableShouldContain(String tableLocator, String text) { tableShouldContain(tableLocator, text, "INFO"); } /** * Verify the content of any table cells of the table identified by * <b>tableLocator</b> contains <b>text</b>.<br> * <br> * Key attributes for tables are id and name. See `Introduction` for details * about locators and log levels.<br> * * @param tableLocator * The locator to locate the table. * @param text * The text to verify. * @param logLevel * Default=INFO. Optional log level. */ @RobotKeyword @ArgumentNames({ "tableLocator", "text", "logLevel=INFO" }) public void tableShouldContain(String tableLocator, String text, String logLevel) { WebElement element = TableElementFinder.findByContent(browserManagement.getCurrentWebDriver(), tableLocator, text); if (element == null) { logging.logSource(logLevel); throw new Selenium2LibraryNonFatalException(String.format( "Table identified by '%s' should have contained text '%s'.", tableLocator, text)); } } }
[ "noreply@github.com" ]
lakshmi592.noreply@github.com
9fd711f4af9c51b795b2e7f8b369eacec58e1ad8
4810edc242ec66add1094d502b4481193b93be08
/Development/source/EnglishEveryday/app/src/main/java/com/me/englisheveryday/services/BootReceiver.java
1af03adf1af66e0298234cc7ea1ae2b565ca7e14
[]
no_license
hotaduc125/englisheveryday
1a962b871a42e3118f853b64b9ddbb4128021e4a
413857a8974f9c1800dfab869528a0109ad81eed
refs/heads/master
2021-01-10T10:07:48.875481
2016-03-29T07:39:04
2016-03-29T07:39:04
54,187,079
0
0
null
null
null
null
UTF-8
Java
false
false
757
java
package com.me.englisheveryday.services; import android.appwidget.AppWidgetManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import com.me.englisheveryday.provider.EnglishWidgetProvider; /** * Created by enclaveit on 3/22/16. */ public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(context, EnglishWidgetProvider.class)); if (ids.length > 0) { Alarm.getInstance().setAlarm(context); } } }
[ "alvin@enclave.vn" ]
alvin@enclave.vn
fc22374954dcbcf677c5ba6d023a760cdfc4713f
43136bddffe010dca0305dec6f929e80708bf1f7
/src/main/java/com/example/demo/checkAutowire/UserInfoService1.java
54ec35aa41131db73c804fb00d7391ed04ad6e7c
[]
no_license
Sonal-Kodulkar/GitPractice1
ec28c337607fd0f707aa3752a1fe9a5096b9ab1b
21716ceb3570a8950e5046dc0cf0806dee732501
refs/heads/master
2023-01-02T18:38:01.654913
2020-10-28T13:25:15
2020-10-28T13:25:15
307,960,440
0
0
null
null
null
null
UTF-8
Java
false
false
546
java
package com.example.demo.checkAutowire; import org.springframework.stereotype.Component; @Component public class UserInfoService1 { private String msg; // @Override // public String toString() { // return "UserInfoService1{" + // "msg='" + msg + '\'' + // '}'; // } public String getMsg() { return msg; } public String setMsg(String msg) { this.msg = msg; return msg; } // public UserInfoService1(String msg) { // this.msg = msg; // } }
[ "sonal.kodulkar@example.com" ]
sonal.kodulkar@example.com
d1fe595cfa613d6b9ddc7c6004e25df1adefca68
e5c59200aca89a2cabd7cbb7b553401e89ba5de4
/predictweasel/src/main/java/org/leastweasel/predict/web/domain/ResetPasswordRequest.java
0db68f6f8b147545834749733322f37762b5dca8
[]
no_license
leastweasel/PredictWeasel
140c3e367bdba7f81dedd2505a3ba3afcae7f658
f433756eb441f7d1c32162ba92527180f9a1368e
refs/heads/master
2016-09-05T21:25:29.621552
2015-03-10T22:24:45
2015-03-10T22:24:45
20,028,946
0
0
null
null
null
null
UTF-8
Java
false
false
1,932
java
/** * The Least Weasel Organisation * Copyright (C) 2004-2014 by Andrew Gillies */ package org.leastweasel.predict.web.domain; import static org.leastweasel.predict.domain.User.MIN_PASSWORD_LENGTH; import javax.validation.constraints.Size; import org.apache.commons.lang.StringUtils; import org.hibernate.validator.constraints.NotBlank; /** * The command object used when a user resets their password and enters a new one. */ public class ResetPasswordRequest { private String password; private String confirmPassword; private String passwordReminder; /** * Get the user's new password. * * @return the new password */ @NotBlank @Size(min=MIN_PASSWORD_LENGTH) public String getPassword() { return password; } /** * Set the user's new password. Removes external whitespace and replaces blank strings with * null. * * @param password the new password */ public void setPassword(String password) { this.password = StringUtils.trimToNull(password); } /** * Get the password reminder. * * @return the password reminder */ public String getPasswordReminder() { return passwordReminder; } public void setPasswordReminder(String passwordReminder) { this.passwordReminder = passwordReminder; } /** * Get the confirmation of the user's password. This is only retrieved for validation: it is * not persisted. */ public String getConfirmPassword() { return confirmPassword; } /** * Set the confirmation of the user's password. Removes external whitespace and replaces blank * strings with null. * * @param confirmPassword the password confirmation */ public void setConfirmPassword(String confirmPassword) { this.confirmPassword = StringUtils.trimToNull(confirmPassword); } }
[ "andrew@leastweasel.org" ]
andrew@leastweasel.org
736be30b7a2037bc4b5a694937675210a9744df3
117cdfe3d94c2d9cce90aaa8e95f3afa92d17eba
/src/test/java/reactor/core/support/LogTests.java
d63939df0e7ba0cd2e50e07b12f06f9c76be7b92
[ "Apache-2.0" ]
permissive
bclozel/reactor-core
735aff5b32e2902d008662229ca07a7858ac5059
0e23c5297efb2dc96ff06f0402308486d607aa31
refs/heads/master
2020-04-02T20:58:37.210367
2016-01-20T10:33:50
2016-01-20T10:33:50
50,024,160
0
0
null
2016-01-20T10:55:50
2016-01-20T10:55:50
null
UTF-8
Java
false
false
1,477
java
/* * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.core.support; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import org.junit.Test; /** * @author Stephane Maldini */ public class LogTests { static Logger log = Logger.getLogger(LogTests.class); @Test public void testExtension() throws Exception { AtomicInteger count = new AtomicInteger(); Logger.Extension extension = (c, level, msg, args) -> { if(level == Level.FINEST) { System.out.println("extension"); count.incrementAndGet(); } }; log.trace("test"); Logger.enableExtension(extension); log.trace("test"); log.trace("test"); log.info("test"); log.debug("test"); log.debug("test"); Logger.disableExtension(extension); log.trace("test"); Assert.isTrue(count.get() == 2, "Extension should have been used by 2 traces only"); } }
[ "smaldini@pivotal.io" ]
smaldini@pivotal.io
d21b59310405ff490e8891efd22550007649f203
29d7f1473d423e5b6f7ad6cdca9a5fcebb77aad7
/EVA_EXAMEN_SEGUNDA_OPORTUNIDAD/src/Nodo.java
c99c4ddba44a9b5711016e98858d99d63749abaf
[]
no_license
DanielPonce99/SEGUNDA-OPORTUNIDAD
718c91ac655b1970aca08601fceb1b31a4378b7b
bc612a2a8dbde287e2a57e1cc3a1c74e21f0ae20
refs/heads/master
2020-06-01T13:24:12.013326
2019-06-07T18:53:50
2019-06-07T18:53:50
190,793,810
0
0
null
null
null
null
UTF-8
Java
false
false
720
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author invitado */ public class Nodo { //ATRIBUTOS DATOS private int dato; //ATRIBUTO PARA CREAR LA LISTA (REFERENCIAS) private Nodo sig; public Nodo() { this.sig = null; } public Nodo(int dato) { this.dato = dato; } public int getDato() { return dato; } public void setDato(int dato) { this.dato = dato; } public Nodo getSig() { return sig; } public void setSig(Nodo sig) { this.sig = sig; } }
[ "invitado@iMac-de-administrador-16.local" ]
invitado@iMac-de-administrador-16.local
456a4b5c03c295275c258d2afc5afc13255a77ee
15d9127e26a176d5eafcefba195acd058365cc5d
/src/main/java/assignment/web/HomeController.java
9276cede2c6b5f69257a47566f1ca169e5c3130d
[]
no_license
simon998yang/assignment
9f236832d312fe146146f129017f8ba8a99044ca
6f8b83eaeaffe902269ae8ace9131ce09fb53844
refs/heads/master
2016-09-14T13:13:48.724950
2016-04-15T12:02:41
2016-04-15T12:02:41
56,312,609
0
0
null
null
null
null
UTF-8
Java
false
false
536
java
package assignment.web; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeController { @Value("${application.authorName:Simon}") private String authorName = ""; @RequestMapping("/") String home() { return "home"; } @ModelAttribute("authorName") public String getAuthorName() { return this.authorName; } }
[ "simon998.yang@gmail.com" ]
simon998.yang@gmail.com
86a2bbaedc89928216123e41f6e8344a85510134
116403f45c50c2ff0952400a932d7467b87aaf62
/src/main/java/io/github/oaschi/paperwarp/PWUtils.java
9105339a1732d633ee06cb1bb559da12d8d70a4f
[]
no_license
derheimel/PaperWarp
f3c853e267348d67aadc554448f6cb615b61a516
d443b531b24aa4424d0baea08d6bd9c8a2b700d4
refs/heads/master
2021-01-19T09:42:12.999396
2014-05-22T14:36:08
2014-05-22T14:36:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
566
java
package io.github.oaschi.paperwarp; public class PWUtils { public static String stripLeadingHyphens(String str){ if(str == null) return null; if(str.startsWith("-")){ return str.substring(1); } if(str.startsWith("--")){ return str.substring(2); } return str; } public static String combineStringArray(String[] args, char seperator){ if(args.length == 0) return null; String combinedString = ""; for(String str : args){ combinedString += str + seperator; } return combinedString.substring(0, combinedString.length() - 1); } }
[ "aarooon@gmx.at" ]
aarooon@gmx.at
4c8ddde201e7e83d700c7e8807cc0f32633a27e2
8cd0b0c83bb5df2ba859c609b802e399156b07c0
/Java/SpringDemo/Spring_AOP_dynamicProxy/src/com/pb/ActionTest.java
d054a65228c0c41cf04280ba40dffbb275090eaa
[]
no_license
schangxiang/Code
132d487da67565433425d0d55d078f8fe64638f0
09899b46e3d030257fda54bae0c4c231801ac8a8
refs/heads/master
2022-12-09T11:49:28.457231
2019-08-14T01:31:45
2019-08-14T01:31:45
148,011,117
0
0
null
2022-12-08T05:52:33
2018-09-09T09:28:53
HTML
GB18030
Java
false
false
324
java
package com.pb; public class ActionTest { public static void main(String[] args) { //创建代理对象iuserServ LogHandler handler = new LogHandler(); IUserServ iuserServ = (IUserServ)handler.createProxy(new UserServImpl()); iuserServ.deleteUserById(new User()); } }
[ "schangxiang@126.com" ]
schangxiang@126.com
5154c654cc788ce9aa1f22081e1f445d161abcaa
3fd356f6977b9ff11abc51ead9e225892ff0c442
/charm-dynac-interface-app/src/test/java/com/cgi/charm/dynac/mapping/msi/MsiControlRequestTest.java
e3cdc99257db900b2712dd28a9f0feebb1446c5b
[]
no_license
kommurunagendra/MulesoftExamples
b8989c0e15413d0f4ab57521be929e86765c45ff
888a2434709440f1a7a0bae92c296809eeb9cf11
refs/heads/master
2023-05-14T17:03:46.772434
2021-06-11T13:44:05
2021-06-11T13:44:05
376,017,579
0
0
null
null
null
null
UTF-8
Java
false
false
798
java
package com.cgi.charm.dynac.mapping.msi; import org.custommonkey.xmlunit.Transform; import org.junit.Test; import com.cgi.charm.dynac.mapping.XsltTest; /** * @author CHARM CGI TEAM */ public class MsiControlRequestTest extends XsltTest { public MsiControlRequestTest() { super("xslt/msi/transformToControlReqCDM.xsl"); } @Override protected void configParameters(Transform testTransform) { testTransform.setParameter("current_time_in_millis", "1445503691000"); testTransform.setParameter("message_uuid", "00767d19-ca89-4451-af9c-537d25f6a369"); } @Test public void shouldTestControlReqMsi() throws Exception { expectTransformResult( "messages/msi/mocked_dms_control_reqest.xml", "messages/msi/mocked_msi_control_request.xml"); } }
[ "nagendrareddyk@Nagendras-MacBook-Pro.local" ]
nagendrareddyk@Nagendras-MacBook-Pro.local
cb3115d75927b78fff41e90494eeb4a2a7d877c4
3893c0a1b138b24ffb55c81bb58140b8b0ee7723
/JKBD-master/app/src/main/java/com/example/myapplication/bean/BaseInfo.java
9dc28f846e9095f34473aa29f14feaf6da3c1dff
[]
no_license
yufeilong92/jkbd_2018.12.5
999af23c801d255027878f0d49588635f5c86f7d
6f3f1236f62acfe0b1c820bc4ad6eb1cfd214684
refs/heads/master
2020-04-09T18:12:28.768402
2018-12-05T11:01:54
2018-12-05T11:01:54
160,504,853
0
0
null
null
null
null
UTF-8
Java
false
false
606
java
package com.example.myapplication.bean; /** * 实体类基类 * <p> * Created by Mjj on 2016/12/20. */ public class BaseInfo { private int code; private String success; private String msg; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getSuccess() { return success; } public void setSuccess(String success) { this.success = success; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
[ "931697478@qq.com" ]
931697478@qq.com
2d81449470fcbe602314860efe4787c4f70884d7
e9f8dfe7ba3a684260610934e08d2570ca578744
/source/1_JAVA/ch15_exception/src/com/lec/ex03_exceptionExs/Friend.java
a8ad0a2d769869cd369941c5145e47d46c24f39c
[]
no_license
cherryuki/bigdata
87864d6058ae23d854c3b146d11dc7fc2bc3f8eb
928a1a302977017c47724edb5b5a722484cdcfb4
refs/heads/main
2023-04-16T20:32:14.017057
2021-04-30T12:37:57
2021-04-30T12:37:57
317,099,037
0
0
null
null
null
null
UTF-8
Java
false
false
792
java
package com.lec.ex03_exceptionExs; //20-12-16_Exception ⓒcherryuki(ji) import java.text.SimpleDateFormat; import java.util.Date; public class Friend { private String name; private String tel; private Date enterDate; public Friend(String name, String tel) { this.name=name; this.tel=tel; enterDate=new Date(); } @Override public String toString() { String post = tel.substring(tel.lastIndexOf("-")+1); SimpleDateFormat sdf = new SimpleDateFormat("yyyy년도 친구됨"); return "Friend [name=" + name + ", tel=***-****-"+post+", "+sdf.format(enterDate)+"]"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } }
[ "cherry__love@naver.com" ]
cherry__love@naver.com
bcfa6d188edf233ae3d9f7e5a29d13676d9eb5d2
7c44073a75cedb1511f2bc156dd2458b3b383cc6
/app/src/main/java/zhaoliang/com/android52/ui/day07/sdcardbroad/SDCardBroadActivity.java
c41bf432b9e6258c0e406e2eec63c0c284ed04ca
[]
no_license
BruceAnda/Android52
480d7b4ba7bfcac85d738999cc6919066122bdac
8bb4191d6fb789f33a09005550b329802dd70e65
refs/heads/master
2021-01-23T01:41:29.560725
2017-04-26T06:29:36
2017-04-26T06:29:36
64,477,380
1
0
null
null
null
null
UTF-8
Java
false
false
378
java
package zhaoliang.com.android52.ui.day07.sdcardbroad; import android.app.Activity; import android.os.Bundle; import zhaoliang.com.android52.R; public class SDCardBroadActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sdcard_broad); } }
[ "2668645098@qq.com" ]
2668645098@qq.com
3fe8d185be7a17a1e04d12b7934771f2157e2185
7534af566339f6de278d83a46286e2e0a6c41e11
/tzapi4android/src/main/java/com/tianzunchina/android/api/login/User.java
6295c302ebf6aae80fb3b93afd975300e5c5faf4
[]
no_license
sljjyy/TZAPIForAndroid
6441f322c0cfc104f217cb0e9d60eed2b730d536
a2db0d83624b30c3c65a98d4d7bb297d082f05cb
refs/heads/master
2021-01-17T04:13:12.104678
2017-12-14T09:33:20
2017-12-14T09:33:20
52,776,215
5
1
null
null
null
null
UTF-8
Java
false
false
1,707
java
package com.tianzunchina.android.api.login; import android.content.Context; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.util.Map; /** * 用户实体类 * CraetTime 2016-3-3 * @author SunLiang */ public class User implements Serializable { private static final long serialVersionUID = 1L; private int ID; // 用户编号 private String account; //登陆名 用户名 private String password; private String name; // 真实姓名 private String IDCard; // 身份证号 private String phoneNum; // 手机号 private String address; // 居住地址 private String email; private String headPath; //头像路径 private String nickName;//昵称 private Map<String, String> attributeMap; // 获取人员情况构造函数 (参数 flag 为了区别2个不同的构造函数) public User(JSONObject json, Context context, int flag) throws JSONException { ID = json.getInt("UserID"); account = json.getString("Account"); } private boolean isNull(String str) { return null == str || "null".equals(str) || "".equals(str) || 0 == str.length(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (ID != user.ID) return false; return account != null ? account.equals(user.account) : user.account == null; } @Override public int hashCode() { int result = ID; result = 31 * result + (account != null ? account.hashCode() : 0); return result; } }
[ "sljjyy@hotmail.com" ]
sljjyy@hotmail.com
8e4c108fa50b3ee03a0373f21eb787c00b19d3da
8d1a4839521728711b5a2b5482220524576b740e
/APPLICATION/JDK-UTILS/JavaCollectionExmaple/src/main/java/com/adarsh/collection/HashMapExample.java
8220248cec7cec8488ce31c04c5cf67b029348c5
[]
no_license
adarshkumarsingh83/java_jse
cad6d6fb10fe9173bcd3364ce70da7d185b67af3
01a8a5e110feebf4741e845472097ef312a1db96
refs/heads/master
2023-01-14T08:17:56.693872
2023-01-04T17:43:47
2023-01-04T17:43:47
22,602,920
2
0
null
2022-07-15T18:28:37
2014-08-04T12:17:06
Java
UTF-8
Java
false
false
10,616
java
package com.adarsh.collection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Created with IntelliJ IDEA. * User: Adarsh_K * Date: 2/18/14 * Time: 8:34 PM * To change this template use File | Settings | File Templates. */ public class HashMapExample { public static void main(String[] args) { } public static void hashMapBasicOperattion() { HashMap<String, String> hm = new HashMap<String, String>(); //add key-value pair to hashmap hm.put("first", "FIRST INSERTED"); hm.put("second", "SECOND INSERTED"); hm.put("third", "THIRD INSERTED"); System.out.println(hm); //getting value for the given key from hashmap System.out.println("Value of second: " + hm.get("second")); System.out.println("Is HashMap empty? " + hm.isEmpty()); hm.remove("third"); System.out.println(hm); System.out.println("Size of the HashMap: " + hm.size()); } /*How to iterate through HashMap*/ public static void hashMapIteration() { final HashMap<String, String> hm = new HashMap<String, String>(); //add key-value pair to hashmap hm.put("first", "FIRST INSERTED"); hm.put("second", "SECOND INSERTED"); hm.put("third", "THIRD INSERTED"); System.out.println(hm); final Set<String> keys = hm.keySet(); for (String key : keys) { System.out.println("Value of " + key + " is: " + hm.get(key)); } } /*How to copy Map content to another HashMap*/ public static void hashMapCopy() { final HashMap<String, String> hm = new HashMap<String, String>(); //add key-value pair to hashmap hm.put("first", "FIRST INSERTED"); hm.put("second", "SECOND INSERTED"); hm.put("third", "THIRD INSERTED"); System.out.println(hm); HashMap<String, String> subMap = new HashMap<String, String>(); subMap.put("s1", "S1 VALUE"); subMap.put("s2", "S2 VALUE"); hm.putAll(subMap); System.out.println(hm); } /*How to search a key in HashMap*/ public static void hashMapSearchKey() { final HashMap<String, String> hm = new HashMap<String, String>(); //add key-value pair to hashmap hm.put("first", "FIRST INSERTED"); hm.put("second", "SECOND INSERTED"); hm.put("third", "THIRD INSERTED"); System.out.println(hm); if (hm.containsKey("first")) { System.out.println("The hashmap contains key first"); } else { System.out.println("The hashmap does not contains key first"); } if (hm.containsKey("fifth")) { System.out.println("The hashmap contains key fifth"); } else { System.out.println("The hashmap does not contains key fifth"); } } /*How to get all keys from HashMap*/ public static void hashMapGetAllKey() { final HashMap<String, String> hm = new HashMap<String, String>() { { //add key-value pair to hashmap put("first", "FIRST INSERTED"); put("second", "SECOND INSERTED"); put("third", "THIRD INSERTED"); } }; System.out.println(hm); Set<String> keys = hm.keySet(); for (String key : keys) { System.out.println(key); } } /*How to get entry set from HashMap*/ public static void hashMapGetEntrySet() { final HashMap<String, String> hm = new HashMap<String, String>(); //add key-value pair to hashmap hm.put("first", "FIRST INSERTED"); hm.put("second", "SECOND INSERTED"); hm.put("third", "THIRD INSERTED"); System.out.println(hm); //getting value for the given key from hashmap Set<Map.Entry<String, String>> entires = hm.entrySet(); for (Map.Entry<String, String> ent : entires) { System.out.println(ent.getKey() + " ==> " + ent.getValue()); } } /*How to delete all elements from HashMap*/ public static void hashSetDeleteAllElement() { final HashMap<String, String> hm = new HashMap<String, String>(); //add key-value pair to hashmap hm.put("first", "FIRST INSERTED"); hm.put("second", "SECOND INSERTED"); hm.put("third", "THIRD INSERTED"); System.out.println("My HashMap content:"); System.out.println(hm); System.out.println("Clearing HashMap:"); hm.clear(); System.out.println("Content After clear:"); System.out.println(hm); } /*How to eliminate duplicate user defined objects as a key from HashMap*/ public static void hashSetEliminateDuplicate() { final class Price{ private String item; private int price; public Price(String itm, int pr){ this.item = itm; this.price = pr; } public int hashCode(){ int hashcode = 0; hashcode = price*20; hashcode += item.hashCode(); return hashcode; } public boolean equals(Object obj){ if (obj instanceof Price) { Price pp = (Price) obj; return (pp.item.equals(this.item) && pp.price == this.price); } else { return false; } } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String toString(){ return "item: "+item+" price: "+price; } } final HashMap<Price, String> hm = new HashMap<Price, String>(); hm.put(new Price("Banana", 20), "Banana"); hm.put(new Price("Apple", 40), "Apple"); hm.put(new Price("Orange", 30), "Orange"); Set<Price> keys = hm.keySet(); for(Price p:keys){ System.out.println(p+"==>"+hm.get(p)); } Price key = new Price("Banana", 20); System.out.println("Adding duplicate key..."); hm.put(key, "Grape"); System.out.println("After adding dulicate key:"); Set<Price> keys1 = hm.keySet(); for(Price p:keys1){ System.out.println(p+"==>"+hm.get(p)); } } /*How to find user defined objects as a key from HashMap*/ public static void hashMapCustomObjectAsKey(){ final class Price{ private String item; private int price; public Price(String itm, int pr){ this.item = itm; this.price = pr; } public int hashCode(){ System.out.println("In hashcode"); int hashcode = 0; hashcode = price*20; hashcode += item.hashCode(); return hashcode; } public boolean equals(Object obj){ System.out.println("In equals"); if (obj instanceof Price) { Price pp = (Price) obj; return (pp.item.equals(this.item) && pp.price == this.price); } else { return false; } } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String toString(){ return "item: "+item+" price: "+price; } } final HashMap<Price, String> hm = new HashMap<Price, String>(); hm.put(new Price("Banana", 20), "Banana"); hm.put(new Price("Apple", 40), "Apple"); hm.put(new Price("Orange", 30), "Orange"); Set<Price> keys = hm.keySet(); for(Price p:keys){ System.out.println(p+"==>"+hm.get(p)); } Price key = new Price("Banana", 20); System.out.println("Does key available? "+hm.containsKey(key)); } /*How to delete user defined objects as a key from HashMap*/ public static void hashMapCustomObjectDelete(){ final class Price{ private String item; private int price; public Price(String itm, int pr){ this.item = itm; this.price = pr; } public int hashCode(){ System.out.println("In hashcode"); int hashcode = 0; hashcode = price*20; hashcode += item.hashCode(); return hashcode; } public boolean equals(Object obj){ System.out.println("In equals"); if (obj instanceof Price) { Price pp = (Price) obj; return (pp.item.equals(this.item) && pp.price == this.price); } else { return false; } } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String toString(){ return "item: "+item+" price: "+price; } } final HashMap<Price, String> hm = new HashMap<Price, String>(); hm.put(new Price("Banana", 20), "Banana"); hm.put(new Price("Apple", 40), "Apple"); hm.put(new Price("Orange", 30), "Orange"); Set<Price> keys = hm.keySet(); for(Price p:keys){ System.out.println(p+"==>"+hm .get(p)); } Price key = new Price("Banana", 20); System.out.println("Deleting key..."); hm.remove(key); System.out.println("After deleting key:"); Set<Price> keys1 = hm.keySet(); for(Price p:keys1){ System.out.println(p+"==>"+hm.get(p)); } } }
[ "us-guest@USMB113823-2.local" ]
us-guest@USMB113823-2.local
28f81c3d0e1aa19a0a181fa32b4caa852cbbee93
c978b38042c719e28265a67f6638b6ad0ccd27a5
/src/CrackingTheCodingInterview/Q15_06_Synchronized_Methods/Question.java
a5f35f6816f241beb46d96ef6199a09e99269e2c
[]
no_license
gspyadav/LeetCodeFishercoder
2a2a70c47608db75df9b847260067196f03d785a
0f135f2a468466f783ce763b6666c34f17b17bd0
refs/heads/master
2023-07-11T04:44:58.018418
2023-06-26T07:04:09
2023-06-26T07:04:09
192,256,996
1
1
null
null
null
null
UTF-8
Java
false
false
1,191
java
package CrackingTheCodingInterview.Q15_06_Synchronized_Methods; public class Question { /** * @param args */ public static void main(String[] args) { /* Part 1 Demo -- same instance */ System.out.println("Part 1 Demo with same instance."); Foo fooA = new Foo("ObjectOne"); MyThread thread1a = new MyThread(fooA, "Dog", "A"); MyThread thread2a = new MyThread(fooA, "Cat", "A"); thread1a.start(); thread2a.start(); while (thread1a.isAlive() || thread2a.isAlive()) { }; System.out.println("\n\n"); /* Part 1 Demo -- difference instances */ System.out.println("Part 1 Demo with different instances."); Foo fooB1 = new Foo("ObjectOne"); Foo fooB2 = new Foo("ObjectTwo"); MyThread thread1b = new MyThread(fooB1, "Dog", "A"); MyThread thread2b = new MyThread(fooB2, "Cat", "A"); thread1b.start(); thread2b.start(); while (thread1b.isAlive() || thread2b.isAlive()) { }; System.out.println("\n\n"); /* Part 2 Demo */ System.out.println("Part 2 Demo."); Foo fooC = new Foo("ObjectOne"); MyThread thread1c = new MyThread(fooC, "Dog", "A"); MyThread thread2c = new MyThread(fooC, "Cat", "B"); thread1c.start(); thread2c.start(); } }
[ "gspyadav.m@gmail.com" ]
gspyadav.m@gmail.com
ea754cde2b46bcab28ed5848b0bab2c5c362dc9a
347556ea0c25735a70f08c45e1de72b50baa966f
/app/src/main/java/com/mtpv/LawnOrder/WitnessFormActivity.java
2cf314331030db7928bf209448930fcd0f7aa6a8
[]
no_license
mtpvgithub/MtpvChallan
a5993479a45bfd33935763abae8608232bdf7d35
a7540d6dc776fe668895b9ec960db1c04fe2e74d
refs/heads/master
2021-01-24T08:50:26.462432
2017-06-14T08:39:45
2017-06-14T08:39:45
93,390,695
0
1
null
null
null
null
UTF-8
Java
false
false
108,864
java
package com.mtpv.LawnOrder; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.text.Html; import android.text.InputFilter; import android.text.InputType; import android.util.Base64; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.button.R; import com.mtpv.LawnOrder.OffenderActivity.AsyncGetDLDetails; import com.mtpv.LawnOrder.OffenderActivity.AsyncGetIDDetails; import com.mtpv.LawnOrder.OffenderActivity.AsyncGetRCDetails; public class WitnessFormActivity extends Activity { public static final String witnessDetails = null; public static String ET_WitnessDetails ="NA"; List<String> list; public static TextView wt_gender, wt_gender2, wt_gender3, wt_gender4; public static String wt_id1_Spinner = null; public static String wt_id2_Spinner = null; public static String wt_id3_Spinner = null; public static String wt_id4_Spinner = null, ET_Gender=null, ET_Gender2=null, ET_Gender3=null, ET_Gender4=null; public static StringBuffer previewWitnessPromtBuf=new StringBuffer(); public static EditText witness_name, witness_fname, witness_age, witness_dob, witness_phone, witness_address, witness_city, witness_state, id_text_wtns, witness_name2, witness_fname2, witness_age2, witness_phone2, witness_address2, witness_city2, witness_id2,id_text_wtns2, witness_name3, witness_fname3, witness_age3, witness_phone3, witness_address3, witness_city3, witness_id3,id_text_wtns3, witness_name4, witness_fname4, witness_age4, witness_phone4, witness_address4, witness_city4, witness_id4,id_text_wtns4 ; Button wt_submit_btn, add_witns, remve_witns2,remve_witns3, remve_witns4; ImageView wt_details,wt_details2,wt_details3,wt_details4,back_btn, submit_btn; LinearLayout wt_layout2, wt_layout3, wt_layout4 ; RadioGroup wt_gender_group, wt_gender_group2, wt_gender_group3, wt_gender_group4; RadioButton wt_male, wt_female, wt_others, wt_male2, wt_female2, wt_others2, wt_male3, wt_female3, wt_others3, wt_male4, wt_female4, wt_others4; @SuppressWarnings("unused") private Calendar cal; @SuppressWarnings("unused") private int day; @SuppressWarnings("unused") private int month; @SuppressWarnings("unused") private int year; int clickcount = 0; Spinner witness_id_options, witness_id_options2, witness_id_options3, witness_id_options4; public static String selectedID=""; public static String selectedID2=""; public static String selectedID3=""; public static String selectedID4=""; static Map<String,String> idMap=null; TextView witness; ImageView details, details2, details3, details4; EditText wt_id_details, wt_id_details2, wt_id_details3, wt_id_details4 ; public static String id1_Spinner = null; public static String id2_Spinner = null; public static String id3_Spinner = null; public static String id4_Spinner = null; public static Map<String,String>get_detailsmap1=new HashMap<String,String >(); public static Map<String,String>get_detailsmap2=new HashMap<String,String >(); public static Map<String,String>get_detailsmap3=new HashMap<String,String >(); public static Map<String,String>get_detailsmap4=new HashMap<String,String >(); public static boolean get_detailsFlg1=false,get_detailsFlg2=false,get_detailsFlg3=false,get_detailsFlg4=false; public static String NAMESPACE = "http://service.mother.com"; public static String SOAP_ACTION_ID = NAMESPACE + "getDetailsByAADHAR", challanResponse; public static String challanGenresp =""; final int PROGRESS_DIALOG = 1; @SuppressWarnings("unused") @SuppressLint("ShowToast") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_witness_form); cal = Calendar.getInstance(); day = cal.get(Calendar.DAY_OF_MONTH); month = cal.get(Calendar.MONTH); year = cal.get(Calendar.YEAR); WitnessFormActivity.previewWitnessPromtBuf=new StringBuffer(); details = (ImageView)findViewById(R.id.details); details2 = (ImageView)findViewById(R.id.details2); details3 = (ImageView)findViewById(R.id.details3); details4 = (ImageView)findViewById(R.id.details4); wt_id_details = (EditText)findViewById(R.id.wt_id_details); wt_id_details2 = (EditText)findViewById(R.id.wt_id_details2); wt_id_details3 = (EditText)findViewById(R.id.wt_id_details3); wt_id_details4 = (EditText)findViewById(R.id.wt_id_details4); witness = (TextView)findViewById(R.id.witness); witness_name = (EditText)findViewById(R.id.witness_name); witness_fname = (EditText)findViewById(R.id.witness_fname); witness_age = (EditText)findViewById(R.id.witness_age); witness_phone = (EditText)findViewById(R.id.witness_phone); witness_address = (EditText)findViewById(R.id.witness_address); witness_city = (EditText)findViewById(R.id.witness_city); //wt_id_details = (EditText)findViewById(R.id.wt_id_details); witness_id_options = (Spinner)findViewById(R.id.witness_id_options); witness_name2 = (EditText)findViewById(R.id.witness_name2); witness_fname2 = (EditText)findViewById(R.id.witness_fname2); witness_age2 = (EditText)findViewById(R.id.witness_age2); witness_phone2 = (EditText)findViewById(R.id.witness_phone2); witness_address2 = (EditText)findViewById(R.id.witness_address2); witness_city2 = (EditText)findViewById(R.id.witness_city2); //wt_id_details2 = (EditText)findViewById(R.id.wt_id_details2); witness_id_options2 = (Spinner)findViewById(R.id.witness_id_options2); witness_name3 = (EditText)findViewById(R.id.witness_name3); witness_fname3 = (EditText)findViewById(R.id.witness_fname3); witness_age3 = (EditText)findViewById(R.id.witness_age3); witness_phone3 = (EditText)findViewById(R.id.witness_phone3); witness_address3 = (EditText)findViewById(R.id.witness_address3); witness_city3 = (EditText)findViewById(R.id.witness_city3); //wt_id_details3 = (EditText)findViewById(R.id.wt_id_details3); witness_id_options3 = (Spinner)findViewById(R.id.witness_id_options3); witness_name4 = (EditText)findViewById(R.id.witness_name4); witness_fname4 = (EditText)findViewById(R.id.witness_fname4); witness_age4 = (EditText)findViewById(R.id.witness_age4); witness_phone4 = (EditText)findViewById(R.id.witness_phone4); witness_address4 = (EditText)findViewById(R.id.witness_address4); witness_city4 = (EditText)findViewById(R.id.witness_city4); //wt_id_details4 = (EditText)findViewById(R.id.wt_id_details4); witness_id_options4 = (Spinner)findViewById(R.id.witness_id_options4); wt_layout2 = (LinearLayout)findViewById(R.id.wt_layout2); wt_layout3 = (LinearLayout)findViewById(R.id.wt_layout3); wt_layout4 = (LinearLayout)findViewById(R.id.wt_layout4); wt_gender_group = (RadioGroup)findViewById(R.id.wt_gender_group); wt_male = (RadioButton)findViewById(R.id.wt_male); wt_female = (RadioButton)findViewById(R.id.wt_female); wt_others = (RadioButton)findViewById(R.id.wt_other); wt_gender = (TextView)findViewById(R.id.wt_gender); wt_gender_group.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub switch (checkedId) { case R.id.wt_male: wt_gender.setText("M"); // Toast.makeText(getApplicationContext(), "Your gender is Male", Toast.LENGTH_SHORT).show(); break; case R.id.wt_female: wt_gender.setText("F"); // Toast.makeText(getApplicationContext(), "Your gender is Female", Toast.LENGTH_SHORT).show(); break; case R.id.wt_other: wt_gender.setText("O"); // Toast.makeText(getApplicationContext(), "Your gender is other", Toast.LENGTH_SHORT).show(); break; } } }); wt_gender_group2 = (RadioGroup)findViewById(R.id.wt_gender_group2); wt_male2 = (RadioButton)findViewById(R.id.wt_male2); wt_female2 = (RadioButton)findViewById(R.id.wt_female2); wt_others2 = (RadioButton)findViewById(R.id.wt_other2); wt_gender2 = (TextView)findViewById(R.id.wt_gender2); wt_gender_group2.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub switch (checkedId) { case R.id.wt_male2: wt_gender2.setText("M"); // Toast.makeText(getApplicationContext(), "Your gender is Male", Toast.LENGTH_SHORT).show(); break; case R.id.wt_female2: wt_gender2.setText("F"); // Toast.makeText(getApplicationContext(), "Your gender is Female", Toast.LENGTH_SHORT).show(); break; case R.id.wt_other2: wt_gender2.setText("O"); // Toast.makeText(getApplicationContext(), "Your gender is other", Toast.LENGTH_SHORT).show(); break; } } }); wt_gender_group3 = (RadioGroup)findViewById(R.id.wt_gender_group3); wt_male3 = (RadioButton)findViewById(R.id.wt_male3); wt_female3 = (RadioButton)findViewById(R.id.wt_female3); wt_others3 = (RadioButton)findViewById(R.id.wt_other3); wt_gender3 = (TextView)findViewById(R.id.wt_gender3); wt_gender_group3.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub switch (checkedId) { case R.id.wt_male3: wt_gender3.setText("M"); // Toast.makeText(getApplicationContext(), "Your gender is Male", Toast.LENGTH_SHORT).show(); break; case R.id.wt_female3: wt_gender3.setText("F"); // Toast.makeText(getApplicationContext(), "Your gender is Female", Toast.LENGTH_SHORT).show(); break; case R.id.wt_other3: wt_gender3.setText("O"); // Toast.makeText(getApplicationContext(), "Your gender is other", Toast.LENGTH_SHORT).show(); break; } } }); wt_gender_group4 = (RadioGroup)findViewById(R.id.wt_gender_group4); wt_male4 = (RadioButton)findViewById(R.id.wt_male4); wt_female4 = (RadioButton)findViewById(R.id.wt_female4); wt_others4 = (RadioButton)findViewById(R.id.wt_other4); wt_gender4 = (TextView)findViewById(R.id.wt_gender4); wt_gender_group4.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub switch (checkedId) { case R.id.wt_male4: wt_gender4.setText("M"); // Toast.makeText(getApplicationContext(), "Your gender is Male", Toast.LENGTH_SHORT).show(); break; case R.id.wt_female4: wt_gender4.setText("F"); // Toast.makeText(getApplicationContext(), "Your gender is Female", Toast.LENGTH_SHORT).show(); break; case R.id.wt_other4: wt_gender4.setText("O"); // Toast.makeText(getApplicationContext(), "Your gender is other", Toast.LENGTH_SHORT).show(); break; } } }); witness_id_options = (Spinner)findViewById(R.id.witness_id_options); idMap=new DataBase(getApplicationContext()).getIdMap(getApplicationContext()); list = new ArrayList<String>(); /*list.add("-Select ID");*/ for(String idCode: idMap.keySet()){ list.add(idMap.get(idCode)); } ArrayAdapter<String> adp = new ArrayAdapter<String> (this, R.layout.spinner_item, list); adp.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); witness_id_options.setAdapter(adp); witness_id_options.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub switch(arg2) { /*case 0 : wt_id_details.setHint("Enter ID Details"); wt_id_details.setText(""); break;*/ case 0 : wt_id_details.setHint(getLabel("1")); wt_id_details.setFilters(new InputFilter[] { new InputFilter.LengthFilter(12) }); wt_id_details.setInputType(InputType.TYPE_CLASS_NUMBER); wt_id_details.setText(""); break; case 1 : wt_id_details.setHint(getLabel("2")); wt_id_details.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details.setText(""); break; case 2 : wt_id_details.setHint(getLabel("3")); wt_id_details.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details.setText(""); break; case 3 : wt_id_details.setHint(getLabel("4")); wt_id_details.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details.setText(""); break; case 4 : wt_id_details.setHint(getLabel("5")); wt_id_details.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details.setText(""); break; case 5 : wt_id_details.setHint(getLabel("6")); wt_id_details.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details.setText(""); break; case 6 : wt_id_details.setHint(getLabel("7")); wt_id_details.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details.setText(""); break; case 7 : wt_id_details.setHint(getLabel("8")); wt_id_details.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) }); wt_id_details.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details.setInputType(InputType.TYPE_CLASS_NUMBER); wt_id_details.setText(""); break; case 8 : wt_id_details.setHint(getLabel("9")); wt_id_details.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details.setText(""); break; case 9 : wt_id_details.setHint(getLabel("10")); wt_id_details.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details.setText(""); break; default : wt_id_details.setHint("Nothing Selected"); break; } } public CharSequence getLabel(String selected) { String label=""; try { for(String idCode: WitnessFormActivity.idMap.keySet()){ if(idCode.equals(selected)){ label="ENTER "+WitnessFormActivity.idMap.get(idCode); WitnessFormActivity.selectedID=WitnessFormActivity.idMap.get(idCode).toString(); } } } catch (Exception e) { e.printStackTrace(); } Log.i("selected label name "+selected,label); return label; } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); witness_id_options2 = (Spinner)findViewById(R.id.witness_id_options2); idMap=new DataBase(getApplicationContext()).getIdMap(getApplicationContext()); list = new ArrayList<String>(); /*list.add("-Select ID");*/ for(String idCode: idMap.keySet()){ list.add(idMap.get(idCode)); } ArrayAdapter<String> adp2 = new ArrayAdapter<String> (this, R.layout.spinner_item, list); adp2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); witness_id_options2.setAdapter(adp2); witness_id_options2.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub switch(arg2) { /*case 0 : wt_id_details2.setHint("Enter ID Details"); wt_id_details2.setText(""); break;*/ case 0 : wt_id_details2.setHint(getLabel2("1")); wt_id_details2.setFilters(new InputFilter[] { new InputFilter.LengthFilter(12) }); wt_id_details2.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details2.setInputType(InputType.TYPE_CLASS_NUMBER); wt_id_details2.setText(""); break; case 1 : wt_id_details2.setHint(getLabel2("2")); wt_id_details2.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details2.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details2.setText(""); break; case 2 : wt_id_details2.setHint(getLabel2("3")); wt_id_details2.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details2.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details2.setText(""); break; case 3 : wt_id_details2.setHint(getLabel2("4")); wt_id_details2.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details2.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details2.setText(""); break; case 4 : wt_id_details2.setHint(getLabel2("5")); wt_id_details2.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details2.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details2.setText(""); break; case 5 : wt_id_details2.setHint(getLabel2("6")); wt_id_details2.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details2.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details2.setText(""); break; case 6 : wt_id_details2.setHint(getLabel2("7")); wt_id_details2.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details2.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details2.setText(""); break; case 7 : wt_id_details2.setHint(getLabel2("8")); wt_id_details2.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) }); wt_id_details2.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details2.setInputType(InputType.TYPE_CLASS_NUMBER); wt_id_details2.setText(""); break; case 8 : wt_id_details2.setHint(getLabel2("9")); wt_id_details2.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details2.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details2.setText(""); break; case 9 : wt_id_details2.setHint(getLabel2("10")); wt_id_details2.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details2.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details2.setText(""); break; default : wt_id_details2.setHint("Nothing Selected"); break; } } public CharSequence getLabel2(String selected) { String label=""; try { for(String idCode: WitnessFormActivity.idMap.keySet()){ if(idCode.equals(selected)){ label="ENTER "+WitnessFormActivity.idMap.get(idCode); WitnessFormActivity.selectedID2=WitnessFormActivity.idMap.get(idCode).toString(); } } } catch (Exception e) { e.printStackTrace(); } Log.i("selected label name "+selected,label); return label; } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); witness_id_options3 = (Spinner)findViewById(R.id.witness_id_options3); idMap=new DataBase(getApplicationContext()).getIdMap(getApplicationContext()); list = new ArrayList<String>(); /*list.add("-Select ID");*/ for(String idCode: idMap.keySet()){ list.add(idMap.get(idCode)); } ArrayAdapter<String> adp3 = new ArrayAdapter<String> (this, R.layout.spinner_item, list); adp3.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); witness_id_options3.setAdapter(adp2); witness_id_options3.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub switch(arg2) { /*case 0 : wt_id_details3.setHint("Enter ID Details"); wt_id_details3.setText(""); break;*/ case 0 : wt_id_details3.setHint(getLabel3("1")); wt_id_details3.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) }); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_NUMBER); wt_id_details3.setText(""); break; case 1 : wt_id_details3.setHint(getLabel3("2")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details3.setText(""); break; case 2 : wt_id_details3.setHint(getLabel3("3")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details3.setText(""); break; case 3 : wt_id_details3.setHint(getLabel3("4")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details3.setText(""); break; case 4 : wt_id_details3.setHint(getLabel3("5")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details3.setText(""); break; case 5 : wt_id_details3.setHint(getLabel3("6")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details3.setText(""); break; case 6 : wt_id_details3.setHint(getLabel3("7")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details3.setText(""); break; case 7 : wt_id_details3.setHint(getLabel3("8")); wt_id_details3.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) }); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details3.setText(""); break; case 8 : wt_id_details3.setHint(getLabel3("9")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details3.setText(""); break; case 9 : wt_id_details3.setHint(getLabel3("10")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details3.setText(""); break; default : wt_id_details3.setHint("Nothing Selected"); break; } } public CharSequence getLabel3(String selected) { String label=""; try { for(String idCode: WitnessFormActivity.idMap.keySet()){ if(idCode.equals(selected)){ label="ENTER "+WitnessFormActivity.idMap.get(idCode); WitnessFormActivity.selectedID3=WitnessFormActivity.idMap.get(idCode).toString(); } } } catch (Exception e) { e.printStackTrace(); } Log.i("selected label name "+selected,label); return label; } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); witness_id_options4 = (Spinner)findViewById(R.id.witness_id_options4); idMap=new DataBase(getApplicationContext()).getIdMap(getApplicationContext()); list = new ArrayList<String>(); /*list.add("-Select ID");*/ for(String idCode: idMap.keySet()){ list.add(idMap.get(idCode)); } ArrayAdapter<String> adp4 = new ArrayAdapter<String> (this,R.layout.spinner_item, list); adp3.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); witness_id_options4.setAdapter(adp4); witness_id_options4.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub switch(arg2) { /*case 0 : wt_id_details4.setHint("Enter ID Details"); wt_id_details4.setText(""); break;*/ case 0 : wt_id_details4.setHint(getLabel4("1")); wt_id_details4.setFilters(new InputFilter[] { new InputFilter.LengthFilter(12) }); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_NUMBER); wt_id_details4.setText(""); break; case 1 : wt_id_details4.setHint(getLabel4("2")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details4.setText(""); break; case 2 : wt_id_details4.setHint(getLabel4("3")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details4.setText(""); break; case 3 : wt_id_details4.setHint(getLabel4("4")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details4.setText(""); break; case 4 : wt_id_details4.setHint(getLabel4("5")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details4.setText(""); break; case 5 : wt_id_details4.setHint(getLabel4("6")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details4.setText(""); break; case 6 : wt_id_details4.setHint(getLabel4("7")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details4.setText(""); break; case 7 : wt_id_details4.setHint(getLabel4("8")); wt_id_details4.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) }); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_NUMBER); wt_id_details4.setText(""); break; case 8 : wt_id_details4.setHint(getLabel4("9")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details4.setText(""); break; case 9 : wt_id_details4.setHint(getLabel4("10")); wt_id_details3.setFilters(new InputFilter[] {new InputFilter.AllCaps()}); wt_id_details3.setInputType(InputType.TYPE_CLASS_TEXT); wt_id_details4.setText(""); break; default : wt_id_details4.setHint("Nothing Selected"); break; } } public CharSequence getLabel4(String selected) { String label=""; try { for(String idCode: WitnessFormActivity.idMap.keySet()){ if(idCode.equals(selected)){ label="ENTER "+WitnessFormActivity.idMap.get(idCode); WitnessFormActivity.selectedID4=WitnessFormActivity.idMap.get(idCode).toString(); } } } catch (Exception e) { e.printStackTrace(); } Log.i("selected label name "+selected,label); return label; } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); add_witns = (Button)findViewById(R.id.add_witns); add_witns.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub clickcount=clickcount+1; if(clickcount>3){ Toast toast = Toast.makeText(getApplicationContext(), "You Can Add Only Four Witness Details", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show(); } else{ if(clickcount==1){ wt_layout2.setVisibility(View.VISIBLE); } if(clickcount==2){ wt_layout3.setVisibility(View.VISIBLE); } if(clickcount==3){ wt_layout4.setVisibility(View.VISIBLE); add_witns.setVisibility(View.GONE); } } } }); remve_witns2 = (Button)findViewById(R.id.remve_witns2); remve_witns2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub clickcount=clickcount-1; wt_layout2.setVisibility(View.GONE); } }); remve_witns3 = (Button)findViewById(R.id.remve_witns3); remve_witns3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub clickcount=clickcount-1; wt_layout3.setVisibility(View.GONE); } }); remve_witns4 = (Button)findViewById(R.id.remve_witns4); remve_witns4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub clickcount=clickcount-1; wt_layout4.setVisibility(View.GONE); } }); details.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub get_detailsFlg2=false; get_detailsFlg3=false; get_detailsFlg4=false; get_detailsFlg1=true; if(WitnessFormActivity.selectedID.toString().trim().equals("AADHAAR NO")){ Log.i("id service called", "AADHAAR NO"); //AADHAR new AsyncGetIDDetails().execute(); }else if(WitnessFormActivity.selectedID.toString().trim().equals("DRIVING LICENCE")){ Log.i("id service called", "DRIVING LICENCE"); // DRIVING LICENSE new AsyncGetDLDetails().execute(); }else if(WitnessFormActivity.selectedID.toString().trim().equals("VEHICLE NO")){ Log.i("id service called", "VEHCILE NO"); // VEHICLLE RC new AsyncGetRCDetails().execute(); } } }); details2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub get_detailsFlg2=true; get_detailsFlg1=false; get_detailsFlg3=false; get_detailsFlg4=false; if(WitnessFormActivity.selectedID.toString().trim().equals("AADHAAR NO")){ Log.i("id service called", "AADHAAR NO"); //AADHAR new AsyncGetIDDetails().execute(); }else if(WitnessFormActivity.selectedID.toString().trim().equals("DRIVING LICENCE")){ Log.i("id service called", "DRIVING LICENCE"); // DRIVING LICENSE new AsyncGetDLDetails().execute(); }else if(WitnessFormActivity.selectedID.toString().trim().equals("VEHICLE NO")){ Log.i("id service called", "VEHCILE NO"); // VEHICLLE RC new AsyncGetRCDetails().execute(); } } }); details3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub get_detailsFlg3=true; get_detailsFlg1=false; get_detailsFlg2=false; get_detailsFlg4=false; if(WitnessFormActivity.selectedID.toString().trim().equals("AADHAAR NO")){ Log.i("id service called", "AADHAAR NO"); //AADHAR new AsyncGetIDDetails().execute(); }else if(WitnessFormActivity.selectedID.toString().trim().equals("DRIVING LICENCE")){ Log.i("id service called", "DRIVING LICENCE"); // DRIVING LICENSE new AsyncGetDLDetails().execute(); }else if(WitnessFormActivity.selectedID.toString().trim().equals("VEHICLE NO")){ Log.i("id service called", "VEHCILE NO"); // VEHICLLE RC new AsyncGetRCDetails().execute(); } } }); details4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub get_detailsFlg4=true; get_detailsFlg1=false; get_detailsFlg3=false; get_detailsFlg2=false; if(WitnessFormActivity.selectedID.toString().trim().equals("AADHAAR NO")){ Log.i("id service called", "AADHAAR NO"); //AADHAR new AsyncGetIDDetails().execute(); }else if(WitnessFormActivity.selectedID.toString().trim().equals("DRIVING LICENCE")){ Log.i("id service called", "DRIVING LICENCE"); // DRIVING LICENSE new AsyncGetDLDetails().execute(); }else if(WitnessFormActivity.selectedID.toString().trim().equals("VEHICLE NO")){ Log.i("id service called", "VEHCILE NO"); // VEHICLLE RC new AsyncGetRCDetails().execute(); } } }); witness_phone = (EditText)findViewById(R.id.witness_phone); witness_address = (EditText)findViewById(R.id.witness_address); witness_city = (EditText)findViewById(R.id.witness_city); // witness_state = (EditText)findViewById(R.id.witness_state); back_btn = (ImageView)findViewById(R.id.back_btn); if(!PreviewActivity.witnesFlg){ back_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub WitnessFormActivity.previewWitnessPromtBuf=null; finish(); } }); }else { back_btn.setVisibility(View.GONE); } submit_btn = (ImageView)findViewById(R.id.submit_btn); submit_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Boolean valdflg=true; Boolean wtFLG2 =false ; Boolean wtFLG3 =false ; Boolean wtFLG4 =false ; if (wt_layout2.getVisibility() == View.VISIBLE) { wtFLG2 = true ; }else if (wt_layout3.getVisibility() == View.VISIBLE) { wtFLG3 = true ; }else if (wt_layout4.getVisibility() == View.VISIBLE) { wtFLG4 = true ; } if(witness.getVisibility() == View.VISIBLE){ if(witness_name.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_name.setError(Html.fromHtml("<font color='black'>Please Enter Name</font>")); witness_name.requestFocus(); valdflg=false; } else if(witness_fname.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_fname.setError(Html.fromHtml("<font color='black'>Please Enter Father Name</font>")); witness_fname.requestFocus(); valdflg=false; } else if(witness_age.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_age.setError(Html.fromHtml("<font color='black'>Please Enter Age</font>")); witness_age.requestFocus(); valdflg=false; } else if(witness_phone.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_phone.setError(Html.fromHtml("<font color='black'>Please Enter Mobile No</font>")); witness_phone.requestFocus(); valdflg=false; } else if(!validateMobileNo(witness_phone.getText().toString())){ new AlertDialog.Builder(WitnessFormActivity.this) .setTitle("Mobile Number Status") .setMessage("Please Enter Valid Mobile Number") .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Your code witness_phone.requestFocus(); } }) .show(); valdflg=false; } else if(witness_address.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_address.setError(Html.fromHtml("<font color='black'>Please Enter Address</font>")); witness_address.requestFocus(); valdflg=false; } else if(witness_city.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_city.setError(Html.fromHtml("<font color='black'>Please Enter City/District</font>")); witness_city.requestFocus(); valdflg=false; } else if(wt_gender_group.getCheckedRadioButtonId() == -1) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ showToast("Please Select Gender"); valdflg=false; } } else if (wt_layout2.getVisibility()==View.VISIBLE && wtFLG2) { if(witness_name2.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_name2.setError(Html.fromHtml("<font color='black'>Please Enter Name</font>")); witness_name2.requestFocus(); valdflg=false; } else if(witness_fname2.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_fname2.setError(Html.fromHtml("<font color='black'>Please Enter Father Name</font>")); witness_fname2.requestFocus(); valdflg=false; } else if(witness_age2.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_age2.setError(Html.fromHtml("<font color='black'>Please Enter Age</font>")); witness_age2.requestFocus(); valdflg=false; } else if(witness_phone2.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_phone2.setError(Html.fromHtml("<font color='black'>Please Enter Mobile No</font>")); witness_phone2.requestFocus(); valdflg=false; } else if(!validateMobileNo(witness_phone2.getText().toString())){ new AlertDialog.Builder(WitnessFormActivity.this) .setTitle("Mobile Number Status") .setMessage("Please Enter Valid Mobile Number") .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Your code witness_phone2.requestFocus(); } }) .show(); valdflg=false; } else if(witness_address2.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_address2.setError(Html.fromHtml("<font color='black'>Please Enter Address</font>")); witness_address2.requestFocus(); valdflg=false; } else if(witness_city2.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_city2.setError(Html.fromHtml("<font color='black'>Please Enter City/District</font>")); witness_city2.requestFocus(); valdflg=false; } else if(wt_gender_group2.getCheckedRadioButtonId() == -1) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ showToast("Please Select Gender"); valdflg=false; } } else if (wt_layout3.getVisibility()==View.VISIBLE && wtFLG3) { if(witness_name3.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_name3.setError(Html.fromHtml("<font color='black'>Please Enter Name</font>")); witness_name3.requestFocus(); valdflg=false; } else if(witness_fname3.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_fname3.setError(Html.fromHtml("<font color='black'>Please Enter Father Name</font>")); witness_fname3.requestFocus(); valdflg=false; } else if(witness_age3.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_age3.setError(Html.fromHtml("<font color='black'>Please Enter Age</font>")); witness_age3.requestFocus(); valdflg=false; } else if(witness_phone3.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_phone3.setError(Html.fromHtml("<font color='black'>Please Enter Mobile No</font>")); witness_phone3.requestFocus(); valdflg=false; } else if(!validateMobileNo(witness_phone3.getText().toString())){ new AlertDialog.Builder(WitnessFormActivity.this) .setTitle("Mobile Number Status") .setMessage("Please Enter Valid Mobile Number") .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Your code witness_phone3.requestFocus(); } }) .show(); valdflg=false; } else if(witness_address3.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_address3.setError(Html.fromHtml("<font color='black'>Please Enter Address</font>")); witness_address3.requestFocus(); valdflg=false; } else if(witness_city3.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_city3.setError(Html.fromHtml("<font color='black'>Please Enter City/District</font>")); witness_city3.requestFocus(); valdflg=false; } else if(wt_gender_group3.getCheckedRadioButtonId() == -1) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ showToast("Please Select Gender"); valdflg=false; } } else if (wt_layout4.getVisibility()==View.VISIBLE && wtFLG4) { if(witness_name4.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_name4.setError(Html.fromHtml("<font color='black'>Please Enter Name</font>")); witness_name4.requestFocus(); valdflg=false; } else if(witness_fname4.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_fname4.setError(Html.fromHtml("<font color='black'>Please Enter Father Name</font>")); witness_fname4.requestFocus(); valdflg=false; } else if(witness_age4.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Name", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_age4.setError(Html.fromHtml("<font color='black'>Please Enter Age</font>")); witness_age4.requestFocus(); valdflg=false; } else if(witness_phone4.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_phone4.setError(Html.fromHtml("<font color='black'>Please Enter Mobile No</font>")); witness_phone4.requestFocus(); valdflg=false; } else if(!validateMobileNo(witness_phone4.getText().toString())){ new AlertDialog.Builder(WitnessFormActivity.this) .setTitle("Mobile Number Status") .setMessage("Please Enter Valid Mobile Number") .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Your code witness_phone4.requestFocus(); } }) .show(); valdflg=false; } else if(witness_address4.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_address4.setError(Html.fromHtml("<font color='black'>Please Enter Address</font>")); witness_address4.requestFocus(); valdflg=false; } else if(witness_city4.getText().toString().length()==0) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Phone Number", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ witness_city4.setError(Html.fromHtml("<font color='black'>Please Enter City/District</font>")); witness_city4.requestFocus(); valdflg=false; } else if(wt_gender_group4.getCheckedRadioButtonId() == -1) { /*Toast toast = Toast.makeText(getApplicationContext(), "Please Select Gender", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ showToast("Please Select Gender"); valdflg=false; } } if(valdflg){ try { Log.i("WitnessFormActivity.selectedID :", WitnessFormActivity.selectedID); wt_id1_Spinner=WitnessFormActivity.selectedID.trim().length()>1?WitnessFormActivity.selectedID.toString().trim():"NA"; wt_id2_Spinner=WitnessFormActivity.selectedID2.trim().length()>1?WitnessFormActivity.selectedID2.toString().trim():"NA"; wt_id3_Spinner=WitnessFormActivity.selectedID3.trim().length()>1?WitnessFormActivity.selectedID3.toString().trim():"NA"; wt_id4_Spinner=WitnessFormActivity.selectedID4.trim().length()>1?WitnessFormActivity.selectedID4.toString().trim():"NA"; ET_Gender = wt_gender.getText().toString(); JSONObject witnessobj1 = new JSONObject(); witnessobj1.put("witness_name", WitnessFormActivity.witness_name!=null?WitnessFormActivity.witness_name.getText().toString():""); witnessobj1.put("witness_fname", WitnessFormActivity.witness_fname!=null?WitnessFormActivity.witness_fname.getText().toString():""); witnessobj1.put("witness_age", WitnessFormActivity.witness_age!=null?WitnessFormActivity.witness_age.getText().toString():""); witnessobj1.put("witness_gender",ET_Gender); Log.i("Witness Gender ::",ET_Gender); witnessobj1.put("witness_phone", WitnessFormActivity.witness_phone!=null?WitnessFormActivity.witness_phone.getText().toString():""); witnessobj1.put("witness_address", WitnessFormActivity.witness_address!=null?WitnessFormActivity.witness_address.getText().toString():""); witnessobj1.put("witness_city", WitnessFormActivity.witness_city!=null?WitnessFormActivity.witness_city.getText().toString():""); witnessobj1.put("wt_id_details", wt_id_details.getText()!=null?wt_id_details.getText().toString():"NA"); witnessobj1.put("witness_id_code", getIDCode(wt_id1_Spinner)!=null?getIDCode(wt_id1_Spinner):"NA"); Log.i("witness_name.getText() Value :::",getIDCode(wt_id1_Spinner)); //Log.i("WitnessFormActivity.previewWitnessPromtBuf Value :::", WitnessFormActivity.previewWitnessPromtBuf+""); // if(witness_name.getText()!=null && witness_name.getText().toString().trim().length()>2){ WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 1 Name :").append(witness_name.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 1 Father Name :").append(witness_fname.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 1 DOB :").append(witness_age.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 1 Gender :").append(wt_gender.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 1 Mobile :").append(witness_phone.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 1 Address :").append(witness_address.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 1 City :").append(witness_city.getText().toString()); //WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 2 FPS :").append(); } ET_Gender2 = wt_gender2.getText().toString(); JSONObject witnessobj2 = new JSONObject(); witnessobj2.put("witness_name", WitnessFormActivity.witness_name2!=null?WitnessFormActivity.witness_name2.getText().toString():""); witnessobj2.put("witness_fname", WitnessFormActivity.witness_fname2!=null?WitnessFormActivity.witness_fname2.getText().toString():""); witnessobj2.put("witness_age", WitnessFormActivity.witness_name2!=null?WitnessFormActivity.witness_name2.getText().toString():""); witnessobj2.put("witness_gender", wt_gender2.getText().toString()); witnessobj2.put("witness_phone", WitnessFormActivity.witness_age2!=null?WitnessFormActivity.witness_age2.getText().toString():""); witnessobj2.put("witness_address", WitnessFormActivity.witness_address2!=null?WitnessFormActivity.witness_address2.getText().toString():""); witnessobj2.put("witness_city", WitnessFormActivity.witness_name2!=null?WitnessFormActivity.witness_name2.getText().toString():""); witnessobj2.put("wt_id_details", wt_id_details2.getText()!=null?wt_id_details2.getText().toString():"NA"); witnessobj2.put("witness_id_code", wt_id2_Spinner!=null?getIDCode2(wt_id2_Spinner):"NA"); Log.i("Spinner Value 2:::", getIDCode2(wt_id2_Spinner)); if(witness_name2.getText()!=null && witness_name2.getText().toString().trim().length()>2){ WitnessFormActivity.previewWitnessPromtBuf.append("\n\n Witness 2 Name :").append(witness_name2.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 2 Father Name :").append(witness_fname2.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 2 DOB :").append(witness_age2.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 2 Gender :").append(wt_gender2.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 2 Mobile :").append(witness_phone2.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 2 Address :").append(witness_address2.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 2 City :").append(witness_city2.getText().toString()); //WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 2 FPS :").append(); } ET_Gender3 = wt_gender3.getText().toString(); JSONObject witnessobj3 = new JSONObject(); witnessobj3.put("witness_name", WitnessFormActivity.witness_name3!=null?WitnessFormActivity.witness_name3.getText().toString():""); witnessobj3.put("witness_fname", WitnessFormActivity.witness_fname3!=null?WitnessFormActivity.witness_fname3.getText().toString():""); witnessobj3.put("witness_age", WitnessFormActivity.witness_age3!=null?WitnessFormActivity.witness_age3.getText().toString():""); witnessobj3.put("witness_gender", wt_gender3.getText()!=null?WitnessFormActivity.wt_gender3.getText().toString():"M"); witnessobj3.put("witness_phone", WitnessFormActivity.witness_phone3!=null?WitnessFormActivity.witness_phone3.getText().toString():""); witnessobj3.put("witness_address", WitnessFormActivity.witness_address3!=null?WitnessFormActivity.witness_address3.getText().toString():""); witnessobj3.put("witness_city", WitnessFormActivity.witness_city3!=null?WitnessFormActivity.witness_city3.getText().toString():""); witnessobj3.put("wt_id_details", wt_id_details3.getText()!=null?wt_id_details3.getText().toString():"NA"); witnessobj3.put("witness_id_code", wt_id3_Spinner!=null?getIDCode3(wt_id3_Spinner):"NA"); if(witness_name3.getText()!=null && witness_name3.getText().toString().trim().length()>2){ WitnessFormActivity.previewWitnessPromtBuf.append("\n\n Witness 3 Name :").append(witness_name3.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 3 Father Name :").append(witness_fname3.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 3 DOB :").append(witness_age3.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 3 Gender :").append(wt_gender3.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 3 Mobile :").append(witness_phone3.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 3 Address :").append(witness_address3.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 3 City :").append(witness_city3.getText().toString()); //WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 2 FPS :").append(); } ET_Gender4 = wt_gender4.getText().toString(); JSONObject witnessobj4 = new JSONObject(); witnessobj4.put("witness_name", WitnessFormActivity.witness_name4!=null?WitnessFormActivity.witness_name4.getText().toString():""); witnessobj4.put("witness_fname", WitnessFormActivity.witness_fname4!=null?WitnessFormActivity.witness_fname4.getText().toString():""); witnessobj4.put("witness_age", WitnessFormActivity.witness_age4!=null?WitnessFormActivity.witness_age4.getText().toString():""); witnessobj4.put("witness_gender", wt_gender4.getText().toString()); witnessobj4.put("witness_phone", WitnessFormActivity.witness_phone4!=null?WitnessFormActivity.witness_phone4.getText().toString():""); witnessobj4.put("witness_address", WitnessFormActivity.witness_address4!=null?WitnessFormActivity.witness_address4.getText().toString():""); witnessobj4.put("witness_city", WitnessFormActivity.witness_city4!=null?WitnessFormActivity.witness_city4.getText().toString():""); witnessobj4.put("wt_id_details", wt_id_details4.getText()!=null?wt_id_details4.getText().toString():"NA"); witnessobj4.put("witness_id_code", wt_id4_Spinner!=null?getIDCode4(wt_id4_Spinner):"NA"); if(witness_name4.getText()!=null && witness_name4.getText().toString().trim().length()>2){ WitnessFormActivity.previewWitnessPromtBuf.append("\n\n Witness 4 Name :").append(witness_name4.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 4 Father Name :").append(witness_fname4.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 4 DOB :").append(witness_age4.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 4 Gender :").append(wt_gender4.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 4 Mobile :").append(witness_phone4.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 4 Address :").append(witness_address4.getText().toString()); WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 4 City :").append(witness_city4.getText().toString()); //WitnessFormActivity.previewWitnessPromtBuf.append("\n Witness 2 FPS :").append(); } JSONArray witnessDetails = new JSONArray(); witnessDetails.put(witnessobj1); witnessDetails.put(witnessobj2); witnessDetails.put(witnessobj3); witnessDetails.put(witnessobj4); JSONObject witnessObj = new JSONObject(); witnessObj.put("Witness", witnessDetails); ET_WitnessDetails = witnessObj.toString(); /*String emailStr = email.getText().toString()*/ Log.i("ET_WitnessDetails ::",ET_WitnessDetails); Log.i("Witness Gender ::",WitnessFormActivity.wt_gender.getText().toString()); finish(); OffenderActivity.add_witness_tick.setVisibility(View.VISIBLE); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); try { if(WitnessFormActivity.ET_WitnessDetails!=null && WitnessFormActivity.ET_WitnessDetails.length()>10){ JSONObject jsonObj = new JSONObject(WitnessFormActivity.ET_WitnessDetails); // Getting JSON Array node JSONArray jsonArray = jsonObj.getJSONArray("Witness"); // looping through All Witness for (int i = 0, size = jsonArray.length(); i < size; i++) { JSONObject c = jsonArray.getJSONObject(i); //witness_id_code if(c.getString("witness_name")!=null && c.getString("witness_name").trim().length()>2){ String idCode=c.getString("witness_id_code"); String idDet=c.getString("wt_id_details"); if(i==0){ WitnessFormActivity.witness_name.setText(c.getString("witness_name")); WitnessFormActivity.witness_fname.setText(c.getString("witness_name")); WitnessFormActivity.witness_age.setText(c.getString("witness_age").toString()); if("M".equals(ET_Gender)){ wt_male.setChecked(true); }else if("F".equals(ET_Gender)){ wt_female.setChecked(true); }else if("O".equals(ET_Gender)){ wt_others.setChecked(true); } WitnessFormActivity.witness_phone.setText(c.getString("witness_phone").toString()); WitnessFormActivity.witness_address.setText(c.getString("witness_address").toString()); WitnessFormActivity.witness_city.setText(c.getString("witness_city").toString()); } else if(i==1){ wt_layout2.setVisibility(View.VISIBLE); WitnessFormActivity.witness_name2.setText(c.getString("witness_name")); WitnessFormActivity.witness_fname2.setText(c.getString("witness_name")); WitnessFormActivity.witness_age2.setText(c.getString("witness_age").toString()); if("M".equals(ET_Gender2)){ wt_male2.setChecked(true); }else if("F".equals(ET_Gender2)){ wt_female2.setChecked(true); }else if("O".equals(ET_Gender2)){ wt_others2.setChecked(true); } WitnessFormActivity.witness_phone2.setText(c.getString("witness_phone").toString()); WitnessFormActivity.witness_address2.setText(c.getString("witness_address").toString()); WitnessFormActivity.witness_city2.setText(c.getString("witness_city").toString()); }else if(i==2){ wt_layout3.setVisibility(View.VISIBLE); WitnessFormActivity.witness_name3.setText(c.getString("witness_name")); WitnessFormActivity.witness_fname3.setText(c.getString("witness_name")); WitnessFormActivity.witness_age3.setText(c.getString("witness_age").toString()); if("M".equals(ET_Gender3)){ wt_male3.setChecked(true); }else if("F".equals(ET_Gender3)){ wt_female3.setChecked(true); }else if("O".equals(ET_Gender3)){ wt_others3.setChecked(true); } WitnessFormActivity.witness_phone3.setText(c.getString("witness_phone").toString()); WitnessFormActivity.witness_address3.setText(c.getString("witness_address").toString()); WitnessFormActivity.witness_city3.setText(c.getString("witness_city").toString()); } else if(i==3){ wt_layout4.setVisibility(View.VISIBLE); WitnessFormActivity.witness_name4.setText(c.getString("witness_name")); WitnessFormActivity.witness_fname4.setText(c.getString("witness_name")); WitnessFormActivity.witness_age4.setText(c.getString("witness_age").toString()); if("M".equals(ET_Gender4)){ wt_male4.setChecked(true); }else if("F".equals(ET_Gender4)){ wt_female4.setChecked(true); }else if("O".equals(ET_Gender4)){ wt_others4.setChecked(true); } WitnessFormActivity.witness_phone4.setText(c.getString("witness_phone").toString()); WitnessFormActivity.witness_address4.setText(c.getString("witness_address").toString()); WitnessFormActivity.witness_city4.setText(c.getString("witness_city").toString()); } } } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }//on create end /******************** Get Details BY AADHAAR NO Class AsyncGetIDDetails Starts****************************/ class AsyncGetIDDetails extends AsyncTask<Void,Void, String>{ ProgressDialog dialog = new ProgressDialog(WitnessFormActivity.this); /* (non-Javadoc) * @see android.os.AsyncTask#doInBackground(java.lang.Object[]) */ @Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub Log.i("getIDDetails method called ", "YES"); try { String ip = ""; SQLiteDatabase db = openOrCreateDatabase(DataBase.DATABASE_NAME,MODE_PRIVATE, null); String selectQuery = "SELECT * FROM " + DataBase.IP_TABLE; // SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { Log.i("DATABASE IP VALUE :",""+ cursor.getString(0)); ip=cursor.getString(0); } while (cursor.moveToNext()); } db.close(); // INSERT ID PROOF DETAILS START SoapObject request = new SoapObject(NAMESPACE, "getDetailsByAADHAR"); Log.i("respondent_id_details :::::::::::::",wt_id_details.getText().toString()); if(get_detailsFlg1){ request.addProperty("UID", wt_id_details.getText().toString()); request.addProperty("EID", wt_id_details.getText().toString()); } if(get_detailsFlg2){ request.addProperty("UID", wt_id_details2.getText().toString()); request.addProperty("EID", wt_id_details2.getText().toString()); } if(get_detailsFlg3){ request.addProperty("UID", wt_id_details3.getText().toString()); request.addProperty("EID", wt_id_details3.getText().toString()); } if(get_detailsFlg4){ request.addProperty("UID", wt_id_details4.getText().toString()); request.addProperty("EID", wt_id_details4.getText().toString()); } SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); Log.i("request", "" + request); HttpTransportSE androidHttpTransport = new HttpTransportSE(ip+"/HydPettyCaseService/services/PettyCaseServiceImpl?wsdl"); Log.i("androidHttpTransport", "" + androidHttpTransport); androidHttpTransport.call(SOAP_ACTION_ID, envelope); Object result = envelope.getResponse(); challanGenresp=result.toString(); Log.i("** getDetailsByAADHAR response***", "" + challanGenresp); runOnUiThread(new Runnable() { public void run(){ // http://service.mother.com/HydPettyCaseService/services/PettyCaseServiceImpl?wsdl if(challanGenresp!=null && challanGenresp.length()>25 ){ try { JSONObject jsonObj = new JSONObject(challanGenresp); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("ID_DETAILS"); // looping through All Contacts JSONObject c = contacts.getJSONObject(0); Log.i("Name :::", c.getString("NAME")) ; Log.i("Father Name :::", c.getString("FNAME")) ; Log.i("DOB :::", c.getString("DOB")) ; Log.i("get_detailsFlg1 :::", ""+get_detailsFlg1) ; //15/05/1994 if(get_detailsFlg1){ witness_name.setText(c.getString("NAME")); witness_fname.setText(c.getString("FNAME")); /* witness_age.setText(c.getString("DOB").toString());*/ String date_birth = c.getString("DOB"); String[] split_dob = date_birth.split("/"); String service_year = "" + split_dob[2]; int final_age = year - Integer.parseInt(service_year); Log.i("final_age ::::::::", "" + final_age); witness_age.setText("" + final_age); if("M".equals(c.getString("GENDER"))){ wt_male.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address.setText(completeAddress); witness_phone.setText(c.getString("PHONE_NO").toString()); witness_city.setText(c.get("DISTRICT").toString()); Log.i("Image 1 byte[]",""+ Base64.decode(c.getString("IMAGE").toString().trim().getBytes(),1)); /*if(c.getString("IMAGE")!=null && c.getString("IMAGE").toString().trim().length()>100 ){ image1ByteArray=Base64.decode(c.getString("IMAGE").toString().trim().getBytes(),1); Bitmap bmp = BitmapFactory.decodeByteArray(image1ByteArray, 0, image1ByteArray.length); respondent_img1.setImageBitmap(bmp); }else { respondent_img1.setImageResource(R.drawable.photo); }*/ } if(get_detailsFlg2){ witness_name2.setText(c.getString("NAME")); witness_fname2.setText(c.getString("FNAME")); /* witness_age2.setText(c.getString("DOB").toString());*/ String date_birth = c.getString("DOB"); String [] split_dob = date_birth.split("\\/"); String service_year = ""+split_dob[2]; int final_age = year-Integer.parseInt(service_year); Log.i("final_age ::::::::", ""+final_age); witness_age2.setText(""+final_age); if("M".equals(c.getString("GENDER"))){ wt_male2.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female2.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others2.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address2.setText(completeAddress); witness_phone2.setText(c.getString("PHONE_NO").toString()); witness_city2.setText(c.get("DISTRICT").toString()); Log.i("Image 1 byte[]",""+ Base64.decode(c.getString("IMAGE").toString().trim().getBytes(),1)); /*if(c.getString("IMAGE")!=null && c.getString("IMAGE").toString().trim().length()>100 ){ image1ByteArray=Base64.decode(c.getString("IMAGE").toString().trim().getBytes(),1); Bitmap bmp = BitmapFactory.decodeByteArray(image1ByteArray, 0, image1ByteArray.length); respondent_img1.setImageBitmap(bmp); }else { respondent_img1.setImageResource(R.drawable.photo); }*/ } if(get_detailsFlg3){ witness_name3.setText(c.getString("NAME")); witness_fname3.setText(c.getString("FNAME")); /* witness_age3.setText(c.getString("DOB").toString());*/ String date_birth = c.getString("DOB"); String [] split_dob = date_birth.split("\\/"); String service_year = ""+split_dob[2]; int final_age = year-Integer.parseInt(service_year); Log.i("final_age ::::::::", ""+final_age); witness_age3.setText(""+final_age); if("M".equals(c.getString("GENDER"))){ wt_male3.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female3.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others3.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address3.setText(completeAddress); witness_phone3.setText(c.getString("PHONE_NO").toString()); witness_city3.setText(c.get("DISTRICT").toString()); Log.i("Image 1 byte[]",""+ Base64.decode(c.getString("IMAGE").toString().trim().getBytes(),1)); /*if(c.getString("IMAGE")!=null && c.getString("IMAGE").toString().trim().length()>100 ){ image1ByteArray=Base64.decode(c.getString("IMAGE").toString().trim().getBytes(),1); Bitmap bmp = BitmapFactory.decodeByteArray(image1ByteArray, 0, image1ByteArray.length); respondent_img1.setImageBitmap(bmp); }else { respondent_img1.setImageResource(R.drawable.photo); }*/ } if(get_detailsFlg4){ witness_name4.setText(c.getString("NAME")); witness_fname4.setText(c.getString("FNAME")); /* witness_age4.setText(c.getString("DOB").toString());*/ String date_birth = c.getString("DOB"); String [] split_dob = date_birth.split("\\/"); String service_year = ""+split_dob[2]; int final_age = year-Integer.parseInt(service_year); Log.i("final_age ::::::::", ""+final_age); witness_age4.setText(""+final_age); if("M".equals(c.getString("GENDER"))){ wt_male4.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female4.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others4.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address4.setText(completeAddress); witness_phone4.setText(c.getString("PHONE_NO").toString()); witness_city4.setText(c.get("DISTRICT").toString()); Log.i("Image 1 byte[]",""+ Base64.decode(c.getString("IMAGE").toString().trim().getBytes(),1)); /*if(c.getString("IMAGE")!=null && c.getString("IMAGE").toString().trim().length()>100 ){ image1ByteArray=Base64.decode(c.getString("IMAGE").toString().trim().getBytes(),1); Bitmap bmp = BitmapFactory.decodeByteArray(image1ByteArray, 0, image1ByteArray.length); respondent_img1.setImageBitmap(bmp); }else { respondent_img1.setImageResource(R.drawable.photo); }*/ } } catch(Exception e){ e.printStackTrace(); } }else{ Log.i("no data from service", "no "); /*Toast toast = Toast.makeText(getApplicationContext(), "No data Found", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ showToast("No Data Found"); } } }); // // INSERT ID PROOF DETAILS END } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); //showDialog(PROGRESS_DIALOG); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); showDialog(PROGRESS_DIALOG); } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); removeDialog(PROGRESS_DIALOG); if (!isNetworkAvailable()) { // do something AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(WitnessFormActivity.this); alertDialogBuilder.setMessage(" Mobile Data is Disabled in your Device \n Please Enable Mobile Data?") .setCancelable(false) .setPositiveButton("Ok", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int id){ } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } } } /******************** Get Details BY RC Class AsyncGetIDDetails Ends****************************/ /******************** Get Details BY Driving License Class AsyncGetDLDetails Starts****************************/ class AsyncGetDLDetails extends AsyncTask<Void,Void, String>{ ProgressDialog dialog = new ProgressDialog(WitnessFormActivity.this); @Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub Log.i("getDetailsByDrivingLicence method called ", "YES"); try { String ip = ""; SQLiteDatabase db = openOrCreateDatabase(DataBase.DATABASE_NAME,MODE_PRIVATE, null); String selectQuery = "SELECT * FROM " + DataBase.IP_TABLE; // SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { Log.i("DATABASE IP VALUE :",""+ cursor.getString(0)); ip=cursor.getString(0); } while (cursor.moveToNext()); } db.close(); // INSERT ID PROOF DETAILS START SoapObject request = new SoapObject(NAMESPACE, "getDetailsByDrivingLicence"); Log.i("respondent_id_details :::::::::::::",wt_id_details.getText().toString()); if(get_detailsFlg1){ request.addProperty("dl_no", wt_id_details.getText().toString()); } if(get_detailsFlg2){ request.addProperty("dl_no", wt_id_details2.getText().toString()); } if(get_detailsFlg3){ request.addProperty("dl_no", wt_id_details3.getText().toString()); } if(get_detailsFlg4){ request.addProperty("dl_no", wt_id_details4.getText().toString()); } // request.addProperty("EID", respondent_id_details.getText().toString()); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); Log.i("request", "" + request); HttpTransportSE androidHttpTransport = new HttpTransportSE(ip+"/HydPettyCaseService/services/PettyCaseServiceImpl?wsdl"); Log.i("androidHttpTransport", "" + androidHttpTransport); androidHttpTransport.call(SOAP_ACTION_ID, envelope); Object result = envelope.getResponse(); challanGenresp=result.toString(); Log.i("** getDetailsByDrivingLicence response***", "" + challanGenresp); runOnUiThread(new Runnable() { public void run(){ if(challanGenresp!=null && challanGenresp.length()>25 ){ try { JSONObject jsonObj = new JSONObject(challanGenresp); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("LICENSE_DETAILS"); // looping through All Contacts JSONObject c = contacts.getJSONObject(0); if(get_detailsFlg1){ witness_name.setText(c.getString("NAME")); witness_fname.setText(c.getString("FNAME")); witness_age.setText(c.getString("DOB").toString()); if("M".equals(c.getString("GENDER"))){ wt_male.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address.setText(completeAddress); witness_phone.setText(c.getString("PHONE_NO").toString()); } if(get_detailsFlg2){ witness_name2.setText(c.getString("NAME")); witness_fname2.setText(c.getString("FNAME")); witness_age2.setText(c.getString("DOB").toString()); if("M".equals(c.getString("GENDER"))){ wt_male2.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female2.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others2.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address2.setText(completeAddress); witness_phone2.setText(c.getString("PHONE_NO").toString()); } if(get_detailsFlg3){ witness_name3.setText(c.getString("NAME")); witness_fname3.setText(c.getString("FNAME")); witness_age3.setText(c.getString("DOB").toString()); if("M".equals(c.getString("GENDER"))){ wt_male3.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female3.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others3.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address3.setText(completeAddress); witness_phone3.setText(c.getString("PHONE_NO").toString()); } if(get_detailsFlg4){ witness_name4.setText(c.getString("NAME")); witness_fname4.setText(c.getString("FNAME")); witness_age4.setText(c.getString("DOB").toString()); if("M".equals(c.getString("GENDER"))){ wt_male4.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female4.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others4.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address4.setText(completeAddress); witness_phone4.setText(c.getString("PHONE_NO").toString()); } } catch(Exception e){ e.printStackTrace(); } }else{ Log.i("no data from service", "no "); /*Toast toast = Toast.makeText(getApplicationContext(), "No data Found", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ showToast("No Data Found"); } } }); // // INSERT ID PROOF DETAILS END } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); //showDialog(PROGRESS_DIALOG); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); showDialog(PROGRESS_DIALOG); } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); removeDialog(PROGRESS_DIALOG); if (!isNetworkAvailable()) { // do something AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(WitnessFormActivity.this); alertDialogBuilder.setMessage(" Mobile Data is Disabled in your Device \n Please Enable Mobile Data?") .setCancelable(false) .setPositiveButton("Ok", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int id){ } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } } } /******************** Get Details BY Driving License Class AsyncGetDLDetails Ends****************************/ /******************** Get Details BY RC Class AsyncGetRCDetails Starts****************************/ class AsyncGetRCDetails extends AsyncTask<Void,Void, String>{ ProgressDialog dialog = new ProgressDialog(WitnessFormActivity.this); @Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub Log.i("getDetailsByRC method called ", "YES"); try { String ip = ""; SQLiteDatabase db = openOrCreateDatabase(DataBase.DATABASE_NAME,MODE_PRIVATE, null); String selectQuery = "SELECT * FROM " + DataBase.IP_TABLE; // SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { Log.i("DATABASE IP VALUE :",""+ cursor.getString(0)); ip=cursor.getString(0); } while (cursor.moveToNext()); } db.close(); // INSERT ID PROOF DETAILS START SoapObject request = new SoapObject(NAMESPACE, "getDetailsByRC"); Log.i("respondent_id_details :::::::::::::",wt_id_details.getText().toString()); if(get_detailsFlg1){ request.addProperty("regn_no", wt_id_details.getText().toString()); } if(get_detailsFlg2){ request.addProperty("regn_no", wt_id_details2.getText().toString()); } if(get_detailsFlg3){ request.addProperty("regn_no", wt_id_details3.getText().toString()); } if(get_detailsFlg4){ request.addProperty("regn_no", wt_id_details4.getText().toString()); } // request.addProperty("EID", respondent_id_details.getText().toString()); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); Log.i("request", "" + request); HttpTransportSE androidHttpTransport = new HttpTransportSE(ip+"/HydPettyCaseService/services/PettyCaseServiceImpl?wsdl"); Log.i("androidHttpTransport", "" + androidHttpTransport); androidHttpTransport.call(SOAP_ACTION_ID, envelope); Object result = envelope.getResponse(); challanGenresp=result.toString(); Log.i("** getDetailsByRC response***", "" + challanGenresp); runOnUiThread(new Runnable() { public void run(){ if(challanGenresp!=null && challanGenresp.length()>25 ){ try { JSONObject jsonObj = new JSONObject(challanGenresp); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("RC_DETAILS"); // looping through All Contacts JSONObject c = contacts.getJSONObject(0); if(get_detailsFlg1){ witness_name.setText(c.getString("NAME")); witness_fname.setText(c.getString("FNAME")); witness_age.setText(c.getString("DOB").toString()); if("M".equals(c.getString("GENDER"))){ wt_male.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address.setText(completeAddress); witness_phone.setText(c.getString("PHONE_NO").toString()); } if(get_detailsFlg2){ witness_name2.setText(c.getString("NAME")); witness_fname2.setText(c.getString("FNAME")); witness_age2.setText(c.getString("DOB").toString()); if("M".equals(c.getString("GENDER"))){ wt_male2.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others2.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address2.setText(completeAddress); witness_phone2.setText(c.getString("PHONE_NO").toString()); } if(get_detailsFlg3){ witness_name3.setText(c.getString("NAME")); witness_fname3.setText(c.getString("FNAME")); witness_age3.setText(c.getString("DOB").toString()); if("M".equals(c.getString("GENDER"))){ wt_male3.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female3.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others3.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address3.setText(completeAddress); witness_phone3.setText(c.getString("PHONE_NO").toString()); } if(get_detailsFlg4){ witness_name4.setText(c.getString("NAME")); witness_fname4.setText(c.getString("FNAME")); witness_age4.setText(c.getString("DOB").toString()); if("M".equals(c.getString("GENDER"))){ wt_male4.setChecked(true); }else if("F".equals(c.getString("GENDER"))){ wt_female4.setChecked(true); }else if("O".equals(c.getString("GENDER"))){ wt_others4.setChecked(true); } String completeAddress=c.getString("HNO")+c.getString("STREET")+c.getString("VILLAGE")+c.getString("MANDAL") +c.getString("DISTRICT")+c.getString("STATE")+c.getString("PIN_CODE"); witness_address4.setText(completeAddress); witness_phone4.setText(c.getString("PHONE_NO").toString()); } } catch(Exception e){ e.printStackTrace(); } }else{ Log.i("no data from service", "no "); /*Toast toast = Toast.makeText(getApplicationContext(), "No data Found", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, -200); View toastView = toast.getView(); toastView.setBackgroundResource(R.drawable.toast_background); toast.show();*/ showToast("No Data Found"); } } }); // // INSERT ID PROOF DETAILS END } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); //showDialog(PROGRESS_DIALOG); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); showDialog(PROGRESS_DIALOG); } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); removeDialog(PROGRESS_DIALOG); if (!isNetworkAvailable()) { // do something AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(WitnessFormActivity.this); alertDialogBuilder.setMessage(" Mobile Data is Disabled in your Device \n Please Enable Mobile Data?") .setCancelable(false) .setPositiveButton("Ok", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int id){ } }); AlertDialog alert = alertDialogBuilder.create(); alert.show(); } } } /******************** Get Details BY RC Class AsyncGetRCDetails Ends****************************/ protected boolean validateMobileNo(String mobileNo) { boolean flg=false; try { if(mobileNo!=null && mobileNo.trim().length()==10 &&( "7".equals(mobileNo.trim().substring(0,1)) || "8".equals(mobileNo.trim().substring(0,1)) || "9".equals(mobileNo.trim().substring(0,1)))){ flg=true; }else if(mobileNo!=null && mobileNo.trim().length()==11 && "0".equals(mobileNo.trim().substring(0,1)) ){ flg=true; } } catch (Exception e) { e.printStackTrace(); flg=false; } Log.i("mobile number",mobileNo+" Length "+mobileNo.trim().length()+"1 letter"+mobileNo.trim().substring(0,1)); Log.i("mobile verify flag",flg+""); return flg; } public String getIDCode(String eT_ID) { String idCd="NA"; try { for(String idCode: idMap.keySet()){ if(eT_ID.equals(idMap.get(idCode))){ idCd=idCode; } } } catch (Exception e) { idCd="NA"; e.printStackTrace(); } Log.i("idCd for "+eT_ID+" :", idCd); return idCd; } public String getIDCode2(String eT_ID) { String idCd="NA"; try { for(String idCode: idMap.keySet()){ if(eT_ID.equals(idMap.get(idCode))){ idCd=idCode; } } } catch (Exception e) { // TODO: handle exception } Log.i("idCd for "+eT_ID+" :", idCd); return idCd; } public String getIDCode3(String eT_ID) { String idCd="NA"; try { for(String idCode: idMap.keySet()){ if(eT_ID.equals(idMap.get(idCode))){ idCd=idCode; } } } catch (Exception e) { // TODO: handle exception } Log.i("idCd for "+eT_ID+" :", idCd); return idCd; } public String getIDCode4(String eT_ID) { String idCd="NA"; try { for(String idCode: idMap.keySet()){ if(eT_ID.equals(idMap.get(idCode))){ idCd=idCode; } } } catch (Exception e) { // TODO: handle exception } Log.i("idCd for "+eT_ID+" :", idCd); return idCd; } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } /*protected Dialog onCreateDialog(int id) { return new DatePickerDialog(this, datePickerListener, year, month, day); } private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) { witness_dob.setText(selectedDay + " / " + (selectedMonth + 1) + " / " + selectedYear); } };*/ @SuppressWarnings("deprecation") @Override protected Dialog onCreateDialog(int id) { // TODO Auto-generated method stub switch (id) { case PROGRESS_DIALOG: ProgressDialog pd = ProgressDialog.show(this, "", "", true); pd.setContentView(R.layout.custom_progress_dialog); pd.setCancelable(false); return pd; default: break; } return super.onCreateDialog(id); } @SuppressWarnings("unused") private void showToast(String msg) { // TODO Auto-generated method stub // Toast.makeText(getApplicationContext(), "" + msg, Toast.LENGTH_SHORT).show(); Toast toast = Toast.makeText(getApplicationContext(), "" + msg, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); View toastView = toast.getView(); ViewGroup group = (ViewGroup) toast.getView(); TextView messageTextView = (TextView) group.getChildAt(0); //messageTextView.setTextSize(24); toastView.setBackgroundResource(R.drawable.toast_background); toast.show(); } @Override public void onBackPressed() { } }
[ "srinivaskasani.mtpv@gmail.com" ]
srinivaskasani.mtpv@gmail.com
cfcc1ba58dde423ee948a6076032971ce9559555
3016374f9ee1929276a412eb9359c0420d165d77
/InstrumentAPK/sootOutput/com.waze_source_from_JADX/com/google/android/gms/internal/zzawh.java
ad7f190f10d04777577c6388ab0dde8a8d7f77be
[]
no_license
DulingLai/Soot_Instrumenter
190cd31e066a57c0ddeaf2736a8d82aec49dadbf
9b13097cb426b27df7ba925276a7e944b469dffb
refs/heads/master
2021-01-02T08:37:50.086354
2018-04-16T09:21:31
2018-04-16T09:21:31
99,032,882
4
3
null
null
null
null
UTF-8
Java
false
false
1,774
java
package com.google.android.gms.internal; import dalvik.annotation.Signature; import java.io.IOException; import java.sql.Time; import java.text.DateFormat; import java.text.SimpleDateFormat; /* compiled from: dalvik_source_com.waze.apk */ public final class zzawh extends zzavg<Time> { public static final zzavh bYW = new C08021(); private final DateFormat bZw = new SimpleDateFormat("hh:mm:ss a"); /* compiled from: dalvik_source_com.waze.apk */ static class C08021 implements zzavh { C08021() throws { } public <T> zzavg<T> zza(@Signature({"<T:", "Ljava/lang/Object;", ">(", "Lcom/google/android/gms/internal/zzauo;", "Lcom/google/android/gms/internal/zzawk", "<TT;>;)", "Lcom/google/android/gms/internal/zzavg", "<TT;>;"}) zzauo com_google_android_gms_internal_zzauo, @Signature({"<T:", "Ljava/lang/Object;", ">(", "Lcom/google/android/gms/internal/zzauo;", "Lcom/google/android/gms/internal/zzawk", "<TT;>;)", "Lcom/google/android/gms/internal/zzavg", "<TT;>;"}) zzawk<T> $r2) throws { return $r2.hN() == Time.class ? new zzawh() : null; } } public synchronized void zza(zzawn $r1, Time $r2) throws IOException { $r1.zzyp($r2 == null ? null : this.bZw.format($r2)); } public /* synthetic */ Object zzb(zzawl $r1) throws IOException { return zzn($r1); } public synchronized Time zzn(zzawl $r1) throws IOException { Time $r4; if ($r1.hC() == zzawm.NULL) { $r1.nextNull(); $r4 = null; } else { try { $r4 = new Time(this.bZw.parse($r1.nextString()).getTime()); } catch (Throwable $r8) { throw new zzavd($r8); } } return $r4; } }
[ "laiduling@alumni.ubc.ca" ]
laiduling@alumni.ubc.ca
621343e0845adee2dc4c22cb2109ed0afb0b6fba
65c3f20222b570c058734686e75272e9c809df1a
/NavTools/src/navtools/util/FileWalker.java
ca0e8e96f0fd8f7ae9b5e2f2ecb02773e6808762
[]
no_license
GoDieBawb/NavTools
507c2e151e0fa6d054ca07bf5bd4b9214746d0b8
d398f5a46171f8f755b51851635a924c968795cb
refs/heads/master
2020-12-25T14:14:34.832179
2016-09-18T02:20:43
2016-09-18T02:20:43
67,671,169
0
0
null
null
null
null
UTF-8
Java
false
false
1,131
java
package navtools.util; import java.io.File; public class FileWalker { private String filePath; public String walk(String path, String fileName) { File root = new File( path ); File[] list = root.listFiles(); if (list == null) return filePath; for ( File f : list ) { String[] cutPath = f.getAbsolutePath().split("/"); String[] stripFile = cutPath[cutPath.length-1].split("\\."); String currentFile = stripFile[0]; if ( f.isDirectory() ) { walk( f.getAbsolutePath(), fileName ); } else { if (currentFile.toLowerCase().equalsIgnoreCase(fileName)) { if (f.getAbsolutePath().contains("Empty/")) continue; filePath = f.getAbsolutePath(); break; } } } return filePath; } }
[ "meancraft@hotmail.com" ]
meancraft@hotmail.com
9dbaf6e5c74296815d42f7156fca3054cec414ea
a9dccedabda6a0b32dbf583b178a090e7a7503c5
/src/storage/BinaryFormatHandler.java
ae96a75dcf31ad7ee0446379d081d4714f1b9815
[]
no_license
mshaban-msft/Vector-Paint
ebba72795b93e515cb398c88255b62fe8ebf2bef
aa86030e03e59af5833256d4ea2bfab7899b4579
refs/heads/master
2021-09-24T15:09:26.007129
2017-06-25T14:05:55
2017-06-25T14:05:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,337
java
package storage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class BinaryFormatHandler { //01_Save Image //***************************** //***************************************************************************** public static boolean saveImage(Object image, String fileDirectory) { File imageFile=new File(fileDirectory); try{ //open file FileOutputStream tmp=new FileOutputStream(imageFile); ObjectOutputStream fileWriter=new ObjectOutputStream(tmp); //write to file fileWriter.writeObject(image); //close file fileWriter.close(); tmp.close(); return true; }catch(Exception e){ return false; } } //02_Load Image //***************************** //***************************************************************************** public static Object loadImage(String fileDirectory){ File imageFile=new File(fileDirectory); try{ //open file FileInputStream tmp=new FileInputStream(imageFile); ObjectInputStream fileReader=new ObjectInputStream(tmp); //read from file Object image=(Object)fileReader.readObject(); //close file fileReader.close(); tmp.close(); return image; }catch (Exception e){ return null; } } }
[ "mohamed.shaapan.1@gmail.com" ]
mohamed.shaapan.1@gmail.com
f89cc53d68e778074f0c129d4dc01f709559e9bc
7773ea6f465ffecfd4f9821aad56ee1eab90d97a
/java/java-tests/testData/inspection/dataFlow/tracker/BasedOnPreviousRelationContracts.java
b0df0572e23c5a29734048ed4722a687809a513c
[ "Apache-2.0" ]
permissive
aghasyedbilal/intellij-community
5fa14a8bb62a037c0d2764fb172e8109a3db471f
fa602b2874ea4eb59442f9937b952dcb55910b6e
refs/heads/master
2023-04-10T20:55:27.988445
2020-05-03T22:00:26
2020-05-03T22:26:23
261,074,802
2
0
Apache-2.0
2020-05-04T03:48:36
2020-05-04T03:48:35
null
UTF-8
Java
false
false
521
java
/* Value is always false (b.equals("x"); line#15) According to hard-coded contract, method 'equals' returns 'false' value when this != parameter (equals; line#15) Condition 'b != "x"' was deduced It's known that 'b != a' from line #12 (a.equals(b); line#12) and it's known that 'a == "x"' from line #14 (a.equals("x"); line#14) */ public class T { void test(String a, String b) { if(a.equals(b)) { } else if (a.equals("x")) { if (<selection>b.equals("x")</selection>) {} } } }
[ "intellij-monorepo-bot-no-reply@jetbrains.com" ]
intellij-monorepo-bot-no-reply@jetbrains.com
8e224684aa3f69609847bf3c181cb61117502625
15d6868ac4dafeef2246f1159737815b12295ee1
/vpn-pms/src/main/java/com/asb/pms/SpringConfiguration.java
2ab78551e634da8c1320ad1d953d673b650eb238
[]
no_license
puppyriver/vpn4
e8e17bc8674c9f9dc4e1a0f38b241952c137cdad
15c50d20c0655c4a2ac49a328dbbde265219e88e
refs/heads/master
2020-04-05T13:35:51.397364
2019-04-02T08:12:01
2019-04-02T08:12:01
83,522,275
0
0
null
null
null
null
UTF-8
Java
false
false
762
java
package com.asb.pms; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import javax.sql.DataSource; /** * Author: Ronnie.Chen * Date: 2016/10/17 * Time: 13:12 * rongrong.chen@alcatel-sbell.com.cn */ public class SpringConfiguration implements InitializingBean{ private DataSource dataSource = null; public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } private Logger logger = LoggerFactory.getLogger(SpringConfiguration.class); @Override public void afterPropertiesSet() throws Exception { Configuration.setDataSource(dataSource); } }
[ "rongrong.chen@alcatel-sbell.com.cn" ]
rongrong.chen@alcatel-sbell.com.cn
cbd4755022777ba9b09829d4f765fba22aa38d07
3476915d393a562e547a7b0efd7536daa25e1103
/src/main/java/com/wangrollin/leetcode/n2_codingInterviews/p20/problem28/Solution2.java
9f07a6177aa60fbc14218ac59b5dd2245cd68b92
[ "Apache-2.0" ]
permissive
wangrollin/leetcode-java
3c4987fb67685571c5332e4b5e23172eec54e4c0
82b8e029ebad195db082fa4453f1852d88b76062
refs/heads/master
2023-04-16T14:23:53.605531
2021-04-29T16:17:55
2021-04-29T16:17:55
218,214,448
0
0
null
null
null
null
UTF-8
Java
false
false
2,137
java
package com.wangrollin.leetcode.n2_codingInterviews.p20.problem28; import java.util.LinkedList; import java.util.Queue; /** * 对称的二叉树 * * 请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。 * * 例如,二叉树[1,2,2,3,4,4,3] 是对称的。 * 1 * / \ * 2 2 * / \ / \ * 3 4 4 3 * 但是下面这个[1,2,2,null,3,null,3] 则不是镜像对称的: * 1 * / \ * 2 2 * \ \ * 3 3 * * 示例 1: * 输入:root = [1,2,2,3,4,4,3] * 输出:true * * 示例 2: * 输入:root = [1,2,2,null,3,null,3] * 输出:false * * 限制: * 0 <= 节点个数 <= 1000 * * 注意:本题与主站 101 题相同:https://leetcode-cn.com/problems/symmetric-tree/ * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof * * Solution2 * 广度优先遍历,BFS,迭代 */ public class Solution2 { public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } return checkLeftAndRight(root.left, root.right); } private boolean checkLeftAndRight(TreeNode left, TreeNode right) { Queue<TreeNode> queue1 = new LinkedList<>(); queue1.add(left); Queue<TreeNode> queue2 = new LinkedList<>(); queue2.add(right); while (!queue1.isEmpty() && !queue2.isEmpty()) { TreeNode node1 = queue1.poll(); TreeNode node2 = queue2.poll(); if (node1 == null && node2 == null) { continue; } else if (node1 == null || node2 == null || node1.val != node2.val) { return false; } else { queue1.add(node1.left); queue1.add(node1.right); queue2.add(node2.right); queue2.add(node2.left); } } return true; } private static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
[ "wangrollin@foxmail.com" ]
wangrollin@foxmail.com
5ca565ce5486e58b3c3b50f339af40fdef023344
99747123c4a1cdb98cfb6b484c5be7e269ced9f5
/文件/thinkinginjavaexamples/annotations/database/DBTable.java
ce89f1a92cc0e0ef8ef2cb1d306a8753896c52c0
[ "Apache-2.0" ]
permissive
CodingSoldier/java-learn
0dea60617be635d6d028cd3c4302bd2975526dbf
114358e63c41a1884ca660b70e13ed25bc12fbc6
refs/heads/master
2023-05-28T14:46:52.437585
2023-05-12T09:07:34
2023-05-12T09:07:34
113,655,752
27
20
Apache-2.0
2023-05-12T09:10:03
2017-12-09T08:51:50
Java
UTF-8
Java
false
false
287
java
//: annotations/database/DBTable.java package com.thinkinginjavaexamples.annotations.database; import java.lang.annotation.*; @Target(ElementType.TYPE) // Applies to classes only @Retention(RetentionPolicy.RUNTIME) public @interface DBTable { public String name() default ""; } ///:~
[ "tfz9011@163.com" ]
tfz9011@163.com
68f201a7471dfbcb99576c09f7de17eb3f9ad9c0
6f73b4881072bf9b9415f6a8e62d720f2b95b88e
/Assignment 6/src/Town.java
294c350c8c4e08669646f89e6a85ab004f9e2061
[]
no_license
natiwb/Assignment-6-Graphs
848f17be278b4b660fabdc188e73f883693f2009
730e8b74ee200e43487d82f2e943bc19d598178b
refs/heads/master
2022-07-06T04:56:12.902454
2020-05-19T02:57:44
2020-05-19T02:57:44
264,584,418
0
0
null
null
null
null
UTF-8
Java
false
false
1,786
java
import java.util.LinkedList; public class Town implements Comparable<Town> { String name; LinkedList<Town> adjacent = new LinkedList<>(); public Town(String name) { this.name=name; } public Town(Town debreMarkos) { this.name=debreMarkos.name; } public String getName() { return name; } public void setName(String name) { this.name = name; } /* compareTo public int compareTo(Town o) Compare to method Specified by: compareTo in interface java.lang.Comparable<Town> Returns: 0 if names are equal, a positive or negative number if the names are not equal */ public int compareTo(Town o) { if(o.getName().equalsIgnoreCase(this.getName())) { return 0; } else return 1; } /* toString public java.lang.String toString() To string method Overrides: toString in class java.lang.Object Returns: the town name */ @Override public String toString() { return name; } /* hashCode public int hashCode() Overrides: hashCode in class java.lang.Object Returns: the hashcode for the name of the town */ @Override public int hashCode() { return name.hashCode(); } /* equals public boolean equals(java.lang.Object obj) Overrides: equals in class java.lang.Object Returns: true if the town names are equal, false if not */ @Override public boolean equals(Object obj) { if(obj == null || !(obj instanceof Town)) { return false; } else { Town comp = (Town)obj; if(comp.getName().equalsIgnoreCase(name)) { return true; } else return false; } } public LinkedList<Town> getAdjacent() { return adjacent; } //for adding adjacent towns public LinkedList<Town> addAdjacentTown(Town t) { adjacent.add(t); return adjacent; } }
[ "nathanbekele120@gmail.com" ]
nathanbekele120@gmail.com
e09a6811f1613396d1ece9424109f9ec08f56b29
2a0de6bdd7ba008020b450466bb9f1da4f8902c1
/step01_springDI/src/main/java/sample06/Customer.java
624d88047df41a4de3752f14054fdb6326eaf8dd
[]
no_license
KostaJavaEdu/SpringWorkspace
7bab507a8d1e66ba9d35fa88899ecc74f07b0b1c
649339532fd2d84f008ad7b22ef6c10b2e2f81a5
refs/heads/master
2023-02-07T08:26:22.120045
2021-01-01T11:43:54
2021-01-01T11:43:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
670
java
package sample06; public class Customer { private String id; private int age; private String addr; public Customer() { System.out.println("Customer() 기본생성자 호출.."); } public Customer(String id) { System.out.println("Customer(String id) 기본생성자"); this.id = id; } public void setId(String id) { this.id = id; System.out.println("setId(String id) 호출됨 id : " + id); } public void setAge(int age) { this.age = age; System.out.println("setAge(int age) 호출됨 age : " + age); } public void setAddr(String addr) { this.addr = addr; System.out.println("setAddr(String addr) 호출됨 addr : " + addr); } }
[ "sn0716@naver.com" ]
sn0716@naver.com
bc6f14313d0c0347624d924b4b7209d555fc9208
e2fc012286878a82b6299f8358a2a992187bc303
/Simple-Blogging-CRUD-JDBC/src/model/DeletePost.java
45dde069355691e35aba23191fe81871fc618cc6
[]
no_license
lakhan712/Simple-Blogging-CRUD-using-JDBC
6ec49afb9d13e003fab5bb5ef4033c0bb868da04
e81b936ef89aa63d590ae2c13cdd4a0b058a8198
refs/heads/master
2022-12-08T00:25:52.444732
2020-09-01T13:45:06
2020-09-01T13:45:06
291,999,921
0
0
null
null
null
null
UTF-8
Java
false
false
860
java
package model; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class DeletePost { private static final String QUERY = "DELETE FROM post where id = ?"; private static Connection conn; private static PreparedStatement pst; public static boolean deletePost(int id) { conn = Connect.getConnection(); try { pst = conn.prepareStatement(QUERY); pst.setInt(1, id); pst.executeUpdate(); System.out.println("Post is deleted..."); return true; }catch(Exception e) { System.out.println("we are in catch block"); System.out.println(e); e.printStackTrace(); return false; }finally { try { pst.close(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
[ "Lakhan Mnae@Jarvis" ]
Lakhan Mnae@Jarvis
915803d382c31bd805ad03fcd0678e2f6b9e9d08
746169b0978e7cd3d752c689aba4c09606763a09
/MyFrameworkNew/src/test/java/com/gurock/testrail/APIClient.java
29d6b0de278ff472e4234c29bae84c94f17b3844
[]
no_license
bijenderprasad/herbertjava
312d1a128b256a4fc740f956edbe94829351508b
ec596a58cec8391d1e1eb592b2d07461a3ddc905
refs/heads/master
2021-06-24T18:29:57.004973
2019-08-29T09:24:40
2019-08-29T09:24:40
140,158,750
0
0
null
2020-10-12T22:37:46
2018-07-08T10:39:59
HTML
UTF-8
Java
false
false
8,302
java
/** * TestRail API binding for Java (API v2, available since TestRail 3.0) * Updated for TestRail 5.7 * * Learn more: * * http://docs.gurock.com/testrail-api2/start * http://docs.gurock.com/testrail-api2/accessing * * Copyright Gurock Software GmbH. See license.md for details. */ package com.gurock.testrail; import java.net.URL; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.util.Base64; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import com.gurock.testrail.APIException; public class APIClient { private String m_user; private String m_password; private String m_url; public APIClient(String base_url) { if (!base_url.endsWith("/")) { base_url += "/"; } this.m_url = base_url + "index.php?/api/v2/"; } /** * Get/Set User * * Returns/sets the user used for authenticating the API requests. */ public String getUser() { return this.m_user; } public void setUser(String user) { this.m_user = user; } /** * Get/Set Password * * Returns/sets the password used for authenticating the API requests. */ public String getPassword() { return this.m_password; } public void setPassword(String password) { this.m_password = password; } /** * Send Get * * Issues a GET request (read) against the API and returns the result * (as Object, see below). * * Arguments: * * uri The API method to call including parameters * (e.g. get_case/1) * * Returns the parsed JSON response as standard object which can * either be an instance of JSONObject or JSONArray (depending on the * API method). In most cases, this returns a JSONObject instance which * is basically the same as java.util.Map. * * If 'get_attachment/:attachment_id', returns a String */ public Object sendGet(String uri, String data) throws MalformedURLException, IOException, APIException { return this.sendRequest("GET", uri, data); } public Object sendGet(String uri) throws MalformedURLException, IOException, APIException { return this.sendRequest("GET", uri, null); } /** * Send POST * * Issues a POST request (write) against the API and returns the result * (as Object, see below). * * Arguments: * * uri The API method to call including parameters * (e.g. add_case/1) * data The data to submit as part of the request (e.g., * a map) * If adding an attachment, must be the path * to the file * * Returns the parsed JSON response as standard object which can * either be an instance of JSONObject or JSONArray (depending on the * API method). In most cases, this returns a JSONObject instance which * is basically the same as java.util.Map. */ public Object sendPost(String uri, Object data) throws MalformedURLException, IOException, APIException { return this.sendRequest("POST", uri, data); } private Object sendRequest(String method, String uri, Object data) throws MalformedURLException, IOException, APIException { URL url = new URL(this.m_url + uri); // Create the connection object and set the required HTTP method // (GET/POST) and headers (content type and basic auth). HttpURLConnection conn = (HttpURLConnection)url.openConnection(); String auth = getAuthorization(this.m_user, this.m_password); conn.addRequestProperty("Authorization", "Basic " + auth); if (method.equals("POST")) { conn.setRequestMethod("POST"); // Add the POST arguments, if any. We just serialize the passed // data object (i.e. a dictionary) and then add it to the // request body. if (data != null) { if (uri.startsWith("add_attachment")) // add_attachment API requests { String boundary = "TestRailAPIAttachmentBoundary"; //Can be any random string File uploadFile = new File((String)data); conn.setDoOutput(true); conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream ostreamBody = conn.getOutputStream(); BufferedWriter bodyWriter = new BufferedWriter(new OutputStreamWriter(ostreamBody)); bodyWriter.write("\n\n--" + boundary + "\r\n"); bodyWriter.write("Content-Disposition: form-data; name=\"attachment\"; filename=\"" + uploadFile.getName() + "\""); bodyWriter.write("\r\n\r\n"); bodyWriter.flush(); //Read file into request InputStream istreamFile = new FileInputStream(uploadFile); int bytesRead; byte[] dataBuffer = new byte[1024]; while ((bytesRead = istreamFile.read(dataBuffer)) != -1) { ostreamBody.write(dataBuffer, 0, bytesRead); } ostreamBody.flush(); //end of attachment, add boundary bodyWriter.write("\r\n--" + boundary + "--\r\n"); bodyWriter.flush(); //Close streams istreamFile.close(); ostreamBody.close(); bodyWriter.close(); } else // Not an attachment { conn.addRequestProperty("Content-Type", "application/json"); byte[] block = JSONValue.toJSONString(data). getBytes("UTF-8"); conn.setDoOutput(true); OutputStream ostream = conn.getOutputStream(); ostream.write(block); ostream.close(); } } } else // GET request { conn.addRequestProperty("Content-Type", "application/json"); } // Execute the actual web request (if it wasn't already initiated // by getOutputStream above) and record any occurred errors (we use // the error stream in this case). int status = conn.getResponseCode(); InputStream istream; if (status != 200) { istream = conn.getErrorStream(); if (istream == null) { throw new APIException( "TestRail API return HTTP " + status + " (No additional error message received)" ); } } else { istream = conn.getInputStream(); } // If 'get_attachment/' returned valid status code, save the file if ((istream != null) && (uri.startsWith("get_attachment/"))) { FileOutputStream outputStream = new FileOutputStream((String)data); int bytesRead = 0; byte[] buffer = new byte[1024]; while ((bytesRead = istream.read(buffer)) > 0) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); istream.close(); return (String) data; } // Not an attachment received // Read the response body, if any, and deserialize it from JSON. String text = ""; if (istream != null) { BufferedReader reader = new BufferedReader( new InputStreamReader( istream, "UTF-8" ) ); String line; while ((line = reader.readLine()) != null) { text += line; text += System.getProperty("line.separator"); } reader.close(); } Object result; if (!text.equals("")) { result = JSONValue.parse(text); } else { result = new JSONObject(); } // Check for any occurred errors and add additional details to // the exception message, if any (e.g. the error message returned // by TestRail). if (status != 200) { String error = "No additional error message received"; if (result != null && result instanceof JSONObject) { JSONObject obj = (JSONObject) result; if (obj.containsKey("error")) { error = '"' + (String) obj.get("error") + '"'; } } throw new APIException( "TestRail API returned HTTP " + status + "(" + error + ")" ); } return result; } private static String getAuthorization(String user, String password) { try { return new String(Base64.getEncoder().encode((user + ":" + password).getBytes())); } catch (IllegalArgumentException e) { // Not thrown } return ""; } }
[ "bijenderprasad@QAIT.COM" ]
bijenderprasad@QAIT.COM
fa009bff7f22c1925ab1fd28a465308bdd4d6256
ac8c7d7d71da2f9afff4622ac5a1025e910648d4
/src/aula/Constants.java
2553cafeaa268052f7f1c4a8bc63d8793f73b4ac
[]
no_license
Joordep/java-mongo-homework
a2925481e60aff59aaf4c3c017456379d970cb6a
1765b4b916400e071af1f55159004092fc32e670
refs/heads/master
2021-01-22T19:04:32.863816
2015-05-13T03:55:18
2015-05-13T03:55:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
841
java
package aula; /** * This class holds the constants used throughout the code * @author natan * * these could very well be an enum though... */ public class Constants { public final static String INVALID_INPUT = "INVALID_INPUT"; public final static String ACTION = "acao"; public final static String INSERT = "insert"; public final static String DELETE = "delete"; public final static String UPDATE = "update"; public final static String QUERY = "query"; public final static String HELP = "help"; public final static String COST = "valor"; public final static String YEAR = "valor"; public final static String QTT = "qtd"; public final static String NAME = "nome"; public final static String PLACE_OF_ORIGIN = "origem"; public final static String EXIT = "EXIT"; }
[ "streppels@gmail.com" ]
streppels@gmail.com
d839d8e466d69146830412b13bc70ac3e5a047ab
ffabf5c0656255f72301659d575a454d45150e77
/src/main/java/com/knowmyminister/searchservice/domain/Author.java
9b25974e746f8c2d5a80e966e73442ad7268c40e
[]
no_license
mahendrabagul/knowmyminister-search-service
0b37de0853fef9596ddaee75f610156b41b2d588
02c2c6926ea94dd5b18828d63f5859c6b6e5a1a6
refs/heads/master
2020-12-06T15:33:59.539222
2018-04-02T13:06:24
2018-04-02T13:06:24
232,497,442
0
0
null
null
null
null
UTF-8
Java
false
false
736
java
package com.knowmyminister.searchservice.domain; /** * Created by mahendra.hiraman on 4/2/2018. */ //@Document(indexName = "knowmyminister", type = "authors") public class Author { // @Id private String id; private String firstName; private String lastName; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
[ "mahendrahiraman.bagul@team.telstra.com" ]
mahendrahiraman.bagul@team.telstra.com
c5d9c0d3956fb6abb1ea1dbe73d5d8c58cfb116a
a714c4219e5b40f4d0e7760e4067dfa4a5eaca5a
/app/src/main/java/net/majorkernelpanic/streaming/video/VideoStream.java
772dc7e1d55864d5f5456b056e2621238418b040
[ "Apache-2.0" ]
permissive
mariodv95/apuppet-android
d714ca18921581d3453dfc43332d4538ccb9df2e
56cbd0d7e04d1fd760d77ac714e9efbbb33d2193
refs/heads/master
2023-07-14T01:26:58.339133
2021-08-17T11:27:25
2021-08-17T11:27:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
23,479
java
/* * aPuppet: Open Source Remote Access Software for Android * https://apuppet.org * * Copyright (C) 2020 apuppet.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.majorkernelpanic.streaming.video; import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import net.majorkernelpanic.streaming.MediaStream; import net.majorkernelpanic.streaming.Stream; import net.majorkernelpanic.streaming.exceptions.CameraInUseException; import net.majorkernelpanic.streaming.exceptions.ConfNotSupportedException; import net.majorkernelpanic.streaming.exceptions.InvalidSurfaceException; import net.majorkernelpanic.streaming.gl.SurfaceView; import net.majorkernelpanic.streaming.hw.EncoderDebugger; import net.majorkernelpanic.streaming.hw.NV21Convertor; import net.majorkernelpanic.streaming.rtp.MediaCodecInputStream; import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Parameters; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.media.MediaRecorder; import android.os.Looper; import android.os.ParcelFileDescriptor; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; /** * Don't use this class directly. */ public abstract class VideoStream extends MediaStream { protected final static String TAG = "VideoStream"; protected VideoQuality mRequestedQuality = VideoQuality.DEFAULT_VIDEO_QUALITY.clone(); protected VideoQuality mQuality = mRequestedQuality.clone(); protected SurfaceHolder.Callback mSurfaceHolderCallback = null; protected SurfaceView mSurfaceView = null; protected SharedPreferences mSettings = null; protected int mVideoEncoder, mCameraId = 0; protected int mRequestedOrientation = 0, mOrientation = 0; protected Camera mCamera; protected Thread mCameraThread; protected Looper mCameraLooper; protected boolean mCameraOpenedManually = true; protected boolean mFlashEnabled = false; protected boolean mSurfaceReady = false; protected boolean mUnlocked = false; protected boolean mPreviewStarted = false; protected boolean mUpdated = false; protected String mMimeType; protected String mEncoderName; protected int mEncoderColorFormat; protected int mCameraImageFormat; protected int mMaxFps = 0; /** * Don't use this class directly. * Uses CAMERA_FACING_BACK by default. */ public VideoStream() { this(CameraInfo.CAMERA_FACING_BACK); } /** * Don't use this class directly * @param camera Can be either CameraInfo.CAMERA_FACING_BACK or CameraInfo.CAMERA_FACING_FRONT */ @SuppressLint("InlinedApi") public VideoStream(int camera) { super(); setCamera(camera); } /** * Sets the camera that will be used to capture video. * You can call this method at any time and changes will take effect next time you start the stream. * @param camera Can be either CameraInfo.CAMERA_FACING_BACK or CameraInfo.CAMERA_FACING_FRONT */ public void setCamera(int camera) { CameraInfo cameraInfo = new CameraInfo(); int numberOfCameras = Camera.getNumberOfCameras(); for (int i=0;i<numberOfCameras;i++) { Camera.getCameraInfo(i, cameraInfo); if (cameraInfo.facing == camera) { mCameraId = i; break; } } } /** Switch between the front facing and the back facing camera of the phone. * If {@link #startPreview()} has been called, the preview will be briefly interrupted. * If {@link #start()} has been called, the stream will be briefly interrupted. * You should not call this method from the main thread if you are already streaming. * @throws IOException * @throws RuntimeException **/ public void switchCamera() throws RuntimeException, IOException { if (Camera.getNumberOfCameras() == 1) throw new IllegalStateException("Phone only has one camera !"); boolean streaming = mStreaming; boolean previewing = mCamera!=null && mCameraOpenedManually; mCameraId = (mCameraId == CameraInfo.CAMERA_FACING_BACK) ? CameraInfo.CAMERA_FACING_FRONT : CameraInfo.CAMERA_FACING_BACK; setCamera(mCameraId); stopPreview(); mFlashEnabled = false; if (previewing) startPreview(); if (streaming) start(); } /** * Returns the id of the camera currently selected. * Can be either {@link CameraInfo#CAMERA_FACING_BACK} or * {@link CameraInfo#CAMERA_FACING_FRONT}. */ public int getCamera() { return mCameraId; } /** * Sets a Surface to show a preview of recorded media (video). * You can call this method at any time and changes will take effect next time you call {@link #start()}. */ public synchronized void setSurfaceView(SurfaceView view) { mSurfaceView = view; if (mSurfaceHolderCallback != null && mSurfaceView != null && mSurfaceView.getHolder() != null) { mSurfaceView.getHolder().removeCallback(mSurfaceHolderCallback); } if (mSurfaceView != null && mSurfaceView.getHolder() != null) { mSurfaceHolderCallback = new Callback() { @Override public void surfaceDestroyed(SurfaceHolder holder) { mSurfaceReady = false; stopPreview(); Log.d(TAG,"Surface destroyed !"); } @Override public void surfaceCreated(SurfaceHolder holder) { mSurfaceReady = true; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d(TAG,"Surface Changed !"); } }; mSurfaceView.getHolder().addCallback(mSurfaceHolderCallback); mSurfaceReady = true; } } /** Turns the LED on or off if phone has one. */ public synchronized void setFlashState(boolean state) { // If the camera has already been opened, we apply the change immediately if (mCamera != null) { if (mStreaming && mMode == MODE_MEDIARECORDER_API) { lockCamera(); } Parameters parameters = mCamera.getParameters(); // We test if the phone has a flash if (parameters.getFlashMode()==null) { // The phone has no flash or the choosen camera can not toggle the flash throw new RuntimeException("Can't turn the flash on !"); } else { parameters.setFlashMode(state?Parameters.FLASH_MODE_TORCH:Parameters.FLASH_MODE_OFF); try { mCamera.setParameters(parameters); mFlashEnabled = state; } catch (RuntimeException e) { mFlashEnabled = false; throw new RuntimeException("Can't turn the flash on !"); } finally { if (mStreaming && mMode == MODE_MEDIARECORDER_API) { unlockCamera(); } } } } else { mFlashEnabled = state; } } /** * Toggles the LED of the phone if it has one. * You can get the current state of the flash with {@link VideoStream#getFlashState()}. */ public synchronized void toggleFlash() { setFlashState(!mFlashEnabled); } /** Indicates whether or not the flash of the phone is on. */ public boolean getFlashState() { return mFlashEnabled; } /** * Sets the orientation of the preview. * @param orientation The orientation of the preview */ public void setPreviewOrientation(int orientation) { mRequestedOrientation = orientation; mUpdated = false; } /** * Sets the configuration of the stream. You can call this method at any time * and changes will take effect next time you call {@link #configure()}. * @param videoQuality Quality of the stream */ public void setVideoQuality(VideoQuality videoQuality) { if (!mRequestedQuality.equals(videoQuality)) { mRequestedQuality = videoQuality.clone(); mUpdated = false; } } /** * Returns the quality of the stream. */ public VideoQuality getVideoQuality() { return mRequestedQuality; } /** * Some data (SPS and PPS params) needs to be stored when {@link #getSessionDescription()} is called * @param prefs The SharedPreferences that will be used to save SPS and PPS parameters */ public void setPreferences(SharedPreferences prefs) { mSettings = prefs; } /** * Configures the stream. You need to call this before calling {@link #getSessionDescription()} * to apply your configuration of the stream. */ public synchronized void configure() throws IllegalStateException, IOException { super.configure(); mOrientation = mRequestedOrientation; } /** * Starts the stream. * This will also open the camera and display the preview * if {@link #startPreview()} has not already been called. */ public synchronized void start() throws IllegalStateException, IOException { if (!mPreviewStarted) mCameraOpenedManually = false; super.start(); Log.d(TAG,"Stream configuration: FPS: "+mQuality.framerate+" Width: "+mQuality.resX+" Height: "+mQuality.resY); } /** Stops the stream. */ public synchronized void stop() { if (mCamera != null) { if (mMode == MODE_MEDIACODEC_API) { mCamera.setPreviewCallbackWithBuffer(null); } if (mMode == MODE_MEDIACODEC_API_2) { ((SurfaceView)mSurfaceView).removeMediaCodecSurface(); } super.stop(); // We need to restart the preview if (!mCameraOpenedManually) { destroyCamera(); } else { try { startPreview(); } catch (RuntimeException e) { e.printStackTrace(); } } } } public synchronized void startPreview() throws CameraInUseException, InvalidSurfaceException, RuntimeException { mCameraOpenedManually = true; if (!mPreviewStarted) { createCamera(); updateCamera(); } } /** * Stops the preview. */ public synchronized void stopPreview() { mCameraOpenedManually = false; stop(); } /** * Video encoding is done by a MediaRecorder. */ protected void encodeWithMediaRecorder() throws IOException, ConfNotSupportedException { Log.d(TAG,"Video encoded using the MediaRecorder API"); // We need a local socket to forward data output by the camera to the packetizer createSockets(); // Reopens the camera if needed destroyCamera(); createCamera(); // The camera must be unlocked before the MediaRecorder can use it unlockCamera(); try { mMediaRecorder = new MediaRecorder(); mMediaRecorder.setCamera(mCamera); mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mMediaRecorder.setVideoEncoder(mVideoEncoder); mMediaRecorder.setPreviewDisplay(mSurfaceView.getHolder().getSurface()); mMediaRecorder.setVideoSize(mRequestedQuality.resX,mRequestedQuality.resY); mMediaRecorder.setVideoFrameRate(mRequestedQuality.framerate); // The bandwidth actually consumed is often above what was requested mMediaRecorder.setVideoEncodingBitRate((int)(mRequestedQuality.bitrate*0.8)); // We write the output of the camera in a local socket instead of a file ! // This one little trick makes streaming feasible quiet simply: data from the camera // can then be manipulated at the other end of the socket FileDescriptor fd = null; if (sPipeApi == PIPE_API_PFD) { fd = mParcelWrite.getFileDescriptor(); } else { fd = mSender.getFileDescriptor(); } mMediaRecorder.setOutputFile(fd); mMediaRecorder.prepare(); mMediaRecorder.start(); } catch (Exception e) { throw new ConfNotSupportedException(e.getMessage()); } InputStream is = null; if (sPipeApi == PIPE_API_PFD) { is = new ParcelFileDescriptor.AutoCloseInputStream(mParcelRead); } else { is = mReceiver.getInputStream(); } // This will skip the MPEG4 header if this step fails we can't stream anything :( try { byte buffer[] = new byte[4]; // Skip all atoms preceding mdat atom while (!Thread.interrupted()) { while (is.read() != 'm'); is.read(buffer,0,3); if (buffer[0] == 'd' && buffer[1] == 'a' && buffer[2] == 't') break; } } catch (IOException e) { Log.e(TAG,"Couldn't skip mp4 header :/"); stop(); throw e; } // The packetizer encapsulates the bit stream in an RTP stream and send it over the network mPacketizer.setInputStream(is); mPacketizer.start(); mStreaming = true; } /** * Video encoding is done by a MediaCodec. */ protected void encodeWithMediaCodec() throws RuntimeException, IOException { if (mMode == MODE_MEDIACODEC_API_2) { // Uses the method MediaCodec.createInputSurface to feed the encoder encodeWithMediaCodecMethod2(); } else { // Uses dequeueInputBuffer to feed the encoder encodeWithMediaCodecMethod1(); } } /** * Video encoding is done by a MediaCodec. */ @SuppressLint("NewApi") protected void encodeWithMediaCodecMethod1() throws RuntimeException, IOException { Log.d(TAG,"Video encoded using the MediaCodec API with a buffer"); // Updates the parameters of the camera if needed createCamera(); updateCamera(); // Estimates the frame rate of the camera measureFramerate(); // Starts the preview if needed if (!mPreviewStarted) { try { mCamera.startPreview(); mPreviewStarted = true; } catch (RuntimeException e) { destroyCamera(); throw e; } } EncoderDebugger debugger = EncoderDebugger.debug(mSettings, mQuality.resX, mQuality.resY); final NV21Convertor convertor = debugger.getNV21Convertor(); mMediaCodec = MediaCodec.createByCodecName(debugger.getEncoderName()); MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", mQuality.resX, mQuality.resY); mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, mQuality.bitrate); mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, mQuality.framerate); mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,debugger.getEncoderColorFormat()); mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1); mMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); mMediaCodec.start(); Camera.PreviewCallback callback = new Camera.PreviewCallback() { long now = System.nanoTime()/1000, oldnow = now, i=0; ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers(); @Override public void onPreviewFrame(byte[] data, Camera camera) { oldnow = now; now = System.nanoTime()/1000; if (i++>3) { i = 0; //Log.d(TAG,"Measured: "+1000000L/(now-oldnow)+" fps."); } try { int bufferIndex = mMediaCodec.dequeueInputBuffer(500000); if (bufferIndex>=0) { inputBuffers[bufferIndex].clear(); if (data == null) Log.e(TAG,"Symptom of the \"Callback buffer was to small\" problem..."); else convertor.convert(data, inputBuffers[bufferIndex]); mMediaCodec.queueInputBuffer(bufferIndex, 0, inputBuffers[bufferIndex].position(), now, 0); } else { Log.e(TAG,"No buffer available !"); } } finally { mCamera.addCallbackBuffer(data); } } }; for (int i=0;i<10;i++) mCamera.addCallbackBuffer(new byte[convertor.getBufferSize()]); mCamera.setPreviewCallbackWithBuffer(callback); // The packetizer encapsulates the bit stream in an RTP stream and send it over the network mPacketizer.setInputStream(new MediaCodecInputStream(mMediaCodec)); mPacketizer.start(); mStreaming = true; } /** * Video encoding is done by a MediaCodec. * But here we will use the buffer-to-surface method */ @SuppressLint({ "InlinedApi", "NewApi" }) protected void encodeWithMediaCodecMethod2() throws RuntimeException, IOException { Log.d(TAG,"Video encoded using the MediaCodec API with a surface"); // Updates the parameters of the camera if needed createCamera(); updateCamera(); // Estimates the frame rate of the camera measureFramerate(); EncoderDebugger debugger = EncoderDebugger.debug(mSettings, mQuality.resX, mQuality.resY); mMediaCodec = MediaCodec.createByCodecName(debugger.getEncoderName()); MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", mQuality.resX, mQuality.resY); mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, mQuality.bitrate); mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, mQuality.framerate); mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1); mMediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); Surface surface = mMediaCodec.createInputSurface(); ((SurfaceView)mSurfaceView).addMediaCodecSurface(surface); mMediaCodec.start(); // The packetizer encapsulates the bit stream in an RTP stream and send it over the network mPacketizer.setInputStream(new MediaCodecInputStream(mMediaCodec)); mPacketizer.start(); mStreaming = true; } /** * Returns a description of the stream using SDP. * This method can only be called after {@link Stream#configure()}. * @throws IllegalStateException Thrown when {@link Stream#configure()} wa not called. */ public abstract String getSessionDescription() throws IllegalStateException; /** * Opens the camera in a new Looper thread so that the preview callback is not called from the main thread * If an exception is thrown in this Looper thread, we bring it back into the main thread. * @throws RuntimeException Might happen if another app is already using the camera. */ private void openCamera() throws RuntimeException { final Semaphore lock = new Semaphore(0); final RuntimeException[] exception = new RuntimeException[1]; mCameraThread = new Thread(new Runnable() { @Override public void run() { Looper.prepare(); mCameraLooper = Looper.myLooper(); try { mCamera = Camera.open(mCameraId); } catch (RuntimeException e) { exception[0] = e; } finally { lock.release(); Looper.loop(); } } }); mCameraThread.start(); lock.acquireUninterruptibly(); if (exception[0] != null) throw new CameraInUseException(exception[0].getMessage()); } protected synchronized void createCamera() throws RuntimeException { if (mSurfaceView == null) throw new InvalidSurfaceException("Invalid surface !"); if (mSurfaceView.getHolder() == null || !mSurfaceReady) throw new InvalidSurfaceException("Invalid surface !"); if (mCamera == null) { openCamera(); mUpdated = false; mUnlocked = false; mCamera.setErrorCallback(new Camera.ErrorCallback() { @Override public void onError(int error, Camera camera) { // On some phones when trying to use the camera facing front the media server will die // Whether or not this callback may be called really depends on the phone if (error == Camera.CAMERA_ERROR_SERVER_DIED) { // In this case the application must release the camera and instantiate a new one Log.e(TAG,"Media server died !"); // We don't know in what thread we are so stop needs to be synchronized mCameraOpenedManually = false; stop(); } else { Log.e(TAG,"Error unknown with the camera: "+error); } } }); try { // If the phone has a flash, we turn it on/off according to mFlashEnabled // setRecordingHint(true) is a very nice optimization if you plane to only use the Camera for recording Parameters parameters = mCamera.getParameters(); if (parameters.getFlashMode()!=null) { parameters.setFlashMode(mFlashEnabled?Parameters.FLASH_MODE_TORCH:Parameters.FLASH_MODE_OFF); } parameters.setRecordingHint(true); mCamera.setParameters(parameters); mCamera.setDisplayOrientation(mOrientation); try { if (mMode == MODE_MEDIACODEC_API_2) { mSurfaceView.startGLThread(); mCamera.setPreviewTexture(mSurfaceView.getSurfaceTexture()); } else { mCamera.setPreviewDisplay(mSurfaceView.getHolder()); } } catch (IOException e) { throw new InvalidSurfaceException("Invalid surface !"); } } catch (RuntimeException e) { destroyCamera(); throw e; } } } protected synchronized void destroyCamera() { if (mCamera != null) { if (mStreaming) super.stop(); lockCamera(); mCamera.stopPreview(); try { mCamera.release(); } catch (Exception e) { Log.e(TAG,e.getMessage()!=null?e.getMessage():"unknown error"); } mCamera = null; mCameraLooper.quit(); mUnlocked = false; mPreviewStarted = false; } } protected synchronized void updateCamera() throws RuntimeException { // The camera is already correctly configured if (mUpdated) return; if (mPreviewStarted) { mPreviewStarted = false; mCamera.stopPreview(); } Parameters parameters = mCamera.getParameters(); mQuality = VideoQuality.determineClosestSupportedResolution(parameters, mQuality); int[] max = VideoQuality.determineMaximumSupportedFramerate(parameters); double ratio = (double)mQuality.resX/(double)mQuality.resY; mSurfaceView.requestAspectRatio(ratio); parameters.setPreviewFormat(mCameraImageFormat); parameters.setPreviewSize(mQuality.resX, mQuality.resY); parameters.setPreviewFpsRange(max[0], max[1]); try { mCamera.setParameters(parameters); mCamera.setDisplayOrientation(mOrientation); mCamera.startPreview(); mPreviewStarted = true; mUpdated = true; } catch (RuntimeException e) { destroyCamera(); throw e; } } protected void lockCamera() { if (mUnlocked) { Log.d(TAG,"Locking camera"); try { mCamera.reconnect(); } catch (Exception e) { Log.e(TAG,e.getMessage()); } mUnlocked = false; } } protected void unlockCamera() { if (!mUnlocked) { Log.d(TAG,"Unlocking camera"); try { mCamera.unlock(); } catch (Exception e) { Log.e(TAG,e.getMessage()); } mUnlocked = true; } } /** * Computes the average frame rate at which the preview callback is called. * We will then use this average frame rate with the MediaCodec. * Blocks the thread in which this function is called. */ private void measureFramerate() { final Semaphore lock = new Semaphore(0); final Camera.PreviewCallback callback = new Camera.PreviewCallback() { int i = 0, t = 0; long now, oldnow, count = 0; @Override public void onPreviewFrame(byte[] data, Camera camera) { i++; now = System.nanoTime()/1000; if (i>3) { t += now - oldnow; count++; } if (i>20) { mQuality.framerate = (int) (1000000/(t/count)+1); lock.release(); } oldnow = now; } }; mCamera.setPreviewCallback(callback); try { lock.tryAcquire(2,TimeUnit.SECONDS); Log.d(TAG,"Actual framerate: "+mQuality.framerate); if (mSettings != null) { Editor editor = mSettings.edit(); editor.putInt(PREF_PREFIX+"fps"+mRequestedQuality.framerate+","+mCameraImageFormat+","+mRequestedQuality.resX+mRequestedQuality.resY, mQuality.framerate); editor.commit(); } } catch (InterruptedException e) {} mCamera.setPreviewCallback(null); } }
[ "mayorow@gmail.com" ]
mayorow@gmail.com
45ba350eab93cbfb4e04d485a852b73a846b3c9a
782074c2e0193351b5e5cf33ad977bf0fb3bb006
/src/ru/netology/graphics/image/BadImageSizeException.java
2e28f5d8e898e8c0aa1323cf17f52aa5ace7a6f3
[]
no_license
jtn1983/javabasicsdiploma
f4c6b9df756238299988a3a73ae4cd18a380fbbb
4ef61408fa8f1aa775d2592f1598f84b5c37879d
refs/heads/master
2023-05-30T17:28:36.185812
2021-06-18T10:43:37
2021-06-18T10:43:37
377,286,598
0
0
null
null
null
null
UTF-8
Java
false
false
422
java
package ru.netology.graphics.image; public class BadImageSizeException extends Exception { public BadImageSizeException(double ratio, double maxRatio) { super("Максимальное соотношение сторон изображения " + maxRatio + ", а у этой " + ratio); } public BadImageSizeException() { super("Ошибка в размерах картинки!"); } }
[ "yakov@tenilin.ru" ]
yakov@tenilin.ru
b0f1775a233e2b924b63004e362e79decd691120
f70a61c454be09757309eb6817c289971dd50cef
/T Academy/Android/day12/gcm/GCMKimProject/src/com/example/gcmkimproject/MainActivity.java
2fd53e673897d79c212bd2373dc0d85010a01bd6
[]
no_license
ace0625/Android-work
02cf8db7ed5fdc0df04fed0b6638b744feee9602
5c2491a0e5642294b9f764b80a7950bf9c428c3d
refs/heads/master
2021-01-01T05:19:14.765823
2016-05-25T21:16:04
2016-05-25T21:16:04
59,698,057
0
0
null
null
null
null
UHC
Java
false
false
10,050
java
package com.example.gcmkimproject; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.media.MediaPlayer; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; public static final String EXTRA_MESSAGE = "message"; public static final String PROPERTY_REG_ID = "registration_id"; private static final String PROPERTY_APP_VERSION = "appVersion"; private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; String SENDER_ID = "908544295302"; TextView mDisplay; GoogleCloudMessaging gcm; AtomicInteger msgId = new AtomicInteger(); SharedPreferences prefs; Context context; String regid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDisplay = (TextView)findViewById(R.id.display); context = getApplicationContext(); //구글 체크하느 부분 if (checkPlayServices()) { Log.v(TAG, "success"); gcm = GoogleCloudMessaging.getInstance(this); regid = getRegistrationId(context); if (regid.isEmpty()) { Log.v(TAG, "등록 안되어 있음"); registerInBackground(); }else{ Log.v(TAG, "ID : " + regid); } }else{ Log.v(TAG, "fail"); } findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!getRegistrationId(context).equals("")){ unRegisterInBackground(); } } }); findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gcm = GoogleCloudMessaging.getInstance(context); regid = getRegistrationId(context); if (regid.isEmpty()) { Log.v(TAG, "등록 안되어 있음"); registerInBackground(); }else{ Log.v(TAG, "ID : " + regid); } } }); findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW"); String id = Integer.toString(msgId.incrementAndGet()); Log.v(TAG, "regid : " + getRegistrationId(context)); gcm.send(SENDER_ID + "@gcm.googleapis.com", getRegistrationId(context), data); // gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent message"; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } }); } private void unRegisterInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } // regid = gcm.register(SENDER_ID); gcm.unregister(); msg = "Device unregister, registration ID=" + regid; Log.v(TAG, "Device unregister, : " + regid); // You should send the registration ID to your server over HTTP, // so it can use GCM/HTTP or CCS to send messages to your app. // The request to your server should be authenticated if your app // is using accounts. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device // will send upstream messages to a server that echo back the // message using the 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, ""); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; Log.v(TAG, "regId : " + regid); // You should send the registration ID to your server over HTTP, // so it can use GCM/HTTP or CCS to send messages to your app. // The request to your server should be authenticated if your app // is using accounts. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device // will send upstream messages to a server that echo back the // message using the 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } /** * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP * or CCS to send messages to your app. Not needed for this demo since the * device sends upstream messages to a server that echoes back the message * using the 'from' address in the message. */ private void sendRegistrationIdToBackend() { Log.v(TAG, "서버에 등록하는 부분 소스 작성"); } public void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); } public String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } // Check if app was updated; if so, it must clear the registration ID // since the existing regID is not guaranteed to work with the new // app version. int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed."); return ""; } return registrationId; } private SharedPreferences getGCMPreferences(Context context) { // This sample app persists the registration ID in shared preferences, but // how you store the regID in your app is up to you. return getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE); } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Could not get package name: " + e); } } private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(TAG, "This device is not supported."); finish(); } return false; } return true; } @Override protected void onResume() { checkPlayServices(); super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
[ "hckim0625@gmail.com" ]
hckim0625@gmail.com
772cd448dbf89df3c79805f8446e44b30fc5101a
fd143b55e024772e7ccb8c2e99056de3fddb0d73
/src/com/olivierpicard/Grapher/Interpreter/VariableStandaloneNode.java
b015f6ce3d984f8ac9691edd0c1216f9d8fed38a
[]
no_license
olivierpicard/Grapher
84795aa6ddc6dec25fdb7eb4fe85aa011442c902
83971d16a7b2e2ed686bd5337fad9578fcc37645
refs/heads/master
2021-09-21T22:26:00.458954
2018-09-01T20:27:12
2018-09-01T20:27:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
332
java
package com.olivierpicard.Grapher.Interpreter; public class VariableStandaloneNode extends StandaloneNode { public VariableStandaloneNode() { super(); } @Override public float Compute(float argument) { return argument; } @Override public String toString() { return "x0 "; } }
[ "trafic-du-974@hotmail.fr" ]
trafic-du-974@hotmail.fr
2b75a8d27deccf62ccba66ed3d969d11f6fe42fd
fa67793e8d325785ba9ce747ef2c6a816d4f1630
/spring/src/main/java/br/com/zup/challenge/spring/Application.java
c69e96715880c7d6445d47946cba9dfba7730c76
[]
no_license
stefanielibarinozup/Challenge-Back-End
d94f96a837fd6da27649593e49015ccfad3ac8c8
271cddfd00bb3b786b03e411bd50d70244e191e4
refs/heads/master
2021-06-19T02:03:57.310698
2019-11-26T20:41:25
2019-11-26T20:41:25
216,926,365
0
0
null
2021-06-04T02:17:29
2019-10-22T23:14:44
Java
UTF-8
Java
false
false
890
java
package br.com.zup.challenge.spring; import br.com.zup.challenge.spring.crud.CreateData; import br.com.zup.challenge.spring.crud.DeleteData; import br.com.zup.challenge.spring.crud.ListData; import br.com.zup.challenge.spring.crud.ReadData; import br.com.zup.challenge.spring.service.ServiceSpring; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import java.io.IOException; import java.security.Provider; @SpringBootApplication public class Application implements CommandLineRunner { public static void main(String[] args) throws IOException { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { ServiceSpring.operacoesComandos(args); } }
[ "stefanie.libarino@zup.com.br" ]
stefanie.libarino@zup.com.br
0c6dc494d2976281bbee4ac249cf424a7f6c259d
7b4131cb2ef1b726164a01afcaa671d8bc82fbcc
/app/src/main/java/com/covid19/Dashboard.java
fe509ee0ec829aa4cd77a1973da4ceead30f4365
[]
no_license
Rinanda1/UAS1822500006AplikasiPasienCovid19
659b00ac8aeaecee4729f38b68b707fd624966bb
f72c4491447e92c6eaeae55b9f89e23c8f2ed79c
refs/heads/main
2023-07-02T04:00:59.663242
2021-08-05T05:34:39
2021-08-05T05:34:39
392,913,007
0
0
null
null
null
null
UTF-8
Java
false
false
1,439
java
package com.covid19; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Dashboard extends AppCompatActivity { Button btnExit; Button btnTambah; Button btnLihat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); btnTambah = (Button)findViewById(R.id.btnTambah); btnLihat = (Button)findViewById(R.id.btnLihat); btnExit = (Button)findViewById(R.id.btnExit); btnTambah.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Dashboard.this,TambahData.class); startActivity(intent); } }); btnLihat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Dashboard.this,TampilData.class); startActivity(intent); } }); btnExit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //perintah untuk mengakhiri aplikasi finish(); } }); } }
[ "1822500006@mahasiswa.atmaluhur.ac.id" ]
1822500006@mahasiswa.atmaluhur.ac.id
7ad29651d225d24c716d3db6d515dc9844fda696
262f2dfe07c7b0f7c76bcc0364cd71e812edacff
/反射(黑马视频)/src/cn/itcast_01/Person.java
8eb302b6cca6f897a6441d711bf1fd1a2dc2e413
[]
no_license
gaohanghang/Hello
f02787555352041699500b2079f3a102200c167e
ae50db9058e7fc82ca6489f18d7019f196f5d2e8
refs/heads/master
2021-01-01T19:31:10.328510
2018-04-19T12:26:37
2018-04-19T12:26:37
98,598,113
0
0
null
null
null
null
UTF-8
Java
false
false
982
java
package cn.itcast_01; public class Person { private String name; int age; public String address; public Person() { } private Person(String name){ this.name = name; } Person(String name, int age) { this.name = name; this.age = age; } public Person(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } public void show() { System.out.println("show"); } public void method(String s) { System.out.println("method "+s); } public String getString(String s, int i) { return s + "---" + i; } private void function() { System.out.println("function"); } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; } }
[ "1341947277@qq.com" ]
1341947277@qq.com
19b5e5db9015a07a8fe5b765704b20ae773fa37c
e7b53778c678ccc87cc2c09eb3f44f44906133d1
/rxlmdb-grpc/src/main/java/org/deephacks/rxlmdb/RxDbServiceGrpc.java
6268ed63e3fee1cadc6ba1f6509ab48f8f9e62fe
[]
no_license
deephacks/RxLMDB
e517d49dd2b078e15c372e79e15f2094cfda9a3b
6b4d01db73e5630141974dd26622a562b0f3244f
refs/heads/master
2023-08-30T07:50:58.307350
2016-05-18T19:59:48
2016-05-18T19:59:48
35,449,960
21
3
null
null
null
null
UTF-8
Java
false
false
4,587
java
package org.deephacks.rxlmdb; import com.google.protobuf.ByteString; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import org.deephacks.rxlmdb.Rxdb.*; import org.fusesource.lmdbjni.LMDBException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observer; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import java.util.List; import java.util.concurrent.TimeUnit; final class RxDbServiceGrpc implements DatabaseServiceGrpc.DatabaseService { private static final Logger logger = LoggerFactory.getLogger(RxDbServiceGrpc.class); private static final KeyRange.KeyRangeType[] TYPES = KeyRange.KeyRangeType.values(); private RxLmdb lmdb; private RxDb db; RxDbServiceGrpc(RxDb db) { this.lmdb = db.lmdb; this.db = db; } @Override public void put(PutMsg msg, StreamObserver<Empty> response) { try { db.put(new KeyValue(msg.getKey().toByteArray(), msg.getVal().toByteArray())); response.onCompleted(); } catch (LMDBException e) { if (logger.isErrorEnabled()) { logger.error("LMDB error " + e.getErrorCode() + " '" + e.getMessage() + "'"); } throw new StatusRuntimeException(Status.INTERNAL); } } @Override public StreamObserver<PutMsg> batch(StreamObserver<Empty> response) { SerializedSubject<KeyValue, KeyValue> subject = PublishSubject.<KeyValue>create().toSerialized(); Observable<List<KeyValue>> buffer = subject.buffer(10, TimeUnit.NANOSECONDS, 512); db.batch(buffer); return new StreamObserver<PutMsg>() { @Override public void onNext(PutMsg msg) { subject.onNext(new KeyValue(msg.getKey().toByteArray(), msg.getVal().toByteArray())); } @Override public void onError(Throwable t) { subject.onError(t); } @Override public void onCompleted() { subject.onCompleted(); } }; } @Override public void get(Rxdb.GetMsg msg, StreamObserver<ValueMsg> response) { try { byte[] bytes = db.get(msg.getKey().toByteArray()); ValueMsg.Builder builder = ValueMsg.newBuilder(); if (bytes != null) { builder.setVal(ByteString.copyFrom(bytes)); } response.onNext(builder.build()); response.onCompleted(); } catch (LMDBException e) { if (logger.isErrorEnabled()) { logger.error("LMDB error " + e.getErrorCode() + " '" + e.getMessage() + "'"); } throw new StatusRuntimeException(Status.INTERNAL); } } @Override public void delete(DeleteMsg msg, StreamObserver<BooleanMsg> response) { try { boolean delete = db.delete(msg.getKey().toByteArray()); response.onNext(BooleanMsg.newBuilder().setValue(delete).build()); response.onCompleted(); } catch (LMDBException e) { if (logger.isErrorEnabled()) { logger.error("LMDB error " + e.getErrorCode() + " '" + e.getMessage() + "'"); } throw new StatusRuntimeException(Status.INTERNAL); } } @Override public void scan(KeyRangeMsg msg, StreamObserver<KeyValueMsg> response) { KeyRange.KeyRangeType type = TYPES[msg.getType().getNumber()]; KeyRange keyRange = new KeyRange(msg.getStart().toByteArray(), msg.getStop().toByteArray(), type); try { db.scan(keyRange).subscribe(new Observer<List<KeyValue>>() { @Override public void onCompleted() { response.onCompleted(); } @Override public void onError(Throwable throwable) { if (throwable instanceof LMDBException) { if (logger.isErrorEnabled()) { LMDBException e = (LMDBException) throwable; logger.error("LMDB error " + e.getErrorCode() + " '" + e.getMessage() + "'"); } response.onError(new StatusRuntimeException(Status.INTERNAL)); } else { response.onError(throwable); } } @Override public void onNext(List<KeyValue> kvs) { for (KeyValue kv : kvs) { ByteString k = ByteString.copyFrom(kv.key()); ByteString v = ByteString.copyFrom(kv.value()); KeyValueMsg msg = KeyValueMsg.newBuilder().setKey(k).setVal(v).build(); response.onNext(msg); } } }); } catch (LMDBException e) { if (logger.isErrorEnabled()) { logger.error("LMDB error " + e.getErrorCode() + " '" + e.getMessage() + "'"); } throw new StatusRuntimeException(Status.INTERNAL); } } }
[ "stoffe@gmail.com" ]
stoffe@gmail.com
a37a2a9f02180842d280f305bfba81d1941ea620
c5e468f1026d2cd06f8663b39ba6e0be10da884b
/src/com/mine/myrpc/server/RpcServer.java
e5830466fab6c2f07a0b60f633ec6f3fb201a498
[]
no_license
ycyangcheng/MyRpc
6fecc0df4749b6e310e8a3ed279851c55e5e101a
9888d5e4e467cb4f87708d8004c5354ee580ecc4
refs/heads/master
2022-09-25T23:02:56.149150
2020-06-05T06:34:55
2020-06-05T06:34:55
269,539,174
0
0
null
null
null
null
UTF-8
Java
false
false
218
java
package com.mine.myrpc.server; /** * @author: Yang Cheng * @create: 2020-06-05 14:17 * @desc: */ public class RpcServer { public static void main(String[] args) { System.err.println("======"); } }
[ "yangcheng317@163.com" ]
yangcheng317@163.com
ba7bfd544dde4c230ebcc0608fffe6e2d317ebf8
4a8ec4f20fb2a07d852d1d09ff947cad57641208
/snf4j-core/src/test/java/org/snf4j/core/DelayedThreadFactory.java
5b1a217a051d96684097c132aa2c6de66fb9e641
[ "MIT" ]
permissive
snf4j/snf4j
d2ba7a8d03d5b007b937acc009ecc8c22762f7bf
3e01af01fce0b9997458603c40cb76db53e9bf6a
refs/heads/master
2023-06-08T05:00:14.051635
2022-08-16T15:39:57
2022-08-16T15:39:57
83,964,294
32
3
MIT
2022-08-16T15:39:58
2017-03-05T11:14:57
Java
UTF-8
Java
false
false
2,244
java
/* * -------------------------------- MIT License -------------------------------- * * Copyright (c) 2017 SNF4J contributors * * 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 org.snf4j.core; import java.util.concurrent.ThreadFactory; /** * Factory creating a thread with delayed execution of the target's <code>run</code> method. * * @author <a href="http://snf4j.org">SNF4J.ORG</a> */ public class DelayedThreadFactory implements ThreadFactory { private long delay; /** * Constructs a thread with given delay. * * @param delay the delay in milliseconds */ public DelayedThreadFactory(long delay) { this.delay = delay; } @Override public Thread newThread(Runnable target) { return new Thread(new DelayedRunner(target, delay), target.toString()); } static class DelayedRunner implements Runnable { private Runnable r; private long delay; DelayedRunner(Runnable r, long delay) { this.r = r; this.delay = delay; } @Override public void run() { try { Thread.sleep(delay); } catch (InterruptedException e) { //Ignore } r.run(); } } }
[ "noreply@github.com" ]
snf4j.noreply@github.com
4316be84984871780fbe00a5af5694596503fa30
fe70ceb1f98c4f4a59d8d08f83e2336df262b8bb
/BTECHNOTES2/app/src/main/java/com/example/btechnotes/sem1.java
8dd9fbd47246f1d5ace480ce9e0809275dd5fedb
[]
no_license
nscspc/Android_Studio
6c05f2257601fd3737eb1b3acf246955368af366
7f7ae7bd989cfdb8ed5328b1d8c4f15774b6cff7
refs/heads/master
2023-06-28T15:34:32.169011
2021-08-10T05:28:36
2021-08-10T05:28:36
394,536,630
0
0
null
null
null
null
UTF-8
Java
false
false
102
java
package com.example.btechnotes; import android.app.Activity; public class sem1 extends Activity { }
[ "saininaveen933@gmail.com" ]
saininaveen933@gmail.com
77107758b02139a14edf5e377abf5c150d64658f
46cd645185358bec989b62deeab6558b65c7927c
/app/src/main/java/preview/valteck/bortexapp/ui/login_and_registration_activities/RegisterActivity.java
1e24545d1034769df2ae348ee4d65c3b3981f450
[]
no_license
Sterlingryan/Android-Preview-App
b302b388b298f0dfdd9237f334551983d4c9bda0
588e9d4b3bedfee3247f3e21d83495ef161f5062
refs/heads/master
2021-01-06T20:44:17.675617
2017-11-10T13:33:05
2017-11-10T13:33:05
99,551,564
2
1
null
null
null
null
UTF-8
Java
false
false
3,818
java
package preview.valteck.bortexapp.ui.login_and_registration_activities; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import android.content.Intent; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import preview.valteck.bortexapp.R; import preview.valteck.bortexapp.ui.MainActivity; /** * Created by SterlingRyan on 8/16/2017. */ public class RegisterActivity extends AppCompatActivity { FirebaseAuth mAuth; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register_activity); mAuth = FirebaseAuth.getInstance(); // Get view references final EditText emailAddressEditText = (EditText) findViewById(R.id.email); EditText nameAndSurnameEditText = (EditText) findViewById(R.id.name); final EditText passwordEditText = (EditText) findViewById(R.id.password); Button registerButton = (Button) findViewById(R.id.button_register); Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar); //set view functionality registerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String emailAddress = emailAddressEditText.getText().toString(); String password = passwordEditText.getText().toString(); if(emailAddress.isEmpty()|| password.isEmpty()){ showSnackBar("Email or Password is incorrect"); } else{ registerWithEmailAndPassword(emailAddress, password); } } }); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material); upArrow.setColorFilter(getResources().getColor(R.color.colorText), PorterDuff.Mode.SRC_ATOP); getSupportActionBar().setHomeAsUpIndicator(upArrow); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } private void registerWithEmailAndPassword(String email, String password){ mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ // Sign in success therefore sign in showSnackBar("Sign in successful"); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } else { showSnackBar("Sign in unsuccessful"); } } }); } /** * Show a message * @param message */ private void showSnackBar(String message){ Snackbar snackbar = Snackbar.make(findViewById(R.id.coordinator_layout), message, Snackbar.LENGTH_SHORT); snackbar.show(); } }
[ "ryanaquilina001@gmail.com" ]
ryanaquilina001@gmail.com
0667642e14229d300f43fed113dbc0e198f2b910
a8bd8519a3870162ab99fcf8ad2fc3f919d3be60
/videos-pojo/src/main/java/com/video/pojo/vo/PublisherVideo.java
29cefbdef70c49c82e087a64621503176d91ebaf
[]
no_license
unluckygod/WchatVideo-dev
219b4899afcbf6fa8134aa0ad10c650b224cb6f7
6f48e6d210304817b5112d740cc2cf3a6fb3103d
refs/heads/master
2020-12-08T18:56:25.304136
2019-05-17T06:25:47
2019-05-17T06:25:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
435
java
package com.video.pojo.vo; public class PublisherVideo { public UsersVO publisher; public boolean userLikeVideo; public UsersVO getPublisher() { return publisher; } public void setPublisher(UsersVO publisher) { this.publisher = publisher; } public boolean isUserLikeVideo() { return userLikeVideo; } public void setUserLikeVideo(boolean userLikeVideo) { this.userLikeVideo = userLikeVideo; } }
[ "872978036@qq.com" ]
872978036@qq.com
c29e90ca5b202916ddfd4500706002c225cd1b9d
3c8209538534a5c6af8f05569125774439c7b3dc
/app/src/androidTest/java/com/example/todoapp2/ExampleInstrumentedTest.java
25689d910e1ea8f910b841a0ca5af87946fd3bb9
[]
no_license
sgries123/ToDoApp2
4247a3c87dc139ea99192a19cd141ac8c9f51e80
55abd537952ad42de2af79af081d3d576d89ec0a
refs/heads/main
2023-04-21T19:33:01.795668
2021-05-06T21:50:44
2021-05-06T21:50:44
365,046,186
0
0
null
null
null
null
UTF-8
Java
false
false
754
java
package com.example.todoapp2; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.example.todoapp2", appContext.getPackageName()); } }
[ "sandra.gries@valpo.edu" ]
sandra.gries@valpo.edu
615f7b13e1c2e76e0b57aaffff4542a1b7313677
883c2058ccaf2bf2d0145f1e34eb9142d9fd900d
/src/main/java/com/as/behavioral/chainOfResposibility/simpleExample/Main.java
5c41f72f94bbec803f00f471681fefd4c6eaaba2
[]
no_license
AndriySV/JavaPatterns
6eac712970da98a8aed02fcf38e2d7db6b0322cf
bed7e829435a39d19d08cd9e07755dfd91035911
refs/heads/develop
2021-06-25T00:51:06.680581
2017-03-25T20:14:57
2017-03-25T20:14:57
27,065,257
2
0
null
2014-12-10T18:40:19
2014-11-24T07:20:31
Java
UTF-8
Java
false
false
426
java
package com.as.behavioral.chainOfResposibility.simpleExample; import com.as.behavioral.chainOfResposibility.simpleExample.handler.Handler; import com.as.behavioral.chainOfResposibility.simpleExample.handler.SpamHandler; public class Main { public static void main(String[] args) { Handler handler; String condition = "fan"; handler = new SpamHandler(condition); handler.handelRequest(); } }
[ "A.S.Elips@gmail.com" ]
A.S.Elips@gmail.com
005454bd2d944e4a7c3b711790320a35c1147983
d2d0eaeacb5cde398f8b24d8c6370ba76188449c
/hphcAndroid-master/app/src/main/java/com/hphc/mystudies/studyAppModule/studyModel/ChartDataSourceActivity.java
305a73beea04d4e2761dbe4c2fa201e76d07f033
[ "MIT" ]
permissive
rmasiniexpert/FDA-My-Studies-Mobile-Application-System
1bf05be8123d8e5544b865bdeca4e7bd110455df
d7ed3b543158872be6ff6e5f02b7a92100b24d40
refs/heads/master
2022-12-23T08:05:32.348966
2020-11-18T21:56:19
2020-11-18T21:56:19
156,874,225
0
0
null
2022-12-16T02:42:15
2018-11-09T14:36:41
Java
UTF-8
Java
false
false
1,915
java
/* * Copyright © 2017-2018 Harvard Pilgrim Health Care Institute (HPHCI) and its Contributors. * 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. * * Funding Source: Food and Drug Administration ("Funding Agency") effective 18 September 2014 as Contract no. * HHSF22320140030I/HHSF22301006T (the "Prime Contract"). * * 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 NON-INFRINGEMENT. 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.hphc.mystudies.studyAppModule.studyModel; import java.io.Serializable; import io.realm.RealmObject; public class ChartDataSourceActivity extends RealmObject implements Serializable{ private String activityId; private String version; public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
[ "Adam_Paczuski@harvardpilgrim.org" ]
Adam_Paczuski@harvardpilgrim.org
88dc42ac2900527e17325458a109cc79bfd5467f
eca69197507341718c7107d014e793b1170078be
/oplexecutor/src/main/java/org/imf/oplexecutor/fims/mdcf/h/SORTBY.java
abfd902eec1254e58e7cf66786def44c53d9f406
[]
no_license
ben2602/OPLExecutor
1328a5b1b38579fff808574d20c06e0d56884adc
9c3b4d86c575052361e8bef72bec5fbd3cc98636
refs/heads/master
2021-01-13T03:15:08.135417
2017-04-07T09:42:11
2017-04-07T09:42:11
77,609,883
1
0
null
null
null
null
UTF-8
Java
false
false
2,425
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // 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.03.13 at 10:49:01 AM CET // package org.imf.oplexecutor.fims.mdcf.h; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SORT_BY complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SORT_BY"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="field" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="descending" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SORT_BY") public class SORTBY { @XmlAttribute(name = "field", required = true) protected String field; @XmlAttribute(name = "descending") protected Boolean descending; /** * Gets the value of the field property. * * @return * possible object is * {@link String } * */ public String getField() { return field; } /** * Sets the value of the field property. * * @param value * allowed object is * {@link String } * */ public void setField(String value) { this.field = value; } /** * Gets the value of the descending property. * * @return * possible object is * {@link Boolean } * */ public boolean isDescending() { if (descending == null) { return false; } else { return descending; } } /** * Sets the value of the descending property. * * @param value * allowed object is * {@link Boolean } * */ public void setDescending(Boolean value) { this.descending = value; } }
[ "Benjamin@benjaminsapfel" ]
Benjamin@benjaminsapfel
2c7ab31ac89316909722c6c813b1f53b74b60f34
b9c0c9cf440f2f25553428ef2ae654401c64d208
/Azure2PCF/src/main/java/com/app/Azure2PCF/customException/EmptyInputException.java
706b69e1f9c5b51f92852b1b5891bd9a0378ab04
[]
no_license
namo90/SpringBootProject
4bb9afbfee0b01af45ec11c44e98b6b6105b65f4
0a9487cc4b9efbb994ab1d4f0dfc32a1d35d706a
refs/heads/main
2023-07-15T17:54:54.819959
2021-08-24T04:23:38
2021-08-24T04:23:38
395,004,457
0
0
null
null
null
null
UTF-8
Java
false
false
408
java
package com.app.Azure2PCF.customException; import org.springframework.stereotype.Component; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Component @Data @AllArgsConstructor @NoArgsConstructor public class EmptyInputException extends RuntimeException { private static final long serialVersionUID = 1L; private String errorCode; private String errorMessage; }
[ "Namo.Shelke@SYPUL616WZ93.synechron.com" ]
Namo.Shelke@SYPUL616WZ93.synechron.com
57ea66ba695b474770c902e8354c39e960f46ca5
7bdd096c60948321b936631633e049cc7f9adb4d
/LMCalculator/src/CalcGui/BaseConvPanel.java
e1eba83e5f565cc7bcb073866c2624e1392c2ce0
[]
no_license
lmiori92/lmcalculator
22d34f50ba80234daa352372ef877be0337ac342
fd6bc1bed2c7b93561c25b1c6f3335d015b415bc
refs/heads/master
2021-01-10T08:15:03.031760
2016-02-29T20:02:16
2016-02-29T20:02:16
52,720,341
0
0
null
null
null
null
UTF-8
Java
false
false
2,271
java
/* * Lorenzo Miori - 18/01/2012 * This panel contains the buttons for base conversion methods */ /* Copyright (C) 2012 Lorenzo Miori This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package CalcGui; import java.awt.*; import javax.swing.*; import java.awt.event.*; /** * @author lorenzo */ public class BaseConvPanel extends JPanel implements ActionListener { private DisplayPanel display; private JButton[] advButtons; /* This array has the same index as the correspondent button meaning */ private final DisplayPanel.OPERATION[] BTN_BINDS = { DisplayPanel.OPERATION.BINDEC, DisplayPanel.OPERATION.DECBIN }; public BaseConvPanel(DisplayPanel display) { this.display = display; setLayout(new GridLayout(0, 2, 10, 10)); setBorder(BorderFactory.createTitledBorder("Base conversion")); /* Initialize every button */ advButtons = new JButton[]{ new JButton("BIN <-> DEC"), new JButton("DEC <-> BIN") }; setBindings(); } private void setBindings() { int i = 0; for (JButton btn : advButtons) { btn.addActionListener(this); btn.setActionCommand(Integer.toString(i)); add(btn); i++; } } @Override public void actionPerformed(ActionEvent ae) { int key = Integer.parseInt(ae.getActionCommand()); /* Do the appropriate calculus */ display.performCalc(BTN_BINDS[key]); /* direct calculus, no need to wait for equal event from user */ display.performCalc(DisplayPanel.OPERATION.EQUAL); } }
[ "memoryS60@gmail.com" ]
memoryS60@gmail.com
ccb68b71e8fa2692a3bc3efa3425af28e7b9fe2c
e281f28daf70cc7df36c58e3b6df0e2af4f7f540
/src/main/java/chouti/lda/LDADataset.java
021cf7c7baa6e4087758317bd88c17f7e536f0f3
[]
no_license
yexiaoming20140413/machinelearn
eac852af9c46a87b161d8a44ce90962610462acf
e33ddc13f90bb4cd0ffb9ef7f8da6dff2d865d5c
refs/heads/master
2020-12-24T11:11:15.082693
2016-11-08T11:19:50
2016-11-08T11:19:50
73,178,416
0
0
null
null
null
null
UTF-8
Java
false
false
7,826
java
/* * Copyright (C) 2007 by * * Xuan-Hieu Phan * hieuxuan@ecei.tohoku.ac.jp or pxhieu@gmail.com * Graduate School of Information Sciences * Tohoku University * * Cam-Tu Nguyen * ncamtu@gmail.com * College of Technology * Vietnam National University, Hanoi * * JGibbsLDA is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * JGibbsLDA is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGibbsLDA; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ package chouti.lda; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Vector; public class LDADataset implements Serializable { //--------------------------------------------------------------- // Instance Variables //--------------------------------------------------------------- private static final long serialVersionUID = 433950602299295108L; public Dictionary localDict; // local dictionary public Document[] docs; // a list of documents public int M; // number of documents public int V; // number of words // map from local coordinates (id) to global ones // null if the global dictionary is not set public Map<Integer, Integer> lid2gid; //link to a global dictionary (optional), null for train data, not null for test data public Dictionary globalDict; //-------------------------------------------------------------- // Constructor //-------------------------------------------------------------- public LDADataset(){ localDict = new Dictionary(); M = 0; V = 0; docs = null; globalDict = null; lid2gid = null; } public LDADataset(int M){ localDict = new Dictionary(); this.M = M; this.V = 0; docs = new Document[M]; globalDict = null; lid2gid = null; } public LDADataset(int M, Dictionary globalDict){ localDict = new Dictionary(); this.M = M; this.V = 0; docs = new Document[M]; this.globalDict = globalDict; lid2gid = new HashMap<Integer, Integer>(); } //------------------------------------------------------------- //Public Instance Methods //------------------------------------------------------------- /** * set the document at the index idx if idx is greater than 0 and less than M * @param doc document to be set * @param idx index in the document array */ public void setDoc(Document doc, int idx){ if (0 <= idx && idx < M){ docs[idx] = doc; } } /** * set the document at the index idx if idx is greater than 0 and less than M * @param str string contains doc * @param idx index in the document array */ public void setDoc(String str, int idx){ if (0 <= idx && idx < M){ if(str==null)str=""; str=str.replaceAll(" "," "); String[] words = str.split("[ \\t\\n]"); Vector<Integer> ids = new Vector<Integer>(); for (String word : words){ if(word.equals(""))continue; int _id = localDict.word2id.size(); if (localDict.contains(word)) _id = localDict.getID(word); if (globalDict != null){ //get the global id Integer id = globalDict.getID(word); //System.out.println(id); if (id != null){ localDict.addWord(word); lid2gid.put(_id, id); ids.add(_id); } else { //not in global dictionary //do nothing currently } } else { localDict.addWord(word); ids.add(_id); } } Document doc = new Document(ids, str); docs[idx] = doc; V = localDict.word2id.size(); //lid2gid } } //--------------------------------------------------------------- // I/O methods //--------------------------------------------------------------- /** * read a dataset from a stream, create new dictionary * @return dataset if success and null otherwise */ public static LDADataset readDataSet(String filename){ try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), LDAOption.chartSet)); LDADataset data = readDataSet(reader); reader.close(); return data; } catch (Exception e){ System.out.println("Read Dataset Error: " + e.getMessage()); e.printStackTrace(); return null; } } /** * read a dataset from a file with a preknown vocabulary * @param filename file from which we read dataset * @param dict the dictionary * @return dataset if success and null otherwise */ public static LDADataset readDataSet(String filename, Dictionary dict){ try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), LDAOption.chartSet)); LDADataset data = readDataSet(reader, dict); reader.close(); return data; } catch (Exception e){ System.out.println("Read Dataset Error: " + e.getMessage()); e.printStackTrace(); return null; } } /** * read a dataset from a stream, create new dictionary * @return dataset if success and null otherwise */ public static LDADataset readDataSet(BufferedReader reader){ try { //read number of document String line; line = reader.readLine(); System.out.println(line); int M = Integer.parseInt(line); LDADataset data = new LDADataset(M); for (int i = 0; i < M; ++i){ line = reader.readLine(); ////System.out.println(line); data.setDoc(line, i); } return data; } catch (Exception e){ System.out.println("Read Dataset Error: " + e.getMessage()); e.printStackTrace(); return null; } } /** * read a dataset from a stream with respect to a specified dictionary * @param reader stream from which we read dataset * @param dict the dictionary * @return dataset if success and null otherwise */ public static LDADataset readDataSet(BufferedReader reader, Dictionary dict){ try { //read number of document String line; line = reader.readLine(); int M = Integer.parseInt(line); System.out.println("NewM:" + M); LDADataset data = new LDADataset(M, dict); for (int i = 0; i < M; ++i){ line = reader.readLine(); data.setDoc(line, i); } return data; } catch (Exception e){ System.out.println("Read Dataset Error: " + e.getMessage()); e.printStackTrace(); return null; } } /** * read a dataset from a string, create new dictionary * @param strs String from which we get the dataset, documents are seperated by newline character * @return dataset if success and null otherwise */ public static LDADataset readDataSet(String[] strs){ LDADataset data = new LDADataset(strs.length); for (int i = 0 ; i < strs.length; ++i){ data.setDoc(strs[i], i); } return data; } /** * read a dataset from a string with respect to a specified dictionary * @param strs String from which we get the dataset, documents are seperated by newline character * @param dict the dictionary * @return dataset if success and null otherwise */ public static LDADataset readDataSet(String[] strs, Dictionary dict){ //System.out.println("readDataset..."); LDADataset data = new LDADataset(strs.length, dict); for (int i = 0 ; i < strs.length; ++i){ //System.out.println("set doc " + i); data.setDoc(strs[i], i); } return data; } }
[ "yexiaoming@gozap.com" ]
yexiaoming@gozap.com