blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
766e6211ca5c9c1b3737fe38754d8d47abcdaa00
Java
SilentHiKing/MyApplication
/app/src/main/java/com/h/myapplication/bean/Errors.java
UTF-8
619
2.15625
2
[]
no_license
package com.h.myapplication.bean; public class Errors { public final static Throwable ERROR_NETWORK = new NetworkError(); public final static Throwable ERROR_SINGLE = new SingleError(); public final static Throwable ERROR_EMPTY_INPUT = new EmptyInputError(); public final static Throwable ERROR_EMPTY_RESULTS = new EmptyResultsError(); static public class NetworkError extends Throwable { } static public class EmptyInputError extends Throwable { } static public class EmptyResultsError extends Throwable { } static public class SingleError extends Throwable { } }
true
9ca5f1327926b034cccc35862fe2015a9569da18
Java
kptnewler/ZhongSuLogistics
/app/src/main/java/com/zhongsuwuliu/zhongsulogistics/JavaBean/ContainerBean.java
UTF-8
1,001
2.1875
2
[]
no_license
package com.zhongsuwuliu.zhongsulogistics.JavaBean; import java.io.Serializable; /** * Created by 刺雒 on 2016/11/23. */ public class ContainerBean implements Serializable{ private String ContainerID;//货箱ID private String KindID;//种类ID private String WarehouseID;//绑定库区ID private String temporaryID;//临时编号 public String getTemporaryID() { return temporaryID; } public void setTemporaryID(String temporaryID) { this.temporaryID = temporaryID; } public String getContainerID() { return ContainerID; } public void setContainerID(String containerID) { ContainerID = containerID; } public String getKindID() { return KindID; } public void setKindID(String kindID) { KindID = kindID; } public String getWarehouseID() { return WarehouseID; } public void setWarehouseID(String warehouseID) { WarehouseID = warehouseID; } }
true
79012682927cfc49f47b4f59df144f380132c9fa
Java
rusl-krow/Shagaliev_11-806
/HW5/src/com/company/num2.java
UTF-8
412
3.15625
3
[]
no_license
import java.util.Scanner; public class num2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String number = sc.next(); char[] ch = number.toCharArray(); int res = 0; for (int i = 0; i < ch.length; i++) { res += Math.pow(10, ch.length - i - 1) * (ch[i] - '0'); } System.out.println(res); } }
true
cdfcc567b08ca2cfc0d904979a402b09caa9a6ca
Java
beststarry/CS2110Projects
/src/a1/Person.java
UTF-8
5,165
4.09375
4
[]
no_license
package a1; /** an instance of a person */ public class Person { // class invariant: non-null and non-empty string private String name; // class invariant: any integer that represents a valid year private int birthYear; // class invariant: in range [1..12] private int birthMonth; // class invariant: in range [1..31] private int birthDay; // class invariant: integer >=0 private int numChildren; // class invariant: a person's mother of type Person, null if unknown private Person mother; // class invariant: a person's father of type Person, null if unknown private Person father; /** * Constructor: Initialize a person with the given name and birthdate, and unknown parents. * The name must be non-null and non-empty. * * @param name is non-null and non-empty * @param birthYear is a valid year * @param birthMonth is in the range 1..12 * @param birthDay must be in the range 1..31 * */ public Person(String name, int birthYear, int birthMonth, int birthDay) { assert(name!=null && name!=""); assert(birthMonth>=1 && birthMonth<=12); assert(birthDay>=1 && birthDay <=31); this.name = name; this.birthYear = birthYear; this.birthMonth = birthMonth; this.birthDay = birthDay; this.mother = null; this.father = null; } /** returns this person's name */ public String name() { return name; } /** returns this person's mother */ public Person mother() { return this.mother; } /** returns this person's father */ public Person father() { return this.father; } /** returns this person's birth year */ public int birthYear() { return birthYear; } /** returns this person's birth month*/ public int birthMonth() { return birthMonth; } /** returns this person's birth day */ public int birthDay() { return this.birthDay; } /** returns the number of Persons with this as a parent */ public int numChildren() { return numChildren; } /** * changes this person's mother to m * if m is null, mother is unknown * * calls a helper function checkMother * @param m is this person's mother of type of Person */ public void setMother(Person m) { if (m == null) { if(this.mother!=null) { this.mother.numChildren --; this.mother = null; } } else { checkMother(m); this.mother = m; this.mother.numChildren ++; } } /** * changes this person's father to f * if f is null, father is unknown * * calls a helper function checkFather * @param f is this person's father of type Person * */ public void setFather(Person f) { if (f == null) { if(this.father!=null) { this.father.numChildren --; this.father = null; } } else { checkFather(f); this.father = f; this.father.numChildren ++; } } /** * checks if previous father and current father are the same person * updates numChildren of previous father if they are different fathers * * @param f is a father of type Person **/ private void checkFather(Person f) { if (this.father!=null && this.father!=f) { this.father.numChildren--; } } /** * checks if previous father and current father are the same person * updates numChildren of previous father if they are different fathers * * @param m is a mother of type Person **/ private void checkMother(Person m) { if (this.mother!=null && this.mother!=m) { this.mother.numChildren--; } } /** * Change this person’s name * @param name a String of new name. */ public void setName(String name) { assert(name != null && name!=""); this.name=name; } /** * Change this person’s birth year to y. * @param y a integer of new birth year. */ public void setBirthYear(int y) { birthYear=y; } /** * Change this person’s birth month to m. * @param m a integer of new birth month. */ public void setBirthMonth(int m) { assert(m>=1 && m<=12); birthMonth=m; } /** * Change this person’s birth day to d. * @param d a integer of new birth day. */ public void setBirthDay(int d) { assert(d>=1 && d <=31); birthDay=d; } /** * Find if one is the a half sibling of another. * Precondition: requires that other is non-null. * @param other a Person object one compared with. * @return true if this and other share a known parent. */ public boolean isHalfSibling(Person other) { assert(other != null); if (other.father()==this.father() || other.father()==this.mother() || other.mother()== this.mother() || other.mother()== this.father()) return true; return false; } /** * Find if one is older than another. * Precondition: requires that other is non-null. * @param other a Person object one compared with. * @return true if this person’s birthday is before other’s. */ public boolean isOlderThan(Person other) { assert(other != null); if (this.birthYear() != other.birthYear()) return this.birthYear() < other.birthYear(); if (this.birthMonth() != other.birthMonth()) return this.birthMonth() < other.birthMonth(); if (this.birthDay()!= other.birthDay()) return this.birthDay() < other.birthDay(); return false; } }
true
6ee6f008a3f8b9cc93bb06db86439f8421456029
Java
filipushandi23/Threadther-Server
/src/java/WS/WSCashier.java
UTF-8
2,315
2.421875
2
[]
no_license
/* * 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 WS; import controller.CustomerCtrl; import controller.MovieCtrl; import dao.StudioDAO; import dao.UserDAO; import java.util.ArrayList; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import model.Movie; import model.Schedule; import model.Seat; import model.Studio; import model.User; /** * * @author Jovin Angelico */ @WebService(serviceName = "WSCashier") public class WSCashier { /** * This is a sample web service operation */ @WebMethod(operationName = "login") public boolean login(@WebParam(name = "email") String email, @WebParam(name = "password") String password) { return new CustomerCtrl().login(email, password); } @WebMethod(operationName = "getUserByEmail") public User getUserByEmail(@WebParam(name = "email") String email){ return new UserDAO().findById(email); } @WebMethod(operationName = "getShowingMovies") public ArrayList<Movie> getShowingMovies() { return new MovieCtrl().showShowingMovies(); } @WebMethod(operationName = "getMovieById") public Movie getMovieById(@WebParam(name = "movieId")String movieId) { return new MovieCtrl().getMovie(movieId); } @WebMethod(operationName = "getComingSoonMovies") public ArrayList<Movie> getComingSoonMovies() { return new MovieCtrl().showComingSoonMovies(); } @WebMethod(operationName = "getAllScheduleByMovieId") public ArrayList<Schedule> getAllScheduleByMovieId(@WebParam(name = "movieId") int movieId) { return new MovieCtrl().showScheduleByMovie(movieId); } @WebMethod(operationName = "getSeatByStudioNumber") public ArrayList<Seat> getSeatByStudioNumber(@WebParam(name = "studioNumber") int studioNumber) { return new MovieCtrl().showSeatByStudioNumber(studioNumber); } @WebMethod(operationName = "getStudioByStudioNumber") public Studio getStudioByStudioNumber(@WebParam(name = "studioNumber") String studioNumber) { return new StudioDAO().findById(studioNumber); } }
true
18b73d837e45d6d21598e3fb03fb4bd48b50e9d6
Java
JO-YUN/app-api-fy
/src/main/java/com/mscs/app/web/dao/NewsInfoNHMapper.java
UTF-8
867
1.890625
2
[]
no_license
package com.mscs.app.web.dao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.mscs.app.common.dto.resp.RespNewsInfoNHDto; import com.mscs.app.common.util.Page; import com.mscs.app.web.model.NewsInfo; import com.mscs.app.web.model.NewsInfoNH; @Repository @Mapper public interface NewsInfoNHMapper { public List<RespNewsInfoNHDto> queryNewsInfoListPage(@Param("page")Page page, @Param("obj")NewsInfoNH obj); public int queryNewsInfoForCount(@Param("page")Page page, @Param("obj") NewsInfoNH obj); public RespNewsInfoNHDto queryNewsInfoById(@Param("obj") NewsInfoNH obj); public List<RespNewsInfoNHDto> queryNewsInfoList(@Param("obj") NewsInfoNH obj); void updateNewsInfoData(NewsInfo news); }
true
ee83b6fce96db105d8d3e47889d720a43665e6e6
Java
liferayenespanol/BookingSystem
/BookingSystem-portlet/docroot/WEB-INF/src/com/LiferayEnEspanol/booking/model/impl/MeetingRoomModelImpl.java
UTF-8
22,182
1.695313
2
[]
no_license
package com.LiferayEnEspanol.booking.model.impl; import com.LiferayEnEspanol.booking.model.MeetingRoom; import com.LiferayEnEspanol.booking.model.MeetingRoomModel; import com.LiferayEnEspanol.booking.model.MeetingRoomSoap; import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.json.JSON; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.ProxyUtil; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.model.CacheModel; import com.liferay.portal.model.impl.BaseModelImpl; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.util.PortalUtil; import com.liferay.portlet.expando.model.ExpandoBridge; import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil; import java.io.Serializable; import java.sql.Types; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * The base model implementation for the MeetingRoom service. Represents a row in the &quot;LiferayEnEspanol_MeetingRoom&quot; database table, with each column mapped to a property of this class. * * <p> * This implementation and its corresponding interface {@link com.LiferayEnEspanol.booking.model.MeetingRoomModel} exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in {@link MeetingRoomImpl}. * </p> * * @author Jesus Flores * @see MeetingRoomImpl * @see com.LiferayEnEspanol.booking.model.MeetingRoom * @see com.LiferayEnEspanol.booking.model.MeetingRoomModel * @generated */ @JSON(strict = true) public class MeetingRoomModelImpl extends BaseModelImpl<MeetingRoom> implements MeetingRoomModel { /* * NOTE FOR DEVELOPERS: * * Never modify or reference this class directly. All methods that expect a meeting room model instance should use the {@link com.LiferayEnEspanol.booking.model.MeetingRoom} interface instead. */ public static final String TABLE_NAME = "LiferayEnEspanol_MeetingRoom"; public static final Object[][] TABLE_COLUMNS = { { "meetingRoomId", Types.BIGINT }, { "groupId", Types.BIGINT }, { "companyId", Types.BIGINT }, { "userId", Types.BIGINT }, { "userName", Types.VARCHAR }, { "createDate", Types.TIMESTAMP }, { "modifiedDate", Types.TIMESTAMP }, { "name", Types.VARCHAR }, { "code_", Types.VARCHAR }, { "capacity", Types.INTEGER }, { "location", Types.BOOLEAN }, { "active_", Types.BOOLEAN } }; public static final String TABLE_SQL_CREATE = "create table LiferayEnEspanol_MeetingRoom (meetingRoomId LONG not null primary key,groupId LONG,companyId LONG,userId LONG,userName VARCHAR(75) null,createDate DATE null,modifiedDate DATE null,name VARCHAR(75) null,code_ VARCHAR(75) null,capacity INTEGER,location BOOLEAN,active_ BOOLEAN)"; public static final String TABLE_SQL_DROP = "drop table LiferayEnEspanol_MeetingRoom"; public static final String ORDER_BY_JPQL = " ORDER BY meetingRoom.name ASC"; public static final String ORDER_BY_SQL = " ORDER BY LiferayEnEspanol_MeetingRoom.name ASC"; public static final String DATA_SOURCE = "liferayDataSource"; public static final String SESSION_FACTORY = "liferaySessionFactory"; public static final String TX_MANAGER = "liferayTransactionManager"; public static final boolean ENTITY_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get( "value.object.entity.cache.enabled.com.LiferayEnEspanol.booking.model.MeetingRoom"), true); public static final boolean FINDER_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get( "value.object.finder.cache.enabled.com.LiferayEnEspanol.booking.model.MeetingRoom"), true); public static final boolean COLUMN_BITMASK_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get( "value.object.column.bitmask.enabled.com.LiferayEnEspanol.booking.model.MeetingRoom"), true); public static long ACTIVE_COLUMN_BITMASK = 1L; public static long CAPACITY_COLUMN_BITMASK = 2L; public static long NAME_COLUMN_BITMASK = 4L; public static final long LOCK_EXPIRATION_TIME = GetterUtil.getLong(com.liferay.util.service.ServiceProps.get( "lock.expiration.time.com.LiferayEnEspanol.booking.model.MeetingRoom")); private static ClassLoader _classLoader = MeetingRoom.class.getClassLoader(); private static Class<?>[] _escapedModelInterfaces = new Class[] { MeetingRoom.class }; private long _meetingRoomId; private long _groupId; private long _companyId; private long _userId; private String _userUuid; private String _userName; private Date _createDate; private Date _modifiedDate; private String _name; private String _originalName; private String _code; private int _capacity; private int _originalCapacity; private boolean _setOriginalCapacity; private boolean _location; private boolean _active; private boolean _originalActive; private boolean _setOriginalActive; private long _columnBitmask; private MeetingRoom _escapedModel; public MeetingRoomModelImpl() { } /** * Converts the soap model instance into a normal model instance. * * @param soapModel the soap model instance to convert * @return the normal model instance */ public static MeetingRoom toModel(MeetingRoomSoap soapModel) { if (soapModel == null) { return null; } MeetingRoom model = new MeetingRoomImpl(); model.setMeetingRoomId(soapModel.getMeetingRoomId()); model.setGroupId(soapModel.getGroupId()); model.setCompanyId(soapModel.getCompanyId()); model.setUserId(soapModel.getUserId()); model.setUserName(soapModel.getUserName()); model.setCreateDate(soapModel.getCreateDate()); model.setModifiedDate(soapModel.getModifiedDate()); model.setName(soapModel.getName()); model.setCode(soapModel.getCode()); model.setCapacity(soapModel.getCapacity()); model.setLocation(soapModel.getLocation()); model.setActive(soapModel.getActive()); return model; } /** * Converts the soap model instances into normal model instances. * * @param soapModels the soap model instances to convert * @return the normal model instances */ public static List<MeetingRoom> toModels(MeetingRoomSoap[] soapModels) { if (soapModels == null) { return null; } List<MeetingRoom> models = new ArrayList<MeetingRoom>(soapModels.length); for (MeetingRoomSoap soapModel : soapModels) { models.add(toModel(soapModel)); } return models; } @Override public long getPrimaryKey() { return _meetingRoomId; } @Override public void setPrimaryKey(long primaryKey) { setMeetingRoomId(primaryKey); } @Override public Serializable getPrimaryKeyObj() { return _meetingRoomId; } @Override public void setPrimaryKeyObj(Serializable primaryKeyObj) { setPrimaryKey(((Long) primaryKeyObj).longValue()); } @Override public Class<?> getModelClass() { return MeetingRoom.class; } @Override public String getModelClassName() { return MeetingRoom.class.getName(); } @Override public Map<String, Object> getModelAttributes() { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("meetingRoomId", getMeetingRoomId()); attributes.put("groupId", getGroupId()); attributes.put("companyId", getCompanyId()); attributes.put("userId", getUserId()); attributes.put("userName", getUserName()); attributes.put("createDate", getCreateDate()); attributes.put("modifiedDate", getModifiedDate()); attributes.put("name", getName()); attributes.put("code", getCode()); attributes.put("capacity", getCapacity()); attributes.put("location", getLocation()); attributes.put("active", getActive()); return attributes; } @Override public void setModelAttributes(Map<String, Object> attributes) { Long meetingRoomId = (Long) attributes.get("meetingRoomId"); if (meetingRoomId != null) { setMeetingRoomId(meetingRoomId); } Long groupId = (Long) attributes.get("groupId"); if (groupId != null) { setGroupId(groupId); } Long companyId = (Long) attributes.get("companyId"); if (companyId != null) { setCompanyId(companyId); } Long userId = (Long) attributes.get("userId"); if (userId != null) { setUserId(userId); } String userName = (String) attributes.get("userName"); if (userName != null) { setUserName(userName); } Date createDate = (Date) attributes.get("createDate"); if (createDate != null) { setCreateDate(createDate); } Date modifiedDate = (Date) attributes.get("modifiedDate"); if (modifiedDate != null) { setModifiedDate(modifiedDate); } String name = (String) attributes.get("name"); if (name != null) { setName(name); } String code = (String) attributes.get("code"); if (code != null) { setCode(code); } Integer capacity = (Integer) attributes.get("capacity"); if (capacity != null) { setCapacity(capacity); } Boolean location = (Boolean) attributes.get("location"); if (location != null) { setLocation(location); } Boolean active = (Boolean) attributes.get("active"); if (active != null) { setActive(active); } } @JSON @Override public long getMeetingRoomId() { return _meetingRoomId; } @Override public void setMeetingRoomId(long meetingRoomId) { _meetingRoomId = meetingRoomId; } @JSON @Override public long getGroupId() { return _groupId; } @Override public void setGroupId(long groupId) { _groupId = groupId; } @JSON @Override public long getCompanyId() { return _companyId; } @Override public void setCompanyId(long companyId) { _companyId = companyId; } @JSON @Override public long getUserId() { return _userId; } @Override public void setUserId(long userId) { _userId = userId; } @Override public String getUserUuid() throws SystemException { return PortalUtil.getUserValue(getUserId(), "uuid", _userUuid); } @Override public void setUserUuid(String userUuid) { _userUuid = userUuid; } @JSON @Override public String getUserName() { if (_userName == null) { return StringPool.BLANK; } else { return _userName; } } @Override public void setUserName(String userName) { _userName = userName; } @JSON @Override public Date getCreateDate() { return _createDate; } @Override public void setCreateDate(Date createDate) { _createDate = createDate; } @JSON @Override public Date getModifiedDate() { return _modifiedDate; } @Override public void setModifiedDate(Date modifiedDate) { _modifiedDate = modifiedDate; } @JSON @Override public String getName() { if (_name == null) { return StringPool.BLANK; } else { return _name; } } @Override public void setName(String name) { _columnBitmask = -1L; if (_originalName == null) { _originalName = _name; } _name = name; } public String getOriginalName() { return GetterUtil.getString(_originalName); } @JSON @Override public String getCode() { if (_code == null) { return StringPool.BLANK; } else { return _code; } } @Override public void setCode(String code) { _code = code; } @JSON @Override public int getCapacity() { return _capacity; } @Override public void setCapacity(int capacity) { _columnBitmask |= CAPACITY_COLUMN_BITMASK; if (!_setOriginalCapacity) { _setOriginalCapacity = true; _originalCapacity = _capacity; } _capacity = capacity; } public int getOriginalCapacity() { return _originalCapacity; } @JSON @Override public boolean getLocation() { return _location; } @Override public boolean isLocation() { return _location; } @Override public void setLocation(boolean location) { _location = location; } @JSON @Override public boolean getActive() { return _active; } @Override public boolean isActive() { return _active; } @Override public void setActive(boolean active) { _columnBitmask |= ACTIVE_COLUMN_BITMASK; if (!_setOriginalActive) { _setOriginalActive = true; _originalActive = _active; } _active = active; } public boolean getOriginalActive() { return _originalActive; } public long getColumnBitmask() { return _columnBitmask; } @Override public ExpandoBridge getExpandoBridge() { return ExpandoBridgeFactoryUtil.getExpandoBridge(getCompanyId(), MeetingRoom.class.getName(), getPrimaryKey()); } @Override public void setExpandoBridgeAttributes(ServiceContext serviceContext) { ExpandoBridge expandoBridge = getExpandoBridge(); expandoBridge.setAttributes(serviceContext); } @Override public MeetingRoom toEscapedModel() { if (_escapedModel == null) { _escapedModel = (MeetingRoom) ProxyUtil.newProxyInstance(_classLoader, _escapedModelInterfaces, new AutoEscapeBeanHandler(this)); } return _escapedModel; } @Override public Object clone() { MeetingRoomImpl meetingRoomImpl = new MeetingRoomImpl(); meetingRoomImpl.setMeetingRoomId(getMeetingRoomId()); meetingRoomImpl.setGroupId(getGroupId()); meetingRoomImpl.setCompanyId(getCompanyId()); meetingRoomImpl.setUserId(getUserId()); meetingRoomImpl.setUserName(getUserName()); meetingRoomImpl.setCreateDate(getCreateDate()); meetingRoomImpl.setModifiedDate(getModifiedDate()); meetingRoomImpl.setName(getName()); meetingRoomImpl.setCode(getCode()); meetingRoomImpl.setCapacity(getCapacity()); meetingRoomImpl.setLocation(getLocation()); meetingRoomImpl.setActive(getActive()); meetingRoomImpl.resetOriginalValues(); return meetingRoomImpl; } @Override public int compareTo(MeetingRoom meetingRoom) { int value = 0; value = getName().compareTo(meetingRoom.getName()); if (value != 0) { return value; } return 0; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof MeetingRoom)) { return false; } MeetingRoom meetingRoom = (MeetingRoom) obj; long primaryKey = meetingRoom.getPrimaryKey(); if (getPrimaryKey() == primaryKey) { return true; } else { return false; } } @Override public int hashCode() { return (int) getPrimaryKey(); } @Override public void resetOriginalValues() { MeetingRoomModelImpl meetingRoomModelImpl = this; meetingRoomModelImpl._originalName = meetingRoomModelImpl._name; meetingRoomModelImpl._originalCapacity = meetingRoomModelImpl._capacity; meetingRoomModelImpl._setOriginalCapacity = false; meetingRoomModelImpl._originalActive = meetingRoomModelImpl._active; meetingRoomModelImpl._setOriginalActive = false; meetingRoomModelImpl._columnBitmask = 0; } @Override public CacheModel<MeetingRoom> toCacheModel() { MeetingRoomCacheModel meetingRoomCacheModel = new MeetingRoomCacheModel(); meetingRoomCacheModel.meetingRoomId = getMeetingRoomId(); meetingRoomCacheModel.groupId = getGroupId(); meetingRoomCacheModel.companyId = getCompanyId(); meetingRoomCacheModel.userId = getUserId(); meetingRoomCacheModel.userName = getUserName(); String userName = meetingRoomCacheModel.userName; if ((userName != null) && (userName.length() == 0)) { meetingRoomCacheModel.userName = null; } Date createDate = getCreateDate(); if (createDate != null) { meetingRoomCacheModel.createDate = createDate.getTime(); } else { meetingRoomCacheModel.createDate = Long.MIN_VALUE; } Date modifiedDate = getModifiedDate(); if (modifiedDate != null) { meetingRoomCacheModel.modifiedDate = modifiedDate.getTime(); } else { meetingRoomCacheModel.modifiedDate = Long.MIN_VALUE; } meetingRoomCacheModel.name = getName(); String name = meetingRoomCacheModel.name; if ((name != null) && (name.length() == 0)) { meetingRoomCacheModel.name = null; } meetingRoomCacheModel.code = getCode(); String code = meetingRoomCacheModel.code; if ((code != null) && (code.length() == 0)) { meetingRoomCacheModel.code = null; } meetingRoomCacheModel.capacity = getCapacity(); meetingRoomCacheModel.location = getLocation(); meetingRoomCacheModel.active = getActive(); return meetingRoomCacheModel; } @Override public String toString() { StringBundler sb = new StringBundler(25); sb.append("{meetingRoomId="); sb.append(getMeetingRoomId()); sb.append(", groupId="); sb.append(getGroupId()); sb.append(", companyId="); sb.append(getCompanyId()); sb.append(", userId="); sb.append(getUserId()); sb.append(", userName="); sb.append(getUserName()); sb.append(", createDate="); sb.append(getCreateDate()); sb.append(", modifiedDate="); sb.append(getModifiedDate()); sb.append(", name="); sb.append(getName()); sb.append(", code="); sb.append(getCode()); sb.append(", capacity="); sb.append(getCapacity()); sb.append(", location="); sb.append(getLocation()); sb.append(", active="); sb.append(getActive()); sb.append("}"); return sb.toString(); } @Override public String toXmlString() { StringBundler sb = new StringBundler(40); sb.append("<model><model-name>"); sb.append("com.LiferayEnEspanol.booking.model.MeetingRoom"); sb.append("</model-name>"); sb.append( "<column><column-name>meetingRoomId</column-name><column-value><![CDATA["); sb.append(getMeetingRoomId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>groupId</column-name><column-value><![CDATA["); sb.append(getGroupId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>companyId</column-name><column-value><![CDATA["); sb.append(getCompanyId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>userId</column-name><column-value><![CDATA["); sb.append(getUserId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>userName</column-name><column-value><![CDATA["); sb.append(getUserName()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>createDate</column-name><column-value><![CDATA["); sb.append(getCreateDate()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>modifiedDate</column-name><column-value><![CDATA["); sb.append(getModifiedDate()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>name</column-name><column-value><![CDATA["); sb.append(getName()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>code</column-name><column-value><![CDATA["); sb.append(getCode()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>capacity</column-name><column-value><![CDATA["); sb.append(getCapacity()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>location</column-name><column-value><![CDATA["); sb.append(getLocation()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>active</column-name><column-value><![CDATA["); sb.append(getActive()); sb.append("]]></column-value></column>"); sb.append("</model>"); return sb.toString(); } }
true
e4674f4d988ebe69d14d832a141f6eefb09e5851
Java
sinimal-hit/sinamal
/stu-dorm-sys/src/main/java/org/example/controller/DormController.java
UTF-8
1,391
2.296875
2
[]
no_license
package org.example.controller; import org.example.model.Dorm; import org.example.service.DormService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/dorm") public class DormController { @Autowired private DormService dormService; //根据宿舍楼id查询寝室列表数据字典项 @GetMapping("/queryAsDict") public Object queryAsDict(@RequestParam("dictionaryKey") String buildingId){ List<Dorm> list = dormService.queryAsDict(buildingId); return list; } @GetMapping("/query") public Object query(Dorm dorm){ List<Dorm> list = dormService.query(dorm); return list; } @PostMapping("/add") public Object add(@RequestBody Dorm dorm){ int n = dormService.add(dorm); return null; } //修改时,根据id查询详情 @GetMapping("/queryById") public Object queryById(Integer id){ Dorm d = dormService.queryById(id); return d; } @PostMapping("/update") public Object update(@RequestBody Dorm dorm){ int n = dormService.update(dorm); return null; } @GetMapping("/delete") public Object delete(@RequestParam List<Integer> ids){ int n = dormService.delete(ids); return null; } }
true
f636ac631effd0e60a8f66a5aafc7c7a5dd262c1
Java
Abhimagic/FreeCRM
/FreeCRM/src/test/java/TestRunner/Runner.java
UTF-8
489
1.59375
2
[]
no_license
package TestRunner; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features="Features/TagTest.feature", glue="stepDefination", format = {"pretty","html:target/html/","json:target/cucumber-json.json", "usage:target/cucumber-usage.json","junit:target/cucumber-result.xml"}, monochrome = true, tags={"~@RegressionTest" ,"@End2End"}) public class Runner { }
true
0d1b84468879f6bdee3f16889b4c705c9109123f
Java
xianhe005/AIDLClient
/app/src/main/java/com/hxh/aidlclient/MainActivity.java
UTF-8
4,183
2.09375
2
[]
no_license
package com.hxh.aidlclient; import android.annotation.SuppressLint; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.TextView; import com.hxh.aidllib.aidl.IRemoteService; import java.util.List; @SuppressLint("SetTextI18n") public class MainActivity extends AppCompatActivity { private IRemoteService mRemoteService; private TextView mPidText; private boolean mBind; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPidText = (TextView) findViewById(R.id.tv_pid); mPidText.setText("the client pid is " + android.os.Process.myPid()); } @Override protected void onStart() { super.onStart(); //Intent intent = new Intent(); //intent.setClassName("com.hxh.aidl", "com.hxh.aidl.service.RemoteService"); Intent intent = new Intent(); intent.setAction("com.hxh.aidl.remote_service"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ intent = new Intent(createExplicitFromImplicitIntent(this,intent)); } bindService(intent, mConnection, BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); unbindService(mConnection); mBind = false; } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mRemoteService = IRemoteService.Stub.asInterface(service); mBind = true; } @Override public void onServiceDisconnected(ComponentName name) { mRemoteService = null; mBind = false; } }; public void onClick(View view) { switch (view.getId()) { case R.id.btn_show_pid: if (mBind) { try { int pid = mRemoteService.sayHello().getPid(); Log.i("HELLO_MSG", "the service pid is " + pid); mPidText.setText("the service pid is " + pid); } catch (RemoteException e) { e.printStackTrace(); } } break; case R.id.btn_say_hello: if (mBind) { try { String msg = mRemoteService.sayHello().getMsg(); Log.i("HELLO_MSG", msg); mPidText.setText(msg); } catch (RemoteException e) { e.printStackTrace(); } } break; } } public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) { // Retrieve all services that can match the given intent PackageManager pm = context.getPackageManager(); List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0); // Make sure only one match was found if (resolveInfo == null || resolveInfo.size() != 1) { return null; } // Get component info and create ComponentName ResolveInfo serviceInfo = resolveInfo.get(0); String packageName = serviceInfo.serviceInfo.packageName; String className = serviceInfo.serviceInfo.name; ComponentName component = new ComponentName(packageName, className); // Create a new intent. Use the old one for extras and such reuse Intent explicitIntent = new Intent(implicitIntent); // Set the component to be explicit explicitIntent.setComponent(component); return explicitIntent; } }
true
10b77aa1cad2bfcd554e76ceeb189467ac3d53d6
Java
gayathriksoman/revelio
/app/src/main/java/com/example/gayathri/revelio/Maps.java
UTF-8
1,957
2.0625
2
[]
no_license
package com.example.gayathri.revelio; import android.annotation.TargetApi; import android.app.Fragment; //import android.support.v4.app.Fragment; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; //import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; /** * Created by gayathri on 5/2/17. */ public class Maps extends Fragment implements OnMapReadyCallback{ @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_gmap, container, false); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); MapFragment fragment = (MapFragment)getChildFragmentManager().findFragmentById(R.id.map); fragment.getMapAsync(this); //setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. /*SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this);*/ } @Override public void onMapReady(GoogleMap googleMap) { LatLng marker = new LatLng(33,44); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(marker, 13)); googleMap.addMarker(new MarkerOptions().title("NITC maps").position(marker)); } }
true
604f2b4c7d7507fdeb589c0e22fc3cf05400ddf3
Java
Harvey44/linkwallet
/app/src/main/java/com/mobile/linkwallet/Read.java
UTF-8
6,206
2.015625
2
[]
no_license
package com.mobile.linkwallet; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.github.loadingview.LoadingView; import com.mobile.linkwallet.Api.ApiClient; import com.mobile.linkwallet.adapters.UnreadAdapter; import com.mobile.linkwallet.models.MessageResponse; import com.mobile.linkwallet.models.Noty; import com.mobile.linkwallet.storage.SharedPrefManager; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * A simple {@link Fragment} subclass. */ public class Read extends Fragment { Button read, unread; private RecyclerView rv_read; private ArrayList<Noty> noties; private UnreadAdapter adapter; LoadingView lv; SharedPreferences.Editor editor; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_read, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); editor = this.getActivity().getSharedPreferences("Lang", Context.MODE_PRIVATE).edit(); read = view.findViewById(R.id.read); unread = view.findViewById(R.id.unread); rv_read = view.findViewById(R.id.recyclerView_read); lv = view.findViewById(R.id.lv); lv.start(); rv_read.setLayoutManager(new LinearLayoutManager(getActivity())); unread.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changeFragment(); } }); if(isNetworkAvailable()){ read_noty(); } } private void changeFragment() { Fragment fragment = new Unread(); getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.relativeLayout, fragment).setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE).commit(); } private void read_noty(){ String Cmd = "list_notification"; String Type = "read"; String Email = SharedPrefManager.getInstance(getActivity()).getUser().getEmail(); int id = SharedPrefManager.getInstance(getActivity()).getUser().getId(); //SharedPreferences sharedPreference = getActivity().getSharedPreferences("my_shared_preff", Context.MODE_PRIVATE); final String authToken = "Bearer " + SharedPrefManager.getInstance(getActivity()).getUser().getLogin_token(); Call<MessageResponse> call = ApiClient.getInstance().getApi().noty(id, Email, Type, Cmd, authToken); call.enqueue(new Callback<MessageResponse>() { @Override public void onResponse(Call<MessageResponse> call, Response<MessageResponse> response) { MessageResponse messageResponse = response.body(); if (messageResponse != null && !messageResponse.isError()) { lv.stop(); noties = response.body().getResult(); adapter = new UnreadAdapter(getActivity(), noties); rv_read.setAdapter(adapter); //Toast.makeText(getActivity(), messageResponse.getResult().get(0).getImage(), Toast.LENGTH_LONG).show(); } else if(messageResponse.isError() && messageResponse.getErrorMessage().equals("Inavlid Token Request")){ logout(); } } @Override public void onFailure(Call<MessageResponse> call, Throwable t) { // Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_LONG).show(); } }); } private void checknetwork(){ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("No Internet Connection"); builder.setMessage("Please Enable Internet Connection"); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } private boolean isNetworkAvailable(){ ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); if(isConnected){ Log.d("Network", "Connected"); return true; } else{ checknetwork(); Log.d("Network", "Not Connected"); return false; } } private void logout() { SharedPrefManager.getInstance(getActivity()).clear(); SharedPreferences.Editor editor = getActivity().getSharedPreferences("save", Context.MODE_PRIVATE).edit(); editor.putBoolean("value", false); editor.apply(); Intent intent = new Intent(getActivity(), Login.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }
true
374658c2ef41cf16e5dcb954f9e27fe6d2307de5
Java
StefanGecko/ComputerDatabaseTestNG
/src/test/java/tests/FilterComputerTests.java
UTF-8
737
2.296875
2
[]
no_license
package tests; import org.testng.annotations.Test; import pages.MainPage; import utils.ExtentReports.ExtentTestManager; public class FilterComputerTests extends BaseTest { @Test(description = "TC: 18 - Validate if filtering is done by ComputerName.") public void filterSingleComputerTest() throws InterruptedException{ //ExtentReports Description ExtentTestManager.getTest().setDescription("TC: 18 - Validate if filtering is done by ComputerName."); //*************PAGE INSTANTIATIONS************* MainPage mainPage = new MainPage(driver, wait); //*************PAGE METHODS******************** //Open Computer Database page mainPage.filterByComputerName(); } }
true
8ad51fc172389776dc3a9c553e12c386a9bbf187
Java
EMCECS/nfs-client-java
/src/main/java/com/emc/ecs/nfsclient/rpc/RpcResponseHandler.java
UTF-8
2,103
2.484375
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/** * Copyright 2016-2018 Dell Inc. or its subsidiaries. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.emc.ecs.nfsclient.rpc; import java.io.IOException; /** * This class allows users to specify how new response instances are created * during repeated RPC calls, and how responses are validated before their data * is used. * * @author seibed */ public abstract class RpcResponseHandler<T> { /** * The current response. */ private T _response; /** * Get the current response. * * @return the current response */ public T getResponse() { return _response; } /** * Create a new response and return it. * * @return the new response */ public T getNewResponse() { _response = makeNewResponse(); return _response; } /** * This is implemented in all concrete subclasses, so that the new response * can be created using any available parameters. * * @return the new response. */ protected abstract T makeNewResponse(); /** * This is implemented in all concrete subclasses to check responses for * validity, and throws an IOException if the response indicates that the * request failed. * * @param request * This is used for error messages, to aid debugging, since the * response will likely not have enough data to determine the * request that caused it. * @throws IOException */ public abstract void checkResponse(RpcRequest request) throws IOException; }
true
b9277d5e5f2b7e3510864d5c7b64dc6fdaee0942
Java
oguzozturk/WirelessTransmitterRange
/WeightedEdge.java
UTF-8
457
3.109375
3
[ "Apache-2.0" ]
permissive
public class WeightedEdge extends AbstractGraph.Edges implements Comparable <WeightedEdge> { public double weight; //Created a weighted edge on(u,v) public WeightedEdge(int u,int v,double weight){ super(u,v); this.weight=weight; } //Compare two edges on weights @Override public int compareTo(WeightedEdge edge){ if(weight> edge.weight) return 1; else if(weight == edge.weight) return 0; else return -1; } }
true
c5412ba3386b75ede82a62c6665ba144e211226d
Java
kalvian1060/IACaculator
/app/src/main/java/com/goo/iacaculator/view/activity/SubmitActivity.java
UTF-8
965
1.851563
2
[]
no_license
package com.goo.iacaculator.view.activity; import android.webkit.WebView; import com.goo.iacaculator.R; import com.goo.iacaculator.base.BaseSwipeBackActivity; import com.goo.iacaculator.presenter.SubmitPresenter; import com.goo.iacaculator.view.vinterface.SubmitVInterface; public class SubmitActivity extends BaseSwipeBackActivity<SubmitVInterface, SubmitPresenter> implements SubmitVInterface { private WebView mWvInfo; @Override protected SubmitPresenter createPresenter() { return new SubmitPresenter(this); } @Override protected int setContentViewById() { return R.layout.activity_submit; } @Override protected void initAttributes() { } @Override protected void initView() { mWvInfo = $(R.id.wv_info); showToolbarAndShowNavigation("反馈"); mWvInfo.loadUrl("file:///android_asset/info.html"); } @Override protected void findAllViewById() { } }
true
bded66c3acbaf8df0cacb745ce77a696c3696a3d
Java
SeahawksRawesome/LeagueInvaders
/src/Alien.java
UTF-8
593
2.8125
3
[]
no_license
import java.awt.Color; import java.awt.Graphics; public class Alien extends GameObject { int xspeed = 2; int yspeed = 3; int counter = 0; Alien(int x, int y, int width, int height) { super(); this.x = x; this.y = y; this.height = height; this.width = width; } void update() { super.update(); y += yspeed; x += xspeed; counter++; if (counter > 20) { counter = 0; xspeed = -xspeed; } // if (counter == .6) { // xspeed = xspeed; // counter = 0; // } } void draw(Graphics g) { g.drawImage(GamePanel.alienImg, x, y, width, height, null); } }
true
01d1ea2fad106b9c3582ea19d51e231126a66d6a
Java
BlackJet/Contest
/src/algo3/order/QuickOrderer.java
UTF-8
1,189
3.546875
4
[]
no_license
package algo3.order; public class QuickOrderer extends ArrayOrderer { @Override protected int[] orderArray() { order(0, array.length - 1); return array; } private void order(int start, int end) { if(start >= end) return; int separatorPos = divide(start, end); order(start, separatorPos - 1); order(separatorPos + 1, end); } private int getSeparatorPos(int start, int end) { return start + (end - start)/2; } private int divide(int start, int end) { int separatorPos = getSeparatorPos(start, end); swap(end, separatorPos); int firstGreatPos = -1; int separator = get(end); for (int i = start; i < end; i++) { if(get(i) <= separator) { if(firstGreatPos != -1) { swap(firstGreatPos, i); firstGreatPos++; } } else { if(firstGreatPos == -1) { firstGreatPos = i; } } } if(firstGreatPos != -1) swap(firstGreatPos, end); return firstGreatPos == -1 ? end: firstGreatPos; } }
true
4722c6a05cab9e324ccf8692a7640814f882b2f5
Java
luishsantos/AirportVConc
/AirportVConc/src/sharedRegions/ArrivalTerminalTransferQuay.java
UTF-8
4,381
3.078125
3
[]
no_license
package sharedRegions; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import entities.BusDriver; import entities.BusDriverStates; import mainProject.SimulPar; public class ArrivalTerminalTransferQuay { /** * General Repository of Information * @serialField repository */ private RepositoryInfo repository; /** * Queue of passengers waiting for a Bus * @serialField waitingForBus */ private Queue<Integer> waitingForBus; /** * Queue of passengers in the Bus * @serialField inTheBus */ private Queue<Integer> inTheBus; /** * Boolena signal that tells us if the Bus Driver is ready to receive Passengers */ private boolean busDriverReadyToReceivePassengers = false; /** * Arrival Terminal Transfer Quay instantiation * @param repository repositoryInfo * */ public ArrivalTerminalTransferQuay(RepositoryInfo repository) { this.repository = repository; this.waitingForBus = new LinkedList<>(); this.inTheBus = new LinkedList<>(); } /***** PASSENGER FUNCTIONS *********/ /** * Passenger is put in the waiting list to enter the Bus * @param id int * */ public synchronized void takeABus(int id) { waitingForBus.add(id); repository.registerPassengerToTakeABus(id); if (waitingForBus.size() == SimulPar.BUS_CAPACITY) { notifyAll(); //If we have enough persons to wake up the driver let's do it } } /** * Passenger is waiting for the Bus to arrive * @param id int * */ public synchronized void waitForBus(int id) { while (true) { try { wait(); if (this.busDriverReadyToReceivePassengers) { Object[] tempArr = waitingForBus.toArray(); for (int i = 0; i < 3; i++) { if (id == (Integer) tempArr[i]) { return; } } } } catch (InterruptedException e) { } } } /** * Passenger is put in the list of passengers inside the Bus * @param id int * */ public synchronized void enterTheBus(int id) { inTheBus.add(id); repository.registerPassengerToEnterTheBus(id); notifyAll(); } /***** DRIVER FUNCTIONS *********/ /** * Bus Driver is ready to Departure * Bus Driver reach his schedule * */ public synchronized boolean readyToDeparture() { this.busDriverReadyToReceivePassengers = false; try { wait(SimulPar.BUS_SCHEDULE_MILLIS); } catch (InterruptedException e) {} return (waitingForBus.size() > 0); } /** * Bus Driver drives to the Departure Terminal * */ public void goToDepartureTerminal() { try { repository.setBusDriverState(BusDriverStates.DRIVING_FORWARD); Thread.currentThread().sleep((long) (new Random().nextInt(SimulPar.MAX_SLEEP - SimulPar.MIN_SLEEP + 1) + SimulPar.MAX_SLEEP)); } catch (InterruptedException e) { } } /** * Bus Driver parks the Bus * */ public void parkTheBus() { repository.setBusDriverState(BusDriverStates.PARKING_AT_THE_ARRIVAL_TERMINAL); } /** * Bus Driver announce Bus Boarding of the Passengers * */ public synchronized void announcingBusBoarding() { BusDriver busDriver = (BusDriver) Thread.currentThread(); this.busDriverReadyToReceivePassengers = true; this.inTheBus.clear(); int numberOfPassengers = (waitingForBus.size() > 3 ? 3 : waitingForBus.size()); busDriver.setPassengersInTheBus(numberOfPassengers); notifyAll(); try { while (numberOfPassengers != inTheBus.size()) { wait(2000); } } catch (InterruptedException e) {} this.busDriverReadyToReceivePassengers = false; for (int i = 0; i < numberOfPassengers; i++) { waitingForBus.poll(); } } /** * Set if Bus Driver's work day is over * */ public synchronized void setBusDriverEndOfWork() { notifyAll(); } }
true
279ae9b702e594ae6305be53bb0e9102597e3f65
Java
w-k-s/Service-Marketplace
/customer-service/src/main/java/com/wks/servicemarketplace/customerservice/adapters/web/ApiResource.java
UTF-8
3,536
2.140625
2
[]
no_license
package com.wks.servicemarketplace.customerservice.adapters.web; import com.wks.servicemarketplace.common.CustomerUUID; import com.wks.servicemarketplace.common.auth.Authentication; import com.wks.servicemarketplace.common.auth.User; import com.wks.servicemarketplace.common.errors.CoreException; import com.wks.servicemarketplace.common.errors.ErrorType; import com.wks.servicemarketplace.customerservice.api.AddressRequest; import com.wks.servicemarketplace.customerservice.api.CustomerService; import com.wks.servicemarketplace.customerservice.core.usecase.address.AddAddressUseCase; import com.wks.servicemarketplace.customerservice.core.usecase.address.FindAddressByCustomerUuidUseCase; import com.wks.servicemarketplace.customerservice.core.usecase.customer.GetCustomerUseCase; import org.glassfish.jersey.process.internal.RequestScoped; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.util.Optional; @Path(CustomerService.PATH_V1_) @RequestScoped public class ApiResource { private final FindAddressByCustomerUuidUseCase findAddressUseCase; private final GetCustomerUseCase getCustomerUseCase; private final AddAddressUseCase addAddressUseCase; @Inject public ApiResource(GetCustomerUseCase getCustomerUseCase, FindAddressByCustomerUuidUseCase findAddressUseCase, AddAddressUseCase addAddressUseCase) { this.getCustomerUseCase = getCustomerUseCase; this.addAddressUseCase = addAddressUseCase; this.findAddressUseCase = findAddressUseCase; } @GET @Path(CustomerService.ENDPOINT_GET_CUSTOMER) @Produces(MediaType.APPLICATION_JSON) public Response getCustomer(@Context SecurityContext securityContext) { final var authentication = (Authentication) securityContext.getUserPrincipal(); final var customerId = Optional.ofNullable(authentication.getUserId()) .map(CustomerUUID::of) .orElseThrow(() -> new CoreException(ErrorType.AUTHENTICATION, "token does not contain user id", null, null)); return Response.ok(getCustomerUseCase.execute(customerId)).build(); } @GET @Path(CustomerService.ENDPOINT_GET_ADDRESSES) @Produces(MediaType.APPLICATION_JSON) public Response getAddresses(@Context SecurityContext securityContext) { final var authentication = (Authentication) securityContext.getUserPrincipal(); final var customerId = Optional.ofNullable(authentication.getUserId()) .map(CustomerUUID::of) .orElseThrow(() -> new CoreException(ErrorType.AUTHENTICATION, "token does not contain user id", null, null)); return Response.ok(findAddressUseCase.execute(customerId)).build(); } @POST @Path(CustomerService.ENDPOINT_ADD_ADDRESS) @Produces(MediaType.APPLICATION_JSON) public Response addAddress(final AddressRequest.Builder addressRequest, @Context SecurityContext securityContext) throws CoreException { final var authentication = (Authentication) securityContext.getUserPrincipal(); return Response.ok(addAddressUseCase.execute( addressRequest .authentication(authentication) .build()) ).build(); } }
true
a32a8b839ac38fdaf708181cca779ed11427c9a8
Java
19029489/TW-ListView
/app/src/main/java/com/myapplicationdev/android/tw_listview/SecondActivity.java
UTF-8
1,766
2.4375
2
[]
no_license
package com.myapplicationdev.android.tw_listview; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.util.ArrayList; public class SecondActivity extends AppCompatActivity { TextView tvYear; ArrayList<Module> moduleY1; ArrayList<Module> moduleY2; ArrayList<Module> moduleY3; ArrayAdapter aa; ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); lv = (ListView) this.findViewById(R.id.lvModule); tvYear = (TextView) this.findViewById(R.id.textView2); moduleY1 = new ArrayList<Module>(); moduleY1.add(new Module("C208", true)); moduleY1.add(new Module("C200", false)); moduleY1.add(new Module("C346", true)); moduleY2 = new ArrayList<Module>(); moduleY2.add(new Module("C308", true)); moduleY3 = new ArrayList<Module>(); moduleY3.add(new Module("C248", false)); Intent i = getIntent(); String year = i.getStringExtra(Intent.EXTRA_TEXT); if(year.equals("Year 1")){ tvYear.setText("Year 1"); aa = new ModuleAdapter(this, R.layout.row, moduleY1); } else if(year.equals("Year 2")) { tvYear.setText("Year 2"); aa = new ModuleAdapter(this, R.layout.row, moduleY2); } else { tvYear.setText("Year 3"); aa = new ModuleAdapter(this, R.layout.row, moduleY3); } lv.setAdapter(aa); } }
true
589a93b18cc9fe9772650da9b59c117a631c7680
Java
AssSina/Logistics
/src/main/java/com/sanyang/logistics/jaj/dao/TruckDimDaoImp.java
UTF-8
1,433
2.0625
2
[]
no_license
package com.sanyang.logistics.jaj.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.sanyang.logistics.base.pojo.TruckDim; import com.sanyang.logistics.jaj.mapper.TruckDimMapper; /** * 车辆数据访问层实现类 * @author asus * */ @Repository("truckDimDao") public class TruckDimDaoImp implements TruckDimDao{ @Autowired private TruckDimMapper truckDimMapper; @Override public List<TruckDim> getTruckDim(TruckDim truckDim) { // TODO Auto-generated method stub return truckDimMapper.getTruckDim(truckDim); } @Override public void insertTruckDim(TruckDim truckDim) { // TODO Auto-generated method stub truckDimMapper.insertSelective(truckDim); } @Override public void deleteTruckDim(Integer truckId) { // TODO Auto-generated method stub truckDimMapper.deleteByPrimaryKey(truckId); } @Override public TruckDim getTruckDimById(Integer truckId) { // TODO Auto-generated method stub return truckDimMapper.selectByPrimaryKey(truckId); } @Override public void updateTruckDim(TruckDim truckDim) { // TODO Auto-generated method stub truckDimMapper.updateByPrimaryKeySelective(truckDim); } @Override public List<TruckDim> getOwnerTypeDimById() { // TODO Auto-generated method stub return truckDimMapper.getOwnerTypeDimById(); } }
true
d502dc0392cfed60458e8603eb437cef85fbcceb
Java
wsws1996/my-java-project
/eclipseworkspace/mybatis2/test/com/wang/mybatis/mapper/UserMapperTest.java
UTF-8
1,242
2.21875
2
[]
no_license
package com.wang.mybatis.mapper; import java.io.InputStream; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import com.wang.mybatis.po.User; public class UserMapperTest { private SqlSessionFactory sqlSessionFactory; @Before public void setUp() throws Exception { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = (new SqlSessionFactoryBuilder()).build(inputStream); } @Test public void testFindUserById() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findUserById(10); System.out.println(user); } @Test public void testFindUserByList() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> list=userMapper.findUserByList("fa"); for (User user : list) { System.out.println(user); } } }
true
83f1e88607ddb4b39b216fa12cf9bde799ba8748
Java
FasterXML/woodstox
/src/main/java/com/ctc/wstx/io/BaseInputSource.java
UTF-8
5,558
2.09375
2
[ "Apache-2.0" ]
permissive
package com.ctc.wstx.io; import java.io.IOException; import java.net.URL; import javax.xml.stream.XMLStreamException; /** * Abstract base class that implements shared functionality that all current * {@link WstxInputSource} implementations Woodstox includes need. */ public abstract class BaseInputSource extends WstxInputSource { final String mPublicId; /** * URL for/from systemId points to original source of input, if known; null if not * known (source constructed with just a stream or reader). Used for * resolving references from the input that's read from this source. * Can be overridden by reader; done if P_BASE_URL is changed on * stream reader for which this input source is the currently * active input source. */ SystemId mSystemId; /** * Input buffer this input source uses, if any. */ protected char[] mBuffer; /** * Length of the buffer, if buffer used */ protected int mInputLast; /* //////////////////////////////////////////////////////////////// // Saved location information; active information is directly // handled by Reader, and then saved to input source when switching // to a nested input source. //////////////////////////////////////////////////////////////// */ /** * Number of characters read from the current input source prior to * the current buffer */ long mSavedInputProcessed = 0; int mSavedInputRow = 1; int mSavedInputRowStart = 0; int mSavedInputPtr = 0; /* //////////////////////////////////////////////////////////////// // Some simple lazy-loading/reusing support... //////////////////////////////////////////////////////////////// */ transient WstxInputLocation mParentLocation = null; /* //////////////////////////////////////////////////////////////// // Life-cycle //////////////////////////////////////////////////////////////// */ protected BaseInputSource(WstxInputSource parent, String fromEntity, String publicId, SystemId systemId) { super(parent, fromEntity); mSystemId = systemId; mPublicId = publicId; } @Override public void overrideSource(URL src) { //19-May-2014, tatu: I assume this should also override observed systemId... mSystemId = SystemId.construct(src); } @Override public abstract boolean fromInternalEntity(); @Override public URL getSource() throws IOException { return (mSystemId == null) ? null : mSystemId.asURL(); } @Override public String getPublicId() { return mPublicId; } @Override public String getSystemId() { return (mSystemId == null) ? null : mSystemId.toString(); } @Override protected abstract void doInitInputLocation(WstxInputData reader); @Override public abstract int readInto(WstxInputData reader) throws IOException, XMLStreamException; @Override public abstract boolean readMore(WstxInputData reader, int minAmount) throws IOException, XMLStreamException; @Override public void saveContext(WstxInputData reader) { // First actual input data mSavedInputPtr = reader.mInputPtr; // then location mSavedInputProcessed = reader.mCurrInputProcessed; mSavedInputRow = reader.mCurrInputRow; mSavedInputRowStart = reader.mCurrInputRowStart; } @Override public void restoreContext(WstxInputData reader) { reader.mInputBuffer = mBuffer; reader.mInputEnd = mInputLast; reader.mInputPtr = mSavedInputPtr; // then location reader.mCurrInputProcessed = mSavedInputProcessed; reader.mCurrInputRow = mSavedInputRow; reader.mCurrInputRowStart = mSavedInputRowStart; } @Override public abstract void close() throws IOException; /* ////////////////////////////////////////////////////////// // Methods for accessing location information ////////////////////////////////////////////////////////// */ /** * This method only gets called by the 'child' input source (for example, * contents of an expanded entity), to get the enclosing context location. */ @Override protected final WstxInputLocation getLocation() { // Note: columns are 1-based, need to add 1. return getLocation(mSavedInputProcessed + mSavedInputPtr - 1L, mSavedInputRow, mSavedInputPtr - mSavedInputRowStart + 1); } @Override public final WstxInputLocation getLocation(long total, int row, int col) { WstxInputLocation pl; if (mParent == null) { pl = null; } else { /* 13-Apr-2005, TSa: We can actually reuse parent location, since * it can not change during lifetime of this child context... */ pl = mParentLocation; if (pl == null) { mParentLocation = pl = mParent.getLocation(); } pl = mParent.getLocation(); } /* !!! 15-Apr-2005, TSa: This will cause overflow for total count, * but since StAX 1.0 API doesn't have any way to deal with that, * let's just let that be... */ return new WstxInputLocation(pl, getPublicId(), getSystemId(), total, row, col); } }
true
99000b61c4202c925e4cf298f0caca0f16c2bf3a
Java
peterpavles/password-manager
/src/main/java/org/panteleyev/pwdmanager/PasswordManagerApplication.java
UTF-8
4,161
2.15625
2
[ "BSD-2-Clause" ]
permissive
/* * Copyright (c) 2016, 2020, Petr Panteleyev <petr@panteleyev.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 HOLDER 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.panteleyev.pwdmanager; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.control.Alert; import javafx.stage.Stage; import java.io.File; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; public class PasswordManagerApplication extends Application { private static final Logger LOGGER = Logger.getLogger(PasswordManagerApplication.class.getName()); private static final String FORMAT_PROP = "java.util.logging.SimpleFormatter.format"; private static final String FORMAT = "%1$tF %1$tk:%1$tM:%1$tS %2$s%n%4$s: %5$s%6$s%n"; private static final String OPTIONS_DIRECTORY = ".password-manager"; private static final String UI_BUNDLE_PATH = "org.panteleyev.pwdmanager.ui"; private static PasswordManagerApplication application; public static final ResourceBundle RB = ResourceBundle.getBundle(UI_BUNDLE_PATH); public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { application = this; if (initLogDirectory()) { String formatProperty = System.getProperty(FORMAT_PROP); if (formatProperty == null) { System.setProperty(FORMAT_PROP, FORMAT); } LogManager.getLogManager() .readConfiguration(PasswordManagerApplication.class.getResourceAsStream("logger.properties")); } Thread.setDefaultUncaughtExceptionHandler((t, e) -> uncaughtException(e)); stage.setTitle(AboutDialog.APP_TITLE); new MainWindowController(stage); stage.show(); } static PasswordManagerApplication getApplication() { return application; } private static boolean initLogDirectory() { File optionsDir = getSettingsDirectory(); File logDir = new File(optionsDir, "logs"); return logDir.exists() ? logDir.isDirectory() : logDir.mkdir(); } private static File getSettingsDirectory() { var dir = new File(System.getProperty("user.home") + File.separator + OPTIONS_DIRECTORY); if (!dir.exists()) { //noinspection ResultOfMethodCallIgnored dir.mkdir(); } else { if (!dir.isDirectory()) { throw new RuntimeException("Options directory cannot be opened/created"); } } return dir; } private static void uncaughtException(Throwable e) { LOGGER.log(Level.SEVERE, "Uncaught exception", e); Platform.runLater(() -> { Alert alert = new Alert(Alert.AlertType.ERROR, e.toString()); alert.showAndWait(); }); } }
true
d9a201139aa4ce64e14658cb05f32eae4e8daf3f
Java
tlsJP/SpaceMapping
/src/main/java/com/jp/core/SpaceFactory.java
UTF-8
218
1.765625
2
[]
no_license
package com.jp.core; /** * What a cool name, but this just builds a room. This will borrow heavily from the stuff I made from * the Graphs repo * * Created by JP on 4/4/2017. */ public class SpaceFactory { }
true
63d176194785f615d07ccd81b7465a5b4b49ef51
Java
FP-July/PicEngine
/src/main/java/dao/DBConstants.java
UTF-8
2,203
2.53125
3
[]
no_license
package dao; public class DBConstants { //status codes public static final int SUCCESS = 1000; public static final int SQL_EXCUTION_ERROR = 1001; //proj public static final int PROJ_ALREADY_EXIST = 1100; public static final int NO_SUCH_PROJ = 1101; //user public static final int USER_ALREADY_EXIST = 1200; public static final int NO_SUCH_USER = 1201; public static final int WRONG_PW = 1202; //status strings public static final String STR_SUCCESS = "success"; public static final String STR_SQL_EXCUTION_ERROR = "error occured when excuting sql"; //proj public static final String STR_PROJ_ALREADY_EXIST = "task already exists"; public static final String STR_NO_SUCH_PROJ = "no such task"; //user public static final String STR_USER_ALREADY_EXIST = "user already exists"; public static final String STR_NO_SUCH_USER = "no such user"; public static final String STR_WRONG_PW = "wrong password"; public static final String USER_TABLE = "userData"; public static final String PROJ_TABLE = "projectData"; public static final String DB_PATH = "/home/jt/sqlite"; public static enum DB_PREVILIGE {admin, user}; public static final String[] tableCreateSQL = { "CREATE TABLE IF NOT EXISTS " + USER_TABLE + " "+ "(username TEXT PRIMARYKEY NOT NULL," + "password TEXT NOT NULL," + "permission INTEGER NOT NULL);", "CREATE TABLE IF NOT EXISTS " + PROJ_TABLE + " " + "(projID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "username TEXT NOT NULL," + "projName TEXT NOT NULL," + "status INTEGER NOT NULL," + "runtime INTEGER NOT NULL," + "finishedTime INTEGER," + "progress INTEGER NOT NULL," + "type TEXT NOT NULL," + "createTime LONG NOT NULL);" }; public static String codeToString(int status) { switch (status) { case SUCCESS: return STR_SUCCESS; case SQL_EXCUTION_ERROR: return STR_SQL_EXCUTION_ERROR; case PROJ_ALREADY_EXIST: return STR_PROJ_ALREADY_EXIST; case NO_SUCH_PROJ: return STR_NO_SUCH_PROJ; case NO_SUCH_USER: return STR_NO_SUCH_USER; case USER_ALREADY_EXIST: return STR_USER_ALREADY_EXIST; case WRONG_PW: return STR_WRONG_PW; default: return "未知错误。"; } } }
true
aa1646bb164dde0ec2c0289dafc793a30b9655bd
Java
bg1bgst333/Sample
/android/Environment/getExternalStoragePublicDirectory/src/Environment/Environment_/src/com/bgstation0/android/sample/environment_/MainActivity.java
SHIFT_JIS
4,516
2.921875
3
[ "MIT" ]
permissive
package com.bgstation0.android.sample.environment_; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Environment; import android.text.Editable; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { // otB[h̒`. Context context = null; // Context^contextnullŏ. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; // contextthisi[. } // IvVj[쐬鎞. @Override public boolean onCreateOptionsMenu(Menu menu){ // j[̍쐬 getMenuInflater().inflate(R.menu.main, menu); // getMenuInflaterMenuItem擾, ̂܂inflateŎw肳ꂽR.menu.mainmenu쐬. return true; // trueԂ. } // j[Iꂽ. @Override public boolean onOptionsItemSelected(MenuItem item){ // ǂ̃j[Iꂽ. switch (item.getItemId()){ // ACeIDƂɐU蕪. // Write file case R.id.menu_write_file: // t@C擾. EditText edittextName = (EditText)findViewById(R.id.edittext_filename); // findViewByIdedittext_filename擾. Editable textName = edittextName.getText(); // edittextName.getTextŃeLXg擾. String filename = textName.toString(); // textName.toStringŕ擾. // t@Ce擾. EditText edittextContent = (EditText)findViewById(R.id.edittext_filecontent); // findViewByIdedittext_filecontent擾. Editable textContent = edittextContent.getText(); // edittextContent.getTextŃeLXg擾. String filecontent = textContent.toString(); // textContent.toStringŕ擾. // t@C`FbN. if (filename.length() == 0){ Toast.makeText(this, "filename is empty!", Toast.LENGTH_SHORT).show(); // "filename is empty!"ƕ\. break; // rŔ. } // Xg[W̃_E[htH_Ƀt@C. FileOutputStream out = null; // FileOutputStream^outnullɏ. try{ // tryň͂. String state = Environment.getExternalStorageState(); // Environment.getExternalStorageStateœstate擾. if (Environment.MEDIA_MOUNTED.equals(state)){ // MEDIA_MOUNTEDȂ. //File ext_dir = context.getExternalFilesDir(null); // context.getExternalFilesDir(null)œXg[W̃AvP[VtH_gbvext_dir擾. //File ext_storage_dir = Environment.getExternalStorageDirectory(); // Environment.getExternalStorageDirectoryŃXg[W̃gbvfBNgext_storage_dir擾. File ext_downloads_dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); // Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)DownloadfBNgext_downloads_dir擾. File ext_file = new File(ext_downloads_dir, filename); // filenameFileIuWFNgext_file𐶐. out = new FileOutputStream(ext_file); // ext_fileFileOutputStreamIuWFNgout𐶐. out.write(filecontent.getBytes()); // out.writefilecontent. out.close(); // out.closeŕ‚. Toast.makeText(this, ext_file.getPath(), Toast.LENGTH_LONG).show(); // Toastext_filẽpX\. } } catch (FileNotFoundException fileNotEx){ // t@C‚Ȃ. Toast.makeText(this, "File not found!", Toast.LENGTH_SHORT).show(); // "File not found!"ƕ\. } catch (IOException ioEx){ // IOG[. Toast.makeText(this, "IO error!", Toast.LENGTH_SHORT).show(); // "IO Error!"ƕ\. } break; // Ŕ. } return super.onOptionsItemSelected(item); // eNX菈 } }
true
590d8c820aaa7a6bf68eb67919f135ee7c2358df
Java
capp59marcelo/startup-lanches
/src/main/java/br/com/startupLanches/exception/PedidoNotFoundException.java
UTF-8
224
1.96875
2
[]
no_license
package br.com.startupLanches.exception; public class PedidoNotFoundException extends Exception { private static final long serialVersionUID = 1L; public PedidoNotFoundException(String message) { super(message); } }
true
d591e59ed0019ac6df33534d6855d1af598d65ad
Java
MischaFvG/Homework_number_11
/src/com/cat/Board.java
UTF-8
980
3.328125
3
[]
no_license
package com.cat; import javafx.scene.canvas.GraphicsContext; import java.util.ArrayList; import java.util.List; public class Board { private GraphicsContext graphicsContext; private List<Shape> shapes = new ArrayList<>(); public Board(GraphicsContext graphicsContext) { this.graphicsContext = graphicsContext; shapes.add(new Square(34, 21, graphicsContext, this)); shapes.add(new Ball(245, 675, graphicsContext, this)); shapes.add(new Cat(555, 667, graphicsContext, this)); } public void move() { for (Shape shape : shapes) { shape.move(); } } public void draw() { clean(); for (Shape shape : shapes) { shape.draw(); } } public List<Shape> getShapes() { return shapes; } private void clean() { graphicsContext.clearRect(0, 0, graphicsContext.getCanvas().getWidth(), graphicsContext.getCanvas().getHeight()); } }
true
679bde40b60801e53b5fcaea51dffcb79e3b4365
Java
929753733/githubdemo4
/Test/src/com/inspur/StaticDemo.java
UTF-8
787
3.1875
3
[]
no_license
package com.inspur; public class StaticDemo { String a = "aaa"; static String b = "aaa"; public static void aaa() { System.out.println("aaaaa"); } public void bbb() { System.out.println(a); System.out.println(b); ccc(); ggg(); System.out.println("bbbbb"); } public static void ccc() { System.out.println(b); StaticDemo staticDemo = new StaticDemo(); staticDemo.bbb(); System.out.println("ccccc"); class eee { final String aString = "aaaa"; } } class fff { StaticDemo staticDemo2 = new StaticDemo(); public void ggg() { System.out.println(); } } public void ggg() { System.out.println("gggg"); } public static void main(String[] args) { ccc(); System.out.println(Integer.MAX_VALUE); System.out.println(); } }
true
7c402f8c620eefe836d267b951bb036ac48f480a
Java
fangzhzh/AndroidSavingTest
/app/src/main/java/com/example/zhenfang/myapplication/databaseImp/orm/builder/DBCacheBuilder.java
UTF-8
874
2.609375
3
[]
no_license
package com.example.zhenfang.myapplication.databaseImp.orm.builder; import com.example.zhenfang.myapplication.databaseImp.orm.bean.DBCache; /** * @author zhangzf * @since 6/22/15 5:34 PM */ public class DBCacheBuilder { private String key; private String value; private DBCacheBuilder() { } public static DBCacheBuilder aDBCache() { return new DBCacheBuilder(); } public DBCacheBuilder withKey(String key) { this.key = key; return this; } public DBCacheBuilder withValue(String value) { this.value = value; return this; } public DBCacheBuilder but() { return aDBCache().withKey(key).withValue(value); } public DBCache build() { DBCache dBCache = new DBCache(); dBCache.setKey(key); dBCache.setValue(value); return dBCache; } }
true
e52fa9cb159d5bbaf14ddcbe84d18680ed092a77
Java
Shawnarun/Pharmacymanagement_System_netbeans
/src/sukiva/distributor.java
UTF-8
18,505
1.953125
2
[]
no_license
/* * 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 sukiva; import java.awt.Font; import java.awt.HeadlessException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JOptionPane; import javax.swing.plaf.basic.BasicInternalFrameUI; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import static sukiva.Admin.q; /** * * @author Snake_Eye */ public class distributor extends javax.swing.JInternalFrame { DefaultTableModel defaultTableModel = new DefaultTableModel(); Connection connection = null; PreparedStatement prp = null; ResultSet rs = null; int delete; /** Creates new form employer */ public distributor() { initComponents(); BasicInternalFrameUI bi = (BasicInternalFrameUI)this.getUI(); bi.setNorthPane(null); this.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); tname.setBackground(new java.awt.Color(0,0,0,1)); tcn.setBackground(new java.awt.Color(0,0,0,1)); tsrn.setBackground(new java.awt.Color(0,0,0,1)); tsrn.setBackground(new java.awt.Color(0,0,0,1)); tddue.setBackground(new java.awt.Color(0,0,0,1)); tdsearch.setBackground(new java.awt.Color(0,0,0,0)); tdsearch2.setBackground(new java.awt.Color(0,0,0,1)); dscroll.setBackground(new java.awt.Color(0,0,0,1)); dscroll.getViewport().setBackground(new java.awt.Color(0,0,0,1)); dt.setBackground(new java.awt.Color(0,0,0,1)); JTableHeader header = dt.getTableHeader(); header.setEnabled(false); header.setBackground(new java.awt.Color(0,0,0,0)); dt.getTableHeader().setFont(new Font("Times New Roman", Font.BOLD, 14)); dt.setDefaultEditor(Object.class, null); Object columns[] = {"Company Name"," Agent Name", " Contact Number","Due","ID"}; defaultTableModel.setColumnIdentifiers(columns); dt.setModel(defaultTableModel); loadData(); } public void loadData() { connection = DataBase.database.ConnectDb(); String sql = "SELECT `coname`, `cnum`, `salesrn`, `due`,`did` FROM `distributors`"; try { prp = connection.prepareStatement(sql); rs = prp.executeQuery(); Object columnData[] = new Object[5]; while (rs.next()) { columnData[0] = rs.getString("coname"); columnData[1] = rs.getString("salesrn"); columnData[2] = rs.getString("cnum"); columnData[3] = rs.getString("due"); columnData[4] = rs.getString("did"); defaultTableModel.addRow(columnData); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, e); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { dadd = new javax.swing.JButton(); name = new javax.swing.JLabel(); agn = new javax.swing.JLabel(); tsrn = new javax.swing.JTextField(); dsearch = new javax.swing.JButton(); tname = new javax.swing.JTextField(); dupdate = new javax.swing.JButton(); tcn = new javax.swing.JTextField(); ddelete = new javax.swing.JButton(); cn = new javax.swing.JLabel(); dscroll = new javax.swing.JScrollPane(); dt = new javax.swing.JTable(); tdsearch = new javax.swing.JComboBox<>(); tdsearch2 = new javax.swing.JTextField(); tddue = new javax.swing.JTextField(); ddue = new javax.swing.JLabel(); bg = new javax.swing.JLabel(); setBorder(null); setPreferredSize(new java.awt.Dimension(958, 558)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); dadd.setBackground(new java.awt.Color(176, 106, 179)); dadd.setFont(new java.awt.Font("Ebrima", 1, 14)); // NOI18N dadd.setForeground(new java.awt.Color(0, 0, 204)); dadd.setText("Add"); dadd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { daddActionPerformed(evt); } }); getContentPane().add(dadd, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 320, 80, 40)); name.setFont(new java.awt.Font("Ebrima", 1, 18)); // NOI18N name.setForeground(new java.awt.Color(0, 0, 0)); name.setText("Company Name"); getContentPane().add(name, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 140, 30)); agn.setFont(new java.awt.Font("Ebrima", 1, 18)); // NOI18N agn.setForeground(new java.awt.Color(0, 0, 0)); agn.setText("Sales Rep Name"); getContentPane().add(agn, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, 140, 30)); tsrn.setFont(new java.awt.Font("Ebrima", 0, 14)); // NOI18N tsrn.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); tsrn.setOpaque(false); tsrn.setPreferredSize(new java.awt.Dimension(6, 22)); getContentPane().add(tsrn, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 110, 160, 20)); dsearch.setBackground(new java.awt.Color(176, 106, 179)); dsearch.setFont(new java.awt.Font("Ebrima", 1, 18)); // NOI18N dsearch.setForeground(new java.awt.Color(0, 0, 204)); dsearch.setText("Search"); getContentPane().add(dsearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 450, 110, 30)); tname.setFont(new java.awt.Font("Ebrima", 0, 14)); // NOI18N tname.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); tname.setOpaque(false); tname.setPreferredSize(new java.awt.Dimension(6, 22)); tname.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tnameActionPerformed(evt); } }); getContentPane().add(tname, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 30, 160, 20)); dupdate.setBackground(new java.awt.Color(176, 106, 179)); dupdate.setFont(new java.awt.Font("Ebrima", 1, 14)); // NOI18N dupdate.setForeground(new java.awt.Color(0, 0, 204)); dupdate.setText("update"); dupdate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dupdateActionPerformed(evt); } }); getContentPane().add(dupdate, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 320, 90, 40)); tcn.setFont(new java.awt.Font("Ebrima", 0, 14)); // NOI18N tcn.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); tcn.setOpaque(false); tcn.setPreferredSize(new java.awt.Dimension(6, 22)); getContentPane().add(tcn, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 70, 160, 20)); ddelete.setBackground(new java.awt.Color(176, 106, 179)); ddelete.setFont(new java.awt.Font("Ebrima", 1, 14)); // NOI18N ddelete.setForeground(new java.awt.Color(0, 0, 204)); ddelete.setText("Delete"); ddelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ddeleteActionPerformed(evt); } }); getContentPane().add(ddelete, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 320, 80, 40)); cn.setFont(new java.awt.Font("Ebrima", 1, 18)); // NOI18N cn.setForeground(new java.awt.Color(0, 0, 0)); cn.setText("Contact No"); getContentPane().add(cn, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, 120, 30)); dscroll.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); dscroll.setOpaque(false); dt.setBackground(new java.awt.Color(176, 106, 179)); dt.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); dt.setFont(new java.awt.Font("Ebrima", 0, 14)); // NOI18N dt.setForeground(new java.awt.Color(0, 0, 0)); dt.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); dt.setGridColor(new java.awt.Color(0, 0, 0)); dt.setOpaque(false); dt.setSelectionBackground(new java.awt.Color(170, 106, 181)); dt.setSelectionForeground(new java.awt.Color(0, 0, 0)); dt.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { dtMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { dtMouseEntered(evt); } }); dscroll.setViewportView(dt); getContentPane().add(dscroll, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 0, 610, 530)); tdsearch.setFont(new java.awt.Font("Ebrima", 1, 18)); // NOI18N tdsearch.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Company Name", "Contact No", "Sales Rep Name", "Due" })); tdsearch.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); tdsearch.setOpaque(false); tdsearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tdsearchActionPerformed(evt); } }); getContentPane().add(tdsearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 390, 160, 40)); tdsearch2.setFont(new java.awt.Font("Ebrima", 0, 14)); // NOI18N tdsearch2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); tdsearch2.setOpaque(false); tdsearch2.setPreferredSize(new java.awt.Dimension(6, 22)); tdsearch2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tdsearch2ActionPerformed(evt); } }); getContentPane().add(tdsearch2, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 450, 160, 30)); tddue.setFont(new java.awt.Font("Ebrima", 0, 14)); // NOI18N tddue.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); tddue.setOpaque(false); tddue.setPreferredSize(new java.awt.Dimension(6, 22)); getContentPane().add(tddue, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 150, 160, 20)); ddue.setFont(new java.awt.Font("Ebrima", 1, 18)); // NOI18N ddue.setForeground(new java.awt.Color(0, 0, 0)); ddue.setText("Due"); getContentPane().add(ddue, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 140, 120, 30)); bg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sukiva/images/internal.png"))); // NOI18N bg.setText("jLabel1"); bg.setMaximumSize(new java.awt.Dimension(998, 580)); bg.setMinimumSize(new java.awt.Dimension(998, 580)); bg.setPreferredSize(new java.awt.Dimension(960, 560)); getContentPane().add(bg, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1010, -1)); pack(); }// </editor-fold>//GEN-END:initComponents private void tnameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tnameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tnameActionPerformed private void daddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_daddActionPerformed // TODO add your handling code here: String name = tname.getText(); String cn = tcn.getText(); String srn = tsrn.getText(); String due = tddue.getText(); if(name.equals("")||cn.equals("")||srn.equals("")||due.equals("")){ JOptionPane.showMessageDialog(null,"Complete Your Employer Information","Missing Information",2); } else { String sql = "INSERT INTO `distributors`(`coname`, `cnum`, `salesrn`, `due`) VALUES (?,?,?,?)"; if (connection != null) { try { prp = connection.prepareStatement(sql); prp.setString(1, name); prp.setString(2, cn); prp.setString(3, srn); prp.setString(4, due); prp.execute(); defaultTableModel.getDataVector().removeAllElements(); defaultTableModel.fireTableDataChanged(); loadData(); JOptionPane.showMessageDialog(null, "Data Saved"); } catch (SQLException e) { JOptionPane.showMessageDialog(null, e); } } } tname.setText(""); tcn.setText(""); tsrn.setText(""); tddue.setText(""); }//GEN-LAST:event_daddActionPerformed private void dupdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dupdateActionPerformed // TODO add your handling code here: String fullname = tname.getText(); String username = tsrn.getText(); String contact_no = tcn.getText(); String due= tddue.getText(); if(fullname.equals("")||contact_no.equals("")||username.equals("")||due.equals("")){ JOptionPane.showMessageDialog(null,"Complete Your Employer Information","Missing Information",2); } else { String sql = "UPDATE `distributors` SET `coname`='"+ fullname +"',`cnum`='"+ contact_no +"',`salesrn`='"+ username +"',`due`='"+ due +"' WHERE did ='" + delete + "'"; try { prp = connection.prepareStatement(sql); prp.execute(); defaultTableModel.getDataVector().removeAllElements(); defaultTableModel.fireTableDataChanged(); loadData(); q.removeAll(); distributor ne = new distributor(); q.add(ne).setVisible(true); JOptionPane.showMessageDialog(null, "Data Updated"); } catch (HeadlessException | SQLException e) { JOptionPane.showMessageDialog(null, e); } } }//GEN-LAST:event_dupdateActionPerformed private void tdsearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tdsearchActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tdsearchActionPerformed private void tdsearch2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tdsearch2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tdsearch2ActionPerformed private void dtMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dtMouseEntered // TODO add your handling code here: }//GEN-LAST:event_dtMouseEntered private void dtMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dtMouseClicked // TODO add your handling code here: int row = dt.getSelectedRow(); tname.setText(dt.getValueAt(row, 0).toString()); tsrn.setText(dt.getValueAt(row, 1).toString()); tcn.setText(dt.getValueAt(row, 2).toString()); tddue.setText(dt.getValueAt(row, 3).toString()); delete = Integer.parseInt(dt.getValueAt(row, 4).toString()); }//GEN-LAST:event_dtMouseClicked private void ddeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ddeleteActionPerformed // TODO add your handling code here: String name=tsrn.getText(); String sql = "Delete from `distributors` where did ='" + delete + "'"; try { prp = connection.prepareStatement(sql); prp.execute(); JOptionPane.showMessageDialog(null, "Employer " + name + " has been deleted"); defaultTableModel.getDataVector().removeAllElements(); defaultTableModel.fireTableDataChanged(); loadData(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Employer nicid " + delete + " not found"); } tname.setText(""); tcn.setText(""); tsrn.setText(""); tddue.setText(""); }//GEN-LAST:event_ddeleteActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel agn; private javax.swing.JLabel bg; private javax.swing.JLabel cn; private javax.swing.JButton dadd; private javax.swing.JButton ddelete; private javax.swing.JLabel ddue; private javax.swing.JScrollPane dscroll; private javax.swing.JButton dsearch; private javax.swing.JTable dt; private javax.swing.JButton dupdate; private javax.swing.JLabel name; private javax.swing.JTextField tcn; public javax.swing.JTextField tddue; private javax.swing.JComboBox<String> tdsearch; private javax.swing.JTextField tdsearch2; public javax.swing.JTextField tname; public javax.swing.JTextField tsrn; // End of variables declaration//GEN-END:variables }
true
9786ec9903e477eceacd4b05d4c29a7f92eca79d
Java
wayden-jones/Java-MasterClass
/NumberOfDaysInMonth/src/com/company/Main.java
UTF-8
657
3.625
4
[]
no_license
package com.company; public class Main { public static void main(String[] args) { System.out.println(getDaysInMonth(11, 2001)); } public static int getDaysInMonth(int month, int year) { LeapYear myLeapYear = new LeapYear(); if (month < 1 || month > 12 || year < 1 || year > 9999) return -1; switch (month) { case 9: case 4: case 6: case 11: return 30; case 2: if(myLeapYear.isLeapYear(year)) return 29; else return 28; default: return 31; } } }
true
17c199dd2f991dc4961339a1460c20239bfc880b
Java
maks7/Core-Java-2-HW
/W3-FilesPaths/FilesPaths/test/com/hackbulgaria/tests/TextTest.java
UTF-8
1,833
2.8125
3
[]
no_license
package com.hackbulgaria.tests; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import com.hackbulgaria.task7.text.Text; public class TextTest { Text text = new Text(); @Before public void setUp() { text = new Text(); } @Test public void test_compressString() { String str = "buffalo."; int dictSize = 256; Map<String, Integer> dictionary = new HashMap<>(); for (int i = 0; i < 256; i++) { dictionary.put("" + (char)i, i); } System.out.println(text.compressString(str, dictionary)); } @Test public void test_decompressString() { String str = "buffalo"; List<Integer> compressed = new ArrayList<>(); compressed.add(new Integer(98)); compressed.add(new Integer(117)); compressed.add(new Integer(102)); compressed.add(new Integer(102)); compressed.add(new Integer(97)); compressed.add(new Integer(108)); compressed.add(new Integer(111)); int dictSize = 256; Map<Integer, String> dictionary = new HashMap<>(); for (int i = 0; i < 256; i++) { dictionary.put(i,"" + (char) i); } System.out.println(text.decompressString(compressed, dictionary)); } @Test public void test_compress() { Path path = Paths.get(".\\res\\task7_2.txt"); text.compress(path); } @Test public void test_decompress() { Path path = Paths.get(".\\res\\task7_2.compr"); text.decompress(path); } }
true
716dd6dd8ab92982a341effa09a271cde79ee24c
Java
etillson/automation
/RandomGen.java
UTF-8
1,226
2.890625
3
[]
no_license
package test1; import java.util.Random; public class RandomGen extends seleniumTest{ public String randomId(){ int randId = 1 + (int)(Math.random()* 999999999); return Integer.toString(randId); } public String randomId(int length){ int temp = Integer.parseInt(concatenateDigits(length)); int randId = 1 + (int)(Math.random()* temp); return Integer.toString(randId); } public String randomUsername(){ String alphabet = new String("abcdefghijklmnopqrstuvwxyz"); int n = alphabet.length(); String result = new String(); Random r = new Random(); for (int i=0; i<10; i++) result = result + alphabet.charAt(r.nextInt(n)); return result; } public String randomPassword(){ String alphabet = new String("1234567890abcdefghijklmnopqrstuvwxyz!@#$%&*"); int n = alphabet.length(); String result = new String(); Random r = new Random(); for (int i=0; i<10; i++) result = result + alphabet.charAt(r.nextInt(n)); return result; } public static String concatenateDigits(int digits) { StringBuilder sb = new StringBuilder(); for (int k = 0; k<digits; k++) { sb.append(9); } return sb.toString(); } }
true
55f2fab9e12c781170e399d0c17134a13fc12a32
Java
xuepeng11/medicine-admin
/src/main/java/com/xpjava/medicine/entity/MedicineChn.java
UTF-8
1,037
1.914063
2
[]
no_license
package com.xpjava.medicine.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * * @since 2019-12-03 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class MedicineChn implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Integer id; private String goodsId; private String goodsName; private Date produceDate; private Date expireDate; private BigDecimal bidMoney; private BigDecimal saleMoney; private Integer quantity; private String producer; @TableField(exist = false) private String produceDateTemp; @TableField(exist = false) private String expireDateTemp; }
true
0be5deb03f1bc4d87b7a63fb18fbf8b29423232d
Java
prasannasv/IshaEventManager
/src/main/java/org/ishausa/events/MailPoller.java
UTF-8
3,889
2.453125
2
[ "Apache-2.0" ]
permissive
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.ishausa.events; import com.google.common.base.Throwables; import org.ishausa.oauth.OAuth2Authenticator; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Store; /** * * @author psriniv */ public class MailPoller { private static final Logger log = Logger.getLogger(MailPoller.class.getName()); private static final long POLLING_FREQUENCY_MINUTES = 15; private static final String INBOX = "inbox"; private static final String GMAIL_IMAP_HOST = "imap.gmail.com"; private static final int GMAIL_IMAP_PORT = 993; private Account account; private CountDownLatch runCountLatch; private CopyOnWriteArrayList<MailListener> listeners = new CopyOnWriteArrayList<MailListener>(); private ScheduledExecutorService pollerThread = Executors.newSingleThreadScheduledExecutor(); public static interface MailListener { void onNewMail(Message m); } public MailPoller(Account account, int runs) { this.account = account; runCountLatch = new CountDownLatch(runs); log.info("Initializing OAuth2 Authenticator"); OAuth2Authenticator.initialize(); } public void start() { log.info("Scheduling mail checker task"); pollerThread.scheduleWithFixedDelay(new MailCheckTask(), 0, POLLING_FREQUENCY_MINUTES, TimeUnit.MINUTES); } public void addListener(MailListener listener) { listeners.add(listener); } public void removeListener(MailListener listener) { listeners.remove(listener); } public void waitForRuns() throws InterruptedException { runCountLatch.await(); } public void shutdown() { pollerThread.shutdown(); try { pollerThread.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { //ignore during shutdown } finally { if (!pollerThread.isShutdown()) { pollerThread.shutdownNow(); } } } private void notifyListeners(Message m) { for (MailListener l : listeners) { l.onNewMail(m); } } private class MailCheckTask implements Runnable { @Override public void run() { try { log.info("Beginning run of Mail Check Task"); Store store = OAuth2Authenticator.connectToImap(GMAIL_IMAP_HOST, GMAIL_IMAP_PORT, account.getUser(), account.getAccessToken(), false); Folder inbox = store.getFolder(INBOX); inbox.open(Folder.READ_WRITE); log.info("inbox folder opened for read. inbox: " + inbox); int totalMessagesCount = inbox.getMessageCount(); int unreadMessagesCount = inbox.getUnreadMessageCount(); log.info("Total messages: " + totalMessagesCount + ", unread messages: " + unreadMessagesCount); Message[] unreadMessages = inbox.getMessages(totalMessagesCount - unreadMessagesCount + 1, totalMessagesCount); for (Message m : unreadMessages) { notifyListeners(m); } inbox.close(false); store.close(); } catch (Throwable t) { log.warning("Exception while checking mail: " + Throwables.getStackTraceAsString(t)); } finally { log.info("Finished run"); runCountLatch.countDown(); } } } }
true
5047e2640eec6e908931591ba51f58b5f6db0a13
Java
lonuslan/daily-leetcode
/src/main/java/com/lonuslan/dailyleetcode/chapter1/LongestSubstringWithoutRepeatingCharacters.java
UTF-8
4,752
3.984375
4
[]
no_license
package com.lonuslan.dailyleetcode.chapter1; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @author :lonus_lan * @date :Created in 2020/1/30 16:48 * @description: longest substring without repeating characters * @modified By: */ public class LongestSubstringWithoutRepeatingCharacters { /** * problem description: * * Given a string, find the length of the longest substring without repeating characters. * * Example 1: * * Input: "abcabcbb" * Output: 3 * Explanation: The answer is "abc", with the length of 3. * Example 2: * * Input: "bbbbb" * Output: 1 * Explanation: The answer is "b", with the length of 1. * Example 3: * * Input: "pwwkew" * Output: 3 * Explanation: The answer is "wke", with the length of 3. * Note that the answer must be a substring, "pwke" is a subsequence and not a substring. */ /** * 方法1: 暴力选择 * approach: Brute Force * Time complexity : O(n^3) * Space complexity : O(min(n, m)). * * @param s * @return */ public static int lengthOfLongestSubstring(String s) { if (s == null){ throw new IllegalArgumentException("Illegal input parameters"); } int length = s.length(); int aus = 0; for (int i = 0; i < length; i++){ for (int j = 0; j < length; j++){ if (allUnique(s, i, j)){ aus = Math.max(aus, j - i); } } } return aus; } /** * return true if the characters in the substring are all unique, * otherwise false. We can iterate through all the possible * substrings of the given string s and call the function allUnique. * If it turns out to be true, then we update our answer of the maximum length of substring without duplicate characters. * @param s * @param start * @param end * @return */ public static boolean allUnique(String s, int start, int end){ Set<Character> set = new HashSet<Character>(); // use the set collection properties, it do not have a duplicate element for (int i = start; i < end; i++) { Character ch = s.charAt(i); if (set.contains(ch)) { //if the substring has a duplicate character we return false , or we return true return false; } set.add(ch); } return true; } /** * approach_2: Sliding Window * Time complexity : O(n) * Space complexity : O(min(n, m)). * * @param s * @return */ public static int lengthOfLongestSubstring_approach_2(String s) { if (s == null){ throw new IllegalArgumentException("Illegal input parameters"); } int length = s.length(); Set<Character> set = new HashSet<Character>(); int aus = 0, i = 0, j = 0; while (i < length && j < length){ if (!set.contains(s.charAt(j))){ set.add(s.charAt(j++)); aus = Math.max(aus, j - i); }else { set.remove(s.charAt(i++)); } } return aus; } /** * approach_3: Sliding Window Optimized * Time complexity : O(n) * Space complexity(HashMap) : O(min(n, m)). * Space complexity(Table) : O(m) * * @param s * @return */ public static int lengthOfLongestSubstring_approach_3(String s) { if (s == null){ throw new IllegalArgumentException("Illegal input parameters"); } int n = s.length(), ans = 0; Map<Character, Integer> map = new HashMap<>(16); // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); } ans = Math.max(ans, j - i + 1); map.put(s.charAt(j), j + 1); } return ans; } public static int lengthOfLongestSubstring_approach_3_2(String s) { if (s == null){ throw new IllegalArgumentException("Illegal input parameters"); } int n = s.length(), ans = 0; int[] index = new int[128]; // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { i = Math.max(index[s.charAt(j)], i); ans = Math.max(ans, j - i + 1); index[s.charAt(j)] = j + 1; } return ans; } }
true
f9433f1adcc3de50294b250b54d031aa60020409
Java
jekkos/runwalkvideo
/runwalk-video/src/main/java/com/runwalk/video/io/VideoFileManager.java
UTF-8
11,963
2.390625
2
[]
no_license
package com.runwalk.video.io; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FilenameUtils; import org.jdesktop.application.utils.AppHelper; import org.jdesktop.application.utils.PlatformType; import com.google.common.collect.ImmutableSet; import com.runwalk.video.entities.Analysis; import com.runwalk.video.entities.Customer; import com.runwalk.video.entities.Recording; import com.runwalk.video.entities.RecordingStatus; import com.runwalk.video.settings.SettingsManager; import de.humatic.dsj.DSJException; import de.humatic.dsj.DSJUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This manager caches the recordings together with their corresponding video files. * It performs some simple file checking at data loading time to see whether the files actually exist. * This file checking logic was previously encapsulated in the {@link Recording} bean itself, * which was a bad design choice when the idea came up to create a server component for the application, * as the files are only locally accessible from each customer's file system. * * @author Jeroen Peelaerts * */ public class VideoFileManager { private static final Logger LOGGER = LoggerFactory.getLogger(VideoFileManager.class); private Map<Recording, RecordingStatus> recordingStatusMap = new HashMap<Recording, RecordingStatus>(); /** A sorted view on the key set of the cached {@link #recordingStatusMap}. */ private Map<String, Recording> fileNameRecordingMap = new HashMap<String, Recording>(); private final SettingsManager appSettings; public VideoFileManager(SettingsManager appSettings) { this.appSettings = appSettings; } /** * Get a {@link Recording} from the cache that is associated with the video file on the * given path. Will return <code>null</code> if nothing was found. * * @param videoPath The path to get the Recording for * @return The found recording */ public Recording getRecording(String videoPath) { Recording result = null; String fileName = FilenameUtils.getName(videoPath); // O(1) time complexity for this operation Recording recording = fileNameRecordingMap.get(fileName); if (recording.getVideoFileName().equals(fileName)) { result = recording; } return result; } public RecordingStatus getRecordingStatus(Recording recording) { RecordingStatus recordingStatus = recordingStatusMap.get(recording); return recordingStatus == null ? RecordingStatus.NON_EXISTANT_FILE : recordingStatus; } public boolean addToCache(Recording recording, RecordingStatus recordingStatus) { synchronized(recordingStatusMap) { RecordingStatus cachedRecordingStatus = recordingStatusMap.get(recording); if (recordingStatus != null && cachedRecordingStatus == null) { // O(1) time complexity for this operation fileNameRecordingMap.put(recording.getVideoFileName(), recording); // O(1) time complexity for this operation return recordingStatusMap.put(recording, recordingStatus) != null; } } return false; } private File resolveVideoFile(VideoFolderRetrievalStrategy videoFolderRetrievalStrategy, Recording recording, RecordingStatus recordingStatus) { File result = null; if (recordingStatus == RecordingStatus.UNCOMPRESSED) { result = getUncompressedVideoFile(recording); } else { result = getCompressedVideoFile(videoFolderRetrievalStrategy, recording); } return result; } private File getVideoFile(VideoFolderRetrievalStrategy videoFolderRetrievalStrategy, Recording recording) { synchronized(recordingStatusMap) { RecordingStatus recordingStatus = recordingStatusMap.get(recording); File videoFile = resolveVideoFile(videoFolderRetrievalStrategy, recording, recordingStatus); LOGGER.debug("Resolved videoFile {} with recordingStatus {}", videoFile.getAbsolutePath(), recordingStatus); if (recordingStatus == null) { File compressedVideoFile = getCompressedVideoFile(videoFolderRetrievalStrategy, recording); File uncompressedVideoFile = getUncompressedVideoFile(recording); if (canReadAndExists(compressedVideoFile)) { recordingStatus = RecordingStatus.COMPRESSED; videoFile = compressedVideoFile; // duration wasn't saved.. set again checkRecordingDuration(recording, videoFile); } else if (canReadAndExists(uncompressedVideoFile)) { recordingStatus = RecordingStatus.UNCOMPRESSED; // duration wasn't saved.. set again videoFile = uncompressedVideoFile; checkRecordingDuration(recording, videoFile); } else if (recording.getDuration() == 0) { // video file does not exist and duration is set to 0, prolly nothing recorded yet recordingStatus = RecordingStatus.READY; videoFile = uncompressedVideoFile; } else { LOGGER.warn("No videofile found for recording with filename " + recording.getVideoFileName()); recordingStatus = RecordingStatus.NON_EXISTANT_FILE; } LOGGER.debug("Add recording {} with status {} to cache", recording.getVideoFileName(), recordingStatus); addToCache(recording, recordingStatus); } return videoFile; } } public boolean isRecorded(List<Recording> recordings) { boolean result = false; for (Recording recording : recordings) { RecordingStatus recordingStatus = recordingStatusMap.get(recording); result |= recordingStatus != null && recordingStatus.isRecorded(); } return result; } public boolean isRecorded(Recording... recordings) { return isRecorded(Arrays.asList(recordings)); } /** * Returns an {@link ImmutableSet} containing all the currently cached {@link Recording}s . * Best practice is to assign this {@link Set} to a local variable directly, as calls to this method can * become expensive as the cached {@link #recordingStatusMap} size grows larger. * * @return The immutable set */ public Set<Recording> getCachedRecordings() { ImmutableSet.Builder<Recording> setBuilder = ImmutableSet.builder(); return setBuilder.addAll(recordingStatusMap.keySet()).build(); } public File getVideoFile(Recording recording) { return getVideoFile(getVideoFolderRetrievalStrategy(), recording); } /** * Check if the duration for the given recording and videofile is synchronized correctly. * If not, then get the duration of the video file and set it on the recording. * * @param recording The recording to check the duration for * @param videoFile The video file representing the given recording */ private void checkRecordingDuration(Recording recording, File videoFile) { if (recording.getDuration() == 0) { long duration = getDuration(videoFile); recording.setDuration(duration); LOGGER.warn("Previously unsaved duration for " + recording.getVideoFileName() + " now set to " + duration); } } public boolean updateCache(Recording recording, RecordingStatus recordingStatus) { // O(1) time complexity for this operation fileNameRecordingMap.put(recording.getVideoFileName(), recording); // O(1) time complexity for this operation return recordingStatusMap.put(recording, recordingStatus) != null; } public int refreshCache() { int filesMissing = 0; for (Recording recording : recordingStatusMap.keySet()) { filesMissing += refreshCache(recording); } return filesMissing; } public int refreshCache(List<Analysis> analyses) { int filesMissing = 0; for (Analysis analysis : analyses) { filesMissing += refreshCache(analysis); } return filesMissing; } /** * This method will iterate over the {@link Recording}s of the given {@link Analysis} and * clear it's cache entries. The method will return the number of missing video files when done refreshing. * * @param analysis The analysis for which the recording cache should be refreshed * @return The number of missing video files */ public int refreshCache(Analysis analysis) { int filesMissing = 0; for (Recording recording : analysis.getRecordings()) { filesMissing += refreshCache(recording); } return filesMissing; } public int refreshCache(Recording recording) { File videoFile = refreshCache(getVideoFolderRetrievalStrategy(), recording); return videoFile == null ? 1 : 0; } public File refreshCache(VideoFolderRetrievalStrategy videoFolderRetrievalStrategy, Recording recording) { removeRecording(recording); return getVideoFile(videoFolderRetrievalStrategy, recording); } private boolean removeRecording(Recording recording) { RecordingStatus removedRecordingStatus = recordingStatusMap.remove(recording); Recording removedRecording = fileNameRecordingMap.remove(recording.getVideoFileName()); return removedRecordingStatus != null && removedRecording != null; } public boolean canReadAndExists(File videoFile) { return videoFile != null && videoFile.exists() && videoFile.canRead(); } public boolean canReadAndExists(Recording recording) { File videoFile = getVideoFile(recording); return canReadAndExists(videoFile); } public File getCompressedVideoFile(VideoFolderRetrievalStrategy videoFolderRetrievalStrategy, Recording recording) { File parentFolder = videoFolderRetrievalStrategy.getVideoFolder(getAppSettings().getVideoDir(), recording); return new File(parentFolder, recording.getVideoFileName()); } public File getCompressedVideoFile(Recording recording) { return getCompressedVideoFile(getVideoFolderRetrievalStrategy(), recording); } public File getUncompressedVideoFile(Recording recording) { return new File(getAppSettings().getUncompressedVideoDir(), recording.getVideoFileName()); } public SettingsManager getAppSettings() { return appSettings; } public VideoFolderRetrievalStrategy getVideoFolderRetrievalStrategy() { return getAppSettings().getVideoFolderRetrievalStrategy(); } public void setVideoFolderRetrievalStrategy(VideoFolderRetrievalStrategy videoFolderRetrievalStrategy) { getAppSettings().setVideoFolderRetrievalStrategy(videoFolderRetrievalStrategy); } /** * Get the duration of the given video file using a native video library. * Be aware that this can be a pretty expensive method invocation. * * @param videoFile The file to get the duration for * @return The duration */ public static long getDuration(File videoFile) { long duration = 0; try { if (videoFile.exists() && AppHelper.getPlatform() == PlatformType.WINDOWS) { duration = DSJUtils.getBasicFileStats(videoFile.getAbsolutePath())[0]; } } catch(DSJException e) { String hresultToHexString = DSJException.hresultToHexString(e.getErrorCode()); LOGGER.error("Failed to read meta info from for file " + videoFile.getAbsolutePath() + " (hex code: 0x" + hresultToHexString + ")", e); } return duration; } public boolean hasDuplicateFiles(Recording recording) { return getCompressedVideoFile(recording).exists() && getUncompressedVideoFile(recording).exists(); } /** * Delete the video file from the disk for the given {@link Recording}. If there are both * compressed and uncompressed versions, then the only the compressed one will be removed. * * @param recording The recording to remove the video file for */ private void deleteVideoFile(Recording recording) { File videoFile = getVideoFile(recording); removeRecording(recording); if (videoFile != null) { videoFile.deleteOnExit(); LOGGER.debug(videoFile.getAbsolutePath() + " scheduled for removal."); } } public void deleteVideoFiles(Analysis analysis) { for(Recording recording : analysis.getRecordings()) { deleteVideoFile(recording); } } public void deleteVideoFiles(Customer customer) { for (Analysis analysis : customer.getAnalyses()) { deleteVideoFiles(analysis); } } public File getVideoDir() { return getAppSettings().getVideoDir(); } public File getUncompressedVideoDir() { return getAppSettings().getUncompressedVideoDir(); } }
true
d066f5c92363315e689d45ca8b58fb4df58bf626
Java
vittin/battleshipServer
/src/main/java/org/cucumbers/Ship.java
UTF-8
384
2.9375
3
[]
no_license
package org.cucumbers; /** Created by Mateusz on 2016-06-11. */ class Ship { private final int size; private int shotParts = 0; Ship(int size){ this.size = size; } boolean isAlive() { return (size - shotParts) > 0; } int getSize() { return size; } void damage() { this.shotParts = this.shotParts + 1; } }
true
8bf94ffe3f77af99c986fb8fe8b118397579e726
Java
kkutschera/GoLiteJavaCompiler
/test.java
UTF-8
4,659
3.171875
3
[]
no_license
import java.util.Arrays; import java.util.ArrayList; import java.lang.ArrayIndexOutOfBoundsException; class Slice<T>{ public int cap; public int len; public ArrayList<T> elementList; public Slice() { elementList = new ArrayList<>(0); cap = 0; len = 0; } public Slice<T> append(T element) { if (len == cap) { ArrayList<T> newElementList; int newCap = 0; if (cap == 0) { newElementList = new ArrayList<>(2); newCap = 2; } else { newElementList = new ArrayList<>(cap * 2); newCap = cap * 2; } // Copy over old elements for (int i = 0; i < cap; i++) { newElementList.add(i, elementList.get(i)); } Slice<T> newSlice = new Slice<>(); newSlice.cap = newCap; newElementList.add(len, element); newSlice.len = len + 1; newSlice.elementList = newElementList; return newSlice; } else{ elementList.add(len, element); Slice<T> newSlice = new Slice<>(); newSlice.len = len + 1; newSlice.cap = cap; newSlice.elementList = elementList; return newSlice; } } public Slice<T> copy() { Slice<T> copy = new Slice<>(); copy.cap = this.cap; copy.len = this.len; copy.elementList = this.elementList; return copy; } // TODO: handle the different cases with appropriate errors public T get(int index) throws ArrayIndexOutOfBoundsException { if (index < 0) { throw new ArrayIndexOutOfBoundsException("Slice index must be non-negative."); } else if (index >= cap) { throw new ArrayIndexOutOfBoundsException("Index must be less than the capacity of the slice."); } else if (index >= len) { throw new ArrayIndexOutOfBoundsException("Index must be less than the length of the slice."); } else { return elementList.get(index); } } // TODO: handle the different cases with appropriate errors public void put (int index, T element) throws ArrayIndexOutOfBoundsException { if (index < 0) { throw new ArrayIndexOutOfBoundsException("Slice index must be non-negative."); } else if (index >= cap) { throw new ArrayIndexOutOfBoundsException("Index must be less than the capacity of the slice."); } else if (index >= len) { throw new ArrayIndexOutOfBoundsException("Index must be less than the length of the slice."); } else { elementList.add(index, element); } } }// Utility class containing all methods to cast between types class Cast { public static Integer castToInteger(Integer i) { return i; } public static Integer castToInteger(Double d) { return d.intValue(); } public static Integer castToInteger(Character c) { return (int) c; } public static Double castToDouble(Integer i) { return i.doubleValue(); } public static Double castToDouble(Double d) { return d; } public static Double castToDouble(Character c) { return (double) c; } public static String castToString(Integer i) { return new Character((char) i.intValue()).toString(); } public static String castToString(String s) { return s; } public static String castToString(Character c) { return c.toString(); } public static Character castToCharacter(Integer i) { return new Character((char) i.intValue()); } public static Character castToCharacter(Double d) { return new Character((char) d.intValue()); } public static Character castToCharacter(Character c) { return c; } } public class test { public static Boolean __golite__true = Boolean.TRUE; public static Boolean __golite__false = Boolean.FALSE; public static Cast castUtil = new Cast(); public static void __golite__main () { Integer[][] __golite__list_1 = new Integer[3][4]; for(int _golite_iter_i0 = 0; _golite_iter_i0 < 4; _golite_iter_i0++){ for(int _golite_iter_i1 = 0; _golite_iter_i1 < 3; _golite_iter_i1++){ __golite__list_1[_golite_iter_i0][_golite_iter_i1] = new Integer(0); } } ; __golite__list_1[new Integer(1)][new Integer(1)] = new Integer(3); System.out.print(__golite__list_1[new Integer(1)][new Integer(1)]); System.out.println(); System.out.print(__golite__list_1[new Integer(0)][new Integer(0)]); System.out.println(); } public static void main(String[] args) { __golite__main(); } }
true
e863205ca76bf3032f1a2373447e30e076f039c9
Java
lichunbo123/moji-lcb
/client/Test/app/src/main/java/cn/edu/hebtu/software/test/Activity/LoginInActivity.java
UTF-8
9,579
1.882813
2
[]
no_license
package cn.edu.hebtu.software.test.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.text.method.TransformationMethod; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Set; import androidx.appcompat.app.AppCompatActivity; import cn.edu.hebtu.software.test.Data.User; import cn.edu.hebtu.software.test.R; import cn.edu.hebtu.software.test.Setting.MyApplication; import cn.edu.hebtu.software.test.Util.DetermineConnServer; import cn.edu.hebtu.software.test.Util.PermissionUtils; import cn.edu.hebtu.software.test.Util.SharedUtil; import cn.jpush.android.api.JPushInterface; import cn.jpush.android.api.TagAliasCallback; /** * @ProjectName: MoJi * @Description: 登录页面 * @Author: 李晓萌 * @CreateDate: 2019/12/2 16:23 * @Version: 1.0 */ public class LoginInActivity extends AppCompatActivity implements View.OnClickListener{ private Button btnSignIn; private EditText edtPhone; private EditText edtPwd; private ImageView ivEye; private TextView tvfgPwd; private TextView tvSignup; private boolean isHideFirst = true;//输入框密码是否是隐藏的,默认为true private MyApplication data; private String ip; private User user; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case 1: Toast.makeText(LoginInActivity.this,"手机号或密码不正确",Toast.LENGTH_SHORT).show(); break; case 2: user = (User) msg.obj; final MyApplication data = (MyApplication) getApplication(); data.setUser(user); //登陆成功,如果退出登录时已关闭推送功能,则再次登录时恢复此功能 if(JPushInterface.isPushStopped(getApplicationContext())){ JPushInterface.resumePush(getApplicationContext()); } if(!"success".equals(SharedUtil.getString("isGuide", getApplicationContext(), user.getUserId()))){ // 调用 Handler 来异步设置别名,一般都是用userId来进行设置别名(唯一性)。 JPushInterface.setAlias(getApplicationContext(),user.getUserId() ,mAliasCallback); } Intent in = new Intent(LoginInActivity.this,MainActivity.class); startActivity(in); finish(); break; case 3: Toast.makeText(LoginInActivity.this, "未连接到服务器", Toast.LENGTH_SHORT).show(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loginin); PermissionUtils.openNotifiPermission(this); data = (MyApplication) getApplication(); ip = data.getIp(); data.setMsgPermission("open"); getViews(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); } ivEye.setOnClickListener(this); ivEye.setImageResource(R.mipmap.biyanjing); btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnSignIn: String phone = edtPhone.getText().toString().trim(); String pwd = edtPwd.getText().toString().trim(); if(pwd.length() < 6) { Toast.makeText(getApplicationContext(), "密码少于6位", Toast.LENGTH_SHORT).show(); }else if(pwd.length() > 12){ Toast.makeText(getApplicationContext(), "密码多于12位", Toast.LENGTH_SHORT).show(); }else{ login(phone,pwd); } } } }); //TextView的事件回调函数 tvfgPwd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); tvSignup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(LoginInActivity.this,RegistActivity.class); startActivity(intent); } }); } private void getViews() { edtPhone = findViewById(R.id.edt_phone); btnSignIn = findViewById(R.id.btnSignIn); edtPwd = findViewById(R.id.edt_pwd); ivEye = findViewById(R.id.iv_eye); tvfgPwd = findViewById(R.id.tv_fgpwd); tvSignup = findViewById(R.id.tv_signup); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_eye: if (isHideFirst == true) { ivEye.setImageResource(R.mipmap.yanjing); //密文 HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance(); edtPwd.setTransformationMethod(method1); isHideFirst = false; } else { ivEye.setImageResource(R.mipmap.biyanjing); //密文 TransformationMethod method = PasswordTransformationMethod.getInstance(); edtPwd.setTransformationMethod(method); isHideFirst = true; } // 光标的位置 int index = edtPwd.getText().toString().length(); edtPwd.setSelection(index); break; } } /** * @author 春波 * @time 2019/12/10 16:44 * @Description:登录 */ private void login(String phone, String pwd) { new Thread(){ public void run(){ try { Message msg = Message.obtain(); if(DetermineConnServer.isConnByHttp(LoginInActivity.this)){ User threadUser = new User(); URL url = new URL("http://" + ip + ":8080/MoJi/user/login?phone=" + phone + "&password=" + pwd); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String str = reader.readLine(); if("0".equals(str)){ msg.what = 1; }else { Gson gson = new Gson(); Log.e("user=", str); threadUser = gson.fromJson(str, User.class); msg.what = 2; msg.obj = threadUser; } }else { msg.what = 3; } handler.sendMessage(msg); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } /** * @author: 张璐婷 * @time: 2019/12/12 9:18 * @Description: 设置别名回调 */ private final TagAliasCallback mAliasCallback = new TagAliasCallback() { @Override public void gotResult(int code, String alias, Set<String> tags) { Log.e("setAliasCallback_code", code + ""); switch (code) { case 0: // 这里往 SharePreference 里写一个成功设置的状态。成功设置一次后,以后不必再次设置了。 SharedUtil.putString("isGuide",LoginInActivity.this, user.getUserId(), "success"); break; case 6002: // 延迟 60 秒来调用 Handler 设置别名(网络不佳时) handler.sendMessageDelayed(handler.obtainMessage(1001, alias), 1000 * 60); break; default: break; } } }; }
true
3c5edc03c57f36e75cc20005863e9617a24e8e7f
Java
liuxiaoming7708/p2p
/parent/mgrsite/src/main/java/com.payease.p2p/mgrsite/controller/RealAuthController.java
UTF-8
1,264
1.929688
2
[]
no_license
package com.payease.p2p.mgrsite.controller; import com.payease.p2p.base.query.RealAuthQueryObject; import com.payease.p2p.base.service.IRealAuthService; import com.payease.p2p.base.util.JSONResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * 后台 实名认证审核 * Created by liuxiaoming on 2017/6/28. */ @Controller public class RealAuthController { @Autowired private IRealAuthService realAuthService; /** * 分页查询实名认证列表 * @param model * @return */ @RequestMapping("realAuth") public String realAuth(@ModelAttribute("qo")RealAuthQueryObject qo, Model model){ model.addAttribute("pageResult",this.realAuthService.query(qo)); return "realAuth/list"; } @RequestMapping("realAuth_audit") @ResponseBody public JSONResult realAuth_audit(Long id,String remark,int state){ this.realAuthService.audit(id,remark,state); return new JSONResult(); } }
true
3d5a4c292df06bdb23a7e52e94efdfa4a3d1b41f
Java
Bouowmx/APCS
/06-Quickselect/Quickselect.java
UTF-8
2,153
3.9375
4
[ "MIT" ]
permissive
import java.util.Arrays; import java.util.Random; import static java.lang.System.out; public class Quickselect { //Quickselect is one word //I tried creating quickselect for ints. It didn't work because with int, one cannot indicate "empty" space(s) for the pivot: 0, -1, or any other integer don't work. Integer was the next best thing but with the compareTo method, why not with Comparable? public static <E extends Comparable<? super E>> E quickselect(E[] a, int n) {return quickselect(a, n, 0, a.length);} private static <E extends Comparable<? super E>> E quickselect(E[] a, int n, int left, int right) { if ((right - left) <= 1) {return a[left];} //Following Java conventions of excluding the latter Random random = new Random(); E pValue = a[left + random.nextInt(right - left - 1)]; E[] aCopy = Arrays.copyOf(a, a.length); //Iteration would be a better idea, considering all the copying Arrays.fill(aCopy, left, right, null); int j = left, k = right - 1; for (int i = left; i < right; i++) { if (a[i].compareTo(pValue) < 0) {aCopy[j++] = a[i];} if (a[i].compareTo(pValue) > 0) {aCopy[k--] = a[i];} } for (int i = left; i < right; i++) {if (aCopy[i] == null) {aCopy[i] = pValue;}} int pIndex = -1; for (int i = left; i < right; i++) { if (aCopy[i].equals(pValue)) { pIndex = i; break; } } if (pIndex < n) {return quickselect(aCopy, n, pIndex + 1, right);} if (pIndex > n) {return quickselect(aCopy, n, left, pIndex);} //No need to use pIndex - 1 because the exclusion of the latter in a range already compensates return aCopy[pIndex]; } public static void main(String[] args) { Integer[] a = new Integer[20]; Random random = new Random(); for (int i = 0; i < a.length; i++) {a[i] = random.nextInt(10);} out.println("nth smallest element in " + Arrays.toString(a) + ":"); Integer[] aCopy = Arrays.copyOf(a, a.length); Arrays.sort(aCopy); out.println(" sorted: " + Arrays.toString(aCopy)); out.println("n|nth smallest element"); out.println("----------------------"); for (int i = 0; i < 10; i++) { out.println(i + "|" + quickselect(a, i)); } } }
true
e048d88e969d5de32b94c27a8ddcdcd5bf9a49ec
Java
viianaisabel/exercicios_java
/POO I/Lista 5/Peixe.java
UTF-8
329
3.171875
3
[]
no_license
package Lista_5; public final class Peixe extends Animal implements Aquatico { public Peixe(int x, int y) { super(x, y); } @Override public void nada(Posicao posDestino) { System.out.println("Peixe nadando de posição ("+this.x+","+this.y+") para ("+posDestino.x+","+posDestino.y+")"); } }
true
7d4f6273a3ccd97fab1d0d082e3d9020552c11f6
Java
mcteach21/CircularMenuDemo
/app/src/main/java/mchou/apps/main/tools/Animations.java
UTF-8
820
2.15625
2
[]
no_license
package mchou.apps.main.tools; import androidx.appcompat.app.ActionBar; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import mchou.apps.main.R; public class Animations { public static void AnimateActionBar(Context context, ActionBar actionbar, int animate_duration) { ColorDrawable begin = new ColorDrawable(context.getResources().getColor(R.color.antiquewhite, null)); ColorDrawable end = new ColorDrawable(context.getResources().getColor(R.color.maroon, null)); TransitionDrawable actionBarTransition = new TransitionDrawable(new Drawable[] {begin, end}); actionbar.setBackgroundDrawable(actionBarTransition); actionBarTransition.startTransition(animate_duration); } }
true
58889cbb5d3331f28ecf9137ca8cdd0a84478e9b
Java
Angular2Guy/AngularPortfolioMgr
/backend/src/main/java/ch/xxx/manager/adapter/client/NasdaqConnector.java
UTF-8
3,490
2.140625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2019 Sven Loesekann 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 ch.xxx.manager.adapter.client; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.net.SocketException; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import org.apache.commons.net.PrintCommandListener; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import org.springframework.stereotype.Component; import ch.xxx.manager.domain.utils.MyLogPrintWriter; import ch.xxx.manager.usecase.service.NasdaqClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Component public class NasdaqConnector implements NasdaqClient { private static final Logger LOGGER = LoggerFactory.getLogger(NasdaqConnector.class); private static final String HOST = "ftp.nasdaqtrader.com"; private static final String DIR = "/symboldirectory/"; private static final List<String> IMPORT_FILES = Arrays.asList("nasdaqlisted.txt", "otherlisted.txt"); public Mono<List<String>> importSymbols() { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(new MyLogPrintWriter(LOGGER, Level.INFO)))); try { ftp.setStrictReplyParsing(false); ftp.connect(HOST); ftp.enterLocalPassiveMode(); ftp.login("anonymous", "sven@gmx.de"); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.disconnect(); throw new SocketException(String.format("Failed to connect to %s", HOST)); } FTPFile[] files = ftp.listFiles(DIR); if (2 != Arrays.stream(files).map(FTPFile::getName).filter(file -> IMPORT_FILES.contains(file)).count()) { throw new FileNotFoundException( String.format("Files: %s, %s", IMPORT_FILES.get(0), IMPORT_FILES.get(1))); } } catch (IOException e) { throw new RuntimeException(e); } return Flux.concat(this.importSymbols(IMPORT_FILES.get(0), ftp), this.importSymbols(IMPORT_FILES.get(1), ftp)).collectList() .doAfterTerminate(() -> { try { ftp.logout(); ftp.disconnect(); } catch (IOException e) { throw new RuntimeException(String.format("Failed to close ftp connection to: %s", HOST)); } }); } private Flux<String> importSymbols(String fileName, FTPClient ftp) { String[] symbols = new String[0]; try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { if(ftp.retrieveFile(String.format("/%s/%s", DIR, fileName), baos)) { LOGGER.info("File imported: {}", fileName); } else { LOGGER.warn("File import failed: {}", fileName); } symbols = baos.toString(Charset.defaultCharset()).split("\\r?\\n"); } catch (IOException e) { throw new RuntimeException(e); } return Flux.fromArray(symbols); } }
true
96d67ce4ea336dbec9219769a46dfb752ade32f8
Java
BackupTheBerlios/nwnprc
/DocGen/prc/utils/ScrollMerchantGen.java
UTF-8
10,942
2.59375
3
[]
no_license
package prc.utils; import static prc.Main.verbose; import java.util.*; import java.io.*; import prc.autodoc.*; import prc.autodoc.Main.TLKStore; import prc.autodoc.Main.TwoDAStore; /** * A little tool that parses des_crft_scroll, extracts unique item resrefs from it and * makes a merchant selling those resrefs. * * @author Heikki 'Ornedan' Aitakangas */ public class ScrollMerchantGen { /** * Ye olde maine methode. * * @param args The arguments * @throws IOException If the writing fails, just die on the exception */ public static void main(String[] args) throws IOException{ if(args.length == 0) readMe(); String twoDAPath = null; String tlkPath = null; // parse args for(String param : args) {//2dadir tlkdir | [--help] // Parameter parseage if(param.startsWith("-")) { if(param.equals("--help")) readMe(); else{ for(char c : param.substring(1).toCharArray()) { switch(c) { default: System.out.println("Unknown parameter: " + c); readMe(); } } } } else { // It's a pathname if(twoDAPath == null) twoDAPath = param; else if(tlkPath == null) tlkPath = param; else{ System.out.println("Unknown parameter: " + param); readMe(); } } } // Load data TwoDAStore twoDA = new TwoDAStore(twoDAPath); TLKStore tlks = new TLKStore("dialog.tlk", "prc_consortium.tlk", tlkPath); doScrollMerchantGen(twoDA, tlks); } /** * Performs the scroll merchant generation. Made public for the purposes of BuildScrollHack. * * @param twoDA A TwoDAStore for loading 2da data from * @param tlks A TLKStore for reading tlk data from * @throws IOException Just tossed back up */ public static void doScrollMerchantGen(TwoDAStore twoDA, TLKStore tlks) throws IOException { // Load the 2da file Data_2da scrolls2da = twoDA.get("des_crft_scroll"); Data_2da spells2da = twoDA.get("spells"); // Loop over the scroll entries and get a list of unique resrefs TreeMap<Integer, TreeMap<String, String>> arcaneScrollResRefs = new TreeMap<Integer, TreeMap<String, String>>(); TreeMap<Integer, TreeMap<String, String>> divineScrollResRefs = new TreeMap<Integer, TreeMap<String, String>>(); String entry; for(int i = 0; i < scrolls2da.getEntryCount(); i++) { // Skip subradials if(spells2da.getEntry("Master", i).equals("****")) { if(!(entry = scrolls2da.getEntry("Wiz_Sorc", i)).equals("****")) addScroll(arcaneScrollResRefs, spells2da, tlks, i, entry.toLowerCase()); if(!(entry = scrolls2da.getEntry("Cleric", i)).equals("****")) addScroll(divineScrollResRefs, spells2da, tlks, i, entry.toLowerCase()); if(!(entry = scrolls2da.getEntry("Paladin", i)).equals("****")) addScroll(divineScrollResRefs, spells2da, tlks, i, entry.toLowerCase()); if(!(entry = scrolls2da.getEntry("Druid", i)).equals("****")) addScroll(divineScrollResRefs, spells2da, tlks, i, entry.toLowerCase()); if(!(entry = scrolls2da.getEntry("Ranger", i)).equals("****")) addScroll(divineScrollResRefs, spells2da, tlks, i, entry.toLowerCase()); if(!(entry = scrolls2da.getEntry("Bard", i)).equals("****")) addScroll(arcaneScrollResRefs, spells2da, tlks, i, entry.toLowerCase()); } } String xmlPrefix = "<gff name=\"prc_scrolls.utm\" type=\"UTM \" version=\"V3.2\" >" + "\n" + " <struct id=\"-1\" >" + "\n" + " <element name=\"ResRef\" type=\"11\" value=\"prc_scrolls\" />" + "\n" + " <element name=\"LocName\" type=\"12\" value=\"64113\" >" + "\n" + " <localString languageId=\"0\" value=\"prc_scrolls\" />" + "\n" + " </element>" + "\n" + " <element name=\"Tag\" type=\"10\" value=\"prc_scrolls\" />" + "\n" + " <element name=\"MarkUp\" type=\"5\" value=\"100\" />" + "\n" + " <element name=\"MarkDown\" type=\"5\" value=\"100\" />" + "\n" + " <element name=\"BlackMarket\" type=\"0\" value=\"0\" />" + "\n" + " <element name=\"BM_MarkDown\" type=\"5\" value=\"15\" />" + "\n" + " <element name=\"IdentifyPrice\" type=\"5\" value=\"-1\" />" + "\n" + " <element name=\"MaxBuyPrice\" type=\"5\" value=\"-1\" />" + "\n" + " <element name=\"StoreGold\" type=\"5\" value=\"-1\" />" + "\n" + " <element name=\"OnOpenStore\" type=\"11\" value=\"\" />" + "\n" + " <element name=\"OnStoreClosed\" type=\"11\" value=\"\" />" + "\n" + " <element name=\"WillNotBuy\" type=\"15\" />" + "\n" + " <element name=\"WillOnlyBuy\" type=\"15\" >" + "\n" + " <struct id=\"97869\" >" + "\n" + " <element name=\"BaseItem\" type=\"5\" value=\"29\" />" + "\n" + " </struct>" + "\n" + " </element>" + "\n" + " <element name=\"StoreList\" type=\"15\" >" + "\n" + " <struct id=\"0\" />" + "\n" + " <struct id=\"4\" />" + "\n" + " <struct id=\"2\" >" + "\n" + " <element name=\"ItemList\" type=\"15\" >" + "\n"; String xmlSuffix = " </element>" + "\n" + " </struct>" + "\n" + " <struct id=\"3\" />" + "\n" + " <struct id=\"1\" />" + "\n" + " </element>" + "\n" + " <element name=\"ID\" type=\"0\" value=\"5\" />" + "\n" + " <element name=\"Comment\" type=\"10\" value=\"\" />" + "\n" + " </struct>" + "\n" + "</gff>" + "\n"; StringBuffer xmlString = new StringBuffer(); int posCounter = 0; // First arcane scrolls for(Map<String, String> levelScrollResRefs : arcaneScrollResRefs.values()) for(String name : levelScrollResRefs.keySet()) { String resref = levelScrollResRefs.get(name); xmlString.append( " <struct id=\"" + posCounter + "\" >" + "\n" + " <element name=\"InventoryRes\" type=\"11\" value=\"" + resref + "\" />" + "<!-- " + name + " -->" + "\n" + " <element name=\"Repos_PosX\" type=\"2\" value=\"" + (posCounter % 10) + "\" />" + "\n" + " <element name=\"Repos_Posy\" type=\"2\" value=\"" + (posCounter / 10) + "\" />" + "\n" + " <element name=\"Infinite\" type=\"0\" value=\"1\" />" + "\n" + " </struct>" + "\n" ); posCounter++; } // Then divine scrolls for(Map<String, String> levelScrollResRefs : divineScrollResRefs.values()) for(String name : levelScrollResRefs.keySet()) { String resref = levelScrollResRefs.get(name); xmlString.append( " <struct id=\"" + posCounter + "\" >" + "\n" + " <element name=\"InventoryRes\" type=\"11\" value=\"" + resref + "\" />" + "<!-- " + name + " -->" + "\n" + " <element name=\"Repos_PosX\" type=\"2\" value=\"" + (posCounter % 10) + "\" />" + "\n" + " <element name=\"Repos_Posy\" type=\"2\" value=\"" + (posCounter / 10) + "\" />" + "\n" + " <element name=\"Infinite\" type=\"0\" value=\"1\" />" + "\n" + " </struct>" + "\n" ); posCounter++; } File target = new File("prc_scrolls.utm.xml"); // Clean up old version if necessary if(target.exists()) { if(verbose) System.out.println("Deleting previous version of " + target.getName()); target.delete(); } if(verbose) System.out.println("Writing brand new version of " + target.getName()); target.createNewFile(); // Creater the writer and print FileWriter writer = new FileWriter(target, true); writer.write(xmlPrefix + xmlString.toString() + xmlSuffix); // Clean up writer.flush(); writer.close(); } private static void addScroll(TreeMap<Integer, TreeMap<String, String>> scrollResRefs, Data_2da spells2da, TLKStore tlks, int rowNum, String scrollResRef) { int innateLevel = -1, tlkRef = -1; // HACK - Skip non-PRC scrolls if(!scrollResRef.startsWith("prc_scr_")) return; try { innateLevel = Integer.parseInt(spells2da.getEntry("Innate", rowNum)); } catch (NumberFormatException e) { System.err.println("Non-number value in spells.2da Innate column on line " + rowNum + ": " + spells2da.getEntry("Innate", rowNum)); return; } try { tlkRef = Integer.parseInt(spells2da.getEntry("Name", rowNum)); } catch (NumberFormatException e) { System.err.println("Non-number value in spells.2da Name column on line " + rowNum + ": " + spells2da.getEntry("Name", rowNum)); return; } if(scrollResRefs.get(innateLevel) == null) scrollResRefs.put(innateLevel, new TreeMap<String, String>()); scrollResRefs.get(innateLevel).put(tlks.get(tlkRef), scrollResRef); } /** * Prints the use instructions for this program and kills execution. */ private static void readMe() { // 0 1 2 3 4 5 6 7 8 // 12345678901234567890123456789012345678901234567890123456789012345678901234567890 System.out.println("Usage:\n"+ " java -jar prc.jar scrmrchgen 2dadir tlkdir | [--help]\n"+ "\n"+ "2dadir Path to a directory containing des_crft_scroll.2da and spells.2da.\n" + "tlkdir Path to a directory containing dialog.tlk and prc_consortium.tlk\n" + "\n"+ "--help prints this info you are reading\n" + "\n" + "\n" + "Generates a merchant file - prc_scrolls.utm - based on the given scroll list\n" + "2da file. The merchant file will be written to current directory in Pspeed's\n" + "XML <-> Gff -xml format\n" ); System.exit(0); } }
true
47a88f40997bc843b301e522079e7a7fb49b8de9
Java
RafalBrendanWelz/PraceDomoweSDA
/praceDomoweSourceCode/src/Grudzien/SwietaPaczkaZads/czasData.java
UTF-8
9,599
3.09375
3
[]
no_license
package Grudzien.SwietaPaczkaZads; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.Random; import java.util.Scanner; import java.util.regex.Pattern; public class czasData { public static void zadCzasData() throws InterruptedException { //zad1Start(); //zad2Start(); //zad3Start(); //zad4Start(); //zad5Start(); zad6Start(); } private static void zad6Start() { LocalTime startAplikac = LocalTime.now(); System.out.println("Aplikacja Przepowie ci prawdopodobną datę twojej śmierci: "); System.out.println("Wpisz datę swoich urodzin "); LocalDate urodziny = dajDate(); int[] skracanieZycia = zad6Pytania(); LocalDate dataSmierc = urodziny.plusDays( 36500 - skracanieZycia[0]*364 ); System.out.println(skracanieZycia[0]); System.out.println("Aplikacja Przewiduje że zginiesz w naturalny sposób następującego dnia"); dataSmierc.format( DateTimeFormatter.ofPattern("dd:MM:yyyy") ); System.out.println(dataSmierc); if (skracanieZycia[1] > 0){ System.out.println("Ponadto masz szansę umrzeć na zawał serca w wieku: "); System.out.println(" " + ( urodziny.plusYears( skracanieZycia[1] ).getYear() - urodziny.getYear() ) + " lat, w " + urodziny.plusYears( skracanieZycia[1] ) ); } if (skracanieZycia[2] > 0){ System.out.println("Ponadto masz szansę umrzeć w wypadku samochodowym w wieku: "); System.out.println(" " + ( urodziny.plusYears( skracanieZycia[2] ).getYear() - urodziny.getYear() ) + " lat, w " + urodziny.plusYears( skracanieZycia[2] ) ); } System.out.println("\nPonadto na szukaniu swojej daty śmierci aktualnie spędziłeś/aś: "); System.out.println(" " + Duration.between(startAplikac, LocalTime.now() ).getSeconds() + " sekund" ); } private static int[] zad6Pytania() { int wynikSkr = 0; System.out.println("Wpisz 'm' jeśli jesteś mężczyzną, lub 'k' jeśli jesteś Kobietą"); char plec = ustawPlec( dajChar() ); switch ( plec ){ case 'm':{ wynikSkr += 8; break; } case 'k':{ break; } default:{ wynikSkr += 15; } } System.out.println("Czy palisz papierosy, jak tak to ile papierosów dziennie palisz? wpisz liczbę "); int ilePet = dajIlePetow(); wynikSkr = wynikSkr + (int)( ilePet * 1.5 ); System.out.println("Czy żyjesz w stresie, w skali od 0 do 10 jak duży stres na co dzień odczuwasz? "); byte stresPoziom = dajStresPoziom(); int kiedyZaw = 0, ileRazTrue = 0; for (int i = 0; i <= stresPoziom; i++) { Random losZawal = new Random(); int losLiczba = losZawal.nextInt(100); if (losLiczba > 90){ ileRazTrue++; kiedyZaw = 60; } } kiedyZaw = kiedyZaw - (int)(ileRazTrue / 3); wynikSkr = wynikSkr + (int)(ileRazTrue * 2 / 3); System.out.println("Jak często przebywasz w okolicach ulic i samochodów? W skali od 0 (raz na miesiąc lub mniej) do 10 (pracuję jeżdżąc samochodem 8+ h dziennie) "); byte autaPoziom = dajStresPoziom(); int kiedyWyp = 0; ileRazTrue = 0; for (int i = 0; i <= autaPoziom; i++) { Random losZawal = new Random(); int losLiczba = losZawal.nextInt(100); if (losLiczba > 90){ ileRazTrue++; kiedyWyp = 85; } } kiedyWyp = kiedyZaw - (ileRazTrue * 5); wynikSkr = wynikSkr + (int)(ileRazTrue * 4 / 5); return new int[] {wynikSkr, kiedyZaw, kiedyWyp}; } private static byte dajStresPoziom() { Scanner wpisz = new Scanner(System.in); while ( !wpisz.hasNextByte(10) ){ wpisz.next(); } byte wynik = wpisz.nextByte(); return wynik; } private static int dajIlePetow() { Scanner wpisz = new Scanner(System.in); while ( !wpisz.hasNextInt() ){ wpisz.next(); } int wynik = wpisz.nextInt(); if ( wynik < 0 ){ return 0; }else if ( wynik > 100){ return 100; }else { return wynik; } } private static char ustawPlec( char plec ) { if (plec == 'k' || plec == 'm'){ return plec; }else { return 'n'; } } private static char dajChar() { Scanner wpisz = new Scanner(System.in); return wpisz.next().charAt(0); } private static void zad5Start() { System.out.println("Obliczę twój wiek na podstawie daty urodzin. "); LocalDate urodziny = dajDate(); LocalDateTime urod = LocalDateTime.of(urodziny.getYear(), urodziny.getMonth(), urodziny.getDayOfMonth(), 0, 0); Period ileLat = Period.between( urodziny, LocalDate.now() ); System.out.println("Masz " + ileLat.getYears() + " lat, " + ileLat.getMonths() + " miesięcy i " + ileLat.getDays() + " dni"); Duration ileSek = Duration.between(urod, LocalDateTime.now() ); System.out.println("Urodziłeś się " + ileSek.getSeconds() + " sekund temu. " ); } private static void zad4Start() { System.out.println("Podam różnicę między dwoma datami: "); LocalDate dataPocz = dajDate(); dataPocz.format( DateTimeFormatter.ofPattern("yyyy::MM::dd") ); System.out.println(dataPocz); LocalDate dataKoniec = dajDate(); dataKoniec.format( DateTimeFormatter.ofPattern("MM::yyyy::dd") ); System.out.println(dataKoniec); Period roznica = Period.between(dataPocz, dataKoniec); System.out.println("Minęło pomiędzy nimi: " + roznica.getYears() + " lat, " + roznica.getMonths() + " miesięcy, " + roznica.getDays() + " dni"); } private static void zad3Start() { System.out.println("Wyświetlam różnicę dwóch dat."); System.out.println("Wpisz datę rozpoczęcia: "); LocalDate dataPoczatek = dajDate(); System.out.println("Wpisz datę zakończenia: "); LocalDate dataKoniec = dajDate(); Period okresRoznicy = Period.between( dataPoczatek, dataKoniec ); System.out.println( "Okres pomiędzy nimi to: " + okresRoznicy.getYears() + " lat " + okresRoznicy.getMonths() + " mies " + okresRoznicy.getDays() + " dni"); System.out.println(okresRoznicy); } private static void zad2Start() { System.out.println("Podaj date rozpoczęcia dzialania planu: "); LocalDate dzien0Programu = dajDate(); System.out.println("Czas na ostatnie przygotowania i testy: " + dzien0Programu.plusDays(-10) ); System.out.println("Przewidywane czas kiedy będzie działał bezbłędnie (po poprawieniu błędów) " + dzien0Programu.plusDays(10) ); System.out.println(dzien0Programu.lengthOfYear()); } private static LocalDate dajDate() { Scanner wpisz = new Scanner(System.in); int[] data = new int[3]; System.out.println("Wpisz który rok "); while (!wpisz.hasNextInt() ){ wpisz.next(); } data[2] = wpisz.nextInt(); System.out.println("Wpisz który miesiąc (1 - 12)"); while (!wpisz.hasNextInt() ){ wpisz.next(); } data[1] = wpisz.nextInt(); if (data[1] < 1 || data[1] > 12){ data[1] = 1; } LocalDate rokMiesPod = LocalDate.of(data[2], data[1], 1); System.out.println("Wpisz który dzień miesiąca (1 - 31) "); while (!wpisz.hasNextInt() ){ wpisz.next(); } data[0] = wpisz.nextInt(); if (data[0] < 1 ){ data[0] = 1; }else if ( data[0] > rokMiesPod.lengthOfMonth() ){ data[0] = rokMiesPod.lengthOfMonth() ; } return LocalDate.of(data[2], data[1], data[0]) ; } private static void zad1Start() throws InterruptedException { LocalTime takiCzas = LocalTime.now(); System.out.println(takiCzas); Thread.sleep(2000); LocalTime drugiCzas = LocalTime.now(); System.out.println(drugiCzas); int roznWCzasie = drugiCzas.getSecond() - takiCzas.getSecond(); System.out.print("Różnica w czasie wynosi: " + roznWCzasie + " s"); System.out.println("To były testy teraz pętla od czasów: "); System.out.println("*************************************"); System.out.println("Wpisz date by wypisać date \n time by wypisać obecny czas \n datetime by wypisać oba \n quit by zakończyć."); wypisujCzasDoQuit(); } private static int wypisujCzasDoQuit() { String decyzja = dajTekst(); switch (decyzja){ case "datetime":{ System.out.println(LocalDateTime.now()); break; } case "time":{ System.out.println(LocalTime.now()); break; } case "date":{ System.out.println(LocalDate.now()); break; } case "quit":{ return 0; } } return wypisujCzasDoQuit(); } private static String dajTekst() { Scanner wpisz = new Scanner(System.in); return wpisz.next().toLowerCase().trim(); } }
true
d0f9c49b6f0a92d48ade1f012ad1e0a174c2ccd8
Java
YuryMatskevich/Drools
/deliveryCost/src/main/java/com/gmail/ynmatskevich/calculate/DeliveryCostWithDrools.java
UTF-8
1,911
3.171875
3
[ "Apache-2.0" ]
permissive
package com.gmail.ynmatskevich.calculate; import org.drools.compiler.kie.builder.impl.KieServicesImpl; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; /** * The class cost the price for current weight and distance * using drools */ public class DeliveryCostWithDrools implements Calculator { private double weight; private double distance; private double price; /** * Constructor for creating a {@link DeliveryCostWithDrools} * * @param weight weight of a goods * @param distance the distance to which the goods will be delivered */ public DeliveryCostWithDrools(double weight, double distance) { isValid(weight); isValid(distance); this.weight = weight; this.distance = distance; } public double getWeight() { return weight; } public void setPrice(double price) { this.price = price; } @Override public double doDeliveryCost() { choicePrice(this); return weight * distance * price; } /** * Get a price of delivering which is depend on weight via drools * and set it to a price field */ private void choicePrice(DeliveryCostWithDrools deliveryCostWithDrools) { KieServices ks = KieServicesImpl.Factory.get(); KieContainer kc = ks.getKieClasspathContainer(); KieSession kieSession = kc.newKieSession("ksession-rules"); kieSession.insert(deliveryCostWithDrools); kieSession.fireAllRules(); } /** * Check if the value is valid * * @param value a value is being checked */ private void isValid(double value) { if (value <= 0) { throw new IllegalArgumentException( String.format("The value can not be negative: value = %s", value) ); } } }
true
240d6089232e9b930d44a2804f3d4851c1008ab3
Java
swapnanildutta/WoSafe
/Files/src/main/java/com/saif/wosafe/settings/WebViewActivity.java
UTF-8
691
2.015625
2
[ "MIT" ]
permissive
package com.saif.wosafe.settings; import android.content.Intent; import android.os.Bundle; import android.webkit.WebView; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.saif.wosafe.R; public class WebViewActivity extends AppCompatActivity { WebView webView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_webview); webView = findViewById(R.id.WebView); webView.getSettings().setJavaScriptEnabled(true); String url = getIntent().getStringExtra("url"); webView.loadUrl(url); } }
true
18900182898ee744c549791bb94413e0d4d2948a
Java
HZKun/algorithm-datastruct
/src/main/java/vip/qmwk/leetcode/sort/SelectSort.java
UTF-8
1,003
4
4
[]
no_license
package vip.qmwk.leetcode.sort; import java.util.Arrays; /** * 选择排序 * * 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。 * * */ public class SelectSort implements Sort{ @Override public void sort(int[] arr) { for (int i = 0; i < arr.length; i++) { for (int j = i; j < arr.length; j++) { if (arr[i] > arr[j]) { int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } } public static void main(String[] args) { int[] arr = {1,3,6,2,4,5,3,2,4,2,3,2,1}; Sort selectSort = new SelectSort(); selectSort.sort(arr); System.out.println(Arrays.toString(arr)); } }
true
e2690c0ee0f8fe85c650736e0ec22d24e3d1e05e
Java
kluxa/dungeon-raider
/src/dungeon/Path.java
UTF-8
258
2.03125
2
[]
no_license
package dungeon; import enemies.*; import dungeon.*; import player.*; import items.*; import game.*; public class Path extends Tile { @Override public char toChar() { return ' '; } @Override public String getImageName() { return "path"; } }
true
df846270a88c9f46beec4320247fab5ef32f54bb
Java
okaxel/udacitypopularmovies
/app/src/main/java/hu/drorszagkriszaxel/popularmovies/MovieFromInternet.java
UTF-8
5,395
2.734375
3
[ "MIT" ]
permissive
package hu.drorszagkriszaxel.popularmovies; import android.os.AsyncTask; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by Axel Ország-Krisz Dr. */ public class MovieFromInternet extends AsyncTask<String,Void,Movie[]> { // Variables to store constructor's parameters private GenericMovieListener mListener; private String mApiPath; private String[] mNoHardStriings; /** * Simple constructor * * @param listener Holds the activity's listener instance * @param ApiPath Access path of TheMovieDb API, this way no sort order is needed * @param noHardStriings To avoid any hard-coded string, the needed strings are sent this way */ MovieFromInternet(GenericMovieListener listener, String ApiPath, String[] noHardStriings) { mListener = listener; mApiPath = ApiPath; mNoHardStriings = noHardStriings; } /** * Constructs the Movie array for the GridView's PosterAdapter. * * Some if varibale != null added to avoid NullPointerExceptions. * * @param strings Required but not used * @return Movie array for the GridView PosterAdapter on null in case of failure */ @Override protected Movie[] doInBackground(String... strings) { // Initializing variables forward to catch exceptions and handle scope at the same time. URL apiUrl = null; String jsonString = null; try { apiUrl = new URL(mApiPath); } catch (MalformedURLException e) { Log.e(mNoHardStriings[0],e.getLocalizedMessage()); } if (apiUrl != null) { // Some other catch and scope related initialization here. HttpURLConnection connection = null; BufferedReader reader = null; try { connection = (HttpURLConnection) apiUrl.openConnection(); connection.setRequestMethod(mNoHardStriings[1]); connection.connect(); InputStream inputStream = connection.getInputStream(); if (inputStream != null) { reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String oneLine; while ((oneLine = reader.readLine()) != null) { stringBuilder.append(oneLine) .append("\n"); } if (stringBuilder.length() > 0) { jsonString = stringBuilder.toString(); } } } catch (IOException e) { Log.e(mNoHardStriings[0],e.getLocalizedMessage()); } finally { if (connection != null) connection.disconnect(); if (reader != null) { try { reader.close(); } catch (IOException e) { Log.e(mNoHardStriings[0],e.getLocalizedMessage()); } } } } if (jsonString != null) { try { return jsonToMovies(jsonString); } catch (JSONException e) { Log.e(mNoHardStriings[0],e.getLocalizedMessage(),e); e.printStackTrace(); } } return null; // This return point isn't the best place at all. } /** * Loads the EventListener from MainActivity to handle the result in the main thread. * * @param movies The generated array of movies to create adapter */ @Override protected void onPostExecute(Movie[] movies) { super.onPostExecute(movies); mListener.GenericEventListener(movies); } /** * Converts the JSON string into movies object. * * @param json JSON string of TheMovieDb API * @return Array of Movie objects * @throws JSONException In case of error it trows an exception */ private Movie[] jsonToMovies(String json) throws JSONException { JSONObject moviesObject = new JSONObject(json); JSONArray moviesArray = moviesObject.getJSONArray(mNoHardStriings[2]); Movie[] movies = new Movie[moviesArray.length()]; for (int i=0; i<moviesArray.length(); i++) { movies[i] = new Movie(); JSONObject oneMovie = moviesArray.getJSONObject(i); movies[i].setId(oneMovie.getInt(mNoHardStriings[3])); movies[i].setVoteAverage(oneMovie.getDouble(mNoHardStriings[4])); movies[i].setTitle(oneMovie.getString(mNoHardStriings[5])); movies[i].setPosterPath(oneMovie.getString(mNoHardStriings[6])); movies[i].setOriginalTitle(oneMovie.getString(mNoHardStriings[7])); movies[i].setOverview(oneMovie.getString(mNoHardStriings[8])); movies[i].setReleaseDate(oneMovie.getString(mNoHardStriings[9])); movies[i].setPopularity(oneMovie.getDouble(mNoHardStriings[10])); } return movies; } }
true
67576100f0c8e90a85008d801bdca3f71ca05f8b
Java
zibul444/JavaRush
/JavaRushHomeWork/src/com/javarush/test/level06/lesson05/task04/abcPoint.java
UTF-8
365
2.921875
3
[]
no_license
package com.javarush.test.level06.lesson05.task04; /** * Created by Михаил Алексеевич on 17.12.2015. */ public class abcPoint { abcPoint(int a, int b) { x = a; y = b; } int x, y; public static void main(String[] args) { abcPoint p = new abcPoint(5,3), p1; p1 = p; p = null; System.out.println(p.x); } }
true
5c8b3dd9f78f66476c5699006887762211ff11ce
Java
Mungrel/krescendos-android
/app/src/main/java/com/krescendos/input/LikeButtonClickListener.java
UTF-8
1,900
2.28125
2
[]
no_license
package com.krescendos.input; import android.view.View; import android.widget.ImageButton; import com.krescendos.R; import com.krescendos.firebase.FirebaseManager; import com.krescendos.model.Track; import com.krescendos.model.VoteDirection; import com.krescendos.model.VoteItem; public class LikeButtonClickListener implements View.OnClickListener { private ImageButton likeButton; private ImageButton dislikeButton; private String partyId; private VoteItem<Track> item; public LikeButtonClickListener(ImageButton likeButton, ImageButton dislikeButton, String partyId, VoteItem<Track> item) { this.likeButton = likeButton; this.dislikeButton = dislikeButton; this.likeButton.setTag("off"); this.dislikeButton.setTag("off"); this.partyId = partyId; this.item = item; } @Override public void onClick(View view) { boolean dislikeWasActive = dislikeButton.getTag().equals("on"); toggleState(); boolean off = likeButton.getTag().equals("off"); VoteDirection direction = (off) ? VoteDirection.DOWN : VoteDirection.UP; FirebaseManager.vote(partyId, item.getItemId(), direction, dislikeWasActive); updateImage(); } private void updateImage() { boolean off = likeButton.getTag().equals("off"); if (off) { likeButton.setImageResource(R.drawable.like_off); } else { likeButton.setImageResource(R.drawable.like_on); dislikeButton.setImageResource(R.drawable.dislike_off); } } private void toggleState() { boolean off = likeButton.getTag().equals("off"); if (off) { likeButton.setTag("on"); dislikeButton.setTag("off"); } else { likeButton.setTag("off"); } } }
true
53ed137658e4d08ceee9e14fcb27719a1d665c3e
Java
mcrose/icarusdb-commons
/src/main/java/py/org/icarusdb/commons/util/BundleHelper.java
UTF-8
2,350
2.390625
2
[]
no_license
/** * Copyright 2014 Roberto Gamarra [icarus] ** ( Betto McRose ) * mcrose@icarusdb.com.py | mcrose.dev@gmail.com * * as you wish... at your service ;-P * * IcarusDB.com.py * * 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 py.org.icarusdb.commons.util; import java.util.Locale; import java.util.ResourceBundle; /** * @author Betto McRose [icarus] * mcrose@icarusdb.com.py * mcrose.dev@gmail.com * */ public class BundleHelper { /** * <p> * default message bundle in IcarusDB's common-lib jar<br> * "py.com.icarusdb.messages.CommonMessages"<br> * </p> * @param key * @return message */ public static String getBundleMessage(String key) { return getBundleMessage("py.com.icarusdb.common.CommonMessages", key); } public static String getBundleMessage(String bundleName, String key) { return getBundleMessage(bundleName, key, Locale.getDefault()); } /** * returns the requested <b>key</b> message with the given <b>bundleName</b> * * @param bundleName * @param key * @param locale * @return message */ public static String getBundleMessage(String bundleName, String key, Locale locale) { try { ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale); if(bundle.containsKey(key)) { return bundle.getString(key); } /* * may be is a "common" pre-defined property bundle * look up for it in base common messages */ if(!bundleName.contains("CommonMessages")) { return getBundleMessage(key); } } catch (Exception e) { /*nothing*/ } return null; } }
true
b567f391fd2ae5c91d0c6a86c4c9809beb961278
Java
Huang-W/GoWebServer
/ProjectGo/src/main/java/go/view/datamodel/impl/GoViewImpl.java
UTF-8
8,518
2.25
2
[]
no_license
package go.view.datamodel.impl; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.WindowConstants; import java.util.LinkedList; import java.util.List; import go.view.datamodel.GoMove; import go.view.datamodel.GoView; import go.view.observer.GoScreenObserver; import go.view.observer.GoViewConfigObserver; import go.view.observer.GoViewConfigSubject; import go.view.observer.GoViewObserver; import go.view.observer.GoViewSubject; import go.view.screen.controller.ScreenController; import go.view.screen.controller.impl.ScreenControllerImpl; import go.view.screen.impl.ConfigScreen; import go.view.screen.impl.GameScreen; import go.view.screen.impl.GoScreenImpl; import go.view.screen.impl.WelcomeScreen; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; @SuppressWarnings("serial") public class GoViewImpl extends JFrame implements GoView, GoViewSubject, GoScreenObserver, GoViewConfigSubject { private File audioFile = new File("audio/gostone.wav"); private ConfigScreen configScreen; private GoScreenImpl currentScreen; private GoScreenImpl gameScreen; private GoScreenImpl welcomeScreen; private ScreenController configScreenController; private ScreenController gameScreenController; private ScreenController welcomeScreenController; private final String[] options = {"Close App", "Restart", "Cancel"}; private final int CLOSE_APP = 0; private final int RESTART_APP = 1; private final int CANCEL = 2; private final String PASS = "PASS"; private final String UNDO = "UNDO"; private final String QUICK_START = "QUICK_START"; private final String CONFIG_START = "CONFIG_START"; private final String SET_BOARD_SIZE_NINE = "SET_BOARD_SIZE_NINE"; private final String SET_BOARD_SIZE_THIRTEEN = "SET_BOARD_SIZE_THIRTEEN"; private final String SET_BOARD_SIZE_NINETEEN = "SET_BOARD_SIZE_NINETEEN"; private List<GoViewObserver> viewObservers; private List<GoViewConfigObserver> viewConfigObservers; public GoViewImpl() { viewObservers = new LinkedList<>(); viewConfigObservers = new LinkedList<>(); configScreen = new ConfigScreen(); gameScreen = new GameScreen(); welcomeScreen = new WelcomeScreen(); currentScreen = welcomeScreen; configScreenController = new ScreenControllerImpl(configScreen); gameScreenController = new ScreenControllerImpl(gameScreen); welcomeScreenController = new ScreenControllerImpl(welcomeScreen); configScreenController.getGoScreenSubject().registerGoScreenObserver(this); gameScreenController.getGoScreenSubject().registerGoScreenObserver(this); welcomeScreenController.getGoScreenSubject().registerGoScreenObserver(this); GoViewImpl.this.setBackground(Color.GRAY); GoViewImpl.this.setLayout(new BorderLayout()); GoViewImpl.this.add(gameScreen, BorderLayout.NORTH); GoViewImpl.this.add(welcomeScreen, BorderLayout.SOUTH); GoViewImpl.this.add(configScreen, BorderLayout.EAST); GoViewImpl.this.setResizable(false); GoViewImpl.this.setLocationByPlatform(true); showWelcomeScreen(); GoViewImpl.this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); GoViewImpl.this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (welcomeScreen.equals(currentScreen) == false) { int chosenOption = JOptionPane.showOptionDialog(GoViewImpl.this, "Would you like to close the app or start a new game?", "Confirm Close", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[CLOSE_APP]); if (chosenOption == RESTART_APP) { GoViewImpl.this.notifyObserversOfWindowCloseEvent(); showWelcomeScreen(); return; } else if (chosenOption == CANCEL) { return; } } GoViewImpl.this.setVisible(false); GoViewImpl.this.dispose(); } }); } @Override public void handleActionEvent(ActionEvent event) { switch(event.getActionCommand()) { case QUICK_START: if (ConfigScreen.BOARD_SIZE() != 9) notifyObserversOfScreenSizeConfigEvent(9); showGameScreen(); break; case PASS: notifyObserversOfPassTurnRequest(); break; case UNDO: notifyObserversOfUndoMoveRequest(); break; case CONFIG_START: showConfigScreen(); break; case SET_BOARD_SIZE_NINE: notifyObserversOfScreenSizeConfigEvent(9); showGameScreen(); break; case SET_BOARD_SIZE_THIRTEEN: notifyObserversOfScreenSizeConfigEvent(13); showGameScreen(); break; case SET_BOARD_SIZE_NINETEEN: notifyObserversOfScreenSizeConfigEvent(19); showGameScreen(); default: System.out.println("I dont how know to throw the exceptions"); } } @Override public void handleMouseEvent(MouseEvent event) { Point point = new Point(event.getX(), event.getY()); notifyObserversOfMouseClick(point); System.out.println("xCoord: " + event.getX() + " yCoord: " + event.getY()); } @Override public void drawStone(GoMove move) { currentScreen.paintOval(move.getPoint(), move.getStoneColor()); playAudioClip(); } @Override public void drawEmptySpace(Point location) { currentScreen.paintGrid(location); } @Override public void announceGameWinner(Color color) { String winner = color.equals(Color.BLACK) ? "BLACK" : "WHITE"; if (gameScreen.equals(currentScreen)) { int chosenOption = JOptionPane.showOptionDialog(GoViewImpl.this, winner + " Wins!\n" + "Would you like to close the app or start a new game?", winner + " Wins!", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[CLOSE_APP]); if (chosenOption == RESTART_APP) { GoViewImpl.this.notifyObserversOfWindowCloseEvent(); showWelcomeScreen(); return; } else if (chosenOption == CANCEL) { return; } } GoViewImpl.this.setVisible(false); GoViewImpl.this.dispose(); } @Override public void configureBoardSize(int boardSize) { System.out.println("configure board size in goview"); configScreen.setBoardSize(boardSize); } private void showGameScreen() { currentScreen = gameScreen; welcomeScreenController.hideScreen(); configScreenController.hideScreen(); gameScreenController.showScreen(); validate(); pack(); GoViewImpl.this.setVisible(true); } private void showWelcomeScreen() { currentScreen = welcomeScreen; configScreenController.hideScreen(); gameScreenController.hideScreen(); welcomeScreenController.showScreen(); validate(); pack(); GoViewImpl.this.setVisible(true); } private void showConfigScreen() { currentScreen = configScreen; gameScreenController.hideScreen(); welcomeScreenController.hideScreen(); configScreenController.showScreen(); validate(); pack(); GoViewImpl.this.setVisible(true); } private void playAudioClip() { try { Clip audioClip = AudioSystem.getClip(); AudioInputStream ais = AudioSystem.getAudioInputStream(audioFile); audioClip.open(ais); audioClip.start(); audioClip.wait(150); audioClip.stop(); audioClip.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void notifyObserversOfMouseClick(Point point) { viewObservers.forEach(observer -> observer.handleMouseClickEvent(point)); } @Override public void notifyObserversOfPassTurnRequest() { viewObservers.forEach(observer -> observer.handlePassTurnRequest()); } @Override public void notifyObserversOfUndoMoveRequest() { viewObservers.forEach(observer -> observer.handleUndoMoveRequest()); } @Override public void notifyObserversOfWindowCloseEvent() { viewObservers.forEach(observer -> observer.handleWindowClose()); } @Override public void notifyObserversOfScreenSizeConfigEvent(int boardSize) { viewConfigObservers.forEach(observer -> observer.handleBoardSizeConfigure(boardSize)); } @Override public void addViewObserver(GoViewObserver observer) { viewObservers.add(observer); } @Override public void addViewConfigObserver(GoViewConfigObserver observer) { viewConfigObservers.add(observer); } }
true
f9ea1ed7e2b9ae575b0773a2b8afbfd2b94eef62
Java
lisycn/wepaysp
/wepaysp-parent/wepaysp_web/src/main/java/com/zbsp/wepaysp/manage/web/util/SysUserUtil.java
UTF-8
3,900
2.265625
2
[]
no_license
package com.zbsp.wepaysp.manage.web.util; import com.zbsp.wepaysp.manage.web.security.ManageUser; import com.zbsp.wepaysp.po.manage.SysUser; public class SysUserUtil { /** * 是否是顶级服务商 * * @return */ public static boolean isTopPartner(ManageUser manageUser) { int level = 0; if (manageUser.getUserLevel() == null) { return false; } else { level = manageUser.getUserLevel(); if (level == SysUser.UserLevel.partner.getValue() && manageUser.getDataPartner() != null && manageUser.getDataPartner().getLevel() == 1) {// 顶级服务商 return true; } } return false; } /** * 是否是代理商(含顶级代理商) * * @return */ public static boolean isPartner(ManageUser manageUser) { int level = 0; if (manageUser.getUserLevel() == null) { return false; } else { level = manageUser.getUserLevel(); if (level != SysUser.UserLevel.partner.getValue() || manageUser.getDataPartner() == null) { return false; } } return true; } /** * 是否是业务员 * * @return */ public static boolean isPartnerEmployee(ManageUser manageUser) { int level = 0; if (manageUser.getUserLevel() == null) { return false; } else { level = manageUser.getUserLevel(); if (level != SysUser.UserLevel.salesman.getValue() || manageUser.getDataPartnerEmployee() == null) { return false; } } return true; } /** * 是否是商户 * * @return */ public static boolean isDealer(ManageUser manageUser) { int level = 0; if (manageUser.getUserLevel() == null) { return false; } else { level = manageUser.getUserLevel(); if (level != SysUser.UserLevel.dealer.getValue() || manageUser.getDataDealer() == null) { return false; } } return true; } /** * 是否是收银员(含店长) * * @return */ public static boolean isDealerEmployee(ManageUser manageUser) { int level = 0; if (manageUser.getUserLevel() == null) { return false; } else { level = manageUser.getUserLevel(); if ((level != SysUser.UserLevel.cashier.getValue() && level != SysUser.UserLevel.shopManager.getValue()) || manageUser.getDataDealerEmployee() == null) { return false; } } return true; } /** * 是否是店长 * * @return */ public static boolean isStoreManager(ManageUser manageUser) { int level = 0; if (manageUser.getUserLevel() == null) { return false; } else { level = manageUser.getUserLevel(); if (level != SysUser.UserLevel.shopManager.getValue() || manageUser.getDataDealerEmployee() == null || manageUser.getDataDealerEmployee().getStore() == null) { return false; } } return true; } /** * 是否是学校 * * @return */ public static boolean isSchool(ManageUser manageUser) { int level = 0; if (manageUser.getUserLevel() == null) { return false; } else { level = manageUser.getUserLevel(); if (level != SysUser.UserLevel.school.getValue() || manageUser.getDataSchool() == null) { return false; } } return true; } }
true
9758b86939179585838b110d1c11010519fc292b
Java
rogue-three/GymChampion_API
/src/main/java/com/gymchampion/GymChampion/model/SetScheme.java
UTF-8
1,367
2.53125
3
[]
no_license
package com.gymchampion.GymChampion.model; import javax.persistence.*; @Entity @Table(name = "set_scheme") public class SetScheme { @Id @Column(name = "set_scheme_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int setSchemeId; @Column(name = "reps", nullable = false) private int reps; @Column(name = "weight", nullable = false) private double weight; @ManyToOne @JoinColumn(name = "training_id") private Training training; @ManyToOne @JoinColumn(name = "exercise_id") private Exercise exercise; public SetScheme() {} public SetScheme(int reps, int weight) { this.reps = reps; this.weight = weight; } public int getSetSchemeId() { return this.setSchemeId; } public void setSetSchemeId(int setSchemeId) { this.setSchemeId = setSchemeId; } public int getReps() { return this.reps; } public void setReps(int reps) { this.reps = reps; } public double getWeight() { return this.weight; } public void setWeight(double weight) { this.weight = weight; } public Training getTraining() { return this.training; } public void setTraining(Training training) { this.training = training; } public Exercise getExercise() { return this.exercise; } public void setExercise(Exercise exercise) { this.exercise = exercise; } }
true
fb130be21fb6434c472653d3e1f857921ab0abce
Java
bellmit/core-4
/modules/components/component-mail/src/main/java/org/ow2/easybeans/component/mail/factory/AbsJavaMailFactory.java
UTF-8
4,621
2.25
2
[]
no_license
/** * EasyBeans * Copyright (C) 2007 Bull S.A.S. * Contact: easybeans@ow2.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * -------------------------------------------------------------------------- * $Id: AbsJavaMailFactory.java 5650 2010-11-04 14:50:58Z benoitf $ * -------------------------------------------------------------------------- */ package org.ow2.easybeans.component.mail.factory; import java.io.IOException; import java.util.Properties; import javax.mail.Authenticator; import javax.naming.NamingException; import javax.naming.RefAddr; import javax.naming.Reference; import javax.naming.StringRefAddr; import javax.naming.spi.ObjectFactory; import org.ow2.util.marshalling.Serialization; /** * Abstract JNDI factory for Mail factories. * @author Florent BENOIT */ public abstract class AbsJavaMailFactory implements ObjectFactory { /** * User name for authentication. */ public static final String AUTHENTICATION_USERNAME = "auth.name"; /** * Password for authentication. */ public static final String AUTHENTICATION_PASSWORD = "auth.pass"; /** * Properties used for mail factory. */ public static final String MAIL_PROPERTIES = "mail.properties"; /** * Gets an authenticator for the given reference. * @param reference the given reference * @return an authenticator or null if there is none. */ protected Authenticator getAuthenticator(final Reference reference) { // Get auth name String authName = getString(reference, AUTHENTICATION_USERNAME); // Get auth password String authPass = getString(reference, AUTHENTICATION_PASSWORD); // Build an authenticator if the properties have been set. SimpleAuthenticator authenticator = null; if (authName != null && authPass != null) { authenticator = new SimpleAuthenticator(authName, authPass); } return authenticator; } /** * Gets the session properties. * @param reference the given reference * @return session properties * @throws NamingException if object is not read. */ public Properties getSessionProperties(final Reference reference) throws NamingException { return getObject(reference, MAIL_PROPERTIES); } /** * Get the given string from the reference. * @param reference the given reference * @param propertyName the given property * @return the given string */ public String getString(final Reference reference, final String propertyName) { RefAddr tmpRefAddr = reference.get(propertyName); String tmpValue = null; if (tmpRefAddr instanceof StringRefAddr) { tmpValue = (String) ((StringRefAddr) tmpRefAddr).getContent(); } return tmpValue; } /** * Load a given object for the given property name. * @param reference the given reference * @param propertyName the given property * @return the loaded object * @throws NamingException if object is not read. * @param <T> the type of the object to load */ @SuppressWarnings("unchecked") public <T> T getObject(final Reference reference, final String propertyName) throws NamingException { RefAddr refAddr = reference.get(propertyName); T obj = null; if (refAddr != null) { try { obj = (T) Serialization.loadObject((byte[]) refAddr.getContent()); } catch (IOException e) { NamingException ne = new NamingException("Cannot load mail session properties object"); ne.initCause(e); throw ne; } catch (ClassNotFoundException e) { NamingException ne = new NamingException("Cannot load mail session properties object"); ne.initCause(e); throw ne; } } return obj; } }
true
6e4485d4641f41097f16b4e0daf09eb9d85af1ee
Java
kimminkyeng/CodingStudy
/0814_database/src/T1_Dbconnection/DbConnRun.java
UTF-8
215
1.898438
2
[]
no_license
package T1_Dbconnection; public class DbConnRun { public static void main(String[] args) { DbConnection conn = new DbConnection(); //DbConnection 클래스의 결과 : 드라이버 검색완료. } }
true
e0a50312e7f06b7e9514b6ba5b91fdb737ab8024
Java
cozos/emrfs-hadoop
/com/amazon/ws/emr/hadoop/fs/shaded/com/amazonaws/metrics/ServiceLatencyProvider.java
UTF-8
1,679
1.9375
2
[]
no_license
package com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.metrics; import com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.annotation.NotThreadSafe; import com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.util.TimingInfo; import com.amazon.ws.emr.hadoop.fs.shaded.org.apache.commons.logging.Log; import com.amazon.ws.emr.hadoop.fs.shaded.org.apache.commons.logging.LogFactory; @NotThreadSafe public class ServiceLatencyProvider { private final long startNano = System.nanoTime(); private long endNano = startNano; private final ServiceMetricType serviceMetricType; public ServiceLatencyProvider(ServiceMetricType type) { serviceMetricType = type; } public ServiceMetricType getServiceMetricType() { return serviceMetricType; } public ServiceLatencyProvider endTiming() { if (endNano != startNano) { throw new IllegalStateException(); } endNano = System.nanoTime(); return this; } public double getDurationMilli() { if (endNano == startNano) { LogFactory.getLog(getClass()).debug("Likely to be a missing invocation of endTiming()."); } return TimingInfo.durationMilliOf(startNano, endNano); } public String getProviderId() { return super.toString(); } public String toString() { return String.format("providerId=%s, serviceMetricType=%s, startNano=%d, endNano=%d", new Object[] { getProviderId(), serviceMetricType, Long.valueOf(startNano), Long.valueOf(endNano) }); } } /* Location: * Qualified Name: com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.metrics.ServiceLatencyProvider * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
1353503a3939fb2e9732f4cde164a4f660c50837
Java
danvarga1985/Recipe_App
/src/main/java/daniel/varga/recipeapp/services/UnitOfMeasureService.java
UTF-8
215
1.789063
2
[]
no_license
package daniel.varga.recipeapp.services; import daniel.varga.recipeapp.commands.UnitOfMeasureCommand; import java.util.Set; public interface UnitOfMeasureService { Set<UnitOfMeasureCommand> listAllUoms(); }
true
0f9043c95a7558d37595d47a281e80799ec726d3
Java
fniftaly/dev_demo
/NetBeansProjects/Mvnsrn/src/main/java/com/controller/UserController.java
UTF-8
2,531
2.640625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.controller; import com.google.gson.Gson; import com.model.User; import com.model.UserImpl; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * * @author farad */ @Controller public class UserController { UserImpl usr = new UserImpl(); ArrayList<User> users = new ArrayList(); @RequestMapping(value = "addUser", method = RequestMethod.POST) public @ResponseBody String addUser(@RequestParam(value = "first") String first, @RequestParam(value = "last") String last, @RequestParam(value = "email") String email, @RequestParam(value = "date") String date) { User newuser = new User(first, last, email, date); if (usr.addUser(newuser)) { return "User created!"; } else { return "User is not created"; } } /** * Taking all registers users * from table in this case from * file * gson API used for storing array into json format */ @RequestMapping(value = "getUsers.htm", method = RequestMethod.GET) public @ResponseBody String getUsers() { usr.readfile(); // HashMap<String, User> map = usr.getUser(); // users.clear(); // for (Map.Entry<String, User> entry : map.entrySet()) { // users.add(entry.getValue()); } Gson gson = new Gson(); // String json = gson.toJson(users); // return json; } /** * Delete user from db based on * user email address * * then refresh HasMap for display */ @RequestMapping(value = "deleteUser.htm", method = RequestMethod.POST) public @ResponseBody String deleteUser(@RequestParam(value = "email") String email) { // HashMap<String, User> allusr = usr.getUser(); // if(usr.removeuser(email)){ // usr.readfile(); // return "User has been deleted!"; } // return null; } }
true
81705b2d2d32ac1e4cb1188f42151cda7c62c28b
Java
ConanWu/java-test-e2e
/junit/src/main/java/cn/wl/test/Hello.java
UTF-8
146
1.773438
2
[]
no_license
package cn.wl.test; /** * Created by zjjwu on 2017/3/16. */ public class Hello { public String sayHello(){ return "Hello"; } }
true
0c0040e2b5d3d26bcb8c3642c5b74f632356527c
Java
shuile/ReadingList
/DesignPatterns/HeadFirstDesignPatterns/src/com/shui/headfirstdesignpatterns/chapter6/SimpleRemoteControl.java
UTF-8
356
2.53125
3
[]
no_license
package com.shui.headfirstdesignpatterns.chapter6; /** * @author shui. * @date 2021/7/16. * @time 14:13. */ public class SimpleRemoteControl { Command slot; public SimpleRemoteControl() { } public void setCommand(Command command) { slot = command; } public void buttonWasPressed() { slot.execute(); } }
true
dd3071c95af961f51dcca8330fdc8e984ddbfb19
Java
massfords/we99
/we99-jpa/src/main/java/edu/harvard/we99/services/storage/entities/PlateMetricsEntity.java
UTF-8
2,092
2.1875
2
[ "Apache-2.0" ]
permissive
package edu.harvard.we99.services.storage.entities; import javax.annotation.Generated; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * @author mford */ @Entity public class PlateMetricsEntity { /** * Primary key field is auto generated */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String label; private Double avgPositive; private Double avgNegative; private Double zee; private Double zeePrime; @Generated("generated by IDE") public Long getId() { return id; } @Generated("generated by IDE") public PlateMetricsEntity setId(Long id) { this.id = id; return this; } @Generated("generated by IDE") public String getLabel() { return label; } @Generated("generated by IDE") public PlateMetricsEntity setLabel(String label) { this.label = label; return this; } @Generated("generated by IDE") public Double getAvgPositive() { return avgPositive; } @Generated("generated by IDE") public PlateMetricsEntity setAvgPositive(Double avgPositive) { this.avgPositive = avgPositive; return this; } @Generated("generated by IDE") public Double getAvgNegative() { return avgNegative; } @Generated("generated by IDE") public PlateMetricsEntity setAvgNegative(Double avgNegative) { this.avgNegative = avgNegative; return this; } @Generated("generated by IDE") public Double getZee() { return zee; } @Generated("generated by IDE") public PlateMetricsEntity setZee(Double zee) { this.zee = zee; return this; } @Generated("generated by IDE") public Double getZeePrime() { return zeePrime; } @Generated("generated by IDE") public PlateMetricsEntity setZeePrime(Double zeePrime) { this.zeePrime = zeePrime; return this; } }
true
86febfc7f60f4a664f2997377d8b2cbc8039424e
Java
fdale15/OOP-Servlet-Project
/src/com/forrestdale/utils/ModelLoader.java
UTF-8
1,197
2.640625
3
[]
no_license
package com.forrestdale.utils; /** * Created by forrestdale on 2/16/17. */ import com.forrestdale.Main; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ModelLoader { private String mFilename = ""; private boolean mHeader = false; public ModelLoader(String filename, boolean header) { mFilename = new String(filename); mHeader = header; } protected List<String[]> getRows() { List<String[]> result = new ArrayList<String[]>(); try { Scanner file = new Scanner(Thread.currentThread().getContextClassLoader().getResourceAsStream(mFilename)); // Scanner file = new Scanner(new FileReader(mFilename)); while (file.hasNext()) { if (!mHeader) { result.add(file.nextLine().split(",")); } else { mHeader = false; file.nextLine(); } } } catch (Exception e) { System.out.println("File was not located."); } return result; } }
true
d8713eb1438b2a315f0bbd20b069e5ba785da5fc
Java
jinny-c/jiddProject
/src/main/java/com/jidd/view/controller/JiddUserController.java
UTF-8
9,715
1.8125
2
[]
no_license
package com.jidd.view.controller; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.ResponseBody; import com.jidd.basic.async.IAsyncTaskExecutor; import com.jidd.basic.async.SimpleAsyncTaskExecutor; import com.jidd.basic.common.ServiceProvider; import com.jidd.basic.httpclient.RequestResponseContext; import com.jidd.basic.security.JiddSecureAnno; import com.jidd.basic.utils.JiddStringUtils; import com.jidd.basic.utils.JiddTraceLogUtil; import com.jidd.db.user.service.IJiddMgmtUmgService; import com.jidd.view.base.JiddBaseController; import com.jidd.view.controller.dto.UserBaseDto; import com.jidd.view.controller.dto.UserLoginDto; import com.jidd.view.exception.JiddControllerException; import com.jidd.view.exception.JiddGlobalValidException; import com.jidd.view.wechat.service.IJiddPubNumTokenCacheService; /** * * @history */ @Controller @RequestMapping("/user") public class JiddUserController extends JiddBaseController { /* Slf4j */ private static Logger log = LoggerFactory.getLogger(JiddUserController.class); @Autowired private IJiddMgmtUmgService jiddMgmtUmgService; // SpringContextListener中初始化公众号别名,在生成推广码时使用别名 public static Map<String, String> pubMap = new HashMap<String, String>(); /** 异步线程 **/ private IAsyncTaskExecutor asyncTaskExecutor = new SimpleAsyncTaskExecutor(); // 验证码字符个数 private static final int CODE_COUNT = 4; private static final char[] CODE_SEQUENCE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST}) public String index() throws JiddControllerException{ log.info("index enter"); //清除Session //getSession().removeAttribute(""); //getSession().setAttribute(PAYMENT_TOKEN, scanReq.getToken()); IJiddPubNumTokenCacheService jiddTokeCache = ServiceProvider.getService("jiddPubNumTokenCacheService"); if (null == jiddTokeCache) { log.error("该服务[jiddPubNumTokenCacheService]未注册,请检查配置"); throw new JiddControllerException("error","服务未注册"); } //jiddTokeCache.getAccessToken("pubNo", "appId"); log.info("accToken={}",jiddTokeCache.getAccessToken("pubNo", "appId")); if (null != jiddTokeCache) { log.info("jidd test"); //return toRequestForward("/user/tips.htm"); } return toRedirect("/user/info.htm"); } @RequestMapping(value = "/toLogin", method = {RequestMethod.GET, RequestMethod.POST}) public String toLogin() throws JiddControllerException{ log.info("toLogin enter"); //getSession().removeAttribute(""); //getSession().setAttribute(PAYMENT_TOKEN, scanReq.getToken()); int res = jiddMgmtUmgService.queryCount(); log.info("res={}",res); return toUserHtml("login"); } @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST}) public String login(@JiddSecureAnno UserLoginDto reqDto) throws JiddControllerException{ log.info("login enter,reqDto:{}", reqDto); if(JiddStringUtils.isNotBlank(reqDto.getMobile())){ reqDto.getChannel().equals(reqDto.getMobile()); } if(JiddStringUtils.isBlank(reqDto.getAction())){ throw new JiddControllerException("error","登录出错了"); } return toUserHtml("tips"); } @RequestMapping(value = "/info", method = {RequestMethod.GET, RequestMethod.POST}) public String info(Model model, UserBaseDto reqDto) { log.info("info enter"); if(JiddStringUtils.isBlank(reqDto.getMobile())){ //reqDto.getChannel().equals(reqDto.getMobile()); reqDto.getMobile().equals(reqDto.getChannel()); } model.addAttribute("message", "hello word!"); return toUserHtml("tips"); } @RequestMapping(value = "/toSuccess", method = {RequestMethod.GET, RequestMethod.POST}) public String toSuccess(Model model) { log.info("info enter"); HttpServletRequest request = RequestResponseContext.getRequest(); String flag = request.getParameter("flag"); log.info("toSuccess,flag={}", flag); flag ="02"; model.addAttribute("flag", flag); return toUserHtml("res_success"); } @RequestMapping(value = "/userInfo", method = {RequestMethod.GET, RequestMethod.POST}) public String userInfo(Model model) { log.info("userInfo enter"); return toUserHtml("userInfo"); } /** * 通配符入口 * @param model * @param wildcard * @return * @throws JiddControllerException */ @RequestMapping(value = "/publicEntrance{wildcard}", method = {RequestMethod.GET, RequestMethod.POST}) //@ResponseBody public Object publicEntrance(Model model, @PathVariable String wildcard) throws JiddControllerException { log.info("interaction enter,wildcard=[{}]",wildcard); if("_1".equals(wildcard)){ log.info("userInfo start"); return toRequestForward("/user/userInfo.htm"); } if("_2".equals(wildcard)){ log.info("toSuccess start"); return toRedirect("/user/toSuccess.htm"); } log.info("toSucc start"); return toSucc(); } /** * 手机验证码 * @return */ @RequestMapping(value = "/getMobileVerifiCode", method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String getMobileVerifiCode(UserLoginDto reqDto){ try { log.info("getMobileVerifiCode start,reqDto={}", reqDto); SecureRandom random = new SecureRandom(); StringBuilder randomCode = new StringBuilder(); for (int i = 0; i < CODE_COUNT; i++) { String strRand = String.valueOf(CODE_SEQUENCE[random.nextInt(CODE_SEQUENCE.length)]); randomCode.append(strRand); } log.info("success,verifyCode=" + randomCode.toString()); return randomCode.toString(); } catch (Exception e) { log.info("getMobileVerifiCode exception:{}", e); return "error"; } } /** * 图形验证码 * @return */ @RequestMapping(value = "/getVerifiCode", method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String getVerifiCode(){ try { log.info("TraceID:{}, getVerifiCode start:", JiddTraceLogUtil.getTraceId()); SecureRandom random = new SecureRandom(); StringBuilder randomCode = new StringBuilder(); for (int i = 0; i < CODE_COUNT; i++) { String strRand = String.valueOf(CODE_SEQUENCE[random.nextInt(CODE_SEQUENCE.length)]); randomCode.append(strRand); } List<Future<String>> results = new ArrayList<Future<String>>(); final String rCode = randomCode.toString(); initThreadPool(); int count = 1; do { this.executorService.execute(new Runnable() { @Override public void run() { asyncSendVerifiCode(rCode); } }); results.add(executorService.submit(new ImportDataProcessor( rCode))); count++; } while (count < 3); log.info("success,verifyCode=" + randomCode.toString()); String st = null; for (Future<String> result : results) { try { st = result.get(); log.info("st={}",st); } catch (Exception e) { log.error("exception",e); } } return randomCode.toString(); } catch (Exception e) { log.info("getVerifiCode exception:{}", e); return "error"; } } /** * 异步线程 * */ private void asyncSendVerifiCode(final String code) { try { asyncTaskExecutor.exeWithoutResult(new IAsyncTaskExecutor.AsyncTaskCallBack<Object>() { @Override public Object invork() throws JiddGlobalValidException { try { log.info("asynchronous start,code={}",code); } catch (Exception e) { log.error("asynchronous exception", e); } return null; } }); } catch (Exception e) { log.error("do asynchronous exception",e); } } // 任务执行器 private ExecutorService executorService; // 5线程执行 private void initThreadPool() { if (executorService == null) { executorService = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.DiscardPolicy()); } } /** * 线程执行的类 * */ private class ImportDataProcessor implements Callable<String> { private String value; public ImportDataProcessor(String value) { this.value = value; } @Override public String call() throws Exception { try { log.info("ImportDataProcessor,code={}",value); return JiddStringUtils.join(value,"123"); } catch (Exception e) { log.error("query userBean exception:",e); } return null; } } }
true
72d188efa093716002118e8ca8f68c104789a9c2
Java
erankitarora/erankitarora.github.io
/projects/StudentInformationSystem/src/org/iiitb/sis/admin/news/service/SearchCourseByFacultyService.java
UTF-8
424
2.0625
2
[]
no_license
package org.iiitb.sis.admin.news.service; import org.iiitb.sis.admin.news.model.SearchCourseByFacultyModel; public class SearchCourseByFacultyService { public String search(SearchCourseByFacultyModel result) { String getMesaage = result.getCourseID(); System.out.println("hello"); if(getMesaage.equals("Success")) { System.out.println(getMesaage); return "Success"; } else return "Failure"; } }
true
36ad9e39e7c0ab622c57a71deda2908fbecc1dcc
Java
dzungvu/Reup_JZU_NEWS
/JzuNews/app/src/main/java/com/software/dzungvu/jzunews/BussinessPage.java
UTF-8
9,236
1.6875
2
[]
no_license
package com.software.dzungvu.jzunews; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Toast; import com.software.dzungvu.adapter.ElementsAdapter; import com.software.dzungvu.adapter.ElementsGridAdapter; import com.software.dzungvu.configuration.Configuration; import com.software.dzungvu.model.NewsElements; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; public class BussinessPage extends AppCompatActivity { ProgressDialog progressDialog; private ListView lvNews; private GridView gvNews; private NewsElements elements; private ArrayList<NewsElements> newsElementsArrayList; private ElementsAdapter elementsAdapter; private ElementsGridAdapter elementsGridAdapter; private LinearLayout llNews; private Toolbar toolbar; public static InputStream getInputStream(URL url) { try { return url.openConnection().getInputStream(); } catch (IOException e) { e.printStackTrace(); return null; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_news_page); this.setTitle("Business Page"); addControls(); addEvents(); } private void addControls() { lvNews = findViewById(R.id.lvNews); gvNews = findViewById(R.id.gvNews); llNews = findViewById(R.id.llNews); newsElementsArrayList = new ArrayList<>(); progressDialog = new ProgressDialog(this); toolbar = findViewById(R.id.newsToolBar); setSupportActionBar(toolbar); String link = Configuration.RSS_LINK + Configuration.BUSSINESS_LINK; if (haveNetworkConnection()) { GetRssFile task = new GetRssFile(); task.execute(link); } else { Toast.makeText(this, "No internet", Toast.LENGTH_LONG).show(); } lvNews.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(BussinessPage.this, WebViewContent.class); intent.putExtra("URLNEWS", newsElementsArrayList.get(position).getLink()); startActivity(intent); } }); lvNews.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Bundle bundle = new Bundle(); bundle.putString("LINK", newsElementsArrayList.get(position).getLink()); bundle.putString("DESCRIPTION", newsElementsArrayList.get(position).getDescription()); bundle.putString("PUBDATE", newsElementsArrayList.get(position).getPubDate()); bundle.putString("TITLE", newsElementsArrayList.get(position).getTitle()); bundle.putString("GUID", newsElementsArrayList.get(position).getGuid()); Intent intent = new Intent(BussinessPage.this, PopupActivity.class); intent.putExtras(bundle); startActivity(intent); return true; } }); } private void addEvents() { } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.list_news_menu_action_bar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.mnuBack: this.finish(); return true; case R.id.mnu_news_grid_view: Toast.makeText(this, "Grid view", Toast.LENGTH_LONG).show(); lvNews.setVisibility(View.GONE); gvNews.setVisibility(View.VISIBLE); return true; case R.id.mnu_news_list_view: Toast.makeText(this, "List view", Toast.LENGTH_LONG).show(); lvNews.setVisibility(View.VISIBLE); gvNews.setVisibility(View.GONE); return true; default: return onOptionsItemSelected(item); } } private boolean haveNetworkConnection() { boolean haveWifiConnection = false; boolean haveMobileConnection = false; ConnectivityManager cm = (ConnectivityManager) BussinessPage.this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] netInfo = cm.getAllNetworkInfo(); for (NetworkInfo ni : netInfo) { if (ni.getTypeName().equalsIgnoreCase("WIFI")) haveWifiConnection = ni.isConnected(); if (ni.getTypeName().equalsIgnoreCase("MOBILE")) haveMobileConnection = ni.isConnected(); } return haveMobileConnection || haveWifiConnection; } @SuppressLint("StaticFieldLeak") public class GetRssFile extends AsyncTask<String, Void, ArrayList<NewsElements>> { @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.setTitle("Loading data"); progressDialog.setMessage("Please wait!"); progressDialog.show(); } @Override protected void onPostExecute(ArrayList<NewsElements> newsElementses) { super.onPostExecute(newsElementses); progressDialog.dismiss(); elementsAdapter = new ElementsAdapter(BussinessPage.this, R.layout.item_news, newsElementsArrayList); lvNews.setAdapter(elementsAdapter); elementsGridAdapter = new ElementsGridAdapter(BussinessPage.this, R.layout.item_news_grid, newsElementsArrayList); gvNews.setAdapter(elementsGridAdapter); } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); } @Override protected ArrayList<NewsElements> doInBackground(String... params) { try { URL url = new URL(params[0]); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(getInputStream(url), "UTF-8"); int eventType = xpp.getEventType(); elements = new NewsElements(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (xpp.getName().equalsIgnoreCase("title")) { elements.setTitle(xpp.nextText()); } if (xpp.getName().equalsIgnoreCase("description")) { elements.setDescription(xpp.nextText()); } if (xpp.getName().equalsIgnoreCase("pubDate")) { elements.setPubDate(xpp.nextText()); } if (xpp.getName().equalsIgnoreCase("link")) { elements.setLink(xpp.nextText()); } if (xpp.getName().equalsIgnoreCase("guid")) { elements.setGuid(xpp.nextText()); } } if (elements.getTitle() != null && elements.getDescription() != null && elements.getPubDate() != null && elements.getLink() != null && elements.getGuid() != null) { newsElementsArrayList.add(new NewsElements( elements.getTitle() , elements.getDescription() , elements.getPubDate() , elements.getLink() , elements.getGuid())); elements = new NewsElements(); } eventType = xpp.next(); } return newsElementsArrayList; } catch (XmlPullParserException | IOException e) { e.printStackTrace(); } return null; } } }
true
6372a33f913ba8c5f9289a204aea3fadaf0bae0f
Java
Crazyhell13/MovieManager
/src/test/java/ru/netology/domain/MovieManagerOneObjectTest.java
UTF-8
1,903
2.703125
3
[]
no_license
package ru.netology.domain; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MovieManagerOneObjectTest { private Movie first = new Movie(6, "Гарри Поттер и философский камень", "Фэнтези", "URL",false); @Test public void shouldAddMoviesDefault (){ MovieManager manager = new MovieManager (); manager.addMovie(first); int expected = 1; int actual = manager.getFilms().length; assertEquals(expected,actual); } @Test public void shouldAddMovies (){ MovieManager manager = new MovieManager (5); manager.addMovie(first); int expected = 1; int actual = manager.getFilms().length; assertEquals(expected,actual); } @Test public void shouldAddMoviesNullLength (){ MovieManager manager = new MovieManager (0); manager.addMovie(first); int expected = 1; int actual = manager.getFilms().length; assertEquals(expected,actual); } @Test public void shouldShowLastMoviesDefault (){ MovieManager manager = new MovieManager(); manager.addMovie(first); Movie[]expected = new Movie[]{first}; Movie[]actual = manager.showLastMovies(); assertArrayEquals(expected,actual); } @Test public void shouldShowLastMovies (){ MovieManager manager = new MovieManager(5); manager.addMovie(first); Movie[]expected = new Movie[]{first}; Movie[]actual = manager.showLastMovies(); assertArrayEquals(expected,actual); } @Test public void shouldShowLastMoviesNullLength (){ MovieManager manager = new MovieManager(0); manager.addMovie(first); Movie[]expected = new Movie[]{first}; Movie[]actual = manager.showLastMovies(); assertArrayEquals(expected,actual); } }
true
8eb0dfa06cc91d57fd66db269039d71c38cc89e4
Java
Sambor123/foodie-server
/src/main/java/com/foodie/web/service/impl/DishService.java
UTF-8
1,447
2.046875
2
[]
no_license
package com.foodie.web.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.foodie.web.dao.DishMapper; import com.foodie.web.model.Dish; import com.foodie.web.service.IDishService; @Service public class DishService implements IDishService{ @Autowired private DishMapper dishMapper; @Override public Dish selectByPrimaryKey(String id) { // TODO Auto-generated method stub return dishMapper.selectByPrimaryKey(id); } @Override public int insert(Dish dish) { // TODO Auto-generated method stub return dishMapper.insert(dish); } @Override public List<Dish> getHotRecipes(Integer count) { // TODO Auto-generated method stub return null; } @Override public List<Dish> getNewRecipes(Integer count) { // TODO Auto-generated method stub return null; } @Override public List<Dish> getAll() { // TODO Auto-generated method stub return dishMapper.getAll(); } @Override public List<Dish> search(String queryString){ // TODO Auto-generated method stub return dishMapper.search(queryString); } @Override public List<Dish> selectByRestaurantId(String id) { // TODO Auto-generated method stub return dishMapper.selectByRestaurantId(id); } @Override public int delete(Dish dish) { // TODO Auto-generated method stub String id=dish.getId(); return dishMapper.deleteByPrimaryKey(id); } }
true
91eac2aae81e8a748ad0a4e643ad4f7c7604b648
Java
RenaudBernard59/COMP-S13-2-Java-5-Exercices
/ExercicesPOO/src/main/java/ch/conceptforge/exercicespoo/Exercice05/PersonneDescription.java
UTF-8
1,355
3.375
3
[]
no_license
/* * 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 ch.conceptforge.exercicespoo.Exercice05; /** * * @author renob */ public class PersonneDescription { private int age; private int taille; public PersonneDescription(int age, int taille) { if (age != 0) { if (age > 20 && taille < 100) { System.out.println("Vous êtes peut être un nain adulte?"); } else if (age > 20 && taille > 200) { System.out.println("Vous êtes un géant adulte "); } else if ( age < 3 || taille < 50) { System.out.println("Vous êtes peut être un bébé "); } else if ((age >= 15 && age <= 18) && (taille >= 150 && taille <= 180)) { System.out.println("Vous êtes un ado !"); } else { System.out.println("Vous êtes Normal quoi !"); } }//END MegaIf }//END Construct public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getTaille() { return taille; } public void setTaille(int taille) { this.taille = taille; } }
true
59cdd2bb1592dd55e3b9e7f8dc4f54cec3bd2257
Java
swaswani/SakshiWaswani_Assignments
/Core_Java_Assignment-1/src/AvgTotalMarks.java
UTF-8
1,212
3.578125
4
[]
no_license
public class AvgTotalMarks { public static void main(String[] args) { int totalA , totalB , totalC , totalSub1 , totalSub2 , totalSub3 ; float avgA , avgB, avgC , avgSub1 , avgSub2 , avgSub3 ; // Subject wise marks for student 1 :- int a1=95 , b1=65 , c1=75 ; int a2=60 , b2=75 , c2=80 ; int a3=91 , b3=87 , c3=70 ; totalA=a1+a2+a3; totalB=b1+b2+b3; totalC=c1+c2+c3; System.out.println("Total marks of each subject :- \n Subject-A : "+totalA+" , Subject-B : "+totalB+" , Subject-C : "+totalC); avgA=totalA/3; avgB=totalB/3; avgC=totalC/3; System.out.println(); System.out.println("Average marks of each subject :- \n Subject-A : "+avgA+" , Subject-B : "+avgB+" , Subject-C : "+avgC); totalSub1=a1+b1+c1; totalSub2=a2+b2+c2; totalSub3=a3+b3+c3; System.out.println(); System.out.println("Total marks of each Student :- \n Student-1 : "+totalSub1+" , Student-2 : "+totalSub2+" , Student-3 : "+totalSub3); avgSub1=totalSub1/3; avgSub2=totalSub2/3; avgSub3=totalSub3/3; System.out.println(); System.out.println("Average of each Student :- \n Student-1 : "+avgSub1+" , Student-2 : "+avgSub2+" , Student-3 : "+avgSub3); } }
true
1e1b1d8d9cffa5ff87a63324056bb286f3159a53
Java
BulkSecurityGeneratorProject/eAuth-v2
/egov-eauth/eauth-ui/eauth-ui-backend/src/main/java/bg/bulsi/egov/idp/dto/RegisterRequest.java
UTF-8
2,440
2.203125
2
[ "Apache-2.0" ]
permissive
package bg.bulsi.egov.idp.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Objects; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import org.springframework.validation.annotation.Validated; /** * RegisterRequest */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-02-25T16:48:07.018+02:00[Europe/Sofia]") @JacksonXmlRootElement(localName = "RegisterRequest") @XmlRootElement(name = "RegisterRequest") @XmlAccessorType(XmlAccessType.FIELD)public class RegisterRequest implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("method") @JacksonXmlProperty(localName = "method") private OTPMethod method = null; public RegisterRequest method(OTPMethod method) { this.method = method; return this; } /** * Get method * @return method **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid public OTPMethod getMethod() { return method; } public void setMethod(OTPMethod method) { this.method = method; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RegisterRequest registerRequest = (RegisterRequest) o; return Objects.equals(this.method, registerRequest.method); } @Override public int hashCode() { return Objects.hash(method); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class RegisterRequest {\n"); sb.append(" method: ").append(toIndentedString(method)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
true
d251d0345b30da3480288f2b399ed4bf4c11a891
Java
NationalCrimeAgency/elasticsearch-extract
/src/test/java/uk/gov/nca/elasticsearch/extract/ExtractSettingsTest.java
UTF-8
5,629
2.0625
2
[ "Apache-2.0" ]
permissive
/* National Crime Agency (c) Crown Copyright 2018 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 uk.gov.nca.elasticsearch.extract; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import io.annot8.components.base.processors.Regex; import io.annot8.components.base.processors.Regex.RegexSettings; import io.annot8.components.cyber.processors.IPv4; import io.annot8.components.cyber.processors.IPv6; import io.annot8.components.cyber.processors.Url; import io.annot8.core.settings.EmptySettings; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; import uk.gov.nca.elasticsearch.extract.ExtractSettings.ProcessorSettingsPair; public class ExtractSettingsTest { @Test public void testFields(){ ExtractSettings settings = new ExtractSettings(); //Test that we can add new fields assertFalse(settings.isAllFields()); assertTrue(settings.getFields().isEmpty()); settings.withField("field1"); assertFalse(settings.getFields().isEmpty()); assertTrue(settings.getFields().contains("field1")); settings.withFields(Arrays.asList("field2", "field3")); assertTrue(settings.getFields().contains("field1")); assertTrue(settings.getFields().contains("field2")); assertTrue(settings.getFields().contains("field3")); //Test all fields settings.withAllFields(); assertTrue(settings.isAllFields()); assertTrue(settings.getFields().isEmpty()); //Test adding a field - should disable allFields settings.withField("field1"); assertFalse(settings.isAllFields()); } @Test public void testTargetField(){ ExtractSettings settings = new ExtractSettings(); assertEquals(ExtractSettings.DEFAULT_TARGET_FIELD, settings.getTargetField()); settings.withTargetField("target"); assertEquals("target", settings.getTargetField()); } @Test public void testProcessors(){ ExtractSettings settings = new ExtractSettings(); assertEquals(ExtractSettings.DEFAULT_PROCESSORS, settings.getProcessors()); RegexSettings regexSettings = new RegexSettings(Pattern.compile("[0-9]"), 0, "digit"); settings.withProcessor(IPv4.class); settings.withProcessor(Regex.class, regexSettings); settings.withProcessors(Arrays.asList(IPv6.class, Url.class)); List<ProcessorSettingsPair> processors = settings.getProcessors(); assertEquals(4, processors.size()); ProcessorSettingsPair ipv4 = new ProcessorSettingsPair(IPv4.class); ProcessorSettingsPair regex = new ProcessorSettingsPair(Regex.class, regexSettings); ProcessorSettingsPair ipv6 = new ProcessorSettingsPair(IPv6.class); ProcessorSettingsPair url = new ProcessorSettingsPair(Url.class); assertTrue(processors.contains(ipv4)); assertTrue(processors.contains(regex)); assertTrue(processors.contains(ipv6)); assertTrue(processors.contains(url)); } @Test public void testProcessorNames(){ ExtractSettings settings = new ExtractSettings(); assertEquals(ExtractSettings.DEFAULT_PROCESSORS, settings.getProcessors()); RegexSettings regexSettings = new RegexSettings(Pattern.compile("[0-9]"), 0, "digit"); settings.withProcessorName("io.annot8.components.cyber.processors.IPv4"); settings.withProcessorName("io.annot8.components.base.processors.Regex", regexSettings); settings.withProcessorNames(Arrays.asList("io.annot8.components.cyber.processors.IPv6", "io.annot8.components.cyber.processors.Url")); try{ // Test non-existent class settings.withProcessorName("not.a.real.Class"); fail("Expected exception not thrown"); }catch (IllegalArgumentException iae){ //Expected exception, do nothing } try{ // Test non-existent class with settings settings.withProcessorName("not.a.real.Class", EmptySettings.getInstance()); fail("Expected exception not thrown"); }catch (IllegalArgumentException iae){ //Expected exception, do nothing } List<ProcessorSettingsPair> processors = settings.getProcessors(); assertEquals(4, processors.size()); ProcessorSettingsPair ipv4 = new ProcessorSettingsPair(IPv4.class); ProcessorSettingsPair regex = new ProcessorSettingsPair(Regex.class, regexSettings); ProcessorSettingsPair ipv6 = new ProcessorSettingsPair(IPv6.class); ProcessorSettingsPair url = new ProcessorSettingsPair(Url.class); assertTrue(processors.contains(ipv4)); assertTrue(processors.contains(regex)); assertTrue(processors.contains(ipv6)); assertTrue(processors.contains(url)); } @Test public void testProcessorSettingsPair(){ ProcessorSettingsPair psp1 = new ProcessorSettingsPair(IPv4.class); ProcessorSettingsPair psp2 = new ProcessorSettingsPair(IPv4.class, EmptySettings.getInstance()); ProcessorSettingsPair psp3 = new ProcessorSettingsPair(IPv6.class); assertEquals(psp1, psp2); assertNotEquals(psp1, psp3); assertNotEquals(psp1, "Hello world"); } }
true
565d6465fd168fc3f8c0281ab209a9fc6a80b337
Java
snyh/toy
/JavaSender/src/Node.java
UTF-8
7,692
2.4375
2
[]
no_license
package SenderTest; import javax.swing.text.*; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JComboBox; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.border.EmptyBorder; import javax.swing.SwingUtilities; import javax.swing.JOptionPane; import javax.swing.JFileChooser; import javax.swing.UIManager; import java.awt.Color; import java.awt.Dimension; import java.awt.BorderLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Hashtable; import java.util.UUID; import java.net.InetAddress; import java.util.Iterator; public class Node { private Peer myself_; private Peer select_peer_; protected FileSender fser_; protected FileReceiver frer_; private Hashtable<UUID, Peer> peers_; protected Server server_; protected Client client_; private NodeView view_; public InetAddress getAddrByUUID(UUID u) { return peers_.get(u).addr; } public int getPortByUUID(UUID u) { return peers_.get(u).port; } public String getNameByUUID(UUID u) { return peers_.get(u).name; } public Node() { peers_ = new Hashtable<UUID, Peer>(); view_ = new NodeView(this); view_.setVisible(true); server_ = new Server(this, view_.name); new Thread(server_).start(); /* 无法保证client_在 Server 运行之前创建,因此将new Client放在Server.run中 client_ = new Client(this); */ } public void setMySelf(Peer p) { myself_ = p; } public Peer getMySelf() { return myself_; } public void addNode(Peer p) { //检测当前Node 是否已经存储,如果存储则不予处理 //若不存在则添加记录,并向所有节点广播此节点 if (peers_.get(p.uuid) == null) { //首先将新发现的节点存放到peers_中,然后显示到ComboBox上并提示发现新节点 peers_.put(p.uuid, p); view_.addNode(p); Logger.append("["+p.name + "]", Color.BLUE); Logger.append(" has login!\n", Color.red); //将新发现的节点发送给登录到本节点的Peer上去 Iterator<Peer> peer_it = peers_.values().iterator(); while (peer_it.hasNext()) { //向tmp发送所有已经登录到本节点的信息 Peer tmp = peer_it.next(); if (tmp == myself_) break; //循环发送 Iterator<Peer> info_it = peers_.values().iterator(); while(info_it.hasNext()) { Peer p_info = info_it.next(); //节点信息 System.out.println(p_info); client_.sendEvent(new EventLogin(p_info), tmp.addr, tmp.port); } } } } public void delNode(UUID u) { Peer p = peers_.get(u); if (p != null) { peers_.remove(u); view_.delNode(p); Logger.append("["+p.name + "]", Color.BLUE); Logger.append(" has logout!\n", Color.RED); } } public void logout() { Iterator<Peer> it = peers_.values().iterator(); while (it.hasNext()) { //回送所有当前节点已经知道的节点信息 Peer tmp = it.next(); client_.sendEvent(new EventLogout(myself_.uuid), tmp.addr, tmp.port); } System.out.println("logouted! \n"); System.exit(0); } public void receiveMessage(UUID u, String msg) { Logger.append("[From:" + peers_.get(u).name + "]: ", Color.BLUE); Logger.append(msg+"\n", Color.cyan); } public void sendMessage(UUID u, String msg) { if (u.equals(myself_.uuid)) { //向自己发送信息使用灰色标记 Logger.append("[Yourself]: ", Color.BLUE); Logger.append(msg+"\n", Color.GRAY); //并且并不实际发送信息 } else { Logger.append("[To:" + peers_.get(u).name + "]: ", Color.BLUE); Logger.append(msg+"\n"); client_.sendEvent(new EventMessage(u, msg), peers_.get(u).addr, peers_.get(u).port); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Node n1 = new Node(); } }); } } class NodeView extends JFrame { public String name; public NodeView(Node n) { this_node_ = n; try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { System.out.println("Error setting Java LAF: " + e); } initUI(); //获取登录名 name = JOptionPane.showInputDialog("Please input you nickname"); setTitle(name + "@ Java Sender Test!"); g_send_message_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Peer p = (Peer)g_nodes_.getSelectedItem(); this_node_.sendMessage(p.uuid, g_message_field_.getText()); } }); g_transfer_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(null)) { Peer peer = (Peer)g_nodes_.getSelectedItem(); String dirname = chooser.getSelectedFile().getAbsolutePath(); Logger.append("Ready transfer " + dirname + " to" + peer.name + " \n" , Color.red); this_node_.fser_ = new FileSender(dirname); this_node_.client_.sendEvent( new EventTransferRequest(this_node_.getMySelf().uuid), this_node_.getAddrByUUID(peer.uuid), this_node_.getPortByUUID(peer.uuid) ); } } }); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { this_node_.logout(); } }); } public void addNode(final Peer p) { SwingUtilities.invokeLater(new Runnable() { public void run() { g_nodes_.addItem(p); } }); } public void delNode(final Peer p) { SwingUtilities.invokeLater(new Runnable() { public void run() { g_nodes_.removeItem(p); } }); } private final void initUI() { JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(new EmptyBorder(new Insets(20, 20, 20, 20))); JPanel topbox = new JPanel(); topbox.setLayout(new BoxLayout(topbox, BoxLayout.X_AXIS)); panel.add(topbox, BorderLayout.NORTH); g_nodes_ = new JComboBox(); String init_str = "This message will send to peer!"; g_message_field_ = new JTextField(init_str); //g_message_field_.select(0, init_str.length()); g_send_message_ = new JButton("Send"); topbox.add(g_nodes_); topbox.add(g_message_field_); topbox.add(g_send_message_); g_text_pane_ = new JTextPane(); //g_text_pane_.setEditable(false); g_text_pane_.setPreferredSize(new Dimension(450, 250)); Logger.setLogView(g_text_pane_); //设置Logger输出位置 JScrollPane s = new JScrollPane(); s.setViewportView(g_text_pane_); panel.add(s); JPanel bottombox = new JPanel(); bottombox.setLayout(new BoxLayout(bottombox, BoxLayout.X_AXIS)); panel.add(bottombox, BorderLayout.SOUTH); JButton b = new JButton("Clear"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { g_text_pane_.setText(""); } }); bottombox.add(b); g_transfer_ = new JButton("Transfer Files"); bottombox.add(g_transfer_); add(panel); pack(); setLocationRelativeTo(null); } /* GUI相关的成员 */ private JComboBox g_nodes_; private JTextField g_message_field_; private JButton g_send_message_; private JTextPane g_text_pane_; private Node this_node_; private JButton g_transfer_; }
true
c0711de3a84feca437955560205363ca5baf4c27
Java
peternadykamal/Bank-Queue-System
/src/sample/DataController.java
UTF-8
21,221
2.5
2
[]
no_license
package sample; import sample.AccountPackage.Account; import sample.AccountPackage.MoneyMarketAccount; import sample.AccountPackage.SavingsAccount; import sample.LoanPackage.BusinessLoan; import sample.LoanPackage.Loan; import sample.LoanPackage.PersonalLoan; import sample.PersonPackage.Client; import sample.PersonPackage.Moderator; import sample.PersonPackage.Person; import sample.PersonPackage.Teller; import java.sql.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Objects; public class DataController { private static String host = "PeterDesktop"; private static String portNumber = "3306"; private static String dataBase = "bank_db"; private static String userName = "bank user"; private static String password = "12345678"; private static Connection connection; public static boolean startConnection(){ String url = "JDBC" + ":" + "mysql" +"://" + host + ":" + portNumber + "/" + dataBase; try { Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection(url,userName,password); } catch (SQLException | ClassNotFoundException throwables) { return false; } return true; } public static boolean closeConnection(){ try { connection.close(); } catch (SQLException throwables) { return false; } return true; } public static Account selectAccount(int AccountID) throws SQLException { if(startConnection() == true){ Statement statement = connection.createStatement(); } return null; } public static boolean insertClint(Client client){ String[] array = client.getProperties(); try { PreparedStatement statement = connection.prepareStatement("insert into people" + "(first_name , last_name , phone_number, address , password , person_type)" + "values (?,?,?,?,?,?)"); for (int i=0 ;i<6;i++){ statement.setString(i+1,array[i]); } statement.execute(); statement = connection.prepareStatement("select id from bank_db.people order by id desc limit 1"); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ client.id = (int) resultSet.getObject("id"); } } catch (SQLException throwables) { return false; } return true; } public static boolean insertEmployee(Person person){ String[] array = person.getProperties(); try { PreparedStatement statement = connection.prepareStatement("insert into people" + "(first_name , last_name , phone_number, address , password , salary ,working_hours, person_type)" + "values (?,?,?,?,?,?,?,?)"); for (int i=0 ;i<8;i++){ statement.setString(i+1,array[i]); } statement.execute(); statement = connection.prepareStatement("select id from bank_db.people order by id desc limit 1"); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ person.id = (int) resultSet.getObject("id"); } } catch (SQLException throwables) { return false; } return true; } public static boolean insertAccount(Account account,Client client){ String[] array = account.getProperties(); try { PreparedStatement statement = connection.prepareStatement("insert into accounts" + "(balance , accountState , penaltyUnderMin , lastAddedInterest , " + " account_type, withdrawTimesInThisMonths, currentMonthNumber, person_id )" + "values (?,?,?,?,?,?,?,?)"); for (int i=0 ;i<8;i++){ if(i<array.length){ if(i == 1 || i==2) statement.setBoolean(i+1, Boolean.parseBoolean(array[i])); else statement.setString(i+1,array[i]); } else if (i==7) statement.setString(i+1, String.valueOf(client.id)); else statement.setNull(i+1, java.sql.Types.NULL); } statement.execute(); statement = connection.prepareStatement("select id from bank_db.accounts order by id desc limit 1"); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ account.accountId = (int) resultSet.getObject("id"); } } catch (SQLException throwables) { return false; } return true; } public static boolean insertLoan(Loan loan,Client client){ String[] array = loan.getProperties(); try { PreparedStatement statement = connection.prepareStatement("insert into loans" + "(loanedAmount ,timePeriod ,interest ,loanBirthDate ," + " paidMonths ,penalty ,loan_type ,person_id)" + "values (?,?,?,?,?,?,?,?)"); for (int i=0 ;i<8;i++){ if(i<array.length){ if(i == 5) statement.setBoolean(i+1, Boolean.parseBoolean(array[i])); else statement.setString(i+1,array[i]); } else if (i==7) statement.setString(i+1, String.valueOf(client.id)); } statement.execute(); statement = connection.prepareStatement("select id from bank_db.loans order by id desc limit 1"); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ loan.loanID = (int) resultSet.getObject("id"); } } catch (SQLException throwables) { return false; } return true; } public static Client selectClint(int personId){ Client client; try { PreparedStatement statement = connection.prepareStatement( "select person_type,id,first_name,last_name,phone_number" + ",address,password from people where id = "+ personId); ResultSet resultSet = statement.executeQuery(); ArrayList<String> array = new ArrayList<>(); while (resultSet.next()){ array.add(String.valueOf(resultSet.getObject("person_type"))); array.add(String.valueOf(resultSet.getObject("id"))); array.add(String.valueOf(resultSet.getObject("first_name"))); array.add(String.valueOf(resultSet.getObject("last_name"))); array.add(String.valueOf(resultSet.getObject("phone_number"))); array.add(String.valueOf(resultSet.getObject("address"))); array.add(String.valueOf(resultSet.getObject("password"))); } if(array.size()>0){ if(!Objects.equals(array.get(0), "client")) throw new SQLException(); else { client = new Client( Integer.parseInt(array.get(1)),array.get(2),array.get(3), array.get(4),array.get(5),array.get(6), selectAccountList(Integer.parseInt(array.get(1))), selectLoanList(Integer.parseInt(array.get(1))) ); } } else throw new SQLException(); } catch (SQLException throwables) { return null; } return client; } private static ArrayList<Account> selectAccountList(int personId){ ArrayList<Account> accounts = new ArrayList<>(); try { PreparedStatement statement = connection.prepareStatement( "select account_type,id,balance,accountState,penaltyUnderMin" + ",lastAddedInterest,withdrawTimesInThisMonths,currentMonthNumber " + "from accounts where person_id = "+ personId); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ ArrayList<String> array = new ArrayList<>(); array.add(String.valueOf(resultSet.getObject("account_type"))); array.add(String.valueOf(resultSet.getObject("id"))); array.add(String.valueOf(resultSet.getObject("balance"))); array.add(String.valueOf(resultSet.getBoolean("accountState"))); array.add(String.valueOf(resultSet.getBoolean("penaltyUnderMin"))); array.add(String.valueOf(resultSet.getObject("lastAddedInterest"))); array.add(String.valueOf(resultSet.getObject("withdrawTimesInThisMonths"))); array.add(String.valueOf(resultSet.getObject("currentMonthNumber"))); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.0"); LocalDateTime dateTime = LocalDateTime.parse(array.get(5), formatter); if(array.get(0).equals("Savings")){ SavingsAccount savingsAccount = new SavingsAccount( Integer.parseInt(array.get(1)),Double.parseDouble(array.get(2)), Boolean.parseBoolean(array.get(3)),Boolean.parseBoolean(array.get(4)), dateTime,Integer.parseInt(array.get(6)), Integer.parseInt(array.get(7)) ); accounts.add(savingsAccount); } else if(array.get(0).equals("MoneyMarket")){ MoneyMarketAccount moneyMarketAccount = new MoneyMarketAccount( Integer.parseInt(array.get(1)),Double.parseDouble(array.get(2)), Boolean.parseBoolean(array.get(3)),Boolean.parseBoolean(array.get(4)), dateTime ); accounts.add(moneyMarketAccount); } } if(accounts.size()==0) return new ArrayList<Account>(); } catch (SQLException throwables) { return null; } return accounts; } private static ArrayList<Loan> selectLoanList(int personId){ ArrayList<Loan> loans = new ArrayList<>(); try { PreparedStatement statement = connection.prepareStatement( "select loan_type,id,loanedAmount,timePeriod,interest" + ",loanBirthDate,paidMonths,penalty " + "from loans where person_id = "+ personId); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ ArrayList<String> array = new ArrayList<>(); array.add(String.valueOf(resultSet.getObject("loan_type"))); array.add(String.valueOf(resultSet.getObject("id"))); array.add(String.valueOf(resultSet.getObject("loanedAmount"))); array.add(String.valueOf(resultSet.getObject("timePeriod"))); array.add(String.valueOf(resultSet.getObject("interest"))); array.add(String.valueOf(resultSet.getObject("loanBirthDate"))); array.add(String.valueOf(resultSet.getObject("paidMonths"))); array.add(String.valueOf(resultSet.getBoolean("penalty"))); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.0"); LocalDateTime BirthDate = LocalDateTime.parse(array.get(5), formatter); if(array.get(0).equals("Business")){ BusinessLoan businessLoan = new BusinessLoan( Integer.parseInt(array.get(1)),Integer.parseInt(array.get(2)), Integer.parseInt(array.get(3)),Double.parseDouble(array.get(4)), BirthDate,Integer.parseInt(array.get(6)),Boolean.parseBoolean(array.get(7)) ); loans.add(businessLoan); } else if(array.get(0).equals("Personal")){ PersonalLoan personalLoan = new PersonalLoan( Integer.parseInt(array.get(1)),Integer.parseInt(array.get(2)), Integer.parseInt(array.get(3)),Double.parseDouble(array.get(4)), BirthDate,Integer.parseInt(array.get(6)),Boolean.parseBoolean(array.get(7)) ); loans.add(personalLoan); } } if(loans.size()==0) return new ArrayList<Loan>(); } catch (SQLException throwables) { return null; } return loans; } public static Teller selectTeller(int personId){ Teller employee; try { PreparedStatement statement = connection.prepareStatement( "select person_type,id,first_name,last_name,phone_number" + ",address,password,salary,working_hours from people where id = "+ personId); ResultSet resultSet = statement.executeQuery(); ArrayList<String> array = new ArrayList<>(); while (resultSet.next()){ array.add(String.valueOf(resultSet.getObject("person_type"))); array.add(String.valueOf(resultSet.getObject("id"))); array.add(String.valueOf(resultSet.getObject("first_name"))); array.add(String.valueOf(resultSet.getObject("last_name"))); array.add(String.valueOf(resultSet.getObject("phone_number"))); array.add(String.valueOf(resultSet.getObject("address"))); array.add(String.valueOf(resultSet.getObject("password"))); array.add(String.valueOf(resultSet.getObject("salary"))); array.add(String.valueOf(resultSet.getObject("working_hours"))); } if(array.size()>0){ if(!Objects.equals(array.get(0), "teller")) throw new SQLException(); else { employee = new Teller( Integer.parseInt(array.get(1)),array.get(2),array.get(3), array.get(4),array.get(5),array.get(6), Double.parseDouble(array.get(7)),Integer.parseInt(array.get(8)) ); } } else throw new SQLException(); } catch (SQLException throwables) { return null; } return employee; } public static Moderator selectModerator(int personId){ Moderator employee; try { PreparedStatement statement = connection.prepareStatement( "select person_type,id,first_name,last_name,phone_number" + ",address,password,salary,working_hours from people where id = "+ personId); ResultSet resultSet = statement.executeQuery(); ArrayList<String> array = new ArrayList<>(); while (resultSet.next()){ array.add(String.valueOf(resultSet.getObject("person_type"))); array.add(String.valueOf(resultSet.getObject("id"))); array.add(String.valueOf(resultSet.getObject("first_name"))); array.add(String.valueOf(resultSet.getObject("last_name"))); array.add(String.valueOf(resultSet.getObject("phone_number"))); array.add(String.valueOf(resultSet.getObject("address"))); array.add(String.valueOf(resultSet.getObject("password"))); array.add(String.valueOf(resultSet.getObject("salary"))); array.add(String.valueOf(resultSet.getObject("working_hours"))); } if(array.size()>0){ if(!Objects.equals(array.get(0), "moderator")) throw new SQLException(); else { employee = new Moderator( Integer.parseInt(array.get(1)),array.get(2),array.get(3), array.get(4),array.get(5),array.get(6), Double.parseDouble(array.get(7)),Integer.parseInt(array.get(8)) ); } } else throw new SQLException(); } catch (SQLException throwables) { return null; } return employee; } public static boolean updateAccount(Account account,Client client){ String[] array = account.getProperties(); try { PreparedStatement statement = connection.prepareStatement("update accounts" + " set balance = ? , accountState = ? , penaltyUnderMin = ? , lastAddedInterest = ? , " + " account_type = ? , withdrawTimesInThisMonths = ? , currentMonthNumber = ? , person_id = ?" + " where id = " + account.accountId); for (int i=0 ;i<8;i++){ if(i<array.length){ if(i == 1 || i==2) statement.setBoolean(i+1, Boolean.parseBoolean(array[i])); else statement.setString(i+1,array[i]); } else if (i==7) statement.setInt(i+1, client.id); else statement.setNull(i+1, java.sql.Types.NULL); } statement.execute(); } catch (SQLException throwables) { return false; } return true; } public static boolean updateLoan(Loan loan, Client client){ String[] array = loan.getProperties(); try { PreparedStatement statement = connection.prepareStatement("update loans" + " set loanedAmount = ? ,timePeriod = ? ,interest = ? ,loanBirthDate = ? , " + " paidMonths = ? ,penalty = ? ,loan_type = ? ,person_id = ? " + " where id =" + loan.loanID); for (int i=0 ;i<8;i++){ if(i<array.length){ if(i == 5) statement.setBoolean(i+1, Boolean.parseBoolean(array[i])); else statement.setString(i+1,array[i]); } else if (i==7) statement.setString(i+1, String.valueOf(client.id)); } statement.execute(); } catch (SQLException throwables) { return false; } return true; } public static boolean updateClint(Client client){ String[] array = client.getProperties(); try { PreparedStatement statement = connection.prepareStatement("update people" + " set first_name = ? , last_name = ? , phone_number = ? , address = ? , password = ? , person_type = ? " + " where id = " + client.id); for (int i=0 ;i<6;i++){ statement.setString(i+1,array[i]); } statement.execute(); for (Account account : client.getAccounts()) { DataController.updateAccount(account, client); } for (Loan loan : client.getLoans()) { DataController.updateLoan(loan, client); } } catch (SQLException throwables) { return false; } return true; } public static boolean updateEmployee(Person person){ String[] array = person.getProperties(); try { PreparedStatement statement = connection.prepareStatement("update people" + " set first_name = ? , last_name = ? , phone_number = ? , address = ? , password = ? " + ", salary = ? ,working_hours = ? , person_type = ? " + " where id = " + person.id); for (int i=0 ;i<8;i++){ statement.setString(i+1,array[i]); } statement.execute(); } catch (SQLException throwables) { return false; } return true; } public static boolean dropAccount(Account account){ try { PreparedStatement statement = connection.prepareStatement("delete from accounts" + " where id = " + account.accountId); statement.execute(); } catch (SQLException throwables) { return false; } return true; } public static boolean dropLoan(Loan loan){ try { PreparedStatement statement = connection.prepareStatement("delete from loans" + " where id = " + loan.loanID); statement.execute(); } catch (SQLException throwables) { return false; } return true; } public static boolean dropPerson(Person person){ try { PreparedStatement statement = connection.prepareStatement("delete from people" + " where id = " + person.id); statement.execute(); } catch (SQLException throwables) { return false; } return true; } }
true
8dbe3b2f538708097df80e0d6a354ea7001a296d
Java
TulioTriste/bukkit-core
/src/main/java/net/pandamc/core/servermonitor/menu/ServerMonitorMenu.java
UTF-8
1,008
2.390625
2
[]
no_license
package net.pandamc.core.servermonitor.menu; import net.pandamc.core.servermonitor.button.ServerMonitorButton; import net.pandamc.core.util.menu.Button; import net.pandamc.core.util.menu.Menu; import org.bukkit.entity.Player; import java.util.HashMap; import java.util.Map; public class ServerMonitorMenu extends Menu { @Override public String getTitle(Player player) { return "&aServer Monitor"; } @Override public int getSize() { return 9 * 3; } @Override public Map<Integer, Button> getButtons(Player player) { Map<Integer, Button> buttons = new HashMap<>(); buttons.put(getSlot(1, 1), new ServerMonitorButton("hub")); buttons.put(getSlot(2, 1), new ServerMonitorButton("practice")); buttons.put(getSlot(3, 1), new ServerMonitorButton("kitmap")); buttons.put(getSlot(4, 1), new ServerMonitorButton("squads")); buttons.put(getSlot(5, 1), new ServerMonitorButton("combo")); return buttons; } }
true
da2aefa9c9f69fbbc441b8ec08af5c7f86d3f442
Java
zx150842/task-scheduler
/admin/src/main/java/com/dts/admin/common/vo/CronJob.java
UTF-8
2,026
2.21875
2
[]
no_license
package com.dts.admin.common.vo; import java.util.Date; /** * @author zhangxin */ public class CronJob { private String jobId; // task名字 private String tasks; // cron表达式 private String cronExpression; // job提交到的worker组 private String workerGroup; // job状态 private int status; // job允许运行的最大时间(s) private long maxRunTimeSec = -1; private Date lastTriggerTime; private String desc; public CronJob() {} public CronJob(String jobId, String tasks, String cronExpression, String workerGroup, int status, long maxRunTimeSec, Date lastTriggerTime) { this.jobId = jobId; this.tasks = tasks; this.cronExpression = cronExpression; this.workerGroup = workerGroup; this.status = status; this.maxRunTimeSec = maxRunTimeSec; this.lastTriggerTime = lastTriggerTime; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getTasks() { return tasks; } public void setTasks(String tasks) { this.tasks = tasks; } public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getWorkerGroup() { return workerGroup; } public void setWorkerGroup(String workerGroup) { this.workerGroup = workerGroup; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public long getMaxRunTimeSec() { return maxRunTimeSec; } public void setMaxRunTimeSec(long maxRunTimeSec) { this.maxRunTimeSec = maxRunTimeSec; } public Date getLastTriggerTime() { return lastTriggerTime; } public void setLastTriggerTime(Date lastTriggerTime) { this.lastTriggerTime = lastTriggerTime; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
true
a10798bb9ea8c6f03ea099ef71ecde6bc09d358f
Java
comdata/HomeAutomation
/src/main/java/cm/homeautomation/services/gasmeter/GasMeterService.java
UTF-8
1,551
2.125
2
[]
no_license
package cm.homeautomation.services.gasmeter; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.transaction.Transactional.TxType; import javax.ws.rs.GET; import javax.ws.rs.Path; import cm.homeautomation.configuration.ConfigurationService; import cm.homeautomation.entities.GasIntervalData; import cm.homeautomation.services.base.BaseService; @Path("gas") @Transactional(value = TxType.REQUIRES_NEW) public class GasMeterService extends BaseService { @Inject EntityManager em; @Inject ConfigurationService configurationService; @GET @Path("readInterval") public List<GasIntervalData> getPowerDataForIntervals() { String minutes = "60"; @SuppressWarnings("unchecked") List<Object[]> rawResultList = em .createNativeQuery("select count(*)/100 as QM, FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(TIMESTAMP)/(" + minutes + " * 60))*" + minutes + "*60) as TIMESLICE from GASMETERPING where date(TIMESTAMP)>=date(now()- interval 7 day) GROUP BY ROUND(UNIX_TIMESTAMP(TIMESTAMP)/(" + minutes + " * 60));", Object[].class) .getResultList(); List<GasIntervalData> results = new ArrayList<GasIntervalData>(); for (Object[] resultElement : rawResultList) { GasIntervalData gasIntervalData = new GasIntervalData((BigDecimal) resultElement[0], (Timestamp) resultElement[1]); results.add(gasIntervalData); } return results; } }
true
6bc117fc3c4d48bc5801754018ca41645f8858f6
Java
xiezhuolin/tesla
/app/src/main/java/cn/acewill/pos/next/base/fragment/BaseFragment.java
UTF-8
2,240
2.09375
2
[]
no_license
package cn.acewill.pos.next.base.fragment; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import cn.acewill.pos.R; import cn.acewill.pos.next.config.MyApplication; import cn.acewill.pos.next.widget.CatLoadingView; /** * BaseFragment * Created by DHH on 2016/1/28. */ public class BaseFragment extends Fragment { public Context mContext; public Activity aty; public Resources resources; public MyApplication myApplication; protected boolean isVisible; @Override public void onAttach(Context context) { super.onAttach(context); this.mContext = context; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.resources = getResources(); this.aty = getActivity(); this.myApplication = MyApplication.getInstance(); } public String getStringById(int resId){ String str = ""; if (resources != null){ str = resources.getString(resId); } return str; } public void showToast(String sth) { MyApplication.getInstance().ShowToast(sth); } CatLoadingView mView; public void showProgress() { try { mView = new CatLoadingView(); mView.show(getActivity().getSupportFragmentManager(), ""); } catch (Exception e) { e.printStackTrace(); } } public void showProgress(String str) { try { mView = new CatLoadingView(); if(!TextUtils.isEmpty(str)) { mView.setText(str); } mView.show(getActivity().getSupportFragmentManager(), ""); } catch (Exception e) { e.printStackTrace(); } } public void dissmiss() { try { if(mView != null) { mView.setText(resources.getString(R.string.sth_loading)); mView.dismiss(); } } catch (Resources.NotFoundException e) { e.printStackTrace(); } } }
true
4b4c76f8dba33619b32994cd6ddc277f0b83735a
Java
stanislavkisyov/ProgrammingFundamentalsInJava
/src/Lap/Lists/P02_Append_Lists.java
UTF-8
640
3.046875
3
[]
no_license
package Lap.Lists; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class P02_Append_Lists { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); char[] separators = " | ".toCharArray(); String[] input = scanner.nextLine().split(String.valueOf(separators)); List<String> reversed = new ArrayList<String>(); System.out.println(); for (int i = 0; i < input.length; i++) { } //Todo: Не мога да измисля решение: } }
true
62ca86d2f96caee1cc59c3bd3f72f0f65062241f
Java
erzih/diklat
/src/com/id/diklatpku/MainActivity.java
UTF-8
1,009
1.84375
2
[]
no_license
package com.id.diklatpku; import com.id.diklatpku.R; import com.id.diklatpku.listpiket.PetugasPiketFragment; import android.app.TabActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.widget.TabHost; @SuppressWarnings("deprecation") public class MainActivity extends TabActivity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stu super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TabHost tabhost = getTabHost(); TabHost.TabSpec spec; Intent intent; intent = new Intent().setClass(this, Activity_DetilUser.class); spec = tabhost.newTabSpec("akunpengguna") .setIndicator("AKUN PENGGUNA", null).setContent(intent); tabhost.addTab(spec); intent = new Intent().setClass(this, PetugasPiketFragment.class); spec = tabhost.newTabSpec("petugaspiket") .setIndicator("PETUGAS PIKET", null).setContent(intent); tabhost.addTab(spec); } }
true
cf0c1f751d81fc66d726f5bf0b74de142a623332
Java
martinidea/gcuMath
/app/src/main/java/com/gcu/math/base/util/StringUtils.java
UTF-8
365
2.609375
3
[]
no_license
package com.gcu.math.base.util; /** * Created by Martin on 2016/9/8. */ public class StringUtils { public static String endPoint(String s) { if (s == null) { return ""; } int pointIndex = s.lastIndexOf("."); if (pointIndex != -1) { return s.substring(pointIndex); } return ""; } }
true
6e87523403022979b55e7a0552b087bf5c5fdc43
Java
SAHARSH123/OracleJ2EE
/webservice/wsclientapp/src/com/client/ws/WSClient.java
UTF-8
429
2.1875
2
[]
no_license
package com.client.ws; import client.ws.CalcService; import client.ws.CalcService_Service; public class WSClient { public static void main(String[] args) { CalcService_Service service= new CalcService_Service(); CalcService obj =service.getCalcServicePort(); int sum=obj.add(100,50); System.out.println("Sum is "+sum); int diff= obj.subract(100,60); } }
true
54e1437a616235a32075e06d1d06effbe391caae
Java
LivanAlex/Epam
/java-online/src/by/jonline/four/class05/Counter.java
UTF-8
533
3.40625
3
[]
no_license
package by.jonline.four.class05; public class Counter { private long counter; /** Sets default value of counter = 0 */ public Counter() { counter = 0; } /** Sets value of counter */ public Counter(long counter) { this.counter = counter; } public long getCounter() { return counter; } public void setCounter(long counter) { this.counter = counter; } /** Increases value of counter */ public void increase() { counter++; } /** Decreases value of counter */ public void decrease() { counter--; } }
true
cd4fca1aefb2e07833105a582b267febf385ee53
Java
gg1302112/tank
/src/com/zyjk/tank/Bullet.java
UTF-8
2,576
2.765625
3
[]
no_license
package com.zyjk.tank; import org.w3c.dom.css.Rect; import javax.annotation.Resource; import java.awt.*; /** * @Auther: lzw * @Date: 20/10/7 - 10 - 07 - 17:00 * @Description: com.zyjk.tank * @version: 1.0 */ public class Bullet { private int x,y; public static int WIDTH = ResourceMgr.bulletD.getWidth(); public static int HEIGHT = ResourceMgr.bulletD.getHeight(); private Group group = Group.BAD; private Dir dir; private static final int SPEED = 10; private boolean living = true; TankFrame tf = null; Rectangle rect = new Rectangle(); public Bullet(int x, int y, Dir dir,Group group,TankFrame tf) { this.x = x; this.y = y; this.dir = dir; this.group = group; this.tf = tf; rect.x = x; rect.y = y; rect.height=HEIGHT; rect.width= WIDTH; } public void paint(Graphics g){ if(!living) tf.bullets.remove(this); switch (dir){ case LEFT: g.drawImage(ResourceMgr.bulletL,x,y,null); break; case RIGHT: g.drawImage(ResourceMgr.bulletR,x,y,null); break; case UP: g.drawImage(ResourceMgr.bulletU,x,y,null); break; case DOWN: g.drawImage(ResourceMgr.bulletD,x,y,null); break; default: break; } move(); } private void move() { switch (dir) { case LEFT: x -= SPEED; break; case UP: y -= SPEED; break; case RIGHT: x += SPEED; break; case DOWN: y += SPEED; break; } rect.x = x; rect.y = y; if (x<0 || x>tf.getGameWidth() || y<0 || y>tf.getGameHeight()) living=false; } public void collideWith(Tank tank) { if (this.group == tank.getGroup()){ return;} // Rectangle rect1 = new Rectangle(this.x,this.y,WIDTH,HEIGHT); // Rectangle rect2 = new Rectangle(tank.getX(),tank.getY(),tank.WIDTH,tank.HEIGHT); if (this.rect.intersects(tank.rect)){ tank.die(); this.die(); int eX = tank.getX() + tank.WIDTH/2 - Explode.WIDTH/2; int eY = tank.getY() + tank.HEIGHT/2 - Explode.HEIGHT/2; tf.explodes.add(new Explode(eX,eY,tf)); } } private void die() { this.living = false; } }
true
54ee7dfac102e2e5cb4d30b429e3a6aad0fcebca
Java
heishandian/recommendersystem
/recommendersystem/src/main/java/com/huangkai/service/IUserRegisterService.java
UTF-8
186
1.679688
2
[]
no_license
package com.huangkai.service; import java.util.List; import com.huangkai.model.Movie_genres; public interface IUserRegisterService { List<Movie_genres> getAllMovie_genres(); }
true
62ceb87f25b80b16376e8c1a23f16772b7480c15
Java
codeghoul/u-binge
/src/main/java/com/finalassessment/ubinge/controller/DeliveryGuyController.java
UTF-8
4,737
2.515625
3
[]
no_license
package com.finalassessment.ubinge.controller; import com.finalassessment.ubinge.dto.DeliveryGuyDTO; import com.finalassessment.ubinge.dto.OrderDTO; import com.finalassessment.ubinge.dto.OrderModificationDTO; import com.finalassessment.ubinge.service.DeliveryGuyService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @Slf4j @RestController /** * Controller to map all delivery guy related operations. */ public class DeliveryGuyController { private DeliveryGuyService deliveryGuyService; @Autowired public DeliveryGuyController(DeliveryGuyService deliveryGuyService) { this.deliveryGuyService = deliveryGuyService; } /** * Returns list of all delivery guys. * * @return */ @GetMapping(value = "/deliveryguys") public ResponseEntity<List<DeliveryGuyDTO>> getAllDeliveryGuys() { log.debug("Getting all Delivery Guys."); return ResponseEntity.status(HttpStatus.OK).body(deliveryGuyService.findAll()); } /** * Returns a delivery guy with given id. * * @param deliveryGuyId * @return */ @GetMapping(value = "/deliveryguys/{deliveryGuyId}") public ResponseEntity<DeliveryGuyDTO> getDeliveryGuy(@PathVariable Long deliveryGuyId) { log.debug("Getting Delivery Guy by id."); return ResponseEntity.status(HttpStatus.OK).body(deliveryGuyService.findById(deliveryGuyId)); } /** * Returns list of orders assigned to delivery guy with given id. * * @param deliveryGuyId * @return */ @GetMapping(value = "/deliveryguys/{deliveryGuyId}/orders") public ResponseEntity<List<OrderDTO>> getDeliveryGuyOrders(@PathVariable Long deliveryGuyId) { log.debug("Getting Orders assigned to Delivery Guy."); return ResponseEntity.status(HttpStatus.OK).body(deliveryGuyService.getDeliveryGuyOrders(deliveryGuyId)); } /** * Returns a order by given id assigned to delivery guy with given id. * * @param deliveryGuyId * @param orderId * @return */ @GetMapping(value = "/deliveryguys/{deliveryGuyId}/orders/{orderId}") public ResponseEntity<OrderDTO> getDeliveryGuyOrderById(@PathVariable Long deliveryGuyId, @PathVariable Long orderId) { log.debug("Getting Order assigned to Delivery Guy using given OrderId."); return ResponseEntity.status(HttpStatus.OK).body(deliveryGuyService.getDeliveryGuyOrderById(deliveryGuyId, orderId)); } /** * Persists a delivery guy in the database. * * @param deliveryGuyDTO * @return */ @PostMapping(value = "/deliveryguys") public ResponseEntity<DeliveryGuyDTO> saveDeliveryGuy(@Valid @RequestBody DeliveryGuyDTO deliveryGuyDTO) { log.debug("Saving Delivery Guy."); return ResponseEntity.status(HttpStatus.CREATED).body(deliveryGuyService.save(deliveryGuyDTO)); } /** * Modifies a delivery guy with given id in the database. * * @param deliveryGuyDTO * @param deliveryGuyId * @return */ @PutMapping(value = "/deliveryguys/{deliveryGuyId}") public ResponseEntity<DeliveryGuyDTO> updateDeliveryGuy(@Valid @RequestBody DeliveryGuyDTO deliveryGuyDTO, @PathVariable Long deliveryGuyId) { log.debug("Updating Delivery Guy by id."); return ResponseEntity.status(HttpStatus.OK).body(deliveryGuyService.update(deliveryGuyDTO, deliveryGuyId)); } /** * Modify a specific order status as delivered/picked up by delivery guy. * * @param deliveryGuyId * @param orderId * @param modification * @return */ @PutMapping(value = "/deliveryguys/{deliveryGuyId}/orders/{orderId}") public ResponseEntity<OrderDTO> modifyOrder(@PathVariable Long deliveryGuyId, @PathVariable Long orderId, @Valid @RequestBody OrderModificationDTO modification) { log.debug("Modifying Delivery Guy Order."); return ResponseEntity.status(HttpStatus.OK).body(deliveryGuyService.modifyOrder(deliveryGuyId, orderId, modification)); } /** * Delete a delivery guy entry from database belonging to given id. * * @param deliveryGuyId * @return */ @DeleteMapping(value = "/deliveryguys/{deliveryGuyId}") public ResponseEntity<?> deleteDeliveryGuyById(@PathVariable Long deliveryGuyId) { log.debug("Deleting Delivery Guy by id."); deliveryGuyService.deleteById(deliveryGuyId); return ResponseEntity.noContent().build(); } }
true
2ae0b97af5ff91afb634e4ec2fae3976880d728c
Java
akyekth/hopsworks
/hopsworks-common/src/main/java/io/hops/hopsworks/common/dao/jobs/description/JobDescriptionFacade.java
UTF-8
5,211
2.25
2
[ "Apache-2.0" ]
permissive
package io.hops.hopsworks.common.dao.jobs.description; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import io.hops.hopsworks.common.jobs.jobhistory.JobState; import io.hops.hopsworks.common.jobs.jobhistory.JobType; import io.hops.hopsworks.common.dao.user.Users; import io.hops.hopsworks.common.dao.AbstractFacade; import io.hops.hopsworks.common.dao.project.Project; import io.hops.hopsworks.common.jobs.configuration.JobConfiguration; import io.hops.hopsworks.common.jobs.configuration.ScheduleDTO; import io.hops.hopsworks.common.metadata.exception.DatabaseException; /** * Facade for management of persistent JobDescription objects. */ @Stateless public class JobDescriptionFacade extends AbstractFacade<JobDescription> { @PersistenceContext(unitName = "kthfsPU") private EntityManager em; private static final Logger logger = Logger.getLogger( JobDescriptionFacade.class. getName()); public JobDescriptionFacade() { super(JobDescription.class); } @Override protected EntityManager getEntityManager() { return em; } /** * Find all the jobs in this project with the given type. * <p/> * @param project * @param type * @return */ public List<JobDescription> findJobsForProjectAndType( Project project, JobType type) { TypedQuery<JobDescription> q = em.createNamedQuery( "JobDescription.findByProjectAndType", JobDescription.class); q.setParameter("project", project); q.setParameter("type", type); return q.getResultList(); } /** * Find all the jobs defined in the given project. * <p/> * @param project * @return */ public List<JobDescription> findForProject(Project project) { TypedQuery<JobDescription> q = em.createNamedQuery( "JobDescription.findByProject", JobDescription.class); q.setParameter("project", project); return q.getResultList(); } /** * Create a new JobDescription instance. * <p/> * @param creator The creator of the job. * @param project The project in which this job is defined. * @param config The job configuration file. * @return * @throws IllegalArgumentException If the JobConfiguration object is not * parseable to a known class. * @throws NullPointerException If any of the arguments user, project or * config are null. */ //This seems to ensure that the entity is actually created and can later //be found using em.find(). @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public JobDescription create(Users creator, Project project, JobConfiguration config) throws IllegalArgumentException, NullPointerException { //Argument checking if (creator == null || project == null || config == null) { throw new NullPointerException( "Owner, project and config must be non-null."); } //First: create a job object JobDescription job = new JobDescription(config, project, creator, config. getAppName()); //Finally: persist it, getting the assigned id. em.persist(job); em.flush(); //To get the id. return job; } /** * Find the JobDescription with given id. * <p/> * @param id * @return The found entity or null if no such exists. */ public JobDescription findById(Integer id) { return em.find(JobDescription.class, id); } public void removeJob(JobDescription job) throws DatabaseException { try { JobDescription managedJob = em.find(JobDescription.class, job.getId()); em.remove(em.merge(managedJob)); em.flush(); } catch (SecurityException | IllegalStateException ex) { throw new DatabaseException("Could not delete job " + job.getName(), ex); } } public boolean updateJobSchedule(int jobId, ScheduleDTO schedule) throws DatabaseException { boolean status = false; try { JobDescription managedJob = em.find(JobDescription.class, jobId); JobConfiguration config = managedJob.getJobConfig(); config.setSchedule(schedule); TypedQuery<JobDescription> q = em.createNamedQuery( "JobDescription.updateConfig", JobDescription.class); q.setParameter("id", jobId); q.setParameter("jobconfig", config); int result = q.executeUpdate(); logger.log(Level.INFO, "Updated entity count = {0}", result); if (result == 1) { status = true; } } catch (SecurityException | IllegalArgumentException ex) { throw new DatabaseException("Could not update job ", ex); } return status; } public List<JobDescription> getRunningJobs(Project project) { TypedQuery<JobDescription> q = em.createNamedQuery( "Execution.findJobsForExecutionInState", JobDescription.class); q.setParameter("project", project); q.setParameter("stateCollection", JobState.getRunningStates()); return q.getResultList(); } }
true
b034f126a2ffba7e0b741bdc802bcad86e94ab1f
Java
hpatrick5/FTCLeagueRandomizer
/src/Model.java
UTF-8
849
2.484375
2
[]
no_license
import java.io.Serializable; import java.util.ArrayList; import java.util.TreeMap; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Hannah */ public class Model implements Serializable{ private TreeMap<Integer, Team> teams; private ArrayList<League> leagues; public Model(){ teams = new TreeMap(); leagues = new ArrayList(); } public TreeMap<Integer, Team> getTeams() { return teams; } public void setTeams(TreeMap<Integer, Team> teams) { this.teams = teams; } public ArrayList<League> getLeagues() { return leagues; } public void setLeagues(ArrayList<League> leagues) { this.leagues = leagues; } }
true
e0afea8656a79a9345fa70c561c5b7eac6f7234c
Java
Corentin-Luc-Artaud/isadevops-2018-2019
/teami-cli-admin/src/main/java/fr/unice/polytech/si4/isa/devops/teami/commands/GenerateInitialPlanning.java
UTF-8
584
2.015625
2
[]
no_license
package fr.unice.polytech.si4.isa.devops.teami.commands; import fr.unice.polytech.si4.isa.devops.teami.api.CeremonyManagerApi; import fr.unice.polytech.si4.isa.devops.teami.framework.Command; public class GenerateInitialPlanning extends Command<CeremonyManagerApi> { @Override public String identifier() { return "generatePlanning"; } @Override public void execute() throws Exception { shell.ceremonyManagerApi.ceremony.generateInitialPlanning(); } @Override public String describe() { return "generateplanning"; } }
true
ccced7fe291dbf3f829a3756265c82fdc07c4681
Java
Evans-Marshall/HibernateDemo
/HibernateDemo/src/HibernateDemo/TestDAO.java
UTF-8
1,450
2.640625
3
[]
no_license
package HibernateDemo; import org.hibernate.*; import java.util.*; public class TestDAO { SessionFactory factory = null; Session session = null; private static TestDAO single_instance = null; private TestDAO() { factory = HibernateUtils.getSessionFactory(); } public static TestDAO getInstance() { if (single_instance == null) { single_instance = new TestDAO(); } return single_instance; } public List<FamilyToSQL> getFamily () { try { session = factory.openSession(); session.getTransaction().begin(); String sql = "from HibernateDemo.FamilyToSQL"; List<FamilyToSQL> cs = (List<FamilyToSQL>)session.createQuery(sql).getResultList(); session.getTransaction().commit(); return cs; } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); return null; }finally { session.close(); } } public FamilyToSQL getFamilyToSQL(String title) { try { session = factory.openSession(); session.getTransaction().begin(); String sql = "from HibernateDemo.FamilyToSQL"; FamilyToSQL c = (FamilyToSQL)session.createQuery(sql).getSingleResult(); session.getTransaction().commit(); return c; } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); return null; } finally { session.close(); } } }
true
cb6f492f0e583465d43c6ca2f7a013c346737ea5
Java
scheshan/spring-cloud-extended
/eureka-server/src/main/java/com/heshan/cloud/eureka/server/ExtendedAutoConfiguration.java
UTF-8
1,765
1.875
2
[ "Apache-2.0" ]
permissive
package com.heshan.cloud.eureka.server; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClientConfig; import com.netflix.eureka.EurekaServerConfig; import com.netflix.eureka.registry.PeerAwareInstanceRegistry; import com.netflix.eureka.resources.ServerCodecs; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.netflix.eureka.server.InstanceRegistryProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; /** * ExtendedAutoConfiguration * * @author heshan * @date 2020/2/15 */ @Configuration public class ExtendedAutoConfiguration { @Bean public ExtendedEndpoint extendedEndpoint(ClientRequestManager clientRequestManager) { return new ExtendedEndpoint(clientRequestManager); } @Bean @Primary public PeerAwareInstanceRegistry registry(InstanceRegistryProperties instanceRegistryProperties, EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, ServerCodecs serverCodecs, EurekaClient eurekaClient) { return new ExtendedInstanceRegistry(serverConfig, clientConfig, serverCodecs, eurekaClient, instanceRegistryProperties.getExpectedNumberOfRenewsPerMin(), instanceRegistryProperties.getDefaultOpenForTrafficCount()); } @Bean public ClientRequestManager clientRequestManager(PeerAwareInstanceRegistry registry, ExtendedConfigBean config) { return new ClientRequestManager(registry, config); } @Bean @ConfigurationProperties(prefix = "extended.eureka-server") public ExtendedConfigBean extendedConfigBean() { return new ExtendedConfigBean(); } }
true
f2312966d269da701d7f3d9aabc9a0514356d43e
Java
eliashomsi/RestoApp-ECSE223
/RestoApp/src/ca/mcgill/ecse223/resto/controller/Controller.java
UTF-8
38,731
2.46875
2
[]
no_license
package ca.mcgill.ecse223.resto.controller; import java.awt.Rectangle; import java.sql.Time; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import ca.mcgill.ecse223.resto.application.RestoApplication; import ca.mcgill.ecse223.resto.model.Bill; import ca.mcgill.ecse223.resto.model.LoyaltyCard; import ca.mcgill.ecse223.resto.model.Menu; import ca.mcgill.ecse223.resto.model.MenuItem; import ca.mcgill.ecse223.resto.model.MenuItem.ItemCategory; import ca.mcgill.ecse223.resto.model.Order; import ca.mcgill.ecse223.resto.model.OrderItem; import ca.mcgill.ecse223.resto.model.PricedMenuItem; import ca.mcgill.ecse223.resto.model.Reservation; import ca.mcgill.ecse223.resto.model.RestoApp; import ca.mcgill.ecse223.resto.model.Seat; import ca.mcgill.ecse223.resto.model.Table; import ca.mcgill.ecse223.resto.model.Table.Status; import ca.mcgill.ecse223.resto.view.OrderView; import ca.mcgill.ecse223.resto.view.TableView; public class Controller { private RestoApp service; /** * constructor for the controller * * @param service * the model system */ public Controller(RestoApp service) { super(); this.service = service; } /** * This method adds a new table to the system * * @param number: * table number * @param x: * table location * @param y: * table location * @param width: * table width * @param length: * table length * @param numberOfSeats: * number of seats on that table * @return a new table view * * @throws InvalidInputException */ public TableView addTable(int number, int x, int y, int width, int length, int numberOfSeats) throws InvalidInputException { // check input if (x < 0 || y < 0) throw new InvalidInputException("one of the location parameters is negative"); if (number < 0) throw new InvalidInputException("table id cannot be negative"); if (width <= 0 || length <= 0) throw new InvalidInputException("dimensions of table cannot be negative"); if (numberOfSeats <= 0) throw new InvalidInputException("number of seats is zero or negative"); // check if another table has the same number for (Table t : service.getCurrentTables()) { if (t.getNumber() == number) throw new InvalidInputException("the table number already exists"); } Rectangle rect = new Rectangle(x, y, width, length); // check if the table clash for (Table t : service.getCurrentTables()) { if (tableOverLap(tableToRectangle(t), rect)) { throw new InvalidInputException("the table overlaps with another table"); } } // passed all checks Table newt = new Table(number, x, y, width, length, service); for (int i = 0; i < numberOfSeats; i++) { newt.addCurrentSeat(new Seat(newt)); } // add table to currentTable service.addCurrentTable(newt); // // HANI'S TESTER CODE // Order order = new Order(null, null, service, newt); // order.addOrderItem(4, new PricedMenuItem(100, service, new // MenuItem("4131chicken", service.getMenu())), // newt.getSeat(0)); // order.addOrderItem(4, new PricedMenuItem(50, service, new // MenuItem("81312burger", service.getMenu())), // newt.getSeat(1)); // order.addOrderItem(4, new PricedMenuItem(50, service, new // MenuItem("31123steak", service.getMenu())), // newt.getSeat(2)); // System.out.print("adding order was successful: " + newt.addOrder(order)); // service.addCurrentOrder(order); // for (Order o : newt.getOrders()) { // for (OrderItem oi : o.getOrderItems()) { // System.out.println(oi); // } // } // saving RestoApplication.save(); return convertToViewObject(newt); } /** * check if a reservation is near */ public static boolean isReservedNow(Table table) { // check if reserved if (table.getReservations().size() == 0) return false; // there is reservation check if any of them clash for (Reservation r : table.getReservations()) { final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); int hours = c.get(Calendar.HOUR_OF_DAY); int minutes = c.get(Calendar.MINUTE); // calendar eventDate object to hold day, month and year Calendar eventDate = Calendar.getInstance(); eventDate.set(year, month, day); // eventTime holds the number of milliseconds since the start of the day -- done // by converting hours and minutes to milliseconds long eventTime = hours * 3600000 + minutes * 60000; Time time = new Time(eventTime); if (r.doesOverlap(convertDate(eventDate.getTime()), time)) { // this.color = Color.GREEN; return true; } } return false; } /** * Checks if all tables are current * * @return true or false if table are not current */ public boolean checkIfTablesAreCurrent(List<Table> tables) { List<Integer> tableNumbers = this.getAllCurrentTableNumbers(); for (Table t : tables) if (!tableNumbers.contains(t.getNumber())) return false; return true; } /** * This method would add an order item to a list of seats * * @param quantity * the quantity must be strictly positive * @param o * the order that parents the order item * @param seats * the list of seats for that order item * @param i * the priced menuitem * @throws InvalidInputException * exceptions are thrown on different occasions. */ public void orderItem(int quantity, Order o, List<Seat> seats, PricedMenuItem i) throws InvalidInputException { // get restoapp RestoApp r = RestoApplication.getRestoApp(); // check for current tables in order if (!checkIfTablesAreCurrent(o.getTables())) throw new InvalidInputException("Some of the tables in the order are not current" + r.getCurrentTables().toString() + " " + o.getTables()); // checking quantity if (quantity <= 0) throw new InvalidInputException("quantity has to be > 0"); // checking for nulls if (o == null || seats == null || i == null) throw new InvalidInputException("Order or seat or menu item is null"); // check if all seats are contained in one of the tables if (!areSeatsInTables(seats, o.getTables())) { throw new InvalidInputException("One or more of the seats does not belong to a table of that order"); } // create the order item OrderItem orderItem = new OrderItem(quantity, i, o, seats.toArray(new Seat[seats.size()])); // adding the order item to all tables for (Seat s : seats) { s.getTable().addToOrderItem(orderItem, s); } // saving RestoApplication.save(); } public boolean areSeatsInTables(List<Seat> seats, List<Table> tables) { for (Seat s : seats) { boolean found = false; for (Table t : tables) { if (t.getCurrentSeats().contains(s)) { found = true; break; } } if (found == false) { return false; } } return true; } /** * Give a list of all tables views * * @return list of all table views */ public List<TableView> getAllCurrentTables() { List<TableView> tvs = new ArrayList<TableView>(); for (Table t : service.getCurrentTables()) { System.out.println(t.getNumber()); tvs.add(convertToViewObject(t)); } return tvs; } /** * Give a list of all Orders views * * @return list of all table views */ public List<OrderView> getAllCurrentOrders() { List<OrderView> orders = new ArrayList<OrderView>(); for (Order order : service.getCurrentOrders()) { if (order.getTables().size() == 0) continue; orders.add(convertToViewObject(order)); } return orders; } /** * Changing a table location * * @param number: * number of the table * @param newX: * new coordinates * @param newY: * new coordinates * @throws InvalidInputException * thrown when arguments are wrong or on overlap */ public void changeTableLocation(int number, int newX, int newY) throws InvalidInputException { if (newX < 0 || newY < 0) throw new InvalidInputException("negative coordinates"); Table found = null; for (Table t : service.getCurrentTables()) { if (t.getNumber() == number) { found = t; break; } } if (found == null) throw new InvalidInputException("table was not found"); // dimensions with the new location Rectangle rect = new Rectangle(newX, newY, found.getX(), found.getY()); // check for collision for (Table t : service.getCurrentTables()) { if (t == found) continue; if (tableOverLap(rect, tableToRectangle(t))) throw new InvalidInputException("table will collide with table number " + t.getNumber()); } // all good set new coordinates found.setX(newX); found.setY(newY); // saving RestoApplication.save(); } /** * returns a list of all table numbers * * @return an array of Integers */ public List<Integer> getAllTableNumbers() { List<Integer> list = new ArrayList<>(); for (Table t : service.getTables()) list.add(t.getNumber()); return list; } // corrected method public List<Integer> getAllCurrentTableNumbers() { List<Integer> list = new ArrayList<>(); for (Table t : service.getCurrentTables()) { list.add(t.getNumber()); System.out.println(t.getNumber()); } return list; } /** * get a table by number * * @param number * the number of the table * @return a table view object or null if not found */ public TableView getTableByNumber(int number) { for (Table t : service.getTables()) { if (t.getNumber() == number) return convertToViewObject(t); } return null; } /** CONVERSION METHODS **/ TableView convertToViewObject(Table t) { return new TableView(t); } OrderView convertToViewObject(Order t) { return new OrderView(t); } /** HELPER METHODS **/ /** * This method checks if two line segments specified by the starting point and * length do intersect or not * * @param first: * coordinate of the first point * @param firstWidth: * the length of the first line segment * @param second: * coordinate of the second point * @param secondWidth: * coordinate of the second line segment * @return boolean: overlap or not */ private boolean linearIntersection(double first, double firstWidth, double second, double secondWidth) { // make sure first is smaller if (first > second) { double tmp = first; first = second; second = tmp; tmp = firstWidth; firstWidth = secondWidth; secondWidth = tmp; } if (first + firstWidth > second) return true; return false; } /** * This method checks if two tables overlap or not * * @param rect1 * the first rectangle * @param rect2 * the second rectangle * @return boolean: overlap or not */ private boolean tableOverLap(Rectangle rect1, Rectangle rect2) { return linearIntersection(rect1.getX(), rect1.getWidth(), rect2.getX(), rect2.getWidth()) && linearIntersection(rect1.getY(), rect1.getHeight(), rect2.getY(), rect2.getHeight()); } private Rectangle tableToRectangle(Table t) { return new Rectangle(t.getX(), t.getY(), t.getWidth(), t.getLength()); } /** * Method for displaying the menu categories and the menu items */ public List<ItemCategory> getItemCategories() { ArrayList<ItemCategory> menuCategories = new ArrayList<ItemCategory>(); ItemCategory[] itemCategories = ItemCategory.values(); for (int i = 0; i < itemCategories.length; i++) { ItemCategory category = itemCategories[i]; menuCategories.add(category); } return menuCategories; } public ArrayList<MenuItem> getMenuItems(ItemCategory selectedItemCategory) throws InvalidInputException { ArrayList<MenuItem> categoryItemsList = new ArrayList<MenuItem>(); RestoApp restoApp = RestoApplication.getRestoApp(); for (MenuItem menuItem : restoApp.getMenu().getMenuItems()) { String error = ""; if (menuItem.getItemCategory() == null) { error = "This item does not belong to any category"; throw new InvalidInputException(error.trim()); } else if (menuItem.getItemCategory().equals(selectedItemCategory) && menuItem.hasCurrentPricedMenuItem()) { categoryItemsList.add(menuItem); } } return categoryItemsList; } public void updateTable(Table table, int newNumber, int numberOfSeats) throws InvalidInputException { if (table == null) throw new InvalidInputException("Wrong Input"); if (table.hasReservations()) throw new InvalidInputException("table has reservation"); if (numberOfSeats <= 0) throw new InvalidInputException("number of seats must be >= 0"); if (newNumber <= 0) throw new InvalidInputException("the id must be >= 0"); List<Order> currentOrders = service.getCurrentOrders(); for (Order t : currentOrders) { List<Table> tables = t.getTables(); if (tables.contains(table)) throw new InvalidInputException("Table has current orders"); } if (!table.setNumber(newNumber) && table.getNumber() != newNumber) throw new InvalidInputException("Duplicate number"); int currentNumberOfSeats = table.numberOfCurrentSeats(); for (int count = 0; count < numberOfSeats - currentNumberOfSeats; count++) { Seat seat = table.addSeat(); table.addCurrentSeat(seat); } for (int count = 0; count < currentNumberOfSeats - numberOfSeats; count++) { Seat seat = table.getCurrentSeat(0); table.removeCurrentSeat(seat); } RestoApplication.save(); } public void removeTable(int number) throws InvalidInputException { // retrieve table by its unique id Table foundTable = Table.getWithNumber(number); // if no table by specified id was found => throw exception if (foundTable == null) { throw new InvalidInputException("no such table exists"); } // table cannot be removed if it has reservations => throw exception if (foundTable.hasReservations()) { throw new InvalidInputException("cannot remove table due to existing reservations"); } List<Order> orders = service.getCurrentOrders(); List<Table> tables; // iterate through all orders to check if table is in use (has orders) => throw // exception for (Order order : orders) { tables = order.getTables(); if (tables.contains(foundTable)) throw new InvalidInputException("table contains orders"); } // remove table completely, temp solution service.removeCurrentTable(foundTable); RestoApplication.save(); } /** * public static void addMenuItem(String name, ItemCategory category, double * price) throws InvalidInputException this method adds a new * * @param name * of the new menu item * @param category * the category of the new menu item * @param price * the price of the new item */ public static void addMenuItem(String name, ItemCategory category, double price) throws InvalidInputException { RestoApp r = RestoApplication.getRestoApp(); Menu menu = r.getMenu(); if (price <= 0) throw new InvalidInputException("price must be positive"); if (name == null || name.length() == 0) throw new InvalidInputException("name is empty"); if (category == null) throw new InvalidInputException("category is null"); if (MenuItem.hasWithName(name) && !(MenuItem.getWithName(name).hasCurrentPricedMenuItem())) { PricedMenuItem pmi = MenuItem.getWithName(name).addPricedMenuItem(price, r); MenuItem.getWithName(name).setCurrentPricedMenuItem(pmi); } else { MenuItem menuItem = null; try { menuItem = new MenuItem(name, menu); } catch (RuntimeException e) { throw new InvalidInputException(e.getMessage()); } menuItem.setItemCategory(category); PricedMenuItem pmi = menuItem.addPricedMenuItem(price, r); menuItem.setCurrentPricedMenuItem(pmi); } RestoApplication.save(); } /** * this method starts an order to a list of tables * * @param tables * is the list of tables in question * @throws InvalidInputException * thorws exception on different error cases */ public static void startOrder(List<Table> tables) throws InvalidInputException { RestoApp service = RestoApplication.getRestoApp(); if (tables == null) throw new InvalidInputException("No tables given"); List<Table> currentTables = service.getCurrentTables(); for (Table t : tables) { boolean contains = currentTables.contains(t); if (contains == false) throw new InvalidInputException("Table given not in currentTables"); } boolean orderCreated = false; Order newOrder = null; for (Table t : tables) { if (orderCreated) { t.addToOrder(newOrder); } else { Order lastOrder = null; if (t.numberOfOrders() > 0) { lastOrder = t.getOrder(t.numberOfOrders() - 1); } t.startOrder(); if (t.numberOfOrders() > 0 && !t.getOrder(t.numberOfOrders() - 1).equals(lastOrder)) { orderCreated = true; newOrder = t.getOrder(t.numberOfOrders() - 1); } } } if (!orderCreated) { throw new InvalidInputException("The order couldn't be created"); } service.addCurrentOrder(newOrder); RestoApplication.save(); } /** * This method removes a menu item * * @param menuItem * the menuItem to be removed * @throws InvalidInputException * when something is wrong */ public static void removeMenuItem(MenuItem menuItem) throws InvalidInputException { if (menuItem == null) throw new InvalidInputException("menuItem is null"); boolean current = menuItem.hasCurrentPricedMenuItem(); if (!current) throw new InvalidInputException("menuItem does not have current priced menu item"); menuItem.setCurrentPricedMenuItem(null); RestoApplication.save(); } /** * Updates a menu item with the new name and category and price * * @param menuItem * the old menu item * @param name * the new name * @param category * the new category * @param price * the new price * @throws InvalidInputException * handles errors in input */ public static void updateMenuItem(MenuItem menuItem, String name, ItemCategory category, double price) throws InvalidInputException { if (price <= 0) throw new InvalidInputException("price must be positive"); if (name == null || name.length() == 0) throw new InvalidInputException("name is empty"); if (category == null) throw new InvalidInputException("category is null"); if (menuItem == null) throw new InvalidInputException("menuItem is null"); boolean current = menuItem.hasCurrentPricedMenuItem(); if (!current) throw new InvalidInputException("menuItem does not have current priced menu item"); boolean duplicate = menuItem.setName(name); if (!duplicate) throw new InvalidInputException("menuItem has duplicate name"); menuItem.setItemCategory(category); if (price != menuItem.getCurrentPricedMenuItem().getPrice()) { RestoApp r = RestoApplication.getRestoApp(); PricedMenuItem pmi = menuItem.addPricedMenuItem(price, r); menuItem.setCurrentPricedMenuItem(pmi); } RestoApplication.save(); } /** * add an orderItem to the order * * @param menuItem * which menu item * @param quantity * how many * @param seats * the list of seats that would share the order item * @throws InvalidInputException * when input is wrong */ public static void orderMenuItem(MenuItem menuItem, int quantity, List<Seat> seats) throws InvalidInputException { if (seats == null || seats.size() == 0) throw new InvalidInputException("seats are empty or null"); if (quantity <= 0) throw new InvalidInputException("quantity should be positive"); if (menuItem == null) throw new InvalidInputException("menuItem is null"); RestoApp r = RestoApplication.getRestoApp(); boolean current = menuItem.hasCurrentPricedMenuItem(); if (!current) throw new InvalidInputException("menuItem does not have current priced menu item"); List<Table> currentTables = r.getCurrentTables(); Order lastOrder = null; for (Seat seat : seats) { Table table = seat.getTable(); boolean currentTable = currentTables.contains(table); if (!currentTable) throw new InvalidInputException("one of the seats has non-current table"); if (!table.getCurrentSeats().contains(seat)) throw new InvalidInputException("Seat is not current"); // alt if (lastOrder == null) { if (table.numberOfOrders() > 0) { lastOrder = table.getOrder(table.numberOfOrders() - 1); } else { throw new InvalidInputException("There are no orders on table id :" + table.getNumber()); } } else { Order comparedOrder = null; if (table.numberOfOrders() > 0) { comparedOrder = table.getOrder(table.numberOfOrders() - 1); } else { throw new InvalidInputException("There are no orders on table id :" + table.getNumber()); } if (!comparedOrder.equals(lastOrder)) { throw new InvalidInputException("Compared order with last order mismatch"); } } } if (lastOrder == null) { throw new InvalidInputException("no order was found on the seats"); } // pmi PricedMenuItem pmi = menuItem.getCurrentPricedMenuItem(); boolean itemCreated = false; OrderItem newItem = null; for (Seat seat : seats) { Table table = seat.getTable(); if (itemCreated) { table.addToOrderItem(newItem, seat); } else { OrderItem lastitem = null; if (lastOrder.numberOfOrderItems() > 0) { lastitem = lastOrder.getOrderItem(lastOrder.numberOfOrderItems() - 1); } // create order item table.orderItem(quantity, lastOrder, seat, pmi); if (lastOrder.numberOfOrderItems() > 0 && !lastOrder.getOrderItem(lastOrder.numberOfOrderItems() - 1).equals(lastitem)) { itemCreated = true; newItem = lastOrder.getOrderItem(lastOrder.numberOfOrderItems() - 1); } } } if (!itemCreated) { throw new InvalidInputException("could not create order item successfully"); } RestoApplication.save(); } /** * overloaded method in case the name of the item was specified instead of the * item itself * * @param menuItem * @param quantity * @param seats * @throws InvalidInputException */ public static void orderMenuItem(String menuItem, int quantity, List<Seat> seats) throws InvalidInputException { if (menuItem == null || menuItem.length() == 0) throw new InvalidInputException("the name is null or empty"); MenuItem mi = MenuItem.getWithName(menuItem); if (mi == null) throw new InvalidInputException("menuItem was not found"); orderMenuItem(mi, quantity, seats); } public static List<String> getAListOfAllEmails() { RestoApp r = RestoApplication.getRestoApp(); List<String> list = new ArrayList<String>(); for (LoyaltyCard card : r.getLoyaltyCards()) list.add(card.getEmailAddress()); return list; } /** * This methods end an order * * @param order * the order * @param email * the email address which would have the points * @throws InvalidInputException */ private static java.sql.Date convertDate(java.util.Date utilDate) { return new java.sql.Date(utilDate.getTime()); // java.util.Calendar cal = Calendar.getInstance(); // cal.setTime(utilDate); // cal.set(Calendar.HOUR_OF_DAY, 0); // cal.set(Calendar.MINUTE, 0); // cal.set(Calendar.SECOND, 0); // cal.set(Calendar.MILLISECOND, 0); // java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime()); // your // sql date // return sqlDate; } public static void endOrder(Order order, String emailAddress) throws InvalidInputException { RestoApp service = RestoApplication.getRestoApp(); List<Order> currentOrders = service.getCurrentOrders(); LoyaltyCard foundCard = null; if (order == null) { throw new InvalidInputException("Order is null"); } if (!currentOrders.contains(order)) { throw new InvalidInputException("Order being ended does not exist"); } if (!checkIfStringEmptyOrNull(emailAddress)) { boolean hasCard = LoyaltyCard.hasWithEmailAddress(emailAddress); if (!hasCard) { throw new InvalidInputException("Loyalty card with entered email address does not exist."); } else { foundCard = LoyaltyCard.getWithEmailAddress(emailAddress); } } // creating a new list (professor hint) List<Table> tables = new ArrayList<Table>(); for (Table t : order.getTables()) { tables.add(t); } // adding points for (int i = 0; i < tables.size(); i++) { Table table = tables.get(i); if (table != null && table.numberOfOrders() > 0 && table.getOrder(table.numberOfOrders() - 1).equals(order) && !checkIfStringEmptyOrNull(emailAddress)) { foundCard.addOrder(order); } } Controller.calculatePoints(foundCard); // ending orders for (int i = 0; i < tables.size(); i++) { Table table = tables.get(i); if (table != null && table.numberOfOrders() > 0 && table.getOrder(table.numberOfOrders() - 1).equals(order) && !checkIfStringEmptyOrNull(emailAddress)) { table.endOrder(order); } } if (allTablesAvailableOrDifferentCurrentOrder(tables, order) && !checkIfStringEmptyOrNull(emailAddress)) service.removeCurrentOrder(order); RestoApplication.save(); } /** * This methods end an order * * @param order * the order * @param email * the email address which would have the points * @throws InvalidInputException */ public static void endOrder(Order order) throws InvalidInputException { RestoApp service = RestoApplication.getRestoApp(); List<Order> currentOrders = service.getCurrentOrders(); if (order == null) { throw new InvalidInputException("Order is null"); } if (!currentOrders.contains(order)) { throw new InvalidInputException("Order being ended does not exist"); } // creating a new list (professor hint) List<Table> tables = new ArrayList<Table>(); for (Table t : order.getTables()) { tables.add(t); } // ending orders for (int i = 0; i < tables.size(); i++) { Table table = tables.get(i); if (table != null && table.numberOfOrders() > 0 && table.getOrder(table.numberOfOrders() - 1).equals(order)) { table.endOrder(order); } } if (allTablesAvailableOrDifferentCurrentOrder(tables, order)) service.removeCurrentOrder(order); RestoApplication.save(); } /** * helper method * * @param tables * @param order * @return */ public static boolean allTablesAvailableOrDifferentCurrentOrder(List<Table> tables, Order order) { boolean result = false; for (Table table : tables) { if (table.getStatus() == Status.Available || !table.getOrder(table.numberOfOrders() - 1).equals(order)) { result = true; } } return result; } /** * this method does reservation * * @param date * @param time * @param numberInParty * @param contactName * @param contactEmailAddress * @param contactPhoneNumber * @param tables * @throws Exception */ public static void reserve(Date date, Time time, int numberInParty, String contactName, String contactEmailAddress, String contactPhoneNumber, List<Table> tables) throws Exception { // check for date and time for null values if (date == null || time == null) { throw new InvalidInputException("date/time values might be null"); } if (checkIfStringEmptyOrNull(contactName)) { throw new InvalidInputException("contact name is empty or null"); } if (checkIfStringEmptyOrNull(contactEmailAddress)) { throw new InvalidInputException("contactEmailAddress is empty or null"); } if (!isValidEmailAddress(contactEmailAddress)) { throw new InvalidInputException("email format is wrong"); } if (!isValidPhoneNumber(contactPhoneNumber)) throw new InvalidInputException("phone should be 10 digits 5149393333"); // checks for negative quantity if (numberInParty < 0) { throw new InvalidInputException("negative quantity"); } // adds all strings to a list of input to be validated List<String> inputs = new ArrayList<>(); inputs.add(contactName); inputs.add(contactEmailAddress); inputs.add(contactPhoneNumber); // checks a list of input for an empty/null Strings checkInput(inputs); RestoApp restoApp = RestoApplication.getRestoApp(); int seatCapacity = 0; List<Table> currentTables = restoApp.getCurrentTables(); for (Table table : tables) { if (!currentTables.contains(table)) { throw new InvalidInputException("table is not current table parameter"); } seatCapacity += table.numberOfCurrentSeats(); List<Reservation> reservations = table.getReservations(); for (Reservation reservation : reservations) { if (reservation.doesOverlap(convertDate(date), time)) { throw new InvalidInputException("time/date overlap"); } } } if (seatCapacity < numberInParty) { throw new InvalidInputException("seat capactiy is less than the number in party"); } new Reservation(new java.sql.Date(date.getTime()), time, numberInParty, contactName, contactEmailAddress, contactPhoneNumber, restoApp, tables.toArray(new Table[tables.size()])); RestoApplication.save(); } /** * this method checks input * * @param inputs * @throws InvalidInputException */ private static void checkInput(List<String> inputs) throws InvalidInputException { for (String input : inputs) { if (input == null || input.length() == 0) throw new InvalidInputException("null or empty values"); } } public PricedMenuItem getPricedMenuItem(String name) throws InvalidInputException { for (PricedMenuItem m : this.service.getPricedMenuItems()) { if (m.getMenuItem().getName().equals(name)) { return m; } } throw new InvalidInputException("Priced Menu Item " + name + " was not found"); } /** * this method would get a list of all order items * * @param table * @return a list of all order items * @throws InvalidInputException * in case of wrong input */ public List<OrderItem> getOrderItems(Table table) throws InvalidInputException { if (table == null) throw new InvalidInputException("the table is null"); RestoApp r = RestoApplication.getRestoApp(); if (!r.getCurrentTables().contains(table)) { throw new InvalidInputException("the table is not current"); } if (table.getStatus() == Status.Available) { throw new InvalidInputException("the table should not be availble"); } Order lastOrder = null; if (table.numberOfOrders() > 0) { lastOrder = table.getOrder(table.numberOfOrders() - 1); } else { throw new InvalidInputException("table has no orders"); // should never be thrown } List<Seat> currentSeats = table.getCurrentSeats(); List<OrderItem> result = new ArrayList<OrderItem>(); for (Seat seat : currentSeats) { List<OrderItem> orderitems = seat.getOrderItems(); for (OrderItem orderitem : orderitems) { Order order = orderitem.getOrder(); if (lastOrder.equals(order) && !result.contains(orderitem)) result.add(orderitem); } } return result; } public static void issueBill(List<Seat> seats) throws InvalidInputException { RestoApp r = RestoApplication.getRestoApp(); if (seats == null || seats.size() == 0) { throw new InvalidInputException("seats are empty or null"); } Order lastOrder = null; List<Table> currentTables = r.getCurrentTables(); for (Seat seat : seats) { if (!currentTables.contains(seat.getTable())) { throw new InvalidInputException("one of the seats belong to non-current table"); } Table table = seat.getTable(); if (!table.getCurrentSeats().contains(seat)) { throw new InvalidInputException("one of the seats is not current"); } if (lastOrder == null) { if (table.numberOfOrders() > 0) { lastOrder = table.getOrder(table.numberOfOrders() - 1); } else { throw new InvalidInputException("table has no orders"); } } else { Order comparedOrder = null; if (table.numberOfOrders() > 0) { comparedOrder = table.getOrder(table.numberOfOrders() - 1); } else { throw new InvalidInputException("There are no orders on table id :" + table.getNumber()); } if (!comparedOrder.equals(lastOrder)) { throw new InvalidInputException("Compared order with last order mismatch"); } } } if (lastOrder == null) throw new InvalidInputException("order was not found to issue the bill"); boolean billCreated = false; Bill newBill = null; for (Seat seat : seats) { Table table = seat.getTable(); if (billCreated) { table.addToBill(newBill, seat); } else { Bill lastBill = null; if (lastOrder.numberOfBills() > 0) lastBill = lastOrder.getBill(lastOrder.numberOfBills() - 1); table.billForSeat(lastOrder, seat); if (lastOrder.numberOfBills() > 0 && !lastOrder.getBill(lastOrder.numberOfBills() - 1).equals(lastBill)) { billCreated = true; newBill = lastOrder.getBill(lastOrder.numberOfBills() - 1); } } } if (!billCreated) throw new InvalidInputException("bill was not created successfully"); RestoApplication.save(); } /** * this method cancel an order item * * @param orderItem * which order item to cancel * @throws InvalidInputException * in case input is wrong */ public void cancelOrderItem(OrderItem orderItem) throws InvalidInputException { if (orderItem == null) { throw new InvalidInputException("orderitem is null"); } List<Seat> seats = orderItem.getSeats(); Order order = orderItem.getOrder(); List<Table> tables = new ArrayList<Table>(); for (Seat s : seats) { Table table = s.getTable(); Order lastOrder = null; if (table.numberOfOrders() > 0) { lastOrder = table.getOrder(table.numberOfOrders() - 1); } else { throw new InvalidInputException("This table has 0 orders (should never be thrown)"); } if (lastOrder.equals(order) && !tables.contains(table)) { tables.add(table); } } for (Table t : tables) { t.cancelOrderItem(orderItem); } RestoApplication.save(); } /** * this method cancels an order * * @param table * the table to cancel the order on * @throws InvalidInputException */ public void cancelOrder(Table table) throws InvalidInputException { if (table == null) throw new InvalidInputException("Table is null"); RestoApp r = RestoApplication.getRestoApp(); List<Table> currentTables = r.getCurrentTables(); boolean current = currentTables.contains(table); if (!current) { throw new InvalidInputException("Table does not exist as a current table"); } table.cancelOrder(); RestoApplication.save(); } /** * returns a list of loyalty cards * * @return list */ public List<LoyaltyCard> displayLoyaltyCards() { List<LoyaltyCard> cards = service.getLoyaltyCards(); return cards; } /** * registers loyalty cards * * @param clientName * name * @param phoneNumber * * @param emailAddress * @throws InvalidInputException */ public void registerLoyaltyCard(String clientName, String phoneNumber, String emailAddress) throws InvalidInputException { boolean hasLoyaltyCard = LoyaltyCard.hasWithEmailAddress(emailAddress); if (hasLoyaltyCard == true) { throw new InvalidInputException("Loyalty card with entered email already exists."); } else if (checkIfStringEmptyOrNull(clientName)) { throw new InvalidInputException("Please enter client name."); } else if (checkIfStringEmptyOrNull(phoneNumber)) { throw new InvalidInputException("Please enter client phone number."); } else if (checkIfStringEmptyOrNull(emailAddress)) { throw new InvalidInputException("Please enter client email address."); } else if (!isValidEmailAddress(emailAddress)) { throw new InvalidInputException("non-valid email address <>@<>.<>"); } else if (!isValidPhoneNumber(phoneNumber)) { throw new InvalidInputException("non-valid phone number must be 10 digits example: 5149903943"); } else { service.addLoyaltyCard(0.00, clientName, phoneNumber, emailAddress); RestoApplication.save(); } } private static boolean checkIfStringEmptyOrNull(String str) { return (str == null || str.length() == 0); } /** * checks for valid email * * @param email * @return */ private static boolean isValidEmailAddress(String email) { String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern); java.util.regex.Matcher m = p.matcher(email); return m.matches(); } /** * checks for valid phone number * * @param phone * @return */ private static boolean isValidPhoneNumber(String phone) { if (phone.length() != 10) return false; for (int i = 0; i < 10; i++) { if (!Character.isDigit(phone.charAt(i))) return false; } return true; } /** * remove a loyalty card using email * * @param emailAddress * @throws InvalidInputException */ public void removeExistingLoyaltyCard(String emailAddress) throws InvalidInputException { LoyaltyCard selectedCard = LoyaltyCard.getWithEmailAddress(emailAddress); if (selectedCard == null) throw new InvalidInputException("card was not found"); selectedCard.delete(); RestoApplication.save(); } /** * calculate the points for the loyalty card * * @param aCard * @return */ public static void calculatePoints(LoyaltyCard aCard) { List<Order> allOrders = aCard.getOrders(); Double price = aCard.getPoint(); for (Order aOrder : allOrders) { List<OrderItem> orderItems = aOrder.getOrderItems(); for (OrderItem orderItem : orderItems) price += orderItem.getPricedMenuItem().getPrice() * orderItem.getQuantity(); } aCard.setPoint(price); RestoApplication.save(); } public static List<Table> getAllTableObject() { // TODO Auto-generated method stub RestoApp r = RestoApplication.getRestoApp(); return r.getCurrentTables(); } /** * checks if a new reservation on that time and date is available * * @param table * @param date * @param time * @return */ public static boolean TableAvaialbeOnTimeAndDate(Table table, Date date, Time time, int set) { for (Reservation r : table.getReservations()) { if (table.getCurrentSeats().size() <set || r.doesOverlap(convertDate(date), time)) return false; } return true; } }
true
df5ecd31d78a98ab93f682e7e1c0e7736a21fa5d
Java
VadimGuryanov/Spring-Boot-Semestrovka
/src/main/java/ru/itis/springboothomework/models/CovidData.java
UTF-8
6,566
2.171875
2
[]
no_license
package ru.itis.springboothomework.models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; public class CovidData { @JsonProperty("updated") private long updated; @JsonProperty("country") private String country; @JsonProperty("countryInfo") private CountryInfo countryInfo; @JsonProperty("cases") private long cases; @JsonProperty("todayCases") private long todayCases; @JsonProperty("deaths") private long deaths; @JsonProperty("todayDeaths") private long todayDeaths; @JsonProperty("recovered") private long recovered; @JsonProperty("active") private long active; @JsonProperty("critical") private long critical; @JsonProperty("casesPerOneMillion") private long casesPerOneMillion; @JsonProperty("deathsPerOneMillion") private long deathsPerOneMillion; @JsonProperty("tests") private long tests; @JsonProperty("testsPerOneMillion") private long testsPerOneMillion; @JsonProperty("continent") private String continent; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CovidData covidData = (CovidData) o; return updated == covidData.updated && cases == covidData.cases && todayCases == covidData.todayCases && deaths == covidData.deaths && todayDeaths == covidData.todayDeaths && recovered == covidData.recovered && active == covidData.active && critical == covidData.critical && casesPerOneMillion == covidData.casesPerOneMillion && deathsPerOneMillion == covidData.deathsPerOneMillion && tests == covidData.tests && testsPerOneMillion == covidData.testsPerOneMillion && Objects.equals(country, covidData.country) && Objects.equals(countryInfo, covidData.countryInfo) && Objects.equals(continent, covidData.continent); } @Override public int hashCode() { return Objects.hash(updated, country, countryInfo, cases, todayCases, deaths, todayDeaths, recovered, active, critical, casesPerOneMillion, deathsPerOneMillion, tests, testsPerOneMillion, continent); } public long getUpdated() { return updated; } public void setUpdated(long updated) { this.updated = updated; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public CountryInfo getCountryInfo() { return countryInfo; } public void setCountryInfo(CountryInfo countryInfo) { this.countryInfo = countryInfo; } public long getCases() { return cases; } public void setCases(long cases) { this.cases = cases; } public long getTodayCases() { return todayCases; } public void setTodayCases(long todayCases) { this.todayCases = todayCases; } public long getDeaths() { return deaths; } public void setDeaths(long deaths) { this.deaths = deaths; } public long getTodayDeaths() { return todayDeaths; } public void setTodayDeaths(long todayDeaths) { this.todayDeaths = todayDeaths; } public long getRecovered() { return recovered; } public void setRecovered(long recovered) { this.recovered = recovered; } public long getActive() { return active; } public void setActive(long active) { this.active = active; } public long getCritical() { return critical; } public void setCritical(long critical) { this.critical = critical; } public long getCasesPerOneMillion() { return casesPerOneMillion; } public void setCasesPerOneMillion(long casesPerOneMillion) { this.casesPerOneMillion = casesPerOneMillion; } public long getDeathsPerOneMillion() { return deathsPerOneMillion; } public void setDeathsPerOneMillion(long deathsPerOneMillion) { this.deathsPerOneMillion = deathsPerOneMillion; } public long getTests() { return tests; } public void setTests(long tests) { this.tests = tests; } public long getTestsPerOneMillion() { return testsPerOneMillion; } public void setTestsPerOneMillion(long testsPerOneMillion) { this.testsPerOneMillion = testsPerOneMillion; } public String getContinent() { return continent; } public void setContinent(String continent) { this.continent = continent; } } class CountryInfo { @JsonProperty("_id") private long _id; @JsonProperty("iso2") private String iso2; @JsonProperty("iso3") private String iso3; @JsonProperty("lat") private long lat; @JsonProperty("long") private int _long; @JsonProperty("flag") private String flag; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CountryInfo that = (CountryInfo) o; return _id == that._id && lat == that.lat && _long == that._long && Objects.equals(iso2, that.iso2) && Objects.equals(iso3, that.iso3) && Objects.equals(flag, that.flag); } @Override public int hashCode() { return Objects.hash(_id, iso2, iso3, lat, _long, flag); } public long get_id() { return _id; } public void set_id(long _id) { this._id = _id; } public String getIso2() { return iso2; } public void setIso2(String iso2) { this.iso2 = iso2; } public String getIso3() { return iso3; } public void setIso3(String iso3) { this.iso3 = iso3; } public long getLat() { return lat; } public void setLat(long lat) { this.lat = lat; } public int get_long() { return _long; } public void set_long(int _long) { this._long = _long; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } }
true