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
0274d5591b2ed122eef0353300dcdfd1d22c7a35
Java
Mohamed-Abdelhamed/ticketing-support-system
/src/Ticket/SolvedTicket.java
UTF-8
379
2.140625
2
[]
no_license
package Ticket; import ticketingsystem.Date; public class SolvedTicket { protected Date TimeTakenToBeSolved; public Date getTimeTakenToBeSolved() { return TimeTakenToBeSolved; } public void setTimeTakenToBeSolved(Date TimeTakenToBeSolved) { this.TimeTakenToBeSolved = TimeTakenToBeSolved; } public void SolvedTickets(){ } }
true
d7b6d219a3276c71fe10b9f0e783fa640f867f16
Java
ArtursKuzmiks/SpringStudy
/src/main/java/com/example/Tests/Example2/App.java
UTF-8
2,778
2.90625
3
[ "MIT" ]
permissive
package com.example.Tests.Example2; import com.example.Tests.Example2.ApplicationConfig.AppConfig; import com.example.Tests.Example2.Service.CustomerService; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Artur Kuzmik on 18.29.5 */ public class App { public static void main(String[] args) throws IOException { AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); CustomerService customerService = context.getBean(CustomerService.class); int menu; System.out.println("Menu"); System.out.println("1: Check the table"); System.out.println("2: Add customer"); System.out.println("3: Remote customer"); System.out.println("4: Correct data"); System.out.println("5: Sort by order date and Surname"); System.out.println("6: Debtors list"); System.out.println("7: Cost of all orders"); System.out.println("0: END"); try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { loop: for (; ; ) { System.out.print("\nInput: "); menu = Integer.parseInt(br.readLine()); switch (menu) { case 1: customerService.printCustomers(); break; case 2: customerService.addCustomer(); customerService.printCustomers(); break; case 3: customerService.deleteCustomer(); customerService.printCustomers(); break; case 4: customerService.editCustomer(); break; case 5: customerService.sortDateSurname(); break; case 6: customerService.debtors(); break; case 7: customerService.allPrice(); break; case 0: System.out.println("The work is finished."); break loop; default: System.out.print("There is no such option, try again.\n"); break; } } } catch (IllegalArgumentException e) { System.out.println("Input error"); } } }
true
beff03e01d1d85823867765702d599443bc864de
Java
DevelopmentOnTheEdge/be5
/server/src/main/java/com/developmentontheedge/be5/server/authentication/rememberme/InvalidCookieException.java
UTF-8
240
1.875
2
[]
no_license
package com.developmentontheedge.be5.server.authentication.rememberme; public class InvalidCookieException extends RememberMeAuthenticationException { public InvalidCookieException(String message) { super(message); } }
true
357b737dcabe1bd34f4eb7d640a61729cfe0f99f
Java
umesh-lewa/cg-training-java
/Day_3/BasicsLabBook/src/labbook2/Q4.java
UTF-8
937
3.578125
4
[]
no_license
package labbook2; public class Q4 { public static void main(String[] args) { Q4 obj1 = new Q4(); Stack obj = new Stack(5); obj.insert(123); obj.insert(56); obj.insert(34); obj.display(); obj.remove(); obj.remove(); obj.display(); } } class Stack { private int arr[]; private int top; private int len; Stack(int limit){ this.arr = new int[limit]; this.top = -1; this.len = limit; } public int insert(int num) { if(!isFull()) { top++; this.arr[top] = num; return 1; } return 0; } public int remove() { if(!isEmpty()) { int num = arr[top]; top--; return num; } return -1; } public int length() { return top + 1; } public Boolean isEmpty() { return top == -1; } public Boolean isFull() { return top == len - 1; } public void display() { for(int i = 0; i <= this.top; i++) { System.out.println(this.arr[i]); } } }
true
392bc44068df6295ee304cf10010a902d7399622
Java
Razarion/razarion
/razarion-ui-service/src/test/java/com/btxtech/uiservice/cdimock/TestInventoryUiService.java
UTF-8
527
1.890625
2
[]
no_license
package com.btxtech.uiservice.cdimock; import com.btxtech.shared.dto.InventoryInfo; import com.btxtech.uiservice.inventory.InventoryUiService; import javax.enterprise.context.ApplicationScoped; import java.util.function.Consumer; /** * Created by Beat * on 09.11.2017. */ @ApplicationScoped public class TestInventoryUiService extends InventoryUiService { @Override protected void loadServerInventoryInfo(Consumer<InventoryInfo> inventoryInfoConsumer) { throw new UnsupportedOperationException(); } }
true
bc78ead0feff3209f33d1b55a44eebd4cd67740b
Java
yacovyi/kafka-error-handler
/src/main/java/com/ws/ng/kafkaerrorhandler/model/IcdEntity.java
UTF-8
240
1.945313
2
[]
no_license
package com.ws.ng.kafkaerrorhandler.model; public class IcdEntity { private String wsType; public String getWsType() { return wsType; } public void setWsType(String wsType) { this.wsType = wsType; } }
true
d62afa437dc43ec538a08eca72ac7026d8755339
Java
DhanashreeC/LibraryManagementSystem
/OnlineLibraryManagementSystem/src/main/java/com/my/onlinelibrary/exception/UserException.java
UTF-8
283
2.3125
2
[]
no_license
package com.my.onlinelibrary.exception; public class UserException extends Exception{ public UserException(String message) { super("LibrarianException-"+message); } public UserException(String message, Throwable cause) { super("LibrarianException-"+message,cause); } }
true
42c193938c20b2ea63569acccece3cedf05617d1
Java
battleground/storm-mobile
/app/src/main/java/com/baofeng/mobile/network2/VideoClient.java
UTF-8
1,814
1.976563
2
[ "Apache-2.0" ]
permissive
package com.baofeng.mobile.network2; import com.baofeng.mobile.bean.FilterBean; import com.baofeng.mobile.bean.Page; import com.baofeng.mobile.bean.Status; import com.baofeng.mobile.bean.Video; import com.loopj.android.http.RequestParams; import java.util.List; /** * 影库 */ public class VideoClient extends ApiClient { /** * 获取指定圈子下的视频列表 * * @param category 分类 * @param type 筛选 类型 * @param area 筛选 地区 * @param year 筛选 年限 * @param sort 筛选 排序 * @param page 页数 * @param pageSize 每页数量 * @param handler 回调 */ public void getVideoList(String category, String sort, String type, String area, String year, int page, int pageSize, final JsonResponseHandler<Status<Page<Video>>> handler, final Object tag) { RequestParams params = getRequestParams(); params.put(Params.METHOD, "me2.video.list"); params.put("category", category); putNotNull(params, "tag", type); putNotNull(params, "area", area); putNotNull(params, "year", year); putNotNull(params, "sort", sort); params.put("page", page); params.put("pageSize", pageSize); params.put("extend", "name,category,cover,dbscore,isend,unum,resolution"); post(params, handler); } /** * 获取筛选类型 * * @param httpHandler */ public void getVideoFilter(JsonResponseHandler<Status<List<FilterBean>>> httpHandler) { RequestParams params = getRequestParams(); params.put(Params.METHOD, "me2.video.category"); params.put("ysort", 2); params.put(Params.EXTEND, "tags,areas,years"); post(params, httpHandler); } }
true
ab377ca03f118cd51953cd4ecda6c71b27a49ff8
Java
marzenakulikowska/warehousing-app
/src/main/java/pl/coderslab/StoragePlace.java
UTF-8
1,593
2.421875
2
[]
no_license
package pl.coderslab; import org.hibernate.validator.constraints.Range; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import java.util.ArrayList; import java.util.List; @Entity @Table(name ="storagePlace") public class StoragePlace { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank @Pattern(regexp ="[A|B|C|D|E|F|G]") private String column; @Pattern(regexp = "[0|1|2|3]") private String level; @Range(min = 1, max = 19) private int place; @Pattern(regexp = "[TAK|NIE]") private String available; @OneToMany(mappedBy = "storagePlace") private List<Cargo> cargoList = new ArrayList<>(); public List<Cargo> getCargoList() { return cargoList; } public void setCargoList(List<Cargo> cargoList) { this.cargoList = cargoList; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getColumn() { return column; } public void setColumn(String column) { this.column = column; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public int getPlace() { return place; } public void setPlace(int place) { this.place = place; } public String getAvailable() {return available;} public void setAvailable(String available) { this.available = available; } }
true
9262d702d41e8666c1ed0d1969ea0c71a6d85a00
Java
rayhan-ferdous/code2vec
/codebase/selected/seltrans/1262093.java
UTF-8
4,205
1.8125
2
[]
no_license
package com . tysanclan . site . projectewok . entities ; import java . util . Arrays ; import java . util . Date ; import javax . persistence . * ; import org . hibernate . annotations . AccessType ; import org . hibernate . annotations . Cache ; import org . hibernate . annotations . Index ; import com . jeroensteenbeeke . hyperion . data . DomainObject ; @ Entity @ AccessType ( "field" ) @ Cache ( usage = org . hibernate . annotations . CacheConcurrencyStrategy . TRANSACTIONAL , region = "main" ) public class BattleNetUserPresence implements DomainObject { public static final long serialVersionUID = 1L ; public static final int USER_BLIZZREP = 0x01 ; public static final int USER_CHANNELOP = 0x02 ; public static final int USER_SPEAKER = 0x04 ; public static final int USER_ADMIN = 0x08 ; public static final int USER_NOUDP = 0x10 ; public static final int USER_SQUELCHED = 0x20 ; public static final int USER_GUEST = 0x40 ; private static final String [ ] KNOWN_CLIENTS = { "LTRD" , "VD2D" , "PX2D" , "PXES" , "RATS" , "NB2W" , "PX3W" , "3RAW" } ; public static enum SpecialType { SERVER_ADMIN ( "bnet-battlenet.gif" , USER_ADMIN ) , BLIZZREP ( "bnet-blizzard.gif" , USER_BLIZZREP ) , OPERATOR ( "bnet-channelops.gif" , USER_CHANNELOP ) , SPEAKER ( "bnet-speaker.gif" , USER_SPEAKER ) , SQUELCHED ( "bnet-squelch.gif" , USER_SQUELCHED ) , NONE ( null , 0x0 ) ; private final String image ; private final int requiredFlag ; private SpecialType ( String image , int requiredFlag ) { this . image = image ; this . requiredFlag = requiredFlag ; } public String getImage ( ) { return image ; } public static SpecialType get ( int flags ) { for ( SpecialType type : values ( ) ) { if ( ( type . requiredFlag & flags ) == type . requiredFlag ) { return type ; } } return NONE ; } } @ Id @ GeneratedValue ( strategy = GenerationType . SEQUENCE , generator = "BattleNetUserPresence" ) @ SequenceGenerator ( name = "BattleNetUserPresence" , sequenceName = "SEQ_ID_BattleNetUserPresence" ) private Long id ; @ ManyToOne ( optional = false , fetch = FetchType . LAZY ) @ Index ( name = "IDX_BattleNetUserPresence_Channel" ) private BattleNetChannel channel ; @ Column ( nullable = false ) private String username ; @ Column ( nullable = false ) @ Enumerated ( EnumType . STRING ) private SpecialType specialType ; @ Column ( nullable = false ) private String client ; @ Column ( nullable = false ) private Date lastUpdate ; public BattleNetUserPresence ( ) { } @ Override public Long getId ( ) { return this . id ; } public void setId ( Long id ) { this . id = id ; } public BattleNetChannel getChannel ( ) { return channel ; } public void setChannel ( BattleNetChannel channel ) { this . channel = channel ; } public String getUsername ( ) { return username ; } public void setUsername ( String username ) { this . username = username ; } public SpecialType getSpecialType ( ) { return specialType ; } public void setSpecialType ( SpecialType specialType ) { this . specialType = specialType ; } public String getClient ( ) { return client ; } public void setClient ( String client ) { this . client = client ; } public Date getLastUpdate ( ) { return lastUpdate ; } public void setLastUpdate ( Date lastUpdate ) { this . lastUpdate = lastUpdate ; } public static boolean isKnownClient ( String client2 ) { return Arrays . asList ( KNOWN_CLIENTS ) . contains ( client2 ) ; } }
true
91d4e3085021071706c5b8ce4a5e70caa15477b6
Java
harriks/camel-dubbo
/src/main/java/com/gateway/dubbo/config/RouteContainer.java
UTF-8
12,442
1.679688
2
[]
no_license
package com.gateway.dubbo.config; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.gateway.dubbo.camel.DubboCamelComponent; import com.gateway.dubbo.camel.InterfaceInfo; import com.gateway.dubbo.camel.InterfaceRegistry; import com.gateway.dubbo.entity.ConnectorDubboParameterEntity; import com.gateway.dubbo.entity.ConnectorDubboRouteEntity; import com.gateway.dubbo.processor.DefaultInProcessor; import com.gateway.dubbo.processor.ExceptionProcessor; import com.gateway.dubbo.service.ConnectorDubboParameterService; import com.gateway.dubbo.service.ConnectorDubboRouteService; import com.gateway.dubbo.util.SourceCreator; import com.gateway.dubbo.util.TemplateInfo; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.camel.CamelContext; import org.apache.camel.Route; import org.apache.camel.builder.RouteBuilder; import org.apache.dubbo.common.compiler.support.JdkCompiler; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * camel容器配置信息 */ @Data @Slf4j @Component @EnableScheduling public class RouteContainer implements InitializingBean { @Autowired private CamelContext camelContext; private InterfaceRegistry registry = InterfaceRegistry.getInstance(); @Autowired private ConnectorDubboRouteService routeService; @Autowired private ConnectorDubboParameterService parameterService; //缓存类信息 private Map<String,TemplateInfo> cache = new ConcurrentHashMap<>(); @Autowired private DefaultInProcessor inProcessor; @Autowired private ExceptionProcessor exceptionProcessor; @Autowired private DubboServiceConfig dubboServiceConfig; @Autowired private SourceCreator sourceCreator; private Map<String,Integer> retries = new HashMap<>(); private final static String dubboSchema = "dubbo://"; @Override public void afterPropertiesSet() throws Exception { //注册新的主键 camelContext.addComponent("dubbo",new DubboCamelComponent()); } /** * 定时刷新 */ @Scheduled(fixedDelayString = "${camel.refreshPeriod}") public void refresh(){ log.info("同步路由信息开始!"); //加载方法信息并分组 LambdaQueryWrapper<ConnectorDubboParameterEntity> parameterQueryWrapper = new LambdaQueryWrapper<>(); parameterQueryWrapper.select(ConnectorDubboParameterEntity::getRouteId,ConnectorDubboParameterEntity::getParameterName,ConnectorDubboParameterEntity::getParameterType) .eq(ConnectorDubboParameterEntity::getDelFalg,false).orderByAsc(ConnectorDubboParameterEntity::getRouteId, ConnectorDubboParameterEntity::getSort); Map<Long,List<ConnectorDubboParameterEntity>> paramters =parameterService.list(parameterQueryWrapper).stream() .collect(Collectors.toMap(ConnectorDubboParameterEntity::getRouteId, p -> { List<ConnectorDubboParameterEntity> names = new ArrayList<>(); names.add(p); return names; },(a,b)-> {a.addAll(b);return a;})); //加载路由信息 LambdaQueryWrapper<ConnectorDubboRouteEntity> routeQueryWrapper = new LambdaQueryWrapper<>(); routeQueryWrapper.select(ConnectorDubboRouteEntity::getId,ConnectorDubboRouteEntity::getInterfaceClass,ConnectorDubboRouteEntity::getConfigCenterAddress, ConnectorDubboRouteEntity::getMethodName,ConnectorDubboRouteEntity::getRouteServicePath,ConnectorDubboRouteEntity::getRouteServicePort, ConnectorDubboRouteEntity::getVersion).eq(ConnectorDubboRouteEntity::getIsValiable,true); List<ConnectorDubboRouteEntity> routeEntities = routeService.list(routeQueryWrapper); //删除信息 checkRemoveRoutes(routeEntities); //编译信息 Map<String,TemplateInfo> sourceInfo = routeEntities.stream().collect(Collectors.toMap(ConnectorDubboRouteEntity::getInterfaceClass,r -> { TemplateInfo templateInfo = new TemplateInfo(r.getInterfaceClass()); List<ConnectorDubboParameterEntity> names = paramters.get(r.getId()); if (names == null) { names = new ArrayList<>(); } templateInfo.addMethod(r.getMethodName(),names.toArray(new ConnectorDubboParameterEntity[names.size()])); return templateInfo; }, (r1,r2) -> { r1.getMethods().addAll(r2.getMethods()); return r1; })); //做对比,来判断哪些需要编译 checkComplierRoute(sourceInfo); //重新编译后,判断新增接口 List<String> routeIds = camelContext.getRoutes().stream() .map(Route::getRouteId).collect(Collectors.toList()); List<ConnectorDubboRouteEntity> addRoutes = routeEntities.stream().filter(r -> { //没有添加进去的需要标识出来,重试次数超过5次不在执行 return !routeIds.contains(dubboServiceConfig.getRouteIdPrefx() + r.getId()) && retries.getOrDefault(dubboServiceConfig.getRouteIdPrefx() + r.getId(),0)<= 5; }).collect(Collectors.toList()); addRoutes(addRoutes,paramters); log.info("同步路由信息结束!"); } /** * 判断是否需要重新编译 * @param sourceInfo */ private void checkComplierRoute(Map<String, TemplateInfo> sourceInfo) { log.info("校验重新编译类信息!"); List<TemplateInfo> templateInfos = sourceInfo.values().stream().filter( t -> { TemplateInfo classInfo = cache.get(t.getInterfaceClass()); if (classInfo == null) { return true; } //如果不不同表示需要编译 return !classInfo.equals(t); }).collect(Collectors.toList()); //防止重复类,不能重新加载。 JdkCompiler jdkCompiler = new JdkCompiler(); for (TemplateInfo templateInfo : templateInfos) { log.info("重新编译类:{}",templateInfo.getClassName()); try{ Class clazz = jdkCompiler.doCompile(templateInfo.getInterfaceClass(),sourceCreator.createSource(templateInfo)); //动态编译类的所有方法都需要注册 Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { InterfaceInfo interfaceInfo = new InterfaceInfo(); interfaceInfo.setInterfaceClass(clazz); interfaceInfo.setMethod(method); //key值为类名:方法名:参数个数 String key = templateInfo.getInterfaceClass() + ":" + method.getName() + ":" + method.getParameterCount(); registry.registry(key,interfaceInfo); } //编译通过,缓存起来 cache.put(templateInfo.getInterfaceClass(),templateInfo); }catch (Throwable t) { log.error("编译类:{}出错!",templateInfo.getInterfaceClass()); t.printStackTrace(); } } } /** * 校验是否有需要删除的路由信息 * 在部署,但是数据库中已经没有了 * @param routeEntities */ private void checkRemoveRoutes(List<ConnectorDubboRouteEntity> routeEntities) { log.info("校验删除路由信息!"); List<String> routeIds = routeEntities.stream().map(r -> dubboServiceConfig.getRouteIdPrefx() + r.getId()) .collect(Collectors.toList()); //没有包含在记录中的数据都需要删除 List<Route> routes = camelContext.getRoutes().stream().filter(r -> !routeIds.contains(r.getRouteId())).collect(Collectors.toList()); for (Route route : routes) { try { removeRoutes(route.getRouteId()); } catch (Exception e) { log.error("删除路由{}出现异常!",route.getRouteId()); e.printStackTrace(); } } } /** * 尝试删除路由 * @param routeId * @throws Exception */ private void removeRoutes(String routeId) throws Exception { log.info("尝试删除路由:{}",routeId); if (camelContext.getRoute(routeId) == null) { log.info("路由未启动!"); return; } //尝试停止路由,并删除 camelContext.getRouteController().stopRoute(routeId); if (camelContext.removeRoute(routeId)) { retries.remove(routeId); return; } throw new RuntimeException("删除路由失败"); } /** * 添加路由信息, * dubbo格式: * dubbo://configcenteraddress:port?backup=address:port,address:port&version=&interfaceClass&parameterNames= */ private void addRoutes(List<ConnectorDubboRouteEntity> classInfos, Map<Long, List<ConnectorDubboParameterEntity>> paramters) { //需要编译的话在之前编译,且注册到registry中。 log.info("添加路由信息开始!"); RouteBuilder r = new RouteBuilder() { @Override public void configure() throws Exception { //异常处理 errorHandler(defaultErrorHandler().onExceptionOccurred(exceptionProcessor)); for (ConnectorDubboRouteEntity routeEntity : classInfos) { String routeId = dubboServiceConfig.getRouteIdPrefx() + routeEntity.getId(); log.info("尝试添加路由:{}",routeId); //监听地址 String linstenerId = dubboServiceConfig.getListenerAddress() + ":" + routeEntity.getRouteServicePort() + routeEntity.getRouteServicePath(); log.debug("路由监听地址:{}",linstenerId); //调用服务地址 StringBuilder toaddress = new StringBuilder(dubboSchema); toaddress.append(routeEntity.getConfigCenterAddress()); if (!toaddress.toString().contains("?")) { toaddress.append("?"); } else { toaddress.append("&"); } toaddress.append("interfaceClass=").append(routeEntity.getInterfaceClass()) .append("&methodName=").append(routeEntity.getMethodName()); if (!StringUtils.isEmpty(routeEntity.getVersion())) { toaddress.append("&version=").append(routeEntity.getVersion()); } if(paramters.get(routeEntity.getId()) != null && paramters.get(routeEntity.getId()).size() > 0 ) { String parameterNames = paramters.get(routeEntity.getId()).stream().map(ConnectorDubboParameterEntity::getParameterName).collect(Collectors.joining(",")); toaddress.append("&parameterNames=").append(parameterNames); String parameterTypes = paramters.get(routeEntity.getId()).stream().map(ConnectorDubboParameterEntity::getParameterType).collect(Collectors.joining(",")); toaddress.append("&parameterTypes=").append(parameterTypes); } log.debug("路由服务地址:{}",toaddress.toString()); //添加路由 from(linstenerId) .process(inProcessor) .routeId(routeId) .to(toaddress.toString()); //设置重试次数 retries.put(routeId, retries.getOrDefault(routeId,-1) + 1); } } }; try { camelContext.addRoutes(r); } catch (Exception e) { log.error(""); e.printStackTrace(); } log.info("添加路由信息结束!"); } }
true
e6e846ecf904971c179092a7ffd27ef8f53a3a2a
Java
dpetrocelli/unlu2019
/LU/src/main/java/Class2/pi.java
UTF-8
191
2.359375
2
[]
no_license
package Class2; public class pi implements Tarea{ int pi = 0; public Object ejecutar() { // TODO Auto-generated method stub for (int i=0; i<10; i++) { pi+=1; } return pi; } }
true
929043359ad8b798469c5edc02ce8a870ede5ce0
Java
qysnssl/y_project-RuoYi-Vue-master
/RuoYi-Vue/ruoyi-system/src/main/java/com/ruoyi/system/domain/News.java
UTF-8
2,153
2.0625
2
[ "MIT" ]
permissive
package com.ruoyi.system.domain; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; /** * 【请填写功能名称】对象 news * * @author ruoyi * @date 2021-06-10 */ public class News extends BaseEntity { private static final long serialVersionUID = 1L; /** 主键 */ private Long id; /** 新闻标题 */ @Excel(name = "新闻标题") private String title; /** 新闻概述 */ @Excel(name = "新闻概述") private String brief; /** 新闻正文 */ @Excel(name = "新闻正文") private String content; /** $column.columnComment */ @Excel(name = "新闻正文") private Integer deleteFlag; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public void setBrief(String brief) { this.brief = brief; } public String getBrief() { return brief; } public void setContent(String content) { this.content = content; } public String getContent() { return content; } public void setDeleteFlag(Integer deleteFlag) { this.deleteFlag = deleteFlag; } public Integer getDeleteFlag() { return deleteFlag; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("title", getTitle()) .append("brief", getBrief()) .append("content", getContent()) .append("createTime", getCreateTime()) .append("createBy", getCreateBy()) .append("updateTime", getUpdateTime()) .append("updateBy", getUpdateBy()) .append("deleteFlag", getDeleteFlag()) .toString(); } }
true
b91885f188b782fc937f10911759ecf17ecba8ff
Java
Harrison-Dolin/Spreadsheets
/src/model/formula/IFormulaFunction.java
UTF-8
192
1.742188
2
[]
no_license
package edu.cs3500.spreadsheets.model.formula; /** * Represents a function that is a formula {FormulaInterface}. */ public interface IFormulaFunction extends FormulaInterface { }
true
60915ee428144b8cef1dfa8b45bdc16abb7179b1
Java
Slavik3/SummaryTask1
/src/ua/nure/kozlov/SummaryTask1/Demo.java
WINDOWS-1251
833
2.90625
3
[]
no_license
//JTH-73 package ua.nure.kozlov.SummaryTask1; /** * * Demonstrates work of the program * @author Slavik Kozlov * */ import java.io.FileNotFoundException; public class Demo { public static void main(String[] args) throws FileNotFoundException { System.setProperty("file.encoding", "Cp1251"); Train train = new Train(); train.read("1.txt"); System.out.println(train); System.out.println(" = " + train.amountOfLuggage()); System.out.println(" = " + train.numberOfPassengers()); Vagon v = new Platzkart(); train.add(v); train.print(); v.getComfortLevel(); train.sort(); train.print(); train.del(v); System.out.println("" + v.getComfortLevel()); System.out.println("train size= " + train.size()); } }
true
2690e44e59f2c4b55492df96ba85f83170f13abe
Java
xobyx/ANDROID
/SimpleBlocker/src/com/simpleblocker/data/models/Phone.java
UTF-8
1,220
2.859375
3
[]
no_license
package com.simpleblocker.data.models; /** * * */ public final class Phone extends Id { private Contact contact; private String contactPhone; private String contactPhoneType; //------- Getters & Setters --------------// public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } public String getContactPhone() { return contactPhone; } public void setContactPhone(String contactPhone) { this.contactPhone = contactPhone; } public String getContactPhoneType() { return contactPhoneType; } public void setContactPhoneType(String contactPhoneType) { this.contactPhoneType = contactPhoneType; } //---------------------------------------------// /** * @param contact * @param contactPhone * @param contactPhoneType */ public Phone (final Contact contact, final String contactPhone, final String contactPhoneType) { super(); this.contact = contact; this.contactPhone = contactPhone; this.contactPhoneType = contactPhoneType; } @Override public String toString() { return "Phone [contact=" + contact + ", contactPhone=" + contactPhone + ", contactPhoneType=" + contactPhoneType + "]"; } }
true
b493f7a5848ec3229184892f177d40447900c6d8
Java
cw01393/Lect-lv9
/rpg/src/models/Player.java
UTF-8
293
1.960938
2
[]
no_license
package models; import java.util.Scanner; public class Player { public static Scanner sc = new Scanner(System.in); public static int money; public static Player instance = new Player(); public Guild guild = new Guild(); public Inventory inven = new Inventory(); }
true
b6343322640eb8ac9afb73520c1e59e0e7660c18
Java
Ashleychen/MEETING
/src/UI/BookingUI.java
UTF-8
8,986
2.640625
3
[]
no_license
package UI; import java.awt.Color; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; import java.util.Calendar; import java.util.Date; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.jdesktop.swingx.JXDatePicker; import dataControl.DataController; public class BookingUI extends JFrame{ private JLabel organizerNameLabel; private JLabel organizerNameTextLabel; private JLabel topicLabel; private JTextArea topicTextArea; private JScrollPane topicScrollPane; private JLabel personNumLabel; private JSpinner personNumSpinner; private JLabel startDateLabel; private JXDatePicker startDatePicker; private JButton startDateButton; private JLabel startTimeLabel; private JSpinner startHourSpinner; private JLabel startHourLabel; private JSpinner startMinuteSpinner; private JLabel startMinuteLabel; private JLabel endTimeLabel; private JSpinner endHourSpinner; private JLabel endHourLabel; private JSpinner endMinuteSpinner; private JLabel endMinuteLabel; private JButton submitButton; private String topicText; private int memberNum; private Date bookingStartTime; private Date bookingEndTime; private String userName; private String password; private String buildingName; private String floorName; private String roomName; private int startHour; private int endHour; private int startMinute; private int endMinute; private DataController dataController; public BookingUI(int userID, int personNum, Date startDate, String bn, String fn, String rn, String dbUserName, String dbPassword, String dbPort) throws SQLException, ClassNotFoundException { super(); this.setVisible(true); this.setSize(450, 500); JPanel panel = new JPanel(); this.placeComponents(panel, userID, personNum, startDate, bn, fn, rn, dbUserName, dbPassword, dbPort); getContentPane().add(panel); } public void placeComponents(JPanel panel, int userID, int personNum, Date startDate, String bn, String fn, String rn, String dbUserName, String dbPassword, String dbPort) throws SQLException, ClassNotFoundException { panel.setLayout(null); dataController = new DataController(dbUserName, dbPassword, dbPort); userName = dataController.getUserName(userID); buildingName = bn; floorName = fn; roomName = rn; organizerNameLabel = new JLabel("会议组织者"); organizerNameLabel.setBounds(10, 20, 80, 25); panel.add(organizerNameLabel); organizerNameTextLabel = new JLabel(userName); organizerNameTextLabel.setBounds(100, 20, 200, 35); getContentPane().add(organizerNameTextLabel); topicLabel = new JLabel("会议主题"); topicLabel.setBounds(10, 45, 80, 25); panel.add(topicLabel); topicTextArea = new JTextArea("请填写会议用途!", 7, 15); topicTextArea.setLineWrap(true); topicScrollPane = new JScrollPane(topicTextArea); topicScrollPane.setBounds(100, 45, 300, 200); panel.add(topicScrollPane); personNumLabel = new JLabel("与会人数"); personNumLabel.setBounds(10, 255, 80, 25); panel.add(personNumLabel); SpinnerNumberModel personNumSpinnerModel = new SpinnerNumberModel(personNum, 1, personNum, 1); memberNum = personNum; personNumSpinner = new JSpinner(personNumSpinnerModel); personNumSpinner.setBounds(100, 255, 80, 25); JFormattedTextField formattedTextField = ((JSpinner.DefaultEditor)personNumSpinner.getEditor()).getTextField(); formattedTextField.setEditable(false); formattedTextField.setBackground(Color.white); personNumSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // TODO Auto-generated method stub memberNum = (int) ((JSpinner)(e.getSource())).getValue(); } }); panel.add(personNumSpinner); startDateLabel = new JLabel("开始日期"); startDateLabel.setBounds(10, 280, 80, 25); panel.add(startDateLabel); int minHour = 8; int maxHour = 19; int minMinute = 0; int maxMinute = 59; startHour = minHour; startMinute = minMinute; endHour = maxHour; endMinute = minMinute; Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); calendar.set(Calendar.HOUR_OF_DAY, minHour); calendar.set(Calendar.MINUTE, minMinute); calendar.set(Calendar.SECOND, 0); bookingStartTime = calendar.getTime(); bookingEndTime = calendar.getTime(); startDatePicker = new JXDatePicker(); startDatePicker.setDate(bookingStartTime); startDatePicker.setBounds(100, 280, 118, 39); panel.add(startDatePicker); startTimeLabel = new JLabel("开始时间"); startTimeLabel.setBounds(10, 330, 80, 25); panel.add(startTimeLabel); SpinnerNumberModel startHourSpinnerModel = new SpinnerNumberModel(minHour, minHour, maxHour, 1); SpinnerNumberModel startMinuteSpinnerModel = new SpinnerNumberModel(minMinute, minMinute, maxMinute, 1); startHourSpinner = new JSpinner(startHourSpinnerModel); startHourSpinner.setBounds(100, 330, 80, 25); panel.add(startHourSpinner); startHourSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // TODO Auto-generated method stub startHour = (int) ((JSpinner)(e.getSource())).getValue(); } }); startHourLabel = new JLabel("时"); startHourLabel.setBounds(190, 330, 80, 25); panel.add(startHourLabel); startMinuteSpinner = new JSpinner(startMinuteSpinnerModel); startMinuteSpinner.setBounds(280, 330, 80, 25); panel.add(startMinuteSpinner); startMinuteSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // TODO Auto-generated method stub startMinute = (int) ((JSpinner)(e.getSource())).getValue(); } }); startMinuteLabel = new JLabel("分"); startMinuteLabel.setBounds(370, 330, 80, 25); panel.add(startMinuteLabel); SpinnerNumberModel endHourSpinnerModel = new SpinnerNumberModel(minHour, minHour, maxHour, 1); SpinnerNumberModel endMinuteSpinnerModel = new SpinnerNumberModel(minMinute, minMinute, maxMinute, 1); endTimeLabel = new JLabel("结束时间"); endTimeLabel.setBounds(10, 365, 80, 25); panel.add(endTimeLabel); endHourSpinner = new JSpinner(endHourSpinnerModel); endHourSpinner.setBounds(100, 365, 80, 25); panel.add(endHourSpinner); endHourSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // TODO Auto-generated method stub endHour = (int) ((JSpinner)(e.getSource())).getValue(); } }); endHourLabel = new JLabel("时"); endHourLabel.setBounds(190, 365, 80, 25); panel.add(endHourLabel); endMinuteSpinner = new JSpinner(endMinuteSpinnerModel); endMinuteSpinner.setBounds(280, 365, 80, 25); panel.add(endMinuteSpinner); endMinuteSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // TODO Auto-generated method stub endMinute = (int) ((JSpinner)(e.getSource())).getValue(); } }); endMinuteLabel = new JLabel("分"); endMinuteLabel.setBounds(370, 365, 80, 25); panel.add(endMinuteLabel); submitButton = new JButton("提交"); submitButton.setBounds(300, 440, 80, 25); panel.add(submitButton); submitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Calendar calendar = Calendar.getInstance(); calendar.setTime(startDatePicker.getDate()); calendar.set(Calendar.HOUR_OF_DAY, startHour); calendar.set(Calendar.MINUTE, startMinute); bookingStartTime = calendar.getTime(); calendar.set(Calendar.HOUR_OF_DAY, endHour); calendar.set(Calendar.MINUTE, endMinute); bookingEndTime = calendar.getTime(); if (bookingStartTime.compareTo(bookingEndTime) >= 0) { JOptionPane.showMessageDialog(null, "预定时间设置错误"); //} else if (dataController.checkUser(userName, password) == 0) { //JOptionPane.showMessageDialog(null, "用户不存在"); } else { try { int uid = userID; int roomId = dataController.getRoomId(buildingName, floorName, roomName); topicText = topicTextArea.getText(); dataController.addMeetingRecord(uid, bookingStartTime, bookingEndTime, roomId, memberNum, topicText); JOptionPane.showMessageDialog(null, "预定成功"); bookSuccess(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); } public void bookSuccess() { this.dispose(); } }
true
30359e10d9e0d4d9705a8d3628565a70fea7d108
Java
qoo7972365/timmy
/OSWE/oswe/openCRX/rtjar/rt.jar.src/com/sun/xml/internal/ws/wsdl/parser/MemberSubmissionAddressingWSDLParserExtension.java
UTF-8
3,008
1.515625
2
[]
no_license
/* */ package com.sun.xml.internal.ws.wsdl.parser; /* */ /* */ import com.sun.xml.internal.ws.api.addressing.AddressingVersion; /* */ import com.sun.xml.internal.ws.api.model.wsdl.WSDLFeaturedObject; /* */ import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLBoundOperation; /* */ import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLBoundPortType; /* */ import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLPort; /* */ import com.sun.xml.internal.ws.developer.MemberSubmissionAddressingFeature; /* */ import com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil; /* */ import javax.xml.namespace.QName; /* */ import javax.xml.stream.XMLStreamReader; /* */ import javax.xml.ws.WebServiceFeature; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class MemberSubmissionAddressingWSDLParserExtension /* */ extends W3CAddressingWSDLParserExtension /* */ { /* */ public boolean bindingElements(EditableWSDLBoundPortType binding, XMLStreamReader reader) { /* 45 */ return addressibleElement(reader, (WSDLFeaturedObject)binding); /* */ } /* */ /* */ /* */ public boolean portElements(EditableWSDLPort port, XMLStreamReader reader) { /* 50 */ return addressibleElement(reader, (WSDLFeaturedObject)port); /* */ } /* */ /* */ private boolean addressibleElement(XMLStreamReader reader, WSDLFeaturedObject binding) { /* 54 */ QName ua = reader.getName(); /* 55 */ if (ua.equals(AddressingVersion.MEMBER.wsdlExtensionTag)) { /* 56 */ String required = reader.getAttributeValue("http://schemas.xmlsoap.org/wsdl/", "required"); /* 57 */ binding.addFeature((WebServiceFeature)new MemberSubmissionAddressingFeature(Boolean.parseBoolean(required))); /* 58 */ XMLStreamReaderUtil.skipElement(reader); /* 59 */ return true; /* */ } /* */ /* 62 */ return false; /* */ } /* */ /* */ /* */ public boolean bindingOperationElements(EditableWSDLBoundOperation operation, XMLStreamReader reader) { /* 67 */ return false; /* */ } /* */ /* */ /* */ /* */ protected void patchAnonymousDefault(EditableWSDLBoundPortType binding) {} /* */ /* */ /* */ protected String getNamespaceURI() { /* 76 */ return AddressingVersion.MEMBER.wsdlNsUri; /* */ } /* */ /* */ /* */ protected QName getWsdlActionTag() { /* 81 */ return AddressingVersion.MEMBER.wsdlActionTag; /* */ } /* */ } /* Location: /Users/timmy/timmy/OSWE/oswe/openCRX/rt.jar!/com/sun/xml/internal/ws/wsdl/parser/MemberSubmissionAddressingWSDLParserExtension.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
true
524ad6e4042059ee03d92b445620b586fc26360e
Java
wildstang/2011_software
/NutronCode/src/edu/neu/nutrons/lib/MotorMechanism.java
UTF-8
591
2.515625
3
[]
no_license
/* * MotorMechanism * * This interface is used to define mechanisms on the robot that have a motor * hooked up to some kind of feedback. Using this abstraction allows for sweeping * changes in the low level that dont affect control logic, like a simulator */ package edu.neu.nutrons.lib; /** * * @author NUTRONS_PROGRAMMING */ public interface MotorMechanism { public void set(double speed); public double getPos(); public double getRate(); public boolean getUpperLimit(); public boolean getLowerLimit(); public void setInvertedSensor(boolean inverted); }
true
08b9f94052c386e1ff642668c4b1343761abb0f5
Java
guffyWave/Khurshid-Web-Delegation
/app/src/main/java/lab/computing/khurshid/khurshidwebdelegation/dto/WebRequest.java
UTF-8
2,427
2.109375
2
[]
no_license
package lab.computing.khurshid.khurshidwebdelegation.dto; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.util.Date; @DatabaseTable public class WebRequest { @DatabaseField(generatedId = true) int id; @DatabaseField(unique = true) String url; @DatabaseField(dataType = DataType.SERIALIZABLE) WebParam<String, String> webParams = new WebParam<String, String>(); @DatabaseField String responseString; @DatabaseField boolean shouldCache; @DatabaseField(dataType = DataType.ENUM_STRING) RequestStatus requestStatus; @DatabaseField(dataType = DataType.DATE_STRING) Date requestTimeStamp; @DatabaseField(dataType = DataType.DATE_STRING) Date responseTimeStamp; public WebRequest() { } public WebRequest(String url) { super(); this.url = url; this.requestStatus = RequestStatus.PENDING; this.requestTimeStamp = new Date(); } public WebParam<String, String> getWebParams() { return webParams; } public void setWebParams(WebParam<String, String> webParams) { this.webParams = webParams; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getResponseString() { return responseString; } public void setResponseString(String responseString) { this.responseString = responseString; } public RequestStatus getRequestStatus() { return requestStatus; } public void setRequestStatus(RequestStatus requestStatus) { this.requestStatus = requestStatus; } public Date getRequestTimeStamp() { return requestTimeStamp; } public void setRequestTimeStamp(Date requestTimeStamp) { this.requestTimeStamp = requestTimeStamp; } public Date getResponseTimeStamp() { return responseTimeStamp; } public void setResponseTimeStamp(Date responseTimeStamp) { this.responseTimeStamp = responseTimeStamp; } public boolean isShouldCache() { return shouldCache; } public void setShouldCache(boolean shouldCache) { this.shouldCache = shouldCache; } }
true
2834f0b7241874a523e216235c1a3cd8d182b2fa
Java
DarenSu/Community
/src/main/java/com/nowcoder/community/controller/DiscussPostController.java
UTF-8
3,020
2.40625
2
[]
no_license
package com.nowcoder.community.controller; import com.nowcoder.community.entity.DiscussPost; import com.nowcoder.community.entity.User; import com.nowcoder.community.service.DiscussPostService; import com.nowcoder.community.service.UserService; import com.nowcoder.community.util.CommunityUtil; import com.nowcoder.community.util.HostHolder; 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 java.util.Date; @Controller @RequestMapping("/discuss") public class DiscussPostController { @Autowired private DiscussPostService discussPostService; @Autowired private HostHolder hostHolder;// 有用于获取当前用户 @Autowired UserService userService; // 增加帖子的请求,异步请求 因为是增加数据,浏览器会提交很多数据,所以用POST @RequestMapping(path = "/add", method = RequestMethod.POST) @ResponseBody public String addDiscussPost(String title, String content) {// 页面只需要传输需要过滤的内容就可以 User user = hostHolder.getUser(); if (user == null) { return CommunityUtil.getJSONString(403, "你还没有登录哦!"); } // 构造一个实体出来 DiscussPost post = new DiscussPost(); post.setUserId(user.getId()); post.setTitle(title); post.setContent(content); post.setCreateTime(new Date()); discussPostService.addDiscussPost(post); // 报错的情况,将来统一处理. return CommunityUtil.getJSONString(0, "发布成功!"); } // 帖子详细信息展示 @RequestMapping( path = "/detail/{discussPostId}", method = RequestMethod.GET) // model对象携带相关数据,主要是查询的结果 public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model){ // 帖子 DiscussPost post = discussPostService.findDiscussPostById(discussPostId); //model存储查询的信息 model.addAttribute("post", post); // 但是post里面存储的是用户的id,不是用户的名字,所以需要继续查询用户得到名字 // 查询名字有两种方法,一种是在discusspost-mapper.xml中查询语句selectDiscussPostById中进行关联查询, // 虽然关联查询快点,但是这样子会使的这个查询语句不是很好复用,因为很多别的功能并不需要查询用户名 // 所以使用仙茶道id,再在user表中查询用户名等信息 // 作者 User user = userService.findUserById(post.getUserId()); model.addAttribute("user", user); return "/site/discuss-detail"; } }
true
924280b82c9840f051adbca3c4c6e5d64f1ce58d
Java
MarianoPaniagua/KafkaTest1
/src/main/java/com/pani/KafkaTest/controller/ApacheKafkaWebController.java
UTF-8
1,563
2.125
2
[]
no_license
package com.pani.KafkaTest.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.pani.KafkaTest.converter.PostConverter; import com.pani.KafkaTest.dto.PostDto; import com.pani.KafkaTest.dto.UserDto; import com.pani.KafkaTest.entity.Post; import com.pani.KafkaTest.entity.User; import com.pani.KafkaTest.service.PostService; import com.pani.KafkaTest.service.UserService; import com.pani.KafkaTest.service.impl.KafkaSender; @RestController @RequestMapping(value = "/kafka/") public class ApacheKafkaWebController { @Autowired KafkaSender kafkaSender; @Autowired UserService userService; @Autowired PostService postService; @Autowired PostConverter postConverter; @PostMapping(value = "/post") public String producer(@RequestBody Post post) { String topic = post.getTopic(); // just to tes, need to only be a dto PostDto postDto = postConverter.entityToDto(post); kafkaSender.sendPost(topic, post); postService.addPost(postDto); kafkaSender.sendUserPostingNotification(post.getSenderId()); return "Post sent to the Kafka Topic: '" + topic + "' Successfully"; } @KafkaListener(topics = "java_topic") public void getPostFor__java_topic(Post post) { System.out.println(post.toString()); } }
true
e10776af3f32b780f3b4bc617a655fd41065172f
Java
thanasit/hello-ews-openshift
/src/main/java/th/or/pao/revenueonline/model/base/Province.java
UTF-8
2,517
2.109375
2
[]
no_license
package th.or.pao.revenueonline.model.base; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import java.io.Serializable; import java.util.List; @Entity @Table(name = "PROVINCE") @JsonIgnoreProperties(ignoreUnknown = true) public class Province implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") private Long id; @Column(name = "CODE") private String code; @Column(name = "PROVINCE", nullable = false) private String provinceName; @Column(name = "IS_ACTIVE") private Boolean isActive; @OneToMany(mappedBy = "province", cascade = CascadeType.ALL) @JsonBackReference(value = "districts") private List<District> districts; @OneToMany(mappedBy = "province", cascade = CascadeType.ALL) @JsonBackReference(value = "companies") private List<Company> companies; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getProvinceName() { return provinceName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName; } public List<District> getDistricts() { return districts; } public void setDistricts(List<District> districts) { this.districts = districts; } public Boolean getActive() { return isActive; } public void setActive(Boolean active) { isActive = active; } public List<Company> getCompanies() { return companies; } public void setCompanies(List<Company> companies) { this.companies = companies; } @Override public String toString() { return "Province{" + "id=" + id + ", code='" + code + '\'' + ", provinceName='" + provinceName + '\'' + ", isActive=" + isActive + ", districts=" + districts + ", companies=" + companies + '}'; } }
true
d0b1b727ae26fca755fb8e34f77f72c7b8823e9e
Java
iundarigun/design-patterns
/src/main/java/cat/ocanalias/designpatterns/nullobject/solucao/Main.java
UTF-8
926
3.546875
4
[]
no_license
package cat.ocanalias.designpatterns.nullobject.solucao; import cat.ocanalias.designpatterns.nullobject.Carrinho; /** * Created by uri on 18/11/16. */ public class Main { /** * Vamos supor que temos uma aplicaçao de compra e temos um carrinho * Precisamos pegar o carrinho da request. Agora o processo de criar o carrinho * vai voltar um objeto com os valores predefinidos * @param args */ public static void main(String... args){ Carrinho carrinho = criarCarrinhoDesdeRequest(args); System.out.println("O valor do carrinho é " + carrinho.getValor()); System.out.println("O valor do tamanho é " + carrinho.getTamanho()); } private static Carrinho criarCarrinhoDesdeRequest(String...args){ if (args.length>0){ return new Carrinho(new Double(args.length),new Double(args.length)); } return new CarrinhoNulo(); } }
true
4dea7f1883881457beb1ab5702bd81f486cdf3c2
Java
aguisset/BattleshipGame
/documents-export-2015-11-28/Grid.java
UTF-8
1,463
3.203125
3
[]
no_license
package grid; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Grid extends Cell{ /*Grid dimension & ship position*/ private int grid[][]; private int shipPosition[][]; /*Grid size*/ private int x; private int y; /*Ship position*/ private int xShip; private int yShip; /*Ship number*/ private int nbShip; private Set<Ship> ships; private int i; public Grid(int x, int y, int nbShip){ super(); this.grid = new int[x][y]; this.shipPosition = new int[nbShip][2]; this.ships = new HashSet<Ship>(); } public Grid(){ super(); grid = new int[9][9]; /*Default : three boats*/ this.shipPosition = new int[3][2]; } /*Init ship position in the grid*/ private void initShipPosition(int nbShip, Cell cell){ while(cell.getToken()==true){ xShip = (int)(Math.random() * (x + 1)); yShip = (int)(Math.random() * (y + 1)); } shipPosition[nbShip][1] = xShip; shipPosition[nbShip][2] = yShip; } /*Access*/ public int getXShipPosition(int nbShip){ return shipPosition[nbShip][1]; } public int getYShipPosition(int nbShip){ return shipPosition[nbShip][2]; } /*Access to all ships*/ Set<Ship> getShips() { return ships; } }
true
2f5ba65b6a890b80048e3728f9cb141d512aca5c
Java
Samyak81/RetrofitExample
/src/main/java/com/example/darshan/retrofitdemo/RetroApp.java
UTF-8
329
1.679688
2
[]
no_license
package com.example.darshan.retrofitdemo; import android.app.Application; import com.activeandroid.ActiveAndroid; /** * Created by darshan.mistry on 9/1/2015. */ public class RetroApp extends Application { @Override public void onCreate() { super.onCreate(); ActiveAndroid.initialize(this); } }
true
f15a5bfed76765065019b04443961b3ae5f730d5
Java
tsdavid/QBox
/src/main/java/com/dk/codingTest/hyndaiCard/bfsDfs/TargetNumber.java
UTF-8
1,104
3.359375
3
[]
no_license
package com.dk.codingTest.hyndaiCard.bfsDfs; import java.lang.annotation.Target; public class TargetNumber { public static void main(String[] args) { int[] numbers = {1, 1, 1, 1, 1}; int target = 3; int returns = 5; TargetNumber targetNumber = new TargetNumber(); System.out.println(targetNumber.velog_solution(numbers, target)); } public int velog_solution(int[] numbers, int target){ int answer = 0; answer = bfs(numbers, target, numbers[0], 1) + bfs(numbers, target, -numbers[0], 1); return answer; } public int bfs(int[] numbers, int target, int sum, int i){ System.out.println( "Call BFS : Sum : " + sum + " int i : " + i ); if( i==numbers.length){ if(sum == target){ return 1; }else{ return 0; } } int result = 0; result += bfs(numbers, target, sum + numbers[i], i + 1); result += bfs(numbers, target, sum - numbers[i], i + 1); return result; } }
true
4637100e8eb42c6bceb68885782ea0ee507d2e46
Java
tmyzh13/FusionWorker
/app/src/main/java/com/bm/fusionworker/presenter/InspectionItemInfoPresenter.java
UTF-8
1,712
1.90625
2
[]
no_license
package com.bm.fusionworker.presenter; import com.bm.fusionworker.model.UserHelper; import com.bm.fusionworker.model.apis.InspectionItemInfoApi; import com.bm.fusionworker.model.beans.BaseData; import com.bm.fusionworker.model.beans.InspectionItemInfoBean; import com.bm.fusionworker.model.beans.RepairItemInfoBean; import com.bm.fusionworker.model.beans.RequestItemInfoBean; import com.bm.fusionworker.model.interfaces.InspectionItemInfoView; import com.corelibs.api.ApiFactory; import com.corelibs.api.ResponseTransformer; import com.corelibs.base.BasePresenter; import com.corelibs.subscriber.ResponseSubscriber; import com.trello.rxlifecycle.ActivityEvent; /** * Created by issuser on 2018/5/21. */ public class InspectionItemInfoPresenter extends BasePresenter<InspectionItemInfoView> { private InspectionItemInfoApi api; @Override public void onStart() { } @Override protected void onViewAttach() { super.onViewAttach(); api = ApiFactory.getFactory().create(InspectionItemInfoApi.class); } public void getInspectionItemInfoAction(RequestItemInfoBean bean) { String token = UserHelper.getSavedUser().token; api.getInspectionItemInfo(token, bean) .compose(new ResponseTransformer<>(this.<BaseData<InspectionItemInfoBean>>bindUntilEvent(ActivityEvent.DESTROY))) .subscribe(new ResponseSubscriber<BaseData<InspectionItemInfoBean>>(view) { @Override public void success(BaseData<InspectionItemInfoBean> inspectionItemInfoBeanBaseData) { view.renderData(inspectionItemInfoBeanBaseData.data); } }); } }
true
6ab2f642fc4bbb7ab40b6abd30aa94b5dd062bbc
Java
Jade5916/zealot
/src/main/java/com/blinkfox/zealot/exception/ZealotException.java
UTF-8
611
2.5
2
[ "Apache-2.0" ]
permissive
package com.blinkfox.zealot.exception; /** * 自定义的Zealot运行时异常. * * @author blinkfox on 2018-04-24. */ public class ZealotException extends RuntimeException { private static final long serialVersionUID = 1L; /** * 附带日志消息参数的构造方法. * @param msg 日志消息 */ public ZealotException(String msg) { super(msg); } /** * 附带日志消息参数的构造方法. * @param msg 日志消息 * @param t Throwable对象 */ public ZealotException(String msg, Throwable t) { super(msg, t); } }
true
580a08f6c5b854d4dccfd2e77a16dd4a3bc29c16
Java
katanike/learning-Datastructures-and-Algorithms
/Algorithms/hackerRank/MigratoryBirds.java
UTF-8
1,431
3.640625
4
[]
no_license
import java.util.*; public class MigratoryBirds { public static void main(String args[]) { List<Integer> arr=new ArrayList<Integer>(); arr.add(1); arr.add(4); arr.add(4); arr.add(4); arr.add(5); arr.add(3); HashMap<Integer,Integer> birds=new HashMap<Integer,Integer>(); int count1 = 0; int count2 = 0; int count3 = 0; int count4 = 0; int count5 = 0; for (int i = 0; i < arr.size();i++) { switch(arr.get(i)) { case 1: { count1++; birds.put(1, count1); break; } case 2: { count2++; birds.put(2, count2); break; } case 3: { count3++; birds.put(3, count3); break; } case 4: { count4++; birds.put(4, count4); break; } case 5: { count5++; birds.put(5, count5); break; } } } Map.Entry<Integer, Integer> maxEntry = null; for (Map.Entry<Integer, Integer> entry : birds.entrySet()) { if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) { maxEntry = entry; } } System.out.println(maxEntry.getKey()); } }
true
52f32957714417c57f9b370bb70b107b3d6ee9ea
Java
RaulG89/CPM-1
/2015/Modulo_2015/src/igu/PanelCardLayout/PanelListaCruceros.java
UTF-8
27,913
2.09375
2
[]
no_license
package igu.PanelCardLayout; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.TableModelEvent; import javax.swing.table.*; import igu.VentanaPrincipal; import igu.PanelCardLayout.util.FiltrosCruceros; import igu.PanelCardLayout.util.RadioButtonEditor; import igu.PanelCardLayout.util.RadioButtonRenderer; import logica.Crucero; public class PanelListaCruceros extends JPanel { private static final long serialVersionUID = 4598024009655129251L; private ButtonGroup grupoBotonesFiltros, grupoBotonesTabla; private JPanel pnTitulo; private JLabel lblListaCrucerosDisponibles; private JPanel pnTablaCruceros; private JPanel pnFiltros; private JPanel pnTituloSeleccionarCrucero; private JScrollPane scListaCruceros; private DefaultTableModel modeloTablaCruceros; private JTable tablaCruceros; private JButton btnSiguienteListaCruceros; private JComboBox<String> cbOpcionesFiltros; private JPanel pnOpcionesFiltros; private JPanel pnFiltrosTodos; private JPanel pnSeleccionFiltros; private JLabel lblPorFavorSeleccione; private JScrollPane scOpcionesFiltros; private JPanel pnBotones; private JLabel lblSeleccionarCrucero; private JButton btnCancelarListaCruceros; private VentanaPrincipal vp; public PanelListaCruceros(VentanaPrincipal vp) { this.setVp(vp); getCbOpciones().grabFocus(); grupoBotonesFiltros = new ButtonGroup(); grupoBotonesTabla = new ButtonGroup(); this.setLayout(new BorderLayout(0, 0)); this.add(getPnTitulo(), BorderLayout.NORTH); this.add(getPnTablaCruceros(), BorderLayout.CENTER); this.add(getPnBotones(), BorderLayout.SOUTH); crearFiltros(); agregarTodo(); btnSiguienteListaCruceros.setEnabled(false); cbOpcionesFiltros.setSelectedIndex(0); } private JPanel getPnTitulo() { if (pnTitulo == null) { pnTitulo = new JPanel(); pnTitulo.add(getLblListaCrucerosDisponibles()); } return pnTitulo; } private JLabel getLblListaCrucerosDisponibles() { if (lblListaCrucerosDisponibles == null) { lblListaCrucerosDisponibles = new JLabel( "Lista de cruceros disponibles:"); lblListaCrucerosDisponibles .setFont(new Font("Tahoma", Font.PLAIN, 40)); } return lblListaCrucerosDisponibles; } private JPanel getPnTablaCruceros() { if (pnTablaCruceros == null) { pnTablaCruceros = new JPanel(); pnTablaCruceros.setLayout(new BorderLayout(0, 0)); pnTablaCruceros.add(getPnFiltros(), BorderLayout.NORTH); pnTablaCruceros.add(getScListaCruceros(), BorderLayout.CENTER); } return pnTablaCruceros; } private JPanel getPnFiltros() { if (pnFiltros == null) { pnFiltros = new JPanel(); pnFiltros.setLayout(new BorderLayout(0, 0)); pnFiltros.add(getPnTituloSeleccionarCrucero(), BorderLayout.NORTH); pnFiltros.add(getPnFiltrosTodos(), BorderLayout.CENTER); } return pnFiltros; } private JPanel getPnFiltrosTodos() { if (pnFiltrosTodos == null) { pnFiltrosTodos = new JPanel(); pnFiltrosTodos.setLayout(new BorderLayout(0, 0)); pnFiltrosTodos.add(getPnSeleccionFiltros(), BorderLayout.NORTH); pnFiltrosTodos.add(getScOpcionesFiltros(), BorderLayout.CENTER); } return pnFiltrosTodos; } private JScrollPane getScOpcionesFiltros() { if (scOpcionesFiltros == null) { scOpcionesFiltros = new JScrollPane(); scOpcionesFiltros.setViewportView(getPnOpcionesFiltros()); } return scOpcionesFiltros; } private JPanel getPnSeleccionFiltros() { if (pnSeleccionFiltros == null) { pnSeleccionFiltros = new JPanel(); pnSeleccionFiltros.add(getLblPorFavorSeleccione()); pnSeleccionFiltros.add(getCbOpciones()); } return pnSeleccionFiltros; } private JLabel getLblPorFavorSeleccione() { if (lblPorFavorSeleccione == null) { lblPorFavorSeleccione = new JLabel("Filtros: "); lblPorFavorSeleccione.setDisplayedMnemonic('F'); lblPorFavorSeleccione.setLabelFor(getCbOpciones()); lblPorFavorSeleccione.setFont(new Font("Tahoma", Font.PLAIN, 16)); } return lblPorFavorSeleccione; } private JPanel getPnTituloSeleccionarCrucero() { if (pnTituloSeleccionarCrucero == null) { pnTituloSeleccionarCrucero = new JPanel(); pnTituloSeleccionarCrucero.add(getLblSeleccionarCrucero()); } return pnTituloSeleccionarCrucero; } private JLabel getLblSeleccionarCrucero() { if (lblSeleccionarCrucero == null) { lblSeleccionarCrucero = new JLabel( "Por favor seleccione un crucero:"); lblSeleccionarCrucero.setFont(new Font("Tahoma", Font.PLAIN, 16)); } return lblSeleccionarCrucero; } private JPanel getPnBotones() { if (pnBotones == null) { pnBotones = new JPanel(); FlowLayout flowLayout = (FlowLayout) pnBotones.getLayout(); flowLayout.setAlignment(FlowLayout.RIGHT); pnBotones.add(getBtnSiguienteListaCruceros()); pnBotones.add(getBtnCancelarListaCruceros()); } return pnBotones; } JButton getBtnSiguienteListaCruceros() { if (btnSiguienteListaCruceros == null) { btnSiguienteListaCruceros = new JButton("Siguiente"); btnSiguienteListaCruceros.setToolTipText( "Muestra los detalles del crucero seleccionado"); btnSiguienteListaCruceros.setMnemonic('S'); btnSiguienteListaCruceros .setFont(new Font("Tahoma", Font.PLAIN, 12)); btnSiguienteListaCruceros.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (int i = 0; i < tablaCruceros.getRowCount(); i++) { JRadioButton radio = (JRadioButton) tablaCruceros .getValueAt(i, tablaCruceros.getColumnCount() - 1); if (radio.isSelected()) { Object[] cruceroSeleccionado = new Object[] { tablaCruceros.getValueAt(i, 0), tablaCruceros.getValueAt(i, 1), tablaCruceros.getValueAt(i, 2), tablaCruceros.getValueAt(i, 4), tablaCruceros.getValueAt(i, 6) }; for (int j = 0; j < getVp().getCatalogo() .getCruceros().size(); j++) { if (getVp().getCatalogo().getCruceros().get(j) .getZona() .equals(cruceroSeleccionado[0]) && getVp().getCatalogo().getCruceros() .get(j).getPuertoSalida() .equals(cruceroSeleccionado[1]) && getVp().getCatalogo().getCruceros() .get(j).getItinerario() .equals(cruceroSeleccionado[2]) && cruceroSeleccionado[3].equals(getVp() .getCatalogo().getCruceros() .get(j).getDuracionDias()) && getVp().getCatalogo().getCruceros() .get(j).getBarco() .getDenominacion() .equals(cruceroSeleccionado[4])) { getVp().setCrucero(getVp().getCatalogo() .getCruceros().get(j)); } } break; } } if (getVp().getCrucero() != null) { vp.cargarCrucero(); ((CardLayout) getVp().getPnReservas().getLayout()) .next(getVp().getPnReservas()); } else { JOptionPane.showMessageDialog(null, "Por favor seleccione un crucero", "Error", JOptionPane.ERROR_MESSAGE); } } }); } return btnSiguienteListaCruceros; } private JButton getBtnCancelarListaCruceros() { if (btnCancelarListaCruceros == null) { btnCancelarListaCruceros = new JButton("Cancelar"); btnCancelarListaCruceros .setToolTipText("Vuelve a la pantalla de inicio"); btnCancelarListaCruceros.setMnemonic('C'); btnCancelarListaCruceros .setFont(new Font("Tahoma", Font.PLAIN, 12)); btnCancelarListaCruceros.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getVp().inicializar(); } }); } return btnCancelarListaCruceros; } private JScrollPane getScListaCruceros() { if (scListaCruceros == null) { scListaCruceros = new JScrollPane(); scListaCruceros.setViewportView(getTablaCruceros()); } return scListaCruceros; } private JTable getTablaCruceros() { if (tablaCruceros == null) { setModeloTablaCruceros(new DefaultTableModel( new Object[] { "Zona", "Puerto de salida", "Itinerario", "Admisión de menores", "Dias de duración", "Fechas", "Barco", "Descuento", "Seleccionado" }, 0)); tablaCruceros = new JTable(getModeloTablaCruceros()) { private static final long serialVersionUID = 4283967148348124808L; @Override public boolean isCellEditable(int row, int col) { if (col == 8) return true; return false; } public void tableChanged(TableModelEvent e) { super.tableChanged(e); repaint(); } }; tablaCruceros.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent arg0) { activarBotonSiguienteListaCruceros(); } }); tablaCruceros.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { activarBotonSiguienteListaCruceros(); } }); tablaCruceros.getTableHeader().setReorderingAllowed(false); tablaCruceros.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); DefaultTableCellRenderer celda = new DefaultTableCellRenderer(); celda.setHorizontalAlignment(SwingConstants.CENTER); tablaCruceros.setDefaultRenderer(Object.class, celda); tablaCruceros.getColumn("Seleccionado") .setCellRenderer(new RadioButtonRenderer()); tablaCruceros.getColumn("Seleccionado") .setCellEditor(new RadioButtonEditor(new JCheckBox())); } return tablaCruceros; } private void activarBotonSiguienteListaCruceros() { for (int i = 0; i < tablaCruceros.getRowCount(); i++) { JRadioButton radio = (JRadioButton) tablaCruceros.getValueAt(i, tablaCruceros.getColumnCount() - 1); if (radio.isSelected()) btnSiguienteListaCruceros.setEnabled(true); } } private void crearFiltros() { if (getCbOpcionesFiltros().getSelectedItem().equals("Zona")) { cargarFiltrosZona(); asignarMnemonicosFiltros(); } else if (getCbOpcionesFiltros().getSelectedItem() .equals("Puerto de salida")) { cargarFiltrosPuertoSalida(); asignarMnemonicosFiltros(); } else if (getCbOpcionesFiltros().getSelectedItem() .equals("Itinerario")) { cargarFiltrosItinerario(); asignarMnemonicosFiltros(); } else if (getCbOpcionesFiltros().getSelectedItem() .equals("Admisión de menores")) { cargarFiltrosMenores(); asignarMnemonicosFiltros(); } else if (getCbOpcionesFiltros().getSelectedItem() .equals("Dias de duración")) cargarFiltrosDiasDuracion(); else if (getCbOpcionesFiltros().getSelectedItem().equals("Fechas")) cargarFiltrosFechas(); else if (getCbOpcionesFiltros().getSelectedItem().equals("Barco")) { cargarFiltrosBarco(); asignarMnemonicosFiltros(); } else if (getCbOpcionesFiltros().getSelectedItem() .equals("Precio de camarote")) cargarFiltrosPrecio(); } @SuppressWarnings("deprecation") private void asignarMnemonicosFiltros() { ArrayList<Character> mnemonicos = new ArrayList<Character>(); mnemonicos.add(' '); mnemonicos.add('F'); mnemonicos.add('S'); mnemonicos.add('C'); mnemonicos.add('f'); mnemonicos.add('s'); mnemonicos.add('c'); for (int i = 0; i < pnOpcionesFiltros.getComponentCount(); i++) { JRadioButton radio = (JRadioButton) pnOpcionesFiltros .getComponent(i); int contador = 0; boolean correcto = false; Character e = radio.getLabel().charAt(contador); do { if (mnemonicos.contains(e)) { contador++; if (contador == radio.getLabel().length()) { e = radio.getLabel().charAt(0); break; } else e = radio.getLabel().charAt(contador); } else { if (Character.isUpperCase(e)) { mnemonicos.add(e); mnemonicos.add(Character.toLowerCase(e)); } else { mnemonicos.add(e); mnemonicos.add(Character.toUpperCase(e)); } correcto = true; } } while (!correcto); radio.setMnemonic(e); } } private void cargarFiltrosZona() { ArrayList<String> filtros = new ArrayList<String>(); for (Crucero a : getVp().getCatalogo().getCruceros()) if (!filtros.contains(a.getZona())) filtros.add(a.getZona()); añadirRadioBoton(filtros); } private void añadirRadioBoton(ArrayList<String> filtros) { for (String a : filtros) { JRadioButton radio = new JRadioButton(a); radio.addActionListener(new FiltrosCruceros(this)); grupoBotonesFiltros.add(radio); pnOpcionesFiltros.add(radio); } JRadioButton radio = new JRadioButton("Todos", true); radio.addActionListener(new FiltrosCruceros(this)); grupoBotonesFiltros.add(radio); pnOpcionesFiltros.add(radio); } JComboBox<String> getCbOpciones() { if (getCbOpcionesFiltros() == null) { String[] opciones = { "Zona", "Puerto de salida", "Itinerario", "Admisión de menores", "Dias de duración", "Fechas", "Barco", "Precio de camarote" }; setCbOpcionesFiltros(new JComboBox<String>()); getCbOpcionesFiltros().setToolTipText( "Selecciona la caracteristica por la cual se van ha filtrar los cruceros"); getCbOpcionesFiltros().setFont(new Font("Tahoma", Font.PLAIN, 12)); getCbOpcionesFiltros().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { inicializarTablaCruceros(); } }); getCbOpcionesFiltros() .setModel(new DefaultComboBoxModel<String>(opciones)); } return getCbOpcionesFiltros(); } private void inicializarTablaCruceros() { borrarTabla(); grupoBotonesFiltros = new ButtonGroup(); pnOpcionesFiltros.removeAll(); crearFiltros(); pnOpcionesFiltros.updateUI(); pnOpcionesFiltros.repaint(); repaint(); agregarCrucerosTabla(); } private void borrarTabla() { while (getModeloTablaCruceros().getRowCount() > 0) { getModeloTablaCruceros().removeRow(0); } } public JPanel getPnOpcionesFiltros() { if (pnOpcionesFiltros == null) { pnOpcionesFiltros = new JPanel(); pnOpcionesFiltros.setLayout(new GridLayout(0, 2, 0, 0)); } return pnOpcionesFiltros; } private void agregarCrucerosTabla() { borrarTabla(); if (getCbOpcionesFiltros().getSelectedIndex() == 0) agregarTablaZona(); else if (getCbOpcionesFiltros().getSelectedIndex() == 1) agregarTablaPuertoSalida(); else if (getCbOpcionesFiltros().getSelectedIndex() == 2) agregarTablaItinerario(); else if (getCbOpcionesFiltros().getSelectedIndex() == 3) agregarTablaMenores(); else if (getCbOpcionesFiltros().getSelectedIndex() == 4) agregarTablaDiasDuracion(); else if (getCbOpcionesFiltros().getSelectedIndex() == 5) agregarTablaFechas(); else if (getCbOpcionesFiltros().getSelectedIndex() == 6) agregarTablaBarco(); else if (getCbOpcionesFiltros().getSelectedIndex() == 7) agregarTablaPrecio(); } private void agregarTablaZona() { String filtro = new String(); for (Component componente : pnOpcionesFiltros.getComponents()) { JRadioButton radio = (JRadioButton) componente; if (radio.isSelected()) { filtro = radio.getText(); break; } } if (filtro.equals("Todos")) agregarTodo(); else { for (Crucero crucero : getVp().getCatalogo().getCruceros()) { if (crucero.getZona().equals(filtro)) { añadirCruceroTabla(crucero); } } } } public void agregarTablaPuertoSalida() { String filtro = new String(); for (Component componente : pnOpcionesFiltros.getComponents()) { JRadioButton radio = (JRadioButton) componente; if (radio.isSelected()) { filtro = radio.getText(); break; } } if (filtro.equals("Todos")) agregarTodo(); else { for (Crucero crucero : getVp().getCatalogo().getCruceros()) { if (crucero.getPuertoSalida().equals(filtro)) { añadirCruceroTabla(crucero); } } } } public void agregarTablaItinerario() { String filtro = new String(); for (Component componente : pnOpcionesFiltros.getComponents()) { JRadioButton radio = (JRadioButton) componente; if (radio.isSelected()) { filtro = radio.getText(); break; } } if (filtro.equals("Todos")) agregarTodo(); else { for (Crucero crucero : getVp().getCatalogo().getCruceros()) { String[] ciudades = crucero.getItinerario().split("-"); for (String ciudad : ciudades) if (ciudad.equals(filtro)) { añadirCruceroTabla(crucero); } } } } public void agregarTablaMenores() { String filtro = new String(); for (Component componente : pnOpcionesFiltros.getComponents()) { JRadioButton radio = (JRadioButton) componente; if (radio.isSelected()) { filtro = radio.getText(); break; } } boolean admisionMenores = false; if (filtro.equals("Si")) admisionMenores = true; for (Crucero crucero : getVp().getCatalogo().getCruceros()) { if (crucero.isMenores() == admisionMenores) { añadirCruceroTabla(crucero); } } } public void agregarTablaDiasDuracion() { JSlider radio = (JSlider) pnOpcionesFiltros.getComponent(0); int dias = radio.getValue(); for (Crucero crucero : getVp().getCatalogo().getCruceros()) { if (crucero.getDuracionDias() <= dias) { añadirCruceroTabla(crucero); } } } @SuppressWarnings("unchecked") public void agregarTablaFechas() { JComboBox<String> combo = (JComboBox<String>) pnOpcionesFiltros .getComponent(0); String seleccion = (String) combo.getSelectedItem(); String[] aux2 = seleccion.split(" "); for (int i = 0; i < getVp().getMeses().length; i++) { if (getVp().getMeses()[i].equals(aux2[0])) { aux2[0] = "" + (i + 1); break; } } seleccion = aux2[0] + "/" + aux2[1]; ArrayList<Crucero> cruceros = new ArrayList<Crucero>(); for (Crucero crucero : getVp().getCatalogo().getCruceros()) { for (int i = 0; i < crucero.getFechas().length; i++) { if (!cruceros.contains(crucero) && crucero.getFechas()[i].contains(seleccion)) { cruceros.add(crucero); } } } for (Crucero crucero : cruceros) añadirCruceroTabla(crucero); } public void agregarTablaBarco() { String filtro = new String(); for (Component componente : pnOpcionesFiltros.getComponents()) { JRadioButton radio = (JRadioButton) componente; if (radio.isSelected()) { filtro = radio.getText(); break; } } if (filtro.equals("Todos")) agregarTodo(); else { for (Crucero crucero : getVp().getCatalogo().getCruceros()) { if (crucero.getBarco().getDenominacion().equals(filtro)) { añadirCruceroTabla(crucero); } } } } @SuppressWarnings("unchecked") public void agregarTablaPrecio() { JComboBox<String> desde = (JComboBox<String>) pnOpcionesFiltros .getComponent(1); JComboBox<String> hasta = (JComboBox<String>) pnOpcionesFiltros .getComponent(3); String desdeString = (String) desde.getSelectedItem(); float precioDesde = Float .parseFloat(desdeString.substring(0, desdeString.length() - 2)); String hastaString = (String) hasta.getSelectedItem(); float precioHasta = Float .parseFloat(hastaString.substring(0, desdeString.length() - 2)); for (Crucero crucero : getVp().getCatalogo().getCruceros()) { if (crucero.getBarco() .getPrecioCamarotesDoblesExteriores() >= precioDesde && crucero.getBarco() .getPrecioCamarotesDoblesExteriores() <= precioHasta || crucero.getBarco() .getPrecioCamarotesDoblesInteriores() >= precioDesde && crucero.getBarco() .getPrecioCamarotesDoblesInteriores() <= precioHasta || crucero.getBarco() .getPrecioCamarotesFamiliaresExteriores() >= precioDesde && crucero.getBarco() .getPrecioCamarotesFamiliaresExteriores() <= precioHasta || crucero.getBarco() .getPrecioCamarotesFamiliaresInteriores() >= precioDesde && crucero.getBarco() .getPrecioCamarotesFamiliaresInteriores() <= precioHasta) añadirCruceroTabla(crucero); } } public void añadirCruceroTabla(Crucero crucero) { String aux = new String(), menores = "No"; for (String a : crucero.getFechas()) aux += a + " - "; if (crucero.isMenores()) menores = "Si"; String descuento = "No"; if (crucero.isDescuento()) descuento = "Si"; JRadioButton radio = new JRadioButton(); grupoBotonesTabla.add(radio); getModeloTablaCruceros().addRow(new Object[] { crucero.getZona(), crucero.getPuertoSalida(), crucero.getItinerario(), menores, crucero.getDuracionDias(), aux.substring(0, aux.length() - 3), crucero.getBarco().getDenominacion(), descuento, radio }); int[] tamaño = new int[8]; for (int i = 0; i < tablaCruceros.getColumnCount() - 1; i++) { for (int j = 0; j < tablaCruceros.getRowCount(); j++) { if (tamaño[i] < tablaCruceros.getValueAt(j, i).toString() .length()) { tamaño[i] = tablaCruceros.getValueAt(j, i).toString() .length(); } } } tablaCruceros.getColumnModel().getColumn(0) .setPreferredWidth(tamaño[0] * 10); tablaCruceros.getColumnModel().getColumn(1).setPreferredWidth(125); tablaCruceros.getColumnModel().getColumn(2) .setPreferredWidth(tamaño[2] * 7); tablaCruceros.getColumnModel().getColumn(3).setPreferredWidth(150); tablaCruceros.getColumnModel().getColumn(4).setPreferredWidth(125); tablaCruceros.getColumnModel().getColumn(5) .setPreferredWidth(tamaño[5] * 7); tablaCruceros.getColumnModel().getColumn(6) .setPreferredWidth(tamaño[6] * 10); tablaCruceros.getColumnModel().getColumn(7).setPreferredWidth(100); tablaCruceros.getColumnModel().getColumn(8).setPreferredWidth(100); } public void agregarTodo() { for (Crucero crucero : getVp().getCatalogo().getCruceros()) añadirCruceroTabla(crucero); } private void cargarFiltrosPuertoSalida() { ArrayList<String> filtros = new ArrayList<String>(); for (Crucero a : getVp().getCatalogo().getCruceros()) if (!filtros.contains(a.getPuertoSalida())) filtros.add(a.getPuertoSalida()); añadirRadioBoton(filtros); } private void cargarFiltrosItinerario() { ArrayList<String> filtros = new ArrayList<String>(); for (Crucero a : getVp().getCatalogo().getCruceros()) if (!filtros.contains(a.getItinerario())) filtros.add(a.getItinerario()); ArrayList<String> ciudades = new ArrayList<String>(); for (String a : filtros) { String[] b = a.split("-"); for (String c : b) if (!ciudades.contains(c)) ciudades.add(c); } añadirRadioBoton(ciudades); } private void cargarFiltrosMenores() { JRadioButton radio = new JRadioButton("Si", true); radio.addActionListener(new FiltrosCruceros(this)); grupoBotonesFiltros.add(radio); pnOpcionesFiltros.add(radio); JRadioButton radio2 = new JRadioButton("No"); radio2.addActionListener(new FiltrosCruceros(this)); grupoBotonesFiltros.add(radio2); pnOpcionesFiltros.add(radio2); } private void cargarFiltrosDiasDuracion() { int max = 0, min = Integer.MAX_VALUE; for (Crucero a : getVp().getCatalogo().getCruceros()) { if (max < a.getDuracionDias()) max = a.getDuracionDias(); if (min > a.getDuracionDias()) min = a.getDuracionDias(); } JSlider slider = new JSlider(min, max); slider.setMajorTickSpacing(1); slider.setPaintLabels(true); slider.setPaintTicks(true); slider.setPaintTrack(true); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent arg0) { borrarTabla(); agregarTablaDiasDuracion(); } }); pnOpcionesFiltros.add(slider); } private void cargarFiltrosFechas() { ArrayList<String> fechasCruceros = new ArrayList<String>(); for (Crucero crucero : getVp().getCatalogo().getCruceros()) { for (String fecha : crucero.getFechas()) fechasCruceros.add(fecha); } int mesMax = 0, anioMax = 0, mesMin = Integer.MAX_VALUE, anioMin = Integer.MAX_VALUE; for (String fecha : fechasCruceros) { String[] aux = fecha.split("/"); int mes = Integer.parseInt(aux[1]); int anio = Integer.parseInt(aux[2]); if (mesMax < mes) mesMax = mes; if (mesMin > mes) mesMin = mes; if (anioMax < anio) anioMax = anio; if (anioMin > anio) anioMin = anio; } int numeroMeses = mesMax - mesMin + 1; if (anioMax > anioMin) { int mesesDeMas = 0; for (String fecha : fechasCruceros) { String[] aux = fecha.split("/"); if (aux[2].equals(String.valueOf(anioMax))) mesesDeMas = Integer.valueOf(aux[1]); } numeroMeses += mesesDeMas; } JComboBox<String> mesesSalidasCruceros = new JComboBox<String>(); String[] salidas = new String[numeroMeses]; for (int i = 0; i < salidas.length; i++) { if (i < 12) salidas[i] = getVp().getMeses()[i] + " " + anioMin; else salidas[i] = getVp().getMeses()[i - 12] + " " + (anioMin + 1); } mesesSalidasCruceros.addActionListener(new FiltrosCruceros(this)); pnOpcionesFiltros.add(mesesSalidasCruceros); mesesSalidasCruceros .setModel(new DefaultComboBoxModel<String>(salidas)); } private void cargarFiltrosBarco() { ArrayList<String> filtros = new ArrayList<String>(); for (Crucero a : getVp().getCatalogo().getCruceros()) if (!filtros.contains(a.getBarco().getDenominacion())) filtros.add(a.getBarco().getDenominacion()); añadirRadioBoton(filtros); } private void cargarFiltrosPrecio() { float precioMaximo = 0; for (Crucero crucero : getVp().getCatalogo().getCruceros()) { if (crucero.getBarco().getPrecioCamarotesDoblesExteriores() > 0) precioMaximo = crucero.getBarco() .getPrecioCamarotesDoblesExteriores(); if (crucero.getBarco().getPrecioCamarotesDoblesInteriores() > 0) precioMaximo = crucero.getBarco() .getPrecioCamarotesDoblesInteriores(); if (crucero.getBarco().getPrecioCamarotesFamiliaresExteriores() > 0) precioMaximo = crucero.getBarco() .getPrecioCamarotesFamiliaresExteriores(); if (crucero.getBarco().getPrecioCamarotesFamiliaresInteriores() > 0) precioMaximo = crucero.getBarco() .getPrecioCamarotesFamiliaresInteriores(); } ArrayList<String> precios = new ArrayList<String>(); while (precioMaximo > 0) { precios.add("" + precioMaximo + " €"); precioMaximo -= 10; } DefaultComboBoxModel<String> modeloPrecioDesde = new DefaultComboBoxModel<String>(); DefaultComboBoxModel<String> modeloPrecioHasta = new DefaultComboBoxModel<String>(); for (int i = precios.size() - 1; i >= 0; i--) { if (i == 0) modeloPrecioDesde.addElement(precios.get(i)); else if (i == precios.size() - 1) modeloPrecioHasta.addElement(precios.get(i)); else { modeloPrecioDesde.addElement(precios.get(i)); modeloPrecioHasta.addElement(precios.get(i)); } } JLabel lblDesdePrecio = new JLabel("Desde:"); pnOpcionesFiltros.add(lblDesdePrecio); JComboBox<String> cbDesdePrecio = new JComboBox<String>(); cbDesdePrecio.setModel(modeloPrecioHasta); pnOpcionesFiltros.add(cbDesdePrecio); lblDesdePrecio.setLabelFor(cbDesdePrecio); lblDesdePrecio.setDisplayedMnemonic('D'); JLabel lblHastaPrecio = new JLabel("Hasta:"); pnOpcionesFiltros.add(lblHastaPrecio); JComboBox<String> cbHastaPrecio = new JComboBox<String>(); cbHastaPrecio.setModel(modeloPrecioDesde); pnOpcionesFiltros.add(cbHastaPrecio); cbHastaPrecio.setSelectedIndex(modeloPrecioDesde.getSize() - 1); lblHastaPrecio.setLabelFor(cbHastaPrecio); lblHastaPrecio.setDisplayedMnemonic('H'); cbDesdePrecio.addActionListener(new FiltrosCruceros(this)); cbHastaPrecio.addActionListener(new FiltrosCruceros(this)); } public JComboBox<String> getCbOpcionesFiltros() { return cbOpcionesFiltros; } public void setCbOpcionesFiltros(JComboBox<String> cbOpcionesFiltros) { this.cbOpcionesFiltros = cbOpcionesFiltros; } public DefaultTableModel getModeloTablaCruceros() { return modeloTablaCruceros; } public void setModeloTablaCruceros(DefaultTableModel modeloTablaCruceros) { this.modeloTablaCruceros = modeloTablaCruceros; } public VentanaPrincipal getVp() { return vp; } public void setVp(VentanaPrincipal vp) { this.vp = vp; } }
true
46cb15729eeb4482ffc9e4f9ed85141b3309d1e3
Java
erikness/graph
/src/com/erikleeness/graph/Vector2D.java
UTF-8
496
3.078125
3
[]
no_license
package com.erikleeness.graph; public class Vector2D { public Vector2D(double x, double y) { this.x = x; this.y = y; } public double x; public double y; public boolean inBounds(int xmin, int ymin, int xmax, int ymax) { return x >= xmin && x <= xmax && y >= ymin && y <= ymax; } public boolean isFinite() { return !(Double.isInfinite(x) || Double.isInfinite(y) || Double.isNaN(x) || Double.isNaN(y)); } public String toString() { return "(" + x + "," + y + ")"; } }
true
34b603e1bf7ddd2113da52c1c8ef2b2c8085e736
Java
AmryRp/HRManagement
/src/models/EntityLocation.java
UTF-8
1,628
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 models; /** * * @author amry4 */ public class EntityLocation { private Integer Id; public EntityLocation() { } private String Address; private String ZipCode; public EntityLocation(Integer Id, String Address, String ZipCode, String City, String Province, String idCountry) { this.Id = Id; this.Address = Address; this.ZipCode = ZipCode; this.City = City; this.Province = Province; this.idCountry = idCountry; } private String City; private String Province; private String idCountry; public Integer getId() { return Id; } public void setId(int Id) { this.Id = Id; } public String getAddress() { return Address; } public void setAdrress(String Address) { this.Address = Address; } public String getZipCode() { return ZipCode; } public void setZipCode(String ZipCode) { this.ZipCode = ZipCode; } public String getCity() { return City; } public void setCity(String City) { this.City = City; } public String getProvince() { return Province; } public void setProvince(String Province) { this.Province = Province; } public String getIdCountry() { return idCountry; } public void setIdCountry(String idCounty) { this.idCountry = idCounty; } }
true
1a6152851e432e2487785d7eb58db424db93a9c4
Java
HeNanFei/graduation
/mservice2/src/main/java/com/zjt/graduation/mservice2/config/RabbitMessageListener.java
UTF-8
2,705
2.046875
2
[]
no_license
package com.zjt.graduation.mservice2.config; import cn.hutool.json.JSONUtil; import com.fasterxml.jackson.databind.ObjectMapper; import com.rabbitmq.client.Channel; import com.zjt.graduation.common.dto.order.Messager; import com.zjt.graduation.common.entity.Orders; import com.zjt.graduation.common.entity.SellGood; import com.zjt.graduation.common.service.OrderService; import com.zjt.graduation.common.service.SellGoodService; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.List; @Component public class RabbitMessageListener implements ChannelAwareMessageListener { private static final String ORDER_PREFIX= "ORDER_PREFIX_"; @Autowired private RedisTemplate redisTemplate; @Autowired private OrderService orderService; @Autowired private SellGoodService sellGoodService; @Autowired private ObjectMapper objectMapper; @RabbitListener(queues = "deadQueue" , ackMode = "MANUAL") @Override public void onMessage(Message message, Channel channel) throws Exception { try{ //System.out.println(String.valueOf(message.getBody())); String jsonString = new String(message.getBody(),"UTF-8"); //订单超时未支付 Messager messager = JSONUtil.toBean(jsonString, Messager.class); Orders byId = orderService.getById(messager.getOrderId()); byId.setStatus(2); byId.setStatusText("订单超时关闭"); orderService.updateById(byId); Long sellGoodId = byId.getSellGoodId(); SellGood sellGood = sellGoodService.getById(sellGoodId); Integer total = sellGood.getNumber()+byId.getNumber(); sellGood.setNumber(total); sellGoodService.updateById(sellGood); List<String> range = redisTemplate.opsForList().range(ORDER_PREFIX + sellGood.getGoodName() + "_record", 0, 10000); if(!CollectionUtils.isEmpty(range)){ redisTemplate.opsForList().leftPop(ORDER_PREFIX + sellGood.getGoodName() + "_record"); } channel.basicAck(message.getMessageProperties().getDeliveryTag(),true); }catch (Exception e){ //channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,false); e.printStackTrace(); } } }
true
90d056ffb279bfda68fd113fcdcfe53028a20f25
Java
valetedo/seeg-sampling
/src/main/java/com/biolab/xtens/contact/bean/PersonalData.java
UTF-8
45,050
1.984375
2
[]
no_license
package com.biolab.xtens.contact.bean; import java.util.Date; public class PersonalData { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_PRS_DATA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private Integer idPrsData; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.SURNAME * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String surname; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.NAME * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String name; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_SEX * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idSex; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.BIRTH_DATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private Date birthDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.DECEASE_DATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private Date deceaseDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.INSERT_DATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private Date insertDate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.DATE_LAST_UPDATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private Date dateLastUpdate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_BIR_MUNICIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idBirMunicip; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_BIR_SUBAREA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idBirSubarea; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_NATIONALITY * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idNationality; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_CITIZENSHIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idCitizenship; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_MARITAL_STATUS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idMaritalStatus; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_PROFESSION * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idProfession; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.RES_CAP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String resCap; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.RES_ADDRESS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String resAddress; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_RES_MUNICIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idResMunicip; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_RES_SUBAREA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idResSubarea; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.DOM_ADDRESS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String domAddress; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_DOM_MUNICIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idDomMunicip; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_DOM_SUBAREA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idDomSubarea; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.DOM_CAP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String domCap; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.TEL1_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String tel1Pref; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.TEL1_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String tel1Num; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.TEL2_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String tel2Pref; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.TEL2_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String tel2Num; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.TEL3_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String tel3Pref; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.TEL3_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String tel3Num; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.FAX_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String faxPref; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.FAX_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String faxNum; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.EMAIL * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String email; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.TAX_CODE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String taxCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.HEALTH_CODE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String healthCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.EXPIRE_HEALTH_CODE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private Date expireHealthCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_EDUCATION * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String idEducation; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.ID_FAMILY_DOCTOR * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private Long idFamilyDoctor; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.DELETED * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String deleted; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.EXT_CONTACT * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String extContact; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.EXT_TEL_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String extTelPref; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.EXT_TEL_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String extTelNum; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.EXT_ADDRESS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String extAddress; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.CLINICAL_NOTES * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String clinicalNotes; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.FIRST_VISIT * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String firstVisit; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column PERSONAL_DATA.LAST_VISIT * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ private String lastVisit; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_PRS_DATA * * @return the value of PERSONAL_DATA.ID_PRS_DATA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public Integer getIdPrsData() { return idPrsData; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_PRS_DATA * * @param idPrsData the value for PERSONAL_DATA.ID_PRS_DATA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdPrsData(Integer idPrsData) { this.idPrsData = idPrsData; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.SURNAME * * @return the value of PERSONAL_DATA.SURNAME * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getSurname() { return surname; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.SURNAME * * @param surname the value for PERSONAL_DATA.SURNAME * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setSurname(String surname) { this.surname = surname == null ? null : surname.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.NAME * * @return the value of PERSONAL_DATA.NAME * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.NAME * * @param name the value for PERSONAL_DATA.NAME * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_SEX * * @return the value of PERSONAL_DATA.ID_SEX * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdSex() { return idSex; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_SEX * * @param idSex the value for PERSONAL_DATA.ID_SEX * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdSex(String idSex) { this.idSex = idSex == null ? null : idSex.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.BIRTH_DATE * * @return the value of PERSONAL_DATA.BIRTH_DATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public Date getBirthDate() { return birthDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.BIRTH_DATE * * @param birthDate the value for PERSONAL_DATA.BIRTH_DATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.DECEASE_DATE * * @return the value of PERSONAL_DATA.DECEASE_DATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public Date getDeceaseDate() { return deceaseDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.DECEASE_DATE * * @param deceaseDate the value for PERSONAL_DATA.DECEASE_DATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setDeceaseDate(Date deceaseDate) { this.deceaseDate = deceaseDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.INSERT_DATE * * @return the value of PERSONAL_DATA.INSERT_DATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public Date getInsertDate() { return insertDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.INSERT_DATE * * @param insertDate the value for PERSONAL_DATA.INSERT_DATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setInsertDate(Date insertDate) { this.insertDate = insertDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.DATE_LAST_UPDATE * * @return the value of PERSONAL_DATA.DATE_LAST_UPDATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public Date getDateLastUpdate() { return dateLastUpdate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.DATE_LAST_UPDATE * * @param dateLastUpdate the value for PERSONAL_DATA.DATE_LAST_UPDATE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setDateLastUpdate(Date dateLastUpdate) { this.dateLastUpdate = dateLastUpdate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_BIR_MUNICIP * * @return the value of PERSONAL_DATA.ID_BIR_MUNICIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdBirMunicip() { return idBirMunicip; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_BIR_MUNICIP * * @param idBirMunicip the value for PERSONAL_DATA.ID_BIR_MUNICIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdBirMunicip(String idBirMunicip) { this.idBirMunicip = idBirMunicip == null ? null : idBirMunicip.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_BIR_SUBAREA * * @return the value of PERSONAL_DATA.ID_BIR_SUBAREA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdBirSubarea() { return idBirSubarea; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_BIR_SUBAREA * * @param idBirSubarea the value for PERSONAL_DATA.ID_BIR_SUBAREA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdBirSubarea(String idBirSubarea) { this.idBirSubarea = idBirSubarea == null ? null : idBirSubarea.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_NATIONALITY * * @return the value of PERSONAL_DATA.ID_NATIONALITY * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdNationality() { return idNationality; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_NATIONALITY * * @param idNationality the value for PERSONAL_DATA.ID_NATIONALITY * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdNationality(String idNationality) { this.idNationality = idNationality == null ? null : idNationality.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_CITIZENSHIP * * @return the value of PERSONAL_DATA.ID_CITIZENSHIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdCitizenship() { return idCitizenship; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_CITIZENSHIP * * @param idCitizenship the value for PERSONAL_DATA.ID_CITIZENSHIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdCitizenship(String idCitizenship) { this.idCitizenship = idCitizenship == null ? null : idCitizenship.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_MARITAL_STATUS * * @return the value of PERSONAL_DATA.ID_MARITAL_STATUS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdMaritalStatus() { return idMaritalStatus; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_MARITAL_STATUS * * @param idMaritalStatus the value for PERSONAL_DATA.ID_MARITAL_STATUS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdMaritalStatus(String idMaritalStatus) { this.idMaritalStatus = idMaritalStatus == null ? null : idMaritalStatus.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_PROFESSION * * @return the value of PERSONAL_DATA.ID_PROFESSION * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdProfession() { return idProfession; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_PROFESSION * * @param idProfession the value for PERSONAL_DATA.ID_PROFESSION * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdProfession(String idProfession) { this.idProfession = idProfession == null ? null : idProfession.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.RES_CAP * * @return the value of PERSONAL_DATA.RES_CAP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getResCap() { return resCap; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.RES_CAP * * @param resCap the value for PERSONAL_DATA.RES_CAP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setResCap(String resCap) { this.resCap = resCap == null ? null : resCap.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.RES_ADDRESS * * @return the value of PERSONAL_DATA.RES_ADDRESS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getResAddress() { return resAddress; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.RES_ADDRESS * * @param resAddress the value for PERSONAL_DATA.RES_ADDRESS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setResAddress(String resAddress) { this.resAddress = resAddress == null ? null : resAddress.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_RES_MUNICIP * * @return the value of PERSONAL_DATA.ID_RES_MUNICIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdResMunicip() { return idResMunicip; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_RES_MUNICIP * * @param idResMunicip the value for PERSONAL_DATA.ID_RES_MUNICIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdResMunicip(String idResMunicip) { this.idResMunicip = idResMunicip == null ? null : idResMunicip.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_RES_SUBAREA * * @return the value of PERSONAL_DATA.ID_RES_SUBAREA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdResSubarea() { return idResSubarea; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_RES_SUBAREA * * @param idResSubarea the value for PERSONAL_DATA.ID_RES_SUBAREA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdResSubarea(String idResSubarea) { this.idResSubarea = idResSubarea == null ? null : idResSubarea.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.DOM_ADDRESS * * @return the value of PERSONAL_DATA.DOM_ADDRESS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getDomAddress() { return domAddress; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.DOM_ADDRESS * * @param domAddress the value for PERSONAL_DATA.DOM_ADDRESS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setDomAddress(String domAddress) { this.domAddress = domAddress == null ? null : domAddress.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_DOM_MUNICIP * * @return the value of PERSONAL_DATA.ID_DOM_MUNICIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdDomMunicip() { return idDomMunicip; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_DOM_MUNICIP * * @param idDomMunicip the value for PERSONAL_DATA.ID_DOM_MUNICIP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdDomMunicip(String idDomMunicip) { this.idDomMunicip = idDomMunicip == null ? null : idDomMunicip.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_DOM_SUBAREA * * @return the value of PERSONAL_DATA.ID_DOM_SUBAREA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdDomSubarea() { return idDomSubarea; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_DOM_SUBAREA * * @param idDomSubarea the value for PERSONAL_DATA.ID_DOM_SUBAREA * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdDomSubarea(String idDomSubarea) { this.idDomSubarea = idDomSubarea == null ? null : idDomSubarea.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.DOM_CAP * * @return the value of PERSONAL_DATA.DOM_CAP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getDomCap() { return domCap; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.DOM_CAP * * @param domCap the value for PERSONAL_DATA.DOM_CAP * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setDomCap(String domCap) { this.domCap = domCap == null ? null : domCap.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.TEL1_PREF * * @return the value of PERSONAL_DATA.TEL1_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getTel1Pref() { return tel1Pref; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.TEL1_PREF * * @param tel1Pref the value for PERSONAL_DATA.TEL1_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setTel1Pref(String tel1Pref) { this.tel1Pref = tel1Pref == null ? null : tel1Pref.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.TEL1_NUM * * @return the value of PERSONAL_DATA.TEL1_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getTel1Num() { return tel1Num; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.TEL1_NUM * * @param tel1Num the value for PERSONAL_DATA.TEL1_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setTel1Num(String tel1Num) { this.tel1Num = tel1Num == null ? null : tel1Num.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.TEL2_PREF * * @return the value of PERSONAL_DATA.TEL2_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getTel2Pref() { return tel2Pref; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.TEL2_PREF * * @param tel2Pref the value for PERSONAL_DATA.TEL2_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setTel2Pref(String tel2Pref) { this.tel2Pref = tel2Pref == null ? null : tel2Pref.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.TEL2_NUM * * @return the value of PERSONAL_DATA.TEL2_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getTel2Num() { return tel2Num; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.TEL2_NUM * * @param tel2Num the value for PERSONAL_DATA.TEL2_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setTel2Num(String tel2Num) { this.tel2Num = tel2Num == null ? null : tel2Num.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.TEL3_PREF * * @return the value of PERSONAL_DATA.TEL3_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getTel3Pref() { return tel3Pref; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.TEL3_PREF * * @param tel3Pref the value for PERSONAL_DATA.TEL3_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setTel3Pref(String tel3Pref) { this.tel3Pref = tel3Pref == null ? null : tel3Pref.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.TEL3_NUM * * @return the value of PERSONAL_DATA.TEL3_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getTel3Num() { return tel3Num; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.TEL3_NUM * * @param tel3Num the value for PERSONAL_DATA.TEL3_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setTel3Num(String tel3Num) { this.tel3Num = tel3Num == null ? null : tel3Num.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.FAX_PREF * * @return the value of PERSONAL_DATA.FAX_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getFaxPref() { return faxPref; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.FAX_PREF * * @param faxPref the value for PERSONAL_DATA.FAX_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setFaxPref(String faxPref) { this.faxPref = faxPref == null ? null : faxPref.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.FAX_NUM * * @return the value of PERSONAL_DATA.FAX_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getFaxNum() { return faxNum; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.FAX_NUM * * @param faxNum the value for PERSONAL_DATA.FAX_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setFaxNum(String faxNum) { this.faxNum = faxNum == null ? null : faxNum.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.EMAIL * * @return the value of PERSONAL_DATA.EMAIL * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getEmail() { return email; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.EMAIL * * @param email the value for PERSONAL_DATA.EMAIL * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setEmail(String email) { this.email = email == null ? null : email.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.TAX_CODE * * @return the value of PERSONAL_DATA.TAX_CODE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getTaxCode() { return taxCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.TAX_CODE * * @param taxCode the value for PERSONAL_DATA.TAX_CODE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setTaxCode(String taxCode) { this.taxCode = taxCode == null ? null : taxCode.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.HEALTH_CODE * * @return the value of PERSONAL_DATA.HEALTH_CODE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getHealthCode() { return healthCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.HEALTH_CODE * * @param healthCode the value for PERSONAL_DATA.HEALTH_CODE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setHealthCode(String healthCode) { this.healthCode = healthCode == null ? null : healthCode.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.EXPIRE_HEALTH_CODE * * @return the value of PERSONAL_DATA.EXPIRE_HEALTH_CODE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public Date getExpireHealthCode() { return expireHealthCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.EXPIRE_HEALTH_CODE * * @param expireHealthCode the value for PERSONAL_DATA.EXPIRE_HEALTH_CODE * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setExpireHealthCode(Date expireHealthCode) { this.expireHealthCode = expireHealthCode; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_EDUCATION * * @return the value of PERSONAL_DATA.ID_EDUCATION * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getIdEducation() { return idEducation; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_EDUCATION * * @param idEducation the value for PERSONAL_DATA.ID_EDUCATION * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdEducation(String idEducation) { this.idEducation = idEducation == null ? null : idEducation.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.ID_FAMILY_DOCTOR * * @return the value of PERSONAL_DATA.ID_FAMILY_DOCTOR * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public Long getIdFamilyDoctor() { return idFamilyDoctor; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.ID_FAMILY_DOCTOR * * @param idFamilyDoctor the value for PERSONAL_DATA.ID_FAMILY_DOCTOR * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setIdFamilyDoctor(Long idFamilyDoctor) { this.idFamilyDoctor = idFamilyDoctor; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.DELETED * * @return the value of PERSONAL_DATA.DELETED * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getDeleted() { return deleted; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.DELETED * * @param deleted the value for PERSONAL_DATA.DELETED * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setDeleted(String deleted) { this.deleted = deleted == null ? null : deleted.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.EXT_CONTACT * * @return the value of PERSONAL_DATA.EXT_CONTACT * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getExtContact() { return extContact; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.EXT_CONTACT * * @param extContact the value for PERSONAL_DATA.EXT_CONTACT * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setExtContact(String extContact) { this.extContact = extContact == null ? null : extContact.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.EXT_TEL_PREF * * @return the value of PERSONAL_DATA.EXT_TEL_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getExtTelPref() { return extTelPref; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.EXT_TEL_PREF * * @param extTelPref the value for PERSONAL_DATA.EXT_TEL_PREF * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setExtTelPref(String extTelPref) { this.extTelPref = extTelPref == null ? null : extTelPref.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.EXT_TEL_NUM * * @return the value of PERSONAL_DATA.EXT_TEL_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getExtTelNum() { return extTelNum; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.EXT_TEL_NUM * * @param extTelNum the value for PERSONAL_DATA.EXT_TEL_NUM * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setExtTelNum(String extTelNum) { this.extTelNum = extTelNum == null ? null : extTelNum.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.EXT_ADDRESS * * @return the value of PERSONAL_DATA.EXT_ADDRESS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getExtAddress() { return extAddress; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.EXT_ADDRESS * * @param extAddress the value for PERSONAL_DATA.EXT_ADDRESS * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setExtAddress(String extAddress) { this.extAddress = extAddress == null ? null : extAddress.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.CLINICAL_NOTES * * @return the value of PERSONAL_DATA.CLINICAL_NOTES * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getClinicalNotes() { return clinicalNotes; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.CLINICAL_NOTES * * @param clinicalNotes the value for PERSONAL_DATA.CLINICAL_NOTES * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setClinicalNotes(String clinicalNotes) { this.clinicalNotes = clinicalNotes == null ? null : clinicalNotes.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.FIRST_VISIT * * @return the value of PERSONAL_DATA.FIRST_VISIT * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getFirstVisit() { return firstVisit; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.FIRST_VISIT * * @param firstVisit the value for PERSONAL_DATA.FIRST_VISIT * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setFirstVisit(String firstVisit) { this.firstVisit = firstVisit == null ? null : firstVisit.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column PERSONAL_DATA.LAST_VISIT * * @return the value of PERSONAL_DATA.LAST_VISIT * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public String getLastVisit() { return lastVisit; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column PERSONAL_DATA.LAST_VISIT * * @param lastVisit the value for PERSONAL_DATA.LAST_VISIT * * @mbggenerated Sun Apr 14 16:24:57 CEST 2013 */ public void setLastVisit(String lastVisit) { this.lastVisit = lastVisit == null ? null : lastVisit.trim(); } }
true
19ff2b4c8e25d7688e55b20a2bafe4266e170828
Java
HEITAOCHAO/tensqure
/tensquare_user/src/main/java/com/tensquare/user/interceptor/JWTInterceptor.java
UTF-8
1,045
2.359375
2
[]
no_license
package com.tensquare.user.interceptor; import io.jsonwebtoken.Claims; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import util.JwtUtil; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class JWTInterceptor extends HandlerInterceptorAdapter { @Autowired private JwtUtil jwtUtil; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("经过拦截器!"); try { String token = request.getHeader("token"); Claims claims = jwtUtil.parser(token); if(claims.get("roles").equals("admin")){ request.setAttribute("admin_claims", claims); }else if(claims.get("roles").equals("user")){ request.setAttribute("user_claims", claims); } }catch (Exception e){ e.printStackTrace(); return false; } return true; } }
true
3b1ac954489556659534dc7a99a587c62c0148fe
Java
dalzinho/terminus
/src/main/java/com/terminl/demo/database/entity/visit/AirportVisitRepository.java
UTF-8
263
1.640625
2
[]
no_license
package com.terminl.demo.database.entity.visit; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface AirportVisitRepository extends JpaRepository<AirportVisit, Integer> { }
true
080203c58ee196aff09c8aa30c8823d467203ada
Java
uiocool/MyDemo
/app/src/main/java/com/example/administrator/mydemo/util/JsonUtil.java
UTF-8
2,646
2.5
2
[]
no_license
package com.example.administrator.mydemo.util; import com.example.administrator.mydemo.entity.AtDemand; import com.example.administrator.mydemo.entity.TabAccount; import com.example.administrator.mydemo.entity.TestData; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class JsonUtil { public static List<TestData> TestJson(String json){ //Json的解析类对象 JsonParser parser = new JsonParser(); //将JSON的String 转成一个JsonArray对象 JsonArray jsonArray = parser.parse(json).getAsJsonArray(); Gson gson = new Gson(); ArrayList<TestData> list = new ArrayList<>(); //加强for循环遍历JsonArray for (JsonElement testdata : jsonArray) { //使用GSON,直接转成Bean对象 TestData td = gson.fromJson(testdata, TestData.class); list.add(td); } return list; } public static List<AtDemand> toAtDemandList(String json){ //Json的解析类对象 JsonParser parser = new JsonParser(); //将JSON的String 转成一个JsonArray对象 JsonArray jsonArray = parser.parse(json).getAsJsonArray(); Gson gson = new Gson(); ArrayList<AtDemand> list = new ArrayList<>(); //加强for循环遍历JsonArray for (JsonElement atDemand : jsonArray) { //使用GSON,直接转成Bean对象 AtDemand ar = gson.fromJson(atDemand, AtDemand.class); list.add(ar); } return list; } public static List<TabAccount> toTabAccount(String json){ //Json的解析类对象 JsonParser parser = new JsonParser(); //将JSON的String 转成一个JsonArray对象 JsonArray jsonArray = parser.parse(json).getAsJsonArray(); Gson gson = new Gson(); ArrayList<TabAccount> list = new ArrayList<>(); //加强for循环遍历JsonArray for (JsonElement tabAccount : jsonArray) { //使用GSON,直接转成Bean对象 TabAccount ta = gson.fromJson(tabAccount, TabAccount.class); list.add(ta); } return list; } public static boolean IsJson(String json){ boolean b = false; JsonParser parser = new JsonParser(); try { JsonArray jsonArray = parser.parse(json).getAsJsonArray(); b = true; }catch (Exception e){ b = false; } return b; } }
true
92b04ecb75aec5b4bcf14f4fc4d7155f16845991
Java
bestjonav2/EVA3_PRACTICAS
/EVA3_11_BROADCAST_RECIEVER/app/src/main/java/com/bj/j622/eva3_11_broadcast_reciever/CustomService.java
UTF-8
1,665
2.609375
3
[]
no_license
package com.bj.j622.eva3_11_broadcast_reciever; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class CustomService extends Service { Thread hilo; Intent dataIntent; @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @Override public void onCreate() { super.onCreate(); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); dataIntent = new Intent("service"); dataIntent.putExtra("msg","start"); sendBroadcast(dataIntent); Runnable run346 = new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(1000); Log.wtf("aaaaa??","test"); dataIntent = new Intent("service"); dataIntent.putExtra("msg","test"); sendBroadcast(dataIntent); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }; hilo = new Thread(run346); hilo.start(); } @Override public void onDestroy() { super.onDestroy(); hilo.interrupt(); dataIntent = new Intent("service"); dataIntent.putExtra("msg","destroy"); sendBroadcast(dataIntent); } }
true
7db25850b78d61493f5e7a5bdae358ba799003af
Java
michaelpcote/HealthSystem
/Health_Interactions/src/PatientDAOTest.java
UTF-8
752
2.265625
2
[]
no_license
import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import dao.oracle.PatientDAO; import beans.Patient; public class PatientDAOTest { private Patient patient = null; @Before public void setUp() throws Exception { patient = new Patient(); patient.setAddress("1409 Kennon Road"); patient.setCity("Garner"); patient.setState("NC"); patient.setZip("27529"); patient.setFname("Michael"); patient.setLname("Cote'"); patient.setSex(1); patient.setDob("1979-03-03"); patient.setPublicStatus("yes"); } @After public void tearDown() throws Exception { } @Test public void testInsertPatient() { PatientDAO pdao = new PatientDAO(); pdao.insertPatient(patient); } }
true
284e15f331d62e8f80898c7de7221c8600dbe813
Java
richardvclam/arbitrader
/src/main/java/com/rlam/arbitrader/App.java
UTF-8
3,458
3.140625
3
[]
no_license
package com.rlam.arbitrader; import java.util.ArrayList; public class App { public static final boolean test = true; public static String[] currencies = {"USD", "BTC", "ETH", "LTC"}; public static double[][] marketRates = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; private static double initialStake = 1000; private ArrayList<String[]> opportunity; private double orderPrice; private String orderID; private boolean inTransaction; public App() { inTransaction = false; orderPrice = 0; orderID = ""; } public void onArbitrageOpportunity(ArrayList<String[]> opportunity) { if (!inTransaction) { System.out.println("There is an opportunity!"); this.opportunity = opportunity; // Set a limit buy order for first transaction Market marketObj = getMarket(opportunity.get(0)[0], opportunity.get(0)[1]); orderPrice = marketObj.getPrice() - marketObj.getIncrement(); System.out.println("Buying @ " + orderPrice); inTransaction = true; if (!test) { // TODO write the real HTTP POST requests } } } public void onPriceChange(Market marketObj) { } private static Market getMarket(String from, String to) { for (Market m : Market.values()) { String market = m.getMarket(); if (market.equals(from + "-" + to) || market.equals(to + "-" + from)) { return m; } } return null; } public static void main(String[] args) { App app = new App(); // MarketListener runs on its own thread. // MarketListener is constantly listening for price changes in the market. // This application will use these prices to calculate arbitrage opportunities. MarketListener listener = new MarketListener(app); listener.start(); // After obtaining an opportunity, set a limit buy order for first transaction // Obtain order_id from response // On every price update, recalculate arbitrage opportunity using the price we originally // entered in. // TODO: If opportunity is gone, come up with a plan to mitigate risk // Listen for completed orders and check if their order_id is equal to ours // Repeat with next transaction } // public static void arbitrage() { // // V currencies // int V = currencies.length; // // // create complete network // EdgeWeightedDigraph G = new EdgeWeightedDigraph(V); // for (int v = 0; v < V; v++) { // for (int w = 0; w < V; w++) { // double rate = marketRates[v][w]; // DirectedEdge e = new DirectedEdge(v, w, -Math.log(rate)); // G.addEdge(e); // } // } // // // find negative cycle // BellmanFordSP spt = new BellmanFordSP(G, 0); // // if (spt.hasNegativeCycle()) { // double stake = intialStake + total; // double beginningStake = stake; // for (DirectedEdge e : spt.negativeCycle()) { // Market marketObj = getMarket(currencies[e.from()], currencies[e.to()]); // System.out.printf("%10.5f %s ", stake, currencies[e.from()]); // stake *= Math.exp(-e.weight()); // System.out.printf("= %10.5f %s @ %10.5f %s \n", stake, currencies[e.to()], marketObj.getPrice(), marketObj.getMarket()); // } // System.out.println("Profit: " + (stake - beginningStake)); // total += (stake - beginningStake); // System.out.println("Total: " + total); // } else { // System.out.println("No arbitrage opportunity"); // } // } }
true
67f08463765d692ee13842fa7a938bcb8d9ed6c1
Java
fishtzz/JieMaster
/app/src/main/java/com/szmaster/jiemaster/network/base/HttpConnector.java
UTF-8
8,761
2.25
2
[]
no_license
package com.szmaster.jiemaster.network.base; import android.os.Build; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import com.szmaster.jiemaster.App; import com.szmaster.jiemaster.Constants; import com.szmaster.jiemaster.db.PreferenceImp; import com.szmaster.jiemaster.network.base.HttpLoggingInterceptor.Level; import com.szmaster.jiemaster.utils.CommonUtil; import com.szmaster.jiemaster.utils.Log; import okhttp3.FormBody; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * retrofit封装 * Created by luozhaocheng on 3/5/16. */ public class HttpConnector { private static final Map<String, Retrofit> mAllRetrofits = new HashMap<String, Retrofit>(); private static final Map<String, Retrofit> mAllEncryptionRetrofits = new HashMap<String, Retrofit>(); private static final Map<String, Retrofit> mManualRetrofits = new HashMap<>(); private static Object lock = new Object(); private static Object encryptionLock = new Object(); private static Object manualLock = new Object(); public static final Retrofit getServer(String uri) { synchronized (lock) { Retrofit retrofit = mAllRetrofits.get(uri); if (retrofit == null) { retrofit = new Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(uri) .client(getOkHttpClient()) .build(); } mAllRetrofits.put(uri, retrofit); return retrofit; } } public static final Retrofit getEncryptionServer(String uri, String md5Key, String desKey) { synchronized (encryptionLock) { String key = uri + md5Key + desKey; Retrofit retrofit = mAllEncryptionRetrofits.get(key); if (retrofit == null) { retrofit = new Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(uri) .client(getEncryptionOkHttpClient(md5Key, desKey)) .build(); } mAllEncryptionRetrofits.put(key, retrofit); return retrofit; } } private static OkHttpClient getOkHttpClient() { OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); CustomInterceptor interceptor = new CustomInterceptor(); clientBuilder.addInterceptor(interceptor); if (Constants.IS_DEBUG) { // print Log HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { Log.d(HttpConnector.class, message); } }); logInterceptor.setLevel(Level.BODY); clientBuilder.interceptors().add(logInterceptor); } clientBuilder.connectTimeout(Constants.TIMEOUT, TimeUnit.SECONDS); clientBuilder.readTimeout(10, TimeUnit.SECONDS); clientBuilder.writeTimeout(10, TimeUnit.SECONDS); return clientBuilder.build(); } private static OkHttpClient getEncryptionOkHttpClient(String md5Key, String desKey) { OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); CustomInterceptor interceptor = new CustomInterceptor(true, md5Key, desKey); clientBuilder.addInterceptor(interceptor); if (Constants.IS_DEBUG) { // print Log HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { Log.d(HttpConnector.class, message); } }); logInterceptor.setLevel(Level.BODY); clientBuilder.interceptors().add(logInterceptor); } clientBuilder.connectTimeout(10, TimeUnit.SECONDS); clientBuilder.readTimeout(10, TimeUnit.SECONDS); clientBuilder.writeTimeout(10, TimeUnit.SECONDS); return clientBuilder.build(); } private static class CustomInterceptor implements Interceptor { private boolean encryptionFormParams = false; private String mMd5Key; private String mDesKey; public CustomInterceptor(boolean encryptionFormParams, String md5Key, String desKey) { this.encryptionFormParams = encryptionFormParams; mMd5Key = md5Key; mDesKey = desKey; } public CustomInterceptor() { } @Override public Response intercept(Chain chain) throws IOException { // HttpUrl.Builder urlBuilder = chain.request().url().newBuilder(); // 设置基础参数 // urlBuilder.addQueryParameter("sign", CommonUtil.getSign()); // urlBuilder.addQueryParameter("imei", PreferenceImp.getIMEICache()); // urlBuilder.addQueryParameter("mac", PreferenceImp.getIMEICache()); // urlBuilder.addQueryParameter("SerialNumber", Build.SERIAL); // if (Constants.IS_DEBUG) { // urlBuilder.addQueryParameter("type", Constants.DEBUG); // } else { // urlBuilder.addQueryParameter("type", Constants.RELEASE); // } // 设置Form 表单及Cookie Request.Builder newBuilder = chain.request().newBuilder(); // newBuilder.url(urlBuilder.build()); RequestBody body = chain.request().body(); HashMap<String, String> map = new HashMap<>(); if (body instanceof MultipartBody) { newBuilder.method(chain.request().method(), body); } else { FormBody.Builder builder = new FormBody.Builder(); // 如果加密参数 if (body instanceof FormBody) { if (encryptionFormParams) { FormBody formBody = (FormBody) body; HashMap<String, String> params = new HashMap<>(); for (int i = 0; i < formBody.size(); i++) { params.put(formBody.encodedName(i), formBody.encodedValue(i)); } // FormBody newFormBody = new FormBody.Builder() // .add("parad", EncryptionTools.getParad(params, mMd5Key, mDesKey)) // .build(); // newBuilder.method(chain.request().method(), newFormBody);} } else { FormBody formBody = (FormBody) body; for (int i = 0; i < formBody.size(); i++) { builder.add(formBody.encodedName(i), formBody.encodedValue(i)); map.put(formBody.encodedName(i), formBody.encodedValue(i)); } } } //在body中写入公共参数 int time = (int) (System.currentTimeMillis() / 1000); map.put(Constants.KEY_TIME, time + ""); map.put(Constants.KEY_IMEI, PreferenceImp.getIMEICache()); map.put(Constants.KEY_MAC, PreferenceImp.getMacCache()); map.put(Constants.KEY_SERIALNUMBER, Build.SERIAL); map.put(Constants.KEY_VERSION, CommonUtil.getVersionName()); map.put(Constants.KEY_CHANNEL, CommonUtil.getChannel()); builder.add(Constants.KEY_SIGN, CommonUtil.getSign(map)); builder.add(Constants.KEY_TIME, time + ""); builder.add(Constants.KEY_IMEI, PreferenceImp.getIMEICache()); builder.add(Constants.KEY_MAC, PreferenceImp.getMacCache()); builder.add(Constants.KEY_SERIALNUMBER, Build.SERIAL); builder.add(Constants.KEY_VERSION, CommonUtil.getVersionName()); builder.add(Constants.KEY_CHANNEL, CommonUtil.getChannel()); newBuilder.method(chain.request().method(), builder.build()); } Request newRequest = newBuilder.build(); return chain.proceed(newRequest); } } }
true
56bacd42c29c26da5efc4339f1d2436496fd8e9a
Java
KevzPeter/Computer_Graphics
/Stickman.java
UTF-8
702
3.171875
3
[ "MIT" ]
permissive
import java.awt.*; import javax.swing.*; class MyCanvas3 extends JComponent { public void paint(Graphics g) { g.drawRect(5,5,190,190); g.drawOval(90,60,20,20); g.drawLine(100,80,100,120); g.drawLine(100,100,80,100); g.drawLine(100,100,120,75); g.drawLine(100,120,85,135); g.drawLine(100,120,115,135); } } public class Stickman { public static void main(String[] a) { JFrame window = new JFrame(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setBounds(0, 0, 200, 200); window.getContentPane().add(new MyCanvas3()); window.setVisible(true); } }
true
7c0f698bf7d0a9776e09c2cc52c53f39d01937ad
Java
shanzalewis/Portfolio
/VendingMachineSimulator/src/VendingMachineSimulator.java
UTF-8
8,516
3.265625
3
[]
no_license
/** * EN.605.201 Introduction to Java Programming * This is the main class for Vending Machine Simulator. * At program startup, the vending machine is loaded with a variety of products * in a variety of packaging. Also included is the cost of each item. * The program is designed to load a different set of products from text files. At program startup, * money is loaded into the vending machine.The money consists of different monetary objects * for the specified currency, for example $1 bills, $5 bills, quarters, and dimes. * The program is designed to use different national currencies, Euro, Yen, and US dollars * without changing source code. The money is maintained as paper bills and coins, not just amounts. * * @version 1.0 January 27, 2020 * @author shanzalewis */ import java.io.*; import java.util.*; public class VendingMachineSimulator { public static Scanner input = new Scanner(System.in); public static void main(String[] args) throws Exception { String usd = "USD.txt"; //US dollars text file String yen = "Yen.txt"; //Yen text file String euro = "Euro.txt"; //Euro text file String bottles = "Row1 - Bottles.txt"; //drinks text file String bags = "Row2 - Bags.txt"; //snacks text file String paper_wrapper = "Row3 - Paper Wrapper.txt"; //candy text file String[]line = new String[100]; String info = null; int item_amount = 0; String[]s = new String [100]; String name = null; String cost = null; String amount = null; double item_cost = 0; String amt_rem = null; int amount_remaining = 0; int item_num =0; int money = 0; double total_bottle = 0; double total_bag = 0; double total_paper_wrapper = 0; double owed = 0; Bottles bottle_item = new Bottles(); String denom = null; String quantity = null; int currency_quantity = 0; int quantity_remaining = 0; String quant_rem = null; int new_quantity = 0; double change = 0; Bags bag_item = new Bags(); PaperWrapper paper_wrapper_item = new PaperWrapper(); double total = 0; displayInventory(bottles, bags, paper_wrapper); getCommand(line, info, item_amount, s, bottles, bags, paper_wrapper, name, cost, amount, item_cost, amt_rem, item_num, amount_remaining, money, total_bottle, total_bag, total_paper_wrapper, owed, bottle_item, name, cost, item_amount, item_num, denom, currency_quantity, quantity_remaining, bag_item, paper_wrapper_item, total); } /* * Reads and prints drinks text file * @param String bottles Calls Bottles text file */ public static void displayBottles(String bottles) { try (FileReader reader = new FileReader(bottles)) { int i; while ((i = reader.read()) != -1) System.out.print((char) i); } catch(IOException e) { System.out.println("I/O Error: " + e.getMessage()); } } /* * Reads and prints snacks text file * @param String bags Calls Bags text file */ public static void displayBags(String bags) { try (FileReader reader = new FileReader(bags)) { int i; while ((i = reader.read()) != -1) System.out.print((char) i); } catch(IOException e) { System.out.println("I/O Error: " + e.getMessage()); } } /* * Reads and prints candy text file * @param String paper_wrapper Calls Paper Wrapper text file */ public static void displayPaperWrapper(String paper_wrapper) { try (FileReader reader = new FileReader(paper_wrapper)) { int i; while ((i = reader.read()) != -1) System.out.print((char) i); } catch(IOException e) { System.out.println("I/O Error: " + e.getMessage()); } } /* * Displays the current vending machine inventory */ public static void displayInventory(String bottles, String bags, String paper_wrapper) throws Exception { displayBottles(bottles); System.out.println(); displayBags(bags); System.out.println(); displayPaperWrapper(paper_wrapper); System.out.println(); } /** * Prompts user to choose Soda, Snacks or Candy. User enters selection. * @param String []line * @param String info * @param int item_amount * @param String[] * @param String bottles * @param String bags * @param String paper_wrapper * @param String name * @param String cost * @param String amount * @param double item_cost * @param String amt_rem * @param int item_num * @param int amount_remaining * @param int money * @param double total_bottle * @param double total_bag * @param double total_paper_wrapper * @param double owed * @param Bottles bottle_item * @param String denom * @param String quantity * @param int currency_quantity * @param int quantity_remaining * @param String quant_rem * @param int new_quantity * @param double change * @param Bags bag_item * @param PaperWrapper paper_wrapper_item * @param double total */ public static void getCommand(String []line, String info, int item_amount, String[] s, String bottles, String bags, String paper_wrapper, String name, String cost, String amount, double item_cost, String amt_rem, int item_num, int amount_remaining, int money, double total_bottle, double total_bag, double total_paper_wrapper, double owed, Bottles bottle_item, String denom, String quantity, int currency_quantity, int quantity_remaining, String quant_rem, int new_quantity, double change, Bags bag_item, PaperWrapper paper_wrapper_item,double total)throws Exception { System.out.println(); System.out.println("1 - Soda, 2 - Snacks, 3 - Candy"); //prints options System.out.print("Select Row: "); int row = input.nextInt(); //stores user selection if ((row >= 1) || (row <= 3)) //switches between options based on user selection { switch (row) { case 1: bottle_item = new Bottles(line, s, info, name, cost, amount, item_cost, //calls new Bottle class item_amount, amt_rem,bottles, item_num, amount_remaining); bottle_item.calcItemCurr(money, total_bottle, total_bag, total_paper_wrapper, owed, line, info, s, bottle_item, name, cost, amount, item_cost, item_amount, amt_rem, bottles, item_num, amount_remaining, denom, quantity, currency_quantity, quantity_remaining, quant_rem, new_quantity, change, bag_item, paper_wrapper_item, paper_wrapper, total); break; case 2: bag_item = new Bags(line, s, info, name, cost, amount, item_cost, //calls new Bags class item_amount, amt_rem,bottles, item_num, amount_remaining); bag_item.calcItemCurr(money, total_bottle, total_bag, total_paper_wrapper, owed, line, info, s, bottle_item, name, cost, amount, item_cost, item_amount, amt_rem, bottles, item_num, amount_remaining, denom, quantity, currency_quantity, quantity_remaining, quant_rem, new_quantity, change, bag_item, paper_wrapper_item, paper_wrapper, total); break; case 3: paper_wrapper_item = new PaperWrapper(line, s, info, name, cost, amount, //calls new Paper_Wrapper class item_cost, item_amount, amt_rem,bottles, item_num, amount_remaining); paper_wrapper_item.calcItemCurr(money, total_bottle, total_bag, total_paper_wrapper, owed, line, info, s, bottle_item, name, cost, amount, item_cost, item_amount, amt_rem, bottles, item_num, amount_remaining, denom, quantity, currency_quantity, quantity_remaining, quant_rem, new_quantity, change, bag_item, paper_wrapper_item, paper_wrapper, total); break; } } else { //catches invalid entry and prompts for valid selection System.out.println("1 - Soda, 2 - Snacks, 3 - Candy" + "\nPlease enter a valid row option: "); displayInventory(bottles, bags, paper_wrapper); getCommand(line, info, item_amount, s, bottles, bags, paper_wrapper, name, cost, amount, item_cost, amt_rem, item_num, amount_remaining, money, total_bottle, total_bag, total_paper_wrapper, owed, bottle_item, name, cost, item_amount, item_num, denom, currency_quantity, quantity_remaining, bag_item, paper_wrapper_item, total); } } }
true
5aa2f8cfe8bf8086ede61fd5204226a785db48e1
Java
droidsde/eclip_app
/AntiVirusProxanh2/src/com/security/virusscanner/antivirus/SplashActivity.java
UTF-8
2,597
1.984375
2
[]
no_license
package com.security.virusscanner.antivirus; import java.io.IOException; import java.util.Calendar; import com.security.virusscanner.antivirus.R; import com.security.virusscanner.antivirus.free.DataHelper; import com.security.virusscanner.antivirus.service.ScanService; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.database.SQLException; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.ImageView; public class SplashActivity extends Activity { ImageView scan_img; private MediaPlayer mp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(ScanService.isRunning()){ Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); } setContentView(R.layout.activity_splash); setRA(this); if(getSharedPreferences("VX", 0).getBoolean("VS_FIRSTRUN", true)){ DataHelper d = new DataHelper(getApplicationContext()); try { d.createDataBase(); } catch (IOException ioe) { throw new Error("Unable to create database"); } try { d.openDataBase(); } catch (SQLException sqle) { throw sqle; } } scan_img = (ImageView) findViewById(R.id.scan_img); Animation anim = new MyAnimation(scan_img, 100); anim.setDuration(2500); anim.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { scan_img.setVisibility(View.GONE); stopPlaying(); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); } }); anim.setRepeatCount(1); scan_img.startAnimation(anim); stopPlaying(); mp = MediaPlayer.create(getApplicationContext(), R.raw.scanning_sound); mp.start(); } private void stopPlaying() { if (mp != null) { mp.stop(); mp.release(); mp = null; } } private void setRA(Context context) { Calendar updateTime = Calendar.getInstance(); updateTime.set(Calendar.HOUR_OF_DAY, 17); updateTime.set(Calendar.MINUTE, 38); int r = 1 + (int) (Math.random() * 15); int s = r * 1000; } }
true
ced583b3ecbd17f371f0d16fd41b6b81252821e1
Java
holmes/intellij
/base/src/com/google/idea/blaze/base/console/BlazeConsoleServiceImpl.java
UTF-8
1,906
1.835938
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.base.console; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import javax.annotation.Nullable; import org.jetbrains.annotations.NotNull; /** Implementation for BlazeConsoleService */ public class BlazeConsoleServiceImpl implements BlazeConsoleService { @NotNull private final Project project; @NotNull private final BlazeConsoleView blazeConsoleView; BlazeConsoleServiceImpl(@NotNull Project project) { this.project = project; blazeConsoleView = BlazeConsoleView.getInstance(project); } @Override public void print(@NotNull String text, @NotNull ConsoleViewContentType contentType) { blazeConsoleView.print(text, contentType); } @Override public void clear() { blazeConsoleView.clear(); } @Override public void setStopHandler(@Nullable Runnable runnable) { blazeConsoleView.setStopHandler(runnable); } @Override public void activateConsoleWindow() { ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(BlazeConsoleToolWindowFactory.ID); if (toolWindow != null) { toolWindow.activate(null); } } }
true
158885533b4bbb664015d91668007e3878b37ac5
Java
PerDalsten/MusicLibraryToolsSpring
/src/main/java/dk/purplegreen/musiclibrary/tools/model/AlbumCollection.java
UTF-8
773
2.296875
2
[]
no_license
package dk.purplegreen.musiclibrary.tools.model; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit; @XStreamAlias("albums") @XmlRootElement(name = "albums") public class AlbumCollection { @XStreamImplicit @XmlElement(name = "album") private List<Album> albums = new ArrayList<>(); public AlbumCollection() { } public AlbumCollection(Collection<Album> albums) { this.albums.addAll(albums); } public List<Album> getAlbums() { return albums; } public void addAlbum(Album album) { getAlbums().add(album); } }
true
0259c67d3c0817a077cab768e9bcd5f740199bb2
Java
Shubhamb162/EcommerceProject
/projectbackend/src/main/java/niit/projectbackend/projectbackend/dao/impl/CartDaoImpl.java
UTF-8
1,164
2.234375
2
[]
no_license
package niit.projectbackend.projectbackend.dao.impl; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import niit.projectbackend.projectbackend.Cart; import niit.projectbackend.projectbackend.dao.CartDao; @Repository("cartDao") @Transactional public class CartDaoImpl implements CartDao { @Autowired private SessionFactory sessionFactory; @Override public boolean addCart(Cart cart) { try { sessionFactory.getCurrentSession().persist(cart); return true; } catch (Exception ex) { return false; } } @Override public boolean deleteCart(Cart cart) { try { sessionFactory.getCurrentSession().delete(cart); return true; } catch (Exception ex) { return false; } } @Override public boolean updateCart(Cart cart) { try { sessionFactory.getCurrentSession().update(cart); return true; } catch (Exception e) { return false; } } @Override public Cart getCart(Integer id) { return sessionFactory.getCurrentSession().get(Cart.class, id); } }
true
2c8f89d2b4e3255c0a746f03b5f697d45dd66cde
Java
guojunhua/Demo1
/haha/src/main/java/com/lzl_rjkx/doctor/utils/MyParams.java
UTF-8
473
1.703125
2
[]
no_license
package com.lzl_rjkx.doctor.utils; import org.xutils.http.RequestParams; /** * Created by Administrator on 2016/3/18. */ public class MyParams { public final static RequestParams getParams(String url,String appToken){ RequestParams params=new RequestParams(url); params.addHeader("USER-AGENT-TYPE", "android"); params.addBodyParameter("appToken", appToken); params.addBodyParameter("imeiStr", "000"); return params; } }
true
3f68f4d5d5a387b189d4d3e6946114d3e3f4ab4d
Java
qfsf0220/gitxuexi
/test001/src/KFjava/test20170424/LogicCalc.java
UTF-8
910
3.609375
4
[]
no_license
package KFjava.test20170424; /** * Created by Administrator on 2017/4/24. */ public class LogicCalc { public static void main (String args []){ int a = 5; int b = 10; int c = 10; int e= 10; int f= 10; if (a>2 |b++ >10){ // |这个是非短路或操作 a>2做完 还会继续操作b++ 虽然b++操作对结果没有影响 System.out.println("A:"+a + " B:"+b); } if (a>2 || c++ >10){// ||这个是短路操作。如果第一个为true了 结果就已经是true了 所以跳过c++ 直接执行下面操作 System.out.println("A:"+a + " C:"+c); } if (a>2 & ++e>10){ // 非短路操作 ++i是先加 再赋值 i++是先赋值再加 System.out.println("A:"+a + " E:"+e); } if (a>2 && ++f>10){ //短路操作 System.out.println("A:"+a + " F:"+f); } } }
true
37d1ac9dc1c31f333219a18c450f07a63154098e
Java
selbiselbi/jdonref
/JDONREFv4/src/main/java/org/elasticsearch/index/query/jdonrefv4/JDONREFv4QueryBuilder.java
UTF-8
2,940
1.960938
2
[]
no_license
package org.elasticsearch.index.query.jdonrefv4; import java.io.IOException; import org.elasticsearch.common.lucene.search.jdonrefv4.MaximumScoreBooleanQuery; import org.elasticsearch.common.xcontent.ToXContent.Params; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.BaseQueryBuilder; import org.elasticsearch.index.query.BoostableQueryBuilder; /** * * @author Julien */ public class JDONREFv4QueryBuilder extends BaseQueryBuilder { private final String value; private String queryName; protected int debugDoc = -1; protected boolean debugMode = JDONREFv4QueryParser.DEFAULTDEBUGMODE; protected String default_field = JDONREFv4QueryParser.DEFAULTFIELD; protected boolean progressiveShouldMatch = JDONREFv4QueryParser.DEFAULTPROGRESSIVESHOULDMATCH; public JDONREFv4QueryBuilder debugMode(boolean debugMode) { this.debugMode = debugMode; return this; } /** * Construct a new JDONREFv3 Query. * * @param value The adress to search for. */ public JDONREFv4QueryBuilder(String value) { this.value = value; } /** * Set the debugDoc for this query. * * @param debugDoc * @return */ public JDONREFv4QueryBuilder debugDoc(int debugDoc) { this.debugDoc = debugDoc; return this; } /** * Sets the query name for the filter that can be used when searching for matched_filters per hit. */ public JDONREFv4QueryBuilder queryName(String queryName) { this.queryName = queryName; return this; } public JDONREFv4QueryBuilder field(String default_field) { this.default_field = default_field; return this; } public JDONREFv4QueryBuilder progressiveShouldMatch(boolean progressiveShouldMatch) { this.progressiveShouldMatch = progressiveShouldMatch; return this; } static boolean iamhere = false; @Override public void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(JDONREFv4QueryParser.NAME); builder.field("value", value); if (!JDONREFv4QueryParser.DEFAULTFIELD.equals(default_field)) { builder.field("default_field",default_field); } if (debugMode!=JDONREFv4QueryParser.DEFAULTDEBUGMODE) { builder.field("debugMode",debugMode); } if (progressiveShouldMatch!=JDONREFv4QueryParser.DEFAULTPROGRESSIVESHOULDMATCH) { builder.field("progressive_should_match",progressiveShouldMatch); } if (debugDoc!=-1) { builder.field("debugDoc",debugDoc); } if (queryName != null) { builder.field("_name", queryName); } builder.endObject(); } }
true
67b9e149df07a2bd43d4d50607404a9beb6f38f3
Java
drbgfc/chpl-api
/chpl/chpl-service/src/main/java/gov/healthit/chpl/entity/surveillance/SurveillanceNonconformityEntity.java
UTF-8
8,059
1.898438
2
[ "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
package gov.healthit.chpl.entity.surveillance; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.Where; import gov.healthit.chpl.entity.CertificationCriterionEntity; import gov.healthit.chpl.entity.NonconformityStatusEntity; import gov.healthit.chpl.util.Util; @Entity @Table(name = "surveillance_nonconformity") public class SurveillanceNonconformityEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "surveillance_requirement_id") private Long surveillanceRequirementId; @Column(name = "certification_criterion_id") private Long certificationCriterionId; @OneToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "certification_criterion_id", insertable = false, updatable = false) private CertificationCriterionEntity certificationCriterionEntity; @Column(name = "nonconformity_type") private String type; @Column(name = "nonconformity_status_id") private Long nonconformityStatusId; @OneToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "nonconformity_status_id", insertable = false, updatable = false) private NonconformityStatusEntity nonconformityStatus; @Column(name = "date_of_determination") private Date dateOfDetermination; @Column(name = "corrective_action_plan_approval_date") private Date capApproval; @Column(name = "corrective_action_start_date") private Date capStart; @Column(name = "corrective_action_must_complete_date") private Date capMustCompleteDate; @Column(name = "corrective_action_end_date") private Date capEndDate; @Column(name = "summary") private String summary; @Column(name = "findings") private String findings; @Column(name = "sites_passed") private Integer sitesPassed; @Column(name = "total_sites") private Integer totalSites; @Column(name = "developer_explanation") private String developerExplanation; @Column(name = "resolution") private String resolution; @Column(name = "deleted") private Boolean deleted; @Column(name = "last_modified_user") private Long lastModifiedUser; @Column(name = "creation_date", insertable = false, updatable = false) private Date creationDate; @Column(name = "last_modified_date", insertable = false, updatable = false) private Date lastModifiedDate; @OneToMany(fetch = FetchType.LAZY, mappedBy = "nonconformityId") @Basic(optional = false) @Column(name = "surveillance_nonconformity_id", nullable = false) @Where(clause = "deleted <> 'true'") private Set<SurveillanceNonconformityDocumentationEntity> documents = new HashSet<SurveillanceNonconformityDocumentationEntity>(); public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getType() { return type; } public void setType(final String type) { this.type = type; } public Date getDateOfDetermination() { return Util.getNewDate(dateOfDetermination); } public void setDateOfDetermination(final Date dateOfDetermination) { this.dateOfDetermination = Util.getNewDate(dateOfDetermination); } public Date getCapApproval() { return Util.getNewDate(capApproval); } public void setCapApproval(final Date capApproval) { this.capApproval = Util.getNewDate(capApproval); } public Date getCapStart() { return Util.getNewDate(capStart); } public void setCapStart(final Date capStart) { this.capStart = Util.getNewDate(capStart); } public Date getCapMustCompleteDate() { return Util.getNewDate(capMustCompleteDate); } public void setCapMustCompleteDate(final Date capMustCompleteDate) { this.capMustCompleteDate = Util.getNewDate(capMustCompleteDate); } public Date getCapEndDate() { return Util.getNewDate(capEndDate); } public void setCapEndDate(final Date capEndDate) { this.capEndDate = Util.getNewDate(capEndDate); } public String getSummary() { return summary; } public void setSummary(final String summary) { this.summary = summary; } public String getFindings() { return findings; } public void setFindings(final String findings) { this.findings = findings; } public Integer getSitesPassed() { return sitesPassed; } public void setSitesPassed(final Integer sitesPassed) { this.sitesPassed = sitesPassed; } public Integer getTotalSites() { return totalSites; } public void setTotalSites(final Integer totalSites) { this.totalSites = totalSites; } public String getDeveloperExplanation() { return developerExplanation; } public void setDeveloperExplanation(final String developerExplanation) { this.developerExplanation = developerExplanation; } public String getResolution() { return resolution; } public void setResolution(final String resolution) { this.resolution = resolution; } public Date getCreationDate() { return Util.getNewDate(creationDate); } public void setCreationDate(final Date creationDate) { this.creationDate = Util.getNewDate(creationDate); } public Boolean getDeleted() { return deleted; } public void setDeleted(final Boolean deleted) { this.deleted = deleted; } public Date getLastModifiedDate() { return Util.getNewDate(lastModifiedDate); } public void setLastModifiedDate(final Date lastModifiedDate) { this.lastModifiedDate = Util.getNewDate(lastModifiedDate); } public Long getLastModifiedUser() { return lastModifiedUser; } public void setLastModifiedUser(final Long lastModifiedUser) { this.lastModifiedUser = lastModifiedUser; } public Long getSurveillanceRequirementId() { return surveillanceRequirementId; } public void setSurveillanceRequirementId(final Long surveillanceRequirementId) { this.surveillanceRequirementId = surveillanceRequirementId; } public Long getCertificationCriterionId() { return certificationCriterionId; } public void setCertificationCriterionId(final Long certificationCriterionId) { this.certificationCriterionId = certificationCriterionId; } public CertificationCriterionEntity getCertificationCriterionEntity() { return certificationCriterionEntity; } public void setCertificationCriterionEntity(final CertificationCriterionEntity certificationCriterionEntity) { this.certificationCriterionEntity = certificationCriterionEntity; } public Long getNonconformityStatusId() { return nonconformityStatusId; } public void setNonconformityStatusId(final Long nonconformityStatusId) { this.nonconformityStatusId = nonconformityStatusId; } public NonconformityStatusEntity getNonconformityStatus() { return nonconformityStatus; } public void setNonconformityStatus(final NonconformityStatusEntity nonconformityStatus) { this.nonconformityStatus = nonconformityStatus; } public Set<SurveillanceNonconformityDocumentationEntity> getDocuments() { return documents; } public void setDocuments(final Set<SurveillanceNonconformityDocumentationEntity> documents) { this.documents = documents; } }
true
8814ffe93f524551631685059f40e2d326bc2262
Java
Kuuskinen/SmitBookRental
/src/main/java/com/example/smitbookrental/service/ReservationRepository.java
UTF-8
746
1.984375
2
[]
no_license
package com.example.smitbookrental.service; import com.example.smitbookrental.entity.ReservationEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface ReservationRepository extends JpaRepository<ReservationEntity, Long> { @Query("SELECT entity FROM ReservationEntity entity WHERE entity.bookId = ?1") ReservationEntity getReservation(Long bookId); @Query("SELECT entity FROM ReservationEntity entity WHERE entity.lenderId = ?1") List<ReservationEntity> getReservationsByUserId(Integer userId); }
true
e9660d68c2df279e6b3e24027a32474a7380e48e
Java
NikoletaDeleva/TrainingRepo
/Homework2/src/Six.java
UTF-8
391
3.421875
3
[]
no_license
import java.util.Scanner; public class Six { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Vuvedi chislo:"); int chislo = input.nextInt(); int sum = 0; for(int count = 1; count<=chislo; count++) { sum +=count; }System.out.println("Sumata na vsichki chisla do " + chislo +" e ravna na " + sum); input.close(); } }
true
23b4d8996a6343f2c7d8187f57deebaeaa7943a0
Java
mahesh122000/Data-Structures
/Binary-Tree/Binary_Tree_Tilt.java
UTF-8
585
3
3
[]
no_license
class Solution { int sum; public int findTilt(TreeNode root) { if(root==null) return 0; sum=0; fill(root); find(root); return sum; } int fill(TreeNode root) { if(root==null) return 0; int l=fill(root.left); int r=fill(root.right); int c=root.val; root.val=Math.abs(l-r); return l+r+c; } void find(TreeNode root) { if(root==null) return; sum+=root.val; find(root.left); find(root.right); } }
true
b47d01865ebb32165972ea37a4d89389437ac3c9
Java
Atlanca/LearningGit
/app/src/main/java/chalmers/talex/learninggit/DietModel/Categories.java
UTF-8
183
1.59375
2
[]
no_license
package chalmers.talex.learninggit.DietModel; /** * Created by SAMSUNG on 2017-03-25. */ public enum Categories { PORK, FISH, CHICKEN , BEEF, SALAD, VEGETABLE, FRUIT, GRAIN }
true
558bc033af0e99a4cc1110ee40902303718e1809
Java
opus-research/ancient-organic
/src/java/br/pucrio/inf/organic/extensions/ui/agglomeration/AgglomerationLabelProvider.java
UTF-8
2,144
2.359375
2
[]
no_license
package br.pucrio.inf.organic.extensions.ui.agglomeration; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.StyledString; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.swt.graphics.Image; import spirit.core.smells.CodeSmell; import br.pucrio.inf.organic.extensionPoints.AgglomerationModel; import br.pucrio.inf.organic.extensions.OrganicActivator; /** * Label provider for agglomerations. * @author Willian * */ public class AgglomerationLabelProvider extends StyledCellLabelProvider { private static final String ICONS_URL = "icons/"; private static final String PROJECT_IMG = "project.png"; private static final String AGGLOMERATION_TYPE_IMG = "agglomerationType.jpg"; private static final String AGGLOMERATION_IMG = "agglomeration.png"; @Override public void update(ViewerCell cell) { Object element = cell.getElement(); StyledString text = new StyledString(); text.append(getText(element)); cell.setImage(getImage(element)); cell.setText(text.toString()); cell.setStyleRanges(text.getStyleRanges()); super.update(cell); } private String getText(Object node) { return node.toString(); } /** * Returns an Image instance for a given node * according to the node's type * @param node * @return Image */ private Image getImage(Object node) { String imgUrl = null; if (node instanceof ProjectResults) { imgUrl = PROJECT_IMG; } else if (node instanceof AgglomerationTypeResults) { imgUrl = AGGLOMERATION_TYPE_IMG; } else if (node instanceof AgglomerationModel) { imgUrl = AGGLOMERATION_IMG; } if (imgUrl != null) { ImageDescriptor icon; URL url = null; try { url = new URL(OrganicActivator.getDefault().getDescriptor().getInstallURL(),ICONS_URL + imgUrl); } catch (MalformedURLException e) { System.err.println("Exception while opening icon: " + e); } icon = ImageDescriptor.createFromURL(url); return icon.createImage(); } return null; } }
true
29a6d786873a635eb7b9ce322c4db1babc72e932
Java
ADDPALADIN1983/A_Gregos_Capstone
/app/src/main/java/com/example/a_gregos_capstone/ViewPagerAdapter.java
UTF-8
968
2.328125
2
[]
no_license
package com.example.a_gregos_capstone; import java.util.List; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.ViewModelProviders; import androidx.viewpager2.adapter.FragmentStateAdapter; public class ViewPagerAdapter extends FragmentStateAdapter { List<String> categories; public ViewPagerAdapter(@NonNull FragmentActivity fragmentActivity) { super(fragmentActivity); PersonCategoryViewModel categoryViewModel = new PersonCategoryViewModel(fragmentActivity.getApplication()); categories = categoryViewModel.getCategoryNames(); } @NonNull @Override public Fragment createFragment(int position) { Fragment fragment = null; fragment = new PeopleFragment(categories.get(position)); return fragment; } @Override public int getItemCount() { return categories.size(); } }
true
af4b8a2a7bb8aa6bcdefda82f42ca1c7113676a8
Java
MirelleGushomoto/Projeto05POO
/Projeto-06-master/src/java/br/com/fatecpg/jdbc/Compras.java
UTF-8
3,348
2.203125
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 br.com.fatecpg.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; /** * * @author gabri */ public class Compras { private String idcliente; private int idproduto; private String quantidade; private String valor; private String dtcompra; private String dtenvio; private String companhia; public static ArrayList<Compras> getList(int comprasid) throws Exception{ Class.forName("org.apache.derby.jdbc.ClientDriver"); String url = "jdbc:derby://localhost:1527/sample"; Connection con = DriverManager.getConnection(url, "app", "app"); String SQL = "SELECT * FROM PURCHASE_ORDER WHERE CUSTOMER_ID = ?"; PreparedStatement st = con.prepareStatement(SQL); st.setInt(1,comprasid); ResultSet rs = st.executeQuery(); ArrayList<Compras> list = new ArrayList<>(); while (rs.next()){ Compras y = new Compras( rs.getString("CUSTOMER_ID"), rs.getInt("PRODUCT_ID"), rs.getString("QUANTITY"), rs.getString("SHIPPING_COST"), rs.getString("SALES_DATE"), rs.getString("SHIPPING_DATE"), rs.getString("FREIGHT_COMPANY") ); list.add(y); } rs.close();st.close();con.close(); return list; } public Compras() { } public Compras(String idcliente,int idproduto, String quantidade, String valor, String dtcompra, String dtenvio, String companhia) { this.idcliente = idcliente; this.idproduto = idproduto; this.quantidade = quantidade; this.valor = valor; this.dtcompra = dtcompra; this.dtenvio = dtenvio; this.companhia = companhia; } public String getIdcliente() { return idcliente; } public void setIdcliente(String idcliente) { this.idcliente = idcliente; } public int getIdproduto() { return idproduto; } public void setIdproduto(int idproduto) { this.idproduto = idproduto; } public String getQuantidade() { return quantidade; } public void setQuantidade(String quantidade) { this.quantidade = quantidade; } public String getValor() { return valor; } public void setValor(String valor) { this.valor = valor; } public String getDtcompra() { return dtcompra; } public void setDtcompra(String dtcompra) { this.dtcompra = dtcompra; } public String getDtenvio() { return dtenvio; } public void setDtenvio(String dtenvio) { this.dtenvio = dtenvio; } public String getCompanhia() { return companhia; } public void setCompanhia(String companhia) { this.companhia = companhia; } }
true
8fb2f9de9266ddf214476e8a3c4c8ee46718412f
Java
fcevatyilmaz/Spring-Projects
/018_PrototypeScope/src/main/java/com/furkanyilmaz/SelamApp.java
UTF-8
936
1.96875
2
[]
no_license
package com.furkanyilmaz; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SelamApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeansConfig.xml"); Selam selamNesnesi1 = context.getBean("beanSelam",Selam.class); selamNesnesi1.setMesaj("Beşitaş"); selamNesnesi1.goster(); Selam selamNesnesi2 = context.getBean("beanSelam",Selam.class); selamNesnesi2.setMesaj("Galatasaray"); selamNesnesi2.goster(); selamNesnesi1.goster(); selamNesnesi2.setMesaj("Fenerbahçe"); selamNesnesi1.goster(); selamNesnesi2.goster(); Selam selamNesnesi3 = context.getBean("beanSelam",Selam.class); selamNesnesi3.goster(); selamNesnesi3.setMesaj("TrabzonSpor"); selamNesnesi1.goster(); selamNesnesi2.goster(); selamNesnesi3.goster(); } }
true
73877117c6b204737f384cffd510d876f76507bf
Java
bitterbit/quotes-app
/QuoteApp/src/main/java/com/gtr/quotes/views/QuoteViewPhone.java
UTF-8
761
2.109375
2
[]
no_license
package com.gtr.quotes.views; import android.content.Context; import com.galtashma.lazyparse.LazyParseObjectHolder; import com.gtr.quotes.quote.Quote; public class QuoteViewPhone extends QuoteView { public QuoteViewPhone(Context context, LazyParseObjectHolder<Quote> quote) { super(context, quote); } @Override public QuoteViewVars getVars() { QuoteViewVars vars = new QuoteViewVars(); vars.pic_size = 100; vars.top_margin = 90; vars.header_to_body_margin = 0; vars.image_to_title_margin = 0; vars.landscape_top_margin = 50; vars.landscape_image_to_title_margin = 20; vars.landscape_header_width = 400; vars.width_parentage = 99; return vars; } }
true
ba065edaf0e2058b2ebfb8de2875b484573e063e
Java
wire2coder/android_baking_app
/app/src/androidTest/java/com/bkk/android/android_bake1/TabletTest.java
UTF-8
2,863
1.984375
2
[]
no_license
package com.bkk.android.android_bake1; import android.support.test.espresso.contrib.RecyclerViewActions; import android.support.test.espresso.matcher.ViewMatchers; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.bkk.android.android_bake1.Util.KeyUtil; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.security.Key; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static com.bkk.android.android_bake1.Util.KeyUtil.BROWNIES; import static com.bkk.android.android_bake1.Util.KeyUtil.CHEESECAKE; import static com.bkk.android.android_bake1.Util.KeyUtil.NUTELLA_PIE; import static com.bkk.android.android_bake1.Util.KeyUtil.YELLOW_CAKE; @RunWith(AndroidJUnit4.class) public class TabletTest { // helper public void wait2Sec() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); // @Before // public void stubAllExternalIntents() { // // By default Espresso Intents does not stub any Intents. Stubbing needs to be setup before // // every test run. In this case all external Intents will be blocked. // intending(not(isInternal())).respondWith(new ActivityResult(Activity.RESULT_OK, null)); // } @Test public void checkForFourRecipes() { // onView(ViewMatchers.withId(R.id.recipe_recycler)) // .perform(RecyclerViewActions.scrollToPosition(1)); wait2Sec(); onView(withText(NUTELLA_PIE)).check(matches(isDisplayed())); onView(withText(BROWNIES)).check(matches(isDisplayed())); onView(withText(YELLOW_CAKE)).check(matches(isDisplayed())); onView(withText(CHEESECAKE)).check(matches(isDisplayed())); } @Test public void checkForVideoPlayerInTablet() { // I put the wait in here to look at the screen animation // the wait function has nothing to do with IdlingResources wait2Sec(); onView(ViewMatchers.withId(R.id.recipe_recycler)) .perform(RecyclerViewActions.actionOnItemAtPosition(0,click())); // the wait function has nothing to do with IdlingResources wait2Sec(); onView(withId(R.id.playerView)).check(matches(isDisplayed())); } } // class
true
142d5c12696d990a1de5c860f693d9bef1f204df
Java
dickiep/relationAndroid
/commented but not working/RelationBN-2/app/src/main/java/com/dickies/android/relationbn/productdisplay/CategoryProductsDisplayActivity.java
UTF-8
2,744
2.171875
2
[]
no_license
package com.dickies.android.relationbn.productdisplay; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import com.dickies.android.relationbn.R; import com.dickies.android.relationbn.utils.Product; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Phil on 20/08/2018. */ public class CategoryProductsDisplayActivity extends AppCompatActivity { private RecyclerView recyclerView; private Toolbar toolbar; private LinearLayoutManager layoutManager; private ProductAdapter mAdapter; private Intent mIntent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Log.d("POP Oncreate : ", "In here"); setContentView(R.layout.popupwindow); mIntent = getIntent(); int id = mIntent.getIntExtra("categoryID",3); String title = mIntent.getStringExtra("categoryTitle"); //Log.d("POP Oncreate : ", String.valueOf(id)); fetchProducts(id); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(title); getSupportActionBar().setDisplayHomeAsUpEnabled(true); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); layoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); } ApiInterface apiInterface; private ArrayList<Product> products; public void fetchProducts(int key) { apiInterface = ApiClient.getApiClient().create(ApiInterface.class); Call<ArrayList<Product>> call = apiInterface.getProductsByCategory(key); call.enqueue(new Callback<ArrayList<Product>>() { @Override public void onResponse(Call<ArrayList<Product>> call, Response<ArrayList<Product>> response) { products = response.body(); //Log.d("POP Fetch : ", "phild"+products.toString()); mAdapter = new ProductAdapter(products, getApplicationContext()); recyclerView.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); } @Override public void onFailure(Call<ArrayList<Product>> call, Throwable t) { Log.d("Error",t.toString()); } }); } }
true
4d58dadae63668f0a64ac0510cf885ccc69997cf
Java
powerex/MPIUsed
/src/main/java/com/mathpar/parallel/stat/FMD/Test.java
UTF-8
3,745
2.203125
2
[]
no_license
/** * Copyright © 2011 Mathparca Ltd. All rights reserved. */ package com.mathpar.parallel.stat.FMD; import com.mathpar.matrix.MatrixD; import com.mathpar.matrix.file.dense.FileMatrixD; import com.mathpar.number.Element; import com.mathpar.number.Newton; import com.mathpar.number.NumberZ; import com.mathpar.number.Ring; import java.io.File; import java.util.ArrayList; import java.util.Random; import mpi.MPI; /** * * @author r1d1 */ public class Test { public static void main(String[] args) throws Exception { int []tmpInt={4}; Ring ring= new Ring("Z[x,y,z]"); String[] chMod = {"rm", "-R", "/tmp/mA/"}; Process chmod = Runtime.getRuntime().exec(chMod); chmod.waitFor(); String[] chMod1 = {"mkdir", "/tmp/mA/"}; Process chmod1 = Runtime.getRuntime().exec(chMod); chmod1.waitFor(); File f1 = new File("/tmp/mA/tmp1"); File f2 = new File("/tmp/mA/tmp2"); File f3 = new File("/tmp/mA/tmp3"); int nbits=9000,mSize=4,depth=1; FileMatrixD fm1=new FileMatrixD(f1,depth, mSize, mSize, nbits); FileMatrixD fm2=new FileMatrixD(f2,depth, mSize, mSize, nbits); FileMatrixD trueRes=fm1.multCU(fm2, f3); System.out.println(fm1.toMatrixD().toString()); System.out.println(""); System.out.println(fm2.toMatrixD().toString()); System.out.println(""); System.out.println(trueRes.toMatrixD().toString()); ArrayList<NumberZ> mods=new ArrayList<NumberZ>(); NumberZ lenComp=new NumberZ(nbits,new Random()); NumberZ comp100=new NumberZ(100); NumberZ lenComparator=lenComp.multiply(lenComp).multiply(comp100); NumberZ product=new NumberZ(1); for (long i=1000000000; product.compareTo(lenComparator, ring)==-1; i++){ NumberZ cur=new NumberZ(i); if (cur.isProbablePrime(1)){ mods.add(cur); product=product.multiply(cur); } } System.out.println(product.toString(ring)); Newton.initRArray(mods); for (int i=0; i<mods.size(); i++){ // System.out.println(mods.get(i).toString(ring)); } FileMatrixD []arA=new FileMatrixD[mods.size()]; FileMatrixD []arB=new FileMatrixD[mods.size()]; FileMatrixD []arC=new FileMatrixD[mods.size()]; for (int i=0; i<mods.size(); i++){ File curPathA=new File("/tmp/mA/modsA"+mods.get(i).toString(ring)); arA[i]=fm1.copyByMod(curPathA, mods.get(i), ring); File curPathB=new File("/tmp/mA/modsB"+mods.get(i).toString(ring)); arB[i]=fm2.copyByMod(curPathB, mods.get(i), ring); //System.out.println("modA for mod with i="+String.valueOf(i)+arA[i].toMatrixD().toString(ring)); //System.out.println("modB for mod with i="+String.valueOf(i)+arB[i].toMatrixD().toString(ring)); File curPathC=new File("/tmp/mA/modsC"+mods.get(i).toString(ring)); arC[i]=arA[i].multCU(arB[i], curPathC, mods.get(i).longValue()); //System.out.println("modC for mod with i="+String.valueOf(i)+arC[i].toMatrixD().toString(ring)); } File modResF = new File("/tmp/mA/modRes"); FileMatrixD modRes=new FileMatrixD(modResF,1); modRes.restoreByGarner(arC, mods); System.out.println(""); System.out.println(modRes.toMatrixD().toString()); if (!trueRes.toMatrixD().subtract(modRes.toMatrixD(), ring).isZero(ring)){ System.out.println("FALSE"); } else { System.out.println("TRUE"); } } }
true
56613b2529385985088b0d433d42ec1925ab1687
Java
nizeyu/Practice
/0314. Binary Tree Vertical Order Traversal.java
UTF-8
1,513
3.34375
3
[]
no_license
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Position { TreeNode node; int column; public Position(TreeNode node, int column) { this.node = node; this.column = column; } } class Solution { public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) { return result; } TreeMap<Integer, List<Integer>> tmap = new TreeMap<>(); Queue<Position> q = new LinkedList<>(); q.offer(new Position(root, 0)); while (!q.isEmpty()) { Position p = q.poll(); List<Integer> list = tmap.get(p.column); if (list == null) { list = new ArrayList<>(); tmap.put(p.column, list); } list.add(p.node.val); if (p.node.left != null) { q.offer(new Position(p.node.left, p.column - 1)); } if (p.node.right != null) { q.offer(new Position(p.node.right, p.column + 1)); } } for(Integer key : tmap.keySet()) { List<Integer> list = tmap.get(key); if (list != null) { result.add(list); } } return result; } }
true
17f2bdf4e4017f04f18e55d3c444e7633c02d353
Java
togetherworks/Procurement-System
/src/main/java/com/ncs/iframe4/ps/action/CustomerAction.java
UTF-8
620
1.859375
2
[]
no_license
package com.ncs.iframe4.ps.action; import java.io.Serializable; import com.ncs.iframe4.ps.service.CustomerService; /** * * Common action User: qinjun Date: 12-1-16 Time: 上午10:49 To change this * template use File | Settings | File Templates. */ public class CustomerAction implements Serializable { private static final long serialVersionUID = 0L; private CustomerService customerService; public CustomerService getCustomerService() { return customerService; } public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } }
true
2f7a6dca0fa60fd8b8055dcf80c517e40457db0b
Java
dilip-devaraj/Interview
/Interview/src/ReverseListKGroup.java
UTF-8
1,536
3.84375
4
[]
no_license
public class ReverseListKGroup { public ListNode reverseKGroup(ListNode head, int k) { ListNode curr = head; int count = 0; while (curr != null && count != k) { // find the k+1 node curr = curr.next; count++; } if (count == k) { // if k+1 node is found curr = reverseKGroup(curr, k); // reverse list with k+1 node as head // head - head-pointer to direct part, // curr - head-pointer to reversed part; while (count-- > 0) { // reverse current k-group: ListNode tmp = head.next; // tmp - next head in direct part head.next = curr; // preappending "direct" head to the reversed list curr = head; // move head of reversed part to a new node head = tmp; // move "direct" head to the next node in direct part } head = curr; } return head; } public static void main(String[] args) { ReverseListKGroup rLKG = new ReverseListKGroup(); ListNode head = new ListNode(); head.data = 1; ListNode nextNode; ListNode prevNode = head; int i=2; while(i <= 5) { nextNode = new ListNode(); nextNode.data = i; prevNode.next = nextNode; prevNode = prevNode.next; i++; } nextNode = head; while(nextNode !=null) { System.out.println(nextNode.data); nextNode = nextNode.next; } System.out.println(); head = rLKG.reverseKGroup(head, 2); nextNode = head; while(nextNode !=null) { System.out.println(nextNode.data); nextNode = nextNode.next; } System.out.println(); System.out.println( -2 >> 1); System.out.println( -2 >>> 1); } }
true
b3d07d84f2305c8561d2e9ec2c68a8b2848b43ac
Java
BuZhiheng/xx
/platform/src/main/java/com/horen/cortp/platform/contract/ExperienceCreateTxtContract.java
UTF-8
920
1.78125
2
[]
no_license
package com.horen.cortp.platform.contract; import android.content.Intent; import android.widget.EditText; import com.horen.cortp.platform.bean.ExperienceCreate; import com.jaydenxiao.common.base.BaseModel; import com.jaydenxiao.common.base.BasePresenter; import com.jaydenxiao.common.base.BaseView; /** * Created by HOREN on 2017/11/15. */ public interface ExperienceCreateTxtContract { class Model implements BaseModel { } interface View extends BaseView { void setTitle(String title); void setEditText(String txt); void setDeleteGone(); void setCommit(ExperienceCreate experienceCreate, int resultCodeCreateTxtSuccess,int position,String id); } abstract class Presenter extends BasePresenter<View,Model> { public abstract void init(Intent intent); public abstract void sureClick(EditText editText); public abstract void delClick(); } }
true
80f8f50a9e6961730dd99aa45612347b1849135e
Java
yehecan/bw-calendar-engine
/bw-calendar-engine-impl/src/main/java/org/bedework/calsvc/Calendars.java
UTF-8
20,978
1.5
2
[]
no_license
/* ******************************************************************** Licensed to Jasig under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Jasig licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.bedework.calsvc; import org.bedework.access.Acl.CurrentAccess; import org.bedework.access.PrivilegeDefs; import org.bedework.calcorei.Calintf; import org.bedework.calcorei.CoreCalendarsI.GetSpecialCalendarResult; import org.bedework.calfacade.svc.BwAuthUser; import org.bedework.calfacade.BwCalendar; import org.bedework.calfacade.svc.BwPreferences; import org.bedework.calfacade.BwPrincipal; import org.bedework.calfacade.BwResource; import org.bedework.calfacade.CalFacadeDefs; import org.bedework.calfacade.base.BwShareableDbentity; import org.bedework.calfacade.exc.CalFacadeAccessException; import org.bedework.calfacade.exc.CalFacadeException; import org.bedework.calfacade.svc.EventInfo; import org.bedework.calsvci.CalendarsI; import org.bedework.calsvci.ResourcesI; import org.bedework.calsvci.SynchI; import org.bedework.util.misc.Util; import net.fortuna.ical4j.model.Component; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.TreeSet; /** This acts as an interface to the database for calendars. * * @author Mike Douglass douglm - rpi.edu */ class Calendars extends CalSvcDb implements CalendarsI { private final String publicCalendarRootPath; //private String userCalendarRootPath; /** Constructor * * @param svci interface * @throws CalFacadeException */ Calendars(final CalSvc svci) throws CalFacadeException { super(svci); publicCalendarRootPath = Util.buildPath(true, "/", getBasicSyspars() .getPublicCalendarRoot()); //userCalendarRootPath = "/" + getBasicSyspars().getUserCalendarRoot(); } @Override public String getPublicCalendarsRootPath() throws CalFacadeException { return publicCalendarRootPath; } @Override public BwCalendar getPublicCalendars() throws CalFacadeException { return getCal().getCalendar(publicCalendarRootPath, PrivilegeDefs.privRead, true); } @Override public String getHomePath() throws CalFacadeException { if (isGuest()) { return publicCalendarRootPath; } if (isPublicAdmin()) { if (!getSyspars().getWorkflowEnabled()) { return publicCalendarRootPath; } final BwAuthUser au = getSvc().getUserAuth().getUser(getPars().getAuthUser()); final boolean isApprover = isSuper() || (au != null) && au.isApproverUser(); // Do they have approver status? if (isApprover) { return publicCalendarRootPath; } return Util.buildPath(true, getSyspars().getWorkflowRoot()); // "/", // getPrincipal().getAccountNoSlash()); } return getSvc().getPrincipalInfo().getCalendarHomePath(); } @Override public BwCalendar getHome() throws CalFacadeException { return getCal().getCalendar(getHomePath(), PrivilegeDefs.privRead, true); } @Override public BwCalendar getHome(final BwPrincipal principal, final boolean freeBusy) throws CalFacadeException { final int priv; if (freeBusy) { priv = PrivilegeDefs.privReadFreeBusy; } else { priv = PrivilegeDefs.privRead; } return getCal().getCalendar(getSvc().getPrincipalInfo().getCalendarHomePath(principal), priv, true); } @Override public Collection<BwCalendar> decomposeVirtualPath(final String vpath) throws CalFacadeException { final Collection<BwCalendar> cols = new ArrayList<>(); /* First see if the vpath is an actual path - generally the case for * personal calendar users. */ BwCalendar curCol = get(vpath); if ((curCol != null) && !curCol.getAlias()) { cols.add(curCol); return cols; } final String[] pathEls = normalizeUri(vpath).split("/"); if ((pathEls == null) || (pathEls.length == 0)) { return cols; } /* First, keep adding elements until we get a BwCalendar result. * This handles the user root not being accessible */ curCol = null; String startPath = ""; int pathi = 1; // Element 0 is a zero length string while (pathi < pathEls.length) { startPath = Util.buildPath(true, startPath, "/", pathEls[pathi]); pathi++; try { curCol = get(startPath); } catch (final CalFacadeAccessException cfae) { curCol = null; } if (curCol != null) { // Found the start collection if (debug) { trace("Start vpath collection:" + curCol.getPath()); } break; } } if (curCol == null) { // Bad vpath return null; } buildCollection: for (;;) { cols.add(curCol); if (debug) { trace(" vpath collection:" + curCol.getPath()); } // Follow the chain of references for curCol until we reach a non-alias if (curCol.getInternalAlias()) { final BwCalendar nextCol = resolveAlias(curCol, false, false); if (nextCol == null) { // Bad vpath curCol.setDisabled(true); curCol.setLastRefreshStatus("400"); return null; } curCol = nextCol; continue buildCollection; } /* Not an alias - do we have any more path elements */ if (pathi >= pathEls.length) { break buildCollection; } /* Not an alias and we have more path elements. * It should be a collection. Look for the next path * element as a child name */ if (curCol.getCalType() != BwCalendar.calTypeFolder) { // Bad vpath return null; } /* for (BwCalendar col: getChildren(curCol)) { if (col.getName().equals(pathEls[pathi])) { // Found our child pathi++; curCol = col; continue buildCollection; } } */ final BwCalendar col = get(curCol.getPath() + "/" + pathEls[pathi]); if (col == null) { /* Child not found - bad vpath */ return null; } pathi++; curCol = col; } return cols; } @Override public Collection<BwCalendar> getChildren(final BwCalendar col) throws CalFacadeException { if (col.getCalType() == BwCalendar.calTypeAlias) { resolveAlias(col, true, false); } return getCal().getCalendars(col.getAliasedEntity()); } @Override public Set<BwCalendar> getAddContentCollections(final boolean includeAliases) throws CalFacadeException { final Set<BwCalendar> cals = new TreeSet<>(); getAddContentCalendarCollections(includeAliases, getHome(), cals); return cals; } @Override public boolean isEmpty(final BwCalendar val) throws CalFacadeException { return getSvc().getCal().isEmpty(val); } /* (non-Javadoc) * @see org.bedework.calsvci.CalendarsI#get(java.lang.String) */ @Override public BwCalendar get(String path) throws CalFacadeException{ if (path == null) { return null; } if ((path.length() > 1) && (path.startsWith(CalFacadeDefs.bwUriPrefix))) { path = path.substring(CalFacadeDefs.bwUriPrefix.length()); } return getCal().getCalendar(path, PrivilegeDefs.privAny, false); } @Override public BwCalendar getSpecial(final int calType, final boolean create) throws CalFacadeException { return getSpecial(null, calType, create); } @Override public BwCalendar getSpecial(final String principal, final int calType, final boolean create) throws CalFacadeException { final BwPrincipal pr; if (principal == null) { pr = getPrincipal(); } else { pr = getPrincipal(principal); } final Calintf.GetSpecialCalendarResult gscr = getSvc().getCal().getSpecialCalendar( pr, calType, create, PrivilegeDefs.privAny); if (!gscr.noUserHome) { return gscr.cal; } getSvc().getUsersHandler().add(getPrincipal().getAccount()); return getCal().getSpecialCalendar(pr, calType, create, PrivilegeDefs.privAny).cal; } @Override public void setPreferred(final BwCalendar val) throws CalFacadeException { getSvc().getPrefsHandler().get().setDefaultCalendarPath(val.getPath()); } @Override public String getPreferred(final String entityType) throws CalFacadeException { final int calType; switch (entityType) { case Component.VEVENT: final String path = getSvc().getPrefsHandler().get() .getDefaultCalendarPath(); if (path != null) { return path; } calType = BwCalendar.calTypeCalendarCollection; break; case Component.VTODO: calType = BwCalendar.calTypeTasks; break; case Component.VPOLL: calType = BwCalendar.calTypePoll; break; default: return null; } final GetSpecialCalendarResult gscr = getCal().getSpecialCalendar(getPrincipal(), calType, true, PrivilegeDefs.privAny); return gscr.cal.getPath(); } @Override public BwCalendar add(BwCalendar val, final String parentPath) throws CalFacadeException { updateOK(val); setupSharableEntity(val, getPrincipal().getPrincipalRef()); val.adjustCategories(); if (val.getPwNeedsEncrypt()) { encryptPw(val); } val = getCal().add(val, parentPath); ((Preferences)getSvc().getPrefsHandler()).updateAdminPrefs(false, val, null, null, null); final SynchI synch = getSvc().getSynch(); if (val.getExternalSub()) { if (!synch.subscribe(val)) { throw new CalFacadeException(CalFacadeException.subscriptionFailed); } } return val; } @Override public void rename(final BwCalendar val, final String newName) throws CalFacadeException { getSvc().getCal().renameCalendar(val, newName); } @Override public void move(final BwCalendar val, final BwCalendar newParent) throws CalFacadeException { getSvc().getCal().moveCalendar(val, newParent); } @Override public void update(final BwCalendar val) throws CalFacadeException { val.adjustCategories(); /* Ensure it's not in admin prefs if it's a folder. * User may have switched from calendar to folder. */ if (!val.getCalendarCollection() && isPublicAdmin()) { /* Remove from preferences */ ((Preferences)getSvc().getPrefsHandler()).updateAdminPrefs(true, val, null, null, null); } if (val.getPwNeedsEncrypt()) { encryptPw(val); } getCal().updateCalendar(val); } @Override public boolean delete(final BwCalendar val, final boolean emptyIt, final boolean sendSchedulingMessage) throws CalFacadeException { return delete(val, emptyIt, false, sendSchedulingMessage); } @Override public boolean isUserRoot(final BwCalendar cal) throws CalFacadeException { if ((cal == null) || (cal.getPath() == null)) { return false; } final String[] ss = cal.getPath().split("/"); final int pathLength = ss.length - 1; // First element is empty string return (pathLength == 2) && (ss[1].equals(getBasicSyspars().getUserCalendarRoot())); } /* (non-Javadoc) * @see org.bedework.calsvci.CalendarsI#resolveAlias(org.bedework.calfacade.BwCalendar, boolean, boolean) */ @Override public BwCalendar resolveAlias(final BwCalendar val, final boolean resolveSubAlias, final boolean freeBusy) throws CalFacadeException { return getCal().resolveAlias(val, resolveSubAlias, freeBusy); } @Override public SynchStatusResponse getSynchStatus(final String path) throws CalFacadeException { return getSvc().getSynch().getSynchStatus(get(path)); } @Override public CheckSubscriptionResult checkSubscription(final String path) throws CalFacadeException { return getSvc().getSynch().checkSubscription(get(path)); } @Override public String getSyncToken(final String path) throws CalFacadeException { return getCal().getSyncToken(path); } /* ==================================================================== * package private methods * ==================================================================== */ /** * @param val an href * @return list of any aliases for the current user pointing at the given href * @throws CalFacadeException */ List<BwCalendar> findUserAlias(final String val) throws CalFacadeException { return getCal().findAlias(val); } Set<BwCalendar> getSynchCols(final String path, final String lastmod) throws CalFacadeException { return getCal().getSynchCols(path, lastmod); } BwCalendar getSpecial(final BwPrincipal owner, final int calType, final boolean create, final int access) throws CalFacadeException { final Calintf.GetSpecialCalendarResult gscr = getSvc().getCal().getSpecialCalendar( owner, calType, create, PrivilegeDefs.privAny); if (gscr.noUserHome) { getSvc().getUsersHandler().add(owner.getAccount()); } return getSvc().getCal().getSpecialCalendar(owner, calType, create, PrivilegeDefs.privAny).cal; } boolean delete(final BwCalendar val, final boolean emptyIt, final boolean reallyDelete, final boolean sendSchedulingMessage) throws CalFacadeException { if (!emptyIt) { /** Only allow delete if not in use */ if (!getCal().isEmpty(val)) { throw new CalFacadeException(CalFacadeException.collectionNotEmpty); } } final BwPreferences prefs = getSvc().getPrefsHandler().get( getSvc().getUsersHandler().getPrincipal(val.getOwnerHref())); if (val.getPath().equals(prefs.getDefaultCalendarPath())) { throw new CalFacadeException(CalFacadeException.cannotDeleteDefaultCalendar); } /* Remove any sharing */ if (val.getCanAlias()) { getSvc().getSharingHandler().delete(val); } getSvc().getSharingHandler().unsubscribe(val); /* Remove from preferences */ ((Preferences)getSvc().getPrefsHandler()).updateAdminPrefs(true, val, null, null, null); /* If it' an alias we just delete it - otherwise we might need to empty it. */ if (!val.getInternalAlias() && emptyIt) { if (val.getCalendarCollection()) { final Events events = ((Events)getSvc().getEventsHandler()); for (final EventInfo ei: events.getSynchEvents(val.getPath(), null)) { events.delete(ei, false, sendSchedulingMessage, true); } } /* Remove resources */ final ResourcesI resI = getSvc().getResourcesHandler(); final Collection<BwResource> rs = resI.getAll(val.getPath()); if (!Util.isEmpty(rs)) { for (final BwResource r: rs) { resI.delete(Util.buildPath(false, r.getColPath(), "/", r.getName())); } } for (final BwCalendar cal: getChildren(val)) { if (!delete(cal, true, true, sendSchedulingMessage)) { // Somebody else at it getSvc().rollbackTransaction(); throw new CalFacadeException(CalFacadeException.collectionNotFound, cal.getPath()); } } } getSvc().getSynch().unsubscribe(val, true); val.getProperties().clear(); /* Attempt to tombstone it */ return getSvc().getCal().deleteCalendar(val, reallyDelete); } /* ==================================================================== * private methods * ==================================================================== */ private void getAddContentCalendarCollections(final boolean includeAliases, final BwCalendar root, final Set<BwCalendar> cals) throws CalFacadeException { if (!includeAliases && root.getAlias()) { return; } final BwCalendar col = resolveAlias(root, true, false); if (col == null) { // No access or gone return; } if (col.getCalType() == BwCalendar.calTypeCalendarCollection) { /* We might want to add the busy time calendar here - * presumably we will want availability stored somewhere. * These might be implicit operations however. */ final CurrentAccess ca = getSvc().checkAccess(col, PrivilegeDefs.privWriteContent, true); if (ca.getAccessAllowed()) { cals.add(root); // Might be an alias, might not } return; } if (root.getCalendarCollection()) { // Leaf but cannot add here return; } for (final BwCalendar ch: getChildren(root)) { getAddContentCalendarCollections(includeAliases, ch, cals); } } private void encryptPw(final BwCalendar val) throws CalFacadeException { try { val.setRemotePw(getSvc().getEncrypter().encrypt(val.getRemotePw())); } catch (final Throwable t) { throw new CalFacadeException(t); } } /* This provides some limits to shareable entity updates for the * admin users. It is applied in addition to the normal access checks * applied at the lower levels. */ private void updateOK(final Object o) throws CalFacadeException { if (isGuest()) { throw new CalFacadeAccessException(); } if (isSuper()) { // Always ok return; } if (!(o instanceof BwShareableDbentity)) { throw new CalFacadeAccessException(); } if (!isPublicAdmin()) { // Normal access checks apply return; } final BwShareableDbentity ent = (BwShareableDbentity)o; if (getPars().getAdminCanEditAllPublicContacts() || ent.getCreatorHref().equals(getPrincipal().getPrincipalRef())) { return; } throw new CalFacadeAccessException(); } private String normalizeUri(String uri) throws CalFacadeException { /*Remove all "." and ".." components */ try { uri = new URI(null, null, uri, null).toString(); uri = new URI(URLEncoder.encode(uri, "UTF-8")).normalize().getPath(); uri = Util.buildPath(true, URLDecoder.decode(uri, "UTF-8")); if (debug) { trace("Normalized uri=" + uri); } return uri; } catch (final Throwable t) { if (debug) { error(t); } throw new CalFacadeException("Bad uri: " + uri); } } }
true
a26ec745494fea3a3ebe42dd12de4a780a800aef
Java
kannabi/graphony
/Isoline/src/ru/nsu/ccfit/schukin/IsolineView/CoordinatesBar.java
UTF-8
1,915
2.890625
3
[]
no_license
package ru.nsu.ccfit.schukin.IsolineView; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.text.DecimalFormat; import static ru.nsu.ccfit.schukin.Entities.Const.DEFAULT_HEIGHT; import static ru.nsu.ccfit.schukin.Entities.Const.DEFAULT_WIDTH; import static ru.nsu.ccfit.schukin.Entities.Const.LEGEND_BACKGROUND_COLOR; /** * Created by kannabi on 04.04.2017. */ public class CoordinatesBar extends JPanel{ private int width = DEFAULT_WIDTH; private int height = DEFAULT_HEIGHT / 18; private BufferedImage buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); public CoordinatesBar (){ setPreferredSize(new Dimension(width, height)); spanWhole(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(buffer, 0, 0, null); } public void drawValues(double x, double y, double functionValue){ spanHalf(); Graphics g = buffer.createGraphics(); Font font = new Font("Helvetica", Font.PLAIN, 22); g.setFont(font); g.setColor(Color.black); String values = "x: " + new DecimalFormat("#.###").format(x) + " | " + "y: " + new DecimalFormat("#.###").format(y) + " | " + "f: " + new DecimalFormat("#.###").format(functionValue); g.drawString(values, 5, height - height / 2 + 10); repaint(); } private void spanWhole(){ for (int i = 0; i < width; ++i) for (int j = 0; j < height; ++j) buffer.setRGB(i, j, LEGEND_BACKGROUND_COLOR); } private void spanHalf(){ for (int i = 0; i < width / 2; ++i) for (int j = 0; j < height; ++j) buffer.setRGB(i, j, LEGEND_BACKGROUND_COLOR); } }
true
3fbd65d97765fc7b8f8b95301c0c7f14686f125f
Java
menakaprabu/Learnbay
/src/main/java/Companies/eBay/MinMeetingRequired.java
UTF-8
937
3.140625
3
[]
no_license
package Companies.eBay; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Queue; public class MinMeetingRequired { private static int minMeetingRooms(int[][] intervals) { if (intervals.length == 0) { return 0; } Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); int count = 1; Queue<Integer> q = new PriorityQueue<>(); q.add(intervals[0][1]); for (int i = 1; i < intervals.length; i++) { if (q.peek() > intervals[i][0]) { count++; } else { q.poll(); } q.add(intervals[i][1]); } return count; } public static void main(String[] args){ int[][] intervals = {{0,30},{5,10},{15,20}}; int count = minMeetingRooms(intervals); System.out.println("count ="+count); } }
true
7c962b75742f8d8c332b4776568eaee7bca22143
Java
afahmip/ArkavQuariumJava
/src/com/arkavquarium/controller/GameOption.java
UTF-8
166
1.84375
2
[]
no_license
package com.arkavquarium.controller; /** * Represents the options on the game. */ enum GameOption { NONE, BUY_FOOD, BUY_GUPPY, BUY_PIRANHA, BUY_EGG, TAKE_COIN }
true
25b2e39a92e0404955ad25ebb6465a329921eb3d
Java
tripti91/Foodwayz
/app/src/main/java/com/foodwayz/owner/OwnerFreagment/Resturent_detail_Fragment.java
UTF-8
17,279
1.5625
2
[]
no_license
package com.foodwayz.owner.OwnerFreagment; import android.Manifest; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import com.foodwayz.owner.HomeActivity; import com.foodwayz.R; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import java.util.ArrayList; import java.util.List; /** * Created by Belal on 18/09/16. */ public class Resturent_detail_Fragment extends Fragment implements OnMapReadyCallback, View.OnClickListener { private TabLayout tabLayout; private ViewPager viewPager; //private MapView mapView; // private GoogleMap mMap; double latitude; double longitude; private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 0; private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 0; private ImageView background_image; TextView tv_get_direction,rating_write_review; Button bt_Order_now; TextView bt_order_food_now; ScrollView scrollView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.resturent_detail, container, false); HomeActivity.action_bar_share.setVisibility(View.VISIBLE); scrollView = (ScrollView)view.findViewById(R.id.scrollView); HomeActivity.title.setVisibility(View.VISIBLE); HomeActivity.action_bar_delete.setVisibility(view.GONE); tv_get_direction = (TextView)view.findViewById(R.id.tv_get_direction); rating_write_review= (TextView)view.findViewById(R.id.rating_write_review); bt_Order_now= (Button)view.findViewById(R.id.bt_Order_now); bt_Order_now.setOnClickListener(this); bt_order_food_now= (TextView)view.findViewById(R.id.bt_order_food_now); bt_order_food_now.setOnClickListener(this); viewPager = (ViewPager) view.findViewById(R.id.viewpager); setupViewPager(viewPager); HomeActivity.title.setVisibility(View.VISIBLE); HomeActivity.city.setVisibility(View.GONE); HomeActivity.location.setVisibility(View.GONE); tabLayout = (TabLayout) view.findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); setupTabIcons(); background_image = (ImageView) view.findViewById(R.id.background_image); Bitmap icon = BitmapFactory.decodeResource(getActivity().getResources(), R.mipmap.splash); icon = processImage(icon); BitmapDrawable ob = new BitmapDrawable(getResources(), icon); // mapView = (MapView) view.findViewById(R.id.map); // mapView.onCreate(savedInstanceState); // mapView.onResume(); // mapView.getMapAsync(this); tv_get_direction.setOnClickListener(this); rating_write_review.setOnClickListener(this); ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager()); adapter.addFrag(new Review_fragment(), "Reviews"); return view; } private void setupTabIcons() { TextView tabOne = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.custom_tab, null); tabOne.setTextColor(Color.parseColor("#333333")); tabOne.setGravity(Gravity.CENTER); tabOne.setText("Reviews"); tabOne.setTextSize(12); tabLayout.getTabAt(0).setCustomView(tabOne); TextView tabTwo = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.custom_tab, null); tabTwo.setTextColor(Color.parseColor("#333333")); tabTwo.setGravity(Gravity.CENTER); tabTwo.setText("About"); tabLayout.getTabAt(1).setCustomView(tabTwo); TextView tabThree = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.custom_tab, null); tabThree.setTextColor(Color.parseColor("#333333")); tabThree.setGravity(Gravity.CENTER); tabThree.setText("Gallary"); tabLayout.getTabAt(2).setCustomView(tabThree); } public void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager()); adapter.addFrag(new Review_fragment(), "Reviews"); adapter.addFrag(new About_ResturentDetail_Fragment(), "Abouts"); adapter.addFrag(new Gallary_fragment(), "Gallarys"); viewPager.setAdapter(adapter); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //you can set the title for your toolbar here for different fragments different titles getActivity().setTitle("Menu 1"); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_get_direction: //scrollView.fullScroll(View.FOCUS_DOWN); Bundle bundle = new Bundle(); bundle.putString("Lat", "22.7196"); bundle.putString("Log", "75.8577"); Fragment fragments = new GetDirection_Fragment(); fragments.setArguments(bundle); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.content_frame, fragments); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); break; case R.id.rating_write_review: ShowReviewdialog(); break; case R.id.btn_order: Fragment fragment = new OrderPlace_Fragment(); FragmentManager fragmentManagers = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransactions = fragmentManagers.beginTransaction(); fragmentTransactions.replace(R.id.content_frame, fragment); fragmentTransactions.addToBackStack("back"); fragmentTransactions.commit(); break; case R.id.bt_order_food_now: Fragment fragment_ = new OrderPlace_Fragment(); FragmentManager fragmentManager_ = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction_ = fragmentManager_.beginTransaction(); fragmentTransaction_.replace(R.id.content_frame, fragment_); fragmentTransaction_.addToBackStack("back"); fragmentTransaction_.commit(); break; } } private void ShowReviewdialog() { final Dialog mDialog = new Dialog(getActivity()); mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mDialog.getWindow().setBackgroundDrawable( new ColorDrawable(Color.TRANSPARENT)); mDialog.setContentView(R.layout.feedback); /* spinner = (Spinner) mDialog.findViewById(R.id.spinner); bt_Search_food = (Button) mDialog.findViewById(R.id.bt_Search_food); SpinAdapter dataAdapter = new SpinAdapter(HomeActivity.this, simple_spinner_item, city_detail); // Drop down layout style - list view with radio button dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner spinner.setAdapter(dataAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { City = city_detail.get(arg2).getCity_name(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); bt_Search_food.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle bundle =new Bundle(); bundle.putString("City",City); bundle.putString("Area",Area); Fragment fragments = new Menu1(); fragments.setArguments(bundle); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.content_frame, fragments); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); mDialog.dismiss(); City =""; Area=""; } }); tv_Address = (AutoCompleteTextView) mDialog.findViewById(R.id.tv_Address); tv_Address.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { adapter = new AutocompleteAdapters(HomeActivity.this, android.R.layout.simple_dropdown_item_1line, City); tv_Address.setAdapter(adapter); tv_Address.setThreshold(1); } @Override public void afterTextChanged(Editable editable) { } }); tv_Address.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Area= adapter.getItem(position).getCity_name(); System.out.println("countryName---->"+Area); tv_Address.setText(Area); } });*/ mDialog.show(); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFrag(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } @Override public void onMapReady(GoogleMap googleMap) { if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling requestReadPhoneMapPermission(); requestMap_access_fine_location(); return; } // mMap = googleMap; // mMap.animateCamera(CameraUpdateFactory.zoomTo((float) 2.6), 200, null); // mMap.getUiSettings().setMapToolbarEnabled(false); // mMap.getUiSettings().setZoomControlsEnabled(false); //mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); // mMap.setMyLocationEnabled(true); // LocationManager lm = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE); // List<String> providers = lm.getProviders(true); // Location l = null; // // for (int i = 0; i < providers.size(); i++) { // l = lm.getLastKnownLocation(providers.get(i)); // if (l != null) { // latitude = l.getLatitude(); // longitude = l.getLongitude(); // break; // } // } // // if (mMap != null) { // // CameraPosition cameraPosition = new CameraPosition.Builder() // .target(new LatLng(22.7196, 75.8577)).zoom(15).build(); // mMap.animateCamera(CameraUpdateFactory // .newCameraPosition(cameraPosition)); // } } private void requestReadPhoneMapPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)) { new AlertDialog.Builder(getActivity()) .setTitle("Permission Req") .setCancelable(false) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION); } }) // .setIcon(R.drawable.arrow) .show(); } else { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION); } } private void requestMap_access_fine_location() { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) { new AlertDialog.Builder(getActivity()) .setTitle("Permission Req") .setCancelable(false) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); } }) // .setIcon(R.drawable.icon) .show(); } else { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); } } private Bitmap processImage(Bitmap bitmap) { Bitmap bmp; bmp = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); BitmapShader shader = new BitmapShader(bitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); float radius = bitmap.getWidth(); Canvas canvas = new Canvas(bmp); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setShader(shader); RectF rect = new RectF(-bitmap.getWidth() / 2f, 0, bitmap.getWidth() / 2f, bitmap.getHeight()); canvas.drawOval(rect, paint); return bmp; } @Override public void onResume() { super.onResume(); getView().setFocusableInTouchMode(true); getView().requestFocus(); getView().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) { onBackPressed(); return true; } return false; } }); } public void onBackPressed() { if (getActivity().getSupportFragmentManager().getBackStackEntryCount() > 0) { getActivity().getSupportFragmentManager().popBackStack(); } else { getActivity().finish(); } } }
true
cd9258969e13b043aa963d2d71bfba84dc5f7c2f
Java
JAVA-FOR-YOUR-HOSPITAL/Hospital-reservation-program
/src/Hostpital_System_View/ViewMain2.java
UHC
9,319
2.484375
2
[]
no_license
package Hostpital_System_View; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.time.Month; import java.util.ArrayList; import java.util.Calendar; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JRadioButton; import Hostpital_System_Model.Book_markDAO; import Hostpital_System_Model.DeptDAO; import Hostpital_System_Model.DoctorDAO; import Hostpital_System_Model.HospitalDAO; import Hostpital_System_Model.InfoVO; import Hostpital_System_Model.ReservationDAO; import java.awt.Font; public class ViewMain2 { private JFrame frame; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ViewMain2 window = new ViewMain2(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public ViewMain2() { initialize(); Dimension frameSize = frame.getSize(); // ũ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // (ȭ - ȭ ) / 2, (ȭ - ȭ ) / 2 frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2); frame.setVisible(true); } /** * Initialize the contents of the frame. */ private void initialize() { ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>(); frame = new JFrame(); frame.setBounds(100, 100, 368, 565); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel backgdMain = new JLabel(new ImageIcon("img/ViewMain2.png")); backgdMain.setBounds(0, 0, 352, 526); frame.getContentPane().setLayout(null); JButton home_bt = new JButton(new ImageIcon("img/home_bt.png")); home_bt.setBounds(150, 5, 60, 60); frame.getContentPane().add(home_bt); home_bt.setBorderPainted(false); home_bt.setFocusPainted(false); home_bt.setContentAreaFilled(false); JButton mine_bt = new JButton(new ImageIcon("img/mine_bt.png")); mine_bt.setBounds(300, 10, 60, 60); frame.getContentPane().add(mine_bt); mine_bt.setBorderPainted(false); mine_bt.setFocusPainted(false); mine_bt.setContentAreaFilled(false); mine_bt.addActionListener(new ActionListener() { // ͸Ŭ ۼ public void actionPerformed(ActionEvent e) { MyPage mp = new MyPage(); frame.dispose(); } }); JButton back_bt = new JButton(new ImageIcon("img/back_bt.png")); back_bt.setBounds(5, 10, 60, 60); frame.getContentPane().add(back_bt); back_bt.setBorderPainted(false); back_bt.setFocusPainted(false); back_bt.setContentAreaFilled(false); JButton nowDay = new JButton(); nowDay.setBounds(30, 110, 95, 23); frame.getContentPane().add(nowDay); nowDay.setBorderPainted(false); nowDay.setFocusPainted(false); nowDay.setContentAreaFilled(false); nowDay.addActionListener(new ActionListener() { // ͸Ŭ ۼ public void actionPerformed(ActionEvent e) { ViewMain vm = new ViewMain(); frame.dispose(); } }); JLabel startDay = new JLabel(""); startDay.setFont(new Font("12ԵƮ帲Medium", Font.PLAIN, 13)); startDay.setBounds(60, 160, 95, 15); frame.getContentPane().add(startDay); Calendar cal = Calendar.getInstance(); cal.setTime(new java.util.Date(System.currentTimeMillis())); String toDay = new java.text.SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); startDay.setText(toDay); JLabel finalDay = new JLabel(""); finalDay.setFont(new Font("12ԵƮ帲Medium", Font.PLAIN, 13)); finalDay.setBounds(210, 160, 78, 15); frame.getContentPane().add(finalDay); cal.add(Calendar.DATE, 31); String day = new java.text.SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); finalDay.setText(day); JLabel reserveDay = new JLabel(""); reserveDay.setFont(new Font("12ԵƮ帲Medium", Font.PLAIN, 12)); reserveDay.setBounds(90, 216, 120, 15); frame.getContentPane().add(reserveDay); JLabel hosN = new JLabel(""); hosN.setFont(new Font("12ԵƮ帲Medium", Font.PLAIN, 12)); hosN.setBounds(90, 240, 120, 15); frame.getContentPane().add(hosN); JLabel depN = new JLabel(""); depN.setFont(new Font("12ԵƮ帲Medium", Font.PLAIN, 12)); depN.setBounds(90, 264, 120, 15); frame.getContentPane().add(depN); JLabel docN = new JLabel(""); docN.setFont(new Font("12ԵƮ帲Medium", Font.PLAIN, 12)); docN.setBounds(90, 288, 120, 15); frame.getContentPane().add(docN); JLabel reserveDay2 = new JLabel(""); reserveDay2.setFont(new Font("12ԵƮ帲Medium", Font.PLAIN, 12)); reserveDay2.setBounds(90, 339, 120, 15); frame.getContentPane().add(reserveDay2); JLabel hosN2 = new JLabel(""); hosN2.setFont(new Font("12ԵƮ帲Medium", Font.PLAIN, 12)); hosN2.setBounds(90, 363, 120, 15); frame.getContentPane().add(hosN2); JLabel depN2 = new JLabel(""); depN2.setFont(new Font("12ԵƮ帲Medium", Font.PLAIN, 12)); depN2.setBounds(90, 386, 120, 15); frame.getContentPane().add(depN2); JLabel docN2 = new JLabel(""); docN2.setFont(new Font("12ԵƮ帲Medium", Font.PLAIN, 12)); docN2.setBounds(90, 410, 120, 15); frame.getContentPane().add(docN2); ReservationDAO dao = new ReservationDAO(); list = dao.showRes_mon(InfoVO.getId()); if(list == null) { System.out.println(" ϴ."); }else { for(int i = 0; i < list.size(); i++) { if(i == 0) { reserveDay.setText(list.get(i).get(3)); hosN.setText(list.get(i).get(0)); depN.setText(list.get(i).get(1)); docN.setText(list.get(i).get(2)); }else { reserveDay2.setText(list.get(i).get(3)); hosN2.setText(list.get(i).get(0)); depN2.setText(list.get(i).get(1)); docN2.setText(list.get(i).get(2)); } } } JRadioButton bookSelect_bt = new JRadioButton(); bookSelect_bt.setOpaque(false); bookSelect_bt.setIcon(new ImageIcon("img/bookCheck_bt1.png")); bookSelect_bt.setBounds(290, 190, 37, 37); bookSelect_bt.setSelectedIcon(new ImageIcon("img/bookCheck_bt2.png")); frame.getContentPane().add(bookSelect_bt); JRadioButton bookSelect2_bt = new JRadioButton(); bookSelect2_bt.setSelectedIcon(new ImageIcon("img/bookCheck_bt2.png")); bookSelect2_bt.setOpaque(false); bookSelect2_bt.setIcon(new ImageIcon("img/bookCheck_bt1.png")); bookSelect2_bt.setBounds(290, 317, 37, 37); frame.getContentPane().add(bookSelect2_bt); home_bt.addActionListener(new ActionListener() { // ͸Ŭ ۼ public void actionPerformed(ActionEvent e) { if(bookSelect_bt.isSelected() == true) { HospitalDAO hos = new HospitalDAO(); int hos_num = hos.getHos_num(hosN.getText()); DeptDAO dept = new DeptDAO(); int dept_num = dept.getDept_num(hos_num, depN.getText()); DoctorDAO doc = new DoctorDAO(); String doc_id = doc.getDoc_id(hos_num, dept_num, docN.getText()); Book_markDAO dao = new Book_markDAO(); int result = dao.book_mark(InfoVO.getId(), hos_num, dept_num, doc_id); if(result == 1) { System.out.println(" "); } } if(bookSelect2_bt.isSelected() == true) { HospitalDAO hos = new HospitalDAO(); int hos_num = hos.getHos_num(hosN2.getText()); DeptDAO dept = new DeptDAO(); int dept_num = dept.getDept_num(hos_num, depN2.getText()); DoctorDAO doc = new DoctorDAO(); String doc_id = doc.getDoc_id(hos_num, dept_num, docN2.getText()); Book_markDAO dao = new Book_markDAO(); int result = dao.book_mark(InfoVO.getId(), hos_num, dept_num, doc_id); if(result == 1) { System.out.println(" "); } } GUIMain.main(null); frame.dispose(); } }); JButton cancel = new JButton(new ImageIcon("img/cancel2.png")); cancel.setBounds(250, 280, 66, 23); frame.getContentPane().add(cancel); cancel.setBorderPainted(false); cancel.setFocusPainted(false); cancel.setContentAreaFilled(false); cancel.addActionListener(new ActionListener() { // ͸Ŭ ۼ public void actionPerformed(ActionEvent e) { ViewMain2 vm2 = new ViewMain2(); frame.dispose(); } }); JButton cancel2 = new JButton(new ImageIcon("img/cancel2.png")); cancel2.setBounds(250, 404, 66, 23); frame.getContentPane().add(cancel2); cancel2.setBorderPainted(false); cancel2.setFocusPainted(false); cancel2.setContentAreaFilled(false); cancel2.addActionListener(new ActionListener() { // ͸Ŭ ۼ public void actionPerformed(ActionEvent e) { ViewMain2 vm3 = new ViewMain2(); frame.dispose(); } }); frame.getContentPane().add(backgdMain); } }
true
cf911ac9dfd728558779ae456bcfadbe938b5f3b
Java
YumTao/Topology
/storm-wordcount/src/main/java/com/yumtao/driver/WordCountTp.java
UTF-8
1,490
2.65625
3
[]
no_license
package com.yumtao.driver; import backtype.storm.Config; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.topology.TopologyBuilder; import backtype.storm.tuple.Fields; /** * Topology任务注册类 1.指定sport实例 2.指定bolt实例 3.提交任务 * * @author yumTao * */ public class WordCountTp { public static void main(String[] args) throws Exception { TopologyBuilder builder = new TopologyBuilder(); // 设置sport(id, sport实例,并发度) builder.setSpout("productWordSpt", new MyWordSport(), 2); // 设置bolt,并制定分组策略,入参为输入的对应id,这里是sport的id builder.setBolt("splitBolt", new MyWordSplitBolt(), 2).shuffleGrouping("productWordSpt"); // 设置bolt,并制定分组策略,入参为输入的对应id,这里是上一个bolt的id builder.setBolt("counterBolt", new MyCounterBolt(), 4).fieldsGrouping("splitBolt", new Fields("word")); StormTopology wordcountTopology = builder.createTopology(); Config config = new Config(); // 设置worker数 config.setNumWorkers(2); // 3.提交任务两种方式,集群模式和本地模式 // 集群模式 StormSubmitter.submitTopology("taowordcount", config, wordcountTopology); // 本地模式 // LocalCluster localCluster = new LocalCluster(); // // 提交任务(任务名,配置,topology实例) // localCluster.submitTopology("taowordcount", config, wordcountTopology); } }
true
33f8ceb4d684cc5b700f035051cc9859224b027b
Java
yobbo-wang/MS
/src/main/java/wang/yobbo/sys/controller/SysMenuController.java
UTF-8
3,243
2.15625
2
[]
no_license
package wang.yobbo.sys.controller; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; 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; import wang.yobbo.common.appengine.InvokeResult; import wang.yobbo.sys.entity.SysMenu; import wang.yobbo.sys.entity.SysMenuTable; import wang.yobbo.sys.service.SysMenuService; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller @RequestMapping("menu") public class SysMenuController { @Autowired private SysMenuService sysMenuService; @RequestMapping(value = "findByPId", method = RequestMethod.POST) @ResponseBody public List<SysMenu> findByPId(HttpServletRequest request){ String pid = new String(); if(request.getParameter("PID") != null || StringUtils.isNotEmpty(request.getParameter("PID"))){ pid = request.getParameter("PID"); } List<SysMenu> menus = this.sysMenuService.findByPId(pid); return menus; } @RequestMapping(value = "save", method = RequestMethod.POST) @ResponseBody public InvokeResult save(SysMenu sysMenu){ try{ if(StringUtils.isEmpty(sysMenu.getParent_id())){ sysMenu.setParent_id(null); } this.sysMenuService.save(sysMenu); return InvokeResult.success("保存成功!"); }catch (Exception e){ e.printStackTrace(); return InvokeResult.failure("保存失败!"); } } @RequestMapping(value = "addEntity", method = RequestMethod.POST) @ResponseBody public InvokeResult addEntity(SysMenuTable sysMenuTable){ try{ if(StringUtils.isEmpty(sysMenuTable.getMenu_id())){ return InvokeResult.failure("请选择对应菜单,再添加实体!"); } this.sysMenuService.addEntity(sysMenuTable); return InvokeResult.success("保存成功!"); }catch (Exception e){ e.printStackTrace(); return InvokeResult.failure("保存失败!"); } } @RequestMapping(value = "deleteEntity", method = RequestMethod.POST) @ResponseBody public InvokeResult deleteEntity(@RequestParam(value="id") String id){ try{ int count = this.sysMenuService.deleteEntity(id); return InvokeResult.success("已删除" + count + "条记录!"); }catch (Exception e){ e.printStackTrace(); return InvokeResult.failure("删除失败!"); } } @RequestMapping(value = "delete", method = RequestMethod.POST) @ResponseBody public InvokeResult delete(@RequestParam(value="id") String id){ try{ int count = this.sysMenuService.delete(id); return InvokeResult.success("已删除" + count + "条记录!"); }catch (Exception e){ e.printStackTrace(); return InvokeResult.failure("删除失败!"); } } }
true
cedee591d0ff917b9e1ab2ea7d961300b327be8d
Java
h2oai/h2o-3
/h2o-mapreduce-generic/src/main/java/water/hadoop/h2odriver.java
UTF-8
82,228
1.585938
2
[ "Apache-2.0" ]
permissive
package water.hadoop; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import water.H2O; import water.H2OStarter; import water.ProxyStarter; import water.hadoop.clouding.fs.CloudingEvent; import water.hadoop.clouding.fs.CloudingEventType; import water.hadoop.clouding.fs.FileSystemBasedClouding; import water.hadoop.clouding.fs.FileSystemCloudingEventSource; import water.hive.ImpersonationUtils; import water.hive.HiveTokenGenerator; import water.init.NetworkInit; import water.network.SecurityUtils; import water.util.ArrayUtils; import water.util.BinaryFileTransfer; import water.util.StringUtils; import water.webserver.iface.Credentials; import java.io.*; import java.lang.reflect.Method; import java.net.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import static water.hive.DelegationTokenRefresher.*; import static water.util.JavaVersionUtils.JAVA_VERSION; /** * Driver class to start a Hadoop mapreduce job which wraps an H2O cluster launch. * * Adapted from * https://svn.apache.org/repos/asf/hadoop/common/trunk/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/SleepJob.java */ @SuppressWarnings("deprecation") public class h2odriver extends Configured implements Tool { enum CloudingMethod { CALLBACKS, FILESYSTEM } final static String ARGS_CONFIG_FILE_PATTERN = "/etc/h2o/%s.args"; final static String DEFAULT_ARGS_CONFIG = "h2odriver"; final static String ARGS_CONFIG_PROP = "ai.h2o.args.config"; final static String DRIVER_JOB_CALL_TIMEOUT_SEC = "ai.h2o.driver.call.timeout"; final static String H2O_AUTH_TOKEN_REFRESHER_ENABLED = "h2o.auth.tokenRefresher.enabled"; final static String H2O_DYNAMIC_AUTH_S3A_TOKEN_REFRESHER_ENABLED = "h2o.auth.dynamicS3ATokenRefresher.enabled"; private static final int GEN_PASSWORD_LENGTH = 16; static { if(!JAVA_VERSION.isKnown()) { System.err.println("Couldn't parse Java version: " + System.getProperty("java.version")); System.exit(1); } } final static int DEFAULT_CLOUD_FORMATION_TIMEOUT_SECONDS = 120; final static int CLOUD_FORMATION_SETTLE_DOWN_SECONDS = 2; final static int DEFAULT_EXTRA_MEM_PERCENT = 10; // Options that are parsed by the main thread before other threads are created. static String jobtrackerName = null; static int numNodes = -1; static String outputPath = null; static String mapperXmx = null; static int extraMemPercent = -1; // Between 0 and 10, typically. Cannot be negative. static String mapperPermSize = null; static String driverCallbackBindIp = null; static String driverCallbackPublicIp = null; static int driverCallbackPort = 0; // By default, let the system pick the port. static PortRange driverCallbackPortRange = null; static String network = null; static boolean disown = false; static String clusterReadyFileName = null; static String clusterFlatfileName = null; static String hadoopJobId = ""; static String applicationId = ""; static int cloudFormationTimeoutSeconds = DEFAULT_CLOUD_FORMATION_TIMEOUT_SECONDS; static int nthreads = -1; static String contextPath = null; static int basePort = -1; static int portOffset = -1; static boolean beta = false; static boolean enableRandomUdpDrop = false; static boolean enableExceptions = false; static boolean enableVerboseGC = true; static boolean enablePrintGCDetails = !JAVA_VERSION.useUnifiedLogging(); static boolean enablePrintGCTimeStamps = !JAVA_VERSION.useUnifiedLogging(); static boolean enableVerboseClass = false; static boolean enablePrintCompilation = false; static boolean enableExcludeMethods = false; static boolean enableLog4jDefaultInitOverride = true; static String logLevel; static boolean enableDebug = false; static boolean enableSuspend = false; static int debugPort = 5005; // 5005 is the default from IDEA static String flowDir = null; static ArrayList<String> extraArguments = new ArrayList<String>(); static ArrayList<String> extraJvmArguments = new ArrayList<String>(); static String jksFileName = null; static String jksPass = null; static String jksAlias = null; static boolean hostnameAsJksAlias = false; static String securityConf = null; static boolean internal_secure_connections = false; static boolean allow_insecure_xgboost = false; static boolean use_external_xgboost = false; static boolean hashLogin = false; static boolean ldapLogin = false; static boolean kerberosLogin = false; static boolean spnegoLogin = false; static String spnegoProperties = null; static boolean pamLogin = false; static String loginConfFileName = null; static boolean formAuth = false; static String sessionTimeout = null; static String userName = System.getProperty("user.name"); static boolean client = false; static boolean proxy = false; static String runAsUser = null; static String principal = null; static String keytabPath = null; static boolean reportHostname = false; static boolean driverDebug = false; static String hiveJdbcUrlPattern = null; static String hiveHost = null; static String hivePrincipal = null; static boolean refreshHiveTokens = false; static boolean refreshHdfsTokens = false; static String hiveToken = null; static CloudingMethod cloudingMethod = CloudingMethod.CALLBACKS; static String cloudingDir = null; static String autoRecoveryDir = null; static boolean disableFlow = false; static boolean swExtBackend = false; static boolean configureS3UsingS3A = false; static boolean refreshS3ATokens = false; String proxyUrl = null; // All volatile fields represent a runtime state that might be touched by different threads volatile JobWrapper job = null; volatile CtrlCHandler ctrlc = null; volatile CloudingManager cm = null; // Modified while clouding-up volatile boolean clusterIsUp = false; volatile boolean clusterFailedToComeUp = false; volatile boolean clusterHasNodeWithLocalhostIp = false; volatile boolean shutdownRequested = false; // Output of clouding volatile String clusterIp = null; volatile int clusterPort = -1; volatile static String flatfileContent = null; // Only used for debugging volatile AtomicInteger numNodesStarted = new AtomicInteger(); private static Credentials make(String user) { return new Credentials(user, SecurityUtils.passwordGenerator(GEN_PASSWORD_LENGTH)); } public void setShutdownRequested() { shutdownRequested = true; } public boolean getShutdownRequested() { return shutdownRequested; } public void setClusterIpPort(String ip, int port) { clusterIp = ip; clusterPort = port; } public String getPublicUrl() { String url; if (client) { url = H2O.getURL(NetworkInit.h2oHttpView.getScheme()); } else if (proxy) { url = proxyUrl; } else { url = getClusterUrl(); } return url; } private String getClusterUrl() { String scheme = (jksFileName == null) ? "http" : "https"; return scheme + "://" + clusterIp + ":" + clusterPort; } public static boolean usingYarn() { Class clazz = null; try { clazz = Class.forName("water.hadoop.H2OYarnDiagnostic"); } catch (Exception ignore) {} return (clazz != null); } public static void maybePrintYarnLogsMessage(boolean printExtraNewlines) { if (usingYarn()) { if (printExtraNewlines) { System.out.println(); } System.out.println("For YARN users, logs command is 'yarn logs -applicationId " + applicationId + "'"); if (printExtraNewlines) { System.out.println(); } } } public static void maybePrintYarnLogsMessage() { maybePrintYarnLogsMessage(true); } private static class PortRange { int from; int to; public PortRange(int from, int to) { this.from = from; this.to = to; } void validate() { if (from > to) error("Invalid port range (lower bound larger than upper bound: " + this + ")."); if ((from == 0) && (to != 0)) error("Invalid port range (lower bound cannot be 0)."); if (to > 65535) error("Invalid port range (upper bound > 65535)."); } boolean isSinglePort() { return from == to; } static PortRange parse(String rangeSpec) { if (rangeSpec == null) throw new NullPointerException("Port range is not specified (null)."); String[] ports = rangeSpec.split("-"); if (ports.length != 2) throw new IllegalArgumentException("Invalid port range specification (" + rangeSpec + ")"); return new PortRange(parseIntLenient(ports[0]), parseIntLenient(ports[1])); } private static int parseIntLenient(String s) { return Integer.parseInt(s.trim()); } @Override public String toString() { return "[" + from + "-" + to + "]"; } } public static class H2ORecordReader extends RecordReader<Text, Text> { H2ORecordReader() { } @Override public void initialize(InputSplit split, TaskAttemptContext context) { } @Override public boolean nextKeyValue() throws IOException { return false; } @Override public Text getCurrentKey() { return null; } @Override public Text getCurrentValue() { return null; } @Override public void close() throws IOException { } @Override public float getProgress() throws IOException { return 0; } } public static class EmptySplit extends InputSplit implements Writable { @Override public void write(DataOutput out) throws IOException { } @Override public void readFields(DataInput in) throws IOException { } @Override public long getLength() { return 0L; } @Override public String[] getLocations() { return new String[0]; } } public static class H2OInputFormat extends InputFormat<Text, Text> { H2OInputFormat() { } @Override public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException { List<InputSplit> ret = new ArrayList<InputSplit>(); int numSplits = numNodes; for (int i = 0; i < numSplits; ++i) { ret.add(new EmptySplit()); } return ret; } @Override public RecordReader<Text, Text> createRecordReader( InputSplit ignored, TaskAttemptContext taskContext) throws IOException { return(new H2ORecordReader()); } } public static void killJobAndWait(JobWrapper job) { boolean killed = false; try { System.out.println("Attempting to clean up hadoop job..."); job.killJob(); for (int i = 0; i < 5; i++) { if (job.isComplete()) { System.out.println("Killed."); killed = true; break; } Thread.sleep(1000); } } catch (Exception ignore) { } finally { if (! killed) { System.out.println("Kill attempt failed, please clean up job manually."); } } } /** * Handle Ctrl-C and other catchable shutdown events. * If we successfully catch one, then try to kill the hadoop job if * we have not already been told it completed. * * (Of course kill -9 cannot be handled.) */ class CtrlCHandler extends Thread { volatile boolean _complete = false; public void setComplete() { _complete = true; } @Override public void run() { if (_complete) { return; } _complete = true; try { if (job.isComplete()) { return; } } catch (Exception ignore) { } killJobAndWait(job); maybePrintYarnLogsMessage(); } } private void reportClientReady(String ip, int port) { assert client; if (clusterReadyFileName != null) { createClusterReadyFile(ip, port); System.out.println("Cluster notification file (" + clusterReadyFileName + ") created (using Client Mode)."); } if (clusterFlatfileName != null) { createFlatFile(flatfileContent); System.out.println("Cluster flatfile (" + clusterFlatfileName+ ") created."); } } private void reportProxyReady(String proxyUrl) throws Exception { assert proxy; if (clusterReadyFileName != null) { URL url = new URL(proxyUrl); createClusterReadyFile(url.getHost(), url.getPort()); System.out.println("Cluster notification file (" + clusterReadyFileName + ") created (using Proxy Mode)."); } if (clusterFlatfileName != null) { createFlatFile(flatfileContent); System.out.println("Cluster flatfile (" + clusterFlatfileName+ ") created."); } } private void reportClusterReady(String ip, int port) throws Exception { setClusterIpPort(ip, port); if (clusterFlatfileName != null) { createFlatFile(flatfileContent); System.out.println("Cluster flatfile (" + clusterFlatfileName+ ") created."); } if (client || proxy) return; // Hadoop cluster ready but we have to wait for client or proxy to come up if (clusterReadyFileName != null) { createClusterReadyFile(ip, port); System.out.println("Cluster notification file (" + clusterReadyFileName + ") created."); } } private static void createFlatFile(String flatFileContent) { String fileName = clusterFlatfileName + ".tmp"; try { File file = new File(fileName); BufferedWriter output = new BufferedWriter(new FileWriter(file)); output.write(flatFileContent); output.flush(); output.close(); File file2 = new File(clusterFlatfileName); boolean success = file.renameTo(file2); if (! success) { throw new RuntimeException("Failed to create file " + clusterReadyFileName); } } catch (IOException e) { throw new RuntimeException(e); } } private static void createClusterReadyFile(String ip, int port) { String fileName = clusterReadyFileName + ".tmp"; String text1 = ip + ":" + port + "\n"; String text2 = hadoopJobId + "\n"; try { File file = new File(fileName); BufferedWriter output = new BufferedWriter(new FileWriter(file)); output.write(text1); output.write(text2); output.flush(); output.close(); File file2 = new File(clusterReadyFileName); boolean success = file.renameTo(file2); if (! success) { throw new RuntimeException("Failed to create file " + clusterReadyFileName); } } catch (IOException e) { throw new RuntimeException(e); } } /** * Read and handle one Mapper->Driver Callback message. */ static class CallbackHandlerThread extends Thread { private Socket _s; private CallbackManager _cm; void setSocket (Socket value) { _s = value; } void setCallbackManager (CallbackManager value) { _cm = value; } @Override public void run() { MapperToDriverMessage msg = new MapperToDriverMessage(); try { msg.read(_s); char type = msg.getType(); if (type == MapperToDriverMessage.TYPE_EOF_NO_MESSAGE) { // Ignore it. _s.close(); return; } // System.out.println("Read message with type " + (int)type); if (type == MapperToDriverMessage.TYPE_EMBEDDED_WEB_SERVER_IP_PORT) { // System.out.println("H2O node " + msg.getEmbeddedWebServerIp() + ":" + msg.getEmbeddedWebServerPort() + " started"); _s.close(); } else if (type == MapperToDriverMessage.TYPE_FETCH_FLATFILE) { // DO NOT close _s here! // Callback manager accumulates sockets to H2O nodes so it can // a synthesized flatfile once everyone has arrived. _cm.registerNode(msg.getEmbeddedWebServerIp(), msg.getEmbeddedWebServerPort(), msg.getAttempt(), _s); } else if (type == MapperToDriverMessage.TYPE_CLOUD_SIZE) { _s.close(); _cm.announceNodeCloudSize(msg.getEmbeddedWebServerIp(), msg.getEmbeddedWebServerPort(), msg.getLeaderWebServerIp(), msg.getLeaderWebServerPort(), msg.getCloudSize()); } else if (type == MapperToDriverMessage.TYPE_EXIT) { String hostAddress = _s.getInetAddress().getHostAddress(); _s.close(); _cm.announceFailedNode(msg.getEmbeddedWebServerIp(), msg.getEmbeddedWebServerPort(), hostAddress, msg.getExitStatus()); } else { _s.close(); System.err.println("MapperToDriverMessage: Read invalid type (" + type + ") from socket, ignoring..."); } } catch (Exception e) { System.out.println("Exception occurred in CallbackHandlerThread"); System.out.println(e.toString()); e.printStackTrace(); } } } abstract class CloudingManager extends Thread { private final int _targetCloudSize; // desired number of nodes the cloud should eventually have private volatile AtomicInteger _numNodesReportingFullCloudSize = new AtomicInteger(); // number of fully initialized nodes CloudingManager(int targetCloudSize) { _targetCloudSize = targetCloudSize; } void announceNewNode(String ip, int port) { System.out.println("H2O node " + ip + ":" + port + " is joining the cluster"); if ("127.0.0.1".equals(ip)) { clusterHasNodeWithLocalhostIp = true; } numNodesStarted.incrementAndGet(); } void announceNodeCloudSize(String ip, int port, String leaderWebServerIp, int leaderWebServerPort, int cloudSize) throws Exception { System.out.println("H2O node " + ip + ":" + port + " reports H2O cluster size " + cloudSize + " [leader is " + leaderWebServerIp + ":" + leaderWebServerPort + "]"); if (cloudSize == _targetCloudSize) { announceCloudReadyNode(leaderWebServerIp, leaderWebServerPort); } } // announces a node that has a complete information about the rest of the cloud void announceCloudReadyNode(String leaderWebServerIp, int leaderWebServerPort) throws Exception { // Do this under a synchronized block to avoid getting multiple cluster ready notification files. synchronized (h2odriver.class) { if (! clusterIsUp) { int n = _numNodesReportingFullCloudSize.incrementAndGet(); if (n == _targetCloudSize) { reportClusterReady(leaderWebServerIp, leaderWebServerPort); clusterIsUp = true; } } } } void announceFailedNode(String ip, int port, String hostAddress, int exitStatus) { System.out.println("H2O node " + ip + ":" + port + (hostAddress != null ? " on host " + hostAddress : "") + " exited with status " + exitStatus); if (! clusterIsUp) { clusterFailedToComeUp = true; } } boolean cloudingInProgress() { return !(clusterIsUp || clusterFailedToComeUp || getShutdownRequested()); } void setFlatfile(String flatfile) { flatfileContent = flatfile; } final int targetCloudSize() { return _targetCloudSize; } protected void fatalError(String message) { System.out.println("ERROR: " + message); System.exit(1); } abstract void close() throws Exception; abstract void setMapperParameters(Configuration conf); } class FileSystemEventManager extends CloudingManager { private volatile FileSystemCloudingEventSource _event_source; FileSystemEventManager(int targetCloudSize, Configuration conf, String cloudingDir) throws IOException { super(targetCloudSize); _event_source = new FileSystemCloudingEventSource(conf, cloudingDir); } @Override public synchronized void start() { Path cloudingPath = _event_source.getPath(); System.out.println("Using filesystem directory to exchange information about started H2O nodes during the clouding process: " + cloudingPath); System.out.println("(You can override this by adding -clouding_dir argument.)"); try { if (! _event_source.isEmpty()) { fatalError("Clouding directory `" + cloudingPath + "` already exists/is not empty."); } } catch (IOException e) { throw new RuntimeException(e); } super.start(); } @Override void close() { _event_source = null; } boolean isOpen() { return _event_source != null; } @Override void setMapperParameters(Configuration conf) { conf.set(h2omapper.H2O_CLOUDING_IMPL, FileSystemBasedClouding.class.getName()); conf.set(h2omapper.H2O_CLOUDING_DIR_KEY, _event_source.getPath().toString()); conf.setInt(h2omapper.H2O_CLOUD_SIZE_KEY, targetCloudSize()); } private boolean sleep() { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); maybeLogException(e); return false; } return true; } @Override public void run() { FileSystemCloudingEventSource eventSource; while (cloudingInProgress() && (eventSource = _event_source) != null) { try { for (CloudingEvent event : eventSource.fetchNewEvents()) { if (processEvent(event)) { close(); return; // stop processing events immediately } } } catch (Exception e) { maybeLogException(e); close(); return; } if (! sleep()) { close(); return; } } } boolean processEvent(CloudingEvent event) throws Exception { CloudingEventType type = event.getType(); switch (type) { case NODE_STARTED: announceNewNode(event.getIp(), event.getPort()); break; case NODE_FAILED: int exitCode = 42; try { exitCode = Integer.parseInt(event.readPayload()); } catch (Exception e) { e.printStackTrace(); } announceFailedNode(event.getIp(), event.getPort(), null, exitCode); break; case NODE_CLOUDED: URI leader = URI.create(event.readPayload()); announceNodeCloudSize(event.getIp(), event.getPort(), leader.getHost(), leader.getPort(), targetCloudSize()); break; } return type.isFatal(); } private void maybeLogException(Exception e) { if (cloudingInProgress() && isOpen()) { // simply ignore any exceptions that happen post-clouding e.printStackTrace(); } } } /** * Start a long-running thread ready to handle Mapper->Driver messages. */ class CallbackManager extends CloudingManager { private volatile ServerSocket _ss; // Nodes and socks private final HashMap<String, Integer> _dupChecker = new HashMap<>(); final ArrayList<String> _nodes = new ArrayList<>(); final ArrayList<Socket> _socks = new ArrayList<>(); CallbackManager(int targetCloudSize) { super(targetCloudSize); } void setMapperParameters(Configuration conf) { conf.set(h2omapper.H2O_CLOUDING_IMPL, NetworkBasedClouding.class.getName()); conf.set(h2omapper.H2O_DRIVER_IP_KEY, driverCallbackPublicIp); conf.set(h2omapper.H2O_DRIVER_PORT_KEY, Integer.toString(_ss.getLocalPort())); conf.setInt(h2omapper.H2O_CLOUD_SIZE_KEY, targetCloudSize()); } @Override public synchronized void start() { try { _ss = bindCallbackSocket(); int actualDriverCallbackPort = _ss.getLocalPort(); System.out.println("Using mapper->driver callback IP address and port: " + driverCallbackPublicIp + ":" + actualDriverCallbackPort + (!driverCallbackBindIp.equals(driverCallbackPublicIp) ? " (internal callback address: " + driverCallbackBindIp + ":" + actualDriverCallbackPort + ")" : "")); System.out.println("(You can override these with -driverif and -driverport/-driverportrange and/or specify external IP using -extdriverif.)"); } catch (IOException e) { throw new RuntimeException("Failed to start Callback Manager", e); } super.start(); } protected ServerSocket bindCallbackSocket() throws IOException { return h2odriver.bindCallbackSocket(); } @Override void close() throws Exception { ServerSocket ss = _ss; _ss = null; ss.close(); } void registerNode(String ip, int port, int attempt, Socket s) { synchronized (_dupChecker) { final String entry = ip + ":" + port; if (_dupChecker.containsKey(entry)) { int prevAttempt = _dupChecker.get(entry); if (prevAttempt == attempt) { // This is bad. fatalError("Duplicate node registered (" + entry + "), exiting"); } else if (prevAttempt > attempt) { // Suspicious, we are receiving attempts out-of-order, stick with the latest attempt. System.out.println("WARNING: Received out-of-order node registration attempt (" + entry + "): " + "#attempt=" + attempt + " (previous was #" + prevAttempt + ")."); } else { // prevAttempt < attempt _dupChecker.put(entry, attempt); int old = _nodes.indexOf(entry); if (old < 0) { fatalError("Inconsistency found: old node entry for a repeated register node attempt doesn't exist, entry: " + entry); } assert entry.equals(_nodes.get(old)); // inject a fresh socket _socks.set(old, s); } } else { announceNewNode(ip, port); _dupChecker.put(entry, attempt); _nodes.add(entry); _socks.add(s); } if (_nodes.size() != targetCloudSize()) { return; } System.out.println("Sending flatfiles to nodes..."); assert (_nodes.size() == targetCloudSize()); assert (_nodes.size() == _socks.size()); // Build the flatfile and send it to all nodes. String flatfile = ""; for (String val : _nodes) { flatfile += val; flatfile += "\n"; } for (int i = 0; i < _socks.size(); i++) { Socket nodeSock = _socks.get(i); DriverToMapperMessage msg = new DriverToMapperMessage(); msg.setMessageFetchFlatfileResponse(flatfile); try { System.out.println(" [Sending flatfile to node " + _nodes.get(i) + "]"); msg.write(nodeSock); nodeSock.close(); } catch (Exception e) { System.out.println("ERROR: Failed to write to H2O node " + _nodes.get(i)); System.out.println(e.toString()); if (e.getMessage() != null) { System.out.println(e.getMessage()); } e.printStackTrace(); System.exit(1); } } // only set if everything went fine setFlatfile(flatfile); } } @Override public void run() { while (true) { try { Socket s = _ss.accept(); CallbackHandlerThread t = new CallbackHandlerThread(); t.setSocket(s); t.setCallbackManager(this); t.start(); } catch (SocketException e) { if (getShutdownRequested()) { _ss = null; return; } else { System.out.println("Exception occurred in CallbackManager"); System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)")); e.printStackTrace(); } } catch (Exception e) { System.out.println("Exception occurred in CallbackManager"); System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)")); e.printStackTrace(); } } } } /** * Print usage and exit 1. */ static void usage() { System.err.printf( "\n" + "Usage: h2odriver\n" + " [generic Hadoop ToolRunner options]\n" + " -n | -nodes <number of H2O nodes (i.e. mappers) to create>\n" + " -mapperXmx <per mapper Java Xmx heap size>\n" + " [-h | -help]\n" + " [-jobname <name of job in jobtracker (defaults to: 'H2O_nnnnn')>]\n" + " (Note nnnnn is chosen randomly to produce a unique name)\n" + " [-principal <kerberos principal> -keytab <keytab path> [-run_as_user <impersonated hadoop username>] | -run_as_user <hadoop username>]\n" + " [-refreshHdfsTokens]\n" + " [-refreshS3ATokens]\n" + " [-hiveHost <hostname:port> -hivePrincipal <hive server kerberos principal>]\n" + " [-hiveJdbcUrlPattern <pattern for constructing hive jdbc url>]\n" + " [-refreshHiveTokens]\n" + " [-clouding_method <callbacks|filesystem (defaults: to 'callbacks')>]\n" + " [-driverif <ip address of mapper->driver callback interface>]\n" + " [-driverport <port of mapper->driver callback interface>]\n" + " [-driverportrange <range portX-portY of mapper->driver callback interface>; eg: 50000-55000]\n" + " [-extdriverif <external ip address of mapper->driver callback interface>]\n" + " [-clouding_dir <hdfs directory used to exchange node information in the clouding procedure>]\n" + " [-network <IPv4network1Specification>[,<IPv4network2Specification> ...]\n" + " [-timeout <seconds>]\n" + " [-disown]\n" + " [-notify <notification file name>]\n" + " [-flatfile <generated flatfile name>]\n" + " [-extramempercent <0 to 20>]\n" + " [-nthreads <maximum typical worker threads, i.e. cpus to use>]\n" + " [-context_path <context_path> the context path for jetty]\n" + " [-auto_recovery_dir <hdfs directory where to store recovery data>]\n" + " [-baseport <starting HTTP port for H2O nodes; default is 54321>]\n" + " [-flow_dir <server side directory or hdfs directory>]\n" + " [-ea]\n" + " [-verbose:gc]\n" + " [-XX:+PrintGCDetails]\n" + " [-XX:+PrintGCTimeStamps]\n" + " [-Xlog:gc=info]\n" + " [-license <license file name (local filesystem, not hdfs)>]\n" + " [-o | -output <hdfs output dir>]\n" + "\n" + "Notes:\n" + " o Each H2O node runs as a mapper.\n" + " o Only one mapper may be run per host.\n" + " o There are no combiners or reducers.\n" + " o Each H2O cluster should have a unique jobname.\n" + " o -mapperXmx and -nodes are required.\n" + "\n" + " o -mapperXmx is set to both Xms and Xmx of the mapper to reserve\n" + " memory up front.\n" + " o -extramempercent is a percentage of mapperXmx. (Default: " + DEFAULT_EXTRA_MEM_PERCENT + ")\n" + " Extra memory for internal JVM use outside of Java heap.\n" + " mapreduce.map.memory.mb = mapperXmx * (1 + extramempercent/100)\n" + " o -libjars with an h2o.jar is required.\n" + " o -driverif and -driverport/-driverportrange let the user optionally\n" + " specify the network interface and port/port range (on the driver host)\n" + " for callback messages from the mapper to the driver. These parameters are\n" + " only used when clouding_method is set to `filesystem`.\n" + " o -extdriverif lets the user optionally specify external (=not present on the host)\n" + " IP address to be used for callback messages from mappers to the driver. This can be\n" + " used when driver is running in an isolated environment (eg. Docker container)\n" + " and communication to the driver port is forwarded from outside of the host/container.\n" + " Should be used in conjunction with -driverport option.\n" + " o -network allows the user to specify a list of networks that the\n" + " H2O nodes can bind to. Use this if you have multiple network\n" + " interfaces on the hosts in your Hadoop cluster and you want to\n" + " force H2O to use a specific one.\n" + " (Example network specification: '10.1.2.0/24' allows 256 legal\n" + " possibilities.)\n" + " o -timeout specifies how many seconds to wait for the H2O cluster\n" + " to come up before giving up. (Default: " + DEFAULT_CLOUD_FORMATION_TIMEOUT_SECONDS + " seconds\n" + " o -disown causes the driver to exit as soon as the cloud forms.\n" + " Otherwise, Ctrl-C of the driver kills the Hadoop Job.\n" + " o -notify specifies a file to write when the cluster is up.\n" + " The file contains one line with the IP and port of the embedded\n" + " web server for one of the H2O nodes in the cluster. e.g.\n" + " 192.168.1.100:54321\n" + " o Flags [-verbose:gc], [-XX:+PrintGCDetails] and [-XX:+PrintGCTimeStamps]\n" + " are deperacated in Java 9 and removed in Java 10.\n" + " The option [-Xlog:gc=info] replaces these flags since Java 9.\n" + " o All mappers must start before the H2O cloud is considered up.\n" + "\n" + "Examples:\n" + " hadoop jar h2odriver.jar -nodes 1 -mapperXmx 6g\n" + " hadoop jar h2odriver.jar -nodes 1 -mapperXmx 6g -notify notify.txt -disown\n" + "\n" + "Exit value:\n" + " 0 means the cluster exited successfully with an orderly Shutdown.\n" + " (From the Web UI or the REST API.)\n" + "\n" + " non-zero means the cluster exited with a failure.\n" + " (Note that Ctrl-C is treated as a failure.)\n" + "\n" ); System.exit(1); } /** * Print an error message, print usage, and exit 1. * @param s Error message */ static void error(String s) { System.err.printf("\nERROR: " + "%s\n\n", s); usage(); } /** * Print a warning message. * @param s Warning message */ static void warning(String s) { System.err.printf("\nWARNING: " + "%s\n\n", s); } /** * Read a file into a string. * @param fileName File to read. * @return Byte contents of file. */ static private byte[] readBinaryFile(String fileName) throws IOException { ByteArrayOutputStream ous = null; InputStream ios = null; try { byte[] buffer = new byte[4096]; ous = new ByteArrayOutputStream(); ios = new FileInputStream(new File(fileName)); int read; while ((read = ios.read(buffer)) != -1) { ous.write(buffer, 0, read); } } finally { try { if (ous != null) ous.close(); } catch (IOException ignore) {} try { if (ios != null) ios.close(); } catch (IOException ignore) {} } return ous.toByteArray(); } /** * Parse remaining arguments after the ToolRunner args have already been removed. * @param args Argument list */ private String[] parseArgs(String[] args) { int i = 0; boolean driverArgs = true; while (driverArgs) { if (i >= args.length) { break; } String s = args[i]; if (s.equals("-h") || s.equals("help") || s.equals("-help") || s.equals("--help")) { usage(); } else if (s.equals("-n") || s.equals("-nodes")) { i++; if (i >= args.length) { usage(); } numNodes = Integer.parseInt(args[i]); } else if (s.equals("-o") || s.equals("-output")) { i++; if (i >= args.length) { usage(); } outputPath = args[i]; } else if (s.equals("-jobname")) { i++; if (i >= args.length) { usage(); } jobtrackerName = args[i]; } else if (s.equals("-mapperXmx")) { i++; if (i >= args.length) { usage(); } mapperXmx = args[i]; } else if (s.equals("-extramempercent")) { i++; if (i >= args.length) { usage(); } extraMemPercent = Integer.parseInt(args[i]); } else if (s.equals("-mapperPermSize")) { i++; if (i >= args.length) { usage(); } mapperPermSize = args[i]; } else if (s.equals("-extdriverif")) { i++; if (i >= args.length) { usage(); } driverCallbackPublicIp = args[i]; } else if (s.equals("-driverif")) { i++; if (i >= args.length) { usage(); } driverCallbackBindIp = args[i]; } else if (s.equals("-driverport")) { i++; if (i >= args.length) { usage(); } driverCallbackPort = Integer.parseInt(args[i]); } else if (s.equals("-driverportrange")) { i++; if (i >= args.length) { usage(); } driverCallbackPortRange = PortRange.parse(args[i]); } else if (s.equals("-network")) { i++; if (i >= args.length) { usage(); } network = args[i]; } else if (s.equals("-timeout")) { i++; if (i >= args.length) { usage(); } cloudFormationTimeoutSeconds = Integer.parseInt(args[i]); } else if (s.equals("-disown")) { disown = true; } else if (s.equals("-notify")) { i++; if (i >= args.length) { usage(); } clusterReadyFileName = args[i]; } else if (s.equals("-flatfile")) { i++; if (i >= args.length) { usage(); } clusterFlatfileName = args[i]; } else if (s.equals("-nthreads")) { i++; if (i >= args.length) { usage(); } nthreads = Integer.parseInt(args[i]); } else if (s.equals("-context_path")) { i++; if (i >= args.length) { usage(); } contextPath = args[i]; } else if (s.equals("-baseport")) { i++; if (i >= args.length) { usage(); } basePort = Integer.parseInt(args[i]); if ((basePort < 0) || (basePort > 65535)) { error("Base port must be between 1 and 65535"); } } else if (s.equals("-port_offset")) { i++; if (i >= args.length) { usage(); } portOffset = Integer.parseInt(args[i]); if ((portOffset <= 0) || (portOffset > 65534)) { error("Port offset must be between 1 and 65534"); } } else if (s.equals("-beta")) { beta = true; } else if (s.equals("-random_udp_drop")) { enableRandomUdpDrop = true; } else if (s.equals("-ea")) { enableExceptions = true; } else if (s.equals("-verbose:gc") || s.equals("-Xlog:gc=info")) { enableVerboseGC = true; } else if (s.equals("-verbose:class")) { enableVerboseClass = true; } else if (s.equals("-XX:+PrintCompilation")) { enablePrintCompilation = true; } else if (s.equals("-exclude")) { enableExcludeMethods = true; } else if (s.equals("-Dlog4j.defaultInitOverride=true")) { enableLog4jDefaultInitOverride = true; } else if (s.equals("-log_level")) { i++; if (i >= args.length) { usage(); } logLevel = args[i]; } else if (s.equals("-debug")) { enableDebug = true; } else if (s.equals("-suspend")) { enableSuspend = true; } else if (s.equals("-debugport")) { i++; if (i >= args.length) { usage(); } debugPort = Integer.parseInt(args[i]); if ((debugPort < 0) || (debugPort > 65535)) { error("Debug port must be between 1 and 65535"); } } else if (s.equals("-XX:+PrintGCDetails")) { if (!JAVA_VERSION.useUnifiedLogging()) { enablePrintGCDetails = true; } else { error("Parameter -XX:+PrintGCDetails is unusable, running on JVM with deprecated GC debugging flags."); } } else if (s.equals("-XX:+PrintGCTimeStamps")) { if (!JAVA_VERSION.useUnifiedLogging()) { enablePrintGCDetails = true; } else { error("Parameter -XX:+PrintGCTimeStamps is unusable, running on JVM with deprecated GC debugging flags."); } } else if (s.equals("-gc")) { enableVerboseGC = true; enablePrintGCDetails = !JAVA_VERSION.useUnifiedLogging(); enablePrintGCTimeStamps = !JAVA_VERSION.useUnifiedLogging(); } else if (s.equals("-nogc")) { enableVerboseGC = false; enablePrintGCDetails = false; enablePrintGCTimeStamps = false; } else if (s.equals("-flow_dir")) { i++; if (i >= args.length) { usage(); } flowDir = args[i]; } else if (s.equals("-J")) { i++; if (i >= args.length) { usage(); } extraArguments.add(args[i]); } else if (s.equals("-JJ")) { i++; if (i >= args.length) { usage(); } extraJvmArguments.add(args[i]); } else if (s.equals("-jks")) { i++; if (i >= args.length) { usage(); } jksFileName = args[i]; } else if (s.equals("-jks_pass")) { i++; if (i >= args.length) { usage(); } jksPass = args[i]; } else if (s.equals("-jks_alias")) { i++; if (i >= args.length) { usage(); } jksAlias = args[i]; } else if (s.equals("-hostname_as_jks_alias")) { hostnameAsJksAlias = true; } else if (s.equals("-internal_secure_connections")) { internal_secure_connections = true; } else if (s.equals("-internal_security_conf") || s.equals("-internal_security")) { if(s.equals("-internal_security")){ System.out.println("The '-internal_security' configuration is deprecated. " + "Please use '-internal_security_conf' instead."); } i++; if (i >= args.length) { usage(); } securityConf = args[i]; } else if (s.equals("-allow_insecure_xgboost")) { allow_insecure_xgboost = true; } else if (s.equals("-use_external_xgboost")) { use_external_xgboost = true; } else if (s.equals("-hash_login")) { hashLogin = true; } else if (s.equals("-ldap_login")) { ldapLogin = true; } else if (s.equals("-kerberos_login")) { kerberosLogin = true; } else if (s.equals("-spnego_login")) { spnegoLogin = true; } else if (s.equals("-spnego_properties")) { i++; if (i >= args.length) { usage(); } spnegoProperties = args[i]; } else if (s.equals("-pam_login")) { pamLogin = true; } else if (s.equals("-login_conf")) { i++; if (i >= args.length) { usage(); } loginConfFileName = args[i]; } else if (s.equals("-form_auth")) { formAuth = true; } else if (s.equals("-disable_flow")) { disableFlow = true; } else if (s.equals("-sw_ext_backend")) { swExtBackend = true; } else if (s.equals("-configure_s3_using_s3a")) { configureS3UsingS3A = true; } else if (s.equals("-session_timeout")) { i++; if (i >= args.length) { usage(); } sessionTimeout = args[i]; } else if (s.equals("-user_name")) { i++; if (i >= args.length) { usage(); } userName = args[i]; } else if (s.equals("-client")) { client = true; driverArgs = false; } else if (s.equals("-proxy")) { proxy = true; driverArgs = false; } else if (s.equals("-run_as_user")) { i++; if (i >= args.length) { usage(); } runAsUser = args[i]; } else if (s.equals("-principal")) { i++; if (i >= args.length) { usage(); } principal = args[i]; } else if (s.equals("-keytab")) { i++; if (i >= args.length) { usage (); } keytabPath = args[i]; } else if (s.equals("-report_hostname")) { reportHostname = true; } else if (s.equals("-driver_debug")) { driverDebug = true; } else if (s.equals("-hiveJdbcUrlPattern")) { i++; if (i >= args.length) { usage (); } hiveJdbcUrlPattern = args[i]; } else if (s.equals("-hiveHost")) { i++; if (i >= args.length) { usage (); } hiveHost = args[i]; } else if (s.equals("-hivePrincipal")) { i++; if (i >= args.length) { usage (); } hivePrincipal = args[i]; } else if (s.equals("-refreshTokens") || // for backwards compatibility s.equals("-refreshHiveTokens")) { refreshHiveTokens = true; } else if (s.equals("-hiveToken")) { i++; if (i >= args.length) { usage (); } hiveToken = args[i]; } else if (s.equals("-refreshHdfsTokens")) { refreshHdfsTokens = true; } else if (s.equals("-refreshS3ATokens")) { refreshS3ATokens = true; } else if (s.equals("-clouding_method")) { i++; if (i >= args.length) { usage(); } cloudingMethod = CloudingMethod.valueOf(args[i].toUpperCase()); } else if (s.equals("-clouding_dir")) { i++; if (i >= args.length) { usage(); } cloudingDir = args[i]; } else if (s.equals("-auto_recovery_dir")) { i++; if (i >= args.length) { usage(); } autoRecoveryDir = args[i]; } else { error("Unrecognized option " + s); } i++; } String[] otherArgs = new String[Math.max(args.length - i, 0)]; for (int j = 0; j < otherArgs.length; j++) otherArgs[j] = args[i++]; return otherArgs; } private void validateArgs() { // Check for mandatory arguments. if (numNodes < 1) { error("Number of H2O nodes must be greater than 0 (must specify -n)"); } if (mapperXmx == null) { error("Missing required option -mapperXmx"); } // Check for sane arguments. if (! mapperXmx.matches("[1-9][0-9]*[mgMG]")) { error("-mapperXmx invalid (try something like -mapperXmx 4g)"); } if (mapperPermSize != null) { if (!mapperPermSize.matches("[1-9][0-9]*[mgMG]")) { error("-mapperPermSize invalid (try something like -mapperPermSize 512m)"); } } if (extraMemPercent < 0) { extraMemPercent = DEFAULT_EXTRA_MEM_PERCENT; } if (jobtrackerName == null) { Random rng = new Random(); int num = rng.nextInt(99999); jobtrackerName = "H2O_" + num; } if (network == null) { network = ""; } else { String[] networks; if (network.contains(",")) { networks = network.split(","); } else { networks = new String[1]; networks[0] = network; } for (String n : networks) { Pattern p = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)/(\\d+)"); Matcher m = p.matcher(n); boolean b = m.matches(); if (! b) { error("network invalid: " + n); } for (int k = 1; k <=4; k++) { int o = Integer.parseInt(m.group(k)); if ((o < 0) || (o > 255)) { error("network invalid: " + n); } int bits = Integer.parseInt(m.group(5)); if ((bits < 0) || (bits > 32)) { error("network invalid: " + n); } } } } if (network == null) { error("Internal error, network should not be null at this point"); } if ((nthreads >= 0) && (nthreads < 4)) { error("nthreads invalid (must be >= 4): " + nthreads); } if ((driverCallbackPort != 0) && (driverCallbackPortRange != null)) { error("cannot specify both -driverport and -driverportrange (remove one of these options)"); } if (driverCallbackPortRange != null) driverCallbackPortRange.validate(); if (sessionTimeout != null) { if (! formAuth) { error("session timeout can only be enabled for Form-based authentication (use the '-form_auth' option)"); } int timeout = 0; try { timeout = Integer.parseInt(sessionTimeout); } catch (Exception e) { /* ignored */ } if (timeout <= 0) { error("invalid session timeout specification (" + sessionTimeout + ")"); } } ImpersonationUtils.validateImpersonationArgs( principal, keytabPath, runAsUser, h2odriver::error, h2odriver::warning ); if (hivePrincipal != null && hiveHost == null && hiveJdbcUrlPattern == null) { error("delegation token generator requires Hive host to be set (use the '-hiveHost' or '-hiveJdbcUrlPattern' option)"); } if (refreshHiveTokens && hivePrincipal == null) { error("delegation token refresh requires Hive principal to be set (use the '-hivePrincipal' option)"); } if (client && disown) { error("client mode doesn't support the '-disown' option"); } if (proxy && disown) { error("proxy mode doesn't support the '-disown' option"); } if (jksAlias != null && hostnameAsJksAlias) { error("options -jks_alias and -hostname_as_jks_alias are mutually exclusive, specify only one of them"); } } private static String calcMyIp(String externalIp) throws Exception { Enumeration nis = NetworkInterface.getNetworkInterfaces(); System.out.println("Determining driver " + (externalIp != null ? "(internal) " : "") + "host interface for mapper->driver callback..."); while (nis.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) nis.nextElement(); Enumeration ias = ni.getInetAddresses(); while (ias.hasMoreElements()) { InetAddress ia = (InetAddress) ias.nextElement(); String s = ia.getHostAddress(); System.out.println(" [Possible callback IP address: " + s + (externalIp != null ? "; external IP specified: " + externalIp : "") + "]"); } } InetAddress ia = InetAddress.getLocalHost(); return ia.getHostAddress(); } private final int CLUSTER_ERROR_JOB_COMPLETED_TOO_EARLY = 5; private final int CLUSTER_ERROR_TIMEOUT = 3; private int waitForClusterToComeUp() throws Exception { final long startMillis = System.currentTimeMillis(); while (true) { DBG("clusterFailedToComeUp=", clusterFailedToComeUp, ";clusterIsUp=", clusterIsUp); if (clusterFailedToComeUp) { System.out.println("ERROR: At least one node failed to come up during cluster formation"); killJobAndWait(job); return 4; } DBG("Checking if the job already completed"); if (job.isComplete()) { return CLUSTER_ERROR_JOB_COMPLETED_TOO_EARLY; } if (clusterIsUp) { break; } long nowMillis = System.currentTimeMillis(); long deltaMillis = nowMillis - startMillis; DBG("Cluster is not yet up, waiting for ", deltaMillis, "ms."); if (cloudFormationTimeoutSeconds > 0) { if (deltaMillis > (cloudFormationTimeoutSeconds * 1000)) { System.out.println("ERROR: Timed out waiting for H2O cluster to come up (" + cloudFormationTimeoutSeconds + " seconds)"); System.out.println("ERROR: (Try specifying the -timeout option to increase the waiting time limit)"); if (clusterHasNodeWithLocalhostIp) { System.out.println(); System.out.println("NOTE: One of the nodes chose 127.0.0.1 as its IP address, which is probably wrong."); System.out.println("NOTE: You may want to specify the -network option, which lets you specify the network interface the mappers bind to."); System.out.println("NOTE: Typical usage is: -network a.b.c.d/24"); } killJobAndWait(job); return CLUSTER_ERROR_TIMEOUT; } } final int ONE_SECOND_MILLIS = 1000; Thread.sleep (ONE_SECOND_MILLIS); } return 0; } private void waitForClusterToShutdown() throws Exception { while (! job.isComplete()) { final int ONE_SECOND_MILLIS = 1000; Thread.sleep (ONE_SECOND_MILLIS); } } /* * Clean up driver-side resources after the hadoop job has finished. * * This method was added so that it can be called from inside * Spring Hadoop and the driver can be created and then deleted from inside * a single process. */ private void cleanUpDriverResources() { ctrlc.setComplete(); try { Runtime.getRuntime().removeShutdownHook(ctrlc); } catch (IllegalStateException ignore) { // If "Shutdown in progress" exception would be thrown, just ignore and don't bother to remove the hook. } ctrlc = null; try { setShutdownRequested(); CloudingManager cloudingManager = cm; cm = null; if (cloudingManager != null) { cloudingManager.close(); } } catch (Exception e) { System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)")); e.printStackTrace(); } try { if (! job.isComplete()) { System.out.println("ERROR: Job not complete after cleanUpDriverResources()"); } } catch (Exception e) { System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)")); e.printStackTrace(); } // At this point, resources are released. // The hadoop job has completed (job.isComplete() is true), // so the cluster memory and cpus are freed. // The driverCallbackSocket has been closed so a new one can be made. // The callbackManager itself may or may not have finished, but it doesn't // matter since the server socket has been closed. } private String calcHadoopVersion() { try { Process p = new ProcessBuilder("hadoop", "version").start(); p.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = br.readLine(); if (line == null) { line = "(unknown)"; } return line; } catch (Exception e) { return "(unknown)"; } } private int mapperArgsLength = 0; private int mapperConfLength = 0; private void addMapperArg(Configuration conf, String name) { conf.set(h2omapper.H2O_MAPPER_ARGS_BASE + mapperArgsLength, name); mapperArgsLength++; } private void addMapperArg(Configuration conf, String name, String value) { addMapperArg(conf, name); addMapperArg(conf, value); } private void addMapperConf(Configuration conf, String name, String value, String payloadFileName) { try { byte[] payloadData = readBinaryFile(payloadFileName); addMapperConf(conf, name, value, payloadData); } catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.append("Failed to read config file (").append(payloadFileName).append(")"); if (e.getLocalizedMessage() != null) { sb.append(": "); sb.append(e.getLocalizedMessage()); } error(sb.toString()); } } private void addMapperConf(Configuration conf, String name, String value, byte[] payloadData) { String payload = BinaryFileTransfer.convertByteArrToString(payloadData); conf.set(h2omapper.H2O_MAPPER_CONF_ARG_BASE + mapperConfLength, name); conf.set(h2omapper.H2O_MAPPER_CONF_BASENAME_BASE + mapperConfLength, value); conf.set(h2omapper.H2O_MAPPER_CONF_PAYLOAD_BASE + mapperConfLength, payload); mapperConfLength++; } private static ServerSocket bindCallbackSocket() throws IOException { Exception ex = null; int permissionExceptionCount = 0; // try to detect likely unintended range specifications // eg.: running with non-root user & setting range 100-1100 (the effective range would be 1024-1100 = not what user wanted) ServerSocket result = null; for (int p = driverCallbackPortRange.from; (result == null) && (p <= driverCallbackPortRange.to); p++) { ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); InetSocketAddress sa = new InetSocketAddress(driverCallbackBindIp, p); try { int backlog = Math.max(50, numNodes * 3); // minimum 50 (bind's default) or numNodes * 3 (safety constant, arbitrary) ss.bind(sa, backlog); result = ss; } catch (BindException e) { if ("Permission denied".equals(e.getMessage())) permissionExceptionCount++; ex = e; } catch (SecurityException e) { permissionExceptionCount++; ex = e; } catch (IOException | RuntimeException e) { ex = e; } } if ((permissionExceptionCount > 0) && (! driverCallbackPortRange.isSinglePort())) warning("Some ports (count=" + permissionExceptionCount + ") of the specified port range are not available" + " due to process restrictions (range: " + driverCallbackPortRange + ")."); if (result == null) if (ex instanceof IOException) throw (IOException) ex; else { assert ex != null; throw (RuntimeException) ex; } return result; } private int run2(String[] args) throws Exception { // Arguments that get their default value set based on runtime info. // ----------------------------------------------------------------- // PermSize // Java 7 and below need a larger PermSize for H2O. // Java 8 no longer has PermSize, but rather MetaSpace, which does not need to be set at all. if (JAVA_VERSION.getMajor() <= 7) { mapperPermSize = "256m"; } // Parse arguments. // ---------------- args = ArrayUtils.append(args, getSystemArgs()); // append "system-level" args to user specified args String[] otherArgs = parseArgs(args); validateArgs(); // Set up configuration. // --------------------- Configuration conf = getConf(); ImpersonationUtils.impersonate(conf, principal, keytabPath, runAsUser); if (cloudingMethod == CloudingMethod.FILESYSTEM) { if (cloudingDir == null) { cloudingDir = new Path(outputPath, ".clouding").toString(); } cm = new FileSystemEventManager(numNodes, conf, cloudingDir); } else { // Set up callback address and port. // --------------------------------- if (driverCallbackBindIp == null) { driverCallbackBindIp = calcMyIp(driverCallbackPublicIp); } if (driverCallbackPublicIp == null) { driverCallbackPublicIp = driverCallbackBindIp; } if (driverCallbackPortRange == null) { driverCallbackPortRange = new PortRange(driverCallbackPort, driverCallbackPort); } cm = new CallbackManager(numNodes); } cm.start(); // Set memory parameters. long processTotalPhysicalMemoryMegabytes; { Pattern p = Pattern.compile("([1-9][0-9]*)([mgMG])"); Matcher m = p.matcher(mapperXmx); boolean b = m.matches(); if (!b) { System.out.println("(Could not parse mapperXmx."); System.out.println("INTERNAL FAILURE. PLEASE CONTACT TECHNICAL SUPPORT."); System.exit(1); } assert (m.groupCount() == 2); String number = m.group(1); String units = m.group(2); long megabytes = Long.parseLong(number); if (units.equals("g") || units.equals("G")) { megabytes = megabytes * 1024; } // YARN container must be sized greater than Xmx. // YARN will kill the application if the RSS of the process is larger than // mapreduce.map.memory.mb. long jvmInternalMemoryMegabytes = (long) ((double) megabytes * ((double) extraMemPercent) / 100.0); processTotalPhysicalMemoryMegabytes = megabytes + jvmInternalMemoryMegabytes; conf.set("mapreduce.job.ubertask.enable", "false"); String mapreduceMapMemoryMb = Long.toString(processTotalPhysicalMemoryMegabytes); conf.set("mapreduce.map.memory.mb", mapreduceMapMemoryMb); // MRv1 standard options, but also required for YARN. StringBuilder sb = new StringBuilder() .append("-Xms").append(mapperXmx) .append(" -Xmx").append(mapperXmx) .append(((mapperPermSize != null) && (mapperPermSize.length() > 0)) ? (" -XX:PermSize=" + mapperPermSize) : "") .append((enableExceptions ? " -ea" : "")) .append((enableVerboseGC ? " " + JAVA_VERSION.getVerboseGCFlag() : "")) .append((enablePrintGCDetails ? " -XX:+PrintGCDetails" : "")) .append((enablePrintGCTimeStamps ? " -XX:+PrintGCTimeStamps" : "")) .append((enableVerboseClass ? " -verbose:class" : "")) .append((enablePrintCompilation ? " -XX:+PrintCompilation" : "")) .append((enableExcludeMethods ? " -XX:CompileCommand=exclude,water/fvec/NewChunk.append2slowd" : "")) .append((enableLog4jDefaultInitOverride ? " -Dlog4j.defaultInitOverride=true" : "")) .append((enableDebug ? " -agentlib:jdwp=transport=dt_socket,server=y,suspend=" + (enableSuspend ? "y" : "n") + ",address=" + debugPort : "")); for (String s : extraJvmArguments) { sb.append(" ").append(s); } String mapChildJavaOpts = sb.toString(); conf.set("mapreduce.map.java.opts", mapChildJavaOpts); if (!usingYarn()) { conf.set("mapred.child.java.opts", mapChildJavaOpts); conf.set("mapred.map.child.java.opts", mapChildJavaOpts); // MapR 2.x requires this. } System.out.println("Memory Settings:"); System.out.println(" mapreduce.map.java.opts: " + mapChildJavaOpts); System.out.println(" Extra memory percent: " + extraMemPercent); System.out.println(" mapreduce.map.memory.mb: " + mapreduceMapMemoryMb); } conf.set("mapreduce.client.genericoptionsparser.used", "true"); if (!usingYarn()) { conf.set("mapred.used.genericoptionsparser", "true"); } conf.set("mapreduce.map.speculative", "false"); if (!usingYarn()) { conf.set("mapred.map.tasks.speculative.execution", "false"); } conf.set("mapreduce.map.maxattempts", "1"); if (!usingYarn()) { conf.set("mapred.map.max.attempts", "1"); } conf.set("mapreduce.job.jvm.numtasks", "1"); if (!usingYarn()) { conf.set("mapred.job.reuse.jvm.num.tasks", "1"); } cm.setMapperParameters(conf); // Arguments. addMapperArg(conf, "-name", jobtrackerName); if (network.length() > 0) { addMapperArg(conf, "-network", network); } if (nthreads >= 0) { addMapperArg(conf, "-nthreads", Integer.toString(nthreads)); } if (contextPath != null) { addMapperArg(conf, "-context_path", contextPath); } if (basePort >= 0) { addMapperArg(conf, "-baseport", Integer.toString(basePort)); } if (portOffset >= 1) { addMapperArg(conf, "-port_offset", Integer.toString(portOffset)); } if (beta) { addMapperArg(conf, "-beta"); } if (enableRandomUdpDrop) { addMapperArg(conf, "-random_udp_drop"); } if (flowDir != null) { addMapperArg(conf, "-flow_dir", flowDir); } if (logLevel != null) { addMapperArg(conf, "-log_level", logLevel); } if ((new File(".h2o_no_collect")).exists() || (new File(System.getProperty("user.home") + "/.h2o_no_collect")).exists()) { addMapperArg(conf, "-ga_opt_out"); } String hadoopVersion = calcHadoopVersion(); addMapperArg(conf, "-ga_hadoop_ver", hadoopVersion); if (configureS3UsingS3A) { addMapperArg(conf, "-configure_s3_using_s3a"); } if (jksPass != null) { addMapperArg(conf, "-jks_pass", jksPass); } if (hostnameAsJksAlias) { addMapperArg(conf, "-hostname_as_jks_alias"); } else if (jksAlias != null) { addMapperArg(conf, "-jks_alias", jksAlias); } if (hashLogin) { addMapperArg(conf, "-hash_login"); } if (ldapLogin) { addMapperArg(conf, "-ldap_login"); } if (kerberosLogin) { addMapperArg(conf, "-kerberos_login"); } if (spnegoLogin) { addMapperArg(conf, "-spnego_login"); } if (pamLogin) { addMapperArg(conf, "-pam_login"); } if (formAuth) { addMapperArg(conf, "-form_auth"); } if (sessionTimeout != null) { addMapperArg(conf, "-session_timeout", sessionTimeout); } if (disableFlow) { addMapperArg(conf, "-disable_flow"); } if (autoRecoveryDir != null) { addMapperArg(conf, "-auto_recovery_dir", autoRecoveryDir); } if (swExtBackend) { addMapperArg(conf, "-allow_clients"); } addMapperArg(conf, "-user_name", userName); for (String s : extraArguments) { addMapperArg(conf, s); } if (client) { addMapperArg(conf, "-md5skip"); addMapperArg(conf, "-disable_web"); addMapperArg(conf, "-allow_clients"); } // Proxy final Credentials proxyCredentials = proxy ? make(userName) : null; final String hashFileEntry = proxyCredentials != null ? proxyCredentials.toHashFileEntry() : null; // HttpServerLoader.INSTANCE.getHashFileEntry() if (hashFileEntry != null) { final byte[] hashFileData = StringUtils.bytesOf(hashFileEntry); addMapperArg(conf, "-hash_login"); addMapperConf(conf, "-login_conf", "login.conf", hashFileData); } if (allow_insecure_xgboost) { addMapperArg(conf, "-allow_insecure_xgboost"); } if (use_external_xgboost) { addMapperArg(conf, "-use_external_xgboost"); } conf.set(h2omapper.H2O_MAPPER_ARGS_LENGTH, Integer.toString(mapperArgsLength)); // Config files. if (jksFileName != null) { addMapperConf(conf, "-jks", "h2o.jks", jksFileName); } if (loginConfFileName != null) { addMapperConf(conf, "-login_conf", "login.conf", loginConfFileName); } else if (kerberosLogin) { // Use default Kerberos configuration file final byte[] krbConfData = StringUtils.bytesOf( "krb5loginmodule {\n" + " com.sun.security.auth.module.Krb5LoginModule required;\n" + "};" ); addMapperConf(conf, "-login_conf", "login.conf", krbConfData); } else if (pamLogin) { // Use default PAM configuration file final byte[] pamConfData = StringUtils.bytesOf( "pamloginmodule {\n" + " de.codedo.jaas.PamLoginModule required\n" + " service = h2o;\n" + "};" ); addMapperConf(conf, "-login_conf", "login.conf", pamConfData); } if (spnegoLogin && spnegoProperties != null) { addMapperConf(conf, "-spnego_properties", "spnego.properties", spnegoProperties); } // SSL if (null != securityConf && !securityConf.isEmpty()) { addMapperConf(conf, "-internal_security_conf", "security.config", securityConf); } else if(internal_secure_connections) { SecurityUtils.SSLCredentials credentials = SecurityUtils.generateSSLPair(); securityConf = SecurityUtils.generateSSLConfig(credentials); addMapperConf(conf, "", credentials.jks.name, credentials.jks.getLocation()); addMapperConf(conf, "-internal_security_conf", "default-security.config", securityConf); } conf.set(h2omapper.H2O_MAPPER_CONF_LENGTH, Integer.toString(mapperConfLength)); // Run job. We are running a zero combiner and zero reducer configuration. // ------------------------------------------------------------------------ job = submitJob(conf); System.out.println("Job name '" + jobtrackerName + "' submitted"); System.out.println("JobTracker job ID is '" + job.getJobID() + "'"); hadoopJobId = job.getJobID(); applicationId = hadoopJobId.replace("job_", "application_"); maybePrintYarnLogsMessage(false); // Register ctrl-c handler to try to clean up job when possible. ctrlc = new CtrlCHandler(); Runtime.getRuntime().addShutdownHook(ctrlc); System.out.println("Waiting for H2O cluster to come up..."); int rv = waitForClusterToComeUp(); if ((rv == CLUSTER_ERROR_TIMEOUT) || (rv == CLUSTER_ERROR_JOB_COMPLETED_TOO_EARLY)) { // Try to print YARN diagnostics. try { // Wait a short time before trying to print diagnostics. // Try to give the Resource Manager time to clear out this job itself from it's state. Thread.sleep(3000); Class clazz = Class.forName("water.hadoop.H2OYarnDiagnostic"); if (clazz != null) { @SuppressWarnings("all") Method method = clazz.getMethod("diagnose", String.class, String.class, int.class, int.class, int.class); String queueName; queueName = conf.get("mapreduce.job.queuename"); if (queueName == null) { queueName = conf.get("mapred.job.queue.name"); } if (queueName == null) { queueName = "default"; } method.invoke(null, applicationId, queueName, numNodes, (int)processTotalPhysicalMemoryMegabytes, numNodesStarted.get()); } return rv; } catch (Exception e) { if (System.getenv("H2O_DEBUG_HADOOP") != null) { System.out.println(); e.printStackTrace(); System.out.println(); } } System.out.println("ERROR: H2O cluster failed to come up"); return rv; } else if (rv != 0) { System.out.println("ERROR: H2O cluster failed to come up"); return rv; } if (job.isComplete()) { System.out.println("ERROR: H2O cluster failed to come up"); return 2; } System.out.printf("H2O cluster (%d nodes) is up\n", numNodes); if (disown) { // Do a short sleep here just to make sure all of the cloud // status stuff in H2O has settled down. Thread.sleep(CLOUD_FORMATION_SETTLE_DOWN_SECONDS); System.out.println("Open H2O Flow in your web browser: " + getPublicUrl()); System.out.println("Disowning cluster and exiting."); Runtime.getRuntime().removeShutdownHook(ctrlc); return 0; } if (client) { if (flatfileContent == null) throw new IllegalStateException("ERROR: flatfile should have been created by now."); final File flatfile = File.createTempFile("h2o", "txt"); flatfile.deleteOnExit(); try (Writer w = new BufferedWriter(new FileWriter(flatfile))) { w.write(flatfileContent); w.close(); } catch (IOException e) { System.out.println("ERROR: Failed to write flatfile."); e.printStackTrace(); System.exit(1); } String[] generatedClientArgs = new String[]{ "-client", "-flatfile", flatfile.getAbsolutePath(), "-md5skip", "-user_name", userName, "-name", jobtrackerName }; if (securityConf != null) generatedClientArgs = ArrayUtils.append(generatedClientArgs, new String[]{"-internal_security_conf", securityConf}); generatedClientArgs = ArrayUtils.append(generatedClientArgs, otherArgs); H2OStarter.start(generatedClientArgs, true); reportClientReady(H2O.SELF_ADDRESS.getHostAddress(), H2O.API_PORT); } if (proxy) { proxyUrl = ProxyStarter.start(otherArgs, proxyCredentials, getClusterUrl(), reportHostname); reportProxyReady(proxyUrl); } if (! (client || proxy)) System.out.println("(Note: Use the -disown option to exit the driver after cluster formation)"); System.out.println(); System.out.println("Open H2O Flow in your web browser: " + getPublicUrl()); System.out.println(); System.out.println("(Press Ctrl-C to kill the cluster)"); System.out.println("Blocking until the H2O cluster shuts down..."); waitForClusterToShutdown(); cleanUpDriverResources(); boolean success = job.isSuccessful(); int exitStatus; exitStatus = success ? 0 : 1; System.out.println("Current time is " + new Date()); System.out.println((success ? "" : "ERROR: ") + "Job was" + (success ? " " : " not ") + "successful"); if (success) { System.out.println("Exiting with status 0"); } else { System.out.println("Exiting with nonzero exit status"); } return exitStatus; } private String[] getSystemArgs() { String[] args = new String[0]; String config = getConf().get(ARGS_CONFIG_PROP, DEFAULT_ARGS_CONFIG); File argsConfig = new File(String.format(ARGS_CONFIG_FILE_PATTERN, config)); if (! argsConfig.exists()) { File defaultArgsConfig = new File(String.format(ARGS_CONFIG_FILE_PATTERN, DEFAULT_ARGS_CONFIG)); if (defaultArgsConfig.exists()) { System.out.println("ERROR: There is no arguments file for configuration '" + config + "', however, " + "the arguments file exists for the default configuration.\n " + "Please create an arguments file also for configuration '" + config + "' and store it in '" + argsConfig.getAbsolutePath() + "' (the file can be empty)."); System.exit(1); } return args; } try (BufferedReader r = new BufferedReader(new FileReader(argsConfig))) { String arg; while ((arg = r.readLine()) != null) { args = ArrayUtils.append(args, arg.trim()); } } catch (IOException e) { e.printStackTrace(); System.out.println("ERROR: System level H2O arguments cannot be read from file " + argsConfig.getAbsolutePath() + "; " + (e.getMessage() != null ? e.getMessage() : "(null)")); System.exit(1); } return args; } private JobWrapper submitJob(Configuration conf) throws Exception { // Set up job stuff. // ----------------- final Job j = new Job(conf, jobtrackerName); j.setJarByClass(getClass()); j.setInputFormatClass(H2OInputFormat.class); j.setMapperClass(h2omapper.class); j.setNumReduceTasks(0); j.setOutputKeyClass(Text.class); j.setOutputValueClass(Text.class); boolean haveHiveToken; if (hiveToken != null) { System.out.println("Using pre-generated Hive delegation token."); HiveTokenGenerator.addHiveDelegationToken(j, hiveToken); haveHiveToken = true; } else { haveHiveToken = HiveTokenGenerator.addHiveDelegationTokenIfHivePresent(j, hiveJdbcUrlPattern, hiveHost, hivePrincipal); } if ((refreshHiveTokens && !haveHiveToken) || refreshHdfsTokens || refreshS3ATokens) { if (runAsUser != null) j.getConfiguration().set(H2O_AUTH_USER, runAsUser); if (principal != null) j.getConfiguration().set(H2O_AUTH_PRINCIPAL, principal); if (keytabPath != null) { byte[] payloadData = readBinaryFile(keytabPath); String payload = BinaryFileTransfer.convertByteArrToString(payloadData); j.getConfiguration().set(H2O_AUTH_KEYTAB, payload); } } if (refreshHiveTokens) { j.getConfiguration().setBoolean(H2O_HIVE_USE_KEYTAB, !haveHiveToken); if (hiveJdbcUrlPattern != null) j.getConfiguration().set(H2O_HIVE_JDBC_URL_PATTERN, hiveJdbcUrlPattern); if (hiveHost != null) j.getConfiguration().set(H2O_HIVE_HOST, hiveHost); if (hivePrincipal != null) j.getConfiguration().set(H2O_HIVE_PRINCIPAL, hivePrincipal); } j.getConfiguration().setBoolean(H2O_AUTH_TOKEN_REFRESHER_ENABLED, refreshHdfsTokens); j.getConfiguration().setBoolean(H2O_DYNAMIC_AUTH_S3A_TOKEN_REFRESHER_ENABLED, refreshS3ATokens); if (outputPath != null) FileOutputFormat.setOutputPath(j, new Path(outputPath)); else j.setOutputFormatClass(NullOutputFormat.class); DBG("Submitting job"); j.submit(); JobWrapper jw = JobWrapper.wrap(j); DBG("Job submitted, id=", jw.getJobID()); return jw; } /** * The run method called by ToolRunner. * @param args Arguments after ToolRunner arguments have been removed. * @return Exit value of program. */ @Override public int run(String[] args) { int rv = -1; try { rv = run2(args); } catch (org.apache.hadoop.mapred.FileAlreadyExistsException e) { if (ctrlc != null) { ctrlc.setComplete(); } System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)")); System.exit(1); } catch (Exception e) { System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)")); e.printStackTrace(); System.exit(1); } return rv; } private static abstract class JobWrapper { final String _jobId; final Job _job; JobWrapper(Job job) { _job = job; _jobId = _job.getJobID().toString(); } String getJobID() { return _jobId; } abstract boolean isComplete() throws IOException; abstract void killJob() throws IOException; abstract boolean isSuccessful() throws IOException; static JobWrapper wrap(Job job) { if (driverDebug) { int timeoutSeconds = job.getConfiguration().getInt(DRIVER_JOB_CALL_TIMEOUT_SEC, 10); DBG("Timeout for Hadoop calls set to ", timeoutSeconds, "s"); return new AsyncExecutingJobWrapper(job, timeoutSeconds); } else return new DelegatingJobWrapper(job); } } private static class DelegatingJobWrapper extends JobWrapper { DelegatingJobWrapper(Job job) { super(job); } @Override boolean isComplete() throws IOException { return _job.isComplete(); } @Override boolean isSuccessful() throws IOException { return _job.isSuccessful(); } @Override void killJob() throws IOException { _job.killJob(); } } private static class AsyncExecutingJobWrapper extends JobWrapper { private final ExecutorService _es; private final int _timeoutSeconds; AsyncExecutingJobWrapper(Job job, int timeoutSeconds) { super(job); _es = Executors.newCachedThreadPool(); _timeoutSeconds = timeoutSeconds; } @Override boolean isComplete() throws IOException { return runAsync("isComplete", new Callable<Boolean>() { @Override public Boolean call() throws Exception { return _job.isComplete(); } }); } @Override boolean isSuccessful() throws IOException { return runAsync("isSuccessful", new Callable<Boolean>() { @Override public Boolean call() throws Exception { return _job.isSuccessful(); } }); } @Override void killJob() throws IOException { runAsync("killJob", new Callable<Void>() { @Override public Void call() throws Exception { _job.killJob(); return null; } }); } private <T> T runAsync(String taskName, Callable<T> task) throws IOException { Future<T> future = _es.submit(task); try { long start = System.currentTimeMillis(); DBG("Executing job.", taskName, "(); id=", _jobId); T result = future.get(_timeoutSeconds, TimeUnit.SECONDS); DBG("Operation job.", taskName, "() took ", (System.currentTimeMillis() - start), "ms"); return result; } catch (TimeoutException ex) { throw new RuntimeException("Operation " + taskName + " was not able to complete in " + _timeoutSeconds + "s.", ex); } catch (Exception e) { throw new IOException("Operation " + taskName + " failed", e); } } } private static void DBG(Object... objs) { if (! driverDebug) return; StringBuilder sb = new StringBuilder("DBG: "); for( Object o : objs ) sb.append(o); System.out.println(sb.toString()); } /** * Main entry point * @param args Full program args, including those that go to ToolRunner. * @throws Exception */ public static void main(String[] args) throws Exception { int exitCode = ToolRunner.run(new h2odriver(), args); maybePrintYarnLogsMessage(); System.exit(exitCode); } }
true
626905672c2824e1e2c0eb535dca5ef43ea742a6
Java
Scriptgate/engine-core
/src/main/java/net/scriptgate/engine/image/ImageLoader.java
UTF-8
2,797
2.609375
3
[]
no_license
package net.scriptgate.engine.image; import javax.imageio.ImageIO; import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import static java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment; import static java.awt.Transparency.TRANSLUCENT; import static java.lang.Integer.toHexString; public abstract class ImageLoader<T> { private static final String resources = ""; private static final String extension = ".png"; protected final Map<String, T> repository; public ImageLoader() { this.repository = new HashMap<>(); } public static BufferedImage loadImage(String name) { BufferedImage imageFromResource = readImageFromResource(name); return createCompatibleImage(imageFromResource); } private static BufferedImage readImageFromResource(String name) { try (InputStream imageStream = ImageLoader.class.getClassLoader().getResourceAsStream(getPath(name))) { return ImageIO.read(imageStream); } catch (IOException | IllegalArgumentException ex) { throw new RuntimeException("Exception reading image with filepath: " + getPath(name)); } } private static BufferedImage createCompatibleImage(BufferedImage image) { GraphicsConfiguration graphicsConfiguration = getLocalGraphicsEnvironment() .getDefaultScreenDevice() .getDefaultConfiguration(); BufferedImage compatibleImage = graphicsConfiguration.createCompatibleImage(image.getWidth(), image.getHeight(), TRANSLUCENT); Graphics g = compatibleImage.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return compatibleImage; } private static String getPath(String name) { return resources + name + extension; } public T getTexture(String resourceName) { T texture = repository.get(resourceName); if (texture != null) { return texture; } texture = loadTexture(resourceName); repository.put(resourceName, texture); return texture; } protected abstract T loadTexture(String path); public String[] pixelsToHexArray(int[] pixels) { String[] hexValues = new String[pixels.length]; for (int i = 0; i < pixels.length; i++) { hexValues[i] = toHexString(pixels[i]).substring(2).toUpperCase(); } return hexValues; } public String[] imageToHexArray(BufferedImage image) { int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); return pixelsToHexArray(pixels); } }
true
eed9d68dcb8226f92be98ef750393710b86fdd86
Java
juanicastellan0/CarWorkshop
/src/jic/controllers/RepairOrderController.java
UTF-8
3,593
3.265625
3
[ "MIT" ]
permissive
package jic.controllers; import jic.models.Car; import jic.models.RepairOrder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Scanner; public class RepairOrderController { private static Scanner scanner = new Scanner(System.in); public static void add(ArrayList<RepairOrder> repair_orders, ArrayList<Car> cars) throws ParseException { System.out.println("\nEnter a car"); Car car = Car.search(scanner, cars); System.out.println("\nEnter a problem description"); String problem_description = scanner.nextLine(); System.out.println("\nEnter the repair price"); Long repair_price = scanner.nextLong(); SimpleDateFormat date_formatter = new SimpleDateFormat("dd/MM/yyyy"); RepairOrder repair_order = new RepairOrder( car, problem_description, enterAdmissionDate(date_formatter), enterRepairDate(date_formatter), repair_price); repair_orders.add(repair_order); } public static void index(ArrayList<RepairOrder> repair_orders) { if (repair_orders.isEmpty()) { System.out.println("Repair order list is empty"); } System.out.println("\nRepair orders: "); for (RepairOrder repair_order : repair_orders) { System.out.println("- car: " + repair_order.getCar() + "\n- repair price: " + repair_order.getRepairPrice()); } } public static void update(ArrayList<RepairOrder> repair_orders, ArrayList<Car> cars) throws ParseException { RepairOrderController.index(repair_orders); System.out.println("\nSelect a repair order to update"); RepairOrder repair_order = RepairOrder.search(scanner, repair_orders); boolean repair_order_not_found = true; while (repair_order_not_found) { if (repair_order != null) { repair_order_not_found = false; System.out.println("\nEnter a car"); repair_order.setCar(Car.search(scanner, cars)); System.out.println("\nEnter the problem description"); repair_order.setProblemDescription(scanner.nextLine()); SimpleDateFormat date_formatter = new SimpleDateFormat("dd/MM/yyyy"); System.out.println("\nEnter a admission date"); repair_order.setAdmissionDate(enterAdmissionDate(date_formatter)); System.out.println("\nEnter the repair date"); repair_order.setRepairDate(enterRepairDate(date_formatter)); System.out.println("\nEnter a repair price"); repair_order.setRepairPrice(scanner.nextLong()); } else { System.out.println("Repair order not found"); repair_order_not_found = false; } } } private static Date enterAdmissionDate(SimpleDateFormat date_formatter) throws ParseException { System.out.println("\nEnter the admission date with this format: dd/MM/yyyy"); String string_admission_date = scanner.nextLine(); return date_formatter.parse(string_admission_date); } private static Date enterRepairDate(SimpleDateFormat date_formatter) throws ParseException { System.out.println("\nEnter the repair date with this format: dd/MM/yyyy"); String string_repair_date = scanner.nextLine(); return date_formatter.parse(string_repair_date); } }
true
d18d4ebc8693521aae3402b0210a21e3eb305da7
Java
studyforeign/genuinetest
/genuine-modules/genuine-kdb/src/main/java/com.sn.genuinetest/module/kdb/util/ValidatorRegistry.java
UTF-8
1,868
2.484375
2
[]
no_license
package com.sn.genuinetest.module.kdb.util; import com.sn.genuinetest.module.kdb.util.q.QType; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static com.sn.genuinetest.module.kdb.util.q.QType.*; import static org.apache.logging.log4j.LogManager.getLogger; public class ValidatorRegistry { public static final Logger LOGGER = getLogger(ValidatorRegistry.class); private static Map<QType, KdbTypeValidator> registry = new HashMap<>(); static { register(INT, IntegerValidator.class); register(LONG, LongValidator.class); register(STRING, StringValidator.class); register(DATE, DateValidator.class); register(DOUBLE, DoubleValidator.class); } private static void register(QType type, Class<? extends KdbTypeValidator> validator) { try { if (!registry.containsKey(type)) { registry.put(type, validator.newInstance()); } } catch (Exception e) { LOGGER.error("Unable to register validator of type {}", validator); } } private static QType getType(String column) { if (registry.get(INT).test(column)) { return INT; } else if (registry.get(LONG).test(column)) { return LONG; } else if (registry.get(DATE).test(column)) { return CHAR; } else if (registry.get(DOUBLE).test(column)) { return DOUBLE; } else { return STRING; } } public static QType[] getTypes(String[] columns) throws IOException { int numberOfColumns = columns.length; QType qTypes[] = new QType[numberOfColumns]; for (int i = 0; i < numberOfColumns; i++) { qTypes[i] = getType(columns[i]); } return qTypes; } }
true
452f859253069ddfc174ea3c36bb4d44d1b62a6a
Java
cengler/caeycae-mdi-sample
/src/com/appspot/mdisample/client/event/NavigationTabEvent.java
UTF-8
1,849
2.390625
2
[]
no_license
package com.appspot.mdisample.client.event; import com.appspot.mdisample.client.module.content.navigation.NavigationTabElement; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; import com.gwtplatform.mvp.client.HasEventBus; /** * @author Olivier Monaco * @author Christian Goudreau */ public class NavigationTabEvent extends GwtEvent<NavigationTabEvent.NavigationTabHandler> { public interface NavigationTabHandler extends EventHandler { public void onCloseTab(NavigationTabElement element); public void onRevealTab(NavigationTabElement element); } private static enum Action { REVEAL, CLOSE; } private static Type<NavigationTabHandler> type; public static void fireClose(HasEventBus source, NavigationTabElement element) { if (type != null) { source.fireEvent(new NavigationTabEvent(Action.CLOSE, element)); } } public static void fireReveal(HasEventBus source, NavigationTabElement element) { if (type != null) { source.fireEvent(new NavigationTabEvent(Action.REVEAL, element)); } } public static Type<NavigationTabHandler> getType() { if (type == null) { type = new Type<NavigationTabHandler>(); } return type; } private NavigationTabElement element; private Action action; public NavigationTabEvent(Action action, NavigationTabElement element) { this.element = element; this.action = action; } @Override protected void dispatch(NavigationTabHandler handler) { switch (action) { case REVEAL: handler.onRevealTab(element); break; case CLOSE: handler.onCloseTab(element); break; } } @Override public Type<NavigationTabHandler> getAssociatedType() { return getType(); } public NavigationTabElement getElement() { return element; } }
true
3d0a8c9e9a296ed0b39fe988f3e4ceafbce3fde4
Java
YamAzoulay/menuColors
/app/src/main/java/com/example/yam35/menucolors/Main2Activity.java
UTF-8
1,502
2.203125
2
[]
no_license
package com.example.yam35.menucolors; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; public class Main2Activity extends AppCompatActivity { LinearLayout layout01; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); layout01 = (LinearLayout) findViewById(R.id.layout01); } public void back (View view) { Intent t = new Intent(this, MainActivity.class); startActivity(t); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); menu.add(0,0,250,"Green"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { String st = item.getTitle().toString(); if (st.equals("Red")) layout01.setBackgroundColor(Color.RED); if (st.equals("Blue")) layout01.setBackgroundColor(Color.BLUE); if (st.equals("Yellow")) layout01.setBackgroundColor(Color.YELLOW); if (st.equals("Green")) layout01.setBackgroundColor(Color.GREEN); return super.onOptionsItemSelected(item); } }
true
84497c75b4b572fdf8c07c8df2d4e9209a18700b
Java
bacali95/ACM-Algorithms
/src/com/eniso/acm/Mathematics/NumberTheory/PrimeNumbers.java
UTF-8
1,158
3.625
4
[]
no_license
package com.eniso.acm.Mathematics.NumberTheory; import java.io.*; import java.util.*; public class PrimeNumbers { static BitSet isPrime = new BitSet(10000000); static ArrayList<Long> primes = new ArrayList<>(); static void sieve() { isPrime.set(0); isPrime.set(1); for (long i = 2; i < isPrime.size(); i++) { if (!isPrime.get((int) i)) { primes.add(i); for (long j = 2 * i; j < isPrime.size(); j += i) { isPrime.set((int) j); } } } } static boolean isPrime(long n) { if (n < isPrime.size()) { return !isPrime.get((int) n); } for (int i = 0; i < primes.size(); i++) { long u = primes.get(i); if (u * u > n) { break; } if (n % u == 0) { return false; } } return true; } public static void main(String[] args) { PrintWriter out = new PrintWriter(System.out); sieve(); out.println(isPrime(136117223861L)); out.close(); } }
true
c8eb2e7e022fd27efa4a5e9091ce767f8877d6c6
Java
moutainhigh/Fexie-Spring-MVC-Backend
/fexie_openservice/fexie-common/src/main/java/com/yuzhidi/ro/product/ProductCartDetailRO.java
UTF-8
587
1.617188
2
[]
no_license
package com.yuzhidi.ro.product; import lombok.Data; import java.util.List; /** * 商品购物车 * Created by chen.qiu on 2017/4/28 at 20:40. */ @Data public class ProductCartDetailRO implements java.io.Serializable { private boolean is_vip; private double total; private long count; private boolean select_all; private double economical; private double all_total; private double league_economical; private List<ProductCartRO> list; private List<ProductCartRO> select_list; private List<ProductThumbRO> lose_list; //已失效商品 }
true
38324710ccb352bb5a77fdd87b6761f0edadc16f
Java
marcoaureliomunhoz/android
/apps/androidx/MemoList/app/src/main/java/br/com/marcoaureliomunhoz/memolist/activities/MemoListActivity.java
UTF-8
4,944
2.171875
2
[]
no_license
package br.com.marcoaureliomunhoz.memolist.activities; import br.com.marcoaureliomunhoz.memolist.MemoListApplication; import br.com.marcoaureliomunhoz.memolist.R; import br.com.marcoaureliomunhoz.memolist.adapters.MemoListRecyclerAdapter; import br.com.marcoaureliomunhoz.memolist.callbacks.MemoListItemTouchHelperCallback; import br.com.marcoaureliomunhoz.memolist.listeners.OnItemMemoListRecyclerClickListener; import br.com.marcoaureliomunhoz.memolist.models.Record; import br.com.marcoaureliomunhoz.memolist.repositories.RepositoryTemplate; import br.com.marcoaureliomunhoz.memolist.services.CloneRepositoryAsyncTask; import butterknife.BindView; import butterknife.ButterKnife; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MemoListActivity extends AppCompatActivity { public static final int REQUEST_INSERT = 1; public static final int REQUEST_UPDATE = 2; public static final String EXTRA_RESULT_MODEL_NAME = "result_model"; private final RepositoryTemplate<Record> repository = MemoListApplication.repository; private MemoListRecyclerAdapter adapter = null; private int listRefreshCount = 0; @BindView(R.id.listRecords) RecyclerView listRecords; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_memo_list); ButterKnife.bind(this); setTitle(R.string.memo_list_actitivy_title); } @Override protected void onResume() { super.onResume(); prepareMemoListRecyclerView(); if (listRefreshCount == 0) refreshList(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.memo_list_activity_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.menu_item_add_record) { openMemoForm(null); } else if (item.getItemId() == R.id.menu_item_refresh_list) { refreshList(); } return super.onOptionsItemSelected(item); } private void refreshList() { new CloneRepositoryAsyncTask<Record>( repository, list -> adapter.refresh(list) ).execute(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Record record = null; if (resultCode == Activity.RESULT_OK) { record = (Record) data.getSerializableExtra(MemoListActivity.EXTRA_RESULT_MODEL_NAME); } boolean resultOk = (resultCode == Activity.RESULT_OK) && (record != null); if (requestCode == MemoListActivity.REQUEST_INSERT) { if (resultOk) adapter.insert(record); } else if (requestCode == MemoListActivity.REQUEST_UPDATE) { if (resultOk) adapter.update(record); } } private void prepareMemoListRecyclerView() { if (adapter == null) { prepareLayoutForMemoListRecyclerView(); prepareAdapterForMemoListRecyclerView(); prepareListenersForMemoListRecyclerView(); prepareTouchForMemoListRecyclerView(); } } private void prepareLayoutForMemoListRecyclerView() { LinearLayoutManager layoutManager = new LinearLayoutManager(this); listRecords.setLayoutManager(layoutManager); } private void prepareListenersForMemoListRecyclerView() { adapter.setOnItemRecyclerClickListener(new OnItemMemoListRecyclerClickListener() { @Override public void onItemClick(Record record, int position) { openMemoForm(record); } }); } private void prepareAdapterForMemoListRecyclerView() { adapter = new MemoListRecyclerAdapter(this, null); listRecords.setAdapter(adapter); } private void prepareTouchForMemoListRecyclerView() { ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new MemoListItemTouchHelperCallback(adapter)); itemTouchHelper.attachToRecyclerView(listRecords); } private void openMemoForm(Record record) { Intent intent = new Intent(this, MemoFormActivity.class); intent.putExtra(MemoFormActivity.EXTRA_MODEL_NAME, record); int requestCode = record == null ? MemoListActivity.REQUEST_INSERT : MemoListActivity.REQUEST_UPDATE; startActivityForResult(intent, requestCode); } }
true
4f056fc9e6db725c5805851595bf7e6fccf01b44
Java
ZerocksX/Java-Course-2017
/hw15-0036492049/src/main/java/hr/fer/zemris/java/dao/DAOProvider.java
UTF-8
386
2.28125
2
[]
no_license
package hr.fer.zemris.java.dao; import hr.fer.zemris.java.dao.jpa.JPADAOImpl; /** * {@link DAO} provider * @author Pavao Jerebić */ public class DAOProvider { /** * Instance of {@link DAO} implementation */ private static DAO dao = new JPADAOImpl(); /** * getter for DAO * @return DAO */ public static DAO getDAO() { return dao; } }
true
69d9c69d99a43405243a403b2bc6cdf722d08a7b
Java
victorperone/PadroesdeProjetos
/Mediator/mediator/src/mediator/TorreMediator.java
UTF-8
812
3.140625
3
[]
no_license
package mediator; import java.util.ArrayList; public class TorreMediator implements Mediator{ protected ArrayList<Colleague> avioes; public TorreMediator() { avioes = new ArrayList<Colleague>(); } public void adicionarColleague(Colleague colleague) { avioes.add(colleague); } @Override public void enviar(String mensagem, Colleague colleague) { for (Colleague contato : avioes) { if (contato != colleague) { definirProtocolo(contato); contato.receberMensagem(mensagem); } } } private void definirProtocolo(Colleague contato) { if (contato instanceof AviaoPista) { System.out.println("Ola, como esta o clima?"); } else if (contato instanceof AviaoVoando) { System.out.println("Ola, a pista esta livre?"); } } }
true
458d7efe9d757f862b19c8541d551a0c87252622
Java
sanwaralkmali/imglib2
/src/test/java/net/imglib2/util/StopWatchTest.java
UTF-8
1,921
3.140625
3
[ "BSD-2-Clause" ]
permissive
package net.imglib2.util; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; public class StopWatchTest { @Ignore // NB: This is not a test. But it's a short demo how StopWatch could be used during debugging. @Test public void demo() throws InterruptedException { StopWatch sw = StopWatch.createAndStart(); Thread.sleep( 42 ); System.out.println( sw ); } @Ignore // NB: Time measurement depends on side effects. The test might sometimes fail. Better ignore to avoid confusion. @Test public void testCreateAndStart() throws InterruptedException { StopWatch sw = StopWatch.createAndStart(); Thread.sleep( 42 ); long nanoTime = sw.nanoTime(); assertEquals( 42e6, nanoTime, 1e6); } @Ignore // NB: Time measurement depends on side effects. The test might sometimes fail. Better ignore it to avoid confusion. @Test public void testStartStop() throws InterruptedException { StopWatch sw = StopWatch.createStopped(); Thread.sleep( 10 ); sw.start(); Thread.sleep( 10 ); sw.stop(); Thread.sleep( 10 ); long nanoTime = sw.nanoTime(); assertEquals( 10e6, nanoTime, 1e6); } @Ignore // NB: Time measurement depends on side effects. The test might sometimes fail. Better ignore it to avoid confusion. @Test public void testSeconds() throws InterruptedException { StopWatch sw = StopWatch.createAndStart(); Thread.sleep( 42 ); double time = sw.seconds(); assertEquals( 0.042, time, 0.010); } @Test public void testSecondsToString() { assertEquals("42.000 s", StopWatch.secondsToString(42)); assertEquals("42.000 ms", StopWatch.secondsToString(42e-3)); assertEquals("42.000 \u00b5s", StopWatch.secondsToString(42e-6)); assertEquals("42.000 ns", StopWatch.secondsToString(42e-9)); assertEquals("-42.000 ms", StopWatch.secondsToString(-42e-3)); assertEquals("42.000 s", StopWatch.secondsToString(42.00000000001)); } }
true
90b372a7af66ae2c2bda85af8c37a24cfe3452ba
Java
cha63506/CompSecurity
/Shopping/amazon_shopping_source/src/com/amazon/rio/j2me/client/services/mShop/BarcodeSearchRequest.java
UTF-8
1,460
1.6875
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.amazon.rio.j2me.client.services.mShop; public class BarcodeSearchRequest { private String barcode; private String barcodeType; private String clickStreamOrigin; private Boolean includeAddOnItems; private int maxImageDimension; private int size; public BarcodeSearchRequest() { } public String getBarcode() { return barcode; } public String getBarcodeType() { return barcodeType; } public String getClickStreamOrigin() { return clickStreamOrigin; } public Boolean getIncludeAddOnItems() { return includeAddOnItems; } public int getMaxImageDimension() { return maxImageDimension; } public int getSize() { return size; } public void setBarcode(String s) { barcode = s; } public void setBarcodeType(String s) { barcodeType = s; } public void setClickStreamOrigin(String s) { clickStreamOrigin = s; } public void setIncludeAddOnItems(Boolean boolean1) { includeAddOnItems = boolean1; } public void setMaxImageDimension(int i) { maxImageDimension = i; } public void setSize(int i) { size = i; } }
true
d138a937ced579725f05bcaeb9ccdefe8746c926
Java
razkevich/swagger-gen
/src/test/java/ru/sbrf/ufs/eu/bh/services/valueobjects/admin/producttype/BankingProductSubtypeUpdateVO.java
UTF-8
825
2.0625
2
[]
no_license
package ru.sbrf.ufs.eu.bh.services.valueobjects.admin.producttype; public class BankingProductSubtypeUpdateVO { private Long typeId; private Long id; private Integer sequence; private String productSubtype; public Integer getSequence() { return sequence; } public void setSequence(Integer sequence) { this.sequence = sequence; } public Long getTypeId() { return typeId; } public void setTypeId(Long typeId) { this.typeId = typeId; } public String getProductSubtype() { return productSubtype; } public void setProductSubtype(String productSubtype) { this.productSubtype = productSubtype; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
true
eb9ee42c0da96b21ddda256db462c3f409088d1e
Java
IdelsTak/dpml-svn
/tags/SDK-2.0.2/main/depot/tools/src/main/dpml/tools/tasks/RMICTask.java
UTF-8
5,011
1.984375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2006 Stephen McConnell * * 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 dpml.tools.tasks; import java.io.File; import java.util.ArrayList; import java.util.List; import dpml.library.Scope; import dpml.tools.Context; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Rmic; import org.apache.tools.ant.types.Path; /** * Compile sources located in ${project.target}/main to java class file under * the ${project.target}/classes directory. Properties influencing the compilation * include: * <ul> * <li>project.javac.debug : boolean true (default) or false</li> * <li>project.javac.fork: boolean true or false (default) </li> * <li>project.javac.deprecation: boolean true (default) or false</li> * </ul> * @author <a href="@PUBLISHER-URL@">@PUBLISHER-NAME@</a> * @version @PROJECT-VERSION@ */ public class RMICTask extends GenericTask { static { System.setProperty( "com.sun.CORBA.ORBDynamicStubFactoryFactoryClass", "com.sun.corba.se.impl.presentation.rmi.StubFactoryFactoryStaticImpl" ); } private List<Include> m_includes = new ArrayList<Include>(); private List<Include> m_excludes = new ArrayList<Include>(); private String m_classPathRef; private File m_base; /** * Creation of a new RMIC task instance. */ public RMICTask() { super(); } /** * Set the id of the compilation classpath. * @param id the classpath reference */ public void setClasspathRef( String id ) { m_classPathRef = id; } /** * Set the base directory. * @param base the base directory */ public void setBase( File base ) { m_base = base; } /** * Create and add a new include statement. * @return the include */ public Include createInclude() { Include include = new Include(); m_includes.add( include ); return include; } /** * Create and add a new exclude statement. * @return the exclude */ public Include createExclude() { Include include = new Include(); m_excludes.add( include ); return include; } /** * Task initialization. */ public void init() { setTaskName( "rmic" ); } /** * Task execution. */ public void execute() { Context context = getContext(); if( null == m_base ) { setBase( context.getTargetClassesMainDirectory() ); } if( !m_base.exists() ) { return; } final Rmic rmic = (Rmic) getProject().createTask( "rmic" ); rmic.setTaskName( "rmic" ); final Project project = getProject(); rmic.setProject( project ); rmic.setBase( m_base ); final Path classpath = getClasspath(); rmic.setClasspath( classpath ); // populate includes/excludes for( Include include : m_includes ) { String name = include.getName(); rmic.createInclude().setName( name ); } for( Include exclude : m_excludes ) { String name = exclude.getName(); rmic.createExclude().setName( name ); } // initialize and execute rmic.init(); rmic.execute(); } private Path getClasspath() { if( null != m_classPathRef ) { return (Path) getProject().getReference( m_classPathRef ); } else { getContext().getPath( Scope.RUNTIME ); setClasspathRef( "project.compile.path" ); return getClasspath(); } } /** * Include datatype. */ public static class Include { private String m_name; /** * Set the include name. * @param name the include name */ public void setName( String name ) { m_name = name; } /** * Get the include name. * @return the include name */ public String getName() { return m_name; } } }
true
730640e51338e3b3d75c71849291e530cccd3942
Java
rbkmoney/magista
/src/main/java/com/rbkmoney/magista/query/BaseQuery.java
UTF-8
1,735
2.5625
3
[ "Apache-2.0" ]
permissive
package com.rbkmoney.magista.query; /** * Created by vpankrashkin on 04.08.16. */ public abstract class BaseQuery<T, CT> implements Query<T, CT> { private final Object descriptor; private QueryParameters queryParameters; private Query parentQuery; public BaseQuery(Object descriptor, QueryParameters params) { if (descriptor == null || params == null) { throw new NullPointerException("Null descriptor or params're not allowed"); } this.descriptor = descriptor; this.queryParameters = createQueryParameters(params, params.getDerivedParameters());// y, this is bad } @Override public Object getDescriptor() { return descriptor; } @Override public Query getParentQuery() { return parentQuery; } @Override public void setParentQuery(Query query) { this.parentQuery = query; this.queryParameters = createQueryParameters(queryParameters, extractParameters(query)); } @Override public QueryParameters getQueryParameters() { return queryParameters; } protected QueryParameters createQueryParameters(QueryParameters parameters, QueryParameters derivedParameters) { return new QueryParameters(parameters, derivedParameters); } protected QueryParameters extractParameters(Query query) { return query == null ? null : query.getQueryParameters(); } protected <R extends QueryContext> R getContext(QueryContext context, Class<R> expectedType) { if (expectedType.isAssignableFrom(context.getClass())) { return (R) context; } else { throw new QueryExecutionException("Wrong context type"); } } }
true
6922c0bb3b92c84930d8944745369aacb41e917c
Java
SheepYang1993/MobileSafe
/app/src/main/java/com/sheepyang/mobilesafe/ui/ToolsActivity.java
UTF-8
573
1.867188
2
[]
no_license
package com.sheepyang.mobilesafe.ui; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.sheepyang.mobilesafe.R; /** * Created by SheepYang on 2016/6/11 14:00. */ public class ToolsActivity extends BaseActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tools); } public void queryAddress(View v) { Intent intent = new Intent(this, AddressActivity.class); startActivity(intent); } }
true
c148027d7f6791d05f9abe2181528b1319dd0066
Java
MaibornWolff/codecharta
/analysis/import/SourceCodeParser/src/test/resources/max-nesting-level/lambda_function.java
UTF-8
225
2.796875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "BSD-3-Clause", "LGPL-3.0-only" ]
permissive
class LambdaFunction { public void lamba() { FuncInterface fobj = (int x) -> { if(a<b) { System.out.println(2 * x); } }; fobj.abstractFunction(5); } }
true
5a12029569d1d77bf29b627d811a97426bef8a84
Java
Guifamelo/Guithub
/ListaHerança/testePessoa.java
UTF-8
586
2.453125
2
[]
no_license
package listaPOO; public class testePessoa { public static void mais(String args[]) { pessoa guilherme = new pessoa("Guilherme", 1014); vendedor leonardo = new vendedor ("Leonardo", 1015, 1000, 10); administrador laurent = new administrador ("Laurent", 1016, 500); pessoa guigui = new vendedor("Guigui", 1017,1000, 10); pessoa guiga = new administrador ("Guiga", 1018,700); System.out.println(guilherme.getMatricula()); System.out.println(leonardo.getComissao()); System.out.println(laurent.getAjudaDeCusto()); System.out.println(guigui.getMatricula()); } }
true
560b58d2538c3e9ed9933113e329405ccb6692d8
Java
webprotocol/MosaicSpring
/src/main/java/com/hybrid/controllers/PrimaryController.java
UTF-8
3,782
2.203125
2
[]
no_license
package com.hybrid.controllers; import com.gluonhq.particle.application.ParticleApplication; import com.gluonhq.particle.state.StateManager; import com.gluonhq.particle.view.ViewManager; import java.util.ResourceBundle; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextInputDialog; import javafx.stage.WindowEvent; import javafx.application.Platform; import javax.inject.Inject; import org.controlsfx.control.action.Action; import org.controlsfx.control.action.ActionMap; import org.controlsfx.control.action.ActionProxy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class PrimaryController { private boolean first = true; @FXML private Label label; @FXML private Button button; @FXML private ResourceBundle resources; @Autowired ApplicationContext ctx; private Action actionSignin; public PrimaryController() { } public void initialize() { ActionMap.register(this); actionSignin = ActionMap.action("signin"); button.setOnAction(e -> { viewManager.switchView("secondary"); }); Platform.runLater(new Runnable() { public void run() { } }); javafx.application.Platform.runLater(new Runnable() { @Override public void run() { app.getPrimaryStage().setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { exit(); System.out.println("### close()..."); } }); } }); System.out.println("PrimaryController.initialize()... " + ctx.getBean(FXMLLoader.class).getControllerFactory()); } @Inject private ParticleApplication app; @Inject private ViewManager viewManager; @Inject private StateManager stateManager; @Inject private FXMLLoader fxmlLoader; public void init() { System.out.println("PrimaryController.init()... " + fxmlLoader.getControllerFactory()); } public void postInit() { if (first) { stateManager.setPersistenceMode(StateManager.PersistenceMode.USER); addUser(stateManager.getProperty("UserName").orElse("").toString()); first = false; } app.getParticle().getToolBarActions().add(actionSignin); } public void dispose() { app.getParticle().getToolBarActions().remove(actionSignin); } public void addUser(String userName) { label.setText(resources.getString("label.text") + (userName.isEmpty() ? "" : ", " + userName) + "!"); stateManager.setProperty("UserName", userName); } @ActionProxy(text="Sign In") private void signin() { TextInputDialog input = new TextInputDialog(stateManager.getProperty("UserName").orElse("").toString()); input.setTitle("User name"); input.setHeaderText(null); input.setContentText("Input your name:"); input.showAndWait().ifPresent(this::addUser); } @ActionProxy(text="Exit", accelerator="alt+F4") private void exit() { System.out.println("PrimaryControllor.exit()..."); AnnotationConfigEmbeddedWebApplicationContext actx = (AnnotationConfigEmbeddedWebApplicationContext) ctx; actx.close(); System.out.println("ctx.close()..."); app.exit(); } }
true
d26f7130f6147b87d65fbfd7b40083e2ea215adf
Java
bmickow/Calculator
/Calculator.java
UTF-8
41,571
2.9375
3
[]
no_license
import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JComponent; import java.awt.event.ActionListener; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.awt.event.ActionEvent; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.awt.Font; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import java.awt.Color; import javax.swing.JTextField; import java.util.Stack; /* This is a Java GUI replica of a Windows calculator in programmer mode. * A stack is used to push and pop a String of operands and operators to and * from the stack. When the the division and mod operations are entered peek * is used to make sure a zero was not the previous number entered. When equal * is entered the string is calculated using the ScriptEngineManager class. */ public class FinalCalculator2 { private JFrame frame; private final Action action = new SwingAction(); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("Js"); Stack<String> myStringStack = new Stack<String>(); String firstNumber; String secondNumber; String result; String operations; private Object math; private JTextField outPutText2; private JTextField hex_textField; private JTextField dec_textField_1; private JTextField bin_textField; private JTextField oct_textField; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ProgrammerCalculator window = new ProgrammerCalculator(); window.frame.setVisible(true); //window.frame.setResizable(true); //window.frame.setEnabled(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public FinalCalculator2() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame("Calculator"); frame.getContentPane().setBackground(new Color(236, 236, 236)); frame.setUndecorated(false); frame.setVisible(true); frame.setBounds(0, 100, 484, 745); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); ((JComponent) frame.getContentPane()).setBorder(BorderFactory.createMatteBorder(0, 0, 0, 0, Color.blue)); frame.setLocationRelativeTo(null); //frame.setEnabled(true); JTextField outPutText = new JTextField(""); //outPutText.setMinimumFractionDigits(2); outPutText.setEditable(false); outPutText.setBorder(javax.swing.BorderFactory.createEmptyBorder()); outPutText.setOpaque(false); outPutText2.setColumns(20); outPutText2 = new JTextField(); outPutText2.setEditable(false); outPutText2.setOpaque(false); outPutText2.setFont(new Font("Tahoma", Font.PLAIN, 18)); outPutText2.setBounds(76, 80, 376, 26); frame.getContentPane().add(outPutText2); outPutText2.setColumns(20); outPutText2.setHorizontalAlignment(SwingConstants.RIGHT); outPutText2.setBorder(javax.swing.BorderFactory.createEmptyBorder()); hex_textField = new JTextField(); hex_textField.setFont(new Font("Tahoma", Font.PLAIN, 18)); hex_textField.setEditable(false); hex_textField.setOpaque(false); hex_textField.setBounds(61, 174, 175, 26); frame.getContentPane().add(hex_textField); hex_textField.setColumns(20); hex_textField.setBorder(javax.swing.BorderFactory.createEmptyBorder()); dec_textField_1 = new JTextField(); dec_textField_1.setFont(new Font("Tahoma", Font.PLAIN, 18)); dec_textField_1.setEditable(false); dec_textField_1.setOpaque(false); dec_textField_1.setBounds(61, 214, 175, 26); frame.getContentPane().add(dec_textField_1); dec_textField_1.setColumns(20); dec_textField_1.setBorder(new EmptyBorder(0, 0, 0, 0)); oct_textField = new JTextField(); oct_textField.setFont(new Font("Tahoma", Font.PLAIN, 18)); oct_textField.setEditable(false); oct_textField.setOpaque(false); oct_textField.setBounds(61, 254, 175, 26); frame.getContentPane().add(oct_textField); oct_textField.setColumns(20); oct_textField.setBorder(javax.swing.BorderFactory.createEmptyBorder()); bin_textField = new JTextField(); bin_textField.setFont(new Font("Tahoma", Font.PLAIN, 18)); bin_textField.setEditable(false); bin_textField.setOpaque(false); bin_textField.setBounds(61, 294, 175, 26); frame.getContentPane().add(bin_textField); bin_textField.setColumns(20); bin_textField.setBorder(javax.swing.BorderFactory.createEmptyBorder()); JButton button_0 = new JButton("0"); button_0.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_0.setBackground(new Color(255, 255, 255)); button_0.setBounds(241, 646, 75, 50); frame.getContentPane().add(button_0); JButton button_1 = new JButton("1"); button_1.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_1.setBackground(new Color(255, 255, 255)); button_1.setBounds(162, 592, 75, 50); frame.getContentPane().add(button_1); JButton button_2 = new JButton("2"); button_2.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_2.setBackground(new Color(255, 255, 255)); button_2.setBounds(241, 592, 75, 50); frame.getContentPane().add(button_2); JButton button_3 = new JButton("3"); button_3.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_3.setBackground(new Color(255, 255, 255)); button_3.setBounds(320, 592, 75, 50); frame.getContentPane().add(button_3); JButton button_4 = new JButton("4"); button_4.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_4.setBackground(new Color(255, 255, 255)); button_4.setAlignmentY(0.0f); button_4.setBounds(162, 538, 75, 50); frame.getContentPane().add(button_4); JButton button_5 = new JButton("5"); button_5.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_5.setBackground(new Color(255, 255, 255)); button_5.setAlignmentY(0.0f); button_5.setBounds(241, 538, 75, 50); frame.getContentPane().add(button_5); JButton button_6 = new JButton("6"); button_6.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_6.setBackground(new Color(255, 255, 255)); button_6.setAlignmentY(0.0f); button_6.setBounds(320, 538, 75, 50); frame.getContentPane().add(button_6); JButton button_7 = new JButton("7"); button_7.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_7.setBackground(new Color(255, 255, 255)); button_7.setAlignmentY(0.0f); button_7.setBounds(162, 484, 75, 50); frame.getContentPane().add(button_7); JButton button_8 = new JButton("8"); button_8.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_8.setBackground(new Color(255, 255, 255)); button_8.setAlignmentY(0.0f); button_8.setBounds(241, 484, 75, 50); frame.getContentPane().add(button_8); JButton button_9 = new JButton("9"); button_9.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_9.setBackground(new Color(255, 255, 255)); button_9.setAlignmentY(0.0f); button_9.setBounds(320, 484, 75, 50); frame.getContentPane().add(button_9); JButton button_A = new JButton("A"); button_A.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_A.setBackground(new Color(255, 255, 255)); button_A.setAlignmentY(0.0f); button_A.setBounds(4, 484, 75, 50); button_A.setRolloverEnabled(true); frame.getContentPane().add(button_A); button_A.setEnabled(false); JButton button_B = new JButton("B"); button_B.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_B.setBackground(new Color(255, 255, 255)); button_B.setAlignmentY(0.0f); button_B.setBounds(83, 484, 75, 50); frame.getContentPane().add(button_B); button_B.setEnabled(false); JButton button_C = new JButton("C"); button_C.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_C.setBackground(new Color(255, 255, 255)); button_C.setAlignmentY(0.0f); button_C.setBounds(4, 538, 75, 50); frame.getContentPane().add(button_C); button_C.setEnabled(false); JButton button_D = new JButton("D"); button_D.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_D.setBackground(new Color(255, 255, 255)); button_D.setAlignmentY(0.0f); button_D.setBounds(83, 538, 75, 50); frame.getContentPane().add(button_D); button_D.setEnabled(false); JButton button_E = new JButton("E"); button_E.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_E.setBackground(new Color(255, 255, 255)); button_E.setBounds(4, 592, 75, 50); frame.getContentPane().add(button_E); button_E.setEnabled(false); JButton button_F = new JButton("F"); button_F.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_F.setBackground(new Color(255, 255, 255)); button_F.setBounds(83, 592, 75, 50); frame.getContentPane().add(button_F); button_F.setEnabled(false); JButton button_divide = new JButton("\u00F7"); button_divide.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_divide.setBackground(new Color(245, 245, 245)); button_divide.setAlignmentY(0.0f); button_divide.setBounds(399, 430, 75, 50); frame.getContentPane().add(button_divide); JButton button_multiply = new JButton("\u00D7"); button_multiply.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_multiply.setBackground(new Color(245, 245, 245)); button_multiply.setAlignmentY(0.0f); button_multiply.setBounds(399, 484, 75, 50); frame.getContentPane().add(button_multiply); JButton button_sub = new JButton("\u2212"); button_sub.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_sub.setBackground(new Color(245, 245, 245)); button_sub.setAlignmentY(0.0f); button_sub.setBounds(399, 538, 75, 50); frame.getContentPane().add(button_sub); JButton button_add = new JButton("+"); button_add.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_add.setBackground(new Color(245, 245, 245)); button_add.setBounds(399, 592, 75, 50); frame.getContentPane().add(button_add); JButton button_equals = new JButton("="); button_equals.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_equals.setBackground(new Color(245, 245, 245)); button_equals.setBounds(399, 646, 75, 50); frame.getContentPane().add(button_equals); button_equals.setEnabled(false); JButton buttonDecimal = new JButton("."); buttonDecimal.setFont(new Font("Tahoma", Font.PLAIN, 18)); buttonDecimal.setBackground(new Color(245, 245, 245)); buttonDecimal.setBounds(320, 646, 75, 50); frame.getContentPane().add(buttonDecimal); buttonDecimal.setEnabled(false); JButton buttonPlusMinus = new JButton("\u00B1"); buttonPlusMinus.setFont(new Font("Tahoma", Font.PLAIN, 18)); buttonPlusMinus.setBackground(new Color(245, 245, 245)); buttonPlusMinus.setBounds(162, 646, 75, 50); frame.getContentPane().add(buttonPlusMinus); JButton buttonRightPara = new JButton(")"); buttonRightPara.setFont(new Font("Tahoma", Font.PLAIN, 18)); buttonRightPara.setBackground(new Color(245, 245, 245)); buttonRightPara.setBounds(83, 646, 75, 50); frame.getContentPane().add(buttonRightPara); JButton buttonLeftPara = new JButton("("); buttonLeftPara.setFont(new Font("Tahoma", Font.PLAIN, 18)); buttonLeftPara.setForeground(new Color(0, 0, 0)); buttonLeftPara.setBackground(new Color(245, 245, 245)); buttonLeftPara.setAlignmentY(0.0f); buttonLeftPara.setBounds(4, 646, 75, 50); frame.getContentPane().add(buttonLeftPara); JButton button_back = new JButton("\u232b"); button_back.setBackground(new Color(245, 245, 245)); button_back.setAlignmentY(0.0f); button_back.setBounds(320, 430, 75, 50); frame.getContentPane().add(button_back); JButton button_clear = new JButton("C"); button_clear.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_clear.setBackground(new Color(245, 245, 245)); button_clear.setAlignmentY(0.0f); button_clear.setBounds(241, 430, 75, 50); frame.getContentPane().add(button_clear); JButton button_ce = new JButton("CE"); button_ce.setBackground(new Color(245, 245, 245)); button_ce.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_ce.setAlignmentY(0.0f); button_ce.setBounds(162, 430, 75, 50); frame.getContentPane().add(button_ce); JButton button_mod = new JButton("Mod"); button_mod.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_mod.setBackground(new Color(245, 245, 245)); button_mod.setAlignmentY(0.0f); button_mod.setBounds(83, 430, 75, 50); frame.getContentPane().add(button_mod); JButton button_up = new JButton("\u2191"); button_up.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_up.setBackground(new Color(245, 245, 245)); button_up.setAlignmentY(0.0f); button_up.setBounds(4, 430, 75, 50); frame.getContentPane().add(button_up); JButton button_and = new JButton("And"); button_and.setBackground(new Color(245, 245, 245)); button_and.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_and.setAlignmentY(0.0f); button_and.setBounds(399, 376, 75, 50); frame.getContentPane().add(button_and); JButton button_not = new JButton("Not"); button_not.setBackground(new Color(245, 245, 245)); button_not.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_not.setAlignmentY(0.0f); button_not.setBounds(320, 376, 75, 50); frame.getContentPane().add(button_not); JButton button_or = new JButton("Or"); button_or.setBackground(new Color(245, 245, 245)); button_or.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_or.setAlignmentY(0.0f); button_or.setBounds(162, 376, 75, 50); frame.getContentPane().add(button_or); JButton button_rsh = new JButton("Rsh"); button_rsh.setBackground(new Color(245, 245, 245)); button_rsh.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_rsh.setAlignmentY(0.0f); button_rsh.setBounds(83, 376, 75, 50); frame.getContentPane().add(button_rsh); JButton button_M = new JButton("M"); button_M.setBorderPainted(false); button_M.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_M.setAlignmentY(0.0f); button_M.setOpaque(false); button_M.setContentAreaFilled(false); button_M.setBounds(399, 332, 75, 40); frame.getContentPane().add(button_M); JButton button_word = new JButton("WORD"); button_word.setBorderPainted(false); button_word.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_word.setAlignmentY(0.0f); button_word.setOpaque(false); button_word.setContentAreaFilled(false); button_word.setBounds(189, 332, 100, 40); frame.getContentPane().add(button_word); JButton button_dots2 = new JButton("..."); button_dots2.setBorderPainted(false); button_dots2.setFont(new Font("Tahoma", Font.PLAIN, 35)); button_dots2.setAlignmentY(0.0f); button_dots2.setOpaque(false); button_dots2.setContentAreaFilled(false); button_dots2.setBounds(83, 332, 75, 40); frame.getContentPane().add(button_dots2); JButton button_dots1 = new JButton("\u2026"); button_dots1.setBorderPainted(false); button_dots1.setFont(new Font("Tahoma", Font.PLAIN, 35)); button_dots1.setOpaque(false); button_dots1.setContentAreaFilled(false); button_dots1.setAlignmentY(0.0f); button_dots1.setBounds(4, 332, 75, 40); frame.getContentPane().add(button_dots1); JButton button_xor = new JButton("Xor"); button_xor.setBackground(new Color(245, 245, 245)); button_xor.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_xor.setAlignmentY(0.0f); button_xor.setBounds(241, 376, 75, 50); frame.getContentPane().add(button_xor); JButton button_lsh = new JButton("Lsh"); button_lsh.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_lsh.setInheritsPopupMenu(true); button_lsh.setIgnoreRepaint(true); //btnLsh.setOpaque(false); //btnLsh.setContentAreaFilled(false); button_lsh.setBackground(new Color(240, 240, 240)); button_lsh.setAlignmentY(0.0f); button_lsh.setBounds(4, 376, 75, 50); frame.getContentPane().add(button_lsh); JButton button_ms = new JButton("MS"); button_ms.setBorderPainted(false); button_ms.setBorder(UIManager.getBorder("Button.border")); button_ms.setFont(new Font("Tahoma", Font.PLAIN, 18)); button_ms.setAlignmentY(0.0f); button_ms.setOpaque(false); button_ms.setContentAreaFilled(false); button_ms.setBounds(320, 332, 75, 40); frame.getContentPane().add(button_ms); JButton button_bin = new JButton("BIN"); button_bin.setBorderPainted(false); button_bin.setForeground(Color.BLACK); button_bin.setOpaque(false); button_bin.setContentAreaFilled(false); button_bin.setBorder(UIManager.getBorder("Button.border")); button_bin.setFont(new Font("Calibri Light", Font.BOLD, 20)); button_bin.setOpaque(false); button_bin.setHorizontalAlignment(SwingConstants.LEFT); button_bin.setAlignmentY(0.0f); button_bin.setBounds(0, 288, 478, 40); frame.getContentPane().add(button_bin); JButton button_oct = new JButton("OCT"); button_oct.setBorderPainted(false); button_oct.setOpaque(false); button_oct.setContentAreaFilled(false); button_oct.setBorder(UIManager.getBorder("Button.border")); button_oct.setFont(new Font("Calibri Light", Font.BOLD, 20)); button_oct.setOpaque(false); button_oct.setHorizontalAlignment(SwingConstants.LEFT); button_oct.setAlignmentY(0.0f); button_oct.setBounds(0, 248, 478, 40); frame.getContentPane().add(button_oct); JButton button_dec = new JButton("DEC"); button_dec.setBorderPainted(false); button_dec.setContentAreaFilled(false); button_dec.setBorder(UIManager.getBorder("Button.border")); button_dec.setFont(new Font("Calibri Light", Font.BOLD, 20)); button_dec.setOpaque(false); button_dec.setHorizontalAlignment(SwingConstants.LEFT); button_dec.setAlignmentY(0.0f); button_dec.setBounds(0, 208, 478, 40); frame.getContentPane().add(button_dec); JButton button_hex = new JButton("HEX"); button_hex.setBorderPainted(false); button_hex.setOpaque(false); button_hex.setContentAreaFilled(false); button_hex.setBorder(UIManager.getBorder("Button.border")); button_hex.setFont(new Font("Calibri Light", Font.BOLD, 20)); button_hex.setHorizontalAlignment(SwingConstants.LEFT); button_hex.setAlignmentY(0.0f); button_hex.setBounds(0, 168, 478, 40); frame.getContentPane().add(button_hex); //JTextField outPutText = new JTextField("0"); outPutText.setBackground(new Color(240, 240, 240)); outPutText.setFont(new Font("Tahoma", Font.PLAIN, 45)); outPutText.setHorizontalAlignment(SwingConstants.RIGHT); outPutText.setBounds(4, 89, 459, 80); frame.getContentPane().add(outPutText); //outPutLabel.setText("1"); JLabel label_programmer = new JLabel(" Programmer"); label_programmer.setFont(new Font("Calibri Light", Font.PLAIN, 35)); label_programmer.setBounds(76, 0, 402, 70); frame.getContentPane().add(label_programmer); JButton label_trigram = new JButton("\u2630"); label_trigram.setBorderPainted(false); label_trigram.setAlignmentY(0.0f); label_trigram.setOpaque(false); label_trigram.setContentAreaFilled(false); label_trigram.setBounds(4, 0, 70, 70); frame.getContentPane().add(label_trigram); JButton button_45 = new JButton("New button"); button_45.setAlignmentY(0.0f); button_45.setBounds(478, 0, 75, 50); frame.getContentPane().add(button_45); button_0.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + button_0.getText(); outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + button_1.getText(); outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + button_2.getText(); outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + button_3.getText(); outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + button_4.getText(); outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + button_5.getText(); outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + button_6.getText(); outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_7.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + button_7.getText(); outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_8.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + button_8.getText(); outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_9.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + button_9.getText(); outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_A.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + 10; outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_B.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + 11; outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_C.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + 12; outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_D.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + 13; outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_E.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + 14; outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_F.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + 15; outPutText.setText(inum); dec_textField_1.setText(inum); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_divide.setEnabled(true); button_multiply.setEnabled(true); button_sub.setEnabled(true); button_add.setEnabled(true); button_mod.setEnabled(true); button_equals.setEnabled(true); } }); button_divide.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText(); myStringStack.push(inum); firstNumber = outPutText.getText(); outPutText.setText(null); operations = ("\u00F7"); outPutText2.setText(outPutText2.getText() + firstNumber + " \u00F7 "); myStringStack.push("/"); button_divide.setEnabled(false); } }); button_multiply.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText(); myStringStack.push(inum); firstNumber = outPutText.getText(); outPutText.setText(null); operations = ("\u00D7"); //outPutText2.setText(firstNumber + " \u00D7"); outPutText2.setText(outPutText2.getText() + firstNumber + " \u00D7 "); myStringStack.push("*"); button_multiply.setEnabled(false); } }); button_sub.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText(); myStringStack.push(inum); firstNumber = outPutText.getText(); outPutText.setText(null); operations = ("\u2212"); outPutText2.setText(outPutText2.getText() + firstNumber + " \u2212 "); myStringStack.push("-"); button_sub.setEnabled(false); } }); button_add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText(); myStringStack.push(inum); firstNumber = outPutText.getText(); outPutText.setText(null); operations = ("+"); outPutText2.setText(outPutText2.getText() + firstNumber + " + "); myStringStack.push("+"); button_add.setEnabled(false); } }); button_mod.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText(); myStringStack.push(inum); firstNumber = outPutText.getText(); outPutText.setText(null); operations = ("mod"); outPutText2.setText(outPutText2.getText() + firstNumber + " Mod "); myStringStack.push("%"); button_mod.setEnabled(false); } }); button_equals.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText(); myStringStack.push(inum); String formattedString = myStringStack.toString(); String s = formattedString.replace("[", "").replace(",", "").replace("]", ""); //outPutText.setText(s); DecimalFormat dc = new DecimalFormat("0.00"); try { Object answer = engine.eval(s); int result = new Integer(answer.toString()); int x = (int) Math.floor(result); //String i = Integer.toString(x); outPutText.setText(Integer.toString(x)); //System.out.print(Integer.toString(x)); } catch (ScriptException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } outPutText2.setText(""); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); button_equals.setEnabled(false); myStringStack.clear(); } }); buttonDecimal.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(!outPutText.getText().contains(".")) { outPutText.setText(outPutText.getText() + buttonDecimal.getText()); } } }); button_clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myStringStack.clear(); outPutText.setText(""); outPutText2.setText(""); dec_textField_1.setText(""); bin_textField.setText(""); oct_textField.setText(""); hex_textField.setText(""); button_divide.setEnabled(false); button_multiply.setEnabled(false); button_sub.setEnabled(false); button_add.setEnabled(false); button_mod.setEnabled(false); button_equals.setEnabled(true); } }); button_ce.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { outPutText.setText(""); } }); button_back.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String backSpace = null; if(outPutText.getText().length() > 0) { StringBuilder stringBuilder = new StringBuilder(outPutText.getText()); stringBuilder.deleteCharAt(outPutText.getText().length() - 1); backSpace = stringBuilder.toString(); outPutText.setText(backSpace); dec_textField_1.setText(backSpace); bin_textField.setText(backSpace); oct_textField.setText(backSpace); hex_textField.setText(backSpace); } } }); buttonPlusMinus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int operator = Integer.parseInt(String.valueOf(outPutText.getText())); operator = operator * (-1); outPutText.setText(String.valueOf(operator)); dec_textField_1.setText(String.valueOf(operator)); int A = Integer.parseInt(outPutText.getText()); bin_textField.setText(Integer.toString(A, 2)); int B = Integer.parseInt(outPutText.getText()); oct_textField.setText(Integer.toString(B, 8)); int C = Integer.parseInt(outPutText.getText()); hex_textField.setText(Integer.toString(C, 16)); } }); button_dec.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { button_2.setEnabled(true); button_3.setEnabled(true); button_4.setEnabled(true); button_5.setEnabled(true); button_6.setEnabled(true); button_7.setEnabled(true); button_8.setEnabled(true); button_9.setEnabled(true); button_A.setEnabled(false); button_B.setEnabled(false); button_C.setEnabled(false); button_D.setEnabled(false); button_E.setEnabled(false); button_F.setEnabled(false); } }); button_bin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { button_2.setEnabled(false); button_3.setEnabled(false); button_4.setEnabled(false); button_5.setEnabled(false); button_6.setEnabled(false); button_7.setEnabled(false); button_8.setEnabled(false); button_9.setEnabled(false); button_A.setEnabled(false); button_B.setEnabled(false); button_C.setEnabled(false); button_D.setEnabled(false); button_E.setEnabled(false); button_F.setEnabled(false); } }); button_oct.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { button_2.setEnabled(true); button_3.setEnabled(true); button_4.setEnabled(true); button_5.setEnabled(true); button_6.setEnabled(true); button_7.setEnabled(true); button_8.setEnabled(false); button_9.setEnabled(false); button_A.setEnabled(false); button_B.setEnabled(false); button_C.setEnabled(false); button_D.setEnabled(false); button_E.setEnabled(false); button_F.setEnabled(false); } }); button_hex.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { button_2.setEnabled(true); button_3.setEnabled(true); button_4.setEnabled(true); button_5.setEnabled(true); button_6.setEnabled(true); button_7.setEnabled(true); button_8.setEnabled(true); button_9.setEnabled(true); button_A.setEnabled(true); button_B.setEnabled(true); button_C.setEnabled(true); button_D.setEnabled(true); button_E.setEnabled(true); button_F.setEnabled(true); } }); buttonRightPara.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + buttonRightPara.getText(); outPutText.setText(inum); } }); buttonLeftPara.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inum = outPutText.getText() + buttonLeftPara.getText(); outPutText.setText(inum); } }); } private class SwingAction extends AbstractAction { public SwingAction() { putValue(NAME, "SwingAction"); putValue(SHORT_DESCRIPTION, "Some short description"); } public void actionPerformed(ActionEvent e) { } } }
true
bde5de6724b421fbbe67e3defdd4c1828b346531
Java
Piglet719/iThome
/code/SelectionSort.java
UTF-8
587
3.515625
4
[]
no_license
public class SelectionSort { public static void main(String[] args){ int[] arr = {41, 24, 97, 6, 19, 53, 78}; int n = arr.length; for(int i = 0 ; i < n-1 ; i++){ int min = i; for(int j = i+1 ; j < n ; j++){ if(arr[min] > arr[j]){ //找最小值 min = j; } } int t = arr[i]; //兩數交換 arr[i] = arr[min]; arr[min] = t; } for(int i = 0 ; i < n ; i++){ System.out.printf("%d ", arr[i]); } } }
true
108b8d8b7e892c1e7aec06c4c1241bb1d399c699
Java
sabex/udacity-project1
/starter/cloudstorage/src/main/java/com/udacity/jwdnd/course1/cloudstorage/services/FileService.java
UTF-8
1,736
2.6875
3
[]
no_license
package com.udacity.jwdnd.course1.cloudstorage.services; import com.udacity.jwdnd.course1.cloudstorage.mapper.FileMapper; import com.udacity.jwdnd.course1.cloudstorage.model.File; import com.udacity.jwdnd.course1.cloudstorage.model.User; import java.io.IOException; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @Service public class FileService { private FileMapper fileMapper; public FileService(FileMapper fileMapper) { this.fileMapper = fileMapper; } public int createFile(MultipartFile multipartFile, User user) throws IOException { // validate if (multipartFile.isEmpty()) { throw new RuntimeException("Choose a file before Uploading"); } if (isFileNameExists(user, multipartFile.getOriginalFilename())) { throw new RuntimeException( "File named " + multipartFile.getOriginalFilename() + " already exists."); } File file = File.builder() .fileName(multipartFile.getOriginalFilename()) .fileSize(String.valueOf(multipartFile.getSize())) .contentType(multipartFile.getContentType()) .fileData(multipartFile.getBytes()) .build(); return (fileMapper.insert(file, user)); } public List<File> getFiles(User user) { return fileMapper.getFiles(user); } public File getFile(User user, Integer fileId) { return fileMapper.getFile(user, fileId); } public boolean isFileNameExists(User user, String filename) { File file = fileMapper.getFileByName(user, filename); return (file != null); } public int deleteFile(Integer fileId, User user) { return fileMapper.delete(user, fileId); } }
true