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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
71989393a37736c73d733ff2943ac579c3edbe06 | Java | Kkorrru/Look-Note | /app/src/main/java/com/example/looknote/ListViewAdapter.java | UTF-8 | 2,478 | 2.390625 | 2 | [] | no_license | package com.example.looknote;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ListViewAdapter extends BaseAdapter {
ArrayList<ListViewitem> items = new ArrayList<ListViewitem>();
Context context;
public void addItem(ListViewitem item){
items.add(item);
}
public void delItem(int i){
items.remove(i);
}
@Override
public int getCount(){ //ArrayList의 사이즈 리턴
return items.size();
}
@Override
public Object getItem(int position){ //해당 position에 있는 item을 return
return items.get(position);
}
@Override
public long getItemId(int position){ // position값 return
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
context = parent.getContext();
ListViewitem ListViewitem = items.get(position);
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_recommand, parent, false);
}
TextView textView;
ImageView imageView;
textView = convertView.findViewById(R.id.date_num);
textView.setText(ListViewitem.getDate_num());
imageView = convertView.findViewById(R.id.satisf);
imageView.setImageResource(ListViewitem.getStaisfImage(ListViewitem.getSatisf()));
textView = convertView.findViewById(R.id.top_c);
textView.setText(ListViewitem.getTop_c());
textView = convertView.findViewById(R.id.bottom_c);
textView.setText(ListViewitem.getBottom_c());
textView = convertView.findViewById(R.id.acc_c);
textView.setText(ListViewitem.getAcc());
textView = convertView.findViewById(R.id.diary_c);
textView.setText(ListViewitem.getDiary());
textView = convertView.findViewById(R.id.max_tem);
textView.setText(ListViewitem.getMax_tem());
textView = convertView.findViewById(R.id.min_tem);
textView.setText(ListViewitem.getMin_tem());
textView = convertView.findViewById(R.id.sky);
textView.setText(ListViewitem.getSky());
return convertView;
}
}
| true |
26c71f3f4cc6c203827049bf156a0b8f4843f152 | Java | mcdiae/kludje | /kludje-experimental/src/main/java/uk/kludje/experimental/collect/array/SingletonIterator.java | UTF-8 | 1,121 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2015 McDowell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.kludje.experimental.collect.array;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Created by user on 27/12/15.
*/
final class SingletonIterator<E> implements Iterator<E> {
private final E element;
private boolean served;
public SingletonIterator(E element) {
this.element = element;
}
@Override
public boolean hasNext() {
return !served;
}
@Override
public E next() {
if (served) {
throw new NoSuchElementException();
}
return element;
}
}
| true |
8c00fd77ba6bd77234d8443a44b6eac68fad231c | Java | QiJiYinQiao/workspaces | /oasys/.svn/pristine/28/2884edbf12f75d54e0e8463ddd555d304bedf60c.svn-base | UTF-8 | 8,749 | 1.820313 | 2 | [] | no_license | package com.oasys.model;
// Generated 2015-12-11 13:36:55 by Hibernate Tools 4.0.0
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import org.springframework.format.annotation.DateTimeFormat;
import com.oasys.viewModel.WorkFlowTasksModel;
/**
* TOaAdUseStampApp generated by hbm2java
*/
@Entity
@Table(name = "t_oa_ad_use_stamp_app", catalog = "oasys", uniqueConstraints = @UniqueConstraint(columnNames = "APP_NO"))
public class UseStampApp implements java.io.Serializable, Cloneable {
private Integer usaId;
private String appNo;
private Integer applicantNo;
private Integer appDept;
/** 使用性质 */
private String useNature;
private Date appDate;
private String appStatus;
/** 移交时间 */
private Date turnoverDtime;
/** 用章开始时间 */
private Date useBgDate;
/** 用章结束时间 */
private Date useEdDate;
private String procStatus;
private String remark;
/** 申请人姓名 */
private String applicantName;
/** 申请人部门 */
private String fullName;
/** 印章类型 */
private String stampType;
/** 印章名称 */
private String stampName;
/** 附加表id */
private Integer saaId;
/**印章id*/
private String stampNameId;
/**
* 开始申请时间
*/
private String appDateS;
/**
* //结束时间
*/
private String appDateE;
/** 借款端、财富端 */
private String myId;
/** WorkFlow propertites */
private WorkFlowTasksModel taskModel;// task对象
private String result;// 审批通过或驳回标识
private String taskID;// 任务taskID
private String formKey;// 跳转对应的受理页面JSP配置(在流程图的formKey中设置)
private String assistant;// 指定的候选人
private String isSuccess;// 是否通过标识
private String ideaRemark;// 审批意见
private String definitionKey;// 流程表示key
public UseStampApp() {
}
public UseStampApp(Integer usaId, String appNo, Integer applicantNo,
Integer appDept, String useNature, Date appDate, String appStatus,
Date turnoverDtime, Date useBgDate, Date useEdDate,
String procStatus, String remark, String applicantName,
String fullName, String stampType, String stampName, Integer saaId,
String appDateS, String appDateE, String myId,
WorkFlowTasksModel taskModel, String result, String taskID,
String formKey, String assistant, String isSuccess,
String ideaRemark, String definitionKey,String stampNameId) {
super();
this.usaId = usaId;
this.appNo = appNo;
this.applicantNo = applicantNo;
this.appDept = appDept;
this.useNature = useNature;
this.appDate = appDate;
this.appStatus = appStatus;
this.turnoverDtime = turnoverDtime;
this.useBgDate = useBgDate;
this.useEdDate = useEdDate;
this.procStatus = procStatus;
this.remark = remark;
this.applicantName = applicantName;
this.fullName = fullName;
this.stampType = stampType;
this.stampName = stampName;
this.saaId = saaId;
this.appDateS = appDateS;
this.appDateE = appDateE;
this.myId = myId;
this.taskModel = taskModel;
this.result = result;
this.taskID = taskID;
this.formKey = formKey;
this.assistant = assistant;
this.isSuccess = isSuccess;
this.ideaRemark = ideaRemark;
this.definitionKey = definitionKey;
this.stampNameId=stampNameId;
}
@Transient
public String getStampNameId() {
return stampNameId;
}
public void setStampNameId(String stampNameId) {
this.stampNameId = stampNameId;
}
@Transient
public String getAppDateS() {
return appDateS;
}
public void setAppDateS(String appDateS) {
this.appDateS = appDateS;
}
@Transient
public String getAppDateE() {
return appDateE;
}
public void setAppDateE(String appDateE) {
this.appDateE = appDateE;
}
@Transient
public String getMyId() {
return myId;
}
public void setMyId(String myId) {
this.myId = myId;
}
@Transient
public WorkFlowTasksModel getTaskModel() {
return taskModel;
}
public void setTaskModel(WorkFlowTasksModel taskModel) {
this.taskModel = taskModel;
}
@Transient
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
@Transient
public String getTaskID() {
return taskID;
}
public void setTaskID(String taskID) {
this.taskID = taskID;
}
@Transient
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
@Transient
public String getAssistant() {
return assistant;
}
public void setAssistant(String assistant) {
this.assistant = assistant;
}
@Transient
public String getIsSuccess() {
return isSuccess;
}
public void setIsSuccess(String isSuccess) {
this.isSuccess = isSuccess;
}
@Transient
public String getIdeaRemark() {
return ideaRemark;
}
public void setIdeaRemark(String ideaRemark) {
this.ideaRemark = ideaRemark;
}
@Transient
public String getDefinitionKey() {
return definitionKey;
}
public void setDefinitionKey(String definitionKey) {
this.definitionKey = definitionKey;
}
@Transient
public String getApplicantName() {
return applicantName;
}
public void setApplicantName(String applicantName) {
this.applicantName = applicantName;
}
@Transient
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
@Transient
public String getStampType() {
return stampType;
}
public void setStampType(String stampType) {
this.stampType = stampType;
}
@Transient
public String getStampName() {
return stampName;
}
public void setStampName(String stampName) {
this.stampName = stampName;
}
@Transient
public Integer getSaaId() {
return saaId;
}
public void setSaaId(Integer saaId) {
this.saaId = saaId;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "USA_ID", unique = true, nullable = false)
public Integer getUsaId() {
return this.usaId;
}
public void setUsaId(Integer usaId) {
this.usaId = usaId;
}
@Column(name = "APP_NO", unique = true, length = 25)
public String getAppNo() {
return this.appNo;
}
public void setAppNo(String appNo) {
this.appNo = appNo;
}
@Column(name = "APPLICANT_NO")
public Integer getApplicantNo() {
return this.applicantNo;
}
public void setApplicantNo(Integer applicantNo) {
this.applicantNo = applicantNo;
}
@Column(name = "APP_DEPT")
public Integer getAppDept() {
return this.appDept;
}
public void setAppDept(Integer appDept) {
this.appDept = appDept;
}
@Column(name = "USE_NATURE", length = 1)
public String getUseNature() {
return this.useNature;
}
public void setUseNature(String useNature) {
this.useNature = useNature;
}
@Temporal(TemporalType.DATE)
@Column(name = "APP_DATE", length = 10)
@DateTimeFormat(pattern = "yyyy-MM-dd")
public Date getAppDate() {
return this.appDate;
}
public void setAppDate(Date appDate) {
this.appDate = appDate;
}
@Column(name = "APP_STATUS", length = 100)
public String getAppStatus() {
return this.appStatus;
}
public void setAppStatus(String appStatus) {
this.appStatus = appStatus;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "TURNOVER_DTIME", length = 19)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getTurnoverDtime() {
return this.turnoverDtime;
}
public void setTurnoverDtime(Date turnoverDtime) {
this.turnoverDtime = turnoverDtime;
}
@Temporal(TemporalType.DATE)
@Column(name = "USE_BG_DATE", length = 10)
@DateTimeFormat(pattern = "yyyy-MM-dd")
public Date getUseBgDate() {
return this.useBgDate;
}
public void setUseBgDate(Date useBgDate) {
this.useBgDate = useBgDate;
}
@Temporal(TemporalType.DATE)
@Column(name = "USE_ED_DATE", length = 10)
@DateTimeFormat(pattern = "yyyy-MM-dd")
public Date getUseEdDate() {
return this.useEdDate;
}
public void setUseEdDate(Date useEdDate) {
this.useEdDate = useEdDate;
}
@Column(name = "PROC_STATUS", length = 1)
public String getProcStatus() {
return this.procStatus;
}
public void setProcStatus(String procStatus) {
this.procStatus = procStatus;
}
@Column(name = "REMARK", length = 200)
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
}
| true |
e411060ea7a53a66c1b062f183bfcc34dcfa77f5 | Java | luckysoftgo/datax-sync | /datax-admin/src/main/java/com/application/base/admin/service/impl/DataxPluginServiceImpl.java | UTF-8 | 597 | 1.5625 | 2 | [] | no_license | package com.application.base.admin.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.application.base.admin.entity.DataxPlugin;
import com.application.base.admin.mapper.DataxPluginMapper;
import com.application.base.admin.service.DataxPluginService;
import org.springframework.stereotype.Service;
/**
* datax插件信息表服务实现类
* @author admin
* @since 2019-05-20
* @version v1.0
*/
@Service("dataxPluginService")
public class DataxPluginServiceImpl extends ServiceImpl<DataxPluginMapper, DataxPlugin> implements DataxPluginService {
} | true |
feb2241cd5d13b14e41b5b08b6ec4fd7c19ae9b6 | Java | ThiFeonir/estrutura-de-dados-2 | /src/SIMPLEX/Linha.java | UTF-8 | 1,456 | 3.28125 | 3 | [] | no_license | package SIMPLEX;
import java.util.ArrayList;
/**
* Created by thial on 03/09/2017.
*/
public class Linha {
double menor = 0;
private ArrayList<Double> valores = new ArrayList<>();
public Linha(double[] array){
for (int i = 0; i <array.length ; i++) {
valores.add(array[i]);
}
}
public ArrayList<Double> getValores() {
return valores;
}
public int getMenor(){
int posi = 0;
for (int i = 0; i <valores.size() ; i++) {
if (valores.get(i)<menor) {
menor = valores.get(i);
posi = i;
}
}
menor = 0;
return posi;
}
public void transformarLinha(Linha linha, int posi){
double pivo = valores.get(posi);
for (int i = 0; i < valores.size(); i++) {
double valorLinha = linha.valores.get(i);
double aux = valores.get(i);
valores.set(i,aux - (valorLinha * pivo));
}
}
public void transformarLinha(int posi){
double pivo = valores.get(posi);
for (int i = 0; i < valores.size(); i++) {
valores.set(i,valores.get(i)/ pivo);
}
}
public double getPivo(int posi){
return valores.get(posi);
}
public boolean hasNegative(){
for (double valor:
valores) {
if (valor < 0)
return true;
}
return false;
}
}
| true |
55cae291618377326fa495949b120ba43ca29b3c | Java | balaudt/zi | /src/main/java/zi/jam/y15/qual/CNew.java | UTF-8 | 2,989 | 2.703125 | 3 | [] | no_license | package zi.jam.y15.qual;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Stack;
import org.apache.commons.lang3.text.StrBuilder;
import com.google.common.collect.ImmutableMap;
public class CNew {
public static final String FOLDER_ROOT = "C:/ft/1/";
static byte[][] matrix = new byte[][] { { 1, 2, 3, 4 }, { 2, -1, 4, -3 }, { 3, -4, -1, 2 }, { 4, 3, -2, -1 } };
static ImmutableMap<Character, Byte> map = ImmutableMap.<Character, Byte> builder().put('1', (byte) 1).put('i', (byte) 2)
.put('j', (byte) 3).put('k', (byte) 4).build();
static char[] in;
static Stack<Integer> stack;
static byte[][] resultMatrix;
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(FOLDER_ROOT + "C-small-attempt1.in"));
BufferedWriter writer = new BufferedWriter(new FileWriter(FOLDER_ROOT + "C-small-attempt1.out"));
int t = Integer.parseInt(reader.readLine());
for (int i = 0; i < t; i++) {
StrBuilder builder = new StrBuilder("Case #").append(i + 1).append(": ");
String[] inStr = reader.readLine().split(" ");
int c = Integer.parseInt(inStr[0]);
int n = Integer.parseInt(inStr[1]);
String str = reader.readLine();
in = new char[n * c];
char[] inChars = str.toString().toCharArray();
for (int j = 0; j < n; j++) {
for (int k = 0; k < inChars.length; k++) {
in[j * inChars.length + k] = inChars[k];
}
}
resultMatrix = new byte[n * c][n * c];
for (int j = 0; j < resultMatrix.length; j++) {
resultMatrix[j][j] = map.get(in[j]);
}
for (int j = 1; j < resultMatrix.length; j++) {
for (int k = 0; j + k < resultMatrix.length; k++) {
byte l1 = resultMatrix[k][j + k - 1];
byte l2 = resultMatrix[j + k][j + k];
boolean sign = false;
if (l1 < 0) {
sign = true;
l1 *= -1;
}
if (l2 < 0) {
sign = !sign;
l2 *= -1;
}
resultMatrix[k][j + k] = matrix[l1 - 1][l2 - 1];
if (sign)
resultMatrix[k][j + k] *= -1;
}
}
// for (int j = 0; j < resultMatrix.length; j++) {
// System.out.println(j + "\t" + Arrays.toString(resultMatrix[j]));
// }
boolean isPossible = false;
int j, k = 0;
for (j = 0; j < resultMatrix.length - 2 && !isPossible; j++) {
if (resultMatrix[0][j] != 2)
continue;
for (k = j + 1; k < resultMatrix.length - 1; k++) {
if (resultMatrix[j + 1][k] == 3 && resultMatrix[k + 1][resultMatrix.length - 1] == 4) {
// System.out.println(j + "\t" + k);
isPossible = true;
break;
}
}
}
if (isPossible)
builder.append("YES");
else
builder.append("NO");
builder.append('\n');
String builderStr = builder.toString();
System.out.print(builderStr);
writer.write(builderStr);
}
reader.close();
writer.close();
}
}
| true |
4635b5e253153f061db941cb21847bce83d8df8e | Java | damogui/jbl_app_back | /core/src/main/java/hmap/core/signReceive/service/ISignReceiveService.java | UTF-8 | 477 | 1.609375 | 2 | [] | no_license | package hmap.core.signReceive.service;
import hmap.core.signReceive.dto.SignReceiveDTO;
import net.sf.json.JSONObject;
import java.util.Map;
/**
* @describe:
* @author: guanqun.guo
* @email: guanqun.guo@hand-china.com
* @date: Create in 11:59 2017/6/1
*/
public interface ISignReceiveService {
/**
* @return
* @describe 签到接收通用接口
* @author: guanqun.guo
* @param:
* @Date: 8:57 2017/6/1
*/
JSONObject receive(SignReceiveDTO dto);
}
| true |
78771831b8bac810784f9304b3e56a377d67a8b1 | Java | coffey6/maintain | /src/main/java/online/zhaopei/myproject/sqlprovide/ecssent/GoodSqlProvide.java | UTF-8 | 8,779 | 1.9375 | 2 | [
"MIT"
] | permissive | package online.zhaopei.myproject.sqlprovide.ecssent;
import java.io.Serializable;
import org.apache.ibatis.jdbc.SQL;
import com.alibaba.druid.util.StringUtils;
import online.zhaopei.myproject.domain.ecssent.Good;
public class GoodSqlProvide implements Serializable {
/**
* serialVersionUID
*/
private static final long serialVersionUID = -2734765559004701414L;
public String getGoodListSql(final Good good) {
return new SQL() {{
this.SELECT("*");
StringBuffer goodsSql = new StringBuffer("");
goodsSql.append("select cgh.seq_no");
goodsSql.append(",cgh.cbe_code");
goodsSql.append(",cgh.cbe_name");
goodsSql.append(",cgh.apply_code");
goodsSql.append(",cgh.apply_name");
goodsSql.append(",cgl.list_no");
goodsSql.append(",cgl.goods_no");
goodsSql.append(",cgl.shelf_goods_name");
goodsSql.append(",cgl.describe");
goodsSql.append(",cgl.code_ts");
goodsSql.append(",cgl.goods_name");
goodsSql.append(",cgl.goods_model");
goodsSql.append(",cgl.unit");
goodsSql.append(",cgl.currency");
goodsSql.append(",cgl.unit1");
goodsSql.append(",cgl.unit2");
goodsSql.append(",cgl.price");
goodsSql.append(",cgl.price_rmb");
goodsSql.append(",cgl.tax_code");
goodsSql.append(",cgl.ecp_code");
goodsSql.append(",cgl.ecp_name");
goodsSql.append(",cgl.country");
goodsSql.append(",cgl.image");
goodsSql.append(",cgl.bar_code");
goodsSql.append(",cgl.limitation_goods_code");
goodsSql.append(",cgl.position_seq");
goodsSql.append(",cgl.is_tax");
goodsSql.append(",cgl.is_permit");
goodsSql.append(",cgl.brands");
goodsSql.append(",cgl.supervise_id");
goodsSql.append(",cgl.item_no");
goodsSql.append(",cgl.apply_user");
goodsSql.append(",cgl.status");
goodsSql.append(",cgl.approve_man");
goodsSql.append(",cgl.approve_time");
goodsSql.append(",cgl.approve_opinion");
goodsSql.append(",cgl.dec_time");
goodsSql.append(",cgl.update_time");
goodsSql.append(",cgl.indb_time");
goodsSql.append(",cgl.shelf_goods_name_foreign");
goodsSql.append(",cgl.batch_numbers");
goodsSql.append(",cgl.modify_mark");
goodsSql.append(",cgl.is_simple");
goodsSql.append(" from cur_goods_head cgh inner join cur_goods_list cgl on cgh.seq_no = cgl.seq_no");
goodsSql.append(" where 1 = 1");
if (!StringUtils.isEmpty(good.getCbeCode())) {
goodsSql.append(" and cgh.cbe_code = '" + good.getCbeCode() + "'");
}
if (!StringUtils.isEmpty(good.getCbeName())) {
goodsSql.append(" and cgh.cbe_name like '%" + good.getCbeName() + "%'");
}
if (!StringUtils.isEmpty(good.getApplyCode())) {
goodsSql.append(" and cgh.apply_code = '" + good.getApplyCode() + "'");
}
if (!StringUtils.isEmpty(good.getApplyName())) {
goodsSql.append(" and cgh.apply_name like '%" + good.getApplyName() + "%'");
}
if (!StringUtils.isEmpty(good.getGoodsNo())) {
goodsSql.append(" and cgl.goods_no = '" + good.getGoodsNo() + "'");
}
if (!StringUtils.isEmpty(good.getShelfGoodsName())) {
goodsSql.append(" and cgl.shelf_goods_name like '%" + good.getShelfGoodsName() + "%'");
}
if (!StringUtils.isEmpty(good.getStatus())) {
goodsSql.append(" and cgl.status = '" + good.getStatus() + "'");
}
if (!StringUtils.isEmpty(good.getGoodsNo())) {
goodsSql.append(" and cgl.goods_no = '" + good.getGoodsNo() + "'");
}
if (!StringUtils.isEmpty(good.getBeginDecTime())) {
goodsSql.append(" and to_char(cgl.dec_time, 'yyyy-mm-dd') >= '" + good.getBeginDecTime() + "'");
}
if (!StringUtils.isEmpty(good.getEndDecTime())) {
goodsSql.append(" and to_char(cgl.dec_time, 'yyyy-mm-dd') <= '" + good.getEndDecTime() + "'");
}
if (!StringUtils.isEmpty(good.getDecTimeStr())) {
goodsSql.append(" and to_char(cgl.dec_time, 'yyyy-mm-dd') = '" + good.getDecTimeStr() + "'");
}
if (!StringUtils.isEmpty(good.getItemNo())) {
goodsSql.append(" and cgl.item_no like '" + good.getItemNo() + "%'");
}
if (!StringUtils.isEmpty(good.getGoodsName())) {
goodsSql.append(" and cgl.goods_name like '%" + good.getGoodsName() + "%'");
}
if (!StringUtils.isEmpty(good.getShelfGoodsName())) {
goodsSql.append(" and cgl.shelf_goods_name like '%" + good.getShelfGoodsName() + "%'");
}
if (!StringUtils.isEmpty(good.getCodeTs())) {
goodsSql.append(" and cgl.code_ts like '%" + good.getCodeTs() + "'");
}
if (!StringUtils.isEmpty(good.getTaxCode())) {
goodsSql.append(" and cgl.tax_code like '%" + good.getTaxCode() + "'");
}
goodsSql.append(" union all");
goodsSql.append(" select pgh.seq_no");
goodsSql.append(",pgh.cbe_code");
goodsSql.append(",pgh.cbe_name");
goodsSql.append(",pgh.apply_code");
goodsSql.append(",pgh.apply_name");
goodsSql.append(",pgl.list_no");
goodsSql.append(",pgl.goods_no");
goodsSql.append(",pgl.shelf_goods_name");
goodsSql.append(",pgl.describe");
goodsSql.append(",pgl.code_ts");
goodsSql.append(",pgl.goods_name");
goodsSql.append(",pgl.goods_model");
goodsSql.append(",pgl.unit");
goodsSql.append(",pgl.currency");
goodsSql.append(",pgl.unit1");
goodsSql.append(",pgl.unit2");
goodsSql.append(",pgl.price");
goodsSql.append(",pgl.price_rmb");
goodsSql.append(",pgl.tax_code");
goodsSql.append(",pgl.ecp_code");
goodsSql.append(",pgl.ecp_name");
goodsSql.append(",pgl.country");
goodsSql.append(",pgl.image");
goodsSql.append(",pgl.bar_code");
goodsSql.append(",pgl.limitation_goods_code");
goodsSql.append(",pgl.position_seq");
goodsSql.append(",pgl.is_tax");
goodsSql.append(",pgl.is_permit");
goodsSql.append(",pgl.brands");
goodsSql.append(",pgl.supervise_id");
goodsSql.append(",pgl.item_no");
goodsSql.append(",pgl.apply_user");
goodsSql.append(",pgl.status");
goodsSql.append(",pgl.approve_man");
goodsSql.append(",pgl.approve_time");
goodsSql.append(",pgl.approve_opinion");
goodsSql.append(",pgl.dec_time");
goodsSql.append(",pgl.update_time");
goodsSql.append(",pgl.indb_time");
goodsSql.append(",pgl.shelf_goods_name_foreign");
goodsSql.append(",pgl.batch_numbers");
goodsSql.append(",pgl.modify_mark");
goodsSql.append(",pgl.is_simple");
goodsSql.append(" from pre_goods_head pgh inner join pre_goods_list pgl on pgh.seq_no = pgl.seq_no");
goodsSql.append(" where 1 = 1");
if (!StringUtils.isEmpty(good.getCbeCode())) {
goodsSql.append(" and pgh.cbe_code = '" + good.getCbeCode() + "'");
}
if (!StringUtils.isEmpty(good.getCbeName())) {
goodsSql.append(" and pgh.cbe_name like '%" + good.getCbeName() + "%'");
}
if (!StringUtils.isEmpty(good.getApplyCode())) {
goodsSql.append(" and pgh.apply_code = '" + good.getApplyCode() + "'");
}
if (!StringUtils.isEmpty(good.getApplyName())) {
goodsSql.append(" and pgh.apply_name like '%" + good.getApplyName() + "%'");
}
if (!StringUtils.isEmpty(good.getGoodsNo())) {
goodsSql.append(" and pgl.goods_no = '" + good.getGoodsNo() + "'");
}
if (!StringUtils.isEmpty(good.getShelfGoodsName())) {
goodsSql.append(" and pgl.shelf_goods_name like '%" + good.getShelfGoodsName() + "%'");
}
if (!StringUtils.isEmpty(good.getStatus())) {
goodsSql.append(" and pgl.status = '" + good.getStatus() + "'");
}
if (!StringUtils.isEmpty(good.getGoodsNo())) {
goodsSql.append(" and pgl.goods_no = '" + good.getGoodsNo() + "'");
}
if (!StringUtils.isEmpty(good.getBeginDecTime())) {
goodsSql.append(" and to_char(pgl.dec_time, 'yyyy-mm-dd') >= '" + good.getBeginDecTime() + "'");
}
if (!StringUtils.isEmpty(good.getEndDecTime())) {
goodsSql.append(" and to_char(pgl.dec_time, 'yyyy-mm-dd') <= '" + good.getEndDecTime() + "'");
}
if (!StringUtils.isEmpty(good.getDecTimeStr())) {
goodsSql.append(" and to_char(pgl.dec_time, 'yyyy-mm-dd') = '" + good.getDecTimeStr() + "'");
}
if (!StringUtils.isEmpty(good.getItemNo())) {
goodsSql.append(" and pgl.item_no like '" + good.getItemNo() + "%'");
}
if (!StringUtils.isEmpty(good.getGoodsName())) {
goodsSql.append(" and pgl.goods_name like '%" + good.getGoodsName() + "%'");
}
if (!StringUtils.isEmpty(good.getShelfGoodsName())) {
goodsSql.append(" and pgl.shelf_goods_name like '%" + good.getShelfGoodsName() + "%'");
}
if (!StringUtils.isEmpty(good.getCodeTs())) {
goodsSql.append(" and pgl.code_ts like '%" + good.getCodeTs() + "'");
}
if (!StringUtils.isEmpty(good.getTaxCode())) {
goodsSql.append(" and pgl.tax_code like '%" + good.getTaxCode() + "'");
}
this.FROM("(" + goodsSql.toString() + ")");
}}.toString();
}
}
| true |
a651500327937d2e3e54b8ebe3795b2f515e667d | Java | Naty558/Construccion_De_Software1 | /src/SEMANA06_TEORICO/Ejercicio07.java | UTF-8 | 1,017 | 2.75 | 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 SEMANA06_TEORICO;
import java.util.ArrayList;
import java.util.Iterator;
/**
*
* @author NATY
*/
class persona{
private String name;
private double sueldo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSueldo() {
return sueldo;
}
public void setSueldo(double sueldo) {
this.sueldo = sueldo;
}
}
class padron implements Iterable<persona>{
ArrayList<persona> list= new ArrayList<>();
void add(worker p1){
list.add(p1);
}
@Override
public Iterator iterator(){
return list.iterator();
}
}
class Servicios{
}
public class Ejercicio07 {
public static void main(String[] args){
}
}
| true |
75d9cc978e35bc1415aaa0aab4e9c6176870b1e3 | Java | bremerle3/cse431 | /cse431-spring16-bremer/Labs/4/src/lab8/RefType.java | UTF-8 | 1,672 | 2.875 | 3 | [] | no_license | package lab8;
import java.util.Vector;
import lab7.*;
import java.util.Enumeration;
import java.util.StringTokenizer;
public class RefType extends TypeBridge {
public Vector rname;
public RefType (Vector rname) {
this.rname = rname;
}
public RefType(String s) {
this(encode(s));
}
private static Vector encode(String s) {
Vector ans = new Vector();
Enumeration e = new StringTokenizer(s, ".");
while (e.hasMoreElements()) ans.addElement(e.nextElement());
return ans;
}
public int hashCode() {
int ans = 0;
for (int i=0; i < rname.size(); ++i) {
ans += rname.elementAt(i).hashCode();
}
return(ans);
}
public boolean isPrimitive() { return false; }
public String getTypeString() {
return ("L"+getClassSig()+";");
}
public String getClassSig() {
String mid="";
Enumeration e = rname.elements();
while (e.hasMoreElements()) {
if (mid.length() > 0) mid += "/";
mid += (String)e.nextElement();
}
return(mid);
}
public String getTypeName() { return(rname.toString()); }
public boolean equals(Object ov) {
boolean ans = true;
if (! (ov instanceof RefType)) return(false);
RefType rt = (RefType)ov;
if (this.rname.size() != rt.rname.size()) return(false);
for (int i=0; i < this.rname.size(); ++i) {
if (! this.rname.elementAt(i).equals(rt.rname.elementAt(i)))
return(false);
}
return(ans);
}
}
| true |
28b57e3113dfd22541aee895f4b9dbb5c2dc3649 | Java | LayneMobile/Stash | /library/stash/src/main/java/stash/subscribers/BaseSubscriber.java | UTF-8 | 3,393 | 2.265625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2016 Layne Mobile, LLC
*
* 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 stash.subscribers;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import rx.Subscriber;
import stash.annotations.Keep;
import stash.exceptions.StashBaseException;
import stash.exceptions.StashUnknownException;
public abstract class BaseSubscriber<T> extends NotifyingSubscriber<T> {
private static final AtomicIntegerFieldUpdater<BaseSubscriber> FINISHED_UPDATOR
= AtomicIntegerFieldUpdater.newUpdater(BaseSubscriber.class, "finished");
@Keep private volatile int finished;
private volatile boolean calledSuper;
protected BaseSubscriber() {
super();
}
protected BaseSubscriber(Subscriber<?> op) {
super(op);
}
protected BaseSubscriber(Subscriber<?> subscriber, boolean shareSubscriptions) {
super(subscriber, shareSubscriptions);
}
/**
* Called when there is new data. May be called more than once depending on the observable implementation.
*
* @param t the data
*/
@Override
public abstract void onNext(T t);
/**
* Called when there is an error.
*
* @param e the wrapped exception that occurred
*/
protected abstract void onError(StashBaseException e);
/**
* Called when either {@link #onCompleted()}, {@link #onError(Throwable)} or {@link #onUnsubscribe()} is called.
* Will only be called once. Use this method to dismiss dialogs, etc.
*
* @param complete true if the observable completed, false if unsubscribe() was called before completing
*/
protected void onFinished(boolean complete) {
calledSuper = true;
// allow subclass implementation
}
@Override
public final void onError(Throwable e) {
// handle
try {
onError(cast(e));
} finally {
if (FINISHED_UPDATOR.compareAndSet(this, 0, 1)) {
callFinished(true);
}
}
}
@Override
public final void onCompleted() {
if (FINISHED_UPDATOR.compareAndSet(this, 0, 1)) {
callFinished(true);
}
}
@Override
protected final void onUnsubscribe() {
// Only call finished here if onCompleted or onError has not been called
if (FINISHED_UPDATOR.compareAndSet(this, 0, 1)) {
callFinished(false);
}
}
private void callFinished(boolean completed) {
calledSuper = false;
onFinished(completed);
if (!calledSuper) {
throw new IllegalStateException("must call super in onFinished()");
}
}
private static StashBaseException cast(Throwable e) {
if (e instanceof StashBaseException) {
return (StashBaseException) e;
}
return new StashUnknownException(e);
}
}
| true |
9a8f432e07a9df7d1a7fa1f51b6b4af214413de9 | Java | asamm/lomaps-generator | /osmToolsBasic/src/main/java/com/asamm/osmTools/mapConfig/MapSource.java | UTF-8 | 1,872 | 2.65625 | 3 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.asamm.osmTools.mapConfig;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
*
* @author volda
*/
public class MapSource {
// define xml file
private List<ItemMapPack> mMapPackList;
public MapSource() {
mMapPackList = new ArrayList<>();
}
public boolean hasData() {
return mMapPackList.size() > 0;
}
public void addMapPack(ItemMapPack mapPack) {
mapPack.validate();
this.mMapPackList.add(mapPack);
}
public Iterator<ItemMapPack> getMapPacksIterator() {
return mMapPackList.iterator();
}
public ItemMapPack getMapPackByDir(String dirName){
for (int i = 0, m = mMapPackList.size(); i < m; i++){
ItemMapPack mp = mMapPackList.get(i);
if (mp.getDirGen().contains(dirName) || mp.getDir().contains(dirName)){
return mp;
}
ItemMapPack mpSub = mp.getMapPackByDir(dirName);
if (mpSub != null){
return mpSub;
}
}
return null;
}
/**
* Search in definitions for map specified by it's ID
* @param mapId ID of map we search for
* @return found item
*/
public ItemMap getMapById(String mapId) {
// search for map
for (int i = 0, m = mMapPackList.size(); i < m; i++){
ItemMapPack mp = mMapPackList.get(i);
ItemMap map = mp.getMapById(mapId);
if (map != null) {
return map;
}
}
// throw exception if maps wasn't found
throw new IllegalArgumentException("Map '" + mapId + "', not found");
}
}
| true |
5d89951f788b36a5dfa06576addcb3a8ca2c8b7a | Java | iantal/AndroidPermissions | /apks/malware/app71/source/com/lepeng/fastjson/parser/deserializer/ClassDerializer.java | UTF-8 | 1,032 | 2.203125 | 2 | [
"Apache-2.0"
] | permissive | package com.lepeng.fastjson.parser.deserializer;
import com.lepeng.fastjson.JSONException;
import com.lepeng.fastjson.parser.DefaultJSONParser;
import com.lepeng.fastjson.parser.JSONLexer;
import com.lepeng.fastjson.util.TypeUtils;
import java.lang.reflect.Type;
public class ClassDerializer
implements ObjectDeserializer
{
public static final ClassDerializer instance = new ClassDerializer();
public ClassDerializer() {}
public Object deserialze(DefaultJSONParser paramDefaultJSONParser, Type paramType, Object paramObject)
{
paramDefaultJSONParser = paramDefaultJSONParser.getLexer();
if (paramDefaultJSONParser.token() == 8)
{
paramDefaultJSONParser.nextToken();
return null;
}
if (paramDefaultJSONParser.token() != 4) {
throw new JSONException("expect className");
}
paramType = paramDefaultJSONParser.stringVal();
paramDefaultJSONParser.nextToken(16);
return TypeUtils.loadClass(paramType);
}
public int getFastMatchToken()
{
return 4;
}
}
| true |
2fb6f7715fd705c30389e1a3be954717e9de82d3 | Java | WeTheInternet/xapi | /io/src/main/java/xapi/io/api/StringReader.java | UTF-8 | 2,906 | 2.90625 | 3 | [
"BSD-3-Clause"
] | permissive | package xapi.io.api;
import xapi.collect.fifo.Fifo;
import xapi.collect.fifo.SimpleFifo;
import xapi.log.X_Log;
import xapi.string.X_String;
/**
* An implementation of {@link LineReader} designed to stream lines of text to one or more
* delegate LineReaders. It also stores all input so that a new LineReader can be added
* at any time, and it will still receive all text that was streamed to this reader.
* <p>
* This is handy for such use cases as forwarding an external processes std in and std out,
* where we might need to add a listener to the process after it has already started.
* <p>
* This class has also been enhanced with the {@link #waitToEnd()} method,
* which will block until the line producer (such as a thread streaming input from an external process)
* has signalled that the stream is finished by calling {@link #onEnd()}.
*
* @author "James X. Nelson (james@wetheinter.net)"
*
*/
public class StringReader implements LineReader {
private StringBuilder b;
private final Fifo<LineReader> delegates = new SimpleFifo<LineReader>();
boolean finished;
@Override
public void onStart() {
b = new StringBuilder();
if (delegates.isEmpty())return;
for (LineReader delegate : delegates.forEach()) {
delegate.onStart();
}
}
@Override
public void onLine(String line) {
synchronized (this) {
b.append(line);
if (delegates.isEmpty())return;
for (LineReader delegate : delegates.forEach()) {
delegate.onLine(line);
}
}
}
@Override
public final void onEnd() {
X_Log.trace(StringReader.class,"ending", this);
try {
for (LineReader delegate : delegates.forEach()) {
X_Log.debug(StringReader.class,"ending delegate", delegate.getClass(), delegate);
delegate.onEnd();
}
} finally {
finished = true;
onEnd0();
}
synchronized (delegates) {
delegates.notifyAll();
}
}
protected void onEnd0() {
}
@Override
public String toString() {
return String.valueOf(b);
}
public synchronized void forwardTo(LineReader callback) {
if (callback == null) {
return;
}
X_Log.debug(StringReader.class,getClass().getName(),"forwardingTo", callback.getClass().getName(),":", callback);
if (b != null) {// not null only after we have started streaming
callback.onStart();
for (String line : X_String.splitNewLine(b.toString())) {
callback.onLine(line);
}
}
delegates.give(callback);
if (finished) {
callback.onEnd();
}
}
public void waitToEnd() throws InterruptedException {
if (finished) {
return;
}
synchronized (delegates) {
delegates.wait();
}
}
public void waitToEnd(long timeout, int nanos) throws InterruptedException {
if (finished) {
return;
}
synchronized (delegates) {
delegates.wait(timeout, nanos);
}
}
}
| true |
c8cd7832ce82bd29701e6cd962759e6626c5581a | Java | LilBreivik/ManagingTool | /resources/src/main/java/resources/components/elements/POJO/Schedule/LectureSchedulePOJOalt.java | UTF-8 | 1,080 | 2.1875 | 2 | [] | no_license | package resources.components.elements.POJO.Schedule;
import java.util.List;
import resources.components.elements.POJO.Lecture.Timing.LectureDayTimingsPOJO;
public class LectureSchedulePOJOalt {
private String lectureName;
private String lectureNameShortcut;
private boolean isPractice;
private List<LectureDayTimingsPOJO> timingsForALecture;
public String getLectureNameShortcut() {
return lectureNameShortcut;
}
public void setLectureNameShortcut(String lectureNameShortcut) {
this.lectureNameShortcut = lectureNameShortcut;
}
public String getLectureName() {
return lectureName;
}
public void setLectureName(String lectureName) {
this.lectureName = lectureName;
}
public List<LectureDayTimingsPOJO> getTimingsForALecture() {
return timingsForALecture;
}
public void setTimingsForALecture(List<LectureDayTimingsPOJO> timingsForALecture) {
this.timingsForALecture = timingsForALecture;
}
public boolean isPractice() {
return isPractice;
}
public void setPractice(boolean isPractice) {
this.isPractice = isPractice;
}
}
| true |
e4800882b2628f4c910fe022f6afa846bd8266c6 | Java | welin8154/HA | /src/ntou/hearingaid/sound/Speaker.java | UTF-8 | 5,127 | 2.328125 | 2 | [] | no_license | package ntou.hearingaid.sound;
import java.util.ArrayList;
import ntou.hearingaid.parameter.Parameter;
import ntou.hearingaid.peformance.PerformanceParameter;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;
/*
* 將處理完成聲音進行輸出
*/
public class Speaker extends Thread
{
private int playBufSize;
private AudioTrack audioTrack;
private boolean isPlaying = false;
private ArrayList<short[]> Signals = new ArrayList<short[]>();
private int SampleRate = SoundParameter.frequency;
/*
* 建構函式
* SampleRate - 取樣頻率
*/
public Speaker(int SampleRate)
{
this.SampleRate = SampleRate;
//playBufSize=AudioTrack.getMinBufferSize(SampleRate, SoundParameter.channelConfiguration, SoundParameter.audioEncoding);
playBufSize = AudioTrack.getMinBufferSize(SampleRate, AudioFormat.CHANNEL_CONFIGURATION_STEREO, SoundParameter.audioEncoding);
//STREAM_MUSIC MODE_STREAM
//audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SampleRate, SoundParameter.channelConfiguration, SoundParameter.audioEncoding, playBufSize, AudioTrack.MODE_STREAM);
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SampleRate, AudioFormat.CHANNEL_CONFIGURATION_STEREO, SoundParameter.audioEncoding, playBufSize, AudioTrack.MODE_STREAM);
}
public Speaker()
{
playBufSize = AudioTrack.getMinBufferSize(SampleRate, SoundParameter.channelConfiguration, SoundParameter.audioEncoding);
//STREAM_MUSIC MODE_STREAM
audioTrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL, SampleRate, SoundParameter.channelConfiguration, SoundParameter.audioEncoding, playBufSize, AudioTrack.MODE_STREAM);
//audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SoundParameter.frequency, SoundParameter.channelConfiguration, SoundParameter.audioEncoding, playBufSize, AudioTrack.MODE_STREAM);
}
/*
* 加入新訊號
* data - 欲加入的訊號
*/
public void AddSignals(short[] data)
{
synchronized (Signals)
{
Signals.add(data);
//PerformanceParameter.SpeakerTime.add(System.currentTimeMillis());
}
/*synchronized (PerformanceParameter.SpeakerTime)
{
PerformanceParameter.SpeakerTime.add(System.currentTimeMillis());
}*/
}
//將聲音訊號進行輸出
public void run()
{
PerformanceParameter.SpeakerTime = new ArrayList<Long>();
PerformanceParameter.avg_SpeakerTime = 0;
audioTrack.play();
while(isPlaying)
{
/*
* 讀取最早一筆訊號
*/
short[] buff = null;
yield();
synchronized (Signals)
{
if(Signals.size()==0)
continue;
buff = Signals.get(0);
Signals.remove(0);
}
//Calculatedb(buff);
if(buff.length > 0)
{
//撥放
audioTrack.write(buff, 0, buff.length);
/*synchronized (PerformanceParameter.SpeakerTime)
{
if(PerformanceParameter.SpeakerTime.size()>0)
{
long delaytime = System.currentTimeMillis()-PerformanceParameter.SpeakerTime.get(0);
//Log.d("debug", "Speaker接收到輸出延遲:"+String.valueOf(delaytime));
PerformanceParameter.SpeakerTime.remove(0);
if(PerformanceParameter.avg_SpeakerTime==0)
PerformanceParameter.avg_SpeakerTime = delaytime;
else
PerformanceParameter.avg_SpeakerTime = (PerformanceParameter.avg_SpeakerTime + delaytime)/2;
Log.d("debug", "平均Speaker接收到輸出延遲:"+String.valueOf(PerformanceParameter.avg_SpeakerTime));
}
}*/
/*synchronized (PerformanceParameter.recvTime)
{
if(PerformanceParameter.recvTime.size()>0)
{
long delaytime = System.currentTimeMillis()-PerformanceParameter.recvTime.get(0);
//Log.d("debug", "接收到輸出延遲:"+String.valueOf(delaytime));
PerformanceParameter.recvTime.remove(0);
if(PerformanceParameter.avg_recvTime ==0)
PerformanceParameter.avg_recvTime = delaytime;
else
PerformanceParameter.avg_recvTime = (PerformanceParameter.avg_recvTime + delaytime)/2;
Log.d("debug", "平均接收到輸出延遲:"+String.valueOf(PerformanceParameter.avg_recvTime));
}
}*/
}
}
audioTrack.stop();
Signals.clear();
PerformanceParameter.SpeakerTime.clear();
PerformanceParameter.avg_SpeakerTime = 0;
}
public void open()
{
isPlaying = true;
this.start();
}
public void close()
{
isPlaying = false;
this.interrupt();
//this.stop();
}
/*
* 計算音量
* data - 欲分析資料
* return 音量
*/
private int Calculatedb(short[] data)
{
short min = data[0];
double sum = 0;
for(int i = 0; i < data.length; i++)
{
sum = sum + Math.pow(data[i],2);
}
/*for(int i=0;i<256;i++)
{
sum = sum+Math.pow(data[i],2);
}*/
sum = 10 * Math.log10(sum / data.length);
//Log.d("debug", String.valueOf(SoundParameter.bufferSize));
//Log.d("debug", String.valueOf(sum));
return (int)sum;
}
} | true |
71c626b867a5099a5a226eb027710fe7b53836d4 | Java | ashah23/game-project | /apcs/Driver.java | UTF-8 | 261 | 2.0625 | 2 | [] | no_license | /*Name:
*Date:
*Period:
*Teacher:
*Description:
*/
package apcs;
public class Driver
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("hello dylan");
}
}
| true |
b2b263bb37cfe8414d05c4c750170f5c2b1414eb | Java | vannhan1345/C0220G1-NguyenVanNhan-module2 | /java-web/Case_Study/case_study_furama/src/main/java/com/codegym/model/ContractDetail.java | UTF-8 | 1,344 | 2.484375 | 2 | [] | no_license | package com.codegym.model;
import javax.persistence.*;
@Entity
public class ContractDetail {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String number;
private String amount;
@ManyToOne
private AccompanyingService accompanyingService;
@ManyToOne
private Contract contract;
public Contract getContract() {
return contract;
}
public void setContract(Contract contract) {
this.contract = contract;
}
public AccompanyingService getAccompanyingService() {
return accompanyingService;
}
public void setAccompanyingService(AccompanyingService accompanyingService) {
this.accompanyingService = accompanyingService;
}
public ContractDetail() {
}
public ContractDetail(Long id,String number, String amount) {
this.id = id;
this.number=number;
this.amount = amount;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
| true |
a7156c21db8a3ca554568115f6f8c6c6d2725cd4 | Java | JustRyaan/library_jre8 | /src/CD.java | WINDOWS-1252 | 1,427 | 3 | 3 | [] | no_license | import java.time.Duration;
public class CD extends ElectronicMedia {
private CDType type;
private Integer numTracks;
private String artist;
public CD(String stockID, String title, Double price, String publisher, String runtime, String typeofCase,
CDType type, Integer numTracks, String artist) {
super(stockID, title, price, publisher, runtime, typeofCase);
this.type = type;
this.numTracks = numTracks;
this.artist = artist;
}
// Getter methods
public CDType getCDType() {
return this.type;
}
public Integer getNumTracks() {
return this.numTracks;
}
public String getArtist() {
return this.artist;
}
@Override
// Prints all info about the CD
public String getFullInfo() {
return "===============================================" +
"\n CD #ID: " + this.getStockID() +
"\n===============================================" +
"\nTitle: " + this.getTitle() +
"\nArtist: " + this.getArtist() +
"\nPublisher: " + this.getPublisher() +
"\nTracks: " + this.getNumTracks() +
"\nRuntime: " + this.getRuntime() +
"\nCase type: " + this.getTypeofCase() +
"\nCD type: " + this.getCDType() +
"\nPrice: " + this.getPrice();
}
}
| true |
d666ebb038b69e18bc690f6aab6e13f7f3c0628e | Java | ianujjain/HybridFramework | /HybridFramework/Main/main/Main.java | UTF-8 | 5,560 | 2.140625 | 2 | [] | no_license | package main;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import config.ApplicationMapping;
import filesystem.Directory;
import filesystem.Excel;
import helper.Constants;
import helper.ExtentManager;
import helper.Utility;
import report.Report;
import base.KeyWordBuilder;
public class Main {
ApplicationMapping objAppMap = ApplicationMapping.getInstance();
KeyWordBuilder objKeyWordBuilder = KeyWordBuilder.getInstance();
ExtentReports extent;
ExtentTest test;
WebDriver driver;
HashMap<String, String> objRepo = null;
Utility objUtility = Utility.getInstance();
Directory objDir = Directory.getInstance();
Excel objExcel = Excel.getInstance();
private Logger Log = Logger.getLogger(Main.class.getName());
@BeforeClass
void initializeStaticData() throws Exception {
objUtility.killProcess();
Log.info(objDir.deleteDirectory(new File(Constants.TEMP_FILES)));
extent = ExtentManager.GetExtent();
objExcel.createTestResultExcel();
}
@Test
void Start() throws IOException {
try {
Object[][] ExcelData = null;
int rowCount = 0;
String ScName, ObjectType, ObjectXpathAlias, ObjectValue, Excute, StrValue;
String TcBeginStatus = "";
String suitName[] = Constants.SUIT_TO_RUN.split(Constants.DELIMA_COMMA);
for (int i = 0; i < suitName.length; i++) {
ExcelData = objExcel.getSuit(suitName[i]);
Constants.CURRENT_SUIT = suitName[i];
objExcel.getObjectRepository(suitName[i]);
objExcel.LogReport(suitName[i], "Step Name","Message", "Status");
objExcel.LogReport(suitName[i],"Creating Object Repository For "+suitName[i]," Operation Successful.", "PASS");
rowCount = ExcelData.length;
for (int j = 1; j < rowCount; j++) {
//#######################################################################
//#######################################################################
ScName = (String) ExcelData[j][0]; //#####################
Constants.TEMP_MSG = ScName;
ObjectType = (String) ExcelData[j][1];// Name Of Action #####################
ObjectXpathAlias = (String) ExcelData[j][2];// Locator #####################
ObjectValue = (String) ExcelData[j][3]; // #####################
StrValue = (String) ExcelData[j][4]; //#####################
Excute = (String) ExcelData[j][5]; // #####################
// #######################################################################
// #######################################################################
if (ObjectXpathAlias.equals("TCBEGIN") && Excute.equals("Y")) {
Log.info("TC START: " + ScName + " ,Alias: " + ObjectXpathAlias);
TcBeginStatus = "Y";
objExcel.LogReport(suitName[i], ScName,"TestCase for "+ScName+" Started", ObjectXpathAlias);
Report.extentCreateTest(ScName, "Test case for "+ScName+" Started");
}
if (ObjectXpathAlias.equals("TCEND") && Excute.equals("Y")) {
Log.info("TC TCEND: " + ScName + " ,Alias: " + ObjectXpathAlias);
Constants.IGN_NEXT_EXE_COND = "N";
TcBeginStatus = "Y";
objExcel.LogReport(suitName[i], ScName,"TestCase for "+ScName+" Finished",ObjectXpathAlias);
//test = extent.createTest("TC END: " + ScName);
}
// #####################################################################
if (ObjectType.equals(" ") || Excute.equals(null) || Excute.equals("N"))
{
if (TcBeginStatus.equals("Y"))
{
Log.info("Skip This Row. Excute: N");
}
}
else
{
if (Constants.IGN_NEXT_EXE_COND.equals("Y"))
{
Log.warn("Skipping ScName=" + ScName);
//if (ObjectValue.equals("LOGREPORT"))
//{
//objExcel.LogReport(suitName[i],ScName,"Skipping This Step", "SKIP");
Report.logReort("Skipping This Step" ,Constants.SKIP);
//}
if (ObjectXpathAlias.equals("TCEND"))
{
Log.info("Setting IGNEXECCOND back to N");
Constants.IGN_NEXT_EXE_COND = "N";
objExcel.LogReport(suitName[i], ScName,"TestCase for "+ScName+" Finished", ObjectXpathAlias);
}
}
else
{
if (!ObjectType.equals("") && !ObjectXpathAlias.equals("TCEND") && !ObjectXpathAlias.equals("TCBEGIN")) {
String objLocator = objExcel.getObjectSelector(ObjectXpathAlias);
if (!objLocator.equals(null))
{
if (!ScName.equals(null) && !ScName.equals(""))
{
Log.info("Step# " + ScName + ", Alias# " + ObjectXpathAlias + " Selector# "+ objLocator + " ObjectType# " + ObjectType);
objKeyWordBuilder.Operation(ObjectType, objLocator, ObjectValue, StrValue);
}
}
}
}
}
// #####################################################################
}
}
} catch (Exception e) {
Log.error("Exception: " + e.getMessage());
}
}
@AfterClass
public void tear() {
extent.flush();
// objUtility.killProcess();
}
} | true |
ed8fee6b68b70aeb66c0465fd9340263134565fc | Java | IvanGreen/quiz | /src/main/java/studio/fabrique/quiz/services/QuizQuestionService.java | UTF-8 | 937 | 2.375 | 2 | [] | no_license | package studio.fabrique.quiz.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import studio.fabrique.quiz.entities.Question;
import studio.fabrique.quiz.entities.QuizQuestion;
import studio.fabrique.quiz.repositories.QuizQuestionRepository;
import java.util.ArrayList;
import java.util.List;
//Service for searching questions using quiz
@Service
public class QuizQuestionService {
@Autowired
private QuizQuestionRepository quizQuestionRepository;
public List<Question> getQuestionsByQuizId(Long id){
List<QuizQuestion> allQuizQuestionList = quizQuestionRepository.findAll();
List<Question> questionList = new ArrayList<>();
for (QuizQuestion q : allQuizQuestionList) {
if (q.getQuiz().getId() == id){
questionList.add(q.getQuestion());
}
}
return questionList;
}
}
| true |
8a647fd4f82bdf7e496eb6fed7d5e42eec873802 | Java | songmingjun3/article | /Article/src/bean/Category.java | UTF-8 | 328 | 2.1875 | 2 | [] | no_license | package bean;
import annotation.Column;
import annotation.Table;
@Table(tableName = "t_category")
public class Category {
@Column(field ="category_id",type ="int(2)",defaultNull=false,primaryKey=true)
private Integer categoryId;
@Column(field="category_name",type = "varchar(20)")
private String categoryName;
}
| true |
5691528c3e91d2fec7a3b487a4e90fa8ab2ee922 | Java | hsmnn/M526 | /Theme2/Serie1/ex2/src/main/java/ch/epai/ict/m526/theme2/serie1/Composee.java | UTF-8 | 571 | 3.359375 | 3 | [] | no_license | package ch.epai.ict.m526.theme2.serie1;
public class Composee extends Piece {
private int nombreMax;
Composee(String nom, int nombreMax) {
super(nom);
this.nombreMax = nombreMax;
}
public int tailleMax() {
return this.nombreMax;
}
public int taille() {
return this.composee.size();
}
public void construire(Simple piece){
if (this.composee.size() < nombreMax) {
this.composee.add(piece);
} else {
System.out.println("Construction impossible.");
}
}
} | true |
aee9993da2a22adbc29bd9e23b9dd51c6f21c308 | Java | AlfredLee1991/study | /src/main/java/com/framework/validate/role/MyRoleValidate.java | UTF-8 | 662 | 1.9375 | 2 | [] | no_license | package com.framework.validate.role;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Repository;
import com.framework.validate.annotation.UserRole;
import com.framework.validate.result.ValidateResult;
/**
* 功能描述:添加功能描述.<br/>
*
* #date: 2016年10月11日 上午8:49:50<br/>
* #author 李旭<br/>
* #since 1.0.0<br/>
*/
@Repository
public class MyRoleValidate implements RoleValidateBeanFactory{
@Override
public ValidateResult roleValidate(JoinPoint point, UserRole[] roles) {
return new ValidateResult("roleValidate", "success", "login success", null);
}
}
| true |
822dd2c006c6ca4d6cb1da24291f27f821a18861 | Java | iorproject/IOR | /src/ReceiptBodyRecognition/IReceiptBodyRecognition.java | UTF-8 | 371 | 2.03125 | 2 | [] | no_license | package ReceiptBodyRecognition;
public interface IReceiptBodyRecognition {
// List<ApproveIndicator> getApprovedIdentifiers();
// String getTotalIdentifier();
String getTotalPrice();
boolean recognize(String content);
// void setApproveIndicators(List<ApproveIndicator> approveIndicators);
// void setTotalIndicators(List<String> totalIndicators);
}
| true |
ea3572ffc8ed86bfcbed88a3fe276f2bb71f48d1 | Java | ystory/ehcache-core-2.6.11 | /src/test/java/net/sf/ehcache/distribution/MulticastRMIPeerProviderTest.java | UTF-8 | 7,255 | 2 | 2 | [] | no_license | /**
* Copyright 2003-2007 Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.ehcache.distribution;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeThat;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.util.RetryAssert;
import org.hamcrest.collection.IsEmptyCollection;
import org.hamcrest.core.IsSame;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static net.sf.ehcache.distribution.AbstractRMITest.createRMICacheManagerConfiguration;
/**
* Multicast tests. These require special machine configuration.
* <p/>
* Running on a single machine, as these tests do, you need to add a route command so that two multiCast sockets
* can be added at the same time.
* <ol>
* <li>Mac OSX: <code>route add -net 224.0.0.0 -interface lo0</code>
* <li>Linux (from JGroups doco, untested): <code>route add -net 224.0.0.0 netmask 224.0.0.0 dev lo</code>
* </ol>
*
* @author Greg Luck
* @version $Id$
*/
public class MulticastRMIPeerProviderTest extends AbstractRMITest {
/**
* Cache Manager 1
*/
protected CacheManager manager1;
/**
* Cache Manager 2
*/
protected CacheManager manager2;
/**
* Cache Manager 3
*/
protected CacheManager manager3;
/**
* {@inheritDoc}
*/
@Before
public void setUp() throws Exception {
List<Configuration> configurations = new ArrayList<Configuration>();
configurations.add(createRMICacheManagerConfiguration()
.defaultCache(createAsynchronousCache())
.cache(createAsynchronousCache().name("asynchronousCache"))
.name("MulticastRMIPeerProviderTest-1"));
configurations.add(createRMICacheManagerConfiguration()
.defaultCache(createAsynchronousCache())
.cache(createAsynchronousCache().name("asynchronousCache"))
.name("MulticastRMIPeerProviderTest-2"));
configurations.add(createRMICacheManagerConfiguration()
.defaultCache(createAsynchronousCache())
.cache(createAsynchronousCache().name("asynchronousCache"))
.name("MulticastRMIPeerProviderTest-3"));
List<CacheManager> managers = startupManagers(configurations);
manager1 = managers.get(0);
manager2 = managers.get(1);
manager3 = managers.get(2);
//wait for cluster to establish
waitForClusterMembership(10, TimeUnit.SECONDS, manager1, manager2, manager3);
}
/**
* {@inheritDoc}
*/
@After
public void tearDown() throws Exception {
if (manager1 != null) {
manager1.shutdown();
}
if (manager2 != null) {
manager2.shutdown();
}
if (manager3 != null) {
manager3.shutdown();
}
RetryAssert.assertBy(30, TimeUnit.SECONDS, new Callable<Set<Thread>>() {
public Set<Thread> call() throws Exception {
return getActiveReplicationThreads();
}
}, IsEmptyCollection.<Thread>empty());
}
/**
* Make sure no exceptions get logged. Manual inspection.
*/
@Test
public void testSolePeer() throws Exception {
tearDown();
manager1 = new CacheManager(createRMICacheManagerConfiguration()
.cache(new CacheConfiguration().maxEntriesLocalHeap(0).name("non-replicating"))
.name("MulticastRMIPeerProviderTest-4"));
}
/**
* test remote cache peers
*/
@Test
public void testProviderFromCacheManager() throws InterruptedException {
MulticastKeepaliveHeartbeatSender.setHeartBeatStaleTime(3000);
Ehcache m1sampleCache1 = manager1.getCache("asynchronousCache");
Ehcache m2sampleCache1 = manager2.getCache("asynchronousCache");
Ehcache m3sampleCache1 = manager3.getCache("asynchronousCache");
assertThat(m1sampleCache1.getGuid(), not(is(m2sampleCache1.getGuid())));
assertThat(m1sampleCache1.getGuid(), not(is(m3sampleCache1.getGuid())));
//Now remove a node, wait for the cluster to self-heal and then test
manager1.shutdown();
waitForClusterMembership(10, TimeUnit.SECONDS, manager2, manager3);
}
/**
* The default caches for ehcache-dsitributed1-6.xml are set to replicate.
* We create a new cache from the default and expect it to be replicated.
*/
@Test
public void testProviderCreatedFromDefaultCache() throws InterruptedException {
//manual does not nor should it work this way
assumeThat(getClass(), IsSame.<Class<?>>sameInstance(MulticastRMIPeerProviderTest.class));
manager1.addCache("fromDefaultCache");
manager2.addCache("fromDefaultCache");
manager3.addCache("fromDefaultCache");
waitForClusterMembership(10, TimeUnit.SECONDS, manager1, manager2, manager3);
}
@Test
public void testDeleteReplicatedCache() throws InterruptedException {
//manual does not nor should it work this way
assumeThat(getClass(), IsSame.<Class<?>>sameInstance(MulticastRMIPeerProviderTest.class));
MulticastKeepaliveHeartbeatSender.setHeartBeatStaleTime(3000);
manager1.addCache("fromDefaultCache");
manager2.addCache("fromDefaultCache");
manager3.addCache("fromDefaultCache");
waitForClusterMembership(10, TimeUnit.SECONDS, manager1, manager2, manager3);
manager1.removeCache("fromDefaultCache");
waitForClusterMembership(10, TimeUnit.SECONDS, manager2, manager3);
}
/**
* Determines that the multicast TTL default is 1, which means that packets are restricted to the same subnet.
* peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446, multicastPacketTimeToLive=255
*/
@Test
public void testMulticastTTL() throws IOException {
InetAddress groupAddress = InetAddress.getByName("230.0.0.1");
MulticastSocket socket = new MulticastSocket();
socket.joinGroup(groupAddress);
try {
assertThat(socket.getTimeToLive(), is(1));
} finally {
socket.leaveGroup(groupAddress);
}
}
}
| true |
ad99706097eb99d76be58bab3e6cc1d9375b0de6 | Java | MounikaChava304/CS680 | /hw03/test/src/edu/umb/cs680/hw03/StudentTest.java | UTF-8 | 2,318 | 2.859375 | 3 | [] | no_license | package edu.umb.cs680.hw03;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test;
public class StudentTest {
@Test
public void InStateStudentStatusisINSTATE() {
Student intl = Student.createinStateStudent("Marc", "Boston");
assertEquals(StudentStatus.INSTATE, intl.getStatus());
}
@Test
public void OutStateStudentStatusisOUTSTATE() {
Student intl = Student.createOutStateStudent("Marc", "Boston", 5);
assertEquals(StudentStatus.OUTSTATE, intl.getStatus());
}
@Test
public void IntlStudentSTATUSisINTL() {
Student intl = Student.createIntlStudent("Marc", "Boston", 120, "Europe");
assertEquals(StudentStatus.INTL, intl.getStatus());
}
@Test
public void IntlStudentTUITIONis15000() {
Student intl = Student.createIntlStudent("Marc", "Boston", 120, "Europe");
assertEquals(15000, intl.getTuition());
}
@Test
public void OutStateStudentTUITIONis10000() {
Student intl = Student.createOutStateStudent("Marc", "Boston", 5);
assertEquals(10000, intl.getTuition());
}
@Test
public void InStateStudentTUITIONis7000() {
Student intl = Student.createinStateStudent("Marc", "Boston");
assertEquals(7000, intl.getTuition());
}
@Test
public void InStateStudentTUITIONisNot10000() {
Student intl = Student.createinStateStudent("Marc", "Boston");
assertNotEquals(10000, intl.getTuition());
}
@Test
public void InStateStudentTUITIONisNot15000() {
Student intl = Student.createinStateStudent("Marc", "Boston");
assertNotEquals(15000, intl.getTuition());
}
@Test
public void OutStateStudentTUITIONisNot15000() {
Student intl = Student.createOutStateStudent("Marc", "Boston", 5);
assertNotEquals(15000, intl.getTuition());
}
@Test
public void OutStateStudentTUITIONisNot7000() {
Student intl = Student.createOutStateStudent("Marc", "Boston", 5);
assertNotEquals(7000, intl.getTuition());
}
@Test
public void IntlStudentTUITIONisNot7000() {
Student intl = Student.createIntlStudent("Marc", "Boston", 120, "Europe");
assertNotEquals(7000, intl.getTuition());
}
@Test
public void IntlStudentTUITIONisNot10000() {
Student intl = Student.createIntlStudent("Marc", "Boston", 120, "Europe");
assertNotEquals(10000, intl.getTuition());
}
}
| true |
6866f3b2e1916c45dd3ddf70aa01000acacc457c | Java | wppfiyy/myapplication | /src/main/java/com/example/myapplication/contract/MyContract.java | UTF-8 | 581 | 1.882813 | 2 | [] | no_license | package com.example.myapplication.contract;
import com.example.myapplication.Ben.BannerBen;
import com.example.myapplication.base.BaseModel;
import com.example.myapplication.base.BaseView;
import com.example.myapplication.net.CallBackInterface;
public class MyContract {
public interface IMainView extends BaseView {
void onInit(BannerBen bannerBen);
}
public interface IMainPresenter{
void fun();
}
public interface IMainModel extends BaseModel {
<T>void getLogin(String newlist, CallBackInterface<T> callBackInterface);
}
}
| true |
027b8c500654ca79780ce99337c6864aa0706aaa | Java | yuf1011/jfs | /src/jfs/authentication/ntlm/message/NtlmMessageTypeValues.java | UTF-8 | 250 | 2.078125 | 2 | [] | no_license | package jfs.authentication.ntlm.message;
public class NtlmMessageTypeValues {
public static final int NtLmNegotiate = 0x00000001;
public static final int NtLmChallenge = 0x00000002;
public static final int NtLmAuthenticate = 0x00000003;
}
| true |
3532891be3fde01860f48c96dafd16832333d018 | Java | mominirfan1990/GitJavaWorkplace | /Demos/loopassignment/src/whileloop.java | UTF-8 | 3,118 | 3.65625 | 4 | [] | no_license | /*
public class whileloop
{
public static void main(String[] args)
{
int i=1;
while(i<10)
{
System.out.println("Hello");
i++; // i=i+1; // i+=1;
}
}
}
*/
/*
public class whileloop
{
public static void main(String[] args)
{
int i=110;
while(i>=106)
{
System.out.println("Hello" + i);
i--;
}
}
}
public class whileloop
{
public static void main(String[] args)
{
int i=10;
while(i>=0)
{
System.out.println(i);
i--;
}
}
}
*/
/*
import java.util.Scanner;
public class whileloop
{
public static void main(String[] args)
{
int i=1,n;
Scanner sc;
sc=new Scanner(System.in); //no=newScanner(Syetem.in).nextInt();
System.out.println("Please eneter Number");
n=sc.nextInt();
while(i<=10) //IMP dont put ; after while it will terminate while loop
{
System.out.println(n*i);
i++;
// or used System.out.println(i++*n);
}
}
}
public class whileloop
{
public static void main(String[] args)
{
int i=1,sum=0;
while(i<=10)
{
sum=sum+i;
i++;
}
System.out.println(sum);
}
}
*/
/*
// 1st 50 no divisible by 3
public class whileloop
{
public static void main(String[] args)
{
int i=1,no=50;
while(i<=50)
{
if(i%3==0)
{
System.out.println(i);
}
i++;
}
}
}
//factorial
import java.util.Scanner;
public class whileloop
{
public static void main(String[] args)
{
int i=1,no;
Scanner sc=new Scanner(System.in);
System.out.println("Please eneter Number");
no=sc.nextInt();
while(i<=no)
{
if(no%i ==0)
{
System.out.println(i);
}
i++;
}
}
}
*/
/*
// prime no
import java.util.Scanner;
public class whileloop
{
public static void main(String[] args)
{
boolean flag=false;
int i=2,no;
Scanner sc=new Scanner(System.in);
System.out.println("Please eneter Number");
no=sc.nextInt();
while(i<=no/2)
{
if(no%i ==0)
{
flag =true;
break;
}
i++;
}
if(flag == false)
{
System.out.println("Given No is prime");
}
else
{
System.out.println("Given no is not prime");
}
}
}
*/
/*
//Reverse the given no and find total digit of given no.
import java.util.Scanner;
public class whileloop
{
public static void main(String[] args)
{
int no, rem,sum=0;
Scanner sc=new Scanner(System.in);
System.out.println("Please eneter Number");
no=sc.nextInt();
while (no>0)
{
sum=sum+1;
rem=no%10;
System.out.print(rem); // println show o/p at new line
no=no/10;
} System.out.println(" ");
System.out.println(sum);
}
}
*/
// addition of enetered digit
import java.util.Scanner;
public class whileloop
{
public static void main(String[] args)
{
int no, sum, rem,totaldigit=0;
Scanner sc=new Scanner(System.in);
System.out.println("Please eneter no");
no = sc.nextInt();
while (no>0)
{
rem=no%10;
System.out.print(rem);
//no=no/10;
totaldigit=totaldigit+rem;
}
System.out.println(" ");
System.out.println(totaldigit);
}
} | true |
64ae1cbcedc90cd50482838e11762b98c1bf2106 | Java | Shivani69/SeleniumTrainingSession | /src/com/test/utility/TestUtil.java | UTF-8 | 1,301 | 2.640625 | 3 | [] | no_license | package com.test.utility;
import java.util.ArrayList;
import com.excel.utility.Xls_Reader;
public class TestUtil {
static Xls_Reader reader;
public static <reader> ArrayList<Object[]> getDataFromExcel() {
ArrayList<Object[]> myData = new ArrayList<Object[]>();
try {
reader = new Xls_Reader("C:/tools/projects/workspace/JavaTraining/SeleniumTrainingSession/src/com/testdata/HalfEbayTestData.xlsx");
}catch(Exception e) {
e.printStackTrace();
}
for (int rowNum =2; rowNum<= reader.getRowCount("RegTestData");rowNum++) {
String firstName = reader.getCellData("RegTestData","firstname",rowNum);
String lastName = reader.getCellData("RegTestData","lastname",rowNum);
String address1= reader.getCellData("RegTestData","address1",rowNum);
String address2= reader.getCellData("RegTestData","address2",rowNum);
String city= reader.getCellData("RegTestData","city",rowNum);
String state= reader.getCellData("RegTestData","state",rowNum);
String zipCode= reader.getCellData("RegTestData","zipcode",rowNum);
String emailAddress= reader.getCellData("RegTestData","emailaddress",rowNum);
Object ob[]= {firstName,lastName,address1,address2,city, state,zipCode,emailAddress,};
myData.add(ob);
}
return myData;
}
}
| true |
c3321cd7977147619b1f595a6c8f11d1a4a0be1a | Java | notCnectd/practice-java-leetcode | /src/com/bsdl/medium/_0430/Flatten_a_Multilevel_Doubly_Linked_List.java | UTF-8 | 1,347 | 3.609375 | 4 | [] | no_license | package com.bsdl.medium._0430;
import java.util.Stack;
/*
// Definition for a Node.
class Node {
public int val;
public Node prev;
public Node next;
public Node child;
};
*/
class Node {
public int val;
public Node prev;
public Node next;
public Node child;
}
class Flatten_a_Multilevel_Doubly_Linked_List {
public Node flatten(Node head) {
Stack<Node> stack = new Stack<>();
if (head != null) {
if (head.next != null) {
stack.push(head.next);
}
if (head.child != null) {
stack.push(head.child);
}
}else {
return null;
}
Node hNode = new Node();
hNode.val = head.val;
hNode.prev = null;
hNode.child = null;
Node newNode = hNode;
while (!stack.isEmpty()) {
Node node = new Node();
Node tmpNode = stack.pop();
newNode.next = node;
node.prev = newNode;
node.val = tmpNode.val;
node.child = null;
newNode = newNode.next;
if (tmpNode.next != null) {
stack.push(tmpNode.next);
}
if (tmpNode.child != null) {
stack.push(tmpNode.child);
}
}
return hNode;
}
} | true |
6a92666ff401042d8e0499ca2b6bc55a08a1cbb6 | Java | dsivaraman/userInfo | /src/main/java/com/siva/standup/userInfo/model/AccountProfile.java | UTF-8 | 1,889 | 2.328125 | 2 | [] | no_license | package com.siva.standup.userInfo.model;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "AccountProfile")
public class AccountProfile implements Serializable {
private long id;
private String name;
private String userName;
private String password;
private String country;
public AccountProfile() { }
public AccountProfile(String name, String userName, String password, String country) {
this.name = name;
this.userName = userName;
this.password = password;
this.country = country;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "userName", nullable = false, unique = true)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "country", nullable = false)
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "AccountProfile{" +
"id=" + id +
", name='" + name + '\'' +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", country='" + country + '\'' +
'}';
}
}
| true |
8caa2af1615ace7cb526979dd4191ec4cfacc4bf | Java | bdjss/dubbo-server | /src/main/java/org/david/dubbo/service/impl/HelloServiceImpl.java | UTF-8 | 410 | 2.3125 | 2 | [] | no_license |
package org.david.dubbo.service.impl;
import org.david.dubbo.service.HelloService;
/**
* @author david
* @date 2015.2.10
*/
public class HelloServiceImpl implements HelloService {
/**
* 暴露的接口
*
* @param name
* @return
*/
@Override
public String sayHello(String name) {
System.out.println("call sayHello");
return "Hello " + name;
}
}
| true |
54ec07d44c137e20dc6656473fbd5661cff90a70 | Java | tiwari-gaurav/FlipImage | /app/src/main/java/com/flipimage/response/Photo.java | UTF-8 | 11,827 | 1.835938 | 2 | [] | no_license |
package com.flipimage.response;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Photo implements Parcelable
{
@SerializedName("id")
@Expose
private String id;
@SerializedName("secret")
@Expose
private String secret;
@SerializedName("server")
@Expose
private String server;
@SerializedName("farm")
@Expose
private Integer farm;
@SerializedName("dateuploaded")
@Expose
private String dateuploaded;
@SerializedName("isfavorite")
@Expose
private Integer isfavorite;
@SerializedName("license")
@Expose
private String license;
@SerializedName("safety_level")
@Expose
private String safetyLevel;
@SerializedName("rotation")
@Expose
private Integer rotation;
@SerializedName("originalsecret")
@Expose
private String originalsecret;
@SerializedName("originalformat")
@Expose
private String originalformat;
@SerializedName("owner")
@Expose
private Owner owner;
@SerializedName("title")
@Expose
private Title title;
@SerializedName("description")
@Expose
private Description description;
@SerializedName("visibility")
@Expose
private Visibility visibility;
@SerializedName("dates")
@Expose
private Dates dates;
@SerializedName("views")
@Expose
private String views;
@SerializedName("editability")
@Expose
private Editability editability;
@SerializedName("publiceditability")
@Expose
private Publiceditability publiceditability;
@SerializedName("usage")
@Expose
private Usage usage;
@SerializedName("comments")
@Expose
private Comments comments;
@SerializedName("notes")
@Expose
private Notes notes;
@SerializedName("people")
@Expose
private People people;
@SerializedName("tags")
@Expose
private Tags tags;
@SerializedName("urls")
@Expose
private Urls urls;
@SerializedName("media")
@Expose
private String media;
public final static Creator<Photo> CREATOR = new Creator<Photo>() {
@SuppressWarnings({
"unchecked"
})
public Photo createFromParcel(Parcel in) {
return new Photo(in);
}
public Photo[] newArray(int size) {
return (new Photo[size]);
}
}
;
protected Photo(Parcel in) {
this.id = ((String) in.readValue((String.class.getClassLoader())));
this.secret = ((String) in.readValue((String.class.getClassLoader())));
this.server = ((String) in.readValue((String.class.getClassLoader())));
this.farm = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.dateuploaded = ((String) in.readValue((String.class.getClassLoader())));
this.isfavorite = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.license = ((String) in.readValue((String.class.getClassLoader())));
this.safetyLevel = ((String) in.readValue((String.class.getClassLoader())));
this.rotation = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.originalsecret = ((String) in.readValue((String.class.getClassLoader())));
this.originalformat = ((String) in.readValue((String.class.getClassLoader())));
this.owner = ((Owner) in.readValue((Owner.class.getClassLoader())));
this.title = ((Title) in.readValue((Title.class.getClassLoader())));
this.description = ((Description) in.readValue((Description.class.getClassLoader())));
this.visibility = ((Visibility) in.readValue((Visibility.class.getClassLoader())));
this.dates = ((Dates) in.readValue((Dates.class.getClassLoader())));
this.views = ((String) in.readValue((String.class.getClassLoader())));
this.editability = ((Editability) in.readValue((Editability.class.getClassLoader())));
this.publiceditability = ((Publiceditability) in.readValue((Publiceditability.class.getClassLoader())));
this.usage = ((Usage) in.readValue((Usage.class.getClassLoader())));
this.comments = ((Comments) in.readValue((Comments.class.getClassLoader())));
this.notes = ((Notes) in.readValue((Notes.class.getClassLoader())));
this.people = ((People) in.readValue((People.class.getClassLoader())));
this.tags = ((Tags) in.readValue((Tags.class.getClassLoader())));
this.urls = ((Urls) in.readValue((Urls.class.getClassLoader())));
this.media = ((String) in.readValue((String.class.getClassLoader())));
}
/**
* No args constructor for use in serialization
*
*/
public Photo() {
}
/**
*
* @param tags
* @param visibility
* @param urls
* @param editability
* @param originalformat
* @param people
* @param dateuploaded
* @param isfavorite
* @param publiceditability
* @param id
* @param farm
* @param title
* @param originalsecret
* @param dates
* @param views
* @param description
* @param rotation
* @param owner
* @param usage
* @param secret
* @param server
* @param safetyLevel
* @param notes
* @param license
* @param media
* @param comments
*/
public Photo(String id, String secret, String server, Integer farm, String dateuploaded, Integer isfavorite, String license, String safetyLevel, Integer rotation, String originalsecret, String originalformat, Owner owner, Title title, Description description, Visibility visibility, Dates dates, String views, Editability editability, Publiceditability publiceditability, Usage usage, Comments comments, Notes notes, People people, Tags tags, Urls urls, String media) {
super();
this.id = id;
this.secret = secret;
this.server = server;
this.farm = farm;
this.dateuploaded = dateuploaded;
this.isfavorite = isfavorite;
this.license = license;
this.safetyLevel = safetyLevel;
this.rotation = rotation;
this.originalsecret = originalsecret;
this.originalformat = originalformat;
this.owner = owner;
this.title = title;
this.description = description;
this.visibility = visibility;
this.dates = dates;
this.views = views;
this.editability = editability;
this.publiceditability = publiceditability;
this.usage = usage;
this.comments = comments;
this.notes = notes;
this.people = people;
this.tags = tags;
this.urls = urls;
this.media = media;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public Integer getFarm() {
return farm;
}
public void setFarm(Integer farm) {
this.farm = farm;
}
public String getDateuploaded() {
return dateuploaded;
}
public void setDateuploaded(String dateuploaded) {
this.dateuploaded = dateuploaded;
}
public Integer getIsfavorite() {
return isfavorite;
}
public void setIsfavorite(Integer isfavorite) {
this.isfavorite = isfavorite;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getSafetyLevel() {
return safetyLevel;
}
public void setSafetyLevel(String safetyLevel) {
this.safetyLevel = safetyLevel;
}
public Integer getRotation() {
return rotation;
}
public void setRotation(Integer rotation) {
this.rotation = rotation;
}
public String getOriginalsecret() {
return originalsecret;
}
public void setOriginalsecret(String originalsecret) {
this.originalsecret = originalsecret;
}
public String getOriginalformat() {
return originalformat;
}
public void setOriginalformat(String originalformat) {
this.originalformat = originalformat;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public Title getTitle() {
return title;
}
public void setTitle(Title title) {
this.title = title;
}
public Description getDescription() {
return description;
}
public void setDescription(Description description) {
this.description = description;
}
public Visibility getVisibility() {
return visibility;
}
public void setVisibility(Visibility visibility) {
this.visibility = visibility;
}
public Dates getDates() {
return dates;
}
public void setDates(Dates dates) {
this.dates = dates;
}
public String getViews() {
return views;
}
public void setViews(String views) {
this.views = views;
}
public Editability getEditability() {
return editability;
}
public void setEditability(Editability editability) {
this.editability = editability;
}
public Publiceditability getPubliceditability() {
return publiceditability;
}
public void setPubliceditability(Publiceditability publiceditability) {
this.publiceditability = publiceditability;
}
public Usage getUsage() {
return usage;
}
public void setUsage(Usage usage) {
this.usage = usage;
}
public Comments getComments() {
return comments;
}
public void setComments(Comments comments) {
this.comments = comments;
}
public Notes getNotes() {
return notes;
}
public void setNotes(Notes notes) {
this.notes = notes;
}
public People getPeople() {
return people;
}
public void setPeople(People people) {
this.people = people;
}
public Tags getTags() {
return tags;
}
public void setTags(Tags tags) {
this.tags = tags;
}
public Urls getUrls() {
return urls;
}
public void setUrls(Urls urls) {
this.urls = urls;
}
public String getMedia() {
return media;
}
public void setMedia(String media) {
this.media = media;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(id);
dest.writeValue(secret);
dest.writeValue(server);
dest.writeValue(farm);
dest.writeValue(dateuploaded);
dest.writeValue(isfavorite);
dest.writeValue(license);
dest.writeValue(safetyLevel);
dest.writeValue(rotation);
dest.writeValue(originalsecret);
dest.writeValue(originalformat);
dest.writeValue(owner);
dest.writeValue(title);
dest.writeValue(description);
dest.writeValue(visibility);
dest.writeValue(dates);
dest.writeValue(views);
dest.writeValue(editability);
dest.writeValue(publiceditability);
dest.writeValue(usage);
dest.writeValue(comments);
dest.writeValue(notes);
dest.writeValue(people);
dest.writeValue(tags);
dest.writeValue(urls);
dest.writeValue(media);
}
public int describeContents() {
return 0;
}
}
| true |
dcda69928693625720245ac23c0b65fa7247fae1 | Java | yugi0922/Laboratory | /java_gold/src/java_gold/chapter5/Sample5_18_6.java | UTF-8 | 302 | 2.859375 | 3 | [] | no_license | package java_gold.chapter5;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Sample5_18_6 {
public static void main(String[] args) {
//6 IntStream -> Stream<Integer>
IntStream stream6o = IntStream.of(1, 2, 3);
Stream<Integer> stream6n = stream6o.boxed();
}
}
| true |
942d8e2e5cdf941a7ed4403c1592f19d5564e661 | Java | escapin/givenClauseLoop | /src/givenClauseLoop/core/Unifier.java | UTF-8 | 8,662 | 3.40625 | 3 | [] | no_license | package givenClauseLoop.core;
import java.util.*;
import givenClauseLoop.bean.*;
/**
* @author Enrico Scapin
*
*/
public class Unifier {
/**
* Returns a Map<Variable, Term> representing the most general unifier, MGU (i.e.
* a set of variable/term pairs) or null which is used to indicate a failure to
* find MGU.
*
* @param arg1 the terms' list of the first predicate
* @param arg2 the terms' list of the second predicate
* @return a Map<Variable, Term> representing the substitution (i.e. a set
* of variable/term pairs) or null which is used to indicate a
* failure to find MGU.
*/
public static Map<Variable, Term> findMGU(List<Term> arg1, List<Term> arg2){
Map<Variable, Term> sigma = new HashMap<Variable, Term>();
sigma = unify(arg1, arg2, sigma);
return cascadeSubstitution(sigma);
}
/**
* After you have been created the substitution sigma, you need to "cascade"
* this substitution because there should be instances of variables (that are members
* of sigma's domain) that are also in the codomain's terms. In this case you have to
* replace all the occurences of these variables with the corresponding term presents
* in the substitution.
*
* @param sigma the substitution that must be "cascaded"
* @return the cascaded substitution
*/
private static Map<Variable, Term> cascadeSubstitution(Map<Variable, Term> sigma){
if(sigma==null)
return null;
Term tNew;
for(Variable v1: sigma.keySet())
for(Variable v2: sigma.keySet())
if(!v1.equals(v2) && v1.equals(sigma.get(v2))){
tNew=sigma.get(v1);
if(occurCheck(v2, tNew, sigma))
return null;
sigma.put(v2, tNew);
}
return sigma;
}
/**
* Returns a Map<Variable, Term> representing the substitution (i.e. a set
* of variable/term pairs) or null which is used to indicate a failure to
* unify.
*
* @param arg1 the terms' list of the first predicate
* @param arg2 the terms' list of the first predicate
* @param sigma the substitution built up so far
* @return a Map<Variable, Term> representing the substitution (i.e. a set
* of variable/term pairs) or null which is used to indicate a
* failure to unify.
*/
private static Map<Variable, Term> unify(List<Term> arg1, List<Term> arg2, Map<Variable, Term> sigma) {
if (sigma == null) {
return null;
} else if (arg1.size() != arg2.size()) {
return null;
} else if (arg1.size() == 0 && arg2.size() == 0) {
return sigma;
} else if (arg1.size() == 1 && arg2.size() == 1) {
return unify(arg1.get(0), arg2.get(0), sigma);
} else {
return unify(arg1.subList(1, arg1.size()), arg2.subList(1, arg2.size()),
unify(arg1.get(0), arg2.get(0), sigma));
}
}
/**
* Returns a Map<Variable, Term> representing the substitution (i.e. a set
* of variable/term pairs) or null which is used to indicate a failure to
* unify.
*
* @param x a term
* @param y a term
* @param sigma the substitution built up so far
* @return a Map<Variable, Term> representing the substitution (i.e. a set
* of variable/term pairs) or null which is used to indicate a
* failure to unify.
*/
private static Map<Variable, Term> unify(Term x, Term y,
Map<Variable, Term> sigma) {
if (sigma == null) {
return null;
} else if (x.equals(y)) {
// if the two term are equals return the substitution without any modification
return sigma;
} else if (x instanceof Variable) {
// else if VARIABLE?(x) then return UNIFY-VAR(x, y, sigma)
return unifyVar((Variable) x, y, sigma);
} else if (y instanceof Variable) {
// else if VARIABLE?(y) then return UNIFY-VAR(y, x, sigma)
return unifyVar((Variable) y, x, sigma);
} else if (x instanceof Function && y instanceof Function) {
// else if FUNCTION?(x) and FUNCTION?(y) then
if(x.getName().equals(y.getName())) // the function's name must be the same
return unify(((Function) x).getArgs(), ((Function) y).getArgs(), sigma);
else // CLASH!!!
return null;
} else {
return null;
}
}
/**
* Makes the unification between a variable and a term if it is possible,
* return null otherwise.
* The term must not be equal to the variable, otherwise return null!
*
* @param var the variable that will be part of the substitution's domain
* @param x the term that will be the image of var in the substitution
* @param sigma the substitution
* @return the substitution
*/
private static Map<Variable, Term> unifyVar(Variable var, Term x,
Map<Variable, Term> sigma) {
if (sigma.keySet().contains(var)) {
// if {var/val} belongs to sigma then return UNIFY(val, x, sigma)
return unify(sigma.get(var), x, sigma);
} else if (sigma.keySet().contains(x)) {
// else if {x/val} belongs to sigma then return UNIFY(var, val, sigma)
return unify(var, sigma.get(x), sigma);
} else if (occurCheck(var, x, sigma)) { // OCCUR CHECK!!!
return null;
} else {
sigma.put(var, x);
return sigma;
}
}
/**
*
* Occur Check happens: (1) if x is equals to y (or a variables' chain makes them equal);
* (2) when you should make a substitution between a variable and a term
* that contain the same variable at different nested level of a function.
* e.g. var <-- g(var)
* If an occur check exists, this method finds it.
*
* @param var the variable that should be substituted
* @param x the term that should be substituted instead of var
* @param sigma the substitution
* @return true if an occur check exists, false otherwise.
*/
private static boolean occurCheck(Variable var, Term x, Map<Variable, Term> sigma) {
if (x instanceof Variable && var.equals(x)) { // (1) you cannot unify the same variable
return true;
} else if (x instanceof Variable && sigma.containsKey(x)){
// (1) recursion in case of variables' chains
return occurCheck(var, sigma.get(x), sigma);
} else if (x instanceof Function) {
// (2) same var in different nested level of a function
Function f = (Function) x;
for (Term t : f.getArgs())
if (occurCheck(var, t, sigma))
return true;
}
return false;
}
/**
* Returns a Map<Variable, Term> representing the left-substitution (i.e. a set
* of variable/term pairs) or null which is used to indicate a failure to
* unify.
*
* @param arg1 the terms' list of the first predicate
* @param arg2 the terms' list of the first predicate
* @return a Map<Variable, Term> representing the substitution (i.e. a set
* of variable/term pairs) or null which is used to indicate a
* failure to unify.
*/
public static Map<Variable, Term> findLeftSubst(List<Term> arg1, List<Term> arg2){
if(arg1==null || arg2==null || arg1.size()!=arg2.size())
return null;
else{
Map<Variable, Term> sigma = new HashMap<Variable, Term>();
for(int i=0;i<arg1.size();i++)
if((sigma=unifyLeft(arg1.get(i), arg2.get(i), sigma))==null)
return null;
return sigma;
}
}
/**
* Returns a Map<Variable, Term> representing the left-substitution (i.e. a set
* of variable/term pairs) or null which is used to indicate a failure to
* unify.
*
* @param x a term
* @param y a term
* @param sigma the substitution built up so far
* @return a Map<Variable, Term> representing the substitution (i.e. a set
* of variable/term pairs) or null which is used to indicate a
* failure to unify.
*/
private static Map<Variable, Term> unifyLeft(Term x, Term y,
Map<Variable, Term> sigma) {
if (sigma == null) {
return null;
} else if (x.equals(y)) {
// if the two term are equals return the substitution without any modification
return sigma;
} else if (x instanceof Variable){
Term t=sigma.get((Variable) x);
//System.out.println("\n" + x + ", " + t + "\t" + y);
if(t==null)
sigma.put((Variable) x, y);
else if(!t.equals(y)) // you should unify these two term, but the same variable is already used
// to unify another term different from y
return null;
return sigma;
} else if (x instanceof Function && y instanceof Function) {
if(x.getName().equals(y.getName())){ // the function's name must be the same
for(int i=0;i<((Function)x).nArgs();i++)
if((sigma=unifyLeft(((Function)x).getArgs().get(i), ((Function)y).getArgs().get(i), sigma))==null)
return null;
return sigma;
} else // CLASH!!!
return null;
} else {
/* - two different constant
* - left(constant) && ( right(variable) || right(function) )
* - left(function) && ( right(constant) || right(variable) )
*/
return null;
}
}
} | true |
c9e36dd4d7f72e0fbec31bfb7cf8e20b1da58395 | Java | xieliang/spliceengine | /db-testing/src/test/java/com/splicemachine/dbTesting/unitTests/harness/BasicUnitTest.java | UTF-8 | 3,018 | 2.34375 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | /*
* Apache Derby is a subproject of the Apache DB project, and is licensed under
* the Apache License, Version 2.0 (the "License"); you may not use these files
* 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.
*
* Splice Machine, Inc. has modified this file.
*
* All Splice Machine modifications are Copyright 2012 - 2016 Splice Machine, Inc.,
* and are licensed to you under the License; you may not use this file except in
* compliance with the License.
*
* 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.splicemachine.dbTesting.unitTests.harness;
import com.splicemachine.db.iapi.services.stream.HeaderPrintWriter;
// For testing
//import java.io.OutputStreamWriter;
class BasicUnitTest implements UnitTest
{
String traceMessage;
int testType;
int testDuration;
boolean result;
Error exception;
BasicUnitTest(String traceMessage,
int testType,
int testDuration,
boolean result,
Error exception){
this.traceMessage = traceMessage;
this.testType = testType;
this.testDuration = testDuration;
this.result = result;
this.exception = exception;
}
public String toString(){
return ("testType: "+testType+" testDuration: "+
testDuration+" traceMessage: "+traceMessage+
" result: "+result+" exception: "+exception);
}
public boolean Execute (HeaderPrintWriter output) {
output.printlnWithHeader(toString());
if (exception != null)
throw exception;
return result;
}
public int UnitTestDuration(){
return testDuration;
}
public int UnitTestType(){
return testType;
}
private void executeCatch(HeaderPrintWriter output){
try{
Execute(output);
}
catch (Error e){
System.out.println("Caught exception:"+ e);
}
}
/*
public static void main(String[] Args){
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BasicGetLogHeader glh = new BasicGetLogHeader(
true, true, "hi" );
BasicHeaderPrintWriter hpw = new BasicHeaderPrintWriter(osw,glh);
BasicUnitTest t1 =
new BasicUnitTest("hi Eric",1,1,true,null);
t1.executeCatch(hpw);
BasicUnitTest t2 =
new BasicUnitTest("hi my dear boy",1,1,true,null);
t2.executeCatch(hpw);
BasicUnitTest t3 =
new BasicUnitTest("hi my dear boy",1,1,true,
new Error("bogus Error"));
t3.executeCatch(hpw);
}
*/
}
| true |
4c2a65e4ac080b700240a7dbd5923aaca92dd6ed | Java | 06112497liu/ssm | /common-dao/src/main/java/com/bbd/dao/WarnNotifierExtDao.java | UTF-8 | 569 | 1.78125 | 2 | [] | no_license | package com.bbd.dao;
import com.bbd.domain.WarnNotifier;
import com.bbd.domain.WarnNotifierExample;
import com.mybatis.domain.PageBounds;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface WarnNotifierExtDao {
/**
* 删除指定配置id下的预警通知人
* @param settingId
* @return
*/
int delNotifierBySettingId(@Param(value = "settingId") Long settingId);
/**
* 批量添加预警通知人
* @param list
* @return
*/
int batchInsertNotifier(List<WarnNotifier> list);
} | true |
3886d89a25b881d948f8ec77c410434ed36bb7e2 | Java | T-Campbell18/Princeton | /COS226/Wordnet/DeluxeBFS.java | UTF-8 | 5,277 | 3.078125 | 3 | [] | no_license | import java.util.Hashtable;
import edu.princeton.cs.algs4.Digraph;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.Stack;
public class DeluxeBFS {
private static final int INFINITY = Integer.MAX_VALUE;
private Hashtable<Integer, Boolean> marked;
private Hashtable<Integer, Integer> edgeTo;
private Hashtable<Integer, Integer> distTo;
private int size;
public DeluxeBFS(Digraph G, int s) {
marked = new Hashtable<Integer, Boolean>();
distTo = new Hashtable<Integer, Integer>();
edgeTo = new Hashtable<Integer, Integer>();
size = G.V();
for (Integer x: distTo.keySet())
distTo.put(x, INFINITY);
validateVertex(s);
bfs(G, s);
}
public DeluxeBFS(Digraph G, Iterable<Integer> sources) {
marked = new Hashtable<Integer, Boolean>();
distTo = new Hashtable<Integer, Integer>();
edgeTo = new Hashtable<Integer, Integer>();
for (Integer x : distTo.keySet()) {
distTo.put(x, INFINITY);
}
validateVertices(sources);
bfs(G, sources);
}
// BFS from single source
private void bfs(Digraph G, int s) {
Queue<Integer> q = new Queue<Integer>();
marked.put(s, true);
distTo.put(s, 0);
q.enqueue(s);
while (!q.isEmpty()) {
int v = q.dequeue();
for (int w : G.adj(v)) {
if (!marked.get(s)) {
edgeTo.put(w, v);
distTo.put(w, distTo.get(v) + 1);
marked.put(w, true);
q.enqueue(w);
}
}
}
}
// BFS from multiple sources
private void bfs(Digraph G, Iterable<Integer> sources) {
Queue<Integer> q = new Queue<Integer>();
for (int s : sources) {
marked.put(s, true);
distTo.put(s, 0);
q.enqueue(s);
}
while (!q.isEmpty()) {
int v = q.dequeue();
for (int w : G.adj(v)) {
if (!marked.get(w)) {
edgeTo.put(w, v);
distTo.put(w, distTo.get(v) + 1);
marked.put(w, true);
q.enqueue(w);
}
}
}
}
public boolean hasPathTo(int v) {
//validateVertex(v);
return marked.get(v);
}
public int distTo(int v) {
//validateVertex(v);
return distTo.get(v);
}
public Iterable<Integer> pathTo(int v) {
validateVertex(v);
if (!hasPathTo(v)) return null;
Stack<Integer> path = new Stack<Integer>();
int x;
for (x = v; distTo.get(x) != 0; x = edgeTo.get(x))
path.push(x);
path.push(x);
return path;
}
// throw an IllegalArgumentException unless {@code 0 <= v < V}
private void validateVertex(int v) {
if (v < 0 || v >= size)
throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (size-1));
}
// throw an IllegalArgumentException unless {@code 0 <= v < V}
private void validateVertices(Iterable<Integer> vertices) {
if (vertices == null) {
throw new IllegalArgumentException("argument is null");
}
int V = marked.size();
for (int v : vertices) {
if (v < 0 || v >= V) {
throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
}
}
}
/**
* Unit tests the {@code BreadthFirstDirectedPaths} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
/*In in = new In(args[0]);
Digraph G = new Digraph(in);
// StdOut.println(G);
int s = Integer.parseInt(args[1]);
BreadthFirstDirectedPaths bfs = new BreadthFirstDirectedPaths(G, s);
for (int v = 0; v < G.V(); v++) {
if (bfs.hasPathTo(v)) {
StdOut.printf("%d to %d (%d): ", s, v, bfs.distTo(v));
for (int x : bfs.pathTo(v)) {
if (x == s) StdOut.print(x);
else StdOut.print("->" + x);
}
StdOut.println();
}
else {
StdOut.printf("%d to %d (-): not connected\n", s, v);
}*/
}
}
public static void main(String[] args)
{
In in = new In(args[0]);
Digraph G = new Digraph(in);
ShortestCommonAncestor sca = new ShortestCommonAncestor(G);
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
a.add(2);
a.add(3);
b.add(4);
b.add(8);
int length = sca.length(a, b);
int ancestor = sca.ancestor(a, b);
StdOut.printf("length = %d, ancestor = %d\n", length, ancestor);
while (!StdIn.isEmpty())
{
int v = StdIn.readInt();
int w = StdIn.readInt();
length = sca.length(v, w);
ancestor = sca.ancestor(v, w);
StdOut.printf("length = %d, ancestor = %d\n", length, ancestor);
}
}
| true |
cc50825712d95d526024611518a44391d89c238d | Java | hexianzhi/BookCollection | /app/src/main/java/com/example/gedune/bookcollection/net/MyHttpCallback.java | UTF-8 | 386 | 2.015625 | 2 | [] | no_license | package com.example.gedune.bookcollection.net;
import okhttp3.Call;
/**
* Created by zhengwen on 16/12/6.
*/
public interface MyHttpCallback<T> {
/***
* 请求成功,httpcode 200,业务code ==1
*
* @param data
*/
public void onResponse(Call call, Object data);
/**
* @param e
*/
public void onFailure(Call call , Exception e);
}
| true |
af2e0c8ed99917cacaf4bbb99a0f5a547696c609 | Java | 39179219huangtao/HuangTaoBlog | /JavaProject/hyc/hyc-order/order-api/src/main/java/com/hyc/shop/order/OrderCommentService.java | UTF-8 | 1,591 | 1.875 | 2 | [] | no_license | package com.hyc.shop.order;
import com.hyc.shop.order.bo.*;
import com.hyc.shop.order.dto.OrderCommentCreateDTO;
import com.hyc.shop.order.dto.OrderCommentPageDTO;
import com.hyc.shop.order.dto.OrderCommentStateInfoPageDTO;
import com.hyc.shop.order.dto.OrderCommentTimeOutPageDTO;
import java.util.List;
/**
* 订单评论模块
*
* @author wtz
* @time 2019-05-14 22:10
*/
public interface OrderCommentService {
/**
* 评论创建
* @param orderCommentCreateDTO
* @return
*/
OrderCommentCreateBO createOrderComment(OrderCommentCreateDTO orderCommentCreateDTO);
/**
* 获取评论列表的分页
* @param orderCommentPageDTO
* @return
*/
OrderCommentPageBO getOrderCommentPage(OrderCommentPageDTO orderCommentPageDTO);
/**
* 获取评论详情
* @param commentId
* @return
*/
OrderCommentInfoBO getOrderCommentInfo(Integer commentId);
/**
* 获取订单评论状态详情
* @param orderCommentStateInfoPageDTO
* @return
*/
OrderCommentStateInfoPageBO getOrderCommentStateInfoPage(OrderCommentStateInfoPageDTO orderCommentStateInfoPageDTO);
/**
* 获取订单评论超时分页
* @param orderCommentTimeOutPageDTO
* @return
*/
List<OrderCommentTimeOutBO> getOrderCommentTimeOutPage(OrderCommentTimeOutPageDTO orderCommentTimeOutPageDTO);
/**
* 批量更新订单评论状态
* @param orderCommentTimeOutBOList
*/
void updateBatchOrderCommentState(List<OrderCommentTimeOutBO> orderCommentTimeOutBOList);
}
| true |
47575f7f670098cfb1e16c0cdd632c97b67f7b30 | Java | fuhongliang/Android-MeiWei | /app/src/main/java/com/ifhu/meiwei/ui/activity/order/OrderActivity.java | UTF-8 | 2,041 | 2.0625 | 2 | [] | no_license | package com.ifhu.meiwei.ui.activity.order;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ifhu.meiwei.R;
import com.ifhu.meiwei.adapter.OrderAdapter;
import com.ifhu.meiwei.bean.BaseEntity;
import com.ifhu.meiwei.bean.OrderBean;
import com.ifhu.meiwei.net.BaseObserver;
import com.ifhu.meiwei.net.RetrofitApiManager;
import com.ifhu.meiwei.net.SchedulerUtils;
import com.ifhu.meiwei.net.service.OrdersService;
import com.ifhu.meiwei.ui.base.BaseActivity;
import com.ifhu.meiwei.utils.ToastHelper;
import com.ifhu.meiwei.utils.UserLogic;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class OrderActivity extends BaseActivity {
List<OrderBean> orderBeanList = new ArrayList<>();
OrderAdapter orderAdapter;
@BindView(R.id.tv_head)
TextView tvHead;
@BindView(R.id.lv_order)
ListView lvOrder;
int type = 1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
ButterKnife.bind(this);
orderAdapter = new OrderAdapter(orderBeanList, this);
lvOrder.setAdapter(orderAdapter);
orderList();
}
/**
* 订单列表接口
*/
public void orderList() {
setLoadingMessageIndicator(true);
RetrofitApiManager.createUpload(OrdersService.class).orderList(UserLogic.getUser().getMember_id(), type)
.compose(SchedulerUtils.ioMainScheduler()).subscribe(new BaseObserver<OrderBean>(true) {
@Override
protected void onApiComplete() {
setLoadingMessageIndicator(false);
}
@Override
protected void onSuccees(BaseEntity<OrderBean> t) throws Exception {
orderAdapter.setOrderBeanList(orderBeanList);
}
});
}
}
| true |
b82c1b4aa1563327d5e50101ca0430f04833a8c3 | Java | hyb1234hi/reverse-wechat | /weixin6519android1140/src/sourcecode/com/tencent/mm/ui/KeyboardLinearLayout.java | UTF-8 | 2,841 | 1.820313 | 2 | [] | no_license | package com.tencent.mm.ui;
import android.content.Context;
import android.util.AttributeSet;
import com.tencent.gmtrace.GMTrace;
import com.tencent.mm.sdk.platformtools.w;
import com.tencent.mm.ui.base.OnLayoutChangedLinearLayout;
public class KeyboardLinearLayout
extends OnLayoutChangedLinearLayout
{
public String TAG;
private boolean mHasInit;
private int mHeight;
private boolean vJd;
public a vJe;
public KeyboardLinearLayout(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
GMTrace.i(2532151656448L, 18866);
this.TAG = "MicroMsg.KeyboardLinearLayout";
this.mHasInit = false;
this.mHasInit = false;
this.mHeight = 0;
this.vJd = false;
this.TAG += getId();
GMTrace.o(2532151656448L, 18866);
}
public KeyboardLinearLayout(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(paramContext, paramAttributeSet, paramInt);
GMTrace.i(2532285874176L, 18867);
this.TAG = "MicroMsg.KeyboardLinearLayout";
this.mHasInit = false;
GMTrace.o(2532285874176L, 18867);
}
public void oD(int paramInt)
{
GMTrace.i(2532688527360L, 18870);
if (this.vJe != null) {
this.vJe.oD(paramInt);
}
GMTrace.o(2532688527360L, 18870);
}
public void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
GMTrace.i(2532420091904L, 18868);
super.onLayout(paramBoolean, paramInt1, paramInt2, paramInt3, paramInt4);
xP(paramInt4);
GMTrace.o(2532420091904L, 18868);
}
public void xP(int paramInt)
{
GMTrace.i(2532554309632L, 18869);
if (!this.mHasInit)
{
this.mHasInit = true;
this.mHeight = paramInt;
w.i(this.TAG, "init height:%d", new Object[] { Integer.valueOf(this.mHeight) });
if (this.vJe != null) {
this.vJe.oD(-1);
}
if ((this.mHasInit) && (!this.vJd) && (this.mHeight - paramInt > 100))
{
this.vJd = true;
oD(-3);
w.w(this.TAG, "show keyboard!! mHeight: " + this.mHeight + " b: " + paramInt);
}
if ((this.mHasInit) && (this.vJd) && (this.mHeight - paramInt <= 100))
{
this.vJd = false;
oD(-2);
w.w(this.TAG, "hide keyboard!! mHeight: " + this.mHeight + " b: " + paramInt);
}
GMTrace.o(2532554309632L, 18869);
return;
}
if (this.mHeight < paramInt) {}
for (int i = paramInt;; i = this.mHeight)
{
this.mHeight = i;
break;
}
}
public static abstract interface a
{
public abstract void oD(int paramInt);
}
}
/* Location: D:\tools\apktool\weixin6519android1140\jar\classes-dex2jar.jar!\com\tencent\mm\ui\KeyboardLinearLayout.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
068f22cee9bbfa2096e8b7eec92d9b3c6708dfed | Java | surenpi/phoenix.webui.framework | /src/main/java/org/suren/autotest/web/framework/jdt/SuRenCompilerRequestor.java | UTF-8 | 2,775 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.suren.autotest.web.framework.jdt;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
/**
* @author suren
* @date 2016年11月26日 下午5:51:03
*/
public class SuRenCompilerRequestor implements ICompilerRequestor
{
private String workDir;
public SuRenCompilerRequestor(String workDir)
{
this.workDir = workDir;
}
public void acceptResult(CompilationResult result)
{
if(result.hasErrors())
{
for(IProblem problem : result.getErrors())
{
String className = new String(problem.getOriginatingFileName()).replace("/", ".");
className = className.substring(0, className.length() - 5);
String message = problem.getMessage();
if (problem.getID() == IProblem.CannotImportPackage)
{
message = problem.getArguments()[0] + " cannot be resolved";
}
throw new RuntimeException(className + ":" + message);
}
}
ClassFile[] clazzFiles = result.getClassFiles();
for (int i = 0; i < clazzFiles.length; i++)
{
String clazzName = join(clazzFiles[i].getCompoundName());
File target = new File(workDir, clazzName.replace(".", "/") + ".class");
try
{
FileUtils.writeByteArrayToFile(target, clazzFiles[i].getBytes());
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
private String join(char[][] chars)
{
StringBuilder sb = new StringBuilder();
for (char[] item : chars)
{
if (sb.length() > 0)
{
sb.append(".");
}
sb.append(item);
}
return sb.toString();
}
}
| true |
cddfdc12f8ee664073cde5dc3d8997b329f4ef04 | Java | yyi/Spring-Security-Third-Edition | /Chapter13/chapter13.02-calendar/src/main/java/com/packtpub/springsecurity/web/access/expression/CustomWebSecurityExpressionRoot.java | UTF-8 | 798 | 2.203125 | 2 | [
"MIT"
] | permissive | package com.packtpub.springsecurity.web.access.expression;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.expression.WebSecurityExpressionRoot;
import javax.transaction.NotSupportedException;
/**
* @creaor:yyi
* @createDate:2020/10/27
* @Describle
*/
public class CustomWebSecurityExpressionRoot extends WebSecurityExpressionRoot {
public CustomWebSecurityExpressionRoot(Authentication authentication, FilterInvocation fi) {
super(authentication, fi);
}
public boolean isLocal() {
try {
return "localhost".equals(request.getServerName());
} catch (UnsupportedOperationException e) {
return false;
}
}
}
| true |
6553e09aae3392820557554f3fde4aecfb6cf1e9 | Java | kingtian123456/goldtest | /src/com/entity/News.java | UTF-8 | 4,566 | 2.140625 | 2 | [] | no_license | package com.entity;
import java.util.Date;
import java.util.List;
public class News {
private Integer newsId;//文章ID
private Integer sortId;//所属类别ID
private String newsTitle;//文章标题
private String newsIntro;//简介
private String newsAuthor;//作者
private String newsCopyfrom;//来源
private String newsKeyword;//关键字
private String newsDefaultpicurl;//首页图片
private String newsUser;//编辑人
private Integer newsOrders;//排序
private Integer newsHits;//点击数
private Integer newsDeleted;//0删除1保存
private Integer newsPassed;//0不显示1显示
private Integer newsOntop;//固定1,0不固定
private Date newsCreatetime;//生成时间
private Date newsUpdatetime;//更改时间
private String newsContent;//文章内容
private Integer comments;//文章评论数
private List<String> list;//关键字分割成list
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public Integer getComments() {
return comments;
}
public void setComments(Integer comments) {
this.comments = comments;
}
public Integer getNewsId() {
return newsId;
}
public void setNewsId(Integer newsId) {
this.newsId = newsId;
}
public Integer getSortId() {
return sortId;
}
public void setSortId(Integer sortId) {
this.sortId = sortId;
}
public String getNewsTitle() {
return newsTitle;
}
public void setNewsTitle(String newsTitle) {
this.newsTitle = newsTitle == null ? null : newsTitle.trim();
}
public String getNewsIntro() {
return newsIntro;
}
public void setNewsIntro(String newsIntro) {
this.newsIntro = newsIntro == null ? null : newsIntro.trim();
}
public String getNewsAuthor() {
return newsAuthor;
}
public void setNewsAuthor(String newsAuthor) {
this.newsAuthor = newsAuthor == null ? null : newsAuthor.trim();
}
public String getNewsCopyfrom() {
return newsCopyfrom;
}
public void setNewsCopyfrom(String newsCopyfrom) {
this.newsCopyfrom = newsCopyfrom == null ? null : newsCopyfrom.trim();
}
public String getNewsKeyword() {
return newsKeyword;
}
public void setNewsKeyword(String newsKeyword) {
this.newsKeyword = newsKeyword == null ? null : newsKeyword.trim();
}
public String getNewsDefaultpicurl() {
return newsDefaultpicurl;
}
public void setNewsDefaultpicurl(String newsDefaultpicurl) {
this.newsDefaultpicurl = newsDefaultpicurl == null ? null : newsDefaultpicurl.trim();
}
public String getNewsUser() {
return newsUser;
}
public void setNewsUser(String newsUser) {
this.newsUser = newsUser == null ? null : newsUser.trim();
}
public Integer getNewsOrders() {
return newsOrders;
}
public void setNewsOrders(Integer newsOrders) {
this.newsOrders = newsOrders;
}
public Integer getNewsHits() {
return newsHits;
}
public void setNewsHits(Integer newsHits) {
this.newsHits = newsHits;
}
public Integer getNewsDeleted() {
return newsDeleted;
}
public void setNewsDeleted(Integer newsDeleted) {
this.newsDeleted = newsDeleted;
}
public Integer getNewsPassed() {
return newsPassed;
}
public void setNewsPassed(Integer newsPassed) {
this.newsPassed = newsPassed;
}
public Integer getNewsOntop() {
return newsOntop;
}
public void setNewsOntop(Integer newsOntop) {
this.newsOntop = newsOntop;
}
public Date getNewsCreatetime() {
return newsCreatetime;
}
public void setNewsCreatetime(Date newsCreatetime) {
this.newsCreatetime = newsCreatetime;
}
public Date getNewsUpdatetime() {
return newsUpdatetime;
}
public void setNewsUpdatetime(Date newsUpdatetime) {
this.newsUpdatetime = newsUpdatetime;
}
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent == null ? null : newsContent.trim();
}
} | true |
46fe6f7a35a8415bb1725be745cf19fbb6348ea4 | Java | Movilizer/movilizer-webservice | /src/main/java/com/movilizer/mds/webservice/models/maf/communications/MafGenericResponse.java | UTF-8 | 665 | 2.0625 | 2 | [
"Apache-2.0"
] | permissive | package com.movilizer.mds.webservice.models.maf.communications;
import com.movilizer.mds.webservice.models.maf.MafGenericScript;
public class MafGenericResponse extends MafResponse { ;
private MafGenericScript genericScript;
public MafGenericResponse(boolean successful, String errorMessage,
MafGenericScript genericScript) {
super(successful, errorMessage);
this.genericScript = genericScript;
}
public MafGenericScript getGenericScript() {
return genericScript;
}
public void setGenericScript(MafGenericScript genericScript) {
this.genericScript = genericScript;
}
}
| true |
f2ac6b35bdfe9743445ad87e8084d76c28793568 | Java | ayushjain7/hashTable | /HashCode.java | UTF-8 | 2,148 | 3.34375 | 3 | [] | no_license | /**
* Created by ayush on 10/9/15.
*/
public class HashCode {
private String[] keys;
private Object[] values;
private int size;
private int numberOfElements;
public HashCode(int size){
this.size = size;
this.keys = new String[size];
this.values = new Object[size];
}
public boolean set(String key, Object value){
int index = findIndex(key);
if(index == -1)
return false;
if(!key.equals(this.keys[index]))
this.numberOfElements++;
this.keys[index] = key;
this.values[index] = value;
return true;
}
public Object get(String key){
int index = findIndex(key);
if(index == -1 || !key.equals(this.keys[index]))
return null;
return values[index];
}
public Object delete(String key){
int index = findIndex(key);
if(index == -1 || !key.equals(this.keys[index]))
return null;
this.keys[index]=null;
numberOfElements--;
Object toRet = this.values[index];
rehash(index);
return toRet;
}
private void rehash(int index) {
int loopIndex = index >= 9 ? 0 : index+ 1;
while(this.keys[loopIndex]!=null && loopIndex != index){
int rehashIndex = findIndex(this.keys[loopIndex]);
if(rehashIndex != loopIndex){
this.keys[rehashIndex] = this.keys[loopIndex];
this.values[rehashIndex] = this.values[loopIndex];
this.keys[loopIndex] = null;
}
loopIndex = loopIndex < this.size -1 ? loopIndex + 1 : 0;
}
}
public float load(){
return (float)numberOfElements/size;
}
private int findIndex(String key){
int hashC = key.hashCode();
int index = hashC%size;
int count = 1;
while(this.keys[index]!=null && !this.keys[index].equals(key)){
count++;
index++;
if(index > this.size-1)
index=0;
if(count >= this.size)
return -1;
}
return index;
}
}
| true |
f715ce24008ee7d0c87d3df52829dea9de99d926 | Java | NikkiaOwens/Polymorphism-Farm | /src/test/java/com/zipcodewilmington/froilansfarm/Friday.java | UTF-8 | 3,428 | 3.09375 | 3 | [] | no_license | package com.zipcodewilmington.froilansfarm;
import com.zipcodewilmington.froilansfarm.Animal.Chicken;
import com.zipcodewilmington.froilansfarm.Animal.Horse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
public class Friday {
Farm froilansFarm = new Farm();
Farmer froilan = new Farmer("Froilan");
Farmer froilanda = new Farmer("Froilanda");
@Before
public void setup(){
froilansFarm.getFarmhouse().getPeople().add(froilan);
froilansFarm.getFarmhouse().getPeople().add(froilanda);
//fill field
ArrayList<CropRow> cropRows = froilansFarm.getField().getRowsOfCrops();
for (int i = 0; i < 5; i++) {
if (i == 0) {
cropRows.add(new CropRow());
} else {
cropRows.add(new CropRow());
// we'll just make the "arbitrary vegetation" tomato plants
}
}
//fill chicken coops
for (int i = 0; i < 4; i++){
ChickenCoop coopToBeAdded = new ChickenCoop();
if (i == 3) { // add 3 on the last chicken coop
for (int j = 0; j < 2; j++) {
coopToBeAdded.getChickens().add(new Chicken());
}
} else {
for (int j = 0; j < 3; j++){
coopToBeAdded.getChickens().add(new Chicken());
}
}
froilansFarm.getChickenCoops().add(coopToBeAdded);
}
//fill stables
for (int i = 0; i < 3; i++){
Stable stableToBeAdded= new Stable();
if (i == 2) { // add 4 to the last stable
for (int j = 0; j < 3; j++) {
stableToBeAdded.getHorses().add(new Horse());
}
}
else {
for (int j = 0; j < 2; j++){
stableToBeAdded.getHorses().add(new Horse());
}
}
froilansFarm.getStables().add(stableToBeAdded);
}
//Vehicles
froilansFarm.getGarage().add(new Tractor());
froilansFarm.getGarage().add(new CropDuster());
}
@Test
public void morningRoutine(){
//ride each horse
// feed them 3 ears of corn
Boolean expectedIsBeingRidden = true;
for (Stable s : froilansFarm.getStables()){
for (Horse h : s.getHorses()){
froilan.mount(h);
Assert.assertEquals(expectedIsBeingRidden, h.getBeingRidden());
froilan.dismount(h);
froilanda.mount(h);
Assert.assertEquals(expectedIsBeingRidden, h.getBeingRidden());
froilanda.dismount(h);
for (int i = 0; i < 3; i++){
h.eat(new EarCorn());
}
}
}
//eat breakfast
froilan.eat(new EarCorn());
for (int i = 0; i < 2; i++){froilan.eat(new Tomato());}
for (int i = 0; i < 5; i++){froilan.eat(new Egg());}
for (int i = 0; i < 2; i++){froilanda.eat(new EarCorn());}
froilanda.eat(new Tomato());
for (int i = 0; i < 2; i++){froilanda.eat(new Egg());}
}
// @Test
// public void vehicleMakeNoiseTest(){
// Vehicle vehicle = new Vehicle();
//
// String expected = "Vroom vroom";
// String actual = vehicle.makeNoise();
//
// }
}
| true |
938e89ba10944ce03398360593d0bc4e457c9714 | Java | project-socialcar/android-app | /SocialCar/app/src/main/java/eu/h2020/sc/ui/drawer/DrawerBuilder.java | UTF-8 | 2,759 | 2.296875 | 2 | [
"MIT"
] | permissive | package eu.h2020.sc.ui.drawer;
import android.content.res.TypedArray;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import eu.h2020.sc.R;
import eu.h2020.sc.ui.commons.RecyclerViewItemClickListener;
/**
* @author Nicola d'Adduzio <nicola.dadduzio@movenda.com>
*/
public class DrawerBuilder {
private AppCompatActivity activity;
private DrawerLayout drawerLayout;
private MyActionBarDrawerToggle mDrawerToggle;
private List<DrawerItem> drawerItems;
public DrawerBuilder(AppCompatActivity activity) {
this.activity = activity;
this.drawerItems = new ArrayList<>();
}
public void setUpNavigationDrawer(Toolbar toolbar, DrawerLayout drawerLayout) {
this.drawerLayout = drawerLayout;
this.mDrawerToggle = new MyActionBarDrawerToggle(this.activity, this.drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
this.drawerLayout.addDrawerListener(mDrawerToggle);
}
public void initItems(String drawerItemTitle) {
this.drawerItems = new ArrayList<>();
this.drawerItems.add(new DrawerItem());
for (int i = 0; i < this.activity.getResources().getStringArray(R.array.drawer_items_titles).length; i++) {
DrawerItem drawerItem = new DrawerItem();
drawerItem.setDrawerItemTitle(this.activity.getResources().getStringArray(R.array.drawer_items_titles)[i]);
if (drawerItem.getDrawerItemTitle().equals(drawerItemTitle))
drawerItem.setItemSelected(true);
this.addDrawerItems(i, drawerItem);
}
}
private void addDrawerItems(int i, DrawerItem drawerItem) {
TypedArray icons = this.activity.getResources().obtainTypedArray(R.array.drawer_items_icons);
drawerItem.setDrawerItemIcon(icons.getResourceId(i, -1));
this.drawerItems.add(drawerItem);
icons.recycle();
}
public void initDrawerList(RecyclerView.LayoutManager mLayoutManager, RecyclerView recyclerViewDrawer, RecyclerViewItemClickListener recyclerViewItemClickListener) {
DrawerAdapter drawerAdapter = new DrawerAdapter(this.drawerItems, this.activity, this.drawerLayout, this.mDrawerToggle);
drawerAdapter.setRecyclerViewItemClickListener(recyclerViewItemClickListener);
drawerAdapter.notifyDataSetChanged();
recyclerViewDrawer.setLayoutManager(mLayoutManager);
recyclerViewDrawer.setHasFixedSize(true);
recyclerViewDrawer.setAdapter(drawerAdapter);
}
public List<DrawerItem> getDrawerItems() {
return drawerItems;
}
}
| true |
147f343314ca363e605b2cfd2b745f606d43161c | Java | djgonza/Programacion | /UT3/Practicas/MaquinaExpendedoraMejorada/MáquinaExpendedora.java | ISO-8859-1 | 2,983 | 3.65625 | 4 | [
"MIT"
] | permissive |
/**
* Este proyecto modela una sencilla mquina expendedora de billetes.
* El precio del ticket se especifica via el constructor.
* Los objetos verifican que un usuario solo introduce cantidades positivas de dinero y solo
* emiten un ticket si se ha introducido suficiente dinero
*/
public class MquinaExpendedora
{
// El precio de un ticket en esta mquina
private int precio;
// Cantidad de dinero introducida por el usuario hasta ahora
private int importe;
// Cantidad total de dinero recogida por la mquina
private int total;
/**
* Crear una mquina que emite tickets de un determinado precio
* El precio ha de ser mayor que 0 y no hay verificacin de esto
*/
public MquinaExpendedora(int precioTicket)
{
precio = precioTicket;
importe = 0;
total = 0;
}
/**
* Devolver el precio de un billete
*/
public int getPrecio()
{
return precio;
}
/**
* Devolver la cantidad de dinero insertada hasta el momento
* para el billete
*/
public int getImporte()
{
return importe;
}
/**
* Recibir una cantidad de dinero de un usuario
* Verificar que la cantidad es positiva
*/
public void insertarDinero(int cantidad)
{
if (cantidad > 0)
{
importe = importe + cantidad;
}
else
{
System.out.println("Introduzca una cantidad positiva: " + cantidad);
}
}
/**
* Imprimir un ticket si se ha introducido suficiente dinero
* y reduce el importe restando el precio del ticket. Escribe un mensaje de error si
* se necesita ms dinero
*/
public void imprimirTicket()
{
if (importe >= precio)
{
// Simula impresin de un billete
System.out.println("##################");
System.out.println("# Mquina expendedora BlueJ");
System.out.println("# Billete:");
System.out.println("# " + precio + " cents.");
System.out.println("##################");
System.out.println();
// Actualizar el total recogido por la mquina con el precio
total = total + precio;
// decrementar el importe con el precio
importe = importe - precio;
}
else
{
System.out.println("# Debe insertar al menos: " +
(precio - importe) + " cntimos ms ");
}
}
/**
* Devolver el dinero del importe y poner el importe a 0
*/
public int devolverCambio()
{
int cambio;
cambio = importe;
importe = 0;
return cambio;
}
/**
*
*/
public int vaciarMaquina()
{
int devolver = total;
total = 0;
return devolver;
}
}
| true |
4f0843066be67aba8c2cfe4f2a8f308134a873cb | Java | d591342/domino-jnx | /domino-jnx-jna/src/main/java/com/hcl/domino/jna/internal/views/ViewFormatDecoder.java | UTF-8 | 15,988 | 1.828125 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* ==========================================================================
* Copyright (C) 2019-2021 HCL America, Inc. ( http://www.hcl.com/ )
* All rights reserved.
* ==========================================================================
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. You may obtain a
* copy of the License at <http://www.apache.org/licenses/LICENSE-2.0>.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
* ==========================================================================
*/
package com.hcl.domino.jna.internal.views;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import com.hcl.domino.commons.design.view.DominoViewColumnFormat;
import com.hcl.domino.commons.design.view.DominoViewFormat;
import com.hcl.domino.commons.misc.ODSTypes;
import com.hcl.domino.commons.richtext.records.MemoryStructureProxy;
import com.hcl.domino.design.format.ViewColumnFormat;
import com.hcl.domino.design.format.ViewColumnFormat2;
import com.hcl.domino.design.format.ViewColumnFormat3;
import com.hcl.domino.design.format.ViewColumnFormat4;
import com.hcl.domino.design.format.ViewColumnFormat5;
import com.hcl.domino.design.format.ViewColumnFormat6;
import com.hcl.domino.design.format.ViewTableFormat;
import com.hcl.domino.design.format.ViewTableFormat2;
import com.hcl.domino.design.format.ViewTableFormat3;
import com.hcl.domino.design.format.ViewTableFormat4;
import com.hcl.domino.misc.ViewFormatConstants;
import com.hcl.domino.richtext.RichTextConstants;
import com.hcl.domino.richtext.records.CDResource;
import com.hcl.domino.richtext.structures.MemoryStructure;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.PointerByReference;
public class ViewFormatDecoder {
public static DominoViewFormat decodeViewFormat(Pointer dataPtr, int valueLength) {
// Since it appears that ODSReadMemory is harmful on platforms we support, use a ByteBuffer for safety
ByteBuffer data = dataPtr.getByteBuffer(0, valueLength);
// TODO see how this differs when VIEW_TABLE_FORMAT.Type is Calendar
// VIEW_CALENDAR_FORMAT doesn't include a column count, which implies that VIEW_TABLE_FORMAT
// may still be present
/*
* All views have:
* - VIEW_TABLE_FORMAT (starts with VIEW_FORMAT_HEADER)
* - VIEW_COLUMN_FORMAT * colCount
* - var data * colCount
*/
DominoViewFormat result = new DominoViewFormat();
ViewTableFormat format1 = readMemory(data, ODSTypes._VIEW_TABLE_FORMAT, ViewTableFormat.class);
result.read(format1);
List<DominoViewColumnFormat> columns = new ArrayList<>();
int columnValuesIndex = 0;
// Always present
{
int vcfSize = MemoryStructureProxy.sizeOf(ViewColumnFormat.class);
ByteBuffer pPackedData = data.duplicate().order(ByteOrder.nativeOrder());
pPackedData.position(pPackedData.position()+(vcfSize * format1.getColumnCount()));
for(int i = 0; i < format1.getColumnCount(); i++) {
ViewColumnFormat tempCol = readMemory(data, ODSTypes._VIEW_COLUMN_FORMAT, ViewColumnFormat.class);
// Find the actual size with variable data and re-read
int varSize = tempCol.getItemNameLength() + tempCol.getTitleLength() + tempCol.getFormulaLength() + tempCol.getConstantValueLength();
ViewColumnFormat fullCol = MemoryStructureProxy.newStructure(ViewColumnFormat.class, varSize);
ByteBuffer fullColData = fullCol.getData();
// Write the ODS value first
fullColData.put(tempCol.getData());
byte[] varData = new byte[varSize];
pPackedData.get(varData);
fullColData.put(varData);
DominoViewColumnFormat viewCol = result.addColumn();
viewCol.read(fullCol);
columns.add(viewCol);
// Mark the column-values index now that it's knowable
if(fullCol.getConstantValueLength() == 0) {
viewCol.readColumnValuesIndex(columnValuesIndex);
columnValuesIndex++;
} else {
viewCol.readColumnValuesIndex(0xFFFF);
}
}
data.position(pPackedData.position());
}
int vtf2size = MemoryStructureProxy.sizeOf(ViewTableFormat2.class);
if(data.remaining() < vtf2size) {
return result;
}
/*
* Read FORMAT2 structures
* - VIEW_TABLE_FORMAT2
* - VIEW_COLUMN_FORMAT2 * colCount
*/
ViewTableFormat2 format2 = readMemory(data, ODSTypes._VIEW_TABLE_FORMAT2, ViewTableFormat2.class);
result.read(format2);
// In case VIEW_TABLE_FORMAT2.Length ever disagrees, increment further
data.position(data.position() + Math.max(0, format2.getLength()-vtf2size));
for(int i = 0; i < format1.getColumnCount(); i++) {
ViewColumnFormat2 col = readMemory(data, ODSTypes._VIEW_COLUMN_FORMAT2, ViewColumnFormat2.class);
if(col.getSignature() != ViewFormatConstants.VIEW_COLUMN_FORMAT_SIGNATURE2) {
throw new IllegalStateException("Read unexpected VIEW_COLUMN_FORMAT2 signature: 0x" + Integer.toHexString(col.getSignature()));
}
columns.get(i).read(col);
}
int vtf3size = MemoryStructureProxy.sizeOf(ViewTableFormat3.class);
if(data.remaining() < vtf3size) {
return result;
}
ViewTableFormat3 format3 = readMemory(data, ODSTypes._VIEW_TABLE_FORMAT3, ViewTableFormat3.class);
result.read(format3);
// In case VIEW_TABLE_FORMAT3.Length ever disagrees, increment further
data.position(data.position() + Math.max(0, format3.getLength()-vtf3size));
// Followed by variable data defined by VIEW_COLUMN_FORMAT2
for(int i = 0; i < format1.getColumnCount(); i++) {
DominoViewColumnFormat col = columns.get(i);
ViewColumnFormat2 fmt = col.getAdapter(ViewColumnFormat2.class);
int hideWhenLen = fmt.getHideWhenFormulaLength();
if(hideWhenLen > 0) {
byte[] formula = new byte[hideWhenLen];
data.get(formula);
col.readHideWhenFormula(formula);
}
int twistieLen = fmt.getTwistieResourceLength();
if(twistieLen > 0) {
ByteBuffer buf = readBuffer(data, twistieLen);
CDResource res = MemoryStructureProxy.newStructure(CDResource.class, twistieLen - MemoryStructureProxy.sizeOf(CDResource.class));
res.getData().put(buf);
col.readTwistie(res);
}
}
// Followed by VIEW_TABLE_FORMAT4 data
int vtf4size = MemoryStructureProxy.sizeOf(ViewTableFormat4.class);
if(data.remaining() < vtf4size) {
return result;
}
int format4len = Short.toUnsignedInt(data.getShort(data.position()));
ViewTableFormat4 format4 = readMemory(data, (short)-1, ViewTableFormat4.class);
result.read(format4);
// In case VIEW_TABLE_FORMAT4.Length ever disagrees, increment further
data.position(data.position() + Math.max(0, format4len-vtf4size));
// Background resource link
int cdresLen = MemoryStructureProxy.sizeOf(CDResource.class);
if(data.remaining() < 2) {
return result;
}
short sig = data.getShort(data.position());
CDResource backgroundRes = null;
if(data.hasRemaining() && sig == RichTextConstants.SIG_CD_HREF) {
// Retrieve the fixed structure to determine the full length of the record
ByteBuffer tempBuf = subBuffer(data, MemoryStructureProxy.sizeOf(CDResource.class));
CDResource res = MemoryStructureProxy.forStructure(CDResource.class, () -> tempBuf);
int len = res.getHeader().getLength();
ByteBuffer buf = readBuffer(data, len);
backgroundRes = MemoryStructureProxy.newStructure(CDResource.class, len - cdresLen);
backgroundRes.getData().put(buf);
result.readBackgroundResource(backgroundRes);
}
// Remaining parts are optional based on previous column flags
// Certainly, nothing afterward is smaller than a WORD
if(data.remaining() < 2) {
return result;
}
// VIEW_COLUMN_FORMAT3 - date/time format
for(int i = 0; i < format1.getColumnCount(); i++) {
DominoViewColumnFormat col = columns.get(i);
ViewColumnFormat2 fmt = col.getAdapter(ViewColumnFormat2.class);
if(fmt.getFlags().contains(ViewColumnFormat2.Flag3.ExtDate)) {
int len = MemoryStructureProxy.sizeOf(ViewColumnFormat3.class);
ByteBuffer tempBuf = subBuffer(data, len);
ViewColumnFormat3 tempCol = MemoryStructureProxy.forStructure(ViewColumnFormat3.class, () -> tempBuf);
if(tempCol.getSignature() != ViewFormatConstants.VIEW_COLUMN_FORMAT_SIGNATURE3) {
throw new IllegalStateException("Encountered unexpected signature when looking for VIEW_COLUMN_FORMAT3: 0x" + Integer.toHexString(tempCol.getSignature()));
}
// Re-read with variable data
int varLen = tempCol.getDateSeparator1Length() + tempCol.getDateSeparator2Length() + tempCol.getDateSeparator3Length()
+ tempCol.getTimeSeparatorLength();
ByteBuffer buf = readBuffer(data, len+varLen);
ViewColumnFormat3 col3 = MemoryStructureProxy.newStructure(ViewColumnFormat3.class, varLen);
col3.getData().put(buf);
col.read(col3);
}
}
if(data.remaining() < 2) {
return result;
}
// VIEW_COLUMN_FORMAT4 - number format
for(int i = 0; i < format1.getColumnCount(); i++) {
DominoViewColumnFormat col = columns.get(i);
ViewColumnFormat2 fmt = col.getAdapter(ViewColumnFormat2.class);
if(fmt.getFlags().contains(ViewColumnFormat2.Flag3.NumberFormat)) {
int len = MemoryStructureProxy.sizeOf(ViewColumnFormat4.class);
ByteBuffer tempBuf = subBuffer(data, len);
ViewColumnFormat4 tempCol = MemoryStructureProxy.forStructure(ViewColumnFormat4.class, () -> tempBuf);
if(tempCol.getSignature() != ViewFormatConstants.VIEW_COLUMN_FORMAT_SIGNATURE4) {
throw new IllegalStateException("Encountered unexpected signature when looking for VIEW_COLUMN_FORMAT4: 0x" + Integer.toHexString(tempCol.getSignature()));
}
// Re-read with variable data
long varLen = tempCol.getCurrencySymbolLength() + tempCol.getDecimalSymbolLength() + tempCol.getMilliSeparatorLength()
+ tempCol.getNegativeSymbolLength();
ByteBuffer buf = readBuffer(data, len+varLen);
ViewColumnFormat4 col4 = MemoryStructureProxy.newStructure(ViewColumnFormat4.class, (int)varLen);
col4.getData().put(buf);
col.read(col4);
}
}
if(data.remaining() < 2) {
return result;
}
// VIEW_COLUMN_FORMAT5 - names format
for(int i = 0; i < format1.getColumnCount(); i++) {
DominoViewColumnFormat col = columns.get(i);
ViewColumnFormat2 fmt = col.getAdapter(ViewColumnFormat2.class);
if(fmt.getFlags().contains(ViewColumnFormat2.Flag3.NamesFormat)) {
int len = MemoryStructureProxy.sizeOf(ViewColumnFormat5.class);
ByteBuffer tempBuf = subBuffer(data, len);
ViewColumnFormat5 tempCol = MemoryStructureProxy.forStructure(ViewColumnFormat5.class, () -> tempBuf);
if(tempCol.getSignature() != ViewFormatConstants.VIEW_COLUMN_FORMAT_SIGNATURE5) {
throw new IllegalStateException("Encountered unexpected signature when looking for VIEW_COLUMN_FORMAT5: 0x" + Integer.toHexString(tempCol.getSignature()));
}
// Re-read with variable data
int totalLen = tempCol.getLength();
ByteBuffer buf = readBuffer(data, totalLen);
ViewColumnFormat5 col5 = MemoryStructureProxy.newStructure(ViewColumnFormat5.class, totalLen - MemoryStructureProxy.sizeOf(ViewColumnFormat5.class));
col5.getData().put(buf);
col.read(col5);
}
}
// Shared-column aliases follow as WORD-prefixed P-strings
for(int i = 0; i < format1.getColumnCount(); i++) {
DominoViewColumnFormat col = columns.get(i);
if(col.isSharedColumn()) {
int aliasLen = Short.toUnsignedInt(data.getShort());
byte[] lmbcs = new byte[aliasLen];
data.get(lmbcs);
String alias = new String(lmbcs, Charset.forName("LMBCS")); //$NON-NLS-1$
col.readSharedColumnName(alias);
}
}
if(data.remaining() < 2) {
return result;
}
// It appears that columns may have "ghost" names here from when they _used_ to be
// shared columns
// TODO figure out if this will need to be somehow interpolated with the above when
// a true shared column followed a former one
while(data.remaining() > 1 && data.getShort(data.position()) != ViewFormatConstants.VIEW_COLUMN_FORMAT_SIGNATURE6) {
int ghostSharedColLen = Short.toUnsignedInt(data.getShort());
data.position(data.position()+ghostSharedColLen);
}
if(data.remaining() < 2) {
return result;
}
// VIEW_COLUMN_FORMAT6 - Hannover
for(int i = 0; i < format1.getColumnCount(); i++) {
DominoViewColumnFormat col = columns.get(i);
ViewColumnFormat2 fmt = col.getAdapter(ViewColumnFormat2.class);
if(fmt.getFlags().contains(ViewColumnFormat2.Flag3.ExtendedViewColFmt6)) {
int len = MemoryStructureProxy.sizeOf(ViewColumnFormat6.class);
ByteBuffer tempBuf = subBuffer(data, len);
ViewColumnFormat6 tempCol = MemoryStructureProxy.forStructure(ViewColumnFormat6.class, () -> tempBuf);
if(tempCol.getSignature() != ViewFormatConstants.VIEW_COLUMN_FORMAT_SIGNATURE6) {
throw new IllegalStateException("Encountered unexpected signature when looking for VIEW_COLUMN_FORMAT6: 0x" + Integer.toHexString(tempCol.getSignature()));
}
// Re-read with variable data
int totalLen = tempCol.getLength();
ByteBuffer buf = readBuffer(data, totalLen);
ViewColumnFormat6 col6 = MemoryStructureProxy.newStructure(ViewColumnFormat6.class, totalLen - MemoryStructureProxy.sizeOf(ViewColumnFormat6.class));
col6.getData().put(buf);
col.read(col6);
}
}
// It seems like it ends with a terminating 0 byte - possibly for padding to hit a WORD boundary
return result;
}
@SuppressWarnings("unused")
private static <T extends MemoryStructure> T readMemory(PointerByReference ppData, short odsType, Class<T> struct) {
// TODO determine if any architectures need ODSReadMemory. On x64 macOS, it seems harmful.
// Docs just say "Intel", but long predate x64. On Windows, it says it should be harmless, but
// care has to be taken on "UNIX", which is everything else.
// Additionally, not all structures here have ODS numbers
// ODSReadMemory cariant
// Memory mem = new Memory(MemoryStructureProxy.sizeOf(struct));
// NotesCAPI.get().ODSReadMemory(ppData, odsType, mem, (short)1);
// return MemoryStructureProxy.forStructure(struct, () -> mem.getByteBuffer(0, mem.size()));
// Straight-read variant
T result = MemoryStructureProxy.newStructure(struct, 0);
int len = MemoryStructureProxy.sizeOf(struct);
result.getData().put(ppData.getValue().getByteBuffer(0, len));
ppData.setValue(ppData.getValue().share(len));
return result;
}
/**
* Reads a structure from the provided ByteBuffer, incrementing its position the size of the struct.
*
* @param <T> the class of structure to read
* @param data the containing data buffer
* @param odsType the ODS type, or {@code -1} if not known
* @param struct a {@link Class} represening {@code <T>}
* @return the read structure
*/
private static <T extends MemoryStructure> T readMemory(ByteBuffer data, short odsType, Class<T> struct) {
T result = MemoryStructureProxy.newStructure(struct, 0);
int len = MemoryStructureProxy.sizeOf(struct);
byte[] bytes = new byte[len];
data.get(bytes);
result.getData().put(bytes);
return result;
}
private static ByteBuffer readBuffer(ByteBuffer buf, long len) {
ByteBuffer result = subBuffer(buf, (int)len);
buf.position(buf.position()+(int)len);
return result;
}
private static ByteBuffer subBuffer(ByteBuffer buf, int len) {
ByteBuffer tempBuf = buf.slice().order(ByteOrder.nativeOrder());
tempBuf.limit(len);
return tempBuf;
}
}
| true |
016b3fdcfed1e02c147d69d689561340aa4c421c | Java | sgalindocifpfbmoll/WordListSearch | /app/src/main/java/com/android/example/wordlistsql/WordItem.java | UTF-8 | 668 | 2.40625 | 2 | [
"Apache-2.0"
] | permissive | package com.android.example.wordlistsql;
public class WordItem {
private int mId;
private String mWord;
private String definition;
public WordItem() {
}
//<editor-fold desc="Getters and Setters">
public int getmId() {
return mId;
}
public void setmId(int mId) {
this.mId = mId;
}
public String getmWord() {
return mWord;
}
public void setmWord(String mWord) {
this.mWord = mWord;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
//</editor-fold>
}
| true |
725db192b3cf4b233e892044fa9af1fb860de5dc | Java | akash-gupta-146/IPSAA-v2.0 | /src/main/java/com/synlabs/ipsaa/jpa/ZoneRepository.java | UTF-8 | 277 | 1.945313 | 2 | [] | no_license | package com.synlabs.ipsaa.jpa;
import com.synlabs.ipsaa.entity.center.Zone;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ZoneRepository extends JpaRepository<Zone, Long>
{
Zone findOneByName(String zone);
int countByName(String name);
}
| true |
59db639569d64fd5c7a3a242e6661928ee7ac107 | Java | lautit/elt_training | /Java/evaluacion_java_tejerina/src/edu/evalucion/java/utils/PedidoUtils.java | UTF-8 | 1,696 | 3.078125 | 3 | [
"MIT"
] | permissive | package edu.evalucion.java.utils;
import java.sql.Date;
import java.util.Random;
import edu.evalucion.java.dao.GestorDePedidos;
import edu.evalucion.java.dao.exceptions.GestorDePedidosException;
import edu.evalucion.java.objects.ItemPedido;
import edu.evalucion.java.objects.Pedido;
public class PedidoUtils {
private static final String estado1 = "Pendiente";
private static final String estado2 = "Procesado";
private static final String estado3 = "Entregado";
private GestorDePedidos gestorDePedidos;
public PedidoUtils(GestorDePedidos gestorDePedidos) {
this.gestorDePedidos = gestorDePedidos;
}
public Pedido popular() {
Pedido pedido = new Pedido(estado(), new Date(new java.util.Date().getTime()));
try {
for(int i = cantidad(); i > 0; i--) {
ItemPedido item = gestorDePedidos.recuperarItem(producto());
item.setCantidad(cantidad());
pedido.addItem(item);
}
} catch (GestorDePedidosException e) {
e.printStackTrace();
}
System.out.println("[MAIN] Populando pedido");
System.out.println(pedido.toString());
System.out.println("");
return pedido;
}
private String estado() {
Random r = new Random();
int i = Math.abs(r.nextInt()%3);
switch (i) {
case 0:
return estado1;
case 1:
return estado2;
case 2:
return estado3;
}
return estado1;
}
private Integer producto() {
Random r = new Random();
return Math.abs(r.nextInt()%20) + 1;
}
private Integer cantidad() {
Random r = new Random();
return Math.abs(r.nextInt()%10) + 1;
}
}
| true |
f8a7e804dfa24c7aff0ab8cfe5fbec26167eedc7 | Java | 4AAAA/JavaDemo | /src/dahuasjms/strategy/refact2/CashContext.java | UTF-8 | 1,051 | 3.390625 | 3 | [] | no_license | package dahuasjms.strategy.refact2;
import dahuasjms.strategy.refact2.impl.CashNormal;
import dahuasjms.strategy.refact2.impl.CashRebate;
import dahuasjms.strategy.refact2.impl.CashReturn;
/**
* 策略模式-上下文
* 结合简单工厂模式创建对象,把客户端选择对象的switch语句后移
* @author Macx
*
*/
public class CashContext {
/**
* 声明策略对象
*/
private CashSuper cs;
/**
* 构造方法,传入具体收费策略
* @param cashSuper
*/
public CashContext(String type) {
switch (type) {
case "正常收费":
this.cs = new CashNormal();
break;
case "满300返100":
this.cs = new CashReturn("300", "100");
break;
case "8折":
this.cs = new CashRebate("0.8");
break;
default:
break;
}
/**
* 简单工厂,目前这种做法还有一个缺陷,还是使用了switch,如果新增一个type,又必须改语句,后期使用注解和反射可以解决。
*/
}
public double getResult(double money) {
return cs.acceptCash(money);
}
}
| true |
99e18c6b5c2a6741a9e4ae081cf32dbe38f18a45 | Java | hjd7893git/idea_web | /src/com/util/Id.java | UTF-8 | 234 | 2.265625 | 2 | [] | no_license | package com.util;
public final class Id {
private static String username;
public static int id=1;
public static String getUsername() {
return username;
}
public static void setUsername(String user) {
username = user;
}
}
| true |
ed83b735750361bbd4db7fb9626b51cc883ae744 | Java | sander-adhese/prebid-server-java | /src/test/java/org/prebid/server/validation/ResponseBidValidatorTest.java | UTF-8 | 4,568 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | package org.prebid.server.validation;
import com.iab.openrtb.response.Bid;
import org.junit.Before;
import org.junit.Test;
import org.prebid.server.bidder.model.BidderBid;
import org.prebid.server.proto.openrtb.ext.response.BidType;
import org.prebid.server.validation.model.ValidationResult;
import java.math.BigDecimal;
import java.util.function.Function;
import static java.util.function.Function.identity;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class ResponseBidValidatorTest {
private ResponseBidValidator responseBidValidator;
@Before
public void setUp() {
responseBidValidator = new ResponseBidValidator();
}
@Test
public void validateShouldFailedIfBidderBidCurrencyIsIncorrect() {
assertThatIllegalArgumentException().isThrownBy(() ->
responseBidValidator.validate(BidderBid.of(
Bid.builder()
.id("bidId1")
.impid("impId1")
.crid("crid1")
.price(BigDecimal.ONE).build(),
null,
"USDD")));
}
@Test
public void validateShouldFailedIfMissingBid() {
final ValidationResult result = responseBidValidator.validate(BidderBid.of(null, null, "USD"));
assertThat(result.getErrors()).hasSize(1)
.containsOnly("Empty bid object submitted.");
}
@Test
public void validateShouldFailedIfBidHasNoId() {
final ValidationResult result = responseBidValidator.validate(givenBid(builder -> builder.id(null)));
assertThat(result.getErrors()).hasSize(1)
.containsOnly("Bid missing required field 'id'");
}
@Test
public void validateShouldFailedIfBidHasNoImpId() {
final ValidationResult result = responseBidValidator.validate(givenBid(builder -> builder.impid(null)));
assertThat(result.getErrors()).hasSize(1)
.containsOnly("Bid \"bidId1\" missing required field 'impid'");
}
@Test
public void validateShouldFailedIfBidHasNoPrice() {
final ValidationResult result = responseBidValidator.validate(givenBid(builder -> builder.price(null)));
assertThat(result.getErrors()).hasSize(1)
.containsOnly("Bid \"bidId1\" does not contain a 'price'");
}
@Test
public void validateShouldFailedIfBidHasNegativePrice() {
final ValidationResult result = responseBidValidator.validate(givenBid(builder -> builder.price(
BigDecimal.valueOf(-1))));
assertThat(result.getErrors()).hasSize(1)
.containsOnly("Bid \"bidId1\" `price `has negative value");
}
@Test
public void validateShouldFailedIfNonDealBidHasZeroPrice() {
final ValidationResult result = responseBidValidator.validate(givenBid(builder -> builder.price(
BigDecimal.valueOf(0))));
assertThat(result.getErrors()).hasSize(1)
.containsOnly("Non deal bid \"bidId1\" has 0 price");
}
@Test
public void validateShouldSuccessForDealZeroPriceBid() {
final ValidationResult result = responseBidValidator.validate(givenBid(builder -> builder.price(
BigDecimal.valueOf(0)).dealid("dealId")));
assertThat(result.hasErrors()).isFalse();
}
@Test
public void validateShouldFailedIfBidHasNoCrid() {
final ValidationResult result = responseBidValidator.validate(givenBid(builder -> builder.crid(null)));
assertThat(result.getErrors()).hasSize(1)
.containsOnly("Bid \"bidId1\" missing creative ID");
}
@Test
public void validateShouldReturnSuccessfulResultForValidBid() {
final ValidationResult result = responseBidValidator.validate(givenBid(identity()));
assertThat(result.hasErrors()).isFalse();
}
private static BidderBid givenBid(Function<Bid.BidBuilder, Bid.BidBuilder> bidCustomizer, BidType mediaType) {
final Bid.BidBuilder bidBuilder = Bid.builder()
.id("bidId1")
.impid("impId1")
.crid("crid1")
.price(BigDecimal.ONE);
return BidderBid.of(bidCustomizer.apply(bidBuilder).build(), mediaType, "USD");
}
private static BidderBid givenBid(Function<Bid.BidBuilder, Bid.BidBuilder> bidCustomizer) {
return givenBid(bidCustomizer, null);
}
}
| true |
bb612b142d232b53fa2da8d99e28e28cd074cdfd | Java | AraxieMR/SimplePetAPI | /src/main/java/com/manheim/apprenticeship/service/PetsService.java | UTF-8 | 1,680 | 2.515625 | 3 | [] | no_license | package com.manheim.apprenticeship.service;
import com.manheim.apprenticeship.dao.model.Human;
import com.manheim.apprenticeship.dao.model.Pets;
import com.manheim.apprenticeship.dao.repository.PetsRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PetsService {
private Logger LOG = LoggerFactory.getLogger(PetsService.class);
@Autowired
private PetsRepository petsRepository;
public List<Pets> getAllPets() {
LOG.info("Finding all the pets");
return petsRepository.findAll();
}
public void createAPet(Pets pet) {
LOG.info("Creating a pet");
petsRepository.save(pet);
}
public void updateAPet(Pets dragon, String name) {
LOG.info("Finding a pet by name");
Pets wolfyInDB = petsRepository.findByName(name);
wolfyInDB.setName(dragon.getName());
wolfyInDB.setBreed(dragon.getBreed());
wolfyInDB.setColor(dragon.getColor());
petsRepository.save(wolfyInDB);
}
public Pets findById(int petId) {
return petsRepository.findById(petId);
}
public Pets findByHumanId(int humanId) {
LOG.info(humanId + "");
return petsRepository.findByHumanId(humanId);
}
public void assignHumanToPet(Pets pet, Human foundHuman) {
pet.setHuman(foundHuman);
petsRepository.save(pet);
}
public void deleteById(int id) {
Pets pet = findByHumanId(id);
if (pet != null)
petsRepository.delete(pet);//need
}
}
| true |
cbfc2d20e31de0348730722478bcac296703c188 | Java | stbland/stbland | /phonebook-gwt/trunk/src/main/java/org/stbland/phonebookgwt/server/PersonServiceImpl.java | UTF-8 | 2,520 | 2.671875 | 3 | [] | no_license | package org.stbland.phonebookgwt.server;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.stbland.phonebookgwt.bean.PersonDto;
import org.stbland.phonebookgwt.client.service.PersonService;
import org.stbland.phonebookgwt.shared.logger.Logger;
import org.stbland.phonebookgwt.shared.logger.LoggerFactory;
@SuppressWarnings("serial")
public class PersonServiceImpl extends AbtractService implements PersonService {
private Logger logger = LoggerFactory.getLogger(PersonServiceImpl.class);
public AbstractList<PersonDto> findAll() {
logger.info("findAll");
AbstractList<PersonDto> list = new ArrayList<PersonDto>(2);
list.add(new PersonDto("Stéphane", "BEAUFORT"));
list.add(new PersonDto("Christian", "KIEHL"));
list.add(new PersonDto("Christophe", "ANTOINE"));
list.add(new PersonDto("Alain", "BARADEL"));
return list;
}
private boolean isFullNameLike(PersonDto person, String fullNameLike) {
return isFullNameLike(person.getFullName(), fullNameLike)
|| isFullNameLike(
person.getLastName() + " " + person.getFirstName(),
fullNameLike);
}
private boolean isFullNameLike(String fullName, String fullNameLike) {
return fullName.startsWith(fullNameLike);
}
public AbstractList<PersonDto> findSuggestions(String fullNameLike,
int limit) {
logger.info("findSuggestions (fullNameLike: " + fullNameLike
+ ", limit: " + Integer.toString(limit));
final List<PersonDto> dtoList = findAll();
AbstractList<PersonDto> newSuggestions = new ArrayList<PersonDto>(limit);
PersonDto dto;
for (Iterator<PersonDto> dtoIterator = dtoList.iterator(); dtoIterator
.hasNext();) {
dto = dtoIterator.next();
if (isFullNameLike(dto, fullNameLike)) {
newSuggestions.add(dto);
if (newSuggestions.size() == limit) {
break;
}
}
}
logger.info("newSuggestions.size: " + newSuggestions.size());
return newSuggestions;
}
public PersonDto find(String firstName, String lastName) {
logger.info("find (firstName: " + firstName + ", lastName: " + lastName);
final List<PersonDto> dtoList = findAll();
PersonDto dto;
for (Iterator<PersonDto> dtoIterator = dtoList.iterator(); dtoIterator
.hasNext();) {
dto = dtoIterator.next();
if (dto.getFirstName().equals(firstName)
&& dto.getLastName().equals(lastName)) {
return dto;
}
}
return null;
}
}
| true |
9880a4122501b6c7cbffc86be9e397972c30dbd7 | Java | zazilibarra/Herencia-y-Polimorfismo | /EjercicioPromedios/Planeta.java | UTF-8 | 472 | 2.734375 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.Iterator;
public class Planeta
{
private ArrayList<Pais>paises;
public Planeta()
{
paises = new ArrayList<Pais>();
}
public void añadePais(Pais p)
{
paises.add(p);
}
public float calculaPromHabitantes()
{
Pais[] arrPaises = new Pais[paises.size()];
arrPaises = paises.toArray(arrPaises);
return Utileria.calculaPromedio(arrPaises);
}
}
| true |
845221c5f37bc031faca698ebb075cd447ec7ce4 | Java | vandana00raj/jenkdemo | /jenksdemo/src/main/java/com/fiserv/controller/democontroller.java | UTF-8 | 138 | 1.6875 | 2 | [] | no_license | package com.fiserv.controller;
public class democontroller {
public void display() {
System.out.println("Welcome to Jenkins!");
}
}
| true |
9a529e8b8efe82cfda2b42db861bd9cc4b87b5c5 | Java | whatafree/JCoffee | /benchmark/bigclonebenchdata_completed/18991846.java | UTF-8 | 1,218 | 3.09375 | 3 | [] | no_license |
class c18991846 {
public static void copyFile(File oldFile, File newFile) throws Exception {
newFile.getParentFile().mkdirs();
newFile.createNewFile();
FileChannel srcChannel =(FileChannel)(Object) (new FileInputStream(oldFile).getChannel());
FileChannel dstChannel =(FileChannel)(Object) (new FileOutputStream(newFile).getChannel());
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close();
dstChannel.close();
}
}
// Code below this line has been added to remove errors
class MyHelperClass {
public MyHelperClass mkdirs(){ return null; }}
class File {
public MyHelperClass createNewFile(){ return null; }
public MyHelperClass getParentFile(){ return null; }}
class FileChannel {
public MyHelperClass transferFrom(FileChannel o0, int o1, MyHelperClass o2){ return null; }
public MyHelperClass size(){ return null; }
public MyHelperClass close(){ return null; }}
class FileInputStream {
FileInputStream(){}
FileInputStream(File o0){}
public MyHelperClass getChannel(){ return null; }}
class FileOutputStream {
FileOutputStream(){}
FileOutputStream(File o0){}
public MyHelperClass getChannel(){ return null; }}
| true |
51d59a187cca6e97fd4a399c6aff16e9f567bb68 | Java | vtinmetrics/SecureEdges | /SecureEdges2/src/br/com/secureedges/testes/Tipo_DispositivoDAOTeste.java | ISO-8859-1 | 1,635 | 2.359375 | 2 | [] | no_license | package br.com.secureedges.testes;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import br.com.secureedges.core.dao.Tipo_DispositivoDAO;
import br.com.secureedges.domain.Dispositivo;
import br.com.secureedges.domain.EntidadeDominio;
import br.com.secureedges.domain.Tipo_Dispositivo;
public class Tipo_DispositivoDAOTeste {
@Test
public void salvar() throws SQLException {
Tipo_Dispositivo tipo_Dispositivo = new Tipo_Dispositivo();
tipo_Dispositivo.setDescricao("iluminao");
Tipo_DispositivoDAO dao = new Tipo_DispositivoDAO();
dao.Salvar(tipo_Dispositivo);
}
@Test
@Ignore
public void editar() throws SQLException {
Tipo_Dispositivo tipo_Dispositivo = new Tipo_Dispositivo();
tipo_Dispositivo.setDescricao("Temperatura");
tipo_Dispositivo.setCodigo(4L);
Tipo_DispositivoDAO dao = new Tipo_DispositivoDAO();
dao.Editar(tipo_Dispositivo);
}
@Test
public void listar() {
List<EntidadeDominio> lista = new ArrayList<>();
Tipo_DispositivoDAO dao = new Tipo_DispositivoDAO();
lista = dao.listar();
System.out.println(lista);
}
public void testeBusca() {
Tipo_DispositivoDAO dao = new Tipo_DispositivoDAO();
Tipo_Dispositivo tipo = (Tipo_Dispositivo) dao.buscarPorCodigo(4L);
System.out.println(tipo.getDescricao());
}
@Test
public void excluir() {
Tipo_DispositivoDAO dao = new Tipo_DispositivoDAO();
Tipo_Dispositivo tipo_Dispositivo = (Tipo_Dispositivo) dao.buscarPorCodigo(4L);
dao.Excluir(tipo_Dispositivo);
}
}
| true |
cb8b80e6835da00e740c110e8ba49d5892902b33 | Java | activateslikestacos/Banana | /src/us/thetaco/banana/commands/ToggleStaffModeCommand.java | UTF-8 | 1,785 | 2.828125 | 3 | [] | no_license | package us.thetaco.banana.commands;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import us.thetaco.banana.Banana;
import us.thetaco.banana.utils.Lang;
public class ToggleStaffModeCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (!(sender instanceof Player)) {
// this will run if the sender is not a player
return new ToggleStaffModeCommandConsole().runToggleStaffModeCommand(sender, args);
}
// this will run if the sender is a player
Player player = (Player) sender;
if (!player.hasPermission("banana.commands.togglestaffmode")) {
player.sendMessage(Lang.NO_PERMISSIONS.toString());
return true;
}
// check if the server is in staff mode.. if it isn't, kick all players who aren't in staff mode, and prevent them
// from joining
if (!Banana.isStaffMode()) {
// first start by setting the server to staff mode
Banana.setStaffMode(true);
// kick all non-staff players
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (!Banana.getPlayerCache().isStaff(p.getUniqueId().toString())) {
p.kickPlayer(Lang.STAFF_MODE_KICK_MESSAGE.toString());
}
}
// message that staff mode has been enabled to all staff members!
Bukkit.broadcastMessage(Lang.STAFF_MODE_ENABLED_BROADCAST.toString());
return true;
} else {
// disable staff mode and notify staff members
Banana.setStaffMode(false);
// announce it's disabling
Bukkit.broadcastMessage(Lang.STAFF_MODE_DISABLED_BROADCAST.toString());
return true;
}
}
}
| true |
72b2f0ab933554dcf2e54826919bc1532100942e | Java | helospark/light-di | /src/main/java/com/helospark/lightdi/properties/converter/LongPropertyConverter.java | UTF-8 | 291 | 2.109375 | 2 | [
"MIT"
] | permissive | package com.helospark.lightdi.properties.converter;
import com.helospark.lightdi.properties.PropertyConverter;
public class LongPropertyConverter implements PropertyConverter<Long> {
@Override
public Long convert(String property) {
return Long.valueOf(property);
}
}
| true |
112eb1466f7c4d9f6fa94c6c1f018bd3b1a780cf | Java | rizalkusumajatinugroho/SimpleMovieApp | /app/src/main/java/com/smu/simplemovieapp/view/DownloadService.java | UTF-8 | 5,356 | 2.234375 | 2 | [] | no_license | package com.smu.simplemovieapp.view;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.smu.simplemovieapp.db.DA_movie_detail;
import com.smu.simplemovieapp.db.DA_movie_header;
import com.smu.simplemovieapp.db.DA_search_history;
import com.smu.simplemovieapp.model.MovieDetail;
import com.smu.simplemovieapp.model.MovieHeader;
import com.smu.simplemovieapp.model.MovieResource;
import com.smu.simplemovieapp.model.SearchHistory;
import com.smu.simplemovieapp.rest.ServiceGenerator;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by sapuser on 12/9/2018.
*/
public class DownloadService extends Service {
private static final String DEBUG_TAG = "DownloadServ";
private DownloaderTask downloaderTask;
private DA_search_history da_search_history;
private DA_movie_header da_movie_header;
private DA_movie_detail da_movie_detail;
private List<MovieHeader> movies = new ArrayList<>();
private SearchHistory searchHistory = new SearchHistory();
private boolean isRunning = true;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
da_search_history = new DA_search_history(getBaseContext());
da_movie_header = new DA_movie_header(getBaseContext());
da_movie_detail = new DA_movie_detail(getBaseContext());
downloaderTask = new DownloaderTask();
downloaderTask.execute();
isRunning = true;
return Service.START_NOT_STICKY;
}
@Override
public void onDestroy() {
if (downloaderTask !=null) {
if(!downloaderTask.isCancelled()) {
downloaderTask.cancel(true);
}
}
isRunning = false;
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class DownloaderTask extends AsyncTask<String, Void, Boolean> {
private static final String DEBUG_TAG = "DownloadService";
@Override
protected Boolean doInBackground(String... params) {
initiateDownload();
return true;
}
public void initiateDownload(){
if (isRunning){
searchHistory = da_search_history.getValue();
Log.d(DEBUG_TAG, searchHistory.getQuery() + " ; page : " + searchHistory.getPage() + "; numpage : " + searchHistory.getNumPage());
if (searchHistory.getQuery() != null && !searchHistory.getQuery().equals("")) {
new ServiceGenerator().getMovie(searchHistory.getQuery(), Integer.parseInt(searchHistory.getPage()), new Callback<MovieResource>() {
@Override
public void onResponse(Call<MovieResource> call, Response<MovieResource> response) {
Log.d(DEBUG_TAG, searchHistory.getPage() + "");
movies = response.body().getSearch();
da_movie_header.insert_or_replace(movies);
getDetailMovie(0);
}
@Override
public void onFailure(Call<MovieResource> call, Throwable t) {
}
});
}else {
initiateDownload();
}
}
}
public void getDetailMovie(final int index){
if (movies != null && movies.get(index) != null){
new ServiceGenerator().getDetail(movies.get(index).getImdbID(), new Callback<MovieDetail>() {
@Override
public void onResponse(Call<MovieDetail> call, Response<MovieDetail> response) {
int insertedDetail = da_movie_detail.insert_or_replace(response.body());
Log.d(DEBUG_TAG, "detail : " + insertedDetail + " ; title : " + response.body().getTitle());
if (index == movies.size()-1){
String numPages = searchHistory.getNumPage();
String page = searchHistory.getPage();
if (page.equals(numPages)){
da_search_history.updateFlagDone(searchHistory.getQuery());
}else{
int pagePlus = Integer.parseInt(searchHistory.getPage()) + 1;
searchHistory.setPage(String.valueOf(pagePlus));
da_search_history.insert_or_replace(searchHistory);
}
initiateDownload();
}else{
int indexPlus = index + 1;
getDetailMovie(indexPlus);
}
}
@Override
public void onFailure(Call<MovieDetail> call, Throwable t) {
}
});
}
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
}
| true |
60b95e6a25a43aa6c4e0ae2de926c04666d1d422 | Java | raguiarperez/Boletin-17 | /Boletin17_1/src/boletin17_1/Boletin17_1.java | UTF-8 | 326 | 2.09375 | 2 | [] | no_license |
package boletin17_1;
/**
*
* @author raguiarperez
*/
public class Boletin17_1 {
public static void main(String[] args) {
Gato gat=new Gato();
Mamífero mam=new Mamífero();
Papagaio pap=new Papagaio();
gat.caminar();
gat.nadar();
pap.caminar();
}
}
| true |
4a81860ded6dcf76bbc0521cc5ad6b652aca032a | Java | joel199583/EA103G4 | /src/listeners/BookshopInitializer.java | UTF-8 | 7,191 | 2.140625 | 2 | [] | no_license | package listeners;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;
import com.book.model.BookDAO;
import com.book.model.BookDAOImpl;
import com.book.model.BookService;
import com.bookpic.model.BookPicDAO;
import com.bookpic.model.BookPicDAOImpl;
import com.bookpic.model.BookPicService;
import com.category.model.CategoryDAO;
import com.category.model.CategoryDAOImpl;
import com.category.model.CategoryService;
import com.language.model.LanguageDAO;
import com.language.model.LanguageDAO_interface;
import com.language.model.LanguageService;
import com.promo.model.PromoDAO;
import com.promo.model.PromoDAOImpl;
import com.promo.model.PromoService;
import com.promodetail.model.PromoDetailDAO;
import com.promodetail.model.PromoDetailDAOImpl;
import com.promodetail.model.PromoDetailService;
import com.publishers.model.PublisherDAO;
import com.publishers.model.PublisherDAO_interface;
import com.publishers.model.PublisherService;
import timers.PromoTimerTask;
import timers.StatisticsTimerTask;
import tools.JedisUtil;
@WebListener
public class BookshopInitializer implements ServletContextListener {
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
private ScheduledExecutorService promoTimerService;
private ScheduledExecutorService statisticsTimerService;
public void contextInitialized(ServletContextEvent sce) {
DataSource dataSource = getDataSource();
ServletContext context = sce.getServletContext();
BookDAO bookDAO = new BookDAOImpl(dataSource);
BookService bookService = new BookService(bookDAO);
context.setAttribute("bookService", bookService);
CategoryDAO categoryDAO = new CategoryDAOImpl(dataSource);
context.setAttribute("categoryService", new CategoryService(categoryDAO));
BookPicDAO bookPicDAO = new BookPicDAOImpl(dataSource);
context.setAttribute("bookPicService", new BookPicService(bookPicDAO));
PromoDAO promoDAO = new PromoDAOImpl(dataSource);
PromoService promoService = new PromoService(promoDAO);
context.setAttribute("promoService", promoService);
PromoDetailDAO promoDetailDAO = new PromoDetailDAOImpl(dataSource);
PromoDetailService promoDetailService = new PromoDetailService(promoDetailDAO);
context.setAttribute("promoDetailService", promoDetailService);
PublisherDAO_interface publisherDAO_interface = new PublisherDAO(dataSource);
context.setAttribute("publisherService", new PublisherService(publisherDAO_interface));
LanguageDAO_interface languageDAO_interface = new LanguageDAO(dataSource);
context.setAttribute("languageService", new LanguageService(languageDAO_interface));
startPromoTimer(promoService, promoDetailService, bookService);
startStatisticsTimer(bookService);
}
private DataSource getDataSource() {
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
return (DataSource) envContext.lookup("jdbc/bookshop");
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
private void startPromoTimer(PromoService promoService, PromoDetailService promoDetailService,
BookService bookService) {
// 啟動當個小時的0分0秒
Calendar c = Calendar.getInstance();
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
// 程式啟動起算到第一輪執行之間的延遲時間
long initDelay = (c.getTimeInMillis() % 1800000 + 1800000) - (System.currentTimeMillis() % 1800000);
// 測試用啟動初始更新(執行一次)
// ScheduledExecutorService startUpService = Executors.newSingleThreadScheduledExecutor();
// Date cur = new Date(System.currentTimeMillis());
// System.out.println("促銷事件測試用初始啟動更新: " + FORMATTER.format(cur));
// startUpService.schedule(new PromoTimerTask(promoService, promoDetailService, bookService), 0,
// TimeUnit.MILLISECONDS);
// 啟動起算下一輪時間開始每30分一次
promoTimerService = Executors.newSingleThreadScheduledExecutor();
Date nextRun = new Date(initDelay + System.currentTimeMillis());
System.out.println("促銷事件更新器啟動時間: " + FORMATTER.format(nextRun));
promoTimerService.scheduleAtFixedRate(new PromoTimerTask(promoService, promoDetailService, bookService),
initDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);
}
private void startStatisticsTimer(BookService bookService) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long current = System.currentTimeMillis();// 當前時間毫秒數
long zero = c.getTimeInMillis();// 今天零點零分零秒的毫秒數
long twelve = zero + 24 * 60 * 60 * 1000 - 1;// 今天23點59分59秒的毫秒數
// 程式啟動起算到第一輪執行之間的延遲時間
long initDelay = twelve - current;
// 測試用啟動初始更新(執行一次)
// ScheduledExecutorService startUpService = Executors.newSingleThreadScheduledExecutor();
// Date cur = new Date(System.currentTimeMillis());
// System.out.println("瀏覽/銷售統計測試用初始啟動更新: " + FORMATTER.format(cur));
// startUpService.schedule(new StatisticsTimerTask(bookService), 0,
// TimeUnit.MILLISECONDS);
// 啟動起算下一輪時間開始每天23:59:59執行一次
statisticsTimerService = Executors.newSingleThreadScheduledExecutor();
Date nextRun = new Date(initDelay + System.currentTimeMillis());
System.out.println("瀏覽/銷售統計更新器下一輪執行時間: " + FORMATTER.format(nextRun));
statisticsTimerService.scheduleAtFixedRate(new StatisticsTimerTask(bookService), initDelay, 1000 * 60 * 60 * 24,
TimeUnit.MILLISECONDS);
}
public void contextDestroyed(ServletContextEvent sce) {
// 關閉兩個Timer
promoTimerService.shutdownNow();
try {
while (!promoTimerService.awaitTermination(2, TimeUnit.SECONDS)) {
System.out.println("promoTimerService執行緒池未關閉");
}
} catch (InterruptedException e) {
System.out.println("promoTimerService執行緒池awaitTermination出例外");
e.printStackTrace();
}
System.out.println("promoTimerService執行緒池關閉");
statisticsTimerService.shutdownNow();
try {
while (!statisticsTimerService.awaitTermination(2, TimeUnit.SECONDS)) {
System.out.println("statisticsTimerService執行緒池未關閉");
}
} catch (InterruptedException e) {
System.out.println("statisticsTimerService執行緒池awaitTermination出例外");
e.printStackTrace();
}
System.out.println("statisticsTimerService執行緒池關閉");
// 關閉Jedis連線池,避免commons-pool-evictor-thread不能關閉
JedisUtil.shutdownJedisPool();
}
}
| true |
7a5d8d99946fa96798526918e22b541a7731a860 | Java | gokulnarayanan95/FoodWasteManagement | /FoodWasteManagement/FoodWasteManagement/src/userinterface/Restaurant/SearchUpdateFoodItemJPanel.java | UTF-8 | 13,614 | 2.234375 | 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 userinterface.Restaurant;
import Business.Enterprise.RestaurantEnterprise;
import Business.FoodItem.FoodItem;
import Business.FoodItem.FoodItemCatalog;
import java.awt.CardLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
*
* @author sachinsenthilkumar
*/
public class SearchUpdateFoodItemJPanel extends javax.swing.JPanel {
private JPanel userProcessContainer;
private FoodItem fooditem;
private RestaurantEnterprise restaurantEnterprise ;
/**
* Creates new form SearchUpdateFoodItemJPanel
*/
public SearchUpdateFoodItemJPanel(JPanel userProcessContainer, RestaurantEnterprise restaurantEnterprise , FoodItem fooditem) {
initComponents();
this.userProcessContainer=userProcessContainer;
this.fooditem=fooditem;
txtFoodName.setEnabled(false);
txtFoodPrice.setEnabled(false);
txtFoodType.setEnabled(false);
txtFoodCuisine.setEnabled(false);
txtFoodID.setEnabled(false);
btnSave.setEnabled(false);
btnUpdate.setEnabled(true);
txtFoodName.setText(fooditem.getFoodName());
txtFoodCuisine.setText(fooditem.getCuisine());
txtFoodID.setText(String.valueOf(fooditem.getFoodId()));
txtFoodPrice.setText(String.valueOf(fooditem.getFoodPrice()));
txtFoodType.setText(fooditem.getType());
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtFoodID = new javax.swing.JTextField();
txtFoodName = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtFoodType = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtFoodCuisine = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtFoodPrice = new javax.swing.JTextField();
btnBack = new javax.swing.JButton();
btnUpdate = new javax.swing.JButton();
btnSave = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
setBackground(new java.awt.Color(0, 0, 204));
setForeground(new java.awt.Color(0, 153, 51));
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Food ID:");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Food Name:");
txtFoodName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtFoodNameActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Food Type");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Food Cuisine:");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Food Price:");
btnBack.setBackground(new java.awt.Color(0, 0, 0));
btnBack.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
btnBack.setForeground(new java.awt.Color(255, 255, 255));
btnBack.setText("Back");
btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBackActionPerformed(evt);
}
});
btnUpdate.setBackground(new java.awt.Color(0, 0, 0));
btnUpdate.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
btnUpdate.setForeground(new java.awt.Color(255, 255, 255));
btnUpdate.setText("Update");
btnUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUpdateActionPerformed(evt);
}
});
btnSave.setBackground(new java.awt.Color(0, 0, 0));
btnSave.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
btnSave.setForeground(new java.awt.Color(255, 255, 255));
btnSave.setText("Save");
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("Update Food Item");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(187, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtFoodName, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(262, 262, 262)
.addComponent(txtFoodID, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtFoodType, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtFoodCuisine, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel2)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnUpdate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtFoodPrice, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
.addComponent(btnSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(350, 350, 350))
.addGroup(layout.createSequentialGroup()
.addComponent(btnBack, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(327, 327, 327)
.addComponent(jLabel6)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel6)
.addComponent(btnBack, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtFoodID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtFoodName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtFoodType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtFoodCuisine, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtFoodPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(45, 45, 45)
.addComponent(btnUpdate)
.addGap(34, 34, 34)
.addComponent(btnSave)
.addGap(223, 223, 223))
);
}// </editor-fold>//GEN-END:initComponents
private void txtFoodNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtFoodNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtFoodNameActionPerformed
private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
// TODO add your handling code here:
userProcessContainer.remove(this);
CardLayout layout = (CardLayout)userProcessContainer.getLayout();
layout.previous(userProcessContainer);
}//GEN-LAST:event_btnBackActionPerformed
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
// TODO add your handling code here:
txtFoodName.setEnabled(true);
txtFoodPrice.setEnabled(true);
txtFoodCuisine.setEnabled(true);
txtFoodType.setEnabled(true);
txtFoodID.setEnabled(false);
btnSave.setEnabled(true);
}//GEN-LAST:event_btnUpdateActionPerformed
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
// TODO add your handling code here:
String FoodName = txtFoodName.getText();
String FoodPrice = txtFoodPrice.getText();
String FoodCuisine = txtFoodCuisine.getText();
String FoodType = txtFoodType.getText();
if((FoodName.equals("") || !(FoodName.matches("[a-zA-Z]+")))||
(FoodCuisine.equals("") || !(FoodCuisine.matches("[a-zA-Z]+"))||
(FoodPrice.equals("") || !(FoodPrice.matches("[0-9]+(?:\\.[0-9]+)?")))||
(FoodType.equals(""))))
{
JOptionPane.showMessageDialog(null,"Invalid Data");}
else{
fooditem.setFoodName(FoodName);
fooditem.setCuisine(FoodCuisine);
fooditem.setType(FoodType);
fooditem.setFoodPrice(Integer.parseInt(FoodPrice));
JOptionPane.showMessageDialog(null, "Product Updated Successfully");
txtFoodName.setText("");
txtFoodCuisine.setText("");
txtFoodPrice.setText("");
txtFoodType.setText("");
}
}//GEN-LAST:event_btnSaveActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnBack;
private javax.swing.JButton btnSave;
private javax.swing.JButton btnUpdate;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JTextField txtFoodCuisine;
private javax.swing.JTextField txtFoodID;
private javax.swing.JTextField txtFoodName;
private javax.swing.JTextField txtFoodPrice;
private javax.swing.JTextField txtFoodType;
// End of variables declaration//GEN-END:variables
}
| true |
1f22370818ddcbdb251dc6304413364854ea8a28 | Java | Lehmakomm/Snake | /src/ee/itcollege/snake/game/GameField.java | UTF-8 | 1,642 | 3.0625 | 3 | [] | no_license | package ee.itcollege.snake.game;
import java.util.Timer;
import java.util.TimerTask;
import ee.itcollege.snake.elements.Apple;
import ee.itcollege.snake.elements.Snake;
import ee.itcollege.snake.lib.CollisionDetector;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
/**
* The main game object that holds the gamefield
*/
public class GameField extends Pane {
private Snake snake = new Snake();
private Apple apple;
private GameBorder gameBorder;
private Timer timer = new Timer();
private Label pointsLabel = new Label("punktid siia!");
public GameField() {
getChildren().add(snake);
pointsLabel.setLayoutX(100);
pointsLabel.setLayoutY(100);
getChildren().add(pointsLabel);
}
// starts the game
public void windowReady() {
gameBorder = new GameBorder(getWidth(), getHeight());
getChildren().add(gameBorder);
createAppleAtRandomPlace();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
tick();
}
}, 100, 100);
}
public void createAppleAtRandomPlace() {
apple = new Apple(Math.random() * getWidth(), Math.random() * getHeight());
getChildren().add(apple);
}
public void tick() {
snake.move();
if (CollisionDetector.collide(snake.getHead(), apple)) {
Platform.runLater(() -> {
snake.eat(apple);
getChildren().remove(apple);
createAppleAtRandomPlace();
});
}
if (snake.collidesItself() || !CollisionDetector.collide(snake.getHead(), gameBorder)) {
gameOver();
}
}
public Snake getSnake() {
return snake;
}
public void gameOver() {
timer.cancel();
}
}
| true |
401040e266e453c8b9643ef58c8cc0cfaef5a9f0 | Java | nostalgiaguy/SampleGit | /SampleGit/src/com/nostalgiaguy/coreconceptpage2/FinalClass.java | UTF-8 | 579 | 3.34375 | 3 | [] | no_license | package com.nostalgiaguy.coreconceptpage2;
//remove the comment and see what happens
class A4 { //extends B{
public A4(){
System.out.println("I M HERE");
}
}
//! class Further extends B {}
//error: Cannot extend final class 'B'
final class B{
int i = 7;
int j = 1;
A4 x = new A4();
void f() {
System.out.println("B.f() function....");
}
}
public class FinalClass {
public static void main(String[] args) {
B n = new B();
n.f();
n.i = 40;
n.j++;
System.out.println("n.i = "+n.i+", n.j = "+n.j);
}
}
| true |
2b0a69ef4cabb2e7e6e62f5f42621a5c7e96765e | Java | yana-chaputina/SQLiteConnector | /src/test/java/ru/rosbank/javaschool/datasource/SqliteConnectorTests.java | UTF-8 | 4,499 | 2.015625 | 2 | [] | no_license | package ru.rosbank.javaschool.datasource;
import lombok.val;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.sqlite.SQLiteDataSource;
import ru.rosbank.javaschool.datasource.annotation.AnnotationSqliteConnector;
import ru.rosbank.javaschool.datasource.groovy.GroovySqliteConnector;
import ru.rosbank.javaschool.datasource.javaconfig.JavaConfiguration;
import ru.rosbank.javaschool.datasource.javaconfig.JavaSqliteConnector;
import ru.rosbank.javaschool.datasource.kotlin.BeansKt;
import ru.rosbank.javaschool.datasource.kotlin.KotlinSqliteConnector;
import ru.rosbank.javaschool.datasource.programmatic.ProgrammaticSqliteConnector;
import ru.rosbank.javaschool.datasource.xml.XmlSqliteConnector;
import static org.junit.jupiter.api.Assertions.*;
class SqliteConnectorTests {
@Test
public void XmlConfig()
{
val context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("context.xml");
context.refresh();
XmlSqliteConnector result=(XmlSqliteConnector)context.getBean("connector");
assertEquals("admin",result.getLogin());
assertEquals("password",result.getPassword());
}
@Test
public void AnnotationConfig()
{
val context = new AnnotationConfigApplicationContext("ru.rosbank.javaschool.datasource.annotation");
AnnotationSqliteConnector result=(AnnotationSqliteConnector)context.getBean("connector");
assertEquals("admin",result.getLogin());
assertEquals("password",result.getPassword());
}
@Test
public void JavaConfig()
{
val context = new AnnotationConfigApplicationContext(JavaConfiguration.class);
JavaSqliteConnector result=(JavaSqliteConnector)context.getBean("connector");
assertEquals("admin",result.getLogin());
assertEquals("password",result.getPassword());
}
@Test
public void ProgrammaticConfig()
{
val context = new GenericApplicationContext();
context.registerBean(PropertySourcesPlaceholderConfigurer.class, () -> {
val configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setLocation(new ClassPathResource("db.properties"));
return configurer;
});
context.registerBean("datasource", SQLiteDataSource.class, db -> {
db.getPropertyValues().addPropertyValue("url","${db_url}");
});
context.registerBean("connector", ProgrammaticSqliteConnector.class,
"${login}", "${password}",
new RuntimeBeanReference("datasource"));
context.refresh();
ProgrammaticSqliteConnector result=(ProgrammaticSqliteConnector)context.getBean("connector");
assertEquals("admin",result.getLogin());
assertEquals("password",result.getPassword());
}
@Test
public void GroovyConfig()
{
val context = new GenericApplicationContext();
val reader = new GroovyBeanDefinitionReader(context);
reader.loadBeanDefinitions("context.groovy");
context.refresh();
GroovySqliteConnector result=(GroovySqliteConnector)context.getBean("connector");
assertEquals("admin",result.getLogin());
assertEquals("password",result.getPassword());
}
@Test
public void KotlinConfig()
{
val factory = new DefaultListableBeanFactory();
factory.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
val context = new GenericApplicationContext(factory);
BeansKt.getBeans().initialize(context);
context.refresh();
KotlinSqliteConnector result=(KotlinSqliteConnector)context.getBean("connector");
assertEquals("admin",result.getLogin());
assertEquals("password",result.getPassword());
}
}
| true |
20ae718131af3403f0eba5fb6fb315c1e23fa234 | Java | Ksu1995/Dictionary | /app/src/main/java/com/ksenia/dictionary/data/network/data/TranslationResponse.java | UTF-8 | 407 | 2.03125 | 2 | [] | no_license | package com.ksenia.dictionary.data.network.data;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by Samsonova_K on 31.05.2017.
*/
public class TranslationResponse {
@JsonProperty("code")
private int mResponseCode;
TranslationResponse(int returnCode) {
mResponseCode = returnCode;
}
TranslationResponse() {
}
public long getResponseCode() {
return mResponseCode;
}
}
| true |
8894e5eb7931e0ed00b880b4e6ea9ec2fcaf1e8b | Java | wangadmin123/httpApp | /tyyh/src/cn/tyyhoa/pojo/OaXsbDailypaper2.java | UTF-8 | 1,402 | 2.09375 | 2 | [] | no_license | package cn.tyyhoa.pojo;
import java.util.Date;
public class OaXsbDailypaper2 {
//ID
private Integer lifeID;
//预习总个数
private Integer preparationCount;
//上机总个数
private Integer obuCount;
//课后共个数
private Integer homeworkCount;
//年级ID编号
private Integer grade_id;
//录入时间
private Date writeTimeDate2;
public Integer getLifeID() {
return lifeID;
}
public void setLifeID(Integer lifeID) {
this.lifeID = lifeID;
}
public Integer getPreparationCount() {
return preparationCount;
}
public void setPreparationCount(Integer preparationCount) {
this.preparationCount = preparationCount;
}
public Integer getObuCount() {
return obuCount;
}
public void setObuCount(Integer obuCount) {
this.obuCount = obuCount;
}
public Integer getHomeworkCount() {
return homeworkCount;
}
public void setHomeworkCount(Integer homeworkCount) {
this.homeworkCount = homeworkCount;
}
public Integer getGrade_id() {
return grade_id;
}
public void setGrade_id(Integer grade_id) {
this.grade_id = grade_id;
}
public Date getWriteTimeDate2() {
return writeTimeDate2;
}
public void setWriteTimeDate2(Date writeTimeDate2) {
this.writeTimeDate2 = writeTimeDate2;
}
}
| true |
aa7b08b2852c9257a33d07ef008eb40ce6aac733 | Java | cloudlu/lytz | /src/test/java/com/lytz/demo/PasswordServiceTest.java | UTF-8 | 1,082 | 2.15625 | 2 | [] | no_license | /**
*
*/
package com.lytz.demo;
import static org.junit.Assert.*;
import java.io.IOException;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.credential.PasswordService;
import org.junit.Test;
/**
* @author cloudlu
*
*/
@Log4j2
public class PasswordServiceTest {
private PasswordService passwordService;
@Test public void testEncode() throws IOException {
passwordService = new org.apache.shiro.authc.credential.DefaultPasswordService();
String submitted = passwordService.encryptPassword("admin");
String saved = "$shiro1$SHA-256$500000$fhIqcpBJYp73cqA+IuEkZA==$f9+Zuno7YpSyrvFD7OVmwRw1y6tD7bOdUcQazW7/SF4=";
if(LOG.isDebugEnabled()){
LOG.debug("current encoded password for admin: {}", submitted);
LOG.debug("previous encoded password for admin: {}", saved);
}
assertFalse(submitted.equals(saved));
assertTrue(passwordService.passwordsMatch("admin", saved));
assertTrue(passwordService.passwordsMatch("admin", submitted));
}
}
| true |
c4f2fef110254369bd78905e344015789aa80ef3 | Java | sharan-sripada/Spring-CRM-REST | /src/main/java/com/springdemo/rest/CustomerRestController.java | UTF-8 | 1,573 | 2.4375 | 2 | [] | no_license | package com.springdemo.rest;
import com.springdemo.entity.Customer;
import com.springdemo.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
public class CustomerRestController {
@Autowired
private CustomerService customerService;
@GetMapping("/customers")
private List<Customer> getCustomers(){
return customerService.getCustomers();
}
@GetMapping("/customers/{customerId}")
private Customer getCustomers(@PathVariable int customerId){
Customer customer=customerService.getCustomer(customerId);
if(customer==null){
throw new CustomerNotFoundException();
}
return customer;
}
@PostMapping("/customers")
private Customer addCustomer(@RequestBody Customer customer){
customer.setId(0);
customerService.saveCustomer(customer);
return customer;
}
@PutMapping("/customers")
private Customer updateCustomer(@RequestBody Customer customer){
customerService.saveCustomer(customer);
return customer;
}
@DeleteMapping("/customers/{customerId}")
private String deleteCustomers(@PathVariable int customerId){
Customer customer=customerService.getCustomer(customerId);
if(customer==null){
throw new CustomerNotFoundException();
}
customerService.deleteCustomer(customerId);
return "Deleted customer:"+customerId;
}
}
| true |
ab15d550d47812f02deb878771e49df946cb70ae | Java | colima/Acquire | /acquire/catissue-persistence/src/main/java/edu/wustl/catissuecore/namegenerator/LabelTokenForPpiUId.java | UTF-8 | 1,575 | 2.359375 | 2 | [] | no_license | package edu.wustl.catissuecore.namegenerator;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.util.SpecimenUtil;
import edu.wustl.common.util.KeySequenceGeneratorUtil;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.dao.exception.DAOException;
/**
* The Class LabelTokenForPpiUId.
*/
public class LabelTokenForPpiUId implements LabelTokens
{
/** The Constant LOGGER. */
private static final Logger LOGGER = Logger.getCommonLogger(LabelTokenForPpiUId.class);
/**
* This will return the value of the token provided.
* @see edu.wustl.catissuecore.namegenerator.LabelTokens#getTokenValue(java.lang.Object,
* java.lang.String, java.lang.Long)
*/
public String getTokenValue(Object object)
{
return getSpecimenCount((Specimen)object);
}
/**
* Gets the specimen count.
*
* @param specimen the specimen
*
* @return the specimen count
*/
private String getSpecimenCount(Specimen specimen)
{
long cprId = specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getId();
long cpId = specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol().getId();
String yearOfColl = SpecimenUtil.getCollectionYear(specimen);
String key = cpId+"_"+cprId+"_"+yearOfColl;
String type = "SpecimenCount";
long ctr = 0;
try
{
ctr = KeySequenceGeneratorUtil.getNextUniqeId(key, type);
}
catch (DAOException e1)
{
LOGGER.info(e1.getMessage());
}
return String.valueOf(ctr);
}
}
| true |
cfad597c76963ff014f4dc102cac285a84f08eed | Java | zhangbin1995/leetcode | /leetcode/src/lc201_400/LeetCode300.java | UTF-8 | 892 | 3.25 | 3 | [] | no_license | package lc201_400;
/**
* 最长上升子序列
* https://leetcode-cn.com/problems/longest-increasing-subsequence/submissions/
* 给定一个无序的整数数组,找到其中最长上升子序列的长度。
*
* @author binzhang
* @date 2019-08-17
*/
public class LeetCode300 {
public int lengthOfLIS(int[] nums) {
if (nums.length <= 1) {
return nums.length;
}
int[] dp = new int[nums.length];
dp[0] = 1;
for (int i = 1 ; i < nums.length ; i ++) {
int max = 1;
for (int j = 0 ; j < i ; j ++) {
if (nums[i] > nums[j]) {
max = Math.max(max, dp[j] + 1);
}
}
dp[i] = max;
}
int res = 0;
for (int i = 0 ; i < dp.length ; i ++) {
res = Math.max(res, dp[i]);
}
return res;
}
}
| true |
3c6b67484b1bc180df6e63bd6c06e79f61acee11 | Java | adrianoqueiroz/owls-api | /src/test/java/org/mindswap/utils/ProcessDataFlowTest.java | ISO-8859-1 | 14,267 | 1.507813 | 2 | [
"MIT"
] | permissive | /*
* Created 29.10.2009
*
* (c) 2009 Thorsten Mller - University of Basel Switzerland
*
* The MIT License
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package org.mindswap.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeNoException;
import java.io.InputStream;
import java.net.URI;
import java.util.StringTokenizer;
import org.junit.Test;
import org.mindswap.owl.OWLClass;
import org.mindswap.owl.OWLFactory;
import org.mindswap.owl.OWLIndividualList;
import org.mindswap.owl.OWLKnowledgeBase;
import org.mindswap.owl.OWLOntology;
import org.mindswap.owl.OWLType;
import org.mindswap.owl.vocabulary.RDFS;
import org.mindswap.owls.process.AtomicProcess;
import org.mindswap.owls.process.CompositeProcess;
import org.mindswap.owls.process.Perform;
import org.mindswap.owls.process.Process;
import org.mindswap.owls.process.Result;
import org.mindswap.owls.process.Sequence;
import org.mindswap.owls.process.variable.Input;
import org.mindswap.owls.process.variable.Loc;
import org.mindswap.owls.process.variable.Output;
import org.mindswap.owls.process.variable.Parameter;
import org.mindswap.owls.profile.Profile;
import org.mindswap.owls.service.Service;
import org.mindswap.owls.vocabulary.OWLS;
import examples.ExampleURIs;
/**
* Note that this test depends on the <tt>RepeatUntil.owl</tt> OWL-S service
* description. If its data flow specification is changed this test is likely
* to fail then.
*
* @author unascribed
* @version $Rev: 2350 $; $Author: thorsten $; $Date: 2009-11-18 17:44:31 +0200 (Wed, 18 Nov 2009) $
*/
public class ProcessDataFlowTest
{
private static final URI baseURI = URI.create("http://example.org");
private OWLClass[] classes;
private Input p0i1, p0i2, p0i3;
private Loc p0l1;
private Output p0o1, p0o2, p0o3, p0o4;
private Input p1i1;
private Output p1o1, p1o2;
private Input p2i1, p2i2;
private Output p2o1;
private Input p3i1;
private Output p3o1;
private Input p4i1, p4i2, p4i3;
private Input p5i1, p5i2, p5i3;
private Output p5o1;
/**
* Test method for {@link org.mindswap.utils.ProcessDataFlow#toString()}.
*/
@Test
public void testToString()
{
OWLKnowledgeBase kb = OWLFactory.createKB();
Service service = null;
try
{
final InputStream inpStr = ClassLoader.getSystemResourceAsStream("owls/1.2/RepeatUntil.owl");
service = kb.readService(inpStr, URIUtils.createURI(
ExampleURIs.REPEAT_UNTIL_OWLS12, "RepeatUntilService")); // service name required because file specifies two services
}
catch (Exception e)
{
assumeNoException(e);
}
Process p = service.getProcess();
String s = ProcessDataFlow.index(p.getOntology(), p).toString();
assertNotNull(s);
// Not the best test. At least, it does verify that expected number of
// data flow bindings were indexed and that (source, sink) pairs are as defined.
StringTokenizer st = new StringTokenizer(s, Utils.LINE_SEPARATOR);
int tokens = 0, idx = -1;
while (st.hasMoreTokens())
{
String t = st.nextToken();
if ((idx = t.indexOf("currentWeight")) > -1 && (idx = t.indexOf("personWeight", idx)) > -1) tokens++;
if ((idx = t.indexOf("newWeight")) > -1 && (idx = t.indexOf("currentWeight", idx)) > -1) tokens++;
if ((idx = t.indexOf("person")) > -1 && (idx = t.indexOf("dietPerson", idx)) > -1) tokens++;
}
assertEquals(3, tokens);
}
/**
* Test method for {@link org.mindswap.utils.ProcessDataFlow#index(OWLOntology, Process)}
* using a atomic process.
*/
@Test
public void testIndexAtomicProcess()
{
OWLKnowledgeBase kb = OWLFactory.createKB();
kb.setReasoner("Transitive"); // sufficient as we only need reflexive-transitive subClassOf closure
OWLOntology ont = kb.createOntology(baseURI);
createClasses(ont);
AtomicProcess aProcess = createAtomicProcess(ont);
ProcessDataFlow pdf = ProcessDataFlow.index(null, aProcess);
// atomic process do not have a data flow --> expected to be empty
String s = pdf.toString();
assertEquals(0, s.length());
OWLOntology pdfAsOnt = pdf.asOntology();
assertEquals(0, pdfAsOnt.size());
// most specific sink type always equal to the parameter type itself
assertEquals(p0i1.getParamType(), pdf.getMostSpecificSinkType(p0i1));
assertEquals(p0i2.getParamType(), pdf.getMostSpecificSinkType(p0i2));
assertEquals(p0i3.getParamType(), pdf.getMostSpecificSinkType(p0i3));
}
/**
* Test method for {@link org.mindswap.utils.ProcessDataFlow#index(OWLOntology, Process)}
* using a composite process.
*/
@Test
public void testIndexCompositeProcess()
{
OWLKnowledgeBase kb = OWLFactory.createKB();
kb.setReasoner("Transitive"); // sufficient as we only need reflexive-transitive subClassOf closure
OWLOntology ont = kb.createOntology(baseURI);
createClasses(ont);
CompositeProcess cProcess = createCompositeProcess(ont);
ProcessDataFlow pdf = ProcessDataFlow.index(null, cProcess);
System.out.println(pdf.toString());
OWLIndividualList<Parameter> sinks = pdf.getSinkParameters(p0i1);
assertNotNull(sinks);
assertTrue(sinks.size() == 1);
assertEquals(p0o1, sinks.get(0));
OWLType msst = pdf.getMostSpecificSinkType(p0i1);
assertNotNull(msst);
assertEquals(classes[0], msst);
sinks = pdf.getSinkParameters(p0i2);
assertNotNull(sinks);
assertTrue(sinks.size() == 1);
assertEquals(p1i1, sinks.get(0));
msst = pdf.getMostSpecificSinkType(p0i2);
assertNotNull(msst);
assertEquals(classes[1], msst);
sinks = pdf.getSinkParameters(p0i3);
assertNotNull(sinks);
assertTrue(sinks.size() == 3);
assertTrue(sinks.contains(p3i1));
assertTrue(sinks.contains(p4i1));
assertTrue(sinks.contains(p5i3));
msst = pdf.getMostSpecificSinkType(p0i3);
assertNotNull(msst);
assertTrue(classes[4].equals(msst) || classes[6].equals(msst)); // incompatible consumers
sinks = pdf.getSinkParameters(p0l1);
assertNotNull(sinks);
assertTrue(sinks.size() == 1);
assertEquals(p0o4, sinks.get(0));
msst = pdf.getMostSpecificSinkType(p0l1);
assertNotNull(msst);
assertEquals(classes[3], msst);
sinks = pdf.getSinkParameters(p1o1);
assertNotNull(sinks);
assertTrue(sinks.size() == 2);
assertTrue(sinks.contains(p0o2));
assertTrue(sinks.contains(p2i2));
msst = pdf.getMostSpecificSinkType(p1o1);
assertNotNull(msst);
assertTrue(classes[0].equals(msst));
sinks = pdf.getSinkParameters(p1o2);
assertNotNull(sinks);
assertTrue(sinks.size() == 1);
assertEquals(p2i1, sinks.get(0));
msst = pdf.getMostSpecificSinkType(p1o2);
assertNotNull(msst);
assertEquals(classes[3], msst);
sinks = pdf.getSinkParameters(p2o1);
assertNotNull(sinks);
assertTrue(sinks.size() == 2);
assertTrue(sinks.contains(p4i2));
assertTrue(sinks.contains(p5i1));
msst = pdf.getMostSpecificSinkType(p2o1);
assertNotNull(msst);
assertTrue(classes[4].equals(msst));
sinks = pdf.getSinkParameters(p3o1);
assertNotNull(sinks);
assertTrue(sinks.size() == 2);
assertTrue(sinks.contains(p4i3));
assertTrue(sinks.contains(p5i2));
msst = pdf.getMostSpecificSinkType(p3o1);
assertNotNull(msst);
assertTrue(classes[6].equals(msst));
sinks = pdf.getSinkParameters(p5o1);
assertNotNull(sinks);
assertTrue(sinks.size() == 1);
assertEquals(p0o3, sinks.get(0));
msst = pdf.getMostSpecificSinkType(p5o1);
assertNotNull(msst);
assertEquals(classes[5], msst);
}
private AtomicProcess createAtomicProcess(final OWLOntology ont)
{
// profile and service are actually not required for the test, but it should not harm, of course
Profile aProfile = ont.createProfile(URIUtils.createURI(baseURI, "profile0"));
Service aService = ont.createService(URIUtils.createURI(baseURI, "service0"));
AtomicProcess aProcess = ont.createAtomicProcess(URIUtils.createURI(baseURI, "ap0"));
aService.addProfile(aProfile);
aService.setProcess(aProcess);
// create Inputs, Outputs
p0i1 = aProcess.createInput(URIUtils.createURI(baseURI, "p0.i1"), classes[0]);
p0i2 = aProcess.createInput(URIUtils.createURI(baseURI, "p0.i2"), classes[1]);
p0i3 = aProcess.createInput(URIUtils.createURI(baseURI, "p0.i3"), classes[2]);
p0o1 = aProcess.createOutput(URIUtils.createURI(baseURI, "p0.o1"), classes[0]);
p0o2 = aProcess.createOutput(URIUtils.createURI(baseURI, "p0.o2"), classes[0]);
p0o3 = aProcess.createOutput(URIUtils.createURI(baseURI, "p0.o3"), classes[5]);
aProfile.addInput(p0i1);
aProfile.addInput(p0i2);
aProfile.addInput(p0i3);
aProfile.addOutput(p0o1);
aProfile.addOutput(p0o2);
aProfile.addOutput(p0o3);
return aProcess;
}
private void createClasses(final OWLOntology ont)
{
classes = new OWLClass[7];
for (int i = 0; i < classes.length; i++)
{
classes[i] = ont.createClass(URIUtils.createURI(baseURI, "C" + i));
}
// add some subclass axioms: C3 subclassOf C1; C4, C5 subclassOf C2; C6 subclassOf C5
classes[3].addProperty(RDFS.subClassOf, classes[1]);
classes[4].addProperty(RDFS.subClassOf, classes[2]);
classes[5].addProperty(RDFS.subClassOf, classes[2]);
classes[6].addProperty(RDFS.subClassOf, classes[5]);
}
private CompositeProcess createCompositeProcess(final OWLOntology ont)
{
CompositeProcess cProcess = ont.createCompositeProcess(URIUtils.createURI(baseURI, "p0"));
Sequence sequence = ont.createSequence(null);
cProcess.setComposedOf(sequence);
// create five atomic processes in the sequence each having some inputs
// and/or outputs and wire them to create a data flow (by means of bindings)
// create Inputs, Outputs, and Loc
p0i1 = cProcess.createInput(URIUtils.createURI(baseURI, "p0.i1"), classes[0]);
p0i2 = cProcess.createInput(URIUtils.createURI(baseURI, "p0.i2"), classes[1]);
p0i3 = cProcess.createInput(URIUtils.createURI(baseURI, "p0.i3"), classes[2]);
p0l1 = cProcess.createLoc(URIUtils.createURI(baseURI, "p0.l1"), classes[1]);
p0o1 = cProcess.createOutput(URIUtils.createURI(baseURI, "p0.o1"), classes[0]);
p0o2 = cProcess.createOutput(URIUtils.createURI(baseURI, "p0.o2"), classes[0]);
p0o3 = cProcess.createOutput(URIUtils.createURI(baseURI, "p0.o3"), classes[5]);
p0o4 = cProcess.createOutput(URIUtils.createURI(baseURI, "p0.o4"), classes[3]);
// first element in sequence
AtomicProcess ap = ont.createAtomicProcess(URIUtils.createURI(baseURI, "p1"));
p1i1 = ap.createInput(URIUtils.createURI(baseURI, "p1.i1"), classes[1]);
p1o1 = ap.createOutput(URIUtils.createURI(baseURI, "p1.o1"), classes[0]);
p1o2 = ap.createOutput(URIUtils.createURI(baseURI, "p1.o2"), classes[1]);
Perform perf1 = ont.createPerform(URIUtils.createURI(baseURI, "perf1"));
perf1.addBinding(p1i1, OWLS.Process.ThisPerform, p0i2);
perf1.setProcess(ap);
sequence.addComponent(perf1);
// second element in sequence
ap = ont.createAtomicProcess(URIUtils.createURI(baseURI, "p2"));
p2i1 = ap.createInput(URIUtils.createURI(baseURI, "p2.i1"), classes[3]);
p2i2 = ap.createInput(URIUtils.createURI(baseURI, "p2.i2"), classes[0]);
p2o1 = ap.createOutput(URIUtils.createURI(baseURI, "p2.o1"), classes[4]);
Perform perf2 = ont.createPerform(URIUtils.createURI(baseURI, "perf2"));
perf2.addBinding(p2i1, perf1, p1o2);
perf2.addBinding(p2i2, perf1, p1o1);
perf2.setProcess(ap);
sequence.addComponent(perf2);
// third element in sequence
ap = ont.createAtomicProcess(URIUtils.createURI(baseURI, "p3"));
p3i1 = ap.createInput(URIUtils.createURI(baseURI, "p3.i1"), classes[4]);
p3o1 = ap.createOutput(URIUtils.createURI(baseURI, "p3.o1"), classes[5]);
Perform perf3 = ont.createPerform(URIUtils.createURI(baseURI, "perf3"));
perf3.addBinding(p3i1, OWLS.Process.ThisPerform, p0i3);
perf3.setProcess(ap);
sequence.addComponent(perf3);
// fourth element in sequence
ap = ont.createAtomicProcess(URIUtils.createURI(baseURI, "p4"));
p4i1 = ap.createInput(URIUtils.createURI(baseURI, "p4.i1"), classes[5]);
p4i2 = ap.createInput(URIUtils.createURI(baseURI, "p4.i2"), classes[2]);
p4i3 = ap.createInput(URIUtils.createURI(baseURI, "p4.i3"), classes[2]);
Perform perf4 = ont.createPerform(URIUtils.createURI(baseURI, "perf4"));
perf4.addBinding(p4i1, OWLS.Process.ThisPerform, p0i3);
perf4.addBinding(p4i2, perf2, p2o1);
perf4.addBinding(p4i3, perf3, p3o1);
perf4.setProcess(ap);
sequence.addComponent(perf4);
// fifth element in sequence
ap = ont.createAtomicProcess(URIUtils.createURI(baseURI, "p5"));
p5i1 = ap.createInput(URIUtils.createURI(baseURI, "p5.i1"), classes[4]);
p5i2 = ap.createInput(URIUtils.createURI(baseURI, "p5.i2"), classes[6]);
p5i3 = ap.createInput(URIUtils.createURI(baseURI, "p5.i3"), classes[6]);
p5o1 = ap.createOutput(URIUtils.createURI(baseURI, "p5.o1"), classes[6]);
Perform perf5 = ont.createPerform(URIUtils.createURI(baseURI, "perf5"));
perf5.addBinding(p5i1, perf2, p2o1);
perf5.addBinding(p5i2, perf3, p3o1);
perf5.addBinding(p5i3, OWLS.Process.ThisPerform, p0i3);
perf5.setProcess(ap);
sequence.addComponent(perf5);
Result result = cProcess.createResult(null);
result.addBinding(p0o1, OWLS.Process.ThisPerform, p0i1);
result.addBinding(p0o2, perf1, p1o1);
result.addBinding(p0o3, perf5, p5o1);
result.addBinding(p0o4, p0l1);
return cProcess;
}
}
| true |
bfbc8e8cc8b060019d8e025e0d57517befffe7ee | Java | CSSE490-Android-Development/SQLite-ScoreApp | /src/edu/rosehulman/example/ShowScores.java | UTF-8 | 3,810 | 2.359375 | 2 | [] | no_license | package edu.rosehulman.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import edu.rosehulman.example.highscores.R;
public class ShowScores extends Activity {
private static final int DIALOG_ID = 1;
private List<Score> mScores;
private ListView mScoreListView;
private ArrayAdapter<Score> mScoreAdapter;
private ScoreDbAdapter mDbAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDbAdapter = new ScoreDbAdapter(this);
mDbAdapter.open();
mScoreListView = (ListView) findViewById(R.id.scores_list);
mScores = new ArrayList<Score>();
Score s = new Score();
s.setName("Eric");
s.setScore(5);
mScores.addAll(mDbAdapter.getAllScores());
mScores.add(s);
mScoreAdapter = new ArrayAdapter<Score>(this, android.R.layout.simple_list_item_1, mScores);
mScoreListView.setAdapter(mScoreAdapter);
mScoreListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
removeScore(mScores.get(position));
return false;
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mDbAdapter.close();
}
private void addScore(Score s) {
Toast.makeText(this, "Adding score: " + s, Toast.LENGTH_SHORT);
s = mDbAdapter.addScore(s);
mScores.add(s);
mScoreAdapter.notifyDataSetChanged();
}
private void removeScore(Score s) {
Toast.makeText(this, "Removing score: " + s, Toast.LENGTH_SHORT);
mDbAdapter.removeScore(s);
mScores.remove(s);
mScoreAdapter.notifyDataSetChanged();
}
@Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
final Dialog dialog = new Dialog(this);
if (id == DIALOG_ID) {
dialog.setContentView(R.layout.add_dialog);
dialog.setTitle(R.string.add_score);
final EditText nameText = (EditText) dialog.findViewById(R.id.name_entry);
final EditText scoreText = (EditText) dialog.findViewById(R.id.score_entry);
final Button addButton = (Button) dialog.findViewById(R.id.add_score_button);
final Button cancelButton = (Button) dialog.findViewById(R.id.cancel_score_button);
addButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Score s = new Score();
s.setName(nameText.getText().toString());
try {
s.setScore(Integer.parseInt(scoreText.getText().toString()));
} catch (NumberFormatException e) {
s.setScore(0);
}
addScore(s);
dialog.dismiss();
}
});
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
return dialog;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.menu_add) {
showDialog(DIALOG_ID);
}
return false;
}
} | true |
15bf0d88faf4748554a18fcda50bd11194cab596 | Java | unknow509/AppBanRuouJavaSwing | /src/Process/Item.java | UTF-8 | 423 | 2.0625 | 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 Process;
/**
*
* @author admin
*/
public class Item {
public int id;
public String des;
public Item() {
}
public Item(int id, String des) {
this.id = id;
this.des = des;
}
}
| true |
0b3d2f0bf8695529d73d15939db51bfb783d0969 | Java | abhinav0419/moborgmap | /src/main/java/com/mob/service/impl/TitleServiceImpl.java | UTF-8 | 591 | 1.984375 | 2 | [] | no_license | package com.mob.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mob.model.Title;
import com.mob.repository.TitleRepository;
import com.mob.service.TitleService;
@Service
public class TitleServiceImpl implements TitleService {
@Autowired
private TitleRepository titleRepo;
@Transactional
public List<Title> getTitleName() {
List<Title> titleName=titleRepo.getTitleName();
return titleName;
}
}
| true |
db9c1a2ea42e9bf19a07b39db1772486d9951452 | Java | the-widmore/WQmsg | /src/com/coderqi/publicutil/voice/Tip.java | UTF-8 | 153 | 1.609375 | 2 | [] | no_license | package com.coderqi.publicutil.voice;
import android.util.Log;
public class Tip {
public static void log(String msg) {
Log.i("调试", msg);
}
}
| true |
d084877647eed1c2f2b217471d39f87b23c4d071 | Java | M-CREATE-ART/HWTABS | /src/main/java/app/HW10/Entity/Human.java | UTF-8 | 3,930 | 3.265625 | 3 | [] | no_license | package app.HW10.Entity;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class Human {
private String name;
private String surname;
private Family family;
private long birthDate;
private int iq;
private HashMap<String, String> schedule = new HashMap<>();
public Human() {
}
public Human(String name, String surname, String birthDate) {
this.name = name;
this.surname = surname;
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
Date date = format.parse(birthDate);
this.birthDate = date.getTime();
} catch (Exception e) {
System.out.println("Wrong date input!");
}
}
public Human(String name, String surname, String birthDate, int iq) {
this.name = name;
this.surname = surname;
this.iq = iq;
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
Date date = format.parse(birthDate);
this.birthDate = date.getTime();
} catch (Exception e) {
System.out.println("Wrong date input!");
}
}
public Human(String name, String surname, String birthDate, int iq, Family family ) {
this.name = name;
this.surname = surname;
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
Date date = format.parse(birthDate);
this.birthDate = date.getTime();
} catch (Exception e) {
System.out.println("Wrong date input!");
} this.iq = iq;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Family getFamily() {
return family;
}
public void setFamily(Family family) {
this.family = family;
}
public long getBirthDate() {
return birthDate;
}
public void setBirthDate(long birthDate) {
this.birthDate = birthDate;
}
public int getIq() {
return iq;
}
public void setIq(int iq) {
this.iq = iq;
}
public HashMap<String, String> getSchedule() {
return schedule;
}
public void setSchedule(HashMap<String, String> schedule) {
this.schedule = schedule;
}
public String greetPet(int petIndex) {
return String.format(" Hello, %s", new ArrayList<>(family.getPets()).get(petIndex).getNickname());
}
public String describePet(int petIndex) {
String trick = new ArrayList<>(family.getPets()).get(petIndex).getTrickLevel() >= 50 ? "very sly.\n" : "almost not sly.\n";
return String.format("I have a %s, he is %d years old, he is %s", new ArrayList<>(family.getPets()).get(petIndex).getSpecies(),new ArrayList<>(family.getPets()).get(petIndex).getAge(), trick);
}
public String describeAge() {
LocalDate today = LocalDate.now();
Date birthday = new Date(birthDate);
LocalDate localBirthDate = birthday.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Period period = Period.between(localBirthDate, today);
return String.format("%s years %s months %s days", period.getYears(), period.getMonths(), period.getDays());
}
@Override
public String toString() {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateFormatted = formatter.format(birthDate);
return String.format("Human{name='%s', surname='%s', Date of birth='%s', iq=%d, schedule=%s}", name, surname, dateFormatted, iq, schedule.toString());
}
}
| true |
6b34281b33510bc83ef9d7be1ad8829d53088a6f | Java | moodrain/secondhand-trade | /src/main/java/muyu/trade/enumeration/GoodsStatus.java | UTF-8 | 467 | 2.578125 | 3 | [] | no_license | package muyu.trade.enumeration;
public enum GoodsStatus {
selling(1, "已上架"),
trading(2, "交易中"),
sold(3, "已卖出");
private String info;
private Integer num;
GoodsStatus(Integer num, String info) {
this.info = info;
this.num = num;
}
public String toString() {
return info;
}
public String getInfo() {
return info;
}
public Integer getNum() {
return num;
}
}
| true |
8572e8b8178c31e3ddfc9731924f3658d404a495 | Java | MinorGlitch/Java-Fundamentals | /Java OOP Advanced/Problems/Dependency Inversion And Interface Segregation - Exercises/src/main/java/models/engines/SterndriveEngine.java | UTF-8 | 537 | 2.9375 | 3 | [] | no_license | package models.engines;
public class SterndriveEngine extends BaseEngine {
private static final int Multiplier = 7;
private int cachedOutput;
public SterndriveEngine(String model, int horsepower, int displacement) {
super(model, horsepower, displacement);
}
public int getOutput() {
if (this.cachedOutput != 0) {
return this.cachedOutput;
}
this.cachedOutput = (super.getHorsepower() * Multiplier) + super.getDisplacement();
return this.cachedOutput;
}
}
| true |
127faaf6dd584584060bad381010ebba843a724c | Java | qannoufoualid/Book-Maker | /src/main/java/com/ihm18/bookmaker/presentation/historycomponent/HistoryPresenter.java | UTF-8 | 1,124 | 2.109375 | 2 | [] | no_license | package com.ihm18.bookmaker.presentation.historycomponent;
import java.net.URL;
import java.util.ResourceBundle;
import javax.inject.Inject;
import com.ihm18.bookmaker.presentation.centralcomponent.CentralModel;
import javafx.beans.property.Property;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
/**
*
* @author oualidqannouf
*/
public class HistoryPresenter implements Initializable {
@Inject
private CentralModel centralModel;
@Inject
private HistoryModel historyModel;
@FXML
private Button goBackButton;
public void launch() {
}
@Override
public void initialize(URL location, ResourceBundle resources) {
goBackButton.disableProperty().bindBidirectional(historyModel.previousViewNotExistsProperty());
}
/**
* Permet d'afficher l'écran precedent.
* @param event event de click
*/
public void getPreviousMainView(ActionEvent event){
historyModel.goBack();
centralModel.setMainView(historyModel.getActiveView(), historyModel.getActiveViewTitle());
}
}
| true |
893491d76116c5b26ab3c415fada35d58c8e65ca | Java | nastyada/patterns | /src/factory/simple/Knight.java | UTF-8 | 216 | 2.421875 | 2 | [] | no_license | package factory.simple;
public class Knight extends Character {
public Knight() {
name = "Knight";
speed = 10;
force = 10;
health = 8;
artifacts.add("Sword");
artifacts.add("Arrow");
}
}
| true |
354d35b852c464d9c3ad3cb670d6b175766c48e4 | Java | psendil/Java-Static-Method | /src/main/java/DoubleIt.java | UTF-8 | 400 | 3.625 | 4 | [] | no_license | /**
* Created by psenthil on 3/28/17.
*/
public class DoubleIt {
public static void main(String[] args) {
int doubleOfDigit;
doubleOfDigit = doubleIt(7);
System.out.println("Double of given number is :" + doubleOfDigit);
}
public static int doubleIt(int parameter){
int result;
result = parameter + parameter;
return result;
}
}
| true |
a09eabd0031358432128d3e1894fb3f57ab22aa2 | Java | msarfrazcss/snippetA | /java/DepartmentController.java | UTF-8 | 3,340 | 2.28125 | 2 | [] | no_license | package com.ats.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ats.model.Department;
import com.ats.service.ATSUtils;
import com.ats.service.DepartmentService;
import org.codehaus.jackson.map.ObjectMapper;
@Controller
@RequestMapping("/admin")
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
@RequestMapping(value="/departments", method=RequestMethod.GET)
public String departments(Model model) {
try {
ObjectMapper mapper = new ObjectMapper();
model.addAttribute("departmentList", mapper.writeValueAsString(departmentService.getDepartmentList()));
model.addAttribute("departments_part", ATSUtils.active1);
model.addAttribute("departments_full", ATSUtils.active2);
model.addAttribute("departmentsAll_part", ATSUtils.active1);
model.addAttribute("departmentsAll_full", ATSUtils.active2);
}catch(Exception ex) {
ex.printStackTrace();
}
return "admin/departments2";
}
@RequestMapping("/departments/create")
public String createDepartment(@ModelAttribute("department") Department department, BindingResult result, Model model){
model.addAttribute("departments_part", ATSUtils.active1);
model.addAttribute("departments_full", ATSUtils.active2);
model.addAttribute("departmentsAll_part", ATSUtils.active1);
model.addAttribute("departmentsAll_full", ATSUtils.active2);
return "admin/departments_add";
}
@RequestMapping(value="/departments/create", method=RequestMethod.POST)
public String createDepartmentDetails(@ModelAttribute("department") Department department, BindingResult result){
int depID = departmentService.addDepartment(department);
System.out.println("Department created: "+ depID);
return "redirect:/admin/departments";
}
@RequestMapping(value="/departments/edit/{id}", method=RequestMethod.GET)
public String editDepartment(@PathVariable("id") int id, @ModelAttribute("department") Department department, BindingResult result, Model model) {
model.addAttribute("departments_part", ATSUtils.active1);
model.addAttribute("departments_full", ATSUtils.active2);
model.addAttribute("departmentsAll_part", ATSUtils.active1);
model.addAttribute("departmentsAll_full", ATSUtils.active2);
model.addAttribute("department", departmentService.getDepartmentById(id));
return "admin/departments_edit";
}
@RequestMapping(value="/departments/edit", method=RequestMethod.POST)
public String editDepartmentDetails(@ModelAttribute("department") Department department, BindingResult result) {
departmentService.updateDepartment(department);
return "redirect:/admin/departments";
}
@RequestMapping("/departments/delete/{id}")
public String deleteSubDepartment(@PathVariable("id") int id){
departmentService.deleteDepartment(id);
return "redirect:/admin/departments";
}
}
| true |
48102afe025066a4bdc10103ab81d923883ca013 | Java | mendox74/dateoperation | /src/main/java/prototype/repository/DateOperationRepository.java | UTF-8 | 1,418 | 2.265625 | 2 | [] | no_license | package prototype.repository;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Delete;
import prototype.domain.DateOperation;
@Mapper
public interface DateOperationRepository {
/*
* 全件取得
*/
@Select("SELECT * FROM date ORDER BY id ASC")
List<DateOperation> findAll();
/*
*個別取得
*/
@Select("SELECT * FROM date WHERE id = #{id}")
DateOperation findOne(int id);
/*
* 新規登録
*/
@Insert("INSERT INTO date(operationId,operationName,operationYear,operationMonth,operationDay) VALUES(#{operationId},#{operationName},#{operationYear},#{operationMonth},#{operationDay})")
void insert (DateOperation dateOperation);
/*
* 計算式更新
*/
@Update("UPDATE date SET operationId = #{operationId}, operationName = #{operationName}, operationYear = #{operationYear}, operationMonth = #{operationMonth}, operationDay = #{operationDay} WHERE id = #{id}")
void updata (DateOperation dateOperation);
/*
* 結果更新
*/
@Update("UPDATE date SET result = #{result} WHERE id = #{id}")
void calulated (DateOperation dateOperation);
/*
* 削除
*/
@Delete("DELETE FROM date WHERE id = #{id}")
void deleteOne (int id);
}
| true |
b9eb4231053118ac6b21ae08f5a06df0c9cb22d3 | Java | JiminWen/LeetcodePractice | /229. Majority Element II.java | UTF-8 | 862 | 2.859375 | 3 | [] | no_license | public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res=new ArrayList<>();
if(nums==null||nums.length==0) return res;
int max1=nums[0],max2=nums[0];
int count1=0,count2=0;
for(int temp:nums){
if(temp==max1){
count1++;
}
else if(temp==max2){
count2++;
}
else if(count1==0){
max1=temp;
count1=1;
}
else if(count2==0){
max2=temp;
count2=1;
}
else{
count1--;
count2--;
}
}
count1=0;
count2=0;
for(int temp:nums){
if(temp==max1) count1++;
if(temp==max2) count2++;
}
if(count1>nums.length/3) res.add(max1);
if(count2>nums.length/3&&max2!=max1) res.add(max2);
return res;
}
} | true |
58d1bb39432b4d1d5222f6ba1fba75b3139278a2 | Java | andraapopescu/my-project | /src/main/java/application/demo/ui/layouts/view/MessagePopop.java | UTF-8 | 7,540 | 2.328125 | 2 | [] | no_license | package application.demo.ui.layouts.view;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import application.demo.service.EmployeeService;
import application.demo.service.MessageService;
import com.vaadin.shared.ui.combobox.FilteringMode;
import com.vaadin.ui.*;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.themes.ValoTheme;
import application.demo.domain.Employee;
import application.demo.domain.User;
import application.demo.domain.Message;
import application.demo.security.FilterLoginService;
import javassist.tools.reflect.Sample;
public class MessagePopop extends Window {
private static final long serialVersionUID = 1L;
private User user;
private static TextField sendTo, subject;
private static TextArea text;
private Button sendButton;
private Message message;
private VerticalLayout vLayout;
private static ComboBox comboBox;
SimpleDateFormat sdf = new SimpleDateFormat( "E , d MMMMM yyyy , hh:mm ");
public MessagePopop(User user) {
this.user = user;
vLayout = createNewMessageLayout();
vLayout.setSpacing(true);
setContent(vLayout);
this.center();
this.setHeight("80%");
this.setWidth("40%");
}
public MessagePopop(Message message) {
this.message = message;
vLayout = createSelectedMessageLayout(message);
vLayout.setSpacing(true);
setContent(vLayout);
this.center();
this.setHeight("100%");
this.setWidth("50%");
}
private VerticalLayout createSelectedMessageLayout(Message message) {
VerticalLayout result = new VerticalLayout();
Label section = new Label("Sent from");
section.addStyleName("h3");
section.addStyleName("colored");
result.addComponent(section);
TextField sentFrom = new TextField();
sentFrom.setValue(message.getSentFrom());
sentFrom.setWidth("50%");
sentFrom.setReadOnly(true);
result.addComponent(sentFrom);
section = new Label("Date when the message was sent");
section.addStyleName("h3");
section.addStyleName("colored");
result.addComponent(section);
TextField date = new TextField();
date.setValue(sdf.format(message.getDate()));
date.setWidth("50%");
date.setReadOnly(true);
result.addComponent(date);
section = new Label("Subject");
section.addStyleName("h3");
section.addStyleName("colored");
result.addComponent(section);
TextField subject = new TextField();
subject.setValue(message.getSubject());
subject.setWidth("50%");
subject.setReadOnly(true);
result.addComponent(subject);
section = new Label("Your message");
section.addStyleName("h3");
section.addStyleName("colored");
result.addComponent(section);
TextArea text = new TextArea();
text.setValue(message.getText());
text.setWidth("50%");
text.setReadOnly(true);
result.addComponent(text);
result.setSpacing(true);
result.setMargin(true);
return result;
}
private VerticalLayout createNewMessageLayout() {
VerticalLayout result = new VerticalLayout();
Label section = new Label("Send to:");
section.addStyleName("h3");
section.addStyleName("colored");
result.addComponent(section);
comboBox = createComboBox();
result.addComponent(comboBox);
section = new Label("Subject");
section.addStyleName("h3");
section.addStyleName("colored");
result.addComponent(section);
subject = new TextField();
subject.setWidth("50%");
result.addComponent(subject);
section = new Label("Message");
section.addStyleName("h3");
section.addStyleName("colored");
result.addComponent(section);
text = new TextArea();
text.setWidth("50%");
text.setHeight("500%");
result.addComponent(text);
sendButton = new Button("Send");
sendButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
sendButton.addStyleName(ValoTheme.BUTTON_SMALL);
sendButton.addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
if (user.getRole().equals("admin")) {
try {
EmployeeService.findEmployeeByEmail(comboBox.getValue().toString()).get(0);
createMessage();
} catch (IndexOutOfBoundsException e) {
sendMessage();
}
} else {
createMessage();
}
}
});
// Disable one item by its item ID
result.addComponent(sendButton);
result.setComponentAlignment(sendButton, Alignment.BOTTOM_LEFT);
result.setMargin(true);
result.setSpacing(true);
return result;
}
public ComboBox createComboBox() {
ComboBox result = new ComboBox();
result.setFilteringMode(FilteringMode.CONTAINS);
for (Employee e : EmployeeService.getAllEmployees()) {
result.addItem(e.getEmail());
}
result.removeItem(FilterLoginService.currentEmployee.getEmail());
result.setWidth("330px");
result.setNewItemsAllowed(true);
result.setTextInputAllowed(true);
return result;
}
private void createMessage() {
message = new Message();
Employee employee;
if (!comboBox.getValue().toString().isEmpty()) {
try {
employee = EmployeeService.findEmployeeByEmail(comboBox.getValue().toString()).get(0);
if (subject.getValue().isEmpty()) {
Notification.show("You may not want to send a message without a subject");
}
if (text.getValue().isEmpty()) {
Notification.show("You may not want to send a message without any text");
}
String from = "Admin";
if (FilterLoginService.currentEmployee != null &&
!FilterLoginService.currentEmployee.getFirstName().equals("admin") ) {
from = FilterLoginService.currentEmployee.getFirstName() + " "
+ FilterLoginService.currentEmployee.getLastName();
}
message = new Message(from, new Date(), subject.getValue(), text.getValue(), employee);
// System.err.println(message);
MessageService.saveMessage(message);
Notification.show("Message SENT !! ");
this.close();
} catch (NullPointerException e) {
Notification.show("The email you introduced is not correct!");
comboBox.setValue("");
} catch (IndexOutOfBoundsException s) {
Notification.show("The email you introduced is not correct!");
comboBox.setValue("");
}
}
}
// clasa noua
public void sendMessage() {
final String username = "licenta.portalgestiunepersonal@gmail.com";
final String password = "aplicatie";
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
javax.mail.Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(javax.mail.Message.RecipientType.TO,
InternetAddress.parse(comboBox.getValue().toString()));
message.setSubject(subject.getValue());
message.setText(text.getValue());
Transport.send(message);
Notification.show("Email SENT !! ");
this.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
| true |
8b471de1c4688863b619e50854f522134812c2a1 | Java | dennisvoliver/minecraft | /net/minecraft/entity/ai/RangedAttackMob.java | UTF-8 | 171 | 2.09375 | 2 | [] | no_license | package net.minecraft.entity.ai;
import net.minecraft.entity.LivingEntity;
public interface RangedAttackMob {
void attack(LivingEntity target, float pullProgress);
}
| true |
ef00b4f250c5a105fa9eca59bcd848696d518c8d | Java | liubinchu/leetcode | /src/main/java/com/leetcode/OfferSord36_25.java | UTF-8 | 3,877 | 3.53125 | 4 | [] | no_license | package com.leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* @author liubi
* @date 2018-12-09 21:35
**/
public class OfferSord36_25 {
/**思路一:
* 算法分析: 注意: 叶子节点 的左右 指针 应该 指向祖先节点
* 左指针指向; 最后一个由右指针产生他/或者他的祖先 的 祖祖先节点
* 右指针指向; 最后一个由左指针产生他/或者他的祖先 的 祖祖先节点
* @param p
* @return
*/
private TreeNode findRightest(TreeNode p){
if(p==null){
return null;
}
while(p.right!=null){
p = p.right;
}
return p;
}
private TreeNode findLeftest(TreeNode p){
if(p==null){
return null;
}
while(p.left!=null){
p = p.left;
}
return p;
}
private void ConvertFun(TreeNode p,TreeNode rightFather, TreeNode leftFather){
TreeNode left = p.left;
TreeNode right = p.right;
if(p.left!=null&&p.right!=null){
p.left = findRightest(left);
p.right = findLeftest(right);
ConvertFun(right,p,leftFather);
ConvertFun(left,rightFather,p);
}
else if(p.left!=null && p.right == null){
p.left = findRightest(left);
p.right = leftFather;
ConvertFun(left,rightFather,p);
}
else if (p.left==null && p.right!=null){
p.left = rightFather;
p.right = findLeftest(right);
ConvertFun(right,p,leftFather);
}
else if(p.left ==null && p.right == null){
p.right = leftFather;
p.left = rightFather;
}
}
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null){
return null;
}
else{
//ConvertFun(pRootOfTree,null,null);
ConvertFun(pRootOfTree);
}
return findLeftest(pRootOfTree);
}
/**
* 思路二: 利用二叉搜索树的中序 遍历顺序就是 元素的排列顺序 因此 在中序遍历的基础上进行指针变化
* 引申:二叉搜索树的线索话 也可以类似实现
* @param root
*/
public void midOrderSearch(TreeNode root){
// 原始的中序遍历
if(root == null){
return;
}
midOrderSearch(root.left);
System.out.println(root.val);
midOrderSearch(root.right);
}
TreeNode lastNodeInList = null;
public void ConvertFun(TreeNode root){
if(root == null){
return;
}
ConvertFun(root.left);
// 将中序遍历的 遍历 部分 改为 更改指针的部分
root.left = lastNodeInList;
if(lastNodeInList!= null){
lastNodeInList.right = root;
}
lastNodeInList = root;
// 将中序遍历的 遍历 部分 改为 更改指针的部分
ConvertFun(root.right);
}
public static void main(String[] args) {
TreeNode root1 = new TreeNode(7);
root1.left = new TreeNode(4);
root1.right = new TreeNode(10);
root1.left.left = new TreeNode(2);
root1.left.right = new TreeNode(5);
root1.right.left = new TreeNode(9);
root1.right.right =new TreeNode(11);
root1.left.left.left = new TreeNode(1);
root1.left.left.right =new TreeNode(3);
root1.left.right.right = new TreeNode(6);
root1.right.left.left =new TreeNode(8);
root1.right.right.right =new TreeNode(12);
OfferSord36_25 solution = new OfferSord36_25();
//solution.midOrderSearch(root1);
root1 = solution.Convert(root1);
while(root1!=null){
System.out.println(root1.val);
root1 = root1.right;
}
}
}
| true |
93b9b6f9ad985ad9b0b41cb0febba4ffe83efdca | Java | hanlizhihao/management-system | /src/main/java/com/changjiang/entity/WorkstationRecord.java | UTF-8 | 3,183 | 2.1875 | 2 | [] | no_license | package com.changjiang.entity;
public class WorkstationRecord {
private Integer id;
private Integer userId;
private String userName;
private String userPhone;
private java.util.Date goWorkTime;
private java.util.Date leaveWorkTime;
private Integer counterId;
private Integer sonAreaId;
private java.util.Date workDay;
private Integer storeId;
private Integer workStationId;
private String number;
public WorkstationRecord() {
super();
}
public WorkstationRecord(Integer id,Integer userId,String userName,String userPhone,java.util.Date goWorkTime,java.util.Date leaveWorkTime,Integer counterId,Integer sonAreaId,java.util.Date workDay,Integer storeId,Integer workStationId,String number) {
super();
this.id = id;
this.userId = userId;
this.userName = userName;
this.userPhone = userPhone;
this.goWorkTime = goWorkTime;
this.leaveWorkTime = leaveWorkTime;
this.counterId = counterId;
this.sonAreaId = sonAreaId;
this.workDay = workDay;
this.storeId = storeId;
this.workStationId = workStationId;
this.number = number;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPhone() {
return this.userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public java.util.Date getGoWorkTime() {
return this.goWorkTime;
}
public void setGoWorkTime(java.util.Date goWorkTime) {
this.goWorkTime = goWorkTime;
}
public java.util.Date getLeaveWorkTime() {
return this.leaveWorkTime;
}
public void setLeaveWorkTime(java.util.Date leaveWorkTime) {
this.leaveWorkTime = leaveWorkTime;
}
public Integer getCounterId() {
return this.counterId;
}
public void setCounterId(Integer counterId) {
this.counterId = counterId;
}
public Integer getSonAreaId() {
return this.sonAreaId;
}
public void setSonAreaId(Integer sonAreaId) {
this.sonAreaId = sonAreaId;
}
public java.util.Date getWorkDay() {
return this.workDay;
}
public void setWorkDay(java.util.Date workDay) {
this.workDay = workDay;
}
public Integer getStoreId() {
return this.storeId;
}
public void setStoreId(Integer storeId) {
this.storeId = storeId;
}
public Integer getWorkStationId() {
return this.workStationId;
}
public void setWorkStationId(Integer workStationId) {
this.workStationId = workStationId;
}
public String getNumber() {
return this.number;
}
public void setNumber(String number) {
this.number = number;
}
}
| true |
a1ddfae456941c4bfd27b01d6755eddd1e0b23cf | Java | tt328307109/HLB_Studio | /HLBPay/src/com/lk/qf/pay/posloan/PolyLoansTabHostActivity.java | UTF-8 | 3,857 | 2.0625 | 2 | [] | no_license | package com.lk.qf.pay.posloan;
import com.lk.bhb.pay.R;
import com.lk.qf.pay.fragment.PolyLoanHKListFragment;
import com.lk.qf.pay.fragment.MyPolyLoanFragment;
import com.lk.qf.pay.wedget.CommonTitleBar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;
public class PolyLoansTabHostActivity extends FragmentActivity implements
OnClickListener {
private CommonTitleBar title;
// 定义FragmentTabHost对象
private FragmentTabHost fragmentTabHost;
// 定义一个线性布局
private LayoutInflater layoutInflater;
// 定义数组来存放Fragment界面
private Class[] fragmentArray = { MyPolyLoanFragment.class,
PolyLoanHKListFragment.class };
// 定义数组来存放按钮图片
// private int[] mImageViewArray =
// {R.drawable.tab_home_btn,R.drawable.tab_message_btn,R.drawable.tab_selfinfo_btn,
// R.drawable.tab_square_btn,R.drawable.tab_more_btn};
// Tab选项卡的文字
private String[] mTextviewArray = { "我的理贷", "还款记录" };
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.poly_loan_tab_layout);
init();
}
private void init() {
Log.i("result", "---------onCreate-------");
title = (CommonTitleBar) findViewById(R.id.titlebar_poly_loans_back);
title.setActName("保理贷");
title.setCanClickDestory(this, true);
findViewById(R.id.btn_applyPolyLoan).setOnClickListener(this);
// 实例化布局
layoutInflater = LayoutInflater.from(this);
// 实例化TabHost对象,得到TabHost
fragmentTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
// fragmentTabHost.setup();
fragmentTabHost.setup(this, getSupportFragmentManager(),
R.id.fl_realtabcontent);
// 得到fragment的个数
int count = fragmentArray.length;
for (int i = 0; i < count; i++) {
// 为每一个Tab按钮设置图标、文字和内容
TabSpec tabSpec = fragmentTabHost.newTabSpec(mTextviewArray[i])
.setIndicator(getTabItemView(i));
// 将Tab按钮添加进Tab选项卡中
fragmentTabHost.addTab(tabSpec, fragmentArray[i], null);
// // 设置Tab按钮的背景
// fragmentTabHost.getTabWidget().getChildAt(i)
// .setBackgroundResource(R.drawable.selector_tab_background);
}
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(PolyLoansTabHostActivity.this,
ApplyPolyLoanByLicaiActivity.class);
startActivity(intent);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// String str = PosData.getPosData().getRandom();
// if (str != null) {
// if (str.equals("isApplySuccess")) {
// Log.i("result", "---------str------------" + str);
// fragmentTabHost.setCurrentTab(1);
// PosData.getPosData().clearPosData();
// }
// }
}
/**
* 给Tab按钮设置图标和文字
*/
private View getTabItemView(int i) {
View view = layoutInflater.inflate(R.layout.tab_view_layout, null);
// //设置图像
// ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
// imageView.setImageResource(mImageViewArray[i]);
// 设置文字
TextView textView = (TextView) view.findViewById(R.id.tv_tab_poly_loan);
textView.setText(mTextviewArray[i]);
return view;
}
// @Override
// public void onClick(View arg0) {
// // TODO Auto-generated method stub
// Intent intent = new Intent(PolyLoansTabHostActivity.this,
// LoanHuanKuanListActivity.class);
// startActivity(intent);
// }
}
| true |
4824555d5bf840977c6516416340123d4ec34cfe | Java | 729533572/reader | /app/src/main/java/com/yn/reader/model/home/HomeGroup.java | UTF-8 | 370 | 1.804688 | 2 | [
"MIT"
] | permissive | package com.yn.reader.model.home;
import com.yn.reader.model.BaseData;
/**
* 首页导航所有信息
* Created by sunxy on 2017/12/26.
*/
public class HomeGroup extends BaseData {
private HomeList data;
public HomeList getData() {
return data;
}
public void setData(HomeList data) {
this.data = data;
}
}
| true |