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
10bb92a7b187d8f252325c03a31ef1b881b67e9d
Java
enjoyGroup/stockWeb
/stockApp/src/th/go/stock/app/enjoy/form/StockMovingReportForm.java
UTF-8
1,260
2.203125
2
[]
no_license
package th.go.stock.app.enjoy.form; import java.util.ArrayList; import java.util.List; import th.go.stock.app.enjoy.bean.ProductQuanHistoryBean; public class StockMovingReportForm { private ProductQuanHistoryBean productQuanHistoryBean; private String errMsg; private String titlePage; private List<ProductQuanHistoryBean> dataList; public StockMovingReportForm(){ this.productQuanHistoryBean = new ProductQuanHistoryBean(); this.errMsg = ""; this.titlePage = ""; this.dataList = new ArrayList<ProductQuanHistoryBean>(); } public ProductQuanHistoryBean getProductQuanHistoryBean() { return productQuanHistoryBean; } public void setProductQuanHistoryBean( ProductQuanHistoryBean productQuanHistoryBean) { this.productQuanHistoryBean = productQuanHistoryBean; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public String getTitlePage() { return titlePage; } public void setTitlePage(String titlePage) { this.titlePage = titlePage; } public List<ProductQuanHistoryBean> getDataList() { return dataList; } public void setDataList(List<ProductQuanHistoryBean> dataList) { this.dataList = dataList; } }
true
caf316d2b40fe993cdc77c776e211a2178771a6e
Java
gaborpolgar/myprojects
/GenericsDemo/src/hu/ak_akademia/genericsdemo/genericsDemo.java
UTF-8
615
2.703125
3
[]
no_license
package hu.ak_akademia.genericsdemo; public class genericsDemo { public static void main(String[] args) { Box<Integer> myNumberBox = new Box<>(); System.out.println(myNumberBox); myNumberBox.putIn(76); // myNumberBox.putIn("alma"); <---- fordítási idejű hibát ad System.out.println(myNumberBox); Integer theThingFromTheBox = myNumberBox.takeOut(); System.out.println(myNumberBox); Box<String> myFavouriteFourtuneCookieQuoteBox = new Box<>(); myFavouriteFourtuneCookieQuoteBox.putIn("Lucky one."); System.out.println(myFavouriteFourtuneCookieQuoteBox); } }
true
8e8594946e22b7074ce27271ed6d5587416fef11
Java
Nekorp/PrototipoWF
/src/main/java/org/nekorp/workflow/desktop/view/model/reporte/global/ParametrosReporteGlobalVB.java
UTF-8
1,500
1.859375
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2013 Nekorp * *Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package org.nekorp.workflow.desktop.view.model.reporte.global; import java.util.Date; import org.springframework.stereotype.Component; /** * */ @Component public class ParametrosReporteGlobalVB { private Date fechaInicial; private Date fechaFinal; private boolean ejecutar; public ParametrosReporteGlobalVB() { fechaInicial = new Date(); fechaFinal = new Date(); } public Date getFechaInicial() { return fechaInicial; } public void setFechaInicial(Date fechaInicial) { this.fechaInicial = fechaInicial; } public Date getFechaFinal() { return fechaFinal; } public void setFechaFinal(Date fechaFinal) { this.fechaFinal = fechaFinal; } public boolean isEjecutar() { return ejecutar; } public void setEjecutar(boolean ejecutar) { this.ejecutar = ejecutar; } }
true
451c2a15563bb13be49256edc24b0f97f5a2a172
Java
elimarcosarouca/imec
/ECM/VIDEO FONTE/modelo/src/main/java/br/fucapi/ads/modelo/dominio/UsuarioToken.java
UTF-8
2,020
2.0625
2
[]
no_license
package br.fucapi.ads.modelo.dominio; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "ECM_USUARIO_TOKEN") public class UsuarioToken extends AbstractEntity implements Serializable { private static final long serialVersionUID = -3197181642608086108L; @Id @GeneratedValue(generator = "SEQ_ECM_USUARIO_TOKEN", strategy = GenerationType.SEQUENCE) @SequenceGenerator(allocationSize = 1, initialValue = 1, sequenceName = "SEQ_ECM_USUARIO_TOKEN", name = "SEQ_ECM_USUARIO_TOKEN") @Column(name = "ID_ECM_USUARIO_TOKEN") private Long id; @Column(name = "token", nullable = false) private String token; @Column(name = "data_geracao") private Date dataGeracao; @Column(name = "username") private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Column(name = "utilizado") private Boolean utilizado; @Column(name = "data_utilizacao") private Date dataUtilizacao; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Date getDataGeracao() { return dataGeracao; } public void setDataGeracao(Date dataGeracao) { this.dataGeracao = dataGeracao; } public Boolean getUtilizado() { return utilizado; } public void setUtilizado(Boolean utilizado) { this.utilizado = utilizado; } public Date getDataUtilizacao() { return dataUtilizacao; } public void setDataUtilizacao(Date dataUtilizacao) { this.dataUtilizacao = dataUtilizacao; } }
true
0d13906151a66d6ecf120d81db1992cc15f7c8d8
Java
Dragberry/one-zero-one-backend
/ozo-backend/ozo-backend-web/src/main/java/org/dragberry/ozo/web/controllers/VersionCheckInterceptor.java
UTF-8
950
2.234375
2
[]
no_license
package org.dragberry.ozo.web.controllers; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dragberry.ozo.common.app.AppVersionChecker; import org.dragberry.ozo.web.exceptions.WrongAppVersionException; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class VersionCheckInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { @SuppressWarnings("rawtypes") Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); String appVersion = (String) pathVariables.get(AppVersionChecker.APP_VERSION_VARIABLE); if (AppVersionChecker.check(appVersion)) { return true; } throw new WrongAppVersionException(); } }
true
e1b79d399918ece2e268408754ca00d9cc433e15
Java
xq85782621/rabbitmq
/src/main/java/com/meizhi/rabbitmq/config/RabbitConfig.java
UTF-8
6,661
2.375
2
[]
no_license
package com.meizhi.rabbitmq.config; import com.meizhi.rabbitmq.topic.cousumer.WarningLogReceiver; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.connection.CorrelationData; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitConfig { /** * 另外一种消息处理机制的写法 */ @Autowired WarningLogReceiver warningLogReceiver; @Value("${spring.rabbitmq.host}") private String host; @Value("${spring.rabbitmq.port}") private int port; @Value("${spring.rabbitmq.username}") private String username; @Value("${spring.rabbitmq.password}") private String password; @Value("${spring.rabbitmq.virtual-host}") private String virtualHost; @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port); connectionFactory.setUsername(username); connectionFactory.setPassword(password); connectionFactory.setVirtualHost(virtualHost); connectionFactory.setPublisherConfirms(true); //发送者确认 return connectionFactory; } @Bean public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) { return new RabbitAdmin(connectionFactory); } @Bean public RabbitTemplate newRabbitTemplate() { RabbitTemplate template = new RabbitTemplate(connectionFactory()); template.setMandatory(true); template.setConfirmCallback(confirmCallback()); template.setReturnCallback(returnCallback()); return template; } //============================= 声明exchange ============================================================ @Bean public TopicExchange exchange() { TopicExchange topicExchange = new TopicExchange(RmConst.EXCHANGE_TOPIC_LOG); return topicExchange; } //============================= 声明 Queue ============================================================ /** * 声明队列的参数 * durable 是否持久化(队列的名字和属性持久化,不是消息) * exclusive 单消费者队列,这个队列只允许一个消费者消费 * autoDelete 自动删除过期的队列,具体控制在map中定义 * */ @Bean public Queue queueLogInfo() { return new Queue(RmConst.QUEUE_LOG_INFO); } @Bean public Queue queueLogError() { return new Queue(RmConst.QUEUE_LOG_ERROR); } @Bean public Queue queueLogWarning() { return new Queue(RmConst.QUEUE_LOG_WARNING); } //============================= queue通过routingKey绑定到exchange ============================================ @Bean public Binding bindingQueueLogInfo() { return BindingBuilder .bind(queueLogInfo()) .to(exchange()) .with(RmConst.LOG_INFO_KEY); } @Bean public Binding bindingQueueLogError() { return BindingBuilder .bind(queueLogError()) .to(exchange()) .with(RmConst.LOG_ERROR_KEY) ; } @Bean public Binding bindingQueueLogWarning() { return BindingBuilder .bind(queueLogWarning()) .to(exchange()) .with(RmConst.LOG_WARNING_KEY); } //===================================== 消费者的另一种写法 ====================================================== @Bean public SimpleMessageListenerContainer messageContainer() { //加载处理消息A的队列 SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory()); //设置接收多个队列里面的消息,这里设置接收队列A //假如想一个消费者处理多个队列里面的信息可以如下设置: //container.setQueues(queueA(),queueB(),queueC()); container.setQueues(queueLogWarning()); container.setExposeListenerChannel(true); //设置最大的并发的消费者数量 container.setMaxConcurrentConsumers(10); //最小的并发消费者的数量 container.setConcurrentConsumers(1); //设置确认模式手工确认 container.setAcknowledgeMode(AcknowledgeMode.MANUAL); container.setMessageListener(warningLogReceiver); return container; } //==================================== 生产者发送确认 =========================================================== @Bean public RabbitTemplate.ConfirmCallback confirmCallback() { return new RabbitTemplate.ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { if (ack) { System.err.println("发送者确认发送给mq成功"); } else { //处理失败的消息 System.err.println("发送者发送给mq失败,考虑重发:" + cause); } } }; } @Bean public RabbitTemplate.ReturnCallback returnCallback() { return new RabbitTemplate.ReturnCallback() { @Override public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) { System.err.println("无法路由的消息,需要考虑另外处理。"); System.err.println("Returned replyText:" + replyText); System.err.println("Returned exchange:" + exchange); System.err.println("Returned routingKey:" + routingKey); String msgJson = new String(message.getBody()); System.err.println("Returned Message:" + msgJson); } }; } }
true
5daab9ddcc328f05804593690e62c45f116bfe9f
Java
szh13818253048/Library
/src/com/sxt/dao/BookDao.java
GB18030
464
2
2
[]
no_license
package com.sxt.dao; import java.util.List; import com.sxt.pojo.Book; import com.sxt.pojo.User; public interface BookDao { /** * ûѯûϢ * @author szh13 * */ //ݿȡͼϢ List<Book> getBookInfoDao(); //ɾͼϢ int deleteBookInfoDao(int id); //ͼϢ int addBookInfoDao(String bid, String bname); //ؼ List<Book> searchlikeInfoDao(String key); }
true
a0eb296e871ef247a1f8d509a15d5c884b6f53aa
Java
huangjian888/jeeweb-mybatis-springboot
/x-restful/x-business-service/src/main/java/com/company/shop/sys/service/modules/sys/mapper/ProcedureConfigMapper.java
UTF-8
496
1.796875
2
[]
no_license
package com.company.shop.sys.service.modules.sys.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.company.shop.sys.service.modules.sys.entity.ProcedureConfigEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface ProcedureConfigMapper extends BaseMapper<ProcedureConfigEntity> { ProcedureConfigEntity getProcedureEntity(); ProcedureConfigEntity getProcedure(@Param("username") String username); }
true
82443f6c6df09b1683ea2f5a9530df0be2d8e4e9
Java
ixrjog/opscloud4
/opscloud-domain/src/main/java/com/baiyi/opscloud/domain/param/datasource/DsInstanceParam.java
UTF-8
2,434
1.789063
2
[ "Apache-2.0" ]
permissive
package com.baiyi.opscloud.domain.param.datasource; import com.baiyi.opscloud.domain.param.IExtend; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.Valid; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * @Author baiyi * @Date 2021/5/18 4:56 下午 * @Version 1.0 */ public class DsInstanceParam { @Data @NoArgsConstructor @Schema public static class AddDsConfig { private Integer id; private String name; private Integer dsType; private String version; private String kind; private Boolean isActive; private Integer credentialId; private String dsUrl; private String propsYml; private String comment; } @Data @NoArgsConstructor @Schema public static class UpdateDsConfig { private Integer id; private String name; private String uuid; private Integer dsType; private String version; private String kind; private Boolean isActive; private Integer credentialId; private String dsUrl; private String propsYml; private String comment; } @Data @Builder @AllArgsConstructor @NoArgsConstructor @Schema public static class DsInstanceQuery implements IExtend { @Schema(description = "数据源类型") private String instanceType; @Schema(description = "有效") @Builder.Default private Boolean isActive = true; private Boolean extend; } @Data @NoArgsConstructor @Schema public static class RegisterDsInstance { private Integer id; @Schema(description = "数据源实例名称") @Valid private String instanceName; private String uuid; @Schema(description = "数据源实例分类") private String kind; @Schema(description = "数据源实例类型") @Valid private String instanceType; @Schema(description = "数据源配置ID", example = "1") private Integer configId; @Schema(description = "父实例ID", example = "1") private Integer parentId; @Schema(description = "有效") private Boolean isActive; @Schema(description = "描述") private String comment; } }
true
af413fc17da5dcebd761b21cb6e00580e60c5dbf
Java
herniadlf/algo3
/src/mapa/FuenteDeRecurso.java
UTF-8
845
2.578125
3
[]
no_license
package src.mapa; import src.Dinero; import src.Recurso; public class FuenteDeRecurso implements Mapeable { protected String nombre; protected Recurso recurso; protected static final int RECURSOS_POR_TURNO = 10; public Recurso getRecurso(){ return recurso; } public FuenteDeRecurso(){ } public FuenteDeRecurso colocarContenido(){ return null; } public boolean esLoMismo(Mapeable aComparar){ return (this.getNombre() == aComparar.getNombre()); } public String getNombre() { return nombre; } public boolean esOcupable() { return false; } public boolean esTerrestre() { return true; } public boolean esAereo() { return false; } public Dinero extraer(){ return null; } }
true
ca994d829e0293beecf9901b45e33cde99f3661f
Java
furabio/tcc-back-end
/src/main/java/br/edu/fatecjahu/classroom/domain/model/Booking.java
UTF-8
760
2.1875
2
[]
no_license
package br.edu.fatecjahu.classroom.domain.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.time.LocalDate; @Entity @EqualsAndHashCode(callSuper = true) @Data @AllArgsConstructor @NoArgsConstructor @Table(name = "bookings") public class Booking extends AbstractEntity { @ManyToOne @JoinColumn(name = "user_id") private User user; @ManyToOne @JoinColumn(name = "classroom_id") private Classroom classroom; @ManyToOne @JoinColumn(name = "period_id") private Period period; @NotNull @Column(name = "booking_date") private LocalDate bookingDate; }
true
608a13118bb51b82a2603454bdbf0fe8f592756b
Java
zakkiibrahiim/Algoritmer_Dat
/src/HelloWorld.java
UTF-8
254
2.953125
3
[]
no_license
public class HelloWorld { public static void main (String[] args){ System.out.println("Hello World"); System.out.println("Teller til 10: "); for (int i = 1; i<=10; i++){ System.out.print(i+" "); } } }
true
79b2e2b2433c442befa6b949f04ffed926d4ef57
Java
anisuzzamanbabla/AndroidMVPBoot
/app/src/main/java/info/anisuzzaman/androidmvpboot/data/database/service/UserDatabaseService.java
UTF-8
546
2.03125
2
[]
no_license
package info.anisuzzaman.androidmvpboot.data.database.service; import java.util.Date; import info.anisuzzaman.androidmvpboot.data.database.callback.DataBaseCallBack; import info.anisuzzaman.androidmvpboot.data.database.entity.User; /** * Created by anisuzzaman on 19/9/20. */ public interface UserDatabaseService { void save(User user, DataBaseCallBack dataBaseCallBack); void load(String userLogin, DataBaseCallBack dataBaseCallBack); void hasUser(String userLogin, Date lastRefreshMax, DataBaseCallBack dataBaseCallBack); }
true
e49c3abd753b2d88d6d238b743827a85c959ce5c
Java
HM-Azijul/Java-Exercise
/Class & Object/Constructor.java
UTF-8
1,633
4.1875
4
[]
no_license
import java.util.Scanner; class add { int a,b; add() //default Constructor { a=0; b=0; } add (int x, int y)//Parameterized Constructor //same name as class; we take two variable(a,b) so parameter also two(x,y) { a=x; b=y; } void input() { Scanner sc=new Scanner(System.in); System.out.println("Enter 1st Number:"); a=sc.nextInt(); System.out.println("Enter 2nd Number:"); b=sc.nextInt(); } void display()//for show a & b value { System.out.println("a="+a +" b="+b); } void output() { int c; c=a+b; System.out.println("Addition="+c); } // public static void main(String[] args) // { // add aa=new add();//if not pass value - it goes default Constructor // aa.display(); // // aa.input(); // aa.output(); // // //Parameterized Constructor // add bb=new add(5,10); //its pass value/parameter - so it called parameter // bb.display(); // bb.output(); // // } } class Constructor { public static void main(String[] args) { add aa=new add();//if not pass value - it goes default Constructor aa.display(); aa.input(); aa.output(); //Parameterized Constructor add bb=new add(5,10); //its pass value/parameter - so it called parameter bb.display(); bb.input(); bb.output(); } }
true
9cad3fc51a27feec9f7b305876503ac402331fa9
Java
Tejinder/Jive-8-src-code
/main/java/com/grail/util/URLUtils.java
UTF-8
1,592
2.203125
2
[]
no_license
package com.grail.util; import javax.servlet.http.HttpServletRequest; import com.jivesoftware.community.JiveGlobals; import java.net.MalformedURLException; import java.net.URL; /** * Created with IntelliJ IDEA. * User: Bhakar * Date: 7/3/14 * Time: 6:20 PM * To change this template use File | Settings | File Templates. */ public class URLUtils { public static String getBaseURL(final HttpServletRequest request) { URL requestUrl; try { requestUrl = new URL(request.getRequestURL().toString()); String portString = requestUrl.getPort() == -1 ? "" : ":" + requestUrl.getPort(); return requestUrl.getProtocol() + "://" + requestUrl.getHost() + portString + request.getContextPath(); } catch (MalformedURLException e) { e.printStackTrace(); } return ""; } public static String getRSATokenBaseURL(final HttpServletRequest request) { String baseUrl = getBaseURL(request); if(baseUrl.contains("synchro_rkp")) { //baseUrl = JiveGlobals.getJiveProperty("rsaTokenURL","") + baseUrl; baseUrl = JiveGlobals.getJiveProperty("rsaTokenURL",""); } return baseUrl; } public static String getSecondBaseURL(String baseUrl) { String secondBaseUrl=""; if(baseUrl.contains("synchro_rkp")) { secondBaseUrl = JiveGlobals.getJiveProperty("jiveURL",""); } else { secondBaseUrl = JiveGlobals.getJiveProperty("rsaTokenURL",""); } return secondBaseUrl; } }
true
28fd2aa15bc8105edcce81bb5813b36717164439
Java
wang4856304/spring-cloud-gateway
/src/main/java/com/wj/CloudGatewayApp.java
UTF-8
2,650
1.75
2
[]
no_license
package com.wj; import com.zaxxer.hikari.pool.ProxyStatement; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.gateway.actuate.GatewayControllerEndpoint; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter; import org.springframework.cloud.gateway.filter.factory.RequestRateLimiterGatewayFilterFactory; import org.springframework.cloud.gateway.handler.RoutePredicateHandlerMapping; import org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory; import org.springframework.cloud.gateway.handler.predicate.RoutePredicateFactory; import org.springframework.cloud.gateway.route.CompositeRouteDefinitionLocator; import org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Bean; import org.springframework.core.Ordered; import java.util.LinkedList; import java.util.List; /** * @author jun.wang * @title: CloudGatewayApp * @projectName ownerpro * @description: TODO * @date 2019/5/7 16:20 */ @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, LiquibaseAutoConfiguration.class}) @EnableDiscoveryClient public class CloudGatewayApp { public static void main(String args[]) { //PathRoutePredicateFactory SpringApplication.run(CloudGatewayApp.class, args); //RouteDefinitionRouteLocator //RequestRateLimiterGatewayFilterFactory //RoutePredicateHandlerMapping //GatewayFilter //Ordered //GlobalFilter List<String> list = new LinkedList<>(); list.add(""); //NettyWriteResponseFilter } /*@Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("", r -> r.path("/test/**") .uri("http://localhost:9820/test/testRes") .uri("http://localhost:9820/test/testJpa") ) .build(); }*/ }
true
8138bb5cb3fccacf6fd65886f9047a120a641625
Java
tamirncode/NanitBday
/NanitBirthday/app/src/main/java/com/birthday/nanit/nanitbirthday/NanitSharedPref.java
UTF-8
327
1.695313
2
[]
no_license
package com.birthday.nanit.nanitbirthday; import android.content.Context; import android.content.SharedPreferences; /** * Shared Preferences editor. */ class NanitSharedPref { public static final String NAME = "name"; public static final String BDAY = "bday"; public static final String PIC_URL = "picUrl"; }
true
c0587b87d73a5892b96e66ef4e15e4737f63779a
Java
zzzhouzhong/dhcc
/src/com/dhcc/ProductActivity.java
UTF-8
6,299
1.960938
2
[]
no_license
package com.dhcc; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONException; import org.json.JSONObject; import com.dhcc.utils.Utils; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; public class ProductActivity extends Activity implements OnClickListener { private static final int RESULT_OK = 0; private String barCodeNum; private TextView jingxiaosang, dingdanhao, dingdanleixing, waibudingdanhao, tuhao, lingjianzhongwenming, tiaoxingma, shuliang, cangwei, rukushijian, chaxun; private ProgressBar progressbar; private EditText saotiaoma; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case RESULT_OK: progressbar.setVisibility(View.GONE); if (msg.obj == null) return; JSONObject data = (JSONObject) msg.obj; showInfo(data); break; default: break; } } private void showInfo(JSONObject data) { try { if (data.getInt("returncode") == 1) { Utils.printToast(ProductActivity.this, "查无此码"); } else { data = data.getJSONObject("daya"); jingxiaosang.setText(getResources().getString(R.string.waibudingdanhao) + data.getString("user_id")); dingdanhao.setText(getResources().getString(R.string.dingdanhao) + data.getString("code_no")); dingdanleixing.setText(getResources().getString(R.string.dingdanleixing) + data.getString("product_category_id")); waibudingdanhao.setText(getResources().getString(R.string.waibudingdanhao) + data.getString("id")); tuhao.setText(getResources().getString(R.string.tuhao) + data.getString("product_id")); lingjianzhongwenming.setText(getResources().getString(R.string.lingjianzhongwenming) + data.getString("product_name")); tiaoxingma.setText(getResources().getString(R.string.tiaoxingma) + data.getString("product_code")); shuliang.setText(getResources().getString(R.string.shuliang) + data.getString("product_num")); cangwei.setText(getResources().getString(R.string.cangwei) + data.getString("id")); rukushijian.setText(getResources().getString(R.string.rukushijian) + data.getString("add_time")); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_product); saotiaoma = (EditText) findViewById(R.id.saotiaoma_result); chaxun = (TextView) findViewById(R.id.chaxun); chaxun.setOnClickListener(this); progressbar = (ProgressBar) findViewById(R.id.prgressbar); Intent intent = getIntent(); barCodeNum = intent.getStringExtra("BarCodeNum"); saotiaoma.setText(barCodeNum); findViewById(R.id.back).setOnClickListener(this); // barCodeNum = "7688164"; jingxiaosang = (TextView) findViewById(R.id.jingxiaosang); dingdanhao = (TextView) findViewById(R.id.dingdanhao); dingdanleixing = (TextView) findViewById(R.id.dingdanleixing); waibudingdanhao = (TextView) findViewById(R.id.waibudingdanhao); tuhao = (TextView) findViewById(R.id.tuhao); lingjianzhongwenming = (TextView) findViewById(R.id.lingjianzhongwenming); tiaoxingma = (TextView) findViewById(R.id.tiaoxingma); shuliang = (TextView) findViewById(R.id.shuliang); cangwei = (TextView) findViewById(R.id.cangwei); rukushijian = (TextView) findViewById(R.id.rukushijian); } private void startRequestInfo() { progressbar.setVisibility(View.VISIBLE); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub requestDetailedInfo(); } }).start(); } protected void requestDetailedInfo() { // TODO Auto-generated method stub if (TextUtils.isEmpty(barCodeNum) || barCodeNum.contains("w")) { return; } String path = "http://114.215.172.39/api/getProductInfo.php"; // String path = "http://114.215.172.39/api/updateStatus.php"; try { JSONObject data = new JSONObject(); barCodeNum = saotiaoma.getText().toString().trim(); if (TextUtils.isEmpty(barCodeNum)) { Utils.printToast(ProductActivity.this, "条码为空"); return; } Log.i("this", barCodeNum + ""); // barCodeNum = "0001"; data.put("product_code", barCodeNum); // data.put("flag", 1); Log.i("this", data.toString()); InputStream is = null; OutputStream os = null; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(50000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); os = conn.getOutputStream(); os.write(data.toString().getBytes()); int code = conn.getResponseCode(); if (code == 200) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); is = conn.getInputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = is.read(buf)) > -1) { bos.write(buf, 0, len); } JSONObject result = new JSONObject(bos.toString()); mHandler.obtainMessage(RESULT_OK, result).sendToTarget(); Log.i("this", result.toString()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onClick(View v) { // TODO Auto-generated method stub int id = v.getId(); switch (id) { case R.id.back: finish(); break; case R.id.chaxun: startRequestInfo(); break; default: break; } } }
true
f82794d3545a9d576eaed46f223a93270cfbb7e5
Java
nazi1992/erupt
/src/main/java/com/example/demo/example/aqs/CountDownlatchExample1.java
UTF-8
1,254
3.265625
3
[]
no_license
package com.example.demo.example.aqs; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by Administrator on 2018/12/7 0007. * 计数器 */ public class CountDownlatchExample1 { private static int ThreadNum = 200; public static void main(String[] args) throws Exception{ CountDownLatch countDownLatch = new CountDownLatch(ThreadNum); ExecutorService executorService = Executors.newCachedThreadPool(); for(int i=0;i<ThreadNum;i++) { final int count = i; executorService.execute(()->{ try { test(count); } catch (Exception e) { e.printStackTrace(); }finally { countDownLatch.countDown();//计数减1 } }); } countDownLatch.await();//能保证所有的线程执行完毕,再执行下面的finish System.out.println("finish"); executorService.shutdown();//释放资源 } private static void test(int i) throws Exception{ Thread.sleep(100); System.out.println("i="+i); Thread.sleep(100); } }
true
75c0906aa875d4579c32dda209de50cc869a5b31
Java
HyeonJung/lolhuni
/src/main/java/com/hj/lolhuni/model/lol/match/TeamBansDto.java
UTF-8
216
1.5625
2
[]
no_license
package com.hj.lolhuni.model.lol.match; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class TeamBansDto { private int pickTurn; private int championId; }
true
e68744f13cc42c89c058a55fcd15a8e9ae47ad71
Java
carloscaceresochoa/misiontic-modulo-java-sesion4
/src/Ejercicio2.java
UTF-8
1,367
3.09375
3
[]
no_license
import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author DELL */ public class Ejercicio2 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here doctorStrangeZonaOscura(); } public static void doctorStrangeZonaOscura(){ Scanner teclado=new Scanner(System.in); int cont=0; char aceptar='n'; while(aceptar!='s'){ System.out.println("Doctor Strange: Dormamu Vengo hacer un trato"); System.out.println("Aceptas mi Condición"); aceptar=teclado.nextLine().charAt(0); if(aceptar!='s'){ System.out.println("Doctor Strange Muere"); cont++; } if(cont==3){ System.out.println("Dormamu: Liberare de este Bucle"); System.out.println("Te traje un poco de mi dimension el " + "tiempo"); } } System.out.println("Doctor Strange Vuelve a su Dimensión y" + " libero a dormamu del bucle tiempo"); } }
true
74b8a4239caf69f5f2cc2c80e0ed1982dc78f6ab
Java
Mouchel-Remy/framework
/TD2/TD2/src/main/java/s4/spring/TD2/controllers/OrganizationController.java
UTF-8
2,277
2.25
2
[]
no_license
package s4.spring.TD2.controllers; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.view.RedirectView; import s4.spring.TD2.entities.Organization; import s4.spring.TD2.repository.OrgasRepository; @Controller @RequestMapping("/orgas/") public class OrganizationController { @Autowired private OrgasRepository orgasRepo; @GetMapping({"","index"}) public String index(Model model) { List<Organization> orgas = orgasRepo.findAll(); model.addAttribute("orgas",orgas); return "index"; } @PostMapping("submit/{id}") public RedirectView submit(@PathVariable int id,Organization postedorga) { Optional<Organization> opt = orgasRepo.findById(id); if(opt.isPresent()) { Organization orga = opt.get(); copyFrom(postedorga,orga); orgasRepo.save(orga); } return new RedirectView("/orgas/"); } @PostMapping("submit") public RedirectView submit_(Organization postedOrga) { if(postedOrga.getId() != 0) { int id = postedOrga.getId(); Optional<Organization> opt = orgasRepo.findById(id); if(opt.isPresent()) { Organization orga = opt.get(); copyFrom(postedOrga,orga); orgasRepo.save(orga); } else { return new RedirectView("/orgas/"); } }else { } return null; } private void copyFrom(Organization source,Organization dest) { dest.setName(source.getName()); dest.setDomain(source.getDomain()); dest.setCity(source.getCity()); dest.setAlisases(source.getAlisases()); } @GetMapping("new") public String frmnew(Model model) { model.addAttribute("orga",new Organization()); return "orgas/frm"; } @GetMapping("edit/{id}") public String frmEdit(@PathVariable int id,Model model) { Optional<Organization> opt = orgasRepo.findById(id); if(opt.isPresent()) { model.addAttribute("orga",opt.get()); return "orgas/frm"; } return "/orgas/404"; } }
true
20b3961bb32f4827eaecf79fd333bc157ff57601
Java
navikt/data-catalog-policies
/data-catalog-policies-app/src/main/java/no/nav/data/catalog/policies/app/common/exceptions/DataCatalogPoliciesTechnicalException.java
UTF-8
743
2.265625
2
[ "MIT" ]
permissive
package no.nav.data.catalog.policies.app.common.exceptions; import lombok.Getter; import org.springframework.http.HttpStatus; @Getter public class DataCatalogPoliciesTechnicalException extends RuntimeException { private final HttpStatus httpStatus; public DataCatalogPoliciesTechnicalException(String message) { super(message); this.httpStatus = HttpStatus.OK; } public DataCatalogPoliciesTechnicalException(String message, Throwable cause) { super(message, cause); this.httpStatus = HttpStatus.OK; } public DataCatalogPoliciesTechnicalException(String message, Throwable cause, HttpStatus httpStatus) { super(message, cause); this.httpStatus = httpStatus; } }
true
4c71a49e5ce0217b8ed0c38fdfe0949814398b8d
Java
Vlavros/JavaAulas
/JavaAulas/src/br/com/vlavros/exercicios/homework/mensagem/TesteMensagem.java
UTF-8
634
2.640625
3
[]
no_license
package br.com.vlavros.exercicios.homework.mensagem; public class TesteMensagem { public static void main(String[] args) { Mensagem msg1 = new MensagemTexto("[email protected]","[email protected]","Titulo da Mensagem de Texto","TEXTO TEXTO TEXTO TEXTO TEXTO"); msg1.tocar(); //msg1.enviarMensagem(); Mensagem msg2 = new MensagemVoz("[email protected]","[email protected]","Titulo da Mensagem de Voz","AUDIO AUDIO AUDIO AUDIO"); msg2.tocar(); //msg2.enviarMensagem(); Mensagem msg3 = new MensagemVideo("[email protected]","[email protected]","Titulo da Mensagem de Video","VIDEO VIDEO VIDEO VIDEO"); msg3.tocar(); //msg3.enviarMensagem(); } }
true
fc3b5eb844622558c4badfc716edbe8234dd388c
Java
Hitonoriol/MadSand
/core/src/hitonoriol/madsand/gui/stages/VFXStage.java
UTF-8
962
2.28125
2
[]
no_license
package hitonoriol.madsand.gui.stages; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.utils.viewport.Viewport; import hitonoriol.madsand.vfx.ShaderManager; public class VFXStage extends Stage { private ShaderManager shaderManager; public VFXStage(Viewport viewport) { super(viewport); shaderManager = new ShaderManager(getBatch()); shaderManager.setEnabledByDefault(true); } @Override public void draw() { Camera camera = getViewport().getCamera(); camera.update(); var root = getRoot(); if (!root.isVisible()) return; var batch = getBatch(); batch.setProjectionMatrix(camera.combined); shaderManager.begin(); root.draw(batch, 1); shaderManager.end(); } public ShaderManager getShaderManager() { return shaderManager; } @Override public void dispose() { super.dispose(); shaderManager.dispose(); } }
true
9e13b4f4e8bf55cd615eda7921783970c9ef73c5
Java
pikingdom/MyProject001
/huaweiguide/src/main/java/com/adapter/honoradapter/view/SimCarView.java
UTF-8
4,407
2.015625
2
[]
no_license
package com.adapter.honoradapter.view; import android.content.Context; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.adapter.honoradapter.util.UIUtil; import com.huawei.hwstartupguide.ChangeViewInterface; import com.huawei.hwstartupguide.R; import com.huawei.hwstartupguide.ui.wifi.NavigationVisibilityChange; /** * Created by xuqunxing on 2017/7/20. */ public class SimCarView extends RelativeLayout implements View.OnClickListener,NavigationVisibilityChange { private ChangeViewInterface changeViewInterface; private TextView mPrevBtn; private TextView mNextBtn; private RelativeLayout buttonBar; public SimCarView(Context context) { super(context); } public SimCarView(Context context, AttributeSet attrs) { this(context, attrs,0); } public SimCarView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); } public SimCarView(Context context, ChangeViewInterface changeViewInterface1) { super(context); changeViewInterface = changeViewInterface1; initView(); } private void initView() { View.inflate(getContext(), R.layout.view_sim_car,this); setLogoViewHeight(); initButtonBar(); } protected void initButtonBar() { buttonBar = (RelativeLayout) findViewById(R.id.button_bar); mPrevBtn = (TextView) findViewById(R.id.prev_btn); mPrevBtn.setVisibility(View.VISIBLE); mPrevBtn.setText(getContext().getString(R.string.back_format)); mNextBtn = (TextView) findViewById(R.id.next_btn); mNextBtn.setVisibility(View.VISIBLE); mNextBtn.setText(getContext().getString(R.string.skip_format)); mPrevBtn.setOnClickListener(this); mNextBtn.setOnClickListener(this); } private void setLogoViewHeight() { View logoView = findViewById(R.id.logo_view); View simLogo = findViewById(R.id.sim_logo); if (logoView != null && simLogo != null) { DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); int logoViewHeight; if (!UIUtil.isPadScreenDevice(getContext())) { logoViewHeight = (displayMetrics.widthPixels * 4) / 5; logoView.getLayoutParams().height = logoViewHeight; ((LinearLayout.LayoutParams) simLogo.getLayoutParams()).topMargin = (logoViewHeight * 4) / 25; } else if (UIUtil.isLandScreen(getContext())) { logoViewHeight = (displayMetrics.widthPixels * 268) / 1000; logoView.getLayoutParams().height = logoViewHeight; ((LinearLayout.LayoutParams) simLogo.getLayoutParams()).topMargin = (logoViewHeight * 13) / 100; } else { logoViewHeight = (displayMetrics.widthPixels * 62) / 100; logoView.getLayoutParams().height = logoViewHeight; ((LinearLayout.LayoutParams) simLogo.getLayoutParams()).topMargin = (logoViewHeight * 38) / 100; } } } @Override public void onClick(View view) { if(view == mPrevBtn){ if(changeViewInterface != null){ changeViewInterface.setCurrentlyShowView(ChangeViewInterface.LANGUAGE_VIEW); } }else if(view == mNextBtn){ if(changeViewInterface != null){ changeViewInterface.setCurrentlyShowView(ChangeViewInterface.PROTOCOL_VIEW); } } } public void onBackPressed() { if(changeViewInterface != null){ changeViewInterface.setCurrentlyShowView(ChangeViewInterface.LANGUAGE_VIEW); } } @Override public void NavigationVisibilityChangeState(boolean isShow) { FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) buttonBar.getLayoutParams(); float currentDensity = getContext().getResources().getDisplayMetrics().density; int margin = (int)(30 * currentDensity + 0.5F); if (isShow){ lp.bottomMargin = margin; }else{ lp.bottomMargin = 0; } buttonBar.setLayoutParams(lp); requestLayout(); } }
true
a470b8ef2f19d6b3cbf19eb9eb419d104f835b24
Java
codingsf/source_code
/TP/admin2.0/src/main/java/cn/fintechstar/admin/model/group/TimePeriod.java
UTF-8
944
2.28125
2
[]
no_license
package cn.fintechstar.admin.model.group; import com.google.gson.annotations.SerializedName; public class TimePeriod { @SerializedName("groupid") private int groupId; // Here groupTCId and groupId are combined and work as composite key private int period; @SerializedName("profitpercentage") private int profitPercentage; public int getGroupId() { return groupId; } public void setGroupId(int groupId) { this.groupId = groupId; } public int getPeriod() { return period; } public void setPeriod(int period) { this.period = period; } public int getProfitPercentage() { return profitPercentage; } public void setProfitPercentage(int profitPercentage) { this.profitPercentage = profitPercentage; } @Override public String toString() { return "TimePeriod [groupId=" + groupId + ", period=" + period + ", profitPercentage=" + profitPercentage + "]"; } }
true
188e340971209192d585906ebd99069350d19e6b
Java
wasilzafar/scholarwebapp
/src/in/scholarreport/struts2/DAO/ReportDAO.java
UTF-8
28,111
2.3125
2
[]
no_license
package in.scholarreport.struts2.DAO; import in.scholarreport.struts2.DTO.DepartmentDTO; import in.scholarreport.struts2.DTO.FacultyDTO; import in.scholarreport.struts2.DTO.MonthlyReportDTO; import in.scholarreport.struts2.DTO.QuarterlyReportDTO; import in.scholarreport.struts2.DTO.ScholarDTO; import in.scholarreport.struts2.DTO.SupervisorDTO; import in.scholarreport.struts2.util.CommonConstants; import in.scholarreport.struts2.util.CommonUtilities; import in.scholarreport.struts2.util.SQLQueries; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.log4j.Logger; public class ReportDAO extends BaseDAO { static Logger logger = Logger.getLogger(ReportDAO.class); public boolean checkExistingMonthlyReport(MonthlyReportDTO newMReport) { return false; } public boolean persistMonthlyReport(MonthlyReportDTO newMReport) { java.sql.Connection conn = getConnection(); boolean persisted = false; try { logger.info("Persisting monthly report "); PreparedStatement stmnt = conn .prepareStatement(SQLQueries.PERSIST_NEW_MONTHLYREPORT); stmnt.setString(1, newMReport.getMreportid() ); stmnt.setDate(2, CommonUtilities.getSQLDate(newMReport.getFromDate())); stmnt.setDate(3, CommonUtilities.getSQLDate(newMReport.getToDate())); stmnt.setString(4, newMReport.getWorkCompleted()); stmnt.setInt(5, newMReport.getLeaves()); stmnt.setString(6, newMReport.getAttachmentFileName()); stmnt.setString(7, newMReport.getStatus()); stmnt.setString(8, newMReport.getScholar().getScholarID()); stmnt.setDate(9, new java.sql.Date(new java.util.Date().getTime())); stmnt.setDate(10, new java.sql.Date(new java.util.Date().getTime())); if (stmnt.executeUpdate() > 0){ logger.info("Monthly report persisted successfully"); persisted = true; } else logger.info("There was some error while persisting monthly report "); persisted = true; } catch (Exception e) { logger.info("Error while persisting monthly report " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return persisted; } public boolean checkExistingQuarterlyReport(QuarterlyReportDTO newQReport) { return false; } public boolean persistQuarterlyReport(QuarterlyReportDTO newQReport) { java.sql.Connection conn = getConnection(); boolean persisted = false; try { PreparedStatement stmnt = conn.prepareStatement(SQLQueries.PERSIST_NEW_QUARTERLYREPORT); stmnt.setString(1, newQReport.getQreportid()); stmnt.setDate(2, CommonUtilities.getSQLDate(newQReport.getFromDate())); stmnt.setDate(3, CommonUtilities.getSQLDate(newQReport.getToDate())); stmnt.setString(4, newQReport.getWorkCompleted()); stmnt.setString(5, newQReport.getAttachmentFileName()); stmnt.setString(6, newQReport.getStatus()); stmnt.setString(7, newQReport.getScholar().getScholarID()); stmnt.setDate(8, new java.sql.Date(new java.util.Date().getTime())); stmnt.setDate(9, new java.sql.Date(new java.util.Date().getTime())); if (stmnt.executeUpdate() > 0){ logger.info("Quarterly report persisted successfully"); persisted = true; } else logger.info("There was some error while persisting quarterly report "); persisted = true; }catch (Exception e) { logger.info("Error while persisting quarterly report "+ e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return persisted; } public List getQuarterlyReportsBySupervisorID(String supID) { Connection conn = getConnection(); ResultSet rs; List reps = new ArrayList(); QuarterlyReportDTO rep; ScholarDTO sch; try { logger.info("Retrieving quarterly reports by supervisor ID "+ supID); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_QUARTERLYREPORT_BY_SUPERVISOR_ID); stmnt.setString(1,supID); rs = stmnt.executeQuery(); while(rs.next()){ rep = new QuarterlyReportDTO(); sch = new ScholarDTO(); sch.setScholarID(rs.getString(1)); sch.setScholarFirstName(rs.getString(2)); sch.setScholarMiddleName(rs.getString(3)); sch.setScholarLastName(rs.getString(4)); rep.setQreportid(rs.getString(5)); rep.setFromDate(rs.getDate(6).toString()); rep.setToDate(rs.getDate(7).toString()); rep.setStatus(rs.getString(8)); rep.setScholar(sch); reps.add(rep); } logger.info("Retrieved quarterly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving monthly reports by supervisor ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public String approveMonthlyReportsById(String[] ids, String status) { boolean allApproved = false; java.sql.Connection conn = getConnection(); String idStr = CommonUtilities.getStringFromArray(ids); StringBuffer query = new StringBuffer(SQLQueries.UPDATE_STATUS_MONTHLYREPORTS_BY_ID); logger.info("String of ids : "+idStr); try { logger.info("Approve monthly reports by IDs" + idStr); Statement stmnt = conn.createStatement(); query.replace(query.indexOf("?"), query.indexOf("?")+1, "'"+status+"'"); query.replace(query.indexOf("?"), query.indexOf("?")+1, idStr); logger.info("Query for approval : "+query.toString()); if(stmnt.executeUpdate(query.toString()) == ids.length){ logger.info("All monthly reports approved for " + idStr); allApproved = true; } else logger.info("There was some error while approving monthly reports " + idStr); } catch (SQLException e) { logger.error("Error while approving monthly reports " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return String.valueOf(allApproved); } public String deleteMonthlyReportsById(String[] ids) { boolean allDeleted = false; java.sql.Connection conn = getConnection(); String idStr = CommonUtilities.getStringFromArray(ids); StringBuffer query = new StringBuffer(SQLQueries.DELETE_MONTHLYREPORTS_BY_ID); try { logger.info("Deleting monthly reports for IDs "+idStr); Statement stmnt = conn.createStatement(); query.replace(query.indexOf("?"), query.indexOf("?")+1, idStr); logger.info("Query for deletion : "+query.toString()); if(stmnt.executeUpdate(query.toString()) == ids.length){ logger.info("Deleted all monthly reports for "+idStr); allDeleted = true; } else logger.info("There was some error while monthly report deletion "+idStr); } catch (SQLException e) { logger.error("Error while deleting monthly reports " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return String.valueOf(allDeleted); } public String approveQuarterlyReportsById(String[] ids, String status) { boolean allApproved = false; java.sql.Connection conn = getConnection(); String idStr = CommonUtilities.getStringFromArray(ids); StringBuffer query = new StringBuffer(SQLQueries.UPDATE_STATUS_QUARTERLYREPORTS_BY_ID); try { logger.info("Approve quarterly reports by IDs" + idStr); Statement stmnt = conn.createStatement(); query.replace(query.indexOf("?"), query.indexOf("?")+1, "'"+status+"'"); query.replace(query.indexOf("?"), query.indexOf("?")+1, idStr); logger.info("Query for approval : "+query.toString()); if(stmnt.executeUpdate(query.toString()) == ids.length){ logger.info("All quarterly reports approved for " + idStr); allApproved = true; } else logger.info("There was some error while approving quarterly reports " + idStr); } catch (SQLException e) { logger.error("Error while approving quarterly reports " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return String.valueOf(allApproved); } public String deleteQuarterlyReportsById(String[] ids) { boolean allDeleted = false; java.sql.Connection conn = getConnection(); String idStr = CommonUtilities.getStringFromArray(ids); StringBuffer query = new StringBuffer(SQLQueries.DELETE_QUARTERLYREPORTS_BY_ID); try { logger.info("Deleting quarterly reports for IDs "+idStr); Statement stmnt = conn.createStatement(); query.replace(query.indexOf("?"), query.indexOf("?")+1, idStr); logger.info("Query for deletion : "+query.toString()); if(stmnt.executeUpdate(query.toString()) == ids.length){ logger.info("Deleted all quarterly reports for "+idStr); allDeleted = true; } else logger.info("There was some error while quarterly report deletion "+idStr); } catch (SQLException e) { logger.error("Error while deleting quarterly reports " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return String.valueOf(allDeleted); } public List getMonthlyReportsByScholarID(String schID) { Connection conn = getConnection(); ResultSet rs; List reps = new ArrayList(); MonthlyReportDTO rep; ScholarDTO sch; try { logger.info("Retrieving quarterly reports by scholar ID "+ schID); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_MONTHLYREPORT_BY_SCHOLAR_ID); stmnt.setString(1,schID); rs = stmnt.executeQuery(); while(rs.next()){ rep = new MonthlyReportDTO(); rep.setMreportid(rs.getString(1)); rep.setFromDate(rs.getDate(2).toString()); rep.setToDate(rs.getDate(3).toString()); rep.setStatus(rs.getString(4)); reps.add(rep); } logger.info("Retrieved monthly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving monthly reports by scholar ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public List getQuarterlyReportsByScholarID(String schID) { Connection conn = getConnection(); ResultSet rs; List reps = new ArrayList(); QuarterlyReportDTO rep; ScholarDTO sch; try { logger.info("Retrieving quarterly reports by scholar ID "+ schID); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_QUARTERLYREPORT_BY_SCHOLAR_ID); stmnt.setString(1,schID); rs = stmnt.executeQuery(); while(rs.next()){ rep = new QuarterlyReportDTO(); rep.setQreportid(rs.getString(1)); rep.setFromDate(rs.getDate(2).toString()); rep.setToDate(rs.getDate(3).toString()); rep.setStatus(rs.getString(4)); reps.add(rep); } logger.info("Retrieved quarterly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving quarterly reports by scholar ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public MonthlyReportDTO getMonthlyReportByID(String id) { Connection conn = getConnection(); ResultSet rs; MonthlyReportDTO rep = null; ScholarDTO sch = null; SupervisorDTO sup = null; DepartmentDTO dep = null; try { logger.info("Retrieving moonthlyly report by report ID "+ id); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_MONTHLYREPORT_BY_ID); stmnt.setString(1,id); rs = stmnt.executeQuery(); while(rs.next()){ rep = new MonthlyReportDTO(); sch = new ScholarDTO(); sup = new SupervisorDTO(); dep = new DepartmentDTO(); sch.setScholarFirstName(rs.getString(1)); sch.setScholarMiddleName(rs.getString(2)); sch.setScholarLastName(rs.getString(3)); dep.setDepartmentname(rs.getString(4)); sup.setSupervisorFirstName(rs.getString(5)); sup.setSupervisorMiddleName(rs.getString(6)); sup.setSupervisorLastName(rs.getString(7)); sch.setDateOfRegistration(rs.getDate(8).toString()); rep.setFromDate(rs.getDate(9).toString()); rep.setToDate(rs.getDate(10).toString()); sch.setTopic(rs.getString(11)); rep.setLeaves(rs.getInt(12)); rep.setStatus(rs.getString(13)); rep.setMreportid(rs.getString(14)); rep.setWorkCompleted(rs.getString(15)); rep.setAttachmentFileName(rs.getString(16)); sch.setDepartment(dep); sch.setSupervisor(sup); rep.setScholar(sch); } logger.info("Retrieved monthly report "); } catch (SQLException e) { logger.error("Error while retrieving monthly report by ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return rep; } public QuarterlyReportDTO getQuarterlyReportByID(String id) { Connection conn = getConnection(); ResultSet rs; QuarterlyReportDTO rep = null; ScholarDTO sch = null; SupervisorDTO sup = null; DepartmentDTO dep = null; try { logger.info("Retrieving quarterly report by report ID "+ id); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_QUARTERLYREPORT_BY_ID); stmnt.setString(1,id); rs = stmnt.executeQuery(); while(rs.next()){ rep = new QuarterlyReportDTO(); sch = new ScholarDTO(); sup = new SupervisorDTO(); dep = new DepartmentDTO(); sch.setScholarFirstName(rs.getString(1)); sch.setScholarMiddleName(rs.getString(2)); sch.setScholarLastName(rs.getString(3)); dep.setDepartmentname(rs.getString(4)); sup.setSupervisorFirstName(rs.getString(5)); sup.setSupervisorMiddleName(rs.getString(6)); sup.setSupervisorLastName(rs.getString(7)); sch.setDateOfRegistration(rs.getDate(8).toString()); rep.setFromDate(rs.getDate(9).toString()); rep.setToDate(rs.getDate(10).toString()); sch.setTopic(rs.getString(11)); rep.setStatus(rs.getString(12)); rep.setQreportid(rs.getString(13)); rep.setWorkCompleted(rs.getString(14)); rep.setAttachmentFileName(rs.getString(15)); sch.setDepartment(dep); sch.setSupervisor(sup); rep.setScholar(sch); } logger.info("Retrieved quarterly report "); } catch (SQLException e) { logger.error("Error while retrieving quarterly report by ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return rep; } public String getMRFileContentDisposition(String id) { java.sql.Connection conn = getConnection(); String fd = null; ResultSet rs = null; try { logger.info("File disposition for monthly report id " + id); PreparedStatement stmnt = conn .prepareStatement(SQLQueries.FILE_DISPOSITION_MONTHLYREPORT); stmnt.setString(1, id); rs = stmnt.executeQuery(); while(rs.next()){ fd = rs.getString(1); } logger.info("Found file disposition as : " + fd); } catch (Exception e) { logger.info("Error while persisting monthly report " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return fd; } public String getQRFileContentDisposition(String id) { java.sql.Connection conn = getConnection(); String fd = null; ResultSet rs = null; try { logger.info("File disposition for quarterly report id " + id); PreparedStatement stmnt = conn .prepareStatement(SQLQueries.FILE_DISPOSITION_QUARTERLYREPORT); stmnt.setString(1, id); rs = stmnt.executeQuery(); while(rs.next()){ fd = rs.getString(1); } logger.info("Found file disposition as : " + fd); } catch (Exception e) { logger.info("Error while persisting quarterly report " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return fd; } public List getMonthlyReportsBySupervisorID(String supID) { Connection conn = getConnection(); ResultSet rs; MonthlyReportDTO rep; List reps = new ArrayList(); ScholarDTO sch; try { logger.info("Retrieving monthly reports by supervisor ID "+ supID); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_MONTHLYREPORT_BY_SUPERVISOR_ID); stmnt.setString(1,supID); rs = stmnt.executeQuery(); while(rs.next()){ rep = new MonthlyReportDTO(); sch = new ScholarDTO(); sch.setScholarID(rs.getString(1)); sch.setScholarFirstName(rs.getString(2)); sch.setScholarMiddleName(rs.getString(3)); sch.setScholarLastName(rs.getString(4)); rep.setMreportid(rs.getString(5)); rep.setFromDate(rs.getDate(6).toString()); rep.setToDate(rs.getDate(7).toString()); rep.setStatus(rs.getString(8)); rep.setScholar(sch); reps.add(rep); } logger.info("Retrieved monthly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving monthly reports by supervisor ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public List getMonthlyReports() { Connection conn = getConnection(); ResultSet rs; MonthlyReportDTO rep; List reps = new ArrayList(); ScholarDTO sch; try { logger.info("Retrieving all monthly reports by supervisor ID "); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_MONTHLYREPORT); rs = stmnt.executeQuery(); while(rs.next()){ rep = new MonthlyReportDTO(); sch = new ScholarDTO(); sch.setScholarID(rs.getString(1)); sch.setScholarFirstName(rs.getString(2)); sch.setScholarMiddleName(rs.getString(3)); sch.setScholarLastName(rs.getString(4)); rep.setMreportid(rs.getString(5)); rep.setFromDate(rs.getDate(6).toString()); rep.setToDate(rs.getDate(7).toString()); rep.setStatus(rs.getString(8)); rep.setScholar(sch); reps.add(rep); } logger.info("Retrieved monthly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving monthly reports by supervisor ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public List getMonthlyReportsByInstituteId(int instituteid) { Connection conn = getConnection(); ResultSet rs; MonthlyReportDTO rep; List reps = new ArrayList(); ScholarDTO sch; try { logger.info("Retrieving all monthly reports by institute ID "); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_MONTHLYREPORT_BY_INSTITUTE_ID); stmnt.setInt(1,instituteid); rs = stmnt.executeQuery(); while(rs.next()){ rep = new MonthlyReportDTO(); sch = new ScholarDTO(); sch.setScholarID(rs.getString(1)); sch.setScholarFirstName(rs.getString(2)); sch.setScholarMiddleName(rs.getString(3)); sch.setScholarLastName(rs.getString(4)); rep.setMreportid(rs.getString(5)); rep.setFromDate(rs.getDate(6).toString()); rep.setToDate(rs.getDate(7).toString()); rep.setStatus(rs.getString(8)); rep.setScholar(sch); reps.add(rep); } logger.info("Retrieved monthly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving monthly reports by institute ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public List getMonthlyReportsByFacultyId(int facultyid) { Connection conn = getConnection(); ResultSet rs; MonthlyReportDTO rep; List reps = new ArrayList(); ScholarDTO sch; try { logger.info("Retrieving all monthly reports by faculty ID "); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_MONTHLYREPORT_BY_FACULTY_ID); stmnt.setInt(1,facultyid); rs = stmnt.executeQuery(); while(rs.next()){ rep = new MonthlyReportDTO(); sch = new ScholarDTO(); sch.setScholarID(rs.getString(1)); sch.setScholarFirstName(rs.getString(2)); sch.setScholarMiddleName(rs.getString(3)); sch.setScholarLastName(rs.getString(4)); rep.setMreportid(rs.getString(5)); rep.setFromDate(rs.getDate(6).toString()); rep.setToDate(rs.getDate(7).toString()); rep.setStatus(rs.getString(8)); rep.setScholar(sch); reps.add(rep); } logger.info("Retrieved monthly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving monthly reports by faculty ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public List getMonthlyReportsByDepartmentId(int departmentid) { Connection conn = getConnection(); ResultSet rs; MonthlyReportDTO rep; List reps = new ArrayList(); ScholarDTO sch; try { logger.info("Retrieving all monthly reports by department ID "); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_MONTHLYREPORT_BY_DEPARTMENT_ID); stmnt.setInt(1,departmentid); rs = stmnt.executeQuery(); while(rs.next()){ rep = new MonthlyReportDTO(); sch = new ScholarDTO(); sch.setScholarID(rs.getString(1)); sch.setScholarFirstName(rs.getString(2)); sch.setScholarMiddleName(rs.getString(3)); sch.setScholarLastName(rs.getString(4)); rep.setMreportid(rs.getString(5)); rep.setFromDate(rs.getDate(6).toString()); rep.setToDate(rs.getDate(7).toString()); rep.setStatus(rs.getString(8)); rep.setScholar(sch); reps.add(rep); } logger.info("Retrieved monthly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving monthly reports by department ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public List getQuarterlyReports() { Connection conn = getConnection(); ResultSet rs; List reps = new ArrayList(); QuarterlyReportDTO rep; ScholarDTO sch; try { logger.info("Retrieving all quarterly reports " ); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_QUARTERLYREPORT); rs = stmnt.executeQuery(); while(rs.next()){ rep = new QuarterlyReportDTO(); sch = new ScholarDTO(); sch.setScholarID(rs.getString(1)); sch.setScholarFirstName(rs.getString(2)); sch.setScholarMiddleName(rs.getString(3)); sch.setScholarLastName(rs.getString(4)); rep.setQreportid(rs.getString(5)); rep.setFromDate(rs.getDate(6).toString()); rep.setToDate(rs.getDate(7).toString()); rep.setStatus(rs.getString(8)); rep.setScholar(sch); reps.add(rep); } logger.info("Retrieved quarterly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving all monthly reports " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public List getQuarterlyReportsByInstituteId(int instituteid) { Connection conn = getConnection(); ResultSet rs; List reps = new ArrayList(); QuarterlyReportDTO rep; ScholarDTO sch; try { logger.info("Retrieving quarterly reports by institute ID " + instituteid); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_QUARTERLYREPORT_BY_INSTITUTE_ID); stmnt.setInt(1, instituteid); rs = stmnt.executeQuery(); while(rs.next()){ rep = new QuarterlyReportDTO(); sch = new ScholarDTO(); sch.setScholarID(rs.getString(1)); sch.setScholarFirstName(rs.getString(2)); sch.setScholarMiddleName(rs.getString(3)); sch.setScholarLastName(rs.getString(4)); rep.setQreportid(rs.getString(5)); rep.setFromDate(rs.getDate(6).toString()); rep.setToDate(rs.getDate(7).toString()); rep.setStatus(rs.getString(8)); rep.setScholar(sch); reps.add(rep); } logger.info("Retrieved quarterly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving monthly reports by institute ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public List getQuarterlyReportsByFacultyId(int facultyid) { Connection conn = getConnection(); ResultSet rs; List reps = new ArrayList(); QuarterlyReportDTO rep; ScholarDTO sch; try { logger.info("Retrieving quarterly reports by faculty ID " + facultyid); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_QUARTERLYREPORT_BY_FACULTY_ID); stmnt.setInt(1, facultyid); rs = stmnt.executeQuery(); while(rs.next()){ rep = new QuarterlyReportDTO(); sch = new ScholarDTO(); sch.setScholarID(rs.getString(1)); sch.setScholarFirstName(rs.getString(2)); sch.setScholarMiddleName(rs.getString(3)); sch.setScholarLastName(rs.getString(4)); rep.setQreportid(rs.getString(5)); rep.setFromDate(rs.getDate(6).toString()); rep.setToDate(rs.getDate(7).toString()); rep.setStatus(rs.getString(8)); rep.setScholar(sch); reps.add(rep); } logger.info("Retrieved quarterly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving monthly reports by faculty ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } public List getQuarterlyReportsByDepartmentId(int departmentid) { Connection conn = getConnection(); ResultSet rs; List reps = new ArrayList(); QuarterlyReportDTO rep; ScholarDTO sch; try { logger.info("Retrieving quarterly reports by department ID " + departmentid); PreparedStatement stmnt = conn.prepareStatement(SQLQueries.RETRIEVE_QUARTERLYREPORT_BY_DEPARTMENT_ID); stmnt.setInt(1, departmentid); rs = stmnt.executeQuery(); while(rs.next()){ rep = new QuarterlyReportDTO(); sch = new ScholarDTO(); sch.setScholarID(rs.getString(1)); sch.setScholarFirstName(rs.getString(2)); sch.setScholarMiddleName(rs.getString(3)); sch.setScholarLastName(rs.getString(4)); rep.setQreportid(rs.getString(5)); rep.setFromDate(rs.getDate(6).toString()); rep.setToDate(rs.getDate(7).toString()); rep.setStatus(rs.getString(8)); rep.setScholar(sch); reps.add(rep); } logger.info("Retrieved quarterly reports "+reps.size()); } catch (SQLException e) { logger.error("Error while retrieving monthly reports by department ID " + e.getMessage()); } try { conn.close(); logger.info("Connection closed successfully "); } catch (SQLException e) { logger.error("Unable to close Connection Object " + e.getMessage()); } return reps; } }
true
7d50ce84bf9d81879e698e06e7996abb4e0281c7
Java
L13HolyUmbra/CSCE145_Homework8
/src/TripComputer.java
UTF-8
8,159
3.671875
4
[]
no_license
//A lot of imports import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /** * * @author Dion de Jong * @version November 14, 2013 * Create a calculator for calculating how long a * particular trip will take. It can account for rest * stops and can calculate by legs of trip. It should throw * exceptions if the user attempts to make two rest stops in a row or * types a negative time. */ //main class public class TripComputer extends JFrame implements ActionListener{ //initialize all of the main things you will need private JButton newLeg; private JButton newStop; private JFormattedTextField Display; private JLabel DisplayLabel; private JFormattedTextField Distance; private JLabel DistanceLabel; private JFormattedTextField Speed; private JLabel SpeedLabel; private JFormattedTextField StopTime; private JLabel StopTimeLabel; //instruction required instance variables private double totalTime = 0; private boolean restStopTaken = false; //constructor public TripComputer() { super("Trip Calculator"); this.setSize(500,500); this.initialize(); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } //Legtime computation method. Receives the parameters of how fast people are going and for how far and determines //how long it will take and adds that to the total time. public double computeLegTime (double distance, double speed) throws NegativeParameterException { //if the parameter is negative throw a negative parameter exception created in a separate class. if (distance < 0 || speed < 0) { throw new NegativeParameterException(); } double LegTime = distance/speed; totalTime += LegTime; restStopTaken = false; return LegTime; } //adds the time the user intends to take on a rest stop to the total time public void takeRestStop (double time) throws NegativeParameterException, TwoStopsException { //if the time is negative or the user has just taken a stop without another leg, throw an exception if (time < 0) { throw new NegativeParameterException(); } if (restStopTaken == true) { throw new TwoStopsException(); } totalTime += time; restStopTaken = true; } //Getter for trip time public double getTripTime() { return totalTime; } //Create the jpanels and everything held in them (define how to create the calculator object) public void initialize() { //Create the content pane that will hold everything. Container c = this.getContentPane(); c.setLayout(null); c.setBackground(Color.pink); c.setForeground(new Color(0,0,0)); c.setVisible(true); //create the panel that holds the buttons, it sits inside your content pane. JPanel ButtonPanel = new JPanel(); //ButtonPanel.setBounds(0, 0, 500, 200); ButtonPanel.setLayout(new FlowLayout()); ButtonPanel.setVisible(true); ButtonPanel.setBackground(Color.PINK); c.add(ButtonPanel); //create the add a new leg button this.newLeg = new JButton(); this.newLeg.setBounds(280, 75, 150, 50); this.newLeg.setActionCommand("newLeg"); this.newLeg.addActionListener(this); this.newLeg.setText("Add New Leg"); c.add(newLeg); //newLeg.setVisible(true); //Create the new stop button this.newStop = new JButton(); this.newStop.setBounds(80, 75, 150, 50); this.newStop.setActionCommand("newStop"); this.newStop.addActionListener(this); this.newStop.setText("Add New Stop"); c.add(newStop); newStop.setVisible(true); //create the first half panel that will hold the display and stop time input JPanel JP1 = new JPanel(); JP1.setBounds(0, 200, 250, 500); JP1.setLayout(null); JP1.setVisible(true); JP1.setBackground(Color.MAGENTA); c.add(JP1); //displays the total trip time. CANT BE EDITED this.Display = new JFormattedTextField(); this.Display.setColumns(1); this.Display.setBounds(90, 360, 75, 35); this.Display.setValue(totalTime); this.Display.setVisible(true); this.Display.setEditable(false); c.add(Display); //Label for display this.DisplayLabel = new JLabel(); this.DisplayLabel.setText("Estimated trip time:"); this.DisplayLabel.setBounds(55,120,800,50); DisplayLabel.setVisible(true); JP1.add(DisplayLabel); //input field for how long a stop will take this.StopTime = new JFormattedTextField(); this.StopTime.setColumns(1); this.StopTime.setBounds(90, 270, 75, 35); this.StopTime.setText("Stop Time"); this.StopTime.setVisible(true); c.add(StopTime); //label for editing stop time for a rest stop this.StopTimeLabel = new JLabel(); this.StopTimeLabel.setText("Amount of time in hours for stop."); this.StopTimeLabel.setBounds(20,35,800,50); StopTimeLabel.setVisible(true); JP1.add(StopTimeLabel); //create a second panel that will hold the input for the leg distance and speed. JPanel JP2 = new JPanel(); JP2.setBounds(250, 200, 250, 500); JP2.setLayout(null); JP2.setVisible(true); JP2.setBackground(Color.MAGENTA); c.add(JP2); //Input field for the distance of the next leg this.Distance = new JFormattedTextField(); this.Distance.setColumns(1); this.Distance.setBounds(335, 270, 75, 35); this.Distance.setText("Distance"); this.Distance.setVisible(true); c.add(Distance); //label for the distance input this.DistanceLabel = new JLabel(); this.DistanceLabel.setText("Distance of your Leg (in MPH)."); this.DistanceLabel.setBounds(50,10,800,100); this.DistanceLabel.setVisible(true); JP2.add(DistanceLabel); //Input field for the speed of the next leg this.Speed = new JFormattedTextField(); this.Speed.setColumns(1); this.Speed.setBounds(335, 360, 75, 35); this.Speed.setText("Speed"); //this.Speed.setValue(new Double(SpeedValue)); this.Speed.setVisible(true); c.add(Speed); //Label for speed input this.SpeedLabel = new JLabel(); this.SpeedLabel.setText("Predicted Speed for leg (in MPH)."); this.SpeedLabel.setBounds(45,100,800,100); this.SpeedLabel.setVisible(true); JP2.add(SpeedLabel); } //what happens when the user presses the two buttons is defined below. @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String source = e.getActionCommand(); //if new leg is pressed if(source.equals("newLeg")) { //parse the values the user has entered in the appropriate fields to doubles String SpeedString = Speed.getText(); double DubSpeed = Double.parseDouble(SpeedString); String DistanceString = Distance.getText(); double DubDistance = Double.parseDouble(DistanceString); //try to get the leg time, try { this.computeLegTime(DubDistance, DubSpeed); } //unless the parameter was negative. catch (NegativeParameterException e1) { e1.printStackTrace(); } } //if the user presses stop if(source.equals("newStop")) { //parse time to a double String StopTimeString = StopTime.getText(); double DubStopTime = Double.parseDouble(StopTimeString); //add it to the total time with the add stop method, try { this.takeRestStop(DubStopTime); } //unless the parameter is negative or the user has just created a stop without a new leg. catch (NegativeParameterException | TwoStopsException e1) { e1.printStackTrace(); } } //display the new total time in the display field (must parse to string). this.Display.setText(Double.toString(getTripTime())); } //main method public static void main(String[] args) { // TODO Auto-generated method stub //create an object of the calculator to be use. TripComputer Calc = new TripComputer(); } }
true
dd2605c317e4cccc58304a5e046b44d997d3e171
Java
coroyoy1/H2BOT
/app/src/main/java/com/example/administrator/h2bot/tpaaffiliate/TPADeliveredInfoFragment.java
UTF-8
8,862
1.71875
2
[]
no_license
package com.example.administrator.h2bot.tpaaffiliate; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.h2bot.R; import com.example.administrator.h2bot.models.MerchantCustomerFile; import com.example.administrator.h2bot.models.OrderModel; import com.example.administrator.h2bot.models.UserFile; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import org.joda.time.DateTime; import de.hdodenhof.circleimageview.CircleImageView; public class TPADeliveredInfoFragment extends Fragment implements View.OnClickListener { TextView orderNo,customerName,customerAddress,customerContactNo,waterStationName,stationAddress,stationContactNo,expectedDate,pricePerGallon,quantity,waterType,totalPrice,userTypeDirection; Button okButton,switchUser; Button backButton; String orderNoGET, customerNoGET, merchantNOGET, transactionNo, dataIssuedGET, deliveryStatusGET ,transStatusGET, transTotalAmountGET, transDeliveryFeeGET, transTotalNoGallonGET, transDeliveryFeePerGallonDetail, transNoDetail, transNoOfGallonDetail, transPartialAmountDetail, transPricePerGallonDetail ,transStatusDetail, transWaterTypeDetail, customerIDUser, contactNoUser, customerNo ; CircleImageView imageView; ProgressDialog progressDialog; FirebaseUser firebaseUser; ImageView imageviewprofile; public String stationID,customerID,orderNumber; Bundle bundle; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tpa_delivered_info_fragment, container, false); orderNo = view.findViewById(R.id.orderNo); customerName = view.findViewById(R.id.customerName); customerAddress = view.findViewById(R.id.customerAddress); customerContactNo = view.findViewById(R.id.customerContactNo); waterStationName = view.findViewById(R.id.waterStationName); stationAddress = view.findViewById(R.id.stationAddress); stationContactNo = view.findViewById(R.id.stationContactNo); expectedDate = view.findViewById(R.id.expectedDate); pricePerGallon = view.findViewById(R.id.pricePerGallon); quantity = view.findViewById(R.id.quantity); waterType = view.findViewById(R.id.waterType); totalPrice = view.findViewById(R.id.totalPrice); okButton = view.findViewById(R.id.okButton); imageviewprofile = view.findViewById(R.id.imageviewprofile); getBunle(); getFromCustomerFile(); getFromBusinessFile(); getFromUserFile(); view.setFocusableInTouchMode(true); view.requestFocus(); view.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(event.getAction() == KeyEvent.ACTION_DOWN) { if (keyCode == KeyEvent.KEYCODE_BACK) { attemptToExit(); return true; } } return false; } }); return view; } public void getBunle() { bundle = this.getArguments(); if (bundle != null) { orderNumber = bundle.getString("orderno"); customerID = bundle.getString("customerid"); stationID = bundle.getString("stationid"); //Log.d("Popo",orderNumber+","+customerID+","+stationID); } } public void getFromCustomerFile() { Log.d("Popo",orderNumber+","+customerID+","+stationID); DatabaseReference customerFile = FirebaseDatabase.getInstance().getReference("Customer_File").child(customerID).child(stationID).child(orderNumber); customerFile.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { orderNo.setText(orderNumber); customerAddress.setText(dataSnapshot.child("order_address").getValue(String.class)); expectedDate.setText(dataSnapshot.child("order_date").getValue(String.class)); pricePerGallon.setText(dataSnapshot.child("order_price_per_gallon").getValue(String.class)); quantity.setText(dataSnapshot.child("order_qty").getValue(String.class)); totalPrice.setText(dataSnapshot.child("order_total_amt").getValue(String.class)); waterType.setText(dataSnapshot.child("order_water_type").getValue(String.class)); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } public void getFromBusinessFile() { DatabaseReference businessfile = FirebaseDatabase.getInstance().getReference("User_WS_Business_Info_File").child(stationID); businessfile.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { stationAddress.setText(dataSnapshot.child("business_address").getValue(String.class)); stationContactNo.setText(dataSnapshot.child("business_tel_no").getValue(String.class)); waterStationName.setText(dataSnapshot.child("business_name").getValue(String.class)); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } public void getFromUserFile() { DatabaseReference userfile = FirebaseDatabase.getInstance().getReference("User_File").child(customerID); userfile.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { customerAddress.setText(dataSnapshot.child("user_firstname").getValue(String.class)+" "+dataSnapshot.child("user_lastname").getValue(String.class)); customerAddress.setText(dataSnapshot.child("user_address").getValue(String.class)); customerContactNo.setText(dataSnapshot.child("user_phone_no").getValue(String.class)); Picasso.get().load(dataSnapshot.child("user_uri").getValue(String.class)).resize(200,200).into(imageviewprofile); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void showMessages(String s) { Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.backCOMACC: TPADeliveredInfoFragment additem = new TPADeliveredInfoFragment(); AppCompatActivity activity = (AppCompatActivity)v.getContext(); activity.getSupportFragmentManager() .beginTransaction() .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.fade_in, android.R.anim.fade_out) .replace(R.id.fragment_container_wp, additem) .addToBackStack(null) .commit(); break; } } public void attemptToExit() { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: getActivity().finish(); break; case DialogInterface.BUTTON_NEGATIVE: //No button clicked break; } } }; } }
true
fbb0119e61737356191e881fecfe5d2b5b52be70
Java
kyungsubbb/Coding-Test
/Programmers/Java/Level 2/쿼드압축 후 개수 세기.java
UTF-8
1,276
3.171875
3
[]
no_license
import java.util.*; class Solution { static int count; static int[] val = new int[2]; public int[] solution(int[][] arr) { int size = arr.length; if(isAvail(arr, 0, 0, size)){ int tmp = arr[0][0]; val[tmp]++; return val; } for(int i=0; i<2; i++){ for(int j=0; j<2; j++){ DFS(arr, size/2, i*(size/2), j*(size/2)); // 배열, 사이즈, 시작점 } } int[] answer = val; return answer; } private static boolean isAvail(int[][] arr, int a, int b, int len){ int tmp = arr[a][b]; for(int i=a; i <a+len; i++){ for(int j=b; j<b+len; j++){ if(arr[i][j] != tmp) return false; } } return true; } private static void DFS(int[][] arr, int size, int x, int y){ int tmp = arr[x][y]; if(size == 1){ val[tmp]++; return; } if(isAvail(arr, x, y, size)){ val[tmp]++; return; } int len = size/2; DFS(arr, len, x, y); DFS(arr, len, x+len, y); DFS(arr, len, x, y+len); DFS(arr, len, x+len, y+len); } }
true
0273c09b2411751f4e98e50774924704e4e0edcf
Java
bellmit/zycami-ded
/src/main/java/com/meicam/sdk/NvsARFaceContext$1.java
UTF-8
2,104
1.710938
2
[]
no_license
/* * Decompiled with CFR 0.151. * * Could not load the following classes: * android.os.Handler */ package com.meicam.sdk; import android.os.Handler; import com.meicam.sdk.NvsARFaceContext; import com.meicam.sdk.NvsARFaceContext$1$1; import com.meicam.sdk.NvsARFaceContext$1$2; import com.meicam.sdk.NvsARFaceContext$1$3; import com.meicam.sdk.NvsARFaceContext$1$4; import com.meicam.sdk.NvsARFaceContext$1$5; import com.meicam.sdk.NvsARFaceContext$NvsARFaceContextInternalCallback; public class NvsARFaceContext$1 implements NvsARFaceContext$NvsARFaceContextInternalCallback { public final /* synthetic */ NvsARFaceContext this$0; public NvsARFaceContext$1(NvsARFaceContext nvsARFaceContext) { this.this$0 = nvsARFaceContext; } public void notifyDetectedAction(long l10) { Handler handler = this.this$0.mainHandler; NvsARFaceContext$1$5 nvsARFaceContext$1$5 = new NvsARFaceContext$1$5(this, l10); handler.post((Runnable)nvsARFaceContext$1$5); } public void notifyFaceItemLoadingBegin(String string2) { Handler handler = this.this$0.mainHandler; NvsARFaceContext$1$1 nvsARFaceContext$1$1 = new NvsARFaceContext$1$1(this, string2); handler.post((Runnable)nvsARFaceContext$1$1); } public void notifyFaceItemLoadingFailed(String string2, int n10) { Handler handler = this.this$0.mainHandler; NvsARFaceContext$1$3 nvsARFaceContext$1$3 = new NvsARFaceContext$1$3(this, string2, n10); handler.post((Runnable)nvsARFaceContext$1$3); } public void notifyFaceItemLoadingFinish() { Handler handler = this.this$0.mainHandler; NvsARFaceContext$1$2 nvsARFaceContext$1$2 = new NvsARFaceContext$1$2(this); handler.post((Runnable)nvsARFaceContext$1$2); } public void notifyObjectLandmark(float[] fArray, int n10, int n11, long l10) { Handler handler = this.this$0.mainHandler; NvsARFaceContext$1$4 nvsARFaceContext$1$4 = new NvsARFaceContext$1$4(this, fArray, n10, n11, l10); handler.post((Runnable)nvsARFaceContext$1$4); } }
true
2abc4595fae45cad051f338fc1691f5382ab8d92
Java
rcouture27/Database-with-SQLite
/MainActivity.java
UTF-8
3,913
2.484375
2
[]
no_license
package com.example.it_lab_local.petlabdatabase; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent addDog = new Intent(this, AddDogActivity.class); startActivity(addDog); return super.onOptionsItemSelected(item); } //return super.onOptionsItemSelected(item); return true; } @Override protected void onResume() { DatabaseConnector dc = new DatabaseConnector(this); dc.open(); Cursor c = dc.getAllDogs(); if (c != null) { final ListView lst = (ListView) findViewById(R.id.lst); final ArrayList<String> list = new ArrayList<String>(); if (c.moveToFirst()) { do { String breed = c.getString(c.getColumnIndex("breed")); String name = c.getString(c.getColumnIndex("name")); int age = c.getInt(c.getColumnIndex("age")); list.add(breed + " " + name + " " + String.valueOf(age)); } while(c.moveToNext()); } final StableArrayAdapter adapter = new StableArrayAdapter(this,android.R.layout.simple_list_item_1,list); lst.setAdapter(adapter); } super.onResume(); } // end onResume private class StableArrayAdapter extends ArrayAdapter<String> { HashMap<String,Integer> midMap = new HashMap<String, Integer>(); public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects){ super(context, textViewResourceId,objects); for(int i=0;i<objects.size();++i){ midMap.put(objects.get(i),i); } } @Override public long getItemId(int position){ String item = getItem(position); return midMap.get(item); } @Override public boolean hasStableIds(){ return true; } } } // end class
true
63f48c6cd21293ad6c0f6280a154af56bc355be8
Java
cnygardtw/lighthouse-charon
/charon/src/test/java/gov/va/api/lighthouse/charon/service/controller/MpiVistaNameResolverTest.java
UTF-8
8,470
1.765625
2
[]
no_license
package gov.va.api.lighthouse.charon.service.controller; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import gov.va.api.lighthouse.charon.api.RpcVistaTargets; import gov.va.api.lighthouse.charon.service.config.ConnectionDetails; import gov.va.api.lighthouse.charon.service.config.VistalinkProperties; import gov.va.api.lighthouse.mpi.MpiConfig; import java.util.List; import java.util.function.Function; import org.assertj.core.api.Assertions; import org.hl7.v3.II; import org.hl7.v3.PRPAIN201310UV02; import org.hl7.v3.PRPAIN201310UV02MFMIMT700711UV01ControlActProcess; import org.hl7.v3.PRPAIN201310UV02MFMIMT700711UV01RegistrationEvent; import org.hl7.v3.PRPAIN201310UV02MFMIMT700711UV01Subject1; import org.hl7.v3.PRPAIN201310UV02MFMIMT700711UV01Subject2; import org.hl7.v3.PRPAMT201304UV02Patient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class MpiVistaNameResolverTest { VistalinkProperties properties = VistalinkProperties.builder() .vista( ConnectionDetails.builder() .divisionIen("0") .host("fakehost") .name("FAKESTATION") .port(1337) .build()) .build(); @Mock PRPAIN201310UV02 mockResponse; @Mock MpiConfig config; PRPAIN201310UV02MFMIMT700711UV01ControlActProcess controlActProcess = PRPAIN201310UV02MFMIMT700711UV01ControlActProcess.builder() .subject( List.of( PRPAIN201310UV02MFMIMT700711UV01Subject1.builder() .registrationEvent( PRPAIN201310UV02MFMIMT700711UV01RegistrationEvent.builder() .subject1( PRPAIN201310UV02MFMIMT700711UV01Subject2.builder() .patient( PRPAMT201304UV02Patient.builder() .id( List.of( II.iIBuilder() .extension( "100005750^PI^FAKESTATION^USVHA^A") .build())) .build()) .build()) .build()) .build())) .build(); @BeforeEach void _init() { MockitoAnnotations.initMocks(this); } @Test void request1309() { var resolver = new MpiVistaNameResolver(properties, config); assertThat(resolver.request1309()).isInstanceOf(Function.class); Function<String, PRPAIN201310UV02> mockFunction = (s) -> { return mockResponse; }; var resolverFunctionOverride = new MpiVistaNameResolver(properties, config); resolverFunctionOverride.request1309(mockFunction); assertThat(resolverFunctionOverride.request1309()).isEqualTo(mockFunction); } @Test void resolveExplodesWhenMultiplePatientsAreFound() { PRPAIN201310UV02MFMIMT700711UV01ControlActProcess controlActProcess = PRPAIN201310UV02MFMIMT700711UV01ControlActProcess.builder() .subject( List.of( PRPAIN201310UV02MFMIMT700711UV01Subject1.builder() .registrationEvent( PRPAIN201310UV02MFMIMT700711UV01RegistrationEvent.builder() .subject1( PRPAIN201310UV02MFMIMT700711UV01Subject2.builder() .patient( PRPAMT201304UV02Patient.builder() .id( List.of( II.iIBuilder() .extension( "100005750^PI^FAKESTATION^USVHA^A") .build())) .build()) .build()) .build()) .build(), PRPAIN201310UV02MFMIMT700711UV01Subject1.builder() .registrationEvent( PRPAIN201310UV02MFMIMT700711UV01RegistrationEvent.builder() .subject1( PRPAIN201310UV02MFMIMT700711UV01Subject2.builder() .patient( PRPAMT201304UV02Patient.builder() .id( List.of( II.iIBuilder() .extension( "100008890^PI^FAKESTATION2^USVHA^A") .build())) .build()) .build()) .build()) .build())) .build(); Mockito.when(mockResponse.getControlActProcess()).thenReturn(controlActProcess); Function<String, PRPAIN201310UV02> mockFunction = (s) -> { return mockResponse; }; MpiVistaNameResolver resolver = new MpiVistaNameResolver(properties, config); resolver.request1309(mockFunction); assertThatExceptionOfType(VistaLinkExceptions.UnknownPatient.class) .isThrownBy(() -> resolver.resolve(RpcVistaTargets.builder().forPatient("1").build())); } @Test void resolveReturnsConnectionDetails() { PRPAIN201310UV02MFMIMT700711UV01ControlActProcess controlActProcess = PRPAIN201310UV02MFMIMT700711UV01ControlActProcess.builder() .subject( List.of( PRPAIN201310UV02MFMIMT700711UV01Subject1.builder() .registrationEvent( PRPAIN201310UV02MFMIMT700711UV01RegistrationEvent.builder() .subject1( PRPAIN201310UV02MFMIMT700711UV01Subject2.builder() .patient( PRPAMT201304UV02Patient.builder() .id( List.of( II.iIBuilder() .extension( "100005750^PI^FAKESTATION^USVHA^A") .build())) .build()) .build()) .build()) .build())) .build(); Mockito.when(mockResponse.getControlActProcess()).thenReturn(controlActProcess); Function<String, PRPAIN201310UV02> mockFunction = (s) -> { return mockResponse; }; MpiVistaNameResolver resolver = new MpiVistaNameResolver(properties, config); resolver.request1309(mockFunction); Assertions.assertThat(resolver.resolve(RpcVistaTargets.builder().forPatient("1").build())) .isEqualTo( List.of( ConnectionDetails.builder() .name("FAKESTATION") .host("fakehost") .port(1337) .divisionIen("0") .build())); } @Test void targetsForPatientReturnsEmptyListWhenNoPatientIsSpecified() { var resolver = new MpiVistaNameResolver(properties, config); assertThat(resolver.resolve(RpcVistaTargets.builder().build())).isEmpty(); } }
true
3a2c79036dbb381c0b597ff1da2a9cae0e99b14b
Java
woojaeK/Algorithm
/Algo/src/baekjoon/Main_9466_텀프로젝트.java
UTF-8
1,442
2.875
3
[]
no_license
package baekjoon; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Main_9466_텀프로젝트 { public static boolean[] visit; public static boolean[] visit2; public static int[] list; public static int N; public static int cnt =0; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int T = Integer.parseInt(br.readLine()); for (int tc = 1; tc <= T; tc++) { N = Integer.parseInt(br.readLine()); list = new int[N + 1]; visit = new boolean[N + 1]; visit2 = new boolean[N + 1]; cnt = 0; st = new StringTokenizer(br.readLine()); for (int i = 1; i <= N; i++) { int a = Integer.parseInt(st.nextToken()); list[i] = a; } for (int i = 1; i <= N; i++) { dfs(i); } System.out.println(N - cnt); } } public static void dfs(int now) { if (visit[now]) return; visit[now] = true; int next = list[now]; if (visit[next] != true) { dfs(next); } else { if (visit2[next] != true) { cnt++; for (int i = next; i !=now; i = list[i]) { cnt++; } } } visit2[now] = true; } }
true
a5a87151bbd0cb5b7e59388635b971e328a1af33
Java
msucil/midpoint
/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/CertificationHook.java
UTF-8
5,003
1.65625
2
[ "Apache-2.0", "GPL-1.0-or-later", "MPL-2.0", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "LGPL-2.0-or-later", "CDDL-1.0", "MIT" ]
permissive
/* * Copyright (c) 2010-2017 Evolveum * * 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.evolveum.midpoint.certification.impl; import com.evolveum.midpoint.model.api.context.EvaluatedAssignment; import com.evolveum.midpoint.model.api.context.EvaluatedPolicyRule; import com.evolveum.midpoint.model.api.context.ModelContext; import com.evolveum.midpoint.model.api.context.ModelState; import com.evolveum.midpoint.model.api.hooks.ChangeHook; import com.evolveum.midpoint.model.api.hooks.HookOperationMode; import com.evolveum.midpoint.model.api.hooks.HookRegistry; import com.evolveum.midpoint.model.impl.lens.LensElementContext; import com.evolveum.midpoint.prism.delta.DeltaSetTriple; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.exception.CommonException; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.CertificationPolicyActionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * Starts ad-hoc certifications as prescribed by "certificate" policy action. * * @author mederly */ @Component public class CertificationHook implements ChangeHook { private static final Trace LOGGER = TraceManager.getTrace(CertificationHook.class); private static final String HOOK_URI = SchemaConstants.NS_MODEL + "/certification-hook-3"; @Autowired private HookRegistry hookRegistry; @Autowired private CertificationManagerImpl certificationManager; @PostConstruct public void init() { hookRegistry.registerChangeHook(HOOK_URI, this); LOGGER.trace("CertificationHook registered."); } @Override public <O extends ObjectType> HookOperationMode invoke(@NotNull ModelContext<O> context, @NotNull Task task, @NotNull OperationResult result) { if (context.getState() != ModelState.FINAL) { return HookOperationMode.FOREGROUND; } LensElementContext<O> focusContext = (LensElementContext<O>) context.getFocusContext(); if (focusContext == null || !FocusType.class.isAssignableFrom(focusContext.getObjectTypeClass())) { return HookOperationMode.FOREGROUND; } List<CertificationPolicyActionType> actions = new ArrayList<>(); actions.addAll(getFocusCertificationActions(context)); actions.addAll(getAssignmentCertificationActions(context)); try { certificationManager.startAdHocCertifications(focusContext.getObjectAny(), actions, task, result); } catch (CommonException e) { throw new SystemException("Couldn't start ad-hoc campaign(s): " + e.getMessage(), e); } return HookOperationMode.FOREGROUND; } private Collection<CertificationPolicyActionType> getFocusCertificationActions(ModelContext<?> context) { return getCertificationActions(context.getFocusContext().getPolicyRules()); } private Collection<CertificationPolicyActionType> getAssignmentCertificationActions(ModelContext<?> context) { DeltaSetTriple<? extends EvaluatedAssignment<?>> evaluatedAssignmentTriple = context.getEvaluatedAssignmentTriple(); if (evaluatedAssignmentTriple == null) { return Collections.emptyList(); } else { return evaluatedAssignmentTriple.stream() .flatMap(ea -> getCertificationActions(ea.getAllTargetsPolicyRules()).stream()) .collect(Collectors.toList()); } } private Collection<CertificationPolicyActionType> getCertificationActions(Collection<EvaluatedPolicyRule> policyRules) { return policyRules.stream() .filter(r -> r.isTriggered() && r.containsEnabledAction(CertificationPolicyActionType.class)) .map(r -> r.getEnabledAction(CertificationPolicyActionType.class)) .collect(Collectors.toList()); } @Override public void invokeOnException(@NotNull ModelContext context, @NotNull Throwable throwable, @NotNull Task task, @NotNull OperationResult result) { // Nothing to do } }
true
1082539d595292df92a97e34f2667d4656aa7128
Java
namkhanh308/CaseStudy2-Restaurant-Manager
/src/storage/ReadWriteFileType.java
UTF-8
1,501
2.90625
3
[]
no_license
package storage; import model.Product; import model.Type; import java.io.*; import java.util.ArrayList; import java.util.List; public class ReadWriteFileType implements Serializable { private static ReadWriteFileType readWriteFileType; private ReadWriteFileType() { } public static ReadWriteFileType getInstance(){ if (readWriteFileType == null){ readWriteFileType = new ReadWriteFileType(); } return readWriteFileType; } public List<Type> readFile() throws IOException, ClassNotFoundException { File file = new File("listType.txt"); if (!file.exists()){ file.createNewFile(); } if (file.length() >0){ FileInputStream fileInputStream = new FileInputStream(file); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); Object object = objectInputStream.readObject(); List<Type> list = (List<Type>) object; objectInputStream.close(); fileInputStream.close(); return list; } else return new ArrayList<>(); } public void writeFile(List<Type> types) throws IOException{ FileOutputStream fileOutputStream = new FileOutputStream("listType.txt"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(types); objectOutputStream.close(); fileOutputStream.close(); } }
true
c30854646f9d81c8381dcb64a5a7bc59700d83e5
Java
marcoucou/com.tinder
/src/com/google/android/m4b/maps/k/d.java
UTF-8
1,313
1.820313
2
[]
no_license
package com.google.android.m4b.maps.k; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.m4b.maps.f.a; import com.google.android.m4b.maps.f.a.a; import com.google.android.m4b.maps.f.b; public final class d implements Parcelable.Creator<c> { public static c a(Parcel paramParcel) { String str2 = null; int j = a.a(paramParcel); int i = 0; String str1 = null; while (paramParcel.dataPosition() < j) { int k = paramParcel.readInt(); switch (0xFFFF & k) { default: a.b(paramParcel, k); break; case 1: i = a.f(paramParcel, k); break; case 2: str1 = a.k(paramParcel, k); break; case 3: str2 = a.k(paramParcel, k); } } if (paramParcel.dataPosition() != j) { throw new a.a("Overread allowed size end=" + j, paramParcel); } return new c(i, str1, str2); } static void a(c paramc, Parcel paramParcel) { int i = b.a(paramParcel); b.a(paramParcel, 1, a); b.a(paramParcel, 2, paramc.a(), false); b.a(paramParcel, 3, paramc.b(), false); b.a(paramParcel, i); } } /* Location: * Qualified Name: com.google.android.m4b.maps.k.d * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
65d82583f16e8463677d635df8c8b00ac8f5c040
Java
jasonzheng/json-type-test
/src/main/java/com/jason/testjson/typehandler/JsonStringTypeHandler.java
UTF-8
2,120
2.59375
3
[]
no_license
package com.jason.testjson.typehandler; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.jason.testjson.utils.JsonUtils; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author zhengjun * @date 2017/12/27 08:40 * @Description: 对象和json字符串映射 */ public abstract class JsonStringTypeHandler<T extends Object> extends BaseTypeHandler<T> { protected static final ObjectMapper objectMapper = JsonUtils.OBJECT_MAPPER; private Class<T> clazz; protected JsonStringTypeHandler(Class<T> clazz) { if (clazz == null) { throw new IllegalArgumentException("Type argument cannot be null"); } this.clazz = clazz; } protected T parse(String json) { if (json == null || json.length() == 0) { return null; } try { return objectMapper.readValue(json, clazz); } catch (Exception e) { throw new RuntimeException("FATAL ERROR read json"); } } @Override public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { String jsonString; try { jsonString = objectMapper.writeValueAsString(parameter); } catch (JsonProcessingException e) { throw new SQLException("invalid json string"); } ps.setString(i, jsonString); } @Override public T getNullableResult(ResultSet rs, String columnName) throws SQLException { return parse(rs.getString(columnName)); } @Override public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return parse(rs.getString(columnIndex)); } @Override public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return parse(cs.getString(columnIndex)); } }
true
cbb2a068282abe8537f82047759aead822900489
Java
g-savitha/InterviewBitSolutions
/Programming/Math/Problems/PrimeSum.java
UTF-8
647
3.234375
3
[]
no_license
public class Solution { public ArrayList<Integer> primesum(int n) { ArrayList<Integer> result = new ArrayList<>(); double sqrt = Math.sqrt(n); for (int i = 2; i < n; i ++) { if (isPrime(i) && isPrime(n - i)) { result.add(i); result.add(n-i); return result; } } return result; } private boolean isPrime(int a) { if (a == 1) { return false; } for (int i = 2; i <= Math.pow(a, 0.5); i++) { if (a % i == 0) { return false; } } return true; } }
true
a767d66124838bcf3c8c26dcc088d846272da1fd
Java
Zanexess/Java-Technotrack
/basic_io/src/ru/mail/track/network/ConnectionHandler.java
UTF-8
360
2.21875
2
[]
no_license
package ru.mail.track.network; import java.io.IOException; import ru.mail.track.Messeges.MessageBase; import ru.mail.track.data.Message; /** * Обработчик сокета */ public interface ConnectionHandler extends Runnable { void send(MessageBase msg) throws IOException; void addListener(MessageListener listener); void stop(); }
true
2bfd647965195a9cd5570de91d12b7bdc6a811d4
Java
radheshyamsingh24/AndroidArchitectureComponents
/CryptoBoom/data/src/main/java/com/radhe/data/repository/CryptoRepository.java
UTF-8
341
1.828125
2
[ "Apache-2.0" ]
permissive
package com.radhe.data.repository; import android.arch.lifecycle.LiveData; import com.radhe.data.models.CoinModel; import java.util.List; public interface CryptoRepository { LiveData<List<CoinModel>> getCryptoCoinsData(); LiveData<String> getErrorStream(); LiveData<Double> getTotalMarketCapStream(); void fetchData(); }
true
d6e41f021efb49363d5d2035998fd0ccf4a072e0
Java
LostReny/Zelda_clone
/Game_01/src/com/pa/entities/Entity.java
UTF-8
3,764
2.453125
2
[]
no_license
package com.pa.entities; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.List; import com.pa.main.Game; import com.pa.world.Camera; import com.pa.world.Node; import com.pa.world.Vector2i; public class Entity { public static BufferedImage LIFEPACK_EN = Game.spritesheet.getSprite(6*16, 0, 16, 16); public static BufferedImage WEAPON_EN = Game.spritesheet.getSprite(7*16, 0, 16, 16); public static BufferedImage BULLET_EN = Game.spritesheet.getSprite(6*16, 16, 16, 16); public static BufferedImage ENEMY_EN = Game.spritesheet.getSprite(7*16, 16, 16, 16); public static BufferedImage ENEMY_FEEDBACK = Game.spritesheet.getSprite(128+16, 16+16, 16, 16); public static BufferedImage GUN_RIGHT = Game.spritesheet.getSprite(128, 0, 16, 16); public static BufferedImage GUN_LEFT = Game.spritesheet.getSprite(144, 0, 16, 16); public static BufferedImage GUN_UP = Game.spritesheet.getSprite(112, 16+16, 16, 16); public static BufferedImage GUN_DOWN = Game.spritesheet.getSprite(112+16, 16+16, 16, 16); public static BufferedImage GUN_DAMAGE_RIGHT = Game.spritesheet.getSprite(6*16, 3*16, 16, 16); public static BufferedImage GUN_DAMAGE_LEFT = Game.spritesheet.getSprite(7*16, 3*16, 16, 16); public static BufferedImage GUN_DAMAGE_UP = Game.spritesheet.getSprite(8*16, 3*16, 16, 16); public static BufferedImage GUN_DAMAGE_DOWN = Game.spritesheet.getSprite(9*16, 3*16, 16, 16); protected double x; protected double y; protected int z; protected int width; protected int height; protected List<Node> path; private BufferedImage sprite; private int maskx, masky, mwidth, mheight; public Entity(int x, int y, int width, int height, BufferedImage sprite) { this.x = x; this.y = y; this.width = width; this.height = height; this.sprite= sprite; this.maskx = 0; this.masky = 0; this.mwidth = width; this.mheight = height; } public void setMask(int maskx, int masky, int mwidth, int mheight) { this.maskx = maskx; this.masky = masky; this.mwidth = mwidth; this.mheight = mheight; } public void setX(int newX) { this.x = newX; } public void sety(int newY) { this.y = newY; } public int getX() { return (int)this.x; } public int getY() { return (int)this.y; } public int getWidth() { return this.width; } public int getHeight() { return this.height; } public void tick() { } public double calculateDistance(int x1, int y1, int x2, int y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } public void followPath(List<Node> path) { // consigo encontrar um caminho if(path != null) { //e se meu caminho for maior que 0, ainda tenho caminho para percorrer if(path.size() > 0) { Vector2i target = path.get(path.size() -1).tile; //xprev = x; //yprev = y; if(x < target.x * 16) { x++; }else if (x > target.x *16) { x--; } if (y < target.y * 16) { y++; }else if (y > target.y * 16) { y--; } if (x == target.x * 16 && y == target.y *16) { path.remove(path.size() - 1); } } } } public static boolean isColliding(Entity e1, Entity e2) { Rectangle e1Mask = new Rectangle(e1.getX() + e1.maskx, e1.getY()+e1.masky,e1.mwidth,e1.mheight); Rectangle e2Mask = new Rectangle(e2.getX() + e2.maskx, e2.getY()+e2.masky,e2.mwidth,e2.mheight); if(e1Mask.intersects(e2Mask) && e1.z == e2.z) { return true; } return false; } // renderizar public void render(Graphics g) { g.drawImage(sprite, this.getX() - Camera.x, this.getY() -Camera.y,null); //g.setColor(Color.red); //g.fillRect( this.getX() + maskx - Camera.x, this.getY() + masky -Camera.y, mwidth, mheight); } }
true
efd36e11b2fd7d13b8f7c1ef867465d7779088de
Java
prateek1404/AlgoPractice
/Search/Gaurav.java
UTF-8
706
3.25
3
[]
no_license
import java.io.*; class Gaurav { public static void main(String args[]) { int ar[] = new int[args.length]; for(int i=0;i<args.length;i++) { ar[i] = Integer.parseInt(args[i]); } try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String num = br.readLine(); int N = Integer.parseInt(num); System.out.println(N); func(ar,N,0); } catch(Exception e) { } } public static boolean func(int[] ar,int N, int index) { if(N-ar[index]==0) { System.out.println("Found bitch!"); return true; } if(N>ar[index]) { if(func(ar,N-ar[index],index+1)) { } } } }
true
da206642a5111a8b3c12b3651e91a6718e3e6ce8
Java
jfsanin/hightail
/Hightail/src/org/hightail/util/ProblemNameFormatter.java
UTF-8
573
2.359375
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 org.hightail.util; /** * * @author Joseph */ public class ProblemNameFormatter { public static String getFormatedName(String originalName, String regularExpression){ return originalName.replaceAll(regularExpression, ""); } public static String getFormatedName(String originalName){ return getFormatedName(originalName, "[^A-Za-z0-9 ._-]"); } }
true
432365bdf8297a1d6a847f71b396639294cc7887
Java
daviaro/Metropolis
/src/java/dao/JornadaDaoImplement.java
UTF-8
4,381
2.703125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import java.util.List; import model.Jornada; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import util.HibernateUtil; /** * * @author chris */ public class JornadaDaoImplement implements JornadaDao { @Override public List<Jornada> mostrarJornadas() { Session session= HibernateUtil.getSessionFactory().getCurrentSession(); List<Jornada> lista=null; String sql = "FROM Jornada"; try{ session.beginTransaction(); lista = session.createQuery(sql).list(); session.getTransaction().commit(); }catch(HibernateException e){ session.getTransaction().rollback(); System.out.println(e.getMessage()); } return lista; } @Override public Jornada buscarJornada(Jornada jornada) { Jornada model=null; Session sesion = HibernateUtil.getSessionFactory().getCurrentSession(); String sql = "FROM Jornada WHERE nombre ='"+jornada.getNombre()+"'"; try{ sesion.beginTransaction(); model = (Jornada) sesion.createQuery(sql).uniqueResult(); sesion.beginTransaction().commit(); }catch(Exception e){ sesion.beginTransaction().rollback(); } return model; } @Override public boolean insertarJornada(Jornada jornada) { boolean flag; Transaction trans = null; Session session = HibernateUtil.getSessionFactory().openSession(); try{ trans = session.beginTransaction(); session.save(jornada); session.getTransaction().commit(); flag=true; }catch(RuntimeException e){ if(trans!=null){ trans.rollback(); } flag=false; }finally{ session.flush(); session.close(); } return flag; } @Override public boolean modificarJornada(Jornada jornada) { boolean flag; Transaction trans = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trans = session.beginTransaction(); session.update(jornada); session.getTransaction().commit(); flag = true; } catch (RuntimeException e) { if (trans != null) { trans.rollback(); } e.printStackTrace(); flag = false; } finally { session.flush(); session.close(); } return flag; } @Override public boolean eliminarJornada(Integer idjornada) { boolean flag; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); try{ session.beginTransaction(); Jornada jornada = (Jornada) session.load(Jornada.class, idjornada); session.delete(jornada); session.getTransaction().commit(); flag=true; }catch(HibernateException e){ flag=false; session.getTransaction().rollback(); } return flag; } @Override public Jornada buscarJornadabyId(Integer idJornada) { Jornada jornada = null; Session session = null; //Se crea un try catch para hacer la consulta String sql = "from Jornada where idJornada = '" + idJornada+ "'"; try { //Se recupera la session actual session = HibernateUtil.getSessionFactory().getCurrentSession(); //inicializo transaccion session.beginTransaction(); Query query = session.createQuery(sql); query.setMaxResults(1); //uniqueResult() para que sea solo un solo resultado jornada = (Jornada) query.uniqueResult(); session.getTransaction().commit(); } catch (HibernateException e) { //si no se cumple se hace un rollback session.getTransaction().rollback(); } return jornada; } }
true
84a0677a1f2e519cf7913c614a6f21dee18db10e
Java
sizovns/axiom-test
/src/main/java/org/example/axiom/test/model/Road.java
UTF-8
1,245
3.109375
3
[]
no_license
package org.example.axiom.test.model; import java.util.HashSet; import java.util.Objects; import java.util.Set; public class Road { private final String name; private final double length; private final Set<String> cities; public Road(String name, double length, String fromCity, String toCity) { this.name = name; this.length = length; cities = new HashSet<>(); cities.add(fromCity); cities.add(toCity); } public String getName() { return name; } public double getLength() { return length; } public Set<String> getCities() { return cities; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Road road = (Road) o; return name.equals(road.name); } @Override public int hashCode() { return Objects.hash(name); } @Override public String toString() { return "Road{" + "name='" + name + '\'' + ", length=" + length + '}'; } }
true
7ca0a1c52d088706bb14f7208c3e07c4641e4e4c
Java
foryoung2018/videoedit
/DongCi_Android/app/src/main/java/com/wmlive/hhvideo/widget/dialog/BaseDialog.java
UTF-8
1,613
2.3125
2
[]
no_license
package com.wmlive.hhvideo.widget.dialog; import android.app.Activity; import android.app.Dialog; import android.content.Context; import cn.wmlive.hhvideo.R; /** * 基础对话框 * (携带阴影背景) */ public class BaseDialog extends Dialog { public Context mContext; public OnActionSheetSelected mOnActionSheetSelected; public BaseDialogOnclicklistener mBaseDialogOnclicklistener; /** * 存放订阅的容器,方便统一解除订阅 */ public BaseDialog(Context context, int styleId) { super(context, styleId); if (context instanceof Activity) { setOwnerActivity((Activity) context); } mContext = context; } public BaseDialog(Context context) { super(context, R.style.BaseDialogTheme); if (context instanceof Activity) { setOwnerActivity((Activity) context); } mContext = context; } public void setmOnActionSheetSelected(OnActionSheetSelected mOnActionSheetSelected) { this.mOnActionSheetSelected = mOnActionSheetSelected; } public void setmBaseDialogOnclicklistener(BaseDialogOnclicklistener mBaseDialogOnclicklistener) { this.mBaseDialogOnclicklistener = mBaseDialogOnclicklistener; } /** * 轮子列表 */ public static interface OnActionSheetSelected { void onClick(int whichButton); } /** * 确定与取消按钮 */ public static interface BaseDialogOnclicklistener { public void onOkClick(Dialog dialog); public void onCancleClick(Dialog dialog); } }
true
d5d2dfc367c843ac9215884f2e4523cc1aaf9477
Java
hpplayer/LeetCode_Round_3
/src/Shortest_Word_Distance_III_p245_sol1.java
WINDOWS-1250
3,017
4.03125
4
[]
no_license
/* 245. Shortest Word Distance III This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2. Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. word1 and word2 may be the same and they represent two individual words in the list. For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. Given word1 = makes, word2 = coding, return 1. Given word1 = "makes", word2 = "makes", return 3. Note: You may assume word1 and word2 are both in the list. */ /** * Intuitive solution * * This problem is an advanced version of Shortest_Word_Distance_I_p243_sol1 with a small modification. * We still use the idea of just comparing the latest index of two inputs * The main body is same, each time we found word1 or word2, we will calculate difference of current index with the index of other word * However now, we allow two inputs to have the same value. In our program, if two inputs are same, then they will always be caught in first if block, which * means we will always update index1 if two inputs are same. Therefore we just need to check if two inputs are same, then check if we have recorded index1 * before, then our program will handle same input case. * So just a small modification and we are good to go! * * Time complexity: O(N) * Space complexity: O(1) * * @author hpPlayer * @date Mar 8, 2016 5:18:20 PM */ public class Shortest_Word_Distance_III_p245_sol1 { public int shortestWordDistance(String[] words, String word1, String word2) { //intuitive idea. similar to Shortest_Word_Distance_I_p243_sol1, but now we need handle same input case in the first if block //we still update the index each time we see a word appears, and check distance for each update, since keep old index will not help us get a shorter distance int index1 = -1, index2 = -1; int result = Integer.MAX_VALUE; for(int i = 0; i < words.length; i++){ if(words[i].equals(word1)){ //index2 will only be updated when two inputs are different //if two inputs are same, then we will only update index1, so if index2 is updated, we are sure two inputs are different if(index2 != -1) result = Math.min(result, i - index2); //Here we only compare index1 with i, if two inputs are same. If two inputs are different, we require comparing index1 with index2 if(word1.equals(word2) && index1 != -1) result = Math.min(result, i - index1); index1 = i; }else if(words[i].equals(word2)){ //we will come to this block only when two inputs are different, therefore the body will be same with Shortest_Word_Distance_I_p243_sol1 if(index1 != -1) result = Math.min(result, i - index1); index2 = i; } } return result; } }
true
330385efa42a35f606530c5da55f6b226243e1c5
Java
luis572/Proyecto1AREP
/src/main/java/edu/escuelaing/arem/framework/pojo.java
UTF-8
1,182
2.40625
2
[ "MIT" ]
permissive
/* * 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 edu.escuelaing.arem.framework; import edu.escuelaing.arem.*; /** * * @author 2137497 */ public class pojo { @web("/cuadrado") public static String cuadraro(String n){ int respuesta=Integer.parseInt(n); respuesta=respuesta*respuesta; return Integer.toString(respuesta); } @html("/cuadra") public static String prueba(String n){ int respuesta=Integer.parseInt(n); respuesta=respuesta*respuesta; return Integer.toString(respuesta); } @web("/suma") public static String suma(String n,String n2){ int respuesta=Integer.parseInt(n); int respuesta2=Integer.parseInt(n2); return Integer.toString(respuesta+respuesta2); } @web("/sumacuadrados") public static String sumacuadrados(String n,String n2){ int respuesta=Integer.parseInt(n); int respuesta2=Integer.parseInt(n2); return Integer.toString(respuesta*respuesta+respuesta2*respuesta2); } }
true
3073d018af30ed8d07518ab8c286fd466f4cfe15
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_d673d08d515ae3f28e95c6bf7813496d36d056c3/FlowUnitPow/2_d673d08d515ae3f28e95c6bf7813496d36d056c3_FlowUnitPow_s.java
UTF-8
2,006
2.703125
3
[]
no_license
/*** * Copyright (C) 2010 Johan Henriksson * This code is under the Endrov / BSD license. See www.endrov.net * for the full text and how to cite. */ package endrov.flowBasic.math; import java.util.Map; import endrov.flow.BadTypeFlowException; import endrov.flow.Flow; import endrov.flow.FlowExec; import endrov.flow.FlowUnitDeclaration; import endrov.typeImageset.AnyEvImage; /** * Flow unit: a^b * @author Johan Henriksson * */ public class FlowUnitPow extends FlowUnitMathBinop { private static final String metaType="add"; /****************************************************************************************************** * Plugin declaration *****************************************************************************************************/ public static void initPlugin() {} static { Flow.addUnitType(new FlowUnitDeclaration("Math","PowerOf",metaType,FlowUnitPow.class, null,"One value to the power of another e.g x^3=x*x*x")); } public FlowUnitPow() { super("A^B",metaType); } public void evaluate(Flow flow, FlowExec exec) throws Exception { Map<String,Object> lastOutput=exec.getLastOutput(this); lastOutput.clear(); Object a=flow.getInputValue(this, exec, "A"); Object b=flow.getInputValue(this, exec, "B"); if(a instanceof Number && b instanceof Number) lastOutput.put("C", NumberMath.pow((Number)a, (Number)b)); else if(a instanceof AnyEvImage && b instanceof Number) lastOutput.put("C", new EvOpImagePowScalar((Number)b).exec1Untyped(exec.ph, (AnyEvImage)a));/* else if(b instanceof AnyEvImage && a instanceof Number) lastOutput.put("C", new EvOpImagePowScalar((Number)a).exec1Untyped((AnyEvImage)b)); else if(a instanceof AnyEvImage && b instanceof AnyEvImage) lastOutput.put("C", new EvOpImageAddImage().exec1Untyped((AnyEvImage)a, (AnyEvImage)b));*/ else throw new BadTypeFlowException("Unsupported numerical types "+a.getClass()+" & "+b.getClass()); } }
true
5bcb539981e6bdbe62d4027bcbbd5b769be0b593
Java
1804Apr23Java/MubangJ
/JDBCBank/src/main/java/com/Revature/Dao/AccountDaoImpl.java
UTF-8
6,256
2.796875
3
[ "MIT" ]
permissive
package com.Revature.Dao; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.Revature.Exceptions.AccountAlreadyExistException; import com.Revature.Exceptions.AccountDoesNotExistException; import com.Revature.Exceptions.AccountHasMoreThanZeroDollarsException; import com.Revature.Exceptions.OverDraftException; import com.Revature.Tables.Account; public class AccountDaoImpl implements AccountDao { private String filename = "connection.properties"; @Override public List<Account> getAccounts(int userId) { List<Account> accounts = new ArrayList<>(); PreparedStatement pstmt = null; try (Connection conn = ConnectionUtil.getConnectionFromFile(filename)) { String sql = "SELECT a.USER_ID, a.ACCOUNT_NAME, a.AMOUNT, u.USER_NAME FROM ACCOUNTS a INNER JOIN USERS u ON u.USER_ID = a.USER_ID WHERE a.USER_ID = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userId); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String username = rs.getString("USER_NAME"); String accountName = rs.getString("ACCOUNT_NAME"); int amount = rs.getInt("AMOUNT"); int userID = rs.getInt("USER_ID"); accounts.add(new Account(username, accountName, amount, userID)); } conn.close(); } catch (IOException | SQLException e2) { e2.printStackTrace(); } return accounts; } @Override public Account getAccountById(int userId, String accountName) { Account account = null; PreparedStatement pstmt = null; try (Connection conn = ConnectionUtil.getConnectionFromFile(filename)) { String sql = "SELECT a.USER_ID, a.ACCOUNT_NAME, a.AMOUNT, u.USER_NAME " + "FROM ACCOUNTS a " + "INNER JOIN USERS u ON u.USER_ID = a.USER_ID " + "WHERE a.USER_ID = ? AND a.ACCOUNT_NAME = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userId); pstmt.setString(2, accountName); ResultSet rs = pstmt.executeQuery(); if (!rs.next()) { throw new AccountDoesNotExistException(); } String username = rs.getString("USER_NAME"); String nameOfAccount = rs.getString("ACCOUNT_NAME"); int amount = rs.getInt("AMOUNT"); int userID = rs.getInt("USER_ID"); account = new Account(username, nameOfAccount, amount, userID); conn.close(); } catch (AccountDoesNotExistException e) { System.out.println(e.getMessage()); return account; } catch (IOException | SQLException e) { e.printStackTrace(); } return account; } @Override public boolean insertAccount(int userId, String accountName, double amount) { PreparedStatement pstmt = null; List<Account> accounts = new ArrayList<>(); accounts = getAccounts(userId); try(Connection conn = ConnectionUtil.getConnectionFromFile(filename)) { for (Account account : accounts) { if (account.getAccountName().equals(accountName)) { throw new AccountAlreadyExistException(); } } if (amount < 0) { throw new OverDraftException(); } String sql = "INSERT INTO ACCOUNTS (USER_ID, ACCOUNT_NAME) VALUES (?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userId); pstmt.setString(2, accountName); int i = 0; i = pstmt.executeUpdate(); conn.close(); if (i > 0) return true; return false; } catch (AccountAlreadyExistException | OverDraftException e) { System.out.println(e.getMessage() + " ( " + accountName + " )"); return false; } catch (IOException | SQLException e2) { e2.printStackTrace(); } return false; } @Override public boolean updateAccount(int userId, String accountName, double amount) { PreparedStatement pstmt = null; Account account = null; try (Connection conn = ConnectionUtil.getConnectionFromFile(filename)) { account = getAccountById(userId, accountName); if (account == null) { throw new AccountDoesNotExistException(); } if ( (amount * -1) > account.getAmount()) { throw new OverDraftException(); } // using a Statement - beware SQL injection String sql = null; sql = "UPDATE ACCOUNTS SET AMOUNT = AMOUNT + ? WHERE USER_ID = ? AND ACCOUNT_NAME = ?"; pstmt = conn.prepareStatement(sql); pstmt.setDouble(1, amount); pstmt.setInt(2, userId); pstmt.setString(3, accountName); int i = pstmt.executeUpdate(); conn.close(); if (i > 0) return true; } catch (OverDraftException e) { System.out.println(e.getMessage()); } catch (AccountDoesNotExistException e2) { e2.getMessage(); } catch (IOException | SQLException e3) { e3.printStackTrace(); } return false; } @Override public boolean deleteAccount(int userId, String accountName) { PreparedStatement pstmt = null; Account account = null; try (Connection conn = ConnectionUtil.getConnectionFromFile(filename)) { account = getAccountById(userId, accountName); if (account == null) { throw new AccountDoesNotExistException(); } if (account.getAmount() != 0) { throw new AccountHasMoreThanZeroDollarsException(); } String sql = "DELETE FROM ACCOUNTS WHERE USER_ID = ? AND ACCOUNT_NAME = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userId); pstmt.setString(2, accountName); int i = pstmt.executeUpdate(); conn.close(); if (i > 0) return true; } catch (AccountHasMoreThanZeroDollarsException | AccountDoesNotExistException e2) { e2.getMessage(); } catch (IOException | SQLException e) { e.printStackTrace(); } return false; } @Override public boolean superDeleteAccounts(int userId) { PreparedStatement pstmt = null; try (Connection conn = ConnectionUtil.getConnectionFromFile(filename)) { String sql = "DELETE FROM ACCOUNTS WHERE USER_ID = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userId); int i = pstmt.executeUpdate(); conn.close(); if (i > 0) return true; else { throw new AccountDoesNotExistException(); } } catch (AccountDoesNotExistException e) { System.out.println(e.getMessage()); } catch (IOException | SQLException e) { e.printStackTrace(); } return false; } }
true
1315113c7b3c30acf5ee139f90a5cc2c61485ec2
Java
troytung/mrp
/src/main/java/com/petfood/mrp/model/DailySchedule.java
UTF-8
1,468
1.984375
2
[]
no_license
package com.petfood.mrp.model; import java.sql.Date; public class DailySchedule extends BaseObject { private Date schedule_dt; private String pro_code; private Integer target_amt; private Integer produced_amt; private Integer packed_amt; private String cus_name; private String pro_name; public Date getSchedule_dt() { return schedule_dt; } public void setSchedule_dt(Date schedule_dt) { this.schedule_dt = schedule_dt; } public String getPro_code() { return pro_code; } public void setPro_code(String pro_code) { this.pro_code = pro_code; } public Integer getTarget_amt() { return target_amt; } public void setTarget_amt(Integer target_amt) { this.target_amt = target_amt; } public Integer getProduced_amt() { return produced_amt; } public void setProduced_amt(Integer produced_amt) { this.produced_amt = produced_amt; } public Integer getPacked_amt() { return packed_amt; } public void setPacked_amt(Integer packed_amt) { this.packed_amt = packed_amt; } public String getCus_name() { return cus_name; } public void setCus_name(String cus_name) { this.cus_name = cus_name; } public String getPro_name() { return pro_name; } public void setPro_name(String pro_name) { this.pro_name = pro_name; } }
true
32295224cd24454cf136031a971ea35967efa0ab
Java
gallb/library2
/library2common/src/main/java/edu/msg/library2common/service/rmi/BorrowServiceRmi.java
UTF-8
929
2.609375
3
[]
no_license
package edu.msg.library2common.service.rmi; import java.rmi.Remote; import java.rmi.RemoteException; import java.sql.Date; import edu.msg.library2common.model.Publication; import edu.msg.library2common.model.User; /** * Provides publication borrowing related services * * @author gallb * */ public interface BorrowServiceRmi extends Remote{ public static final String RMI_NAME = "Borrow"; /** * * @param user - User object representing the person who borrows the book * @param pub - publication object to be borrowed * @param from - sql date containing the value when the book is borrowed * @param until - sql date containing the value until the book must be returned * @return true if the borrow was succesfull false if not * @throws RemoteException */ public boolean borrowPublication (User user, Publication pub, Date from, Date until) throws RemoteException; }
true
6ce7fdce976d957f69787e5b521544bd58c9af0c
Java
limallucas96/hoteliva
/app/src/main/java/com/example/lucas/deliva/data/model/Order.java
UTF-8
1,083
2.203125
2
[]
no_license
package com.example.lucas.deliva.data.model; import com.example.lucas.deliva.data.model.Menu; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.List; public class Order implements Serializable { @SerializedName("id_resident") private Integer userId; @SerializedName("id_room") private Integer roomId; @SerializedName("service") private List<Menu> menuList; private Double orderCost = 0.0; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getRoomId() { return roomId; } public void setRoomId(Integer roomId) { this.roomId = roomId; } public List<Menu> getMenuList() { return menuList; } public void setMenuList(List<Menu> menuList) { this.menuList = menuList; } public Double getOrderCost() { return orderCost; } public void setOrderCost(Double orderCost) { this.orderCost = orderCost; } }
true
76433a8dbc6346c7ae705a5497614ed4df0c381a
Java
shourov-alam/MVVM-Architecture
/app/src/main/java/com/sh/mvvmpractise/User_Adapter.java
UTF-8
1,826
2.21875
2
[]
no_license
package com.sh.mvvmpractise; import android.location.Geocoder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; public class User_Adapter extends RecyclerView.Adapter<User_Adapter.UserViewHolder> { private UserPojo[] userPojos; public User_Adapter(UserPojo[] userPojos) { this.userPojos = userPojos; } @NonNull @Override public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext()); View view=layoutInflater.inflate(R.layout.user_list,parent,false); return new UserViewHolder(view); } @Override public void onBindViewHolder(@NonNull UserViewHolder holder, int position) { holder.name.setText(userPojos[position].getLogin()); holder.id.setText(String.valueOf(userPojos[position].getId())); holder.userUrl.setText(userPojos[position].getUrl()); Glide.with(holder.imageView.getContext()).load(userPojos[position].getAvatarUrl()).into(holder.imageView); } @Override public int getItemCount() { return userPojos.length; } public class UserViewHolder extends RecyclerView.ViewHolder{ ImageView imageView; TextView name,id,userUrl; public UserViewHolder(@NonNull View itemView) { super(itemView); imageView=itemView.findViewById(R.id.images); name=itemView.findViewById(R.id.name); id = itemView.findViewById(R.id.name2); userUrl=itemView.findViewById(R.id.name3); } } }
true
19a415a2d100ec486ab1bd28ffec807ad459054b
Java
SKupreeva/University
/3 course/1 semester/SITAIRIS/Lab 4-5/src/success.java
UTF-8
158
2.25
2
[]
no_license
public class success implements infoType{ @Override public void showType() { System.out.println("Info was successfully extracted."); } }
true
71a9d2dcb8eac495a19db3b2730a9f70678238c3
Java
peace0phmind/blauto
/src/main/java/com/peace/auto/bl/task/ShenQi.java
UTF-8
7,099
2.265625
2
[]
no_license
package com.peace.auto.bl.task; import com.peace.auto.bl.Status; import com.peace.auto.bl.Task; import lombok.extern.slf4j.Slf4j; import org.sikuli.script.FindFailed; import org.sikuli.script.Match; import org.sikuli.script.Pattern; import org.sikuli.script.Region; import java.awt.*; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by mind on 4/30/16. */ @Slf4j public class ShenQi implements IDo { private static final String baseDir = Common.BASE_DIR + "shenqi/"; public boolean Done(Region region, Status status) throws FindFailed, InterruptedException { Match bashou = region.exists(new Pattern(baseDir + "shengyu.png").similar(0.9f), 15); if (bashou != null) { move(bashou, bashou.getCenter().above(300), 1000); Match shenqi = region.exists(baseDir + "shenqi.png"); if (shenqi != null) { shenqi.click(); Thread.sleep(6000L); // 神器召唤 if (status.canDo(Task.SHEN_QI)) { Match zhaohuan = region.exists(baseDir + "zhaohuan.png"); if (zhaohuan != null) { zhaohuan.click(); Thread.sleep(1000L); Match mianfeizhaohuan = region.exists(baseDir + "mianfeizhaohuan.png"); if (mianfeizhaohuan != null) { Thread.sleep(1000L); mianfeizhaohuan.click(); status.Done(Task.SHEN_QI); Thread.sleep(500L); region.click(Common.QUE_DING); } } Thread.sleep(500L); } // 神像升级 if (status.canDo(Task.SHEN_XIANG_SHENG_JI)) { Match shengji = region.exists(baseDir + "shengji.png"); if (shengji != null) { shengji.click(); boolean bjb = false; List<LocalDateTime> times = new ArrayList<>(); List<String> strings = Arrays.asList("jianling.png", "yongling.png", "moling.png", "paoling.png"); int i1 = LocalDateTime.now().getDayOfYear() % 4; for (int j = 0; j < 4; j++) { String shenxiang = strings.get((j + i1) % 4); Match sx = region.exists(baseDir + shenxiang); if (sx != null) { sx.click(); Thread.sleep(500L); // 免费倒计时不存在,则进行免费祭拜 Match daojishi = region.exists(baseDir + "mianfeidaojishi.png"); if (daojishi == null) { Match jb = region.exists(baseDir + "mianfeijibai.png"); if (jb != null) { jb.click(); log.info("祭拜 : {}", shenxiang); bjb = true; } Match gp = region.exists(baseDir + "gongpinjibai.png"); if (gp != null) { for (int i = 0; i < 3; i++) { gp.click(); Match cishu = region.exists(baseDir + "dadaomeiricishu.png"); if (cishu != null) { region.click(Common.QUE_DING); break; } Match chongzhi = region.exists(baseDir + "chongzhi.png"); if (chongzhi != null) { clickInside(region, Common.CLOSE); Thread.sleep(3000l); break; } } } } else { //// String sTime = getWord(daojishi.right(70), "1234567890:"); String sTime = getTime(daojishi.right(70), Arrays.asList(new Color(52, 190, 30), new Color(52, 206, 29), new Color(51, 159, 31))); log.info("sTime: {}", sTime); String[] split = sTime.split(":"); if (split.length == 3) { try { times.add(LocalDateTime.now().plusHours(Integer.parseInt(split[0].trim())) .plusMinutes(Integer.parseInt(split[1].trim())) .plusSeconds(Integer.parseInt(split[2].trim()))); } catch (Exception e) { log.info("{}", e); } } } } } if (bjb) { status.Done(Task.SHEN_XIANG_SHENG_JI); } else { // if (times.size() > 0) { // LocalDateTime largerTime = times.stream().sorted((x, y) -> y.compareTo(x)).findFirst().get(); // log.info("Times: {}, largerTime: {}", times, largerTime); // status.Done(Task.SHEN_XIANG_SHENG_JI, largerTime); // } status.Done(Task.SHEN_XIANG_SHENG_JI, Status.nextCheck()); } } } Thread.sleep(500L); region.click(Common.CLOSE); Thread.sleep(500L); } for (int i = 0; i < 6; i++) { bashou = region.exists(new Pattern(baseDir + "shengyu.png").similar(0.9f), 15); if (bashou != null) { move(bashou, bashou.getCenter().below(300), 1000); return true; } } } return false; } @Override public boolean CanDo(Status status, String userName) { if (!status.canDo(Task.SHEN_QI, userName) && !status.canDo(Task.SHEN_XIANG_SHENG_JI, userName)) { return false; } return true; } }
true
df293b19627ac7881037e4b515a3a3e3e962c23f
Java
GhMelo/LembretesJera
/src/main/java/com/lembreteslivros/Controller/LivrosController.java
UTF-8
1,479
2.21875
2
[]
no_license
package com.lembreteslivros.Controller; import com.lembreteslivros.Model.ListaLivros; import com.lembreteslivros.Repository.LivrosRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RequestMapping("/livroscontroller") @RestController @CrossOrigin (origins = {"*"}) //Aqui defino as urls das requisiçoes, qual metodo sera utilizado e qual verbo web sera utilizado, como post, put, get ou delete //os testes que eu estou fazendo estao sendo no postman, com url direto, pois primeiro crio a api-rest, para depois fazer o frontend //os metodos de busca sao anteriormente definidos no LivrosRepository, e alguns sao utilizados nativos do Springboot public class LivrosController { @Autowired private LivrosRepository livrosRepository; @PostMapping @CrossOrigin (origins = {"*"}) public ListaLivros adicionar(@RequestBody ListaLivros listaLivros) { return livrosRepository.save(listaLivros); } @PutMapping @CrossOrigin (origins = {"*"}) public ListaLivros alterar(@RequestBody ListaLivros listaLivros) { return livrosRepository.save(listaLivros); } @GetMapping @CrossOrigin (origins = {"*"}) List<ListaLivros> mostrarTodos(){ return livrosRepository.buscarTodos(); } @DeleteMapping("/{id}") public void deletar (@PathVariable("id") Integer id){ livrosRepository.delete(id); } }
true
03ed181c2fbc6fcafe51acfbb805d4cf09e4bc5a
Java
bitwiseTek/rivson-web
/rssson-master/persistence/src/main/java/com/bitwise/manageme/rssson/service/users/StaffMemberServiceImpl.java
UTF-8
2,303
2.03125
2
[]
no_license
package com.bitwise.manageme.rssson.service.users; /** * * @author Sika Kay * @date 30/06/16 * */ import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; //import com.bitwise.manageme.rssson.domain.base.Email; import com.bitwise.manageme.rssson.domain.users.StaffMember; import com.bitwise.manageme.rssson.repository.users.StaffMemberRepository; import com.google.common.collect.Lists; @Transactional @Service("staffMemberService") public class StaffMemberServiceImpl implements StaffMemberService { @Autowired private StaffMemberRepository staffMemberRepo; @Override @Transactional(readOnly=true) public List<StaffMember> findAll() { return Lists.newArrayList(this.staffMemberRepo.findAll()); } @Override @Transactional(readOnly=true) public List<StaffMember> findByUserVariables(String key, String value) { return this.staffMemberRepo.findByUserVariables(key, value); } @Override @Transactional(readOnly=true) public List<StaffMember> findByNotRoles(String role, Integer firstResult, Integer maxResult) { return this.staffMemberRepo.findByNotRoles(role, firstResult, maxResult); } /*@Override @Transactional(readOnly=true) public List<StaffMember> findByUniqueEmails(Email email) { return this.staffMemberRepo.findByUniqueEmails(email); }*/ @Override @Transactional(readOnly=false) public StaffMember save(StaffMember staffMember) { return this.staffMemberRepo.save(staffMember); } @Override public void delete(StaffMember staffMember) { this.staffMemberRepo.delete(staffMember); } @Override public StaffMember findById(Long id) { return this.staffMemberRepo.findOne(id); } @Override @Transactional(readOnly=true) public Page<StaffMember> findByStaffId(String staffId, Pageable pageable) { return this.staffMemberRepo.findByStaffId(staffId, pageable); } @Override public Page<StaffMember> findAll(Pageable pageable) { return this.staffMemberRepo.findAll(pageable); } @Override public StaffMember findByStaffId(String staffId) { return this.staffMemberRepo.findByStaffId(staffId); } }
true
9d78edd397dbc45082271affd9b89c6345921e00
Java
AlexanderPopadyuk/Patterns
/src/Composite/Order.java
UTF-8
91
1.851563
2
[]
no_license
/** * Created by Asus on 21.03.2016. */ public interface Order { void toDeliver(); }
true
d8f3a248b60076cb27efa71aa2cc063952d18e8e
Java
xtf-cz/xtf
/core/src/main/java/cz/xtf/core/openshift/PodShell.java
UTF-8
3,073
2.53125
3
[ "MIT" ]
permissive
package cz.xtf.core.openshift; import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import cz.xtf.core.waiting.SimpleWaiter; import cz.xtf.core.waiting.WaiterException; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.client.dsl.ExecListener; import lombok.extern.slf4j.Slf4j; @Slf4j public class PodShell { private final OpenShift openShift; private final String podName; private final String containerName; private final ByteArrayOutputStream baosOutput; private final ByteArrayOutputStream baosError; public PodShell(OpenShift openShift, String dcName) { this(openShift, openShift.getAnyPod(dcName)); } public PodShell(OpenShift openShift, Pod pod) { this(openShift, pod, null); } public PodShell(OpenShift openShift, Pod pod, String containerName) { this.openShift = openShift; this.podName = pod.getMetadata().getName(); this.containerName = containerName; this.baosOutput = new ByteArrayOutputStream(); this.baosError = new ByteArrayOutputStream(); } public PodShellOutput executeWithBash(String command) { return execute("bash", "-c", command); } public PodShellOutput execute(String... commands) { baosOutput.reset(); baosError.reset(); StateExecListener execListener = new StateExecListener(); if (containerName == null) { openShift.pods().withName(podName).writingOutput(baosOutput).writingError(baosError).usingListener(execListener) .exec(commands); } else { openShift.pods().withName(podName).inContainer(containerName).writingOutput(baosOutput).writingError(baosError) .usingListener(execListener).exec(commands); } new SimpleWaiter(execListener::hasExecutionFinished).timeout(TimeUnit.MINUTES, 1) .reason("Waiting for " + Arrays.toString(commands) + " execution in '" + podName + "' pod.").waitFor(); try { new SimpleWaiter(() -> baosOutput.size() > 0 || baosError.size() > 0).timeout(TimeUnit.SECONDS, 10).waitFor(); } catch (WaiterException e) { log.warn("Output from PodShell's execution didn't appear in 10 seconds after channel close."); } return new PodShellOutput(baosOutput.toString().trim(), baosError.toString().trim()); } public class StateExecListener implements ExecListener { private final AtomicBoolean executionDone = new AtomicBoolean(false); @Override public void onOpen() { // DO NOTHING } @Override public void onFailure(Throwable throwable, Response response) { // DO NOTHING } @Override public void onClose(int i, String s) { executionDone.set(true); } public boolean hasExecutionFinished() { return executionDone.get(); } } }
true
35f849b527a361a964cf35ffb4b67b4822c08308
Java
eobermuhlner/wiki-spiderweb
/app/src/main/java/ch/obermuhlner/android/lib/view/graph/LruMap.java
UTF-8
417
2.578125
3
[]
no_license
package ch.obermuhlner.android.lib.view.graph; import java.util.LinkedHashMap; public class LruMap<K,V> extends LinkedHashMap<K, V> { private static final long serialVersionUID = 0L; private int maxSize; public LruMap(int maxSize) { super(16, 0.75f, true); this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) { return size() > maxSize; } }
true
7bbf03c3c42655a542f2e3fc50e94a1a605aece7
Java
Lambolez/DAE_PIDR
/DAE_Database/src/edu/lehigh/dae/utility/general/Description.java
UTF-8
376
1.9375
2
[]
no_license
package edu.lehigh.dae.utility.general; import java.util.Vector; import org.xml.sax.Attributes; public class Description { public Vector<String> elements; public Vector<Attributes> attrs; public Vector<String> values; public Description() { elements = new Vector<String>(); attrs = new Vector<Attributes>(); values = new Vector<String>(); } }
true
d1ee7f74425f8f69d3a2e0853b67f623e39c4396
Java
debjyoti-pandit/SecurityApplication
/app/src/main/java/com/example/debjyotipandit/wawasan/SecurityVisitorsOTP.java
UTF-8
3,422
1.984375
2
[]
no_license
package com.example.debjyotipandit.wawasan; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import bean.Message; import bean.VisitorBean; public class SecurityVisitorsOTP extends AppCompatActivity { private EditText phone, otp; private Button validate; //private View matched, notMatched; private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.security_visitors_otp); phone = findViewById(R.id.secVisitorsPhone); otp = findViewById(R.id.secVisitorsOTP); validate = findViewById(R.id.secVisCheck); validate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { Query query = mDatabase.child(getString(R.string.visitorsCollectionName).toString()).orderByChild("mobileNumber").equalTo(Long.parseLong(phone.getText().toString())); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()) { Message.message(getApplicationContext(), "Before printing key"); Message.message(getApplicationContext(), singleSnapshot.getKey()); VisitorBean visitorBean = singleSnapshot.getValue(VisitorBean.class); Message.message(getApplicationContext(),String.valueOf(visitorBean.getOtpGenerated())); // final View matched = findViewById(R.id.visitorsMatched); // final View notMatched = findViewById(R.id.visitorsNotMatched); if(visitorBean.getOtpGenerated() == Integer.parseInt(otp.getText().toString())){ Message.message(getApplicationContext(),"OTP matched"); otp.getText().clear(); phone.getText().clear(); // matched.setVisibility(View.VISIBLE); // notMatched.setVisibility(View.INVISIBLE); }else{ Message.message(getApplicationContext(),"Sorry! but the OTP didn't matched"); // matched.setVisibility(View.INVISIBLE); // notMatched.setVisibility(View.VISIBLE); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }); } }
true
76807efe7d808652129b22cc0fdddc64c3a27dee
Java
KNMI/climate4impact-portal
/src/model/Predictand.java
UTF-8
4,317
2.59375
3
[]
no_license
package model; import org.json.JSONException; import org.json.JSONObject; public class Predictand { private int zone; private String predictand; private String predictor; private String description; private String dataset; private String variable; private String variableType; private float startLat; private float startLon; private float endLat; private float endLon; private float resLat; private float resLon; private Predictand(PredictandBuilder builder){ this.zone = builder.zone; this.predictand = builder.predictand; this.predictor = builder.predictor; this.description = builder.description; this.dataset = builder.dataset; this.variable = builder.variable; this.variableType = builder.variableType; this.startLat = builder.startLat; this.startLon = builder.startLon; this.endLat = builder.endLat; this.endLon = builder.endLon; this.resLat = builder.resLat; this.resLon = builder.resLon; } public static class PredictandBuilder { private int zone; private String predictand; private String predictor; private String description; private String dataset; private String variable; private String variableType; private float startLat; private float startLon; private float endLat; private float endLon; private float resLat; private float resLon; public PredictandBuilder(JSONObject jsonObject){ try { this.zone = jsonObject.getInt("zone"); this.predictand = jsonObject.getString("predictand"); this.predictor = jsonObject.getString("predictor"); this.description = jsonObject.getString("description"); this.dataset = jsonObject.getString("dataset"); this.variable = jsonObject.getString("variable"); this.variableType = jsonObject.getString("variableType"); this.startLat = Float.parseFloat(jsonObject.getString("startLat")); this.startLon = Float.parseFloat(jsonObject.getString("startLon")); this.endLat = Float.parseFloat(jsonObject.getString("endLat")); this.endLon = Float.parseFloat(jsonObject.getString("endLon")); this.resLat = Float.parseFloat(jsonObject.getString("resLat")); this.resLon = Float.parseFloat(jsonObject.getString("resLon")); } catch (JSONException e) { e.printStackTrace(); } } public Predictand build(){ return new Predictand(this); } } public int getZone() { return zone; } public void setZone(int zone) { this.zone = zone; } public String getPredictand() { return predictand; } public void setPredictand(String predictand) { this.predictand = predictand; } public String getPredictor() { return predictor; } public void setPredictor(String predictor) { this.predictor = predictor; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDataset() { return dataset; } public void setDataset(String dataset) { this.dataset = dataset; } public String getVariable() { return variable; } public void setVariable(String variable) { this.variable = variable; } public String getVariableType() { return variableType; } public void setVariableType(String variableType) { this.variableType = variableType; } public float getStartLat() { return startLat; } public void setStartLat(float startLat) { this.startLat = startLat; } public float getStartLon() { return startLon; } public void setStartLon(float startLon) { this.startLon = startLon; } public float getEndLat() { return endLat; } public void setEndLat(float endLat) { this.endLat = endLat; } public float getEndLon() { return endLon; } public void setEndLon(float endLon) { this.endLon = endLon; } public float getResLat() { return resLat; } public void setResLat(float resLat) { this.resLat = resLat; } public float getResLon() { return resLon; } public void setResLon(float resLon) { this.resLon = resLon; } }
true
9daef4e1ae5a0c70d8e80deb4ac938bf19a4c087
Java
huangjie1991/spring-config
/src/main/java/com/demo/app/SpringConfigApplication.java
UTF-8
424
1.648438
2
[]
no_license
package com.demo.app; import org.springframework.boot.SpringApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.config.server.EnableConfigServer; /** * 配置中心 */ @EnableConfigServer @SpringCloudApplication public class SpringConfigApplication { public static void main(String[] args) { SpringApplication.run(SpringConfigApplication.class, args); } }
true
7cc45df24cfc4bb0dc167d15a838fa6e84e3576c
Java
RafaSalgado/dataStructures
/Comparablee.java
UTF-8
1,119
3.703125
4
[]
no_license
import java.util.ArrayList; import java.util.Collections; public class Comparablee { public static class Person implements Comparable<Person> { String nombre; int semestre; int edad; public Person(String nomnbre, int edad, int semestre) { this.nombre = nomnbre; this.semestre = semestre; this.edad = edad; } @Override public int compareTo(Person o) { if (this.semestre < o.semestre) return -1; else if (semestre > o.semestre) return 1; else { if (edad < o.edad) return -1; else if (edad > o.edad) return 1; } return 0; } } public static void main(String args[]) { ArrayList<Person> persons = new ArrayList<Person>(); persons.add(new Person("jose", 22, 7)); persons.add(new Person("juan", 18, 6)); persons.add(new Person("pedro", 25, 4)); persons.add(new Person("Maria", 30, 9)); persons.add(new Person("Andres", 17, 7)); Collections.sort(persons); for (int i = 0; i < persons.size(); i++) { System.out.println(persons.get(i).nombre + " " + persons.get(i).semestre); } } }
true
452fc7a906fd80f12e17f8a813b99d9abd0798fb
Java
lfdel24/ceiba-backend-crud-personas
/src/main/java/com/lfdel24/crud/dominio/modelo/ValidadorArgumento.java
UTF-8
399
2.53125
3
[]
no_license
package com.lfdel24.crud.dominio.modelo; import com.lfdel24.crud.dominio.exepcion.ExcepcionValorObligatorio; public class ValidadorArgumento { private ValidadorArgumento() { }; public static void validarObligatorio(Object valor, String mensaje) { if (valor == null || valor.toString().isEmpty()) { throw new ExcepcionValorObligatorio(mensaje); } } }
true
6e0dffd4deff5a9bf55997762eb88c39cc6a12a1
Java
Dmm-PS/lost-isle-150-vernox-runesuite
/src/main/java/org/rs2server/rs2/domain/model/player/treasuretrail/clue/ClueScrollRewards.java
UTF-8
21,494
2.328125
2
[ "MIT" ]
permissive
package org.rs2server.rs2.domain.model.player.treasuretrail.clue; import org.rs2server.rs2.domain.service.api.loot.Loot; import org.rs2server.rs2.domain.service.api.loot.LootTable; import org.rs2server.rs2.util.Misc; /** * Defines clue scroll rewards. * * @author tommo */ public class ClueScrollRewards { public static final LootTable JUNK_REWARDS_TABLE = LootTable.of( Loot.of(1269, 30), // Steel Pickaxe Loot.of(849, 30), // Willow Shortbow Loot.of(1271, 30), // Adamant Pickaxe Loot.of(1381, 30), // Staff of Air Loot.of(1169, 30), // Coif Loot.of(1095, 30), // Leather Chaps Loot.of(1131, 30), // Hardleather Body //Black items Loot.of(1217, 30), // Black Dagger Loot.of(1367, 30), // Black Battleaxe Loot.of(1361, 30), // Black Axe Loot.of(1297, 30), // Black Longsword Loot.of(1077, 30), // Black Platelegs Loot.of(1125, 30), // Black Platebody Loot.of(1165, 30) // Black Full helm ); public static final LootTable BASIC_REWARDS_TABLE = LootTable.of( Loot.of(995, 5000, 25000, 75), // Cash money Loot.of(4561, 5, 50, 75), // Purple sweets Loot.of(380, 5, 60, 30), // lobsters Loot.of(556, 80, 300, 30), // Air Runes Loot.of(554, 80, 300, 30), // Fire Runes Loot.of(555, 80, 300, 30), // Water Runes Loot.of(557, 80, 300, 30), // Earth Runes Loot.of(558, 80, 300, 30), // Mind Runes Loot.of(559, 15, 45, 30), // Body Runes Loot.of(561, 15, 60, 30), // Nature Runes Loot.of(562, 30, 60, 30), // Chaos Runes Loot.of(563, 15, 75, 30), // Law Runes Loot.of(565, 15, 75, 30), // Blood Runes Loot.of(1725, 30), // Amulet of Strength Loot.of(1727, 30), // Amulet of Magic Loot.of(1731, 30), // Amulet of Power Loot.of(1478, 30), // Amulet of Accuracy // Black d'hide Loot.of(2491, 1, 2, 20), // vambs Loot.of(2497, 1, 2, 20), // chaps Loot.of(2503, 1, 2, 20), // body // Dragon Loot.of(1377, 15), // Battleaxe Loot.of(1434, 15), // Mace // Rune Loot.of(1359, 20), // Axe Loot.of(1275, 20), // Pickaxe Loot.of(1163, 20), // Full helm Loot.of(1127, 20), // Platebody Loot.of(1079, 20), // Platelegs Loot.of(1201, 20), // Kiteshield Loot.of(9185, 20), // Crossbow // Magic shortbow Loot.of(861, 20) ); public static final LootTable EASY_REWARDS_TABLE = JUNK_REWARDS_TABLE.merge(BASIC_REWARDS_TABLE).merge(LootTable.of( // Bronze (t) Loot.of(12215, 10), Loot.of(12217, 10), Loot.of(12219, 10), Loot.of(12221, 10), Loot.of(12223, 10), // Bronze (g) Loot.of(12205, 10), // body Loot.of(12207, 10), // legs Loot.of(12209, 10), // skirt Loot.of(12211, 10), // helm Loot.of(12213, 10), // kite // Iron (t) Loot.of(12225, 10), Loot.of(12227, 10), Loot.of(12229, 10), Loot.of(12231, 10), Loot.of(12233, 10), // Iron (g) Loot.of(12235, 10), // body Loot.of(12237, 10), // legs Loot.of(12239, 10), // skirt Loot.of(12241, 10), // helm Loot.of(12243, 10), // kite // Black (t) Loot.of(2583, 10), Loot.of(2585, 10), Loot.of(2587, 10), Loot.of(2589, 10), // Black (g) Loot.of(2591, 10), // body Loot.of(2593, 10), // legs Loot.of(2595, 10), // helm Loot.of(2597, 10), // kite // Berets Loot.of(2633, 10), Loot.of(2635, 10), Loot.of(2637, 10), Loot.of(12247, 10), // Highwayman mask Loot.of(2631, 10), // Beanie Loot.of(12245, 10), // Blue wizard (t) Loot.of(7388, 10), // skirt Loot.of(7392, 10), // robe Loot.of(7396, 10), // hat // Blue wizard (g) Loot.of(7386, 10), // skirt Loot.of(7390, 10), // robe Loot.of(7394, 10), // hat // Black wizard (t) Loot.of(12447, 10), // skirt Loot.of(12451, 10), // robe Loot.of(12455, 10), // hat // Black wizard (g) Loot.of(12445, 10), // skirt Loot.of(12449, 10), // robe Loot.of(12453, 10), // hat // Studded leather (t) Loot.of(7364, 10), // body Loot.of(7368, 10), // chaps // Studded leather (g) Loot.of(7362, 10), // body Loot.of(7366, 10), // chaps // Blue elegant Loot.of(10408, 10), // shirt Loot.of(10410, 10), // legs // Red elegant Loot.of(10404, 10), // shirt Loot.of(10406, 10), // legs // Green elegant Loot.of(10412, 10), // shirt Loot.of(10414, 10), // legs // Amulet of magic (t) Loot.of(10366, 10), // Black cane Loot.of(12375, 10), // Guthix robe Loot.of(10462, 10), // top Loot.of(10466, 10), // legs // Saradomin robe Loot.of(10458, 10), // top Loot.of(10464, 10), // legs // Zamorak robe Loot.of(10460, 10), // top Loot.of(10468, 10), // legs // Bandos robe Loot.of(12265, 10), // top Loot.of(12267, 10), // legs // Armadyl robe Loot.of(12253, 10), // top Loot.of(12255, 10), // legs // Imp mask Loot.of(12249, 10), // Goblin mask Loot.of(12251, 10) )); public static final LootTable MEDIUM_REWARDS_TABLE = JUNK_REWARDS_TABLE.merge(BASIC_REWARDS_TABLE).merge(LootTable.of( // Mithril (t) Loot.of(12287, 10), Loot.of(12289, 10), Loot.of(12291, 10), Loot.of(12293, 10), Loot.of(12295, 10), // Mithril (g) Loot.of(12277, 10), // body Loot.of(12279, 10), // legs Loot.of(12281, 10), // kite Loot.of(12283, 10), // helm Loot.of(12285, 10), // skirt // Adamant (t) Loot.of(2599, 10), // body Loot.of(2601, 10), // legs Loot.of(2603, 10), // kite Loot.of(2605, 10), // helm // Adamant (g) Loot.of(2607, 10), // body Loot.of(2609, 10), // legs Loot.of(2611, 10), // kite Loot.of(2613, 10), // helm // Ranger boots Loot.of(2577, 10), // Holy sandals Loot.of(12598, 10), // Wizard boots Loot.of(2579, 10), // Halos Loot.of(12637, 10), Loot.of(12638, 10), Loot.of(12639, 10), // Headbands Loot.of(2645, 10), // red Loot.of(2647, 10), // black Loot.of(2649, 10), // brown Loot.of(12299, 10), // white Loot.of(12301, 10), // blue Loot.of(12303, 10), // gold Loot.of(12305, 10), // pink Loot.of(12307, 10), // green // Boaters Loot.of(7319, 10), // red Loot.of(7321, 10), // orange Loot.of(7323, 10), // green Loot.of(7325, 10), // blue Loot.of(7327, 10), // black Loot.of(12309, 10), // pink Loot.of(12311, 10), // purple Loot.of(12313, 10), // white // Green d'hide (t) Loot.of(7372, 10), // body Loot.of(7380, 10), // chaps // Green d'hide (g) Loot.of(7370, 10), // body Loot.of(7378, 10), // chaps // Black elegant Loot.of(10400, 10), // shirt Loot.of(10402, 10), // legs // White elegant Loot.of(10420, 10), // shirt Loot.of(10422, 10), // legs // Purple elegant Loot.of(10416, 10), // shirt Loot.of(10418, 10), // legs // Pink elegant Loot.of(12315, 10), // shirt Loot.of(12317, 10), // legs // Gold elegant Loot.of(12347, 10), // shirt Loot.of(12349, 10), // legs // Strength amulet (t) Loot.of(10364, 10), // God mitres Loot.of(10452, 10), // saradomin Loot.of(10454, 10), // guthix Loot.of(10456, 10), // zamorak Loot.of(12203, 10), // ancient Loot.of(12259, 10), // armadyl Loot.of(12271, 10), // bandos // God cloaks Loot.of(10446, 10), // saradomin Loot.of(10448, 10), // guthix Loot.of(10450, 10), // zamorak Loot.of(12197, 10), // ancient Loot.of(12261, 10), // armadyl Loot.of(12273, 10), // bandos // Penguin mask Loot.of(12428, 10), // Cat mask Loot.of(12361, 10), // Crier hat Loot.of(12319, 10), // Leprechaun hat Loot.of(12359, 10) )); public static final LootTable HARD_REWARDS_TABLE = JUNK_REWARDS_TABLE.merge(BASIC_REWARDS_TABLE).merge(LootTable.of( // Rune (t) Loot.of(2623, 10), // body Loot.of(2625, 10), // legs Loot.of(2627, 10), // full helm Loot.of(2629, 10), // kite Loot.of(3477, 10), // skirt //Dragon masks Loot.of(12518, 10), // Green dragon mask Loot.of(12520, 10), // Blue dragon mask Loot.of(12522, 10), // Red dragon mask Loot.of(12524, 10), // Black dragon mask // Rune (g) Loot.of(2615, 10), // body Loot.of(2617, 10), // legs Loot.of(2619, 10), // full helm Loot.of(2621, 10), // kite Loot.of(3476, 10), // skirt // Rune (guthix) Loot.of(2669, 10), // body Loot.of(2671, 10), // legs Loot.of(2673, 10), // full helm Loot.of(2675, 10), // kite Loot.of(3480, 10), // skirt // Rune (saradomin) Loot.of(2661, 10), // body Loot.of(2663, 10), // legs Loot.of(2665, 10), // full helm Loot.of(2667, 10), // kite Loot.of(3479, 10), // skirt // Rune (zamorak) Loot.of(2653, 10), // body Loot.of(2655, 10), // legs Loot.of(2657, 10), // full helm Loot.of(2659, 10), // kite Loot.of(3478, 10), // skirt // Gilded Loot.of(3481, 3), // body Loot.of(3483, 3), // legs Loot.of(3485, 3), // skirt Loot.of(3486, 3), // full helm Loot.of(3488, 3), // kite // Blue d'hide (t) Loot.of(7376, 10), // body Loot.of(7384, 10), // chaps // Blue d'hide (g) Loot.of(7374, 10), // body Loot.of(7382, 10), // chaps // Red d'hide (t) Loot.of(12331, 10), // body Loot.of(12333, 10), // chaps // Red d'hide (g) Loot.of(12327, 10), // body Loot.of(12329, 10), // chaps // Enchanted Loot.of(7398, 10), // robe bottom Loot.of(7399, 10), // robe top Loot.of(7400, 10), // hat // Robin hood hat Loot.of(2581, 5), // Cavaliers Loot.of(2639, 10), // tan Loot.of(2641, 10), // dark Loot.of(2643, 10), // black Loot.of(12321, 10), // white Loot.of(12323, 10), // red Loot.of(12325, 10), // navy //Infinity Set Loot.of(6916, 10), // top Loot.of(6918, 10), // hat Loot.of(6920, 10), // boots Loot.of(6922, 10), // gloves Loot.of(6924, 10), // bottoms Loot.of(6916, 10), // top //Mage's book Loot.of(6889, 10), // mage's book //Master wand Loot.of(6914, 10), // master wand // Pirate's hat Loot.of(2651, 10), // Third-age (range) Loot.of(10330, 1), // top Loot.of(10332, 1), // legs Loot.of(10334, 1), // coif Loot.of(10336, 1), // vambs // Third-age (mage) Loot.of(10338, 1), // robe top Loot.of(10340, 1), // robe bottom Loot.of(10342, 1), // hat Loot.of(10344, 1), // amulet // Third-age (melee) Loot.of(10346, 1), // legs Loot.of(10348, 1), // platebody Loot.of(10350, 1), // helmet Loot.of(10352, 1), // kite // Amulet of glory (t) Loot.of(10362, 10), // Guthix d'hide Loot.of(10376, 10), // vambs Loot.of(10378, 10), // body Loot.of(10380, 10), // chaps Loot.of(10382, 10), // coif // Saradomin d'hide Loot.of(10384, 10), // vambs Loot.of(10386, 10), // body Loot.of(10388, 10), // chaps Loot.of(10390, 10), // coif // Zamorak d'hide Loot.of(10368, 10), // vambs Loot.of(10370, 10), // body Loot.of(10372, 10), // chaps Loot.of(10374, 10), // coif // Armadyl d'hide Loot.of(12506, 10), // vambs Loot.of(12508, 10), // body Loot.of(12510, 10), // chaps Loot.of(12512, 10), // coif // Ancient d'hide Loot.of(12490, 10), // vambs Loot.of(12492, 10), // body Loot.of(12494, 10), // chaps Loot.of(12496, 10), // coif // Bandos d'hide Loot.of(12498, 10), // vambs Loot.of(12500, 10), // body Loot.of(12502, 10), // chaps Loot.of(12504, 10), // coif // Vestment stoles Loot.of(10470, 10), // saradomin Loot.of(10472, 10), // guthix Loot.of(10474, 10), // zamorak Loot.of(12257, 10), // armadyl Loot.of(12201, 10), // ancient Loot.of(12269, 10), // bandos // Vestment croziers Loot.of(10440, 10), // saradomin Loot.of(10442, 10), // guthix Loot.of(10444, 10), // zamorak Loot.of(12263, 10), // armadyl Loot.of(12199, 10), // ancient Loot.of(12275, 10), // bandos // Pith helmet Loot.of(12516, 10), // Explorer backpack Loot.of(12514, 10), // Rune cane Loot.of(12379, 10) )); public static final LootTable ELITE_REWARDS_TABLE = JUNK_REWARDS_TABLE.merge(BASIC_REWARDS_TABLE).merge(LootTable.of( //Potions Loot.of(6686, 25, 55, 3), //Saradomin Brew Loot.of(3025, 25, 55, 3), //Super restore Loot.of(11952, 25, 55, 3), //Extended antifire Loot.of(2445, 25, 55, 3), //Ranging potion Loot.of(989, 3), //Crystal key Loot.of(12357, 10), // Katana //Black D'hide (g) Loot.of(12381, 10), // body Loot.of(12383, 10), // chaps //Black D'hide (t) Loot.of(12385, 10), // body Loot.of(12387, 10), // chaps //Musketeer Loot.of(12351, 10), // hat Loot.of(12441, 10), // tabard Loot.of(12443, 10), // pants //Ornament kits Loot.of(12538, 10), // dragon full helm Loot.of(12534, 10), // dragon chain Loot.of(12536, 10), // dragon plate/skirt Loot.of(12532, 10), // dragon sq Loot.of(12530, 10), // light infinity Loot.of(12528, 10), // dark infinity Loot.of(12526, 10), // fury ornament kit //Hats Loot.of(12355, 10), // big pirate hat Loot.of(12430, 10), // afro Loot.of(12432, 10), // top hat Loot.of(12363, 10), // bronze dragon mask Loot.of(12365, 10), // iron dragon mask Loot.of(12367, 10), // steel dragon mask Loot.of(12369, 10), // mith dragon mask Loot.of(12371, 3), // lava dragon mask Loot.of(12337, 10), // sagacious spectacles Loot.of(12353, 10), // monocle Loot.of(12540, 10), // deerstalker Loot.of(12596, 10), // Rangers' tunic Loot.of(12335, 10), // Briefcase Loot.of(12373, 10), // Dragon cane //Books Loot.of(12608, 3), // war Loot.of(12610, 3), // law Loot.of(12612, 3), // darkness //Royal Loot.of(12393, 10), // Royal gown top Loot.of(12395, 10), // Royal gown bottom Loot.of(12397, 10), // Royal crown Loot.of(12439, 10), // Royal sceptre // Gilded Loot.of(3481, 3), // body Loot.of(3483, 3), // legs Loot.of(3485, 3), // skirt Loot.of(3486, 3), // full helm Loot.of(3488, 3), // kite Loot.of(12389, 3), // scimitar Loot.of(12391, 3), // boots // Third-age (range) Loot.of(10330, 1), // top Loot.of(10332, 1), // legs Loot.of(10334, 1), // coif Loot.of(10336, 1), // vambs // Third-age (mage) Loot.of(10338, 1), // robe top Loot.of(10340, 1), // robe bottom Loot.of(10342, 1), // hat Loot.of(10344, 1), // amulet // Third-age (melee) Loot.of(10346, 1), // legs Loot.of(10348, 1), // platebody Loot.of(10350, 1), // helmet Loot.of(10352, 1), // kite // Third-age (various) Loot.of(12426, 1), // longsword Loot.of(12424, 1), // bow Loot.of(12422, 1), // wand Loot.of(12437, 1) // cloak )); public static final LootTable MASTER_REWARDS_TABLE = JUNK_REWARDS_TABLE.merge(BASIC_REWARDS_TABLE).merge(LootTable.of( //Potions Loot.of(6686, 25, 55, 3), //Saradomin Brew Loot.of(3025, 25, 55, 3), //Super restore Loot.of(11952, 25, 55, 3), //Extended antifire Loot.of(2445, 25, 55, 3), //Ranging potion Loot.of(989, 3), //Crystal key Loot.of(12357, 10), // Katana Loot.of(4561, 15), // purple sweets //Black D'hide (g) Loot.of(12381, 10), // body Loot.of(12383, 10), // chaps //Black D'hide (t) Loot.of(12385, 10), // body Loot.of(12387, 10), // chaps //Musketeer Loot.of(12351, 10), // hat Loot.of(12441, 10), // tabard Loot.of(12443, 10), // pants //Ornament kits Loot.of(12538, 10), // dragon full helm Loot.of(12534, 10), // dragon chain Loot.of(12536, 10), // dragon plate/skirt Loot.of(12532, 10), // dragon sq Loot.of(12530, 10), // light infinity Loot.of(12528, 10), // dark infinity Loot.of(12526, 10), // fury ornament kit //Hats Loot.of(12355, 10), // big pirate hat Loot.of(12430, 10), // afro Loot.of(12432, 10), // top hat Loot.of(12363, 10), // bronze dragon mask Loot.of(12365, 10), // iron dragon mask Loot.of(12367, 10), // steel dragon mask Loot.of(12369, 10), // mith dragon mask Loot.of(12371, 3), // lava dragon mask Loot.of(12337, 10), // sagacious spectacles Loot.of(12353, 10), // monocle Loot.of(12540, 10), // deerstalker Loot.of(12596, 10), // Rangers' tunic Loot.of(12335, 10), // Briefcase Loot.of(12373, 10), // Dragon cane //Books Loot.of(12608, 3), // war Loot.of(12610, 3), // law Loot.of(12612, 3), // darkness // Rune (t) Loot.of(2623, 10), // body Loot.of(2625, 10), // legs Loot.of(2627, 10), // full helm Loot.of(2629, 10), // kite Loot.of(3477, 10), // skirt //Dragon masks Loot.of(12518, 10), // Green dragon mask Loot.of(12520, 10), // Blue dragon mask Loot.of(12522, 10), // Red dragon mask Loot.of(12524, 10), // Black dragon mask // Rune (g) Loot.of(2615, 10), // body Loot.of(2617, 10), // legs Loot.of(2619, 10), // full helm Loot.of(2621, 10), // kite Loot.of(3476, 10), // skirt // Rune (guthix) Loot.of(2669, 10), // body Loot.of(2671, 10), // legs Loot.of(2673, 10), // full helm Loot.of(2675, 10), // kite Loot.of(3480, 10), // skirt // Rune (saradomin) Loot.of(2661, 10), // body Loot.of(2663, 10), // legs Loot.of(2665, 10), // full helm Loot.of(2667, 10), // kite Loot.of(3479, 10), // skirt // Rune (zamorak) Loot.of(2653, 10), // body Loot.of(2655, 10), // legs Loot.of(2657, 10), // full helm Loot.of(2659, 10), // kite Loot.of(3478, 10), // skirt // Rune Loot.of(1359, 20), // Axe Loot.of(1275, 20), // Pickaxe Loot.of(1163, 20), // Full helm Loot.of(1127, 20), // Platebody Loot.of(1079, 20), // Platelegs Loot.of(1201, 20), // Kiteshield Loot.of(9185, 20), // Crossbow // Black d'hide Loot.of(2491, 1, 2, 20), // vambs Loot.of(2497, 1, 2, 20), // chaps Loot.of(2503, 1, 2, 20), // body // Dragon Loot.of(1377, 15), // Battleaxe Loot.of(1434, 15), // Mace // Elder robes Loot.of(20517, 1), // Robe top Loot.of(20520, 1), // Robe bottoms // Guthix robe Loot.of(10462, 10), // top Loot.of(10466, 10), // legs // Saradomin robe Loot.of(10458, 10), // top Loot.of(10464, 10), // legs // Zamorak robe Loot.of(10460, 10), // top Loot.of(10468, 10), // legs // Bandos robe Loot.of(12265, 10), // top Loot.of(12267, 10), // legs // Armadyl robe Loot.of(12253, 10), // top Loot.of(12255, 10), // legs // Imp mask Loot.of(12249, 10), // Goblin mask Loot.of(12251, 10), //Infinity Set Loot.of(6916, 10), // top Loot.of(6918, 10), // hat Loot.of(6920, 10), // boots Loot.of(6922, 10), // gloves Loot.of(6924, 10), // bottoms Loot.of(6916, 10), // top //Mage's book Loot.of(6889, 10), // mage's book //Master wand Loot.of(6914, 10), // master wand //Royal Loot.of(12393, 10), // Royal gown top Loot.of(12395, 10), // Royal gown bottom Loot.of(12397, 10), // Royal crown Loot.of(12439, 10), // Royal sceptre // Gilded Loot.of(3481, 3), // body Loot.of(3483, 3), // legs Loot.of(3485, 3), // skirt Loot.of(3486, 3), // full helm Loot.of(3488, 3), // kite Loot.of(12389, 3), // scimitar Loot.of(12391, 3), // boots // Third-age (range) Loot.of(10330, 1), // top Loot.of(10332, 1), // legs Loot.of(10334, 1), // coif Loot.of(10336, 1), // vambs // Third-age (mage) Loot.of(10338, 1), // robe top Loot.of(10340, 1), // robe bottom Loot.of(10342, 1), // hat Loot.of(10344, 1), // amulet // Third-age (melee) Loot.of(10346, 1), // legs Loot.of(10348, 1), // platebody Loot.of(10350, 1), // helmet Loot.of(10352, 1), // kite // Third-age (various) Loot.of(12426, 1), // longsword Loot.of(12424, 1), // bow Loot.of(12422, 1), // wand Loot.of(12437, 1), // cloak Loot.of(20011, 1), // axe Loot.of(20014, 1), // pickaxe // Bloodhound Loot.of(19730, 1))); // Bloodhound }
true
d89dac49179a1cb7f62336039b0690cfc1ac697e
Java
Fellaru/GoF_patterns
/src/main/java/ru/fella/learn/patterns/structural/composite/Main.java
UTF-8
1,269
3.640625
4
[]
no_license
package ru.fella.learn.patterns.structural.composite; import java.time.Instant; import java.util.List; /** * @author fellaru * Компоновшик - группирует простые и составные элементы в структуру типа дерева, * позволяя к элементам и простым и составным обрашаться единообразно */ public class Main { public static void main(String[] args) { Product simpleProduct = simpleProduct(); System.out.println(simpleProduct.cost()); Product compositeProduct = compositeProduct(); System.out.println(compositeProduct.cost()); System.out.println(String.format("%s: %s", "jungle", Instant.now())); } private static Product simpleProduct(){ return new Muffin(); } private static Product compositeProduct(){ Product box1 = new Box(List.of( new Muffin(), new Muffin(), new Milk() )); Product box2 = new Box(List.of( box1, new Milk(), new Muffin() )); return new Box(List.of( box2, new Muffin() )); } }
true
7554dfd7289a4469fab1eead69056e02898f4a00
Java
theanhhp/COFFEE-MANAGEMENT-SOFTWARE-
/src/JformQuanLy/QL_NhanVien1.java
UTF-8
41,388
2.125
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 JformQuanLy; import connect.connect_1; import java.awt.Color; import java.awt.Image; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Vector; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import model.nv; import java.util.Date; /** * * @author win */ public class QL_NhanVien1 extends javax.swing.JPanel { String filename = null; byte[] preson_image = null; String a, b, c; connect_1 hd = new connect_1(); ResultSet rs; Statement st; private DefaultComboBoxModel cbo = new DefaultComboBoxModel(); ArrayList<String> arr = new ArrayList<>(); String ma; connect_1 cho = new connect_1(); String head[] = {"ID", "username", "passwords", "hovaten", "email", "ngaysinh", "gioitinh","sdt","cmnd", "diachi", "lv", "hinh"}; DefaultTableModel model = new DefaultTableModel(head, 0); /** * Creates new form QL_NhanVien1 */ public QL_NhanVien1() { initComponents(); loaddata(); ngayhientai(); } private ArrayList<nv> getlist() { ArrayList<nv> getlist = new ArrayList<>(); try { Connection conn = hd.getconection(); String str = "select * from nhanvien"; st = conn.createStatement(); rs = st.executeQuery(str); nv a; while (rs.next()) { a = new nv(rs.getInt("id"), rs.getString("username"), rs.getString("passwords"), rs.getString("hovaten"), rs.getString("email"), rs.getString("ngaysinh"), rs.getString("gioitinh"), rs.getString("sdt"), rs.getString("diachi"), rs.getDouble("cmnd"), rs.getInt("lv"), rs.getBytes("hinh")); getlist.add(a); } } catch (Exception ex) { System.out.println(ex); } return getlist; } public void ngayhientai(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); dcngay.setDate(date); } private void loaddata() { try { model.setRowCount(0); String user = "sa"; String pass = "123"; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=qlcafe"; Connection con = DriverManager.getConnection(url, user, pass); Statement st = con.createStatement(); String sql = "select * from nhanvien"; ResultSet rs = st.executeQuery(sql); while (rs.next()) { Vector row = new Vector(); row.add(rs.getString(1)); row.add(rs.getString(2)); row.add(rs.getString(3)); row.add(rs.getString(4)); row.add(rs.getString(5)); row.add(rs.getString(6)); row.add(rs.getString(7)); row.add(rs.getString(8)); row.add(rs.getString(9)); row.add(rs.getString(10)); row.add(rs.getString(11)); row.add(rs.getString(12)); model.addRow(row); } table.setModel(model); con.close(); } catch (Exception e) { System.out.println(e); } } private boolean check() { if (txtdangnhap.getText().equals("")) { JOptionPane.showMessageDialog(null, "Tên Đang Nhập không được để trống"); txtdangnhap.setBackground(Color.RED); txtdangnhap.setText(""); return false; } if (txtmatkau.getText().equals("")) { JOptionPane.showMessageDialog(null, " Mật Khẩu không được để trống"); txtmatkau.setBackground(Color.RED); txtmatkau.setText(""); return false; } if (txtsdt1.getText().equals("")) { JOptionPane.showMessageDialog(null, "số điện thoại không được để trống"); txtsdt1.setBackground(Color.RED); txtsdt1.setText(""); return false; } if (txtemail.getText().equals("")) { JOptionPane.showMessageDialog(null, "email không được để trống"); txtemail.setBackground(Color.RED); txtemail.setText(""); return false; } if (txtdiachi.getText().equals("")) { JOptionPane.showMessageDialog(null, "địa chỉ không được để trống"); txtdiachi.setBackground(Color.RED); txtdiachi.setText(""); return false; } if (!(txtemail.getText()).matches("^[\\w-_\\.]+\\@[\\w&&[^0-9]]+\\.[\\w&&[^0-9]]+$")) { JOptionPane.showMessageDialog(this, "Sai định dạng email"); txtemail.requestFocus(); txtemail.setBackground(Color.RED); txtemail.setText(""); return false; } if (txtten.getText().equals("")) { JOptionPane.showMessageDialog(null, " Tên không được để trống"); txtten.setBackground(Color.RED); txtten.setText(""); return false; } if (txtcmnd.getText().equals("")) { JOptionPane.showMessageDialog(null, "Chứng Minh Nhân Dân không được để trống"); txtcmnd.setBackground(Color.RED); txtcmnd.setText(""); return false; } return true; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); buttonGroup2 = new javax.swing.ButtonGroup(); jTabbedPane1 = new javax.swing.JTabbedPane(); jDesktopPane1 = new javax.swing.JDesktopPane(); jPanel40 = new javax.swing.JPanel(); txtemail = new javax.swing.JTextField(); jLabel134 = new javax.swing.JLabel(); jLabel135 = new javax.swing.JLabel(); jLabel136 = new javax.swing.JLabel(); txtdangnhap = new javax.swing.JTextField(); jLabel137 = new javax.swing.JLabel(); jLabel138 = new javax.swing.JLabel(); jLabel139 = new javax.swing.JLabel(); nam = new javax.swing.JRadioButton(); nu = new javax.swing.JRadioButton(); hinh = new javax.swing.JLabel(); jLabel140 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); txtsdt1 = new javax.swing.JTextField(); cbnchon = new javax.swing.JButton(); txtten = new javax.swing.JTextField(); jLabel141 = new javax.swing.JLabel(); txtcmnd = new javax.swing.JTextField(); jLabel142 = new javax.swing.JLabel(); nhanvien = new javax.swing.JRadioButton(); quanly = new javax.swing.JRadioButton(); dcngay = new com.toedter.calendar.JDateChooser(); txtmatkau = new javax.swing.JPasswordField(); jScrollPane1 = new javax.swing.JScrollPane(); txtdiachi = new javax.swing.JTextArea(); btnthem = new javax.swing.JButton(); btnsua = new javax.swing.JButton(); btnxoa = new javax.swing.JButton(); btnnew = new javax.swing.JButton(); jTabbedPane2 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); table = new javax.swing.JTable(); setBorder(javax.swing.BorderFactory.createTitledBorder("")); setToolTipText("aa"); jPanel40.setPreferredSize(new java.awt.Dimension(865, 517)); txtemail.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtemailMouseClicked(evt); } }); txtemail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtemailActionPerformed(evt); } }); jLabel134.setText("Email"); jLabel135.setText("Trang Thái"); jLabel136.setText("Mật Khẩu"); txtdangnhap.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtdangnhapMouseClicked(evt); } }); txtdangnhap.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtdangnhapActionPerformed(evt); } }); jLabel137.setText("Tên Đang Nhập"); jLabel138.setText("Số Điện Thoại"); jLabel139.setText("Giới Tính"); buttonGroup1.add(nam); nam.setSelected(true); nam.setText("Nam"); nam.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { namActionPerformed(evt); } }); buttonGroup1.add(nu); nu.setText("Nữ"); nu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nuActionPerformed(evt); } }); hinh.setBackground(new java.awt.Color(102, 102, 102)); hinh.setOpaque(true); jLabel140.setText("Tên"); jLabel1.setText("Ngày Sinh"); txtsdt1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtsdt1MouseClicked(evt); } }); txtsdt1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtsdt1ActionPerformed(evt); } }); cbnchon.setText("ChỌN"); cbnchon.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbnchonActionPerformed(evt); } }); txtten.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txttenMouseClicked(evt); } }); txtten.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txttenActionPerformed(evt); } }); jLabel141.setText("Cmnd"); txtcmnd.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtcmndMouseClicked(evt); } }); txtcmnd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtcmndActionPerformed(evt); } }); jLabel142.setText("Địa Chỉ"); buttonGroup2.add(nhanvien); nhanvien.setSelected(true); nhanvien.setText("Nhân Viên"); nhanvien.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nhanvienActionPerformed(evt); } }); buttonGroup2.add(quanly); quanly.setText("Quản Lý"); quanly.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { quanlyActionPerformed(evt); } }); dcngay.setEnabled(false); txtdiachi.setColumns(20); txtdiachi.setRows(5); jScrollPane1.setViewportView(txtdiachi); btnthem.setText("Thêm"); btnthem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnthemActionPerformed(evt); } }); btnsua.setText("Sửa"); btnsua.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnsuaActionPerformed(evt); } }); btnxoa.setText("Xóa"); btnxoa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnxoaActionPerformed(evt); } }); btnnew.setText("Mới"); btnnew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnnewActionPerformed(evt); } }); javax.swing.GroupLayout jPanel40Layout = new javax.swing.GroupLayout(jPanel40); jPanel40.setLayout(jPanel40Layout); jPanel40Layout.setHorizontalGroup( jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel40Layout.createSequentialGroup() .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel40Layout.createSequentialGroup() .addContainerGap() .addComponent(hinh, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel40Layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(cbnchon, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel40Layout.createSequentialGroup() .addGap(17, 17, 17) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel136, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel140, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel141, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel40Layout.createSequentialGroup() .addComponent(jLabel137, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel40Layout.createSequentialGroup() .addComponent(btnthem) .addGap(30, 30, 30))) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(dcngay, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(txtmatkau, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtdangnhap, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtten) .addComponent(txtcmnd, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel40Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(btnsua) .addGap(48, 48, 48) .addComponent(btnxoa))) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel40Layout.createSequentialGroup() .addGap(18, 18, Short.MAX_VALUE) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel134, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel142, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel40Layout.createSequentialGroup() .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel40Layout.createSequentialGroup() .addComponent(jLabel139, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(8, 8, 8)) .addComponent(jLabel135, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel138, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel40Layout.createSequentialGroup() .addComponent(nam) .addGap(46, 46, 46) .addComponent(nu, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtsdt1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtemail, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel40Layout.createSequentialGroup() .addComponent(nhanvien) .addGap(18, 18, 18) .addComponent(quanly, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(936, 936, 936)) .addGroup(jPanel40Layout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(btnnew) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); jPanel40Layout.setVerticalGroup( jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel40Layout.createSequentialGroup() .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel40Layout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(hinh, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cbnchon)) .addGroup(jPanel40Layout.createSequentialGroup() .addGap(57, 57, 57) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel137, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtdangnhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel134, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtemail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel136, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtmatkau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtsdt1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel138, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtten, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel140, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel139, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(nam) .addComponent(nu)) .addGap(27, 27, 27) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(dcngay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(quanly) .addComponent(nhanvien)) .addComponent(jLabel135, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel40Layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtcmnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel141) .addComponent(jLabel142, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel40Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE) .addGroup(jPanel40Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnthem) .addComponent(btnsua) .addComponent(btnxoa) .addComponent(btnnew)) .addGap(56, 56, 56)) ); jDesktopPane1.setLayer(jPanel40, javax.swing.JLayeredPane.DEFAULT_LAYER); javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1); jDesktopPane1.setLayout(jDesktopPane1Layout); jDesktopPane1Layout.setHorizontalGroup( jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel40, javax.swing.GroupLayout.DEFAULT_SIZE, 1066, Short.MAX_VALUE) ); jDesktopPane1Layout.setVerticalGroup( jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel40, javax.swing.GroupLayout.DEFAULT_SIZE, 477, Short.MAX_VALUE) ); jTabbedPane1.addTab("Thêm Nhân Viên", jDesktopPane1); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tableMouseClicked(evt); } }); jScrollPane2.setViewportView(table); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 772, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 402, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 47, Short.MAX_VALUE)) ); jTabbedPane2.addTab("Danh Sách Sinh Viên", jPanel1); jTabbedPane1.addTab("Quản Lý Nhân Viên", jTabbedPane2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 802, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING) ); }// </editor-fold>//GEN-END:initComponents private void txtemailMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtemailMouseClicked txtemail.setBackground(Color.WHITE); }//GEN-LAST:event_txtemailMouseClicked private void txtemailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtemailActionPerformed }//GEN-LAST:event_txtemailActionPerformed private void txtdangnhapMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtdangnhapMouseClicked txtdangnhap.setBackground(Color.WHITE); }//GEN-LAST:event_txtdangnhapMouseClicked private void txtdangnhapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtdangnhapActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtdangnhapActionPerformed private void namActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_namActionPerformed // TODO add your handling code here: }//GEN-LAST:event_namActionPerformed private void nuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuActionPerformed // TODO add your handling code here: }//GEN-LAST:event_nuActionPerformed private void txtsdt1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtsdt1MouseClicked txtsdt1.setBackground(Color.WHITE); }//GEN-LAST:event_txtsdt1MouseClicked private void txtsdt1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtsdt1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtsdt1ActionPerformed private void cbnchonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbnchonActionPerformed JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null); File f = chooser.getSelectedFile(); filename = f.getAbsolutePath(); ImageIcon icon = new ImageIcon("D:\\Java 4\\DuAn1\\src\\icon " + filename); icon = new ImageIcon(new ImageIcon(filename).getImage(). getScaledInstance(hinh.getWidth(), hinh.getHeight(), Image.SCALE_SMOOTH)); hinh.setIcon(icon); try { File image = new File(filename); FileInputStream fis = new FileInputStream(image); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] bs = new byte[1024]; for (int i; (i = fis.read(bs)) != -1;) { baos.write(bs, 0, i); } preson_image = baos.toByteArray(); } catch (Exception e) { System.out.println("loi he thong"); } }//GEN-LAST:event_cbnchonActionPerformed private void txttenMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txttenMouseClicked // TODO add your handling code here: }//GEN-LAST:event_txttenMouseClicked private void txttenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txttenActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txttenActionPerformed private void txtcmndMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtcmndMouseClicked // TODO add your handling code here: }//GEN-LAST:event_txtcmndMouseClicked private void txtcmndActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtcmndActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtcmndActionPerformed private void nhanvienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nhanvienActionPerformed // TODO add your handling code here: }//GEN-LAST:event_nhanvienActionPerformed private void quanlyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quanlyActionPerformed // TODO add your handling code here: }//GEN-LAST:event_quanlyActionPerformed private void btnthemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnthemActionPerformed if (check()) { try { Connection con = hd.getconection(); String b = "insert into nhanvien(username,passwords,hovaten,email,ngaysinh,gioitinh,sdt,cmnd,diachi,lv,hinh)values (?,?,?,?,?,?,?,?,?,?,?)"; PreparedStatement pst = con.prepareStatement(b); pst.setString(1, txtdangnhap.getText()); pst.setString(2, txtmatkau.getText()); pst.setString(3, txtten.getText()); pst.setString(4, txtemail.getText()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String date = sdf.format(dcngay.getDate()); pst.setString(5, date); if (nam.isSelected()) { a = "Nam"; } if (nu.isSelected()) { a = "Nữ"; } pst.setString(6, a); pst.setString(7, txtsdt1.getText()); pst.setString(8, txtcmnd.getText()); pst.setString(9, txtdiachi.getText()); if (nam.isSelected()) { c = "1"; } if (nu.isSelected()) { c = "2"; } pst.setString(10, c); pst.setBytes(11, preson_image); pst.executeUpdate(); model = (DefaultTableModel) table.getModel(); model.setRowCount(0); loaddata(); neww(); JOptionPane.showMessageDialog(null, "thành công"); } catch (Exception e) { e.printStackTrace(); } } }//GEN-LAST:event_btnthemActionPerformed private void btnsuaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsuaActionPerformed if (check()) { try { Connection conn = hd.getconection(); int row = table.getSelectedRow(); String value = (table.getModel().getValueAt(row, 0).toString()); String b = "update nhanvien set username=?,passwords=?,hovaten=?, email=?, ngaysinh=?, gioitinh=?, sdt=?,cmnd =?,diachi=?,lv=?,hinh=? where id=" + value; PreparedStatement pst = conn.prepareStatement(b); pst.setString(1, txtdangnhap.getText()); pst.setString(2, txtmatkau.getText()); pst.setString(3, txtten.getText()); pst.setString(4, txtemail.getText()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String date = sdf.format(dcngay.getDate()); pst.setString(5, date); if (nam.isSelected()) { a = "Nam"; } if (nu.isSelected()) { a = "Nữ"; } pst.setString(6, a); pst.setString(7, txtsdt1.getText()); pst.setString(8, txtcmnd.getText()); pst.setString(9, txtdiachi.getText()); if (nam.isSelected()) { c = "1"; } if (nu.isSelected()) { c = "2"; } pst.setString(10, c); pst.setBytes(11, preson_image); pst.executeUpdate(); model = (DefaultTableModel) table.getModel(); model.setRowCount(0); loaddata(); JOptionPane.showMessageDialog(null, "thành công"); } catch (Exception ex) { ex.printStackTrace(); } } }//GEN-LAST:event_btnsuaActionPerformed private void btnxoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnxoaActionPerformed try { Connection conn = hd.getconection(); int row = table.getSelectedRow(); String value = (table.getModel().getValueAt(row, 0).toString()); String query = "delete from nhanvien where id=" + value; PreparedStatement st = conn.prepareStatement(query); st.executeUpdate(); model = (DefaultTableModel) table.getModel(); model.setRowCount(0); loaddata(); JOptionPane.showMessageDialog(null, "Xóa thành công !"); } catch (Exception ex) { System.out.println(ex); } }//GEN-LAST:event_btnxoaActionPerformed public void neww(){ txtdiachi.setText(""); txtdangnhap.setText(""); txtemail.setText(""); txtsdt1.setText(""); txtmatkau.setText(""); txtten.setText(""); hinh.setIcon(null); txtcmnd.setText(""); } private void btnnewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnnewActionPerformed neww(); }//GEN-LAST:event_btnnewActionPerformed private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked try { Connection conn = hd.getconection(); int i = table.getSelectedRow(); TableModel model = table.getModel(); txtdangnhap.setText(model.getValueAt(i, 1).toString()); txtmatkau.setText(model.getValueAt(i, 2).toString()); txtten.setText(model.getValueAt(i, 3).toString()); txtemail.setText(model.getValueAt(i, 4).toString()); try { Date date = new SimpleDateFormat("yyyy-MM-dd").parse((String) model.getValueAt(i, 5)); dcngay.setDate(date); } catch (Exception e) { } String gioitinh = (model.getValueAt(i, 6).toString()); if (gioitinh.equals("Nam")) { nam.setSelected(true); } else { nu.setSelected(true); } txtsdt1.setText(model.getValueAt(i, 7).toString()); txtcmnd.setText(model.getValueAt(i, 8).toString()); txtdiachi.setText(model.getValueAt(i, 9).toString()); String trangthai = (model.getValueAt(i, 10).toString()); if (trangthai.equals("1")) { nhanvien.setSelected(true); } else { quanly.setSelected(true); } try { byte[] img = (getlist().get(i).getHinh()); ImageIcon icon = new ImageIcon(new ImageIcon(img).getImage(). getScaledInstance(hinh.getWidth(), hinh.getHeight(), Image.SCALE_SMOOTH)); hinh.setIcon(icon); } catch (Exception e) { } } catch (Exception e) { e.printStackTrace(); } }//GEN-LAST:event_tableMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnnew; private javax.swing.JButton btnsua; private javax.swing.JButton btnthem; private javax.swing.JButton btnxoa; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.ButtonGroup buttonGroup2; private javax.swing.JButton cbnchon; private com.toedter.calendar.JDateChooser dcngay; private javax.swing.JLabel hinh; private javax.swing.JDesktopPane jDesktopPane1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel134; private javax.swing.JLabel jLabel135; private javax.swing.JLabel jLabel136; private javax.swing.JLabel jLabel137; private javax.swing.JLabel jLabel138; private javax.swing.JLabel jLabel139; private javax.swing.JLabel jLabel140; private javax.swing.JLabel jLabel141; private javax.swing.JLabel jLabel142; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel40; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTabbedPane jTabbedPane2; private javax.swing.JRadioButton nam; private javax.swing.JRadioButton nhanvien; private javax.swing.JRadioButton nu; private javax.swing.JRadioButton quanly; private javax.swing.JTable table; private javax.swing.JTextField txtcmnd; private javax.swing.JTextField txtdangnhap; private javax.swing.JTextArea txtdiachi; private javax.swing.JTextField txtemail; private javax.swing.JPasswordField txtmatkau; private javax.swing.JTextField txtsdt1; private javax.swing.JTextField txtten; // End of variables declaration//GEN-END:variables }
true
412cf28e3c90d8bb3575ba09dba42c3cb9d5c04a
Java
4dz/urlshortener
/src/test/java/com/perry/urlshortener/service/ShortenerServiceImplTest.java
UTF-8
1,181
2.625
3
[ "MIT" ]
permissive
package com.perry.urlshortener.service; import com.perry.urlshortener.UnrecognisedTokenException; import org.junit.Test; import java.net.MalformedURLException; import java.net.URL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; public class ShortenerServiceImplTest { @Test public void shouldConvertUrlToToken() throws MalformedURLException { ShortenerServiceImpl service = new ShortenerServiceImpl(); String shortUrl = service.shorten(new URL("http://test.com/url?param=value")); assertThat(shortUrl, equalTo("-")); } @Test public void shouldConvertTokenToUrl() throws UnrecognisedTokenException, MalformedURLException { String url = "http://test.com/url?param=value"; ShortenerServiceImpl service = new ShortenerServiceImpl(); String token = service.shorten(new URL(url)); assertThat(service.expand(token), equalTo(url)); } @Test(expected=UnrecognisedTokenException.class) public void shouldThrowException_WhenNullToken() throws UnrecognisedTokenException { new ShortenerServiceImpl().expand(null); } }
true
ffaa23153d79d244685afd4dff1f16c24135ca1f
Java
IvDobr/olymp
/src/Compare.java
UTF-8
1,307
3.453125
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Compare { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out, true); String a = "", b = ""; try { a = br.readLine(); b = br.readLine(); } catch (IOException ex) { pw.println("Reading error"); } int len_a = a.length(); int len_b = b.length(); StringBuilder s = new StringBuilder(); if (len_a > len_b) { for (int i = 1; i <= len_a-len_b; i++) { s.append("0"); } b = s.toString() + b; } else { for (int i = 1; i <= len_b-len_a; i++) { s.append("0"); } a = s.toString() + a; } String status = "="; for (int i = 0; i <= a.length() - 1; i++) { if (a.charAt(i) < b.charAt(i)) { status = "<"; break; } else if (a.charAt(i) > b.charAt(i)) { status = ">"; break; } } pw.println(status); } }
true
0a6ca28ad007231e34efeaffa97d60f5c0256d02
Java
itsBen/hdm-wim-devlab
/sharedLib/src/main/java/de/hdm/wim/sharedLib/events/UserContextEvent.java
UTF-8
1,531
2.453125
2
[]
no_license
package de.hdm.wim.sharedLib.events; import de.hdm.wim.sharedLib.Constants.PubSub.AttributeKey; import de.hdm.wim.sharedLib.Constants.PubSub.EventType; /** * The type User context event. * * @author Gezim Krasniqi * @see <a href="https://github.com/Purii/hdm-wim-devlab/blob/master/docs/Events.md#usercontextevent">UserContextEvent</a> */ public class UserContextEvent extends IEvent { /** * Instantiates a new User context event. */ public UserContextEvent(){ this.attributes.put(AttributeKey.EVENT_TYPE, EventType.USER_CONTEXT); } /** * Get user ids string. * * @return the string */ public String getUserIds(){ return this.attributes.get(AttributeKey.USER_IDS).toString(); } /** * Set user ids. * * @param userIds the user ids */ public void setUserIds(String userIds){ this.attributes.put(AttributeKey.USER_IDS, userIds); } /** * Get user names string. * * @return the string */ public String getUserNames(){ return this.attributes.get(AttributeKey.USER_NAMES).toString(); } /** * Set user names. * * @param userNames the user names */ public void setUserNames(String userNames){ this.attributes.put(AttributeKey.USER_NAMES, userNames); } /** * Get context string. * * @return the string */ public String getContext(){ return this.attributes.get(AttributeKey.CONTEXT).toString(); } /** * Set context. * * @param context the context */ public void setContext(String context){ this.attributes.put(AttributeKey.CONTEXT, context); } }
true
95f1d9571901b107e952dec4ce695a88dd162725
Java
Web-AtoZ/Spring
/src/main/java/com/webatoz/backend/domain/board/CreateBoardDomain.java
UTF-8
632
2.015625
2
[]
no_license
package com.webatoz.backend.domain.board; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class CreateBoardDomain { @NotBlank(message = "title must not be blank.") private String title; @NotBlank(message = "content must not be blank.") private String content; @NotNull(message = "userId must not be null.") private Integer userId; private Integer categoryId; private Integer restaurantId; }
true
876141fd2862ac6c84e3dccb926e9282aca7a058
Java
javaherisaber/MunicipalityQom
/app/src/main/java/ir/highteam/shahrdari/qom/adapter/AdapterMessageRecycler.java
UTF-8
2,610
2.265625
2
[]
no_license
package ir.highteam.shahrdari.qom.adapter; import android.content.Context; import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import ir.highteam.shahrdari.qom.R; import ir.highteam.shahrdari.qom.bundle.BundleMessage; /** * Created by mohammad on 5/21/2016. */ public class AdapterMessageRecycler extends RecyclerView.Adapter<AdapterMessageRecycler.MessageViewHolder> { private List<BundleMessage> messageList; private Context contextMain; Typeface tfSans; public AdapterMessageRecycler(List<BundleMessage> messageList, Context context) { this.messageList = messageList; this.contextMain = context; tfSans = Typeface.createFromAsset(contextMain.getAssets(), "IRAN Sans.ttf"); } @Override public void onBindViewHolder(MessageViewHolder appViewHolder, final int position) { BundleMessage messageInfo = messageList.get(position); appViewHolder.txtLotteryCode.setText("کد قرعه کشی : "+messageInfo.lotteryCode); appViewHolder.txtPursueCode.setText("کد پیگیری : "+messageInfo.pursueCode); appViewHolder.txtDate.setText(messageInfo.date); appViewHolder.txtLotteryCode.setTypeface(tfSans); appViewHolder.txtPursueCode.setTypeface(tfSans); appViewHolder.txtDate.setTypeface(tfSans); } @Override public int getItemCount() { return messageList.size(); } @Override public MessageViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_message_item, viewGroup, false); MessageViewHolder message = new MessageViewHolder(itemView); return message; } public class MessageViewHolder extends RecyclerView.ViewHolder { protected TextView txtLotteryCode; protected TextView txtPursueCode; protected TextView txtDate; public MessageViewHolder(View v) { super(v); contextMain = v.getContext(); txtLotteryCode = (TextView) v.findViewById(R.id.txtLotteryCode); txtPursueCode = (TextView) v.findViewById(R.id.txtPursueCode); txtDate = (TextView) v.findViewById(R.id.txtDate); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); } } }
true
14e48c0e956f491013302a5858de2c8e9006a0ef
Java
samplestringz/CSRoulette
/Main.java
UTF-8
21,033
3.671875
4
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import java.util.Scanner; public class Main { // ATTRIBUTES ====================== // --------------------------------- static Player[] player; // THIS ARRAY CONTAINS THE PLAYERS static Scanner input; // SCANNER OBJECT TO READ PLAYER INPUT static int player_count; // HOW MANY PLAYERS? static int number; // THE MAGIC NUMBER static int rounds; // HOW MANY ROUNDS HAVE BEEN PLAYED static int next_player; // WHICH PLAYER GOES NEXT? static int max_rounds; // HOW MANY ROUNDS WILL BE PLAYED? static boolean[] picked; // KEEPS TRACK OF WHICH NUMBERS HAVE BEEN PICKED static boolean lightning_round; // INPUT.....NOW! (MORE INFO IN UPDATE LOG) static boolean sudden_round; // SUDDEN DEATH ROUND (MORE INFO IN UPDATE LOG) // MAIN METHOD ===================== // --------------------------------- public static void main(String[] args) throws IOException { // CREATE A NEW INSTANCE OF A SCANNER, WHICH // ALLOWS US TO ACCEPT INPUT FROM USERS input = new Scanner(System.in); // PRINT A WELCOME MESSAGE WelcomeMessage(); // GET THE NUMBER OF PLAYERS player_count = GetNumberOfPlayers(); // SET THE SIZE OF THE PLAYER ARRAY player = new Player[player_count]; // SET PLAYER NAMES SetPlayerNames(); // DEFAULT MAX # OF ROUNDS (CUSTOMIZABLE) max_rounds = 5; // CHOOSE GAME MODE ChooseMode(); // CHOOSE A RANDOM PLAYER TO START System.out.println("Choosing who goes first...\n"); next_player = (int)(Math.random() * (double)player_count); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~MAIN LOOP~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // THIS LOOP RUNS THE WHOLE GAME while (rounds < max_rounds) { // "PRESS ANY KEY TO CONTINUE" System.out.println("Input to proceed..."); input.next(); // SETUP A NEW ROUND StartNewRound(); // THIS LOOP RUNS A SINGLE ROUND while (GetPlayersLeft() > 1) { // ~~~~~~~~~~~~~~~OBTAINING INPUT~~~~~~~~~~~~~~~ // DID THEY SURVIVE? boolean survived = true; // DETECTS INPUT (LIGHTNING ROUND) boolean input_present = true; // PROMPT THE NEXT PLAYER System.out.println(player[next_player].GetName().toUpperCase() + ", IT IS YOUR TURN."); System.out.print("Choose a number (0-9): "); // 3, 2, 1 SECS TO INPUT, VARIES INVERSELY WITH ROUND NUMBER (LIGHTNING ROUND) if (lightning_round) input_present = TimeInput(GetTimeFrame() ); // STORE THE PLAYER'S CHOICE int choice = 0; // NO INPUT? NO MERCY (LIGHTNING ROUND) if (lightning_round && !input_present) { survived = false; System.out.println("NOT FAST ENOUGH!"); } // GET THEIR CHOICE else { choice = input.nextInt(); input.nextLine(); } // THIS HOLDS A MESSAGE IN CASE THEY CHOSE POORLY String message = ""; // ~~~~~~~~~~~~~~~INTERPRETING CHOICE~~~~~~~~~~~~~~~ if (choice == number) { // THEY PICKED THE MAGIC NUMBER survived = false; message = "Tough luck!"; } else if (choice < 0) { // THEY PICKED A NUMBER TOO LOW (BELOW RANGE) survived = false; message = choice + " was never an option..."; player[next_player].smart = true; System.out.println("Uh, OK..."); } else if (choice > 9) { // THEY PICKED A NUMBER TOO HIGH (ABOVE RANGE) survived = false; message = choice + " was never an option..."; player[next_player].smart = true; System.out.println("Uh, OK..."); } else if (picked[choice]) { // THEY PICKED A NUMBER THAT HAD ALREADY BEEN PICKED survived = false; message = choice + " has already been picked!"; player[next_player].smart = true; System.out.println("Uh, OK..."); } // GIVE SOME SPACE... System.out.println(); // ~~~~~~~~~~~~~~~DETERMINING SURVIVAL~~~~~~~~~~~~~~~ // THEY DIDN'T SURVIVE! if (!survived) { // LET THE USER KNOW THAT THEY FAILED System.out.println("( { K A B O O M } )"); System.out.println(player[next_player].GetName().toUpperCase() + " HAS BEEN ELIMINATED."); System.out.println(message); System.out.println(); java.awt.Toolkit.getDefaultToolkit().beep(); // <-- BEEP! // REMEMBER THAT THEY LOST player[next_player].lost = true; // CHECK TO SEE IF THIS ENDED THE ROUND // AND PREP THE NEXT ROUND IF SO if (GetPlayersLeft() > 1) { SetNewNumber(); ResetPickedNumbers(); } } // THEY DID SURVIVE! else { // RECORD THAT THIS NUMBER IS NO LONGER AVAILABLE picked[choice] = true; // RANDOM CHANCE TO CLOWN ON THE PLAYER (2% CHANCE) if ((int) (Math.random() * 50) == 0) CheekyMessage(); } // WHO'S NEXT? ChooseNextPlayer(); } // INCREASE THE ROUND COUNT rounds++; System.out.println(); // INCREASE SCORE AND RESET PLAYER STATES for (int i = 0; i < player_count; i++) { if (!player[i].lost) { // ADD A POINT TO THE WINNER player[i].score++; // LET EVERYONE KNOW WHO WON System.out.println("-----------------------------------------------"); System.out.println(player[i].GetName().toUpperCase() + " WINS ROUND " + rounds + "."); System.out.println("-----------------------------------------------"); } // RESET THIS FOR THE NEXT ROUND player[i].lost = false; } // SHOW THE SCORES PrintScores(); // MAKE SOME SPACE... System.out.println(); // TAKE TOP TWO PLAYERS IN THE LAST ROUND AND START SUDDEN DEATH if ((player[player.length - 1].score == player[player.length - 2].score) && (rounds == max_rounds - 1) ) { SuddenDeath(); } } System.out.println("-----------------------------------------------"); System.out.println(player[player.length - 1].GetName().toUpperCase() + " WINS THE GAME!!!"); System.out.println("-----------------------------------------------"); // THE GAME HAS ENDED System.out.println("!!! GAME OVER !!!"); } // MISCELLANEOUS METHOD ===================== // --------------------------------- public static void PrintScores () { // GET THE LENGTH OF THE LONGEST NAME int longest_name = LongestName(); // SORT THE PLAYERS BEFOREHAND SortPlayers(); // LOOP THROUGH ALL PLAYERS (BACKWARDS INCREASING ORDER -> DECREASING) for (int i = player_count - 1; i >= 0; i--) { // DETERMINE HOW MANY SPACES WE SHOULD ADD IN // ORDER TO GET THE NAMES AND SCORES TO ALIGN int difference = longest_name - player[i].GetName().length(); // PRINT THE PLAYER'S NAME System.out.print(player[i].GetName()); // PRINT EXTRA SPACES for (int j = 0; j < difference; j++) { System.out.print(" "); } // PRINT POINTS System.out.println(" - " + player[i].score + (player[i].score == 1 ? " pt." : " pts.")); } } public static int LongestName () { // ASSUME THE LONGEST NAME IS 0 CHARACTERS int result = 0; // LOOP THROUGH THE PLAYERS for (int i = 0; i < player_count; i++) { // DID WE FIND A LONGER NAME? if (player[i].GetName().length() > result) result = player[i].GetName().length(); } // RETURN THE RESULT return result; } public static int GetPlayersLeft () { // ASSUME THERE'S NOBODY LEFT... int players_left = 0; // LOOK AT EACH PLAYER AND CHECK IF THEY HAVEN'T LOST for (int i = 0; i < player_count; i++) { if (!player[i].lost) players_left++; } // RETURN THE RESULTS return players_left; } public static void ChooseNextPlayer () { // LOOP UNTIL WE FIND A VALID PLAYER do { // MOVE TO THE NEXT PLAYER next_player++; // IF WE MOVED TOO FAR, WRAP AROUND TO ZERO if (next_player >= player_count) next_player = 0; } while (player[next_player].lost); } public static void ResetPickedNumbers () { // RESET THE PICKED ARRAY picked = new boolean[10]; } public static void SetNewNumber () { // CHOOSE A RANDOM NUMBER [0, 9] number = (int)(Math.random() * 9.1); // PROMPT THE USER System.out.println("A new number has been chosen."); System.out.println(); // SAVED ME WHEN DEBUGGING // System.out.println(number); } public static void StartNewRound () { // ANNOUNCE THE START OF A NEW ROUND System.out.println("The game " + (rounds == 0 ? "begins!" : "continues...")); System.out.println("==============================================="); // GENERATE A NEW NUMBER SetNewNumber(); // RESET PICKED ARRAY ResetPickedNumbers(); } public static void SetPlayerNames () { // LOOP THROUGH THE PLAYERS for (int i = 0; i < player_count; i++) { // PROMPT THE USER System.out.print("Player " + (i+1) + ", enter your name: "); // INSTANTIATE A NEW PLAYER USING THE NAME THAT'S PROVIDED player[i] = new Player(input.nextLine()); // IF THE PLAYER DOESN'T ENTER A NAME, CALL THEM "BIG BRAIN" if (player[i].name.length() == 0) { player[i].name = "Big Brain"; System.out.println("Uh, OK..."); } } // MAKE SOME SPACE... System.out.println(); } public static int GetNumberOfPlayers () { // ASSUME THERE ARE NO PLAYERS int result; // LOOP UNTIL A VALID NUMBER IS ENTERED do { // PROMPT THE USER System.out.print("Enter the number of players: "); // GET THE RESULT & MAKE SOME SPACE result = input.nextInt(); input.nextLine(); System.out.println(); // MUST HAVE AT LEAST TWO PLAYERS if (result < 2) { System.out.println("You need at least two players!\n"); } } while (result < 2); // RETURN THE RESULT return result; } public static void ChooseMode () { // CHOOSE GAME MODE int choice; // KILL LOOP UPON VALID OPTION boolean kill_switch = false; while (!kill_switch) { System.out.println("====GAMEPLAY OPTIONS===="); System.out.println("[1] CLASSIC ROUND\n[2] LIGHTNING ROUND (2 players)\n[3] SET ROUNDS"); System.out.print("Enter your choice: "); // CHOICES - NORMAL MODE, SPEED MODE, SET # OF ROUNDS choice = input.nextInt(); if (choice == 1) { lightning_round = false; kill_switch = true; } if (choice == 2 && player_count == 2) { lightning_round = true; kill_switch = true; } if (choice == 3) { // REMEMBER CURRENT # OF ROUNDS // SO THAT IT DOES NOT UPDATE IF THE PLAYER PUTS AN INVALID NUMBER int temp = max_rounds; do { System.out.println("Set the number of max. rounds (currently " + temp + "): "); max_rounds = input.nextInt(); if (max_rounds < 3) System.out.println("Must play at least 3 rounds!"); } while (max_rounds < 3); } // IF KILL SWITCH IS STILL OFF, THEY MUST HAVE NOT PUT A VALID INPUT else if (!kill_switch) { System.out.println("Invalid Option!\n"); } System.out.println(); } } public static void SuddenDeath () { // YOU'VE BEEN AVOIDING THE NUMBER THE WHOLE TIME; NOW YOU MUST CHOOSE IT! sudden_round = true; // USED AS A WORK AROUND TO THE ChooseNextPlayer() METHOD WHEN THERE ARE >2 PLAYERS int times_looped = 2; // TAKE THE TOP 2 PLAYERS (NOT MOST OPTIMAL WAY BUT DEFINITELY SIMPLER) String[] players_left = {player[player.length - 1].name, player[player.length - 2].name}; // LET THE PLAYERS KNOW THAT THE SUDDEN DEATH ROUND HAS BEGUN System.out.println(); System.out.println("==============================================="); System.out.println("SUDDEN DEATH HAS BEGUN!"); System.out.println("NOW IT IS TIME TO GUESS THE NUMBER!"); System.out.println("-----------------------------------------------"); System.out.println(players_left[0] + " AND " + players_left[1] + "\nGET READY!"); System.out.println("==============================================="); // RESET ANY NUMBERS BEFORE, SET THE FINAL NUMBER ResetPickedNumbers(); SetNewNumber(); while (sudden_round) { // TAKE TURNS BETWEEN THE TWO PLAYERS System.out.println(players_left[times_looped%2]+ ", IT IS YOUR TURN."); System.out.print("Choose a number (0-9): "); // STORE THEIR CHOICE int choice = input.nextInt(); if (choice == number) { // UPDATE (SO THAT THE WINNER IS IN THE LAST INDEX) player[player.length - 1].name = players_left[times_looped%2]; // THEY PICKED THE WINNING NUMBER, END SUDDEN DEATH sudden_round = false; rounds++; } else if (choice < 0) { // THEY PICKED A NUMBER TOO LOW (BELOW RANGE) System.out.println(choice + " was never an option..."); player[next_player].smart = true; System.out.println("Uh, OK..."); } else if (choice > 9) { // THEY PICKED A NUMBER TOO HIGH (ABOVE RANGE) System.out.println(choice + " was never an option..."); player[next_player].smart = true; System.out.println("Uh, OK..."); } else if (picked[choice]) { // THEY PICKED A NUMBER THAT HAD ALREADY BEEN PICKED System.out.println(choice + " has already been picked!"); player[next_player].smart = true; System.out.println("Uh, OK..."); } else { // REMEMBER CHOSEN NUMBER picked[choice] = true; // INCREMENT EACH TIME times_looped++; // LEAVE SOME SPACE... System.out.println(); } } } public static void SortPlayers () { /* BUBBLE SORTING ALGORITHM IN INCREASING ORDER, IMPLEMENTING DESCENDING ORDER CREATES STRANGE BEHAVIOR: ~KNOW~ THAT THE ARRAY WILL BE IN THIS ORDER WHEN DOING ANYTHING */ boolean sorted = false; Player temp; while (!sorted) { sorted = true; for (int i = 0; i < player.length - 1; i++) { if (player[i].score > player[i + 1].score) { // SWAP THE OBJECTS' POSITION IN THE ARRAY temp = player[i]; player[i] = player[i + 1]; player[i + 1] = temp; sorted = false; } } } } public static boolean TimeInput (int time_frame) throws IOException { // BufferedReader OBJECT BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // STORE THE STARTING TIME long startTime = System.currentTimeMillis(); // RUN WHILE ([THE TIME SINCE THIS METHOD WAS CALLED] IS LESS THAN [TIME DESIRED]); // INTENTIONALLY EMPTY, JUST RUNS IN THE BACKGROUND while ((System.currentTimeMillis() - startTime) < time_frame * 1000 && !in.ready()) {} return in.ready(); } public static int GetTimeFrame () { if ( (rounds > (max_rounds/1.6)) ) return 1; else if ( (rounds > (max_rounds/3)) ) return 2; else return 3; } public static void CheekyMessage () { // ADD GAGS HERE int random_number = (int)(Math.random() * 6.1 + 1); String victim = player[next_player].name.toUpperCase(); // LIST OF MESSAGES switch (random_number) { case 1: System.out.println("PLAYER " + victim + "... HAVE A NICE DAY!"); break; case 2: System.out.println("TOASTY!"); break; case 3: System.out.println("BOO, " + victim); break; case 4: System.out.println("DNS SPOOKED YOU!"); break; case 5: System.out.println("INTERESTING CHOICE."); break; case 6: System.out.println("DID " + victim + " REALLY CHOOSE THAT?"); break; } System.out.println(); java.awt.Toolkit.getDefaultToolkit().beep(); // <-- BEEP! } public static void WelcomeMessage () { // PRINTS THE TITLE AND VERSION OF THE GAME System.out.println("==============================================="); System.out.println(" C O M P U T E R"); System.out.println(" S C I E N C E"); System.out.println(" R O U L E T T E"); System.out.println("====================================== v1.2 ==="); System.out.println(); } } // Santi's v1.2 ========================================================================= // * Menu: Classic Round or Lightning Round. -> ChooseMode() // * Classic Round: Mode we all know and love! // * Lightning Round: Limited time for input, no mercy for the slow. -> TimeInput(time) // * Set Rounds: Let's the player set the maximum # of rounds (default at 5). // * Sudden Death: Activates on the last round, takes top two players. -> SuddenDeath() // * Array Sorting Algorithm: Bubble sort (increasing). -> SortPlayers() // * Players sorted by score! -> PrintScores() loop is now backwards // * Winner announced! -> player.length - 1 // * Number now between [0, 9] -> iN cS yOu sTaRt cOuNTinG fRoM 0 // * Just more convenient in actual gameplay; feel free to change it back. // * Gags! Great chance to scare the player. -> CheekyMessage() // * Definitely add more jokes! // * More comments :~) // * Removed Herobrine.
true
aad7dc5d850bf4975cffc53e5ccde8a724e87397
Java
guilherme-gmonteiro/musicPoo
/src/main/java/Controllers/MusicaController.java
UTF-8
966
2.09375
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 Controllers; import DAO.MusicaDao; import Models.Musica; import java.util.ArrayList; /** * * @author guilherme */ public class MusicaController { public static ArrayList<Musica> ultimasAdicionadas() { return MusicaDao.ultimasAdicionadas(); } public static ArrayList<Musica> musicasUsuario() { return MusicaDao.musicasUsuario(); } public static Musica musicaPorId(int id) { return MusicaDao.musicaPorId(id); } public static boolean excluir(int id) { return MusicaDao.excluir(id); } public static boolean salvar(Musica musica) { return MusicaDao.salvar(musica); } public static boolean atualizar(Musica musica) { return MusicaDao.atualizar(musica); } }
true
50bf6ba0a9dcf6290b1770005cef00a79143acb7
Java
vubom01/Bomberman
/src/uet/oop/bomberman/entities/tile/item/Item.java
UTF-8
462
2.625
3
[]
no_license
package uet.oop.bomberman.entities.tile.item; import uet.oop.bomberman.entities.Entity; import uet.oop.bomberman.gui.Sprite; public abstract class Item extends Entity { private int level; public Item(double x, double y, int level, Sprite sprite) { this.x = x; this.y = y; this.sprite = sprite; this.level = level; } public abstract void setValues(); public int getLevel() { return level; } }
true
1bdcbc066445f3242dcdfe12d119c00b81ee99e5
Java
atomqin/leetcode
/problems/567.字符串的排列.java
UTF-8
1,029
2.9375
3
[]
no_license
import java.util.Arrays; /* * @Descripttion: * @Author: atomqin * @Date: 2021-03-29 10:16:58 * @LastEditTime: 2021-03-29 15:52:47 */ /* * @lc app=leetcode.cn id=567 lang=java * * [567] 字符串的排列 */ // @lc code=start class Solution { public boolean checkInclusion(String s1, String s2) { if (s1.length() > s2.length()) return false; int[] window = new int[128]; int[] s1_map = new int[128]; //窗口长度为 s1.length() for (int i = 0; i < s1.length(); i++) { s1_map[s1.charAt(i)]++; window[s2.charAt(i)]++; } if (Arrays.equals(window, s1_map)) return true; int left = 0, right = s1.length(); while (right < s2.length()) { window[s2.charAt(right)]++; right++; window[s2.charAt(left)]--; left++; if (Arrays.equals(window, s1_map)) return true; } return false; } } // @lc code=end
true
bff55c16fe820df5bf4af5b3ef3a5afa020c0049
Java
dannyBoie/ProblemSolverAndroid
/app/src/main/java/domains/puzzle/PuzzleState.java
UTF-8
4,795
3.015625
3
[]
no_license
package domains.puzzle; import framework.problem.State; import java.util.Arrays; public class PuzzleState implements State { private final int[][] tiles; public int[][] getTiles() { return tiles; } public PuzzleState(int[][] tiles) { this.tiles = tiles; } public static class Location { public Location(int row, int column) { this.row = row; this.column = column; } public int getRow() { return row; } public int getColumn() { return column; } @Override public String toString() { return "(" +row+ "," +column+ ")"; } @Override public boolean equals(Object o) { if (o == null) return false; if (o.getClass() != this.getClass()) return false; Location other = (Location) o; return this.row == other.row && this.column == other.column; } @Override public int hashCode() { int hash = 3; hash = 29 * hash + this.row; hash = 29 * hash + this.column; return hash; } private int row; private int column; } public PuzzleState (PuzzleState state, Location loc1, Location loc2) { tiles = copyTiles(state.tiles); int temp = tiles[loc1.row][loc1.column]; tiles[loc1.row][loc1.column] = tiles[loc2.row][loc2.column]; tiles[loc2.row][loc2.column] = temp; } public Location getLocation(int tile) { for (int r = 0; r < tiles.length; r++) { for (int c = 0; c < tiles[r].length; c++) { if (tiles[r][c] == tile) { return new Location(r,c); } } } throw new RuntimeException("Tile " +tile+ " not found in\n" +toString()); } @Override public boolean equals(Object o) { if (o == null) return false; if (o.getClass() != PuzzleState.class) return false; PuzzleState other = (PuzzleState) o; if (this == other) return true; return Arrays.deepEquals(this.tiles, other.tiles); } @Override public int hashCode() { int hash = 7; hash = 67 * hash + Arrays.deepHashCode(this.tiles); return hash; } @Override public String toString() { int width = tiles[0].length; StringBuilder builder = new StringBuilder(); for (int[] row : tiles) { builder.append(horizontalDivider(width)); builder.append("\n"); builder.append(horizontalRow(row)); builder.append("\n"); } builder.append(horizontalDivider(width)); return builder.toString(); } private static String horizontalDivider(int width) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < width; i++) { builder.append("+---"); } builder.append("+"); return builder.toString(); } private static String horizontalRow(int[] tiles) { StringBuilder builder = new StringBuilder(); for (int tile : tiles) { builder.append("|"); builder.append(tileString(tile)); } builder.append("|"); return builder.toString(); } private static String tileString(int tile) { if ( tile == 0 ) return " "; if ( tile/10 == 0 ) return " " + tile + " "; return tile + " "; } private static int[][] copyTiles(int[][] source) { int rows = source.length; int columns = source[0].length; int[][] dest = new int[rows][columns]; for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { dest[r][c] = source[r][c]; } } return dest; } public int getHueristic(State goal) { return sumManhattan(this, goal); } public static int sumManhattan(State current, State goal) { int sum = 0; PuzzleState curr = (PuzzleState)current; PuzzleState fin = (PuzzleState)goal; int currTiles[][] = curr.getTiles(); int finTiles[][] = fin.getTiles(); for(int r = 0; r < currTiles.length; r++) { for(int c = 0; c < currTiles[0].length; c++) { if(currTiles[r][c] != 0) { Location currLoc = curr.getLocation(currTiles[r][c]); Location finLoc = fin.getLocation(currTiles[r][c]); sum += Math.abs(currLoc.getRow() - finLoc.getRow()); sum += Math.abs(currLoc.getColumn() - finLoc.getColumn()); } } } return sum; } }
true
2dee063fd991ea4d96d6c4884eb19f1dbd6dfbe2
Java
fatalaa/leanpoker-android
/app/src/main/java/org/leanpoker/leanpokerandroid/view/activity/EventListActivity.java
UTF-8
1,351
2.015625
2
[]
no_license
package org.leanpoker.leanpokerandroid.view.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.Menu; import org.leanpoker.leanpokerandroid.R; import org.leanpoker.leanpokerandroid.view.adapter.EventListViewPagerAdapter; /** * Created by tbalogh on 06/09/15. */ public class EventListActivity extends BaseActivity { private ViewPager mViewPager; private EventListViewPagerAdapter mViewPagerAdapter; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.actvity_event_list); setupUI(); } private void setupUI() { mViewPagerAdapter = new EventListViewPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager_events_by_time); mViewPager.setAdapter(mViewPagerAdapter); // TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs); // tabLayout.setupWithViewPager(mViewPager); setTitle("Events"); } @Override public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } public static Intent createIntent(final Context context) { return new Intent(context, EventListActivity.class); } }
true
6277433f31c433efd3a53a679fce8d2d623f755e
Java
basd1918/Licenta
/app/src/main/java/com/example/administrator/AddActivity.java
UTF-8
2,689
2.390625
2
[]
no_license
package com.example.administrator; import android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import database.DatabaseHelper; public class AddActivity extends AppCompatActivity { DatabaseHelper myDb; EditText editText_numarAp,editText_numeProprietar,editText_email,editText_ocupatie,editText_numarPersoane; Button buttonAdd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); myDb= new DatabaseHelper(this); editText_numarAp=(EditText)findViewById(R.id.editText_numarAp); editText_numeProprietar=(EditText)findViewById(R.id.editText_numeProprietar); editText_email=(EditText)findViewById(R.id.editText_email); editText_ocupatie=(EditText)findViewById(R.id.editText_ocupatie); editText_numarPersoane=(EditText)findViewById(R.id.editText_numarPersoane); buttonAdd=(Button) findViewById(R.id.buttonAdd); AddData(); } public void AddData(){ buttonAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(editText_numarAp.length()==0){editText_numarAp.setError("Introduceti numarul apartamentului");} else if(editText_numeProprietar.length()==0){editText_numeProprietar.setError("Introduceti proprietarul");} else if(editText_email.length()==0){editText_email.setError("Introduceti email");} else if(editText_ocupatie.length()==0){editText_ocupatie.setError("Introduceti suprafata");} else if(editText_numarPersoane.length()==0){editText_numarPersoane.setError("Introduceti numarul de persoane");} else { boolean isInserted = myDb.insertData(editText_numarAp.getText().toString(), editText_numeProprietar.getText().toString(), editText_email.getText().toString(), editText_ocupatie.getText().toString(), editText_numarPersoane.getText().toString()); if (isInserted == true) { Toast.makeText(AddActivity.this, "Apartament adaugat", Toast.LENGTH_LONG).show(); finish(); } else Toast.makeText(AddActivity.this, "Apartamentul nu a putut fi adaugat...", Toast.LENGTH_LONG).show(); } } }); } }
true
7e4e931a84fe07c0be9a05e3711bfc424d401d82
Java
olegpetskovich/Avis.help
/app/src/main/java/com/pinus/alexdev/avis/network/apiServices/ConversationApiService.java
UTF-8
1,966
1.96875
2
[]
no_license
package com.pinus.alexdev.avis.network.apiServices; import com.pinus.alexdev.avis.dto.Conversation; import com.pinus.alexdev.avis.dto.request.ChatByNumberRequest; import com.pinus.alexdev.avis.dto.response.BranchesResponse; import com.pinus.alexdev.avis.dto.response.ConversationResponse; import java.util.ArrayList; import io.reactivex.Single; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; public interface ConversationApiService { @GET("/api/v1/chat/{chatId}/message/all") Single<ArrayList<Conversation>> getConversationHistory(@Path("chatId") String chatId); @POST("/api/v1/chat/{chatId}") Single<String> setChatViewed(@Path("chatId") String reviewId); @GET("/api/v1/organization/{organizationId}/chat") Single<ArrayList<ConversationResponse>> getOrganizationConversationsList(@Path("organizationId") int organizationId); @GET("/api/v1/organization/{organizationId}/bundle/chats") Single<ArrayList<ConversationResponse>> getConversationsListByBranchId(@Path("organizationId") int organizationId, @Query("branchIdList") int branchIdList); @POST("/api/v1/organization/{organizationId}/branch/{branchId}/chat") Single<ConversationResponse> addChatByNumber(@Path("organizationId") int organizationId, @Body ChatByNumberRequest chatByNumberRequest, @Path("branchId") int branchId); @POST("/api/v1/organization/review/{reviewId}/chat") Single<ConversationResponse> addChatByReviewId(@Path("reviewId") int reviewId); @POST("/api/v1/chat/chat-room/{roomId}/message") Single<ArrayList<Conversation>> getChatList(@Path("roomId") int roomId, @Query("order") String order, @Query("page") int page, @Query("size") int size, @Query("sortBy") String sortBy); @GET("/api/v1/organization/{organizationId}/branch") Single<ArrayList<BranchesResponse>> getBranchList(@Path("organizationId") int organizationId); }
true
41b846f577005f91825cf3af2cf0cc95217722b0
Java
tsuzcx/qq_apk
/com.tencent.mm/classes.jar/com/tencent/mm/protocal/protobuf/cxg.java
UTF-8
5,755
1.648438
2
[]
no_license
package com.tencent.mm.protocal.protobuf; import com.tencent.matrix.trace.core.AppMethodBeat; import i.a.a.b; import java.util.LinkedList; public final class cxg extends esc { public gjx ZiP; public LinkedList<gkl> aaCN; public LinkedList<gkl> aaCO; public int status; public cxg() { AppMethodBeat.i(123599); this.aaCN = new LinkedList(); this.aaCO = new LinkedList(); AppMethodBeat.o(123599); } public final int op(int paramInt, Object... paramVarArgs) { AppMethodBeat.i(123600); if (paramInt == 0) { paramVarArgs = (i.a.a.c.a)paramVarArgs[0]; if (this.BaseResponse == null) { paramVarArgs = new b("Not all required fields were included: BaseResponse"); AppMethodBeat.o(123600); throw paramVarArgs; } if (this.BaseResponse != null) { paramVarArgs.qD(1, this.BaseResponse.computeSize()); this.BaseResponse.writeFields(paramVarArgs); } if (this.ZiP != null) { paramVarArgs.qD(2, this.ZiP.computeSize()); this.ZiP.writeFields(paramVarArgs); } paramVarArgs.e(3, 8, this.aaCN); paramVarArgs.e(4, 8, this.aaCO); paramVarArgs.bS(5, this.status); AppMethodBeat.o(123600); return 0; } if (paramInt == 1) { if (this.BaseResponse == null) { break label750; } } label750: for (paramInt = i.a.a.a.qC(1, this.BaseResponse.computeSize()) + 0;; paramInt = 0) { int i = paramInt; if (this.ZiP != null) { i = paramInt + i.a.a.a.qC(2, this.ZiP.computeSize()); } paramInt = i.a.a.a.c(3, 8, this.aaCN); int j = i.a.a.a.c(4, 8, this.aaCO); int k = i.a.a.b.b.a.cJ(5, this.status); AppMethodBeat.o(123600); return i + paramInt + j + k; if (paramInt == 2) { paramVarArgs = (byte[])paramVarArgs[0]; this.aaCN.clear(); this.aaCO.clear(); paramVarArgs = new i.a.a.a.a(paramVarArgs, unknownTagHandler); for (paramInt = esc.getNextFieldNumber(paramVarArgs); paramInt > 0; paramInt = esc.getNextFieldNumber(paramVarArgs)) { if (!super.populateBuilderWithField(paramVarArgs, this, paramInt)) { paramVarArgs.kFT(); } } if (this.BaseResponse == null) { paramVarArgs = new b("Not all required fields were included: BaseResponse"); AppMethodBeat.o(123600); throw paramVarArgs; } AppMethodBeat.o(123600); return 0; } if (paramInt == 3) { Object localObject1 = (i.a.a.a.a)paramVarArgs[0]; cxg localcxg = (cxg)paramVarArgs[1]; paramInt = ((Integer)paramVarArgs[2]).intValue(); Object localObject2; switch (paramInt) { default: AppMethodBeat.o(123600); return -1; case 1: paramVarArgs = ((i.a.a.a.a)localObject1).aMP(paramInt); i = paramVarArgs.size(); paramInt = 0; while (paramInt < i) { localObject1 = (byte[])paramVarArgs.get(paramInt); localObject2 = new kd(); if ((localObject1 != null) && (localObject1.length > 0)) { ((kd)localObject2).parseFrom((byte[])localObject1); } localcxg.BaseResponse = ((kd)localObject2); paramInt += 1; } AppMethodBeat.o(123600); return 0; case 2: paramVarArgs = ((i.a.a.a.a)localObject1).aMP(paramInt); i = paramVarArgs.size(); paramInt = 0; while (paramInt < i) { localObject1 = (byte[])paramVarArgs.get(paramInt); localObject2 = new gjx(); if ((localObject1 != null) && (localObject1.length > 0)) { ((gjx)localObject2).parseFrom((byte[])localObject1); } localcxg.ZiP = ((gjx)localObject2); paramInt += 1; } AppMethodBeat.o(123600); return 0; case 3: paramVarArgs = ((i.a.a.a.a)localObject1).aMP(paramInt); i = paramVarArgs.size(); paramInt = 0; while (paramInt < i) { localObject1 = (byte[])paramVarArgs.get(paramInt); localObject2 = new gkl(); if ((localObject1 != null) && (localObject1.length > 0)) { ((gkl)localObject2).parseFrom((byte[])localObject1); } localcxg.aaCN.add(localObject2); paramInt += 1; } AppMethodBeat.o(123600); return 0; case 4: paramVarArgs = ((i.a.a.a.a)localObject1).aMP(paramInt); i = paramVarArgs.size(); paramInt = 0; while (paramInt < i) { localObject1 = (byte[])paramVarArgs.get(paramInt); localObject2 = new gkl(); if ((localObject1 != null) && (localObject1.length > 0)) { ((gkl)localObject2).parseFrom((byte[])localObject1); } localcxg.aaCO.add(localObject2); paramInt += 1; } AppMethodBeat.o(123600); return 0; } localcxg.status = ((i.a.a.a.a)localObject1).ajGk.aar(); AppMethodBeat.o(123600); return 0; } AppMethodBeat.o(123600); return -1; } } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes2.jar * Qualified Name: com.tencent.mm.protocal.protobuf.cxg * JD-Core Version: 0.7.0.1 */
true
5fbc7cb56baf4956796202bcbf3a549691c3d42d
Java
Choicelin/common-utils
/src/main/java/tech/ideashare/controller/ModelController.java
UTF-8
399
1.5
2
[]
no_license
package tech.ideashare.controller; import org.springframework.web.bind.annotation.RestController; /** * @Author lixiang * @CreateTime 16/03/2018 **/ @RestController public class ModelController { /** * 传入的Model名称必须要首字母大写 */ // @GetMapping("/methodGen/{modelName}") // public Mono<String> getUser(@PathVariable String modelName) { // } }
true
42b435526f96fbf1d3acec05de876434833dd173
Java
tyears/hqs
/src/main/java/com/cccuu/project/service/dealerproduct/DealerProductService.java
UTF-8
1,611
1.9375
2
[]
no_license
package com.cccuu.project.service.dealerproduct; import java.util.List; import java.util.Map; import com.cccuu.project.model.dealerproduct.DealerProduct; import com.cccuu.project.utils.BaseService; import com.github.pagehelper.PageInfo; /** * 客户产品关联Service * @Description * @Author zhaixiaoliang * @Date 2017年09月15日 10:44:27 */ public interface DealerProductService extends BaseService<DealerProduct>{ /** * 分页查询列表 * @param params * @return */ public PageInfo<Map<String,Object>> queryListByPage(Map<String,String> params); /** * 查询全部列表 * @param params * @return */ public List<Map<String,Object>> queryProductByDealerId(Map<String,String> params); /** * 修改备注 * @param params */ public void updateRemark(Map<String,String> params); /** * 修改评价 * @param params */ public void updateComment(Map<String,String > params); /** * 批量插入 * @param list * @return */ public int addMulti(List<DealerProduct> list); /** * 查询单个经销商产品关联 * @param uuid * @param productNum * @return */ public List<Map<String, Object>> queryOne(String uuid,String productNum); /** * 根据经销商id和产品id判断是否有数据,有时更新,无是新增 * @param dealerProduct * @param type 新增类型 1:赠送给经销商 2:公司赠送 3:经销商赠送 * pj:经销商品种月均评价导入 jh:最新进货日期导入 ht:后台新增 */ public boolean addDP(DealerProduct dealerProduct,String type); public void updateDealerProductMerit(); }
true
90fa7f0c85613334d9dd67e936d6cc003b42432e
Java
Kenway090704/anagyre2
/app/src/main/java/com/aofei/tch/anagyre/connect/adapter/ClipViewPager.java
UTF-8
5,676
2.078125
2
[]
no_license
package com.aofei.tch.anagyre.connect.adapter; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.AccelerateInterpolator; import com.aofei.tch.anagyre.connect.util.SpeedScroller; import com.aofei.tch.anagyre.other.utils.Debug; import com.aofei.tch.anagyre.other.utils.log.LogUtils; import java.lang.reflect.Field; /** * Created by wujian 15/9/27. */ public class ClipViewPager extends ViewPager { public static final String TAG = "ClipViewPager"; public ClipViewPager(Context context) { super(context); } public ClipViewPager(Context context, AttributeSet attrs) { super(context, attrs); } private View preView; private int preIndex; private int preev =0 ; private int tag = -1; @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { preView = viewOfClickOnScreen(ev); if (preView!=null) { tag = (int) preView.getTag(); } preev = (int) ev.getX(); LogUtils.e(TAG, Debug.line(new Exception()) + "hang, NowTag = " + "preev = "+ preev); } if (ev.getAction() == MotionEvent.ACTION_UP) { View view = viewOfClickOnScreen(ev); LogUtils.e(TAG, Debug.line(new Exception()) + "hang, NowTag = " + "ev = "+ ev); if (view != null) { if (preev != 0 ) { LogUtils.e(TAG, Debug.line(new Exception()) + "hang, Curre = " + getCurrentItem() + "num = "+ getChildCount()+"tag: " + tag + "reX "+ preev + "X "+ev.getX()); if ( (preev > (int)ev.getRawX() && getCurrentItem() == getChildCount() - 1 && ((tag == getCurrentItem() - 1) ||tag == -1)) || (preev < ev.getRawX() && getCurrentItem() == 0 && tag == 1) ) { LogUtils.e(TAG, Debug.line(new Exception()) + "hang, NowTag = " + "ev = "+ ev); } else { int index = (int) view.getTag(); if (getCurrentItem() != index && index == preIndex) { setCurrentItem(index); } } } else { int index = (int) view.getTag(); if (getCurrentItem() != index && index == preIndex) { setCurrentItem(index); } } } } return super.dispatchTouchEvent(ev); } /** * @param ev * @return */ private View viewOfClickOnScreen(MotionEvent ev) { int childCount = getChildCount(); float x = ev.getRawX(); float y = ev.getRawY(); // LogUtils.e(TAG, Debug.line(new Exception()) + "hang, count = " + getChildCount()); int[] location = new int[2]; for (int i = 0; i < childCount; i++) { View v = findViewWithTag(i); if (v == null) { return null; } v.getLocationOnScreen(location); int minX = location[0]; int minY = getTop(); int maxX = location[0] + v.getWidth(); int maxY = getBottom(); if ((x > minX && x < maxX) && (y > minY && y < maxY)) { LogUtils.e(TAG, Debug.line(new Exception()) + "hang, Tag = " + v.getTag()); if (ev.getAction() == MotionEvent.ACTION_DOWN) { preIndex = (int) v.getTag(); } return v; } } return null; } // @Override // protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // int height = 0; // // int ww = ScreenUtils.getScreenHeightPx(getContext()); // int hh = ScreenUtils.getScreenWidthPx(getContext()); // int a = ScreenUtils.getDiptoPx(getContext(),ww); // int b = ScreenUtils.getDiptoPx(getContext(),hh); // //// findViewById(R.id.) // //// int wwV = ScreenUtils.getViewHeightPx(this); //// int hhV = ScreenUtils.getViewWidthPx(this); // // for (int i = 0; i < getChildCount(); i++) { // View child = getChildAt(i); // child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); // int h = child.getMeasuredHeight(); //player_img // int w = child.getMeasuredWidth(); // // int c = ScreenUtils.getDiptoPx(getContext(),h); // int d = ScreenUtils.getDiptoPx(getContext(),w); // // if (h > height) // height = h; // } // heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); // // super.onMeasure(widthMeasureSpec, heightMeasureSpec); // } /** * 利用java反射机制,将自定义Scroll和ViewPager结合来调节ViewPager的滑动效果 **/ public void setSpeedScroller(int duration) { try { Field mScroller = null; mScroller = ViewPager.class.getDeclaredField("mScroller"); mScroller.setAccessible(true); SpeedScroller scroller = new SpeedScroller(this.getContext(), new AccelerateInterpolator()); mScroller.set(this, scroller); scroller.setmDuration(duration); } catch (NoSuchFieldException e) { } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } } }
true
91fc02205c285dc199aa0a2ea40f410fe320cd06
Java
beccaree/se325-a1
/src/main/java/nz/ac/auckland/library/domain/Member.java
UTF-8
1,234
2.953125
3
[]
no_license
package nz.ac.auckland.library.domain; import java.util.ArrayList; import java.util.List; 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.OneToMany; import javax.xml.bind.annotation.XmlAttribute; /** * Class represents a person who is a member of the library web service * Child class of Person with extra fields id and current books they hold * @author Rebecca Lee (rlee291) * */ @Entity public class Member extends Person { @Id @GeneratedValue(strategy=GenerationType.AUTO) @XmlAttribute(name="member_id") private long _id; @OneToMany(fetch=FetchType.EAGER) @Column(unique=false) private List<Book> _currentBooks = new ArrayList<Book>(); public Member(long id, String firstname, String lastname) { super(firstname, lastname); _id = id; } protected Member() { super(); } public long getId() { return _id; } public void setId(long id) { _id = id; } public List<Book> getCurrentlyHeldBooks() { return _currentBooks; } public void addToCurrentBooks(Book book) { this._currentBooks.add(book); } }
true
bc57f3eff0721ef2a94b81bc93dd616ae39c5daf
Java
best-lk/netty-code
/netty-server/src/main/java/com/lk/netty/server/packet/req/ReqUserLogout.java
WINDOWS-1252
889
2.1875
2
[]
no_license
package com.lk.netty.server.packet.req; import com.lk.netty.server.io.util.IoSession; import com.lk.netty.server.packet.AbstractPacket; import com.lk.netty.server.packet.PacketType; import com.lk.netty.server.service.UserLoginService; import io.netty.buffer.ByteBuf; /** * ˳¼ * @author likai * 2019412 */ public class ReqUserLogout extends AbstractPacket{ private String userId; @Override public PacketType getPacketType() { return PacketType.ReqUserLogout; } @Override public void execPacket(IoSession session) { UserLoginService.logout(session, this); } @Override public void writeBody(ByteBuf buf) { writeUTF8(buf, userId); } @Override public void readBody(ByteBuf buf) { this.userId = readUTF8(buf); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
true
3c7b8036d82e2937349a461b59c0ad6cba7a567c
Java
LamhotJM/CS-390
/src/objectsclass/lab2/prog1/DeptEmployee.java
UTF-8
810
3.203125
3
[]
no_license
package objectsclass.lab2.prog1; import java.time.LocalDate; public class DeptEmployee { private String name; private double salary; private LocalDate hireDate; public DeptEmployee(String name, double salary, int year, int month, int dayOfMonth) { super(); this.name = name; this.salary = salary; this.hireDate = LocalDate.of(year, month, dayOfMonth);; } public String getName() { return name; } public void setName(String name) { this.name = name; } public LocalDate getHireDate() { return hireDate; } public void setHireDate(LocalDate hireDate) { this.hireDate = hireDate; } public double computeSalary() { return salary; } @Override public String toString() { return "DeptEmployee [name=" + name + ", salary=" + salary + ", hireDate=" + hireDate + "]"; } }
true
fef2bd46ecf8e4d7aa14d5fa9d4cbbf43c0c3b23
Java
ANter-xidian/type-inference
/object-immutability/tests/CFLTests7.java
UTF-8
396
2.46875
2
[ "Apache-2.0" ]
permissive
class DD { String f; } public class CFLTests7 { public static DD dd = new DD(); public static String theString; public static void main(String[] arg) { String s1 = new String("Ana"); String s2 = new String("Antun"); theString = s1; dd.f = s2; m(); n(); } public static void m() { String s3 = theString; } public static void n() { String s4 = dd.f; } }
true
2b488d018a91476542a27ce89206ae5319e9e07d
Java
prakhar2407/SpringCourse
/Dependency_Injection_Final/src/Constructor/Department.java
UTF-8
280
2.90625
3
[]
no_license
package Constructor; public class Department { public String departmentName; public Department(String departmentName) { this.departmentName = departmentName; } @Override public String toString(){ return departmentName; } }
true
0b95330ba4da53083f07172413fb7f174c097af2
Java
SombreLoup/Enseignement
/2017-2018/L2 INFO/CT BPOO 2017-2018/src/boisson/BoissonException.java
UTF-8
212
1.804688
2
[]
no_license
package boisson; public class BoissonException extends Exception { /** * */ private static final long serialVersionUID = -6909012527668890072L; public BoissonException(String msg) { super(msg); } }
true
29d0a39a56b7c12707279b3a141e81d70999a1c1
Java
abeepbeepsheep/exam-clock-2020
/src/test/java/TestEncryption.java
UTF-8
1,656
2.671875
3
[ "Unlicense" ]
permissive
//import com.google.zxing.ChecksumException; //import com.google.zxing.FormatException; //import com.google.zxing.NotFoundException; //import com.google.zxing.WriterException; //import app.nush.examclock.connection.Base64; // //import java.util.Arrays; // //public class TestEncryption { // public static void main(String... args) throws WriterException, NotFoundException, FormatException, ChecksumException { //// BufferedImage bufferedImage = Encryption.generateQRCode(Encryption.createKey(), "123.456.7.89".getBytes()); //// byte[] bytes = Encryption.readQRCode(bufferedImage); //// byte[] receivedKey = Arrays.copyOf(bytes, Encryption.AES_KEY_SIZE / 8); //// byte[] receivedMessage = Arrays.copyOfRange(bytes, Encryption.AES_KEY_SIZE / 8, bytes.length); //// byte[] original = Encryption.decrypt(receivedKey, receivedMessage); //// System.out.println(new String(original)); // // byte[] data = {64, -88, -122, -67, 28, 101, 10, 54, 76, 83, -65, 12, 38, -92, -93, 5, -40, -127, 82, 53, -56, -4, -103, 46, 16, 78, 31, -89, 48, 30, 100, -98, 55, 49, 125, 32, 57, -112, 6, 44, 45, 89, -10, 60, -31, 0}; // char[] encode = Base64.encode(data); // System.out.println("First Test\n\nEncode " + data.length + "=>" + encode.length); // System.out.println(Arrays.toString(data)); // System.out.println(Arrays.toString(encode)); // byte[] decode = Base64.decode(encode); // System.out.println("\nDecode " + encode.length + "=>" + decode.length); // System.out.println(Arrays.toString(encode)); // System.out.println(Arrays.toString(decode)); // } //}
true
0bbea715e27c472081ce01e2c13a9d3d6a2b6d76
Java
blinkawan/Optimistic-Locking-JDBC-Sample
/src/main/java/com/agungsetiawan/optimisticlocking/App.java
UTF-8
1,240
2.4375
2
[]
no_license
package com.agungsetiawan.optimisticlocking; import com.agungsetiawan.optimisticlocking.dao.BukuDao; import com.agungsetiawan.optimisticlocking.entity.Buku; import com.agungsetiawan.optimisticlocking.exception.LockingException; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; import java.sql.SQLException; /** * Hello world! * */ public class App { public static void main( String[] args ) throws SQLException, LockingException { MysqlDataSource dataSource=new MysqlDataSource(); dataSource.setUser("root"); dataSource.setPassword(""); dataSource.setDatabaseName("astral"); dataSource.setServerName("localhost"); BukuDao bukuDao=new BukuDao(); bukuDao.setConnection(dataSource.getConnection()); // Buku buku=new Buku(); // buku.setJudul("Arus Balik"); // buku.setPenulis("Pramoedya Ananta Toer"); Buku bukuSatu=bukuDao.findOne(1); Buku bukuDua=bukuDao.findOne(1); bukuSatu.setPenulis("Pramoedya Ananta T"); bukuDua.setPenulis("Pramoedya AT"); bukuDao.update(bukuSatu); //sukses bukuDao.update(bukuDua); //gagal dataSource.getConnection().close(); } }
true
835a5d0b9e925e985e241dad3ea56801b082523f
Java
krasa/EditorGroups
/src/main/java/krasa/editorGroups/EditorGroupTabTitleProvider.java
UTF-8
2,996
1.976563
2
[ "Apache-2.0" ]
permissive
package krasa.editorGroups; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.impl.EditorTabTitleProvider; import com.intellij.openapi.fileEditor.impl.EditorWindow; import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ui.EDT; import krasa.editorGroups.model.AutoGroup; import krasa.editorGroups.model.EditorGroup; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class EditorGroupTabTitleProvider implements EditorTabTitleProvider { @Nullable @Override public String getEditorTabTitle(@NotNull Project project, @NotNull VirtualFile virtualFile) { String presentableNameForUI = getPresentableNameForUI(project, virtualFile, null, false); if (!EDT.isCurrentThreadEdt()) { return null; } FileEditor textEditor = FileEditorManagerImpl.getInstanceEx(project).getSelectedEditor(virtualFile); return getTitle(project, textEditor, presentableNameForUI); } // /** // * since 2018.2 // * to 2021.3 // */ // @Nullable // @Override // public String getEditorTabTitle(@NotNull Project project, @NotNull VirtualFile file, @Nullable EditorWindow editorWindow) { // String presentableNameForUI = getPresentableNameForUI(project, file, editorWindow, true); // // if (editorWindow != null) { // for (EditorWithProviderComposite editor : editorWindow.getEditors()) { // if (editor.getFile().equals(file)) { // Pair<FileEditor, FileEditorProvider> pair = editor.getSelectedEditorWithProvider(); // FileEditor first = pair.first; // return getTitle(project, first, presentableNameForUI); // } // } // } // // return presentableNameForUI; // } @NotNull public static String getPresentableNameForUI(@NotNull Project project, @NotNull VirtualFile file, EditorWindow editorWindow, boolean newAPI) { List<EditorTabTitleProvider> providers = DumbService.getInstance(project).filterByDumbAwareness( Extensions.getExtensions(EditorTabTitleProvider.EP_NAME)); for (EditorTabTitleProvider provider : providers) { if (provider instanceof EditorGroupTabTitleProvider) { continue; } String result; result = provider.getEditorTabTitle(project, file); if (result != null) { return result; } } return file.getPresentableName(); } private String getTitle(Project project, FileEditor textEditor, String presentableNameForUI) { EditorGroup group = null; if (textEditor != null) { group = textEditor.getUserData(EditorGroupPanel.EDITOR_GROUP); } if (group != null && group.isValid() && !(group instanceof AutoGroup)) { presentableNameForUI = group.getPresentableTitle(project, presentableNameForUI, ApplicationConfiguration.state().isShowSize()); } return presentableNameForUI; } }
true
fcf12b3df8ae95b8d640dcfe555fad8e80c24e38
Java
sanntt/Moviedis
/app/src/main/java/com/example/android/moviedis/Movie.java
UTF-8
600
2.46875
2
[]
no_license
package com.example.android.moviedis; /** * Created by Milhouse on 08/02/2016. */ public class Movie { String id; String title; String posterUri; String releaseDate; String plotSynopsis; String voteAverage; public Movie(String id, String title, String posterUri, String releaseDate, String plotSynopsis, String voteAverage) { this.id = id; this.title = title; this.posterUri = posterUri; this.releaseDate = releaseDate; this.plotSynopsis = plotSynopsis; this.voteAverage = voteAverage; } }
true
aa4adfdbb2950366b908b715667ccb83164b34cd
Java
Yberion/M2-IL
/S1/TAA/tp3/src/main/java/fr/brandon/tp3/part3/domain/kanban/Carte.java
UTF-8
1,079
2.375
2
[ "MIT" ]
permissive
package fr.brandon.tp3.part3.domain.kanban; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class Carte implements Serializable { private static final long serialVersionUID = 4289243947415248657L; private long id; private Section section; private Fiche fiche; public Carte() { super(); } public Carte(Section section, Fiche fiche) { super(); this.section = section; this.fiche = fiche; } @Id @GeneratedValue public long getId() { return id; } public void setId(long id) { this.id = id; } @OneToOne public Section getSection() { return section; } public void setSection(Section section) { this.section = section; } @OneToOne public Fiche getFiche() { return fiche; } public void setFiche(Fiche fiche) { this.fiche = fiche; } }
true