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
0cefe6888de1e8f2dd9961699c6224daa7b692fc
15ea0f48b9da85fd4a12c930014b45ade6a188c1
/firs-web-application_step20/src/main/java/webapp/todo/ListTodoServlet.java
568165134964ff5458bbb6d0d1af0c6812c1e843
[]
no_license
j4sysiak/firs-web-application_step20
1a3a4eb881d6639e4cb874314db953565c158c08
096b7d4d3bbc8c683a28aa4fc5ddf2f2978fb28b
refs/heads/master
2020-04-27T23:44:31.696740
2019-03-10T06:52:40
2019-03-10T06:52:40
174,788,562
0
0
null
null
null
null
UTF-8
Java
false
false
1,482
java
package webapp.todo; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import webapp.login.LoginService; import webapp.todo.TodoService; /* * Browser sends Http Request to Web Server * * Code in Web Server => Input:HttpRequest, Output: HttpResponse * JEE with Servlets * * Web Server responds with Http Response */ //Java Platform, Enterprise Edition (Java EE) JEE6 //Servlet is a Java programming language class //used to extend the capabilities of servers //that host applications accessed by means of //a request-response programming model. //1. extends javax.servlet.http.HttpServlet //2. @WebServlet(urlPatterns = "/login.do") //3. doGet(HttpServletRequest request, HttpServletResponse response) //4. How is the response created? @WebServlet(urlPatterns = "/todo.do") public class ListTodoServlet extends HttpServlet { private TodoService todoService = new TodoService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.getSession().setAttribute("todos", todoService.retrieveTodos()); request.getRequestDispatcher("/WEB-INF/views/todo.jsp").forward(request, response); } }
[ "j4sysiak@gmail.com" ]
j4sysiak@gmail.com
b888ff2dc9a2f8c54631e3d9f25d4aaa113d2194
de7b67d4f8aa124f09fc133be5295a0c18d80171
/workspace_activeMq/activemq-parent/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkConnectorView.java
a65bc007ca2c068f53d46ed1b818ea9cd1d17f54
[ "Apache-2.0" ]
permissive
lin-lee/eclipse_workspace_test
adce936e4ae8df97f7f28965a6728540d63224c7
37507f78bc942afb11490c49942cdfc6ef3dfef8
refs/heads/master
2021-05-09T10:02:55.854906
2018-01-31T07:19:02
2018-01-31T07:19:02
119,460,523
0
1
null
null
null
null
UTF-8
Java
false
false
3,534
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.activemq.broker.jmx; import org.apache.activemq.network.NetworkConnector; public class NetworkConnectorView implements NetworkConnectorViewMBean { private final NetworkConnector connector; public NetworkConnectorView(NetworkConnector connector) { this.connector = connector; } public void start() throws Exception { connector.start(); } public void stop() throws Exception { connector.stop(); } public String getName() { return connector.getName(); } public int getNetworkTTL() { return connector.getNetworkTTL(); } public int getPrefetchSize() { return connector.getPrefetchSize(); } public String getUserName() { return connector.getUserName(); } public boolean isBridgeTempDestinations() { return connector.isBridgeTempDestinations(); } public boolean isConduitSubscriptions() { return connector.isConduitSubscriptions(); } public boolean isDecreaseNetworkConsumerPriority() { return connector.isDecreaseNetworkConsumerPriority(); } public boolean isDispatchAsync() { return connector.isDispatchAsync(); } public boolean isDynamicOnly() { return connector.isDynamicOnly(); } public boolean isDuplex() { return connector.isDuplex(); } public void setBridgeTempDestinations(boolean bridgeTempDestinations) { connector.setBridgeTempDestinations(bridgeTempDestinations); } public void setConduitSubscriptions(boolean conduitSubscriptions) { connector.setConduitSubscriptions(conduitSubscriptions); } public void setDispatchAsync(boolean dispatchAsync) { connector.setDispatchAsync(dispatchAsync); } public void setDynamicOnly(boolean dynamicOnly) { connector.setDynamicOnly(dynamicOnly); } public void setNetworkTTL(int networkTTL) { connector.setNetworkTTL(networkTTL); } public void setPassword(String password) { connector.setPassword(password); } public void setPrefetchSize(int prefetchSize) { connector.setPrefetchSize(prefetchSize); } public void setUserName(String userName) { connector.setUserName(userName); } public String getPassword() { String pw = connector.getPassword(); // Hide the password for security reasons. if (pw != null) { pw = pw.replaceAll(".", "*"); } return pw; } public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority) { connector.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); } }
[ "lilin@lvmama.com" ]
lilin@lvmama.com
e42c5d455349e7aedfc1696b28c34ccc10160bb6
5e99c4411bf45adb5ac4daeac19dc8e89d00edea
/ganttproject-2.6.1-r1499-src/biz.ganttproject.impex.msproject2/src/biz/ganttproject/impex/msproject2/ProjectFileExporter.java
e433f570561616f482f7232957ef0e017b11e0cd
[]
no_license
Cashwin/Testing-GanttProject
7b56f7a7a667fdd4f868aa5c305cd1117151e042
8211abdd7f7552f3a9d3c1eb614df7987d238f64
refs/heads/master
2020-05-16T03:26:18.196911
2014-04-05T21:18:39
2014-04-05T21:18:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
18,263
java
/* GanttProject is an opensource project management tool. License: GPL3 Copyright (C) 2010-2012 Dmitry Barashev, GanttProject Team 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package biz.ganttproject.impex.msproject2; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.swing.DefaultListModel; import biz.ganttproject.core.calendar.GPCalendar; import biz.ganttproject.core.calendar.GanttDaysOff; import biz.ganttproject.core.calendar.GPCalendar.DayType; import biz.ganttproject.core.time.GanttCalendar; import biz.ganttproject.core.time.TimeDuration; import net.sf.mpxj.DateRange; import net.sf.mpxj.Day; import net.sf.mpxj.Duration; import net.sf.mpxj.FieldType; import net.sf.mpxj.MPXJException; import net.sf.mpxj.Priority; import net.sf.mpxj.ProjectCalendar; import net.sf.mpxj.ProjectCalendarException; import net.sf.mpxj.ProjectCalendarHours; import net.sf.mpxj.ProjectFile; import net.sf.mpxj.RelationType; import net.sf.mpxj.Resource; import net.sf.mpxj.ResourceField; import net.sf.mpxj.ResourceType; import net.sf.mpxj.TaskField; import net.sf.mpxj.TaskMode; import net.sf.mpxj.TimeUnit; import net.sourceforge.ganttproject.CustomProperty; import net.sourceforge.ganttproject.CustomPropertyClass; import net.sourceforge.ganttproject.CustomPropertyDefinition; import net.sourceforge.ganttproject.CustomPropertyHolder; import net.sourceforge.ganttproject.CustomPropertyManager; import net.sourceforge.ganttproject.GanttTask; import net.sourceforge.ganttproject.IGanttProject; import net.sourceforge.ganttproject.resource.HumanResource; import net.sourceforge.ganttproject.resource.HumanResourceManager; import net.sourceforge.ganttproject.task.ResourceAssignment; import net.sourceforge.ganttproject.task.Task; import net.sourceforge.ganttproject.task.TaskContainmentHierarchyFacade; import net.sourceforge.ganttproject.task.TaskManager; import net.sourceforge.ganttproject.task.dependency.TaskDependency; import net.sourceforge.ganttproject.task.dependency.TaskDependencySlice; /** * Creates MPXJ ProjectFile from GanttProject's IGanttProject. * * @author dbarashev (Dmitry Barashev) */ class ProjectFileExporter { private IGanttProject myNativeProject; private ProjectFile myOutputProject; public ProjectFileExporter(IGanttProject nativeProject) { myNativeProject = nativeProject; myOutputProject = new ProjectFile(); myOutputProject.setAutoOutlineLevel(true); myOutputProject.setAutoWBS(true); myOutputProject.setAutoOutlineNumber(true); myOutputProject.setAutoResourceUniqueID(false); myOutputProject.setAutoTaskUniqueID(false); } ProjectFile run() throws MPXJException { Map<Integer, net.sf.mpxj.Task> id2mpxjTask = new HashMap<Integer, net.sf.mpxj.Task>(); exportCalendar(); exportTasks(id2mpxjTask); exportDependencies(id2mpxjTask); Map<Integer, Resource> id2mpxjResource = new HashMap<Integer, Resource>(); exportResources(id2mpxjResource); exportAssignments(id2mpxjTask, id2mpxjResource); return myOutputProject; } private void exportCalendar() { ProjectCalendar calendar = myOutputProject.addDefaultBaseCalendar(); exportWeekends(calendar); exportHolidays(calendar); } private boolean isWorkingDay(int day) { return getCalendar().getOnlyShowWeekends() || getCalendar().getWeekDayType(day) == DayType.WORKING; } private void exportWeekends(ProjectCalendar calendar) { ProjectCalendarHours workingDayHours = calendar.getCalendarHours(Day.MONDAY); calendar.setWorkingDay(Day.MONDAY, isWorkingDay(Calendar.MONDAY)); calendar.setWorkingDay(Day.TUESDAY, isWorkingDay(Calendar.TUESDAY)); calendar.setWorkingDay(Day.WEDNESDAY, isWorkingDay(Calendar.WEDNESDAY)); calendar.setWorkingDay(Day.THURSDAY, isWorkingDay(Calendar.THURSDAY)); calendar.setWorkingDay(Day.FRIDAY, isWorkingDay(Calendar.FRIDAY)); calendar.setWorkingDay(Day.SATURDAY, isWorkingDay(Calendar.SATURDAY)); if (calendar.isWorkingDay(Day.SATURDAY)) { copyHours(workingDayHours, calendar.addCalendarHours(Day.SATURDAY)); } calendar.setWorkingDay(Day.SUNDAY, isWorkingDay(Calendar.SUNDAY)); if (calendar.isWorkingDay(Day.SUNDAY)) { copyHours(workingDayHours, calendar.addCalendarHours(Day.SUNDAY)); } } private void copyHours(ProjectCalendarHours from, ProjectCalendarHours to) { for (DateRange range : from) { to.addRange(range); } } private void exportHolidays(ProjectCalendar calendar) { for (GPCalendar.Holiday h : getCalendar().getPublicHolidays()) { if (!h.isRepeating) { Date d = h.date; ProjectCalendarException calendarException = calendar.addCalendarException(d, d); calendarException.addRange(new DateRange(d, d)); } } } private void exportTasks(Map<Integer, net.sf.mpxj.Task> id2mpxjTask) { Map<CustomPropertyDefinition, FieldType> customProperty_fieldType = new HashMap<CustomPropertyDefinition, FieldType>(); collectCustomProperties(getTaskManager().getCustomPropertyManager(), customProperty_fieldType, TaskField.class); for (Entry<CustomPropertyDefinition, FieldType> e : customProperty_fieldType.entrySet()) { myOutputProject.setTaskFieldAlias((TaskField) e.getValue(), e.getKey().getName()); } net.sf.mpxj.Task rootTask = myOutputProject.addTask(); rootTask.setEffortDriven(false); rootTask.setID(0); rootTask.setUniqueID(0); rootTask.setOutlineLevel(0); rootTask.setWBS("0"); rootTask.setOutlineNumber("0"); rootTask.setStart(convertStartTime(getTaskManager().getProjectStart())); rootTask.setFinish(convertFinishTime(getTaskManager().getProjectEnd())); rootTask.setDuration(convertDuration(getTaskManager().createLength( getTaskManager().getRootTask().getDuration().getTimeUnit(), getTaskManager().getProjectStart(), getTaskManager().getProjectEnd()))); // rootTask.setDurationFormat(TimeUnit.DAYS); rootTask.setTaskMode(TaskMode.AUTO_SCHEDULED); int i = 0; for (Task t : getTaskHierarchy().getNestedTasks(getTaskHierarchy().getRootTask())) { exportTask(t, null, 1, ++i, id2mpxjTask, customProperty_fieldType); } } private void exportTask(Task t, net.sf.mpxj.Task mpxjParentTask, int outlineLevel, int ordinalNum, Map<Integer, net.sf.mpxj.Task> id2mpxjTask, Map<CustomPropertyDefinition, FieldType> customProperty_fieldType) { final net.sf.mpxj.Task mpxjTask = mpxjParentTask == null ? myOutputProject.addTask() : mpxjParentTask.addTask(); mpxjTask.setOutlineLevel(outlineLevel); String wbs = (mpxjParentTask == null ? "" : mpxjParentTask.getWBS() + ".") + String.valueOf(ordinalNum); mpxjTask.setWBS(wbs); mpxjTask.setOutlineNumber(wbs); mpxjTask.setUniqueID(convertTaskId(t.getTaskID())); mpxjTask.setID(id2mpxjTask.size() + 1); mpxjTask.setName(t.getName()); mpxjTask.setNotes(t.getNotes()); mpxjTask.setMilestone(t.isMilestone()); mpxjTask.setPercentageComplete(t.getCompletionPercentage()); mpxjTask.setHyperlink(((GanttTask) t).getWebLink()); mpxjTask.setIgnoreResourceCalendar(true); Task[] nestedTasks = getTaskHierarchy().getNestedTasks(t); if (nestedTasks.length > 0) { } mpxjTask.setTaskMode(TaskMode.MANUALLY_SCHEDULED); Date startTime = convertStartTime(t.getStart().getTime()); Date finishTime = convertFinishTime(t.getEnd().getTime()); mpxjTask.setStart(startTime); mpxjTask.setFinish(finishTime); Duration duration = convertDuration(t.getDuration()); mpxjTask.setDuration(duration); mpxjTask.setManualDuration(duration); // mpxjTask.setDurationFormat(TimeUnit.DAYS); Duration[] durations = getActualAndRemainingDuration(mpxjTask); mpxjTask.setActualDuration(durations[0]); mpxjTask.setRemainingDuration(durations[1]); mpxjTask.setPriority(convertPriority(t)); exportCustomProperties(t.getCustomValues(), customProperty_fieldType, new CustomPropertySetter() { @Override public void set(FieldType ft, Object value) { mpxjTask.set(ft, value); } }); id2mpxjTask.put(mpxjTask.getUniqueID(), mpxjTask); int i = 0; for (Task child : nestedTasks) { exportTask(child, mpxjTask, outlineLevel + 1, ++i, id2mpxjTask, customProperty_fieldType); } } private Date convertStartTime(Date gpStartDate) { Date startTime = myOutputProject.getCalendar().getStartTime(gpStartDate); Calendar c = (Calendar) Calendar.getInstance().clone(); c.setTime(gpStartDate); c.set(Calendar.HOUR, startTime.getHours()); c.set(Calendar.MINUTE, startTime.getMinutes()); return c.getTime(); } private Date convertFinishTime(Date gpFinishDate) { Calendar c = (Calendar) Calendar.getInstance().clone(); c.setTime(gpFinishDate); c.add(Calendar.DAY_OF_YEAR, -1); Date finishTime = myOutputProject.getCalendar().getFinishTime(c.getTime()); if (finishTime != null) { c.set(Calendar.HOUR, finishTime.getHours()); c.set(Calendar.MINUTE, finishTime.getMinutes()); } return c.getTime(); } private Duration convertDuration(TimeDuration duration) { return Duration.getInstance(duration.getLength(), TimeUnit.DAYS); } private static Duration[] getActualAndRemainingDuration(net.sf.mpxj.Task mpxjTask) { return getActualAndRemainingDuration(mpxjTask, 1.0); } private static Duration[] getActualAndRemainingDuration(net.sf.mpxj.Task mpxjTask, double load) { TimeUnit durationUnits = mpxjTask.getDuration().getUnits(); double actualWork = (mpxjTask.getDuration().getDuration() * mpxjTask.getPercentageComplete().doubleValue() * load) / 100; double remainingWork = mpxjTask.getDuration().getDuration() - actualWork; return new Duration[] { Duration.getInstance(actualWork, durationUnits), Duration.getInstance(remainingWork, durationUnits) }; } private void exportDependencies(Map<Integer, net.sf.mpxj.Task> id2mpxjTask) { for (Task t : getTaskManager().getTasks()) { net.sf.mpxj.Task mpxjTask = id2mpxjTask.get(convertTaskId(t.getTaskID())); TaskDependencySlice dependencies = t.getDependenciesAsDependant(); for (TaskDependency dep : dependencies.toArray()) { net.sf.mpxj.Task mpxjPredecessor = id2mpxjTask.get(convertTaskId(dep.getDependee().getTaskID())); assert mpxjPredecessor != null : "Can't find mpxj task for id=" + dep.getDependee().getTaskID(); mpxjTask.addPredecessor(mpxjPredecessor, convertConstraint(dep), convertLag(dep)); } } } private RelationType convertConstraint(TaskDependency dep) { switch (dep.getConstraint().getType()) { case finishstart: return RelationType.FINISH_START; case startfinish: return RelationType.START_FINISH; case finishfinish: return RelationType.FINISH_FINISH; case startstart: return RelationType.START_START; default: assert false : "Should not be here"; return null; } } private static Duration convertLag(TaskDependency dep) { // TODO(dbarashev): Get rid of days return Duration.getInstance(dep.getDifference(), TimeUnit.DAYS); } private Priority convertPriority(Task t) { switch (t.getPriority()) { case LOWEST: return Priority.getInstance(Priority.LOWEST); case LOW: return Priority.getInstance(Priority.LOW); case NORMAL: return Priority.getInstance(Priority.MEDIUM); case HIGH: return Priority.getInstance(Priority.HIGH); case HIGHEST: return Priority.getInstance(Priority.HIGHEST); default: assert false : "Should not be here"; return Priority.getInstance(Priority.MEDIUM); } } private int convertTaskId(int taskId) { return taskId == 0 ? getMaxTaskID() + 1 : taskId; } private int getMaxTaskID() { int maxID = 0; for (Task t : getTaskManager().getTasks()) { if (t.getTaskID() > maxID) { maxID = t.getTaskID(); } } return maxID; } private void exportResources(Map<Integer, Resource> id2mpxjResource) throws MPXJException { Map<CustomPropertyDefinition, FieldType> customProperty_fieldType = new HashMap<CustomPropertyDefinition, FieldType>(); collectCustomProperties(getResourceManager().getCustomPropertyManager(), customProperty_fieldType, ResourceField.class); for (Entry<CustomPropertyDefinition, FieldType> e : customProperty_fieldType.entrySet()) { myOutputProject.setResourceFieldAlias((ResourceField) e.getValue(), e.getKey().getName()); } for (HumanResource hr : getResourceManager().getResources()) { exportResource(hr, id2mpxjResource, customProperty_fieldType); } } private void exportResource(HumanResource hr, Map<Integer, Resource> id2mpxjResource, Map<CustomPropertyDefinition, FieldType> customProperty_fieldType) throws MPXJException { final Resource mpxjResource = myOutputProject.addResource(); mpxjResource.setUniqueID(hr.getId() + 1); mpxjResource.setID(id2mpxjResource.size() + 1); mpxjResource.setName(hr.getName()); mpxjResource.setEmailAddress(hr.getMail()); mpxjResource.setType(ResourceType.WORK); mpxjResource.setCanLevel(false); exportDaysOff(hr, mpxjResource); exportCustomProperties(hr, customProperty_fieldType, new CustomPropertySetter() { @Override public void set(FieldType ft, Object value) { mpxjResource.set(ft, value); } }); id2mpxjResource.put(hr.getId(), mpxjResource); } private static <T extends Enum<T>> void collectCustomProperties(CustomPropertyManager customPropertyManager, Map<CustomPropertyDefinition, FieldType> customProperty_fieldType, Class<T> fieldTypeClass) { Map<String, Integer> typeCounter = new HashMap<String, Integer>(); for (CustomPropertyDefinition def : customPropertyManager.getDefinitions()) { Integer count = typeCounter.get(def.getTypeAsString()); if (count == null) { count = 1; } else { count++; } typeCounter.put(def.getTypeAsString(), count); FieldType ft = getFieldType(fieldTypeClass, def, count); customProperty_fieldType.put(def, ft); } } private static <T extends Enum<T>> FieldType getFieldType(Class<T> enumClass, CustomPropertyDefinition def, Integer count) { String name; switch (def.getPropertyClass()) { case BOOLEAN: name = "FLAG"; break; case INTEGER: case DOUBLE: name = "NUMBER"; break; case TEXT: name = "TEXT"; break; case DATE: name = "DATE"; break; default: assert false : "Should not be here"; name = "TEXT"; } try { return (FieldType) Enum.valueOf(enumClass, name + count); } catch (IllegalArgumentException e) { return null; } } private static interface CustomPropertySetter { void set(FieldType ft, Object value); } private static void exportCustomProperties(CustomPropertyHolder holder, Map<CustomPropertyDefinition, FieldType> customProperty_fieldType, CustomPropertySetter setter) { for (CustomProperty cp : holder.getCustomProperties()) { FieldType ft = customProperty_fieldType.get(cp.getDefinition()); if (ft != null) { setter.set(ft, convertValue(cp)); } } } private static Object convertValue(CustomProperty cp) { if (cp.getDefinition().getPropertyClass() == CustomPropertyClass.DATE) { GanttCalendar value = (GanttCalendar) cp.getValue(); return value.getTime(); } return cp.getValue(); } private void exportDaysOff(HumanResource hr, Resource mpxjResource) throws MPXJException { DefaultListModel daysOff = hr.getDaysOff(); if (!daysOff.isEmpty()) { ProjectCalendar resourceCalendar = mpxjResource.addResourceCalendar(); exportWeekends(resourceCalendar); resourceCalendar.setBaseCalendar(myOutputProject.getCalendar()); // resourceCalendar.setUniqueID(hr.getId()); for (int i = 0; i < daysOff.size(); i++) { GanttDaysOff dayOff = (GanttDaysOff) daysOff.get(i); resourceCalendar.addCalendarException(dayOff.getStart().getTime(), dayOff.getFinish().getTime()); } } } private void exportAssignments(Map<Integer, net.sf.mpxj.Task> id2mpxjTask, Map<Integer, Resource> id2mpxjResource) { for (Task t : getTaskManager().getTasks()) { net.sf.mpxj.Task mpxjTask = id2mpxjTask.get(convertTaskId(t.getTaskID())); for (ResourceAssignment ra : t.getAssignments()) { Resource mpxjResource = id2mpxjResource.get(ra.getResource().getId()); net.sf.mpxj.ResourceAssignment mpxjAssignment = mpxjTask.addResourceAssignment(mpxjResource); mpxjAssignment.setUnits(ra.getLoad()); mpxjAssignment.setStart(mpxjTask.getStart()); mpxjAssignment.setFinish(mpxjTask.getFinish()); mpxjAssignment.setWork(mpxjTask.getDuration()); Duration[] durations = getActualAndRemainingDuration(mpxjTask, ra.getLoad() / 100.0); mpxjAssignment.setActualWork(durations[0]); mpxjAssignment.setRemainingWork(durations[1]); } } } private TaskManager getTaskManager() { return myNativeProject.getTaskManager(); } private TaskContainmentHierarchyFacade getTaskHierarchy() { return getTaskManager().getTaskHierarchy(); } private HumanResourceManager getResourceManager() { return myNativeProject.getHumanResourceManager(); } private GPCalendar getCalendar() { return getTaskManager().getCalendar(); } }
[ "fashwinchand@smu.edu" ]
fashwinchand@smu.edu
06920eca73ef3bb0f9f77c162e821cca191869fc
df2585dba6960cb72975d8c1c502a349f471d059
/app/src/main/java/hds/aplications/com/mycp/services/CountryService.java
1f7fb31b38e5ec57fef073953eb6edc0de1b37f2
[]
no_license
vhagar91/ClientApkforMycp
c551ff7fc1169e2321ebac14090331f703ced86d
5c91ff6fb7a31a003d8f8085424336306225f711
refs/heads/master
2020-03-27T03:23:07.674504
2018-08-23T20:12:13
2018-08-23T20:12:13
145,858,635
2
0
null
null
null
null
UTF-8
Java
false
false
524
java
package hds.aplications.com.mycp.services; import java.util.List; import hds.aplications.com.mycp.models.Country; import hds.aplications.com.mycp.models.Destination; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Path; import retrofit.http.Query; /** * Created by Miguel Gomez Leon. * mgleonsc@gmail.com */ public interface CountryService{ @GET("/api/mcp_v1/counties.{format}") void getAll(@Path("format") String format, @Query("key") String key, Callback<List<Country>> callback); }
[ "oviera@uci.cu" ]
oviera@uci.cu
813fac293ce21441a462ae2ed1030e4057c107b4
7ae6360e3093ef87ac6b24878a908ea3999a2f93
/Programmers/Greedy/IslandConnect.java
2bcd541b3047e7e1c3b5bd83d79e401deaa789cd
[]
no_license
LeeJiSeon/Algorithm
5df66bdca67b8b10ec5ad4c3c706004c7f071d42
c2d8b5495a0ca9f47ce6888504f2cb20a05ea554
refs/heads/master
2020-12-24T03:51:15.141350
2020-11-30T02:43:26
2020-11-30T02:43:26
237,372,065
0
0
null
null
null
null
UTF-8
Java
false
false
1,240
java
import java.util.*; class IslanConnect { class Edge implements Comparable<Edge>{ int v1, v2, cost; Edge(int v1, int v2, int cost) { this.v1 = v1; this.v2 = v2; this.cost = cost; } @Override public int compareTo(Edge e) { return this.cost - e.cost; } } int[] parent; PriorityQueue<Edge> adj; public int solution(int n, int[][] costs) { int answer = 0; parent = new int[n]; adj = new PriorityQueue<>(); for(int[] cost : costs) adj.offer(new Edge(cost[0], cost[1], cost[2])); for(int i = 0 ; i < n ; i++) parent[i] = i; while(!adj.isEmpty()) { Edge edge = adj.poll(); if(find(edge.v1) != find(edge.v2)) { union(edge.v1, edge.v2); answer += edge.cost; } } return answer; } private int find(int v) { if(parent[v] == v) return v; return parent[v] = find(parent[v]); } private void union(int v1, int v2) { int f1 = find(v1); int f2 = find(v2); if(f1 != f2) parent[f2] = f1; } }
[ "noreply@github.com" ]
LeeJiSeon.noreply@github.com
4a94f19625330e9cdd1f36dcc76fed74912d9715
af3a7ec44e49b82f52239c1dbb1da6e020808215
/JavaAssignments/src/set2/a14.java
6411e3eb051749a852cba92a376e22ee834909f8
[]
no_license
UttamKr19/learning-java
150082042487808359a6483c05505724dfc6d48c
f7cec8a4f19a1909b149a857a82091cab7e95876
refs/heads/master
2023-07-17T20:06:16.222278
2021-09-01T03:56:45
2021-09-01T03:56:45
401,923,624
0
0
null
null
null
null
UTF-8
Java
false
false
307
java
package set2; public class a14 { static boolean makeBricks(int small,int large,int goal) { if(small+(large*5)>=goal) return true; return false; } public static void main(String[] args) { boolean isPossible=makeBricks(3, 2, 10); System.out.println(isPossible?"Possible":"Not possible"); } }
[ "uttam.kr.work@gmail.com" ]
uttam.kr.work@gmail.com
f2b8642e205a178b13e7160e84d145f6f074c0d7
77623d6dd90f2d1a401ee720adb41c3c0c264715
/DiffTGen-result/output/Closure_38_3_sequencer/target/0/28/evosuite-tests/com/google/javascript/jscomp/CodeConsumer_ESTest_scaffolding.java
57908709bad660fa69c8d33cef6a941b12d5a712
[]
no_license
wuhongjun15/overfitting-study
40be0f062bbd6716d8de6b06454b8c73bae3438d
5093979e861cda6575242d92ca12355a26ca55e0
refs/heads/master
2021-04-17T05:37:48.393527
2020-04-11T01:53:53
2020-04-11T01:53:53
249,413,962
0
0
null
null
null
null
UTF-8
Java
false
false
13,378
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Fri Mar 27 03:54:04 GMT 2020 */ package com.google.javascript.jscomp; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; import org.evosuite.runtime.sandbox.Sandbox; import org.evosuite.runtime.sandbox.Sandbox.SandboxMode; @EvoSuiteClassExclude public class CodeConsumer_ESTest_scaffolding { @org.junit.Rule public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); @BeforeClass public static void initEvoSuiteFramework() { org.evosuite.runtime.RuntimeSettings.className = "com.google.javascript.jscomp.CodeConsumer"; org.evosuite.runtime.GuiSupport.initialize(); org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); org.evosuite.runtime.classhandling.JDKClassResetter.init(); setSystemProperties(); initializeClasses(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); } @Before public void initTestCase(){ threadStopper.storeCurrentThreads(); threadStopper.startRecordingTime(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); org.evosuite.runtime.GuiSupport.setHeadless(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); org.evosuite.runtime.agent.InstrumentingAgent.activate(); } @After public void doneWithTestCase(){ threadStopper.killAndJoinClientThreads(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); org.evosuite.runtime.classhandling.JDKClassResetter.reset(); resetClasses(); org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); } public static void setSystemProperties() { /*No java.lang.System property to set*/ } private static void initializeClasses() { org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(CodeConsumer_ESTest_scaffolding.class.getClassLoader() , "com.google.javascript.rhino.JSDocInfo$StringPosition", "com.google.javascript.rhino.jstype.NoType", "com.google.javascript.rhino.JSDocInfo$Visibility", "com.google.javascript.rhino.jstype.ArrowType", "com.google.javascript.rhino.jstype.PrototypeObjectType", "com.google.javascript.rhino.SimpleErrorReporter", "com.google.common.base.CharMatcher$Whitespace", "com.google.common.base.CharMatcher$ForPredicate", "com.google.javascript.rhino.jstype.NumberType", "com.google.common.base.Predicates$ObjectPredicate", "com.google.javascript.jscomp.CodeConsumer", "com.google.common.base.CharMatcher$JavaDigit", "com.google.common.base.Predicates$SubtypeOfPredicate", "com.google.javascript.rhino.jstype.StaticScope", "com.google.javascript.rhino.jstype.InstanceObjectType", "plume.UtilMDE$EnumerationIterator", "com.google.javascript.rhino.Node$PropListItem", "com.google.javascript.jscomp.ChainableReverseAbstractInterpreter$RestrictByFalseTypeOfResultVisitor", "com.google.common.base.Predicates$ContainsPatternPredicate", "com.google.javascript.rhino.Node", "com.google.javascript.rhino.jstype.ObjectType", "com.google.javascript.rhino.SourcePosition", "com.google.javascript.jscomp.CodePrinter$1", "com.google.common.base.CharMatcher$InRange", "com.google.common.base.CharMatcher$IsNot", "com.google.common.base.CharMatcher$JavaLetter", "com.google.javascript.rhino.JSDocInfo$TrimmedStringPosition", "com.google.common.base.CharMatcher$JavaLetterOrDigit", "com.google.javascript.rhino.JSDocInfo$Marker", "com.google.common.base.CharMatcher$NegatedFastMatcher", "org.apache.oro.text.PatternCache", "com.google.javascript.rhino.Node$NodeMismatch", "com.google.javascript.rhino.jstype.RecordType", "org.apache.oro.text.regex.Pattern", "com.google.common.base.Predicate", "com.google.javascript.rhino.jstype.JSType$2", "com.google.common.base.CharMatcher$IsEither", "com.google.common.base.Predicates$AlwaysFalsePredicate", "com.google.common.base.CharMatcher$Invisible", "com.google.javascript.jscomp.SourceMap$DetailLevel", "com.google.javascript.jscomp.SourceMap$1", "com.google.common.base.CharMatcher$None", "plume.UtilMDE$IteratorEnumeration", "com.google.javascript.rhino.jstype.VoidType", "org.apache.oro.io.RegexFilenameFilter", "com.google.javascript.jscomp.SourceMap", "com.google.javascript.jscomp.InlineCostEstimator$CompiledSizeEstimator", "plume.UtilMDE$FilteredIterator", "com.google.javascript.rhino.jstype.JSType", "com.google.common.base.CharMatcher$Any", "org.apache.oro.text.MalformedCachePatternException", "com.google.common.base.Predicates$InstanceOfPredicate", "com.google.javascript.rhino.Node$StringNode", "org.apache.oro.text.regex.PatternMatcher", "com.google.javascript.rhino.jstype.ProxyObjectType", "plume.UtilMDE$MergedIterator", "com.google.javascript.rhino.jstype.TemplateType", "com.google.javascript.rhino.jstype.NamedType", "com.google.debugging.sourcemap.SourceMapGenerator", "com.google.javascript.rhino.InputId", "com.google.javascript.rhino.jstype.ParameterizedType", "com.google.javascript.rhino.Node$SideEffectFlags", "plume.UtilMDE$WildcardFilter", "com.google.debugging.sourcemap.FilePosition", "com.google.common.base.Predicates", "com.google.javascript.rhino.jstype.NullType", "com.google.javascript.rhino.ErrorReporter", "com.google.javascript.jscomp.CodePrinter$CompactCodePrinter", "com.google.javascript.rhino.jstype.UnknownType", "com.google.javascript.rhino.jstype.ValueType", "com.google.javascript.rhino.Node$FileLevelJsDocBuilder", "com.google.javascript.rhino.jstype.StaticSourceFile", "com.google.javascript.rhino.jstype.BooleanType", "com.google.javascript.rhino.jstype.NoObjectType", "com.google.common.base.CharMatcher", "com.google.javascript.rhino.jstype.JSType$TypePair", "com.google.common.base.CharMatcher$And", "plume.UtilMDE", "com.google.common.base.CharMatcher$5", "org.apache.oro.io.AwkFilenameFilter", "com.google.common.base.CharMatcher$4", "com.google.javascript.rhino.JSDocInfo$1", "com.google.common.base.CharMatcher$3", "com.google.common.base.CharMatcher$2", "com.google.common.base.CharMatcher$9", "com.google.javascript.rhino.jstype.ErrorFunctionType", "com.google.common.base.CharMatcher$8", "com.google.common.base.CharMatcher$AnyOf", "com.google.common.base.CharMatcher$7", "com.google.javascript.rhino.jstype.FunctionType", "com.google.common.base.CharMatcher$6", "com.google.common.base.Predicates$NotNullPredicate", "com.google.common.base.Predicates$CompositionPredicate", "com.google.common.base.Predicates$OrPredicate", "com.google.javascript.rhino.JSDocInfo", "com.google.common.base.CharMatcher$1", "com.google.javascript.jscomp.CodePrinter$MappedCodePrinter$Mapping", "com.google.common.base.CharMatcher$FastMatcher", "com.google.common.base.CharMatcher$JavaIsoControl", "com.google.javascript.jscomp.SemanticReverseAbstractInterpreter$RestrictByTrueInstanceOfResultVisitor", "com.google.common.base.Predicates$IsEqualToPredicate", "com.google.common.base.CharMatcher$12", "com.google.common.base.CharMatcher$11", "com.google.common.base.CharMatcher$10", "com.google.javascript.rhino.jstype.TernaryValue", "com.google.javascript.jscomp.ChainableReverseAbstractInterpreter$RestrictByOneTypeOfResultVisitor", "com.google.javascript.rhino.Node$AncestorIterable", "com.google.javascript.rhino.jstype.IndexedType", "com.google.common.base.CharMatcher$15", "com.google.common.base.Predicates$AssignableFromPredicate", "com.google.common.base.CharMatcher$14", "com.google.common.base.CharMatcher$13", "com.google.javascript.jscomp.CodePrinter$Builder", "com.google.javascript.rhino.jstype.UnresolvedTypeExpression", "com.google.common.base.Predicates$1", "com.google.common.base.Predicates$ContainsPatternFromStringPredicate", "com.google.javascript.jscomp.CodePrinter$PrettyCodePrinter", "com.google.common.base.CharMatcher$BitSetMatcher", "com.google.common.base.SmallCharMatcher", "org.apache.oro.io.GlobFilenameFilter", "com.google.javascript.rhino.jstype.EnumElementType", "com.google.javascript.rhino.jstype.UnionType", "com.google.common.base.CharMatcher$RangesMatcher", "com.google.javascript.rhino.Node$NumberNode", "com.google.common.base.CharMatcher$JavaUpperCase", "com.google.javascript.rhino.jstype.StaticSlot", "com.google.common.base.Predicates$AndPredicate", "plume.UtilMDE$MergedIterator2", "com.google.common.base.CharMatcher$BreakingWhitespace", "plume.MultiVersionControl$StreamOfNewlines", "com.google.javascript.rhino.jstype.SimpleSourceFile", "com.google.javascript.rhino.jstype.EnumType", "com.google.common.base.CharMatcher$NamedFastMatcher", "com.google.javascript.jscomp.PerformanceTracker$CodeSizeEstimatePrinter", "com.google.javascript.rhino.JSDocInfo$TypePosition", "plume.UtilMDE$NullableStringComparator", "com.google.common.base.Predicates$NotPredicate", "com.google.common.base.Equivalence$EquivalentToPredicate", "com.google.javascript.rhino.JSDocInfo$LazilyInitializedInfo", "org.apache.oro.text.regex.PatternCompiler", "com.google.common.base.CharMatcher$LookupTable", "com.google.common.base.CharMatcher$Is", "com.google.javascript.jscomp.ChainableReverseAbstractInterpreter", "plume.MultiVersionControl$IsDirectoryFilter", "com.google.common.base.CharMatcher$SingleWidth", "com.google.javascript.jscomp.CodePrinter$MappedCodePrinter", "com.google.common.base.CharMatcher$JavaLowerCase", "com.google.javascript.rhino.jstype.BooleanLiteralSet", "com.google.javascript.rhino.jstype.StaticReference", "com.google.javascript.jscomp.SemanticReverseAbstractInterpreter$RestrictByFalseInstanceOfResultVisitor", "com.google.javascript.jscomp.ChainableReverseAbstractInterpreter$RestrictByTrueTypeOfResultVisitor", "plume.MultiVersionControl", "org.apache.oro.io.Perl5FilenameFilter", "plume.UtilMDE$RemoveFirstAndLastIterator", "com.google.javascript.rhino.JSDocInfo$NamePosition", "com.google.javascript.rhino.JSDocInfo$LazilyInitializedDocumentation", "com.google.javascript.rhino.jstype.StringType", "com.google.javascript.rhino.jstype.ObjectType$Property", "com.google.javascript.rhino.jstype.JSTypeRegistry", "com.google.common.base.Predicates$IsNullPredicate", "com.google.javascript.jscomp.CodePrinter$Format", "com.google.javascript.jscomp.SourceMap$LocationMapping", "com.google.common.base.CharMatcher$Negated", "com.google.javascript.jscomp.ReverseAbstractInterpreter", "com.google.javascript.rhino.jstype.Visitor", "com.google.common.base.CharMatcher$Ascii", "com.google.javascript.rhino.jstype.NoResolvedType", "com.google.javascript.rhino.jstype.JSTypeNative", "com.google.javascript.rhino.jstype.AllType", "com.google.common.base.CharMatcher$Or", "com.google.javascript.rhino.jstype.FunctionType$Kind", "com.google.common.base.Predicates$AlwaysTruePredicate", "com.google.javascript.jscomp.ChainableReverseAbstractInterpreter$RestrictByTypeOfResultVisitor", "com.google.javascript.rhino.JSTypeExpression", "com.google.common.base.CharMatcher$Digit", "plume.MultiVersionControl$Replacer", "com.google.javascript.jscomp.CodePrinter", "com.google.common.base.Predicates$InPredicate" ); } private static void resetClasses() { org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(CodeConsumer_ESTest_scaffolding.class.getClassLoader()); org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( "com.google.javascript.jscomp.CodeConsumer", "com.google.javascript.jscomp.CodePrinter$MappedCodePrinter", "com.google.javascript.jscomp.CodePrinter$PrettyCodePrinter" ); } }
[ "375882286@qq.com" ]
375882286@qq.com
c2fb0441f0e1f41be3ed3b242f4035bf36487c8c
260343d1b3b753d713f204f394049b80566a5a14
/UserAgent/src/main/java/com/example/demo/controller/PageController.java
7fd27a40ecf922701a105af50ad9d4018fc69cc2
[]
no_license
alihaider8480/cheackSystemRequest
8e88ecb8a103ec0331c969ea346aaf648aca5a91
031144dc3014db5e361854a44cb4b5173d343218
refs/heads/master
2022-04-15T02:58:00.806797
2020-04-13T10:15:29
2020-04-13T10:15:29
255,289,900
1
0
null
null
null
null
UTF-8
Java
false
false
388
java
package com.example.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class PageController { @GetMapping("/") public String gohomePage() { System.out.println("Start....."); return "homePage"; } }
[ "Dev Pc@DESKTOP-DRSB3FD" ]
Dev Pc@DESKTOP-DRSB3FD
0df68d4d50f65b870b31867f5c747a9e27a2ebbc
e2ec6e0428fb4d5a9042b41fa745875f01b6ec81
/SpMVC_iolist/src/main/java/com/biz/iolist/controller/HomeController.java
b689451c52f5edc840fe9e5f24dc45065a1bea09
[]
no_license
smskit726/One_Day_IOList
96383aa8b37695d8d67d07deb1637549a2b8714b
e36618d463015f61a518ff4f867a07fbcab61449
refs/heads/master
2022-12-25T23:13:07.161419
2020-10-01T12:08:37
2020-10-01T12:08:37
299,542,378
0
0
null
null
null
null
UTF-8
Java
false
false
2,760
java
package com.biz.iolist.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.biz.iolist.mapper.ProductDao; import com.biz.iolist.model.ProductVO; import com.biz.iolist.service.ProductService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @Controller @RequiredArgsConstructor public class HomeController { @Autowired private ProductDao productDao; @Qualifier("pService") private final ProductService pService; @Transactional @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Model model) { List<ProductVO> proList = pService.selectAll(); model.addAttribute("PRODUCTS", proList); model.addAttribute("BODY","PRO-LIST"); return "home"; } @RequestMapping(value = "/write", method = RequestMethod.GET) public String write(@ModelAttribute("PROVO") ProductVO proVO, Model model) { model.addAttribute("PROVO", proVO); model.addAttribute("BODY", "PRO-WRITE"); return "home"; } @RequestMapping(value = "/write", method=RequestMethod.POST) public String write(@ModelAttribute("PROVO") ProductVO proVO) { pService.insert(proVO); return "redirect:/"; } @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET) public String detail(@PathVariable("id") Long seq, Model model) { ProductVO proVO = pService.findById(seq); log.debug(proVO.toString()); model.addAttribute("PROVO", proVO); model.addAttribute("BODY", "PRO-DETAIL"); return "home"; } @RequestMapping(value = "/delete", method = RequestMethod.GET) public String delete(@RequestParam("id") Long seq, Model model) { pService.delete(seq); return "redirect:/"; } @RequestMapping(value = "/update", method=RequestMethod.GET) public String update(@RequestParam("id") Long seq, @ModelAttribute("PROVO") ProductVO proVO, Model model) { proVO = pService.findById(seq); model.addAttribute("PROVO", proVO); model.addAttribute("BODY","PRO-WRITE"); return "home"; } @RequestMapping(value = "/update", method=RequestMethod.POST) public String update(@ModelAttribute("PROVO") ProductVO proVO, Model model) { pService.update(proVO); return "redirect:/"; } }
[ "smskit726@gmail.com" ]
smskit726@gmail.com
2ea6416bd8b9712c91fefd362f5237f82114a114
e14f4dd4a058165e447f741156883f31c2ca6d7b
/src/com/tutorialspoint4/MainApp.java
ce9d98b5984775d7e052182f6be81c25185c4982
[]
no_license
MINORHDMI/SpringLearning
dac4fd34c1238b0b86f05f30dccb098a44eeb706
23650b7dfad3a919b910a550e35edcd717932dfb
refs/heads/master
2023-01-08T23:47:21.108665
2020-11-15T14:39:44
2020-11-15T14:39:44
312,201,133
0
0
null
null
null
null
UTF-8
Java
false
false
456
java
package com.tutorialspoint4; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Bean4.xml"); TextEditor te = (TextEditor) context.getBean("textEditor"); te.spellCheck(); } }
[ "1019364668@qq.com" ]
1019364668@qq.com
d2086d47ac2087a0477c2cbee35503ebd64e39d7
2c844e20ac325274761bdcc3479572646e1c4611
/a3/loi_cheng_assignment3/src/cscie97/ledger/test/TestInteractiveLedger.java
34cb41080d9ce9e27501a20c08b271b8ea2f0f3a
[]
no_license
loibucket/hes-2020-CSCI-E-97-Software-Design
7349f5d140749a7f07cb115d09920854cdd05c25
e2c71acf8ba46bf13134abb268ddaca5e9ade8bf
refs/heads/master
2023-02-02T18:12:19.076125
2020-12-13T20:13:35
2020-12-13T20:13:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
666
java
package cscie97.ledger.test; import cscie97.ledger.*; import java.util.*; /** * Processses commands line by line from user input */ public class TestInteractiveLedger { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("LEDGER"); System.out.println("CTRL-C TO EXIT"); try { while (true) { System.out.print("COMMAND:"); String str = sc.nextLine(); CommandProcessor.processCommand(str, 1); } } catch (Exception e) { System.out.print("FINISHED"); sc.close(); } } }
[ "loibucket@users.noreply.github.com" ]
loibucket@users.noreply.github.com
e153de086b5ec769f5a62117e11d77be7d642829
4c4ea3d0cf4df2e0f646035dbb68b75ac415c44d
/src/com/company/MelodyNote.java
9d583f0a56493b347c13e767de95bcb1d72e866c
[]
no_license
KolyaginVlad/untitled
3672f6af67b277a53b87eaeeb5702f8b9e929a7e
999e722416e068e60295044d5a480539c2c97e62
refs/heads/main
2023-01-02T13:54:23.311629
2020-10-26T15:57:41
2020-10-26T15:57:41
307,381,457
0
0
null
null
null
null
UTF-8
Java
false
false
970
java
package com.company; import java.util.ArrayList; import java.util.Iterator; public class MelodyNote implements Iterable{ private ArrayList<Song> songs = new ArrayList<>(); private boolean isOpen; public MelodyNote(Song [] songs) { for (Song s:songs ) { this.songs.add(s); s.addInMelodyNote(this); } isOpen = false; } public MelodyNote() { isOpen = false; } public void addSong(Song song){ if (isOpen){ songs.add(song); song.addInMelodyNote(this); } } @Override public Iterator iterator() { isOpen= true; return new Iterator() { private int i = 0; @Override public boolean hasNext() { return i<songs.size(); } @Override public Object next() { return songs.get(i++); } }; } }
[ "50174448+KolyaginVlad@users.noreply.github.com" ]
50174448+KolyaginVlad@users.noreply.github.com
e45b9f704aca28345c98f294b36fb6ffee48b6ea
163e37c8899cd6689828980baa6d058a064dc98e
/src/JavaIO/FileReaderDemo.java
cd53cf13a958410c370fe55b1ca0ec3dcf61490b
[]
no_license
sh2268411762/Java
f4ffb76decac318d99334251615c5b26bee86b99
1d6e89338e02dddb67056b5353eb498876ef381c
refs/heads/master
2023-01-09T10:51:23.847574
2020-11-11T11:24:51
2020-11-11T11:24:51
257,934,424
0
0
null
null
null
null
UTF-8
Java
false
false
655
java
/** * */ package JavaIO; import java.io.FileReader; /** * @Description FileReader类读取文件 * @author 孙豪 * @version 版本 * @Date 2020年10月24日下午10:03:58 */ public class FileReaderDemo { public static void main(String[] args) { try { FileReader fileReader = new FileReader("Data.json"); char ch = ' '; System.out.println("读取文件中的字符:"); while(ch != '}') { ch = (char)fileReader.read(); System.out.print(ch); } System.out.println("==文件读取完成=="); fileReader.close(); } catch (Exception e) { // TODO: handle exception } } }
[ "2268411762@qq.com" ]
2268411762@qq.com
c671cf1a76a13c232cedd0d56602ad92389525ee
1ae3d829cb03afa5c1a19ea531e0a8fcfe24fce9
/src/corejava/Loops/For_Loop_Examples.java
2ae335e1e3470eddd877b7eaa1448f42451b3f7a
[]
no_license
SiripuramRajesh/NewRepository
39dfaa53f407ebd60fd06b5d0219f80ef39978e8
29499fe11d3f6896a8b6eb1f61ab395581fabe16
refs/heads/master
2023-03-02T06:47:17.354998
2021-02-15T08:26:46
2021-02-15T08:26:46
338,997,241
0
0
null
null
null
null
UTF-8
Java
false
false
946
java
package corejava.Loops; public class For_Loop_Examples { public static void main(String[] args) { /* * Example:--> Print number 1 to 10 */ for (int i = 1; i <=10; i++) { System.out.println(i); } //Print number 10 to 1 using decrement for (int i = 10; i >=1 ; i--) { System.out.println(i); } //How to reverse a string String toolname="webdriver"; char[] c=toolname.toCharArray(); for (int i = c.length-1; i >=0; i--) { char ch=toolname.charAt(i); System.out.print(ch); } System.out.println("\n"); //Array values to iterate using for-loop String tools[]= {"IDE","RC","WD","GRID"}; //Iterate for number of array length for (int i = 0; i < tools.length; i++) { System.out.println(tools[i]); } //Conduct sum between 1 to 100 int sum=0; for (int i = 1; i <= 100; i++) { sum=sum+i; } System.out.println("total value is => "+sum); } }
[ "siripuramrajeswararao@gmail.com" ]
siripuramrajeswararao@gmail.com
dc4fb8039b3b56308f2dad2c97de0300729e007d
7936cee9586ab8b3c0b15f166e0ac9fa787af0d2
/impl/src/test/java/performance/PatternSearchLinear.java
da006752d8ba420077ef328a6c90657986443d20
[]
no_license
theSelfSa/GraphAnomalyDetectionTool
ed1a5003d56661355173dc728f40b18382e5da64
9a5519b74df5f67a1b3f6a9a0738176f103fccf9
refs/heads/master
2021-06-08T00:00:13.337052
2016-08-23T21:03:52
2016-08-23T21:03:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,733
java
package performance; import GAD.algorithms.Algorithms; import GAD.generate.Generator; import GAD.graph.StringEdge; import GAD.graph.StringVertex; import com.opencsv.CSVWriter; import org.jgrapht.DirectedGraph; import org.jgrapht.generate.LinearGraphGenerator; import java.io.FileWriter; import java.io.IOException; import java.util.List; /** * Created by jkordas on 07/08/16. */ public class PatternSearchLinear { public static void main(String[] args) throws IOException, InterruptedException { new PatternSearchLinear().calculate(); } public void calculate() throws IOException { String csv = "performanceResults/patternSearchLinear_3.csv"; CSVWriter writer = new CSVWriter(new FileWriter(csv)); String [] header = " ,3,4,5,6,7,8,9,10,11,12,13,14,15".split(","); writer.writeNext(header); int randomVerticesInsertNumber = 10; for (int i = 3; i < 4; i++) { String result = "substructures number: " + i; for (int j = 3; j < 16; j++) { Generator g = new Generator(i, new LinearGraphGenerator<>(j), null, null, randomVerticesInsertNumber); long startTime = System.currentTimeMillis(); List<DirectedGraph<StringVertex, StringEdge>> bestSubstructures = Algorithms.getInstance().bestSubstructures(g.getResult(), 1); long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; result = result + "," + totalTime; System.out.println("res: " + result); } String [] record = result.split(","); writer.writeNext(record); } writer.close(); } }
[ "jan.kordas@comarch.com" ]
jan.kordas@comarch.com
09797779b26437a9e70b1e37a184f4f8a7c1aab0
facaa8d7391cbb6d7e369b4125db56b7ddbc879a
/axisDemo/src/com/exhui/axis/client/WebservcieDemoService.java
1c4d6b81856ad4b1e51901e54af8b6670ff30f51
[]
no_license
exhui/javaDemo
1784f4b829f774b0bc9b5a59bfcdb35bc451dd25
948af4905f8fa9dd65fb73b95ac89d9800496e1c
refs/heads/master
2016-09-16T13:41:53.067354
2014-03-16T12:00:09
2014-03-16T12:00:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
564
java
/** * WebservcieDemoService.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Nov 19, 2006 (02:31:34 GMT+00:00) WSDL2Java emitter. */ package com.exhui.axis.client; public interface WebservcieDemoService extends javax.xml.rpc.Service { public java.lang.String getwebservcieDemoAddress(); public com.exhui.axis.client.WebservcieDemo getwebservcieDemo() throws javax.xml.rpc.ServiceException; public com.exhui.axis.client.WebservcieDemo getwebservcieDemo(java.net.URL portAddress) throws javax.xml.rpc.ServiceException; }
[ "huixiaopi@outlook.com" ]
huixiaopi@outlook.com
c4d85560ef196e79e61a104435611abf2b759eed
315392d29821e02e6be8a3e21eb0e630804e2fc2
/src/rs/ac/bg/etf/pp1/ast/SingleExprLst.java
32f056ab7e3055b293bdd51dc2976a2376a982a8
[]
no_license
jovana193206/MicroJava-Compiler
36b470dab41c06efd65f32e6796567f12b90827e
fda45adeddf9423e758b2ee6ede42ed7ae58ef4f
refs/heads/master
2022-11-21T03:07:48.259270
2020-07-20T15:40:01
2020-07-20T15:40:01
281,146,749
0
0
null
null
null
null
UTF-8
Java
false
false
1,406
java
// generated with ast extension for cup // version 0.8 // 22/7/2019 15:47:31 package rs.ac.bg.etf.pp1.ast; public class SingleExprLst extends ExprList { private InitElem InitElem; public SingleExprLst (InitElem InitElem) { this.InitElem=InitElem; if(InitElem!=null) InitElem.setParent(this); } public InitElem getInitElem() { return InitElem; } public void setInitElem(InitElem InitElem) { this.InitElem=InitElem; } public void accept(Visitor visitor) { visitor.visit(this); } public void childrenAccept(Visitor visitor) { if(InitElem!=null) InitElem.accept(visitor); } public void traverseTopDown(Visitor visitor) { accept(visitor); if(InitElem!=null) InitElem.traverseTopDown(visitor); } public void traverseBottomUp(Visitor visitor) { if(InitElem!=null) InitElem.traverseBottomUp(visitor); accept(visitor); } public String toString(String tab) { StringBuffer buffer=new StringBuffer(); buffer.append(tab); buffer.append("SingleExprLst(\n"); if(InitElem!=null) buffer.append(InitElem.toString(" "+tab)); else buffer.append(tab+" null"); buffer.append("\n"); buffer.append(tab); buffer.append(") [SingleExprLst]"); return buffer.toString(); } }
[ "jovana.m.matic@gmail.com" ]
jovana.m.matic@gmail.com
a4fe2ea28f03ce98555e69bbe60d1b2dd13d56b1
b88b66a5b8551b70f7a97d97085a211374fb04fa
/app/src/main/java/com/jakeesveld/flashstudyguide/quiz/QuizActivity.java
d575374b2fd3e05e360e0620e2157b3f38b57ef0
[ "MIT" ]
permissive
JakeEsveldDevelopment/FlashStudyGuide
14a45c4d7d4590dcac73a53e6dc2556df96f0d84
4f655dc4e3c65a984d7e1f930c5b982b3117f1b2
refs/heads/master
2020-12-03T18:44:19.915319
2020-02-11T17:19:31
2020-02-11T17:19:31
231,435,023
0
0
null
null
null
null
UTF-8
Java
false
false
4,822
java
package com.jakeesveld.flashstudyguide.quiz; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.google.android.material.snackbar.Snackbar; import com.jakeesveld.flashstudyguide.R; import com.jakeesveld.flashstudyguide.model.Question; import com.jakeesveld.flashstudyguide.model.Quiz; public class QuizActivity extends AppCompatActivity implements QuizContract.view { public static final String QUIZ_KEY = "quiz"; private QuizContract.presenter presenter; private TextView textTitle, textQuestion, textCounter; private RadioGroup radioGroupBoolean, radioGroupMultiple; private RadioButton radioTrue, radioFalse, radioA, radioB, radioC, radioD; private Button buttonSubmit; private Quiz quiz; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz); textTitle = findViewById(R.id.text_title); textQuestion = findViewById(R.id.text_question); textCounter = findViewById(R.id.text_counter); radioGroupBoolean = findViewById(R.id.radio_group_boolean); radioGroupMultiple = findViewById(R.id.radio_group_multiple); radioTrue = findViewById(R.id.radio_true); radioFalse = findViewById(R.id.radio_false); radioA = findViewById(R.id.radio_a); radioB = findViewById(R.id.radio_b); radioC = findViewById(R.id.radio_c); radioD = findViewById(R.id.radio_d); buttonSubmit = findViewById(R.id.button_submit); if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(QUIZ_KEY)) { quiz = (Quiz) getIntent().getSerializableExtra(QUIZ_KEY); } presenter = new QuizPresenter(this, quiz); initializeView(); buttonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (checkValidInput()) { presenter.submitQuestion(getAnswer()); }else{ Snackbar snack = Snackbar.make(view, "Please select an answer", Snackbar.LENGTH_SHORT); snack.getView().setBackgroundColor(Color.WHITE); snack.show(); } } }); } private String getAnswer() { if (radioGroupBoolean.getVisibility() == View.VISIBLE) { return radioTrue.isChecked() ? "true" : "false"; } else { switch (radioGroupMultiple.getCheckedRadioButtonId()) { case R.id.radio_a: return radioA.getText().toString(); case R.id.radio_b: return radioB.getText().toString(); case R.id.radio_c: return radioC.getText().toString(); case R.id.radio_d: return radioD.getText().toString(); default: return null; } } } private boolean checkValidInput() { return radioTrue.isChecked() || radioFalse.isChecked() || radioA.isChecked() || radioB.isChecked() || radioC.isChecked() || radioD.isChecked(); } // initial set up of view with quiz data private void initializeView() { textTitle.setText(quiz.getName()); Question question = quiz.getQuestions().get(0); textQuestion.setText(question.getText()); updateAnswers(question.getType(), question.getAnswers()); } private void updateAnswers(int type, String[] answers) { switch (type) { case Question.TYPE_BOOLEAN: radioGroupBoolean.setVisibility(View.VISIBLE); radioGroupMultiple.setVisibility(View.INVISIBLE); break; case Question.TYPE_MULTIPLE: radioGroupMultiple.setVisibility(View.VISIBLE); radioGroupBoolean.setVisibility(View.INVISIBLE); radioA.setText(String.format("A: %s", answers[0])); radioB.setText(String.format("B: %s", answers[1])); radioC.setText(String.format("C: %s", answers[2])); radioD.setText(String.format("D: %s", answers[3])); } } @Override public void updateView(String question, int type, String[] answers, int counter) { textQuestion.setText(question); textCounter.setText(String.format("Question %s", String.valueOf(counter))); updateAnswers(type, answers); } }
[ "thejakeesveld@gmail.com" ]
thejakeesveld@gmail.com
7fb503e592cef4b48a4b88ce66e345e0fc74158a
e374ee3266feb0a601fbff4cc75a01c31cf8855b
/src/test/java/xsh/raindrops/distribution/zookeeper/MySessionIDPwdZK.java
299e26e225fe40cac4aa3741fb9e972255517f98
[]
no_license
zuiliushang/xsh-code
0e37a1e83264552fe72f6e6aa444be4b07e531e7
c88d8af5f4638acd08043cd00e2933f3e362867d
refs/heads/master
2021-01-23T11:08:09.280437
2018-06-12T02:11:45
2018-06-12T02:11:45
93,125,995
0
0
null
null
null
null
UTF-8
Java
false
false
1,125
java
package xsh.raindrops.distribution.zookeeper; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.Watcher.Event.KeeperState; public class MySessionIDPwdZK implements Watcher{ private static CountDownLatch latch = new CountDownLatch(1); @Override public void process(WatchedEvent paramWatchedEvent) { System.out.println("Receive watched event : " + paramWatchedEvent); if (KeeperState.SyncConnected==paramWatchedEvent.getState()) { latch.countDown(); } } public static void main(String[] args) throws Exception { ZooKeeper zooKeeper = new ZooKeeper(Constant.ZK_LINK_ADDR, 5000, new MySessionIDPwdZK()); long sessionId = zooKeeper.getSessionId(); byte[] passwd = zooKeeper.getSessionPasswd(); zooKeeper = new ZooKeeper(Constant.ZK_LINK_ADDR, 5000, new MySessionIDPwdZK(), 1l, "raindrops".getBytes()); Thread.sleep( Integer.MAX_VALUE ); zooKeeper = new ZooKeeper(Constant.ZK_LINK_ADDR, 5000, new MySessionIDPwdZK(), sessionId, passwd); } }
[ "383688501@qq.com" ]
383688501@qq.com
73923f71af9cbdac55715ecfdeab4c204586b529
a2f37622367478b5671d815562727da25874421b
/core-customize/hybris/bin/custom/braintree/braintreecscockpit/src/com/braintree/components/navigationarea/BraintreecscockpitNavigationAreaModel.java
40d976e9e849c6cf79306fe8815f2ac80039631e
[]
no_license
abhishek-kumar-singh1896/CommercePortal
3d3c7906547d8387411e0473362ffc6b90762aa8
d4f505bf52f99452dc8d28c29532b7a9944c2030
refs/heads/master
2023-02-10T12:57:43.077800
2020-01-10T14:26:24
2020-01-10T14:26:24
299,261,066
1
0
null
null
null
null
UTF-8
Java
false
false
1,124
java
/* * [y] hybris Platform * * Copyright (c) 2000-2013 hybris AG * All rights reserved. * * This software is the confidential and proprietary information of hybris * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with hybris. * * */ package com.braintree.components.navigationarea; import de.hybris.platform.cockpit.components.navigationarea.DefaultNavigationAreaModel; import de.hybris.platform.cockpit.session.impl.AbstractUINavigationArea; import com.braintree.session.impl.BraintreecscockpitNavigationArea; /** * Braintreecscockpit navigation area model. */ public class BraintreecscockpitNavigationAreaModel extends DefaultNavigationAreaModel { public BraintreecscockpitNavigationAreaModel() { super(); } public BraintreecscockpitNavigationAreaModel(final AbstractUINavigationArea area) { super(area); } @Override public BraintreecscockpitNavigationArea getNavigationArea() { return (BraintreecscockpitNavigationArea) super.getNavigationArea(); } }
[ "leireituarte@enterprisewide.com" ]
leireituarte@enterprisewide.com
84d9e7536c1f25c9090e5efdc3d1af5f46c00f64
6191bc3a0466ab22ca988a2b01745b18ed82d37c
/commons/estructuras/class_blockchain.java
bb41e26e62ecc30ffb01aaa36d987f9da103f099
[]
no_license
karl1os/bluechain
d33d23ce4c5d2acd4001af12fdcf2b6e5eb91460
79a2cdebf9b2c178c33b76b327ed774cf8bd045a
refs/heads/master
2020-08-02T07:21:43.308529
2020-05-21T15:33:50
2020-05-21T15:33:50
211,274,489
0
0
null
null
null
null
UTF-8
Java
false
false
2,411
java
package com.aprendeblockchain.miblockchainenjava.commons.estructuras; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /* * La cadena de bloques es esencialmente una lista de bloques enlazados ya que cada bloque tiene el identificador del bloque anterior. * */ public class CadenaDeBloques { // Lista de bloques en la cadena ordenados por altura private List<Bloque> bloques = new ArrayList<Bloque>(); // Saldos actuales de las cuentas private RegistroSaldos saldos = new RegistroSaldos(); public CadenaDeBloques() { } public CadenaDeBloques(CadenaDeBloques cadena) throws Exception { this.setBloques(cadena.getBloques()); } public List<Bloque> getBloques() { return bloques; } public void setBloques(List<Bloque> bloques) throws Exception { this.bloques = new ArrayList<Bloque>(); for (Bloque bloque : bloques) { this.añadirBloque(bloque); } } public boolean estaVacia() { return this.bloques == null || this.bloques.isEmpty(); } public int getNumeroBloques() { return (estaVacia() ? 0 : this.bloques.size()); } public RegistroSaldos getSaldos() { return this.saldos; } /** * Obtener el ultimo bloque en la cadena * * @return Ultimo bloque de la cadena */ public Bloque getUltimoBloque() { if (estaVacia()) { return null; } return this.bloques.get(this.bloques.size() - 1); } /** * Añadir un bloque a la cadena * @param bloque a ser añadido * @throws Exception */ public void añadirBloque(Bloque bloque) throws Exception { // iteramos y procesamos las transacciones. Si todo es correcto lo añadimos a la cadena Iterator<Transaccion> itr = bloque.getTransacciones().iterator(); while (itr.hasNext()) { Transaccion transaccion = (Transaccion) itr.next(); // actualizar saldos saldos.liquidarTransaccion(transaccion); } this.bloques.add(bloque); System.out.println(saldos.toString() + "\n"); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CadenaDeBloques cadena = (CadenaDeBloques) o; if (bloques.size() != cadena.getBloques().size()) return false; for (int i = 0; i < bloques.size(); i++) { if (bloques.get(i) != cadena.getBloques().get(i)) return false; } return true; } @Override public String toString() { return bloques.toString(); } }
[ "noreply@github.com" ]
karl1os.noreply@github.com
ca7c558b909396f2cc7f58fb942b9a5e95f720f9
3e42a29df9672a1b120182ef43a54500ef4c28b6
/app/src/main/java/com/example/user/androidexplorer/ListFragment.java
e7d3ca970485dd694e1185a43cee88d862eacefe
[]
no_license
msmtmsmt123/AndroidExplorer-1
aeb10a59e5a63c377d29e05a0158956a33e5e7f7
9b10bdaf80fff907a3e89f2b34a18581a926086e
refs/heads/master
2021-06-04T18:43:28.227331
2016-09-04T17:36:58
2016-09-04T17:37:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,867
java
package com.example.user.androidexplorer; import android.app.Fragment; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v4.util.LruCache; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.ListView; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; public class ListFragment extends Fragment { private static final boolean HIDEHIDDENFILES = false; private static final boolean SHOWHIDDENFILES = true; private ArrayList<File> fileList = new ArrayList<>(); private ArrayList<File> dirList = new ArrayList<>(); private ArrayList<String> fileDirLlist = new ArrayList<>(); private ArrayList<String> fileSizeList = new ArrayList<>(); private ArrayList<Integer> iconFileDirLlist = new ArrayList<>(); private ArrayList<Date> fileModDate = new ArrayList<>(); private ArrayList<Bitmap> thumbs = new ArrayList<>(); private boolean showHiddenObjects; private MyFileList myFiles; private MyFileList myDirs; private Integer sortStyle; private Boolean folderFirst; private Integer listViewType; private CustomAdapter myAdapter; private LruCache<String, Bitmap> mMemoryCache; private ListView lv; private GridView gv; private LinearLayout frame; private Integer imgDisplayType; private File currDir; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_list, container, false); showHiddenObjects = false; // set default hidden object setting sortStyle = 1; // set default sort setting folderFirst = true; // set folder, file arrangement setting listViewType = 1; // set display type default setting imgDisplayType = 1; // Bitmap cache // Get max available VM memory, exceeding this amount will throw an // OutOfMemory exception. Stored in kilobytes as LruCache takes an // int in its constructor. final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache. final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size will be measured in kilobytes rather than // number of items. return bitmap.getByteCount() / 1024; } }; frame = (LinearLayout) view.findViewById(R.id.Frame_Container); setViewType(); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { String path = bundle.getString("currentPath"); // get current path showHiddenObjects = bundle.getBoolean("hideObjects"); // get current hidden object setting populateScreen(new File(path)); currDir = new File(path); } } public void showHiddenFiles(boolean ishidden) { } public void goUpFolder() { File upFolder = currDir.getParentFile(); populateScreen(upFolder); } public ArrayList<File> getDirList() { return dirList; } public Integer getFileIcon(int i) { return iconFileDirLlist.get(i); } public static boolean isInteger(String s) { return isInteger(s,10); } public static boolean isInteger(String s, int radix) { if(s.isEmpty()) return false; for(int i = 0; i < s.length(); i++) { if(i == 0 && s.charAt(i) == '-') { if(s.length() == 1) return false; else continue; } if(Character.digit(s.charAt(i),radix) < 0) return false; } return true; } public CustomAdapter getMyAdapter() { return myAdapter; } public File getCurrDir() { return currDir; } public void populateScreen(File file) { ((MainActivity) getActivity()).setPathbar(file.toString()); currDir = file; getfile(file); dirList.addAll(fileList); fileDirLlist.clear(); iconFileDirLlist.clear(); fileSizeList.clear(); thumbs.clear(); switch (sortStyle) { case 1: myFiles.sortByFileName(myFiles.FILE_NAME_ASC); myDirs.sortByFileName(myFiles.FILE_NAME_ASC); break; case 2: myFiles.sortByFileName(myFiles.FILE_NAME_DESC); myDirs.sortByFileName(myFiles.FILE_NAME_DESC); break; case 3: myFiles.sortByFileSize(myFiles.FILE_NAME_ASC); myDirs.sortByFileSize(myFiles.FILE_NAME_ASC); break; case 4: myFiles.sortByFileSize(myFiles.FILE_NAME_DESC); myDirs.sortByFileSize(myFiles.FILE_NAME_DESC); break; case 5: myFiles.sortByFileDate(myFiles.FILE_NAME_ASC); myDirs.sortByFileDate(myFiles.FILE_NAME_ASC); break; case 6: myFiles.sortByFileDate(myFiles.FILE_NAME_DESC); myDirs.sortByFileDate(myFiles.FILE_NAME_DESC); break; } if (folderFirst) { for (Integer i = 0; i <= myDirs.size(); i++) { fileDirLlist.add(myDirs.getFile(i).getName()); iconFileDirLlist.add(myDirs.getIcon(i)); fileSizeList.add(myDirs.getSize(i)); fileModDate.add(myDirs.getDate(i)); } for (Integer i = 0; i <= myFiles.size(); i++) { fileDirLlist.add(myFiles.getFile(i).getName()); iconFileDirLlist.add(myFiles.getIcon(i)); fileSizeList.add(myFiles.getSize(i)); fileModDate.add(myFiles.getDate(i)); } } else { for (Integer i = 0; i <= myFiles.size(); i++) { fileDirLlist.add(myFiles.getFile(i).getName()); iconFileDirLlist.add(myFiles.getIcon(i)); fileSizeList.add(myFiles.getSize(i)); fileModDate.add(myFiles.getDate(i)); } for (Integer i = 0; i <= myDirs.size(); i++) { fileDirLlist.add(myDirs.getFile(i).getName()); iconFileDirLlist.add(myDirs.getIcon(i)); fileSizeList.add(myDirs.getSize(i)); fileModDate.add(myDirs.getDate(i)); } } if (myAdapter != null) { myAdapter.refreshEvents(listViewType, mMemoryCache, getActivity(),getActivity().getApplicationContext(),this, fileDirLlist, iconFileDirLlist, fileModDate, fileSizeList, file.toString(), imgDisplayType); /*updateFab(0); selectionMode=false;*/ } else { myAdapter = new CustomAdapter(listViewType, mMemoryCache, getActivity(),getActivity().getApplicationContext(), this, fileDirLlist, iconFileDirLlist, fileModDate, fileSizeList, file.toString(), imgDisplayType); if (listViewType.equals(1)) { lv.setAdapter(myAdapter); } else { gv.setAdapter(myAdapter); } } } public void getfile(File dir) { dirList.clear(); fileList.clear(); File listFile[] = dir.listFiles(); File currFile; Arrays.sort(listFile); // Sorts list alphabetically by default if (listFile != null) { if (listFile.length > 0) { for (int i = 0; i < listFile.length; i++) { currFile = listFile[i]; if (!showHiddenObjects) { if (currFile.isFile()) { if (!currFile.isHidden()) fileList.add(currFile); } else { if (!currFile.isHidden()) dirList.add(currFile); } } else { if (currFile.isFile()) { fileList.add(currFile); } else { dirList.add(currFile); } } } } } // return fileList; myDirs = new MyFileList(getActivity(), dirList); myFiles = new MyFileList(getActivity(), fileList); } public void setViewType() { //ViewGroup parent = (ViewGroup) currAttachedViewType.getParent(); frame.removeAllViews(); View currAttachedViewType; if (listViewType.equals(1)) { currAttachedViewType = getActivity().getLayoutInflater().inflate(R.layout.content_main_detail, null); frame.addView(currAttachedViewType); lv = (ListView) frame.findViewById(R.id.mainListView); } else { currAttachedViewType = getActivity().getLayoutInflater().inflate(R.layout.content_main_grid, null); frame.addView(currAttachedViewType); gv = (GridView) frame.findViewById(R.id.mainGridView); } } }
[ "ninomarlougonzales@gmail.com" ]
ninomarlougonzales@gmail.com
0351358467bc50de53d22b571feb5de138dfd9de
949e30a3f745f06b3f53d9d024784d166f60675b
/app/src/main/java/com/jennifertestu/calculmoyenne/model/TypeDeNote.java
3b51687f04f0b119d85e8851152ee40fae6b4b29
[]
no_license
JenniferTestu/CalculMoyenne
dfee04b1cb262a1ad48889664f616897d19ddb42
4780b22e53aec94a2bd8c0b6bf8874dffab0a982
refs/heads/master
2021-05-24T12:15:34.228600
2020-04-20T14:57:52
2020-04-20T14:57:52
253,555,976
0
0
null
null
null
null
UTF-8
Java
false
false
124
java
package com.jennifertestu.calculmoyenne.model; public enum TypeDeNote { Ecrit, Oral, Pratique, Devoir; }
[ "tes.jenni@gmail.com" ]
tes.jenni@gmail.com
b8104a7600930c23603b8233b16550ef84a8f1e0
ea98f0adaf2d3a44e3a7958ae06b097221a166fd
/src/main/java/com/guinardsolutions/mp/Server.java
5ab8fb558cd9060cded669a3de2543cc52e6c14c
[]
no_license
guinardpaul/MP-SOAP-WS
5ff04706de4ff4b40e5fc5c0579e415a9e727f08
7490a03899d11fd12ae6ae7170c0a00ef0fab210
refs/heads/master
2020-03-13T15:00:06.088798
2018-04-26T14:46:53
2018-04-26T14:46:53
131,169,007
0
0
null
null
null
null
UTF-8
Java
false
false
305
java
package com.guinardsolutions.mp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Server { public static void main(String[] args) { SpringApplication.run(Server.class, args); } }
[ "guinardpaul@gmail.com" ]
guinardpaul@gmail.com
59186064309850068561f58813091cf5fff40683
c4a0f3c1e802ac7fccbfd8512dded107fac7ab35
/test_company/com/bruce/http/Md5Util.java
b21144361158626097713f5650afc5ca1a26b7ca
[]
no_license
rex731083168/companyCode
174dbca79c688b9c62d8b661839e6369e96ab347
dbfed7aa55eb81461140d0ff5044cf38c8fdea72
refs/heads/master
2020-06-06T06:36:46.086292
2017-10-16T09:43:17
2017-10-16T09:43:17
192,666,835
0
0
null
2019-06-19T05:49:35
2019-06-19T05:49:34
null
UTF-8
Java
false
false
1,659
java
package com.bruce.http; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Md5Util { /** * MD5 ���� */ public static String getMD5Str(String str , String coding) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes(coding)); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } /** * MD5 ���� */ public static String getMD5Str(Object...objects){ StringBuilder stringBuilder=new StringBuilder(); for (Object object : objects) { stringBuilder.append(object.toString()); } return getMD5Str(stringBuilder.toString()); } }
[ "bruce@DESKTOP-AAPANO5" ]
bruce@DESKTOP-AAPANO5
968951719520a6ecce7fe97ae2991180838d447e
604156082527a51211771e163259c17bdb2bdbbc
/java/ql/test/library-tests/dataflow/callback-dispatch/A.java
6224a2e3d953f233041d5fbb247669e087f2b24d
[ "MIT" ]
permissive
stifflerstiff0/codeql
2c3c7864e2dad76044a6790768c887c60c77b555
2539e3247af2d571b20b82b29af33ffa579d0a52
refs/heads/main
2023-07-31T11:01:14.827279
2021-10-07T18:18:38
2021-10-07T18:18:38
414,876,946
0
0
MIT
2021-10-08T06:47:41
2021-10-08T06:47:34
null
UTF-8
Java
false
false
4,411
java
package my.callback.qltest; import java.util.*; public class A { public interface Consumer1 { void eat(Object o); } public interface Consumer2 { void eat(Object o); } public interface Consumer3<T> { void eat(T o); } static void applyConsumer1(Object x, Consumer1 con) { // summary: // con.eat(x); } static void applyConsumer2(Object x, Consumer2 con) { // summary: // con.eat(x); } static <T> void applyConsumer3(T x, Consumer3<T> con) { // summary: // con.eat(x); } static <T> T applyConsumer3_ret_postup(Consumer3<T> con) { // summary: // x = new T(); // con.eat(x); // return x; return null; } static <T> void forEach(T[] xs, Consumer3<T> con) { // summary: // x = xs[..]; // con.eat(x); } public interface Producer1<T> { T make(); } static <T> T applyProducer1(Producer1<T> prod) { // summary: // return prod.make(); return null; } static <T> T produceConsume(Producer1<T> prod, Consumer3<T> con) { // summary: // x = prod.make(); // con.eat(x); // return x; return null; } public interface Converter1<T1,T2> { T2 conv(T1 x); } static <T1,T2> T2 applyConverter1(T1 x, Converter1<T1,T2> con) { // summary: // return con.conv(x); return null; } public interface Producer1Consumer3<E> extends Producer1<E[]>, Consumer3<E[]> { } static Object source(int i) { return null; } static void sink(Object o) { } void foo(boolean b1, boolean b2) { applyConsumer1(source(1), p -> { sink(p); // $ flow=1 }); Object handler; if (b1) { handler = (Consumer1)(p -> { sink(p); }); // $ flow=2 } else { handler = (Consumer2)(p -> { sink(p); }); // $ flow=3 } if (b2) { applyConsumer1(source(2), (Consumer1)handler); } else { applyConsumer2(source(3), (Consumer2)handler); } applyConsumer1(source(4), new Consumer1() { @Override public void eat(Object o) { sink(o); // $ flow=4 } }); applyConsumer1(source(5), A::sink); // $ flow=5 Consumer2 c = new MyConsumer2(); applyConsumer2(source(6), c); } static class MyConsumer2 implements Consumer2 { @Override public void eat(Object o) { sink(o); // $ MISSING: flow=6 } } void foo2() { Consumer3<Integer> c = i -> sink(i); // $ flow=7 applyConsumer3((Integer)source(7), c); sink(applyProducer1(() -> (Integer)source(8))); // $ flow=8 sink(applyConverter1((Integer)source(9), i -> i)); // $ flow=9 sink(applyConverter1((Integer)source(10), i -> new int[]{i})[0]); // $ flow=10 Producer1Consumer3<Integer> pc = new Producer1Consumer3<Integer>() { @Override public Integer[] make() { return new Integer[] { (Integer)source(11) }; } @Override public void eat(Integer[] xs) { sink(xs[0]); // $ flow=12 } }; applyConsumer3(new Integer[] { (Integer)source(12) }, pc); sink(applyProducer1(pc)[0]); // $ flow=11 Integer res = applyProducer1(new Producer1<Integer>() { private Integer ii = (Integer)source(13); @Override public Integer make() { return this.ii; } }); sink(res); // $ flow=13 ArrayList<Object> list = new ArrayList<>(); applyConsumer3(list, l -> l.add(source(14))); sink(list.get(0)); // $ flow=14 Consumer3<ArrayList<Object>> tainter = l -> l.add(source(15)); sink(applyConsumer3_ret_postup(tainter).get(0)); // $ flow=15 forEach(new Object[] {source(16)}, x -> sink(x)); // $ flow=16 // Spurious flow from 17 is reasonable as it would likely // also occur if the lambda body was inlined in a for loop. // It occurs from the combination of being able to observe // the side-effect of the callback on the other argument and // being able to chain summaries that update/read arguments, // e.g. fluent apis. // Spurious flow from 18 is due to not matching call targets // in a return-from-call-to-enter-call flow sequence. forEach(new Object[2][], xs -> { sink(xs[0]); xs[0] = source(17); }); // $ SPURIOUS: flow=17 flow=18 Object[][] xss = new Object[][] { { null } }; forEach(xss, x -> {x[0] = source(18);}); sink(xss[0][0]); // $ flow=18 Object res2 = produceConsume(() -> source(19), A::sink); // $ flow=19 sink(res2); // $ flow=19 } }
[ "aschackmull@github.com" ]
aschackmull@github.com
932ffe539e62de66b987769ceb92ebb016add17c
180e78725121de49801e34de358c32cf7148b0a2
/dataset/protocol1/yauaa/learning/6028/TestCaching.java
f839df103e79a3d486161a6f11ae4e2c495971b6
[]
no_license
ASSERT-KTH/synthetic-checkstyle-error-dataset
40e8d1e0a7ebe7f7711def96a390891a6922f7bd
40c057e1669584bfc6fecf789b5b2854660222f3
refs/heads/master
2023-03-18T12:50:55.410343
2019-01-25T09:54:39
2019-01-25T09:54:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,824
java
/* * Yet Another UserAgent Analyzer * Copyright (C) 2013-2018 Niels Basjes * * 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 nl.basjes.parse.useragent; import org.apache.commons.collections4.map.LRUMap; import org.apache.commons.lang3.reflect.FieldUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestCaching { @Test public void testSettingCaching() throws IllegalAccessException { UserAgentAnalyzer uaa = UserAgentAnalyzer .newBuilder() .withCache(42) .hideMatcherLoadStats() .withField("AgentUuid") .build(); assertEquals(42, uaa.getCacheSize()); assertEquals(42, getAllocatedCacheSize(uaa)); uaa.disableCaching(); assertEquals(0, uaa.getCacheSize()); assertEquals(0, getAllocatedCacheSize(uaa)); uaa.setCacheSize(42); assertEquals(42, uaa.getCacheSize()); assertEquals(42, getAllocatedCacheSize(uaa)); } @Test public void testSettingNoCaching() throws IllegalAccessException { UserAgentAnalyzer uaa = UserAgentAnalyzer .newBuilder() .withoutCache() .hideMatcherLoadStats() .withField("AgentUuid") .build(); assertEquals(0, uaa.getCacheSize()); assertEquals(0, getAllocatedCacheSize(uaa)); uaa.setCacheSize(42); assertEquals(42, uaa.getCacheSize()); assertEquals(42, getAllocatedCacheSize(uaa)); uaa.disableCaching(); assertEquals(0, uaa.getCacheSize()); assertEquals(0, getAllocatedCacheSize(uaa)); } @Test public void testCache() throws IllegalAccessException { String uuid = "11111111-2222-3333-4444-555555555555"; String fieldName = "AgentUuid"; UserAgentAnalyzer uaa = UserAgentAnalyzer .newBuilder() .withCache(1) .hideMatcherLoadStats() .withField(fieldName) .build(); UserAgent agent; assertEquals(1, uaa.getCacheSize()); assertEquals(1, getAllocatedCacheSize(uaa)); agent = uaa.parse(uuid); assertEquals(uuid, agent.get(fieldName).getValue()); assertEquals(agent, getCache(uaa).get(uuid)); agent = uaa.parse(uuid); assertEquals(uuid, agent.get(fieldName).getValue()); assertEquals(agent, getCache(uaa).get(uuid)); uaa.disableCaching(); assertEquals(0, uaa.getCacheSize()); assertEquals(0, getAllocatedCacheSize(uaa)); agent = uaa.parse(uuid); assertEquals(uuid, agent.get(fieldName).getValue()); assertEquals(null, getCache(uaa)); } private LRUMap<?, ?> getCache(UserAgentAnalyzer uaa) throws IllegalAccessException { LRUMap<?, ?> actualCache = null; Object rawParseCache = FieldUtils.readField(uaa, "parseCache", true); if (rawParseCache instanceof LRUMap<?, ?>) { actualCache = (LRUMap) rawParseCache; } return actualCache; } private int getAllocatedCacheSize(UserAgentAnalyzer uaa) throws IllegalAccessException { LRUMap<?, ?> cache = getCache(uaa); if (cache == null) { return 0; } return cache.maxSize(); } }
[ "bloriot97@gmail.com" ]
bloriot97@gmail.com
1da54abf637dcf1630111e093eeb37143098bb93
39a01f0cb0ee73729e3152da13a0b66d3da0fd83
/src/main/java/cc/blisscorp/bliss/payment/web/ReportsServerDaemon.java
b64a73c862828b2ee7c7ed7afe3f6dc4db99076a
[]
no_license
jolker/WebPayment
7654a3e09e7f5ce2e56a04ea3a52791b34c380c8
926b9da955903632af616ed69c8939b4df63d1a2
refs/heads/master
2021-09-03T15:15:25.505215
2018-01-10T02:58:56
2018-01-10T02:58:56
116,897,903
0
0
null
null
null
null
UTF-8
Java
false
false
1,019
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cc.blisscorp.bliss.payment.web; import com.bliss.framework.common.LogUtil; import java.io.File; import org.apache.log4j.Logger; /** * * @author anhlnt */ public class ReportsServerDaemon { private static final Logger logger = LogUtil.getLogger(ReportsServerDaemon.class); public static void main(String[] agrs) { JettyServer webserver = new JettyServer(); String pidFile = System.getProperty("pidfile"); try { logger.info("report web server is starting..."); if (pidFile != null) { new File(pidFile).deleteOnExit(); } logger.info("reports web server started"); webserver.start(); } catch (Exception e) { logger.error(LogUtil.stackTrace(e)); System.exit(3); } } }
[ "tuananh.ln155@gmail.com" ]
tuananh.ln155@gmail.com
ea699dc8b917ddf7e49ba255c7678afe9f289b5c
4e1724027a4858497305958549df4d9f77343dc4
/app/src/main/java/com/bawei/wangjiangwei/base/BaseFragment.java
2ccd74a6e9f2532106b9f77c225e5afcedfbf2e9
[]
no_license
Wang-Sir001/WangJiangWei2020218
5cda0b1645788fda66eaa82e9087bfe3ac9678bd
5f04d12ca4afbc9242d49747b5e1559720d0fb2e
refs/heads/master
2021-01-08T00:02:49.886306
2020-02-20T10:37:39
2020-02-20T10:37:39
241,857,645
0
0
null
null
null
null
UTF-8
Java
false
false
1,621
java
package com.bawei.wangjiangwei.base; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.bawei.wangjiangwei.base.mvp.BasePresenter; import com.bawei.wangjiangwei.base.mvp.IBaseView; import butterknife.ButterKnife; import butterknife.Unbinder; public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements IBaseView { public P presenter; private Unbinder bind; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View inflate = inflater.inflate(LayoutId(), container, false); presenter = initPresenter(); if (presenter != null) { presenter.attach(this); } bind = ButterKnife.bind(this, inflate); initView(inflate); return inflate; } protected abstract void initView(View inflate); protected abstract P initPresenter(); protected abstract int LayoutId(); @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(); } protected abstract void initData(); @Override public void onDestroyView() { super.onDestroyView(); if (presenter != null) { presenter.detach(); } if (presenter != null) { bind.unbind(); } } }
[ "wangjiangweis@qq.com" ]
wangjiangweis@qq.com
31e4b9687522e1875300bc60e742f3789558145e
fa8457e60770695210e8e3f4759e5deceb49b24f
/resource/src/root/main/Main.java
72613a74db4c0ed9f3a506bf991beb3a32d4d208
[]
no_license
tuwq/java-tetris
f688708efb3fd45f47e001469e795f9f0fc15cc9
3c9420811c760c3024684262ae89fe3d03152ed8
refs/heads/master
2020-04-09T21:32:29.659067
2019-11-27T13:28:38
2019-11-27T13:28:38
160,605,172
1
0
null
null
null
null
UTF-8
Java
false
false
158
java
package root.main; import root.listener.GameListener; public class Main { public static void main(String[] args) { new GameListener(); } }
[ "aheadqiang@126.com" ]
aheadqiang@126.com
2a2708c3369f6ba0a92ba823fc8be083de9975f0
a7d35270c148be0f633f9d4f0530c163475a59b5
/DummySSLSocketFactory.java
1cc59a0403753e36c0afb164d0fe2d384b72cbaf
[]
no_license
YaroslavNudnenko/DummySSLSocketFactory.java
a99b225b8df5fcb32cd0870fbfefc19ae0df0ff0
7d6569b210438deae9ccbfe37ee0d5612958e066
refs/heads/master
2020-04-29T23:09:36.961468
2019-03-19T08:58:58
2019-03-19T08:58:58
176,468,484
0
0
null
null
null
null
UTF-8
Java
false
false
2,415
java
package imapClient; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.security.SecureRandom; import javax.net.SocketFactory; import javax.net.ssl.*; /** * This class create SSLSocketFactory based on our DummyTrustManager. */ public class DummySSLSocketFactory extends SSLSocketFactory { private SSLSocketFactory factory; public DummySSLSocketFactory() { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{new DummyTrustManager()}, new SecureRandom()); factory = (SSLSocketFactory)sslcontext.getSocketFactory(); } catch(Exception ex) { addExToLogs(ex); } } private void addExToLogs(Exception ex) { Form.saveExceptions(ex, "imapClient.DummySSLSocketFactory");//ex.printStackTrace(); String exception = ex.getClass().getName(); String exMsg = ex.getMessage(); if (exMsg != null) exception += ": " + exMsg; else exception += " at " + ex.getStackTrace()[0].toString(); Throwable cause = ex.getCause(); if (cause != null) exception = exception + " Caused by: " + cause.getMessage(); Form.addLogs("ERROR: "+exception+"\r\n", -1); } public static SocketFactory getDefault() { return new DummySSLSocketFactory(); } public Socket createSocket() throws IOException { return factory.createSocket(); } public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException { return factory.createSocket(socket, s, i, flag); } public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, int j) throws IOException { return factory.createSocket(inaddr, i, inaddr1, j); } public Socket createSocket(InetAddress inaddr, int i) throws IOException { return factory.createSocket(inaddr, i); } public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException { return factory.createSocket(s, i, inaddr, j); } public Socket createSocket(String s, int i) throws IOException { return factory.createSocket(s, i); } public String[] getDefaultCipherSuites() { return factory.getDefaultCipherSuites(); } public String[] getSupportedCipherSuites() { return factory.getSupportedCipherSuites(); } }
[ "noreply@github.com" ]
YaroslavNudnenko.noreply@github.com
68ad5d5c9e99dd641d4cd2393cdbacd8294528a2
af9e34de814e72a68179bc40573b0c6c02b8a9ab
/src/org/it4y/codel/Packet.java
1c80c16cd6dedb5a7c6cdc005ebf1b3d54f23c1b
[]
no_license
lucwillems/JCODEL
372e39c172bceebca0374b44df5b8f1d89a344e4
eab504b835c9c72c728c8ccfbe6823112a71b8fd
refs/heads/master
2016-09-06T08:26:42.380626
2014-11-08T11:13:16
2014-11-08T11:13:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,540
java
/* * Copyright 2014 Luc Willems (T.M.M.) * * 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. * * Codel - The Controlled-Delay Active Queue Management algorithm * Copyright (C) 2011-2012 Kathleen Nichols <nichols@pollere.com> * Copyright (C) 2011-2012 Van Jacobson <van@pollere.net> * * Implemented on linux by : * Copyright (C) 2012 Michael D. Taht <dave.taht@bufferbloat.net> * Copyright (C) 2012 Eric Dumazet <edumazet@google.com> */ package org.it4y.codel; /** * Created by luc on 8/22/14. */ class Packet implements Queueable<Packet> { private Packet nextPacket; public long queueTime; public int size; public Packet(int size) { nextPacket =null; queueTime=System.currentTimeMillis(); this.size=size; } public long getDeltaTime() { return System.currentTimeMillis()-queueTime; } public Packet next() { return nextPacket; } @Override public void next(Packet x) { nextPacket =x; } public void drop() { } }
[ "luc.willems@it4y.eu" ]
luc.willems@it4y.eu
3e370e21c906aa82ac151d19d1e89c20f8dc6019
b6b991da67a70c02dfb3b1f167e43053a9e60152
/zombielink/src/test/java/com/lonepulse/zombielink/model/User.java
a1ce1409febc772aa8e70a2857e9c85bdea0faf9
[ "Apache-2.0" ]
permissive
sahan/ZombieLink
9cb81261b799a3e2e3e878fc70339bcba0b1177f
a9971add56d4f6919a4a5e84c78e9220011d8982
refs/heads/master
2023-03-20T04:12:41.934608
2014-02-17T18:50:30
2014-02-17T18:50:30
7,470,836
1
1
null
2013-07-28T08:18:59
2013-01-06T18:07:45
Java
UTF-8
Java
false
false
2,805
java
package com.lonepulse.zombielink.model; /* * #%L * ZombieLink * %% * Copyright (C) 2013 - 2014 Lonepulse * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.io.Serializable; /** * <p>A mock entity which is used to test the deserializers and the response processor chain.</p> * * @version 1.1.0 * <br><br> * @since 1.3.0 * <br><br> * @category test * <br><br> * @author <a href="http://sahan.me">Lahiru Sahan Jayasinghe</a> */ public class User implements Serializable { private static final long serialVersionUID = -5629006892332071122L; private long id; private String firstName; private String lastName; private int age; private boolean immortal; public User() {} public User(long id, String firstName, String lastName, int age, boolean immortal) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.age = age; this.immortal = immortal; } public long getId() { return id; } public void setId(long 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; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isImmortal() { return immortal; } public void setImmortal(boolean immortal) { this.immortal = immortal; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ (id >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id != other.id) return false; return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("User [id=").append(id) .append(", firstName=").append(firstName) .append(", lastName=").append(lastName) .append(", age=").append(age) .append(", immortal=").append(immortal).append("]"); return builder.toString(); } }
[ "lahiru@lonepulse.com" ]
lahiru@lonepulse.com
fa870d3b236585efab963093094ba31c0a8ea4e1
8be2ef0f4d7729d75ef6fa170a39c2925447b214
/src/org/zeroxlab/apps/coscup2010/TracksActivity.java
02c905e14a0e5784b5070dc0bb4d6e8d41c074f2
[ "Apache-2.0" ]
permissive
kanru/Coscup2010
1108e4a12896a95df5f86fc1d4fb5d1b49e48565
73ed83f8f34fb6d83ea1fffd5ede26411c8f7993
refs/heads/master
2019-01-21T23:08:03.584773
2010-08-14T05:11:24
2010-08-14T05:11:24
835,939
2
0
null
null
null
null
UTF-8
Java
false
false
3,264
java
package org.zeroxlab.apps.coscup2010; import org.zeroxlab.apps.coscup2010.Agenda.Tracks; import android.app.ListActivity; import android.content.Intent; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.SimpleCursorAdapter; import android.widget.SimpleCursorAdapter.ViewBinder; public class TracksActivity extends ListActivity implements ViewBinder { private SimpleCursorAdapter mAdapter; @Override public void onCreate(Bundle savedInstance) { super.onCreate(savedInstance); setContentView(R.layout.tracks); TextView title = (TextView)findViewById(R.id.action_bar_title); title.setText(R.string.title_tracks); final ImageButton btn_home = (ImageButton) findViewById(R.id.btn_home); btn_home.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setClass(TracksActivity.this, LauncherActivity.class); startActivity(intent); } }); final ImageButton btn_search = (ImageButton) findViewById(R.id.btn_search); btn_search.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TracksActivity.this.onSearchRequested(); } }); String[] columns = new String[] { Tracks._ID, Tracks.TITLE }; Cursor cursor = getContentResolver().query(Tracks.CONTENT_URI, columns, null, null, null); startManagingCursor(cursor); int[] to = new int[] { R.id.track_icon, R.id.track_title }; mAdapter = new SimpleCursorAdapter(this, R.layout.track_view, cursor, columns, to); mAdapter.setViewBinder(this); setListAdapter(mAdapter); } public boolean setViewValue(View view, Cursor cursor, int columnIndex) { switch (view.getId()) { case R.id.track_icon: ImageView img = (ImageView) view; Resources res = getResources(); TypedArray icons = res.obtainTypedArray(R.array.track_icons); Drawable drawable = icons.getDrawable(cursor.getInt(columnIndex)); img.setImageDrawable(drawable); return true; default: return false; } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Cursor c = (Cursor)mAdapter.getItem(position); long _id = c.getLong(c.getColumnIndex(Tracks._ID)); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Tracks.CONTENT_URI + "/" + _id), this, TrackActivity.class); startActivity(intent); } }
[ "kanru@0xlab.org" ]
kanru@0xlab.org
448ce2bf2599665e715589e8804c30aeb03d08cf
5e224ff6d555ee74e0fda6dfa9a645fb7de60989
/database/src/main/java/adila/db/q6t10in4g_q6t10in4g.java
a048d28a5bfe998c1205a8dff473f0fd8926ad38
[ "MIT" ]
permissive
karim/adila
8b0b6ba56d83f3f29f6354a2964377e6197761c4
00f262f6d5352b9d535ae54a2023e4a807449faa
refs/heads/master
2021-01-18T22:52:51.508129
2016-11-13T13:08:04
2016-11-13T13:08:04
45,054,909
3
1
null
null
null
null
UTF-8
Java
false
false
227
java
// This file is automatically generated. package adila.db; /* * Auchan Q6T10IN4G * * DEVICE: Q6T10IN4G * MODEL: Q6T10IN4G */ final class q6t10in4g_q6t10in4g { public static final String DATA = "Auchan|Q6T10IN4G|"; }
[ "keldeeb@gmail.com" ]
keldeeb@gmail.com
3a84b1d04cdfb5d1e1333463a2f51155c3146c05
30fdad2689ca921b720bc297a4082c6debd9a8ee
/Hello-spring-study/src/main/java/com/example/hellospring/repository/MemoryMemberRepository.java
e812e3a0342b716a5f1726877f4ecca2da25269e
[]
no_license
junyeon1997/Springboot-imple
88660b26353f2c94bd5a1552866ee257331b3e85
07c5d59ac5145dc94a302a2f3abe0a508442cd43
refs/heads/main
2023-07-20T00:09:02.643525
2021-09-01T15:01:53
2021-09-01T15:01:53
402,090,061
0
0
null
null
null
null
UTF-8
Java
false
false
987
java
package com.example.hellospring.repository; import com.example.hellospring.domain.Member; import org.springframework.stereotype.Repository; import java.util.*; public class MemoryMemberRepository implements MemberRepository{ private static Map<Long, Member> store = new HashMap<>(); private static long sequence = 0L; @Override public Member save(Member member) { member.setId(++sequence); store.put(member.getId(), member); return member; } @Override public Optional<Member> findById(Long id) { return Optional.ofNullable(store.get(id)); } @Override public Optional<Member> findByName(String name) { return store.values().stream() .filter(member -> member.getName().equals(name)) .findAny(); } @Override public List<Member> findAll() { return new ArrayList<>(store.values()); } public void clearStore() { store.clear(); } }
[ "junyeon2012@gmail.com" ]
junyeon2012@gmail.com
a3bc91fe9c8554355c95930837284caf1d53957a
7b5f7427f9e21584408cfc43e4ca9a8f123ec029
/src/main/java/com/testSelenium/hybrid/driver/DriverScript.java
fd51e1af7a3a21f04a9a91714ba915d628884902
[]
no_license
mohit623/HybridFramework
c7785641d5364ea14c2dc4fa72bd6d8875b01e39
59bad3206af56415b786e697e9caa75fa78d485d
refs/heads/master
2020-05-16T15:31:37.396029
2019-04-24T02:43:42
2019-04-24T02:43:42
183,134,033
0
0
null
null
null
null
UTF-8
Java
false
false
1,491
java
package com.testSelenium.hybrid.driver; import java.util.Hashtable; import java.util.Properties; import com.testSelenium.hybrid.keywords.AppKeywords; import com.testSelenium.hybrid.util.Xls_Reader; public class DriverScript { public Properties prop; public Properties envProp; public void setProp(Properties prop) { this.prop = prop; } public void setEnvProp(Properties envProp) { this.envProp = envProp; } public void executeKeywords(String testName,Xls_Reader xls,Hashtable<String, String> testdata) { int rowcount=xls.getRowCount("Keywords"); System.out.println(prop.getClass()); for(int rNum=2;rNum<=rowcount;rNum++) { String tcid =xls.getCellData("Keywords", "TCID", rNum); if(tcid.equals(testName)) { String keyword =xls.getCellData("Keywords", "Keyword", rNum); String Objectkey =xls.getCellData("Keywords", "Object", rNum); String dataKey =xls.getCellData("Keywords", "Data", rNum); System.out.println(prop.getProperty("url")); System.out.println(tcid+"--"+keyword+"--"+prop.getProperty(Objectkey)+"--"+testdata.get(dataKey)); if(keyword.equals("openBrowser")) { } else if(keyword.equals("navigate")) { } else if(keyword.equals("click")) { } else if(keyword.equals("type")) { } else if(keyword.equals("validateLogin")) { } } } } }
[ "ermohit.chawla@gmail.com" ]
ermohit.chawla@gmail.com
52eb0a5b142cc2428024aa12865efe4c9ac35469
7df5331d2c3fd8ed65b318ad733ce50945ce7f1b
/app/src/main/java/com/gank/io/fragment/GirlFragment.java
ca660911e58c479f143fdaeceaa13f7c1f2ca5fa
[]
no_license
ericacx/VVGankIO
3174cd44867c63a93d70874ca1dff655bfccec3f
c88548ef47a6429e0376c54a1541e077cf384a26
refs/heads/master
2020-12-13T20:55:23.770492
2016-07-26T06:56:01
2016-07-26T06:56:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
546
java
package com.gank.io.fragment; import android.os.Bundle; import android.view.View; /** * * _ _ * * __ _(_)_ _(_) __ _ _ __ * * \ \ / / \ \ / / |/ _` | '_ \ * * \ V /| |\ V /| | (_| | | | | * * \_/ |_| \_/ |_|\__,_|_| |_| * <p> * Created by vivian on 16/7/5. */ public class GirlFragment extends BaseFragment { public GirlFragment(){ } @Override public void initView(View view, Bundle savedInstanceState) { } @Override protected int getLayoutId() { return 0; } }
[ "1354458047@qq.com" ]
1354458047@qq.com
43cd7505dc048bd6d410bc2c2acf8d041d00b15a
1c5eb251865d01341358c4af7574c61a78a11709
/src/app/edit/EditBrand.java
959ea93587a18078c0bd484f7157f5ebfec670b6
[]
no_license
semicolondevs/ShoeThis
2b695d89f8afa74200d54c4f740e6ef5147e59ed
7aaf8755ef064d0915db4408153b1a72c75fcc68
refs/heads/master
2016-09-10T16:06:52.282428
2014-03-15T18:58:18
2014-03-15T18:58:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,212
java
package app.edit; import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import app.add.AddBrand; import app.db.DatabaseManager; import app.db.TestConnection; import app.model.Brands; import javax.swing.JTextField; import javax.swing.border.LineBorder; import java.awt.Color; import java.awt.Font; import javax.swing.SwingConstants; import javax.swing.JLabel; import java.awt.SystemColor; import javax.swing.ImageIcon; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.SQLException; import java.awt.event.WindowFocusListener; public class EditBrand extends JDialog { private final JPanel contentPanel = new JPanel(); private JTextField txtBrandId; private JTextField txtBrandName; public EditBrand(final Brands b) { addWindowFocusListener(new WindowFocusListener() { @Override public void windowGainedFocus(WindowEvent arg0) { } @Override public void windowLostFocus(WindowEvent arg0) { dispose(); } }); addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent arg0) { txtBrandId.setText(Integer.toString(b.getBrandId())); txtBrandName.setText(b.getBrandName()); } }); setUndecorated(true); setBounds(100, 100, 229, 202); getContentPane().setLayout(new BorderLayout()); contentPanel.setBackground(Color.WHITE); contentPanel.setBorder(new LineBorder(new Color(51, 153, 255))); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); final JPanel pnlSuccessEdit = new JPanel(); pnlSuccessEdit.setVisible(false); pnlSuccessEdit.setBorder(new LineBorder(new Color(51, 153, 255), 3)); pnlSuccessEdit.setBackground(new Color(255, 255, 255)); pnlSuccessEdit.setBounds(10, 33, 209, 123); contentPanel.add(pnlSuccessEdit); pnlSuccessEdit.setLayout(null); JLabel lblSuccesfullyEdited = new JLabel("Succesfully Edited !"); lblSuccesfullyEdited.setHorizontalAlignment(SwingConstants.CENTER); lblSuccesfullyEdited.setForeground(Color.GREEN); lblSuccesfullyEdited.setFont(new Font("SansSerif", Font.PLAIN, 20)); lblSuccesfullyEdited.setBounds(-41, 28, 287, 29); pnlSuccessEdit.add(lblSuccesfullyEdited); JButton button = new JButton("OK"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); } }); button.setForeground(Color.WHITE); button.setFont(new Font("SansSerif", Font.PLAIN, 15)); button.setBorder(null); button.setBackground(new Color(51, 102, 255)); button.setBounds(61, 77, 89, 35); pnlSuccessEdit.add(button); { txtBrandId = new JTextField(); txtBrandId.setOpaque(false); txtBrandId.setEditable(false); txtBrandId.setHorizontalAlignment(SwingConstants.CENTER); txtBrandId.setForeground(Color.BLACK); txtBrandId.setFont(new Font("SansSerif", Font.PLAIN, 15)); txtBrandId.setColumns(10); txtBrandId.setBorder(new LineBorder(new Color(51, 153, 255))); txtBrandId.setBounds(10, 60, 209, 29); contentPanel.add(txtBrandId); } { JLabel lblBrandId = new JLabel("Brand Id"); lblBrandId.setHorizontalAlignment(SwingConstants.CENTER); lblBrandId.setForeground(SystemColor.textHighlight); lblBrandId.setFont(new Font("SansSerif", Font.PLAIN, 20)); lblBrandId.setBounds(35, 33, 145, 29); contentPanel.add(lblBrandId); } { txtBrandName = new JTextField(); txtBrandName.setHorizontalAlignment(SwingConstants.CENTER); txtBrandName.setForeground(Color.BLACK); txtBrandName.setFont(new Font("SansSerif", Font.PLAIN, 15)); txtBrandName.setColumns(10); txtBrandName.setBorder(new LineBorder(new Color(51, 153, 255))); txtBrandName.setBounds(10, 122, 209, 29); contentPanel.add(txtBrandName); } { JLabel lblBrandName = new JLabel("Brand Name"); lblBrandName.setHorizontalAlignment(SwingConstants.CENTER); lblBrandName.setForeground(SystemColor.textHighlight); lblBrandName.setFont(new Font("SansSerif", Font.PLAIN, 20)); lblBrandName.setBounds(36, 97, 158, 29); contentPanel.add(lblBrandName); } JLabel lblEditBrand = new JLabel("Edit Brand"); lblEditBrand.setForeground(Color.WHITE); lblEditBrand.setFont(new Font("SansSerif", Font.PLAIN, 15)); lblEditBrand.setBounds(10, -1, 162, 23); contentPanel.add(lblEditBrand); JButton btnCloseEditBrand = new JButton("X"); btnCloseEditBrand.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); } }); btnCloseEditBrand.setForeground(Color.WHITE); btnCloseEditBrand.setFont(new Font("SansSerif", Font.BOLD, 11)); btnCloseEditBrand.setBorder(null); btnCloseEditBrand.setBackground(new Color(0, 51, 255)); btnCloseEditBrand.setBounds(192, 0, 37, 22); contentPanel.add(btnCloseEditBrand); JLabel label_1 = new JLabel(""); label_1.setIcon(new ImageIcon(EditBrand.class.getResource("/app/image/title.png"))); label_1.setForeground(Color.WHITE); label_1.setFont(new Font("SansSerif", Font.PLAIN, 15)); label_1.setBounds(0, -1, 450, 23); contentPanel.add(label_1); JButton btnSave = new JButton("Save"); btnSave.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { TestConnection tc = new TestConnection(); DatabaseManager dm = new DatabaseManager(); Brands b = new Brands(); b.setBrandId(Integer.parseInt(txtBrandId.getText())); b.setBrandName(txtBrandName.getText()); try { int rs = dm.updateBrand(tc.getConnection(), b); if(rs==1){ pnlSuccessEdit.setVisible(true); AddBrand ab = new AddBrand(null); ab.setFocusable(true); } } catch (ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); btnSave.setForeground(Color.WHITE); btnSave.setFont(new Font("SansSerif", Font.PLAIN, 15)); btnSave.setBorder(null); btnSave.setBackground(new Color(51, 102, 255)); btnSave.setBounds(72, 162, 89, 35); contentPanel.add(btnSave); } }
[ "johndavidguevarra85@yahoo.com" ]
johndavidguevarra85@yahoo.com
e935796d3586c61bfe6347186b45445a3e2d3a6f
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/9/9_366c9bf62858d7de37303dc006ac7350025cc159/CostDimension/9_366c9bf62858d7de37303dc006ac7350025cc159_CostDimension_t.java
2c9e42b0831433b7f0db80377a146fff9d188117
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
10,142
java
package org.adempiere.engine; import java.util.ArrayList; import java.util.Properties; import org.adempiere.exceptions.AdempiereException; import org.compiere.model.I_AD_Client; import org.compiere.model.I_AD_Org; import org.compiere.model.I_C_AcctSchema; import org.compiere.model.I_M_AttributeInstance; import org.compiere.model.I_M_CostElement; import org.compiere.model.I_M_CostType; import org.compiere.model.I_M_Product; import org.compiere.model.MAcctSchema; import org.compiere.model.MCostType; import org.compiere.model.MLocator; import org.compiere.model.MProduct; import org.compiere.model.MTable; import org.compiere.model.MTransaction; import org.compiere.model.Query; import org.compiere.util.Env; import org.compiere.util.Util; /** * Immutable Cost Dimension * @author Teo Sarca */ public class CostDimension { public static final int ANY = -10; private int AD_Client_ID; private int AD_Org_ID; private int M_Product_ID; private int S_Resource_ID; private int M_AttributeSetInstance_ID; private int M_CostType_ID; private int C_AcctSchema_ID; private int M_CostElement_ID; public CostDimension(MProduct product, MAcctSchema as, int M_CostType_ID, int AD_Org_ID, int M_ASI_ID, int M_CostElement_ID) { this.AD_Client_ID = as.getAD_Client_ID(); this.AD_Org_ID = AD_Org_ID; this.M_Product_ID = product != null ? product.get_ID() : ANY; this.M_AttributeSetInstance_ID = M_ASI_ID; this.M_CostType_ID = M_CostType_ID; this.C_AcctSchema_ID = as.get_ID(); this.M_CostElement_ID = M_CostElement_ID; updateForProduct(product, as); } public CostDimension(int client_ID, int org_ID, int product_ID, int attributeSetInstance_ID, int costType_ID, int acctSchema_ID, int costElement_ID) { this.AD_Client_ID = client_ID; this.AD_Org_ID = org_ID; this.M_Product_ID = product_ID; this.M_AttributeSetInstance_ID = attributeSetInstance_ID; this.M_CostType_ID = costType_ID; this.C_AcctSchema_ID = acctSchema_ID; this.M_CostElement_ID = costElement_ID; // updateForProduct(null, null); } /** * Copy Constructor * * @param costDimension a <code>CostDimension</code> object */ public CostDimension(CostDimension costDimension) { this.AD_Client_ID = costDimension.AD_Client_ID; this.AD_Org_ID = costDimension.AD_Org_ID; this.M_Product_ID = costDimension.M_Product_ID; this.M_AttributeSetInstance_ID = costDimension.M_AttributeSetInstance_ID; this.M_CostType_ID = costDimension.M_CostType_ID; this.C_AcctSchema_ID = costDimension.C_AcctSchema_ID; this.M_CostElement_ID = costDimension.M_CostElement_ID; } private Properties getCtx() { return Env.getCtx(); // TODO } private void updateForProduct(MProduct product, MAcctSchema as) { if (product == null) { product = MProduct.get(getCtx(), this.M_Product_ID); } if (product == null) { // incomplete specified dimension [SKIP] return; } if (as == null) { as = MAcctSchema.get(getCtx(), this.C_AcctSchema_ID); } String CostingLevel = product.getCostingLevel(as, AD_Org_ID); // if (MAcctSchema.COSTINGLEVEL_Client.equals(CostingLevel)) { AD_Org_ID = 0; M_AttributeSetInstance_ID = 0; } else if (MAcctSchema.COSTINGLEVEL_Organization.equals(CostingLevel)) { M_AttributeSetInstance_ID = 0; } else if (MAcctSchema.COSTINGLEVEL_BatchLot.equals(CostingLevel)) { AD_Org_ID = 0; } // this.S_Resource_ID = product.getS_Resource_ID(); } /** * @return the aD_Client_ID */ public int getAD_Client_ID() { return AD_Client_ID; } /** * @return the aD_Org_ID */ public int getAD_Org_ID() { return AD_Org_ID; } /** * @return the m_Product_ID */ public int getM_Product_ID() { return M_Product_ID; } public int getS_Resource_ID() { return S_Resource_ID; } public CostDimension setM_Product_ID(int M_Product_ID) { CostDimension d = new CostDimension(this); d.M_Product_ID = M_Product_ID; d.updateForProduct(null, null); // return d; } public CostDimension setM_Product(MProduct product) { CostDimension d = new CostDimension(this); d.M_Product_ID = product.get_ID(); d.updateForProduct(product, null); return d; } /** * @return the M_AttributeSetInstance_ID */ public int getM_AttributeSetInstance_ID() { return M_AttributeSetInstance_ID; } /** * @return the m_CostType_ID */ public int getM_CostType_ID() { return M_CostType_ID; } /** * @return the c_AcctSchema_ID */ public int getC_AcctSchema_ID() { return C_AcctSchema_ID; } /** * @return the m_CostElement_ID */ public int getM_CostElement_ID() { return M_CostElement_ID; } public Query toQuery(Class<?> clazz, String trxName) { return toQuery(clazz, null, null, trxName); } public Query toQuery(Class<?> clazz, String whereClause, Object[] params, String trxName) { String tableName; // Get Table_Name by Class // TODO: refactor try { tableName = (String)clazz.getField("Table_Name").get(null); } catch (Exception e) { throw new AdempiereException(e); } // Properties ctx = Env.getCtx(); MTable table = MTable.get(ctx, tableName); ArrayList<Object> finalParams = new ArrayList<Object>(); StringBuffer finalWhereClause = new StringBuffer(); finalWhereClause.append(I_AD_Client.COLUMNNAME_AD_Client_ID); finalParams.add(this.AD_Client_ID); finalWhereClause.append(" AND "+I_AD_Org.COLUMNNAME_AD_Org_ID+"=?"); finalParams.add(this.AD_Org_ID); finalWhereClause.append(" AND "+I_M_Product.COLUMNNAME_M_Product_ID+"=?"); finalParams.add(this.M_Product_ID); finalWhereClause.append(" AND "+I_M_AttributeInstance.COLUMNNAME_M_AttributeSetInstance_ID+"=?"); finalParams.add(this.M_AttributeSetInstance_ID); finalWhereClause.append(" AND "+I_C_AcctSchema.COLUMNNAME_C_AcctSchema_ID+"=?"); finalParams.add(this.C_AcctSchema_ID); if (this.M_CostElement_ID != ANY) { finalWhereClause.append(" AND "+I_M_CostElement.COLUMNNAME_M_CostElement_ID+"=?"); finalParams.add(this.M_CostElement_ID); } if (this.M_CostType_ID != ANY && table.getColumn(I_M_CostType.COLUMNNAME_M_CostType_ID) != null) { finalWhereClause.append(" AND "+I_M_CostType.COLUMNNAME_M_CostType_ID+"=?"); finalParams.add(this.M_CostType_ID); } if (!Util.isEmpty(whereClause, true)) { finalWhereClause.append(" AND (").append(whereClause).append(")"); if (params != null && params.length > 0) { for (Object p : params) { finalParams.add(p); } } } return new Query(ctx, tableName, finalWhereClause.toString(), trxName) .setParameters(finalParams); } @Override protected Object clone() { return new CostDimension(this); } @Override public String toString() { final String TAB = ";"; String retValue = ""; retValue = "CostDimension{" + "AD_Client_ID = " + this.AD_Client_ID + TAB + "AD_Org_ID = " + this.AD_Org_ID + TAB + "M_Product_ID = " + this.M_Product_ID + TAB + "M_AttributeSetInstance_ID = " + this.M_AttributeSetInstance_ID + TAB + "M_CostType_ID = " + this.M_CostType_ID + TAB + "C_AcctSchema_ID = " + this.C_AcctSchema_ID + TAB + "M_CostElement_ID = " + this.M_CostElement_ID + TAB + "}"; return retValue; } public static boolean isSameCostDimension(MAcctSchema as, MTransaction trxFrom, MTransaction trxTo) { if (trxFrom.getM_Product_ID() != trxTo.getM_Product_ID()) { throw new AdempiereException("Same product is needed - "+trxFrom+", "+trxTo); } MProduct product = MProduct.get(trxFrom.getCtx(), trxFrom.getM_Product_ID()); String CostingLevel = product.getCostingLevel(as, trxFrom.getAD_Org_ID()); MLocator locatorFrom = MLocator.get(trxFrom.getCtx(), trxFrom.getM_Locator_ID()); MLocator locatorTo = MLocator.get(trxTo.getCtx(), trxTo.getM_Locator_ID()); int Org_ID = locatorFrom.getAD_Org_ID(); int Org_ID_To = locatorTo.getAD_Org_ID(); int ASI_ID = trxFrom.getM_AttributeSetInstance_ID(); int ASI_ID_To = trxTo.getM_AttributeSetInstance_ID(); if (MAcctSchema.COSTINGLEVEL_Client.equals(CostingLevel)) { Org_ID = 0; Org_ID_To = 0; ASI_ID = 0; ASI_ID_To = 0; } else if (MAcctSchema.COSTINGLEVEL_Organization.equals(CostingLevel)) { ASI_ID = 0; ASI_ID_To = 0; } else if (MAcctSchema.COSTINGLEVEL_BatchLot.equals(CostingLevel)) { Org_ID = 0; Org_ID_To = 0; } // return Org_ID == Org_ID_To && ASI_ID == ASI_ID_To; } public static boolean isSameCostDimension(MAcctSchema as, IDocumentLine model) { MProduct product = MProduct.get(model.getCtx(), model.getM_Product_ID()); MLocator locator = MLocator.get(model.getCtx(), model.getM_LocatorTo_ID()); String CostingLevel = product.getCostingLevel(as, model.getAD_Org_ID()); int Org_ID = model.getAD_Org_ID(); int Org_ID_To = locator.getAD_Org_ID(); int ASI_ID = model.getM_AttributeSetInstance_ID(); int ASI_ID_To = model.getM_AttributeSetInstance_ID(); if (MAcctSchema.COSTINGLEVEL_Client.equals(CostingLevel)) { Org_ID = 0; Org_ID_To = 0; ASI_ID = 0; ASI_ID_To = 0; } else if (MAcctSchema.COSTINGLEVEL_Organization.equals(CostingLevel)) { ASI_ID = 0; ASI_ID_To = 0; } else if (MAcctSchema.COSTINGLEVEL_BatchLot.equals(CostingLevel)) { Org_ID = 0; Org_ID_To = 0; } // return Org_ID == Org_ID_To && ASI_ID == ASI_ID_To; } public String getCostingMethod() { MCostType ct = new MCostType(Env.getCtx(), getM_CostType_ID(), null); return ct.getCostingMethod(); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
214a481ff4f99d51e14b367c55211e94e184f25c
cdb189369f83068f1bf4c55d99a2f7fc2a167c2e
/RemoteSystemsTempFiles/gapp/.svn/pristine/c0/c0fa0075d9cbf3c541ce5dc011f4f1d6019eab4b.svn-base
8cce1dcf28b8711f2c86d58f76e310125027c094
[]
no_license
hiren5050/GAPP
2f09b2768379e7b5e91f6d7344d4b13fe29aec5c
663c36cab0a08438f5ecfbb25466dfe0876cf78b
refs/heads/master
2021-01-12T04:02:14.951598
2016-12-27T19:50:26
2016-12-27T19:50:26
77,475,641
0
0
null
null
null
null
UTF-8
Java
false
false
375
package springmvc.model.dao; import java.util.List; import springmvc.model.AdditionalInfo; import springmvc.model.ApplicationStatus; public interface ApplicationStatusDao { ApplicationStatus getApplicationStatus(Integer As_id); List<AdditionalInfo> getApplicationStatus(); ApplicationStatus saveApplicationStatus (ApplicationStatus applicationStatus); }
[ "hphiren96@gmail.com" ]
hphiren96@gmail.com
9474e90329da4ca022f186f5bed92b0e9c444da1
01ff007a1a504f0bc13030438f75bbc9b06e2585
/core/spoofax.eclipse/src/main/java/mb/spoofax/eclipse/editor/ScopeManager.java
b115de436918b47d4c6ef1d46fa19b15482df62e
[ "Apache-2.0" ]
permissive
AZWN/spoofax-pie
48eac24f0ae3cd29895d6c1b7bf4134e69d81537
3428621fc7fe6d21d8b6889ef37cde8c41f9add2
refs/heads/master
2023-03-03T08:17:50.802125
2020-05-18T12:48:45
2020-05-18T12:48:45
267,873,687
0
0
Apache-2.0
2020-05-29T14:08:58
2020-05-29T14:08:58
null
UTF-8
Java
false
false
4,604
java
package mb.spoofax.eclipse.editor; import mb.common.style.Style; import mb.spoofax.eclipse.util.ColorShare; import org.checkerframework.checker.nullness.qual.Nullable; import org.eclipse.jface.text.TextAttribute; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.RGB; import javax.inject.Inject; import javax.inject.Singleton; /** * Manages the scope names and their styles. */ @Singleton public final class ScopeManager { /** The default scope name. */ public static final String DEFAULT_SCOPE = "text"; /** The default text attribute; or {@code null} when it has not been created yet. */ private @Nullable TextAttribute defaultTextAttribute; private final ColorShare colorShare; @Inject public ScopeManager(ColorShare colorShare) { this.colorShare = colorShare; } /** * Gets the styling to use for tokens with the specified scope name. * * @param scope the scope name * @param fallback the fallback style; or {@code null} to specify none * @return the scope style */ public TextAttribute getTokenHighlight(String scope, @Nullable Style fallback) { if (scope.startsWith(DEFAULT_SCOPE)) { return getOrCreateDefault(); } if (fallback != null) return createTextAttributeFromStyle(fallback); else throw new RuntimeException("Not implemented."); } /** * Creates a {@link TextAttribute} that corresponds to the given {@link Style}. * * @param style the style * @return the corresponding text attribute */ private TextAttribute createTextAttributeFromStyle(Style style) { final @Nullable Color foreground = fromStyleColor(style.getColor()); final @Nullable Color background = fromStyleColor(style.getBackgroundColor()); return createTextAttribute(foreground, background, style.isBold(), style.isItalic(), style.isUnderscore(), style.isStrikeout(), null); } /** * Creates a {@link TextAttribute} with the given parameters. * * @param foreground the foreground color; or {@code null} * @param background the background color; or {@code null} * @param bold whether the style is bold * @param italic whether the style is italic * @param underline whether the style is underlined * @param strikethrough whether the style is stricken through * @param font the font to use; or {@code null} * @return the corresponding text attribute */ private TextAttribute createTextAttribute( @Nullable Color foreground, @Nullable Color background, boolean bold, boolean italic, boolean underline, boolean strikethrough, @Nullable Font font) { int fontStyle = SWT.NORMAL; if(bold) { fontStyle |= SWT.BOLD; } if(italic) { fontStyle |= SWT.ITALIC; } if(underline) { fontStyle |= TextAttribute.UNDERLINE; } if(strikethrough) { fontStyle |= TextAttribute.STRIKETHROUGH; } return new TextAttribute(foreground, background, fontStyle, font); } /** * Gets or creates the default text attribute. * * @return the default text attribute */ private TextAttribute getOrCreateDefault() { if (defaultTextAttribute != null) return defaultTextAttribute; Color foreground = fromRGB(0, 0, 0); // FIXME: We should not default to black (e.g., dark mode will be unreadable) defaultTextAttribute = createTextAttribute(foreground, null, false, false, false, false, null); return defaultTextAttribute; } /** * Gets the {@link Color} corresponding to the given {@link mb.common.style.Color}. * * @param color the style color; or {@code null} * @return the SWT color; or {@code null} when the input color is {@code null} */ private @Nullable Color fromStyleColor(mb.common.style.@Nullable Color color) { if (color == null) return null; return fromRGB(color.getRed(), color.getGreen(), color.getBlue()); } /** * Gets the {@link Color} corresponding to the given {@link mb.common.style.Color}. * * @param red the red color component, between 0 and 255 inclusive * @param green the green color component, between 0 and 255 inclusive * @param blue the blue color component, between 0 and 255 inclusive * @return the SWT color */ private Color fromRGB(int red, int green, int blue) { return this.colorShare.getColor(new RGB(red, green, blue)); } }
[ "647530+Virtlink@users.noreply.github.com" ]
647530+Virtlink@users.noreply.github.com
469f24b4af9b9d6dd58e6b6248483bae56a77643
d555e9e56a4e47613c8819ee19d28af2bf1a7200
/src/com/cz4013/binder/ObjectReferenceTable.java
9065e052bfd08fec18d72e722a504b83f13269c8
[]
no_license
sngguojie/CZ4013Binder
3dd2e9a97d2ae19613414a1baa989a922105959d
0369f835fd9a543ebd7f8d32f0d13227daf651a7
refs/heads/master
2021-01-18T19:10:22.324812
2017-04-02T19:09:08
2017-04-02T19:09:08
86,891,055
0
0
null
null
null
null
UTF-8
Java
false
false
1,748
java
package com.cz4013.binder; import java.util.HashMap; /** * Created by danielseetoh on 4/1/17. * This is the table for the server to register the remote object references. * The client will retrieve the remote object references based on the names of the classes. */ public class ObjectReferenceTable { private HashMap<String, String> objectReferenceHashMap; public ObjectReferenceTable () { this.objectReferenceHashMap = new HashMap<String, String>(); } /** * Add a name and object reference into the hashmap. If name already exists, will replace object. This is in case the server restarts. * The object reference should be in the form of "IPAddress,PORT,ObjectHashCode" * @param name * @param remoteObjRef * @return * @throws NameExistsException */ public String addObjectReference(String name, String remoteObjRef) throws NameExistsException{ if (this.objectReferenceHashMap.containsKey(name)){ this.objectReferenceHashMap.replace(name, remoteObjRef); } else { this.objectReferenceHashMap.put(name, remoteObjRef); } return "Success adding object to reference table."; } /** * Get an object reference from the name. If it does not exist, throw a NameDoesNotExistException. * @param name * @return * @throws NameDoesNotExistException */ public String getObjectReference(String name) throws NameDoesNotExistException{ if (this.objectReferenceHashMap.containsKey(name)) { return "Success " + this.objectReferenceHashMap.get(name); } else { throw new NameDoesNotExistException("Failure Remote Reference Name does not exist"); } } }
[ "danielseetoh92@gmail.com" ]
danielseetoh92@gmail.com
bcb019299edddb9e096c1fe937cf36a05f1c29c7
d073cc8bdecb7e5ccc51636b8f37792c265b47be
/src/main/java/study/erik/algorithm/leetcode/math/SumOfSquareNumbers.java
58d8929d37a2c7a0b0a2cabe0f15ba18a1607572
[]
no_license
wwzskyrain/algorithm-practice
c7f101943a7a662015d8ba9c7ca5bb0167ce2fad
99db385cc8a24daf75d859b68d2b31ae3196eada
refs/heads/master
2023-08-31T17:39:24.207987
2023-08-04T03:57:48
2023-08-04T03:57:48
128,034,067
0
4
null
2022-06-17T03:25:44
2018-04-04T08:45:15
Java
UTF-8
Java
false
false
1,468
java
/** * Alipay.com Inc. * Copyright (c) 2004-2022 All Rights Reserved. */ package study.erik.algorithm.leetcode.math; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import study.erik.algorithm.util.LetCodeCommit; /** * @author yueyi * @version : SumOfSquareNumbers.java, v 0.1 2022年04月02日 9:56 下午 yueyi Exp $ */ @RunWith(Parameterized.class) public class SumOfSquareNumbers { @LetCodeCommit(title = "633. Sum of Square Numbers") public boolean judgeSquareSum(int c) { long left = 0, right = (int) Math.sqrt(c); while (left <= right) { // 必须用long,不然会溢出。 // 当right有点大,需要调小的时,不用long就会溢出. long cur = left * left + right * right; if (cur < c) { left++; } else if (cur > c) { right--; } else { return true; } } return false; } @Parameter public int c; @Parameter(1) public boolean expect; @Parameters public static Object[][] data() { return new Object[][] { {2147483600, true}, }; } @Test public void test_() { Assert.assertEquals(expect, judgeSquareSum(c)); } }
[ "wwzskyrain@163.com" ]
wwzskyrain@163.com
a0b40f1e466d298f5f336179d4666b30ce383f1c
49e92f8644b70ccbe40541841fbeec896119104d
/src/main/java/com/malasong/web/controller/AuthenticationController.java
3b4a15d5cc62868cda40e6a6e86fbd322fbb099d
[]
no_license
iamfangyun/malasong
01bcf684281e1946aea059705bf5ad5d50b419d9
b64e9e020be8aae4adcffad78f71909ce52ba0b9
refs/heads/master
2021-05-28T07:11:12.511818
2015-01-08T15:28:09
2015-01-08T15:28:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,486
java
/** * */ package com.malasong.web.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.authentication.LockedException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.WebAttributes; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; /** * @author Downpour */ @Controller public class AuthenticationController { private static final Log logger = LogFactory.getLog(AuthenticationController.class); /** * Session invalid redirect * * @return */ @RequestMapping("/timeout") public String timeout(RedirectAttributes redirectAttributes) { logger.info("Session timeout ... The system will redirect to login page"); // add a flag into session to display on login page redirectAttributes.addFlashAttribute("timeoutErrorMessage", "验证超时"); return "redirect:/login"; } /** * * @param httpSession * @return */ @RequestMapping(value = { "/", "/login" }) public String login(HttpServletRequest request, HttpSession httpSession, @ModelAttribute("timeoutErrorMessage") String timeoutErrorMessage) { // Trying to get AuthenticationException from HttpSession AuthenticationException authenticationException = (AuthenticationException) httpSession.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); // when authentication exception is found, setting up error message to display if (authenticationException != null) { if (logger.isErrorEnabled()) { logger.error("Authentication process exception: " + authenticationException.getMessage()); } request.setAttribute("errorMessage", "验证失败"); if (authenticationException.getCause() instanceof LockedException) { request.setAttribute("errorMessage", authenticationException.getMessage()); } // remove AuthenticationException from httpSession httpSession.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); return "login"; } return "login"; } /** * Execute post login process * * @return */ @RequestMapping("/post-login") public String postLogin() { return "redirect:/home"; } }
[ "10301077@bjtu.edu.cn" ]
10301077@bjtu.edu.cn
3b03064719bbe449d27f4dbc74404b2c6e0e9abc
cb7a7c8e96aed0fdb21d221e3d550000a3b3e189
/app/src/main/java/com/team6378/thanu/frcmanager/Ranking.java
85ac0411053ab2aee31c2147da1ea5899ebc8761
[ "CC0-1.0" ]
permissive
thanusiv/FRC-Scouting
a8e57221713ed99b671423cfe48ce38c0536b3bb
f7cf02005956963250db781483376e3d2da3eea1
refs/heads/master
2022-12-07T07:58:01.426880
2020-08-26T19:42:04
2020-08-26T19:42:04
267,367,574
2
0
null
null
null
null
UTF-8
Java
false
false
2,839
java
package com.team6378.thanu.frcmanager; import java.util.Comparator; public class Ranking { private int teamNumber; private double averageSwitch; private double averageScale; private double averageExchange; private int numberOfGames; private int crossedBaseline; private int autoSwitch; private int autoScale; private int climbs; private int malfunctions; public Ranking(int teamNumber, double averageSwitch, double averageScale, double averageExchange, int crossedBaseline, int autoSwitch, int autoScale, int games, int climbs, int malfunctions){ this.teamNumber = teamNumber; this.averageSwitch = averageSwitch; this.averageScale = averageScale; this.averageExchange = averageExchange; this.crossedBaseline = crossedBaseline; this.autoSwitch = autoSwitch; this.autoScale = autoScale; numberOfGames = games; this.climbs = climbs; this.malfunctions = malfunctions; } public double getAverageExchange() { return averageExchange; } public double getAverageScale() { return averageScale; } public double getAverageSwitch() { return averageSwitch; } public int getTeamNumber() { return teamNumber; } public int getNumberOfGames() {return numberOfGames;} public int getCrossedBaseline(){return crossedBaseline;} public int getAutoScale() { return autoScale; } public int getAutoSwitch() { return autoSwitch; } public int getClimbs(){ return climbs; } public int getMalfunctions() {return malfunctions; } static class TeleopCubesSwitchComparator implements Comparator<Ranking> { @Override public int compare(Ranking o1, Ranking o2) { if (o2.getAverageSwitch() > o1.getAverageSwitch()) return 1; else if (o2.getAverageSwitch() < o1.getAverageSwitch()) return -1; else return 0; } } static class TeleopCubesScaleComparator implements Comparator<Ranking> { @Override public int compare(Ranking o1, Ranking o2) { if (o2.getAverageScale() > o1.getAverageScale()) return 1; else if (o2.getAverageScale() < o1.getAverageScale()) return -1; else return 0; } } static class TeleopCubesExchangeComparator implements Comparator<Ranking> { @Override public int compare(Ranking o1, Ranking o2) { if (o2.getAverageExchange() > o1.getAverageExchange()) return 1; else if (o2.getAverageExchange() < o1.getAverageExchange()) return -1; else return 0; } } }
[ "tsivakar@uwaterloo.ca" ]
tsivakar@uwaterloo.ca
99464937937a33916723e483d6e4fb7835fb1fa8
f61309289815fb17dcfe82867aeda84b62fe9715
/web/src/main/java/com/loeo/admin/service/SysLogService.java
67b666470e3d87c555b3b0612903190740c75f6e
[]
no_license
balancejia/LOEO2
5f10201f69eb26326de10e3c5e7670f2c4074034
d99664fd4ebb2aaa7da695014c2c257134237ffe
refs/heads/master
2020-03-13T04:59:46.090532
2018-04-24T08:02:46
2018-04-24T08:02:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
264
java
package com.loeo.admin.service; import com.loeo.admin.domain.entity.SysLog; import com.baomidou.mybatisplus.service.IService; /** * <p> * 服务类 * </p> * * @author LT * @since 2018-03-08 */ public interface SysLogService extends IService<SysLog> { }
[ "286269159@qq.com" ]
286269159@qq.com
5c79ff9e02407e505f87460385e485543560e935
c1e3d13d9d6e7872d605214bfc0525359284788a
/src/main/java/com/example/demo/interceptor/LoginInterCeptor.java
bfa1892ece0d3bc4982bf2f5de408f2b3261a0ba
[]
no_license
chengyalin1/blog
605a6660857635ec7e5526c2309b0a891734ec2f
46b54767faf45b1d20517d63d10b773e302654ad
refs/heads/master
2022-12-23T16:51:35.366840
2020-09-14T02:19:56
2020-09-14T02:19:56
295,280,923
0
0
null
null
null
null
UTF-8
Java
false
false
667
java
package com.example.demo.interceptor; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 创作: 承亚林 * 时间: 2020-09-08-20:24 */ /** * 账户拦截 */ public class LoginInterCeptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getSession().getAttribute("user")==null){ response.sendRedirect("/admin"); return false; } return true; } }
[ "447786745@qq.com" ]
447786745@qq.com
8574494eed70849cf0019564e5474cba1e23350e
d6a7b9268b27e66207cc258da1e15d0b8f602bf4
/src/org/mindswap/owls/profile/ServiceParameter.java
b06e706bb71e198e18420aa84753ea3cbe9cabd1
[ "MIT" ]
permissive
spechub/owl-s
4e79122e31898d95705af46c4e90558ef93f4c42
198d268a8ce33dcd588a7b0a824df2a6ad9b5aa9
refs/heads/master
2021-01-16T18:29:57.376136
2007-04-11T16:00:15
2007-04-11T16:00:15
40,605,783
2
0
null
2015-08-12T14:40:30
2015-08-12T14:40:29
null
UTF-8
Java
false
false
1,516
java
// The MIT License // // Copyright (c) 2004 Evren Sirin // // 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. /* * Created on Jan 12, 2004 */ package org.mindswap.owls.profile; import org.mindswap.owl.OWLIndividual; /** * @author evren */ public interface ServiceParameter extends OWLIndividual { public String getName(); public void setName(String name); public OWLIndividual getParameter(); public void setParameter(OWLIndividual value); }
[ "ronwalf@996557b4-991a-0410-8976-5794ad31f82a" ]
ronwalf@996557b4-991a-0410-8976-5794ad31f82a
dab95ba7d6634033b14eb70055da16f6955f76af
b263c889a45334041ca2e78b7831f61aebba0d06
/src/main/java/controllers/StudentsController.java
4cae5f124616e02356df7c5d717526007fa7a6a3
[]
no_license
dahgor/university-timetable
b842d1f7ac2c3137e123caa25a3505493291accb
783178027c333fd77cd86addeb04068b68bebeda
refs/heads/master
2023-05-09T00:37:30.524991
2021-05-31T14:56:55
2021-05-31T14:56:55
369,233,420
0
0
null
null
null
null
UTF-8
Java
false
false
3,407
java
package controllers; import dao.entities.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import services.ServiceException; import services.interfaces.GroupService; import services.interfaces.StudentService; @Controller @RequestMapping("/students") public class StudentsController { private StudentService studentService; private GroupService groupService; @Autowired public StudentsController(StudentService studentService, GroupService groupService) { this.studentService = studentService; this.groupService = groupService; } @GetMapping() public String showAll(Model model) { try { model.addAttribute("students", studentService.getAllItems()); } catch (ServiceException e) { e.printStackTrace(); } return "students/show-all"; } @GetMapping("/{id}") public String showById(@PathVariable("id") int id, Model model) { try { model.addAttribute("student", studentService.findById(id)); } catch (ServiceException e) { e.printStackTrace(); } return "students/show-by-id"; } @GetMapping("/new") public String addNew(Model model) { try { model.addAttribute("groups", groupService.getAllItems()); model.addAttribute("student", new Student()); } catch (ServiceException e) { e.printStackTrace(); } return "students/add-new"; } @PostMapping() public String create(@ModelAttribute("student") Student student) { try { studentService.save(student); } catch (ServiceException e) { e.printStackTrace(); } return "redirect:/students"; } @GetMapping("/{id}/edit") public String edit(Model model, @PathVariable("id") int id) { try { model.addAttribute("student", studentService.findById(id)); model.addAttribute("groups", groupService.getAllItems()); } catch (ServiceException e) { e.printStackTrace(); } return "students/edit"; } @PatchMapping("/{id}") public String update(@PathVariable("id") int id, @ModelAttribute("student") Student student) { try { Student oldStudent = studentService.findById(id); if (!student.getFirstName().equals(oldStudent.getFirstName())) { studentService.changeFirstName(student, student.getFirstName()); } if (!student.getLastName().equals(oldStudent.getLastName())) { studentService.changeLastName(student, student.getLastName()); } if (student.getGroupId() != oldStudent.getGroupId()) { studentService.changeGroup(student, groupService.findById(student.getGroupId())); } } catch (ServiceException e) { e.printStackTrace(); } return "redirect:/students"; } @DeleteMapping("/{id}") public String delete(@PathVariable("id") int id) { try { studentService.delete(new Student(id)); } catch (ServiceException e) { e.printStackTrace(); } return "redirect:/students"; } }
[ "denis.gorban@protonmail.ch" ]
denis.gorban@protonmail.ch
f1b673c3114e8a68c4b994b35f964addca378c71
13a0874a8b9f9e9d83142f1715fb7a1bd2e6e3a0
/04-java-spring/springDataOne/dogs/src/main/java/com/danieljohn/dogs/models/Dog.java
4e5494f3fbe0cb5cbf1be2ce4f497088b36dd943
[]
no_license
Java-November-2020/DanielC-Assignments
31011f3c17490a8747ec43f461e933b621cc5d01
42496a5dc23582cec756a47fc4143544dac17739
refs/heads/main
2023-02-04T06:57:30.849469
2020-12-26T20:30:33
2020-12-26T20:30:33
309,191,945
0
0
null
2020-12-26T20:30:34
2020-11-01T21:29:42
Java
UTF-8
Java
false
false
2,034
java
package com.danieljohn.dogs.models; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import org.springframework.format.annotation.DateTimeFormat; import com.sun.istack.NotNull; @Entity @Table(name="dogs") public class Dog { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Size(min=5) @NotBlank private String name; @NotBlank private String breed; @NotNull private int age; @Column(updatable=false) @DateTimeFormat(pattern = "yyy-MM-DD HH:mm:ss") private Date createdAt; @DateTimeFormat(pattern = "yyy-MM-DD HH:mm:ss") private Date updatedAt; //Before you do anything, you do this. @PrePersist protected void onCreate() { this.createdAt = new Date(); } // Does the same as above but for objects that already exist @PreUpdate protected void onUpdate() { this.updatedAt = new Date(); } public Dog() { super(); } public Dog(String name, String breed, int age) { super(); this.name = name; this.breed = breed; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } }
[ "danieljcoh@gmail.com" ]
danieljcoh@gmail.com
4070177c50304b2703022d3dcacf0132b11ff942
5622ab7a2d905bd9b5d53abc303cb02ce4f063da
/src/com/vgdatabase304/Adaptors/ReviewAdaptor.java
22292c2b9e15be9770dfb6a868776a9eea3738ff
[]
no_license
ConnorJBeck/VGDatabase
1df4ce090144494e50952581c1aaf508fd1c24fe
9013c1ca15e246320e2291e0175012d3b58eb12f
refs/heads/master
2021-06-14T06:10:05.586526
2017-04-01T05:43:39
2017-04-01T05:43:39
84,390,678
1
1
null
2017-03-28T22:27:32
2017-03-09T02:51:16
Java
UTF-8
Java
false
false
6,864
java
package com.vgdatabase304.Adaptors; import com.vgdatabase304.Exceptions.InstanceNotFoundException; import com.vgdatabase304.Structures.Game; import com.vgdatabase304.Structures.RegisteredUser; import com.vgdatabase304.Structures.Review; import com.vgdatabase304.Utils.ConnectionManager; import java.sql.*; import java.util.ArrayList; import java.util.List; public class ReviewAdaptor { private static Statement stmt; private static ResultSet rs; public static Review addReviewToDatabase(RegisteredUser user, Game game, String reviewText, double rating) throws SQLException { stmt = ConnectionManager.getStatement(); rs = stmt.executeQuery("SELECT Max(REVIEWID) FROM REVIEW"); int reviewID = 0; if (rs.next()) { reviewID = rs.getInt(1); } reviewID++; String sql = "INSERT INTO REVIEW VALUES (" + reviewID + ", '" + user.getUsername() + "', " + game.getGameID() + ", '" + reviewText + "', sysdate, " + rating + ")"; stmt.executeUpdate(sql); return new Review(reviewID); } public static void removeReviewFromDatabase(Review review) throws SQLException { stmt = ConnectionManager.getStatement(); String sql = "DELETE FROM REVIEW WHERE " + "REVIEWID=" + review.getReviewID(); stmt.executeUpdate(sql); } public static void setReviewID(Review review, int reviewID) throws SQLException { stmt = ConnectionManager.getStatement(); stmt.executeUpdate("UPDATE REVIEW " + "SET REVIEWID=" + reviewID + " WHERE REVIEWID=" + review.getReviewID() ); review.setReviewID(reviewID); } public static RegisteredUser getUsername(Review review) throws SQLException { stmt = ConnectionManager.getStatement(); String sql = "SELECT USERNAME FROM REVIEW WHERE REVIEWID=" + review.getReviewID(); rs = stmt.executeQuery(sql); if (rs.next()) { return new RegisteredUser(rs.getString(1)); } else { throw new InstanceNotFoundException("No record found in REVIEW for " + review.getReviewID()); } } public static void setUsername(Review review, RegisteredUser user) throws SQLException { stmt = ConnectionManager.getStatement(); stmt.executeUpdate("UPDATE REVIEW " + "SET USERNAME='" + user.getUsername() + "' WHERE REVIEWID=" + review.getReviewID() ); } public static Game getGame(Review review) throws SQLException { stmt = ConnectionManager.getStatement(); String sql = "SELECT GAMEID FROM REVIEW WHERE REVIEWID=" + review.getReviewID(); rs = stmt.executeQuery(sql); if (rs.next()) { return new Game(rs.getInt(1)); } else { throw new InstanceNotFoundException("No record found in REVIEW for " + review.getReviewID()); } } public static void setGame(Review review, Game game) throws SQLException { stmt = ConnectionManager.getStatement(); stmt.executeUpdate("UPDATE REVIEW " + "SET GAMEID='" + game.getGameID() + "' WHERE REVIEWID=" + review.getReviewID() ); } public static double getRating(Review review) throws SQLException { stmt = ConnectionManager.getStatement(); String sql = "SELECT RATING FROM REVIEW WHERE REVIEWID=" + review.getReviewID(); rs = stmt.executeQuery(sql); if (rs.next()) { return rs.getDouble(1); } else { throw new InstanceNotFoundException("No record found in REVIEW for " + review.getReviewID()); } } public static void setRating(Review review, double rating) throws SQLException { stmt = ConnectionManager.getStatement(); stmt.executeUpdate("UPDATE REVIEW " + "SET RATING='" + rating + "' WHERE REVIEWID=" + review.getReviewID() ); } public static String getReviewText(Review review) throws SQLException { stmt = ConnectionManager.getStatement(); String sql = "SELECT REVIEWTEXT FROM REVIEW WHERE REVIEWID=" + review.getReviewID(); rs = stmt.executeQuery(sql); if (rs.next()) { return rs.getString(1); } else { throw new InstanceNotFoundException("No record found in REVIEW for " + review.getReviewID()); } } public static void setReviewText(Review review, String reviewText) throws SQLException { stmt = ConnectionManager.getStatement(); stmt.executeUpdate("UPDATE REVIEW " + "SET REVIEWTEXT='" + reviewText + "' WHERE REVIEWID=" + review.getReviewID() ); } public static Timestamp getPostTimestamp(Review review) throws SQLException { stmt = ConnectionManager.getStatement(); String sql = "SELECT POSTDATETIME FROM REVIEW WHERE REVIEWID=" + review.getReviewID(); rs = stmt.executeQuery(sql); if (rs.next()) { return rs.getTimestamp(1); } else { throw new InstanceNotFoundException("No record found in REVIEW for " + review.getReviewID()); } } public static void setPostTimestamp(Review review, Timestamp timestamp) throws SQLException { stmt = ConnectionManager.getStatement(); stmt.executeUpdate("UPDATE REVIEW " + "SET POSTDATETIME='" + timestamp + "' WHERE REVIEWID=" + review.getReviewID() ); } public static List<Review> getAllReviewsByUser(RegisteredUser user) throws SQLException { stmt = ConnectionManager.getStatement(); List<Review> listOfReviews = new ArrayList<>(); rs = stmt.executeQuery("SELECT REVIEWID FROM REVIEW WHERE USERNAME='" + user.getUsername() + "'"); while (rs.next()) { listOfReviews.add(new Review(rs.getInt("REVIEWID"))); } if (listOfReviews.size() > 0) { return listOfReviews; } else { throw new InstanceNotFoundException("No reviews found for user " + user.getUsername()); } } public static List<Review> getAllReviewsByGame(Game game) throws SQLException { stmt = ConnectionManager.getStatement(); List<Review> listOfReviews = new ArrayList<>(); rs = stmt.executeQuery("SELECT REVIEWID FROM REVIEW WHERE GAMEID=" + game.getGameID()+ ""); while (rs.next()) { listOfReviews.add(new Review(rs.getInt("REVIEWID"))); } if (listOfReviews.size() > 0) { return listOfReviews; } else { throw new InstanceNotFoundException("No reviews found for user " + GameAdaptor.getName(game)); } } }
[ "connor.j.beck@gmail.com" ]
connor.j.beck@gmail.com
2607450739061865607215bbc74d77209c3e7794
d6761d0a7a548d36249fd2a22e28b2cd4372b5db
/app/src/main/java/com/kermitlin/lighttherapymed/ui/MainActivity.java
04b016b00c6b5d26ed34f3f8e1c977689522cd9f
[]
no_license
KeRMitLin/LightTherapyMed
6f2e1fe5a5764e29d56728281519da3ec91cab04
4493a525b3fab0c7fb1d98c3524df9a1e5511e84
refs/heads/master
2020-04-16T20:13:18.409810
2016-08-31T07:28:51
2016-08-31T07:28:51
54,897,959
0
0
null
null
null
null
UTF-8
Java
false
false
4,338
java
package com.kermitlin.lighttherapymed.ui; import android.app.DialogFragment; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.kermitlin.lighttherapymed.R; import com.kermitlin.lighttherapymed.ui.usersLists.UsersListsFragment; import com.kermitlin.lighttherapymed.ui.therapyLists.AddTherapyListDialogFragment; import com.kermitlin.lighttherapymed.ui.therapyLists.TherapyListsFragment; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initializeScreen(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onDestroy() { super.onDestroy(); } public void initializeScreen() { ViewPager viewPager = (ViewPager) findViewById(R.id.pager); TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); /** * Create SectionPagerAdapter, set it as adapter to viewPager with setOffscreenPageLimit(2) **/ SectionPagerAdapter adapter = new SectionPagerAdapter(getSupportFragmentManager()); viewPager.setOffscreenPageLimit(2); viewPager.setAdapter(adapter); /** * Setup the mTabLayout with view pager */ tabLayout.setupWithViewPager(viewPager); } /** * Create an instance of the AddMeal dialog fragment and show it */ public void showAddTherapyListDialog(View view) { /* Create an instance of the dialog fragment and show it */ DialogFragment dialog = AddTherapyListDialogFragment.newInstance(); dialog.show(MainActivity.this.getFragmentManager(), "AddTherapyListDialogFragment"); } public class SectionPagerAdapter extends FragmentStatePagerAdapter { public SectionPagerAdapter(FragmentManager fm) { super(fm); } /** * Use positions (0 and 1) to find and instantiate fragments with newInstance() * * @param position */ @Override public Fragment getItem(int position) { Fragment fragment = null; /** * Set fragment to different fragments depending on position in ViewPager */ switch (position) { case 0: fragment = UsersListsFragment.newInstance(); break; case 1: fragment = TherapyListsFragment.newInstance(); break; default: fragment = UsersListsFragment.newInstance(); break; } return fragment; } @Override public int getCount() { return 2; } /** * Set string resources as titles for each fragment by it's position * * @param position */ @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return getString(R.string.pager_title_users_lists); case 1: default: return getString(R.string.pager_title_therapy_lists); } } } }
[ "jostar1620@gmail.com" ]
jostar1620@gmail.com
09195a4f77d0f86f6480748d1d920fc5e6576acb
9ee72c573b8551135725ca852b113c55fc9cbdd5
/MainActivity.java
7be68689636433740cf1451bfb52cf393d1bb79a
[]
no_license
bhtyrsm/Android-RssAndJsoup-Example
f4b5ed4607181da539b3592f7c3d6e81bcbd75bf
ecd3f10a51187f040f6d82efac695ef1e2144499
refs/heads/master
2021-07-07T00:46:16.221532
2017-10-04T11:40:39
2017-10-04T11:40:39
105,761,009
1
0
null
null
null
null
UTF-8
Java
false
false
2,065
java
package com.example.lenovo.ogrenerekkonus; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import java.util.List; public class MainActivity extends Activity implements ParseFeedCallback { private ListView listView; TextView txt; Rss rss; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.rssListview); txt=(TextView)findViewById(R.id.topTitle); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { rss = (Rss) listView.getAdapter().getItem(position); Intent myintent= new Intent(getApplicationContext() ,Main2Activity.class); myintent.putExtra("link", Uri.parse(rss.getOriginalPostUrl().trim()).toString()); startActivity(myintent); } }); new ParseFeedAsyncTask(this).execute((Void) null); } public void finishedLoadingFeeds(List<Rss> feeds) { listView.setAdapter(new RssListAdapter(getApplicationContext(), feeds)); } public boolean internetErisimi() { ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE); if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) { return true; } else { return false; } } }
[ "noreply@github.com" ]
bhtyrsm.noreply@github.com
65ec88a9595d2a6e60f084bc4775ff280996f635
98708a494eb9fc060748be5ab56437fe00e60df2
/src/com/pet/petstore/domain/Customer.java
8f16526e8c4747a328b56e0ea4312fba562fdeaa
[]
no_license
arvnar2407/PetStore
5d04dc1ffed00ca1566a6c33fa458082761d40c6
01ce4b90c19fac28edc079f6bdb4a86de5f9cfd7
refs/heads/master
2021-05-03T10:33:05.056758
2018-02-06T23:54:27
2018-02-06T23:54:27
120,537,159
0
0
null
null
null
null
UTF-8
Java
false
false
4,245
java
package com.pet.petstore.domain; import java.util.Date; public class Customer { private String custId; private String password; private String firstName; private String lastName; private Date dateOFBirth; private String address; private long contactNumber; private long creditCardno; private String cardType; private Date cardExpiryDate; public String getCustId() { return custId; } public void setCustId(final String custId) { this.custId = custId; } public String getPassword() { return password; } public void setPassword(final String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } public Date getDateOFBirth() { return dateOFBirth; } public void setDateOFBirth(Date dateOFBirth) { this.dateOFBirth = dateOFBirth; } public void setCardExpiryDate(Date cardExpiryDate) { this.cardExpiryDate = cardExpiryDate; } public String getAddress() { return address; } public void setAddress(final String address) { this.address = address; } public long getContactNumber() { return contactNumber; } public void setContactNumber(long contactNumber) { this.contactNumber = contactNumber; } public long getCreditCardno() { return creditCardno; } public void setCreditCardno(long creditCardno) { this.creditCardno = creditCardno; } public String getCardType() { return cardType; } public void setCardType(final String cardType) { this.cardType = cardType; } public Date getCardExpiryDate() { return cardExpiryDate; } public void setCiryDate(final Date cardExpiryDate) { this.cardExpiryDate = cardExpiryDate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + ((cardExpiryDate == null) ? 0 : cardExpiryDate.hashCode()); result = prime * result + ((cardType == null) ? 0 : cardType.hashCode()); result = prime * result + (int) (contactNumber ^ (contactNumber >>> 32)); result = prime * result + (int) (creditCardno ^ (creditCardno >>> 32)); result = prime * result + ((custId == null) ? 0 : custId.hashCode()); result = prime * result + ((dateOFBirth == null) ? 0 : dateOFBirth.hashCode()); result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Customer other = (Customer) obj; if (address == null) { if (other.address != null) return false; } else if (!address.equals(other.address)) return false; if (cardExpiryDate == null) { if (other.cardExpiryDate != null) return false; } else if (!cardExpiryDate.equals(other.cardExpiryDate)) return false; if (cardType == null) { if (other.cardType != null) return false; } else if (!cardType.equals(other.cardType)) return false; if (contactNumber != other.contactNumber) return false; if (creditCardno != other.creditCardno) return false; if (custId == null) { if (other.custId != null) return false; } else if (!custId.equals(other.custId)) return false; if (dateOFBirth == null) { if (other.dateOFBirth != null) return false; } else if (!dateOFBirth.equals(other.dateOFBirth)) return false; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; return true; } }
[ "arvnar.2407@gmail.com" ]
arvnar.2407@gmail.com
af201f45c37a6128c6febec521c1e421c2c5f425
3e2e79bedac25ea5608bd89e692a868b4f847b80
/eclipse/sdedit-for-abs/src/net/sf/sdedit/ui/components/ATabbedPane.java
eb3ba23e70da5df6c8085bef6a578ac3773e254d
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
JaacRepo/absCompiler
a50fa03beeaa9b5a2286cb9a0dd5ba2b52484541
8b852a71947c82bfc7172ec4e9c1affb4cb102d4
refs/heads/master
2018-10-16T11:04:35.821401
2018-08-16T14:24:01
2018-08-16T14:24:01
122,403,875
1
0
null
null
null
null
UTF-8
Java
false
false
11,956
java
// Copyright (c) 2006 - 2008, Markus Strauch. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. package net.sf.sdedit.ui.components; import java.awt.Component; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import net.sf.sdedit.util.base64.Base64; /** * An <tt>ATabbedPane</tt> is an advanced <tt>JTabbedPane</tt> that allows * a user to close tabs and that assigns unique names to tabs. * <p> * Unique names are generated according to this policy: If a tab should be * given a name <it>X</it> such that a tab named <it>X</it> * already exists, we search for the smallest integer number * <it>i&gt;0</it> such that there is no tab with the name <it>X-i</it>. * The tab is then named <it>X-i</it>. * * @author Markus Strauch * */ public class ATabbedPane extends JTabbedPane { private final static long serialVersionUID = 0xAB343921; private static String cleanString = "iVBORw0KGgoAAAANSUhEUgAAABA" + "AAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRv" + "YmUgSW1hZ2VSZWFkeXHJZTwAAAOVSURBVHjaYtTUdGdAA4K/fv3U+Pv3rw+QLfT//" + "3+Gf//+vWNiYtjCwsJyAyj2HiT2//8/sGKAAGJB1gkU9Pj581eNnJyctaamMgM/Py" + "8DIyMDw+fPXxlu3rxfdfPmjaPMzIwtTEzMO2B6AAKIBaH5fw4LC1tHeHgQt7u7PYO" + "OjhIDNzcb2IBfv/4x3LjxiGHr1n3WK1duXPPx45sKJiamKSB9AAHECPIC0GZ3ZmbW" + "zQkJkazu7rYMLCyMDD9//gYZCzWcgYGVlRUozsxw9Oh5hv7+Gb8/fXrnC+TvBAggZ" + "hERZb7fv3/PdnCwV7C3twT69w+DlpYcw5s3HxkeP34FdP53IPsDg6qqNAMXFxvQIA" + "4GoGXMFy9eVgK6eg1AADH9/ftbW0hIxEpFRQms0MBAlYGDg51BQ0OegZ2dneH58zd" + "AMRUGKSlhBnFxQYY7dx4CvfSHQVBQyAqkFyCAmIWEFDOlpaVtgQHH8O7dB4aXLz8w" + "qKjIMHBysoE1SUqKMCgoSIC90te3lGHNmu0MDx8+Yfjx4xvQmz9eAgQQCzAwhBiBI" + "fX69RugwC+GR4+eAl3yliEx0Y+Bl5eDQU5ODBwG3d0LGdau3QH0AjMwLFiBruQEBj" + "CTEEAAsYBC+du3HwxPnjxnAMY90JCfoLBlePXqLdAAabDNX778AHvl37+/QP9DYub" + "fP0haAAggJlAi+fr1M8Pbt2+Bml4z8PBwMxQURDMoK0uDbf78+QfYJY2N2Qy2thZA" + "//8CGsIMtOg70MI/7wACiAkYkluAfmH48+cPMOHwMbS1FTJoaspB/bwYqHE6w4cP3" + "xn4+DgYWltzgAGqywCMNbABQBdsAQggJmAsX/3+/esxkPNAoX7jxgNQomKYMWMtw6" + "5dRxkuXLjGMHHiEobv338x3Lv3DEhDLAO6+hjQq1cBAohRWdkOqOGvOwcHz2Z1dU1" + "WcXEJBgkJYYbbtx+AExIogH/9+s2gra0KDOgPwLTxmOHKlfO/v3z55AtM0jsBAggY" + "jfKg0Lz769eP958/f7FnZ2djAyYUBhERQWBUcgLDhItBWFiY4f37j8AYeshw/frVr" + "1++fCwFal4O8iZAAIENAKdpRoZTwLg99/Llc8VPnz7JffnyFWQwMAa+Mdy/fw+YmW" + "4w3Lp1/eiPH19zgJqXwfIQQACBvQDNiaBsC/K/IDCQNICKfNjYWIVAYQNMH++AIb4" + "FGPrg7IycgwECDADIUZC5UWvTuwAAAABJRU5ErkJggg=="; private static String stainedString = "iVBORw0KGgoAAAANSUhEUgAAA" + "BAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEw" + "EAmpwYAAAAB3RJTUUH1wMbBRAgdDDcCwAAAyVJREFUOMtdk0tsVGUYhp/vP2eml9P" + "LzLRAq4MUqKVyS2tIkBZKCCZl0bIgLly68xLcSECjBkx04cIlCy8bFgYXspKaiqZN" + "jGkXalACaGPaUrHTmSntdJzpdOac8//nd6FtiO/++fK+yfPJlXQj/0vSGNNrTDQCp" + "AAibEEhY0rJDLAGYK0FwH2ctNae0Vq/29a+bXBH127qm1oACKoV8g/m387lc1MK+U" + "Ap+WaTcR+DzzuO++Gzp4e9/Wdf4MnBU8SaWxDHwdSq5H+a5u6Xnw/e/nb8RrVafUu" + "EqwByJd2ItXZYKXXzudFzsf3nXkS5MUzgbzWLjMGtq0eUYn5inMlrn4ZV3x91RG45" + "J5vdliiKPnv6cF9Xz/NnsFFE59HjlB4uUJz/g2phhfVclm2H+om3JlBKIdWKk5mf3" + "WPhhrLWHmj0vIHte3soZ5dInziN6zXRefQ4bn0DpaVF0seGaO3eR/OuPTz6/S4mDP" + "EaGge05YAz1OS8mki1nUh0PsFGYYXSg1m2H+on1tRMa1c3rTt30XawD4CJCy9zZ/w" + "rVrNLhGGIMTrvikhKRKisrqADn7XMX1RW8gy8+T7xRJJk70GsMUxcfIVfvhvHcVyU" + "o4jFY1CrplwRwfdrrGUzRMagwxCA0sIc7X1HAAjLJf7OZbHWIiIoUVseKGttIfB9N" + "kolysUi9Z7HqUvv0d53BGsMQXGNeCLJyNVr7D3cjzEaEUGHGm0pKGvtmA41URTR4H" + "mMfvQxHceGAJi89Bpfv/4S1XyWulQ7Zz+5Trq7B601WodEMKaA+0HgTxtjcGMxlu/" + "8jDWGHy6/wczU9yzO/Mbk5QuE5RKr934l9H2iKGIj1NPAfXmnIw4w7LruzY70zlhz" + "WzstOzpYnpsF+K9uQOe+Z1hfeUQxnyPz50JY0dGoCLecoSYHYE5rs1bbqJx0HSeul" + "MJLthFvaKCu0cNLpKiWihSWMuQyi5WKNhdF+AJg8wAi8mOg9e1ysbi7Vi49FVTWEc" + "CvrFNYWiS/+JDs8vJUzUTnRbi+qfnmhH+djyxAMrC21xVGXKVSUWSpWVuwljERtt5" + "5M/8AP9V9H5Qdd08AAAAASUVORK5CYII="; private static Image clean = Base64.decodeBase64EncodedImage(cleanString); private static Image stain = Base64.decodeBase64EncodedImage(stainedString); private List<ATabbedPaneListener> listeners; /** * Constructor. * */ public ATabbedPane() { super(SwingConstants.TOP); listeners = new LinkedList<ATabbedPaneListener>(); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int tabNumber = getUI().tabForCoordinate(ATabbedPane.this, e.getX(), e.getY()); if (tabNumber < 0) return; Rectangle rect = ((ACloseTabIcon) ATabbedPane.this .getIconAt(tabNumber)).getBounds(); if (rect.contains(e.getX(), e.getY())) { ATabbedPane.this.selectAndCloseTab(tabNumber); } } }); } /** * Returns the title of the tab currently being selected or * the empty string, if no tab is selected. * * @return the title of the tab currently being selected */ public String getCurrentTitle() { if (getSelectedIndex() == -1) { return ""; } return getTitleAt(getSelectedIndex()); } /** * Adds an <tt>ATabbedPaneListener</tt> whose responsibility is to * decide whether a tab will actually be closed on user demand. * * @param listener an <tt>ATabbedPaneListener</tt> */ public void addListener(ATabbedPaneListener listener) { listeners.add(listener); } private String generateUniqueTabName(String tabName) { Set<String> titles = new HashSet<String>(); for (int i = 0; i < getTabCount(); i++) { titles.add(getTitleAt(i)); } if (!titles.contains(tabName)) { return tabName; } int i = 1; while (true) { String trial = tabName + "-" + i; if (!titles.contains(trial)) { return trial; } i++; } } /** * Sets the name of the currently selected tab to the given * <tt>title</tt> or to <tt>title</tt> with an integer number appended, * as described in the class comment: {@linkplain ATabbedPane}. * * @param title the new name of the currently selected tab */ public void setTabTitle(String title) { int i = getSelectedIndex(); setTitleAt(i, ""); title = generateUniqueTabName(title); setTitleAt(i, title); } /** * Adds a tab to this <tt>ATabbedPane</tt> and assigns the given * <tt>title</tt> to it, which may be changed as described in the * class comment ({@linkplain ATabbedPane}) in order to get a unique * title. * * @param tab the tab to be added * @param title the title of the tab to be added * @return the unique name of the tab after it has been added */ public String addTab(Component tab, String title) { title = generateUniqueTabName(title); ACloseTabIcon icon = new ACloseTabIcon(tab, this); addTab(title, icon, tab); setSelectedIndex(getTabCount() - 1); return title; } /** * Adds a tab to this <tt>ATabbedPane</tt> and assigns the given * <tt>title</tt> to it, which may be changed as described in the * class comment ({@linkplain ATabbedPane}) in order to get a unique * title. * * @param tab the tab to be added * @param title the title of the tab to be added * @param closeIcon the icon for closing the tab * @return the unique name of the tab after it has been added */ public String addTab(Component tab, String title, ImageIcon closeIcon) { title = generateUniqueTabName(title); ACloseTabIcon icon = new ACloseTabIcon(tab, this, closeIcon); addTab(title, icon, tab); setSelectedIndex(getTabCount() - 1); return title; } /** * Removes the currently selected tab. If <tt>oneOpen</tt> is true * and there is only one tab, it will not be removed. * * @param oneOpen * flag denoting if at least one tab must stay open * @return flag denoting if the current tab has in fact been removed */ public boolean removeCurrentTab(boolean oneOpen) { if (getTabCount() == 0) { return false; } if (oneOpen && getTabCount() == 1) { return false; } int number = getSelectedIndex(); if (number != -1) { remove(number); return true; } return false; } protected void fireCurrentTabClosing() { for (ATabbedPaneListener listener : listeners) { listener.currentTabClosing(); } } private void selectAndCloseTab(int number) { setSelectedIndex(number); if (getTabCount() > 1) { fireCurrentTabClosing(); } } private class ACloseTabIcon implements Icon, StainedListener { private int x_pos; private int y_pos; private Image image; /** * Creates a new <tt>CloseTabIcon</tt> for a tab in a * {@linkplain ATabbedPane}. * * @param tab * a tab * @param pane * the tabbed pane * @param icon */ public ACloseTabIcon(Component tab, ATabbedPane pane, ImageIcon icon) { image = icon.getImage(); } /** * Creates a new <tt>CloseTabIcon</tt> for a possibly * &quot;stainable&quot; tab in a {@linkplain ATabbedPane}. If the * <tt>tab</tt>'s class implements {@linkplain Stainable}, the * <tt>CloseTabIcon</tt> registers as a {@linkplain StainedListener} * and will reflect the stained status of the tab by the color of the * icon. * * @param tab * a tab * @param pane * the tabbed pane */ public ACloseTabIcon(Component tab, ATabbedPane pane) { if (tab instanceof Stainable) { ((Stainable) tab).addStainedListener(this); } image = clean; } /** * Changes the icon so it reflects the state of being * stained or clean. * * @see net.sf.sdedit.ui.components.StainedListener#stainedStatusChanged(boolean) */ public void stainedStatusChanged(boolean stained) { image = stained ? stain : clean; repaint(); } /** * @see javax.swing.Icon#paintIcon(java.awt.Component, * java.awt.Graphics, int, int) */ public void paintIcon(Component c, Graphics g, int x, int y) { g.drawImage(image, x, y, c); this.x_pos = x; this.y_pos = y; } /** * @see javax.swing.Icon#getIconWidth() */ public int getIconWidth() { return image.getWidth(null); } /** * @see javax.swing.Icon#getIconHeight() */ public int getIconHeight() { return image.getHeight(null); } /** * Returns a <tt>Rectangle</tt> where this icon is currently being * displayed. * * @return a <tt>Rectangle</tt> where this icon is currently being * displayed */ public Rectangle getBounds() { return new Rectangle(x_pos, y_pos, getIconWidth(), getIconHeight()); } } }
[ "serbanescu.vlad.nicolae@gmail.com" ]
serbanescu.vlad.nicolae@gmail.com
cd58689675f06522bf9dabacab88251e23b700af
7f4efb192bf5b85a5db1381f243060f5736c7eee
/src/main/java/com/petziferum/backend/model/tree/TreeNode.java
6fd6c5e070e4949f47195324b93e358776d709a9
[]
no_license
petziferum/backend
38c4e9467e131d10ccf9f1ae38cffad8ad2daa28
1527bb55eed6a87a807af8d1c8d7011de5eac0a3
refs/heads/master
2022-12-22T15:15:18.165367
2022-01-24T21:08:30
2022-01-24T21:08:30
240,682,245
0
0
null
null
null
null
UTF-8
Java
false
false
570
java
package com.petziferum.backend.model.tree; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.List; @Document(collection = "tree") public class TreeNode { @Id private String id; private List<Answer> answers; private List<Question> questions; public TreeNode() {} public TreeNode addQuestion(Question q) { this.questions.add(q); return this; } public TreeNode addAnswer(Answer a) { this.answers.add(a); return this; } }
[ "daboarderpjb@gmail.com" ]
daboarderpjb@gmail.com
9d1762f64fa742c0f0a7624a3a7470c1f16c29ed
629e42efa87f5539ff8731564a9cbf89190aad4a
/codes/CollectRefactorClones/edu/pku/sei/codeclone/predictor/StartFeature.java
6b4123f1685d7a85d8aec7c5211dd40cced1faf9
[]
no_license
soniapku/CREC
a68d0b6b02ed4ef2b120fd0c768045424069e726
21d43dd760f453b148134bd526d71f00ad7d3b5e
refs/heads/master
2020-03-23T04:28:06.058813
2018-08-17T13:17:08
2018-08-17T13:17:08
141,085,296
0
4
null
null
null
null
UTF-8
Java
false
false
10,042
java
package edu.pku.sei.codeclone.predictor; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.List; import thirdparty.similarity.Levenshtein; import edu.pku.sei.codeclone.predictor.code.CodeStructure; import edu.pku.sei.codeclone.predictor.code.CodeVisitor; import edu.pku.sei.codeclone.predictor.code.JavaClass; import edu.pku.sei.codeclone.predictor.code.Method; import edu.pku.sei.codeclone.predictor.code.MethodVisitor; import japa.parser.JavaParser; import japa.parser.ParseException; import japa.parser.ast.CompilationUnit; import japa.parser.ast.body.MethodDeclaration; import japa.parser.ast.body.Parameter; public class StartFeature { StartFragment frag; Method startMethod; Method targetMethod; List<String> targetParameters; CompilationUnit startCu; List<JavaClass> classes; private int numCall; private int numFieldRef; private int numLibCall; private int numLocalCall; private int numParaRef; private int lineNum; private boolean isTest; private double fileSimi; private double methodSimi; private double maxSimi; private double sumSimi; private boolean postfix; private int numOtherCall; private boolean local; private double maskFileSimi; private History his; private boolean localMethod; public StartFeature(StartFragment fragment) { // TODO Auto-generated constructor stub this.frag = fragment; this.his = fragment.getHis(); prepareForFeatures(); getCodeFeatures(); getTargetFeatures(); } private void prepareForFeatures() { System.out.println("preparing for features"); // TODO Auto-generated method stub String versionID = this.frag.getVersionID() + ""; String versionPath = this.frag.getFilePath(); versionPath = versionPath.substring(0, versionPath.indexOf(versionID)+versionID.length()); try{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(versionPath+"/projStructure.psj"))); this.classes = (List<JavaClass>)ois.readObject(); ois.close(); File startFile = new File(this.frag.getFilePath()); File targetFile = new File(this.frag.getTargetFilePath()); this.startMethod = getMethod(startFile, this.frag.getStart(), this.frag.getEnd()); this.targetMethod = getMethod(targetFile, this.frag.getTargetStart(), this.frag.getTargetEnd()); }catch(IOException e){ e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Method getMethod(File file, int start, int end) { try { CompilationUnit cu = JavaParser.parse(file); MethodVisitor mv = new MethodVisitor(start, end); mv.visit(cu, null); return mv.getMethod(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Error e){ System.err.println("getMethod1:" + file); e.printStackTrace(); } System.err.println("getMethod2:" + file.getAbsolutePath() + ":"+start); return null; } private void getTargetFeatures() { // TODO Auto-generated method stub String thisFileName = this.frag.getFilePath().substring(this.frag.getFilePath().lastIndexOf('/')+1); String thisMethodName = ""; List<String> thisParaNames = new ArrayList<String>(); if(this.startMethod!=null){ thisMethodName = this.startMethod.getName(); for(String p : this.startMethod.getParameters()){ thisParaNames.add(p); } }else{ System.err.println("target" + this.frag.getFilePath()); System.err.println("target" + this.frag.getStart() + this.frag.getEnd()); } String targetFileName = this.frag.getTargetFilePath().substring(this.frag.getTargetFilePath().lastIndexOf('/')+1); Method targetMethod = this.targetMethod; String targetMethodName = ""; List<String> targetParaNames = new ArrayList<String>(); if(targetMethod!=null){ targetMethodName = targetMethod.getName(); for(String p : targetMethod.getParameters()){ targetParaNames.add(p); } } this.fileSimi = simi(thisFileName, targetFileName); this.methodSimi = simi(thisMethodName, targetMethodName); this.maxSimi = maxsimi(thisParaNames, targetParaNames); this.sumSimi = sumsimi(thisParaNames, targetParaNames); this.postfix = prefix(thisMethodName).equals(prefix(targetMethodName)); this.local = this.frag.getFilePath().equals(this.frag.getTargetFilePath()); this.localMethod = this.local && thisMethodName.equals(targetMethodName); this.maskFileSimi = this.local?0:this.fileSimi; } private String prefix(String thisMethodName) { // TODO Auto-generated method stub if(thisMethodName.equals("")){ return ""; } int index = 0; for(int i = thisMethodName.length()-1; i>=0; i--){ if(Character.isDigit(thisMethodName.charAt(i))){ }else{ index = i; } } return thisMethodName.substring(0, index + 1); } private double maxsimi(List<String> thisParaNames, List<String> targetParaNames) { // TODO Auto-generated method stub if(thisParaNames.size()==0&&targetParaNames.size()==0){ return 1.0; } double maxSimi = 0.0; for(String str1:thisParaNames){ for(String str2:targetParaNames){ double s = simi(str1, str2); if(s>maxSimi){ maxSimi = s; } } } return maxSimi; } private double sumsimi(List<String> thisParaNames, List<String> targetParaNames) { // TODO Auto-generated method stub if(thisParaNames.size()==0&&targetParaNames.size()==0){ return 1.0; } double sumSimi = 0.0; for(String str1:thisParaNames){ for(String str2:targetParaNames){ double s = simi(str1, str2); sumSimi += s; } } return sumSimi; } private double simi(String str1, String str2) { // TODO Auto-generated method stub Levenshtein l = new Levenshtein(); return l.getSimilarity(str1, str2); } private void getCodeFeatures() { System.out.println("Getting Code Features"); try { CompilationUnit cu = JavaParser.parse(new File(this.frag.getFilePath())); String packageName = ""; if(cu.getPackage()!=null){ packageName = cu.getPackage().getName().toString(); }else{ packageName = "$default"; } CodeVisitor cv = new CodeVisitor(this.frag.getStart(), this.frag.getEnd()); CodeStructure cs = new CodeStructure(this.classes, this.frag.getFilePath(), packageName); cv.visit(cu, cs); this.numCall = cs.numCall; this.numFieldRef = cs.numFieldRef; this.numLibCall = cs.numLibCall; this.numLocalCall = cs.numLocalCall; this.numParaRef = cs.numParaRef; this.numOtherCall = cs.numCall - cs.numLibCall - cs.numLocalCall; this.lineNum = this.frag.getEnd() - this.frag.getStart(); this.isTest = this.frag.getFilePath().indexOf("test")!=-1; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch(Error e){ System.err.println("here:" + this.frag.getFilePath()); e.printStackTrace(); } } public String toString(){ String featureString = ""; featureString += this.his.length + ","; featureString += this.his.fileLength + ","; featureString += this.his.getChange() + ","; featureString += this.his.getFilesChange() + ","; featureString += this.his.getRecentChange() + ","; featureString += this.his.getRecentFileChange() + ","; featureString += this.isTest + ","; featureString += this.lineNum + ","; featureString += this.numCall + ","; featureString += this.numLibCall + ","; featureString += this.numLocalCall + ","; featureString += this.numOtherCall + ","; featureString += this.numFieldRef + ","; featureString += this.numParaRef + ","; featureString += this.fileSimi + ","; featureString += this.methodSimi + ","; featureString += this.maxSimi + ","; featureString += this.sumSimi + ","; featureString += this.maskFileSimi + ","; featureString += this.local + ","; // featureString += this.localMethod + ","; featureString += this.postfix ; return featureString; } private String getSource(StartFragment fragment) { // TODO Auto-generated method stub String filePath = fragment.getFilePath(); int start = fragment.getStart(); int end = fragment.getEnd(); filePath = ChangeGenerator.transitPath(filePath); String fragpart = ""; try { BufferedReader in = new BufferedReader(new FileReader(filePath)); int linePointer = 0; for(String line = in.readLine(); line!=null; line = in.readLine()){ if(linePointer>=start&&linePointer<=end){ fragpart+=line; fragpart+="\n"; } linePointer++; } in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return fragpart; } }
[ "sonia@pku.edu.cn" ]
sonia@pku.edu.cn
ab3c75c2c75362228034046ba47d94166658af9b
00b7d1dcbaf27e5624669364c63106f48151399f
/commodity_order/src/main/java/com/commodity/entity/dto/MHaisou.java
a1e27481437cbdeb4cd646d3880bf631e9d748e5
[]
no_license
wangdl000/study
6a431cac415642c2c71457d7c2f63e4acfe29ee6
484c65c2e771f87877c290dfa6fe604f27255184
refs/heads/master
2022-11-17T10:22:17.322933
2021-02-17T02:47:28
2021-02-17T02:47:28
71,193,978
2
0
null
2022-11-16T10:54:14
2016-10-18T00:50:38
HTML
UTF-8
Java
false
false
1,491
java
package com.commodity.entity.dto; import java.util.Date; public class MHaisou extends MHaisouKey { private String haisouName; private String haisouStatusUrl; private Date koushinBi; private String koushinUserid; private Date tourokuBi; private String tourokuUserid; public String getHaisouName() { return haisouName; } public void setHaisouName(String haisouName) { this.haisouName = haisouName == null ? null : haisouName.trim(); } public String getHaisouStatusUrl() { return haisouStatusUrl; } public void setHaisouStatusUrl(String haisouStatusUrl) { this.haisouStatusUrl = haisouStatusUrl == null ? null : haisouStatusUrl.trim(); } public Date getKoushinBi() { return koushinBi; } public void setKoushinBi(Date koushinBi) { this.koushinBi = koushinBi; } public String getKoushinUserid() { return koushinUserid; } public void setKoushinUserid(String koushinUserid) { this.koushinUserid = koushinUserid == null ? null : koushinUserid.trim(); } public Date getTourokuBi() { return tourokuBi; } public void setTourokuBi(Date tourokuBi) { this.tourokuBi = tourokuBi; } public String getTourokuUserid() { return tourokuUserid; } public void setTourokuUserid(String tourokuUserid) { this.tourokuUserid = tourokuUserid == null ? null : tourokuUserid.trim(); } }
[ "wangdl000@yahoo.co.jp" ]
wangdl000@yahoo.co.jp
8fb29794677aaf4dd33427eb34256aba04ee3e32
67ba70ccc6d071cfec004f757499ec8d7d33d2af
/store/src/com/lianwei/store/web/servlet/CartServlet.java
4f00dce209e09f650cc7b9ab74f6eb935d4b7cbf
[]
no_license
yinshuaigelaile/TEST
8fd937428abe09492359b6502dffb6b09270fc86
697511f25164e15f650d4dedd0744656a412195b
refs/heads/master
2021-01-16T14:13:45.929103
2020-02-26T05:01:02
2020-02-26T05:01:02
243,149,196
0
0
null
null
null
null
UTF-8
Java
false
false
1,822
java
package com.lianwei.store.web.servlet; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.lianwei.store.domain.Cart; import com.lianwei.store.domain.CartItem; import com.lianwei.store.domain.Product; import com.lianwei.store.service.ProductService; import com.lianwei.store.service.serviceImpl.ProductServiceImpl; import com.lianwei.store.web.base.BaseServlet; @WebServlet("/CartServlet") public class CartServlet extends BaseServlet{ public String execute(HttpServletRequest req, HttpServletResponse resp) throws Exception { Cart cart = (Cart)req.getSession().getAttribute("cart"); if (null==cart) { cart = new Cart(); req.getSession().setAttribute("cart", cart); } String pid = req.getParameter("pid"); int num = Integer.parseInt(req.getParameter("quantity")); ProductService productService = new ProductServiceImpl(); Product product = productService.findProductByPid(pid); CartItem cartItem = new CartItem(); cartItem.setNum(num); cartItem.setProduct(product); cart.addCartItemToCart(cartItem); System.out.println(cart); resp.sendRedirect("/store/jsp/cart.jsp"); return null; } public String clearCartItem(HttpServletRequest req, HttpServletResponse resp) throws Exception { //获取pid,获取购物车,根据pid移除购物车购物项 String pid = req.getParameter("pid"); Cart cart = (Cart)req.getSession().getAttribute("cart"); cart.clearCartItemFromCart(pid); resp.sendRedirect("/store/jsp/cart.jsp"); return null; } public String clearCart(HttpServletRequest req, HttpServletResponse resp) throws Exception { Cart cart = (Cart)req.getSession().getAttribute("cart"); cart.clearCart(); resp.sendRedirect("/store/jsp/cart.jsp"); return null; } }
[ "2632855426@qq.com" ]
2632855426@qq.com
1db9177f964a4167acc42f6411418ced7d7d61b3
1438e1389f9fef760a389982140911c4e748cc63
/inSquareAndroid/app/src/main/java/com/nsqre/insquare/Utilities/ImageConverter.java
82e4999664c5a2a1f5e4f7a029d1e30e72fc4df1
[ "MIT" ]
permissive
regini/inSquare
26366fb759eb2caa84c5f1ccfb48706c1c3346d4
2f2f39fad110949788ff35c159ebe708b4377e41
refs/heads/master
2021-01-14T13:50:28.841487
2016-09-05T16:05:25
2016-09-05T16:05:25
47,851,734
7
4
null
2016-03-14T12:03:51
2015-12-11T21:23:32
Swift
UTF-8
Java
false
false
1,494
java
package com.nsqre.insquare.Utilities; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; /** * ImageConverter provides a static method that can manipulate a Bitmap image */ public class ImageConverter { /** * Modifies the image passed as parameter to create a new image with rounded corners * @param bitmap The input you want to manipulate * @param pixels The dimension of the rounded corner image returned * @return a bitmap based on the input, but with rounded corners */ public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); final float roundPx = pixels; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } }
[ "Emanuele Grassi" ]
Emanuele Grassi
31d3e8c4b388bebdd29a9263f34288313e665b57
7585acd98427dc9324dae8458bf07550bf58c49d
/user_service/user-server/src/main/java/com/yzeng/userserver/VO/UserVO.java
64518dcd7fcc850eb48519fec2b157ee97c01442
[]
no_license
yzengchn/SpringCloud-scaffolding
96958829b80f212d3b24dcc32ac39dc99f25551b
4fa07d42e26560daa78443e62062e372c3908c9b
refs/heads/master
2020-04-10T02:57:11.596494
2019-01-03T07:37:56
2019-01-03T07:37:56
160,756,675
1
0
null
null
null
null
UTF-8
Java
false
false
915
java
package com.yzeng.userserver.VO; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; /** * <一句话功能简述> * @author <a href="http://www.yzblog.xyz">yzblog</a> * @version [1.0, 2018年12月12日] * @Email yzengchn@163.com * @since [产品/模块版本] */ public class UserVO { @NotEmpty(message="用户名不能为空") private String name; @NotEmpty(message="密码不能为空") private String password; @NotNull(message="年龄不能为空") private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
[ "yzengchn@google.com" ]
yzengchn@google.com
8695b559f6d566f195f70287a1c1038f0b0d66ba
6c6886879c0ec37b9cd5dc23b059dab77c0f5740
/src/dna/depr/metrics/similarityMeasures/MeasuresUndirectedIntWeighted.java
4c14850b5767eb88aa720448f0003c00156a8d82
[]
no_license
Lyfexu/MyDNA
edf478a88e4dc39ae2d18298878676519cdaa3ff
df91e84006ea376ffb1093a73e3aec47abb26094
refs/heads/master
2016-09-06T14:07:21.837451
2015-02-13T01:05:44
2015-02-13T01:05:44
30,733,749
0
0
null
null
null
null
UTF-8
Java
false
false
9,028
java
package dna.depr.metrics.similarityMeasures; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import dna.depr.metrics.MetricOld; import dna.graph.Graph; import dna.graph.IElement; import dna.graph.edges.UndirectedWeightedEdge; import dna.graph.nodes.Node; import dna.graph.nodes.UndirectedNode; import dna.graph.weights.IntWeight; import dna.metrics.IMetric; import dna.series.data.BinnedDistributionLong; import dna.series.data.NodeNodeValueList; import dna.series.data.NodeValueList; import dna.series.data.Value; import dna.updates.batch.Batch; public abstract class MeasuresUndirectedIntWeighted extends MetricOld { /** Contains the result for each similarity measure. */ protected Matrix result; /** Contains the result for each matching measure */ protected Matrix matching; /** Binned Distribution */ protected BinnedDistributionLong binnedDistribution; /** Average per Node Distribution */ protected BinnedDistributionLong binnedDistributionEveryNodeToOtherNodes; /** * Initializes {@link UndirectedIntWeightedEdge} measure. * * @param name * The name of the metric * @param applicationType */ public MeasuresUndirectedIntWeighted(String name, ApplicationType applicationType) { super(name, applicationType, IMetric.MetricType.exact); } /** * Decreases the matching between each pair of the given nodes. * * @param node * * @see #decreaseMatching(UndirectedNode, UndirectedNode) */ protected void decreaseMatching(HashMap<UndirectedNode, Integer> map, UndirectedNode node) { for (Entry<UndirectedNode, Integer> node1 : map.entrySet()) { this.decreaseMatching(node1.getKey(), node1.getValue(), node, map.get(node)); } } /** * Decreases the matching between the given nodes by the min value. */ private void decreaseMatching(UndirectedNode node1, Integer value1, UndirectedNode node2, Integer value2) { this.matching.put(node1, node2, this.matching.get(node1, node2) - Math.min(value1, value2)); } /** * Decrease the matching measure if a node is to be removed. * * @param neighborNodes * The neighbors of the node to be removed. * @see #decreaseMatching(Entry, Entry) */ protected void decreaseMatchingNodeRemove( HashMap<UndirectedNode, Integer> map) { for (Entry<UndirectedNode, Integer> node1 : map.entrySet()) for (Entry<UndirectedNode, Integer> node2 : map.entrySet()) { if (node1.getKey().getIndex() > node2.getKey().getIndex()) continue; decreaseMatching(node1.getKey(), node1.getValue(), node2.getKey(), node2.getValue()); } } /** * Sums the values of a Map. * * @param neighbors * A {@link Map} containing the neighbors with their frequency. * @return The sums of values. */ protected double getMapValueSum(HashMap<UndirectedNode, Integer> neighbors) { double sum = 0.0; for (Entry<UndirectedNode, Integer> e : neighbors.entrySet()) sum = sum + e.getValue(); return sum; } /** * Computes the intersection between the neighbors of two nodes. * * @param neighbors1 * A {@link Map} includes the neighbors of the first node with * their frequency. * @param neighbors2 * A {@link Map} includes the neighbors of the second node with * their frequency. * @return A {@link Map} containing the intersection of neighbors1 and * neighbors2. */ protected HashMap<UndirectedNode, Integer> getMatching( HashMap<UndirectedNode, Integer> neighbors1, HashMap<UndirectedNode, Integer> neighbors2) { final HashMap<UndirectedNode, Integer> neighbors = new HashMap<UndirectedNode, Integer>(); for (Entry<UndirectedNode, Integer> e : neighbors1.entrySet()) if (neighbors2.containsKey(e.getKey())) if (neighbors2.get(e.getKey()) <= e.getValue()) neighbors.put(e.getKey(), neighbors2.get(e.getKey())); else neighbors.put(e.getKey(), e.getValue()); return neighbors; } /** * @param node * The {@link Node} which neighbors are wanted. * @return A {@link Map} containing all neighbors of given node with their * frequency. */ protected HashMap<UndirectedNode, Integer> getNeighborNodes( UndirectedNode node) { final HashMap<UndirectedNode, Integer> neighbors = new HashMap<UndirectedNode, Integer>(); UndirectedWeightedEdge edge; // iterate over all edges and ... for (IElement iEdge : node.getEdges()) { edge = (UndirectedWeightedEdge) iEdge; // ... add the node which is not the given one to the neighbors if (edge.getNode1().equals(node)) neighbors.put(edge.getNode2(), ((IntWeight) edge.getWeight()).getWeight()); else neighbors.put(edge.getNode1(), ((IntWeight) edge.getWeight()).getWeight()); } return neighbors; } @Override public NodeNodeValueList[] getNodeNodeValueLists() { // final int numberOfNodesInGraph = this.g.getNodeCount(); // final NodeNodeValueList nodeNodeValueList = new NodeNodeValueList( // "DiceUndirectedWeighted", numberOfNodesInGraph); // Double dice12; // int node1Index, node2Index; // for (IElement nodeOne : this.g.getNodes()) { // UndirectedNode node1 = (UndirectedNode) nodeOne; // node1Index = node1.getIndex(); // for (IElement nodeTwo : this.g.getNodes()) { // UndirectedNode node2 = (UndirectedNode) nodeTwo; // node2Index = node2.getIndex(); // dice12 = this.diceSimilarity.get(node1, node2); // dice12 = dice12 == null ? 0.0 : dice12; // nodeNodeValueList.setValue(node1Index, node2Index, dice12); // } // } return new NodeNodeValueList[] {}; } @Override public NodeValueList[] getNodeValueLists() { return new NodeValueList[] {}; } @Override public Value[] getValues() { Value v1 = new Value("avarage", this.binnedDistribution.computeAverage()); return new Value[] { v1 }; } /** * Increases the matching between each pair of the given nodes. * * @param node * * @see #increaseMatching(UndirectedNode, UndirectedNode) */ protected void increaseMatching(HashMap<UndirectedNode, Integer> map, UndirectedNode node) { for (Entry<UndirectedNode, Integer> node1 : map.entrySet()) { this.increaseMatching(node1.getKey(), node1.getValue(), node, map.get(node)); } } /** * Increases the matching between the given nodes by min value. */ protected void increaseMatching(UndirectedNode node1, Integer value1, UndirectedNode node2, Integer value2) { Double matchingG = this.matching.get(node1, node2); this.matching.put( node1, node2, matchingG == null ? Math.min(value1, value2) : matchingG + Math.min(value1, value2)); } @Override public boolean isApplicable(Batch b) { return UndirectedNode.class.isAssignableFrom(b.getGraphDatastructures() .getNodeType()); } @Override public boolean isApplicable(Graph g) { return UndirectedNode.class.isAssignableFrom(g.getGraphDatastructures() .getNodeType()); } /** * Update method that will be replaced by the respective specific similarity measure method. */ protected void update(UndirectedNode node1, UndirectedNode undirected2) { } protected void update(UndirectedWeightedEdge edge, HashMap<UndirectedNode, Integer> neighborsNode1, HashMap<UndirectedNode, Integer> neighborsNode2) { this.updateDirectNeighborsMeasure(neighborsNode1, edge.getNode2()); this.updateDirectNeighborsMeasure(neighborsNode2, edge.getNode1()); this.updateMeasureMatching(edge.getNode1(), edge.getNode2()); this.updateMeasureMatching(edge.getNode2(), edge.getNode1()); } /** * Calculates the new similarity measure for each node. * * @param undirectedNode */ protected void updateDirectNeighborsMeasure( HashMap<UndirectedNode, Integer> map, UndirectedNode node) { for (UndirectedNode node1 : map.keySet()) for (UndirectedNode node2 : map.keySet()) { if (node1.getIndex() > node2.getIndex()) continue; this.update(node1, node2); } } /** * Update the similarity measure in the matching range. */ protected void updateMeasureMatching(UndirectedNode node1, UndirectedNode node2) { for (UndirectedNode undirected1 : this.getNeighborNodes(node1).keySet()) if (!undirected1.equals(node2)) for (UndirectedNode undirected2 : this.getNeighborNodes( undirected1).keySet()) this.update(node1, undirected2); } /** * Update the similarity measure if a node is to be removed * * @param nodeToRemove */ protected void updateNodeRemoveMeasure(UndirectedNode nodeToRemove) { for (UndirectedNode undirected1 : this.getNeighborNodes(nodeToRemove) .keySet()) for (UndirectedNode undirected2 : this .getNeighborNodes(undirected1).keySet()) if (!undirected2.equals(nodeToRemove)) for (UndirectedNode undirected3 : this.getNeighborNodes( undirected2).keySet()) if (!undirected3.equals(undirected1) && !undirected3.equals(nodeToRemove)) { update(undirected1, undirected3); } } }
[ "lyfexu@googlemail.com" ]
lyfexu@googlemail.com
aadeb0ba672db22928d505582ce343a0984034eb
56d1c5242e970ca0d257801d4e627e2ea14c8aeb
/src/com/csms/leetcode/number/other/other/LeetcodeMST_04_09.java
92758f2a94cd809f247db1703765d1197b6e03bf
[]
no_license
dai-zi/leetcode
e002b41f51f1dbd5c960e79624e8ce14ac765802
37747c2272f0fb7184b0e83f052c3943c066abb7
refs/heads/master
2022-12-14T11:20:07.816922
2020-07-24T03:37:51
2020-07-24T03:37:51
282,111,073
0
0
null
null
null
null
UTF-8
Java
false
false
1,782
java
package com.csms.leetcode.number.other.other; import com.csms.leetcode.common.TreeNode; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; //二叉搜索树序列 //困难 public class LeetcodeMST_04_09 { public static List<List<Integer>> BSTSequences(TreeNode root) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(root != null) { List<Integer> single = new ArrayList<Integer>(); List<TreeNode> free = new LinkedList<TreeNode>(); single.add(root.val); addList(root, single, free, res); } if(res.size() == 0) { res.add(new ArrayList<Integer>()); } return res; } private static void addList(TreeNode root, List<Integer> single, List<TreeNode> free, List<List<Integer>> res) { if(root == null) { return; } if(root.left != null) { free.add(root.left); } if(root.right != null) { free.add(root.right); } if(free.size() == 0) { List<Integer> one = new ArrayList<Integer>(); for (int i = 0; i < single.size(); i ++) { one.add(single.get(i)); } res.add(one); } for (int i = 0; i < free.size(); i ++) { single.add(free.get(i).val); TreeNode remove = free.remove(i); addList(remove, single, free, res); free.add(i, remove); single.remove(single.size() - 1); } if(root.right != null) { free.remove(root.right); } if(root.left != null) { free.remove(root.left); } } public static void main(String[] args) { } }
[ "liuxiaotongdaizi@sina.com" ]
liuxiaotongdaizi@sina.com
2159f225b4a7bd0bc5d83c1ccc19096f9426d36e
01ec337dddfc2747758f09ed6aad64bcd1060576
/app/src/main/java/com/tencent/temp/SyncMessenger.java
f6e0b045616e6011f9b2c74996f986eb3ebd846d
[]
no_license
garfieldyf/AndroidTest
c95d880d3bb698d0c7b899319536f04ebf8d77da
be91a942c7ba685947a313c6a68c9cfaee3835af
refs/heads/master
2021-08-08T06:44:56.823036
2021-06-24T14:20:18
2021-06-24T14:20:18
128,601,682
1
0
null
null
null
null
UTF-8
Java
false
false
10,195
java
package com.tencent.temp; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.ext.util.DebugUtils; import android.ext.util.Pools; import android.ext.util.Pools.Pool; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.util.Log; /** * Class SyncMessenger * @author Garfield */ public class SyncMessenger implements ServiceConnection { private Messenger mService; private final Intent mIntent; private final Context mContext; /** * Constructor * @param context The <tt>Context</tt>. * @param service The service <tt>Intent</tt>. * @see #SyncMessenger(Context, String, String) */ public SyncMessenger(Context context, Intent service) { mIntent = service; mContext = context.getApplicationContext(); } /** * Constructor * @param context The <tt>Context</tt>. * @param packageName The service package name. * @param className The service fully qualified class name. * @see #SyncMessenger(Context, Intent) */ public SyncMessenger(Context context, String packageName, String className) { this(context, makeService(packageName, className)); } /** * Sends a <tt>Message</tt> to the service. * @param msg The <tt>Message</tt> to send. * @return <tt>true</tt> if the message was successfully * send to the service, <tt>false</tt> otherwise. */ public boolean sendMessage(Message msg) { if (bindService()) { try { mService.send(msg); return true; } catch (RemoteException e) { Log.e(getClass().getName(), new StringBuilder("Couldn't send message - ").append(msg).toString(), e); } } return false; } /** * Sends a <tt>Message</tt> containing only the <em>what</em> value * to the service. * @param what The user-defined message code. * @return <tt>true</tt> if the message was successfully send to the * service, <tt>false</tt> otherwise. */ public final boolean sendMessage(int what) { return sendMessage(Message.obtain(null, what)); } /** * Sends a <tt>Message</tt> containing the <em>what, obj</em> * values to the service. * @param what The user-defined message code. * @param obj The <em>obj</em> value. * @return <tt>true</tt> if the message was successfully send * to the service, <tt>false</tt> otherwise. */ public final boolean sendMessage(int what, Object obj) { return sendMessage(Message.obtain(null, what, obj)); } /** * Sends a <tt>Message</tt> containing the <em>what, arg1, arg2</em> * values to the service. * @param what The user-defined message code. * @param arg1 The <em>arg1</em> value. * @param arg2 The <em>arg2</em> value. * @return <tt>true</tt> if the message was successfully send to the * service, <tt>false</tt> otherwise. */ public final boolean sendMessage(int what, int arg1, int arg2) { return sendMessage(Message.obtain(null, what, arg1, arg2)); } /** * Sends a <tt>Message</tt> containing the <em>what, arg1, arg2, obj</em> * values to the service. * @param what The user-defined message code. * @param arg1 The <em>arg1</em> value. * @param arg2 The <em>arg2</em> value. * @param obj The <em>obj</em> value. * @return <tt>true</tt> if the message was successfully send to the service, * <tt>false</tt> otherwise. */ public final boolean sendMessage(int what, int arg1, int arg2, Object obj) { return sendMessage(Message.obtain(null, what, arg1, arg2, obj)); } /** * Sends a <tt>Message</tt> to the service synchronously. <p><em>This method will * block the calling thread until the message was handled or timeout.</em></p> * @param msg The <tt>Message</tt> to send. * @param timeout The maximum time to wait in milliseconds. * @return The reply message if succeeded, or <tt>null</tt> if an error or timeout. */ public Message sendMessageSync(Message msg, long timeout) { return (bindService() ? SyncHandler.POOL.obtain().sendMessage(mService, msg, timeout) : null); } /** * Sends a <tt>Message</tt> containing only the <em>what</em> value to the service * synchronously. <p><em>This method will block the calling thread until the message * was handled or timeout.</em></p> * @param what The user-defined message code. * @param timeout The maximum time to wait in milliseconds. * @return The reply message if succeeded, or <tt>null</tt> if an error or timeout. */ public final Message sendMessageSync(int what, long timeout) { return sendMessageSync(Message.obtain(null, what), timeout); } /** * Sends a <tt>Message</tt> containing the <em>what, obj</em> values to the service * synchronously. <p><em>This method will block the calling thread until the message * was handled or timeout.</em></p> * @param what The user-defined message code. * @param obj The <em>obj</em> value. * @param timeout The maximum time to wait in milliseconds. * @return The reply message if succeeded, or <tt>null</tt> if an error or timeout. */ public final Message sendMessageSync(int what, Object obj, long timeout) { return sendMessageSync(Message.obtain(null, what, obj), timeout); } /** * Sends a <tt>Message</tt> containing the <em>what, arg1, arg2</em> values to the * service synchronously. <p><em>This method will block the calling thread until * the message was handled or timeout.</em></p> * @param what The user-defined message code. * @param arg1 The <em>arg1</em> value. * @param arg2 The <em>arg2</em> value. * @param timeout The maximum time to wait in milliseconds. * @return The reply message if succeeded, or <tt>null</tt> if an error or timeout. */ public final Message sendMessageSync(int what, int arg1, int arg2, long timeout) { return sendMessageSync(Message.obtain(null, what, arg1, arg2), timeout); } /** * Sends a <tt>Message</tt> containing the <em>what, arg1, arg2, obj</em> values to * the service synchronously. <p><em>This method will block the calling thread until * the message was handled or timeout.</em></p> * @param what The user-defined message code. * @param arg1 The <em>arg1</em> value. * @param arg2 The <em>arg2</em> value. * @param obj The <em>obj</em> value. * @param timeout The maximum time to wait in milliseconds. * @return The reply message if succeeded, or <tt>null</tt> if an error or timeout. */ public final Message sendMessageSync(int what, int arg1, int arg2, Object obj, long timeout) { return sendMessageSync(Message.obtain(null, what, arg1, arg2, obj), timeout); } /** * Disconnects the service. */ public synchronized void disconnect() { if (mService != null) { mContext.unbindService(this); mService = null; } } @Override public synchronized void onServiceDisconnected(ComponentName name) { mService = null; } @Override public synchronized void onServiceConnected(ComponentName name, IBinder service) { mService = new Messenger(service); notifyAll(); } private synchronized boolean bindService() { DebugUtils.__checkError(Looper.myLooper() == Looper.getMainLooper(), "This method can NOT be called from the UI thread"); if (mService != null) { return true; } final boolean successful = mContext.bindService(mIntent, this, Context.BIND_AUTO_CREATE); while (successful && mService == null) { try { // If the service has been started, wait // until the Messenger has been created. wait(); } catch (InterruptedException e) { // Ignored. } } return successful; } private static Intent makeService(String packageName, String className) { final Intent service = new Intent(); service.setClassName(packageName, className); return service; } /** * Nested class <tt>SyncHandler</tt> is an implementation of a {@link Handler}. */ private static final class SyncHandler extends Handler { private static final Looper sLooper; private volatile Message mResult; private final Messenger mReplier; public SyncHandler() { super(sLooper); mReplier = new Messenger(this); } @Override public void handleMessage(Message msg) { mResult = Message.obtain(msg); synchronized (mReplier) { mReplier.notify(); } } public final Message sendMessage(Messenger service, Message msg, long timeout) { final Message result; try { msg.replyTo = mReplier; synchronized (mReplier) { service.send(msg); mReplier.wait(timeout); } } catch (Throwable e) { Log.e(SyncMessenger.class.getName(), new StringBuilder("Couldn't send message synchronously - ").append(msg).toString(), e); } finally { result = mResult; mResult = null; POOL.recycle(this); } return result; } public static final Pool<SyncHandler> POOL = Pools.synchronizedPool(Pools.newPool(SyncHandler::new, 2)); static { final HandlerThread thread = new HandlerThread("SyncMessenger"); thread.start(); sLooper = thread.getLooper(); } } }
[ "yuanfengdiy@sina.com" ]
yuanfengdiy@sina.com
589d78d3ff7ecd6b18ac266084c26c825450e1a6
2b981e021e654ccdc8399930e65215edb6301f99
/book_recommender/src/main/java/rs/sbnz/book_recommender/model/enums/LengthType.java
3a97fdf4a51f5197f62a3cfdcd54a06bf181dabd
[]
no_license
milanjokanovic/SBNZ-Library-book-recommender-system
eed3a6db0c68e0cb30cfad49fc42876172cd69d7
ab05bf0ec438ffe91a4be02dfa86820e6ec46d10
refs/heads/main
2023-07-24T13:33:05.563263
2021-09-10T14:42:38
2021-09-10T14:42:38
359,193,168
0
0
null
null
null
null
UTF-8
Java
false
false
98
java
package rs.sbnz.book_recommender.model.enums; public enum LengthType { SHORT, MEDIUM, LONG }
[ "milan.jokanovic98@gmail.com" ]
milan.jokanovic98@gmail.com
7dd4128181717ee1ddf22a5cc412ada9ea1797f7
339f7a7b7e3a27a9da05f7a269c2b5b78549b97a
/yours-dev-jenkins/mvp-ms-web/src/main/java/com/hsb/mvpmsweb/model/payload/response/FollowResponse.java
764708379b102eb617a1ba124040aff87935f22c
[]
no_license
tangchaolibai/mvp
131f84784fc533b31e5f4e5220536a9dbe13c774
56a83e409a4477655e131008ebc806d51dcdb3d0
refs/heads/master
2023-04-15T03:57:12.190617
2021-04-21T13:50:38
2021-04-21T13:50:38
360,185,381
0
0
null
null
null
null
UTF-8
Java
false
false
584
java
package com.hsb.mvpmsweb.model.payload.response; import org.springframework.validation.annotation.Validated; import com.fasterxml.jackson.annotation.JsonProperty; import com.hsb.mvpmsweb.model.payload.ResponseResult; import io.swagger.annotations.ApiModel; @ApiModel(description = "This entity is used to describe a Follow Response.") @Validated public class FollowResponse { @JsonProperty("result") private ResponseResult result = null; public ResponseResult getResult() { return result; } public void setResult(ResponseResult result) { this.result = result; } }
[ "heweiqing@formssi.com" ]
heweiqing@formssi.com
affa492af0ef4c5fe4d5bd8cd7fc2218320cd601
818d134396f4339664f4db8ce714ee6c2d4ce5be
/src/techquizapp/Pojo/User.java
7ea657f701d8f98c7d5794778476b26a9993dad8
[]
no_license
Harry96444/EasyQuizApplication
ea480882ecd241066cd04a56b01ca565fcfd1cce
128938d08b100bf5039cb0b2a651901cff73634e
refs/heads/master
2023-04-03T18:40:17.710162
2021-04-18T06:46:57
2021-04-18T06:46:57
319,972,488
7
1
null
2021-01-24T14:48:48
2020-12-09T13:56:26
Java
UTF-8
Java
false
false
822
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package techquizapp.Pojo; /** * * @author Harsh Vyas */ public class User { private String userId; private String password; private String userType; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } }
[ "vyasharsh70@gmail.com" ]
vyasharsh70@gmail.com
5d94a7083ded6abcd7f5e9d7a6f99a410ee6a7ae
8adc170873c0a45d98200e3636c3e827df8a5315
/src/test/java/io/github/jhipster/application/web/rest/AccountResourceIT.java
b82abf68fbb0e8670eef8d35b9b44780818385c8
[]
no_license
leratc/mutexParamsAdmin
51ec7d3bc38a8f8b996f815802a20adcd18a6daf
aef3e6daf124a9a18a50d2ec22fe72b54f652f7b
refs/heads/master
2022-12-22T04:15:58.441198
2019-09-10T13:38:00
2019-09-10T13:38:00
196,539,515
0
1
null
2022-12-16T05:02:00
2019-07-12T08:23:02
Java
UTF-8
Java
false
false
34,432
java
package io.github.jhipster.application.web.rest; import io.github.jhipster.application.MutexParamsAdminApp; import io.github.jhipster.application.config.Constants; import io.github.jhipster.application.domain.Authority; import io.github.jhipster.application.domain.User; import io.github.jhipster.application.repository.AuthorityRepository; import io.github.jhipster.application.repository.UserRepository; import io.github.jhipster.application.security.AuthoritiesConstants; import io.github.jhipster.application.service.MailService; import io.github.jhipster.application.service.UserService; import io.github.jhipster.application.service.dto.PasswordChangeDTO; import io.github.jhipster.application.service.dto.UserDTO; import io.github.jhipster.application.web.rest.errors.ExceptionTranslator; import io.github.jhipster.application.web.rest.vm.KeyAndPasswordVM; import io.github.jhipster.application.web.rest.vm.ManagedUserVM; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Integration tests for the {@link AccountResource} REST controller. */ @SpringBootTest(classes = MutexParamsAdminApp.class) public class AccountResourceIT { @Autowired private UserRepository userRepository; @Autowired private AuthorityRepository authorityRepository; @Autowired private UserService userService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private HttpMessageConverter<?>[] httpMessageConverters; @Autowired private ExceptionTranslator exceptionTranslator; @Mock private UserService mockUserService; @Mock private MailService mockMailService; private MockMvc restMvc; private MockMvc restUserMockMvc; @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); doNothing().when(mockMailService).sendActivationEmail(any()); AccountResource accountResource = new AccountResource(userRepository, userService, mockMailService); AccountResource accountUserMockResource = new AccountResource(userRepository, mockUserService, mockMailService); this.restMvc = MockMvcBuilders.standaloneSetup(accountResource) .setMessageConverters(httpMessageConverters) .setControllerAdvice(exceptionTranslator) .build(); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource) .setControllerAdvice(exceptionTranslator) .build(); } @Test public void testNonAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("")); } @Test public void testAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .with(request -> { request.setRemoteUser("test"); return request; }) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("test")); } @Test public void testGetExistingAccount() throws Exception { Set<Authority> authorities = new HashSet<>(); Authority authority = new Authority(); authority.setName(AuthoritiesConstants.ADMIN); authorities.add(authority); User user = new User(); user.setLogin("test"); user.setFirstName("john"); user.setLastName("doe"); user.setEmail("john.doe@jhipster.com"); user.setImageUrl("http://placehold.it/50x50"); user.setLangKey("en"); user.setAuthorities(authorities); when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user)); restUserMockMvc.perform(get("/api/account") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.login").value("test")) .andExpect(jsonPath("$.firstName").value("john")) .andExpect(jsonPath("$.lastName").value("doe")) .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) .andExpect(jsonPath("$.langKey").value("en")) .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); } @Test public void testGetUnknownAccount() throws Exception { when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty()); restUserMockMvc.perform(get("/api/account") .accept(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(status().isInternalServerError()); } @Test @Transactional public void testRegisterValid() throws Exception { ManagedUserVM validUser = new ManagedUserVM(); validUser.setLogin("test-register-valid"); validUser.setPassword("password"); validUser.setFirstName("Alice"); validUser.setLastName("Test"); validUser.setEmail("test-register-valid@example.com"); validUser.setImageUrl("http://placehold.it/50x50"); validUser.setLangKey(Constants.DEFAULT_LANGUAGE); validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse(); restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); } @Test @Transactional public void testRegisterInvalidLogin() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("funky-log!n");// <-- invalid invalidUser.setPassword("password"); invalidUser.setFirstName("Funky"); invalidUser.setLastName("One"); invalidUser.setEmail("funky@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterInvalidEmail() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword("password"); invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("invalid");// <-- invalid invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterInvalidPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword("123");// password with only 3 digits invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("bob@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterNullPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword(null);// invalid null password invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("bob@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterDuplicateLogin() throws Exception { // First registration ManagedUserVM firstUser = new ManagedUserVM(); firstUser.setLogin("alice"); firstUser.setPassword("password"); firstUser.setFirstName("Alice"); firstUser.setLastName("Something"); firstUser.setEmail("alice@example.com"); firstUser.setImageUrl("http://placehold.it/50x50"); firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Duplicate login, different email ManagedUserVM secondUser = new ManagedUserVM(); secondUser.setLogin(firstUser.getLogin()); secondUser.setPassword(firstUser.getPassword()); secondUser.setFirstName(firstUser.getFirstName()); secondUser.setLastName(firstUser.getLastName()); secondUser.setEmail("alice2@example.com"); secondUser.setImageUrl(firstUser.getImageUrl()); secondUser.setLangKey(firstUser.getLangKey()); secondUser.setCreatedBy(firstUser.getCreatedBy()); secondUser.setCreatedDate(firstUser.getCreatedDate()); secondUser.setLastModifiedBy(firstUser.getLastModifiedBy()); secondUser.setLastModifiedDate(firstUser.getLastModifiedDate()); secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // First user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); // Second (non activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); assertThat(testUser.isPresent()).isTrue(); testUser.get().setActivated(true); userRepository.save(testUser.get()); // Second (already activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @Test @Transactional public void testRegisterDuplicateEmail() throws Exception { // First user ManagedUserVM firstUser = new ManagedUserVM(); firstUser.setLogin("test-register-duplicate-email"); firstUser.setPassword("password"); firstUser.setFirstName("Alice"); firstUser.setLastName("Test"); firstUser.setEmail("test-register-duplicate-email@example.com"); firstUser.setImageUrl("http://placehold.it/50x50"); firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Register first user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser1.isPresent()).isTrue(); // Duplicate email, different login ManagedUserVM secondUser = new ManagedUserVM(); secondUser.setLogin("test-register-duplicate-email-2"); secondUser.setPassword(firstUser.getPassword()); secondUser.setFirstName(firstUser.getFirstName()); secondUser.setLastName(firstUser.getLastName()); secondUser.setEmail(firstUser.getEmail()); secondUser.setImageUrl(firstUser.getImageUrl()); secondUser.setLangKey(firstUser.getLangKey()); secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register second (non activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser2.isPresent()).isFalse(); Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); assertThat(testUser3.isPresent()).isTrue(); // Duplicate email - with uppercase email address ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM(); userWithUpperCaseEmail.setId(firstUser.getId()); userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3"); userWithUpperCaseEmail.setPassword(firstUser.getPassword()); userWithUpperCaseEmail.setFirstName(firstUser.getFirstName()); userWithUpperCaseEmail.setLastName(firstUser.getLastName()); userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com"); userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl()); userWithUpperCaseEmail.setLangKey(firstUser.getLangKey()); userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register third (not activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) .andExpect(status().isCreated()); Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); assertThat(testUser4.isPresent()).isTrue(); assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); testUser4.get().setActivated(true); userService.updateUser((new UserDTO(testUser4.get()))); // Register 4th (already activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @Test @Transactional public void testRegisterAdminIsIgnored() throws Exception { ManagedUserVM validUser = new ManagedUserVM(); validUser.setLogin("badguy"); validUser.setPassword("password"); validUser.setFirstName("Bad"); validUser.setLastName("Guy"); validUser.setEmail("badguy@example.com"); validUser.setActivated(true); validUser.setImageUrl("http://placehold.it/50x50"); validUser.setLangKey(Constants.DEFAULT_LANGUAGE); validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); Optional<User> userDup = userRepository.findOneByLogin("badguy"); assertThat(userDup.isPresent()).isTrue(); assertThat(userDup.get().getAuthorities()).hasSize(1) .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); } @Test @Transactional public void testActivateAccount() throws Exception { final String activationKey = "some activation key"; User user = new User(); user.setLogin("activate-account"); user.setEmail("activate-account@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(false); user.setActivationKey(activationKey); userRepository.saveAndFlush(user); restMvc.perform(get("/api/activate?key={activationKey}", activationKey)) .andExpect(status().isOk()); user = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(user.getActivated()).isTrue(); } @Test @Transactional public void testActivateAccountWithWrongKey() throws Exception { restMvc.perform(get("/api/activate?key=wrongActivationKey")) .andExpect(status().isInternalServerError()); } @Test @Transactional @WithMockUser("save-account") public void testSaveAccount() throws Exception { User user = new User(); user.setLogin("save-account"); user.setEmail("save-account@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("save-account@example.com"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey()); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl()); assertThat(updatedUser.getActivated()).isEqualTo(true); assertThat(updatedUser.getAuthorities()).isEmpty(); } @Test @Transactional @WithMockUser("save-invalid-email") public void testSaveInvalidEmail() throws Exception { User user = new User(); user.setLogin("save-invalid-email"); user.setEmail("save-invalid-email@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("invalid email"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); } @Test @Transactional @WithMockUser("save-existing-email") public void testSaveExistingEmail() throws Exception { User user = new User(); user.setLogin("save-existing-email"); user.setEmail("save-existing-email@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); User anotherUser = new User(); anotherUser.setLogin("save-existing-email2"); anotherUser.setEmail("save-existing-email2@example.com"); anotherUser.setPassword(RandomStringUtils.random(60)); anotherUser.setActivated(true); userRepository.saveAndFlush(anotherUser); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("save-existing-email2@example.com"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); } @Test @Transactional @WithMockUser("save-existing-email-and-login") public void testSaveExistingEmailAndLogin() throws Exception { User user = new User(); user.setLogin("save-existing-email-and-login"); user.setEmail("save-existing-email-and-login@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("save-existing-email-and-login@example.com"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); } @Test @Transactional @WithMockUser("change-password-wrong-existing-password") public void testChangePasswordWrongExistingPassword() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-wrong-existing-password"); user.setEmail("change-password-wrong-existing-password@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password")))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue(); } @Test @Transactional @WithMockUser("change-password") public void testChangePassword() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password"); user.setEmail("change-password@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); } @Test @Transactional @WithMockUser("change-password-too-small") public void testChangePasswordTooSmall() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-too-small"); user.setEmail("change-password-too-small@example.com"); userRepository.saveAndFlush(user); String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional @WithMockUser("change-password-too-long") public void testChangePasswordTooLong() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-too-long"); user.setEmail("change-password-too-long@example.com"); userRepository.saveAndFlush(user); String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional @WithMockUser("change-password-empty") public void testChangePasswordEmpty() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-empty"); user.setEmail("change-password-empty@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional public void testRequestPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setLogin("password-reset"); user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/reset-password/init") .content("password-reset@example.com")) .andExpect(status().isOk()); } @Test @Transactional public void testRequestPasswordResetUpperCaseEmail() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setLogin("password-reset"); user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/reset-password/init") .content("password-reset@EXAMPLE.COM")) .andExpect(status().isOk()); } @Test public void testRequestPasswordResetWrongEmail() throws Exception { restMvc.perform( post("/api/account/reset-password/init") .content("password-reset-wrong-email@example.com")) .andExpect(status().isBadRequest()); } @Test @Transactional public void testFinishPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("finish-password-reset"); user.setEmail("finish-password-reset@example.com"); user.setResetDate(Instant.now().plusSeconds(60)); user.setResetKey("reset key"); userRepository.saveAndFlush(user); KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("new password"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); } @Test @Transactional public void testFinishPasswordResetTooSmall() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("finish-password-reset-too-small"); user.setEmail("finish-password-reset-too-small@example.com"); user.setResetDate(Instant.now().plusSeconds(60)); user.setResetKey("reset key too small"); userRepository.saveAndFlush(user); KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("foo"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); } @Test @Transactional public void testFinishPasswordResetWrongKey() throws Exception { KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey("wrong reset key"); keyAndPassword.setNewPassword("new password"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isInternalServerError()); } }
[ "jhipster-bot@jhipster.tech" ]
jhipster-bot@jhipster.tech
02a746f63d352d066426e510a2871b2984b6ee5d
70df4173ef84c594b04003c9ce5872c83b9ce5b5
/permission/src/main/java/com/lxh/permission/commerce/Service/impl/SysUserServiceImpl.java
666ac026ef9e593982235fe4e727c9c14da1aa7f
[]
no_license
lixhua/LifeRecord
027589354f1a79a12ec6f30303df43d8c9e53de0
383200922168e7abe15115c865ab08b621e87ab8
refs/heads/develop
2022-12-11T21:13:02.250848
2019-08-06T05:00:09
2019-08-06T05:00:09
200,611,852
0
0
null
2022-12-11T00:50:06
2019-08-05T08:11:06
Java
UTF-8
Java
false
false
644
java
package com.lxh.permission.commerce.Service.impl; import com.lxh.permission.commerce.Service.SysUserService; import com.lxh.permission.common.mybatis.dao.SysUserMapper; import com.lxh.permission.common.mybatis.model.SysUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class SysUserServiceImpl implements SysUserService { @Autowired private SysUserMapper sysUserMapper; @Override public SysUser selectAll() { SysUser sysUsers = sysUserMapper.selectByPrimaryKey(1); return sysUsers; } }
[ "hunan_lxh@163.com" ]
hunan_lxh@163.com
9a178d988b1ba14ecf05448e8f776f3754a5adbf
f6da983ab8abccb92e6b699895becb6d7e54ec07
/src/main/java/com/filesystem/commands/CommandInterface.java
0e602b86e2cd6bae3a7e88b066ff441d3b5ee41c
[]
no_license
forkhazmodan/filesystem
e6d0724ae28ee09a01e8c21fa917daf209c96cb6
dd642aba78e0d947a070c7ed4de3d83a3e3b65d6
refs/heads/master
2023-02-04T06:52:29.548577
2020-12-27T00:56:45
2020-12-27T00:56:45
324,556,861
0
0
null
null
null
null
UTF-8
Java
false
false
95
java
package com.filesystem.commands; public interface CommandInterface { public void run(); }
[ "4myself.max@gmail.com" ]
4myself.max@gmail.com
4aca6c897a989ecc111173f677997543a3f23a75
39c6a55e0139290414088cc407917a5ceb3e8af5
/src/test/java/de/jilocasin/nearestneighbour/kdtree/generator/RandomKdTreeGenerator.java
ce53b52a7986683a4924faad7fbb8745b1b68dee
[ "Apache-2.0" ]
permissive
Jilocasin/nearest-neighbour
a1090b0b12c3b389758ee6cdbf91127790eaba8d
308a6107f6379dae3fadcdceb01e3dfce5d3f317
refs/heads/master
2020-03-17T23:46:02.556256
2018-10-04T07:05:46
2018-10-04T07:05:46
134,059,624
4
1
null
null
null
null
UTF-8
Java
false
false
922
java
package de.jilocasin.nearestneighbour.kdtree.generator; import java.util.ArrayList; import java.util.List; import de.jilocasin.nearestneighbour.kdtree.KdPoint; import de.jilocasin.nearestneighbour.kdtree.KdTree; public abstract class RandomKdTreeGenerator<T extends Number & Comparable<T>> { public KdTree<T> generate(final int dimensionCount, final int pointCount) { return new KdTree<>(generatePoints(dimensionCount, pointCount)); } public List<KdPoint<T>> generatePoints(final int dimensionCount, final int pointCount) { final List<KdPoint<T>> points = new ArrayList<>(pointCount); for (int i = 0; i < pointCount; i++) { final List<T> position = new ArrayList<>(dimensionCount); for (int axisIndex = 0; axisIndex < dimensionCount; axisIndex++) { position.add(buildRandomValue()); } points.add(new KdPoint<>(position)); } return points; } public abstract T buildRandomValue(); }
[ "mail@jilocasin.de" ]
mail@jilocasin.de
94b6bdc50a26f8edf141b77c6c09b9bc8c8be347
933fbc8fe2d31f183a4a4c4a18f42b608e006e2a
/ABSTRACT CLASS/AbstractClass.java
4bb9802872c22152c06e5345e21921143e72badd
[]
no_license
shivendra05/CORE-JAVA-PROGRAMMING
5986143c1a5098c813425214c19a02886562ff59
bd6f8ba74b27be36a819a307041bb7f2a4bbc330
refs/heads/master
2022-01-26T05:01:44.016694
2020-04-14T18:39:04
2020-04-14T18:39:04
98,048,794
0
0
null
null
null
null
UTF-8
Java
false
false
875
java
//programe to calculate area of circle and rectangle /*Abstract Method cant be final, static and private. It should be always a instance Method */ abstract class AreaOperations{ abstract void area(); } class Circle extends AreaOperations{ double r= 2.3,a; public void area(){ a = 2.14*r*r; System.out.println("Area of Circle is: "+a); } } class Rectangles extends AreaOperations{ int length = 3,width = 4,a; void area(){ a=length*width; System.out.println("Area of Rectangle is: "+a); } } class AbstractClass { public static void main(String[] args) { System.out.println("------Hello this is a abstract class demo -----"); System.out.println("Area of Circle is:---"); AreaOperations op = new Circle(); op.area(); System.out.println("Area of Rectangle is:---"); op = new Rectangles(); op.area(); } }
[ "noreply@github.com" ]
shivendra05.noreply@github.com
f3772be2cb4200f49eac283a01d9a639c8dec1a7
d08f2821e0f37807ec442f4d7e8248165facc17d
/TeamCode/src/main/java/sonic_test/SonicHookTest.java
ae8f576a9d6337f4c41e2978c33d08127b195de7
[]
no_license
lockdown8564/Skystone
7770df6ba88b2fb606d9de27e1094d4b0df6c0b6
9e420db76d60871d52816348727d6ccf5856b36f
refs/heads/master
2020-05-29T19:05:41.682543
2020-03-12T15:33:42
2020-03-12T15:33:42
189,306,060
2
0
null
null
null
null
UTF-8
Java
false
false
923
java
package sonic_test; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import org.firstinspires.ftc.robotcontroller.internal.FtcOpModeRegister; /** * testing hook of intake night before lm1, 12/1/19 */ @Disabled @TeleOp(name="hook test",group="test") public class SonicHookTest extends OpMode { private SonicTestHardware robot = new SonicTestHardware(); public void init(){ robot.init(hardwareMap); } @Override public void init_loop(){ } @Override public void start(){ } @Override public void loop(){ if(gamepad2.x){ robot.hook.setPosition(0.5); } else if(gamepad2.y){ robot.hook.setPosition(0.9); } } @Override public void stop(){ } }
[ "william.trangg@gmail.com" ]
william.trangg@gmail.com
ebe7064bd0e7afd321d7594b67026a6aa8c52922
0091c7ad92ca14a1f598a5ded80a43da25b41082
/parkingos_android_pc/src/com/zld/bean/UploadImg.java
55f12bcab70402553241afda4df41cc3e8c8c91a
[]
no_license
dlzdy/ParkingOS_local
51f9ab839162ab8d9bbf3fc28acf9345645f9708
485ecf823390a933249a80a5c0c84b6d8177845e
refs/heads/master
2020-03-25T10:58:13.822994
2018-11-21T05:36:50
2018-11-21T05:36:50
143,713,467
0
1
null
2018-08-06T10:32:54
2018-08-06T10:32:54
null
GB18030
Java
false
false
3,010
java
package com.zld.bean; import java.io.Serializable; @SuppressWarnings("serial") public class UploadImg implements Serializable { /* * id * account 账户 * orderid 订单id * lefttop 图片左上角x坐标 * rightbottom 图片左上角y坐标 * type 通道类型 * width 图片宽 * height 图片高 * imghomepath 入场图片路径 * imgexitpath 出场图片路径 */ private int id; private String account; private String orderid; private String lefttop; private String rightbottom; private String type; private String width; private String height; private String imghomepath; private String imgexitpath; private String carnumber; private String homeimgup; private String exitimgup; public String getHomeimgup() { return homeimgup; } public void setHomeimgup(String homeimgup) { this.homeimgup = homeimgup; } public String getExitimgup() { return exitimgup; } public void setExitimgup(String exitimgup) { this.exitimgup = exitimgup; } public String getCarnumber() { return carnumber; } public void setCarnumber(String carnumber) { this.carnumber = carnumber; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getOrderid() { return orderid; } public void setOrderid(String orderid) { this.orderid = orderid; } public String getLefttop() { return lefttop; } public void setLefttop(String lefttop) { this.lefttop = lefttop; } public String getRightbottom() { return rightbottom; } public void setRightbottom(String rightbottom) { this.rightbottom = rightbottom; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getWidth() { return width; } public void setWidth(String width) { this.width = width; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public String getImghomepath() { return imghomepath; } public void setImghomepath(String imghomepath) { this.imghomepath = imghomepath; } public String getImgexitpath() { return imgexitpath; } public void setImgexitpath(String imgexitpath) { this.imgexitpath = imgexitpath; } @Override public String toString() { return "UploadImg [id=" + id + ", account=" + account + ", orderid=" + orderid + ", lefttop=" + lefttop + ", rightbottom=" + rightbottom + ", type=" + type + ", width=" + width + ", height=" + height + ", imghomepath=" + imghomepath + ", imgexitpath=" + imgexitpath + ", carnumber=" + carnumber + ", homeimgup=" + homeimgup + ", exitimgup=" + exitimgup + "]"; } public String toEasyString() { return "orderid=" + orderid + ", imghomepath=" + imghomepath + ", imgexitpath=" + imgexitpath + ", carnumber=" + carnumber + ", homeimgup=" + homeimgup + ", exitimgup=" + exitimgup + "]"; } }
[ "you@example.com" ]
you@example.com
7b04accf21fb79438dedbbc771af3a9dd6187559
cc4c2790443f9f2ae322934172475ccf2f382213
/core/src/main/java/alpakkeer/core/jobs/model/JobStatus.java
ee08364bccd601fc6d31aca526da1d826b6353f2
[ "Apache-2.0" ]
permissive
cokeSchlumpf/alpakkeer
df3a5f900c0ab6782e405b92ab0938d6139b1880
fabcf2b4e7ab06e6bffbf1c735d0cea07a6953ba
refs/heads/master
2023-01-10T16:04:23.580145
2020-11-07T08:23:40
2020-11-07T08:23:40
260,839,044
2
1
Apache-2.0
2020-11-07T08:23:41
2020-05-03T06:03:30
Java
UTF-8
Java
false
false
246
java
package alpakkeer.core.jobs.model; import lombok.AllArgsConstructor; import lombok.Value; import java.util.List; @Value @AllArgsConstructor(staticName = "apply") public class JobStatus { String name; JobState state; int queued; }
[ "michael.wellner@de.ibm.com" ]
michael.wellner@de.ibm.com
647e96116776e0af3af976dca9a79227985b233b
854c5eccc15c4e902644043bfeacdfa5d3c2b334
/src/com/joshua/domain/OrderItem.java
fadd55413ffeeeda16df9a140e6d415037d76fd1
[]
no_license
JoshuaXueJH/Estore_MAC
cdfd2ac596057ae3322651865d70af0cecfdd019
acb356ab77e8562035a2150cac1b938f5a447451
refs/heads/master
2021-01-20T13:11:52.140229
2017-03-12T15:06:51
2017-03-12T15:06:51
82,678,073
0
0
null
null
null
null
UTF-8
Java
false
false
502
java
package com.joshua.domain; public class OrderItem { private String order_id; private String product_id; private int buynum; public String getOrder_id() { return order_id; } public void setOrder_id(String order_id) { this.order_id = order_id; } public String getProduct_id() { return product_id; } public void setProduct_id(String prod_id) { this.product_id = prod_id; } public int getBuynum() { return buynum; } public void setBuynum(int buynum) { this.buynum = buynum; } }
[ "xue918715582@126.com" ]
xue918715582@126.com
5721c5eb07896d8c4173ec607b9b5d87eacf5cb2
e1d836abc4a2708f3b5cc8a2894d172e6abe85a1
/src/main/java/cn/niriqiang/blog/service/CategoryService.java
374a73784baa93c995a11d58ffb4023e535949de
[ "Apache-2.0" ]
permissive
fengyuwusong/blog
db6ccd4cdb2396baf2ff44857ad362b8e48256c1
3068ffa2b4e29284e11800844866657694dc50e7
refs/heads/master
2020-05-27T02:25:16.460816
2017-11-30T10:07:27
2017-11-30T10:07:27
82,513,947
5
0
null
null
null
null
UTF-8
Java
false
false
2,942
java
package cn.niriqiang.blog.service; import cn.niriqiang.blog.domain.Category; import cn.niriqiang.blog.domain.CategoryMapper; import cn.niriqiang.blog.dto.Result; import cn.niriqiang.blog.enums.ResultEnum; import cn.niriqiang.blog.exception.ArticleException; import cn.niriqiang.blog.exception.CategoryException; import cn.niriqiang.blog.util.ResultUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by fengyuwusong on 2017/9/27 0:43. */ @Service public class CategoryService { @Autowired private CategoryMapper mapper; @Autowired private ArticleService articleService; public Result insertCategory(Category category) { try { findByCategoryName(category.getCategoryName()); } catch (CategoryException e) { mapper.insert(category); return ResultUtil.success(ResultEnum.OK, category); } throw new CategoryException(ResultEnum.ADD_EXITS); } public Result updateCategory(Category category) { // 查找id是否存在 Category res = (Category) findOne(category.getId()).getData(); // 如果CategoryName是需要修改项 查找更改的categoryName是否已经存在 if (!category.getCategoryName().equals(res.getCategoryName())) { try { findByCategoryName(category.getCategoryName()); } catch (CategoryException e) { mapper.update(category); return ResultUtil.success(ResultEnum.OK, category); } throw new CategoryException(ResultEnum.ADD_EXITS); } mapper.update(category); return ResultUtil.success(ResultEnum.OK, category); } public Result findOne(int id) { Category category = mapper.findOne(id); if (category != null) { return ResultUtil.success(ResultEnum.OK, category); } else { throw new CategoryException(ResultEnum.NOT_FOUND); } } public Result findByCategoryName(String categoryName) { Category category = mapper.findByCategoryName(categoryName); if (category != null) { return ResultUtil.success(ResultEnum.OK, category); } else { throw new CategoryException(ResultEnum.NOT_FOUND); } } public Result findAll() { List<Category> categoryPage = mapper.findAll(); return ResultUtil.success(ResultEnum.OK, categoryPage); } public Result delete(int id) { findOne(id); // 查找该分类下的文章是否存在 若存在则不能删除 try { articleService.findByCategory(1, id); } catch (ArticleException e) { mapper.delete(id); return ResultUtil.success(ResultEnum.OK, id); } throw new CategoryException(ResultEnum.DELETE_FALSE); } }
[ "602766695@qq.com" ]
602766695@qq.com
c0dadaa45702c47be76d28d015596b3c2caf0826
379392993a89ede4a49b38a1f0e57dacbe17ec7d
/com/google/firebase/messaging/FirebaseMessaging.java
e60895214a62fd24c7fc6983f17b079c04d31347
[]
no_license
mdali602/DTC
d5c6463d4cf67877dbba43e7d50a112410dccda3
5a91a20a0fe92d010d5ee7084470fdf8af5dafb5
refs/heads/master
2021-05-12T02:06:40.493406
2018-01-15T18:06:00
2018-01-15T18:06:00
117,578,063
0
1
null
null
null
null
UTF-8
Java
false
false
4,436
java
package com.google.firebase.messaging; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.util.Log; import com.google.firebase.FirebaseApp; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.zzf; import io.fabric.sdk.android.services.settings.SettingsJsonConstants; import java.util.regex.Pattern; public class FirebaseMessaging { public static final String INSTANCE_ID_SCOPE = "FCM"; private static final Pattern zzclA = Pattern.compile("[a-zA-Z0-9-_.~%]{1,900}"); private static FirebaseMessaging zzclB; private PendingIntent zzclC; private final FirebaseInstanceId zzcla; private FirebaseMessaging(FirebaseInstanceId firebaseInstanceId) { this.zzcla = firebaseInstanceId; } public static synchronized FirebaseMessaging getInstance() { FirebaseMessaging firebaseMessaging; synchronized (FirebaseMessaging.class) { if (zzclB == null) { zzclB = new FirebaseMessaging(FirebaseInstanceId.getInstance()); } firebaseMessaging = zzclB; } return firebaseMessaging; } private synchronized void zzh(Context context, Intent intent) { if (this.zzclC == null) { Intent intent2 = new Intent(); intent2.setPackage("com.google.example.invalidpackage"); this.zzclC = PendingIntent.getBroadcast(context, 0, intent2, 0); } intent.putExtra(SettingsJsonConstants.APP_KEY, this.zzclC); } public void send(RemoteMessage remoteMessage) { if (TextUtils.isEmpty(remoteMessage.getTo())) { throw new IllegalArgumentException("Missing 'to'"); } Context applicationContext = FirebaseApp.getInstance().getApplicationContext(); String zzbA = zzf.zzbA(applicationContext); if (zzbA == null) { Log.e("FirebaseMessaging", "Google Play services package is missing. Impossible to send message"); return; } Intent intent = new Intent("com.google.android.gcm.intent.SEND"); zzh(applicationContext, intent); intent.setPackage(zzbA); remoteMessage.zzM(intent); applicationContext.sendOrderedBroadcast(intent, "com.google.android.gtalkservice.permission.GTALK_SERVICE"); } public void subscribeToTopic(String str) { if (str != null && str.startsWith("/topics/")) { Log.w("FirebaseMessaging", "Format /topics/topic-name is deprecated. Only 'topic-name' should be used in subscribeToTopic."); Object substring = str.substring("/topics/".length()); } if (substring == null || !zzclA.matcher(substring).matches()) { String valueOf = String.valueOf("[a-zA-Z0-9-_.~%]{1,900}"); throw new IllegalArgumentException(new StringBuilder((String.valueOf(substring).length() + 55) + String.valueOf(valueOf).length()).append("Invalid topic name: ").append(substring).append(" does not match the allowed format ").append(valueOf).toString()); } FirebaseInstanceId instance = FirebaseInstanceId.getInstance(); String valueOf2 = String.valueOf("S!"); String valueOf3 = String.valueOf(substring); instance.zzjt(valueOf3.length() != 0 ? valueOf2.concat(valueOf3) : new String(valueOf2)); } public void unsubscribeFromTopic(String str) { if (str != null && str.startsWith("/topics/")) { Log.w("FirebaseMessaging", "Format /topics/topic-name is deprecated. Only 'topic-name' should be used in unsubscribeFromTopic."); Object substring = str.substring("/topics/".length()); } if (substring == null || !zzclA.matcher(substring).matches()) { String valueOf = String.valueOf("[a-zA-Z0-9-_.~%]{1,900}"); throw new IllegalArgumentException(new StringBuilder((String.valueOf(substring).length() + 55) + String.valueOf(valueOf).length()).append("Invalid topic name: ").append(substring).append(" does not match the allowed format ").append(valueOf).toString()); } FirebaseInstanceId instance = FirebaseInstanceId.getInstance(); String valueOf2 = String.valueOf("U!"); String valueOf3 = String.valueOf(substring); instance.zzjt(valueOf3.length() != 0 ? valueOf2.concat(valueOf3) : new String(valueOf2)); } }
[ "mohd.ali@xotiv.com" ]
mohd.ali@xotiv.com
e00fa0c2256da1f8620f047be6047f6d74bb26c8
5162ab2b9ce041e09447e657635188e39459d91b
/chapter_001/src/main/java/ru/job4j/array/Matrix.java
30be9c85b099b2eb3e6eaa8b32ed5dd8a5706a71
[ "Apache-2.0" ]
permissive
kamanaft/job4j
2fdecb2d091356a2fa157d2a586bc0705eac5ac2
6d2547186932c2d9dcb2e7c672afc2c9bb0c448b
refs/heads/master
2021-06-30T12:04:18.971608
2020-07-18T18:40:51
2020-07-18T18:40:51
144,139,371
0
0
Apache-2.0
2020-10-12T23:18:19
2018-08-09T10:47:08
Java
UTF-8
Java
false
false
485
java
package ru.job4j.array; /** * @author Alexey Zhukov (mailto:hadzage@gmail.com) * @version $01$ * @since 23.08.2018 */ public class Matrix { public int[][] multiple(int size) { int[][] table = new int[size][size]; for (int index = 0; index != table.length; index++) { for (int yandex = 0; yandex != table.length; yandex++) { table[index][yandex] = (index + 1) * (yandex + 1); } } return table; } }
[ "mailto:hadzage@gmail.com" ]
mailto:hadzage@gmail.com
899dcc8dcba7e4757b7879652a0ea529ba3a0313
fa4cc150076c1f621bc9c581829ae1d9cf6dfc26
/app/src/main/java/com/neuqer/fitornot/business/account/model/request/RegisterByVCodeRequestModel.java
12bdac67ae0e0afeb0cd7fa59c3949448e589566
[]
no_license
BoldFruit/FirOrNotxly
45a2c1a041f0addfd9fe2b499762bcc3f9ef59f9
aafaba28d653d80c3b740ebcae4731909ecf3dda
refs/heads/master
2022-11-22T23:23:26.074526
2020-07-27T10:56:50
2020-07-27T10:56:50
282,869,363
2
0
null
null
null
null
UTF-8
Java
false
false
561
java
package com.neuqer.fitornot.business.account.model.request; /** * @author DuLong * @since 2019/9/10 * email 798382030@qq.com */ public class RegisterByVCodeRequestModel { /** * phone : 13081860884 * VCode : 51627 */ private long phone; private String VCode; public void setPhone(long phone) { this.phone = phone; } public void setVCode(String VCode) { this.VCode = VCode; } public long getPhone() { return phone; } public String getVCode() { return VCode; } }
[ "798382030@qq.com" ]
798382030@qq.com
c52e920f00ece590a0b2b5184970e7d009957de8
8dcbeb02e9378f4c94476e79cf00cfd3f28ec962
/WebTest1/src/Selenium25/TestCase3.java
41a1c427df7608e3862a65e3e44ef5a7c7c6cea5
[]
no_license
ZhuQizhen/Selenium
7457ab2a2a58484b59e7b7df73ed24af7afe4909
d1638fa517d2ea709569c55c265aa6dc395f0c47
refs/heads/master
2021-01-01T20:30:34.323739
2017-07-31T09:46:30
2017-07-31T09:46:30
98,873,750
0
0
null
null
null
null
UTF-8
Java
false
false
1,000
java
package Selenium25; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; //using user defined methods/reusable components public class TestCase3 { public void adminLogin(String username, String password) { driver.get("http://www.gcrit.com/build3/admin/"); driver.findElement(By.name("username")).sendKeys(username); driver.findElement(By.name("password")).sendKeys(password); driver.findElement(By.id("tdb1")).click(); } static WebDriver driver; public void launchBrowser() { driver =new FirefoxDriver(); } public void closeBrowser() { if(!driver.toString().contains("null") ) { driver.close(); } } public static void main(String args[]) { m1(); } public static void m1() { TestCase3 obj = new TestCase3(); obj.launchBrowser(); obj.adminLogin("admin", "admin@123"); obj.closeBrowser(); obj.launchBrowser(); obj.adminLogin("admin", "admin@1234"); obj.closeBrowser(); } }
[ "leaf67697@gmail.com" ]
leaf67697@gmail.com
1f40c039d9e73c34da4bc08f28b3d16cc3eb272f
ceeb37e88389e45aa3164fc88b0270c9dd537869
/huya-search-distributed/search-common/src/main/java/com/huya/search/util/Base64.java
88afe5f46048ada0a42181048b2765d03da48d01
[]
no_license
vjimrunning/huya-search-distributed
8bfb125990a77d19380c89c392599d6070727873
707541cce8fa18d7f55d24b5efce91fe179d4d6d
refs/heads/master
2020-06-25T20:17:43.112055
2018-04-09T08:43:23
2018-04-09T08:43:41
199,412,663
0
1
null
2019-07-29T08:37:08
2019-07-29T08:37:07
null
UTF-8
Java
false
false
79,514
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 com.huya.search.util; //CHECKSTYLE: OFF /** * <p>Encodes and decodes to and from Base64 notation.</p> * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p> * * <p>Example:</p> * * <code>String encoded = Base64.encode( myByteArray );</code> * <br> * <code>byte[] myByteArray = Base64.decode( encoded );</code> * * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass * several pieces of information to the encoder. In the "higher level" methods such as * encodeBytes( bytes, options ) the options parameter can be used to indicate such * things as first gzipping the bytes before encoding them, not inserting linefeeds, * and encoding using the URL-safe and Ordered dialects.</p> * * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>, * Section 2.1, implementations should not add line feeds unless explicitly told * to do so. I've got Base64 set to this behavior now, although earlier versions * broke lines by default.</p> * * <p>The constants defined in Base64 can be OR-ed together to combine options, so you * might make a call like this:</p> * * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code> * <p>to compress the data before encoding it and then making the output have newline characters.</p> * <p>Also...</p> * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code> * * * * <p> * Change Log: * </p> * <ul> * <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the * value 01111111, which is an invalid base 64 character but should not * throw an ArrayIndexOutOfBoundsException either. Led to discovery of * mishandling (or potential for better handling) of other bad input * characters. You should now get an IOException if you try decoding * something that has bad characters in it.</li> * <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded * string ended in the last column; the buffer was not properly shrunk and * contained an extra (null) byte that made it into the string.</li> * <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size * was wrong for files of size 31, 34, and 37 bytes.</li> * <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing * the Base64.OutputStream closed the Base64 encoding (by padding with equals * signs) too soon. Also added an option to suppress the automatic decoding * of gzipped streams. Also added experimental support for specifying a * class loader when using the * {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)} * method.</li> * <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java * footprint with its CharEncoders and so forth. Fixed some javadocs that were * inconsistent. Removed imports and specified things like java.io.IOException * explicitly inline.</li> * <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the * final encoded data will be so that the code doesn't have to create two output * arrays: an oversized initial one and then a final, exact-sized one. Big win * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not * using the gzip options which uses a different mechanism with streams and stuff).</li> * <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some * similar helper methods to be more efficient with memory by not returning a * String but just a byte array.</li> * <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments * and bug fixes queued up and finally executed. Thanks to everyone who sent * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else. * Much bad coding was cleaned up including throwing exceptions where necessary * instead of returning null values or something similar. Here are some changes * that may affect you: * <ul> * <li><em>Does not break lines, by default.</em> This is to keep in compliance with * <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li> * <li><em>Throws exceptions instead of returning null values.</em> Because some operations * (especially those that may permit the GZIP option) use IO streams, there * is a possiblity of an java.io.IOException being thrown. After some discussion and * thought, I've changed the behavior of the methods to throw java.io.IOExceptions * rather than return null if ever there's an error. I think this is more * appropriate, though it will require some changes to your code. Sorry, * it should have been done this way to begin with.</li> * <li><em>Removed all references to System.out, System.err, and the like.</em> * Shame on me. All I can say is sorry they were ever there.</li> * <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed * such as when passed arrays are null or offsets are invalid.</li> * <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings. * This was especially annoying before for people who were thorough in their * own projects and then had gobs of javadoc warnings on this file.</li> * </ul> * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug * when using very small files (~&lt; 40 bytes).</li> * <li>v2.2 - Added some helper methods for encoding/decoding directly from * one file to the next. Also added a main() method to support command line * encoding/decoding from one file to the next. Also added these Base64 dialects: * <ol> * <li>The default is RFC3548 format.</li> * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates * URL and file name friendly format as described in Section 4 of RFC3548. * http://www.faqs.org/rfcs/rfc3548.html</li> * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates * URL and file name friendly format that preserves lexical ordering as described * in http://www.faqs.org/qa/rfcc-1940.html</li> * </ol> * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a> * for contributing the new Base64 dialects. * </li> * * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added * some convenience methods for reading and writing to and from files.</li> * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems * with other encodings (like EBCDIC).</li> * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the * encoded data was a single byte.</li> * <li>v2.0 - I got rid of methods that used booleans to set options. * Now everything is more consolidated and cleaner. The code now detects * when data that's being decoded is gzip-compressed and will decompress it * automatically. Generally things are cleaner. You'll probably have to * change some method calls that you were making to support the new * options format (<tt>int</tt>s that you "OR" together).</li> * <li>v1.5.1 - Fixed bug when decompressing and decoding to a * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. * Added the ability to "suspend" encoding in the Output Stream so * you can turn on and off the encoding if you need to embed base64 * data in an otherwise "normal" stream (like an XML file).</li> * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. * This helps when using GZIP streams. * Added the ability to GZip-compress objects before encoding them.</li> * <li>v1.4 - Added helper methods to read/write files.</li> * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream * where last buffer being read, if not completely full, was not returned.</li> * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> * </ul> * * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rob@iharder.net * @version 2.3.7 */ public class Base64 { /* ******** P U B L I C F I E L D S ******** */ /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding in first bit. Value is one. */ public final static int ENCODE = 1; /** Specify decoding in first bit. Value is zero. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed in second bit. Value is two. */ public final static int GZIP = 2; /** Specify that gzipped data should <em>not</em> be automatically gunzipped. */ public final static int DONT_GUNZIP = 4; /** Do break lines when encoding. Value is 8. */ public final static int DO_BREAK_LINES = 8; /** * Encode using Base64-like encoding that is URL- and Filename-safe as described * in Section 4 of RFC3548: * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. * It is important to note that data encoded this way is <em>not</em> officially valid Base64, * or at the very least should not be called Base64 without also specifying that is * was encoded using the URL- and Filename-safe dialect. */ public final static int URL_SAFE = 16; /** * Encode using the special "ordered" dialect of Base64 described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ public final static int ORDERED = 32; /* ******** P R I V A T E F I E L D S ******** */ /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "US-ASCII"; private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ /** The 64 valid Base64 values. */ /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ private final static byte[] _STANDARD_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] _STANDARD_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ /** * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." */ private final static byte[] _URL_SAFE_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' }; /** * Used in decoding URL- and Filename-safe dialects of Base64. */ private final static byte[] _URL_SAFE_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 62, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 63, // Underscore at decimal 95 -9, // Decimal 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ /** * I don't get the point of this technique, but someone requested it, * and it is described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ private final static byte[] _ORDERED_ALPHABET = { (byte)'-', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'_', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' }; /** * Used in decoding the "ordered" dialect of Base64. */ private final static byte[] _ORDERED_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 0, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 37, // Underscore at decimal 95 -9, // Decimal 96 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ /** * Returns one of the _SOMETHING_ALPHABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getAlphabet( int options ) { if ((options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_ALPHABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_ALPHABET; } else { return _STANDARD_ALPHABET; } } // end getAlphabet /** * Returns one of the _SOMETHING_DECODABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED and URL_SAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getDecodabet( int options ) { if( (options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_DECODABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_DECODABET; } else { return _STANDARD_DECODABET; } } // end getAlphabet /** Defeats instantiation. */ private Base64(){} /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); return b4; } // end encode3to4 /** * <p>Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>.</p> * <p>This is the lowest level of the encoding methods with * all possible parameters.</p> * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options ) { byte[] ALPHABET = getAlphabet( options ); // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, * writing it to the <code>encoded</code> ByteBuffer. * This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} * or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); encoded.put(enc4); } // end input remaining } /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, * writing it to the <code>encoded</code> CharBuffer. * This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} * or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); for( int i = 0; i < 4; i++ ){ encoded.put( (char)(enc4[i] & 0xFF) ); } } // end input remaining } /** * Serializes an object and returns the Base64-encoded * version of that serialized object. * * <p>As of v 2.3, if the object * cannot be serialized or there is another error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @throws java.io.IOException if there is an error * @throws NullPointerException if serializedObject is null * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) throws java.io.IOException { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. * * <p>As of v 2.3, if the object * cannot be serialized or there is another error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * The object is not GZip-compressed before being encoded. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) throws java.io.IOException { if( serializableObject == null ){ throw new NullPointerException( "Cannot serialize a null object." ); } // end if: null // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.util.zip.GZIPOutputStream gzos = null; java.io.ObjectOutputStream oos = null; try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); if( (options & GZIP) != 0 ){ // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream( gzos ); } else { // Not gzipped oos = new java.io.ObjectOutputStream( b64os ); } oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue){ // Fall back to some Java default return new String( baos.toByteArray() ); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @return The data in Base64-encoded form * @throws NullPointerException if source array is null * @since 1.4 */ public static String encodeBytes( byte[] source ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * * <p>As of v 2.3, if there is an error with the GZIP stream, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) throws java.io.IOException { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * <p>As of v 2.3, if there is an error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @return The Base64-encoded data as a String * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes( source, off, len, NO_OPTIONS ); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * * <p>As of v 2.3, if there is an error with the GZIP stream, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { byte[] encoded = encodeBytesToBytes( source, off, len, options ); // Return value according to relevant encoding. try { return new String( encoded, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( encoded ); } // end catch } // end encodeBytes /** * Similar to {@link #encodeBytes(byte[])} but returns * a byte array instead of instantiating a String. This is more efficient * if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @return The Base64-encoded data as a byte[] (of ASCII characters) * @throws NullPointerException if source array is null * @since 2.3.1 */ public static byte[] encodeBytesToBytes( byte[] source ) { byte[] encoded = null; try { encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS ); } catch( java.io.IOException ex ) { assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); } return encoded; } /** * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns * a byte array instead of instantiating a String. This is more efficient * if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.3.1 */ public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress } // end encodeBytesToBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * <p>This is the lowest level of the decoding methods with * all possible parameters.</p> * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param options alphabet type is pulled from this (standard, url-safe, ordered) * @return the number of decoded bytes converted * @throws NullPointerException if source or destination arrays are null * @throws IllegalArgumentException if srcOffset or destOffset are invalid * or there is not enough room in the array. * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Source array was null." ); } // end if if( destination == null ){ throw new NullPointerException( "Destination array was null." ); } // end if if( srcOffset < 0 || srcOffset + 3 >= source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); } // end if if( destOffset < 0 || destOffset +2 >= destination.length ){ throw new IllegalArgumentException( String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); } // end if byte[] DECODABET = getDecodabet( options ); // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; } } // end decodeToBytes /** * Low-level access to decoding ASCII characters in * the form of a byte array. <strong>Ignores GUNZIP option, if * it's set.</strong> This is not generally a recommended method, * although it is used internally as part of the decoding process. * Special case: if len = 0, an empty array is returned. Still, * if you need more speed and reduced memory footprint (and aren't * gzipping), consider this method. * * @param source The Base64 encoded data * @return decoded data * @since 2.3.1 */ public static byte[] decode( byte[] source ) throws java.io.IOException { byte[] decoded = null; // try { decoded = decode( source, 0, source.length, Base64.NO_OPTIONS ); // } catch( java.io.IOException ex ) { // assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); // } return decoded; } /** * Low-level access to decoding ASCII characters in * the form of a byte array. <strong>Ignores GUNZIP option, if * it's set.</strong> This is not generally a recommended method, * although it is used internally as part of the decoding process. * Special case: if len = 0, an empty array is returned. Still, * if you need more speed and reduced memory footprint (and aren't * gzipping), consider this method. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @param options Can specify options such as alphabet type to use * @return decoded data * @throws java.io.IOException If bogus characters exist in source data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len, int options ) throws java.io.IOException { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Cannot decode null source array." ); } // end if if( off < 0 || off + len > source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); } // end if if( len == 0 ){ return new byte[0]; }else if( len < 4 ){ throw new IllegalArgumentException( "Base64-encoded string must have at least four characters, but length specified was " + len ); } // end if byte[] DECODABET = getDecodabet( options ); int len34 = len * 3 / 4; // Estimate on array size byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; // Keep track of where we're writing byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space int b4Posn = 0; // Keep track of four byte input buffer int i = 0; // Source array counter byte sbiDecode = 0; // Special value from DECODABET for( i = off; i < off+len; i++ ) { // Loop through source sbiDecode = DECODABET[ source[i]&0xFF ]; // White space, Equals sign, or legit Base64 character // Note the values such as -5 and -9 in the // DECODABETs at the top of the file. if( sbiDecode >= WHITE_SPACE_ENC ) { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = source[i]; // Save non-whitespace if( b4Posn > 3 ) { // Time to decode? outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( source[i] == EQUALS_SIGN ) { break; } // end if: equals sign } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { // There's a bad input character in the Base64 stream. throw new java.io.IOException( String.format( "Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) ); } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @throws java.io.IOException If there is a problem * @since 1.4 */ public static byte[] decode( String s ) throws java.io.IOException { return decode( s, NO_OPTIONS ); } /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @param options encode options such as URL_SAFE * @return the decoded data * @throws java.io.IOException if there is an error * @throws NullPointerException if <tt>s</tt> is null * @since 1.4 */ public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a * class that cannot be found by the JVM * @since 1.5 */ public static Object decodeToObject( String encodedObject ) throws java.io.IOException, java.lang.ClassNotFoundException { return decodeToObject(encodedObject,NO_OPTIONS,null); } /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * If <tt>loader</tt> is not null, it will be the class loader * used when deserializing. * * @param encodedObject The Base64 data to decode * @param options Various parameters related to decoding * @param loader Optional class loader to use in deserializing classes. * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a * class that cannot be found by the JVM * @since 2.3.4 */ public static Object decodeToObject( String encodedObject, int options, final ClassLoader loader ) throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject, options ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); // If no custom class loader is provided, use Java's builtin OIS. if( loader == null ){ ois = new java.io.ObjectInputStream( bais ); } // end if: no loader provided // Else make a customized object input stream that uses // the provided class loader. else { ois = new java.io.ObjectInputStream(bais){ @Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass }; // end ois } // end else: no custom class loader obj = ois.readObject(); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch catch( java.lang.ClassNotFoundException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @throws java.io.IOException if there is an error * @throws NullPointerException if dataToEncode is null * @since 2.1 */ public static void encodeToFile( byte[] dataToEncode, String filename ) throws java.io.IOException { if( dataToEncode == null ){ throw new NullPointerException( "Data to encode was null." ); } // end iff Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end encodeToFile /** * Convenience method for decoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @throws java.io.IOException if there is an error * @since 2.1 */ public static void decodeToFile( String dataToDecode, String filename ) throws java.io.IOException { Base64.OutputStream bos = null; try{ bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading encoded data * @return decoded byte array * @throws java.io.IOException if there is an error * @since 2.1 */ public static byte[] decodeFromFile( String filename ) throws java.io.IOException { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if( file.length() > Integer.MAX_VALUE ) { throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." ); } // end if: file too big for int index buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return decodedData = new byte[ length ]; System.arraycopy( buffer, 0, decodedData, 0, length ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading binary data * @return base64-encoded string * @throws java.io.IOException if there is an error * @since 2.1 */ public static String encodeFromFile( String filename ) throws java.io.IOException { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return encodedData; } // end encodeFromFile /** * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void encodeFileToFile( String infile, String outfile ) throws java.io.IOException { String encoded = Base64.encodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output. } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end encodeFileToFile /** * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void decodeFileToFile( String infile, String outfile ) throws java.io.IOException { byte[] decoded = Base64.decodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( decoded ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end decodeFileToFile /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64.InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters private int options; // Record options used to create the stream. private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.InputStream} in DECODE mode. * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) { this( in, DECODE ); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: break lines at 76 characters * (only meaningful when encoding) * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) { super( in ); this.options = options; // Record for later this.breakLines = (options & DO_BREAK_LINES) > 0; this.encode = (options & ENCODE) > 0; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[ bufferLength ]; this.position = -1; this.lineLength = 0; this.decodabet = getDecodabet(options); } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ @Override public int read() throws java.io.IOException { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { int b = in.read(); // If end of stream, b is -1. if( b >= 0 ) { b3[i] = (byte)b; numBinaryBytes++; } else { break; // out of for loop } // end else: end of stream } // end for: each needed input byte if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); position = 0; numSigBytes = 4; } // end if: got data else { return -1; // Must be end of stream } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; do{ b = in.read(); } while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); if( b < 0 ) { break; // Reads a -1 if end of stream } // end if: end of stream b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0, options ); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); } // end } // end else: decode } // end else: get data // Got data? if( position >= 0 ) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes ){ return -1; } // end if: got data if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[ position++ ]; if( position >= bufferLength ) { position = -1; } // end if: end return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { throw new java.io.IOException( "Error in Base64 code reading stream." ); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ @Override public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); if( b >= 0 ) { dest[off + i] = (byte) b; } else if( i == 0 ) { return -1; } else { break; // Out of 'for' loop } // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64.OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; private int options; // Record for later private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) { this( out, ENCODE ); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) { super( out ); this.breakLines = (options & DO_BREAK_LINES) != 0; this.encode = (options & ENCODE) != 0; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[ bufferLength ]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; this.options = options; this.decodabet = getDecodabet(options); } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ @Override public void write(int theByte) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { this.out.write( theByte ); return; } // end if: supsended // Encode? if( encode ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) { // Enough to encode. this.out.write( encode3to4( b4, buffer, bufferLength, options ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { this.out.write( NEW_LINE ); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) { // Enough to output. int len = Base64.decode4to3( buffer, 0, b4, 0, options ); out.write( b4, 0, len ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ @Override public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { this.out.write( theBytes, off, len ); return; } // end if: supsended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. * @throws java.io.IOException if there's an error. */ public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position, options ) ); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ @Override public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base64-encoded data in a stream. * * @throws java.io.IOException if there's an error flushing * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base64-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64 //CHECKSTYLE: ON // End Base64.java
[ "junxuezhang@yeah.net" ]
junxuezhang@yeah.net
29be480154cca38050217296fdc46e4fc5248c1b
ac76ca16ec518a4f6eb9f0b0e54ab89768568f03
/Usuarios/app/src/main/java/com/example/lucasfranco/usuarios/Menu.java
34bba7fccaf23f5f3bc9f1f7f02d79d2b941e748
[]
no_license
proflucasscf/Android
f5fa9c5ebf003235c73ceb18c69694b0a44fd8b5
9403963604e909d10ce788afad48ec9b6efda39d
refs/heads/master
2022-07-03T20:22:12.168824
2020-05-14T15:02:13
2020-05-14T15:02:13
263,938,978
0
0
null
null
null
null
UTF-8
Java
false
false
1,546
java
package com.example.lucasfranco.usuarios; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import java.util.List; public class Menu extends AppCompatActivity { TextView lista; DataHelper dataBase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); dataBase = new DataHelper(this); lista = (TextView) this.findViewById(R.id.lista); read(); } @Override protected void onResume() { super.onResume(); read(); } public void insert(View v) { Intent intent = new Intent(Menu.this, Insert.class); startActivity(intent); } public void update(View v) { Intent intent = new Intent(Menu.this, Update.class); startActivity(intent); } public void read(View v) { Intent intent = new Intent(Menu.this, Read.class); startActivity(intent); } public void delete(View v) { Intent intent = new Intent(Menu.this, Delete.class); startActivity(intent); } public void read() { List<String> usuarios = dataBase.SelectAll(); StringBuilder sb = new StringBuilder(); sb.append("Usuarios Cadastrados:\n"); for (String usuario : usuarios) { sb.append(usuario + "\n"); } lista.setText(sb.toString()); } }
[ "proflucasscf@gmail.com" ]
proflucasscf@gmail.com
6ef45f743eb3f974d2af3cffa2b2e341f17f538d
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_c2d8811bb98dfc848f75834e3eb06fd9a9ce87c0/ConfEndpointImpl/2_c2d8811bb98dfc848f75834e3eb06fd9a9ce87c0_ConfEndpointImpl_t.java
edce7932509dc809f6cc125151a4d0a28e379776
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
3,697
java
/* * Mobicents Media Gateway * * The source code contained in this file is in in the public domain. * It can be used in any project or product without prior permission, * license or royalty payments. There is NO WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR STATUTORY, INCLUDING, WITHOUT LIMITATION, * THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, * AND DATA ACCURACY. We do not warrant or make any representations * regarding the use of the software or the results thereof, including * but not limited to the correctness, accuracy, reliability or * usefulness of the software. */ package org.mobicents.media.server.impl.conference; import org.apache.log4j.Logger; import org.mobicents.media.server.impl.BaseEndpoint; import org.mobicents.media.server.impl.BaseResourceManager; import org.mobicents.media.server.impl.common.events.EventID; import org.mobicents.media.server.impl.events.dtmf.DTMFPackage; import org.mobicents.media.server.spi.NotificationListener; import org.mobicents.media.server.spi.ResourceStateListener; import org.mobicents.media.server.spi.UnknownSignalException; /** * * @author Oleg Kulikov */ public class ConfEndpointImpl extends BaseEndpoint { private transient Logger logger = Logger.getLogger(ConfEndpointImpl.class); protected ResourceStateListener mixerStateListener; protected ResourceStateListener splitterStateListener; private DTMFPackage dtmfPackage; public ConfEndpointImpl(String localName) { super(localName); this.mixerStateListener = new MixerStateListener(); this.splitterStateListener = new SplitterStateListener(); } @Override public BaseResourceManager initResourceManager() { return new ConfResourceManager(); } /** * Starts detection DTMF on specified connection with specified parameters. * * The DTMF detector is a resource of the endpoint created and initialized * for each connection. The DTMF detection procedure is actualy devided into * three steps. On first step inactive DTMF detector is created alongside * with connection using the DTMF format negotiated. The second step is used * to initialize detector with media stream. The last step is used to actual * start media analysis and events generation. * * @param connectionID the identifier of the connection * @param params parameters for DTMF detector. * @param listener the call back inetrface. */ private void detectDTMF(String connectionID, String[] params, NotificationListener listener) { if (dtmfPackage == null) { dtmfPackage = new DTMFPackage(this); } try { dtmfPackage.subscribe(EventID.DTMF, null, connectionID, listener); } catch (Exception e) { logger.error("Detection of DTMF failed", e); } } public void play(EventID signalID, String[] params, String connectionID, NotificationListener listener, boolean keepAlive) throws UnknownSignalException { throw new UnsupportedOperationException("Not supported yet."); } @Override public void subscribe(EventID eventID, String connectionID, String params[], NotificationListener listener) { switch (eventID) { case DTMF: logger.info("Start DTMF detector for connection: " + connectionID); this.detectDTMF(connectionID, params, listener); break; } } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
a546a9058ed7017b487ccb3fb5c8c52aad64c7a6
cf00256b9d185e137814e57e9143a7e6d30bbfa8
/src/main/java/com/appslabtest/ormtools/beans/KriBean.java
ac553e5f50fcb8caa82adfaae717bde42883fa38
[]
no_license
cnwachukwu5/ormTools
6177ac1b60a2624feddb36aa4e9a08e2f4277ffa
edbc52d7f1a0b0dcb90ff933a4b8567d601e65f2
refs/heads/master
2020-03-16T13:13:20.130034
2018-07-18T03:22:52
2018-07-18T03:22:52
132,684,047
1
0
null
null
null
null
UTF-8
Java
false
false
8,799
java
package com.appslabtest.ormtools.beans; import java.io.Serializable; import java.util.List; import javax.faces.application.FacesMessage; import org.primefaces.context.RequestContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.SessionScope; import org.springframework.dao.DataAccessException; import com.appslabtest.ormtools.model.KRI; import com.appslabtest.ormtools.model.Department; import com.appslabtest.ormtools.service.DepartmentService; import com.appslabtest.ormtools.service.KRIService; import com.appslabtest.ormtools.utilities.MessengerUtil; import com.appslabtest.ormtools.utilities.IDGen; @SessionScope @Component public class KriBean implements Serializable { private static final long serialVersionUID = 1L; @Autowired KRIService kriService; @Autowired DepartmentService departmentService; private String kri_code; private String kri_desc; private String kri_reason_for_collection; private double kri_lower_bound; private double kri_upper_bound; private Department kri_owner_dept; private boolean kri_status; private String kri_deactivate_reason; private KRI kri = new KRI(); private MessengerUtil messengerUtil = new MessengerUtil(); private boolean isValidated = false; private List<KRI> allDeptKRIs; public List<KRI> getAllDeptKRIs() { return allDeptKRIs; } public void setAllDeptKRIs(List<KRI> allDeptKRIs) { this.allDeptKRIs = allDeptKRIs; } public DepartmentService getDepartmentService() { return departmentService; } public void setDepartmentService(DepartmentService departmentService) { this.departmentService = departmentService; } public KRIService getKriService() { return kriService; } public void setKriService(KRIService kriService) { this.kriService = kriService; } public String getKri_code() { return kri_code; } public void setKri_code(String kri_code) { this.kri_code = kri_code; } public String getKri_desc() { return kri_desc; } public void setKri_desc(String kri_desc) { this.kri_desc = kri_desc; } public String getKri_reason_for_collection() { return kri_reason_for_collection; } public void setKri_reason_for_collection(String kri_reason_for_collection) { this.kri_reason_for_collection = kri_reason_for_collection; } public double getKri_lower_bound() { return kri_lower_bound; } public void setKri_lower_bound(double kri_lower_bound) { this.kri_lower_bound = kri_lower_bound; } public double getKri_upper_bound() { return kri_upper_bound; } public void setKri_upper_bound(double kri_upper_bound) { this.kri_upper_bound = kri_upper_bound; } public Department getKri_owner_dept() { return kri_owner_dept; } public void setKri_owner_dept(Department kri_owner_dept) { this.kri_owner_dept = kri_owner_dept; } public boolean isKri_status() { return kri_status; } public void setKri_status(boolean kri_status) { this.kri_status = kri_status; } public String getKri_deactivate_reason() { return kri_deactivate_reason; } public void setKri_deactivate_reason(String kri_deactivate_reason) { this.kri_deactivate_reason = kri_deactivate_reason; } public KRI getKri() { return kri; } public void setKri(KRI kri) { this.kri = kri; } public void addKRI() { /* * This method adds a new KRI to the KRI table */ checkThresholdValues(); if(isValidated) { try { List<KRI> kris = findOneKRI(kri.getKri_desc()); if((kris.isEmpty())) { KRI newKRI = new KRI(); String kriID = new IDGen().getGeneratedID(kri.getKri_owner_dept().getDept_name()); newKRI.setKri_code(kriID); newKRI.setKri_desc(kri.getKri_desc()); newKRI.setKri_reason_for_collection(kri.getKri_reason_for_collection()); newKRI.setKri_lower_bound(kri.getKri_lower_bound()); newKRI.setKri_upper_bound(kri.getKri_upper_bound()); newKRI.setKri_owner_dept(kri.getKri_owner_dept()); newKRI.setKri_status(kri.isKri_status()); newKRI.setKri_deactivate_reason(""); getKriService().addKRI(newKRI); reset(); messengerUtil.addMessage(FacesMessage.SEVERITY_INFO, "KRI created succesfully", "Add new KRI"); }else { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "This KRI already exists", "Add new KRI"); } }catch(DataAccessException dataAccessException) { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "Error: " + dataAccessException.getMessage(), "KRI creation Error"); } }else { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "Low threshold bound should not be greater than upper bound...", "KRI Threshold values"); } }//End of addKRI public void reset() { kri.setKri_code(""); kri.setKri_desc(""); kri.setKri_reason_for_collection(""); kri.setKri_lower_bound(0); kri.setKri_upper_bound(0); kri.setKri_owner_dept(null); kri.setKri_status(false); kri.setKri_deactivate_reason(""); } public List<KRI> findOneKRI(String kri_desc) { return getKriService().findKRI(kri_desc); } public void checkKRI() { try { KRI kriExists = getKriService().findKRI(kri.getKri_code(), kri.getKri_owner_dept().getDeptid()); if(kriExists == null) { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "There is no record for this KRI", "Find KRI"); }else { kri.setKri_code(kriExists.getKri_code()); kri.setKri_deactivate_reason(kriExists.getKri_deactivate_reason()); kri.setKri_desc(kriExists.getKri_desc()); kri.setKri_lower_bound(kriExists.getKri_lower_bound()); kri.setKri_owner_dept(kriExists.getKri_owner_dept()); kri.setKri_reason_for_collection(kriExists.getKri_reason_for_collection()); kri.setKri_status(kriExists.isKri_status()); kri.setKri_upper_bound(kriExists.getKri_upper_bound()); } }catch (Exception e) { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "Error: " + e, "KRI check error"); } } public void getKRIProperties() { System.out.println("This is invoked ..."); try { List<KRI> kris = getKriService().findKRI(kri.getKri_desc()); if(!(kris.isEmpty())) { kri = kris.get(0); } }catch(Exception e) { e.printStackTrace(); } } public void updateKRI() { System.out.println(kri.getKri_desc()); //partialSubmit if(kri == null) { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "KRI does not exist", "Update KRI"); }else { try { getKriService().updateKRI(kri); messengerUtil.addMessage(FacesMessage.SEVERITY_INFO, "KRI updated successfully", "Update KRI"); }catch (Exception e) { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "Error: " + e, "KRI update error"); } } } public void deleteKRI() { if(kri == null) { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "KRI does not exist", "Delete KRI"); }else { try { if(!(kri.isKri_status())) { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "This KRI has already been deactivated", "Delete KRI"); }else { getKriService().deleteKRI(kri); messengerUtil.addMessage(FacesMessage.SEVERITY_INFO, "KRI deleted successfully", "Delete KRI"); } }catch (Exception e) { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "Error: " + e, "KRI deletion error"); } } } public List<KRI> getAllActiveKRIsForDepartment(Department department){ List<KRI> allActiveKRI = getKriService().findAllActiveKRI(department.getDeptid()); if(allActiveKRI.isEmpty()) { return null; }else { return allActiveKRI; } } public void getAllKRIsForDepartment(){ List<KRI> allKRIs = getKriService().findAllKRIs(kri.getKri_owner_dept().getDeptid()); if(allKRIs.isEmpty()) { messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "There are no KRIs for this department...", "All KRIs"); }else { setAllDeptKRIs(allKRIs); } } public void checkThresholdValues() { if(kri.getKri_lower_bound() > kri.getKri_upper_bound()) { isValidated = false; //messengerUtil.addMessage(FacesMessage.SEVERITY_ERROR, "Low threshold bound should not be greater than upper bound...", "KRI Threshold values"); FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "KRI Threshold values", "Low threshold bound must be less than upper threshold bound..."); RequestContext.getCurrentInstance().showMessageInDialog(facesMessage); }else { isValidated = true; } } public boolean addBatch(List<KRI> kris) { System.out.println("I started executing"); boolean result = false; System.out.println("Size is: " + kris.size()); for(int i = 0; i < kris.size(); i++) { kri = kris.get(i); getKriService().addKRI(kri); } result = true; return result; } }
[ "cnwachukwu5@gmail.com" ]
cnwachukwu5@gmail.com
1a2b508254e239ab84e58a18523c23a76801d5f5
94a8726d3a4900fd5285fde3953bd27d9163dfc8
/src/main/java/sergio/repositories/reactive/UnitOfMeasureReactiveRepository.java
bfe7320277d69ff883adf87c4d3c6ad7cbf5adea
[]
no_license
sergiopoliveira/spring5-mongo-recipe-app
7d225e0eb569c70e761d838f1444f5ce80a03006
cba418d14f76ea028f818307e49834f3121c96ab
refs/heads/master
2020-03-19T08:12:00.978235
2018-06-17T21:00:51
2018-06-17T21:00:51
136,180,280
0
0
null
null
null
null
UTF-8
Java
false
false
370
java
package sergio.repositories.reactive; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import reactor.core.publisher.Mono; import sergio.domain.UnitOfMeasure; public interface UnitOfMeasureReactiveRepository extends ReactiveMongoRepository<UnitOfMeasure, String>{ Mono<UnitOfMeasure> findByDescription(String description); }
[ "sergiopoliveira@outlook.com" ]
sergiopoliveira@outlook.com
55d1d65244c2b04a52f66591ac2ac985d2f15ce7
6ba5c48c419f45ccc7bae9eb2fb3776d03a56d0a
/FilePersistenceTest/app/src/main/java/com/example/filepersistencetest/MainActivity.java
07fb01006c4edd6581b79a372f8b0dc7a498d7dd
[]
no_license
yunlong505/AndroidStudioProjects
f7f19364fc31d8d096246b82d66cabdaf4fc4bc1
744116f1707fc3d56acfb021dba2cc5b0a87a2cc
refs/heads/master
2020-07-30T20:40:59.433650
2019-09-23T12:44:14
2019-09-23T12:44:14
210,353,134
0
0
null
null
null
null
UTF-8
Java
false
false
1,368
java
package com.example.filepersistencetest; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.os.Bundle; import android.widget.EditText; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class MainActivity extends AppCompatActivity { private EditText edit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edit = findViewById(R.id.edit); } @Override protected void onDestroy() { super.onDestroy(); String inputText = edit.getText().toString(); save(inputText); } public void save(String inputText) { FileOutputStream out = null; BufferedWriter writer = null; try { out = openFileOutput("data", Context.MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputText); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
[ "menyunlong505@163.com" ]
menyunlong505@163.com
ff79d6546f433527b48e5fb542f30c1179222e07
350a0b302f24bbf5ba8c4106a08f2f5910d0252b
/src/main/java/com/solid/app/web/rest/UserJWTController.java
1642fb7f46664acbc1deb7423824f5fc41c840c4
[]
no_license
aalok95/SOLIDApp2
f0119c771d72d1dd0768b851a70ca242cddfc285
ef45b86913644f83437a43c07601c0787afcddaa
refs/heads/master
2021-08-23T04:55:51.119491
2017-12-03T12:52:22
2017-12-03T12:52:22
112,927,586
0
0
null
null
null
null
UTF-8
Java
false
false
2,518
java
package com.solid.app.web.rest; import com.solid.app.security.jwt.JWTConfigurer; import com.solid.app.security.jwt.TokenProvider; import com.solid.app.web.rest.vm.LoginVM; import com.codahale.metrics.annotation.Timed; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.http.HttpStatus; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * Controller to authenticate users. */ @RestController @RequestMapping("/api") public class UserJWTController { private final TokenProvider tokenProvider; private final AuthenticationManager authenticationManager; public UserJWTController(TokenProvider tokenProvider, AuthenticationManager authenticationManager) { this.tokenProvider = tokenProvider; this.authenticationManager = authenticationManager; } @PostMapping("/authenticate") @Timed public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe(); String jwt = tokenProvider.createToken(authentication, rememberMe); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK); } /** * Object to return as body in JWT Authentication. */ static class JWTToken { private String idToken; JWTToken(String idToken) { this.idToken = idToken; } @JsonProperty("id_token") String getIdToken() { return idToken; } void setIdToken(String idToken) { this.idToken = idToken; } } }
[ "jhipster-bot@users.noreply.github.com" ]
jhipster-bot@users.noreply.github.com
ba450388f9cb9ba4a6911790a98be5df920807e0
5c79500baf6054a1eb0ffdd5707ecc4c71acbcc7
/src/main/java/com/ciessa/museum/model/legacy/Zrspilr.java
3bab2f4a445e5bf1ed24d586d18df017d563a5dc
[]
no_license
mhapanow/museum
471782baca13a1a016ca292c0712ff3f59f34bbe
43b8bce82e5817e1f1da0057fb8abfa15f5e8a7a
refs/heads/master
2021-07-10T07:00:46.707692
2019-01-28T19:40:39
2019-01-28T19:40:39
104,667,104
1
0
null
2019-01-28T19:20:47
2017-09-24T18:34:43
Java
UTF-8
Java
false
false
10,748
java
package com.ciessa.museum.model.legacy; // Generated Jan 28, 2019 1:33:59 PM by Hibernate Tools 3.2.2.GA import java.math.BigDecimal; /** * Zrspilr generated by hbm2java */ public class Zrspilr implements java.io.Serializable { private String pkid; private String member; private Integer ilyfac; private Integer ilaafc; private String ilcifa; private String ilagig; private Integer ilorg; private Integer illogo; private String ilncct; private String ilncrd; private Integer ilptnr; private Integer ilncax; private String ilntal; private Integer ilcori; private Integer ilcmov; private Integer ilcsmv; private Integer ilnsem; private Integer ilymov; private Integer ilamov; private Integer ilmmov; private Integer ildmov; private Integer ilcdin; private Integer iladin; private Integer ilmdin; private Integer ilddin; private Integer ilchin; private Integer ilahin; private Integer ilmhin; private Integer ildhin; private BigDecimal ilibci; private Integer ildiin; private BigDecimal iltidd; private BigDecimal iltidh; private BigDecimal iltipr; private BigDecimal ilicpm; private String ilubir; private String ilmini; private Integer ilfact; private Integer ilhact; private String ilcope; private String ilxtrf; private Integer ilccyc; private String ilctrs; private Integer ilecsl; private Integer ilnpla; private String ilprmi; public Zrspilr() { } public Zrspilr(String pkid) { this.pkid = pkid; } public Zrspilr(String pkid, String member, Integer ilyfac, Integer ilaafc, String ilcifa, String ilagig, Integer ilorg, Integer illogo, String ilncct, String ilncrd, Integer ilptnr, Integer ilncax, String ilntal, Integer ilcori, Integer ilcmov, Integer ilcsmv, Integer ilnsem, Integer ilymov, Integer ilamov, Integer ilmmov, Integer ildmov, Integer ilcdin, Integer iladin, Integer ilmdin, Integer ilddin, Integer ilchin, Integer ilahin, Integer ilmhin, Integer ildhin, BigDecimal ilibci, Integer ildiin, BigDecimal iltidd, BigDecimal iltidh, BigDecimal iltipr, BigDecimal ilicpm, String ilubir, String ilmini, Integer ilfact, Integer ilhact, String ilcope, String ilxtrf, Integer ilccyc, String ilctrs, Integer ilecsl, Integer ilnpla, String ilprmi) { this.pkid = pkid; this.member = member; this.ilyfac = ilyfac; this.ilaafc = ilaafc; this.ilcifa = ilcifa; this.ilagig = ilagig; this.ilorg = ilorg; this.illogo = illogo; this.ilncct = ilncct; this.ilncrd = ilncrd; this.ilptnr = ilptnr; this.ilncax = ilncax; this.ilntal = ilntal; this.ilcori = ilcori; this.ilcmov = ilcmov; this.ilcsmv = ilcsmv; this.ilnsem = ilnsem; this.ilymov = ilymov; this.ilamov = ilamov; this.ilmmov = ilmmov; this.ildmov = ildmov; this.ilcdin = ilcdin; this.iladin = iladin; this.ilmdin = ilmdin; this.ilddin = ilddin; this.ilchin = ilchin; this.ilahin = ilahin; this.ilmhin = ilmhin; this.ildhin = ildhin; this.ilibci = ilibci; this.ildiin = ildiin; this.iltidd = iltidd; this.iltidh = iltidh; this.iltipr = iltipr; this.ilicpm = ilicpm; this.ilubir = ilubir; this.ilmini = ilmini; this.ilfact = ilfact; this.ilhact = ilhact; this.ilcope = ilcope; this.ilxtrf = ilxtrf; this.ilccyc = ilccyc; this.ilctrs = ilctrs; this.ilecsl = ilecsl; this.ilnpla = ilnpla; this.ilprmi = ilprmi; } public String getPkid() { return this.pkid; } public void setPkid(String pkid) { this.pkid = pkid; } public String getMember() { return this.member; } public void setMember(String member) { this.member = member; } public Integer getIlyfac() { return this.ilyfac; } public void setIlyfac(Integer ilyfac) { this.ilyfac = ilyfac; } public Integer getIlaafc() { return this.ilaafc; } public void setIlaafc(Integer ilaafc) { this.ilaafc = ilaafc; } public String getIlcifa() { return this.ilcifa; } public void setIlcifa(String ilcifa) { this.ilcifa = ilcifa; } public String getIlagig() { return this.ilagig; } public void setIlagig(String ilagig) { this.ilagig = ilagig; } public Integer getIlorg() { return this.ilorg; } public void setIlorg(Integer ilorg) { this.ilorg = ilorg; } public Integer getIllogo() { return this.illogo; } public void setIllogo(Integer illogo) { this.illogo = illogo; } public String getIlncct() { return this.ilncct; } public void setIlncct(String ilncct) { this.ilncct = ilncct; } public String getIlncrd() { return this.ilncrd; } public void setIlncrd(String ilncrd) { this.ilncrd = ilncrd; } public Integer getIlptnr() { return this.ilptnr; } public void setIlptnr(Integer ilptnr) { this.ilptnr = ilptnr; } public Integer getIlncax() { return this.ilncax; } public void setIlncax(Integer ilncax) { this.ilncax = ilncax; } public String getIlntal() { return this.ilntal; } public void setIlntal(String ilntal) { this.ilntal = ilntal; } public Integer getIlcori() { return this.ilcori; } public void setIlcori(Integer ilcori) { this.ilcori = ilcori; } public Integer getIlcmov() { return this.ilcmov; } public void setIlcmov(Integer ilcmov) { this.ilcmov = ilcmov; } public Integer getIlcsmv() { return this.ilcsmv; } public void setIlcsmv(Integer ilcsmv) { this.ilcsmv = ilcsmv; } public Integer getIlnsem() { return this.ilnsem; } public void setIlnsem(Integer ilnsem) { this.ilnsem = ilnsem; } public Integer getIlymov() { return this.ilymov; } public void setIlymov(Integer ilymov) { this.ilymov = ilymov; } public Integer getIlamov() { return this.ilamov; } public void setIlamov(Integer ilamov) { this.ilamov = ilamov; } public Integer getIlmmov() { return this.ilmmov; } public void setIlmmov(Integer ilmmov) { this.ilmmov = ilmmov; } public Integer getIldmov() { return this.ildmov; } public void setIldmov(Integer ildmov) { this.ildmov = ildmov; } public Integer getIlcdin() { return this.ilcdin; } public void setIlcdin(Integer ilcdin) { this.ilcdin = ilcdin; } public Integer getIladin() { return this.iladin; } public void setIladin(Integer iladin) { this.iladin = iladin; } public Integer getIlmdin() { return this.ilmdin; } public void setIlmdin(Integer ilmdin) { this.ilmdin = ilmdin; } public Integer getIlddin() { return this.ilddin; } public void setIlddin(Integer ilddin) { this.ilddin = ilddin; } public Integer getIlchin() { return this.ilchin; } public void setIlchin(Integer ilchin) { this.ilchin = ilchin; } public Integer getIlahin() { return this.ilahin; } public void setIlahin(Integer ilahin) { this.ilahin = ilahin; } public Integer getIlmhin() { return this.ilmhin; } public void setIlmhin(Integer ilmhin) { this.ilmhin = ilmhin; } public Integer getIldhin() { return this.ildhin; } public void setIldhin(Integer ildhin) { this.ildhin = ildhin; } public BigDecimal getIlibci() { return this.ilibci; } public void setIlibci(BigDecimal ilibci) { this.ilibci = ilibci; } public Integer getIldiin() { return this.ildiin; } public void setIldiin(Integer ildiin) { this.ildiin = ildiin; } public BigDecimal getIltidd() { return this.iltidd; } public void setIltidd(BigDecimal iltidd) { this.iltidd = iltidd; } public BigDecimal getIltidh() { return this.iltidh; } public void setIltidh(BigDecimal iltidh) { this.iltidh = iltidh; } public BigDecimal getIltipr() { return this.iltipr; } public void setIltipr(BigDecimal iltipr) { this.iltipr = iltipr; } public BigDecimal getIlicpm() { return this.ilicpm; } public void setIlicpm(BigDecimal ilicpm) { this.ilicpm = ilicpm; } public String getIlubir() { return this.ilubir; } public void setIlubir(String ilubir) { this.ilubir = ilubir; } public String getIlmini() { return this.ilmini; } public void setIlmini(String ilmini) { this.ilmini = ilmini; } public Integer getIlfact() { return this.ilfact; } public void setIlfact(Integer ilfact) { this.ilfact = ilfact; } public Integer getIlhact() { return this.ilhact; } public void setIlhact(Integer ilhact) { this.ilhact = ilhact; } public String getIlcope() { return this.ilcope; } public void setIlcope(String ilcope) { this.ilcope = ilcope; } public String getIlxtrf() { return this.ilxtrf; } public void setIlxtrf(String ilxtrf) { this.ilxtrf = ilxtrf; } public Integer getIlccyc() { return this.ilccyc; } public void setIlccyc(Integer ilccyc) { this.ilccyc = ilccyc; } public String getIlctrs() { return this.ilctrs; } public void setIlctrs(String ilctrs) { this.ilctrs = ilctrs; } public Integer getIlecsl() { return this.ilecsl; } public void setIlecsl(Integer ilecsl) { this.ilecsl = ilecsl; } public Integer getIlnpla() { return this.ilnpla; } public void setIlnpla(Integer ilnpla) { this.ilnpla = ilnpla; } public String getIlprmi() { return this.ilprmi; } public void setIlprmi(String ilprmi) { this.ilprmi = ilprmi; } }
[ "mhapanow@hotmail.com" ]
mhapanow@hotmail.com
1005391e1e67acf5915b4c01e766fa2bd3c12ca5
bca640243a305133cb61b4eaa234f50432a2c953
/src/main/java/edu/tum/uc/jvm/deprecated/container/Field.java
6783c94aca700b0a488d075d16d4971d08eec32b
[]
no_license
alexxx2015/HDFT
7c3f2d731d4b09f3ce4276a7a230bbd7877736d1
52f3ef40dcba824ec3f009c94c463ce4c3be5cda
refs/heads/master
2021-01-19T07:22:08.104947
2017-04-07T14:11:45
2017-04-07T14:11:45
87,539,784
0
0
null
null
null
null
UTF-8
Java
false
false
406
java
package edu.tum.uc.jvm.deprecated.container; public class Field extends Container { private boolean isStatic; public Field(String p_name, boolean p_isStatic){ super(ContainerType.STATIC_ATTR_FIELD); this.setName(p_name); this.setIsStatic(p_isStatic); } public boolean isStatic(){ return isStatic; } private void setIsStatic(boolean p_isStatic){ this.isStatic = p_isStatic; } }
[ "fromm@cs.tum.edu" ]
fromm@cs.tum.edu
495da032d214c1488fa298c4c09b49604e168d7d
60107866469e4b35fd487451ae2d896117045539
/src/main/java/technology/raeder/yoappserver/internal/LoadedYoApp.java
12e8926f3a66184df2b48541116a6d5091ab0b2d
[ "MIT" ]
permissive
RaederDev/YoAppServer
83f9994e0fbc2baa2ade3f4603e88e2272e33aed
291066c1215c96386f4b2cb8c48732b4a84f5d23
refs/heads/master
2021-10-10T06:20:50.152276
2014-09-10T19:59:44
2014-09-10T19:59:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
720
java
package technology.raeder.yoappserver.internal; import technology.raeder.yoappserver.api.YoApp; import technology.raeder.yoappserver.loader.AppConfiguration; public class LoadedYoApp { private final YoApp app; private final AppConfiguration config; /** * A loaded YoApp contains the app instance and the configuration that is linked to the app. * @param app The app instance. * @param config The configuration of the app. */ public LoadedYoApp(YoApp app, AppConfiguration config) { this.app = app; this.config = config; } public YoApp getApp() { return app; } public AppConfiguration getConfig() { return config; } }
[ "github@raeder.technology" ]
github@raeder.technology
1c2d8b8f1daf23c4635446698ae6699b5b50c6f1
9ee66155943d57ca54bc448892b0dbb6bae1c132
/src/java/nc/item/ItemAntimatter.java
61bd2b1cb6db1e89be9e86032814638d25d87800
[]
no_license
QuantumTraverse/NuclearCraft
30162d51b0760ce8cddcc734eac653e3e0951bdb
7ef07e3b1248f23eea243f0913d1150a7c9e7fc6
refs/heads/master
2020-04-05T23:39:37.537788
2016-12-29T01:17:29
2016-12-29T01:17:29
77,307,156
0
0
null
2016-12-25T02:22:07
2016-12-25T02:22:06
null
UTF-8
Java
false
false
1,507
java
package nc.item; import nc.NuclearCraft; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; public class ItemAntimatter extends ItemNC { public ItemAntimatter(String nam, String... lines) { super("", nam, lines); } public boolean onEntityItemUpdate(EntityItem entityItem) { if (entityItem != null) { if (entityItem.onGround) { int x = (int) Math.floor(entityItem.posX); int y = (int) Math.floor(entityItem.posY); int z = (int) Math.floor(entityItem.posZ); for (int i = -((int)0.2D*NuclearCraft.explosionRadius); i <= ((int)0.2D*NuclearCraft.explosionRadius); i++) { for (int j = -((int)0.2D*NuclearCraft.explosionRadius); j <= ((int)0.2D*NuclearCraft.explosionRadius); j++) { for (int k = -((int)0.2D*NuclearCraft.explosionRadius); k <= ((int)0.2D*NuclearCraft.explosionRadius); k++) { if (i*i + j*j + k*k <= ((int)0.2D*NuclearCraft.explosionRadius)*((int)0.2D*NuclearCraft.explosionRadius) && entityItem.worldObj.getBlock(x + i, y + j, z + k) != Blocks.bedrock) { entityItem.worldObj.setBlockToAir(x + i, y + j, z + k); } } } } entityItem.worldObj.playSoundEffect(entityItem.posX, entityItem.posY, entityItem.posZ, "random.explode", 4.0F, 1.0F); entityItem.worldObj.playSoundEffect(entityItem.posX, entityItem.posY, entityItem.posZ, "nc:shield2", 12.0F, 1.0F); entityItem.setDead(); return true; } } return false; } }
[ "joedodd35@gmail.com" ]
joedodd35@gmail.com
fd13fbf6553cb89edee5883ea267d2ff4ac610ae
ddf6a745ee2fda2756aa5a2a987ca30030d78f99
/IS/380/evennumberedexercise/chapter27/Loan.java
392cba91ca7991bbb1be3dd91d138623bf2bc8b0
[]
no_license
jacobtruman/college
1c0a8edcaebd1ed22d637c1ddf7c956ab2125d76
0b06219747ad6c38cf8e2f189c6edb34dbd5a172
refs/heads/master
2021-01-17T23:38:30.599248
2017-03-07T18:58:20
2017-03-07T18:58:20
84,231,612
0
0
null
null
null
null
UTF-8
Java
false
false
1,803
java
package chapter27; public class Loan { private double annualInterestRate; private int numberOfYears; private double loanAmount; private java.util.Date loanDate; /** Construct a loan with interest rate 2.5, 1 year, and $1000 */ public Loan() { this(2.5, 1, 1000); } /** Construct a loan with specified annual interest rate, number of years and loan amount */ public Loan(double annualInterestRate, int numberOfYears, double loanAmount) { this.annualInterestRate = annualInterestRate; this.numberOfYears = numberOfYears; this.loanAmount = loanAmount; loanDate = new java.util.Date(); } /** Return annualInterestRate */ public double getAnnualInterestRate() { return annualInterestRate; } /** Set a new annualInterestRate */ public void setAnnualInterestRate(double annualInterestRate) { this.annualInterestRate = annualInterestRate; } /** Return numberOfYears */ public int getNumberOfYears() { return numberOfYears; } /** Set a new numberOfYears */ public void setNumberOfYears(int numberOfYears) { this.numberOfYears = numberOfYears; } /** Return loanAmount */ public double getLoanAmount() { return loanAmount; } /** Set a newloanAmount */ public void setLoanAmount(double loanAmount) { this.loanAmount = loanAmount; } /** Find monthly payment */ public double monthlyPayment() { double monthlyInterestRate = annualInterestRate / 1200; return loanAmount * monthlyInterestRate / (1 - (Math.pow(1 / (1 + monthlyInterestRate), numberOfYears * 12))); } /** Find total payment */ public double totalPayment() { return monthlyPayment() * numberOfYears * 12; } /** Return loan date */ public java.util.Date getLoanDate() { return loanDate; } }
[ "jatruman@adobe.com" ]
jatruman@adobe.com
4d48c489f93783f1c17ad49f4f1accea98d429bf
151ac8b36fbf36968670e92c82dc76101ebcce95
/vivo-project/vivo/api/src/main/java/edu/cornell/mannlib/semservices/bo/SemanticServicesError.java
a2688c08612458248b9a3ff408ff56d395819d9e
[]
no_license
grahamtriggs/vivo-testing
90caa2966ae0ecba00ec8acc7c896d47b2a5f651
b2f00368a858fe17ab54329e4608410f3251b395
refs/heads/master
2020-12-24T13:36:38.740799
2015-09-25T21:20:26
2015-09-25T21:20:26
42,952,129
0
1
null
2015-09-24T22:03:53
2015-09-22T18:16:04
Java
UTF-8
Java
false
false
1,346
java
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.semservices.bo; public class SemanticServicesError { private String message; private String exception; private String severity; /** * */ public SemanticServicesError() { super(); } /** * @param exception * @param message * @param severity */ public SemanticServicesError(String exception, String message, String severity) { super(); this.exception = exception; this.message = message; this.severity = severity; } /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } /** * @return the exception */ public String getException() { return exception; } /** * @param exception the exception to set */ public void setException(String exception) { this.exception = exception; } /** * @return the severity */ public String getSeverity() { return severity; } /** * @param severity the severity to set */ public void setSeverity(String severity) { this.severity = severity; } }
[ "grahamtriggs@gmail.com" ]
grahamtriggs@gmail.com
4d78e1b7ff0a010585bf6ff75a748fe79535986c
71071f98d05549b67d4d6741e8202afdf6c87d45
/files/Spring_Data_for_Apache_Cassandra/DATACASS-308/spring-data-cassandra/src/test/java/org/springframework/data/cassandra/convert/MappingCassandraConverterUnitTests.java
08a44c5d488aa692e776a0f3e1a3c340411e82ab
[]
no_license
Sun940201/SpringSpider
0adcdff1ccfe9ce37ba27e31b22ca438f08937ad
ff2fc7cea41e8707389cb62eae33439ba033282d
refs/heads/master
2022-12-22T09:01:54.550976
2018-06-01T06:31:03
2018-06-01T06:31:03
128,649,779
1
0
null
2022-12-16T00:51:27
2018-04-08T14:30:30
Java
UTF-8
Java
false
false
26,117
java
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.cassandra.convert; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assume.*; import static org.mockito.Mockito.*; import static org.springframework.data.cassandra.RowMockUtil.*; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.cassandra.core.PrimaryKeyType; import org.springframework.core.SpringVersion; import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.data.cassandra.RowMockUtil; import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext; import org.springframework.data.cassandra.mapping.CassandraMappingContext; import org.springframework.data.cassandra.mapping.CassandraType; import org.springframework.data.cassandra.mapping.PrimaryKey; import org.springframework.data.cassandra.mapping.PrimaryKeyClass; import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; import org.springframework.data.cassandra.mapping.Table; import org.springframework.test.util.ReflectionTestUtils; import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.DataType; import com.datastax.driver.core.DataType.Name; import com.datastax.driver.core.LocalDate; import com.datastax.driver.core.Row; import com.datastax.driver.core.querybuilder.Assignment; import com.datastax.driver.core.querybuilder.BuiltStatement; import com.datastax.driver.core.querybuilder.Clause; import com.datastax.driver.core.querybuilder.Delete.Where; import com.datastax.driver.core.querybuilder.Insert; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.core.querybuilder.Update; import com.datastax.driver.core.querybuilder.Update.Assignments; /** * Unit tests for {@link MappingCassandraConverter}. * * @author Mark Paluch * @soundtrack Outlandich - Dont Leave Me Feat Cyt (Sun Kidz Electrocore Mix) */ @SuppressWarnings("Since15") @RunWith(MockitoJUnitRunner.class) public class MappingCassandraConverterUnitTests { @Rule public final ExpectedException expectedException = ExpectedException.none(); @Mock private Row rowMock; @Mock private ColumnDefinitions columnDefinitionsMock; private CassandraMappingContext mappingContext; private MappingCassandraConverter mappingCassandraConverter; @Before public void setUp() throws Exception { mappingContext = new BasicCassandraMappingContext(); mappingCassandraConverter = new MappingCassandraConverter(mappingContext); mappingCassandraConverter.afterPropertiesSet(); } /** * @see DATACASS-260 */ @Test public void insertEnumShouldMapToString() { WithEnumColumns withEnumColumns = new WithEnumColumns(); withEnumColumns.setCondition(Condition.MINT); Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(withEnumColumns, insert); assertThat(getValues(insert), hasItem((Object) "MINT")); } /** * @see DATACASS-260 */ @Test public void insertEnumDoesNotMapToOrdinalBeforeSpring43() { assumeThat(SpringVersion.getVersion(), not(startsWith("4.3"))); expectedException.expect(ConverterNotFoundException.class); expectedException.expectMessage(allOf(containsString("No converter found"), containsString("java.lang.Integer"))); UnsupportedEnumToOrdinalMapping unsupportedEnumToOrdinalMapping = new UnsupportedEnumToOrdinalMapping(); unsupportedEnumToOrdinalMapping.setAsOrdinal(Condition.MINT); Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(unsupportedEnumToOrdinalMapping, insert); } /** * @see DATACASS-255 */ @Test public void insertEnumMapsToOrdinalWithSpring43() { assumeThat(SpringVersion.getVersion(), startsWith("4.3")); UnsupportedEnumToOrdinalMapping unsupportedEnumToOrdinalMapping = new UnsupportedEnumToOrdinalMapping(); unsupportedEnumToOrdinalMapping.setAsOrdinal(Condition.USED); Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(unsupportedEnumToOrdinalMapping, insert); assertThat(getValues(insert), hasItem((Object) Integer.valueOf(Condition.USED.ordinal()))); } /** * @see DATACASS-260 */ @Test public void insertEnumAsPrimaryKeyShouldMapToString() { EnumPrimaryKey key = new EnumPrimaryKey(); key.setCondition(Condition.MINT); Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(key, insert); assertThat(getValues(insert), hasItem((Object) "MINT")); } /** * @see DATACASS-260 */ @Test public void insertEnumInCompositePrimaryKeyShouldMapToString() { EnumCompositePrimaryKey key = new EnumCompositePrimaryKey(); key.setCondition(Condition.MINT); CompositeKeyThing composite = new CompositeKeyThing(); composite.setKey(key); Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(composite, insert); assertThat(getValues(insert), hasItem((Object) "MINT")); } /** * @see DATACASS-260 */ @Test public void updateEnumShouldMapToString() { WithEnumColumns withEnumColumns = new WithEnumColumns(); withEnumColumns.setCondition(Condition.MINT); Update update = QueryBuilder.update("table"); mappingCassandraConverter.write(withEnumColumns, update); assertThat(getAssignmentValues(update), hasItem((Object) "MINT")); } /** * @see DATACASS-260 */ @Test public void updateEnumAsPrimaryKeyShouldMapToString() { EnumPrimaryKey key = new EnumPrimaryKey(); key.setCondition(Condition.MINT); Update update = QueryBuilder.update("table"); mappingCassandraConverter.write(key, update); assertThat(getWhereValues(update), hasItem((Object) "MINT")); } /** * @see DATACASS-260 */ @Test public void updateEnumInCompositePrimaryKeyShouldMapToString() { EnumCompositePrimaryKey key = new EnumCompositePrimaryKey(); key.setCondition(Condition.MINT); CompositeKeyThing composite = new CompositeKeyThing(); composite.setKey(key); Update update = QueryBuilder.update("table"); mappingCassandraConverter.write(composite, update); assertThat(getWhereValues(update), hasItem((Object) "MINT")); } /** * @see DATACASS-260 */ @Test public void whereEnumAsPrimaryKeyShouldMapToString() { EnumPrimaryKey key = new EnumPrimaryKey(); key.setCondition(Condition.MINT); Where where = QueryBuilder.delete().from("table").where(); mappingCassandraConverter.write(key, where); assertThat(getWhereValues(where), hasItem((Object) "MINT")); } /** * @see DATACASS-260 */ @Test public void whereEnumInCompositePrimaryKeyShouldMapToString() { EnumCompositePrimaryKey key = new EnumCompositePrimaryKey(); key.setCondition(Condition.MINT); CompositeKeyThing composite = new CompositeKeyThing(); composite.setKey(key); Where where = QueryBuilder.delete().from("table").where(); mappingCassandraConverter.write(composite, where); assertThat(getWhereValues(where), hasItem((Object) "MINT")); } /** * @see DATACASS-280 */ @Test public void shouldReadStringCorrectly() { when(rowMock.getString(0)).thenReturn("foo"); String result = mappingCassandraConverter.readRow(String.class, rowMock); assertThat(result, is(equalTo("foo"))); } /** * @see DATACASS-280 */ @Test public void shouldReadIntegerCorrectly() { when(rowMock.getObject(0)).thenReturn(2); Integer result = mappingCassandraConverter.readRow(Integer.class, rowMock); assertThat(result, is(equalTo(2))); } /** * @see DATACASS-280 */ @Test public void shouldReadLongCorrectly() { when(rowMock.getObject(0)).thenReturn(2); Long result = mappingCassandraConverter.readRow(Long.class, rowMock); assertThat(result, is(equalTo(2L))); } /** * @see DATACASS-280 */ @Test public void shouldReadDoubleCorrectly() { when(rowMock.getObject(0)).thenReturn(2D); Double result = mappingCassandraConverter.readRow(Double.class, rowMock); assertThat(result, is(equalTo(2D))); } /** * @see DATACASS-280 */ @Test public void shouldReadFloatCorrectly() { when(rowMock.getObject(0)).thenReturn(2F); Float result = mappingCassandraConverter.readRow(Float.class, rowMock); assertThat(result, is(equalTo(2F))); } /** * @see DATACASS-280 */ @Test public void shouldReadBigIntegerCorrectly() { when(rowMock.getObject(0)).thenReturn(BigInteger.valueOf(2)); BigInteger result = mappingCassandraConverter.readRow(BigInteger.class, rowMock); assertThat(result, is(equalTo(BigInteger.valueOf(2)))); } /** * @see DATACASS-280 */ @Test public void shouldReadBigDecimalCorrectly() { when(rowMock.getObject(0)).thenReturn(BigDecimal.valueOf(2)); BigDecimal result = mappingCassandraConverter.readRow(BigDecimal.class, rowMock); assertThat(result, is(equalTo(BigDecimal.valueOf(2)))); } /** * @see DATACASS-280 */ @Test public void shouldReadUUIDCorrectly() { UUID uuid = UUID.randomUUID(); when(rowMock.getUUID(0)).thenReturn(uuid); UUID result = mappingCassandraConverter.readRow(UUID.class, rowMock); assertThat(result, is(equalTo(uuid))); } /** * @see DATACASS-280 */ @Test public void shouldReadInetAddressCorrectly() throws UnknownHostException{ InetAddress localHost = InetAddress.getLocalHost(); when(rowMock.getInet(0)).thenReturn(localHost); InetAddress result = mappingCassandraConverter.readRow(InetAddress.class, rowMock); assertThat(result, is(equalTo(localHost))); } /** * @see DATACASS-280 * @see DATACASS-271 */ @Test public void shouldReadTimestampCorrectly() { Date date = new Date(1); when(rowMock.getTimestamp(0)).thenReturn(date); Date result = mappingCassandraConverter.readRow(Date.class, rowMock); assertThat(result, is(equalTo(date))); } /** * @see DATACASS-271 */ @Test public void shouldReadDateCorrectly() { LocalDate date = LocalDate.fromDaysSinceEpoch(1234); when(rowMock.getDate(0)).thenReturn(date); LocalDate result = mappingCassandraConverter.readRow(LocalDate.class, rowMock); assertThat(result, is(equalTo(date))); } /** * @see DATACASS-280 */ @Test public void shouldReadBooleanCorrectly() { when(rowMock.getBool(0)).thenReturn(true); Boolean result = mappingCassandraConverter.readRow(Boolean.class, rowMock); assertThat(result, is(equalTo(true))); } /** * @see DATACASS-296 */ @Test public void shouldReadLocalDateCorrectly() { LocalDateTime now = LocalDateTime.now(); Instant instant = now.toInstant(ZoneOffset.UTC); Row rowMock = RowMockUtil.newRowMock(column("id", "my-id", DataType.ascii()), column("localdate", Date.from(instant), DataType.timestamp())); TypeWithLocalDate result = mappingCassandraConverter.readRow(TypeWithLocalDate.class, rowMock); assertThat(result.localDate, is(notNullValue())); assertThat(result.localDate.getYear(), is(now.getYear())); assertThat(result.localDate.getMonthValue(), is(now.getMonthValue())); } /** * @see DATACASS-296 */ @Test public void shouldCreateInsertWithLocalDateCorrectly() { java.time.LocalDate now = java.time.LocalDate.now(); TypeWithLocalDate typeWithLocalDate = new TypeWithLocalDate(); typeWithLocalDate.localDate = now; Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(typeWithLocalDate, insert); assertThat(getValues(insert).contains(LocalDate.fromYearMonthDay(now.getYear(), now.getMonthValue(), now.getDayOfMonth())), is(true)); } /** * @see DATACASS-296 */ @Test public void shouldCreateUpdateWithLocalDateCorrectly() { java.time.LocalDate now = java.time.LocalDate.now(); TypeWithLocalDate typeWithLocalDate = new TypeWithLocalDate(); typeWithLocalDate.localDate = now; Update update = QueryBuilder.update("table"); mappingCassandraConverter.write(typeWithLocalDate, update); assertThat(getAssignmentValues(update).contains(LocalDate.fromYearMonthDay(now.getYear(), now.getMonthValue(), now.getDayOfMonth())), is(true)); } /** * @see DATACASS-296 */ @Test public void shouldCreateInsertWithLocalDateListUsingCassandraDate() { java.time.LocalDate now = java.time.LocalDate.now(); java.time.LocalDate localDate = java.time.LocalDate.of(2010, 7, 4); TypeWithLocalDate typeWithLocalDate = new TypeWithLocalDate(); typeWithLocalDate.list = Arrays.asList(now, localDate); Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(typeWithLocalDate, insert); List<LocalDate> dates = getListValue(insert); assertThat(dates, is(notNullValue(List.class))); assertThat(dates, hasItem(LocalDate.fromYearMonthDay(now.getYear(), now.getMonthValue(), now.getDayOfMonth()))); assertThat(dates, hasItem(LocalDate.fromYearMonthDay(2010, 7, 4))); } /** * @see DATACASS-296 */ @Test public void shouldCreateInsertWithLocalDateSetUsingCassandraDate() { java.time.LocalDate now = java.time.LocalDate.now(); java.time.LocalDate localDate = java.time.LocalDate.of(2010, 7, 4); TypeWithLocalDate typeWithLocalDate = new TypeWithLocalDate(); typeWithLocalDate.set = new HashSet<java.time.LocalDate>(Arrays.asList(now, localDate)); Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(typeWithLocalDate, insert); Set<LocalDate> dates = getSetValue(insert); assertThat(dates, is(notNullValue(Set.class))); assertThat(dates, hasItem(LocalDate.fromYearMonthDay(now.getYear(), now.getMonthValue(), now.getDayOfMonth()))); assertThat(dates, hasItem(LocalDate.fromYearMonthDay(2010, 7, 4))); } /** * @see DATACASS-296 */ @Test public void shouldReadLocalDateTimeUsingCassandraDateCorrectly() { Row rowMock = RowMockUtil.newRowMock(column("id", "my-id", DataType.ascii()), column("localDate", LocalDate.fromYearMonthDay(2010, 7, 4), DataType.date())); TypeWithLocalDateMappedToDate result = mappingCassandraConverter.readRow(TypeWithLocalDateMappedToDate.class, rowMock); assertThat(result.localDate, is(notNullValue())); assertThat(result.localDate.getYear(), is(2010)); assertThat(result.localDate.getMonthValue(), is(7)); assertThat(result.localDate.getDayOfMonth(), is(4)); } /** * @see DATACASS-296 */ @Test public void shouldCreateInsertWithLocalDateUsingCassandraDateCorrectly() { TypeWithLocalDateMappedToDate typeWithLocalDate = new TypeWithLocalDateMappedToDate(); typeWithLocalDate.localDate = java.time.LocalDate.of(2010, 7, 4); Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(typeWithLocalDate, insert); assertThat(getValues(insert).contains(LocalDate.fromYearMonthDay(2010, 7, 4)), is(true)); } /** * @see DATACASS-296 */ @Test public void shouldCreateUpdateWithLocalDateUsingCassandraDateCorrectly() { TypeWithLocalDateMappedToDate typeWithLocalDate = new TypeWithLocalDateMappedToDate(); typeWithLocalDate.localDate = java.time.LocalDate.of(2010, 7, 4); Update update = QueryBuilder.update("table"); mappingCassandraConverter.write(typeWithLocalDate, update); assertThat(getAssignmentValues(update), contains((Object) LocalDate.fromYearMonthDay(2010, 7, 4))); } /** * @see DATACASS-296 */ @Test public void shouldReadLocalDateTimeCorrectly() { LocalDateTime now = LocalDateTime.now(); Instant instant = now.toInstant(ZoneOffset.UTC); Row rowMock = RowMockUtil.newRowMock(column("id", "my-id", DataType.ascii()), column("localDateTime", Date.from(instant), DataType.timestamp())); TypeWithLocalDate result = mappingCassandraConverter.readRow(TypeWithLocalDate.class, rowMock); assertThat(result.localDateTime, is(notNullValue())); assertThat(result.localDateTime.getYear(), is(now.getYear())); assertThat(result.localDateTime.getMinute(), is(now.getMinute())); } /** * @see DATACASS-296 */ @Test public void shouldReadInstantCorrectly() { LocalDateTime now = LocalDateTime.now(); Instant instant = now.toInstant(ZoneOffset.UTC); Row rowMock = RowMockUtil.newRowMock(column("id", "my-id", DataType.ascii()), column("instant", Date.from(instant), DataType.timestamp())); TypeWithInstant result = mappingCassandraConverter.readRow(TypeWithInstant.class, rowMock); assertThat(result.instant, is(notNullValue())); assertThat(result.instant.getEpochSecond(), is(instant.getEpochSecond())); } /** * @see DATACASS-296 */ @Test public void shouldReadZoneIdCorrectly() { Row rowMock = RowMockUtil.newRowMock(column("id", "my-id", DataType.ascii()), column("zoneId", "Europe/Paris", DataType.varchar())); TypeWithZoneId result = mappingCassandraConverter.readRow(TypeWithZoneId.class, rowMock); assertThat(result.zoneId, is(notNullValue())); assertThat(result.zoneId.getId(), is(equalTo("Europe/Paris"))); } /** * @see DATACASS-296 */ @Test public void shouldReadJodaLocalDateTimeUsingCassandraDateCorrectly() { Row rowMock = RowMockUtil.newRowMock(column("id", "my-id", DataType.ascii()), column("localDate", LocalDate.fromYearMonthDay(2010, 7, 4), DataType.date())); TypeWithJodaLocalDateMappedToDate result = mappingCassandraConverter.readRow(TypeWithJodaLocalDateMappedToDate.class, rowMock); assertThat(result.localDate, is(notNullValue())); assertThat(result.localDate.getYear(), is(2010)); assertThat(result.localDate.getMonthOfYear(), is(7)); assertThat(result.localDate.getDayOfMonth(), is(4)); } /** * @see DATACASS-296 */ @Test public void shouldCreateInsertWithJodaLocalDateUsingCassandraDateCorrectly() { TypeWithJodaLocalDateMappedToDate typeWithLocalDate = new TypeWithJodaLocalDateMappedToDate(); typeWithLocalDate.localDate = new org.joda.time.LocalDate(2010, 7, 4); Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(typeWithLocalDate, insert); assertThat(getValues(insert).contains(LocalDate.fromYearMonthDay(2010, 7, 4)), is(true)); } /** * @see DATACASS-296 */ @Test public void shouldCreateUpdateWithJodaLocalDateUsingCassandraDateCorrectly() { TypeWithJodaLocalDateMappedToDate typeWithLocalDate = new TypeWithJodaLocalDateMappedToDate(); typeWithLocalDate.localDate = new org.joda.time.LocalDate(2010, 7, 4); Update update = QueryBuilder.update("table"); mappingCassandraConverter.write(typeWithLocalDate, update); assertThat(getAssignmentValues(update), contains((Object) LocalDate.fromYearMonthDay(2010, 7, 4))); } /** * @see DATACASS-296 */ @Test public void shouldReadThreeTenBpLocalDateTimeUsingCassandraDateCorrectly() { Row rowMock = RowMockUtil.newRowMock(column("id", "my-id", DataType.ascii()), column("localDate", LocalDate.fromYearMonthDay(2010, 7, 4), DataType.date())); TypeWithThreeTenBpLocalDateMappedToDate result = mappingCassandraConverter.readRow(TypeWithThreeTenBpLocalDateMappedToDate.class, rowMock); assertThat(result.localDate, is(notNullValue())); assertThat(result.localDate.getYear(), is(2010)); assertThat(result.localDate.getMonthValue(), is(7)); assertThat(result.localDate.getDayOfMonth(), is(4)); } /** * @see DATACASS-296 */ @Test public void shouldCreateInsertWithThreeTenBpLocalDateUsingCassandraDateCorrectly() { TypeWithThreeTenBpLocalDateMappedToDate typeWithLocalDate = new TypeWithThreeTenBpLocalDateMappedToDate(); typeWithLocalDate.localDate = org.threeten.bp.LocalDate.of(2010, 7, 4); Insert insert = QueryBuilder.insertInto("table"); mappingCassandraConverter.write(typeWithLocalDate, insert); assertThat(getValues(insert).contains(LocalDate.fromYearMonthDay(2010, 7, 4)), is(true)); } /** * @see DATACASS-296 */ @Test public void shouldCreateUpdateWithThreeTenBpLocalDateUsingCassandraDateCorrectly() { TypeWithThreeTenBpLocalDateMappedToDate typeWithLocalDate = new TypeWithThreeTenBpLocalDateMappedToDate(); typeWithLocalDate.localDate = org.threeten.bp.LocalDate.of(2010, 7, 4); Update update = QueryBuilder.update("table"); mappingCassandraConverter.write(typeWithLocalDate, update); assertThat(getAssignmentValues(update), contains((Object) LocalDate.fromYearMonthDay(2010, 7, 4))); } @SuppressWarnings("unchecked") private <T> List<T> getListValue(Insert statement) { List<Object> values = getValues(statement); for (Object value : values) { if (value instanceof List) { return (List<T>) value; } } return null; } @SuppressWarnings("unchecked") private <T> Set<T> getSetValue(Insert statement) { List<Object> values = getValues(statement); for (Object value : values) { if (value instanceof Set) { return (Set<T>) value; } } return null; } @SuppressWarnings("unchecked") private List<Object> getValues(Insert statement) { return (List<Object>) ReflectionTestUtils.getField(statement, "values"); } @SuppressWarnings("unchecked") private List<Object> getAssignmentValues(Update statement) { List<Object> result = new ArrayList<Object>(); Assignments assignments = (Assignments) ReflectionTestUtils.getField(statement, "assignments"); List<Assignment> listOfAssignments = (List<Assignment>) ReflectionTestUtils.getField(assignments, "assignments"); for (Assignment assignment : listOfAssignments) { result.add(ReflectionTestUtils.getField(assignment, "value")); } return result; } private List<Object> getWhereValues(Update statement) { return getWhereValues(statement.where()); } private List<Object> getWhereValues(BuiltStatement where) { List<Object> result = new ArrayList<Object>(); List<Clause> clauses = (List<Clause>) ReflectionTestUtils.getField(where, "clauses"); for (Clause clause : clauses) { result.add(ReflectionTestUtils.getField(clause, "value")); } return result; } @Table public static class UnsupportedEnumToOrdinalMapping { @PrimaryKey private String id; @CassandraType(type = Name.INT) private Condition asOrdinal; public String getId() { return id; } public void setId(String id) { this.id = id; } public Condition getAsOrdinal() { return asOrdinal; } public void setAsOrdinal(Condition asOrdinal) { this.asOrdinal = asOrdinal; } } @Table public static class WithEnumColumns { @PrimaryKey private String id; private Condition condition; public String getId() { return id; } public void setId(String id) { this.id = id; } public Condition getCondition() { return condition; } public void setCondition(Condition condition) { this.condition = condition; } } @PrimaryKeyClass public static class EnumCompositePrimaryKey implements Serializable { @PrimaryKeyColumn(ordinal = 1, type = PrimaryKeyType.PARTITIONED) private Condition condition; public EnumCompositePrimaryKey() {} public EnumCompositePrimaryKey(Condition condition) { this.condition = condition; } public Condition getCondition() { return condition; } public void setCondition(Condition condition) { this.condition = condition; } } @Table public static class EnumPrimaryKey { @PrimaryKey private Condition condition; public Condition getCondition() { return condition; } public void setCondition(Condition condition) { this.condition = condition; } } @Table public static class CompositeKeyThing { @PrimaryKey private EnumCompositePrimaryKey key; public CompositeKeyThing() {} public CompositeKeyThing(EnumCompositePrimaryKey key) { this.key = key; } public EnumCompositePrimaryKey getKey() { return key; } public void setKey(EnumCompositePrimaryKey key) { this.key = key; } } public enum Condition { MINT, USED; } @Table public static class TypeWithLocalDate { @PrimaryKey private String id; java.time.LocalDate localDate; java.time.LocalDateTime localDateTime; List<java.time.LocalDate> list; Set<java.time.LocalDate> set; } /** * Uses Cassandra's {@link Name#DATE} which maps by default to {@link LocalDate} */ @Table public static class TypeWithLocalDateMappedToDate { @PrimaryKey private String id; @CassandraType(type = Name.DATE) java.time.LocalDate localDate; } /** * Uses Cassandra's {@link Name#DATE} which maps by default to Joda {@link LocalDate} */ @Table public static class TypeWithJodaLocalDateMappedToDate { @PrimaryKey private String id; @CassandraType(type = Name.DATE) org.joda.time.LocalDate localDate; } /** * Uses Cassandra's {@link Name#DATE} which maps by default to Joda {@link LocalDate} */ @Table public static class TypeWithThreeTenBpLocalDateMappedToDate { @PrimaryKey private String id; @CassandraType(type = Name.DATE) org.threeten.bp.LocalDate localDate; } @Table public static class TypeWithInstant { @PrimaryKey private String id; Instant instant; } @Table public static class TypeWithZoneId { @PrimaryKey private String id; ZoneId zoneId; } }
[ "527474541@qq.com" ]
527474541@qq.com
5b0319a7898a802a642014531f4013cc9d227410
bd5c659b4f3e524a2985421854d253fa35dc86a2
/src/main/java/org/example/lesson4/InnerClass.java
d2549b2184fcf96c7a40f58ac2b667f597d0a4a5
[]
no_license
zvuk331/learn_java_core
e41a5bad9fa1d89d0f0650a1953a9e0836afd684
25651ac5c7df2e9ecafc1a9d0edc1081707b9fdf
refs/heads/master
2023-03-14T20:08:41.164752
2021-02-26T13:17:37
2021-02-26T13:17:37
328,897,110
0
0
null
2021-02-26T13:17:37
2021-01-12T06:46:30
null
UTF-8
Java
false
false
1,003
java
package org.example.lesson4; public class InnerClass { String color; int horsePower; Engine engine; public InnerClass(String color, int horsePower) { this.color = color; this.horsePower = horsePower; engine = this.new Engine(horsePower); } @Override public String toString() { return "InnerClass{" + "color='" + color + '\'' + ", horsePower=" + horsePower + ", engine=" + engine + '}'; } class Engine { int horsePower; public Engine(int horsePower) { this.horsePower = horsePower; } @Override public String toString() { return "Engine{" + "horsePower=" + horsePower + '}'; } } } class Test2 { public static void main(String[] args) { InnerClass innerClass = new InnerClass("black", 255); System.out.println(innerClass); } }
[ "zvuk331@gmail.com" ]
zvuk331@gmail.com
d131e6f435929c770ba585b4ec386cf87d065209
b2252c544abf98ed8b685a20c62ee6acb68598aa
/FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/external/samples/ConceptTensorFlowObjectDetection.java
b656c10c0b79c4c990bdf64fc73ff6b0bf044906
[ "BSD-3-Clause" ]
permissive
ftcimmortals/SkyStone-master
6140f9b5815601642a04e56ca188b2d2d66e7420
3c0ef81c3e222e8803de95dca3efada705f5a555
refs/heads/master
2020-09-12T04:44:45.488651
2020-02-01T08:48:18
2020-02-01T08:48:18
222,310,758
0
1
null
null
null
null
UTF-8
Java
false
false
8,196
java
/* Copyright (c) 2019 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.robotcontroller.external.samples; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import java.util.List; import org.firstinspires.ftc.robotcore.external.ClassFactory; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer.CameraDirection; import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector; import org.firstinspires.ftc.robotcore.external.tfod.Recognition; /** * This 2019-2020 OpMode illustrates the basics of using the TensorFlow Object Detection API to * determine the position of the Skystone game elements. * * Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name. * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list. * * IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as * is explained below. */ @TeleOp(name = "Concept: TensorFlow Object Detection", group = "Concept") @Disabled public class ConceptTensorFlowObjectDetection extends LinearOpMode { private static final String TFOD_MODEL_ASSET = "Skystone.tflite"; private static final String LABEL_FIRST_ELEMENT = "Stone"; private static final String LABEL_SECOND_ELEMENT = "Skystone"; /* * IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which * 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function. * A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer * web site at https://developer.vuforia.com/license-manager. * * Vuforia license keys are always 380 characters long, and look as if they contain mostly * random data. As an example, here is a example of a fragment of a valid key: * ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ... * Once you've obtained a license key, copy the string from the Vuforia web site * and paste it in to your code on the next line, between the double quotes. */ private static final String VUFORIA_KEY = "AQGs+8X/////AAABmUlgVbItAkXMhUiMsKHBxsOOsOSky4xQM7QN/1ugM+DkgNZQYexbfsQkK4+aDQexx9sWXZr+TPwDLQ8aXvJ3cru61Y/17wBrCRs2hGeLOENx0hRyY+sTnH2PJSXN+qaKSggoE67PpO33KHKdUD48x9T/dzeg9Rtg2PVEQBezKKa1SMq5AJGXTLI2YnjsXPJ/Uk+9TNcXfaCqxWAgFXaT9bLsyaXRLdaudyEq+qG6d73EOsV9RI2LY/RJGFPhL34Cs8WoRLtuXl8uo/mfvaLsaZrj0w6mxF+9hiYPEXrKwCXuFxc0pSXomDaWTE+NyetotMlsYNRJOccVhtUerhZ13nXfxUk7mECSNod/YBYiVrSp"; /** * {@link #vuforia} is the variable we will use to store our instance of the Vuforia * localization engine. */ private VuforiaLocalizer vuforia; /** * {@link #tfod} is the variable we will use to store our instance of the TensorFlow Object * Detection engine. */ private TFObjectDetector tfod; @Override public void runOpMode() { // The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that // first. initVuforia(); if (ClassFactory.getInstance().canCreateTFObjectDetector()) { initTfod(); } else { telemetry.addData("Sorry!", "This device is not compatible with TFOD"); } /** * Activate TensorFlow Object Detection before we wait for the start command. * Do it here so that the Camera Stream window will have the TensorFlow annotations visible. **/ if (tfod != null) { tfod.activate(); } /** Wait for the game to begin */ telemetry.addData(">", "Press Play to start op mode"); telemetry.update(); waitForStart(); if (opModeIsActive()) { while (opModeIsActive()) { if (tfod != null) { // getUpdatedRecognitions() will return null if no new information is available since // the last time that call was made. List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions(); if (updatedRecognitions != null) { telemetry.addData("# Object Detected", updatedRecognitions.size()); // step through the list of recognitions and display boundary info. int i = 0; for (Recognition recognition : updatedRecognitions) { telemetry.addData(String.format("label (%d)", i), recognition.getLabel()); telemetry.addData(String.format(" left,top (%d)", i), "%.03f , %.03f", recognition.getLeft(), recognition.getTop()); telemetry.addData(String.format(" right,bottom (%d)", i), "%.03f , %.03f", recognition.getRight(), recognition.getBottom()); } telemetry.update(); } } } } if (tfod != null) { tfod.shutdown(); } } /** * Initialize the Vuforia localization engine. */ private void initVuforia() { /* * Configure Vuforia by creating a Parameter object, and passing it to the Vuforia engine. */ VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(); parameters.vuforiaLicenseKey = VUFORIA_KEY; parameters.cameraDirection = CameraDirection.BACK; // Instantiate the Vuforia engine vuforia = ClassFactory.getInstance().createVuforia(parameters); // Loading trackables is not necessary for the TensorFlow Object Detection engine. } /** * Initialize the TensorFlow Object Detection engine. */ private void initTfod() { int tfodMonitorViewId = hardwareMap.appContext.getResources().getIdentifier( "tfodMonitorViewId", "id", hardwareMap.appContext.getPackageName()); TFObjectDetector.Parameters tfodParameters = new TFObjectDetector.Parameters(tfodMonitorViewId); tfodParameters.minimumConfidence = 0.8; tfod = ClassFactory.getInstance().createTFObjectDetector(tfodParameters, vuforia); tfod.loadModelFromAsset(TFOD_MODEL_ASSET, LABEL_FIRST_ELEMENT, LABEL_SECOND_ELEMENT); } }
[ "hemantjere@yahoo.com" ]
hemantjere@yahoo.com
687c0d55fd35545d1118781fb537df96dfd354c7
25a40115806d267b7ac6dde7128aae1d6eb55695
/demo-backend/src/main/java/com/sshpr/cgnznt/demo/configuration/BasicConfig.java
8797f960eccb6e902e634e9e8adb96cc7df8ac4f
[]
no_license
SaintAmeN/cgnznt
a6be4e308346f59f0e6d3a5656fdead428669013
5afb7987a4ba5aadf66cbb077a30879ff43d28e4
refs/heads/main
2023-04-02T10:41:27.749912
2021-04-06T21:35:37
2021-04-06T21:43:03
355,283,046
1
0
null
null
null
null
UTF-8
Java
false
false
814
java
package com.sshpr.cgnznt.demo.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.client.RestTemplate; import java.util.UUID; @Configuration public class BasicConfig { @Bean(name = "myName") public String myNameBean() { String randomString = UUID.randomUUID().toString(); return "AmeN - " + randomString.substring(0, 5); } @Bean public PasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } }
[ "p.reclaw@apsystems.tech" ]
p.reclaw@apsystems.tech
d05c1f6056946f9b8ef8dd26feb7457a1aa4c7b8
f3618bd394538114a1352a71b6092d6bd01f5953
/src/main/java/com/example/code/enums/PatternDate.java
e6373ac2830e674759ad6411d7b4c65263811d9c
[]
no_license
axeleguia/tutorial-jdbc-java
dc91de2ff018ef60d600954f81d8be9d47773143
37d12b0dd28026b1af089b61954b4e683ed93946
refs/heads/master
2023-02-03T11:51:53.178486
2016-03-01T20:13:03
2016-03-01T20:13:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
522
java
package com.example.code.enums; public enum PatternDate { yearMonthDay("yearMonthDay", "yyyy-MM-dd hh:mm:ss"), dayMonthYear("dayMonthYear", "dd-MM-yyyy hh:mm:ss"); private String key; private String value; private PatternDate(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
[ "axeleguia.chero@outlook.com" ]
axeleguia.chero@outlook.com