blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
sequence | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
sequence | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
400ca1a875107d87b17749cb0a841cd9e059a63b | 14,989,435,868,988 | 99f53b587a17c9ec941dd49b370e7e16e3c30bb7 | /MainSource/trunk/src/main/java/com/mservice/momo/vertx/visampointpromo/VisaMpointPromoVerticle.java | a052ee27408562d9d8f9276d429f3b47400eb064 | [] | no_license | kevinlee2209/apollo_backend_vertx | https://github.com/kevinlee2209/apollo_backend_vertx | f2b4ec9ae605787b584cd998836aaecd431bfc96 | f35a45a89076afaaae79625a182bec07172ec96c | refs/heads/master | 2018-01-06T06:56:49.564000 | 2016-10-10T12:25:21 | 2016-10-10T12:25:21 | 70,472,922 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mservice.momo.vertx.visampointpromo;
import com.mservice.momo.data.AgentsDb;
import com.mservice.momo.data.DBFactory;
import com.mservice.momo.data.PromotionDb;
import com.mservice.momo.data.TransDb;
import com.mservice.momo.data.model.Promo;
import com.mservice.momo.data.model.colName;
import com.mservice.momo.gateway.internal.core.msg.Core;
import com.mservice.momo.msg.MomoProto;
import com.mservice.momo.util.DataUtil;
import com.mservice.momo.util.NotificationUtils;
import com.mservice.momo.util.StringConstUtil;
import com.mservice.momo.vertx.AppConstant;
import com.mservice.momo.vertx.gift.GiftManager;
import com.mservice.momo.vertx.models.Notification;
import com.mservice.momo.vertx.processor.Common;
import com.mservice.momo.vertx.processor.GiftProcess;
import com.mservice.momo.vertx.processor.Misc;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.platform.Verticle;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by concu on 5/21/15.
*/
public class VisaMpointPromoVerticle extends Verticle {
private Logger logger;
private JsonObject glbCfg;
private GiftManager giftManager;
private TransDb tranDb;
private JsonObject billpayPromoCfg;
private AgentsDb agentsDb;
private GiftProcess giftProcess;
private Common common;
private VisaMpointPromoDb visaMpointPromoDb;
private long totalMoney;
private int percent;
private String agent;
private VisaMpointErrorDb visaMpointErrorDb;
@Override
public void start() {
this.logger = getContainer().logger();
this.common = new Common(vertx, logger, container.config());
this.glbCfg = container.config();
final JsonObject visaMpointCfg = glbCfg.getObject("visampointpromo", new JsonObject());
this.tranDb = DBFactory.createTranDb(vertx, vertx.eventBus(), logger, container.config());
this.agentsDb = new AgentsDb(vertx.eventBus(), logger);
this.giftManager = new GiftManager(vertx, logger, glbCfg);
this.giftProcess = new GiftProcess(common, vertx, logger, glbCfg);
this.visaMpointPromoDb = new VisaMpointPromoDb(vertx, logger);
this.visaMpointErrorDb = new VisaMpointErrorDb(vertx, logger);
Handler<Message<JsonObject>> myHandler = new Handler<Message<JsonObject>>() {
@Override
public void handle(final Message<JsonObject> message) {
final JsonObject reqJson = message.body();
final VisaMpointPromoObj visaMpointPromoObj = new VisaMpointPromoObj(reqJson);
final Common.BuildLog log = new Common.BuildLog(logger);
log.setPhoneNumber(visaMpointPromoObj.phoneNumber);
log.add("", visaMpointPromoObj.phoneNumber);
log.add("trantype", visaMpointPromoObj.tranType);
log.add("tranid", visaMpointPromoObj.tranId);
log.add("cardnumber", visaMpointPromoObj.cardnumber);
log.add("amount", visaMpointPromoObj.visaAmount);
logger.info("tranIdVisa is " + visaMpointPromoObj.visatranId);
Promo.PromoReqObj promoReqObj = new Promo.PromoReqObj();
promoReqObj.COMMAND = Promo.PromoType.PROMO_GET_LIST;
Misc.requestPromoRecord(vertx, promoReqObj, logger, new Handler<JsonObject>() {
@Override
public void handle(JsonObject json) {
final JsonObject joReply = new JsonObject();
JsonArray array = json.getArray("array", null);
log.add("func", "requestPromoRecord");
if (array != null && array.size() > 0) {
ArrayList<PromotionDb.Obj> objs = new ArrayList<>();
PromotionDb.Obj obj_promo = null;
JsonObject jsonTime = new JsonObject();
long visaStartTime = 0;
long visaEndTime = 0;
for (Object o : array) {
// objs.add(new PromotionDb.Obj((JsonObject) o));
obj_promo = new PromotionDb.Obj((JsonObject) o);
if (obj_promo.NAME.equalsIgnoreCase(VisaMpointPromoConst.VISA_PROMO)) {
visaStartTime = obj_promo.DATE_FROM;
visaEndTime = obj_promo.DATE_TO;
break;
}
}
long currentTime = System.currentTimeMillis();
if (currentTime < visaStartTime || currentTime > visaEndTime) {
//Het thoi han khuyen mai
log.add("error", 1000);
log.add("desc", "Da het thoi gian khuyen mai");
joReply.putNumber("error", 1000);
joReply.putString("desc", "Da het thoi gian khuyen mai");
message.reply(joReply);
log.writeLog();
return;
}
JsonObject jsonSearch = new JsonObject();
jsonSearch.putString(colName.VisaMPointPromo.NUMBER, visaMpointPromoObj.phoneNumber);
//jsonSearch.putBoolean(colName.VisaMPointPromo.END_MONTH, false);
final long startTime = visaStartTime;
final long endTime = visaEndTime;
visaMpointPromoDb.searchWithFilter(jsonSearch, new Handler<ArrayList<VisaMpointPromoDb.Obj>>() {
@Override
public void handle(final ArrayList<VisaMpointPromoDb.Obj> objs) {
final JsonObject jsonReply = new JsonObject();
ArrayList<VisaMpointPromoDb.Obj> objs_tmp = new ArrayList<VisaMpointPromoDb.Obj>();
if (objs == null) //Loi khong biet vi sao loi
{
log.add("error", 1000);
log.add("desc", "Loi objs bi null, check lai code");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Loi objs bi null, check lai code");
message.reply(jsonReply);
log.writeLog();
return;
}
objs_tmp = (ArrayList<VisaMpointPromoDb.Obj>) objs.clone();
// Chua co record nao hoac co record ma da update het thang
if (objs != null && objs.size() > 0) {
//Loi khong update, yeu cau backend update
// log.add("error", 1000);
// log.add("desc", "Loi code, backend khong update record");
// jsonReply.putNumber("error", 1000);
// jsonReply.putString("desc", "Loi code, backend khong update record");
// message.reply(jsonReply);
// log.writeLog();
// return;
for (VisaMpointPromoDb.Obj visaObj : objs_tmp) {
if (visaObj.end_month) {
if (visaObj.time_1 < startTime || visaObj.time_2 < startTime) {
objs.remove(visaObj);
} else {
//Da nhan duoc day du point => khong tra thuong nua ....
log.add("error", 1000);
log.add("desc", "Da nhan day du qua roi");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Da nhan day du qua roi");
message.reply(jsonReply);
log.writeLog();
return;
}
}
}
}
if (objs != null && objs.size() == 0) {
JsonObject checkCardNumberJson = new JsonObject();
checkCardNumberJson.putString(colName.VisaMPointPromo.CARD_NUMBER, visaMpointPromoObj.cardnumber);
visaMpointPromoDb.searchWithFilter(checkCardNumberJson, new Handler<ArrayList<VisaMpointPromoDb.Obj>>() {
@Override
public void handle(ArrayList<VisaMpointPromoDb.Obj> checkCardNumberObjs) {
// if (visaMpointCfg == null) {
// //Loi he thong
// log.add("error", 1000);
// log.add("desc", "Loi khong load duoc file config");
// jsonReply.putNumber("error", 1000);
// jsonReply.putString("desc", "Loi khong load duoc file config");
// message.reply(jsonReply);
// log.writeLog();
// return;
// }
totalMoney = visaMpointCfg.getLong("total", 30000);
percent = visaMpointCfg.getInteger("percent", 10);
agent = visaMpointCfg.getString("agent", "visa_promo");
if (checkCardNumberObjs == null) {
log.add("error", 1000);
log.add("desc", "checkCardNumber == null");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Loi he thong");
message.reply(jsonReply);
log.writeLog();
return;
} else if (checkCardNumberObjs != null && checkCardNumberObjs.size() > 0) {
if (checkCardNumberObjs.get(0).number.equalsIgnoreCase(visaMpointPromoObj.phoneNumber)) {
VisaMpointPromoDb.Obj obj = new VisaMpointPromoDb.Obj();
obj.number = visaMpointPromoObj.phoneNumber;
obj.card_number = visaMpointPromoObj.cardnumber;
obj.time_1 = System.currentTimeMillis();
obj.time_2 = 0;
obj.tid_1 = visaMpointPromoObj.tranId;
obj.tid_2 = 0;
obj.trantype_1 = visaMpointPromoObj.tranType;
obj.trantype_2 = 0;
obj.end_month = false;
obj.mpoint_1 = calculateMpoint(visaMpointPromoObj.visaAmount, totalMoney);
obj.mpoint_2 = 0;
obj.promo_count = 1;
obj.tid_visa_1 = visaMpointPromoObj.visatranId;
obj.service_id_1 = visaMpointPromoObj.serviceId;
obj.total_amount_1 = visaMpointPromoObj.totalAmount;
obj.cashin_amount_1 = visaMpointPromoObj.visaAmount;
obj.cashinTime_1 = visaMpointPromoObj.cashinTime;
givePoint1(agent, log, obj, visaMpointPromoObj, message);
log.writeLog();
return;
} else {
log.add("error", 1000);
log.add("desc", "Ban da the nay voi mot vi khac, vui long map lai");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Ban da the nay voi mot vi khac, vui long map lai");
message.reply(jsonReply);
log.writeLog();
return;
}
} else if (checkCardNumberObjs != null && checkCardNumberObjs.size() == 0) {
VisaMpointPromoDb.Obj obj = new VisaMpointPromoDb.Obj();
obj.number = visaMpointPromoObj.phoneNumber;
obj.card_number = visaMpointPromoObj.cardnumber;
obj.time_1 = System.currentTimeMillis();
obj.time_2 = 0;
obj.tid_1 = visaMpointPromoObj.tranId;
obj.tid_2 = 0;
obj.trantype_1 = visaMpointPromoObj.tranType;
obj.trantype_2 = 0;
obj.end_month = false;
obj.mpoint_1 = calculateMpoint(visaMpointPromoObj.visaAmount, totalMoney);
obj.mpoint_2 = 0;
obj.promo_count = 1;
obj.tid_visa_1 = visaMpointPromoObj.visatranId;
obj.service_id_1 = visaMpointPromoObj.serviceId;
obj.total_amount_1 = visaMpointPromoObj.totalAmount;
obj.cashin_amount_1 = visaMpointPromoObj.visaAmount;
obj.cashinTime_1 = visaMpointPromoObj.cashinTime;
givePoint1(agent, log, obj, visaMpointPromoObj, message);
log.writeLog();
return;
} else {
log.add("error", 1000);
log.add("desc", "checkCardNumber == null");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Loi he thong");
message.reply(jsonReply);
log.writeLog();
return;
}
}
});
return;
}
//Lay thoi gian dau tien cua thang hien tai.
// Calendar calendar = Calendar.getInstance();
// long currentTime = System.currentTimeMillis();
// int month = calendar.get(Calendar.MONTH);
// int year = calendar.get(Calendar.YEAR);
//
// calendar.set(year, month, 1, 0, 0, 0);
// long startMonth = calendar.getTimeInMillis();
if (objs.get(0) == null) {
log.add("error", 1000);
log.add("desc", "Loi objs.get(0) bi null, check lai code");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Loi objs.get(0) bi null, check lai code");
message.reply(jsonReply);
log.writeLog();
return;
}
if (objs.get(0).tid_visa_1 == visaMpointPromoObj.visatranId || objs.get(0).tid_visa_2 == visaMpointPromoObj.visatranId) {
log.add("error", 1000);
log.add("desc", "Da tra thuong, khong tra nua");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Da tra thuong, khong tra nua");
message.reply(jsonReply);
log.writeLog();
return;
}
if (!visaMpointPromoObj.cardnumber.equalsIgnoreCase(objs.get(0).card_number)) {
log.add("error", 1000);
log.add("desc", "Loi mapping 1 the khac vao vi, khong tra thuong cho ku");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Loi mapping 1 the khac vao vi, khong tra thuong cho ku");
message.reply(jsonReply);
log.writeLog();
return;
}
if (objs.get(0).time_1 != 0 && objs.get(0).time_2 != 0) {
log.add("error", 1000);
log.add("desc", "Nhan du so lan tra thuong");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Nhan du so lan tra thuong");
message.reply(jsonReply);
log.writeLog();
return;
}
if (objs.get(0).promo_count > 1) {
//Nhan roi nhan hoai, tham qua
log.add("error", 1000);
log.add("desc", "Da nhan day du qua thuong");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Da nhan day du qua thuong");
message.reply(jsonReply);
log.writeLog();
return;
}
long point1 = objs.get(0).mpoint_1;
long point2 = objs.get(0).mpoint_2;
// if (point1 > 29999) {
// //Nhan day du roi, khong tra nua.
// log.add("error", 1000);
// log.add("desc", "Da nhan day du qua thuong");
// jsonReply.putNumber("error", 1000);
// jsonReply.putString("desc", "Da nhan day du qua thuong");
// message.reply(jsonReply);
// return;
// }
if (point1 != 0 && point2 != 0) {
//Nhan day du roi, khong tra nua.
log.add("error", 1000);
log.add("desc", "Da nhan day du qua thuong");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Da nhan day du qua thuong");
message.reply(jsonReply);
log.writeLog();
return;
}
if (objs.get(0).time_1 < startTime) {
//todo Update lai thanh true.
JsonObject jsonUpdate = new JsonObject();
jsonUpdate.putBoolean(colName.VisaMPointPromo.END_MONTH, true);
visaMpointPromoDb.updatePartial(visaMpointPromoObj.phoneNumber, jsonUpdate, new Handler<Boolean>() {
@Override
public void handle(Boolean aBoolean) {
}
});
VisaMpointPromoDb.Obj obj = new VisaMpointPromoDb.Obj();
obj.number = visaMpointPromoObj.phoneNumber;
obj.card_number = visaMpointPromoObj.cardnumber;
obj.time_1 = System.currentTimeMillis();
obj.time_2 = 0;
obj.tid_1 = visaMpointPromoObj.tranId;
obj.tid_2 = 0;
obj.trantype_1 = visaMpointPromoObj.tranType;
obj.trantype_2 = 0;
obj.end_month = false;
obj.mpoint_1 = calculateMpoint(visaMpointPromoObj.visaAmount, totalMoney);
obj.mpoint_2 = 0;
obj.promo_count = 1;
obj.tid_visa_1 = visaMpointPromoObj.visatranId;
//
obj.service_id_1 = visaMpointPromoObj.serviceId;
obj.total_amount_1 = visaMpointPromoObj.totalAmount;
obj.cashin_amount_1 = visaMpointPromoObj.visaAmount;
obj.cashinTime_1 = visaMpointPromoObj.cashinTime;
givePoint1(agent, log, obj, visaMpointPromoObj, message);
//Tao record cho thang moi.
log.writeLog();
return;
}
// if (point1 == 0) {
// // Tra thuong vao point 1
// point1 = calculateMpoint(visaMpointPromoObj.amount, totalMoney);
// VisaMpointPromoDb.Obj obj = new VisaMpointPromoDb.Obj();
// obj.number = visaMpointPromoObj.phoneNumber;
// obj.card_number = visaMpointPromoObj.cardnumber;
// obj.time_1 = System.currentTimeMillis();
// obj.time_2 = 0;
// obj.tid_1 = visaMpointPromoObj.tranId;
// obj.tid_2 = 0;
// obj.trantype_1 = visaMpointPromoObj.tranType;
// obj.trantype_2 = 0;
// obj.end_month = false;
// obj.mpoint_1 = point1;
// obj.mpoint_2 = 0;
// obj.promo_count = 1;
// givePoint1(agent, log, obj, visaMpointPromoObj, message);
// }
// else
if (point2 == 0) {
//Se nhan qua 2.
point2 = calculateMpoint(visaMpointPromoObj.visaAmount, totalMoney);
givePoint2(agent, point2, log, visaMpointPromoObj, message);
log.writeLog();
}
log.writeLog();
}
});//end
}
}
});
}
};
vertx.eventBus().registerLocalHandler(AppConstant.VISA_MPOINT_BUSS_ADDRESS, myHandler);
}
public void givePoint1(final String fromAgent, final Common.BuildLog log, final VisaMpointPromoDb.Obj dbObj, final VisaMpointPromoObj requestObj, final Message<JsonObject> message) {
log.add("func", "givePoint1");
Misc.adjustment(vertx, fromAgent, requestObj.phoneNumber, dbObj.mpoint_1, Core.WalletType.POINT_VALUE, new ArrayList<Misc.KeyValue>(), new Common.BuildLog(logger), new Handler<Common.SoapObjReply>() {
@Override
public void handle(Common.SoapObjReply coreReply) {
//ClaimHistory history = new ClaimHistory(fromAgent, requestObj.phoneNumber, coreReply.error, pointAmount, coreReply.tranId, null, code);
//history.comment = "transferPoint";
//claimHistoryDb.save(history, null);
log.add("func", "adjustment");
log.add("error", coreReply.error);
log.add("tranId", coreReply.tranId);
// log.writeLog();
JsonObject jsonRep = new JsonObject();
if (coreReply.error != 0) {
log.add("error", coreReply.error);
log.add("amount", coreReply.amount);
log.add("desc", "Loi tra ve tu core");
jsonRep.putNumber("error", coreReply.error);
jsonRep.putNumber("amount", coreReply.amount);
jsonRep.putString("desc", "Loi tra ve tu core");
message.reply(jsonRep);
VisaMpointErrorDb.Obj vsErrorObj = new VisaMpointErrorDb.Obj();
vsErrorObj.cardnumber = requestObj.cardnumber;
vsErrorObj.number = requestObj.phoneNumber;
vsErrorObj.tranid = requestObj.tranId;
vsErrorObj.trantype = requestObj.tranType;
vsErrorObj.error = coreReply.error;
vsErrorObj.desc_error = "Loi tra ve tu core";
vsErrorObj.time = System.currentTimeMillis();
vsErrorObj.count = 1;
visaMpointErrorDb.insert(vsErrorObj, new Handler<Integer>() {
@Override
public void handle(Integer integer) {
}
});
log.writeLog();
return;
}
visaMpointPromoDb.insert(dbObj, new Handler<Integer>() {
@Override
public void handle(Integer integer) {
}
});
String notiCaption = "Nhận tiền khuyến mãi ";
String notiBody = "Quý khách vừa nhận được " + NotificationUtils.getAmount(dbObj.mpoint_1) + "đ vào Tài khoản KM khi thực hiện thanh toán bằng thẻ Visa. Quý khách sẽ sử dụng được tiền trong Tài khoản KM khi tích lũy đủ 50.000đ. Chi tiết liên hệ (08 39917199 hoặc http: momo.vn/thanhtoanhoadon";
final Notification noti = new Notification();
noti.priority = 2;
noti.type = MomoProto.NotificationType.NOTI_TRANSACTION_VALUE;
noti.caption = notiCaption;// "Nhận thưởng quà khuyến mãi";
noti.body = notiBody;//"Bạn vừa nhận được thẻ quà tặng trị giá 100.000đ từ chương trình khuyến mãi “Liên kết tài khoản Vietcombank- Cùng nhận thưởng 100.000đ”. Vui lòng về màn hình chính của ứng dụng ví MoMo, nhấn vào “Số tiền trong ví”, bạn sẽ vào “Tài khoản của tôi” và thấy thẻ quà tặng bạn vừa nhận.";
noti.tranId = coreReply.tranId;
noti.time = new Date().getTime();
noti.receiverNumber = DataUtil.strToInt(requestObj.phoneNumber);
Misc.sendNoti(vertx, noti);
log.writeLog();
// common.sendCurrentAgentInfo(vertx, sock, 0, msg.cmdPhone, data);
jsonRep.putNumber(StringConstUtil.TRANDB_TRAN_ID, coreReply.tranId);
jsonRep.putNumber("error", coreReply.error);
jsonRep.putString("desc", "Thanh cong");
logger.info("error is " + coreReply.error);
logger.info("desc is Thanh cong");
message.reply(jsonRep);
return;
}
});
}
public void givePoint2(final String fromAgent, final long pointAmount, final Common.BuildLog log, final VisaMpointPromoObj requestObj, final Message<JsonObject> message) {
log.add("func", "givePoint2");
Misc.adjustment(vertx, fromAgent, requestObj.phoneNumber, pointAmount, Core.WalletType.POINT_VALUE, new ArrayList<Misc.KeyValue>(), new Common.BuildLog(logger), new Handler<Common.SoapObjReply>() {
@Override
public void handle(Common.SoapObjReply coreReply) {
log.add("func", "adjustment");
log.add("error", coreReply.error);
log.add("tranId", coreReply.tranId);
// log.writeLog();
JsonObject jsonRep = new JsonObject();
if (coreReply.error != 0) {
log.add("error", coreReply.error);
log.add("amount", coreReply.amount);
log.add("desc", "Loi tra ve tu core");
jsonRep.putNumber("error", coreReply.error);
jsonRep.putNumber("amount", coreReply.amount);
jsonRep.putString("desc", "Loi tra ve tu core");
VisaMpointErrorDb.Obj vsErrorObj = new VisaMpointErrorDb.Obj();
vsErrorObj.cardnumber = requestObj.cardnumber;
vsErrorObj.number = requestObj.phoneNumber;
vsErrorObj.tranid = requestObj.tranId;
vsErrorObj.trantype = requestObj.tranType;
vsErrorObj.error = coreReply.error;
vsErrorObj.desc_error = "Loi tra ve tu core";
vsErrorObj.time = System.currentTimeMillis();
vsErrorObj.count = 2;
visaMpointErrorDb.insert(vsErrorObj, new Handler<Integer>() {
@Override
public void handle(Integer integer) {
}
});
message.reply(jsonRep);
log.writeLog();
return;
}
// VisaMpointPromoDb.Obj obj = new VisaMpointPromoDb.Obj();
// obj.mpoint_2 = pointAmount;
// obj.tid_2 = requestObj.tranId;
// obj.trantype_2 = requestObj.tranType;
// obj.end_month = false;
// obj.promo_count = 2;
// obj.time_2 = System.currentTimeMillis();
JsonObject joUpdate = new JsonObject();
joUpdate.putNumber(colName.VisaMPointPromo.MPOINT_2, pointAmount);
joUpdate.putNumber(colName.VisaMPointPromo.TID_2, requestObj.tranId);
joUpdate.putNumber(colName.VisaMPointPromo.TRANTYPE_2, requestObj.tranType);
joUpdate.putNumber(colName.VisaMPointPromo.PROMO_COUNT, 2);
joUpdate.putBoolean(colName.VisaMPointPromo.END_MONTH, true);
joUpdate.putNumber(colName.VisaMPointPromo.TIME_2, System.currentTimeMillis());
joUpdate.putNumber(colName.VisaMPointPromo.TID_VISA_2, requestObj.visatranId);
joUpdate.putString(colName.VisaMPointPromo.SERVICE_ID_2, requestObj.serviceId);
joUpdate.putNumber(colName.VisaMPointPromo.TOTAL_AMOUNT_2, requestObj.totalAmount);
joUpdate.putNumber(colName.VisaMPointPromo.CASH_IN_AMOUNT_2, requestObj.visaAmount);
joUpdate.putNumber(colName.VisaMPointPromo.CASH_IN_TIME_2, requestObj.cashinTime);
visaMpointPromoDb.updatePartial(requestObj.phoneNumber, joUpdate, new Handler<Boolean>() {
@Override
public void handle(Boolean aBoolean) {
}
});
String notiCaption = "Nhận tiền khuyến mãi ";
String notiBody = "Quý khách vừa nhận được " + NotificationUtils.getAmount(pointAmount) + "đ vào Tài khoản KM khi thực hiện thanh toán bằng thẻ Visa. Quý khách sẽ sử dụng được tiền trong Tài khoản KM khi tích lũy đủ 50.000đ. Chi tiết liên hệ (08 39917199 hoặc http: momo.vn/thanhtoanhoadon";
final Notification noti = new Notification();
noti.priority = 2;
noti.type = MomoProto.NotificationType.NOTI_TRANSACTION_VALUE;
noti.caption = notiCaption;// "Nhận thưởng quà khuyến mãi";
noti.body = notiBody;//"Bạn vừa nhận được thẻ quà tặng trị giá 100.000đ từ chương trình khuyến mãi “Liên kết tài khoản Vietcombank- Cùng nhận thưởng 100.000đ”. Vui lòng về màn hình chính của ứng dụng ví MoMo, nhấn vào “Số tiền trong ví”, bạn sẽ vào “Tài khoản của tôi” và thấy thẻ quà tặng bạn vừa nhận.";
noti.tranId = coreReply.tranId;
noti.time = new Date().getTime();
// noti.extra = new JsonObject()
// .putString("giftId", gift.getModelId())
// .putString("giftTypeId", gift.typeId)
// .putString("amount", String.valueOf(tranAmount))
// .putString("sender", "Trải nghiệm thanh toán")
// .putString("senderName", "MoMo")
// .putString("msg",giftMessage)
// .putNumber("status", gift.status)
// .putString("serviceid", gift.typeId)
// .toString();
noti.receiverNumber = DataUtil.strToInt(requestObj.phoneNumber);
Misc.sendNoti(vertx, noti);
log.writeLog();
jsonRep.putNumber(StringConstUtil.TRANDB_TRAN_ID, coreReply.tranId);
jsonRep.putNumber("error", coreReply.error);
jsonRep.putString("desc", "Thanh cong");
logger.info("error is " + coreReply.error);
logger.info("desc is Thanh cong");
message.reply(jsonRep);
return;
}
});
}
public long calculateMpoint(long amount, long totalBalance) {
long mpoint = 0;
long mpoint_tmp = (long) (Math.ceil(percent * 0.01 * amount));
if (mpoint_tmp > totalBalance) {
mpoint = totalBalance;
} else {
mpoint = mpoint_tmp;
}
return mpoint;
}
}
| UTF-8 | Java | 38,483 | java | VisaMpointPromoVerticle.java | Java | [
{
"context": "rayList;\nimport java.util.Date;\n\n/**\n * Created by concu on 5/21/15.\n */\npublic class VisaMpointPromoVerti",
"end": 1157,
"score": 0.9995588660240173,
"start": 1152,
"tag": "USERNAME",
"value": "concu"
},
{
"context": " tiết liên hệ (08 39917199 hoặc http: momo.vn/thanhtoanhoadon\";\n final Notification noti = n",
"end": 35957,
"score": 0.5855165123939514,
"start": 35950,
"tag": "USERNAME",
"value": "htoanho"
},
{
"context": "n hệ (08 39917199 hoặc http: momo.vn/thanhtoanhoadon\";\n final Notification noti = new N",
"end": 35961,
"score": 0.6359570622444153,
"start": 35959,
"tag": "USERNAME",
"value": "on"
},
{
"context": " .putString(\"senderName\", \"MoMo\")\n// .putString(\"msg\",gift",
"end": 37018,
"score": 0.9974778890609741,
"start": 37014,
"tag": "USERNAME",
"value": "MoMo"
}
] | null | [] | package com.mservice.momo.vertx.visampointpromo;
import com.mservice.momo.data.AgentsDb;
import com.mservice.momo.data.DBFactory;
import com.mservice.momo.data.PromotionDb;
import com.mservice.momo.data.TransDb;
import com.mservice.momo.data.model.Promo;
import com.mservice.momo.data.model.colName;
import com.mservice.momo.gateway.internal.core.msg.Core;
import com.mservice.momo.msg.MomoProto;
import com.mservice.momo.util.DataUtil;
import com.mservice.momo.util.NotificationUtils;
import com.mservice.momo.util.StringConstUtil;
import com.mservice.momo.vertx.AppConstant;
import com.mservice.momo.vertx.gift.GiftManager;
import com.mservice.momo.vertx.models.Notification;
import com.mservice.momo.vertx.processor.Common;
import com.mservice.momo.vertx.processor.GiftProcess;
import com.mservice.momo.vertx.processor.Misc;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.platform.Verticle;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by concu on 5/21/15.
*/
public class VisaMpointPromoVerticle extends Verticle {
private Logger logger;
private JsonObject glbCfg;
private GiftManager giftManager;
private TransDb tranDb;
private JsonObject billpayPromoCfg;
private AgentsDb agentsDb;
private GiftProcess giftProcess;
private Common common;
private VisaMpointPromoDb visaMpointPromoDb;
private long totalMoney;
private int percent;
private String agent;
private VisaMpointErrorDb visaMpointErrorDb;
@Override
public void start() {
this.logger = getContainer().logger();
this.common = new Common(vertx, logger, container.config());
this.glbCfg = container.config();
final JsonObject visaMpointCfg = glbCfg.getObject("visampointpromo", new JsonObject());
this.tranDb = DBFactory.createTranDb(vertx, vertx.eventBus(), logger, container.config());
this.agentsDb = new AgentsDb(vertx.eventBus(), logger);
this.giftManager = new GiftManager(vertx, logger, glbCfg);
this.giftProcess = new GiftProcess(common, vertx, logger, glbCfg);
this.visaMpointPromoDb = new VisaMpointPromoDb(vertx, logger);
this.visaMpointErrorDb = new VisaMpointErrorDb(vertx, logger);
Handler<Message<JsonObject>> myHandler = new Handler<Message<JsonObject>>() {
@Override
public void handle(final Message<JsonObject> message) {
final JsonObject reqJson = message.body();
final VisaMpointPromoObj visaMpointPromoObj = new VisaMpointPromoObj(reqJson);
final Common.BuildLog log = new Common.BuildLog(logger);
log.setPhoneNumber(visaMpointPromoObj.phoneNumber);
log.add("", visaMpointPromoObj.phoneNumber);
log.add("trantype", visaMpointPromoObj.tranType);
log.add("tranid", visaMpointPromoObj.tranId);
log.add("cardnumber", visaMpointPromoObj.cardnumber);
log.add("amount", visaMpointPromoObj.visaAmount);
logger.info("tranIdVisa is " + visaMpointPromoObj.visatranId);
Promo.PromoReqObj promoReqObj = new Promo.PromoReqObj();
promoReqObj.COMMAND = Promo.PromoType.PROMO_GET_LIST;
Misc.requestPromoRecord(vertx, promoReqObj, logger, new Handler<JsonObject>() {
@Override
public void handle(JsonObject json) {
final JsonObject joReply = new JsonObject();
JsonArray array = json.getArray("array", null);
log.add("func", "requestPromoRecord");
if (array != null && array.size() > 0) {
ArrayList<PromotionDb.Obj> objs = new ArrayList<>();
PromotionDb.Obj obj_promo = null;
JsonObject jsonTime = new JsonObject();
long visaStartTime = 0;
long visaEndTime = 0;
for (Object o : array) {
// objs.add(new PromotionDb.Obj((JsonObject) o));
obj_promo = new PromotionDb.Obj((JsonObject) o);
if (obj_promo.NAME.equalsIgnoreCase(VisaMpointPromoConst.VISA_PROMO)) {
visaStartTime = obj_promo.DATE_FROM;
visaEndTime = obj_promo.DATE_TO;
break;
}
}
long currentTime = System.currentTimeMillis();
if (currentTime < visaStartTime || currentTime > visaEndTime) {
//Het thoi han khuyen mai
log.add("error", 1000);
log.add("desc", "Da het thoi gian khuyen mai");
joReply.putNumber("error", 1000);
joReply.putString("desc", "Da het thoi gian khuyen mai");
message.reply(joReply);
log.writeLog();
return;
}
JsonObject jsonSearch = new JsonObject();
jsonSearch.putString(colName.VisaMPointPromo.NUMBER, visaMpointPromoObj.phoneNumber);
//jsonSearch.putBoolean(colName.VisaMPointPromo.END_MONTH, false);
final long startTime = visaStartTime;
final long endTime = visaEndTime;
visaMpointPromoDb.searchWithFilter(jsonSearch, new Handler<ArrayList<VisaMpointPromoDb.Obj>>() {
@Override
public void handle(final ArrayList<VisaMpointPromoDb.Obj> objs) {
final JsonObject jsonReply = new JsonObject();
ArrayList<VisaMpointPromoDb.Obj> objs_tmp = new ArrayList<VisaMpointPromoDb.Obj>();
if (objs == null) //Loi khong biet vi sao loi
{
log.add("error", 1000);
log.add("desc", "Loi objs bi null, check lai code");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Loi objs bi null, check lai code");
message.reply(jsonReply);
log.writeLog();
return;
}
objs_tmp = (ArrayList<VisaMpointPromoDb.Obj>) objs.clone();
// Chua co record nao hoac co record ma da update het thang
if (objs != null && objs.size() > 0) {
//Loi khong update, yeu cau backend update
// log.add("error", 1000);
// log.add("desc", "Loi code, backend khong update record");
// jsonReply.putNumber("error", 1000);
// jsonReply.putString("desc", "Loi code, backend khong update record");
// message.reply(jsonReply);
// log.writeLog();
// return;
for (VisaMpointPromoDb.Obj visaObj : objs_tmp) {
if (visaObj.end_month) {
if (visaObj.time_1 < startTime || visaObj.time_2 < startTime) {
objs.remove(visaObj);
} else {
//Da nhan duoc day du point => khong tra thuong nua ....
log.add("error", 1000);
log.add("desc", "Da nhan day du qua roi");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Da nhan day du qua roi");
message.reply(jsonReply);
log.writeLog();
return;
}
}
}
}
if (objs != null && objs.size() == 0) {
JsonObject checkCardNumberJson = new JsonObject();
checkCardNumberJson.putString(colName.VisaMPointPromo.CARD_NUMBER, visaMpointPromoObj.cardnumber);
visaMpointPromoDb.searchWithFilter(checkCardNumberJson, new Handler<ArrayList<VisaMpointPromoDb.Obj>>() {
@Override
public void handle(ArrayList<VisaMpointPromoDb.Obj> checkCardNumberObjs) {
// if (visaMpointCfg == null) {
// //Loi he thong
// log.add("error", 1000);
// log.add("desc", "Loi khong load duoc file config");
// jsonReply.putNumber("error", 1000);
// jsonReply.putString("desc", "Loi khong load duoc file config");
// message.reply(jsonReply);
// log.writeLog();
// return;
// }
totalMoney = visaMpointCfg.getLong("total", 30000);
percent = visaMpointCfg.getInteger("percent", 10);
agent = visaMpointCfg.getString("agent", "visa_promo");
if (checkCardNumberObjs == null) {
log.add("error", 1000);
log.add("desc", "checkCardNumber == null");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Loi he thong");
message.reply(jsonReply);
log.writeLog();
return;
} else if (checkCardNumberObjs != null && checkCardNumberObjs.size() > 0) {
if (checkCardNumberObjs.get(0).number.equalsIgnoreCase(visaMpointPromoObj.phoneNumber)) {
VisaMpointPromoDb.Obj obj = new VisaMpointPromoDb.Obj();
obj.number = visaMpointPromoObj.phoneNumber;
obj.card_number = visaMpointPromoObj.cardnumber;
obj.time_1 = System.currentTimeMillis();
obj.time_2 = 0;
obj.tid_1 = visaMpointPromoObj.tranId;
obj.tid_2 = 0;
obj.trantype_1 = visaMpointPromoObj.tranType;
obj.trantype_2 = 0;
obj.end_month = false;
obj.mpoint_1 = calculateMpoint(visaMpointPromoObj.visaAmount, totalMoney);
obj.mpoint_2 = 0;
obj.promo_count = 1;
obj.tid_visa_1 = visaMpointPromoObj.visatranId;
obj.service_id_1 = visaMpointPromoObj.serviceId;
obj.total_amount_1 = visaMpointPromoObj.totalAmount;
obj.cashin_amount_1 = visaMpointPromoObj.visaAmount;
obj.cashinTime_1 = visaMpointPromoObj.cashinTime;
givePoint1(agent, log, obj, visaMpointPromoObj, message);
log.writeLog();
return;
} else {
log.add("error", 1000);
log.add("desc", "Ban da the nay voi mot vi khac, vui long map lai");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Ban da the nay voi mot vi khac, vui long map lai");
message.reply(jsonReply);
log.writeLog();
return;
}
} else if (checkCardNumberObjs != null && checkCardNumberObjs.size() == 0) {
VisaMpointPromoDb.Obj obj = new VisaMpointPromoDb.Obj();
obj.number = visaMpointPromoObj.phoneNumber;
obj.card_number = visaMpointPromoObj.cardnumber;
obj.time_1 = System.currentTimeMillis();
obj.time_2 = 0;
obj.tid_1 = visaMpointPromoObj.tranId;
obj.tid_2 = 0;
obj.trantype_1 = visaMpointPromoObj.tranType;
obj.trantype_2 = 0;
obj.end_month = false;
obj.mpoint_1 = calculateMpoint(visaMpointPromoObj.visaAmount, totalMoney);
obj.mpoint_2 = 0;
obj.promo_count = 1;
obj.tid_visa_1 = visaMpointPromoObj.visatranId;
obj.service_id_1 = visaMpointPromoObj.serviceId;
obj.total_amount_1 = visaMpointPromoObj.totalAmount;
obj.cashin_amount_1 = visaMpointPromoObj.visaAmount;
obj.cashinTime_1 = visaMpointPromoObj.cashinTime;
givePoint1(agent, log, obj, visaMpointPromoObj, message);
log.writeLog();
return;
} else {
log.add("error", 1000);
log.add("desc", "checkCardNumber == null");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Loi he thong");
message.reply(jsonReply);
log.writeLog();
return;
}
}
});
return;
}
//Lay thoi gian dau tien cua thang hien tai.
// Calendar calendar = Calendar.getInstance();
// long currentTime = System.currentTimeMillis();
// int month = calendar.get(Calendar.MONTH);
// int year = calendar.get(Calendar.YEAR);
//
// calendar.set(year, month, 1, 0, 0, 0);
// long startMonth = calendar.getTimeInMillis();
if (objs.get(0) == null) {
log.add("error", 1000);
log.add("desc", "Loi objs.get(0) bi null, check lai code");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Loi objs.get(0) bi null, check lai code");
message.reply(jsonReply);
log.writeLog();
return;
}
if (objs.get(0).tid_visa_1 == visaMpointPromoObj.visatranId || objs.get(0).tid_visa_2 == visaMpointPromoObj.visatranId) {
log.add("error", 1000);
log.add("desc", "Da tra thuong, khong tra nua");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Da tra thuong, khong tra nua");
message.reply(jsonReply);
log.writeLog();
return;
}
if (!visaMpointPromoObj.cardnumber.equalsIgnoreCase(objs.get(0).card_number)) {
log.add("error", 1000);
log.add("desc", "Loi mapping 1 the khac vao vi, khong tra thuong cho ku");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Loi mapping 1 the khac vao vi, khong tra thuong cho ku");
message.reply(jsonReply);
log.writeLog();
return;
}
if (objs.get(0).time_1 != 0 && objs.get(0).time_2 != 0) {
log.add("error", 1000);
log.add("desc", "Nhan du so lan tra thuong");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Nhan du so lan tra thuong");
message.reply(jsonReply);
log.writeLog();
return;
}
if (objs.get(0).promo_count > 1) {
//Nhan roi nhan hoai, tham qua
log.add("error", 1000);
log.add("desc", "Da nhan day du qua thuong");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Da nhan day du qua thuong");
message.reply(jsonReply);
log.writeLog();
return;
}
long point1 = objs.get(0).mpoint_1;
long point2 = objs.get(0).mpoint_2;
// if (point1 > 29999) {
// //Nhan day du roi, khong tra nua.
// log.add("error", 1000);
// log.add("desc", "Da nhan day du qua thuong");
// jsonReply.putNumber("error", 1000);
// jsonReply.putString("desc", "Da nhan day du qua thuong");
// message.reply(jsonReply);
// return;
// }
if (point1 != 0 && point2 != 0) {
//Nhan day du roi, khong tra nua.
log.add("error", 1000);
log.add("desc", "Da nhan day du qua thuong");
jsonReply.putNumber("error", 1000);
jsonReply.putString("desc", "Da nhan day du qua thuong");
message.reply(jsonReply);
log.writeLog();
return;
}
if (objs.get(0).time_1 < startTime) {
//todo Update lai thanh true.
JsonObject jsonUpdate = new JsonObject();
jsonUpdate.putBoolean(colName.VisaMPointPromo.END_MONTH, true);
visaMpointPromoDb.updatePartial(visaMpointPromoObj.phoneNumber, jsonUpdate, new Handler<Boolean>() {
@Override
public void handle(Boolean aBoolean) {
}
});
VisaMpointPromoDb.Obj obj = new VisaMpointPromoDb.Obj();
obj.number = visaMpointPromoObj.phoneNumber;
obj.card_number = visaMpointPromoObj.cardnumber;
obj.time_1 = System.currentTimeMillis();
obj.time_2 = 0;
obj.tid_1 = visaMpointPromoObj.tranId;
obj.tid_2 = 0;
obj.trantype_1 = visaMpointPromoObj.tranType;
obj.trantype_2 = 0;
obj.end_month = false;
obj.mpoint_1 = calculateMpoint(visaMpointPromoObj.visaAmount, totalMoney);
obj.mpoint_2 = 0;
obj.promo_count = 1;
obj.tid_visa_1 = visaMpointPromoObj.visatranId;
//
obj.service_id_1 = visaMpointPromoObj.serviceId;
obj.total_amount_1 = visaMpointPromoObj.totalAmount;
obj.cashin_amount_1 = visaMpointPromoObj.visaAmount;
obj.cashinTime_1 = visaMpointPromoObj.cashinTime;
givePoint1(agent, log, obj, visaMpointPromoObj, message);
//Tao record cho thang moi.
log.writeLog();
return;
}
// if (point1 == 0) {
// // Tra thuong vao point 1
// point1 = calculateMpoint(visaMpointPromoObj.amount, totalMoney);
// VisaMpointPromoDb.Obj obj = new VisaMpointPromoDb.Obj();
// obj.number = visaMpointPromoObj.phoneNumber;
// obj.card_number = visaMpointPromoObj.cardnumber;
// obj.time_1 = System.currentTimeMillis();
// obj.time_2 = 0;
// obj.tid_1 = visaMpointPromoObj.tranId;
// obj.tid_2 = 0;
// obj.trantype_1 = visaMpointPromoObj.tranType;
// obj.trantype_2 = 0;
// obj.end_month = false;
// obj.mpoint_1 = point1;
// obj.mpoint_2 = 0;
// obj.promo_count = 1;
// givePoint1(agent, log, obj, visaMpointPromoObj, message);
// }
// else
if (point2 == 0) {
//Se nhan qua 2.
point2 = calculateMpoint(visaMpointPromoObj.visaAmount, totalMoney);
givePoint2(agent, point2, log, visaMpointPromoObj, message);
log.writeLog();
}
log.writeLog();
}
});//end
}
}
});
}
};
vertx.eventBus().registerLocalHandler(AppConstant.VISA_MPOINT_BUSS_ADDRESS, myHandler);
}
public void givePoint1(final String fromAgent, final Common.BuildLog log, final VisaMpointPromoDb.Obj dbObj, final VisaMpointPromoObj requestObj, final Message<JsonObject> message) {
log.add("func", "givePoint1");
Misc.adjustment(vertx, fromAgent, requestObj.phoneNumber, dbObj.mpoint_1, Core.WalletType.POINT_VALUE, new ArrayList<Misc.KeyValue>(), new Common.BuildLog(logger), new Handler<Common.SoapObjReply>() {
@Override
public void handle(Common.SoapObjReply coreReply) {
//ClaimHistory history = new ClaimHistory(fromAgent, requestObj.phoneNumber, coreReply.error, pointAmount, coreReply.tranId, null, code);
//history.comment = "transferPoint";
//claimHistoryDb.save(history, null);
log.add("func", "adjustment");
log.add("error", coreReply.error);
log.add("tranId", coreReply.tranId);
// log.writeLog();
JsonObject jsonRep = new JsonObject();
if (coreReply.error != 0) {
log.add("error", coreReply.error);
log.add("amount", coreReply.amount);
log.add("desc", "Loi tra ve tu core");
jsonRep.putNumber("error", coreReply.error);
jsonRep.putNumber("amount", coreReply.amount);
jsonRep.putString("desc", "Loi tra ve tu core");
message.reply(jsonRep);
VisaMpointErrorDb.Obj vsErrorObj = new VisaMpointErrorDb.Obj();
vsErrorObj.cardnumber = requestObj.cardnumber;
vsErrorObj.number = requestObj.phoneNumber;
vsErrorObj.tranid = requestObj.tranId;
vsErrorObj.trantype = requestObj.tranType;
vsErrorObj.error = coreReply.error;
vsErrorObj.desc_error = "Loi tra ve tu core";
vsErrorObj.time = System.currentTimeMillis();
vsErrorObj.count = 1;
visaMpointErrorDb.insert(vsErrorObj, new Handler<Integer>() {
@Override
public void handle(Integer integer) {
}
});
log.writeLog();
return;
}
visaMpointPromoDb.insert(dbObj, new Handler<Integer>() {
@Override
public void handle(Integer integer) {
}
});
String notiCaption = "Nhận tiền khuyến mãi ";
String notiBody = "Quý khách vừa nhận được " + NotificationUtils.getAmount(dbObj.mpoint_1) + "đ vào Tài khoản KM khi thực hiện thanh toán bằng thẻ Visa. Quý khách sẽ sử dụng được tiền trong Tài khoản KM khi tích lũy đủ 50.000đ. Chi tiết liên hệ (08 39917199 hoặc http: momo.vn/thanhtoanhoadon";
final Notification noti = new Notification();
noti.priority = 2;
noti.type = MomoProto.NotificationType.NOTI_TRANSACTION_VALUE;
noti.caption = notiCaption;// "Nhận thưởng quà khuyến mãi";
noti.body = notiBody;//"Bạn vừa nhận được thẻ quà tặng trị giá 100.000đ từ chương trình khuyến mãi “Liên kết tài khoản Vietcombank- Cùng nhận thưởng 100.000đ”. Vui lòng về màn hình chính của ứng dụng ví MoMo, nhấn vào “Số tiền trong ví”, bạn sẽ vào “Tài khoản của tôi” và thấy thẻ quà tặng bạn vừa nhận.";
noti.tranId = coreReply.tranId;
noti.time = new Date().getTime();
noti.receiverNumber = DataUtil.strToInt(requestObj.phoneNumber);
Misc.sendNoti(vertx, noti);
log.writeLog();
// common.sendCurrentAgentInfo(vertx, sock, 0, msg.cmdPhone, data);
jsonRep.putNumber(StringConstUtil.TRANDB_TRAN_ID, coreReply.tranId);
jsonRep.putNumber("error", coreReply.error);
jsonRep.putString("desc", "Thanh cong");
logger.info("error is " + coreReply.error);
logger.info("desc is Thanh cong");
message.reply(jsonRep);
return;
}
});
}
public void givePoint2(final String fromAgent, final long pointAmount, final Common.BuildLog log, final VisaMpointPromoObj requestObj, final Message<JsonObject> message) {
log.add("func", "givePoint2");
Misc.adjustment(vertx, fromAgent, requestObj.phoneNumber, pointAmount, Core.WalletType.POINT_VALUE, new ArrayList<Misc.KeyValue>(), new Common.BuildLog(logger), new Handler<Common.SoapObjReply>() {
@Override
public void handle(Common.SoapObjReply coreReply) {
log.add("func", "adjustment");
log.add("error", coreReply.error);
log.add("tranId", coreReply.tranId);
// log.writeLog();
JsonObject jsonRep = new JsonObject();
if (coreReply.error != 0) {
log.add("error", coreReply.error);
log.add("amount", coreReply.amount);
log.add("desc", "Loi tra ve tu core");
jsonRep.putNumber("error", coreReply.error);
jsonRep.putNumber("amount", coreReply.amount);
jsonRep.putString("desc", "Loi tra ve tu core");
VisaMpointErrorDb.Obj vsErrorObj = new VisaMpointErrorDb.Obj();
vsErrorObj.cardnumber = requestObj.cardnumber;
vsErrorObj.number = requestObj.phoneNumber;
vsErrorObj.tranid = requestObj.tranId;
vsErrorObj.trantype = requestObj.tranType;
vsErrorObj.error = coreReply.error;
vsErrorObj.desc_error = "Loi tra ve tu core";
vsErrorObj.time = System.currentTimeMillis();
vsErrorObj.count = 2;
visaMpointErrorDb.insert(vsErrorObj, new Handler<Integer>() {
@Override
public void handle(Integer integer) {
}
});
message.reply(jsonRep);
log.writeLog();
return;
}
// VisaMpointPromoDb.Obj obj = new VisaMpointPromoDb.Obj();
// obj.mpoint_2 = pointAmount;
// obj.tid_2 = requestObj.tranId;
// obj.trantype_2 = requestObj.tranType;
// obj.end_month = false;
// obj.promo_count = 2;
// obj.time_2 = System.currentTimeMillis();
JsonObject joUpdate = new JsonObject();
joUpdate.putNumber(colName.VisaMPointPromo.MPOINT_2, pointAmount);
joUpdate.putNumber(colName.VisaMPointPromo.TID_2, requestObj.tranId);
joUpdate.putNumber(colName.VisaMPointPromo.TRANTYPE_2, requestObj.tranType);
joUpdate.putNumber(colName.VisaMPointPromo.PROMO_COUNT, 2);
joUpdate.putBoolean(colName.VisaMPointPromo.END_MONTH, true);
joUpdate.putNumber(colName.VisaMPointPromo.TIME_2, System.currentTimeMillis());
joUpdate.putNumber(colName.VisaMPointPromo.TID_VISA_2, requestObj.visatranId);
joUpdate.putString(colName.VisaMPointPromo.SERVICE_ID_2, requestObj.serviceId);
joUpdate.putNumber(colName.VisaMPointPromo.TOTAL_AMOUNT_2, requestObj.totalAmount);
joUpdate.putNumber(colName.VisaMPointPromo.CASH_IN_AMOUNT_2, requestObj.visaAmount);
joUpdate.putNumber(colName.VisaMPointPromo.CASH_IN_TIME_2, requestObj.cashinTime);
visaMpointPromoDb.updatePartial(requestObj.phoneNumber, joUpdate, new Handler<Boolean>() {
@Override
public void handle(Boolean aBoolean) {
}
});
String notiCaption = "Nhận tiền khuyến mãi ";
String notiBody = "Quý khách vừa nhận được " + NotificationUtils.getAmount(pointAmount) + "đ vào Tài khoản KM khi thực hiện thanh toán bằng thẻ Visa. Quý khách sẽ sử dụng được tiền trong Tài khoản KM khi tích lũy đủ 50.000đ. Chi tiết liên hệ (08 39917199 hoặc http: momo.vn/thanhtoanhoadon";
final Notification noti = new Notification();
noti.priority = 2;
noti.type = MomoProto.NotificationType.NOTI_TRANSACTION_VALUE;
noti.caption = notiCaption;// "Nhận thưởng quà khuyến mãi";
noti.body = notiBody;//"Bạn vừa nhận được thẻ quà tặng trị giá 100.000đ từ chương trình khuyến mãi “Liên kết tài khoản Vietcombank- Cùng nhận thưởng 100.000đ”. Vui lòng về màn hình chính của ứng dụng ví MoMo, nhấn vào “Số tiền trong ví”, bạn sẽ vào “Tài khoản của tôi” và thấy thẻ quà tặng bạn vừa nhận.";
noti.tranId = coreReply.tranId;
noti.time = new Date().getTime();
// noti.extra = new JsonObject()
// .putString("giftId", gift.getModelId())
// .putString("giftTypeId", gift.typeId)
// .putString("amount", String.valueOf(tranAmount))
// .putString("sender", "Trải nghiệm thanh toán")
// .putString("senderName", "MoMo")
// .putString("msg",giftMessage)
// .putNumber("status", gift.status)
// .putString("serviceid", gift.typeId)
// .toString();
noti.receiverNumber = DataUtil.strToInt(requestObj.phoneNumber);
Misc.sendNoti(vertx, noti);
log.writeLog();
jsonRep.putNumber(StringConstUtil.TRANDB_TRAN_ID, coreReply.tranId);
jsonRep.putNumber("error", coreReply.error);
jsonRep.putString("desc", "Thanh cong");
logger.info("error is " + coreReply.error);
logger.info("desc is Thanh cong");
message.reply(jsonRep);
return;
}
});
}
public long calculateMpoint(long amount, long totalBalance) {
long mpoint = 0;
long mpoint_tmp = (long) (Math.ceil(percent * 0.01 * amount));
if (mpoint_tmp > totalBalance) {
mpoint = totalBalance;
} else {
mpoint = mpoint_tmp;
}
return mpoint;
}
}
| 38,483 | 0.430051 | 0.420875 | 627 | 59.832535 | 40.109169 | 321 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.044657 | false | false | 12 |
eaf89e31ce62a39aa0b37fe7ee9012eecdf91fc6 | 17,738,214,941,486 | 8dd4e02d3f8a047655a3f0158b8157b8f2676554 | /projects/batfish-common-protocol/src/main/java/org/batfish/specifier/InferFromLocationIpSpaceSpecifier.java | e470810171bae336871dfea8f4fd03a7e24ea5c4 | [
"Apache-2.0"
] | permissive | aggie-innovation-platform-private/batfish | https://github.com/aggie-innovation-platform-private/batfish | e75c20316c68507fec9b9691f491df5bba0369b3 | 0f363548a16e1cc0c3f212f8ef3bfffcfeb4a065 | refs/heads/master | 2023-06-21T00:24:24.538000 | 2021-03-11T21:39:11 | 2021-03-11T21:39:11 | 346,859,560 | 0 | 0 | Apache-2.0 | true | 2021-07-21T22:35:27 | 2021-03-11T22:41:12 | 2021-03-11T22:41:13 | 2021-07-21T22:35:26 | 331,137 | 0 | 0 | 1 | null | false | false | package org.batfish.specifier;
import java.util.Set;
import org.batfish.datamodel.IpSpace;
/**
* An {@link IpSpaceSpecifier} that specifies the {@link IpSpace} owned by each {@link Location}.
*/
public final class InferFromLocationIpSpaceSpecifier implements IpSpaceSpecifier {
public static final InferFromLocationIpSpaceSpecifier INSTANCE =
new InferFromLocationIpSpaceSpecifier();
private InferFromLocationIpSpaceSpecifier() {}
@Override
public IpSpaceAssignment resolve(Set<Location> locations, SpecifierContext ctxt) {
IpSpaceAssignment.Builder builder = IpSpaceAssignment.builder();
locations.forEach(
location -> builder.assign(location, ctxt.getLocationInfo(location).getSourceIps()));
return builder.build();
}
}
| UTF-8 | Java | 764 | java | InferFromLocationIpSpaceSpecifier.java | Java | [] | null | [] | package org.batfish.specifier;
import java.util.Set;
import org.batfish.datamodel.IpSpace;
/**
* An {@link IpSpaceSpecifier} that specifies the {@link IpSpace} owned by each {@link Location}.
*/
public final class InferFromLocationIpSpaceSpecifier implements IpSpaceSpecifier {
public static final InferFromLocationIpSpaceSpecifier INSTANCE =
new InferFromLocationIpSpaceSpecifier();
private InferFromLocationIpSpaceSpecifier() {}
@Override
public IpSpaceAssignment resolve(Set<Location> locations, SpecifierContext ctxt) {
IpSpaceAssignment.Builder builder = IpSpaceAssignment.builder();
locations.forEach(
location -> builder.assign(location, ctxt.getLocationInfo(location).getSourceIps()));
return builder.build();
}
}
| 764 | 0.77356 | 0.77356 | 22 | 33.727272 | 33.224007 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false | 12 |
179452af417e2237f523fc6a807cbb43d6be9a82 | 23,837,068,497,926 | 10ff285a199dd3fe238cf59f0df271dd477c8d2d | /examStackQueue/src/Main.java | d2024dfbfdd2afb420225c484129369ad1c5dbfd | [] | no_license | AZIEBA-DS/DataStructures-Algorithms | https://github.com/AZIEBA-DS/DataStructures-Algorithms | 659844bed7e898c35ebbb2351ffff263d7726b39 | 2a5e7ffd099ee44b62030ac8a326fade8e6a7af7 | refs/heads/master | 2023-01-29T14:14:28.243000 | 2020-12-14T05:04:16 | 2020-12-14T05:04:16 | 293,346,134 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package examStackQueue;
public class Main {
public static void main(String[] args) {
MinStack<Integer> stack = new MinStack<Integer>();
stack.push(4);
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
stack.push(5);
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
stack.push(6);
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
stack.push(3);
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
stack.push(1);
stack.push(1);
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
stack.pop();
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
}
}
| UTF-8 | Java | 872 | java | Main.java | Java | [] | null | [] | package examStackQueue;
public class Main {
public static void main(String[] args) {
MinStack<Integer> stack = new MinStack<Integer>();
stack.push(4);
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
stack.push(5);
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
stack.push(6);
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
stack.push(3);
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
stack.push(1);
stack.push(1);
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
stack.pop();
System.out.println("Current Min: " + stack.min());
System.out.println(stack.toString());
}
}
| 872 | 0.630734 | 0.623853 | 33 | 24.424242 | 19.617601 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.272727 | false | false | 12 |
a83191fe33d9bff248166eec39db2c7bdcf765cb | 24,249,385,361,065 | 2e1609777bc29e4e12f45f0bbe874d1154ff0d94 | /ServerJava/src/net/nan21/ebs/dc/DC_MAIN.java | 483d86d9279c2472223fee9aaa1df997be670a76 | [] | no_license | mahmud-hasan/nan21-ebs | https://github.com/mahmud-hasan/nan21-ebs | 001850eaf0fc9bf16a45b60d8a04bbb00003fa3b | 8bc01f25dd846808120db4619b681892846ab227 | refs/heads/master | 2016-09-06T02:13:19.958000 | 2009-05-28T13:10:53 | 2009-05-28T13:10:53 | 35,844,489 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.nan21.ebs.dc;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.nan21.lib.*;
import net.nan21.lib.dc.IDataControl;
public class DC_MAIN extends AbstractDataControl implements IDataControl {
public void init(HttpRequest request, HttpServletResponse response,
HttpSession session, DbManager dbm) throws Exception {
//this._initFields();
super.init(request, response, session, dbm);
}
public void doCustomAction(String customAction) throws Exception,
IOException {
if (customAction.equals("loadMenu")) {
this.loadMenu(this.request.getParam("node"));
}
if (customAction.equals("changeLanguage")) {
this.changeLanguage();
}
if (customAction.equals("logout")) {
this.doLogout();
}
if (customAction.equals("lockSession")) {
this.doLockSession();
}
}
private void loadMenu(String node) throws Exception {
SessionUser user = (SessionUser) this.session
.getAttribute(HttpSession.MAP_KEY_AUTH_USER);
String module = null;
String sql = null;
if (this.request.getParam("module") == null) {
module = "MAIN";
} else {
module = this.request.getParam("module");
}
if (node.equals("root")) {
sql = "select m.*, mt.translation menu_title "
+ " from menuitem m , menuitem_trl mt"
+ " where m.id = mt.menuitem_id"
+ " and m.menubar_code = '"
+ module
+ "'"
+ " and m.menuitem_id is null"
+ " and m.active = 'Y'"
+ " and mt.lang = '"
+ user.getLanguage()
+ "'"
+ " and not exists ("
+ " select 1"
+ " from menuitem_role mr"
+ " where mr. menuitem_id = m.id"
+ " and mr.role_name not in (select ur.role_name"
+ " from sys_user_role ur"
+ " where ur.user_id = (select u.id from sys_user u where u.login_code ='"
+ user.getUserName() + "') )" + " )"
+ " order by m.position";
} else {
sql = "select m.*, mt.translation menu_title"
+ " from menuitem m , menuitem_trl mt"
+ " where m.id = mt.menuitem_id"
+ " and m.menubar_code = '"
+ module
+ "'"
+ " and m.active = 'Y'"
+ " and m.menuitem_id = '"
+ node
+ "'"
+ " and mt.lang = '"
+ user.getLanguage()
+ "'"
+ " and not exists ("
+ " select 1 "
+ " from menuitem_role mr"
+ " where mr. menuitem_id = m.id"
+ " and mr.role_name not in (select ur.role_name"
+ " from sys_user_role ur"
+ " where ur.user_id = (select u.id from sys_user u where u.login_code ='"
+ user.getUserName() + "') )" + " )"
+ " order by m.position";
}
List<Map<String,String>> res = dbm.executeQuery(sql, null);
StringBuffer out = new StringBuffer("");
int x = 0;
Iterator<Map<String,String>> it = res.iterator();
while (it.hasNext()) {
Map<String,String> row = it.next();
String leaf = "";
out.append((x > 0) ? "," : "");
if (row.get("LINK") != null
&& !row.get("LINK").equals("")) {
leaf = ", \"leaf\":\"true\"";
}
out.append("{\"text\":\"" + row.get("MENU_TITLE")
+ "\",\"id\":\"" + row.get("ID")
+ "\",\"cls\":\"folder\"" + leaf + ",\"guiID\":\""
+ row.get("LINK") + "\"}");
x++;
}
write("["+out.toString()+"]");
}
private void changeLanguage() throws IOException {
String nl = this.request.getParam("_p_lang");
if (nl != null && (nl.equals("ro") || nl.equals("en"))) {
this.session.setLanguage(nl);
write("{ success: true, newLanguage:\"" + nl
+ "\" , message: \"OK\"}");
}
}
private void doLogout() throws IOException {
this.session.setAttribute(HttpSession.MAP_KEY_AUTH_USER, null);
write("{ success: true, message: \"OK\"}");
}
private void doLockSession() throws IOException {
this.session.setAttribute(HttpSession.MAP_KEY_AUTH_USER, null);
write("{ success: true, message: \"OK\"}");
}
public void doQuery() throws Exception {}
public void doInsert() throws Exception {}
public void doUpdate() throws Exception {}
public void doDelete() throws Exception {}
public void fetchRecord() throws Exception {}
public void doExport() throws Exception {}
public void initNewRecord() throws Exception {}
public void callProcedure(String proc) throws Exception {}
} | UTF-8 | Java | 4,488 | java | DC_MAIN.java | Java | [] | null | [] | package net.nan21.ebs.dc;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.nan21.lib.*;
import net.nan21.lib.dc.IDataControl;
public class DC_MAIN extends AbstractDataControl implements IDataControl {
public void init(HttpRequest request, HttpServletResponse response,
HttpSession session, DbManager dbm) throws Exception {
//this._initFields();
super.init(request, response, session, dbm);
}
public void doCustomAction(String customAction) throws Exception,
IOException {
if (customAction.equals("loadMenu")) {
this.loadMenu(this.request.getParam("node"));
}
if (customAction.equals("changeLanguage")) {
this.changeLanguage();
}
if (customAction.equals("logout")) {
this.doLogout();
}
if (customAction.equals("lockSession")) {
this.doLockSession();
}
}
private void loadMenu(String node) throws Exception {
SessionUser user = (SessionUser) this.session
.getAttribute(HttpSession.MAP_KEY_AUTH_USER);
String module = null;
String sql = null;
if (this.request.getParam("module") == null) {
module = "MAIN";
} else {
module = this.request.getParam("module");
}
if (node.equals("root")) {
sql = "select m.*, mt.translation menu_title "
+ " from menuitem m , menuitem_trl mt"
+ " where m.id = mt.menuitem_id"
+ " and m.menubar_code = '"
+ module
+ "'"
+ " and m.menuitem_id is null"
+ " and m.active = 'Y'"
+ " and mt.lang = '"
+ user.getLanguage()
+ "'"
+ " and not exists ("
+ " select 1"
+ " from menuitem_role mr"
+ " where mr. menuitem_id = m.id"
+ " and mr.role_name not in (select ur.role_name"
+ " from sys_user_role ur"
+ " where ur.user_id = (select u.id from sys_user u where u.login_code ='"
+ user.getUserName() + "') )" + " )"
+ " order by m.position";
} else {
sql = "select m.*, mt.translation menu_title"
+ " from menuitem m , menuitem_trl mt"
+ " where m.id = mt.menuitem_id"
+ " and m.menubar_code = '"
+ module
+ "'"
+ " and m.active = 'Y'"
+ " and m.menuitem_id = '"
+ node
+ "'"
+ " and mt.lang = '"
+ user.getLanguage()
+ "'"
+ " and not exists ("
+ " select 1 "
+ " from menuitem_role mr"
+ " where mr. menuitem_id = m.id"
+ " and mr.role_name not in (select ur.role_name"
+ " from sys_user_role ur"
+ " where ur.user_id = (select u.id from sys_user u where u.login_code ='"
+ user.getUserName() + "') )" + " )"
+ " order by m.position";
}
List<Map<String,String>> res = dbm.executeQuery(sql, null);
StringBuffer out = new StringBuffer("");
int x = 0;
Iterator<Map<String,String>> it = res.iterator();
while (it.hasNext()) {
Map<String,String> row = it.next();
String leaf = "";
out.append((x > 0) ? "," : "");
if (row.get("LINK") != null
&& !row.get("LINK").equals("")) {
leaf = ", \"leaf\":\"true\"";
}
out.append("{\"text\":\"" + row.get("MENU_TITLE")
+ "\",\"id\":\"" + row.get("ID")
+ "\",\"cls\":\"folder\"" + leaf + ",\"guiID\":\""
+ row.get("LINK") + "\"}");
x++;
}
write("["+out.toString()+"]");
}
private void changeLanguage() throws IOException {
String nl = this.request.getParam("_p_lang");
if (nl != null && (nl.equals("ro") || nl.equals("en"))) {
this.session.setLanguage(nl);
write("{ success: true, newLanguage:\"" + nl
+ "\" , message: \"OK\"}");
}
}
private void doLogout() throws IOException {
this.session.setAttribute(HttpSession.MAP_KEY_AUTH_USER, null);
write("{ success: true, message: \"OK\"}");
}
private void doLockSession() throws IOException {
this.session.setAttribute(HttpSession.MAP_KEY_AUTH_USER, null);
write("{ success: true, message: \"OK\"}");
}
public void doQuery() throws Exception {}
public void doInsert() throws Exception {}
public void doUpdate() throws Exception {}
public void doDelete() throws Exception {}
public void fetchRecord() throws Exception {}
public void doExport() throws Exception {}
public void initNewRecord() throws Exception {}
public void callProcedure(String proc) throws Exception {}
} | 4,488 | 0.575312 | 0.573084 | 146 | 29.746574 | 22.230366 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.061644 | false | false | 12 |
c8d91961b9a8cc674f6cf414f97e961f90cb9077 | 24,558,623,006,943 | 2919b09f58ac52e862131a5c23232b23aeb20da0 | /src/others/Database.java | 24b57a08e359474b8a55129c22146fe66eecd5f0 | [] | no_license | T-Lob/Software | https://github.com/T-Lob/Software | 52d2629b2581d1669e667401911301818ef78801 | 120fceac57f683e90cbf658951142347a6922227 | refs/heads/master | 2021-09-01T03:44:22.388000 | 2017-12-01T21:52:15 | 2017-12-01T21:52:15 | 111,009,498 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package others;
import java.util.ArrayList;
import events.Event;
import events.EventFactory;
import events.Registration;
public class Database {
private static ArrayList<ED> generatedEDs = new ArrayList<ED>();
public static ArrayList<ED> getGeneratedEDs() {
return generatedEDs;
}
public static void addToGeneratedEDs(ED ed) {
Database.generatedEDs.add(ed);
}
public static ED getEDbyName(String edName) {
for (ED ed:generatedEDs) {
if (ed.getEDname().equalsIgnoreCase(edName)) {
return ed;
}
}
return null;
}
public static ArrayList <String> updateEnabledEvents (ArrayList <String> enabledEvents, ED ed) {
ed.setOldEnabledEvents(new ArrayList<String>(ed.getNewEnabledEvents()));
ed.addToNewEnabledEvents("PatientArrival");
ed.addToNewEnabledEvents("endOfInstallation");
ed.addToNewEnabledEvents("endOfConsultation");
ed.addToNewEnabledEvents("endOfTransportation");
if (ed.getState().get("Nurse") > 0 & ed.getState().get("arrivedPatients") > 0) {
ed.addToNewEnabledEvents("Registration");
ed.addToEventQueue(new Registration(ed.getEDname()));
}
if (ed.getState().get("Nurse") > 0 & ed.getNextRegisteredPatient() != null) {
if (ed.getNextRegisteredPatient().getLevel() >= 4 & (ed.getState().get("emptyBoxrooms") > 0 || ed.getState().get("emptyShockrooms") > 0)) {
ed.addToNewEnabledEvents("Installation");
}
else if (ed.getState().get("emptyBoxrooms") > 0) {
ed.addToNewEnabledEvents("Installation");
}
}
if (ed.getState().get("Physician") > 0 & (ed.getState().get("onlyPatientBoxrooms") > 0 || ed.getState().get("onlyPatientShockrooms") > 0)) {
ed.addToNewEnabledEvents("Consultation");
}
if (ed.getState().get("Transporter") >0 & ed.getState().get("waitingForTransportPatients") >0) {
ed.addToNewEnabledEvents("Transportation");
}
if (ed.mriRoom.getState()=="empty") {
ed.addToNewEnabledEvents("mriExamination");
}
if (ed.bloodTestRoom.getState()=="empty") {
ed.addToNewEnabledEvents("bloodTestExamination");
}
if (ed.radioRoom.getState()=="empty") {
ed.addToNewEnabledEvents("radioExamination");
}
return ed.getNewEnabledEvents();
}
public static ArrayList <Event> updateEventQueue (ED ed) {
ArrayList<String> newlyEnabledEvents = ed.getNewlyEnabledEvents();
ArrayList<String> newlyDisabledEvents = ed.getNewlyDisabledEvents();
for (String s: newlyDisabledEvents) {
ed.removeFromEventQueue(s);
}
for (String s: newlyEnabledEvents) {
Event e=EventFactory.createEvent(ed.getEDname(), s);
ed.addToEventQueue(e);
}
ed.sortEventQueue();
return ed.getEventQueue();
}
public static ED execute (Event e, ED ed) {
e.execute();
ed.getEventQueue().remove(e);
ed.updateState();
return ed;
}
} | UTF-8 | Java | 2,747 | java | Database.java | Java | [] | null | [] | package others;
import java.util.ArrayList;
import events.Event;
import events.EventFactory;
import events.Registration;
public class Database {
private static ArrayList<ED> generatedEDs = new ArrayList<ED>();
public static ArrayList<ED> getGeneratedEDs() {
return generatedEDs;
}
public static void addToGeneratedEDs(ED ed) {
Database.generatedEDs.add(ed);
}
public static ED getEDbyName(String edName) {
for (ED ed:generatedEDs) {
if (ed.getEDname().equalsIgnoreCase(edName)) {
return ed;
}
}
return null;
}
public static ArrayList <String> updateEnabledEvents (ArrayList <String> enabledEvents, ED ed) {
ed.setOldEnabledEvents(new ArrayList<String>(ed.getNewEnabledEvents()));
ed.addToNewEnabledEvents("PatientArrival");
ed.addToNewEnabledEvents("endOfInstallation");
ed.addToNewEnabledEvents("endOfConsultation");
ed.addToNewEnabledEvents("endOfTransportation");
if (ed.getState().get("Nurse") > 0 & ed.getState().get("arrivedPatients") > 0) {
ed.addToNewEnabledEvents("Registration");
ed.addToEventQueue(new Registration(ed.getEDname()));
}
if (ed.getState().get("Nurse") > 0 & ed.getNextRegisteredPatient() != null) {
if (ed.getNextRegisteredPatient().getLevel() >= 4 & (ed.getState().get("emptyBoxrooms") > 0 || ed.getState().get("emptyShockrooms") > 0)) {
ed.addToNewEnabledEvents("Installation");
}
else if (ed.getState().get("emptyBoxrooms") > 0) {
ed.addToNewEnabledEvents("Installation");
}
}
if (ed.getState().get("Physician") > 0 & (ed.getState().get("onlyPatientBoxrooms") > 0 || ed.getState().get("onlyPatientShockrooms") > 0)) {
ed.addToNewEnabledEvents("Consultation");
}
if (ed.getState().get("Transporter") >0 & ed.getState().get("waitingForTransportPatients") >0) {
ed.addToNewEnabledEvents("Transportation");
}
if (ed.mriRoom.getState()=="empty") {
ed.addToNewEnabledEvents("mriExamination");
}
if (ed.bloodTestRoom.getState()=="empty") {
ed.addToNewEnabledEvents("bloodTestExamination");
}
if (ed.radioRoom.getState()=="empty") {
ed.addToNewEnabledEvents("radioExamination");
}
return ed.getNewEnabledEvents();
}
public static ArrayList <Event> updateEventQueue (ED ed) {
ArrayList<String> newlyEnabledEvents = ed.getNewlyEnabledEvents();
ArrayList<String> newlyDisabledEvents = ed.getNewlyDisabledEvents();
for (String s: newlyDisabledEvents) {
ed.removeFromEventQueue(s);
}
for (String s: newlyEnabledEvents) {
Event e=EventFactory.createEvent(ed.getEDname(), s);
ed.addToEventQueue(e);
}
ed.sortEventQueue();
return ed.getEventQueue();
}
public static ED execute (Event e, ED ed) {
e.execute();
ed.getEventQueue().remove(e);
ed.updateState();
return ed;
}
} | 2,747 | 0.708409 | 0.704041 | 85 | 31.329412 | 30.275358 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.317647 | false | false | 12 |
5aa7a55ec45114908842cedb81b01d4b19aeae51 | 26,061,861,558,466 | 7d313b996c67764dddea50c7baf91cf818c275b1 | /src/main/java/org/trams/hello/web/controller/company/CompanyAdminController.java | eda05134f413fd6abbb215c6ecf0cb559a753a12 | [] | no_license | minajsaaa/hello_server | https://github.com/minajsaaa/hello_server | f222269d1474c3456a7dbc96f57589547051ed40 | 5e8c00be9e62327425d52bf09a60d36c4c9dd05f | refs/heads/master | 2023-05-25T23:07:59.771000 | 2017-12-25T09:44:07 | 2017-12-25T09:44:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Created on 12 May 2017 ( Time 10:13:21 )
* Generated by Telosys Tools Generator ( version 2.1.1 )
*/
package org.trams.hello.web.controller.company;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.trams.hello.bean.BusinessSub;
import org.trams.hello.bean.PageCustom;
import org.trams.hello.bean.PromotionPage;
import org.trams.hello.bean.PromotionPageLink;
import org.trams.hello.bean.UserItem;
import org.trams.hello.bean.jpa.PromotionPageEntity;
import org.trams.hello.bean.jpa.PromotionPageLinkEntity;
import org.trams.hello.bean.web.company.MemberInfo;
import org.trams.hello.bean.web.company.VoucherFormBusiness;
import org.trams.hello.bean.web.company.VoucherFormBusinessData;
import org.trams.hello.bean.web.company.VoucherInfo;
import org.trams.hello.bean.web.company.VoucherMemberFormBusiness;
import org.trams.hello.bean.web.company.VoucherMemberFormBusinessData;
import org.trams.hello.business.service.BusinessService;
import org.trams.hello.business.service.BusinessSubService;
import org.trams.hello.business.service.PromotionPageLinkService;
import org.trams.hello.business.service.PromotionPageService;
import org.trams.hello.business.service.UserService;
import org.trams.hello.business.service.VoucherService;
import org.trams.hello.business.service.VoucherUserService;
import org.trams.hello.web.common.Login;
import org.trams.hello.web.common.utils.FileUtils;
/**
* Spring MVC controller for 'Faq' management.
*/
@Controller
@RequestMapping("/company/auth")
public class CompanyAdminController extends BaseController {
@Resource
private BusinessSubService businessSubService;
@Resource
private BusinessService businessService;
@Resource
private UserService userService;
@Resource
private VoucherUserService voucherUserService;
@Resource
private VoucherService voucherService;
private static String nav = "business";
@Resource
private PromotionPageService promotionPageService;
@Resource
ServletContext servletContext;
@Resource
private PromotionPageLinkService promotionPageLinkService;
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String index(@RequestParam Map<String, Object> params, HttpSession session, ModelMap map) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd");
UserItem business = Login.getCompanyLogin(session);
List<String> listDateBeforeSevenDays = new ArrayList<>();
List<Integer> totalVouchers = new ArrayList<>();
List<Integer> totalVouchersMember = new ArrayList<>();
Integer totalMemberByBusinessId = userService.totalMemberByBusinessId(business.getId());
Calendar currentDate = Calendar.getInstance();
currentDate.add(Calendar.DATE, -1);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
cal.add(Calendar.DATE, -7);
for (int j = -6; j <= 0; j++) {
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.DATE, -1);
cal2.add(Calendar.DATE, j);
listDateBeforeSevenDays.add(formatter.format(cal2.getTime()));
String dateConvert = sf.format(cal2.getTime());
totalVouchers.add(voucherUserService.totalVouchersByCreateDateAndBusinessId(business.getId(), dateConvert));
totalVouchersMember.add(voucherUserService.totalVoucherMembersByCreateDateAndBusinessId(business.getId(), dateConvert));
}
map.addAttribute("listDateBeforeSevenDays", listDateBeforeSevenDays);
map.addAttribute("totalVouchers", totalVouchers);
map.addAttribute("totalVouchersMember", totalVouchersMember);
map.addAttribute("currentDate", sf.format(currentDate.getTime()));
map.addAttribute("totalMemberByBusinessId", totalMemberByBusinessId);
return getView();
}
@RequestMapping(value = "/business", method = RequestMethod.GET)
public String business(@RequestParam Map<String, Object> params, HttpSession session, ModelMap map) {
try {
UserItem business = Login.getCompanyLogin(session);
List<PromotionPageEntity> list = promotionPageService.getPromotionPageByBussinessId(business.getId());
if(list.size() > 0){
map.addAttribute("item", list.get(0));
List<PromotionPageLinkEntity> list_link = promotionPageLinkService.findByPromotionPageId(list.get(0).getId());
map.addAttribute("list_link", list_link);
}
map.addAttribute("activePage", nav);
} catch (Exception e) {
e.printStackTrace();
}
return getView();
}
@RequestMapping(value = "/business", method = RequestMethod.POST)
public String promotion_post(HttpSession session,
@RequestParam(value = "logoFile") MultipartFile logoFile,
@RequestParam(value = "backgroundFile") MultipartFile backgroundFile,
@RequestParam(value = "decription", defaultValue = "") String decription,
@RequestParam(value = "link", defaultValue = "") String[] link,
@RequestParam(value = "title", defaultValue = "") String[] title,
@RequestParam(value = "idPromotionPage", defaultValue = "0") Integer idPromotionPage,
Model model) {
try {
UserItem business = Login.getCompanyLogin(session);
if(idPromotionPage > 0){
PromotionPage item = promotionPageService.findById(idPromotionPage);
try {
if (backgroundFile.getSize() > 0) {
item.setBackgroundUrl(FileUtils.saveFileOrigin(backgroundFile, servletContext));
item.setBackgroundName(backgroundFile.getOriginalFilename());
}
if (logoFile.getSize() > 0) {
item.setLogoUrl(FileUtils.saveFileOrigin(logoFile, servletContext));
item.setLogoName(logoFile.getOriginalFilename());
}
} catch (Exception e) {
// TODO: handle exception
}
item.setIsShow(1);
promotionPageService.update(item);
}else{
PromotionPage item = new PromotionPage();
try {
if (backgroundFile.getSize() > 0) {
item.setBackgroundUrl(FileUtils.saveFileOrigin(backgroundFile, servletContext));
item.setBackgroundName(backgroundFile.getOriginalFilename());
}
if (logoFile.getSize() > 0) {
item.setLogoUrl(FileUtils.saveFileOrigin(logoFile, servletContext));
item.setLogoName(logoFile.getOriginalFilename());
}
} catch (Exception e) {
// TODO: handle exception
}
item.setStatus((short)1);
item.setBusinessId(business.getId());
item.setIsShow(1);
PromotionPage p =promotionPageService.create(item);
idPromotionPage = p.getId();
}
if (link.length > 0) {
promotionPageLinkService.deleteByPromotionPageId(idPromotionPage);
for (int j = 0; j < title.length; j++) {
PromotionPageLink pl = new PromotionPageLink();
pl.setCreateDate(new Date());
try {
if(link[j] == null ){
pl.setLink("");
}else{
pl.setLink(link[j]);
}
} catch (Exception e) {
pl.setLink("");
}
if(title[j] == null || title[j].equals("")){
pl.setTitle("");
}else{
pl.setTitle(title[j]);
}
pl.setPromotionPageId(idPromotionPage);
pl.setUpdateDate(new Date());
promotionPageLinkService.create(pl);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/company/auth/business";
}
@RequestMapping(value = "/business/reset", method = RequestMethod.POST)
public String reset(HttpSession session,
Model model) {
try {
UserItem business = Login.getCompanyLogin(session);
promotionPageLinkService.deleteByPromotionPageBy_BusinessId(business.getId());
promotionPageService.deletePromotionPageBy_BussinessId(business.getId());
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/company/auth/business";
}
@RequestMapping(value = "/member", method = RequestMethod.GET)
public String member(
@RequestParam(value="page",defaultValue="1") Integer page,
@RequestParam(value="type_search",defaultValue="name_search") String typeSearch,
@RequestParam(value="keyword",defaultValue="") String keyword,
@RequestParam(value="sub_company",defaultValue="0") Integer subCompany,
@RequestParam(value="year_search",defaultValue="2016") Integer yearSearch,
@RequestParam(value="rs_order",defaultValue="name_order") String rsOrder,HttpServletRequest request,
HttpSession session, ModelMap map) {
try {
UserItem business = Login.getCompanyLogin(session);
List<BusinessSub> listBusinessSub = businessSubService.getListBusinessSubByBusinessId(business.getId());
PageCustom<MemberInfo> pageMs = userService.getMembersInfoInCompany(business.getId(), typeSearch, keyword, subCompany, yearSearch, rsOrder, page, 30);
map.put("totalElement", pageMs.getTotalCount());
map.put("endIndex", pageMs.getTotalPages());
map.put("list", pageMs.getList());
map.put("currentIndex", pageMs.getCurrent());
map.put("totalCount",pageMs.getTotalCount());
map.put("size",pageMs.getSize());
map.put("totalPages",pageMs.getTotalPages());
map.put("page", page);
map.put("listBusinessSub", listBusinessSub);
map.put("yearSearch", yearSearch);
map.put("typeSearch", typeSearch);
map.put("keyword", keyword);
map.put("subCompany", subCompany);
map.put("rsOrder", rsOrder);
map.put("pagination_navigator", "/company/auth/member");
map.put("beginIndex", 1);
String param_url= request.getQueryString();
map.put("param_url", param_url);
return getView();
} catch (Exception e) {
e.printStackTrace();
return getView();
}
}
@RequestMapping(value = "/statistics/voucher", method = RequestMethod.GET)
public String voucher(
@RequestParam(value="page",defaultValue="1") Integer page,
@RequestParam(value="keyword",defaultValue="") String keyword,
@RequestParam(value="sub_company",defaultValue="0") Integer subCompany,
@RequestParam(value="year_search",defaultValue="2016") Integer yearSearch,
@RequestParam(value="rs_order",defaultValue="name_order") String rsOrder,HttpServletRequest request,
HttpSession session, ModelMap map) {
try {
UserItem business = Login.getCompanyLogin(session);
List<BusinessSub> listBusinessSub = businessSubService.getListBusinessSubByBusinessId(business.getId());
PageCustom<VoucherInfo> pageMs = voucherUserService.getVoucherInfoInCompany(business.getId(), keyword, subCompany, yearSearch, rsOrder, page, 30);
map.put("totalElement", pageMs.getTotalCount());
map.put("StaticsVoucher", pageMs.getObj());
map.put("endIndex", pageMs.getTotalPages());
map.put("list", pageMs.getList());
map.put("currentIndex", pageMs.getCurrent());
map.put("totalCount",pageMs.getTotalCount());
map.put("size",pageMs.getSize());
map.put("totalPages",pageMs.getTotalPages());
map.put("businessId",business.getId());
map.put("page", page);
map.put("listBusinessSub", listBusinessSub);
map.put("yearSearch", yearSearch);
map.put("keyword", keyword);
map.put("subCompany", subCompany);
map.put("rsOrder", rsOrder);
map.put("pagination_navigator", "/company/auth/statistics/voucher");
map.put("beginIndex", 1);
String param_url= request.getQueryString();
map.put("param_url", param_url);
return getView();
} catch (Exception e) {
e.printStackTrace();
return getView();
}
}
@RequestMapping(value = "/statistics/member_voucher", method = RequestMethod.GET)
public String member_voucher(@RequestParam(value="page",defaultValue="1") Integer page,
@RequestParam(value="keyword",defaultValue="") String keyword,
@RequestParam(value="sub_company",defaultValue="0") Integer subCompany,
@RequestParam(value="year_search",defaultValue="2016") Integer yearSearch,
@RequestParam(value="rs_order",defaultValue="name_order") String rsOrder,HttpServletRequest request,
HttpSession session, ModelMap map) {
try {
UserItem business = Login.getCompanyLogin(session);
List<BusinessSub> listBusinessSub = businessSubService.getListBusinessSubByBusinessId(business.getId());
PageCustom<VoucherInfo> pageMs = voucherUserService.getVoucherMemberInfoInCompany(business.getId(), keyword, subCompany, yearSearch, rsOrder, page, 30);
map.put("totalElement", pageMs.getTotalCount());
map.put("StaticsVoucher", pageMs.getObj());
map.put("endIndex", pageMs.getTotalPages());
map.put("list", pageMs.getList());
map.put("currentIndex", pageMs.getCurrent());
map.put("totalCount",pageMs.getTotalCount());
map.put("size",pageMs.getSize());
map.put("totalPages",pageMs.getTotalPages());
map.put("page", page);
map.put("listBusinessSub", listBusinessSub);
map.put("yearSearch", yearSearch);
map.put("keyword", keyword);
map.put("subCompany", subCompany);
map.put("rsOrder", rsOrder);
map.put("pagination_navigator", "/company/auth/statistics/member_voucher");
map.put("beginIndex", 1);
String param_url= request.getQueryString();
map.put("param_url", param_url);
return getView();
} catch (Exception e) {
e.printStackTrace();
return getView();
}
}
@RequestMapping(value = "/statistics/voucher/export_excel")
public void exportExcelOrders(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value="keyword",defaultValue="") String keyword, HttpSession session,
@RequestParam(value="sub_company",defaultValue="0") Integer subCompany,
@RequestParam(value="year_search",defaultValue="2016") Integer yearSearch,
@RequestParam(value="rs_order",defaultValue="name_order") String rsOrder, Model model) throws ParseException {
UserItem business = Login.getCompanyLogin(session);
List<VoucherInfo> arr = voucherUserService.getVoucherInfoInCompanyExportExcel(business.getId(), keyword, subCompany, yearSearch, rsOrder);
processExportVoucherBusiness(request, response, arr);
}
public void processExportVoucherBusiness(HttpServletRequest request, HttpServletResponse response, List<VoucherInfo> arr) {
List<VoucherFormBusiness> rows = new VoucherFormBusinessData().getFormData(arr);
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String today = formatter.format(new Date());
response.setHeader("Content-Disposition", "attachment; filename=\"" + today + ".xls" + "\";");
response.setHeader("Content-Transfer-Encoding", "binary");
OutputStream out;
try {
out = response.getOutputStream();
String path = request.getSession().getServletContext().getRealPath("/");
FileInputStream fileInput = new FileInputStream(path + "excel_template/voucher_template.xls");
HSSFWorkbook template_workbook = new HSSFWorkbook(fileInput);
HSSFSheet sheet = template_workbook.getSheetAt(0);
int columnIndex = 0;
int rowIndex = 1;
for (VoucherFormBusiness rowItemsObject : rows) {
HSSFRow row = sheet.createRow(rowIndex);
columnIndex = 0;
String[] rowItems = rowItemsObject.toString().split("\\|");
for (String rowItem : rowItems) {
row.createCell(columnIndex).setCellValue(rowItem);
columnIndex++;
}
rowIndex++;
}
try {
template_workbook.write(out);
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("order export excel, workbook wirte io exception");
} finally {
if (fileInput != null)
fileInput.close();
template_workbook.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("order export excel, get output stream io exception");
}
}
@RequestMapping(value = "/statistics/member_voucher/export_excel")
public void exportExcelMemberVoucher(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value="keyword",defaultValue="") String keyword, HttpSession session,
@RequestParam(value="sub_company",defaultValue="0") Integer subCompany,
@RequestParam(value="year_search",defaultValue="2016") Integer yearSearch,
@RequestParam(value="rs_order",defaultValue="name_order") String rsOrder, Model model) throws ParseException {
UserItem business = Login.getCompanyLogin(session);
List<VoucherInfo> arr = voucherUserService.getVoucherMemberInfoInCompanyExportExcel(business.getId(), keyword, subCompany, yearSearch, rsOrder);
processExportMemberVoucherBusiness(request, response, arr);
}
public void processExportMemberVoucherBusiness(HttpServletRequest request, HttpServletResponse response, List<VoucherInfo> arr) {
List<VoucherMemberFormBusiness> rows = new VoucherMemberFormBusinessData().getFormData(arr);
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String today = formatter.format(new Date());
response.setHeader("Content-Disposition", "attachment; filename=\"" + today + ".xls" + "\";");
response.setHeader("Content-Transfer-Encoding", "binary");
OutputStream out;
try {
out = response.getOutputStream();
String path = request.getSession().getServletContext().getRealPath("/");
FileInputStream fileInput = new FileInputStream(path + "excel_template/voucher_member_template.xls");
HSSFWorkbook template_workbook = new HSSFWorkbook(fileInput);
HSSFSheet sheet = template_workbook.getSheetAt(0);
int columnIndex = 0;
int rowIndex = 1;
for (VoucherMemberFormBusiness rowItemsObject : rows) {
HSSFRow row = sheet.createRow(rowIndex);
columnIndex = 0;
String[] rowItems = rowItemsObject.toString().split("\\|");
for (String rowItem : rowItems) {
row.createCell(columnIndex).setCellValue(rowItem);
columnIndex++;
}
rowIndex++;
}
try {
template_workbook.write(out);
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("order export excel, workbook wirte io exception");
} finally {
if (fileInput != null)
fileInput.close();
template_workbook.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("order export excel, get output stream io exception");
}
}
}
| UTF-8 | Java | 18,759 | java | CompanyAdminController.java | Java | [] | null | [] | /*
* Created on 12 May 2017 ( Time 10:13:21 )
* Generated by Telosys Tools Generator ( version 2.1.1 )
*/
package org.trams.hello.web.controller.company;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.trams.hello.bean.BusinessSub;
import org.trams.hello.bean.PageCustom;
import org.trams.hello.bean.PromotionPage;
import org.trams.hello.bean.PromotionPageLink;
import org.trams.hello.bean.UserItem;
import org.trams.hello.bean.jpa.PromotionPageEntity;
import org.trams.hello.bean.jpa.PromotionPageLinkEntity;
import org.trams.hello.bean.web.company.MemberInfo;
import org.trams.hello.bean.web.company.VoucherFormBusiness;
import org.trams.hello.bean.web.company.VoucherFormBusinessData;
import org.trams.hello.bean.web.company.VoucherInfo;
import org.trams.hello.bean.web.company.VoucherMemberFormBusiness;
import org.trams.hello.bean.web.company.VoucherMemberFormBusinessData;
import org.trams.hello.business.service.BusinessService;
import org.trams.hello.business.service.BusinessSubService;
import org.trams.hello.business.service.PromotionPageLinkService;
import org.trams.hello.business.service.PromotionPageService;
import org.trams.hello.business.service.UserService;
import org.trams.hello.business.service.VoucherService;
import org.trams.hello.business.service.VoucherUserService;
import org.trams.hello.web.common.Login;
import org.trams.hello.web.common.utils.FileUtils;
/**
* Spring MVC controller for 'Faq' management.
*/
@Controller
@RequestMapping("/company/auth")
public class CompanyAdminController extends BaseController {
@Resource
private BusinessSubService businessSubService;
@Resource
private BusinessService businessService;
@Resource
private UserService userService;
@Resource
private VoucherUserService voucherUserService;
@Resource
private VoucherService voucherService;
private static String nav = "business";
@Resource
private PromotionPageService promotionPageService;
@Resource
ServletContext servletContext;
@Resource
private PromotionPageLinkService promotionPageLinkService;
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String index(@RequestParam Map<String, Object> params, HttpSession session, ModelMap map) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd");
UserItem business = Login.getCompanyLogin(session);
List<String> listDateBeforeSevenDays = new ArrayList<>();
List<Integer> totalVouchers = new ArrayList<>();
List<Integer> totalVouchersMember = new ArrayList<>();
Integer totalMemberByBusinessId = userService.totalMemberByBusinessId(business.getId());
Calendar currentDate = Calendar.getInstance();
currentDate.add(Calendar.DATE, -1);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
cal.add(Calendar.DATE, -7);
for (int j = -6; j <= 0; j++) {
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.DATE, -1);
cal2.add(Calendar.DATE, j);
listDateBeforeSevenDays.add(formatter.format(cal2.getTime()));
String dateConvert = sf.format(cal2.getTime());
totalVouchers.add(voucherUserService.totalVouchersByCreateDateAndBusinessId(business.getId(), dateConvert));
totalVouchersMember.add(voucherUserService.totalVoucherMembersByCreateDateAndBusinessId(business.getId(), dateConvert));
}
map.addAttribute("listDateBeforeSevenDays", listDateBeforeSevenDays);
map.addAttribute("totalVouchers", totalVouchers);
map.addAttribute("totalVouchersMember", totalVouchersMember);
map.addAttribute("currentDate", sf.format(currentDate.getTime()));
map.addAttribute("totalMemberByBusinessId", totalMemberByBusinessId);
return getView();
}
@RequestMapping(value = "/business", method = RequestMethod.GET)
public String business(@RequestParam Map<String, Object> params, HttpSession session, ModelMap map) {
try {
UserItem business = Login.getCompanyLogin(session);
List<PromotionPageEntity> list = promotionPageService.getPromotionPageByBussinessId(business.getId());
if(list.size() > 0){
map.addAttribute("item", list.get(0));
List<PromotionPageLinkEntity> list_link = promotionPageLinkService.findByPromotionPageId(list.get(0).getId());
map.addAttribute("list_link", list_link);
}
map.addAttribute("activePage", nav);
} catch (Exception e) {
e.printStackTrace();
}
return getView();
}
@RequestMapping(value = "/business", method = RequestMethod.POST)
public String promotion_post(HttpSession session,
@RequestParam(value = "logoFile") MultipartFile logoFile,
@RequestParam(value = "backgroundFile") MultipartFile backgroundFile,
@RequestParam(value = "decription", defaultValue = "") String decription,
@RequestParam(value = "link", defaultValue = "") String[] link,
@RequestParam(value = "title", defaultValue = "") String[] title,
@RequestParam(value = "idPromotionPage", defaultValue = "0") Integer idPromotionPage,
Model model) {
try {
UserItem business = Login.getCompanyLogin(session);
if(idPromotionPage > 0){
PromotionPage item = promotionPageService.findById(idPromotionPage);
try {
if (backgroundFile.getSize() > 0) {
item.setBackgroundUrl(FileUtils.saveFileOrigin(backgroundFile, servletContext));
item.setBackgroundName(backgroundFile.getOriginalFilename());
}
if (logoFile.getSize() > 0) {
item.setLogoUrl(FileUtils.saveFileOrigin(logoFile, servletContext));
item.setLogoName(logoFile.getOriginalFilename());
}
} catch (Exception e) {
// TODO: handle exception
}
item.setIsShow(1);
promotionPageService.update(item);
}else{
PromotionPage item = new PromotionPage();
try {
if (backgroundFile.getSize() > 0) {
item.setBackgroundUrl(FileUtils.saveFileOrigin(backgroundFile, servletContext));
item.setBackgroundName(backgroundFile.getOriginalFilename());
}
if (logoFile.getSize() > 0) {
item.setLogoUrl(FileUtils.saveFileOrigin(logoFile, servletContext));
item.setLogoName(logoFile.getOriginalFilename());
}
} catch (Exception e) {
// TODO: handle exception
}
item.setStatus((short)1);
item.setBusinessId(business.getId());
item.setIsShow(1);
PromotionPage p =promotionPageService.create(item);
idPromotionPage = p.getId();
}
if (link.length > 0) {
promotionPageLinkService.deleteByPromotionPageId(idPromotionPage);
for (int j = 0; j < title.length; j++) {
PromotionPageLink pl = new PromotionPageLink();
pl.setCreateDate(new Date());
try {
if(link[j] == null ){
pl.setLink("");
}else{
pl.setLink(link[j]);
}
} catch (Exception e) {
pl.setLink("");
}
if(title[j] == null || title[j].equals("")){
pl.setTitle("");
}else{
pl.setTitle(title[j]);
}
pl.setPromotionPageId(idPromotionPage);
pl.setUpdateDate(new Date());
promotionPageLinkService.create(pl);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/company/auth/business";
}
@RequestMapping(value = "/business/reset", method = RequestMethod.POST)
public String reset(HttpSession session,
Model model) {
try {
UserItem business = Login.getCompanyLogin(session);
promotionPageLinkService.deleteByPromotionPageBy_BusinessId(business.getId());
promotionPageService.deletePromotionPageBy_BussinessId(business.getId());
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/company/auth/business";
}
@RequestMapping(value = "/member", method = RequestMethod.GET)
public String member(
@RequestParam(value="page",defaultValue="1") Integer page,
@RequestParam(value="type_search",defaultValue="name_search") String typeSearch,
@RequestParam(value="keyword",defaultValue="") String keyword,
@RequestParam(value="sub_company",defaultValue="0") Integer subCompany,
@RequestParam(value="year_search",defaultValue="2016") Integer yearSearch,
@RequestParam(value="rs_order",defaultValue="name_order") String rsOrder,HttpServletRequest request,
HttpSession session, ModelMap map) {
try {
UserItem business = Login.getCompanyLogin(session);
List<BusinessSub> listBusinessSub = businessSubService.getListBusinessSubByBusinessId(business.getId());
PageCustom<MemberInfo> pageMs = userService.getMembersInfoInCompany(business.getId(), typeSearch, keyword, subCompany, yearSearch, rsOrder, page, 30);
map.put("totalElement", pageMs.getTotalCount());
map.put("endIndex", pageMs.getTotalPages());
map.put("list", pageMs.getList());
map.put("currentIndex", pageMs.getCurrent());
map.put("totalCount",pageMs.getTotalCount());
map.put("size",pageMs.getSize());
map.put("totalPages",pageMs.getTotalPages());
map.put("page", page);
map.put("listBusinessSub", listBusinessSub);
map.put("yearSearch", yearSearch);
map.put("typeSearch", typeSearch);
map.put("keyword", keyword);
map.put("subCompany", subCompany);
map.put("rsOrder", rsOrder);
map.put("pagination_navigator", "/company/auth/member");
map.put("beginIndex", 1);
String param_url= request.getQueryString();
map.put("param_url", param_url);
return getView();
} catch (Exception e) {
e.printStackTrace();
return getView();
}
}
@RequestMapping(value = "/statistics/voucher", method = RequestMethod.GET)
public String voucher(
@RequestParam(value="page",defaultValue="1") Integer page,
@RequestParam(value="keyword",defaultValue="") String keyword,
@RequestParam(value="sub_company",defaultValue="0") Integer subCompany,
@RequestParam(value="year_search",defaultValue="2016") Integer yearSearch,
@RequestParam(value="rs_order",defaultValue="name_order") String rsOrder,HttpServletRequest request,
HttpSession session, ModelMap map) {
try {
UserItem business = Login.getCompanyLogin(session);
List<BusinessSub> listBusinessSub = businessSubService.getListBusinessSubByBusinessId(business.getId());
PageCustom<VoucherInfo> pageMs = voucherUserService.getVoucherInfoInCompany(business.getId(), keyword, subCompany, yearSearch, rsOrder, page, 30);
map.put("totalElement", pageMs.getTotalCount());
map.put("StaticsVoucher", pageMs.getObj());
map.put("endIndex", pageMs.getTotalPages());
map.put("list", pageMs.getList());
map.put("currentIndex", pageMs.getCurrent());
map.put("totalCount",pageMs.getTotalCount());
map.put("size",pageMs.getSize());
map.put("totalPages",pageMs.getTotalPages());
map.put("businessId",business.getId());
map.put("page", page);
map.put("listBusinessSub", listBusinessSub);
map.put("yearSearch", yearSearch);
map.put("keyword", keyword);
map.put("subCompany", subCompany);
map.put("rsOrder", rsOrder);
map.put("pagination_navigator", "/company/auth/statistics/voucher");
map.put("beginIndex", 1);
String param_url= request.getQueryString();
map.put("param_url", param_url);
return getView();
} catch (Exception e) {
e.printStackTrace();
return getView();
}
}
@RequestMapping(value = "/statistics/member_voucher", method = RequestMethod.GET)
public String member_voucher(@RequestParam(value="page",defaultValue="1") Integer page,
@RequestParam(value="keyword",defaultValue="") String keyword,
@RequestParam(value="sub_company",defaultValue="0") Integer subCompany,
@RequestParam(value="year_search",defaultValue="2016") Integer yearSearch,
@RequestParam(value="rs_order",defaultValue="name_order") String rsOrder,HttpServletRequest request,
HttpSession session, ModelMap map) {
try {
UserItem business = Login.getCompanyLogin(session);
List<BusinessSub> listBusinessSub = businessSubService.getListBusinessSubByBusinessId(business.getId());
PageCustom<VoucherInfo> pageMs = voucherUserService.getVoucherMemberInfoInCompany(business.getId(), keyword, subCompany, yearSearch, rsOrder, page, 30);
map.put("totalElement", pageMs.getTotalCount());
map.put("StaticsVoucher", pageMs.getObj());
map.put("endIndex", pageMs.getTotalPages());
map.put("list", pageMs.getList());
map.put("currentIndex", pageMs.getCurrent());
map.put("totalCount",pageMs.getTotalCount());
map.put("size",pageMs.getSize());
map.put("totalPages",pageMs.getTotalPages());
map.put("page", page);
map.put("listBusinessSub", listBusinessSub);
map.put("yearSearch", yearSearch);
map.put("keyword", keyword);
map.put("subCompany", subCompany);
map.put("rsOrder", rsOrder);
map.put("pagination_navigator", "/company/auth/statistics/member_voucher");
map.put("beginIndex", 1);
String param_url= request.getQueryString();
map.put("param_url", param_url);
return getView();
} catch (Exception e) {
e.printStackTrace();
return getView();
}
}
@RequestMapping(value = "/statistics/voucher/export_excel")
public void exportExcelOrders(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value="keyword",defaultValue="") String keyword, HttpSession session,
@RequestParam(value="sub_company",defaultValue="0") Integer subCompany,
@RequestParam(value="year_search",defaultValue="2016") Integer yearSearch,
@RequestParam(value="rs_order",defaultValue="name_order") String rsOrder, Model model) throws ParseException {
UserItem business = Login.getCompanyLogin(session);
List<VoucherInfo> arr = voucherUserService.getVoucherInfoInCompanyExportExcel(business.getId(), keyword, subCompany, yearSearch, rsOrder);
processExportVoucherBusiness(request, response, arr);
}
public void processExportVoucherBusiness(HttpServletRequest request, HttpServletResponse response, List<VoucherInfo> arr) {
List<VoucherFormBusiness> rows = new VoucherFormBusinessData().getFormData(arr);
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String today = formatter.format(new Date());
response.setHeader("Content-Disposition", "attachment; filename=\"" + today + ".xls" + "\";");
response.setHeader("Content-Transfer-Encoding", "binary");
OutputStream out;
try {
out = response.getOutputStream();
String path = request.getSession().getServletContext().getRealPath("/");
FileInputStream fileInput = new FileInputStream(path + "excel_template/voucher_template.xls");
HSSFWorkbook template_workbook = new HSSFWorkbook(fileInput);
HSSFSheet sheet = template_workbook.getSheetAt(0);
int columnIndex = 0;
int rowIndex = 1;
for (VoucherFormBusiness rowItemsObject : rows) {
HSSFRow row = sheet.createRow(rowIndex);
columnIndex = 0;
String[] rowItems = rowItemsObject.toString().split("\\|");
for (String rowItem : rowItems) {
row.createCell(columnIndex).setCellValue(rowItem);
columnIndex++;
}
rowIndex++;
}
try {
template_workbook.write(out);
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("order export excel, workbook wirte io exception");
} finally {
if (fileInput != null)
fileInput.close();
template_workbook.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("order export excel, get output stream io exception");
}
}
@RequestMapping(value = "/statistics/member_voucher/export_excel")
public void exportExcelMemberVoucher(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value="keyword",defaultValue="") String keyword, HttpSession session,
@RequestParam(value="sub_company",defaultValue="0") Integer subCompany,
@RequestParam(value="year_search",defaultValue="2016") Integer yearSearch,
@RequestParam(value="rs_order",defaultValue="name_order") String rsOrder, Model model) throws ParseException {
UserItem business = Login.getCompanyLogin(session);
List<VoucherInfo> arr = voucherUserService.getVoucherMemberInfoInCompanyExportExcel(business.getId(), keyword, subCompany, yearSearch, rsOrder);
processExportMemberVoucherBusiness(request, response, arr);
}
public void processExportMemberVoucherBusiness(HttpServletRequest request, HttpServletResponse response, List<VoucherInfo> arr) {
List<VoucherMemberFormBusiness> rows = new VoucherMemberFormBusinessData().getFormData(arr);
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String today = formatter.format(new Date());
response.setHeader("Content-Disposition", "attachment; filename=\"" + today + ".xls" + "\";");
response.setHeader("Content-Transfer-Encoding", "binary");
OutputStream out;
try {
out = response.getOutputStream();
String path = request.getSession().getServletContext().getRealPath("/");
FileInputStream fileInput = new FileInputStream(path + "excel_template/voucher_member_template.xls");
HSSFWorkbook template_workbook = new HSSFWorkbook(fileInput);
HSSFSheet sheet = template_workbook.getSheetAt(0);
int columnIndex = 0;
int rowIndex = 1;
for (VoucherMemberFormBusiness rowItemsObject : rows) {
HSSFRow row = sheet.createRow(rowIndex);
columnIndex = 0;
String[] rowItems = rowItemsObject.toString().split("\\|");
for (String rowItem : rowItems) {
row.createCell(columnIndex).setCellValue(rowItem);
columnIndex++;
}
rowIndex++;
}
try {
template_workbook.write(out);
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("order export excel, workbook wirte io exception");
} finally {
if (fileInput != null)
fileInput.close();
template_workbook.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("order export excel, get output stream io exception");
}
}
}
| 18,759 | 0.732822 | 0.72829 | 463 | 39.516197 | 30.309904 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.399568 | false | false | 12 |
5a3b3c236585a1db4c91db02d7776765a6ba24da | 1,400,159,349,563 | 8e1dbf0ee00312e8f45eb82bf6bad350ae68c0aa | /project/src/main/java/club/emergency/project/mapper/sqlprovider/ByPlusTaskWorkloadProvider.java | 81516f79659b7245991e3d4f4f8944a39ca3e163 | [] | no_license | piglete/DAST | https://github.com/piglete/DAST | ed839d69df3d9c5d738574ee1ad9e803929df056 | 821f06b40a882ed9861c8eedd4fceda935ce5a13 | refs/heads/master | 2020-05-30T20:35:00.822000 | 2019-06-03T08:24:24 | 2019-06-03T08:24:24 | 188,547,093 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package club.emergency.project.mapper.sqlprovider;
import club.map.core.mapper.SqlProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ByPlusTaskWorkloadProvider extends SqlProvider {
protected final Log log = LogFactory.getLog(getClass());
public String getTaskWorkloadList(Integer taskId, String departmentCode, String groupCode, Integer oneInspectionUserId, Integer twoInspectionUserId, Integer threeInspectionUserId, Integer itemApplicationId, Integer flag, String startDate, String endDate) {
StringBuffer sb = new StringBuffer(256);
sb.append("select distinct w.id as id,w.task_id as taskId,w.work_count as workCount,w.item_application_id as itemApplicationId,w.unit_type_id as unitTypeId,w.department_code as departmentCode,w.remark as remark,w.flag as flag,w.create_time as createTime ").append("from ");
sb.append("by_plus_task_workload w,by_plus_task t ");
sb.append("where w.task_id = t.id and t.flag = 2 and w.using_type = 1 and t.using_type = 1 ");
if (taskId != null) {
sb.append("and w.task_id = ").append(taskId).append(" ");
}
if (itemApplicationId != null) {
sb.append("and w.item_application_id = ").append(itemApplicationId).append(" ");
}
if (flag != null) {
sb.append("and w.flag = ").append(flag).append(" ");
}
if (!"".equals(departmentCode)) {
sb.append("and t.department_code = ").append(departmentCode).append(" ");
}
if (!"".equals(groupCode)) {
sb.append("and t.work_group_code = ").append(groupCode).append(" ");
}
if (oneInspectionUserId != null) {
sb.append("and t.one_inspection_user_id = ").append(oneInspectionUserId).append(" ");
}
if (twoInspectionUserId != null) {
sb.append("and t.two_inspection_user_id = ").append(twoInspectionUserId).append(" ");
}
if (threeInspectionUserId != null) {
sb.append("and t.three_inspection_user_id = ").append(threeInspectionUserId).append(" ");
}
if (!"".equals(startDate) && !"".equals(endDate)) {
sb.append("and t.three_check_date between '").append(startDate).append("' and '").append(endDate).append("' ");
}
String sql = sb.toString();
log.debug(sql);
return sql;
}
} | UTF-8 | Java | 2,423 | java | ByPlusTaskWorkloadProvider.java | Java | [] | null | [] | package club.emergency.project.mapper.sqlprovider;
import club.map.core.mapper.SqlProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ByPlusTaskWorkloadProvider extends SqlProvider {
protected final Log log = LogFactory.getLog(getClass());
public String getTaskWorkloadList(Integer taskId, String departmentCode, String groupCode, Integer oneInspectionUserId, Integer twoInspectionUserId, Integer threeInspectionUserId, Integer itemApplicationId, Integer flag, String startDate, String endDate) {
StringBuffer sb = new StringBuffer(256);
sb.append("select distinct w.id as id,w.task_id as taskId,w.work_count as workCount,w.item_application_id as itemApplicationId,w.unit_type_id as unitTypeId,w.department_code as departmentCode,w.remark as remark,w.flag as flag,w.create_time as createTime ").append("from ");
sb.append("by_plus_task_workload w,by_plus_task t ");
sb.append("where w.task_id = t.id and t.flag = 2 and w.using_type = 1 and t.using_type = 1 ");
if (taskId != null) {
sb.append("and w.task_id = ").append(taskId).append(" ");
}
if (itemApplicationId != null) {
sb.append("and w.item_application_id = ").append(itemApplicationId).append(" ");
}
if (flag != null) {
sb.append("and w.flag = ").append(flag).append(" ");
}
if (!"".equals(departmentCode)) {
sb.append("and t.department_code = ").append(departmentCode).append(" ");
}
if (!"".equals(groupCode)) {
sb.append("and t.work_group_code = ").append(groupCode).append(" ");
}
if (oneInspectionUserId != null) {
sb.append("and t.one_inspection_user_id = ").append(oneInspectionUserId).append(" ");
}
if (twoInspectionUserId != null) {
sb.append("and t.two_inspection_user_id = ").append(twoInspectionUserId).append(" ");
}
if (threeInspectionUserId != null) {
sb.append("and t.three_inspection_user_id = ").append(threeInspectionUserId).append(" ");
}
if (!"".equals(startDate) && !"".equals(endDate)) {
sb.append("and t.three_check_date between '").append(startDate).append("' and '").append(endDate).append("' ");
}
String sql = sb.toString();
log.debug(sql);
return sql;
}
} | 2,423 | 0.633512 | 0.631036 | 46 | 51.695652 | 56.722771 | 281 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.847826 | false | false | 12 |
f43abde24c63ab2a79d8a034dc6f2c0bd032dda3 | 21,139,829,053,319 | ae031e9bad3336bb31a552c5e0bb645f2e6d5d07 | /src/main/java/com/ecomotto/focus/repositories/SessionRepository.java | 9944c28a2b4970803064e42016778df5f3fe38c7 | [] | no_license | quangta93/focus | https://github.com/quangta93/focus | 78a90a7c423134227a7934415b68537223d2bebd | 4572931deae6c4571199e0d221c6741e55463dd0 | refs/heads/master | 2019-04-08T21:26:17.306000 | 2015-10-20T03:22:38 | 2015-10-20T03:22:38 | 39,898,755 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ecomotto.focus.repositories;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ecomotto.focus.models.Session;
@Repository
public interface SessionRepository extends CrudRepository<Session, String> {
List<Session> findSessionByUsername(String username);
List<Session> findSessionBySession(String sessionId);
}
| UTF-8 | Java | 483 | java | SessionRepository.java | Java | [] | null | [] | package com.ecomotto.focus.repositories;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ecomotto.focus.models.Session;
@Repository
public interface SessionRepository extends CrudRepository<Session, String> {
List<Session> findSessionByUsername(String username);
List<Session> findSessionBySession(String sessionId);
}
| 483 | 0.838509 | 0.838509 | 17 | 27.411764 | 26.66361 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 12 |
2477e8452cb920e6b83bc257020c8ccbbde17955 | 11,905,649,350,416 | 0e0a9e044ebccdea83d4a7f15f98142488fc79f8 | /engine/androidLite/src/net/fabiensanglard/shmuplite/ShmupLiteActivity.java | 2be3693ad8e8679d3cd30fa9bcd56382bdbd7048 | [] | no_license | shanfl/Shmup | https://github.com/shanfl/Shmup | 3d7c038ac36fb38a24fd8c50c453e72bdad9d5b0 | 99546c2cdb9f1e1740f9f8a840483b58c7799921 | refs/heads/master | 2021-01-18T01:39:11.408000 | 2012-02-18T23:57:59 | 2012-02-18T23:57:59 | 3,500,556 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.fabiensanglard.shmuplite;
import java.io.IOException;
import android.app.NativeActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
public class ShmupLiteActivity extends NativeActivity {
private static Context context;
private static Handler handler;
public static void goToWebsite(final String url){
handler.postAtFrontOfQueue(new Runnable(){
public void run() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ShmupLiteActivity.context.startActivity(intent);
}});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("Pre native code call.");
context = getApplicationContext();
handler = new Handler();
super.onCreate(savedInstanceState);
System.out.println("Post native code call.");
}
} | UTF-8 | Java | 1,040 | java | ShmupLiteActivity.java | Java | [] | null | [] | package net.fabiensanglard.shmuplite;
import java.io.IOException;
import android.app.NativeActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
public class ShmupLiteActivity extends NativeActivity {
private static Context context;
private static Handler handler;
public static void goToWebsite(final String url){
handler.postAtFrontOfQueue(new Runnable(){
public void run() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ShmupLiteActivity.context.startActivity(intent);
}});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("Pre native code call.");
context = getApplicationContext();
handler = new Handler();
super.onCreate(savedInstanceState);
System.out.println("Post native code call.");
}
} | 1,040 | 0.757692 | 0.757692 | 44 | 22.65909 | 19.340187 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.568182 | false | false | 12 |
6ae88014e9d9835049dfc80ae5ce6fdaf8368ba0 | 29,643,864,335,681 | dc042bc245f6b8d4b5448dcfc913ae8eaa964d4d | /wechat/src/main/java/com/calling/repository/client/UserNoticeJpa.java | f3cbe33ea194aeb5f23381beb2dd5cf1e1ecde37 | [] | no_license | luck-1/callnubmer | https://github.com/luck-1/callnubmer | e46b212cd974dfc28720eba120a1bf852617d929 | c38a76fadd375a0ab6d55ff469e7d253f12ceb95 | refs/heads/master | 2020-05-09T14:31:26.284000 | 2019-04-22T05:01:06 | 2019-04-22T05:01:06 | 181,196,813 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.calling.repository.client;
import com.calling.entity.client.UserNotice;
import com.calling.repository.BaseJpa;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* @Description TODO
* @Author zhangyulei
* @Date create at 2018/10/23 0023 on 17:00
**/
public interface UserNoticeJpa extends BaseJpa<UserNotice> {
/**
* 按用户id查询
* @param userId
* @return Result<List<String>>
*/
@Query(value = "select f_notice_type from t_user_notice where f_user_id =:userId",nativeQuery = true)
List<String> selectNotice(@Param("userId")String userId);
/**
* 按用户删除
* @param userId
*/
void deleteByFUserId(String userId);
}
| UTF-8 | Java | 790 | java | UserNoticeJpa.java | Java | [
{
"context": "va.util.List;\n\n/**\n * @Description TODO\n * @Author zhangyulei\n * @Date create at 2018/10/23 0023 on 17:00\n **/\n",
"end": 305,
"score": 0.9996315240859985,
"start": 295,
"tag": "USERNAME",
"value": "zhangyulei"
}
] | null | [] | package com.calling.repository.client;
import com.calling.entity.client.UserNotice;
import com.calling.repository.BaseJpa;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* @Description TODO
* @Author zhangyulei
* @Date create at 2018/10/23 0023 on 17:00
**/
public interface UserNoticeJpa extends BaseJpa<UserNotice> {
/**
* 按用户id查询
* @param userId
* @return Result<List<String>>
*/
@Query(value = "select f_notice_type from t_user_notice where f_user_id =:userId",nativeQuery = true)
List<String> selectNotice(@Param("userId")String userId);
/**
* 按用户删除
* @param userId
*/
void deleteByFUserId(String userId);
}
| 790 | 0.696104 | 0.675325 | 33 | 22.333334 | 24.559965 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 12 |
bd538c9afca96dee841ed07d08298fb43a907764 | 12,884,901,923,911 | 26afe38586d20e6ae01ce3cb46143327548cf794 | /src/main/java/com/sybit/r750explorer/repository/tables/Medien.java | 436e528961552b95b270f2d56a3c7cb87f0d959d | [
"MIT"
] | permissive | Sybit-Education/Coding-Camp-2017 | https://github.com/Sybit-Education/Coding-Camp-2017 | ed6ceceab8213b87f81c10a6ba056feb0b97dc36 | 26e2f18bcf8897805847562b90ac2b5c9f52f10b | refs/heads/master | 2022-01-29T21:57:55.485000 | 2021-12-16T15:52:13 | 2021-12-16T15:52:13 | 98,514,531 | 0 | 0 | MIT | false | 2022-01-07T16:51:09 | 2017-07-27T08:49:44 | 2021-12-16T15:52:17 | 2022-01-07T16:51:07 | 1,181 | 0 | 0 | 8 | Java | false | false | package com.sybit.r750explorer.repository.tables;
import com.google.gson.annotations.SerializedName;
import com.sybit.airtable.vo.Attachment;
import java.util.List;
/**
* Created by fzr on 10.04.17.
*/
public class Medien {
@SerializedName("Überschrift")
private String ueberschrift;
@SerializedName("Location")
private List<String> location;
@SerializedName("Typ")
private String type;
@SerializedName("Text")
private String text;
@SerializedName("Attachments")
private List<Attachment> attachements;
@SerializedName("Link")
private String link;
@SerializedName("Quelle")
private String quelle;
@SerializedName("Sortierung")
private String sort;
/**
* @return the ueberschrift
*/
public String getUeberschrift() {
return ueberschrift;
}
/**
* @param ueberschrift the ueberschrift to set
*/
public void setUeberschrift(String ueberschrift) {
this.ueberschrift = ueberschrift;
}
/**
* @return the location
*/
public List<String> getLocation() {
return location;
}
/**
* @param location the location to set
*/
public void setLocation(List<String> location) {
this.location = location;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}
/**
* @return the attachements
*/
public List<Attachment> getAttachements() {
return attachements;
}
/**
* @param attachements the attachements to set
*/
public void setAttachements(List<Attachment> attachements) {
this.attachements = attachements;
}
/**
* @return the link
*/
public String getLink() {
return link;
}
/**
* @param link the link to set
*/
public void setLink(String link) {
this.link = link;
}
/**
* @return the quelle
*/
public String getQuelle() {
return quelle;
}
/**
* @param quelle the quelle to set
*/
public void setQuelle(String quelle) {
this.quelle = quelle;
}
/**
* @return the sort
*/
public String getSort() {
return sort;
}
/**
* @param sort the sort to set
*/
public void setSort(String sort) {
this.sort = sort;
}
}
| UTF-8 | Java | 2,724 | java | Medien.java | Java | [
{
"context": "chment;\n\nimport java.util.List;\n\n/**\n * Created by fzr on 10.04.17.\n */\npublic class Medien {\n\n @Seri",
"end": 190,
"score": 0.9996116161346436,
"start": 187,
"tag": "USERNAME",
"value": "fzr"
}
] | null | [] | package com.sybit.r750explorer.repository.tables;
import com.google.gson.annotations.SerializedName;
import com.sybit.airtable.vo.Attachment;
import java.util.List;
/**
* Created by fzr on 10.04.17.
*/
public class Medien {
@SerializedName("Überschrift")
private String ueberschrift;
@SerializedName("Location")
private List<String> location;
@SerializedName("Typ")
private String type;
@SerializedName("Text")
private String text;
@SerializedName("Attachments")
private List<Attachment> attachements;
@SerializedName("Link")
private String link;
@SerializedName("Quelle")
private String quelle;
@SerializedName("Sortierung")
private String sort;
/**
* @return the ueberschrift
*/
public String getUeberschrift() {
return ueberschrift;
}
/**
* @param ueberschrift the ueberschrift to set
*/
public void setUeberschrift(String ueberschrift) {
this.ueberschrift = ueberschrift;
}
/**
* @return the location
*/
public List<String> getLocation() {
return location;
}
/**
* @param location the location to set
*/
public void setLocation(List<String> location) {
this.location = location;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}
/**
* @return the attachements
*/
public List<Attachment> getAttachements() {
return attachements;
}
/**
* @param attachements the attachements to set
*/
public void setAttachements(List<Attachment> attachements) {
this.attachements = attachements;
}
/**
* @return the link
*/
public String getLink() {
return link;
}
/**
* @param link the link to set
*/
public void setLink(String link) {
this.link = link;
}
/**
* @return the quelle
*/
public String getQuelle() {
return quelle;
}
/**
* @param quelle the quelle to set
*/
public void setQuelle(String quelle) {
this.quelle = quelle;
}
/**
* @return the sort
*/
public String getSort() {
return sort;
}
/**
* @param sort the sort to set
*/
public void setSort(String sort) {
this.sort = sort;
}
}
| 2,724 | 0.570327 | 0.567022 | 144 | 17.909721 | 15.660865 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.194444 | false | false | 12 |
9e18bc11ff5a3764b5e71c7b17030455f8a7af34 | 12,884,901,923,318 | 52c1f544b37c39a874fd3adcaf6ea3c0f8f76b46 | /chapter_002/src/test/java/ru/kbond/chess/StartGameTest.java | 832e1a36209c2f4eea330f72d6b1b4c3de9b91b3 | [] | no_license | konstbondarenko/junior | https://github.com/konstbondarenko/junior | 105f05982b2ffd7a12bb61073ff566b9556b32b3 | 070415355084fd37f51913472e50421b5a24cdf6 | refs/heads/master | 2021-01-20T15:30:59.463000 | 2019-01-24T15:28:32 | 2019-01-24T15:28:32 | 82,820,392 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.kbond.chess;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
* @author kbondarenko
* @since 05.12.2017
* @version 1
*/
public class StartGameTest {
/**
* Тест, проверяющий перемещение фигуры.
*/
@Test
public void whenSetFigureToPositionThenFigureANewPosition()
throws OccupiedWayException, ImpossibleMoveException, FigureNotFoundException {
Cell source = new Cell(0, 7);
Cell dest = new Cell(1, 6);
DiagonalWay diagonal = new DiagonalWay();
Cell[] result = diagonal.way(source, dest);
Cell[] expected = new Cell[]{new Cell(1, 6), null, null, null, null, null, null};
assertThat(result, is(expected));
}
/**
* Тест, проверяющий возможность хода на ошибки.
*/
@Test
public void whenErrorCheckingThenTrue()
throws OccupiedWayException, ImpossibleMoveException, FigureNotFoundException {
Board board = new Board();
new StartGame(board).play();
Figure bishop = new Bishop(new Cell(0, 7));
Cell dest = new Cell(1, 6);
board.figures[bishop.position.x][bishop.position.y] = bishop;
assertThat(board.move(bishop.position, dest), is(true));
}
/**
* Тест, проверяющий может ли фигура перемещаться по этому пути.
*/
@Test(expected = ImpossibleMoveException.class)
public void whenErrorCheckingThenImpossibleMoveException()
throws OccupiedWayException, ImpossibleMoveException, FigureNotFoundException {
Board board = new Board();
new StartGame(board).play();
Figure bishop = new Bishop(new Cell(0, 7));
Cell dest = new Cell(1, 5);
board.figures[bishop.position.x][bishop.position.y] = bishop;
assertThat(board.move(bishop.position, dest), is(new ImpossibleMoveException()));
}
/**
* Тест, проверяющий есть ли фигура в заданной клетке.
*/
@Test(expected = FigureNotFoundException.class)
public void whenErrorCheckingThenFigureNotFoundException()
throws OccupiedWayException, ImpossibleMoveException, FigureNotFoundException {
Board board = new Board();
new StartGame(board).play();
Figure bishop = new Bishop(new Cell(0, 7));
Cell source = new Cell(2, 7);
Cell dest = new Cell(1, 5);
board.figures[bishop.position.x][bishop.position.y] = bishop;
assertThat(board.move(source, dest), is(new FigureNotFoundException()));
}
/**
* Тест, проверяющий есть ли препятствия на пути фигуры.
*/
@Test(expected = OccupiedWayException.class)
public void whenErrorCheckingThenOccupiedWayException()
throws OccupiedWayException, ImpossibleMoveException, FigureNotFoundException {
Board board = new Board();
new StartGame(board).play();
Figure bishopW = new Bishop(new Cell(0, 2));
Figure bishopB = new Bishop(new Cell(1, 3));
Cell dest = new Cell(2, 4);
board.figures[bishopB.position.x][bishopB.position.y] = bishopB;
board.figures[bishopW.position.x][bishopW.position.y] = bishopW;
assertThat(board.move(bishopW.position, dest), is(new OccupiedWayException()));
}
}
| UTF-8 | Java | 3,488 | java | StartGameTest.java | Java | [
{
"context": ".junit.Assert.assertThat;\n\n/**\n * Test.\n * @author kbondarenko\n * @since 05.12.2017\n * @version 1\n */\npublic cla",
"end": 166,
"score": 0.9994158744812012,
"start": 155,
"tag": "USERNAME",
"value": "kbondarenko"
}
] | null | [] | package ru.kbond.chess;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
* @author kbondarenko
* @since 05.12.2017
* @version 1
*/
public class StartGameTest {
/**
* Тест, проверяющий перемещение фигуры.
*/
@Test
public void whenSetFigureToPositionThenFigureANewPosition()
throws OccupiedWayException, ImpossibleMoveException, FigureNotFoundException {
Cell source = new Cell(0, 7);
Cell dest = new Cell(1, 6);
DiagonalWay diagonal = new DiagonalWay();
Cell[] result = diagonal.way(source, dest);
Cell[] expected = new Cell[]{new Cell(1, 6), null, null, null, null, null, null};
assertThat(result, is(expected));
}
/**
* Тест, проверяющий возможность хода на ошибки.
*/
@Test
public void whenErrorCheckingThenTrue()
throws OccupiedWayException, ImpossibleMoveException, FigureNotFoundException {
Board board = new Board();
new StartGame(board).play();
Figure bishop = new Bishop(new Cell(0, 7));
Cell dest = new Cell(1, 6);
board.figures[bishop.position.x][bishop.position.y] = bishop;
assertThat(board.move(bishop.position, dest), is(true));
}
/**
* Тест, проверяющий может ли фигура перемещаться по этому пути.
*/
@Test(expected = ImpossibleMoveException.class)
public void whenErrorCheckingThenImpossibleMoveException()
throws OccupiedWayException, ImpossibleMoveException, FigureNotFoundException {
Board board = new Board();
new StartGame(board).play();
Figure bishop = new Bishop(new Cell(0, 7));
Cell dest = new Cell(1, 5);
board.figures[bishop.position.x][bishop.position.y] = bishop;
assertThat(board.move(bishop.position, dest), is(new ImpossibleMoveException()));
}
/**
* Тест, проверяющий есть ли фигура в заданной клетке.
*/
@Test(expected = FigureNotFoundException.class)
public void whenErrorCheckingThenFigureNotFoundException()
throws OccupiedWayException, ImpossibleMoveException, FigureNotFoundException {
Board board = new Board();
new StartGame(board).play();
Figure bishop = new Bishop(new Cell(0, 7));
Cell source = new Cell(2, 7);
Cell dest = new Cell(1, 5);
board.figures[bishop.position.x][bishop.position.y] = bishop;
assertThat(board.move(source, dest), is(new FigureNotFoundException()));
}
/**
* Тест, проверяющий есть ли препятствия на пути фигуры.
*/
@Test(expected = OccupiedWayException.class)
public void whenErrorCheckingThenOccupiedWayException()
throws OccupiedWayException, ImpossibleMoveException, FigureNotFoundException {
Board board = new Board();
new StartGame(board).play();
Figure bishopW = new Bishop(new Cell(0, 2));
Figure bishopB = new Bishop(new Cell(1, 3));
Cell dest = new Cell(2, 4);
board.figures[bishopB.position.x][bishopB.position.y] = bishopB;
board.figures[bishopW.position.x][bishopW.position.y] = bishopW;
assertThat(board.move(bishopW.position, dest), is(new OccupiedWayException()));
}
}
| 3,488 | 0.657726 | 0.647059 | 82 | 39.012196 | 27.356497 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.987805 | false | false | 12 |
c8f3174f4632d8e1aad89060e598022d8f93f010 | 26,104,811,291,109 | b1939387e4d7fd2f95ebef9bcc5ebc94e73ca6e1 | /src/com/chapter04/FileWriterDemo.java | 26e9277d70d84a7f969691ba1e39920b347f84eb | [] | no_license | Weikoi/Java_Notes | https://github.com/Weikoi/Java_Notes | e3bc64cb35c183684830240bb2fa66713c3cb161 | 30cc2357500d786393657cd2bc20e0e3c57f40d5 | refs/heads/master | 2020-07-30T15:36:10.972000 | 2019-10-04T09:16:31 | 2019-10-04T09:16:31 | 210,278,848 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.chapter04;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("E:\\IdeaProjects\\summary\\Java_Notes\\src\\data\\a.txt");
fw.write("Learing Java is a wise Decision!");
fw.flush();
fw.close();
}
}
| UTF-8 | Java | 377 | java | FileWriterDemo.java | Java | [] | null | [] |
package com.chapter04;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("E:\\IdeaProjects\\summary\\Java_Notes\\src\\data\\a.txt");
fw.write("Learing Java is a wise Decision!");
fw.flush();
fw.close();
}
}
| 377 | 0.657825 | 0.65252 | 14 | 25.857143 | 27.385756 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 12 |
ba5011edcdd7d657d59d3459643b7c8b1012b679 | 11,433,202,988,997 | 04cf97bc7d752a9d16df818d9818184e7955babe | /Projeto/src/conexaoBD/DMGeral.java | 527f39b90e70dc7174141d623970c558333f0fc5 | [] | no_license | filipe2santos/Zoo | https://github.com/filipe2santos/Zoo | b411de244f921859727560b783de91b205fd4c91 | 43a7b62cfd53e173d959706349b735d90dcc888f | refs/heads/master | 2020-09-04T21:43:31.112000 | 2020-02-05T21:03:06 | 2020-02-05T21:03:06 | 219,899,812 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package conexaoBD;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public abstract class DMGeral {
protected static Connection connection;
public static Connection getConnection() {
return connection;
}
public boolean conectaDataBase(String dataBase, String userName, String password) {
String url = "jdbc:mysql://localhost/" + dataBase + "?serverTimezone=UTC";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(url, userName, password);
// JOptionPane.showMessageDialog(null,"Conexao ao banco de dados feita com
// sucesso!");
return true;
} catch (ClassNotFoundException cnfex) {
JOptionPane.showMessageDialog(null, "Falha ao abrir o driver JDBC/ODBC", "ERROR", 0);
cnfex.printStackTrace();
return false;
} catch (SQLException sqlex) {
JOptionPane.showMessageDialog(null, "Impossível conectar", "ERROR", 0);
sqlex.printStackTrace();
return false;
}
}
public void shutDown() {
try {
connection.close();
} catch (SQLException sqlex) {
System.err.println("Impossível desconectar");
sqlex.printStackTrace();
}
}
abstract public String buscarPessoa(String cpf);
abstract public String listarTodos();
abstract public void excluir(String cpf);
abstract public void excluirTodos();
// incluir e alterar tem parametros diferentes dependendo da classe
} | WINDOWS-1250 | Java | 1,497 | java | DMGeral.java | Java | [] | null | [] | package conexaoBD;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public abstract class DMGeral {
protected static Connection connection;
public static Connection getConnection() {
return connection;
}
public boolean conectaDataBase(String dataBase, String userName, String password) {
String url = "jdbc:mysql://localhost/" + dataBase + "?serverTimezone=UTC";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(url, userName, password);
// JOptionPane.showMessageDialog(null,"Conexao ao banco de dados feita com
// sucesso!");
return true;
} catch (ClassNotFoundException cnfex) {
JOptionPane.showMessageDialog(null, "Falha ao abrir o driver JDBC/ODBC", "ERROR", 0);
cnfex.printStackTrace();
return false;
} catch (SQLException sqlex) {
JOptionPane.showMessageDialog(null, "Impossível conectar", "ERROR", 0);
sqlex.printStackTrace();
return false;
}
}
public void shutDown() {
try {
connection.close();
} catch (SQLException sqlex) {
System.err.println("Impossível desconectar");
sqlex.printStackTrace();
}
}
abstract public String buscarPessoa(String cpf);
abstract public String listarTodos();
abstract public void excluir(String cpf);
abstract public void excluirTodos();
// incluir e alterar tem parametros diferentes dependendo da classe
} | 1,497 | 0.711037 | 0.709699 | 54 | 25.722221 | 25.008455 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 12 |
e03f5f4b7500f9046d8ccbe5ee187c998489d3e4 | 8,392,366,125,577 | bc1213d9c2179408026e1a3ed56b0a42a0847437 | /unic-center/unic-web/src/main/java/com/hb/web/controller/TabControllerImpl.java | a5cb1868bbf4373a93f867973c3f44fcc541a953 | [] | no_license | 191059014/testRepo | https://github.com/191059014/testRepo | a1696cd7ae9aeff2b6504417ff269221a7ee799a | d9b7317356a743a292c536026f8c916da85ddb14 | refs/heads/master | 2020-03-23T16:30:13.185000 | 2018-10-12T13:22:03 | 2018-10-12T13:22:03 | 141,813,601 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hb.web.controller;
import com.hb.base.util.JsonUtils;
import com.hb.web.entity.Tab;
import com.hb.web.service.ITabService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController("tabController")
@RequestMapping("controller/web/TabController")
public class TabControllerImpl {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private ITabService tabService;
@RequestMapping("getTabByTreeId")
public Tab getTabByTreeId(@RequestParam("treeId") String treeId) {
Tab tab = tabService.findTabByTreeId(treeId);
if (logger.isInfoEnabled()) {
logger.info(JsonUtils.toJsonString(tab, true));
}
return tab;
}
}
| UTF-8 | Java | 984 | java | TabControllerImpl.java | Java | [] | null | [] | package com.hb.web.controller;
import com.hb.base.util.JsonUtils;
import com.hb.web.entity.Tab;
import com.hb.web.service.ITabService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController("tabController")
@RequestMapping("controller/web/TabController")
public class TabControllerImpl {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private ITabService tabService;
@RequestMapping("getTabByTreeId")
public Tab getTabByTreeId(@RequestParam("treeId") String treeId) {
Tab tab = tabService.findTabByTreeId(treeId);
if (logger.isInfoEnabled()) {
logger.info(JsonUtils.toJsonString(tab, true));
}
return tab;
}
}
| 984 | 0.75813 | 0.756098 | 31 | 30.741936 | 23.298855 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516129 | false | false | 12 |
4769562f168c2962bb5bc08bb47fb0858d473a1a | 8,392,366,122,750 | 320b9464422b4ac928bf990c8033ae170c65102a | /src/main/java/dyomin/mikhail/vision/filters/simple/detector/GutterDetector.java | a3137d32f27586de7fd00bd828ef90ff01bc077c | [] | no_license | DyominMV/vision | https://github.com/DyominMV/vision | 1410c92da08fc3fd143f1b9e85db56b6fe915460 | aeb5a7bacb6b0c375c02082034fc7b4b98013b6d | refs/heads/master | 2023-05-15T11:03:53.570000 | 2021-06-14T18:17:38 | 2021-06-14T18:17:38 | 336,212,953 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dyomin.mikhail.vision.filters.simple.detector;
import dyomin.mikhail.vision.images.ReadableImage;
import dyomin.mikhail.vision.vectors.Direction;
import dyomin.mikhail.vision.vectors.WrappedDouble;
public class GutterDetector implements Detector<WrappedDouble> {
@Override
public boolean detect(int x, int y, ReadableImage<WrappedDouble> image) {
double here = image.getPixel(x,y).value;
double top = image.getPixel(x, y-1).value;
double topLeft = image.getPixel(x-1, y-1).value;
double left = image.getPixel(x-1, y).value;
double bottomLeft = image.getPixel(x-1, y+1).value;
double bottom = image.getPixel(x, y+1).value;
double bottomRight = image.getPixel(x+1, y+1).value;
double right = image.getPixel(x+1, y).value;
double topRight = image.getPixel(x+1, y-1).value;
double f_x = (right - left) / 2;
double f_y = (bottom - top) / 2;
double f_xx = right + left - 2 * here;
double f_yy = top + bottom - 2 * here;
double f_xy = topLeft + bottomRight - topRight - bottomLeft;
double kAlong = f_x * f_x * f_xx + 2 * f_x * f_y * f_xy + f_y * f_y * f_yy;
double kNormal = f_y * f_y * f_xx - 2 * f_x * f_y * f_xy + f_x * f_x * f_yy;
return kNormal >= 0 && Math.abs(kNormal) >= Math.abs(kAlong);
}
}
| UTF-8 | Java | 1,359 | java | GutterDetector.java | Java | [] | null | [] | package dyomin.mikhail.vision.filters.simple.detector;
import dyomin.mikhail.vision.images.ReadableImage;
import dyomin.mikhail.vision.vectors.Direction;
import dyomin.mikhail.vision.vectors.WrappedDouble;
public class GutterDetector implements Detector<WrappedDouble> {
@Override
public boolean detect(int x, int y, ReadableImage<WrappedDouble> image) {
double here = image.getPixel(x,y).value;
double top = image.getPixel(x, y-1).value;
double topLeft = image.getPixel(x-1, y-1).value;
double left = image.getPixel(x-1, y).value;
double bottomLeft = image.getPixel(x-1, y+1).value;
double bottom = image.getPixel(x, y+1).value;
double bottomRight = image.getPixel(x+1, y+1).value;
double right = image.getPixel(x+1, y).value;
double topRight = image.getPixel(x+1, y-1).value;
double f_x = (right - left) / 2;
double f_y = (bottom - top) / 2;
double f_xx = right + left - 2 * here;
double f_yy = top + bottom - 2 * here;
double f_xy = topLeft + bottomRight - topRight - bottomLeft;
double kAlong = f_x * f_x * f_xx + 2 * f_x * f_y * f_xy + f_y * f_y * f_yy;
double kNormal = f_y * f_y * f_xx - 2 * f_x * f_y * f_xy + f_x * f_x * f_yy;
return kNormal >= 0 && Math.abs(kNormal) >= Math.abs(kAlong);
}
}
| 1,359 | 0.618102 | 0.604121 | 34 | 38.970589 | 27.719694 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.941176 | false | false | 12 |
bac7881b814753c1d81961955506e8becac84457 | 670,014,928,842 | aafa5d2602ad5c4e6ed14209fad7975c96dbb705 | /src/org/torproject/jtor/control/events/ControlEventHandler.java | a5bc264e054738a87ebd0ab14ae165dc043fef2c | [] | no_license | koryk/JTor | https://github.com/koryk/JTor | d1738344c47797a71781bc2d4dfa1f5ab5c90660 | fe691825e1b83fffd14f0dbce4da891675c90f65 | refs/heads/master | 2016-09-06T18:11:38.787000 | 2010-08-16T19:05:57 | 2010-08-16T19:05:57 | 327,714 | 5 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.torproject.jtor.control.events;
import org.torproject.jtor.events.EventHandler;
public abstract class ControlEventHandler implements EventHandler {
protected ControlEventQueue ceq;
public ControlEventHandler(ControlEventQueue ceq) {
this.ceq = ceq;
}
public ControlEventHandler() {}
}
| UTF-8 | Java | 312 | java | ControlEventHandler.java | Java | [] | null | [] | package org.torproject.jtor.control.events;
import org.torproject.jtor.events.EventHandler;
public abstract class ControlEventHandler implements EventHandler {
protected ControlEventQueue ceq;
public ControlEventHandler(ControlEventQueue ceq) {
this.ceq = ceq;
}
public ControlEventHandler() {}
}
| 312 | 0.791667 | 0.791667 | 15 | 19.799999 | 22.774839 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.866667 | false | false | 12 |
9b395c7a7d8cfeb174dfe3ce4186564717a93a6b | 18,391,050,026,427 | c16e32e8485709e68df1cebc99a979866c660184 | /awt-swing/Swing/Graphics/MyF1.java | accd24b1bbfb3dc7ccdad803b733dd6c7002afdb | [] | no_license | SudokuLover/JAVA_DUCAT | https://github.com/SudokuLover/JAVA_DUCAT | c8f331b1ddd4dc36c04908acb9dca313d55f83f5 | 477d64427d17885d383e08fc88329a0397f95bf2 | refs/heads/master | 2020-03-29T08:39:45.794000 | 2018-11-02T12:09:33 | 2018-11-02T12:09:33 | 149,722,142 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyCanvas1 extends Canvas {
public void paint(Graphics g)
{
g.setColor(Color.RED);
g.drawLine(70, 70,200, 200);
System.out.println("paint");
}
}
class MyF1{
MyF1(){
Frame f=new Frame("Graphics");
MyCanvas1 c= new MyCanvas1();
f.add(c);
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}
public static void main(String []args)
{
new MyF1();
}
}
| UTF-8 | Java | 464 | java | MyF1.java | Java | [] | null | [] | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyCanvas1 extends Canvas {
public void paint(Graphics g)
{
g.setColor(Color.RED);
g.drawLine(70, 70,200, 200);
System.out.println("paint");
}
}
class MyF1{
MyF1(){
Frame f=new Frame("Graphics");
MyCanvas1 c= new MyCanvas1();
f.add(c);
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}
public static void main(String []args)
{
new MyF1();
}
}
| 464 | 0.640086 | 0.592672 | 31 | 13.935484 | 12.689685 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.516129 | false | false | 12 |
b7cff71eb3d5de0c6b131a98792991b6be1d1a8b | 25,778,393,741,039 | 43d6d9aeb8cc865e80c2a48b81a050472ba27cef | /app/src/main/java/com/eslamshawky/hp/realdatabase/RealTimeDatabaseFirebase/RecyclerChat.java | 190302dc5d2605fb701d9512482091d61291b041 | [] | no_license | EslamShawkyGithub/RealDatabase | https://github.com/EslamShawkyGithub/RealDatabase | dc4fe02bca4da40520b1291c32e68285f6390c9c | deaaa501f8c5133991c15729aa36e966ca6614b4 | refs/heads/master | 2020-04-14T03:41:36.982000 | 2018-12-31T11:42:44 | 2018-12-31T11:42:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eslamshawky.hp.realdatabase.RealTimeDatabaseFirebase;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.PluralsRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.eslamshawky.hp.realdatabase.R;
import java.util.ArrayList;
import java.util.List;
public class RecyclerChat extends RecyclerView.Adapter<RecyclerChat.MainView> {
private Context context;
ArrayList<ChatModel> chatModels;
public RecyclerChat(Context context, ArrayList<Student> students) {
this.context = context;
this.chatModels = chatModels;
}
public RecyclerChat(Context context) {
this.context = context;
}
public RecyclerChat(DatabaseActivity context, List<ChatModel> chatModelList) {
}
public void setContext(Context context) {
this.context = context;
}
public void setChatModels(ArrayList<ChatModel> chatModels) {
this.chatModels = chatModels;
}
@NonNull
@Override
public MainView onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view =LayoutInflater.from(context).inflate(R.layout.chat,viewGroup,false);
return new RecyclerChat.MainView(view);
}
@Override
public void onBindViewHolder(@NonNull MainView mainView, int i) {
ChatModel model = chatModels.get(i);
System.out.println("this in");
String chat = model.getTextChat();
mainView.textChat.setText(chat);
}
@Override
public int getItemCount() {
return chatModels.size();
}
public class MainView extends RecyclerView.ViewHolder {
TextView textChat;
public MainView(@NonNull View itemView) {
super(itemView);
textChat = itemView.findViewById(R.id.text_chat);
}
}
}
| UTF-8 | Java | 1,960 | java | RecyclerChat.java | Java | [] | null | [] | package com.eslamshawky.hp.realdatabase.RealTimeDatabaseFirebase;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.PluralsRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.eslamshawky.hp.realdatabase.R;
import java.util.ArrayList;
import java.util.List;
public class RecyclerChat extends RecyclerView.Adapter<RecyclerChat.MainView> {
private Context context;
ArrayList<ChatModel> chatModels;
public RecyclerChat(Context context, ArrayList<Student> students) {
this.context = context;
this.chatModels = chatModels;
}
public RecyclerChat(Context context) {
this.context = context;
}
public RecyclerChat(DatabaseActivity context, List<ChatModel> chatModelList) {
}
public void setContext(Context context) {
this.context = context;
}
public void setChatModels(ArrayList<ChatModel> chatModels) {
this.chatModels = chatModels;
}
@NonNull
@Override
public MainView onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view =LayoutInflater.from(context).inflate(R.layout.chat,viewGroup,false);
return new RecyclerChat.MainView(view);
}
@Override
public void onBindViewHolder(@NonNull MainView mainView, int i) {
ChatModel model = chatModels.get(i);
System.out.println("this in");
String chat = model.getTextChat();
mainView.textChat.setText(chat);
}
@Override
public int getItemCount() {
return chatModels.size();
}
public class MainView extends RecyclerView.ViewHolder {
TextView textChat;
public MainView(@NonNull View itemView) {
super(itemView);
textChat = itemView.findViewById(R.id.text_chat);
}
}
}
| 1,960 | 0.704082 | 0.703571 | 71 | 26.605635 | 24.375858 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.492958 | false | false | 12 |
5ab030abf204bcfe7dfd559f5ec169aff877b29b | 28,595,892,286,007 | bc1452cea2da3c6f9186553b097a3a1b1b4ddcb4 | /com.skratchdot.riff.wav/src/com/skratchdot/riff/wav/ChunkDataListTypeIcop.java | 6f1e6c9896a9e8a20f0b8060b72df8f11f3169c2 | [] | no_license | thisisanaccount/riff-wav-for-java | https://github.com/thisisanaccount/riff-wav-for-java | aef252085330cabc8d8bd40e3b89aad02b48456f | 4bdc6523ea118ef4f384abc3a0d8009d31bac9e8 | refs/heads/master | 2021-01-21T18:42:42.039000 | 2015-06-17T09:34:03 | 2015-06-17T09:34:03 | 37,415,162 | 0 | 0 | null | true | 2015-06-14T14:20:13 | 2015-06-14T14:20:13 | 2013-12-13T04:53:40 | 2012-12-15T16:02:50 | 436 | 0 | 0 | 0 | null | null | null | package com.skratchdot.riff.wav;
public interface ChunkDataListTypeIcop extends ChunkDataListType {
}
| UTF-8 | Java | 109 | java | ChunkDataListTypeIcop.java | Java | [] | null | [] | package com.skratchdot.riff.wav;
public interface ChunkDataListTypeIcop extends ChunkDataListType {
}
| 109 | 0.798165 | 0.798165 | 5 | 19.799999 | 26.156452 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 12 |
0dbdbd7a514c516c6804495aae873238bccdf3e9 | 25,074,019,109,624 | f7a721d63a39c3afe1912cf78511012385690f91 | /NebulaData/src/main/java/com/hubspot/nebula/build/BuildDAO.java | 93e53d18a1cdca2cc11fdc904da82bc2bc517a79 | [
"Apache-2.0"
] | permissive | pkdevboxy/Nebula | https://github.com/pkdevboxy/Nebula | 5a9588a4624ace17b7e20a03f9edfaf777fa00ce | 2a3c5e48cebcbb8fee74cc5a05196e91971b0144 | refs/heads/master | 2021-01-16T22:46:51.981000 | 2016-02-03T20:17:22 | 2016-02-03T20:17:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hubspot.nebula.build;
import com.hubspot.rosetta.jdbi.BindWithRosetta;
import com.hubspot.rosetta.jdbi.RosettaMapperFactory;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.GetGeneratedKeys;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapperFactory;
import com.hubspot.nebula.NebulaDataModule;
import com.hubspot.nebula.deploy.Deploy;
@RegisterMapperFactory(RosettaMapperFactory.class)
public interface BuildDAO {
@SqlQuery("SELECT * FROM " + NebulaDataModule.BUILDS_TABLE_NAME + " WHERE id = :id LIMIT 1")
public Build get(@Bind("id") long id);
@SqlQuery("SELECT * FROM " + NebulaDataModule.BUILDS_TABLE_NAME + " WHERE buildKey = :buildKey AND buildNumber = :buildNumber LIMIT 1")
public Build getForDeploy(@BindWithRosetta Deploy deploy);
@SqlUpdate("INSERT INTO " + NebulaDataModule.BUILDS_TABLE_NAME + " (buildKey, number, status, startTime, duration, gitOwner, gitRepo, gitBranch, lastGitCommitSha, bad, artifactLocation) VALUES (:buildKey, :number, :status, :startTime, :duration, :gitOwner, :gitRepo, :gitBranch, :lastGitCommitSha, :bad, :artifactLocation)")
@GetGeneratedKeys
public int create(@BindWithRosetta Build build);
@SqlUpdate("UPDATE " + NebulaDataModule.BUILDS_TABLE_NAME + " SET status = :status WHERE id = :id")
public void setStatus(@Bind("id") long id, @Bind("status") int buildStatusState);
@SqlUpdate("UPDATE " + NebulaDataModule.BUILDS_TABLE_NAME + " SET bad = :bad WHERE id = :id")
public void setBad(@Bind("id") long id, @Bind("bad") boolean bad);
@SqlUpdate("UPDATE " + NebulaDataModule.BUILDS_TABLE_NAME + " SET duration = :duration WHERE id = :id")
public void setDuration(@Bind("id") long id, @Bind("duration") long duration);
@SqlUpdate("UPDATE " + NebulaDataModule.BUILDS_TABLE_NAME + " SET artifactLocation = :artifactLocation WHERE id = :id")
public void setArtifactLocation(@Bind("id") long id, @Bind("artifactLocation") String artifactLocation);
}
| UTF-8 | Java | 2,067 | java | BuildDAO.java | Java | [] | null | [] | package com.hubspot.nebula.build;
import com.hubspot.rosetta.jdbi.BindWithRosetta;
import com.hubspot.rosetta.jdbi.RosettaMapperFactory;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.GetGeneratedKeys;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapperFactory;
import com.hubspot.nebula.NebulaDataModule;
import com.hubspot.nebula.deploy.Deploy;
@RegisterMapperFactory(RosettaMapperFactory.class)
public interface BuildDAO {
@SqlQuery("SELECT * FROM " + NebulaDataModule.BUILDS_TABLE_NAME + " WHERE id = :id LIMIT 1")
public Build get(@Bind("id") long id);
@SqlQuery("SELECT * FROM " + NebulaDataModule.BUILDS_TABLE_NAME + " WHERE buildKey = :buildKey AND buildNumber = :buildNumber LIMIT 1")
public Build getForDeploy(@BindWithRosetta Deploy deploy);
@SqlUpdate("INSERT INTO " + NebulaDataModule.BUILDS_TABLE_NAME + " (buildKey, number, status, startTime, duration, gitOwner, gitRepo, gitBranch, lastGitCommitSha, bad, artifactLocation) VALUES (:buildKey, :number, :status, :startTime, :duration, :gitOwner, :gitRepo, :gitBranch, :lastGitCommitSha, :bad, :artifactLocation)")
@GetGeneratedKeys
public int create(@BindWithRosetta Build build);
@SqlUpdate("UPDATE " + NebulaDataModule.BUILDS_TABLE_NAME + " SET status = :status WHERE id = :id")
public void setStatus(@Bind("id") long id, @Bind("status") int buildStatusState);
@SqlUpdate("UPDATE " + NebulaDataModule.BUILDS_TABLE_NAME + " SET bad = :bad WHERE id = :id")
public void setBad(@Bind("id") long id, @Bind("bad") boolean bad);
@SqlUpdate("UPDATE " + NebulaDataModule.BUILDS_TABLE_NAME + " SET duration = :duration WHERE id = :id")
public void setDuration(@Bind("id") long id, @Bind("duration") long duration);
@SqlUpdate("UPDATE " + NebulaDataModule.BUILDS_TABLE_NAME + " SET artifactLocation = :artifactLocation WHERE id = :id")
public void setArtifactLocation(@Bind("id") long id, @Bind("artifactLocation") String artifactLocation);
}
| 2,067 | 0.754717 | 0.75133 | 37 | 54.864864 | 59.392036 | 326 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.108108 | false | false | 12 |
4b24e9dfd96e7c984ff2add481507ffdf804084c | 27,290,222,268,251 | 810f506dcd90bd719d63f60e3ab3c1f298f2425e | /DemoServer/AdditionalLanguages/java/src/test/java/net/ravendb/demo/test/relatedDocuments/CreateRelatedDocumentsTest.java | 1d25358ebb7c7809dd116832b2eb3adac3e9aea9 | [] | no_license | topalach/demo | https://github.com/topalach/demo | 2e2c37ec98595c4d84b196d3b17d1caf8cb85bf7 | 8dc0c6739406db529b878d7af6e60321fae85e9f | refs/heads/master | 2022-08-30T22:00:26.508000 | 2022-08-25T11:04:46 | 2022-08-25T11:04:46 | 208,802,367 | 0 | 1 | null | true | 2019-09-16T13:08:16 | 2019-09-16T13:08:16 | 2019-09-16T13:06:48 | 2019-09-16T13:06:45 | 22,948 | 0 | 0 | 0 | null | false | false | package net.ravendb.demo.test.relatedDocuments;
import net.ravendb.demo.common.models.Company;
import net.ravendb.demo.relatedDocuments.createRelatedDocuments.CreateRelatedDocuments;
import org.junit.Test;
public class CreateRelatedDocumentsTest {
@Test
public void test() throws Exception {
CreateRelatedDocuments.RunParams params = new CreateRelatedDocuments.RunParams();
params.setProductName("p1");
params.setSupplierName("s2");
params.setSupplierPhone("123");
new CreateRelatedDocuments().run(params);
}
}
| UTF-8 | Java | 568 | java | CreateRelatedDocumentsTest.java | Java | [] | null | [] | package net.ravendb.demo.test.relatedDocuments;
import net.ravendb.demo.common.models.Company;
import net.ravendb.demo.relatedDocuments.createRelatedDocuments.CreateRelatedDocuments;
import org.junit.Test;
public class CreateRelatedDocumentsTest {
@Test
public void test() throws Exception {
CreateRelatedDocuments.RunParams params = new CreateRelatedDocuments.RunParams();
params.setProductName("p1");
params.setSupplierName("s2");
params.setSupplierPhone("123");
new CreateRelatedDocuments().run(params);
}
}
| 568 | 0.744718 | 0.735915 | 19 | 28.894737 | 27.617491 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 12 |
c14cd4a87ca3f44fd11f6cd1a5a52170743fc737 | 31,086,973,305,936 | 6eaf29be8aad9857b4863be13d1c7f10f5df2212 | /src/main/java/com/honpe/enums/EmailEnum.java | 7e6b5e0e36c9caa5124a813b04ccc423f66c31fb | [] | no_license | he313572052/web-api | https://github.com/he313572052/web-api | e8eba1e10beabc243510826b51ff33b0a6bfff2c | ae88dcfb885d66f1c03fde71989969e74d8b93d6 | refs/heads/master | 2018-10-15T23:15:23.753000 | 2018-09-18T08:46:20 | 2018-09-18T08:46:20 | 133,320,604 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.honpe.enums;
public enum EmailEnum {
COMPANY_EMAIL(2, "企业邮箱"), BUSINESS_EMAIL(3, "业务邮箱");
private int email_type;
private String desc;
private EmailEnum(int email_type, String desc) {
this.email_type = email_type;
this.desc = desc;
}
public int getEmail_type() {
return email_type;
}
public void setEmail_type(int email_type) {
this.email_type = email_type;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
| UTF-8 | Java | 549 | java | EmailEnum.java | Java | [] | null | [] | package com.honpe.enums;
public enum EmailEnum {
COMPANY_EMAIL(2, "企业邮箱"), BUSINESS_EMAIL(3, "业务邮箱");
private int email_type;
private String desc;
private EmailEnum(int email_type, String desc) {
this.email_type = email_type;
this.desc = desc;
}
public int getEmail_type() {
return email_type;
}
public void setEmail_type(int email_type) {
this.email_type = email_type;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
| 549 | 0.641651 | 0.637899 | 30 | 15.766666 | 16.138325 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.3 | false | false | 12 |
11c38174b083c5101a5fd0243400f0b611942f9f | 26,182,120,662,456 | 1bbefa8c1ad759257f812b0f3757a0fb2342f2a1 | /src/com/svwpu/manage/mailapply/application/modules/apply/security/LocalGrantedAuthority.java | 1da41aa7d09ded54806d359e4482dec3d604b0ef | [] | no_license | XWay/MailApply | https://github.com/XWay/MailApply | 45923e47fcde2633e7e30d55a0e90b7207fd0c9c | 36ba9cfa4c60dcf385557554ed761ad886094d78 | refs/heads/master | 2018-01-07T16:54:52.025000 | 2012-02-17T23:38:04 | 2012-02-17T23:38:04 | 3,334,469 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.svwpu.manage.mailapply.application.modules.apply.security;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;
public class LocalGrantedAuthority implements GrantedAuthority {
private static final long serialVersionUID = -2034345191085563780L;
private final RoleType role;
public LocalGrantedAuthority(RoleType role) {
Assert.notNull(role, "传入RoleType参数不为空!");
this.role = role;
}
@Override
public String getAuthority() {
return role.name();
}
public boolean equals(Object obj) {
if (obj instanceof String) {
return obj.equals(this.role);
}
if (obj instanceof GrantedAuthority) {
GrantedAuthority attr = (GrantedAuthority) obj;
return this.role.equals(attr.getAuthority());
}
return false;
}
public int hashCode() {
return this.role.hashCode();
}
public String toString() {
return this.role.name();
}
}
| UTF-8 | Java | 931 | java | LocalGrantedAuthority.java | Java | [] | null | [] | package com.svwpu.manage.mailapply.application.modules.apply.security;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;
public class LocalGrantedAuthority implements GrantedAuthority {
private static final long serialVersionUID = -2034345191085563780L;
private final RoleType role;
public LocalGrantedAuthority(RoleType role) {
Assert.notNull(role, "传入RoleType参数不为空!");
this.role = role;
}
@Override
public String getAuthority() {
return role.name();
}
public boolean equals(Object obj) {
if (obj instanceof String) {
return obj.equals(this.role);
}
if (obj instanceof GrantedAuthority) {
GrantedAuthority attr = (GrantedAuthority) obj;
return this.role.equals(attr.getAuthority());
}
return false;
}
public int hashCode() {
return this.role.hashCode();
}
public String toString() {
return this.role.name();
}
}
| 931 | 0.745355 | 0.72459 | 42 | 20.785715 | 21.7108 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.357143 | false | false | 12 |
4dd67073ca61898aa72291ecafe51bb7022e4c7f | 11,252,814,355,402 | 991805b82be711e34f6eeae05718827ec9c3f439 | /src/vn/fpt/edu/view/FormDoiMatKhau.java | a5760c21877b4db6dd206fde5265afd66657c1e8 | [] | no_license | trungle98hn/Ass-G5-Fpoly | https://github.com/trungle98hn/Ass-G5-Fpoly | 287171d105571b19ffe582b7bd8666d5061bd2d9 | 115ae9d775d4bf44e0c563d2a7d522a0f7cb0025 | refs/heads/master | 2021-08-23T20:25:15.395000 | 2017-12-06T11:49:41 | 2017-12-06T11:49:41 | 112,160,799 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 vn.fpt.edu.view;
/**
*
* @author lich - kfc
*/
public class FormDoiMatKhau extends javax.swing.JFrame {
/**
* Creates new form FormDoiMatKhau
*/
public FormDoiMatKhau() {
initComponents();
}
/**
* 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() {
lblMưatKhauCu = new javax.swing.JLabel();
lblMatKhauMoi = new javax.swing.JLabel();
lblNhapLaiMatKhau = new javax.swing.JLabel();
PwMatKhauCu = new javax.swing.JPasswordField();
PwMatKhauMoi = new javax.swing.JPasswordField();
PwNhapLaiMatKhau = new javax.swing.JPasswordField();
btnOK = new javax.swing.JButton();
btnBack = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Đổi mật khẩu");
lblMưatKhauCu.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblMưatKhauCu.setText("Mật Khẩu Cũ");
lblMưatKhauCu.setToolTipText("");
lblMatKhauMoi.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblMatKhauMoi.setText("Mật Khẩu Mới");
lblMatKhauMoi.setToolTipText("");
lblNhapLaiMatKhau.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblNhapLaiMatKhau.setText("Nhập Lại Mật Khẩu");
lblNhapLaiMatKhau.setToolTipText("");
PwMatKhauCu.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
PwMatKhauCu.setToolTipText("");
PwMatKhauMoi.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
PwMatKhauMoi.setToolTipText("");
PwNhapLaiMatKhau.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
PwNhapLaiMatKhau.setToolTipText("");
btnOK.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnOK.setText("OK");
btnOK.setToolTipText("");
btnBack.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnBack.setText("Back");
btnBack.setToolTipText("");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(67, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblMatKhauMoi)
.addComponent(lblMưatKhauCu)
.addComponent(lblNhapLaiMatKhau))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(PwMatKhauCu, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(PwNhapLaiMatKhau, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(PwMatKhauMoi, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(btnOK)
.addGap(50, 50, 50)
.addComponent(btnBack)
.addGap(59, 59, 59)))
.addGap(62, 62, 62))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(PwMatKhauCu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblMưatKhauCu, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(PwMatKhauMoi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblMatKhauMoi))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblNhapLaiMatKhau)
.addComponent(PwNhapLaiMatKhau, 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(btnOK)
.addComponent(btnBack))
.addContainerGap(85, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPasswordField PwMatKhauCu;
private javax.swing.JPasswordField PwMatKhauMoi;
private javax.swing.JPasswordField PwNhapLaiMatKhau;
private javax.swing.JButton btnBack;
private javax.swing.JButton btnOK;
private javax.swing.JLabel lblMatKhauMoi;
private javax.swing.JLabel lblMưatKhauCu;
private javax.swing.JLabel lblNhapLaiMatKhau;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 6,802 | java | FormDoiMatKhau.java | Java | [
{
"context": "r.\n */\npackage vn.fpt.edu.view;\n\n/**\n *\n * @author lich - kfc\n */\npublic class FormDoiMatKhau extends",
"end": 228,
"score": 0.8769621849060059,
"start": 228,
"tag": "USERNAME",
"value": ""
},
{
"context": ".\n */\npackage vn.fpt.edu.view;\n\n/**\n *\n * @author lich - kfc\n */\npublic class FormDoiMatKhau extends jav",
"end": 233,
"score": 0.9618601202964783,
"start": 229,
"tag": "USERNAME",
"value": "lich"
},
{
"context": "package vn.fpt.edu.view;\n\n/**\n *\n * @author lich - kfc\n */\npublic class FormDoiMatKhau extends javax.swi",
"end": 239,
"score": 0.993788480758667,
"start": 236,
"tag": "USERNAME",
"value": "kfc"
}
] | null | [] | /*
* 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 vn.fpt.edu.view;
/**
*
* @author lich - kfc
*/
public class FormDoiMatKhau extends javax.swing.JFrame {
/**
* Creates new form FormDoiMatKhau
*/
public FormDoiMatKhau() {
initComponents();
}
/**
* 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() {
lblMưatKhauCu = new javax.swing.JLabel();
lblMatKhauMoi = new javax.swing.JLabel();
lblNhapLaiMatKhau = new javax.swing.JLabel();
PwMatKhauCu = new javax.swing.JPasswordField();
PwMatKhauMoi = new javax.swing.JPasswordField();
PwNhapLaiMatKhau = new javax.swing.JPasswordField();
btnOK = new javax.swing.JButton();
btnBack = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Đổi mật khẩu");
lblMưatKhauCu.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblMưatKhauCu.setText("Mật Khẩu Cũ");
lblMưatKhauCu.setToolTipText("");
lblMatKhauMoi.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblMatKhauMoi.setText("Mật Khẩu Mới");
lblMatKhauMoi.setToolTipText("");
lblNhapLaiMatKhau.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lblNhapLaiMatKhau.setText("Nhập Lại Mật Khẩu");
lblNhapLaiMatKhau.setToolTipText("");
PwMatKhauCu.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
PwMatKhauCu.setToolTipText("");
PwMatKhauMoi.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
PwMatKhauMoi.setToolTipText("");
PwNhapLaiMatKhau.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
PwNhapLaiMatKhau.setToolTipText("");
btnOK.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnOK.setText("OK");
btnOK.setToolTipText("");
btnBack.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnBack.setText("Back");
btnBack.setToolTipText("");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(67, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblMatKhauMoi)
.addComponent(lblMưatKhauCu)
.addComponent(lblNhapLaiMatKhau))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(PwMatKhauCu, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(PwNhapLaiMatKhau, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(PwMatKhauMoi, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(btnOK)
.addGap(50, 50, 50)
.addComponent(btnBack)
.addGap(59, 59, 59)))
.addGap(62, 62, 62))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(PwMatKhauCu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblMưatKhauCu, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(PwMatKhauMoi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblMatKhauMoi))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblNhapLaiMatKhau)
.addComponent(PwNhapLaiMatKhau, 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(btnOK)
.addComponent(btnBack))
.addContainerGap(85, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPasswordField PwMatKhauCu;
private javax.swing.JPasswordField PwMatKhauMoi;
private javax.swing.JPasswordField PwNhapLaiMatKhau;
private javax.swing.JButton btnBack;
private javax.swing.JButton btnOK;
private javax.swing.JLabel lblMatKhauMoi;
private javax.swing.JLabel lblMưatKhauCu;
private javax.swing.JLabel lblNhapLaiMatKhau;
// End of variables declaration//GEN-END:variables
}
| 6,802 | 0.641306 | 0.62609 | 138 | 48.050724 | 38.537262 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.789855 | false | false | 12 |
29c2fb65f7ce4dce852cfef7cc6b0440340ae4dc | 23,733,989,323,638 | 9c08dce712c55069bb88559a0e90c58b01ccbbbb | /src/main/java/com/memin/magazam/security/social/package-info.java | 2a794c7debba959b2f0fb1370e344f706bdccad0 | [] | no_license | memn/magazam | https://github.com/memn/magazam | b88ceb35a46275925fedd86a97ddeef415386038 | e192186eaa33b29c4f6c2efb4d1b50fd22540f11 | refs/heads/master | 2021-06-13T19:28:51.557000 | 2017-01-19T12:17:04 | 2017-01-19T12:17:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Spring social configuration.
*/
package com.memin.magazam.security.social;
| UTF-8 | Java | 83 | java | package-info.java | Java | [] | null | [] | /**
* Spring social configuration.
*/
package com.memin.magazam.security.social;
| 83 | 0.73494 | 0.73494 | 4 | 19.75 | 17.195566 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 12 |
60f185dc4b4ce96e86b62f3734cb3907c406111e | 22,505,628,687,837 | df3bb750de14ea1d7cef3cd06fcb6f79f0f26f2c | /Event-Project/Java-Files/CalendarScanner.java | 6c7ec9af05b58c2f8b92f179b534b08cb037c4be | [] | no_license | XZ7QN0/Java-Event-Project-Data-Structures-Spring2016 | https://github.com/XZ7QN0/Java-Event-Project-Data-Structures-Spring2016 | fc98aa0a888961a5a5783d99b536899c9f4bead1 | b1fa473bf8b27f36a8d03087d24dd4b6e4a6be0b | refs/heads/master | 2021-05-25T10:09:31.523000 | 2018-03-28T01:28:23 | 2018-03-28T01:28:23 | 127,061,320 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package projectevents;
import java.util.StringTokenizer;
import java.util.Scanner;
import java.io.*;
import java.time.*;
public class CalendarScanner
{
private File m_file;
private Scanner m_fileScanner;
public static void main(String[] args)throws IOException, DateTimeException
{
CalendarScanner myScanner = new CalendarScanner("date.txt");
Event myEvent = myScanner.getEvent();
System.out.println(myEvent);
}
public CalendarScanner(String filename)throws IOException
{
m_file = new File(filename);
m_fileScanner = new Scanner(m_file);
}
/**
traverseDate
*/
private String[] traverseLine(String line)
{
StringTokenizer myTokenizer = new StringTokenizer(line, ",: ");
String[] arr = new String[myTokenizer.countTokens()];
for(int count = 0; count < arr.length; count++)
{
arr[count] = myTokenizer.nextToken();
}
return arr;
}
/**
getEvent method
*/
public Event getEvent()throws DateTimeException
{
String title = getTitle();
String description = getDescription();
String address = getAddress();
String location = getLocation();
String city = getCity(location);
String state = getState(location);
String zip = getZip(location);
String date = getDate();
String dayOfWeek = getDayOfWeek(date);
int month = getMonthOfYear(date);
int day = getDayOfMonth(date);
int year = getYear(date);
int hour = getHour(date);
int minute = getMinute(date);
String AmPm = getAmPm(date);
Event myEvent = new Event(year, month, day, hour, minute, title, description, address, city, zip, state);
return myEvent;
}
/**
getDescription method
*/
public String getDescription()
{
String description = m_fileScanner.nextLine();
return description;
}
/**
getTitle method
*/
public String getTitle()
{
String title = m_fileScanner.nextLine();
return title;
}
/**
getAddress method
*/
public String getAddress()
{
String address = m_fileScanner.nextLine();
return address;
}
/**
get
/**
getDate method
*/
public String getDate()
{
String date = m_fileScanner.nextLine();
return date;
}
/**
getLocation method
*/
public String getLocation()
{
String location = m_fileScanner.nextLine();
return location;
}
/**
getCity method
*/
public String getCity(String location)
{
String [] arr = traverseLine(location);
String city = arr[0];
return city;
}
/**
getState method
*/
public String getState(String location)
{
String [] arr = traverseLine(location);
String state = arr[1];
return state;
}
/**
getZip method
*/
public String getZip(String location)
{
String[] arr = traverseLine(location);
String zip = arr[2];
return zip;
}
/**
getDayOfWeek method
*/
public String getDayOfWeek(String date)
{
String[] arr = traverseLine(date);
String dayOfWeek = arr[0];
return dayOfWeek;
}
/**
getMonthOfYear method
*/
public int getMonthOfYear(String date)
{
String[] arr = traverseLine(date);
String monthOfYear = arr[1];
int month;
switch(monthOfYear)
{
case "January":
month = 1;
break;
case "February":
month = 2;
break;
case "March":
month = 3;
break;
case "April":
month = 4;
break;
case "May":
month = 5;
break;
case "June":
month = 6;
break;
case "July":
month = 7;
break;
case "August":
month = 8;
break;
case "September":
month = 9;
break;
case "October":
month = 10;
break;
case "November":
month = 11;
break;
case "December":
month = 12;
break;
default:
month = -1;
}
return month;
}
/**
getDayOfMonth method
*/
public int getDayOfMonth(String date)
{
String[] arr = traverseLine(date);
String dayOfMonth = arr[2];
int numDayOfMonth = Integer.parseInt(dayOfMonth);
return numDayOfMonth;
}
/**
getYear method
*/
public int getYear(String date)
{
String[] arr = traverseLine(date);
String year = arr[3];
int numYear = Integer.parseInt(year);
return numYear;
}
/**
getHour method
*/
public int getHour(String date)
{
String[] arr = traverseLine(date);
String hour = arr[4];
int numHour = Integer.parseInt(hour);
return numHour;
}
/**
getMinute method
*/
public int getMinute(String date)
{
String[] arr = traverseLine(date);
String minute = arr[5];
int numMinute = Integer.parseInt(minute);
return numMinute;
}
/**
getAmPm method
*/
public String getAmPm(String date)
{
String[] arr = traverseLine(date);
String amPM = arr[6];
return amPM;
}
/**
hasNextLine method
*/
public boolean hasNextLine()
{
return m_fileScanner.hasNextLine();
}
} | UTF-8 | Java | 6,235 | java | CalendarScanner.java | Java | [] | null | [] | package projectevents;
import java.util.StringTokenizer;
import java.util.Scanner;
import java.io.*;
import java.time.*;
public class CalendarScanner
{
private File m_file;
private Scanner m_fileScanner;
public static void main(String[] args)throws IOException, DateTimeException
{
CalendarScanner myScanner = new CalendarScanner("date.txt");
Event myEvent = myScanner.getEvent();
System.out.println(myEvent);
}
public CalendarScanner(String filename)throws IOException
{
m_file = new File(filename);
m_fileScanner = new Scanner(m_file);
}
/**
traverseDate
*/
private String[] traverseLine(String line)
{
StringTokenizer myTokenizer = new StringTokenizer(line, ",: ");
String[] arr = new String[myTokenizer.countTokens()];
for(int count = 0; count < arr.length; count++)
{
arr[count] = myTokenizer.nextToken();
}
return arr;
}
/**
getEvent method
*/
public Event getEvent()throws DateTimeException
{
String title = getTitle();
String description = getDescription();
String address = getAddress();
String location = getLocation();
String city = getCity(location);
String state = getState(location);
String zip = getZip(location);
String date = getDate();
String dayOfWeek = getDayOfWeek(date);
int month = getMonthOfYear(date);
int day = getDayOfMonth(date);
int year = getYear(date);
int hour = getHour(date);
int minute = getMinute(date);
String AmPm = getAmPm(date);
Event myEvent = new Event(year, month, day, hour, minute, title, description, address, city, zip, state);
return myEvent;
}
/**
getDescription method
*/
public String getDescription()
{
String description = m_fileScanner.nextLine();
return description;
}
/**
getTitle method
*/
public String getTitle()
{
String title = m_fileScanner.nextLine();
return title;
}
/**
getAddress method
*/
public String getAddress()
{
String address = m_fileScanner.nextLine();
return address;
}
/**
get
/**
getDate method
*/
public String getDate()
{
String date = m_fileScanner.nextLine();
return date;
}
/**
getLocation method
*/
public String getLocation()
{
String location = m_fileScanner.nextLine();
return location;
}
/**
getCity method
*/
public String getCity(String location)
{
String [] arr = traverseLine(location);
String city = arr[0];
return city;
}
/**
getState method
*/
public String getState(String location)
{
String [] arr = traverseLine(location);
String state = arr[1];
return state;
}
/**
getZip method
*/
public String getZip(String location)
{
String[] arr = traverseLine(location);
String zip = arr[2];
return zip;
}
/**
getDayOfWeek method
*/
public String getDayOfWeek(String date)
{
String[] arr = traverseLine(date);
String dayOfWeek = arr[0];
return dayOfWeek;
}
/**
getMonthOfYear method
*/
public int getMonthOfYear(String date)
{
String[] arr = traverseLine(date);
String monthOfYear = arr[1];
int month;
switch(monthOfYear)
{
case "January":
month = 1;
break;
case "February":
month = 2;
break;
case "March":
month = 3;
break;
case "April":
month = 4;
break;
case "May":
month = 5;
break;
case "June":
month = 6;
break;
case "July":
month = 7;
break;
case "August":
month = 8;
break;
case "September":
month = 9;
break;
case "October":
month = 10;
break;
case "November":
month = 11;
break;
case "December":
month = 12;
break;
default:
month = -1;
}
return month;
}
/**
getDayOfMonth method
*/
public int getDayOfMonth(String date)
{
String[] arr = traverseLine(date);
String dayOfMonth = arr[2];
int numDayOfMonth = Integer.parseInt(dayOfMonth);
return numDayOfMonth;
}
/**
getYear method
*/
public int getYear(String date)
{
String[] arr = traverseLine(date);
String year = arr[3];
int numYear = Integer.parseInt(year);
return numYear;
}
/**
getHour method
*/
public int getHour(String date)
{
String[] arr = traverseLine(date);
String hour = arr[4];
int numHour = Integer.parseInt(hour);
return numHour;
}
/**
getMinute method
*/
public int getMinute(String date)
{
String[] arr = traverseLine(date);
String minute = arr[5];
int numMinute = Integer.parseInt(minute);
return numMinute;
}
/**
getAmPm method
*/
public String getAmPm(String date)
{
String[] arr = traverseLine(date);
String amPM = arr[6];
return amPM;
}
/**
hasNextLine method
*/
public boolean hasNextLine()
{
return m_fileScanner.hasNextLine();
}
} | 6,235 | 0.489334 | 0.485004 | 300 | 19.786667 | 16.675365 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.396667 | false | false | 12 |
e5336baaf70d37e9999f55f75eb36f4f4dbd1026 | 33,809,982,580,519 | c21806eb8f6e7577480cc29d641080dd5dbbfc3d | /src/main/java/org/ubicollab/ubibazaar/api/resources/AppResource.java | 79ebd39bfdf7b5975a25ad97c3cc18d272f8944b | [
"Apache-2.0"
] | permissive | ubibazaar/api | https://github.com/ubibazaar/api | 325cd125c1220ac0f9d578add9f80d7710fa0bae | fa4ecbe78f528690a3bae3cac7b48247eabf676e | refs/heads/master | 2016-09-15T07:27:10.666000 | 2015-05-16T09:38:50 | 2015-05-16T09:38:50 | 32,516,430 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ubicollab.ubibazaar.api.resources;
import java.net.URI;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.ubicollab.ubibazaar.api.ApiProperties;
import org.ubicollab.ubibazaar.api.store.AppStore;
import org.ubicollab.ubibazaar.core.App;
import org.ubicollab.ubibazaar.core.Category;
import com.google.gson.Gson;
@Path("apps")
public class AppResource {
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response getAll() {
return Response.ok(new Gson().toJson(AppStore.getAll())).build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getById(@PathParam(value = "id") String id) {
App found = AppStore.getById(id);
// fail fast and return error if does not exist
// check for existence of the entity
if (found == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(new Gson().toJson(found)).build();
}
@GET
@Path("query")
@Produces(MediaType.APPLICATION_JSON)
public Response getForQuery(
@QueryParam(value = "category") String category,
@QueryParam(value = "platform") String platform,
@QueryParam(value = "author") String author
) {
return Response.ok(new Gson().toJson(AppStore.getAll().stream()
.filter(a -> Objects.isNull(platform)
|| a.getPlatform().getId().equals(platform))
.filter(a -> Objects.isNull(author)
|| a.getAuthor().getId().equals(author))
.filter(a -> Objects.isNull(category)
|| a.getCategory().stream().anyMatch(x -> hasAncestor(x, category)))
.collect(Collectors.toList())))
.build();
}
@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
public Response create(App app) {
// create app
App created = AppStore.create(app);
// construct URI
URI uri = URI.create(ApiProperties.API_URL + "/resources/apps/"
+ created.getId());
// return response with the newly created resource's uri
return Response.created(uri).build();
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(@PathParam(value = "id") String id, App app) {
// first make sure the id in url and in entity are the same...
if (app.getId() == null) {
// complete the missing id in app entity and continue
app.setId(id);
} else if (!app.getId().equals(id)) {
// different id in url and in entity
return Response.status(Status.BAD_REQUEST).build();
}
// fail fast and return error if does not exist
// check for existence of the entity
if (AppStore.getById(id) == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
// update
AppStore.update(app);
return Response.ok().build();
}
@DELETE
@Path("/{id}")
public Response delete(@PathParam(value = "id") String id) {
// fail fast and return error if does not exist
// check for existence of the entity
if (AppStore.getById(id) == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
AppStore.delete(id);
return Response.ok().build();
}
boolean hasAncestor(Category category, String ancestor) {
if(category.getId().equals(ancestor)) {
return true;
}
if(category.getParent() == null) {
return false;
} else {
return hasAncestor(category.getParent(), ancestor);
}
}
}
| UTF-8 | Java | 3,849 | java | AppResource.java | Java | [] | null | [] | package org.ubicollab.ubibazaar.api.resources;
import java.net.URI;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.ubicollab.ubibazaar.api.ApiProperties;
import org.ubicollab.ubibazaar.api.store.AppStore;
import org.ubicollab.ubibazaar.core.App;
import org.ubicollab.ubibazaar.core.Category;
import com.google.gson.Gson;
@Path("apps")
public class AppResource {
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response getAll() {
return Response.ok(new Gson().toJson(AppStore.getAll())).build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getById(@PathParam(value = "id") String id) {
App found = AppStore.getById(id);
// fail fast and return error if does not exist
// check for existence of the entity
if (found == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(new Gson().toJson(found)).build();
}
@GET
@Path("query")
@Produces(MediaType.APPLICATION_JSON)
public Response getForQuery(
@QueryParam(value = "category") String category,
@QueryParam(value = "platform") String platform,
@QueryParam(value = "author") String author
) {
return Response.ok(new Gson().toJson(AppStore.getAll().stream()
.filter(a -> Objects.isNull(platform)
|| a.getPlatform().getId().equals(platform))
.filter(a -> Objects.isNull(author)
|| a.getAuthor().getId().equals(author))
.filter(a -> Objects.isNull(category)
|| a.getCategory().stream().anyMatch(x -> hasAncestor(x, category)))
.collect(Collectors.toList())))
.build();
}
@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
public Response create(App app) {
// create app
App created = AppStore.create(app);
// construct URI
URI uri = URI.create(ApiProperties.API_URL + "/resources/apps/"
+ created.getId());
// return response with the newly created resource's uri
return Response.created(uri).build();
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(@PathParam(value = "id") String id, App app) {
// first make sure the id in url and in entity are the same...
if (app.getId() == null) {
// complete the missing id in app entity and continue
app.setId(id);
} else if (!app.getId().equals(id)) {
// different id in url and in entity
return Response.status(Status.BAD_REQUEST).build();
}
// fail fast and return error if does not exist
// check for existence of the entity
if (AppStore.getById(id) == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
// update
AppStore.update(app);
return Response.ok().build();
}
@DELETE
@Path("/{id}")
public Response delete(@PathParam(value = "id") String id) {
// fail fast and return error if does not exist
// check for existence of the entity
if (AppStore.getById(id) == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
AppStore.delete(id);
return Response.ok().build();
}
boolean hasAncestor(Category category, String ancestor) {
if(category.getId().equals(ancestor)) {
return true;
}
if(category.getParent() == null) {
return false;
} else {
return hasAncestor(category.getParent(), ancestor);
}
}
}
| 3,849 | 0.656274 | 0.656274 | 139 | 26.690647 | 21.524237 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.374101 | false | false | 12 |
3f9e2b84099eec5baf898f7667e9a97cc1dcaffd | 7,069,516,170,456 | 182fd527c82e1c86770296f541b716825bcc29a8 | /src/main/java/org/codenergic/theskeleton/social/SocialConnectionService.java | 4aaf212bff160108790e8f35c5009a92aeb62313 | [
"Apache-2.0"
] | permissive | codenergic/theskeleton | https://github.com/codenergic/theskeleton | 0ff32cc34a582ec9e9d953b9b550df061185bf23 | af254d6a5e9f66bdc8de4b033477fa1c033ebc9e | refs/heads/master | 2021-12-26T22:43:11.350000 | 2019-10-16T15:40:24 | 2019-10-16T15:40:24 | 89,329,118 | 6 | 5 | Apache-2.0 | false | 2021-08-02T22:19:05 | 2017-04-25T07:10:34 | 2019-11-10T16:47:42 | 2021-08-02T22:19:01 | 678 | 4 | 5 | 16 | Java | false | false | /*
* Copyright 2017 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.codenergic.theskeleton.social;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.codenergic.theskeleton.user.UserEntity;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionKey;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.NoSuchConnectionException;
import org.springframework.social.connect.NotConnectedException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
public class SocialConnectionService implements ConnectionRepository {
private ServiceProviderConnectionMapper connectionMapper = new ServiceProviderConnectionMapper();
private String userId;
private SocialConnectionRepository connectionRepository;
private ConnectionFactoryLocator connectionFactoryLocator;
private TextEncryptor textEncryptor = Encryptors.noOpText();
public SocialConnectionService(String userId, SocialConnectionRepository connectionRepository,
ConnectionFactoryLocator connectionFactoryLocator) {
this.userId = userId;
this.connectionRepository = connectionRepository;
this.connectionFactoryLocator = connectionFactoryLocator;
}
@Override
@Transactional
public void addConnection(Connection<?> connection) {
ConnectionData data = connection.createData();
int rank = connectionRepository.getRank(userId, data.getProviderId());
SocialConnectionEntity userConnection = new SocialConnectionEntity()
.setUser(new UserEntity().setId(userId))
.setProvider(data.getProviderId())
.setProviderUserId(data.getProviderUserId())
.setRank(rank)
.setDisplayName(data.getDisplayName())
.setProfileUrl(data.getProfileUrl())
.setImageUrl(data.getImageUrl())
.setAccessToken(encrypt(data.getAccessToken()))
.setSecret(encrypt(data.getSecret()))
.setRefreshToken(encrypt(data.getRefreshToken()))
.setExpireTime(data.getExpireTime());
connectionRepository.save(userConnection);
}
private String encrypt(String text) {
return text == null ? null : textEncryptor.encrypt(text);
}
@Override
public MultiValueMap<String, Connection<?>> findAllConnections() {
List<SocialConnectionEntity> socialConnections = connectionRepository.findByUserIdOrderByRankAsc(userId);
Map<String, List<Connection<?>>> connections = socialConnections.stream()
.map(connectionMapper::mapRow)
.collect(Collectors.groupingBy(connection -> connection.getKey().getProviderId()));
return new LinkedMultiValueMap<>(connections);
}
@Override
public List<Connection<?>> findConnections(String providerId) {
return connectionRepository.findByUserIdAndProviderOrderByRankAsc(userId, providerId)
.stream()
.map(connectionMapper::mapRow)
.collect(Collectors.toList());
}
@SuppressWarnings("unchecked")
@Override
public <A> List<Connection<A>> findConnections(Class<A> apiType) {
List<?> connections = findConnections(getProviderId(apiType));
return (List<Connection<A>>) connections;
}
@Override
public MultiValueMap<String, Connection<?>> findConnectionsToUsers(MultiValueMap<String, String> providerUserIds) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override
public <A> Connection<A> findPrimaryConnection(Class<A> apiType) {
String providerId = getProviderId(apiType);
return (Connection<A>) findPrimaryConnection(providerId)
.orElseThrow(() -> new NotConnectedException(providerId));
}
private Optional<? extends Connection<?>> findPrimaryConnection(String providerId) {
List<SocialConnectionEntity> socialConnections = connectionRepository.findByUserIdAndProviderAndRank(userId, providerId, 1);
return socialConnections.stream()
.map(connection -> connectionMapper.mapRow(connection))
.findFirst();
}
@Override
public Connection<?> getConnection(ConnectionKey connectionKey) {
return connectionRepository
.findByUserIdAndProviderAndProviderUserId(userId, connectionKey.getProviderId(), connectionKey.getProviderUserId())
.map(connectionMapper::mapRow)
.orElseThrow(() -> new NoSuchConnectionException(connectionKey));
}
@SuppressWarnings("unchecked")
@Override
public <A> Connection<A> getConnection(Class<A> apiType,
String providerUserId) {
String providerId = getProviderId(apiType);
return (Connection<A>) getConnection(new ConnectionKey(providerId, providerUserId));
}
@SuppressWarnings("unchecked")
@Override
public <A> Connection<A> getPrimaryConnection(Class<A> apiType) {
String providerId = getProviderId(apiType);
return (Connection<A>) findPrimaryConnection(providerId)
.orElseThrow(() -> new NotConnectedException(providerId));
}
private <A> String getProviderId(Class<A> apiType) {
return connectionFactoryLocator.getConnectionFactory(apiType).getProviderId();
}
@Override
public void removeConnection(ConnectionKey connectionKey) {
SocialConnectionEntity connection = connectionRepository
.findByUserIdAndProviderAndProviderUserId(userId, connectionKey.getProviderId(), connectionKey.getProviderUserId())
.orElseThrow(() -> new NoSuchConnectionException(connectionKey));
connectionRepository.delete(connection);
}
@Override
@Transactional
public void removeConnections(String providerId) {
List<SocialConnectionEntity> connections = connectionRepository.findByUserIdAndProvider(userId, providerId);
connectionRepository.delete(connections);
}
@Override
@Transactional
public void updateConnection(Connection<?> connection) {
ConnectionData data = connection.createData();
SocialConnectionEntity userConnection = connectionRepository
.findByUserIdAndProviderAndProviderUserId(userId, data.getProviderId(), data.getProviderUserId())
.orElseThrow(() -> new NoSuchConnectionException(connection.getKey()))
.setDisplayName(data.getDisplayName())
.setProfileUrl(data.getProfileUrl())
.setImageUrl(data.getImageUrl())
.setAccessToken(encrypt(data.getAccessToken()))
.setSecret(encrypt(data.getSecret()))
.setRefreshToken(encrypt(data.getRefreshToken()))
.setExpireTime(data.getExpireTime());
connectionRepository.save(userConnection);
}
private final class ServiceProviderConnectionMapper {
private String decrypt(String encryptedText) {
return encryptedText == null ? null : textEncryptor.decrypt(encryptedText);
}
private Long expireTime(long expireTime) {
return expireTime == 0 ? null : expireTime;
}
private ConnectionData mapConnectionData(SocialConnectionEntity connection) {
return new ConnectionData(connection.getProvider(),
connection.getProviderUserId(), connection.getDisplayName(),
connection.getProfileUrl(), connection.getImageUrl(), decrypt(connection.getAccessToken()),
decrypt(connection.getSecret()), decrypt(connection.getRefreshToken()),
expireTime(connection.getExpireTime()));
}
Connection<?> mapRow(SocialConnectionEntity connection) {
ConnectionData connectionData = mapConnectionData(connection);
ConnectionFactory<?> connectionFactory = connectionFactoryLocator
.getConnectionFactory(connectionData.getProviderId());
return connectionFactory.createConnection(connectionData);
}
}
}
| UTF-8 | Java | 8,250 | java | SocialConnectionService.java | Java | [] | null | [] | /*
* Copyright 2017 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.codenergic.theskeleton.social;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.codenergic.theskeleton.user.UserEntity;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionKey;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.NoSuchConnectionException;
import org.springframework.social.connect.NotConnectedException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
public class SocialConnectionService implements ConnectionRepository {
private ServiceProviderConnectionMapper connectionMapper = new ServiceProviderConnectionMapper();
private String userId;
private SocialConnectionRepository connectionRepository;
private ConnectionFactoryLocator connectionFactoryLocator;
private TextEncryptor textEncryptor = Encryptors.noOpText();
public SocialConnectionService(String userId, SocialConnectionRepository connectionRepository,
ConnectionFactoryLocator connectionFactoryLocator) {
this.userId = userId;
this.connectionRepository = connectionRepository;
this.connectionFactoryLocator = connectionFactoryLocator;
}
@Override
@Transactional
public void addConnection(Connection<?> connection) {
ConnectionData data = connection.createData();
int rank = connectionRepository.getRank(userId, data.getProviderId());
SocialConnectionEntity userConnection = new SocialConnectionEntity()
.setUser(new UserEntity().setId(userId))
.setProvider(data.getProviderId())
.setProviderUserId(data.getProviderUserId())
.setRank(rank)
.setDisplayName(data.getDisplayName())
.setProfileUrl(data.getProfileUrl())
.setImageUrl(data.getImageUrl())
.setAccessToken(encrypt(data.getAccessToken()))
.setSecret(encrypt(data.getSecret()))
.setRefreshToken(encrypt(data.getRefreshToken()))
.setExpireTime(data.getExpireTime());
connectionRepository.save(userConnection);
}
private String encrypt(String text) {
return text == null ? null : textEncryptor.encrypt(text);
}
@Override
public MultiValueMap<String, Connection<?>> findAllConnections() {
List<SocialConnectionEntity> socialConnections = connectionRepository.findByUserIdOrderByRankAsc(userId);
Map<String, List<Connection<?>>> connections = socialConnections.stream()
.map(connectionMapper::mapRow)
.collect(Collectors.groupingBy(connection -> connection.getKey().getProviderId()));
return new LinkedMultiValueMap<>(connections);
}
@Override
public List<Connection<?>> findConnections(String providerId) {
return connectionRepository.findByUserIdAndProviderOrderByRankAsc(userId, providerId)
.stream()
.map(connectionMapper::mapRow)
.collect(Collectors.toList());
}
@SuppressWarnings("unchecked")
@Override
public <A> List<Connection<A>> findConnections(Class<A> apiType) {
List<?> connections = findConnections(getProviderId(apiType));
return (List<Connection<A>>) connections;
}
@Override
public MultiValueMap<String, Connection<?>> findConnectionsToUsers(MultiValueMap<String, String> providerUserIds) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override
public <A> Connection<A> findPrimaryConnection(Class<A> apiType) {
String providerId = getProviderId(apiType);
return (Connection<A>) findPrimaryConnection(providerId)
.orElseThrow(() -> new NotConnectedException(providerId));
}
private Optional<? extends Connection<?>> findPrimaryConnection(String providerId) {
List<SocialConnectionEntity> socialConnections = connectionRepository.findByUserIdAndProviderAndRank(userId, providerId, 1);
return socialConnections.stream()
.map(connection -> connectionMapper.mapRow(connection))
.findFirst();
}
@Override
public Connection<?> getConnection(ConnectionKey connectionKey) {
return connectionRepository
.findByUserIdAndProviderAndProviderUserId(userId, connectionKey.getProviderId(), connectionKey.getProviderUserId())
.map(connectionMapper::mapRow)
.orElseThrow(() -> new NoSuchConnectionException(connectionKey));
}
@SuppressWarnings("unchecked")
@Override
public <A> Connection<A> getConnection(Class<A> apiType,
String providerUserId) {
String providerId = getProviderId(apiType);
return (Connection<A>) getConnection(new ConnectionKey(providerId, providerUserId));
}
@SuppressWarnings("unchecked")
@Override
public <A> Connection<A> getPrimaryConnection(Class<A> apiType) {
String providerId = getProviderId(apiType);
return (Connection<A>) findPrimaryConnection(providerId)
.orElseThrow(() -> new NotConnectedException(providerId));
}
private <A> String getProviderId(Class<A> apiType) {
return connectionFactoryLocator.getConnectionFactory(apiType).getProviderId();
}
@Override
public void removeConnection(ConnectionKey connectionKey) {
SocialConnectionEntity connection = connectionRepository
.findByUserIdAndProviderAndProviderUserId(userId, connectionKey.getProviderId(), connectionKey.getProviderUserId())
.orElseThrow(() -> new NoSuchConnectionException(connectionKey));
connectionRepository.delete(connection);
}
@Override
@Transactional
public void removeConnections(String providerId) {
List<SocialConnectionEntity> connections = connectionRepository.findByUserIdAndProvider(userId, providerId);
connectionRepository.delete(connections);
}
@Override
@Transactional
public void updateConnection(Connection<?> connection) {
ConnectionData data = connection.createData();
SocialConnectionEntity userConnection = connectionRepository
.findByUserIdAndProviderAndProviderUserId(userId, data.getProviderId(), data.getProviderUserId())
.orElseThrow(() -> new NoSuchConnectionException(connection.getKey()))
.setDisplayName(data.getDisplayName())
.setProfileUrl(data.getProfileUrl())
.setImageUrl(data.getImageUrl())
.setAccessToken(encrypt(data.getAccessToken()))
.setSecret(encrypt(data.getSecret()))
.setRefreshToken(encrypt(data.getRefreshToken()))
.setExpireTime(data.getExpireTime());
connectionRepository.save(userConnection);
}
private final class ServiceProviderConnectionMapper {
private String decrypt(String encryptedText) {
return encryptedText == null ? null : textEncryptor.decrypt(encryptedText);
}
private Long expireTime(long expireTime) {
return expireTime == 0 ? null : expireTime;
}
private ConnectionData mapConnectionData(SocialConnectionEntity connection) {
return new ConnectionData(connection.getProvider(),
connection.getProviderUserId(), connection.getDisplayName(),
connection.getProfileUrl(), connection.getImageUrl(), decrypt(connection.getAccessToken()),
decrypt(connection.getSecret()), decrypt(connection.getRefreshToken()),
expireTime(connection.getExpireTime()));
}
Connection<?> mapRow(SocialConnectionEntity connection) {
ConnectionData connectionData = mapConnectionData(connection);
ConnectionFactory<?> connectionFactory = connectionFactoryLocator
.getConnectionFactory(connectionData.getProviderId());
return connectionFactory.createConnection(connectionData);
}
}
}
| 8,250 | 0.793333 | 0.792121 | 205 | 39.243904 | 30.431995 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.892683 | false | false | 12 |
49821ab84c3582b1ed8fcc5a01166b57c053778e | 35,768,487,659,420 | 5204c3022d95fa8438fd92e02ec6bc473114ebc1 | /news-front/src/main/java/io/md/news/config/ApplicationConfig.java | 67ffad2808b76bd0d0e9b5b45de238398c29a3a3 | [] | no_license | michaeldimchuk/news | https://github.com/michaeldimchuk/news | a5eeccfc8b829965042841a8a656a62465ca6cab | 1ff0dd7b846588845bf1086b06f8d039d8a635a4 | refs/heads/master | 2021-01-23T20:38:28.204000 | 2019-01-09T06:42:45 | 2019-01-09T06:42:45 | 102,869,033 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.md.news.config;
import io.md.news.controller.NewsController;
import io.md.news.controller.PagedNewsController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.concurrent.TimeUnit;
@Import(MockApplicationConfig.class)
@Configuration
public class ApplicationConfig extends WebMvcConfigurerAdapter {
@Bean
public NewsController newsController() {
return new NewsController();
}
@Bean
public PagedNewsController pagedNewsController() {
return new PagedNewsController();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**")
.addResourceLocations("classpath:/static/css/")
.setCacheControl(CacheControl.maxAge(10, TimeUnit.DAYS));
registry.addResourceHandler("/images/**")
.addResourceLocations("classpath:/static/images/")
.setCacheControl(CacheControl.maxAge(10, TimeUnit.DAYS));
}
} | UTF-8 | Java | 1,340 | java | ApplicationConfig.java | Java | [] | null | [] | package io.md.news.config;
import io.md.news.controller.NewsController;
import io.md.news.controller.PagedNewsController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.concurrent.TimeUnit;
@Import(MockApplicationConfig.class)
@Configuration
public class ApplicationConfig extends WebMvcConfigurerAdapter {
@Bean
public NewsController newsController() {
return new NewsController();
}
@Bean
public PagedNewsController pagedNewsController() {
return new PagedNewsController();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**")
.addResourceLocations("classpath:/static/css/")
.setCacheControl(CacheControl.maxAge(10, TimeUnit.DAYS));
registry.addResourceHandler("/images/**")
.addResourceLocations("classpath:/static/images/")
.setCacheControl(CacheControl.maxAge(10, TimeUnit.DAYS));
}
} | 1,340 | 0.752239 | 0.749254 | 37 | 35.243244 | 26.986889 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.432432 | false | false | 12 |
0fdd59a8a4ef9304ca58a10c40d6e7957e7026a4 | 37,941,741,093,783 | 1703a505358b2a126332fb36f92f0d757b65a0d3 | /BeautyParlor1/src/com/henglianmobile/beautyparlor/ui/activity/MeiYouQuanDetailActivity.java | fdc7a731a09bbaff8fa91db6c05f36a9fb8ea9fd | [] | no_license | RyanTech/meirongyuan | https://github.com/RyanTech/meirongyuan | 283a89272014dba837ac7f28cdb36b624c391aeb | 8663939f285b8b27bab7633958ad8d6fb10dd6ba | refs/heads/master | 2018-05-29T23:09:19.440000 | 2015-01-25T11:31:22 | 2015-01-25T11:31:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.henglianmobile.beautyparlor.ui.activity;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.tencent.qzone.QZone.ShareParams;
import com.google.gson.reflect.TypeToken;
import com.henglianmobile.beautyparlor.R;
import com.henglianmobile.beautyparlor.activity.BaseActivity;
import com.henglianmobile.beautyparlor.adapter.GridViewAdapter;
import com.henglianmobile.beautyparlor.adapter.MeiYouQuanPinglunAdapter;
import com.henglianmobile.beautyparlor.app.TApplication;
import com.henglianmobile.beautyparlor.entity.MeiYouQuanCommentListObject;
import com.henglianmobile.beautyparlor.entity.MeiYouQuanDetailObject;
import com.henglianmobile.beautyparlor.entity.beautyparlor.GuangGaoDetailObject;
import com.henglianmobile.beautyparlor.entity.beautyparlor.ProposalDetailObject;
import com.henglianmobile.beautyparlor.ui.wxapi.ShareSDKUtil;
import com.henglianmobile.beautyparlor.util.Const;
import com.henglianmobile.beautyparlor.util.Constant;
import com.henglianmobile.beautyparlor.util.HttpUtil;
import com.henglianmobile.beautyparlor.util.ListViewUtil;
import com.henglianmobile.beautyparlor.util.LogUtil;
import com.henglianmobile.beautyparlor.util.MyAnimateFirstDisplayListener;
import com.henglianmobile.beautyparlor.util.Tools;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
@EActivity(R.layout.activity_meiyouquan_detail)
public class MeiYouQuanDetailActivity extends BaseActivity implements
OnClickListener {
@ViewById
protected TextView tv_meiyou_nick, tv_meiyou_topic, tv_publish_time,
tv_pinglun_count, tv_zan_count;
@ViewById
protected ImageView iv_meiyou_photo, iv_meiyou_pic, iv_meiyou_pic1,
iv_meiyou_pic2, iv_pinglun;
@ViewById
protected GridView gv_meiyou_pics;
@ViewById
protected LinearLayout ll_meiyou_pics, ll_submit_commit, ll_bottom;
@ViewById
protected ListView lv_pinglun;
@ViewById
protected EditText et_comment;
private AlertDialog.Builder builder;
private AlertDialog dialog;
private LinearLayout ll_share_weixin, ll_share_qq;
private List<String> pics;
private String topicPics;
@Extra
protected int tId, tType;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
String text = ShareSDKUtil.actionToString(msg.arg2);
switch (msg.arg1) {
case 0:
Tools.showMsg(MeiYouQuanDetailActivity.this, "分享成功");
dialog.dismiss();
break;
case 1:
Tools.showMsg(MeiYouQuanDetailActivity.this, "分享失败");
dialog.dismiss();
break;
case 2:
Tools.showMsg(MeiYouQuanDetailActivity.this, "取消分享");
dialog.dismiss();
break;
case 3:
Tools.showMsg(MeiYouQuanDetailActivity.this, "分享出现错误");
dialog.dismiss();
break;
case 101: {
// 成功
Platform plat = (Platform) msg.obj;
text = plat.getName() + " completed at " + text;
}
break;
case 102: {
// 失败
if ("WechatClientNotExistException".equals(msg.obj.getClass()
.getSimpleName())) {
text = MeiYouQuanDetailActivity.this.getString(
R.string.wechat_client_inavailable);
} else if ("WechatTimelineNotSupportedException".equals(msg.obj
.getClass().getSimpleName())) {
text = MeiYouQuanDetailActivity.this.getString(
R.string.wechat_client_inavailable);
} else {
text = MeiYouQuanDetailActivity.this.getString(R.string.share_failed);
}
}
break;
case 103: {
// 取消
Platform plat = (Platform) msg.obj;
text = plat.getName() + " canceled at " + text;
}
break;
default:
break;
}
};
};
@AfterViews
protected void getData() {
if (tType == Constant.TIE_YUANSHENG) {
String url = Const.GETMEIYOUQUANDETAILLISTURL + tId;
getDataHttp(url);
} else if (tType == Constant.TIE_GUANGGAO) {
String url = Const.GETMYGUANGGAODETAILURL + tId;
getDataHttpGuangGao(url);
} else if (tType == Constant.TIE_FANGAN) {
String url = Const.GETPROPOSALREQUESTDETAIL + tId;
getDataHttpFangAn(url);
}
String url1 = Const.GETMEIYOUQUANDETAILCOMMENTURL + tId + "&type="
+ tType;
getCommentHttp(url1);
}
private void getDataHttpGuangGao(String url) {
LogUtil.i("url", "MeiYouQuanDetailActivity--url=" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
if (statusCode == 200) {
LogUtil.i("hck", responseString);
Type type = new TypeToken<List<GuangGaoDetailObject>>() {
}.getType();
List<GuangGaoDetailObject> guangGaoDetailObjects = TApplication.gson
.fromJson(responseString, type);
if (guangGaoDetailObjects != null
&& guangGaoDetailObjects.size() != 0) {
GuangGaoDetailObject guangGaoDetailObject = guangGaoDetailObjects
.get(0);
tv_meiyou_nick.setText(guangGaoDetailObject
.getDcNickName());
tv_meiyou_topic.setText(guangGaoDetailObject
.getDcContent());
tv_publish_time.setText(Tools
.DateStrToDateStr(guangGaoDetailObject
.getDtAddTime()));
tv_zan_count.setText(guangGaoDetailObject
.getLikeCount() + "");
// 获取图片
String photoPic = guangGaoDetailObject.getDcHeadImg()
.trim();
if (photoPic != null && !TextUtils.isEmpty(photoPic)) {
ImageLoader.getInstance().displayImage(photoPic,
iv_meiyou_photo, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
}
String topicPics = guangGaoDetailObject.getDcIpath()
.trim();
showPics(topicPics);
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, Tools.HTTP_ERROR);
}
});
}
private void getDataHttpFangAn(String url) {
LogUtil.i("url", "MeiYouQuanDetailActivity--url=" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
if (statusCode == 200) {
LogUtil.i("hck", responseString);
Type type = new TypeToken<List<ProposalDetailObject>>() {
}.getType();
List<ProposalDetailObject> proposalDetailObjects = TApplication.gson
.fromJson(responseString, type);
if (proposalDetailObjects != null
&& proposalDetailObjects.size() != 0) {
ProposalDetailObject proposalDetailObject = proposalDetailObjects
.get(0);
tv_meiyou_nick.setText(proposalDetailObject
.getToNickName());
String topicContent = proposalDetailObject
.getDcContent();
tv_meiyou_topic.setText(topicContent);
tv_publish_time.setText(Tools
.DateStrToDateStr(proposalDetailObject
.getDtAddTime()));
tv_zan_count.setText(proposalDetailObject
.getLikeCount() + "");
// 获取图片
String photoPic = proposalDetailObject.getToHeadImg();
if (photoPic != null && !TextUtils.isEmpty(photoPic)) {
ImageLoader.getInstance().displayImage(photoPic,
iv_meiyou_photo, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
}
String topicPics = proposalDetailObject.getDcIpath()
.trim();
showPics(topicPics);
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, Tools.HTTP_ERROR);
}
});
}
private void getDataHttp(String url) {
LogUtil.i("url", "MeiYouQuanDetailActivity--url=" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
if (statusCode == 200) {
LogUtil.i("hck", responseString);
Type type = new TypeToken<List<MeiYouQuanDetailObject>>() {
}.getType();
List<MeiYouQuanDetailObject> meiYouQuanDetailObjects = TApplication.gson
.fromJson(responseString, type);
if (meiYouQuanDetailObjects != null
&& meiYouQuanDetailObjects.size() != 0) {
MeiYouQuanDetailObject meiYouQuanDetailObject = meiYouQuanDetailObjects
.get(0);
tv_meiyou_nick.setText(meiYouQuanDetailObject
.getDcNickName());
tv_meiyou_topic.setText(meiYouQuanDetailObject
.getDcTopicContent());
tv_publish_time.setText(Tools
.DateStrToDateStr(meiYouQuanDetailObject
.getDtAddTime()));
tv_zan_count.setText(meiYouQuanDetailObject
.getLikeCount() + "");
// 获取图片
String photoPic = meiYouQuanDetailObject.getDcHeadImg()
.trim();
if (photoPic != null && !TextUtils.isEmpty(photoPic)) {
ImageLoader.getInstance().displayImage(photoPic,
iv_meiyou_photo, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
}
topicPics = meiYouQuanDetailObject.getDcIpath().trim();
showPics(topicPics);
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, Tools.HTTP_ERROR);
}
});
}
@Click
protected void btn_back() {
this.finish();
}
@Click
protected void iv_comment_bottom() {
if (ll_submit_commit.getVisibility() == View.GONE) {
ll_submit_commit.setVisibility(View.VISIBLE);
ll_bottom.setVisibility(View.GONE);
} else {
ll_submit_commit.setVisibility(View.GONE);
}
}
@Click
protected void iv_zan_bottom() {
String url = Const.CLICKZANURL + "userId=" + TApplication.user.getUid()
+ "&type=" + tType + "&dnOid=" + tId;
zanHttp(url);
}
/**
* 分享
*/
@Click
protected void iv_share_bottom() {
builder = new AlertDialog.Builder(this);
View view = LayoutInflater.from(this).inflate(R.layout.dialog_share,
null);
// iv_share_weixin,iv_share_qq
ll_share_weixin = (LinearLayout) view
.findViewById(R.id.ll_share_weixin);
ll_share_qq = (LinearLayout) view.findViewById(R.id.ll_share_qq);
ll_share_weixin.setOnClickListener(this);
ll_share_qq.setOnClickListener(this);
builder.setView(view);
dialog = builder.create();
dialog.show();
}
@Override
public void onClick(View v) {
String content = tv_meiyou_topic.getText().toString();
LogUtil.i("info", "qq分享topicContent=" + content);
ShareParams sp = new ShareParams();
sp.setTitle("");
sp.setTitleUrl("http://www.henglianmobile.com"); // 标题的超链接
sp.setText(content);
if (pics.size() != 0) {
sp.setImageUrl(pics.get(0));
// sp.setImageUrl("http://f.hiphotos.baidu.com/image/pic/item/b219ebc4b74543a977adc9d01d178a82b9011473.jpg");
}
sp.setSite("要你好看");
sp.setSiteUrl("http://www.henglianmobile.com");
sp.setVenueName("美容院");
sp.setVenueDescription("This is a beautiful place!");
switch (v.getId()) {
case R.id.ll_share_weixin:
LogUtil.i("info", "微信分享");
shareWeiXin(sp);
break;
case R.id.ll_share_qq:
shareQQ(sp);
break;
default:
break;
}
dialog.dismiss();
}
private void shareWeiXin(ShareParams sp) {
// String content = tv_meiyou_topic.getText().toString();
// ShareParams sp = new ShareParams();
// sp.setTitle("");
// sp.setText(content);
// sp.setShareType(Platform.SHARE_IMAGE);
// sp.setImageUrl("http://www.wyl.cc/wp-content/uploads/2014/02/10060381306b675f5c5.jpg");
// Platform plat = ShareSDK.getPlatform (MeiYouQuanDetailActivity.this, WechatMoments.NAME);
Platform plat = ShareSDK.getPlatform("WechatMoments");
plat.setPlatformActionListener(paListener2);
plat.share(sp);
}
private void shareQQ(ShareParams sp) {
Platform qzone = ShareSDK.getPlatform(QZone.NAME);
qzone.setPlatformActionListener(paListener); // 设置分享事件回调
// 执行图文分享
qzone.share(sp);
}
private void zanHttp(String url) {
LogUtil.i("url", "点赞----url==" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, String responseString) {
if (arg0 == 200) {
LogUtil.i("hck", responseString);
try {
JSONObject jsonObject = new JSONObject(responseString);
int response = jsonObject.getInt("response");
if (response == 0) {
Tools.showMsg(MeiYouQuanDetailActivity.this,
"点赞失败!");
} else if (response > 0) {
Tools.showMsg(MeiYouQuanDetailActivity.this, "赞!!!");
getData();
} else if (response == -2) {
Tools.showMsg(MeiYouQuanDetailActivity.this,
"您已赞!谢谢!");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, HTTP_ERROR);
}
});
}
@Click
protected void btn_send() {// 发送评论
String comment = et_comment.getText().toString().trim();
if (TextUtils.isEmpty(comment)) {
Tools.showMsg(this, "发送内容不能为空!");
return;
}
String url = Const.ADDMEIYOUQUANCOMMENTURL + "tid=" + tId + "&type="
+ tType + "&uid=" + TApplication.user.getUid() + "&fname="
+ TApplication.user.getNickname() + "&content=" + comment;
sendHttpGet(url);
}
private void sendHttpGet(String url) {
LogUtil.i("url", "发送评论----url==" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, String responseString) {
if (arg0 == 200) {
LogUtil.i("hck", responseString);
try {
JSONObject jsonObject = new JSONObject(responseString);
int response = jsonObject.getInt("response");
if (response == 0) {
Tools.showMsg(MeiYouQuanDetailActivity.this,
"发送评论失败!");
} else if (response > 0) {
Tools.showMsg(MeiYouQuanDetailActivity.this,
"评论发送成功!");
ll_submit_commit.setVisibility(View.GONE);
ll_bottom.setVisibility(View.VISIBLE);
et_comment.setText("");
String url = Const.GETMEIYOUQUANDETAILCOMMENTURL
+ tId + "&type=" + tType;
getCommentHttp(url);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, HTTP_ERROR);
}
});
}
private void getCommentHttp(String url) {
LogUtil.i("url", "获取评论----url==" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, String responseString) {
if (arg0 == 200) {
LogUtil.i("hck", responseString);
Type type = new TypeToken<List<MeiYouQuanCommentListObject>>() {
}.getType();
List<MeiYouQuanCommentListObject> meiYouQuanCommentListObjects = TApplication.gson
.fromJson(responseString, type);
if (meiYouQuanCommentListObjects != null) {
MeiYouQuanPinglunAdapter adapter = new MeiYouQuanPinglunAdapter(
MeiYouQuanDetailActivity.this,
meiYouQuanCommentListObjects);
lv_pinglun.setAdapter(adapter);
ListViewUtil
.setListViewHeightBasedOnChildren(lv_pinglun);
tv_pinglun_count.setText(meiYouQuanCommentListObjects
.size() + "");
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, HTTP_ERROR);
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // 按下的如果是BACK,同时没有重复
if (ll_submit_commit.getVisibility() == View.VISIBLE) {
ll_submit_commit.setVisibility(View.GONE);
ll_bottom.setVisibility(View.VISIBLE);
} else {
MeiYouQuanDetailActivity.this.finish();
}
return true;
}
return false;
}
private void showPics(String topicPics) {
LogUtil.i("info", "topicPics====" + topicPics);
pics = new ArrayList<String>();
if (!"".equals(topicPics)) {
String[] topics = topicPics.split(",");
for (int i = 0; i < topics.length; i++) {
pics.add(topics[i]);
}
if (topics.length == 1) {
iv_meiyou_pic.setVisibility(View.VISIBLE);
ll_meiyou_pics.setVisibility(View.GONE);
gv_meiyou_pics.setVisibility(View.GONE);
String picUrlone = topics[0];
ImageLoader.getInstance().displayImage(picUrlone,
iv_meiyou_pic, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
iv_meiyou_pic.setTag(pics);
iv_meiyou_pic.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ShowPicturesActivity_
.intent(MeiYouQuanDetailActivity.this)
.extra("position", 0)
.stringArrayListExtra("pics",
(ArrayList<String>) pics).start();
}
});
} else if (topics.length == 2) {
ll_meiyou_pics.setVisibility(View.VISIBLE);
iv_meiyou_pic.setVisibility(View.GONE);
gv_meiyou_pics.setVisibility(View.GONE);
ImageLoader.getInstance().displayImage(topics[0],
iv_meiyou_pic1, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
ImageLoader.getInstance().displayImage(topics[1],
iv_meiyou_pic2, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
iv_meiyou_pic1.setTag(pics);
iv_meiyou_pic1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ShowPicturesActivity_
.intent(MeiYouQuanDetailActivity.this)
.extra("position", 0)
.stringArrayListExtra("pics",
(ArrayList<String>) pics).start();
}
});
iv_meiyou_pic2.setTag(pics);
iv_meiyou_pic2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ShowPicturesActivity_
.intent(MeiYouQuanDetailActivity.this)
.extra("position", 1)
.stringArrayListExtra("pics",
(ArrayList<String>) pics).start();
}
});
} else if (topics.length >= 3) {
gv_meiyou_pics.setVisibility(View.VISIBLE);
iv_meiyou_pic.setVisibility(View.GONE);
ll_meiyou_pics.setVisibility(View.GONE);
GridViewAdapter adapter = new GridViewAdapter(
MeiYouQuanDetailActivity.this, pics);
gv_meiyou_pics.setAdapter(adapter);
gv_meiyou_pics.setTag(pics);
gv_meiyou_pics
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
ShowPicturesActivity_
.intent(MeiYouQuanDetailActivity.this)
.extra("position", position)
.stringArrayListExtra("pics",
(ArrayList<String>) pics)
.start();
}
});
}
} else {
gv_meiyou_pics.setVisibility(View.GONE);
iv_meiyou_pic.setVisibility(View.GONE);
ll_meiyou_pics.setVisibility(View.GONE);
}
}
private PlatformActionListener paListener = new PlatformActionListener() {
@Override
public void onError(Platform arg0, int arg1, Throwable arg2) {
LogUtil.i("info", "--------");
Message msg = new Message();
msg.arg1 = 3;
handler.sendMessage(msg);
}
@Override
public void onComplete(Platform arg0, int arg1,
HashMap<String, Object> arg2) {
LogUtil.i("info", "-------arg2-" + arg2.toString());
Message msg = new Message();
if (arg2.containsKey("ret")) {
msg.arg1 = 1;
handler.sendMessage(msg);
} else {
msg.arg1 = 0;
handler.sendMessage(msg);
}
}
@Override
public void onCancel(Platform arg0, int arg1) {
LogUtil.i("info", "======");
Message msg = new Message();
msg.arg1 = 2;
handler.sendMessage(msg);
}
};
private PlatformActionListener paListener2 = new PlatformActionListener() {
public void onComplete(Platform plat, int action,
HashMap<String, Object> res) {
Message msg = new Message();
msg.arg1 = 101;
msg.arg2 = action;
msg.obj = plat;
handler.sendMessage(msg);
}
public void onCancel(Platform plat, int action) {
Message msg = new Message();
msg.arg1 = 103;
msg.arg2 = action;
msg.obj = plat;
handler.sendMessage(msg);
}
public void onError(Platform plat, int action, Throwable t) {
t.printStackTrace();
Message msg = new Message();
msg.arg1 = 102;
msg.arg2 = action;
msg.obj = t;
handler.sendMessage(msg);
}
};
}
| GB18030 | Java | 21,766 | java | MeiYouQuanDetailActivity.java | Java | [] | null | [] | package com.henglianmobile.beautyparlor.ui.activity;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.tencent.qzone.QZone.ShareParams;
import com.google.gson.reflect.TypeToken;
import com.henglianmobile.beautyparlor.R;
import com.henglianmobile.beautyparlor.activity.BaseActivity;
import com.henglianmobile.beautyparlor.adapter.GridViewAdapter;
import com.henglianmobile.beautyparlor.adapter.MeiYouQuanPinglunAdapter;
import com.henglianmobile.beautyparlor.app.TApplication;
import com.henglianmobile.beautyparlor.entity.MeiYouQuanCommentListObject;
import com.henglianmobile.beautyparlor.entity.MeiYouQuanDetailObject;
import com.henglianmobile.beautyparlor.entity.beautyparlor.GuangGaoDetailObject;
import com.henglianmobile.beautyparlor.entity.beautyparlor.ProposalDetailObject;
import com.henglianmobile.beautyparlor.ui.wxapi.ShareSDKUtil;
import com.henglianmobile.beautyparlor.util.Const;
import com.henglianmobile.beautyparlor.util.Constant;
import com.henglianmobile.beautyparlor.util.HttpUtil;
import com.henglianmobile.beautyparlor.util.ListViewUtil;
import com.henglianmobile.beautyparlor.util.LogUtil;
import com.henglianmobile.beautyparlor.util.MyAnimateFirstDisplayListener;
import com.henglianmobile.beautyparlor.util.Tools;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
@EActivity(R.layout.activity_meiyouquan_detail)
public class MeiYouQuanDetailActivity extends BaseActivity implements
OnClickListener {
@ViewById
protected TextView tv_meiyou_nick, tv_meiyou_topic, tv_publish_time,
tv_pinglun_count, tv_zan_count;
@ViewById
protected ImageView iv_meiyou_photo, iv_meiyou_pic, iv_meiyou_pic1,
iv_meiyou_pic2, iv_pinglun;
@ViewById
protected GridView gv_meiyou_pics;
@ViewById
protected LinearLayout ll_meiyou_pics, ll_submit_commit, ll_bottom;
@ViewById
protected ListView lv_pinglun;
@ViewById
protected EditText et_comment;
private AlertDialog.Builder builder;
private AlertDialog dialog;
private LinearLayout ll_share_weixin, ll_share_qq;
private List<String> pics;
private String topicPics;
@Extra
protected int tId, tType;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
String text = ShareSDKUtil.actionToString(msg.arg2);
switch (msg.arg1) {
case 0:
Tools.showMsg(MeiYouQuanDetailActivity.this, "分享成功");
dialog.dismiss();
break;
case 1:
Tools.showMsg(MeiYouQuanDetailActivity.this, "分享失败");
dialog.dismiss();
break;
case 2:
Tools.showMsg(MeiYouQuanDetailActivity.this, "取消分享");
dialog.dismiss();
break;
case 3:
Tools.showMsg(MeiYouQuanDetailActivity.this, "分享出现错误");
dialog.dismiss();
break;
case 101: {
// 成功
Platform plat = (Platform) msg.obj;
text = plat.getName() + " completed at " + text;
}
break;
case 102: {
// 失败
if ("WechatClientNotExistException".equals(msg.obj.getClass()
.getSimpleName())) {
text = MeiYouQuanDetailActivity.this.getString(
R.string.wechat_client_inavailable);
} else if ("WechatTimelineNotSupportedException".equals(msg.obj
.getClass().getSimpleName())) {
text = MeiYouQuanDetailActivity.this.getString(
R.string.wechat_client_inavailable);
} else {
text = MeiYouQuanDetailActivity.this.getString(R.string.share_failed);
}
}
break;
case 103: {
// 取消
Platform plat = (Platform) msg.obj;
text = plat.getName() + " canceled at " + text;
}
break;
default:
break;
}
};
};
@AfterViews
protected void getData() {
if (tType == Constant.TIE_YUANSHENG) {
String url = Const.GETMEIYOUQUANDETAILLISTURL + tId;
getDataHttp(url);
} else if (tType == Constant.TIE_GUANGGAO) {
String url = Const.GETMYGUANGGAODETAILURL + tId;
getDataHttpGuangGao(url);
} else if (tType == Constant.TIE_FANGAN) {
String url = Const.GETPROPOSALREQUESTDETAIL + tId;
getDataHttpFangAn(url);
}
String url1 = Const.GETMEIYOUQUANDETAILCOMMENTURL + tId + "&type="
+ tType;
getCommentHttp(url1);
}
private void getDataHttpGuangGao(String url) {
LogUtil.i("url", "MeiYouQuanDetailActivity--url=" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
if (statusCode == 200) {
LogUtil.i("hck", responseString);
Type type = new TypeToken<List<GuangGaoDetailObject>>() {
}.getType();
List<GuangGaoDetailObject> guangGaoDetailObjects = TApplication.gson
.fromJson(responseString, type);
if (guangGaoDetailObjects != null
&& guangGaoDetailObjects.size() != 0) {
GuangGaoDetailObject guangGaoDetailObject = guangGaoDetailObjects
.get(0);
tv_meiyou_nick.setText(guangGaoDetailObject
.getDcNickName());
tv_meiyou_topic.setText(guangGaoDetailObject
.getDcContent());
tv_publish_time.setText(Tools
.DateStrToDateStr(guangGaoDetailObject
.getDtAddTime()));
tv_zan_count.setText(guangGaoDetailObject
.getLikeCount() + "");
// 获取图片
String photoPic = guangGaoDetailObject.getDcHeadImg()
.trim();
if (photoPic != null && !TextUtils.isEmpty(photoPic)) {
ImageLoader.getInstance().displayImage(photoPic,
iv_meiyou_photo, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
}
String topicPics = guangGaoDetailObject.getDcIpath()
.trim();
showPics(topicPics);
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, Tools.HTTP_ERROR);
}
});
}
private void getDataHttpFangAn(String url) {
LogUtil.i("url", "MeiYouQuanDetailActivity--url=" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
if (statusCode == 200) {
LogUtil.i("hck", responseString);
Type type = new TypeToken<List<ProposalDetailObject>>() {
}.getType();
List<ProposalDetailObject> proposalDetailObjects = TApplication.gson
.fromJson(responseString, type);
if (proposalDetailObjects != null
&& proposalDetailObjects.size() != 0) {
ProposalDetailObject proposalDetailObject = proposalDetailObjects
.get(0);
tv_meiyou_nick.setText(proposalDetailObject
.getToNickName());
String topicContent = proposalDetailObject
.getDcContent();
tv_meiyou_topic.setText(topicContent);
tv_publish_time.setText(Tools
.DateStrToDateStr(proposalDetailObject
.getDtAddTime()));
tv_zan_count.setText(proposalDetailObject
.getLikeCount() + "");
// 获取图片
String photoPic = proposalDetailObject.getToHeadImg();
if (photoPic != null && !TextUtils.isEmpty(photoPic)) {
ImageLoader.getInstance().displayImage(photoPic,
iv_meiyou_photo, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
}
String topicPics = proposalDetailObject.getDcIpath()
.trim();
showPics(topicPics);
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, Tools.HTTP_ERROR);
}
});
}
private void getDataHttp(String url) {
LogUtil.i("url", "MeiYouQuanDetailActivity--url=" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
if (statusCode == 200) {
LogUtil.i("hck", responseString);
Type type = new TypeToken<List<MeiYouQuanDetailObject>>() {
}.getType();
List<MeiYouQuanDetailObject> meiYouQuanDetailObjects = TApplication.gson
.fromJson(responseString, type);
if (meiYouQuanDetailObjects != null
&& meiYouQuanDetailObjects.size() != 0) {
MeiYouQuanDetailObject meiYouQuanDetailObject = meiYouQuanDetailObjects
.get(0);
tv_meiyou_nick.setText(meiYouQuanDetailObject
.getDcNickName());
tv_meiyou_topic.setText(meiYouQuanDetailObject
.getDcTopicContent());
tv_publish_time.setText(Tools
.DateStrToDateStr(meiYouQuanDetailObject
.getDtAddTime()));
tv_zan_count.setText(meiYouQuanDetailObject
.getLikeCount() + "");
// 获取图片
String photoPic = meiYouQuanDetailObject.getDcHeadImg()
.trim();
if (photoPic != null && !TextUtils.isEmpty(photoPic)) {
ImageLoader.getInstance().displayImage(photoPic,
iv_meiyou_photo, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
}
topicPics = meiYouQuanDetailObject.getDcIpath().trim();
showPics(topicPics);
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, Tools.HTTP_ERROR);
}
});
}
@Click
protected void btn_back() {
this.finish();
}
@Click
protected void iv_comment_bottom() {
if (ll_submit_commit.getVisibility() == View.GONE) {
ll_submit_commit.setVisibility(View.VISIBLE);
ll_bottom.setVisibility(View.GONE);
} else {
ll_submit_commit.setVisibility(View.GONE);
}
}
@Click
protected void iv_zan_bottom() {
String url = Const.CLICKZANURL + "userId=" + TApplication.user.getUid()
+ "&type=" + tType + "&dnOid=" + tId;
zanHttp(url);
}
/**
* 分享
*/
@Click
protected void iv_share_bottom() {
builder = new AlertDialog.Builder(this);
View view = LayoutInflater.from(this).inflate(R.layout.dialog_share,
null);
// iv_share_weixin,iv_share_qq
ll_share_weixin = (LinearLayout) view
.findViewById(R.id.ll_share_weixin);
ll_share_qq = (LinearLayout) view.findViewById(R.id.ll_share_qq);
ll_share_weixin.setOnClickListener(this);
ll_share_qq.setOnClickListener(this);
builder.setView(view);
dialog = builder.create();
dialog.show();
}
@Override
public void onClick(View v) {
String content = tv_meiyou_topic.getText().toString();
LogUtil.i("info", "qq分享topicContent=" + content);
ShareParams sp = new ShareParams();
sp.setTitle("");
sp.setTitleUrl("http://www.henglianmobile.com"); // 标题的超链接
sp.setText(content);
if (pics.size() != 0) {
sp.setImageUrl(pics.get(0));
// sp.setImageUrl("http://f.hiphotos.baidu.com/image/pic/item/b219ebc4b74543a977adc9d01d178a82b9011473.jpg");
}
sp.setSite("要你好看");
sp.setSiteUrl("http://www.henglianmobile.com");
sp.setVenueName("美容院");
sp.setVenueDescription("This is a beautiful place!");
switch (v.getId()) {
case R.id.ll_share_weixin:
LogUtil.i("info", "微信分享");
shareWeiXin(sp);
break;
case R.id.ll_share_qq:
shareQQ(sp);
break;
default:
break;
}
dialog.dismiss();
}
private void shareWeiXin(ShareParams sp) {
// String content = tv_meiyou_topic.getText().toString();
// ShareParams sp = new ShareParams();
// sp.setTitle("");
// sp.setText(content);
// sp.setShareType(Platform.SHARE_IMAGE);
// sp.setImageUrl("http://www.wyl.cc/wp-content/uploads/2014/02/10060381306b675f5c5.jpg");
// Platform plat = ShareSDK.getPlatform (MeiYouQuanDetailActivity.this, WechatMoments.NAME);
Platform plat = ShareSDK.getPlatform("WechatMoments");
plat.setPlatformActionListener(paListener2);
plat.share(sp);
}
private void shareQQ(ShareParams sp) {
Platform qzone = ShareSDK.getPlatform(QZone.NAME);
qzone.setPlatformActionListener(paListener); // 设置分享事件回调
// 执行图文分享
qzone.share(sp);
}
private void zanHttp(String url) {
LogUtil.i("url", "点赞----url==" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, String responseString) {
if (arg0 == 200) {
LogUtil.i("hck", responseString);
try {
JSONObject jsonObject = new JSONObject(responseString);
int response = jsonObject.getInt("response");
if (response == 0) {
Tools.showMsg(MeiYouQuanDetailActivity.this,
"点赞失败!");
} else if (response > 0) {
Tools.showMsg(MeiYouQuanDetailActivity.this, "赞!!!");
getData();
} else if (response == -2) {
Tools.showMsg(MeiYouQuanDetailActivity.this,
"您已赞!谢谢!");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, HTTP_ERROR);
}
});
}
@Click
protected void btn_send() {// 发送评论
String comment = et_comment.getText().toString().trim();
if (TextUtils.isEmpty(comment)) {
Tools.showMsg(this, "发送内容不能为空!");
return;
}
String url = Const.ADDMEIYOUQUANCOMMENTURL + "tid=" + tId + "&type="
+ tType + "&uid=" + TApplication.user.getUid() + "&fname="
+ TApplication.user.getNickname() + "&content=" + comment;
sendHttpGet(url);
}
private void sendHttpGet(String url) {
LogUtil.i("url", "发送评论----url==" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, String responseString) {
if (arg0 == 200) {
LogUtil.i("hck", responseString);
try {
JSONObject jsonObject = new JSONObject(responseString);
int response = jsonObject.getInt("response");
if (response == 0) {
Tools.showMsg(MeiYouQuanDetailActivity.this,
"发送评论失败!");
} else if (response > 0) {
Tools.showMsg(MeiYouQuanDetailActivity.this,
"评论发送成功!");
ll_submit_commit.setVisibility(View.GONE);
ll_bottom.setVisibility(View.VISIBLE);
et_comment.setText("");
String url = Const.GETMEIYOUQUANDETAILCOMMENTURL
+ tId + "&type=" + tType;
getCommentHttp(url);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, HTTP_ERROR);
}
});
}
private void getCommentHttp(String url) {
LogUtil.i("url", "获取评论----url==" + url);
HttpUtil.get(url, new TextHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, String responseString) {
if (arg0 == 200) {
LogUtil.i("hck", responseString);
Type type = new TypeToken<List<MeiYouQuanCommentListObject>>() {
}.getType();
List<MeiYouQuanCommentListObject> meiYouQuanCommentListObjects = TApplication.gson
.fromJson(responseString, type);
if (meiYouQuanCommentListObjects != null) {
MeiYouQuanPinglunAdapter adapter = new MeiYouQuanPinglunAdapter(
MeiYouQuanDetailActivity.this,
meiYouQuanCommentListObjects);
lv_pinglun.setAdapter(adapter);
ListViewUtil
.setListViewHeightBasedOnChildren(lv_pinglun);
tv_pinglun_count.setText(meiYouQuanCommentListObjects
.size() + "");
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, String arg2,
Throwable arg3) {
Tools.showMsg(MeiYouQuanDetailActivity.this, HTTP_ERROR);
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // 按下的如果是BACK,同时没有重复
if (ll_submit_commit.getVisibility() == View.VISIBLE) {
ll_submit_commit.setVisibility(View.GONE);
ll_bottom.setVisibility(View.VISIBLE);
} else {
MeiYouQuanDetailActivity.this.finish();
}
return true;
}
return false;
}
private void showPics(String topicPics) {
LogUtil.i("info", "topicPics====" + topicPics);
pics = new ArrayList<String>();
if (!"".equals(topicPics)) {
String[] topics = topicPics.split(",");
for (int i = 0; i < topics.length; i++) {
pics.add(topics[i]);
}
if (topics.length == 1) {
iv_meiyou_pic.setVisibility(View.VISIBLE);
ll_meiyou_pics.setVisibility(View.GONE);
gv_meiyou_pics.setVisibility(View.GONE);
String picUrlone = topics[0];
ImageLoader.getInstance().displayImage(picUrlone,
iv_meiyou_pic, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
iv_meiyou_pic.setTag(pics);
iv_meiyou_pic.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ShowPicturesActivity_
.intent(MeiYouQuanDetailActivity.this)
.extra("position", 0)
.stringArrayListExtra("pics",
(ArrayList<String>) pics).start();
}
});
} else if (topics.length == 2) {
ll_meiyou_pics.setVisibility(View.VISIBLE);
iv_meiyou_pic.setVisibility(View.GONE);
gv_meiyou_pics.setVisibility(View.GONE);
ImageLoader.getInstance().displayImage(topics[0],
iv_meiyou_pic1, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
ImageLoader.getInstance().displayImage(topics[1],
iv_meiyou_pic2, TApplication.optionsImage,
new MyAnimateFirstDisplayListener());
iv_meiyou_pic1.setTag(pics);
iv_meiyou_pic1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ShowPicturesActivity_
.intent(MeiYouQuanDetailActivity.this)
.extra("position", 0)
.stringArrayListExtra("pics",
(ArrayList<String>) pics).start();
}
});
iv_meiyou_pic2.setTag(pics);
iv_meiyou_pic2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ShowPicturesActivity_
.intent(MeiYouQuanDetailActivity.this)
.extra("position", 1)
.stringArrayListExtra("pics",
(ArrayList<String>) pics).start();
}
});
} else if (topics.length >= 3) {
gv_meiyou_pics.setVisibility(View.VISIBLE);
iv_meiyou_pic.setVisibility(View.GONE);
ll_meiyou_pics.setVisibility(View.GONE);
GridViewAdapter adapter = new GridViewAdapter(
MeiYouQuanDetailActivity.this, pics);
gv_meiyou_pics.setAdapter(adapter);
gv_meiyou_pics.setTag(pics);
gv_meiyou_pics
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
ShowPicturesActivity_
.intent(MeiYouQuanDetailActivity.this)
.extra("position", position)
.stringArrayListExtra("pics",
(ArrayList<String>) pics)
.start();
}
});
}
} else {
gv_meiyou_pics.setVisibility(View.GONE);
iv_meiyou_pic.setVisibility(View.GONE);
ll_meiyou_pics.setVisibility(View.GONE);
}
}
private PlatformActionListener paListener = new PlatformActionListener() {
@Override
public void onError(Platform arg0, int arg1, Throwable arg2) {
LogUtil.i("info", "--------");
Message msg = new Message();
msg.arg1 = 3;
handler.sendMessage(msg);
}
@Override
public void onComplete(Platform arg0, int arg1,
HashMap<String, Object> arg2) {
LogUtil.i("info", "-------arg2-" + arg2.toString());
Message msg = new Message();
if (arg2.containsKey("ret")) {
msg.arg1 = 1;
handler.sendMessage(msg);
} else {
msg.arg1 = 0;
handler.sendMessage(msg);
}
}
@Override
public void onCancel(Platform arg0, int arg1) {
LogUtil.i("info", "======");
Message msg = new Message();
msg.arg1 = 2;
handler.sendMessage(msg);
}
};
private PlatformActionListener paListener2 = new PlatformActionListener() {
public void onComplete(Platform plat, int action,
HashMap<String, Object> res) {
Message msg = new Message();
msg.arg1 = 101;
msg.arg2 = action;
msg.obj = plat;
handler.sendMessage(msg);
}
public void onCancel(Platform plat, int action) {
Message msg = new Message();
msg.arg1 = 103;
msg.arg2 = action;
msg.obj = plat;
handler.sendMessage(msg);
}
public void onError(Platform plat, int action, Throwable t) {
t.printStackTrace();
Message msg = new Message();
msg.arg1 = 102;
msg.arg2 = action;
msg.obj = t;
handler.sendMessage(msg);
}
};
}
| 21,766 | 0.686285 | 0.677592 | 700 | 29.728571 | 22.028891 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.915714 | false | false | 12 |
926e67e9279d6a8351af2e2d9e71e9334b991790 | 37,194,416,791,376 | 1e988bd4747e4eb2114983d38b6c40b40d98a171 | /src/modelo/ItemCompra.java | 6b23e9dc2530307b3e10022816ca4c1e05e3a064 | [] | no_license | MayconErhardt/depositoDeBebidas | https://github.com/MayconErhardt/depositoDeBebidas | 8206cb84e60f8c4e80bc8ea8fbb4e6ff52f6c3f3 | 6da38c946bb16912569e45798fc9abd3494e9526 | refs/heads/master | 2022-03-21T05:53:43.376000 | 2019-12-12T04:30:26 | 2019-12-12T04:30:26 | 227,518,207 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 modelo;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Maycon
*/
@Entity
@Table(name = "itemcompra")
@NamedQueries({
@NamedQuery(name = "ItemCompra.produtoVencimento",query= "SELECT ic FROM ItemCompra ic where ic.notificar = 'n' and ic.dataVencimento BETWEEN :dataIni and :dataFim")
})
@IdClass(ItemCompraPK.class)
public class ItemCompra implements Serializable{
@Id
@ManyToOne
@JoinColumn(name="compraCod", referencedColumnName = "compraCod")
private CompraProduto compraCod;
@Id
@ManyToOne
@JoinColumn(name="produtoCod", referencedColumnName = "produCod")
private Produto produtoCod;
@Column(name = "quantidade")
private int quantidade;
@Column(name = "valor")
private double valor;
@Column(name = "dataVencimento")
@Temporal(TemporalType.DATE)
private Date dataVencimento;
@Column(name = "notificado")
private char notificar;
public ItemCompra() {
}
public ItemCompra(CompraProduto compraCod, Produto produtoCod, int quantidade, double valor, Date dataVencimento, char notificar) {
this.compraCod = compraCod;
this.produtoCod = produtoCod;
this.quantidade = quantidade;
this.valor = valor;
this.dataVencimento = dataVencimento;
this.notificar = notificar;
}
public CompraProduto getCompraCod() {
return compraCod;
}
public void setCompraCod(CompraProduto compraCod) {
this.compraCod = compraCod;
}
public Produto getProdutoCod() {
return produtoCod;
}
public void setProdutoCod(Produto produtoCod) {
this.produtoCod = produtoCod;
}
public int getQuantidade() {
return quantidade;
}
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
public double getValor() {
return valor;
}
public void setValor(double valor) {
this.valor = valor;
}
public Date getDataVencimento() {
return dataVencimento;
}
public void setDataVencimento(Date dataVencimento) {
this.dataVencimento = dataVencimento;
}
public char getNotificar() {
return notificar;
}
public void setNotificar(char notificar) {
this.notificar = notificar;
}
@Override
public int hashCode() {
int hash = 3;
hash = 73 * hash + Objects.hashCode(this.produtoCod);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ItemCompra other = (ItemCompra) obj;
if (!Objects.equals(this.produtoCod, other.produtoCod)) {
return false;
}
return true;
}
@Override
public String toString() {
return "ItemCompra{" + "compraCod=" + compraCod + ", produtoCod=" + produtoCod + ", quantidade=" + quantidade + ", valor=" + valor + ", dataVencimento=" + dataVencimento + ", notificar=" + notificar + '}';
}
}
| UTF-8 | Java | 3,848 | java | ItemCompra.java | Java | [
{
"context": "javax.persistence.TemporalType;\n\n/**\n *\n * @author Maycon\n */\n@Entity\n@Table(name = \"itemcompra\")\n@NamedQue",
"end": 692,
"score": 0.9836580753326416,
"start": 686,
"tag": "USERNAME",
"value": "Maycon"
}
] | null | [] | /*
* 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 modelo;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author Maycon
*/
@Entity
@Table(name = "itemcompra")
@NamedQueries({
@NamedQuery(name = "ItemCompra.produtoVencimento",query= "SELECT ic FROM ItemCompra ic where ic.notificar = 'n' and ic.dataVencimento BETWEEN :dataIni and :dataFim")
})
@IdClass(ItemCompraPK.class)
public class ItemCompra implements Serializable{
@Id
@ManyToOne
@JoinColumn(name="compraCod", referencedColumnName = "compraCod")
private CompraProduto compraCod;
@Id
@ManyToOne
@JoinColumn(name="produtoCod", referencedColumnName = "produCod")
private Produto produtoCod;
@Column(name = "quantidade")
private int quantidade;
@Column(name = "valor")
private double valor;
@Column(name = "dataVencimento")
@Temporal(TemporalType.DATE)
private Date dataVencimento;
@Column(name = "notificado")
private char notificar;
public ItemCompra() {
}
public ItemCompra(CompraProduto compraCod, Produto produtoCod, int quantidade, double valor, Date dataVencimento, char notificar) {
this.compraCod = compraCod;
this.produtoCod = produtoCod;
this.quantidade = quantidade;
this.valor = valor;
this.dataVencimento = dataVencimento;
this.notificar = notificar;
}
public CompraProduto getCompraCod() {
return compraCod;
}
public void setCompraCod(CompraProduto compraCod) {
this.compraCod = compraCod;
}
public Produto getProdutoCod() {
return produtoCod;
}
public void setProdutoCod(Produto produtoCod) {
this.produtoCod = produtoCod;
}
public int getQuantidade() {
return quantidade;
}
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
public double getValor() {
return valor;
}
public void setValor(double valor) {
this.valor = valor;
}
public Date getDataVencimento() {
return dataVencimento;
}
public void setDataVencimento(Date dataVencimento) {
this.dataVencimento = dataVencimento;
}
public char getNotificar() {
return notificar;
}
public void setNotificar(char notificar) {
this.notificar = notificar;
}
@Override
public int hashCode() {
int hash = 3;
hash = 73 * hash + Objects.hashCode(this.produtoCod);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ItemCompra other = (ItemCompra) obj;
if (!Objects.equals(this.produtoCod, other.produtoCod)) {
return false;
}
return true;
}
@Override
public String toString() {
return "ItemCompra{" + "compraCod=" + compraCod + ", produtoCod=" + produtoCod + ", quantidade=" + quantidade + ", valor=" + valor + ", dataVencimento=" + dataVencimento + ", notificar=" + notificar + '}';
}
}
| 3,848 | 0.641892 | 0.641112 | 162 | 22.753086 | 27.642574 | 213 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407407 | false | false | 12 |
af9623d9dd53c53c6ea1e790910eed7a396c7c07 | 37,194,416,791,903 | 419269159a9d3a7ed3f64eaed5ceb4629f0cb604 | /src/main/java/org/simpleframework/mvc/base/helper/SimpleDatabaseHelper.java | 05b2dd57841d29b2dfde56255c04d323651ca0c3 | [] | no_license | Kenny1993/simple-base | https://github.com/Kenny1993/simple-base | 37655e0fc328c46ca7b2b039f963e55346662745 | e89d6a77c90ac5d29e2c9e3ee798c3d1fe140e8a | refs/heads/master | 2020-12-30T11:51:42.477000 | 2017-05-17T04:30:06 | 2017-05-17T04:30:06 | 91,533,682 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.simpleframework.mvc.base.helper;
import org.apache.commons.dbutils.ResultSetHandler;
import org.simpleframework.mvc.helper.DatabaseHelper;
import org.simpleframework.mvc.base.handler.SimpleBeanListResultSetHandler;
import org.simpleframework.mvc.base.handler.SimpleBeanResultSetHandler;
import java.io.*;
import java.util.List;
import java.util.Map;
/**
* 使用自定义结果集处理器
* Created by Administrator on 2017/4/20.
*/
public final class SimpleDatabaseHelper {
/**
* 查询实体列表
*/
public static <T extends Serializable> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
return DatabaseHelper.queryEntityList(entityClass, new SimpleBeanListResultSetHandler<T>(entityClass), sql, params);
}
/**
* 查询实体
*/
public static <T extends Serializable> T queryEntity(Class<T> entityClass, String sql, Object... params) {
return DatabaseHelper.queryEntity(entityClass, new SimpleBeanResultSetHandler<T>(entityClass), sql, params);
}
/**
* 查询实体列表
*/
public static <T extends Serializable> List<T> queryEntityList(Class<T> entityClass, ResultSetHandler<List<T>> handler, String sql, Object... params) {
return DatabaseHelper.queryEntityList(entityClass, handler, sql, params);
}
/**
* 记录数查询
*/
public static long queryCount(String sql, Object... params) {
return DatabaseHelper.queryCount(sql, params);
}
/**
* 查询实体
*/
public static <T extends Serializable> T queryEntity(Class<T> entityClass, ResultSetHandler<T> handler, String sql, Object... params) {
return DatabaseHelper.queryEntity(entityClass, handler, sql, params);
}
/**
* 查询 Map List
*/
public static List<Map<String, Object>> queryMapList(String sql, Object... params) {
return DatabaseHelper.queryMapList(sql, params);
}
/**
* 执行查询语句
*/
public static List<Map<String, Object>> executeQuery(String sql, Object... params) {
return DatabaseHelper.executeQuery(sql, params);
}
/**
* 执行 SQL 语句(包括update、insert、delete)
*/
public static int executeUpdate(String sql, Object... params) {
return DatabaseHelper.executeUpdate(sql, params);
}
/**
* 执行批量 SQL 语句(包括update、insert、delete)
*/
public static int[] executeBatch(String sql, Object[][] params) {
return DatabaseHelper.executeBatch(sql, params);
}
}
| UTF-8 | Java | 2,591 | java | SimpleDatabaseHelper.java | Java | [] | null | [] | package org.simpleframework.mvc.base.helper;
import org.apache.commons.dbutils.ResultSetHandler;
import org.simpleframework.mvc.helper.DatabaseHelper;
import org.simpleframework.mvc.base.handler.SimpleBeanListResultSetHandler;
import org.simpleframework.mvc.base.handler.SimpleBeanResultSetHandler;
import java.io.*;
import java.util.List;
import java.util.Map;
/**
* 使用自定义结果集处理器
* Created by Administrator on 2017/4/20.
*/
public final class SimpleDatabaseHelper {
/**
* 查询实体列表
*/
public static <T extends Serializable> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
return DatabaseHelper.queryEntityList(entityClass, new SimpleBeanListResultSetHandler<T>(entityClass), sql, params);
}
/**
* 查询实体
*/
public static <T extends Serializable> T queryEntity(Class<T> entityClass, String sql, Object... params) {
return DatabaseHelper.queryEntity(entityClass, new SimpleBeanResultSetHandler<T>(entityClass), sql, params);
}
/**
* 查询实体列表
*/
public static <T extends Serializable> List<T> queryEntityList(Class<T> entityClass, ResultSetHandler<List<T>> handler, String sql, Object... params) {
return DatabaseHelper.queryEntityList(entityClass, handler, sql, params);
}
/**
* 记录数查询
*/
public static long queryCount(String sql, Object... params) {
return DatabaseHelper.queryCount(sql, params);
}
/**
* 查询实体
*/
public static <T extends Serializable> T queryEntity(Class<T> entityClass, ResultSetHandler<T> handler, String sql, Object... params) {
return DatabaseHelper.queryEntity(entityClass, handler, sql, params);
}
/**
* 查询 Map List
*/
public static List<Map<String, Object>> queryMapList(String sql, Object... params) {
return DatabaseHelper.queryMapList(sql, params);
}
/**
* 执行查询语句
*/
public static List<Map<String, Object>> executeQuery(String sql, Object... params) {
return DatabaseHelper.executeQuery(sql, params);
}
/**
* 执行 SQL 语句(包括update、insert、delete)
*/
public static int executeUpdate(String sql, Object... params) {
return DatabaseHelper.executeUpdate(sql, params);
}
/**
* 执行批量 SQL 语句(包括update、insert、delete)
*/
public static int[] executeBatch(String sql, Object[][] params) {
return DatabaseHelper.executeBatch(sql, params);
}
}
| 2,591 | 0.677918 | 0.675071 | 79 | 30.113924 | 37.745647 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64557 | false | false | 12 |
0a598e4b7e27358fc5823a04c419d9a0d7a8b3f4 | 37,160,057,052,685 | db04582a34ac8ab5924a82ee5207af1d368108ee | /src/test/java/com/study/test/synchronize/JavaInnerClassTest.java | c1e989547ca8b17e3fd9ff96bb48ed74d4eb1b96 | [] | no_license | doveylovey/JDK8-Resource | https://github.com/doveylovey/JDK8-Resource | 8e925f38146655378ae067c59e3e9b64fe2202db | 69618a2b5edcefe59b8b1db50db739c902e2d660 | refs/heads/master | 2021-06-24T00:53:02.240000 | 2021-04-18T15:23:01 | 2021-04-18T15:23:01 | 215,064,207 | 1 | 0 | null | false | 2020-10-18T01:37:09 | 2019-10-14T14:22:49 | 2020-10-18T01:36:30 | 2020-10-18T01:36:28 | 26,971 | 0 | 0 | 0 | Java | false | false | package com.study.test.synchronize;
import org.junit.Test;
/**
* 作用描述:内部类与静态内部类。
*
* @author doveylovey
* @version v1.0.0
* @email 1135782208@qq.com
* @date 2020年08月06日
*/
public class JavaInnerClassTest {
/**
* 注意:如果 {@link OuterClass01} 和 {@link JavaInnerClassTest} 不在同一个包中,则需要将 {@link OuterClass01.InnerClass} 声明成 public 的。
* 实例化内部类的代码必须是:OuterClass.InnerClass innerClass = outerClass.new InnerClass();
*/
@Test
public void testOuterClass01() {
OuterClass01 outerClass01 = new OuterClass01();
outerClass01.setUsername("admin");
outerClass01.setPassword("123456");
System.out.println("外部类的属性值:username=" + outerClass01.getUsername() + ",password=" + outerClass01.getPassword());
OuterClass01.InnerClass innerClass = outerClass01.new InnerClass();
innerClass.setAge(18);
innerClass.setAddress("四川省成都市");
System.out.println("内部类的属性值:age=" + innerClass.getAge() + ",address=" + innerClass.getAddress());
innerClass.printOuterClassProperty();
}
/**
* 打印结果与 {@link JavaInnerClassTest#testOuterClass01()} 一样
*/
@Test
public void testStaticInnerClass01() {
OuterClass02 outerClass02 = new OuterClass02();
outerClass02.setUsername("admin");
outerClass02.setPassword("123456");
System.out.println("外部类的属性值:username=" + outerClass02.getUsername() + ",password=" + outerClass02.getPassword());
OuterClass02.StaticInnerClass staticInnerClass = new OuterClass02.StaticInnerClass();
staticInnerClass.setAge(18);
staticInnerClass.setAddress("四川省成都市");
System.out.println("内部类的属性值:age=" + staticInnerClass.getAge() + ",address=" + staticInnerClass.getAddress());
staticInnerClass.printOuterClassProperty();
}
}
/**
* 外部类、普通内部类
*/
class OuterClass01 {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
class InnerClass {
private int age;
private String address;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void printOuterClassProperty() {
System.out.println("在内部类中打印外部类的属性值:username=" + username + ",password=" + password);
}
}
}
/**
* 外部类、静态内部类
*/
class OuterClass02 {
private static String username;
private static String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
static class StaticInnerClass {
private int age;
private String address;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void printOuterClassProperty() {
System.out.println("在内部类中打印外部类的属性值:username=" + username + ",password=" + password);
}
}
}
| UTF-8 | Java | 4,090 | java | JavaInnerClassTest.java | Java | [
{
"context": ".junit.Test;\n\n/**\n * 作用描述:内部类与静态内部类。\n *\n * @author doveylovey\n * @version v1.0.0\n * @email 1135782208@qq.com\n *",
"end": 108,
"score": 0.9997025728225708,
"start": 98,
"tag": "USERNAME",
"value": "doveylovey"
},
{
"context": "* @author doveylovey\n * @version v1.0.0\n * @email 1135782208@qq.com\n * @date 2020年08月06日\n */\npublic class JavaInnerCl",
"end": 155,
"score": 0.9998980760574341,
"start": 138,
"tag": "EMAIL",
"value": "1135782208@qq.com"
},
{
"context": "OuterClass01();\n outerClass01.setUsername(\"admin\");\n outerClass01.setPassword(\"123456\");\n ",
"end": 579,
"score": 0.9988516569137573,
"start": 574,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "rname(\"admin\");\n outerClass01.setPassword(\"123456\");\n System.out.println(\"外部类的属性值:username=\"",
"end": 623,
"score": 0.9993239045143127,
"start": 617,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "OuterClass02();\n outerClass02.setUsername(\"admin\");\n outerClass02.setPassword(\"123456\");\n ",
"end": 1282,
"score": 0.9983083009719849,
"start": 1277,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "rname(\"admin\");\n outerClass02.setPassword(\"123456\");\n System.out.println(\"外部类的属性值:username=\"",
"end": 1326,
"score": 0.9993415474891663,
"start": 1320,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String userna",
"end": 1967,
"score": 0.6839812994003296,
"start": 1959,
"tag": "USERNAME",
"value": "username"
},
{
"context": "sername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n ",
"end": 2055,
"score": 0.746896505355835,
"start": 2047,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String userna",
"end": 2949,
"score": 0.5675115585327148,
"start": 2941,
"tag": "USERNAME",
"value": "username"
},
{
"context": "assword(String password) {\n this.password = password;\n }\n\n static class StaticInnerClass {\n ",
"end": 3191,
"score": 0.7601856589317322,
"start": 3183,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package com.study.test.synchronize;
import org.junit.Test;
/**
* 作用描述:内部类与静态内部类。
*
* @author doveylovey
* @version v1.0.0
* @email <EMAIL>
* @date 2020年08月06日
*/
public class JavaInnerClassTest {
/**
* 注意:如果 {@link OuterClass01} 和 {@link JavaInnerClassTest} 不在同一个包中,则需要将 {@link OuterClass01.InnerClass} 声明成 public 的。
* 实例化内部类的代码必须是:OuterClass.InnerClass innerClass = outerClass.new InnerClass();
*/
@Test
public void testOuterClass01() {
OuterClass01 outerClass01 = new OuterClass01();
outerClass01.setUsername("admin");
outerClass01.setPassword("<PASSWORD>");
System.out.println("外部类的属性值:username=" + outerClass01.getUsername() + ",password=" + outerClass01.getPassword());
OuterClass01.InnerClass innerClass = outerClass01.new InnerClass();
innerClass.setAge(18);
innerClass.setAddress("四川省成都市");
System.out.println("内部类的属性值:age=" + innerClass.getAge() + ",address=" + innerClass.getAddress());
innerClass.printOuterClassProperty();
}
/**
* 打印结果与 {@link JavaInnerClassTest#testOuterClass01()} 一样
*/
@Test
public void testStaticInnerClass01() {
OuterClass02 outerClass02 = new OuterClass02();
outerClass02.setUsername("admin");
outerClass02.setPassword("<PASSWORD>");
System.out.println("外部类的属性值:username=" + outerClass02.getUsername() + ",password=" + outerClass02.getPassword());
OuterClass02.StaticInnerClass staticInnerClass = new OuterClass02.StaticInnerClass();
staticInnerClass.setAge(18);
staticInnerClass.setAddress("四川省成都市");
System.out.println("内部类的属性值:age=" + staticInnerClass.getAge() + ",address=" + staticInnerClass.getAddress());
staticInnerClass.printOuterClassProperty();
}
}
/**
* 外部类、普通内部类
*/
class OuterClass01 {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
class InnerClass {
private int age;
private String address;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void printOuterClassProperty() {
System.out.println("在内部类中打印外部类的属性值:username=" + username + ",password=" + password);
}
}
}
/**
* 外部类、静态内部类
*/
class OuterClass02 {
private static String username;
private static String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
static class StaticInnerClass {
private int age;
private String address;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void printOuterClassProperty() {
System.out.println("在内部类中打印外部类的属性值:username=" + username + ",password=" + password);
}
}
}
| 4,090 | 0.617709 | 0.594645 | 144 | 25.1875 | 27.1119 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.326389 | false | false | 12 |
8c87fc1ddc0857a4c68965fe816259114cf5cbfc | 28,200,755,306,620 | 4789a659235d39ffa490093926cd19ce76cf661d | /jfinalshop-3.0-web/src/main/java/com/jfinalshop/controller/admin/OrderController.java | 667ae392a6b1ff6fb81bc1a3aa08ac9223ade5e0 | [
"Apache-2.0"
] | permissive | goforitlcq/shop-goforit | https://github.com/goforitlcq/shop-goforit | ce356300e3624bdd0653ee37035993bdce390e9e | 4bbeb184ab06282c8d9131ad73020e719ff76e58 | refs/heads/master | 2021-07-09T04:29:19.955000 | 2017-10-05T17:26:29 | 2017-10-05T17:26:29 | 105,915,693 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jfinalshop.controller.admin;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StrKit;
import com.jfinalshop.common.Message;
import com.jfinalshop.common.Pageable;
import com.jfinalshop.model.Admin;
import com.jfinalshop.model.Area;
import com.jfinalshop.model.DeliveryCorp;
import com.jfinalshop.model.Member;
import com.jfinalshop.model.Order;
import com.jfinalshop.model.Order.OrderStatus;
import com.jfinalshop.model.Order.PaymentStatus;
import com.jfinalshop.model.Order.ShippingStatus;
import com.jfinalshop.model.OrderItem;
import com.jfinalshop.model.Payment;
import com.jfinalshop.model.Payment.Status;
import com.jfinalshop.model.Payment.Type;
import com.jfinalshop.model.PaymentMethod;
import com.jfinalshop.model.Product;
import com.jfinalshop.model.Refunds;
import com.jfinalshop.model.Refunds.Method;
import com.jfinalshop.model.Returns;
import com.jfinalshop.model.ReturnsItem;
import com.jfinalshop.model.Shipping;
import com.jfinalshop.model.ShippingItem;
import com.jfinalshop.model.ShippingMethod;
import com.jfinalshop.model.Sn;
import com.jfinalshop.security.ShiroUtil;
import com.jfinalshop.service.AreaService;
import com.jfinalshop.service.DeliveryCorpService;
import com.jfinalshop.service.OrderItemService;
import com.jfinalshop.service.OrderService;
import com.jfinalshop.service.PaymentMethodService;
import com.jfinalshop.service.ProductService;
import com.jfinalshop.service.ShippingMethodService;
import com.jfinalshop.service.SnService;
/**
* Controller - 订单
*
*
*
*/
@ControllerBind(controllerKey = "/admin/order")
public class OrderController extends BaseAdminController {
private AreaService areaService = enhance(AreaService.class);
private ProductService productService = enhance(ProductService.class);
private OrderService orderService = enhance(OrderService.class);
private OrderItemService orderItemService = enhance(OrderItemService.class);
private ShippingMethodService shippingMethodService = enhance(ShippingMethodService.class);
private DeliveryCorpService deliveryCorpService = enhance(DeliveryCorpService.class);
private PaymentMethodService paymentMethodService = enhance(PaymentMethodService.class);
private SnService snService = enhance(SnService.class);
/**
* 检查锁定
*/
public void checkLock() {
Long id = getParaToLong("id");
Order order = orderService.find(id);
if (order == null) {
renderJson(Message.warn("admin.common.invalid"));
return;
}
Admin admin = ShiroUtil.getAdmin();
if (order.isLocked(admin)) {
if (order.getOperator() != null) {
renderJson(Message.warn("admin.order.adminLocked", order.getOperator().getUsername()));
} else {
renderJson(Message.warn("admin.order.memberLocked"));
}
} else {
order.setLockExpire(DateUtils.addSeconds(new Date(), 20));
order.setOperatorId(admin.getId());
orderService.update(order);
renderJson(SUCCESS_MESSAGE);
}
}
/**
* 查看
*/
public void view() {
Long id = getParaToLong("id");
setAttr("methods", Payment.Method.values());
setAttr("refundsMethods", Refunds.Method.values());
setAttr("paymentMethods", paymentMethodService.findAll());
setAttr("shippingMethods", shippingMethodService.findAll());
setAttr("deliveryCorps", deliveryCorpService.findAll());
setAttr("order", orderService.find(id));
render("/admin/order/view.html");
}
/**
* 确认
*/
public void confirm() {
Long id = getParaToLong("id");
Order order = orderService.find(id);
Admin admin = ShiroUtil.getAdmin();
if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.unconfirmed.ordinal() && !order.isLocked(admin)) {
orderService.confirm(order, admin);
addFlashMessage(SUCCESS_MESSAGE);
} else {
addFlashMessage(Message.warn("admin.common.invalid"));
}
redirect("view?id=" + id);
}
/**
* 完成
*/
public void complete() {
Long id = getParaToLong("id");
Order order = orderService.find(id);
Admin admin = ShiroUtil.getAdmin();
if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.confirmed.ordinal() && !order.isLocked(admin)) {
orderService.complete(order, admin);
addFlashMessage(SUCCESS_MESSAGE);
} else {
addFlashMessage(Message.warn("admin.common.invalid"));
}
redirect("view?id=" + id);
}
/**
* 取消
*/
public void cancel() {
Long id = getCookieToLong("id");
Order order = orderService.find(id);
Admin admin = ShiroUtil.getAdmin();
if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.unconfirmed.ordinal() && !order.isLocked(admin)) {
orderService.cancel(order, admin);
addFlashMessage(SUCCESS_MESSAGE);
} else {
addFlashMessage(Message.warn("admin.common.invalid"));
}
redirect("view?id=" + id);
}
/**
* 支付
*/
public void payment() {
Long orderId = getParaToLong("orderId");
Long paymentMethodId = getParaToLong("paymentMethodId");
Payment payment = getModel(Payment.class);
Order order = orderService.find(orderId);
payment.setOrderId(order.getId());
PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
payment.setPaymentMethod(paymentMethod != null ? paymentMethod.getName() : null);
if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (order.getPaymentStatus() != PaymentStatus.unpaid.ordinal() && order.getPaymentStatus() != PaymentStatus.partialPayment.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (payment.getAmount().compareTo(new BigDecimal(0)) <= 0 || payment.getAmount().compareTo(order.getAmountPayable()) > 0) {
renderJson(ERROR_VIEW);
return;
}
Member member = order.getMember();
if (payment.getMethod() == Payment.Method.deposit.ordinal() && payment.getAmount().compareTo(member.getBalance()) > 0) {
renderJson(ERROR_VIEW);
return;
}
Admin admin = ShiroUtil.getAdmin();
if (order.isLocked(admin)) {
renderJson(ERROR_VIEW);
return;
}
payment.setSn(snService.generate(Sn.Type.payment));
payment.setType(Type.payment.ordinal());
payment.setStatus(Status.success.ordinal());
payment.setFee(new BigDecimal(0));
payment.setOperator(admin.getUsername());
payment.setPaymentDate(new Date());
payment.setPaymentPluginId(null);
payment.setExpire(null);
orderService.payment(order, payment, admin);
addFlashMessage(SUCCESS_MESSAGE);
redirect("view?id=" + orderId);
}
/**
* 退款
*/
public void refunds() {
Long orderId = getParaToLong("orderId");
Long paymentMethodId = getParaToLong("paymentMethodId");
Method method = StrKit.notBlank(getPara("method")) ? Method.valueOf(getPara("method")) : null;
Refunds refunds = getModel(Refunds.class);
Order order = orderService.find(orderId);
refunds.setOrderId(order.getId());
refunds.setMethod(method.ordinal());
PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
refunds.setPaymentMethod(paymentMethod != null ? paymentMethod.getName() : null);
if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (order.getPaymentStatus() != PaymentStatus.paid.ordinal() && order.getPaymentStatus() != PaymentStatus.partialPayment.ordinal() && order.getPaymentStatus() != PaymentStatus.partialRefunds.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (refunds.getAmount().compareTo(new BigDecimal(0)) <= 0 || refunds.getAmount().compareTo(order.getAmountPaid()) > 0) {
renderJson(ERROR_VIEW);
return;
}
Admin admin = ShiroUtil.getAdmin();
if (order.isLocked(admin)) {
renderJson(ERROR_VIEW);
return;
}
refunds.setSn(snService.generate(Sn.Type.refunds));
refunds.setOperator(admin.getUsername());
orderService.refunds(order, refunds, admin);
addFlashMessage(SUCCESS_MESSAGE);
redirect("view?id=" + orderId);
}
/**
* 发货
*/
public void shipping() {
Long orderId = getParaToLong("orderId");
Long shippingMethodId = getParaToLong("shippingMethodId");
Long deliveryCorpId = getParaToLong("deliveryCorpId");
Long areaId = getParaToLong("areaId");
Shipping shipping = getModel(Shipping.class);
List<ShippingItem> shippingItems = getModels(ShippingItem.class);
shipping.setShippingItems(shippingItems);
Order order = orderService.find(orderId);
for (Iterator<ShippingItem> iterator = shipping.getShippingItems().iterator(); iterator.hasNext();) {
ShippingItem shippingItem = iterator.next();
if (shippingItem == null || StringUtils.isEmpty(shippingItem.getSn()) || shippingItem.getQuantity() == null || shippingItem.getQuantity() <= 0) {
iterator.remove();
continue;
}
OrderItem orderItem = order.getOrderItem(shippingItem.getSn());
if (orderItem == null || shippingItem.getQuantity() > orderItem.getQuantity() - orderItem.getShippedQuantity()) {
renderJson(ERROR_VIEW);
return;
}
if (orderItem.getProduct() != null && orderItem.getProduct().getStock() != null && shippingItem.getQuantity() > orderItem.getProduct().getStock()) {
renderJson(ERROR_VIEW);
return;
}
shippingItem.setName(orderItem.getFullName());
shippingItem.setShippingId(shipping.getId());
}
shipping.setOrderId(order.getId());
ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
shipping.setShippingMethod(shippingMethod != null ? shippingMethod.getName() : null);
DeliveryCorp deliveryCorp = deliveryCorpService.find(deliveryCorpId);
shipping.setDeliveryCorp(deliveryCorp != null ? deliveryCorp.getName() : null);
shipping.setDeliveryCorpUrl(deliveryCorp != null ? deliveryCorp.getUrl() : null);
shipping.setDeliveryCorpCode(deliveryCorp != null ? deliveryCorp.getCode() : null);
Area area = areaService.find(areaId);
shipping.setArea(area != null ? area.getFullName() : null);
if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (order.getShippingStatus() != ShippingStatus.unshipped.ordinal() && order.getShippingStatus() != ShippingStatus.partialShipment.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
Admin admin = ShiroUtil.getAdmin();
if (order.isLocked(admin)) {
renderJson(ERROR_VIEW);
return;
}
shipping.setSn(snService.generate(Sn.Type.shipping));
shipping.setOperator(admin.getUsername());
orderService.shipping(order, shipping, admin);
addFlashMessage(SUCCESS_MESSAGE);
redirect("view?id=" + orderId);
}
/**
* 退货
*/
public void returns() {
Long orderId = getParaToLong("orderId");
Long shippingMethodId = getParaToLong("shippingMethodId");
Long deliveryCorpId = getParaToLong("deliveryCorpId");
Long areaId = getParaToLong("areaId");
Returns returns = getModel(Returns.class);
List<ReturnsItem> returnsItems = getModels(ReturnsItem.class);
returns.setReturnsItems(returnsItems);
Order order = orderService.find(orderId);
if (order == null) {
renderJson(ERROR_VIEW);
return;
}
for (Iterator<ReturnsItem> iterator = returns.getReturnsItems().iterator(); iterator.hasNext();) {
ReturnsItem returnsItem = iterator.next();
if (returnsItem == null || StringUtils.isEmpty(returnsItem.getSn()) || returnsItem.getQuantity() == null || returnsItem.getQuantity() <= 0) {
iterator.remove();
continue;
}
OrderItem orderItem = order.getOrderItem(returnsItem.getSn());
if (orderItem == null || returnsItem.getQuantity() > orderItem.getShippedQuantity() - orderItem.getReturnQuantity()) {
renderJson(ERROR_VIEW);
return;
}
returnsItem.setName(orderItem.getFullName());
returnsItem.setReturnsId(returns.getId());
}
returns.setOrderId(order.getId());
ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
returns.setShippingMethod(shippingMethod != null ? shippingMethod.getName() : null);
DeliveryCorp deliveryCorp = deliveryCorpService.find(deliveryCorpId);
returns.setDeliveryCorp(deliveryCorp != null ? deliveryCorp.getName() : null);
Area area = areaService.find(areaId);
returns.setArea(area != null ? area.getFullName() : null);
if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (order.getShippingStatus() != ShippingStatus.shipped.ordinal() && order.getShippingStatus() != ShippingStatus.partialShipment.ordinal() && order.getShippingStatus() != ShippingStatus.partialReturns.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
Admin admin = ShiroUtil.getAdmin();
if (order.isLocked(admin)) {
renderJson(ERROR_VIEW);
return;
}
returns.setSn(snService.generate(Sn.Type.returns));
returns.setOperator(admin.getUsername());
orderService.returns(order, returns, admin);
addFlashMessage(SUCCESS_MESSAGE);
redirect("view?id=" + orderId);
}
/**
* 编辑
*/
public void edit() {
Long id = getParaToLong("id");
setAttr("paymentMethods", paymentMethodService.findAll());
setAttr("shippingMethods", shippingMethodService.findAll());
setAttr("order", orderService.find(id));
render("/admin/order/edit.html");
}
/**
* 订单项添加
*/
public void orderItemAdd() {
String productSn = getPara("productSn");
Map<String, Object> data = new HashMap<String, Object>();
Product product = productService.findBySn(productSn);
if (product == null) {
data.put("message", Message.warn("admin.order.productNotExist"));
renderJson(data);
return;
}
if (!product.getIsMarketable()) {
data.put("message", Message.warn("admin.order.productNotMarketable"));
renderJson(data);
return;
}
if (product.getIsOutOfStock()) {
data.put("message", Message.warn("admin.order.productOutOfStock"));
renderJson(data);
return;
}
data.put("sn", product.getSn());
data.put("fullName", product.getFullName());
data.put("price", product.getPrice());
data.put("weight", product.getWeight());
data.put("isGift", product.getIsGift());
data.put("message", SUCCESS_MESSAGE);
renderJson(data);
}
/**
* 计算
*/
public void calculate() {
Order order = getModel(Order.class);
Long areaId = getParaToLong("areaId");
Long paymentMethodId = getParaToLong("paymentMethodId");
Long shippingMethodId = getParaToLong("shippingMethodId");
Map<String, Object> data = new HashMap<String, Object>();
for (Iterator<OrderItem> iterator = order.getOrderItems().iterator(); iterator.hasNext();) {
OrderItem orderItem = iterator.next();
if (orderItem == null || StringUtils.isEmpty(orderItem.getSn())) {
iterator.remove();
}
}
order.setAreaId(areaId);
order.setPaymentMethodId(paymentMethodId);
order.setShippingMethodId(shippingMethodId);
Order pOrder = orderService.find(order.getId());
if (pOrder == null) {
data.put("message", Message.error("admin.common.invalid"));
renderJson(data);
return;
}
for (OrderItem orderItem : order.getOrderItems()) {
if (orderItem.getId() != null) {
OrderItem pOrderItem = orderItemService.find(orderItem.getId());
if (pOrderItem == null || !pOrder.equals(pOrderItem.getOrder())) {
data.put("message", Message.error("admin.common.invalid"));
renderJson(data);
return;
}
Product product = pOrderItem.getProduct();
if (product != null && product.getStock() != null) {
if (pOrder.getIsAllocatedStock()) {
if (orderItem.getQuantity() > product.getAvailableStock() + pOrderItem.getQuantity()) {
data.put("message", Message.warn("admin.order.lowStock"));
renderJson(data);
return;
}
} else {
if (orderItem.getQuantity() > product.getAvailableStock()) {
data.put("message", Message.warn("admin.order.lowStock"));
renderJson(data);
return;
}
}
}
} else {
Product product = productService.findBySn(orderItem.getSn());
if (product == null) {
data.put("message", Message.error("admin.common.invalid"));
renderJson(data);
return;
}
if (product.getStock() != null && orderItem.getQuantity() > product.getAvailableStock()) {
data.put("message", Message.warn("admin.order.lowStock"));
renderJson(data);
return;
}
}
}
Map<String, Object> orderItems = new HashMap<String, Object>();
for (OrderItem orderItem : order.getOrderItems()) {
orderItems.put(orderItem.getSn(), orderItem);
}
order.setFee(pOrder.getFee());
order.setPromotionDiscount(pOrder.getPromotionDiscount());
order.setCouponDiscount(pOrder.getCouponDiscount());
order.setAmountPaid(pOrder.getAmountPaid());
data.put("weight", order.getWeight());
data.put("price", order.getPrice());
data.put("quantity", order.getQuantity());
data.put("amount", order.getAmount());
data.put("orderItems", orderItems);
data.put("message", SUCCESS_MESSAGE);
renderJson(data);
}
/**
* 更新
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public void update() throws IllegalAccessException, InvocationTargetException {
Order order = getModel(Order.class);
Long areaId = getParaToLong("areaId");
Long paymentMethodId = getParaToLong("paymentMethodId");
Long shippingMethodId = getParaToLong("paymentMethodId");
for (Iterator<OrderItem> iterator = order.getOrderItems().iterator(); iterator.hasNext();) {
OrderItem orderItem = iterator.next();
if (orderItem == null || StringUtils.isEmpty(orderItem.getSn())) {
iterator.remove();
}
}
order.setAreaId(areaId);
order.setPaymentMethodId(paymentMethodId);
order.setShippingMethodId(shippingMethodId);
Order pOrder = orderService.find(order.getId());
if (pOrder == null) {
renderJson(ERROR_VIEW);
return;
}
if (pOrder.isExpired() || pOrder.getOrderStatus() != OrderStatus.unconfirmed.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
Admin admin = ShiroUtil.getAdmin();
if (pOrder.isLocked(admin)) {
renderJson(ERROR_VIEW);
return;
}
if (!order.getIsInvoice()) {
order.setInvoiceTitle(null);
order.setTax(new BigDecimal(0));
}
for (OrderItem orderItem : order.getOrderItems()) {
if (orderItem.getId() != null) {
OrderItem pOrderItem = orderItemService.find(orderItem.getId());
if (pOrderItem == null || !pOrder.equals(pOrderItem.getOrder())) {
renderJson(ERROR_VIEW);
return;
}
Product product = pOrderItem.getProduct();
if (product != null && product.getStock() != null) {
if (pOrder.getIsAllocatedStock()) {
if (orderItem.getQuantity() > product.getAvailableStock() + pOrderItem.getQuantity()) {
renderJson(ERROR_VIEW);
return;
}
} else {
if (orderItem.getQuantity() > product.getAvailableStock()) {
renderJson(ERROR_VIEW);
return;
}
}
}
BigDecimal price = pOrderItem.getPrice();
Integer quantity = pOrderItem.getQuantity();
//BeanUtils.copyProperties(pOrderItem, orderItem, new String[] { "price", "quantity" });
//BeanUtils.copyProperties(pOrderItem, orderItem);
orderItem._setAttrs(pOrderItem);
orderItem.remove("price");
orderItem.remove("quantity");
pOrderItem.setPrice(price);
pOrderItem.setQuantity(quantity);
if (pOrderItem.getIsGift()) {
orderItem.setPrice(new BigDecimal(0));
}
} else {
Product product = productService.findBySn(orderItem.getSn());
if (product == null) {
renderJson(ERROR_VIEW);
return;
}
if (product.getStock() != null && orderItem.getQuantity() > product.getAvailableStock()) {
renderJson(ERROR_VIEW);
return;
}
orderItem.setName(product.getName());
orderItem.setFullName(product.getFullName());
if (product.getIsGift()) {
orderItem.setPrice(new BigDecimal(0));
}
orderItem.setWeight(product.getWeight());
orderItem.setThumbnail(product.getThumbnail());
orderItem.setIsGift(product.getIsGift());
orderItem.setShippedQuantity(0);
orderItem.setReturnQuantity(0);
orderItem.setProductId(product.getId());
orderItem.setOrderId(pOrder.getId());
}
}
order.setSn(pOrder.getSn());
order.setOrderStatus(pOrder.getOrderStatus());
order.setPaymentStatus(pOrder.getPaymentStatus());
order.setShippingStatus(pOrder.getShippingStatus());
order.setFee(pOrder.getFee());
order.setPromotionDiscount(pOrder.getPromotionDiscount());
order.setCouponDiscount(pOrder.getCouponDiscount());
order.setAmountPaid(pOrder.getAmountPaid());
order.setPromotion(pOrder.getPromotion());
order.setExpire(pOrder.getExpire());
order.setLockExpire(null);
order.setIsAllocatedStock(pOrder.getIsAllocatedStock());
order.setMemberId(pOrder.getMember().getId());
order.setCouponCode(pOrder.getCouponCode());
// order.setCoupons(pOrder.getCoupons());
// order.setOrderLogs(pOrder.getOrderLogs());
// order.setDeposits(pOrder.getDeposits());
// order.setPayments(pOrder.getPayments());
// order.setRefunds(pOrder.getRefunds());
// order.setShippings(pOrder.getShippings());
// order.setReturns(pOrder.getReturns());
orderService.update(order, admin);
addFlashMessage(SUCCESS_MESSAGE);
redirect("list");
}
/**
* 列表
*/
public void list() {
OrderStatus orderStatus = StrKit.notBlank(getPara("orderStatus")) ? OrderStatus.valueOf(getPara("orderStatus")) : null;
PaymentStatus paymentStatus = StrKit.notBlank(getPara("paymentStatus")) ? PaymentStatus.valueOf(getPara("paymentStatus")) : null;
ShippingStatus shippingStatus = StrKit.notBlank(getPara("shippingStatus")) ? ShippingStatus.valueOf(getPara("shippingStatus")) : null;
Boolean hasExpired = StrKit.notBlank(getPara("shippingStatus")) ? getParaToBoolean("hasExpired") : null;
Pageable pageable = getBean(Pageable.class);
setAttr("pageable", pageable);
setAttr("orderStatus", orderStatus);
setAttr("paymentStatus", paymentStatus);
setAttr("shippingStatus", shippingStatus);
setAttr("hasExpired", hasExpired);
setAttr("page", orderService.findPage(orderStatus, paymentStatus, shippingStatus, hasExpired, pageable));
render("/admin/order/list.html");
}
/**
* 删除
*/
public void delete() {
Long[] ids = getParaValuesToLong("ids");
if (ids != null) {
Admin admin = ShiroUtil.getAdmin();
for (Long id : ids) {
Order order = orderService.find(id);
if (order != null && order.isLocked(admin)) {
renderJson(Message.error("admin.order.deleteLockedNotAllowed", order.getSn()));
return;
}
}
orderService.delete(ids);
}
renderJson(SUCCESS_MESSAGE);
}
} | UTF-8 | Java | 22,802 | java | OrderController.java | Java | [] | null | [] | package com.jfinalshop.controller.admin;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StrKit;
import com.jfinalshop.common.Message;
import com.jfinalshop.common.Pageable;
import com.jfinalshop.model.Admin;
import com.jfinalshop.model.Area;
import com.jfinalshop.model.DeliveryCorp;
import com.jfinalshop.model.Member;
import com.jfinalshop.model.Order;
import com.jfinalshop.model.Order.OrderStatus;
import com.jfinalshop.model.Order.PaymentStatus;
import com.jfinalshop.model.Order.ShippingStatus;
import com.jfinalshop.model.OrderItem;
import com.jfinalshop.model.Payment;
import com.jfinalshop.model.Payment.Status;
import com.jfinalshop.model.Payment.Type;
import com.jfinalshop.model.PaymentMethod;
import com.jfinalshop.model.Product;
import com.jfinalshop.model.Refunds;
import com.jfinalshop.model.Refunds.Method;
import com.jfinalshop.model.Returns;
import com.jfinalshop.model.ReturnsItem;
import com.jfinalshop.model.Shipping;
import com.jfinalshop.model.ShippingItem;
import com.jfinalshop.model.ShippingMethod;
import com.jfinalshop.model.Sn;
import com.jfinalshop.security.ShiroUtil;
import com.jfinalshop.service.AreaService;
import com.jfinalshop.service.DeliveryCorpService;
import com.jfinalshop.service.OrderItemService;
import com.jfinalshop.service.OrderService;
import com.jfinalshop.service.PaymentMethodService;
import com.jfinalshop.service.ProductService;
import com.jfinalshop.service.ShippingMethodService;
import com.jfinalshop.service.SnService;
/**
* Controller - 订单
*
*
*
*/
@ControllerBind(controllerKey = "/admin/order")
public class OrderController extends BaseAdminController {
private AreaService areaService = enhance(AreaService.class);
private ProductService productService = enhance(ProductService.class);
private OrderService orderService = enhance(OrderService.class);
private OrderItemService orderItemService = enhance(OrderItemService.class);
private ShippingMethodService shippingMethodService = enhance(ShippingMethodService.class);
private DeliveryCorpService deliveryCorpService = enhance(DeliveryCorpService.class);
private PaymentMethodService paymentMethodService = enhance(PaymentMethodService.class);
private SnService snService = enhance(SnService.class);
/**
* 检查锁定
*/
public void checkLock() {
Long id = getParaToLong("id");
Order order = orderService.find(id);
if (order == null) {
renderJson(Message.warn("admin.common.invalid"));
return;
}
Admin admin = ShiroUtil.getAdmin();
if (order.isLocked(admin)) {
if (order.getOperator() != null) {
renderJson(Message.warn("admin.order.adminLocked", order.getOperator().getUsername()));
} else {
renderJson(Message.warn("admin.order.memberLocked"));
}
} else {
order.setLockExpire(DateUtils.addSeconds(new Date(), 20));
order.setOperatorId(admin.getId());
orderService.update(order);
renderJson(SUCCESS_MESSAGE);
}
}
/**
* 查看
*/
public void view() {
Long id = getParaToLong("id");
setAttr("methods", Payment.Method.values());
setAttr("refundsMethods", Refunds.Method.values());
setAttr("paymentMethods", paymentMethodService.findAll());
setAttr("shippingMethods", shippingMethodService.findAll());
setAttr("deliveryCorps", deliveryCorpService.findAll());
setAttr("order", orderService.find(id));
render("/admin/order/view.html");
}
/**
* 确认
*/
public void confirm() {
Long id = getParaToLong("id");
Order order = orderService.find(id);
Admin admin = ShiroUtil.getAdmin();
if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.unconfirmed.ordinal() && !order.isLocked(admin)) {
orderService.confirm(order, admin);
addFlashMessage(SUCCESS_MESSAGE);
} else {
addFlashMessage(Message.warn("admin.common.invalid"));
}
redirect("view?id=" + id);
}
/**
* 完成
*/
public void complete() {
Long id = getParaToLong("id");
Order order = orderService.find(id);
Admin admin = ShiroUtil.getAdmin();
if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.confirmed.ordinal() && !order.isLocked(admin)) {
orderService.complete(order, admin);
addFlashMessage(SUCCESS_MESSAGE);
} else {
addFlashMessage(Message.warn("admin.common.invalid"));
}
redirect("view?id=" + id);
}
/**
* 取消
*/
public void cancel() {
Long id = getCookieToLong("id");
Order order = orderService.find(id);
Admin admin = ShiroUtil.getAdmin();
if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.unconfirmed.ordinal() && !order.isLocked(admin)) {
orderService.cancel(order, admin);
addFlashMessage(SUCCESS_MESSAGE);
} else {
addFlashMessage(Message.warn("admin.common.invalid"));
}
redirect("view?id=" + id);
}
/**
* 支付
*/
public void payment() {
Long orderId = getParaToLong("orderId");
Long paymentMethodId = getParaToLong("paymentMethodId");
Payment payment = getModel(Payment.class);
Order order = orderService.find(orderId);
payment.setOrderId(order.getId());
PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
payment.setPaymentMethod(paymentMethod != null ? paymentMethod.getName() : null);
if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (order.getPaymentStatus() != PaymentStatus.unpaid.ordinal() && order.getPaymentStatus() != PaymentStatus.partialPayment.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (payment.getAmount().compareTo(new BigDecimal(0)) <= 0 || payment.getAmount().compareTo(order.getAmountPayable()) > 0) {
renderJson(ERROR_VIEW);
return;
}
Member member = order.getMember();
if (payment.getMethod() == Payment.Method.deposit.ordinal() && payment.getAmount().compareTo(member.getBalance()) > 0) {
renderJson(ERROR_VIEW);
return;
}
Admin admin = ShiroUtil.getAdmin();
if (order.isLocked(admin)) {
renderJson(ERROR_VIEW);
return;
}
payment.setSn(snService.generate(Sn.Type.payment));
payment.setType(Type.payment.ordinal());
payment.setStatus(Status.success.ordinal());
payment.setFee(new BigDecimal(0));
payment.setOperator(admin.getUsername());
payment.setPaymentDate(new Date());
payment.setPaymentPluginId(null);
payment.setExpire(null);
orderService.payment(order, payment, admin);
addFlashMessage(SUCCESS_MESSAGE);
redirect("view?id=" + orderId);
}
/**
* 退款
*/
public void refunds() {
Long orderId = getParaToLong("orderId");
Long paymentMethodId = getParaToLong("paymentMethodId");
Method method = StrKit.notBlank(getPara("method")) ? Method.valueOf(getPara("method")) : null;
Refunds refunds = getModel(Refunds.class);
Order order = orderService.find(orderId);
refunds.setOrderId(order.getId());
refunds.setMethod(method.ordinal());
PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
refunds.setPaymentMethod(paymentMethod != null ? paymentMethod.getName() : null);
if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (order.getPaymentStatus() != PaymentStatus.paid.ordinal() && order.getPaymentStatus() != PaymentStatus.partialPayment.ordinal() && order.getPaymentStatus() != PaymentStatus.partialRefunds.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (refunds.getAmount().compareTo(new BigDecimal(0)) <= 0 || refunds.getAmount().compareTo(order.getAmountPaid()) > 0) {
renderJson(ERROR_VIEW);
return;
}
Admin admin = ShiroUtil.getAdmin();
if (order.isLocked(admin)) {
renderJson(ERROR_VIEW);
return;
}
refunds.setSn(snService.generate(Sn.Type.refunds));
refunds.setOperator(admin.getUsername());
orderService.refunds(order, refunds, admin);
addFlashMessage(SUCCESS_MESSAGE);
redirect("view?id=" + orderId);
}
/**
* 发货
*/
public void shipping() {
Long orderId = getParaToLong("orderId");
Long shippingMethodId = getParaToLong("shippingMethodId");
Long deliveryCorpId = getParaToLong("deliveryCorpId");
Long areaId = getParaToLong("areaId");
Shipping shipping = getModel(Shipping.class);
List<ShippingItem> shippingItems = getModels(ShippingItem.class);
shipping.setShippingItems(shippingItems);
Order order = orderService.find(orderId);
for (Iterator<ShippingItem> iterator = shipping.getShippingItems().iterator(); iterator.hasNext();) {
ShippingItem shippingItem = iterator.next();
if (shippingItem == null || StringUtils.isEmpty(shippingItem.getSn()) || shippingItem.getQuantity() == null || shippingItem.getQuantity() <= 0) {
iterator.remove();
continue;
}
OrderItem orderItem = order.getOrderItem(shippingItem.getSn());
if (orderItem == null || shippingItem.getQuantity() > orderItem.getQuantity() - orderItem.getShippedQuantity()) {
renderJson(ERROR_VIEW);
return;
}
if (orderItem.getProduct() != null && orderItem.getProduct().getStock() != null && shippingItem.getQuantity() > orderItem.getProduct().getStock()) {
renderJson(ERROR_VIEW);
return;
}
shippingItem.setName(orderItem.getFullName());
shippingItem.setShippingId(shipping.getId());
}
shipping.setOrderId(order.getId());
ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
shipping.setShippingMethod(shippingMethod != null ? shippingMethod.getName() : null);
DeliveryCorp deliveryCorp = deliveryCorpService.find(deliveryCorpId);
shipping.setDeliveryCorp(deliveryCorp != null ? deliveryCorp.getName() : null);
shipping.setDeliveryCorpUrl(deliveryCorp != null ? deliveryCorp.getUrl() : null);
shipping.setDeliveryCorpCode(deliveryCorp != null ? deliveryCorp.getCode() : null);
Area area = areaService.find(areaId);
shipping.setArea(area != null ? area.getFullName() : null);
if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (order.getShippingStatus() != ShippingStatus.unshipped.ordinal() && order.getShippingStatus() != ShippingStatus.partialShipment.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
Admin admin = ShiroUtil.getAdmin();
if (order.isLocked(admin)) {
renderJson(ERROR_VIEW);
return;
}
shipping.setSn(snService.generate(Sn.Type.shipping));
shipping.setOperator(admin.getUsername());
orderService.shipping(order, shipping, admin);
addFlashMessage(SUCCESS_MESSAGE);
redirect("view?id=" + orderId);
}
/**
* 退货
*/
public void returns() {
Long orderId = getParaToLong("orderId");
Long shippingMethodId = getParaToLong("shippingMethodId");
Long deliveryCorpId = getParaToLong("deliveryCorpId");
Long areaId = getParaToLong("areaId");
Returns returns = getModel(Returns.class);
List<ReturnsItem> returnsItems = getModels(ReturnsItem.class);
returns.setReturnsItems(returnsItems);
Order order = orderService.find(orderId);
if (order == null) {
renderJson(ERROR_VIEW);
return;
}
for (Iterator<ReturnsItem> iterator = returns.getReturnsItems().iterator(); iterator.hasNext();) {
ReturnsItem returnsItem = iterator.next();
if (returnsItem == null || StringUtils.isEmpty(returnsItem.getSn()) || returnsItem.getQuantity() == null || returnsItem.getQuantity() <= 0) {
iterator.remove();
continue;
}
OrderItem orderItem = order.getOrderItem(returnsItem.getSn());
if (orderItem == null || returnsItem.getQuantity() > orderItem.getShippedQuantity() - orderItem.getReturnQuantity()) {
renderJson(ERROR_VIEW);
return;
}
returnsItem.setName(orderItem.getFullName());
returnsItem.setReturnsId(returns.getId());
}
returns.setOrderId(order.getId());
ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
returns.setShippingMethod(shippingMethod != null ? shippingMethod.getName() : null);
DeliveryCorp deliveryCorp = deliveryCorpService.find(deliveryCorpId);
returns.setDeliveryCorp(deliveryCorp != null ? deliveryCorp.getName() : null);
Area area = areaService.find(areaId);
returns.setArea(area != null ? area.getFullName() : null);
if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
if (order.getShippingStatus() != ShippingStatus.shipped.ordinal() && order.getShippingStatus() != ShippingStatus.partialShipment.ordinal() && order.getShippingStatus() != ShippingStatus.partialReturns.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
Admin admin = ShiroUtil.getAdmin();
if (order.isLocked(admin)) {
renderJson(ERROR_VIEW);
return;
}
returns.setSn(snService.generate(Sn.Type.returns));
returns.setOperator(admin.getUsername());
orderService.returns(order, returns, admin);
addFlashMessage(SUCCESS_MESSAGE);
redirect("view?id=" + orderId);
}
/**
* 编辑
*/
public void edit() {
Long id = getParaToLong("id");
setAttr("paymentMethods", paymentMethodService.findAll());
setAttr("shippingMethods", shippingMethodService.findAll());
setAttr("order", orderService.find(id));
render("/admin/order/edit.html");
}
/**
* 订单项添加
*/
public void orderItemAdd() {
String productSn = getPara("productSn");
Map<String, Object> data = new HashMap<String, Object>();
Product product = productService.findBySn(productSn);
if (product == null) {
data.put("message", Message.warn("admin.order.productNotExist"));
renderJson(data);
return;
}
if (!product.getIsMarketable()) {
data.put("message", Message.warn("admin.order.productNotMarketable"));
renderJson(data);
return;
}
if (product.getIsOutOfStock()) {
data.put("message", Message.warn("admin.order.productOutOfStock"));
renderJson(data);
return;
}
data.put("sn", product.getSn());
data.put("fullName", product.getFullName());
data.put("price", product.getPrice());
data.put("weight", product.getWeight());
data.put("isGift", product.getIsGift());
data.put("message", SUCCESS_MESSAGE);
renderJson(data);
}
/**
* 计算
*/
public void calculate() {
Order order = getModel(Order.class);
Long areaId = getParaToLong("areaId");
Long paymentMethodId = getParaToLong("paymentMethodId");
Long shippingMethodId = getParaToLong("shippingMethodId");
Map<String, Object> data = new HashMap<String, Object>();
for (Iterator<OrderItem> iterator = order.getOrderItems().iterator(); iterator.hasNext();) {
OrderItem orderItem = iterator.next();
if (orderItem == null || StringUtils.isEmpty(orderItem.getSn())) {
iterator.remove();
}
}
order.setAreaId(areaId);
order.setPaymentMethodId(paymentMethodId);
order.setShippingMethodId(shippingMethodId);
Order pOrder = orderService.find(order.getId());
if (pOrder == null) {
data.put("message", Message.error("admin.common.invalid"));
renderJson(data);
return;
}
for (OrderItem orderItem : order.getOrderItems()) {
if (orderItem.getId() != null) {
OrderItem pOrderItem = orderItemService.find(orderItem.getId());
if (pOrderItem == null || !pOrder.equals(pOrderItem.getOrder())) {
data.put("message", Message.error("admin.common.invalid"));
renderJson(data);
return;
}
Product product = pOrderItem.getProduct();
if (product != null && product.getStock() != null) {
if (pOrder.getIsAllocatedStock()) {
if (orderItem.getQuantity() > product.getAvailableStock() + pOrderItem.getQuantity()) {
data.put("message", Message.warn("admin.order.lowStock"));
renderJson(data);
return;
}
} else {
if (orderItem.getQuantity() > product.getAvailableStock()) {
data.put("message", Message.warn("admin.order.lowStock"));
renderJson(data);
return;
}
}
}
} else {
Product product = productService.findBySn(orderItem.getSn());
if (product == null) {
data.put("message", Message.error("admin.common.invalid"));
renderJson(data);
return;
}
if (product.getStock() != null && orderItem.getQuantity() > product.getAvailableStock()) {
data.put("message", Message.warn("admin.order.lowStock"));
renderJson(data);
return;
}
}
}
Map<String, Object> orderItems = new HashMap<String, Object>();
for (OrderItem orderItem : order.getOrderItems()) {
orderItems.put(orderItem.getSn(), orderItem);
}
order.setFee(pOrder.getFee());
order.setPromotionDiscount(pOrder.getPromotionDiscount());
order.setCouponDiscount(pOrder.getCouponDiscount());
order.setAmountPaid(pOrder.getAmountPaid());
data.put("weight", order.getWeight());
data.put("price", order.getPrice());
data.put("quantity", order.getQuantity());
data.put("amount", order.getAmount());
data.put("orderItems", orderItems);
data.put("message", SUCCESS_MESSAGE);
renderJson(data);
}
/**
* 更新
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public void update() throws IllegalAccessException, InvocationTargetException {
Order order = getModel(Order.class);
Long areaId = getParaToLong("areaId");
Long paymentMethodId = getParaToLong("paymentMethodId");
Long shippingMethodId = getParaToLong("paymentMethodId");
for (Iterator<OrderItem> iterator = order.getOrderItems().iterator(); iterator.hasNext();) {
OrderItem orderItem = iterator.next();
if (orderItem == null || StringUtils.isEmpty(orderItem.getSn())) {
iterator.remove();
}
}
order.setAreaId(areaId);
order.setPaymentMethodId(paymentMethodId);
order.setShippingMethodId(shippingMethodId);
Order pOrder = orderService.find(order.getId());
if (pOrder == null) {
renderJson(ERROR_VIEW);
return;
}
if (pOrder.isExpired() || pOrder.getOrderStatus() != OrderStatus.unconfirmed.ordinal()) {
renderJson(ERROR_VIEW);
return;
}
Admin admin = ShiroUtil.getAdmin();
if (pOrder.isLocked(admin)) {
renderJson(ERROR_VIEW);
return;
}
if (!order.getIsInvoice()) {
order.setInvoiceTitle(null);
order.setTax(new BigDecimal(0));
}
for (OrderItem orderItem : order.getOrderItems()) {
if (orderItem.getId() != null) {
OrderItem pOrderItem = orderItemService.find(orderItem.getId());
if (pOrderItem == null || !pOrder.equals(pOrderItem.getOrder())) {
renderJson(ERROR_VIEW);
return;
}
Product product = pOrderItem.getProduct();
if (product != null && product.getStock() != null) {
if (pOrder.getIsAllocatedStock()) {
if (orderItem.getQuantity() > product.getAvailableStock() + pOrderItem.getQuantity()) {
renderJson(ERROR_VIEW);
return;
}
} else {
if (orderItem.getQuantity() > product.getAvailableStock()) {
renderJson(ERROR_VIEW);
return;
}
}
}
BigDecimal price = pOrderItem.getPrice();
Integer quantity = pOrderItem.getQuantity();
//BeanUtils.copyProperties(pOrderItem, orderItem, new String[] { "price", "quantity" });
//BeanUtils.copyProperties(pOrderItem, orderItem);
orderItem._setAttrs(pOrderItem);
orderItem.remove("price");
orderItem.remove("quantity");
pOrderItem.setPrice(price);
pOrderItem.setQuantity(quantity);
if (pOrderItem.getIsGift()) {
orderItem.setPrice(new BigDecimal(0));
}
} else {
Product product = productService.findBySn(orderItem.getSn());
if (product == null) {
renderJson(ERROR_VIEW);
return;
}
if (product.getStock() != null && orderItem.getQuantity() > product.getAvailableStock()) {
renderJson(ERROR_VIEW);
return;
}
orderItem.setName(product.getName());
orderItem.setFullName(product.getFullName());
if (product.getIsGift()) {
orderItem.setPrice(new BigDecimal(0));
}
orderItem.setWeight(product.getWeight());
orderItem.setThumbnail(product.getThumbnail());
orderItem.setIsGift(product.getIsGift());
orderItem.setShippedQuantity(0);
orderItem.setReturnQuantity(0);
orderItem.setProductId(product.getId());
orderItem.setOrderId(pOrder.getId());
}
}
order.setSn(pOrder.getSn());
order.setOrderStatus(pOrder.getOrderStatus());
order.setPaymentStatus(pOrder.getPaymentStatus());
order.setShippingStatus(pOrder.getShippingStatus());
order.setFee(pOrder.getFee());
order.setPromotionDiscount(pOrder.getPromotionDiscount());
order.setCouponDiscount(pOrder.getCouponDiscount());
order.setAmountPaid(pOrder.getAmountPaid());
order.setPromotion(pOrder.getPromotion());
order.setExpire(pOrder.getExpire());
order.setLockExpire(null);
order.setIsAllocatedStock(pOrder.getIsAllocatedStock());
order.setMemberId(pOrder.getMember().getId());
order.setCouponCode(pOrder.getCouponCode());
// order.setCoupons(pOrder.getCoupons());
// order.setOrderLogs(pOrder.getOrderLogs());
// order.setDeposits(pOrder.getDeposits());
// order.setPayments(pOrder.getPayments());
// order.setRefunds(pOrder.getRefunds());
// order.setShippings(pOrder.getShippings());
// order.setReturns(pOrder.getReturns());
orderService.update(order, admin);
addFlashMessage(SUCCESS_MESSAGE);
redirect("list");
}
/**
* 列表
*/
public void list() {
OrderStatus orderStatus = StrKit.notBlank(getPara("orderStatus")) ? OrderStatus.valueOf(getPara("orderStatus")) : null;
PaymentStatus paymentStatus = StrKit.notBlank(getPara("paymentStatus")) ? PaymentStatus.valueOf(getPara("paymentStatus")) : null;
ShippingStatus shippingStatus = StrKit.notBlank(getPara("shippingStatus")) ? ShippingStatus.valueOf(getPara("shippingStatus")) : null;
Boolean hasExpired = StrKit.notBlank(getPara("shippingStatus")) ? getParaToBoolean("hasExpired") : null;
Pageable pageable = getBean(Pageable.class);
setAttr("pageable", pageable);
setAttr("orderStatus", orderStatus);
setAttr("paymentStatus", paymentStatus);
setAttr("shippingStatus", shippingStatus);
setAttr("hasExpired", hasExpired);
setAttr("page", orderService.findPage(orderStatus, paymentStatus, shippingStatus, hasExpired, pageable));
render("/admin/order/list.html");
}
/**
* 删除
*/
public void delete() {
Long[] ids = getParaValuesToLong("ids");
if (ids != null) {
Admin admin = ShiroUtil.getAdmin();
for (Long id : ids) {
Order order = orderService.find(id);
if (order != null && order.isLocked(admin)) {
renderJson(Message.error("admin.order.deleteLockedNotAllowed", order.getSn()));
return;
}
}
orderService.delete(ids);
}
renderJson(SUCCESS_MESSAGE);
}
} | 22,802 | 0.713745 | 0.712909 | 636 | 34.737423 | 30.137033 | 215 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.018868 | false | false | 12 |
69a5b03b89f3e3c05d8462456342840d58b195e4 | 30,949,534,374,591 | e6ed4dfb7367fabc35d23c82a4b0bab75375c4d5 | /lectures/12.Lists/TestListMore.java | a90a8164478010a09b89cf6251fb4967e99cbea7 | [] | no_license | mason2smart/datastructures2018 | https://github.com/mason2smart/datastructures2018 | c272bbabbd1dba25249cf5837a5574cef575f1c8 | 479f4b9e8b6702c591c6dbc34dc1acbdfd42e7e4 | refs/heads/master | 2020-04-17T06:08:07.187000 | 2018-12-11T23:14:06 | 2018-12-11T23:14:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.assertEquals;
public class TestListMore {
List<String> list;
@Before
public void setupList () {
list = new NodeList<String>();
}
@Test
public void testEmptyList () {
assertEquals("[]", list.toString());
assertEquals(0, list.length());
}
@Test
public void testInsertFront () {
list.insertFront("Peter");
list.insertFront("Paul");
assertEquals("[Paul, Peter]", list.toString());
assertEquals(2, list.length());
}
@Test
public void testInsertBack () {
list.insertBack("Peter");
list.insertBack("Paul");
assertEquals("[Peter, Paul]", list.toString());
assertEquals(2, list.length());
}
@Test
public void testRemoveFront () {
list.insertBack("Peter");
list.insertBack("Paul");
list.insertBack("Mike");
assertEquals("[Peter, Paul, Mike]", list.toString());
assertEquals(3, list.length());
list.removeFront();
assertEquals("[Paul, Mike]", list.toString());
assertEquals(2, list.length());
list.removeFront();
assertEquals("[Mike]", list.toString());
assertEquals(1, list.length());
list.removeFront();
assertEquals("[]", list.toString());
assertEquals(0, list.length());
}
@Test
public void testRemoveBack () {
list.insertBack("Peter");
list.insertBack("Paul");
list.insertBack("Mike");
assertEquals("[Peter, Paul, Mike]", list.toString());
assertEquals(3, list.length());
list.removeBack();
assertEquals("[Peter, Paul]", list.toString());
assertEquals(2, list.length());
list.removeBack();
assertEquals("[Peter]", list.toString ());
assertEquals(1, list.length());
list.removeFront();
assertEquals("[]", list.toString ());
assertEquals(0, list.length());
}
@Test
public void testRemoveMiddle () {
list.insertBack("Peter");
Position p = list.insertBack("Paul");
list.insertBack("Mike");
assertEquals("[Peter, Paul, Mike]", list.toString ());
assertEquals(3, list.length ());
list.remove(p);
assertEquals("[Peter, Mike]", list.toString ());
}
}
| UTF-8 | Java | 2,399 | java | TestListMore.java | Java | [
{
"context": "id testInsertFront () {\n list.insertFront(\"Peter\");\n list.insertFront(\"Paul\");\n asse",
"end": 452,
"score": 0.9993389844894409,
"start": 447,
"tag": "NAME",
"value": "Peter"
},
{
"context": "t.insertFront(\"Peter\");\n list.insertFront(\"Paul\");\n assertEquals(\"[Paul, Peter]\", list.toS",
"end": 486,
"score": 0.9995826482772827,
"start": 482,
"tag": "NAME",
"value": "Paul"
},
{
"context": " list.insertFront(\"Paul\");\n assertEquals(\"[Paul, Peter]\", list.toString()); \n assertEquals",
"end": 517,
"score": 0.9340678453445435,
"start": 513,
"tag": "NAME",
"value": "Paul"
},
{
"context": ".insertFront(\"Paul\");\n assertEquals(\"[Paul, Peter]\", list.toString()); \n assertEquals(2, lis",
"end": 524,
"score": 0.8130189180374146,
"start": 519,
"tag": "NAME",
"value": "Peter"
},
{
"context": "oid testInsertBack () { \n list.insertBack(\"Peter\"); \n list.insertBack(\"Paul\");\n asse",
"end": 671,
"score": 0.9992412328720093,
"start": 666,
"tag": "NAME",
"value": "Peter"
},
{
"context": "st.insertBack(\"Peter\"); \n list.insertBack(\"Paul\");\n assertEquals(\"[Peter, Paul]\", list.toS",
"end": 705,
"score": 0.9994602203369141,
"start": 701,
"tag": "NAME",
"value": "Paul"
},
{
"context": " list.insertBack(\"Paul\");\n assertEquals(\"[Peter, Paul]\", list.toString());\n assertEquals(2",
"end": 737,
"score": 0.98785799741745,
"start": 733,
"tag": "NAME",
"value": "eter"
},
{
"context": ".insertBack(\"Paul\");\n assertEquals(\"[Peter, Paul]\", list.toString());\n assertEquals(2, list",
"end": 743,
"score": 0.44920915365219116,
"start": 739,
"tag": "NAME",
"value": "Paul"
},
{
"context": "id testRemoveFront () { \n list.insertBack(\"Peter\"); \n list.insertBack(\"Paul\");\n list",
"end": 890,
"score": 0.9992731213569641,
"start": 885,
"tag": "NAME",
"value": "Peter"
},
{
"context": "st.insertBack(\"Peter\"); \n list.insertBack(\"Paul\");\n list.insertBack(\"Mike\");\n asser",
"end": 924,
"score": 0.9995540380477905,
"start": 920,
"tag": "NAME",
"value": "Paul"
},
{
"context": "list.insertBack(\"Paul\");\n list.insertBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", li",
"end": 957,
"score": 0.9994794726371765,
"start": 953,
"tag": "NAME",
"value": "Mike"
},
{
"context": " list.insertBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", list.toString());\n assertEq",
"end": 989,
"score": 0.9382386803627014,
"start": 984,
"tag": "NAME",
"value": "Peter"
},
{
"context": ".insertBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", list.toString());\n assertEquals(3",
"end": 995,
"score": 0.8957262635231018,
"start": 991,
"tag": "NAME",
"value": "Paul"
},
{
"context": "tBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", list.toString());\n assertEquals(3, list",
"end": 1001,
"score": 0.983025312423706,
"start": 997,
"tag": "NAME",
"value": "Mike"
},
{
"context": " list.removeFront();\n assertEquals(\"[Paul, Mike]\", list.toString());\n assertEquals(2",
"end": 1119,
"score": 0.8691011667251587,
"start": 1115,
"tag": "NAME",
"value": "Paul"
},
{
"context": " list.removeFront();\n assertEquals(\"[Paul, Mike]\", list.toString());\n assertEquals(2, list",
"end": 1125,
"score": 0.8455238342285156,
"start": 1121,
"tag": "NAME",
"value": "Mike"
},
{
"context": " list.removeFront();\n assertEquals(\"[Mike]\", list.toString());\n assertEquals(1, list",
"end": 1243,
"score": 0.7797426581382751,
"start": 1239,
"tag": "NAME",
"value": "Mike"
},
{
"context": "oid testRemoveBack () { \n list.insertBack(\"Peter\"); \n list.insertBack(\"Paul\");\n list",
"end": 1503,
"score": 0.9988847970962524,
"start": 1498,
"tag": "NAME",
"value": "Peter"
},
{
"context": "st.insertBack(\"Peter\"); \n list.insertBack(\"Paul\");\n list.insertBack(\"Mike\");\n asser",
"end": 1537,
"score": 0.9995598793029785,
"start": 1533,
"tag": "NAME",
"value": "Paul"
},
{
"context": "list.insertBack(\"Paul\");\n list.insertBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", li",
"end": 1570,
"score": 0.9995929002761841,
"start": 1566,
"tag": "NAME",
"value": "Mike"
},
{
"context": " list.insertBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", list.toString());\n assertEq",
"end": 1602,
"score": 0.9859325289726257,
"start": 1597,
"tag": "NAME",
"value": "Peter"
},
{
"context": ".insertBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", list.toString());\n assertEquals(3",
"end": 1608,
"score": 0.981737494468689,
"start": 1604,
"tag": "NAME",
"value": "Paul"
},
{
"context": "tBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", list.toString());\n assertEquals(3, list",
"end": 1614,
"score": 0.991206705570221,
"start": 1610,
"tag": "NAME",
"value": "Mike"
},
{
"context": " list.removeBack();\n assertEquals(\"[Peter, Paul]\", list.toString());\n assertEquals(2",
"end": 1732,
"score": 0.7864370346069336,
"start": 1728,
"tag": "NAME",
"value": "eter"
},
{
"context": " list.removeBack();\n assertEquals(\"[Peter]\", list.toString ());\n assertEquals(1, lis",
"end": 1856,
"score": 0.6210897564888,
"start": 1852,
"tag": "NAME",
"value": "eter"
},
{
"context": "d testRemoveMiddle () { \n list.insertBack(\"Peter\"); \n Position p = list.insertBack(\"Paul\");",
"end": 2120,
"score": 0.9979724884033203,
"start": 2115,
"tag": "NAME",
"value": "Peter"
},
{
"context": "(\"Peter\"); \n Position p = list.insertBack(\"Paul\");\n list.insertBack(\"Mike\");\n asser",
"end": 2167,
"score": 0.9984265565872192,
"start": 2163,
"tag": "NAME",
"value": "Paul"
},
{
"context": "list.insertBack(\"Paul\");\n list.insertBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", li",
"end": 2200,
"score": 0.9995459318161011,
"start": 2196,
"tag": "NAME",
"value": "Mike"
},
{
"context": " list.insertBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", list.toString ());\n assertE",
"end": 2232,
"score": 0.9985807538032532,
"start": 2227,
"tag": "NAME",
"value": "Peter"
},
{
"context": ".insertBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", list.toString ());\n assertEquals(3",
"end": 2238,
"score": 0.72883540391922,
"start": 2234,
"tag": "NAME",
"value": "Paul"
},
{
"context": "tBack(\"Mike\");\n assertEquals(\"[Peter, Paul, Mike]\", list.toString ());\n assertEquals(3, lis",
"end": 2244,
"score": 0.9429181814193726,
"start": 2240,
"tag": "NAME",
"value": "Mike"
},
{
"context": ";\n\n list.remove(p);\n assertEquals(\"[Peter, Mike]\", list.toString ());\n }\n}\n\n",
"end": 2361,
"score": 0.9984724521636963,
"start": 2356,
"tag": "NAME",
"value": "Peter"
},
{
"context": " list.remove(p);\n assertEquals(\"[Peter, Mike]\", list.toString ());\n }\n}\n\n",
"end": 2367,
"score": 0.9945303201675415,
"start": 2363,
"tag": "NAME",
"value": "Mike"
}
] | null | [] | import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.assertEquals;
public class TestListMore {
List<String> list;
@Before
public void setupList () {
list = new NodeList<String>();
}
@Test
public void testEmptyList () {
assertEquals("[]", list.toString());
assertEquals(0, list.length());
}
@Test
public void testInsertFront () {
list.insertFront("Peter");
list.insertFront("Paul");
assertEquals("[Paul, Peter]", list.toString());
assertEquals(2, list.length());
}
@Test
public void testInsertBack () {
list.insertBack("Peter");
list.insertBack("Paul");
assertEquals("[Peter, Paul]", list.toString());
assertEquals(2, list.length());
}
@Test
public void testRemoveFront () {
list.insertBack("Peter");
list.insertBack("Paul");
list.insertBack("Mike");
assertEquals("[Peter, Paul, Mike]", list.toString());
assertEquals(3, list.length());
list.removeFront();
assertEquals("[Paul, Mike]", list.toString());
assertEquals(2, list.length());
list.removeFront();
assertEquals("[Mike]", list.toString());
assertEquals(1, list.length());
list.removeFront();
assertEquals("[]", list.toString());
assertEquals(0, list.length());
}
@Test
public void testRemoveBack () {
list.insertBack("Peter");
list.insertBack("Paul");
list.insertBack("Mike");
assertEquals("[Peter, Paul, Mike]", list.toString());
assertEquals(3, list.length());
list.removeBack();
assertEquals("[Peter, Paul]", list.toString());
assertEquals(2, list.length());
list.removeBack();
assertEquals("[Peter]", list.toString ());
assertEquals(1, list.length());
list.removeFront();
assertEquals("[]", list.toString ());
assertEquals(0, list.length());
}
@Test
public void testRemoveMiddle () {
list.insertBack("Peter");
Position p = list.insertBack("Paul");
list.insertBack("Mike");
assertEquals("[Peter, Paul, Mike]", list.toString ());
assertEquals(3, list.length ());
list.remove(p);
assertEquals("[Peter, Mike]", list.toString ());
}
}
| 2,399 | 0.566486 | 0.561484 | 88 | 26.25 | 18.495853 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.977273 | false | false | 12 |
40189d26764e9a85d83d11dd109ae029007c0e92 | 146,028,913,067 | 1720afad928b5eacbe2f3bccf0d8c786b2d2a694 | /src/main/java/pl/whitelines/configuration/AuthenticationFilter.java | b2bc5b2020e7d832e419d6c46f4ce2f9c391943f | [] | no_license | nkopiec/Notebook | https://github.com/nkopiec/Notebook | 8af04814a33542383c97d9de3a7a90682570c27c | 7bb2af7af9c2650950e5e895106eccaf850a88ed | refs/heads/master | 2022-08-05T14:40:10.784000 | 2019-09-12T15:18:37 | 2019-09-12T15:18:37 | 160,388,081 | 0 | 0 | null | false | 2022-07-07T22:52:11 | 2018-12-04T16:36:44 | 2019-09-12T15:18:40 | 2022-07-07T22:52:08 | 39 | 0 | 0 | 2 | Java | false | false | package pl.whitelines.configuration;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(request, response);
}
}
}
| UTF-8 | Java | 984 | java | AuthenticationFilter.java | Java | [] | null | [] | package pl.whitelines.configuration;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(request, response);
}
}
}
| 984 | 0.787602 | 0.787602 | 25 | 38.360001 | 33.231167 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 12 |
cba91f5ff44254c5835306e3761a34bf9252741e | 13,228,499,284,928 | 9903a7e7127fbee262c9a3e311c9aa735d6a9528 | /oa-core/src/main/java/com/hanlin/oa/common/controller/BaseController.java | e95ba7603762a5aa180c0b81b73dc87281214ef3 | [] | no_license | siashan/oa_master | https://github.com/siashan/oa_master | 20b4dc0cd157b9d6aa7494e79479d902bb701eea | d1658214dc2a61323b8ac8c7db73d0768635cc3b | refs/heads/master | 2023-08-03T09:29:16.063000 | 2019-05-24T07:21:00 | 2019-05-24T07:21:00 | 188,372,504 | 0 | 0 | null | false | 2023-07-22T06:37:17 | 2019-05-24T07:17:09 | 2019-05-24T07:24:34 | 2023-07-22T06:37:17 | 51 | 0 | 0 | 3 | Java | false | false | package com.hanlin.oa.common.controller;
import com.hanlin.oa.common.support.orm.Page;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
/**
* @Author: kfc
* @Description: <br/>
* Date:Create in 2019/5/14 19:34
* @Modified By:
*/
public class BaseController {
@Autowired
protected HttpServletRequest req;
/**
* Description: 获取分页对象 <br/>
*
* @param:
* @return:
* @Author: kfc
* @Date: 2018/4/2 9:46
*/
protected Page initPage() {
String cur = req.getParameter("currentPage");
String size = req.getParameter("pageSize");
int curPage = (cur == null || "0".equals(cur) ? 1 : Integer.parseInt(cur));
int pageSize = (size == null ? Page.DEFAULT_LENGTH : Integer.parseInt(size));
return new Page(curPage, pageSize);
}
}
| UTF-8 | Java | 887 | java | BaseController.java | Java | [
{
"context": ".servlet.http.HttpServletRequest;\n\n/**\n * @Author: kfc\n * @Description: <br/>\n * Date:Create in 2019/5/1",
"end": 218,
"score": 0.9996740818023682,
"start": 215,
"tag": "USERNAME",
"value": "kfc"
},
{
"context": " *\n * @param:\n * @return:\n * @Author: kfc\n * @Date: 2018/4/2 9:46\n */\n protected",
"end": 478,
"score": 0.9996570348739624,
"start": 475,
"tag": "USERNAME",
"value": "kfc"
}
] | null | [] | package com.hanlin.oa.common.controller;
import com.hanlin.oa.common.support.orm.Page;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
/**
* @Author: kfc
* @Description: <br/>
* Date:Create in 2019/5/14 19:34
* @Modified By:
*/
public class BaseController {
@Autowired
protected HttpServletRequest req;
/**
* Description: 获取分页对象 <br/>
*
* @param:
* @return:
* @Author: kfc
* @Date: 2018/4/2 9:46
*/
protected Page initPage() {
String cur = req.getParameter("currentPage");
String size = req.getParameter("pageSize");
int curPage = (cur == null || "0".equals(cur) ? 1 : Integer.parseInt(cur));
int pageSize = (size == null ? Page.DEFAULT_LENGTH : Integer.parseInt(size));
return new Page(curPage, pageSize);
}
}
| 887 | 0.634286 | 0.609143 | 32 | 26.34375 | 22.908253 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.40625 | false | false | 3 |
e66991773d9896feb172aa899430ca86684e581c | 25,426,206,406,119 | a39f1f2966486089bfbcde5399ac667dc780fa96 | /src/main/java/com/research/security/service/UserService.java | 0c9218e4459f13b7b68ca99011158656dbc29ce8 | [] | no_license | Private-group/research | https://github.com/Private-group/research | 5c911e67a4b66a5055a7de63ad5f83004fea2794 | b6f3d9fec9d7819b75c112a4c0212caff4eca82d | refs/heads/master | 2021-01-23T05:30:01.046000 | 2017-03-27T09:06:35 | 2017-03-27T09:06:35 | 86,313,866 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.research.security.service;
import java.util.List;
import com.research.security.bean.User;
public class UserService {
public List<User> queryByLoginId(String loginId) {
// TODO Auto-generated method stub
return null;
}
public User getUserByLoginId(String loginId) {
// TODO Auto-generated method stub
return null;
}
}
| UTF-8 | Java | 366 | java | UserService.java | Java | [] | null | [] | package com.research.security.service;
import java.util.List;
import com.research.security.bean.User;
public class UserService {
public List<User> queryByLoginId(String loginId) {
// TODO Auto-generated method stub
return null;
}
public User getUserByLoginId(String loginId) {
// TODO Auto-generated method stub
return null;
}
}
| 366 | 0.710383 | 0.710383 | 19 | 17.263159 | 18.159649 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.894737 | false | false | 3 |
04d69bcb87c760878450768a9857d7f4554acc38 | 17,300,128,282,304 | 155902a06d054ae3e34c0773a8b9c5ffe3c02b2c | /src/IC/lir/instruction/JumpInstructionEnum.java | 20edf122604f8de38fe168f86ffe6d5ef7d4d54a | [] | no_license | Oreneo/tau-compile2011 | https://github.com/Oreneo/tau-compile2011 | 1c4d58b390a077cdc434857b7310e971559531a6 | 0d5f2674135be57b6dd40c4479c3233b0e4af104 | refs/heads/master | 2015-08-21T16:28:18.466000 | 2011-03-17T18:56:48 | 2011-03-17T18:56:48 | 32,281,796 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package IC.lir.instruction;
public enum JumpInstructionEnum {
Unconditional(""),
True("True"),
False("False"),
Greater("G"),
GreaterEqual("GE"),
Less("L"),
LessEqual("LE");
private String name;
private JumpInstructionEnum(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
| UTF-8 | Java | 416 | java | JumpInstructionEnum.java | Java | [] | null | [] | package IC.lir.instruction;
public enum JumpInstructionEnum {
Unconditional(""),
True("True"),
False("False"),
Greater("G"),
GreaterEqual("GE"),
Less("L"),
LessEqual("LE");
private String name;
private JumpInstructionEnum(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
| 416 | 0.519231 | 0.519231 | 25 | 14.64 | 12.48 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44 | false | false | 3 |
e08d7637263ee4a72724a4a4eca825ae667060d4 | 12,412,455,503,809 | c847e5939c57bce939bac7b1775f1c568de0c284 | /ebank/src/com/charge/dao/ChargeInfoDao.java | da3fcd028c8c28d6dee2f6c5f108a30fa2e4440c | [] | no_license | WuLiangHang/JavaWeb202011 | https://github.com/WuLiangHang/JavaWeb202011 | 0af01a555b150e8cb27596c24910d7ca76842f84 | eaa0f9873ed3fc5ffa966e5630636c29414f82ef | refs/heads/master | 2023-01-27T13:50:58.400000 | 2020-12-05T02:07:40 | 2020-12-05T02:07:40 | 315,879,827 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.charge.dao;
import com.charge.entity.ChargeInfo;
public interface ChargeInfoDao {
int updateUser(ChargeInfo chargeInfo);
ChargeInfo queryUserById(String userId);
}
| UTF-8 | Java | 187 | java | ChargeInfoDao.java | Java | [] | null | [] | package com.charge.dao;
import com.charge.entity.ChargeInfo;
public interface ChargeInfoDao {
int updateUser(ChargeInfo chargeInfo);
ChargeInfo queryUserById(String userId);
}
| 187 | 0.780749 | 0.780749 | 9 | 19.777779 | 18.347134 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 3 |
72732656a9486ed3f20c9c8666dd231c7b0996cc | 6,279,242,207,163 | 587664603811d82daeb29feac53552d0b44a0c4d | /src/main/java/it/polito/tdp/PremierLeague/model/Model.java | 20098a1a09a05bc8e71b6421b1175445533ff5ae | [] | no_license | MariMaran/2020-06-03-simulazione | https://github.com/MariMaran/2020-06-03-simulazione | 2bf17e2fa2cafd34cdde60bf8d5e067906264045 | a45abd4b3c3c85a48061ea68a67a6967576e6e15 | refs/heads/master | 2022-11-09T10:29:17.740000 | 2020-06-22T20:50:18 | 2020-06-22T20:50:18 | 274,145,587 | 0 | 0 | null | true | 2020-06-22T13:32:12 | 2020-06-22T13:32:11 | 2020-06-10T06:47:22 | 2020-06-11T18:00:30 | 1,214 | 0 | 0 | 0 | null | false | false | package it.polito.tdp.PremierLeague.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;
import org.jgrapht.graph.SimpleWeightedGraph;
import it.polito.tdp.PremierLeague.db.PremierLeagueDAO;
public class Model {
Graph<Player,DefaultWeightedEdge> grafo;
PremierLeagueDAO dao;
Map<Integer,Player> idMap;
List<Player> dreamTeam;
List<Player> tutti;
double titolaritaMassima;
public Model() {
dao=new PremierLeagueDAO();
}
public List<Player> getDreamTeam(){
List<Player> vuota=new ArrayList();
dreamTeam=new ArrayList();
titolaritaMassima=0;
ricorsione(tutti,0,vuota,0);
return dreamTeam;
}
public void ricorsione(List<Player> daEsaminare, double titolaritaAttuale, List<Player> soluzione, int livello) {
if(livello==3) {
if(titolaritaAttuale>titolaritaMassima) {
titolaritaMassima=titolaritaAttuale;
dreamTeam=new ArrayList(soluzione);
}
return;
}
for(Player p: daEsaminare) {
Set<DefaultWeightedEdge> archiUscenti=grafo.outgoingEdgesOf(p);
Set<DefaultWeightedEdge> archiEntranti=grafo.incomingEdgesOf(p);
List<Player> daEliminare=new ArrayList();
double somma=0;
for(DefaultWeightedEdge d: archiUscenti) {
somma+=grafo.getEdgeWeight(d);
daEliminare.add(grafo.getEdgeTarget(d));
}
for(DefaultWeightedEdge d: archiEntranti) {
somma-=grafo.getEdgeWeight(d);
}
List<Player> nuova=new ArrayList(daEsaminare);
for(Player p2: daEliminare) {
nuova.remove(p2);
}
soluzione.add(p);
nuova.remove(p);
ricorsione(nuova,titolaritaAttuale+somma,soluzione,livello+1);
soluzione.remove(p);
}
}
public void creaGrafo(double minimoGoals) {
idMap=new TreeMap();
tutti=new ArrayList();
grafo=new SimpleDirectedWeightedGraph(DefaultWeightedEdge.class);
List<Player> vertici=dao.getPlayers(minimoGoals);
for(Player p: vertici) {
grafo.addVertex(p);
idMap.put(p.getPlayerID(),p);
tutti.add(p);
}
List<Collegamento> coll=dao.getCollegamento(idMap);
for(Collegamento c: coll) {
if(c.differenza>0) {
grafo.addEdge(c.p1, c.p2);
grafo.setEdgeWeight(c.p1, c.p2, c.differenza);
}
else {
grafo.addEdge(c.p2, c.p1);
grafo.setEdgeWeight(c.p2, c.p1, c.differenza*-1);
}
}
}
}
| UTF-8 | Java | 2,431 | java | Model.java | Java | [] | null | [] | package it.polito.tdp.PremierLeague.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;
import org.jgrapht.graph.SimpleWeightedGraph;
import it.polito.tdp.PremierLeague.db.PremierLeagueDAO;
public class Model {
Graph<Player,DefaultWeightedEdge> grafo;
PremierLeagueDAO dao;
Map<Integer,Player> idMap;
List<Player> dreamTeam;
List<Player> tutti;
double titolaritaMassima;
public Model() {
dao=new PremierLeagueDAO();
}
public List<Player> getDreamTeam(){
List<Player> vuota=new ArrayList();
dreamTeam=new ArrayList();
titolaritaMassima=0;
ricorsione(tutti,0,vuota,0);
return dreamTeam;
}
public void ricorsione(List<Player> daEsaminare, double titolaritaAttuale, List<Player> soluzione, int livello) {
if(livello==3) {
if(titolaritaAttuale>titolaritaMassima) {
titolaritaMassima=titolaritaAttuale;
dreamTeam=new ArrayList(soluzione);
}
return;
}
for(Player p: daEsaminare) {
Set<DefaultWeightedEdge> archiUscenti=grafo.outgoingEdgesOf(p);
Set<DefaultWeightedEdge> archiEntranti=grafo.incomingEdgesOf(p);
List<Player> daEliminare=new ArrayList();
double somma=0;
for(DefaultWeightedEdge d: archiUscenti) {
somma+=grafo.getEdgeWeight(d);
daEliminare.add(grafo.getEdgeTarget(d));
}
for(DefaultWeightedEdge d: archiEntranti) {
somma-=grafo.getEdgeWeight(d);
}
List<Player> nuova=new ArrayList(daEsaminare);
for(Player p2: daEliminare) {
nuova.remove(p2);
}
soluzione.add(p);
nuova.remove(p);
ricorsione(nuova,titolaritaAttuale+somma,soluzione,livello+1);
soluzione.remove(p);
}
}
public void creaGrafo(double minimoGoals) {
idMap=new TreeMap();
tutti=new ArrayList();
grafo=new SimpleDirectedWeightedGraph(DefaultWeightedEdge.class);
List<Player> vertici=dao.getPlayers(minimoGoals);
for(Player p: vertici) {
grafo.addVertex(p);
idMap.put(p.getPlayerID(),p);
tutti.add(p);
}
List<Collegamento> coll=dao.getCollegamento(idMap);
for(Collegamento c: coll) {
if(c.differenza>0) {
grafo.addEdge(c.p1, c.p2);
grafo.setEdgeWeight(c.p1, c.p2, c.differenza);
}
else {
grafo.addEdge(c.p2, c.p1);
grafo.setEdgeWeight(c.p2, c.p1, c.differenza*-1);
}
}
}
}
| 2,431 | 0.726039 | 0.718634 | 93 | 25.139786 | 20.67079 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.623656 | false | false | 3 |
64cea53dc62f72d11bd3e6de397b450c03787c0e | 28,862,180,270,380 | ca030864a3a1c24be6b9d1802c2353da4ca0d441 | /classes10.dex_source_from_JADX/com/facebook/timeline/editfeaturedcontainers/rows/NullStateDeclarations.java | ce225e14276ea1f9b081256346d6d97e36ab1a21 | [] | no_license | pxson001/facebook-app | https://github.com/pxson001/facebook-app | 87aa51e29195eeaae69adeb30219547f83a5b7b1 | 640630f078980f9818049625ebc42569c67c69f7 | refs/heads/master | 2020-04-07T20:36:45.758000 | 2018-03-07T09:04:57 | 2018-03-07T09:04:57 | 124,208,458 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.timeline.editfeaturedcontainers.rows;
import android.content.Context;
import com.facebook.common.propertybag.PropertyBag;
import com.facebook.feed.rows.core.FeedRowSupportDeclaration;
import com.facebook.feed.rows.core.ListItemRowController;
import com.facebook.inject.ContextScope;
import com.facebook.inject.ContextScoped;
import com.facebook.inject.InjectorLike;
import com.facebook.inject.InjectorThreadStack;
import com.facebook.inject.ProvisioningException;
import com.facebook.inject.ScopeSet;
@ContextScoped
/* compiled from: getSuggestedBots failed */
public class NullStateDeclarations implements FeedRowSupportDeclaration {
private static NullStateDeclarations f10825a;
private static final Object f10826b = new Object();
private static NullStateDeclarations m10949a() {
return new NullStateDeclarations();
}
public final void m10951a(ListItemRowController listItemRowController) {
listItemRowController.a(NullStateSectionTitlePartDefinition.f10837a);
listItemRowController.a(NullStateYourPhotosPartDefinition.f10890a);
listItemRowController.a(NullStateClickablePhotoPartDefinition.f10820a);
listItemRowController.a(NullStateSuggestedPagePartDefinition.f10846a);
listItemRowController.a(NullStateSuggestedPagesSectionFooterPartDefinition.f10859a);
}
public static NullStateDeclarations m10950a(InjectorLike injectorLike) {
ScopeSet a = ScopeSet.a();
byte b = a.b((byte) 8);
try {
Context b2 = injectorLike.getScopeAwareInjector().b();
if (b2 == null) {
throw new ProvisioningException("Called context scoped provider outside of context scope");
}
NullStateDeclarations a2;
ContextScope contextScope = (ContextScope) injectorLike.getInstance(ContextScope.class);
PropertyBag a3 = ContextScope.a(b2);
synchronized (f10826b) {
NullStateDeclarations nullStateDeclarations;
if (a3 != null) {
nullStateDeclarations = (NullStateDeclarations) a3.a(f10826b);
} else {
nullStateDeclarations = f10825a;
}
if (nullStateDeclarations == null) {
InjectorThreadStack injectorThreadStack = injectorLike.getInjectorThreadStack();
contextScope.a(b2, injectorThreadStack);
try {
injectorThreadStack.e();
a2 = m10949a();
if (a3 != null) {
a3.a(f10826b, a2);
} else {
f10825a = a2;
}
} finally {
ContextScope.a(injectorThreadStack);
}
} else {
a2 = nullStateDeclarations;
}
}
return a2;
} finally {
a.c(b);
}
}
}
| UTF-8 | Java | 3,056 | java | NullStateDeclarations.java | Java | [] | null | [] | package com.facebook.timeline.editfeaturedcontainers.rows;
import android.content.Context;
import com.facebook.common.propertybag.PropertyBag;
import com.facebook.feed.rows.core.FeedRowSupportDeclaration;
import com.facebook.feed.rows.core.ListItemRowController;
import com.facebook.inject.ContextScope;
import com.facebook.inject.ContextScoped;
import com.facebook.inject.InjectorLike;
import com.facebook.inject.InjectorThreadStack;
import com.facebook.inject.ProvisioningException;
import com.facebook.inject.ScopeSet;
@ContextScoped
/* compiled from: getSuggestedBots failed */
public class NullStateDeclarations implements FeedRowSupportDeclaration {
private static NullStateDeclarations f10825a;
private static final Object f10826b = new Object();
private static NullStateDeclarations m10949a() {
return new NullStateDeclarations();
}
public final void m10951a(ListItemRowController listItemRowController) {
listItemRowController.a(NullStateSectionTitlePartDefinition.f10837a);
listItemRowController.a(NullStateYourPhotosPartDefinition.f10890a);
listItemRowController.a(NullStateClickablePhotoPartDefinition.f10820a);
listItemRowController.a(NullStateSuggestedPagePartDefinition.f10846a);
listItemRowController.a(NullStateSuggestedPagesSectionFooterPartDefinition.f10859a);
}
public static NullStateDeclarations m10950a(InjectorLike injectorLike) {
ScopeSet a = ScopeSet.a();
byte b = a.b((byte) 8);
try {
Context b2 = injectorLike.getScopeAwareInjector().b();
if (b2 == null) {
throw new ProvisioningException("Called context scoped provider outside of context scope");
}
NullStateDeclarations a2;
ContextScope contextScope = (ContextScope) injectorLike.getInstance(ContextScope.class);
PropertyBag a3 = ContextScope.a(b2);
synchronized (f10826b) {
NullStateDeclarations nullStateDeclarations;
if (a3 != null) {
nullStateDeclarations = (NullStateDeclarations) a3.a(f10826b);
} else {
nullStateDeclarations = f10825a;
}
if (nullStateDeclarations == null) {
InjectorThreadStack injectorThreadStack = injectorLike.getInjectorThreadStack();
contextScope.a(b2, injectorThreadStack);
try {
injectorThreadStack.e();
a2 = m10949a();
if (a3 != null) {
a3.a(f10826b, a2);
} else {
f10825a = a2;
}
} finally {
ContextScope.a(injectorThreadStack);
}
} else {
a2 = nullStateDeclarations;
}
}
return a2;
} finally {
a.c(b);
}
}
}
| 3,056 | 0.623037 | 0.591623 | 73 | 40.863014 | 26.344564 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.561644 | false | false | 3 |
48e848c5a59a5d19e2d5ed9f2c2dcb0a102604eb | 27,556,510,189,463 | a0bb26cb16e88860e651d23ddec5a5ff5c62036f | /src/main/java/com/example/SimpleSpringBoot/beans/Weather.java | ebd28a39f558336f54edcfbf0dbfb27b310a8478 | [] | no_license | fromgopi/SampleSpringRest | https://github.com/fromgopi/SampleSpringRest | 3c81353c73e05bdaa0261847b79d6de8d519f4d7 | 7e0b0cd23f0d0b65b66a06d17387c043f1b66706 | refs/heads/master | 2020-03-07T03:44:10.342000 | 2018-05-14T12:42:32 | 2018-05-14T12:43:48 | 127,245,157 | 0 | 0 | null | false | 2018-05-14T12:43:49 | 2018-03-29T06:12:05 | 2018-05-08T12:23:16 | 2018-05-14T12:43:49 | 17,554 | 0 | 0 | 0 | Java | false | null | package com.example.SimpleSpringBoot.beans;
public class Weather {
private Object temp;
private Object temp_min;
private Object temp_max;
private String city_name;
private String country;
private String famous_place;
public String getCity_name() {
return city_name;
}
public void setCity_name(String city_name) {
this.city_name = city_name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFamous_place() {
return famous_place;
}
public void setFamous_place(String famous_place) {
this.famous_place = famous_place;
}
public Object getTemp() {
return temp;
}
public void setTemp(Object temp) {
this.temp = temp;
}
public Object getTemp_min() {
return temp_min;
}
public void setTemp_min(Object temp_min) {
this.temp_min = temp_min;
}
public Object getTemp_max() {
return temp_max;
}
public void setTemp_max(Object temp_max) {
this.temp_max = temp_max;
}
}
| UTF-8 | Java | 1,169 | java | Weather.java | Java | [] | null | [] | package com.example.SimpleSpringBoot.beans;
public class Weather {
private Object temp;
private Object temp_min;
private Object temp_max;
private String city_name;
private String country;
private String famous_place;
public String getCity_name() {
return city_name;
}
public void setCity_name(String city_name) {
this.city_name = city_name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFamous_place() {
return famous_place;
}
public void setFamous_place(String famous_place) {
this.famous_place = famous_place;
}
public Object getTemp() {
return temp;
}
public void setTemp(Object temp) {
this.temp = temp;
}
public Object getTemp_min() {
return temp_min;
}
public void setTemp_min(Object temp_min) {
this.temp_min = temp_min;
}
public Object getTemp_max() {
return temp_max;
}
public void setTemp_max(Object temp_max) {
this.temp_max = temp_max;
}
}
| 1,169 | 0.603935 | 0.603935 | 59 | 18.813559 | 16.49291 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.322034 | false | false | 3 |
2eae0050044bdb2ea86bcd3e53bdd1214fff8786 | 11,716,670,825,919 | 625916fa5fa58e21b55426fdc0fc953931bb2d4e | /src/main/java/mobagame/server/database/PlayerAccountDBO.java | 631fff177842ca6469909674dc1fb3d51fe5e8e3 | [] | no_license | Kurtoid/mobagame | https://github.com/Kurtoid/mobagame | a97ba998c9ba9f07a4e200264174e15bb435bc7e | 8eb1098a821829dc3f5bc331d2d71de3eb3731cd | refs/heads/master | 2020-08-10T08:42:46.622000 | 2020-01-29T23:40:26 | 2020-01-29T23:40:26 | 214,307,824 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mobagame.server.database;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* manages login and signup of users securely
*
* @author Kurt Wilson
*
*/
public class PlayerAccountDBO {
private static int ITERATIONS = 10000;
private static final int KEY_LENGTH = 128;
DatabaseConnectionManager db;
PreparedStatement createAccount;
PreparedStatement loginAccount;
PreparedStatement getAccountByUsername;
PreparedStatement getAccountByEmail;
PreparedStatement getUsernameByIDStatement;
public PlayerAccountDBO() {
try {
db = DatabaseConnectionManager.getInstance();
createAccount = db.getConnection().prepareStatement(
"INSERT INTO PlayerAccount (username, password, email, questionID, questionAnswer, xp, level) VALUES (?, ?, ?, ?, ?, ?, ?)");
loginAccount = db.getConnection()
.prepareStatement("SELECT * FROM PlayerAccount WHERE username = ? AND password = ?");
getAccountByUsername = db.getConnection().prepareStatement("SELECT * FROM PlayerAccount WHERE username = ?");
getAccountByEmail = db.getConnection().prepareStatement("SELECT * FROM PlayerAccount WHERE email = ?");
getUsernameByIDStatement = db.getConnection().prepareStatement("SELECT username FROM PlayerAccount WHERE id=?");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// TODO: return player
/**
* signs up a user to check if the signup is successful, sign the user in if it
* fails, returns a SQLException
*
* @param username
* @param password
* @param emailAddress
* @param securityQuestionID
* @param securityQuestionAnswer
* @throws SQLException
* if user cant be created
*/
public void createAccount(String username, String password, String emailAddress, byte securityQuestionID,
String securityQuestionAnswer) throws SQLException {
try {
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(password.getBytes());
createAccount.setString(1, username);
createAccount.setBytes(2, result);
createAccount.setString(3, emailAddress);
createAccount.setInt(4, securityQuestionID);
createAccount.setString(5, securityQuestionAnswer);
createAccount.setInt(6, 0);
createAccount.setInt(7, 1);
createAccount.executeUpdate();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return new PlayerAccount();
}
/**
* logs in an account, and returns it
* @param username
* @param password
* @return the player, or null if it fails
* @throws SQLException
*/
public PlayerAccount loginAccount(String username, String password) throws SQLException {
try {
loginAccount.setString(1, username);
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(password.getBytes());
loginAccount.setBytes(2, result);
loginAccount.execute();
ResultSet rs = loginAccount.getResultSet();
rs.next();
PlayerAccount p = getPlayerAccountFromResultSet(rs);
return p;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
/**
* gets a player based off of username
* @param username
* @return
* @throws SQLException
*/
public PlayerAccount getAccountByUsername(String username) throws SQLException {
getAccountByUsername.setString(1,username);
getAccountByUsername.executeQuery();
ResultSet rs = getAccountByUsername.getResultSet();
rs.next();
PlayerAccount p = getPlayerAccountFromResultSet(rs);
return p;
}
/**
* gets a player based off of email
* @param email
* @return
* @throws SQLException
*/
public PlayerAccount getAccountByEmail(String email) throws SQLException {
getAccountByEmail.setString(1,email);
getAccountByEmail.executeQuery();
ResultSet rs = getAccountByEmail.getResultSet();
rs.next();
PlayerAccount p = getPlayerAccountFromResultSet(rs);
return p;
}
private PlayerAccount getPlayerAccountFromResultSet(ResultSet rs) throws SQLException {
PlayerAccount p = new PlayerAccount();
p.id = rs.getInt("id");
p.level = rs.getInt("level");
p.username = rs.getString("username");
return p;
}
public static void main(String[] args) {
PlayerAccountDBO dbo = new PlayerAccountDBO();
try {
dbo.createAccount("hgeugfiw", "hfeiow", null, (byte) 0x00, null);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsernameByID(int playerID) throws SQLException {
getUsernameByIDStatement.setInt(1,playerID);
getUsernameByIDStatement.executeQuery();
ResultSet rs = getUsernameByIDStatement.getResultSet();
rs.next();
return rs.getString("username");
}
}
| UTF-8 | Java | 5,046 | java | PlayerAccountDBO.java | Java | [
{
"context": "login and signup of users securely\r\n *\r\n * @author Kurt Wilson\r\n *\r\n */\r\npublic class PlayerAccountDBO {\r\n\r\n\tpri",
"end": 330,
"score": 0.997365415096283,
"start": 319,
"tag": "NAME",
"value": "Kurt Wilson"
},
{
"context": "rs.getInt(\"level\");\r\n\t\tp.username = rs.getString(\"username\");\r\n\t\treturn p;\r\n\t}\r\n\r\n\tpublic static void main(S",
"end": 4469,
"score": 0.9988464117050171,
"start": 4461,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ayerAccountDBO();\r\n\t\ttry {\r\n\t\t\tdbo.createAccount(\"hgeugfiw\", \"hfeiow\", null, (byte) 0x00, null);\r\n\t\t} catch ",
"end": 4625,
"score": 0.9478287696838379,
"start": 4617,
"tag": "USERNAME",
"value": "hgeugfiw"
},
{
"context": "BO();\r\n\t\ttry {\r\n\t\t\tdbo.createAccount(\"hgeugfiw\", \"hfeiow\", null, (byte) 0x00, null);\r\n\t\t} catch (SQLExcept",
"end": 4635,
"score": 0.884265661239624,
"start": 4629,
"tag": "USERNAME",
"value": "hfeiow"
}
] | null | [] | package mobagame.server.database;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* manages login and signup of users securely
*
* @author <NAME>
*
*/
public class PlayerAccountDBO {
private static int ITERATIONS = 10000;
private static final int KEY_LENGTH = 128;
DatabaseConnectionManager db;
PreparedStatement createAccount;
PreparedStatement loginAccount;
PreparedStatement getAccountByUsername;
PreparedStatement getAccountByEmail;
PreparedStatement getUsernameByIDStatement;
public PlayerAccountDBO() {
try {
db = DatabaseConnectionManager.getInstance();
createAccount = db.getConnection().prepareStatement(
"INSERT INTO PlayerAccount (username, password, email, questionID, questionAnswer, xp, level) VALUES (?, ?, ?, ?, ?, ?, ?)");
loginAccount = db.getConnection()
.prepareStatement("SELECT * FROM PlayerAccount WHERE username = ? AND password = ?");
getAccountByUsername = db.getConnection().prepareStatement("SELECT * FROM PlayerAccount WHERE username = ?");
getAccountByEmail = db.getConnection().prepareStatement("SELECT * FROM PlayerAccount WHERE email = ?");
getUsernameByIDStatement = db.getConnection().prepareStatement("SELECT username FROM PlayerAccount WHERE id=?");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// TODO: return player
/**
* signs up a user to check if the signup is successful, sign the user in if it
* fails, returns a SQLException
*
* @param username
* @param password
* @param emailAddress
* @param securityQuestionID
* @param securityQuestionAnswer
* @throws SQLException
* if user cant be created
*/
public void createAccount(String username, String password, String emailAddress, byte securityQuestionID,
String securityQuestionAnswer) throws SQLException {
try {
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(password.getBytes());
createAccount.setString(1, username);
createAccount.setBytes(2, result);
createAccount.setString(3, emailAddress);
createAccount.setInt(4, securityQuestionID);
createAccount.setString(5, securityQuestionAnswer);
createAccount.setInt(6, 0);
createAccount.setInt(7, 1);
createAccount.executeUpdate();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return new PlayerAccount();
}
/**
* logs in an account, and returns it
* @param username
* @param password
* @return the player, or null if it fails
* @throws SQLException
*/
public PlayerAccount loginAccount(String username, String password) throws SQLException {
try {
loginAccount.setString(1, username);
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(password.getBytes());
loginAccount.setBytes(2, result);
loginAccount.execute();
ResultSet rs = loginAccount.getResultSet();
rs.next();
PlayerAccount p = getPlayerAccountFromResultSet(rs);
return p;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
/**
* gets a player based off of username
* @param username
* @return
* @throws SQLException
*/
public PlayerAccount getAccountByUsername(String username) throws SQLException {
getAccountByUsername.setString(1,username);
getAccountByUsername.executeQuery();
ResultSet rs = getAccountByUsername.getResultSet();
rs.next();
PlayerAccount p = getPlayerAccountFromResultSet(rs);
return p;
}
/**
* gets a player based off of email
* @param email
* @return
* @throws SQLException
*/
public PlayerAccount getAccountByEmail(String email) throws SQLException {
getAccountByEmail.setString(1,email);
getAccountByEmail.executeQuery();
ResultSet rs = getAccountByEmail.getResultSet();
rs.next();
PlayerAccount p = getPlayerAccountFromResultSet(rs);
return p;
}
private PlayerAccount getPlayerAccountFromResultSet(ResultSet rs) throws SQLException {
PlayerAccount p = new PlayerAccount();
p.id = rs.getInt("id");
p.level = rs.getInt("level");
p.username = rs.getString("username");
return p;
}
public static void main(String[] args) {
PlayerAccountDBO dbo = new PlayerAccountDBO();
try {
dbo.createAccount("hgeugfiw", "hfeiow", null, (byte) 0x00, null);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsernameByID(int playerID) throws SQLException {
getUsernameByIDStatement.setInt(1,playerID);
getUsernameByIDStatement.executeQuery();
ResultSet rs = getUsernameByIDStatement.getResultSet();
rs.next();
return rs.getString("username");
}
}
| 5,041 | 0.711455 | 0.706104 | 160 | 29.5375 | 26.200165 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.18125 | false | false | 3 |
a1f8430a9621db86e6e55585f7aea6fc28b64137 | 9,706,626,096,351 | 7077dd924399165dbcb3a01315b53e5f9ccf1b1a | /src/main/java/co/leantechniques/maven/buildtime/BuildTimeMavenLifecycleParticipant.java | e99220cdf07235eea3dabfaa66db09639fe22e93 | [
"MIT"
] | permissive | jcarlile/maven-buildtime-extension | https://github.com/jcarlile/maven-buildtime-extension | 9b4579d80ac17da1ccc89346fde90e2eedb7e581 | f152fd2b4b8c522bb55779ff80c672bd26262acb | refs/heads/master | 2021-01-14T11:12:37.470000 | 2014-03-24T16:58:23 | 2014-03-24T16:58:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.leantechniques.maven.buildtime;
import java.util.Properties;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.cli.ExecutionTimingExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.util.StringUtils;
import org.slf4j.Logger;
import com.timgroup.statsd.NoOpStatsDClient;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;
@Component(role = AbstractMavenLifecycleParticipant.class)
public class BuildTimeMavenLifecycleParticipant extends AbstractMavenLifecycleParticipant {
private static final String STATSD_HOST_PROPERTY = "buildtime.statsd.host";
private static final String STATSD_PORT_PROPERTY = "buildtime.statsd.port";
private static final String STATSD_PREFIX = "buildtime.statsd.prefix";
@Requirement
private Logger logger;
private StatsDClient stats;
@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
stats = getStats(session.getTopLevelProject().getProperties());
afterProjectsRead(session, new ExecutionTimingExecutionListener(stats, logger));
}
void afterProjectsRead(MavenSession session, ExecutionTimingExecutionListener listener) {
listener.registerListenerOn(session);
}
@Override
public void afterSessionEnd(MavenSession session) throws MavenExecutionException {
stats.stop();
super.afterSessionEnd(session);
}
private StatsDClient getStats(Properties props) {
String host = props.getProperty(STATSD_HOST_PROPERTY);
String port = props.getProperty(STATSD_PORT_PROPERTY);
String prefix = props.getProperty(STATSD_PREFIX);
if(StringUtils.isNotBlank(host)) {
return new NonBlockingStatsDClient(
prefix == null ? "buildtime" : prefix,
host,
port == null ? 8125 : Integer.valueOf(port));
}
return new NoOpStatsDClient();
}
}
| UTF-8 | Java | 2,189 | java | BuildTimeMavenLifecycleParticipant.java | Java | [] | null | [] | package co.leantechniques.maven.buildtime;
import java.util.Properties;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.cli.ExecutionTimingExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.util.StringUtils;
import org.slf4j.Logger;
import com.timgroup.statsd.NoOpStatsDClient;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;
@Component(role = AbstractMavenLifecycleParticipant.class)
public class BuildTimeMavenLifecycleParticipant extends AbstractMavenLifecycleParticipant {
private static final String STATSD_HOST_PROPERTY = "buildtime.statsd.host";
private static final String STATSD_PORT_PROPERTY = "buildtime.statsd.port";
private static final String STATSD_PREFIX = "buildtime.statsd.prefix";
@Requirement
private Logger logger;
private StatsDClient stats;
@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
stats = getStats(session.getTopLevelProject().getProperties());
afterProjectsRead(session, new ExecutionTimingExecutionListener(stats, logger));
}
void afterProjectsRead(MavenSession session, ExecutionTimingExecutionListener listener) {
listener.registerListenerOn(session);
}
@Override
public void afterSessionEnd(MavenSession session) throws MavenExecutionException {
stats.stop();
super.afterSessionEnd(session);
}
private StatsDClient getStats(Properties props) {
String host = props.getProperty(STATSD_HOST_PROPERTY);
String port = props.getProperty(STATSD_PORT_PROPERTY);
String prefix = props.getProperty(STATSD_PREFIX);
if(StringUtils.isNotBlank(host)) {
return new NonBlockingStatsDClient(
prefix == null ? "buildtime" : prefix,
host,
port == null ? 8125 : Integer.valueOf(port));
}
return new NoOpStatsDClient();
}
}
| 2,189 | 0.755139 | 0.752855 | 59 | 36.101696 | 28.820717 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.016949 | false | false | 3 |
39e757af84511cac822854991ceddf24b3ceac27 | 9,706,626,094,433 | 4a7489b9069fc58ae8f52ea144a1fc0da4ffecbc | /common/src/main/java/com/ibm/fsd/exception/RequestException.java | 154e1b726c7d29448e37796805c3e1ccb82455dc | [
"Apache-2.0"
] | permissive | lx-emart/emart-all | https://github.com/lx-emart/emart-all | be50b0cb31430d5e6891e1ff7af27a2ecc30dd0e | d1d016d86727cfe8bed6a8606202837ea4695488 | refs/heads/master | 2022-10-01T12:53:48.356000 | 2020-06-11T07:03:14 | 2020-06-11T07:03:14 | 271,473,839 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ibm.fsd.exception;
import org.springframework.validation.Errors;
@SuppressWarnings("serial")
public class RequestException extends RuntimeException {
private String errorCode;
private String errorMsg;
private Errors errors;
public RequestException(String errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public RequestException(String errorCode, Errors errors) {
this.errorCode = errorCode;
this.errors = errors;
}
public RequestException(String errorCode, String errorMsg, Errors errors) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
this.errors = errors;
}
public String getErrorCode() {
return errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public Errors getErrors() {
return errors;
}
}
| UTF-8 | Java | 812 | java | RequestException.java | Java | [] | null | [] | package com.ibm.fsd.exception;
import org.springframework.validation.Errors;
@SuppressWarnings("serial")
public class RequestException extends RuntimeException {
private String errorCode;
private String errorMsg;
private Errors errors;
public RequestException(String errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public RequestException(String errorCode, Errors errors) {
this.errorCode = errorCode;
this.errors = errors;
}
public RequestException(String errorCode, String errorMsg, Errors errors) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
this.errors = errors;
}
public String getErrorCode() {
return errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public Errors getErrors() {
return errors;
}
}
| 812 | 0.75 | 0.75 | 39 | 19.820513 | 19.565632 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.461538 | false | false | 3 |
d6f10ea8b77517884fc645c07d63e6e31de989e0 | 32,796,370,304,853 | cdfaa77d1b7ca4c7c7ce0b292d86ebd1942a2dff | /Accueil0/src/com/example/marieanne/spot/ListEv.java | 39e642e1f2df16583291fa9b4c367efcc38f9ec2 | [] | no_license | mbuffier/SPOT | https://github.com/mbuffier/SPOT | cac200e1704a4ca3506d4b9ed40d394f245122a3 | 04734655c9d0e31455647b18870cfcaf383d68eb | refs/heads/master | 2021-01-17T16:04:53.406000 | 2017-03-06T21:09:58 | 2017-03-06T21:09:58 | 84,120,966 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.marieanne.spot;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.marieanne.spot.Data.Event;
import java.util.ArrayList;
import java.util.List;
public class ListEv extends Activity {
private ListView list= null;
private ImageView image =null;
private TextView titreEM=null;
private TextView descEM = null;
private static List<Event> listEvent = new ArrayList<>();
private static List<String> listTitleEvent = new ArrayList<>();
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_ev);
titreEM = (TextView) findViewById(R.id.titreEM);
descEM = (TextView) findViewById(R.id.descEM);
image = (ImageView) findViewById(R.id.imageDuMois);
list = (ListView) findViewById(R.id.liste);
listTitleEvent.clear();
for ( int i=0; i<listEvent.size();i++){
listTitleEvent.add(listEvent.get(i).getTitle());
}
ArrayAdapter<String> listAdapterTitle = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listTitleEvent);
list.setAdapter(listAdapterTitle);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
Intent intent = new Intent(ListEv.this, Evenement.class);
startActivity(intent);
Evenement.changeEvent(listEvent.get(position));
}
});
image.setImageResource(listEvent.get(0).getPicture());
titreEM.setText(listEvent.get(0).getTitle());
descEM.setText(listEvent.get(0).getMotClé());
}
/* public void goToEvent ( View view) {
int ind = list.getCheckedItemPosition();
Evenement.changeEvent(listEvent.get(ind));
}*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_ev, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static void changeListEvent( List<Event> events ) {
listEvent=events;
}
}
| UTF-8 | Java | 3,292 | java | ListEv.java | Java | [] | null | [] | package com.example.marieanne.spot;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.marieanne.spot.Data.Event;
import java.util.ArrayList;
import java.util.List;
public class ListEv extends Activity {
private ListView list= null;
private ImageView image =null;
private TextView titreEM=null;
private TextView descEM = null;
private static List<Event> listEvent = new ArrayList<>();
private static List<String> listTitleEvent = new ArrayList<>();
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_ev);
titreEM = (TextView) findViewById(R.id.titreEM);
descEM = (TextView) findViewById(R.id.descEM);
image = (ImageView) findViewById(R.id.imageDuMois);
list = (ListView) findViewById(R.id.liste);
listTitleEvent.clear();
for ( int i=0; i<listEvent.size();i++){
listTitleEvent.add(listEvent.get(i).getTitle());
}
ArrayAdapter<String> listAdapterTitle = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listTitleEvent);
list.setAdapter(listAdapterTitle);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
Intent intent = new Intent(ListEv.this, Evenement.class);
startActivity(intent);
Evenement.changeEvent(listEvent.get(position));
}
});
image.setImageResource(listEvent.get(0).getPicture());
titreEM.setText(listEvent.get(0).getTitle());
descEM.setText(listEvent.get(0).getMotClé());
}
/* public void goToEvent ( View view) {
int ind = list.getCheckedItemPosition();
Evenement.changeEvent(listEvent.get(ind));
}*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_ev, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static void changeListEvent( List<Event> events ) {
listEvent=events;
}
}
| 3,292 | 0.651778 | 0.650258 | 113 | 28.115044 | 25.675219 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.522124 | false | false | 3 |
e62409589add95a4c17cbce6960e39818af94dfc | 32,993,938,768,229 | 5f52ce485a422109c66fb75ab87ae89623e8d862 | /app/src/main/java/com/example/quick_food/QRCodeScanner.java | 388710e67497e99295a66a3be423eb22705bb76f | [] | no_license | Invader2221/Food-Ordering-System | https://github.com/Invader2221/Food-Ordering-System | d8adaa4af0badbec3f028be841357b5470961d1e | 20327a788fd03b6e4c58c57d91672231487d98e7 | refs/heads/main | 2023-05-29T10:22:18.616000 | 2021-06-13T04:07:08 | 2021-06-13T04:07:08 | 376,433,145 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.quick_food;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.PermissionRequest;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.Result;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.single.PermissionListener;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class QRCodeScanner extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView scannerView;
private TextView txtResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr_scanner);
getSupportActionBar().setTitle("Scan QR Code");
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
//Init
scannerView = (ZXingScannerView) findViewById(R.id.zxscan);
txtResult = (TextView) findViewById(R.id.txt_result);
//request permission
Dexter.withActivity(this)
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
scannerView.setResultHandler(QRCodeScanner.this);
scannerView.startCamera();
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(QRCodeScanner.this, "You must accept this permission", Toast.LENGTH_SHORT).show();
}
@Override
public void onPermissionRationaleShouldBeShown(com.karumi.dexter.listener.PermissionRequest permission, PermissionToken token) {
}
})
.check();
}
@Override
public void onBackPressed() {
}
@Override
protected void onDestroy() {
scannerView.stopCamera();
super.onDestroy();
}
@Override
public void handleResult(Result rawResult) {
//Here we can receive rawResult
processRawResult(rawResult.getText());
// scannerView.startCamera();
}
private void processRawResult(String text) {
Log.e("QRScan>>",text);
Intent intent = new Intent(this, OrderConfirmActivity.class);
intent.putExtra("NEW_ORDER_ID_QR", text);
this.startActivity(intent);
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
scannerView.setResultHandler(QRCodeScanner.this);
scannerView.startCamera();
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
| UTF-8 | Java | 3,670 | java | QRCodeScanner.java | Java | [] | null | [] | package com.example.quick_food;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.PermissionRequest;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.Result;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.single.PermissionListener;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class QRCodeScanner extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView scannerView;
private TextView txtResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr_scanner);
getSupportActionBar().setTitle("Scan QR Code");
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
//Init
scannerView = (ZXingScannerView) findViewById(R.id.zxscan);
txtResult = (TextView) findViewById(R.id.txt_result);
//request permission
Dexter.withActivity(this)
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
scannerView.setResultHandler(QRCodeScanner.this);
scannerView.startCamera();
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(QRCodeScanner.this, "You must accept this permission", Toast.LENGTH_SHORT).show();
}
@Override
public void onPermissionRationaleShouldBeShown(com.karumi.dexter.listener.PermissionRequest permission, PermissionToken token) {
}
})
.check();
}
@Override
public void onBackPressed() {
}
@Override
protected void onDestroy() {
scannerView.stopCamera();
super.onDestroy();
}
@Override
public void handleResult(Result rawResult) {
//Here we can receive rawResult
processRawResult(rawResult.getText());
// scannerView.startCamera();
}
private void processRawResult(String text) {
Log.e("QRScan>>",text);
Intent intent = new Intent(this, OrderConfirmActivity.class);
intent.putExtra("NEW_ORDER_ID_QR", text);
this.startActivity(intent);
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
scannerView.setResultHandler(QRCodeScanner.this);
scannerView.startCamera();
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
| 3,670 | 0.658311 | 0.658038 | 118 | 30.101694 | 27.382225 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
bd9ab72ea7c5076400bd5c5c3dce56acc1b7e32e | 4,337,917,000,610 | edeb88fc2207c34ca257e8d0d87ba956b582ec66 | /javaCursePOS/src/fr/web_en_royans/lebarajus/POS/menu/MenuItem.java | bb1fe1181cb75ce09b39f7f13bb8aae59d8e11b7 | [] | no_license | psic/JavaCursePOS | https://github.com/psic/JavaCursePOS | f7650cc64baf02a5e3e82bfc478f696fd350df47 | f9ca324d6b430763026e8aba2a82f1f9b411a665 | refs/heads/master | 2021-12-13T14:10:14.430000 | 2021-09-13T22:32:16 | 2021-09-13T22:32:16 | 40,506,132 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.web_en_royans.lebarajus.POS.menu;
import java.util.ArrayList;
import java.util.List;
import charvax.swing.JLabel;
public class MenuItem {
private List<Price> price;
private Price selectedPrice;
private String desc;
private String fullDesc;
private String sep = " / ";
private char key;
private boolean isRoot;
private MenuItem parent;
private List<MenuItem> children;
public MenuItem(List<Price> price_, String desc_, char key_, MenuItem parent_){
price = price_;
desc = desc_;
key = key_;
isRoot=false;
if (!parent_.isRoot())
fullDesc = parent_.getFullDesc() + sep + desc;
else
fullDesc = desc;
setParent(parent_);
children = new ArrayList<MenuItem>();
}
public MenuItem() {
parent = null;
isRoot=true;
children = new ArrayList<MenuItem>();
price = new ArrayList<Price>();
}
public boolean isRoot(){return isRoot;}
public String getFullDesc(){
return fullDesc;
}
/**
* @return the price
*/
public List<Price> getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(List<Price> price) {
this.price = price;
}
/**
* @return the desc
*/
public String getDesc() {
return desc;
}
/**
* @param desc the desc to set
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* @return the key
*/
public char getKey() {
return key;
}
/**
* @param key the key to set
*/
public void setKey(char key) {
this.key = key;
}
public void addChild(MenuItem current) {
children.add(current);
}
public boolean hasChild(){
if (children == null)return false;
if(children.size() == 0)
return false;
else return true;
}
/**
* @return the parent
*/
public MenuItem getParent() {
return parent;
}
/**
* @return the Children
*/
public List<MenuItem> getChildren() {
return children;
}
public char[] getChildrenKeys(){
int i=0;
int size = children.size();
if (size > 0){
char[] keys = new char[size];
for(MenuItem item:children){
keys[i] = item.getKey();
i++;
}
return keys;
}
return null;
}
/**
* @param parent the parent to set
*/
public void setParent(MenuItem parent) {
this.parent = parent;
}
void print(String prefix, boolean isTail) {
String prices = "";
if (price != null){
for (Price oneprice : price){
prices += "/ " + oneprice.getDesc() + " (" + oneprice.getKey() + ") :" + oneprice.getPrice() ;
}
System.out.println(prefix + (isTail ? "└── " : "├── ") + desc + " " + key + prices + " -- " + fullDesc);
}
else{
System.out.println(prefix + (isTail ? "└── " : "├── ") + desc + " " + key + " -- " + fullDesc);
}
for (int i = 0; i < children.size() - 1; i++) {
children.get(i).print(prefix + (isTail ? " " : "│ "), false);
}
if (children.size() > 0) {
children.get(children.size() - 1).print(prefix + (isTail ?" " : "│ "), true);
}
}
public boolean hasPrice() {
if (price==null) return false;
return !price.isEmpty();
}
public char[] getPriceKeys() {
int i=0;
int size = price.size();
if (size > 0){
char[] keys = new char[size];
for(Price priceItem : price){
keys[i] = priceItem.getKey();
i++;
}
return keys;
}
return null;
}
public void selectPrice(char c)
{
for(Price priceItem : price)
{
if (priceItem.getKey() == c)
selectedPrice = priceItem;
}
}
public Price getSelectedPrice(){
return selectedPrice;
}
}
| UTF-8 | Java | 3,701 | java | MenuItem.java | Java | [] | null | [] | package fr.web_en_royans.lebarajus.POS.menu;
import java.util.ArrayList;
import java.util.List;
import charvax.swing.JLabel;
public class MenuItem {
private List<Price> price;
private Price selectedPrice;
private String desc;
private String fullDesc;
private String sep = " / ";
private char key;
private boolean isRoot;
private MenuItem parent;
private List<MenuItem> children;
public MenuItem(List<Price> price_, String desc_, char key_, MenuItem parent_){
price = price_;
desc = desc_;
key = key_;
isRoot=false;
if (!parent_.isRoot())
fullDesc = parent_.getFullDesc() + sep + desc;
else
fullDesc = desc;
setParent(parent_);
children = new ArrayList<MenuItem>();
}
public MenuItem() {
parent = null;
isRoot=true;
children = new ArrayList<MenuItem>();
price = new ArrayList<Price>();
}
public boolean isRoot(){return isRoot;}
public String getFullDesc(){
return fullDesc;
}
/**
* @return the price
*/
public List<Price> getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(List<Price> price) {
this.price = price;
}
/**
* @return the desc
*/
public String getDesc() {
return desc;
}
/**
* @param desc the desc to set
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* @return the key
*/
public char getKey() {
return key;
}
/**
* @param key the key to set
*/
public void setKey(char key) {
this.key = key;
}
public void addChild(MenuItem current) {
children.add(current);
}
public boolean hasChild(){
if (children == null)return false;
if(children.size() == 0)
return false;
else return true;
}
/**
* @return the parent
*/
public MenuItem getParent() {
return parent;
}
/**
* @return the Children
*/
public List<MenuItem> getChildren() {
return children;
}
public char[] getChildrenKeys(){
int i=0;
int size = children.size();
if (size > 0){
char[] keys = new char[size];
for(MenuItem item:children){
keys[i] = item.getKey();
i++;
}
return keys;
}
return null;
}
/**
* @param parent the parent to set
*/
public void setParent(MenuItem parent) {
this.parent = parent;
}
void print(String prefix, boolean isTail) {
String prices = "";
if (price != null){
for (Price oneprice : price){
prices += "/ " + oneprice.getDesc() + " (" + oneprice.getKey() + ") :" + oneprice.getPrice() ;
}
System.out.println(prefix + (isTail ? "└── " : "├── ") + desc + " " + key + prices + " -- " + fullDesc);
}
else{
System.out.println(prefix + (isTail ? "└── " : "├── ") + desc + " " + key + " -- " + fullDesc);
}
for (int i = 0; i < children.size() - 1; i++) {
children.get(i).print(prefix + (isTail ? " " : "│ "), false);
}
if (children.size() > 0) {
children.get(children.size() - 1).print(prefix + (isTail ?" " : "│ "), true);
}
}
public boolean hasPrice() {
if (price==null) return false;
return !price.isEmpty();
}
public char[] getPriceKeys() {
int i=0;
int size = price.size();
if (size > 0){
char[] keys = new char[size];
for(Price priceItem : price){
keys[i] = priceItem.getKey();
i++;
}
return keys;
}
return null;
}
public void selectPrice(char c)
{
for(Price priceItem : price)
{
if (priceItem.getKey() == c)
selectedPrice = priceItem;
}
}
public Price getSelectedPrice(){
return selectedPrice;
}
}
| 3,701 | 0.567656 | 0.565206 | 186 | 18.747313 | 19.891253 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.612903 | false | false | 3 |
800c7b8cc69e41665bc503e0aa9221645f0b2fe7 | 4,690,104,307,276 | 34d4e4a9be36a56758b890b6672d2aad0bd2bc0b | /src/main/java/com/syamantakm/grinder/AbstractHttpTestRunner.java | 9b142f5cbe157c00d3b4a6ada6f1ce3d78ba6872 | [] | no_license | syamantm/grinder-example | https://github.com/syamantm/grinder-example | 4a26fa9f31bf288169133a7b145b09566ea9af11 | 28711aaba6882fa4601155f9dafc375346103dee | refs/heads/master | 2021-01-22T12:08:40.560000 | 2013-07-14T18:14:12 | 2013-07-14T18:14:12 | 11,389,924 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.syamantakm.grinder;
import com.syamantakm.annotation.Resource;
import com.syamantakm.api.Request;
import com.syamantakm.api.RequestProvider;
import com.syamantakm.util.PropertyHolder;
import net.grinder.plugin.http.HTTPRequest;
import net.grinder.script.NotWrappableTypeException;
import net.grinder.script.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* @author Syamantak Mukhopadhyay
*/
public abstract class AbstractHttpTestRunner {
public static final Logger LOGGER = LoggerFactory.getLogger(AbstractHttpTestRunner.class);
@Resource
private RequestProvider requestProvider;
@Resource
private PropertyHolder propertyHolder;
private Map<Integer, HTTPRequest> tests;
public AbstractHttpTestRunner() {
LOGGER.info("AbstractHttpTestRunner :: constructor");
}
public void init() throws NotWrappableTypeException {
LOGGER.info("Default Constructor :: HttpTestRunner");
tests = new HashMap<>();
for(Request req : requestProvider.getRequests()) {
if(tests.containsKey(req.getRequestNumber())) {
LOGGER.warn(String.format("Duplicate request found , number : %s", req.getRequestNumber()));
}
HTTPRequest test = new HTTPRequest();
test = (HTTPRequest) new Test(req.getRequestNumber(), req.getName()).wrap(test);
tests.put(req.getRequestNumber(), test);
}
}
public abstract void call() throws Exception;
protected RequestProvider getRequestProvider() {
return requestProvider;
}
protected Map<Integer, HTTPRequest> getTests() {
return tests;
}
protected PropertyHolder getPropertyHolder() {
return propertyHolder;
}
}
| UTF-8 | Java | 1,813 | java | AbstractHttpTestRunner.java | Java | [
{
"context": "til.HashMap;\nimport java.util.Map;\n\n/**\n * @author Syamantak Mukhopadhyay\n */\npublic abstract class AbstractHttpTestRunner ",
"end": 470,
"score": 0.9998800158500671,
"start": 448,
"tag": "NAME",
"value": "Syamantak Mukhopadhyay"
}
] | null | [] | package com.syamantakm.grinder;
import com.syamantakm.annotation.Resource;
import com.syamantakm.api.Request;
import com.syamantakm.api.RequestProvider;
import com.syamantakm.util.PropertyHolder;
import net.grinder.plugin.http.HTTPRequest;
import net.grinder.script.NotWrappableTypeException;
import net.grinder.script.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* @author <NAME>
*/
public abstract class AbstractHttpTestRunner {
public static final Logger LOGGER = LoggerFactory.getLogger(AbstractHttpTestRunner.class);
@Resource
private RequestProvider requestProvider;
@Resource
private PropertyHolder propertyHolder;
private Map<Integer, HTTPRequest> tests;
public AbstractHttpTestRunner() {
LOGGER.info("AbstractHttpTestRunner :: constructor");
}
public void init() throws NotWrappableTypeException {
LOGGER.info("Default Constructor :: HttpTestRunner");
tests = new HashMap<>();
for(Request req : requestProvider.getRequests()) {
if(tests.containsKey(req.getRequestNumber())) {
LOGGER.warn(String.format("Duplicate request found , number : %s", req.getRequestNumber()));
}
HTTPRequest test = new HTTPRequest();
test = (HTTPRequest) new Test(req.getRequestNumber(), req.getName()).wrap(test);
tests.put(req.getRequestNumber(), test);
}
}
public abstract void call() throws Exception;
protected RequestProvider getRequestProvider() {
return requestProvider;
}
protected Map<Integer, HTTPRequest> getTests() {
return tests;
}
protected PropertyHolder getPropertyHolder() {
return propertyHolder;
}
}
| 1,797 | 0.703254 | 0.702151 | 61 | 28.721312 | 26.047958 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540984 | false | false | 3 |
a642e13d545ec2e676c75cfd5928c9b96151c045 | 6,347,961,681,049 | 26ee8e45c35c35305911da71f551b412aebc9556 | /src/MarkdownProcessor/Rules/BlockquoteRule.java | 6ef2b90e71eb33e09644e1eb031901109a6e6758 | [] | no_license | GPalado/MarkdownParser | https://github.com/GPalado/MarkdownParser | 40e8dd0d6c28746a1e2b55d05d69e4d5fcd3af5a | 4c4e2b8f9b64b6fdeab743ee7bddb2c0f4003757 | refs/heads/master | 2020-03-14T20:03:11.486000 | 2018-03-25T02:45:57 | 2018-03-25T02:45:57 | 131,770,297 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package MarkdownProcessor.Rules;
import MarkdownProcessor.Nodes.BlockquoteNode;
import MarkdownProcessor.Nodes.LineNode;
import MarkdownProcessor.Nodes.TextNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class BlockquoteRule implements StructureRule {
@Override
public TextNode applyStructure(Scanner s) {
List<TextNode> children = new ArrayList<>();
while(meetsCondition(s)){
s.reset();
s.next();
s.skip("\\s*");
children.add(new LineNode(ParserHelper.applyEffectRules(new Scanner(s.nextLine()))));
}
return new BlockquoteNode(children);
}
@Override
public boolean meetsCondition(Scanner s) {
s.useDelimiter("\r\n");
return s.hasNext(">{1}\\s{1}.*");
}
}
| UTF-8 | Java | 823 | java | BlockquoteRule.java | Java | [] | null | [] | package MarkdownProcessor.Rules;
import MarkdownProcessor.Nodes.BlockquoteNode;
import MarkdownProcessor.Nodes.LineNode;
import MarkdownProcessor.Nodes.TextNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class BlockquoteRule implements StructureRule {
@Override
public TextNode applyStructure(Scanner s) {
List<TextNode> children = new ArrayList<>();
while(meetsCondition(s)){
s.reset();
s.next();
s.skip("\\s*");
children.add(new LineNode(ParserHelper.applyEffectRules(new Scanner(s.nextLine()))));
}
return new BlockquoteNode(children);
}
@Override
public boolean meetsCondition(Scanner s) {
s.useDelimiter("\r\n");
return s.hasNext(">{1}\\s{1}.*");
}
}
| 823 | 0.657351 | 0.654921 | 30 | 26.433332 | 21.879494 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
e850ac997d1417522157867fbe9a8545a5802f67 | 12,000,138,642,621 | e1d0d103feca5bce1caad758107d7d024577957a | /leetcodeExcecise/src/main/java/leetcode/Test21.java | 569a6dd1e57572a6007ef3fba368c6c65d9d50df | [] | no_license | zhongguodiyidao/leetCode | https://github.com/zhongguodiyidao/leetCode | 053b577dab37cd8b95e39597e47fe818cf439dbf | 88187d13c493e472b984491535a2399b18730989 | refs/heads/master | 2023-01-15T09:40:45.690000 | 2020-11-22T02:36:08 | 2020-11-22T02:36:08 | 307,652,830 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode;
public class Test21 {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = new ListNode();
ListNode zhen = result;
while (l1!=null && l2!=null){
if(l1.val <= l2.val){
result.next = new ListNode(l1.val);
l1 = l1.next;
result = result.next;
}else{
result.next = new ListNode(l2.val);
l2 = l2.next;
result = result.next;
}
}
if(l1!=null){
result.next = l1;
}
if(l2!=null){
result.next = l2;
}
return zhen.next;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(1,new ListNode(2,new ListNode(4)));
ListNode l2 = new ListNode(1,new ListNode(3,new ListNode(4)));
ListNode listNode = new Test21().mergeTwoLists(l1, l2);
while (listNode!=null){
System.out.println(listNode.val);
listNode = listNode.next;
}
}
}
| UTF-8 | Java | 1,074 | java | Test21.java | Java | [] | null | [] | package leetcode;
public class Test21 {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = new ListNode();
ListNode zhen = result;
while (l1!=null && l2!=null){
if(l1.val <= l2.val){
result.next = new ListNode(l1.val);
l1 = l1.next;
result = result.next;
}else{
result.next = new ListNode(l2.val);
l2 = l2.next;
result = result.next;
}
}
if(l1!=null){
result.next = l1;
}
if(l2!=null){
result.next = l2;
}
return zhen.next;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(1,new ListNode(2,new ListNode(4)));
ListNode l2 = new ListNode(1,new ListNode(3,new ListNode(4)));
ListNode listNode = new Test21().mergeTwoLists(l1, l2);
while (listNode!=null){
System.out.println(listNode.val);
listNode = listNode.next;
}
}
}
| 1,074 | 0.5 | 0.472067 | 36 | 28.833334 | 19.264965 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false | 3 |
bbfa89e7d4842f8925280501ea85de4e571390c8 | 12,000,138,641,777 | 772f61d056e2c7ace98211b2a8525e48b4741ffa | /R04-01-Rot-KLargestQuickSelectFloor-environment/src/main/java/problems/FloorBinarySearchImpl.java | 39f78ae8216acf00a18705db1e73f1a989ff0646 | [] | no_license | caetanobca/LEDA | https://github.com/caetanobca/LEDA | dc437ee11d6767bf58101a5b4e52c51c98f5b748 | 50b9a91866ff97835490416825084d21a3d6e0a2 | refs/heads/main | 2023-02-10T21:17:46.452000 | 2021-01-01T17:21:04 | 2021-01-01T17:21:04 | 318,640,450 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package problems;
import util.Util;
public class FloorBinarySearchImpl implements Floor {
Util myUtil = new Util();
@Override
public Integer floor(Integer[] array, Integer x) {
this.sort(array);
int indiceFloor = this.buscaBinaria(array, x, 0, array.length - 1);
if (indiceFloor >= 0){
return array[indiceFloor];
}else {
return null;
}
}
private Integer buscaBinaria(Integer[] array, Integer x, int left, int right) {
if (left <= right) {
int meio = (left + right) / 2;
if (x == array[meio]) {
return meio;
} else if (x < array[meio] && meio > 0) {
if (x > array[meio - 1]) {
return meio - 1;
}
return buscaBinaria(array, x, left, meio - 1);
} else {
if (meio == array.length - 1) {
return meio;
}
return buscaBinaria(array, x, meio + 1, right);
}
}
return -1;
}
/**
* Metodo que ordena o array a partir do algoritmo heapSort que tem custo de O(n.log n) e é in-place
* @param array
*/
private void sort(Integer[] array) {
int meio = array.length / 2;
for (int i = meio - 1; i >= 0; i--)
heapify(array, array.length, i);
for (int j = array.length - 1; j > 0; j--){
myUtil.swap(array, 0, j);
heapify(array, j, 0);
}
}
void heapify(Integer[] array, int n, int i) {
int indiceMaior = i;
int folhaEsquerda = 2 * i + 1;
int folhaDireita = 2 * i + 2;
if (folhaEsquerda < n && array[folhaEsquerda] > array[indiceMaior]){
indiceMaior = folhaEsquerda;
}
if (folhaDireita < n && array[folhaDireita] > array[indiceMaior]){
indiceMaior = folhaDireita;
}
myUtil.swap(array, i, indiceMaior);
if (indiceMaior != i){
heapify(array, n, indiceMaior);
}
}
}
| UTF-8 | Java | 1,698 | java | FloorBinarySearchImpl.java | Java | [] | null | [] | package problems;
import util.Util;
public class FloorBinarySearchImpl implements Floor {
Util myUtil = new Util();
@Override
public Integer floor(Integer[] array, Integer x) {
this.sort(array);
int indiceFloor = this.buscaBinaria(array, x, 0, array.length - 1);
if (indiceFloor >= 0){
return array[indiceFloor];
}else {
return null;
}
}
private Integer buscaBinaria(Integer[] array, Integer x, int left, int right) {
if (left <= right) {
int meio = (left + right) / 2;
if (x == array[meio]) {
return meio;
} else if (x < array[meio] && meio > 0) {
if (x > array[meio - 1]) {
return meio - 1;
}
return buscaBinaria(array, x, left, meio - 1);
} else {
if (meio == array.length - 1) {
return meio;
}
return buscaBinaria(array, x, meio + 1, right);
}
}
return -1;
}
/**
* Metodo que ordena o array a partir do algoritmo heapSort que tem custo de O(n.log n) e é in-place
* @param array
*/
private void sort(Integer[] array) {
int meio = array.length / 2;
for (int i = meio - 1; i >= 0; i--)
heapify(array, array.length, i);
for (int j = array.length - 1; j > 0; j--){
myUtil.swap(array, 0, j);
heapify(array, j, 0);
}
}
void heapify(Integer[] array, int n, int i) {
int indiceMaior = i;
int folhaEsquerda = 2 * i + 1;
int folhaDireita = 2 * i + 2;
if (folhaEsquerda < n && array[folhaEsquerda] > array[indiceMaior]){
indiceMaior = folhaEsquerda;
}
if (folhaDireita < n && array[folhaDireita] > array[indiceMaior]){
indiceMaior = folhaDireita;
}
myUtil.swap(array, i, indiceMaior);
if (indiceMaior != i){
heapify(array, n, indiceMaior);
}
}
}
| 1,698 | 0.606364 | 0.5934 | 83 | 19.445784 | 21.740669 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.277108 | false | false | 3 |
199b3ba4f7884235cc4f7a1b6cb7c1a828278277 | 21,973,052,715,690 | eb754930eedce86f637877a90577b10f895a4f87 | /eclipse-collections/src/main/java/com/fasterxml/jackson/datatype/eclipsecollections/ser/PrimitiveIterableSerializer.java | a02b4b6930c1e4c24bc135ca07066cf94f6addfb | [
"Apache-2.0"
] | permissive | FasterXML/jackson-datatypes-collections | https://github.com/FasterXML/jackson-datatypes-collections | df7b82d6d4dd615238b0c7ee6a54e49112b7d64a | 909bc2e71b6fd4328c2a8033d4a00f3d8cd8152a | refs/heads/2.16 | 2023-09-02T06:50:29.017000 | 2023-06-06T13:26:53 | 2023-06-06T13:26:53 | 50,007,393 | 74 | 58 | Apache-2.0 | false | 2023-06-07T22:50:42 | 2016-01-20T05:39:06 | 2023-06-06T02:58:42 | 2023-06-06T13:30:34 | 2,988 | 70 | 50 | 11 | Java | false | false | package com.fasterxml.jackson.datatype.eclipsecollections.ser;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.WritableTypeId;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.ContainerSerializer;
import java.io.IOException;
import org.eclipse.collections.api.PrimitiveIterable;
public abstract class PrimitiveIterableSerializer<C extends PrimitiveIterable> extends ContainerSerializer<C> {
protected final JavaType _elementType;
protected final BeanProperty _property;
protected final Boolean _unwrapSingle;
public PrimitiveIterableSerializer(
Class<C> type, JavaType elementType,
BeanProperty property, Boolean unwrapSingle
) {
super(type);
_elementType = elementType;
_property = property;
_unwrapSingle = unwrapSingle;
}
protected abstract PrimitiveIterableSerializer<C> withResolved(BeanProperty property, Boolean unwrapSingle);
@Override
public boolean isEmpty(SerializerProvider prov, C value) {
return value.isEmpty();
}
@Override
public JavaType getContentType() {
return _elementType;
}
@Override
public JsonSerializer<?> getContentSerializer() {
return null;
}
@Override
protected ContainerSerializer<?> _withValueTypeSerializer(TypeSerializer vts) {
// no type info for primitives
return this;
}
@Override
public boolean hasSingleElement(C value) {
if (value != null) {
return value.size() == 1;
}
return false;
}
@Override
public final void serialize(C value, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (((_unwrapSingle == null) &&
provider.isEnabled(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED))
|| (Boolean.TRUE.equals(_unwrapSingle))) {
if (hasSingleElement(value)) {
serializeContents(value, gen);
return;
}
}
gen.writeStartArray();
serializeContents(value, gen);
gen.writeEndArray();
}
@Override
public void serializeWithType(C value, JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer)
throws IOException {
g.setCurrentValue(value);
WritableTypeId typeIdDef = typeSer.writeTypePrefix(g, typeSer.typeId(value, JsonToken.START_ARRAY));
serializeContents(value, g);
typeSer.writeTypeSuffix(g, typeIdDef);
}
protected abstract void serializeContents(C value, JsonGenerator gen) throws IOException;
}
| UTF-8 | Java | 3,012 | java | PrimitiveIterableSerializer.java | Java | [] | null | [] | package com.fasterxml.jackson.datatype.eclipsecollections.ser;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.WritableTypeId;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.ContainerSerializer;
import java.io.IOException;
import org.eclipse.collections.api.PrimitiveIterable;
public abstract class PrimitiveIterableSerializer<C extends PrimitiveIterable> extends ContainerSerializer<C> {
protected final JavaType _elementType;
protected final BeanProperty _property;
protected final Boolean _unwrapSingle;
public PrimitiveIterableSerializer(
Class<C> type, JavaType elementType,
BeanProperty property, Boolean unwrapSingle
) {
super(type);
_elementType = elementType;
_property = property;
_unwrapSingle = unwrapSingle;
}
protected abstract PrimitiveIterableSerializer<C> withResolved(BeanProperty property, Boolean unwrapSingle);
@Override
public boolean isEmpty(SerializerProvider prov, C value) {
return value.isEmpty();
}
@Override
public JavaType getContentType() {
return _elementType;
}
@Override
public JsonSerializer<?> getContentSerializer() {
return null;
}
@Override
protected ContainerSerializer<?> _withValueTypeSerializer(TypeSerializer vts) {
// no type info for primitives
return this;
}
@Override
public boolean hasSingleElement(C value) {
if (value != null) {
return value.size() == 1;
}
return false;
}
@Override
public final void serialize(C value, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (((_unwrapSingle == null) &&
provider.isEnabled(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED))
|| (Boolean.TRUE.equals(_unwrapSingle))) {
if (hasSingleElement(value)) {
serializeContents(value, gen);
return;
}
}
gen.writeStartArray();
serializeContents(value, gen);
gen.writeEndArray();
}
@Override
public void serializeWithType(C value, JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer)
throws IOException {
g.setCurrentValue(value);
WritableTypeId typeIdDef = typeSer.writeTypePrefix(g, typeSer.typeId(value, JsonToken.START_ARRAY));
serializeContents(value, g);
typeSer.writeTypeSuffix(g, typeIdDef);
}
protected abstract void serializeContents(C value, JsonGenerator gen) throws IOException;
}
| 3,012 | 0.703519 | 0.703187 | 87 | 33.620689 | 29.315659 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.643678 | false | false | 3 |
9e1487bc9442d47dd12f38db739d41b978148b4b | 29,403,346,138,919 | 1f77f0e1172895a23f6f59d194b065425a48d7d2 | /pubsearch/src/hu/juranyi/zsolt/pubsearch/gui/window/MainWindow.java | 7668447747b0ee32691927f569c3c77457e7830e | [] | no_license | juzraai/PubSearch | https://github.com/juzraai/PubSearch | 359cc2e3f6357fbece8db00d3d27aa6e8082b636 | bbeba6130bff5129a2aae915dd731df2bdd585f5 | refs/heads/master | 2021-01-13T02:36:54.033000 | 2013-02-17T11:32:35 | 2013-02-17T11:32:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hu.juranyi.zsolt.pubsearch.gui.window;
import hu.juranyi.zsolt.pubsearch.gui.tab.MainTab;
import javafx.scene.Scene;
import javafx.scene.control.TabPane;
import javafx.stage.WindowEvent;
/**
* Main window of PubSearch.
*
* @author Jurányi Zsolt (JUZRAAI.ELTE)
*/
public class MainWindow extends AWindow {
public final ConfigWindow configWindow = new ConfigWindow(this);
private final MainTab mainTab = new MainTab(this);
private TabPane tabs = new TabPane();
public MainWindow() {
super("PubSearch", true, false);
tabs.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
tabs.setTabMinWidth(50);
tabs.setTabMaxWidth(200);
tabs.getTabs().add(mainTab);
Scene scene = new Scene(tabs, 640, 450);
setScene(scene);
setCSS();
}
/**
* Extends AWindow's onShownAction with focusing author search field.
* @param event Window event object which triggered this method.
*/
@Override
protected void onShownAction(WindowEvent event) {
super.onShownAction(event);
mainTab.focusAuthorField();
}
public TabPane getTabPane() {
return tabs;
}
} | UTF-8 | Java | 1,197 | java | MainWindow.java | Java | [
{
"context": "t;\n\n/**\n * Main window of PubSearch.\n *\n * @author Jurányi Zsolt (JUZRAAI.ELTE)\n */\npublic class MainWindow extend",
"end": 257,
"score": 0.9998865723609924,
"start": 244,
"tag": "NAME",
"value": "Jurányi Zsolt"
}
] | null | [] | package hu.juranyi.zsolt.pubsearch.gui.window;
import hu.juranyi.zsolt.pubsearch.gui.tab.MainTab;
import javafx.scene.Scene;
import javafx.scene.control.TabPane;
import javafx.stage.WindowEvent;
/**
* Main window of PubSearch.
*
* @author <NAME> (JUZRAAI.ELTE)
*/
public class MainWindow extends AWindow {
public final ConfigWindow configWindow = new ConfigWindow(this);
private final MainTab mainTab = new MainTab(this);
private TabPane tabs = new TabPane();
public MainWindow() {
super("PubSearch", true, false);
tabs.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
tabs.setTabMinWidth(50);
tabs.setTabMaxWidth(200);
tabs.getTabs().add(mainTab);
Scene scene = new Scene(tabs, 640, 450);
setScene(scene);
setCSS();
}
/**
* Extends AWindow's onShownAction with focusing author search field.
* @param event Window event object which triggered this method.
*/
@Override
protected void onShownAction(WindowEvent event) {
super.onShownAction(event);
mainTab.focusAuthorField();
}
public TabPane getTabPane() {
return tabs;
}
} | 1,189 | 0.674749 | 0.665552 | 45 | 25.6 | 22.020596 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511111 | false | false | 3 |
628ba3b1e6b3ef64b212536d24dabf71bb2cca2c | 30,133,490,575,011 | 6cba627401390948b591dd449b95e016a35e21af | /src/main/java/org/wcci/blog/controllers/ClientController.java | 3f0593cbec75dd05ea69ff4f0eff392a792b76df | [] | no_license | 2020-Spring-Cohort/full-stack-blog-NightingaleMedia | https://github.com/2020-Spring-Cohort/full-stack-blog-NightingaleMedia | 47d7ef2dc84402baf2d59753b7a8488a96277bf2 | 4e02d04dda4d735aaad75855e804600de3139e84 | refs/heads/master | 2021-01-08T22:42:27.483000 | 2020-03-02T04:24:18 | 2020-03-02T04:24:18 | 242,164,331 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.wcci.blog.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.wcci.blog.models.Client;
import org.wcci.blog.models.Post;
import org.wcci.blog.storage.ClientStorage;
import org.wcci.blog.storage.PostStorage;
@Controller
public class ClientController {
@Autowired
private ClientStorage clientStorage;
@Autowired
private PostStorage postStorage;
@GetMapping("/clients")
public String displayAllClients(Model model){
model.addAttribute("clients", clientStorage.findAll());
return "all-clients";
}
@GetMapping("/clients/{clientTitle}")
public String displayPostsForClient(Model model,
@PathVariable String clientTitle){
Client client = clientStorage.findByClientName(clientTitle).get();
model.addAttribute("clientInfo", client);
Iterable <Post> posts = postStorage.findPostsByClient(client);
model.addAttribute("postInfo", posts);
return "single-client";
}
}
| UTF-8 | Java | 1,315 | java | ClientController.java | Java | [] | null | [] | package org.wcci.blog.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.wcci.blog.models.Client;
import org.wcci.blog.models.Post;
import org.wcci.blog.storage.ClientStorage;
import org.wcci.blog.storage.PostStorage;
@Controller
public class ClientController {
@Autowired
private ClientStorage clientStorage;
@Autowired
private PostStorage postStorage;
@GetMapping("/clients")
public String displayAllClients(Model model){
model.addAttribute("clients", clientStorage.findAll());
return "all-clients";
}
@GetMapping("/clients/{clientTitle}")
public String displayPostsForClient(Model model,
@PathVariable String clientTitle){
Client client = clientStorage.findByClientName(clientTitle).get();
model.addAttribute("clientInfo", client);
Iterable <Post> posts = postStorage.findPostsByClient(client);
model.addAttribute("postInfo", posts);
return "single-client";
}
}
| 1,315 | 0.734601 | 0.734601 | 40 | 31.875 | 23.866491 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
33e3fdf2627abeb05cd5e9210fefc9dccc83a733 | 24,352,464,588,333 | e9df086c7d575e4047b407a34fd4d2deade82389 | /IRMS-war/src/java/ShoppingMall/RevenueManagedBean.java | f0fee02bf328042c021df073a136d667d75da26d | [] | no_license | seuen/IRMS | https://github.com/seuen/IRMS | c156a8d75b389676cec1f647bab4f3f051f6e0ee | 1f79ec8c7f4bf6382bf1df493b5f136ca6c39ddc | refs/heads/master | 2021-01-10T04:16:17.803000 | 2015-11-09T17:53:42 | 2015-11-09T17:53:42 | 45,855,841 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ShoppingMall;
import ShoppingMall.entity.Contract;
import ShoppingMall.entity.DetailShopOrder;
import ShoppingMall.entity.Shop;
import ShoppingMall.session.ShopRevenueManagementSessionBeanLocal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
/**
*
* @author user
*/
@ManagedBean
@ViewScoped
public class RevenueManagedBean {
@EJB
ShopRevenueManagementSessionBeanLocal srmsbl;
private List<Contract> activeContracts = new ArrayList();
private List<DetailShopOrder> dso = new ArrayList();
private Contract viewContract;
private Date start;
private Date end;
/**
* Creates a new instance of RevenueManagedBean
*/
public RevenueManagedBean() {
}
@PostConstruct
public void init() {
if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("viewContract") != null) {
viewContract = (Contract) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("viewContract");
}
if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("start") != null) {
start = (Date) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("start");
System.out.println("start:"+start);
}
if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("end") != null) {
end = (Date) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("end");
System.out.println("end:"+end);
}
}
public void navigateActiveShops(ActionEvent event) throws IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect("activeContracts.xhtml");
}
public void navigateDetailOrderRevenue(ActionEvent event) throws IOException {
if (start == null || end == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Please specify start date and end date for reporting.", ""));
} else {
viewContract = (Contract) event.getComponent().getAttributes().get("viewContract");
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("viewContract", viewContract);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("start", start);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("end", end);
FacesContext.getCurrentInstance().getExternalContext().redirect("detailOrderRevenue.xhtml");
}
}
public void navigateCurMonthDOR(ActionEvent event) throws IOException {
viewContract = (Contract) event.getComponent().getAttributes().get("viewContract");
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("viewContract", viewContract);
Calendar c = Calendar.getInstance();
end = c.getTime();
System.out.println(end);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("end", end);
c.set(Calendar.DATE, 1);
start = c.getTime();
System.out.println(start);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("start", start);
FacesContext.getCurrentInstance().getExternalContext().redirect("detailOrderRevenue.xhtml");
}
public void navigateCurYearDOR(ActionEvent event) throws IOException {
viewContract = (Contract) event.getComponent().getAttributes().get("viewContract");
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("viewContract", viewContract);
Calendar c = Calendar.getInstance();
end = c.getTime();
System.out.println(end);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("end", end);
c.set(Calendar.MONTH, 0);
c.set(Calendar.DATE, 1);
start = c.getTime();
System.out.println(start);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("start", start);
FacesContext.getCurrentInstance().getExternalContext().redirect("detailOrderRevenue.xhtml");
}
public float calculateMonthlyRevenue(Contract contract) {
Shop shop = contract.getShop();
// System.out.println("shopid calculateMonthlyRevenue: "+shop.getShopId());
Calendar c = Calendar.getInstance();
Date endDate = c.getTime();
// c.set(Calendar.MONTH, 0);
c.set(Calendar.DATE, 1);
Date startDate = c.getTime();
List<DetailShopOrder> list = srmsbl.getDetailShopOrders(shop.getShopId(), startDate, endDate);
float revenue = srmsbl.calculateTotalRevenue(list);
return revenue;
}
public float calculateListRevenues() {
return srmsbl.calculateTotalRevenue(dso);
}
/**
* @return the activeShops
*/
public List<Contract> getActiveContracts() {
activeContracts = srmsbl.getAllActiveContracts();
return activeContracts;
}
/**
* @param activeShops the activeShops to set
*/
public void setActiveContracts(List<Contract> activeShops) {
this.activeContracts = activeShops;
}
/**
* @return the viewShop
*/
public Contract getViewContract() {
return viewContract;
}
/**
* @param viewShop the viewShop to set
*/
public void setViewContract(Contract viewContract) {
this.viewContract = viewContract;
}
/**
* @return the start
*/
public Date getStart() {
return start;
}
/**
* @param start the start to set
*/
public void setStart(Date start) {
this.start = start;
}
/**
* @return the end
*/
public Date getEnd() {
return end;
}
/**
* @param end the end to set
*/
public void setEnd(Date end) {
this.end = end;
}
/**
* @return the dso
*/
public List<DetailShopOrder> getDso() {
dso = srmsbl.getDetailShopOrders(viewContract.getShop().getShopId(), start, end);
return dso;
}
/**
* @param dso the dso to set
*/
public void setDso(List<DetailShopOrder> dso) {
this.dso = dso;
}
}
| UTF-8 | Java | 6,929 | java | RevenueManagedBean.java | Java | [
{
"context": "ax.faces.event.ActionEvent;\r\n\r\n/**\r\n *\r\n * @author user\r\n */\r\n@ManagedBean\r\n@ViewScoped\r\npublic class Reven",
"end": 739,
"score": 0.9838385581970215,
"start": 735,
"tag": "USERNAME",
"value": "user"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ShoppingMall;
import ShoppingMall.entity.Contract;
import ShoppingMall.entity.DetailShopOrder;
import ShoppingMall.entity.Shop;
import ShoppingMall.session.ShopRevenueManagementSessionBeanLocal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
/**
*
* @author user
*/
@ManagedBean
@ViewScoped
public class RevenueManagedBean {
@EJB
ShopRevenueManagementSessionBeanLocal srmsbl;
private List<Contract> activeContracts = new ArrayList();
private List<DetailShopOrder> dso = new ArrayList();
private Contract viewContract;
private Date start;
private Date end;
/**
* Creates a new instance of RevenueManagedBean
*/
public RevenueManagedBean() {
}
@PostConstruct
public void init() {
if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("viewContract") != null) {
viewContract = (Contract) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("viewContract");
}
if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("start") != null) {
start = (Date) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("start");
System.out.println("start:"+start);
}
if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("end") != null) {
end = (Date) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("end");
System.out.println("end:"+end);
}
}
public void navigateActiveShops(ActionEvent event) throws IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect("activeContracts.xhtml");
}
public void navigateDetailOrderRevenue(ActionEvent event) throws IOException {
if (start == null || end == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Please specify start date and end date for reporting.", ""));
} else {
viewContract = (Contract) event.getComponent().getAttributes().get("viewContract");
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("viewContract", viewContract);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("start", start);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("end", end);
FacesContext.getCurrentInstance().getExternalContext().redirect("detailOrderRevenue.xhtml");
}
}
public void navigateCurMonthDOR(ActionEvent event) throws IOException {
viewContract = (Contract) event.getComponent().getAttributes().get("viewContract");
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("viewContract", viewContract);
Calendar c = Calendar.getInstance();
end = c.getTime();
System.out.println(end);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("end", end);
c.set(Calendar.DATE, 1);
start = c.getTime();
System.out.println(start);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("start", start);
FacesContext.getCurrentInstance().getExternalContext().redirect("detailOrderRevenue.xhtml");
}
public void navigateCurYearDOR(ActionEvent event) throws IOException {
viewContract = (Contract) event.getComponent().getAttributes().get("viewContract");
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("viewContract", viewContract);
Calendar c = Calendar.getInstance();
end = c.getTime();
System.out.println(end);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("end", end);
c.set(Calendar.MONTH, 0);
c.set(Calendar.DATE, 1);
start = c.getTime();
System.out.println(start);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("start", start);
FacesContext.getCurrentInstance().getExternalContext().redirect("detailOrderRevenue.xhtml");
}
public float calculateMonthlyRevenue(Contract contract) {
Shop shop = contract.getShop();
// System.out.println("shopid calculateMonthlyRevenue: "+shop.getShopId());
Calendar c = Calendar.getInstance();
Date endDate = c.getTime();
// c.set(Calendar.MONTH, 0);
c.set(Calendar.DATE, 1);
Date startDate = c.getTime();
List<DetailShopOrder> list = srmsbl.getDetailShopOrders(shop.getShopId(), startDate, endDate);
float revenue = srmsbl.calculateTotalRevenue(list);
return revenue;
}
public float calculateListRevenues() {
return srmsbl.calculateTotalRevenue(dso);
}
/**
* @return the activeShops
*/
public List<Contract> getActiveContracts() {
activeContracts = srmsbl.getAllActiveContracts();
return activeContracts;
}
/**
* @param activeShops the activeShops to set
*/
public void setActiveContracts(List<Contract> activeShops) {
this.activeContracts = activeShops;
}
/**
* @return the viewShop
*/
public Contract getViewContract() {
return viewContract;
}
/**
* @param viewShop the viewShop to set
*/
public void setViewContract(Contract viewContract) {
this.viewContract = viewContract;
}
/**
* @return the start
*/
public Date getStart() {
return start;
}
/**
* @param start the start to set
*/
public void setStart(Date start) {
this.start = start;
}
/**
* @return the end
*/
public Date getEnd() {
return end;
}
/**
* @param end the end to set
*/
public void setEnd(Date end) {
this.end = end;
}
/**
* @return the dso
*/
public List<DetailShopOrder> getDso() {
dso = srmsbl.getDetailShopOrders(viewContract.getShop().getShopId(), start, end);
return dso;
}
/**
* @param dso the dso to set
*/
public void setDso(List<DetailShopOrder> dso) {
this.dso = dso;
}
}
| 6,929 | 0.648723 | 0.648001 | 194 | 33.716496 | 33.871758 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.546392 | false | false | 3 |
1600f72b90d3839d447f29973934bb3cbac9b717 | 249,108,118,941 | fe22507aea892e56ccfcf355f5cf495ccbb5fbbe | /app/src/main/java/com/korsun/inspiration/BlogSingleActivity.java | d2178ffcc3d196697c7e5f32404d2892ebbb4669 | [] | no_license | devKors/Inspiration | https://github.com/devKors/Inspiration | 42003eeed266747036a4243908005c6f53953c61 | d3df17d213534f253244628fe9b9c773cdbbe3ff | refs/heads/master | 2017-05-10T14:08:51.135000 | 2017-02-22T10:46:08 | 2017-02-22T10:46:08 | 82,575,742 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.korsun.inspiration;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
public class BlogSingleActivity extends AppCompatActivity {
private ImageView mBlogSingleImage;
private TextView mBlogSingleTitle;
private TextView mBlogSingleDescription;
private Button mBlogSingleRemove;
private String mPostKey;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog_single);
mPostKey = getIntent().getExtras().get("postKey").toString();
mBlogSingleImage = (ImageView) findViewById(R.id.single_blog_image);
mBlogSingleTitle = (TextView) findViewById(R.id.single_blog_title);
mBlogSingleDescription = (TextView) findViewById(R.id.single_blog_description);
mBlogSingleRemove = (Button) findViewById(R.id.single_blog_remove);
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabase.child(mPostKey).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String postTitle = (String) dataSnapshot.child("title").getValue();
String postDescription = (String) dataSnapshot.child("description").getValue();
String postImage = (String) dataSnapshot.child("image").getValue();
String postUId = (String) dataSnapshot.child("uId").getValue();
mBlogSingleTitle.setText(postTitle);
mBlogSingleDescription.setText(postDescription);
Picasso.with(BlogSingleActivity.this).load(postImage).into(mBlogSingleImage);
if (mAuth.getCurrentUser().getUid().equals(postUId)) {
mBlogSingleRemove.setVisibility(View.VISIBLE);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mBlogSingleRemove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDatabase.child(mPostKey).removeValue();
Intent mainIntent = new Intent(BlogSingleActivity.this, MainActivity.class);
startActivity(mainIntent);
}
});
}
}
| UTF-8 | Java | 3,042 | java | BlogSingleActivity.java | Java | [] | null | [] | package com.korsun.inspiration;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
public class BlogSingleActivity extends AppCompatActivity {
private ImageView mBlogSingleImage;
private TextView mBlogSingleTitle;
private TextView mBlogSingleDescription;
private Button mBlogSingleRemove;
private String mPostKey;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog_single);
mPostKey = getIntent().getExtras().get("postKey").toString();
mBlogSingleImage = (ImageView) findViewById(R.id.single_blog_image);
mBlogSingleTitle = (TextView) findViewById(R.id.single_blog_title);
mBlogSingleDescription = (TextView) findViewById(R.id.single_blog_description);
mBlogSingleRemove = (Button) findViewById(R.id.single_blog_remove);
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabase.child(mPostKey).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String postTitle = (String) dataSnapshot.child("title").getValue();
String postDescription = (String) dataSnapshot.child("description").getValue();
String postImage = (String) dataSnapshot.child("image").getValue();
String postUId = (String) dataSnapshot.child("uId").getValue();
mBlogSingleTitle.setText(postTitle);
mBlogSingleDescription.setText(postDescription);
Picasso.with(BlogSingleActivity.this).load(postImage).into(mBlogSingleImage);
if (mAuth.getCurrentUser().getUid().equals(postUId)) {
mBlogSingleRemove.setVisibility(View.VISIBLE);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mBlogSingleRemove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDatabase.child(mPostKey).removeValue();
Intent mainIntent = new Intent(BlogSingleActivity.this, MainActivity.class);
startActivity(mainIntent);
}
});
}
}
| 3,042 | 0.691979 | 0.69165 | 79 | 37.506329 | 28.865412 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.582278 | false | false | 3 |
a83d0a105b5511ee9f70a0280b8e5aef4331ff03 | 17,806,934,435,264 | dae3a5f4e5e66350cd1bda323d4981e7d5eec61c | /src/com/urise/webapp/utill/DateUtill.java | 21af02560cd24bddc36f345f4ea7245c8dc2ed16 | [] | no_license | alex-shostka/basejava | https://github.com/alex-shostka/basejava | b94a959b50fa42a6603d80c3afc0e94bffc3986f | c418db4c4f4d8619f6c41143b350ae89848dd87e | refs/heads/master | 2022-12-13T08:23:02.701000 | 2020-09-08T08:15:55 | 2020-09-08T08:15:55 | 199,700,920 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.urise.webapp.utill;
import java.time.LocalDate;
import java.time.Month;
public class DateUtill {
public static LocalDate of(int year, Month month) {
return LocalDate.of(year, month, 1);
}
}
| UTF-8 | Java | 220 | java | DateUtill.java | Java | [] | null | [] | package com.urise.webapp.utill;
import java.time.LocalDate;
import java.time.Month;
public class DateUtill {
public static LocalDate of(int year, Month month) {
return LocalDate.of(year, month, 1);
}
}
| 220 | 0.704545 | 0.7 | 10 | 21 | 18.363007 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 3 |
cafc5f9a7dc891e63eedd2dd2adddd4366fba0c2 | 26,491,358,300,103 | f6b8f9dac0b7fefa47d67ae4c94100f1d40e71b2 | /IndexEntry.java | f7de2a1adb317a84dc6ed5580739b0d6794b51e3 | [] | no_license | HeadJar/DESCA-2 | https://github.com/HeadJar/DESCA-2 | 047b4da26fb58dee7b6f8b3130042425082b43d0 | 9398bf31d977d9e8f241986cf33bf7fe609ab27d | refs/heads/master | 2019-07-02T00:38:36.569000 | 2017-11-09T14:55:01 | 2017-11-09T14:55:01 | 102,744,034 | 0 | 0 | null | false | 2017-11-09T14:54:30 | 2017-09-07T14:02:15 | 2017-09-07T14:19:08 | 2017-11-09T14:52:57 | 4 | 0 | 0 | 2 | Java | false | null | import java.util.ArrayList;
public class IndexEntry implements Comparable<IndexEntry>{
private String word;
private ArrayList<Integer> numsList;
public IndexEntry(String s)
{
word = s.toUpperCase();
numsList = new ArrayList<Integer>();
}
public void add(int num)
{
if(!numsList.contains(num))
numsList.add(num);
}
public String getWord()
{
return word;
}
public String toString()
{
String s = word + " ";
for(Integer i : numsList)
s += i + ", ";
s = s.substring(0, s.length()-2);
return s;
}
public int compareTo(IndexEntry entry)
{
return word.compareTo(entry.toString());
}
}
| UTF-8 | Java | 783 | java | IndexEntry.java | Java | [] | null | [] | import java.util.ArrayList;
public class IndexEntry implements Comparable<IndexEntry>{
private String word;
private ArrayList<Integer> numsList;
public IndexEntry(String s)
{
word = s.toUpperCase();
numsList = new ArrayList<Integer>();
}
public void add(int num)
{
if(!numsList.contains(num))
numsList.add(num);
}
public String getWord()
{
return word;
}
public String toString()
{
String s = word + " ";
for(Integer i : numsList)
s += i + ", ";
s = s.substring(0, s.length()-2);
return s;
}
public int compareTo(IndexEntry entry)
{
return word.compareTo(entry.toString());
}
}
| 783 | 0.530013 | 0.527458 | 36 | 20.75 | 16.323765 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527778 | false | false | 3 |
1d54b2e5dde5a1b54670aa083561c52f8e19d629 | 8,624,294,349,876 | 3f4cd33ae5f02f532f78649d3fba7e35abf363dc | /BFS.java | b9c53d630a2a8cc45ab6043d257877bdcbe93d77 | [] | no_license | therealshabi/Practice-codes | https://github.com/therealshabi/Practice-codes | d31b9d9073ced11f6a8d199689acc3b584d5f816 | 1972cbfe854d2900db62d7db74bf960762ab5c24 | refs/heads/master | 2021-01-19T16:01:30.859000 | 2017-09-13T16:16:51 | 2017-09-13T16:16:51 | 100,981,399 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class BFS
{
int n=5;
LinkedList<Integer> adj[];
public BFS()
{
adj=new LinkedList[n];
for(int i=0;i<n;i++)
{
adj[i]=new LinkedList();
}
}
public void add(int s, int d)
{
adj[s].add(d);
}
public void traversal(int start)
{
int j;
LinkedList<Integer> queue = new LinkedList<Integer>();
boolean visit[]=new boolean[n];
for(j=0;j<n;j++)
{
// visit[i]=new boolean();
visit[j]=false;
}
visit[start]=true;
queue.add(start);
while(queue.size()!=0)
{
int s=queue.poll();
System.out.print(s+" ");
Iterator<Integer> i = adj[s].listIterator();
while(i.hasNext())
{
int a = i.next();
if(visit[a]!=true)
{
queue.add(a);
visit[a]=true;
}
}
}
}
public static void main(String args[])
{
int i;
BFS vertex=new BFS();
vertex.add(0,1);
vertex.add(0,3);
vertex.add(0,4);
vertex.add(1,2);
vertex.add(1,3);
vertex.add(2,4);
vertex.add(3,4);
vertex.traversal(0);
}
}
| UTF-8 | Java | 1,142 | java | BFS.java | Java | [] | null | [] | import java.util.*;
public class BFS
{
int n=5;
LinkedList<Integer> adj[];
public BFS()
{
adj=new LinkedList[n];
for(int i=0;i<n;i++)
{
adj[i]=new LinkedList();
}
}
public void add(int s, int d)
{
adj[s].add(d);
}
public void traversal(int start)
{
int j;
LinkedList<Integer> queue = new LinkedList<Integer>();
boolean visit[]=new boolean[n];
for(j=0;j<n;j++)
{
// visit[i]=new boolean();
visit[j]=false;
}
visit[start]=true;
queue.add(start);
while(queue.size()!=0)
{
int s=queue.poll();
System.out.print(s+" ");
Iterator<Integer> i = adj[s].listIterator();
while(i.hasNext())
{
int a = i.next();
if(visit[a]!=true)
{
queue.add(a);
visit[a]=true;
}
}
}
}
public static void main(String args[])
{
int i;
BFS vertex=new BFS();
vertex.add(0,1);
vertex.add(0,3);
vertex.add(0,4);
vertex.add(1,2);
vertex.add(1,3);
vertex.add(2,4);
vertex.add(3,4);
vertex.traversal(0);
}
}
| 1,142 | 0.49387 | 0.477233 | 64 | 16.84375 | 13.039865 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.046875 | false | false | 3 |
a49f567e7a14a64c84bd24ae5c5e7f85a7601f32 | 10,995,116,294,689 | 614f587004fec73654351ef10446f82eeb4020aa | /src/main/java/com/keenan/Tickets/service/impl/OrderServiceImpl.java | ddb01e402504be50100baf1552191f78426f2f18 | [] | no_license | Atlas-zqh/Tickets | https://github.com/Atlas-zqh/Tickets | a41b5be4ecd78206efb1dd0661d076ffd3787d40 | 47af8523c1fbb3474a032037a0738282dec7fa8e | refs/heads/master | 2021-09-10T20:38:48.035000 | 2018-04-02T00:18:58 | 2018-04-02T00:18:58 | 124,482,868 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.keenan.Tickets.service.impl;
import com.keenan.Tickets.bean.*;
import com.keenan.Tickets.model.*;
import com.keenan.Tickets.model.util.OrderStatus;
import com.keenan.Tickets.model.util.SeatStatus;
import com.keenan.Tickets.model.util.ShowPlanStatus;
import com.keenan.Tickets.model.util.TicketOrderType;
import com.keenan.Tickets.repository.*;
import com.keenan.Tickets.service.OrderService;
import com.keenan.Tickets.service.ShowPlanService;
import com.keenan.Tickets.util.ParseSeatString;
import com.keenan.Tickets.util.ResultMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author keenan on 28/03/2018
*/
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private TicketOrderRepository ticketOrderRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private VenueRepository venueRepository;
@Autowired
private ShowPlanRepository showPlanRepository;
@Autowired
private SeatRepository seatRepository;
@Autowired
private SeatArrangementRepository seatArrangementRepository;
@Autowired
private UserCouponRepository userCouponRepository;
@Autowired
private ShowPlanService showPlanService;
@Autowired
private LevelCouponRepository levelCouponRepository;
@Override
public ResultMessage checkTicket(String ticketNumber, Long venueId) {
if (ticketNumber == null || ticketNumber.equals("")) {
return new ResultMessage(ResultMessage.ERROR, "请输入订单号");
}
TicketOrder ticketOrder = ticketOrderRepository.findFirstByTicketNumber(ticketNumber);
if (!ticketOrder.getShowPlan().getVenue().getId().equals(venueId)) {
return new ResultMessage(ResultMessage.ERROR, "该订单与当前场馆不对应");
}
if (ticketOrder == null) {
return new ResultMessage(ResultMessage.ERROR, "未找到对应订单");
}
if (!ticketOrder.getTicketOrderType().equals(TicketOrderType.SPOT_TICKETS) && !ticketOrder.getOrderStatus().equals(OrderStatus.SUCCESS_PAID)) {
return new ResultMessage(ResultMessage.ERROR, "该订单无效");
} else if (ticketOrder.getOrderStatus().equals(OrderStatus.COMPLETED)) {
return new ResultMessage(ResultMessage.ERROR, "该订单已完成,无法使用");
} else {
ticketOrder.setOrderStatus(OrderStatus.COMPLETED);
ticketOrderRepository.save(ticketOrder);
User user = ticketOrder.getUser();
// 加积分后,要更改会员等级和所拥有的等级优惠
Double newPoints = user.getPoints() + ticketOrder.getOrderPrice();
if (newPoints < 1500.0) {
user.setLevel(1);
LevelCoupon leve1 = levelCouponRepository.findFirstById(1L);
user.setLevelCoupon(leve1);
} else if (newPoints < 5000.0) {
user.setLevel(2);
LevelCoupon leve2 = levelCouponRepository.findFirstById(2L);
user.setLevelCoupon(leve2);
} else if (newPoints < 15000.0) {
user.setLevel(3);
LevelCoupon leve3 = levelCouponRepository.findFirstById(3L);
user.setLevelCoupon(leve3);
} else if (newPoints < 30000.0) {
user.setLevel(4);
LevelCoupon leve4 = levelCouponRepository.findFirstById(4L);
user.setLevelCoupon(leve4);
} else {
user.setLevel(5);
LevelCoupon leve5 = levelCouponRepository.findFirstById(5L);
user.setLevelCoupon(leve5);
}
user.setPoints(newPoints);
userRepository.save(user);
return new ResultMessage(ResultMessage.SUCCESS, "验票成功");
}
}
@Override
public ResultMessage createOrder(User user, UserCreateOrderBean createOrderBean) {
if (createOrderBean.showPlanId == null || createOrderBean.totalPrice == null
|| createOrderBean.totalPrice == 0 || createOrderBean.section == null
|| createOrderBean.section.trim().equals("")) {
return new ResultMessage(ResultMessage.ERROR, "内容有误");
}
ShowPlan showPlan = showPlanRepository.findFirstById(createOrderBean.showPlanId);
Venue venue = showPlan.getVenue();
TicketOrderType ticketOrderType = TicketOrderType.fromString(createOrderBean.ticketOrderType);
// 创建订单
TicketOrder ticketOrder = new TicketOrder(showPlan, user, new Timestamp(System.currentTimeMillis()), null, ticketOrderType, createOrderBean.totalPrice, String.valueOf(System.currentTimeMillis()), createOrderBean.seatNum, OrderStatus.SUCCESS_UNPAID);
ticketOrderRepository.save(ticketOrder);
// 改变座位状态
if (ticketOrderType.equals(TicketOrderType.CHOOSE_SEATS)) {
List<BriefSeatBean> seatBeans = ParseSeatString.parseFormString(createOrderBean.chosenSeats);
for (BriefSeatBean briefSeatBean : seatBeans) {
Seat seat = seatRepository.findFirstByVenueAndSeatColumnAndSeatRowAndSeatSectionAndIsValid(venue, briefSeatBean.col, briefSeatBean.row, createOrderBean.section, true);
SeatArrangement arrangement = seatArrangementRepository.findSeatArrangementBySeatAndShowPlan(seat, showPlan);
if (arrangement == null || arrangement.getSeatStatus().equals(SeatStatus.BOOKED)) {
return new ResultMessage(ResultMessage.ERROR, "选座失败");
} else {
arrangement.setTicketOrder(ticketOrder);
arrangement.setSeatStatus(SeatStatus.BOOKED);
seatArrangementRepository.save(arrangement);
}
}
}
// 检查活动座位是否还有剩余
showPlanService.checkShowPlanStatus(createOrderBean.showPlanId);
// 优惠券失效
if (createOrderBean.userCouponId != null && createOrderBean.userCouponId != 0L) {
UserCoupon userCoupon = userCouponRepository.findFirstById(createOrderBean.userCouponId);
userCoupon.setUsed(true);
userCouponRepository.save(userCoupon);
}
return new ResultMessage(ResultMessage.SUCCESS, String.valueOf(ticketOrder.getId()));
}
@Override
public TicketOrderPayingBean getTicketOrderPaying(Long orderId) {
TicketOrder ticketOrder = ticketOrderRepository.findFirstById(orderId);
TicketOrderPayingBean payingBean = new TicketOrderPayingBean();
payingBean.orderId = ticketOrder.getId();
payingBean.orderNumber = ticketOrder.getTicketNumber();
payingBean.orderPrice = ticketOrder.getOrderPrice();
payingBean.orderTime = ticketOrder.getOrderTime();
return payingBean;
}
@Override
public ResultMessage payOrder(User user, PayInfoBean payInfoBean) {
// pay
if (user.getBankAccount().equals(payInfoBean.bankAccount) && user.getBankPassword().equals(payInfoBean.password)) {
TicketOrder ticketOrder = ticketOrderRepository.findFirstById(payInfoBean.orderId);
if (ticketOrder.getOrderStatus().equals(OrderStatus.INVALID_EXPIRED)) {
return new ResultMessage(ResultMessage.ERROR, "该订单已失效");
}
if (user.getBalance() < ticketOrder.getOrderPrice()) {
return new ResultMessage(ResultMessage.ERROR, "账户余额不足");
}
user.setBalance(user.getBalance() - ticketOrder.getOrderPrice());
// 完成订单之后才为用户加积分
// user.setPoints(user.getPoints() + ticketOrder.getOrderPrice());
userRepository.save(user);
ticketOrder.setOrderStatus(OrderStatus.SUCCESS_PAID);
ticketOrder.setPayTime(new Timestamp(System.currentTimeMillis()));
ticketOrderRepository.save(ticketOrder);
return new ResultMessage(ResultMessage.SUCCESS, "支付成功");
} else {
return new ResultMessage(ResultMessage.ERROR, "银行账号或密码错误");
}
}
@Override
public UserOrdersBean getUserOrders(User user) {
UserOrdersBean userOrdersBean = new UserOrdersBean();
List<TicketOrder> ticketOrders = ticketOrderRepository.findTicketOrdersByUser(user);
ticketOrders.sort((TicketOrder t1, TicketOrder t2) -> t2.getOrderTime().compareTo(t1.getOrderTime()));
List<UserOrderBriefBean> allOrders = new ArrayList<>();
ticketOrders.forEach(ticketOrder -> allOrders.add(new UserOrderBriefBean(ticketOrder)));
userOrdersBean.allOrders = allOrders;
Map<OrderStatus, List<TicketOrder>> orderStatusMap = ticketOrders.stream().collect(Collectors.groupingBy(TicketOrder::getOrderStatus, Collectors.toList()));
List<UserOrderBriefBean> completedOrders = new ArrayList<>();
if (orderStatusMap.get(OrderStatus.COMPLETED) != null) {
List<TicketOrder> completedTicketOrders = orderStatusMap.get(OrderStatus.COMPLETED);
completedTicketOrders.forEach(ticketOrder -> completedOrders.add(new UserOrderBriefBean(ticketOrder)));
}
userOrdersBean.completedOrders = completedOrders;
List<UserOrderBriefBean> paidOrders = new ArrayList<>();
if (orderStatusMap.get(OrderStatus.SUCCESS_PAID) != null) {
List<TicketOrder> pairTicketOrders = orderStatusMap.get(OrderStatus.SUCCESS_PAID);
pairTicketOrders.forEach(ticketOrder -> paidOrders.add(new UserOrderBriefBean(ticketOrder)));
}
userOrdersBean.paidOrders = paidOrders;
List<UserOrderBriefBean> unpaidOrders = new ArrayList<>();
if (orderStatusMap.get(OrderStatus.SUCCESS_UNPAID) != null) {
List<TicketOrder> unpaidTicketOrders = orderStatusMap.get(OrderStatus.SUCCESS_UNPAID);
unpaidTicketOrders.forEach(ticketOrder -> unpaidOrders.add(new UserOrderBriefBean(ticketOrder)));
}
userOrdersBean.unpaidOrders = unpaidOrders;
List<UserOrderBriefBean> invalidOrders = new ArrayList<>();
List<TicketOrder> invalidTicketOrders = new ArrayList<>();
if (orderStatusMap.get(OrderStatus.INVALID_EXPIRED) != null) {
invalidTicketOrders.addAll(orderStatusMap.get(OrderStatus.INVALID_EXPIRED));
}
if (orderStatusMap.get(OrderStatus.INVALID_REFUND) != null) {
invalidTicketOrders.addAll(orderStatusMap.get(OrderStatus.INVALID_REFUND));
}
if (orderStatusMap.get(OrderStatus.FAILED_ALLOCATE) != null) {
invalidTicketOrders.addAll(orderStatusMap.get(OrderStatus.FAILED_ALLOCATE));
}
invalidTicketOrders.sort((TicketOrder t1, TicketOrder t2) -> t2.getOrderTime().compareTo(t1.getOrderTime()));
invalidTicketOrders.forEach(ticketOrder -> invalidOrders.add(new UserOrderBriefBean(ticketOrder)));
userOrdersBean.invalidOrders = invalidOrders;
return userOrdersBean;
}
@Override
public UserOrderDetailBean getUserOrderDetail(Long orderId) {
TicketOrder ticketOrder = ticketOrderRepository.findFirstById(orderId);
return new UserOrderDetailBean(ticketOrder);
}
@Override
public ResultMessage refundOrder(Long orderId) {
try {
// 改订单状态
TicketOrder ticketOrder = ticketOrderRepository.findFirstById(orderId);
ticketOrder.setOrderStatus(OrderStatus.INVALID_REFUND);
ticketOrderRepository.save(ticketOrder);
// 还位置
Set<SeatArrangement> arrangements = ticketOrder.getSeatArrangements();
for (SeatArrangement arrangement : arrangements) {
arrangement.setTicketOrder(null);
arrangement.setSeatStatus(SeatStatus.AVAILABLE);
seatArrangementRepository.save(arrangement);
}
ShowPlan showPlan = ticketOrder.getShowPlan();
showPlan.setShowPlanStatus(ShowPlanStatus.ABUNDANCE);
showPlanRepository.save(showPlan);
// 还钱
User user = ticketOrder.getUser();
//<li>演出开始前90天退票,将全额退还</li>
//<li>演出开始前60天退票,将退还付款金额的80%</li>
//<li>演出开始前40天退票,将退还付款金额的70%</li>
//<li>演出开始前20天退票,将退还付款金额的50%</li>
//<li>演出开始20天内退票,将不退还</li>
Timestamp showTime = showPlan.getStartTime();
Timestamp today = new Timestamp(System.currentTimeMillis());
int discrepantDays = (int) (showTime.getTime() - today.getTime()) / 1000 / 60 / 60 / 24;
if (discrepantDays >= 90) {
user.setBalance(user.getBalance() + ticketOrder.getOrderPrice());
} else if (discrepantDays >= 60) {
user.setBalance(user.getBalance() + ticketOrder.getOrderPrice() * 0.8);
} else if (discrepantDays >= 40) {
user.setBalance(user.getBalance() + ticketOrder.getOrderPrice() * 0.7);
} else if (discrepantDays >= 20) {
user.setBalance(user.getBalance() + ticketOrder.getOrderPrice() * 0.5);
}
userRepository.save(user);
return new ResultMessage(ResultMessage.SUCCESS, "退款成功");
} catch (Exception e) {
return new ResultMessage(ResultMessage.ERROR, "退款失败");
}
}
@Override
public ResultMessage cancelOrder(Long orderId) {
try {
// 改订单状态
TicketOrder ticketOrder = ticketOrderRepository.findFirstById(orderId);
ticketOrder.setOrderStatus(OrderStatus.INVALID_CANCELED);
ticketOrderRepository.save(ticketOrder);
// 还位置
Set<SeatArrangement> arrangements = ticketOrder.getSeatArrangements();
for (SeatArrangement arrangement : arrangements) {
arrangement.setTicketOrder(null);
arrangement.setSeatStatus(SeatStatus.AVAILABLE);
seatArrangementRepository.save(arrangement);
}
ShowPlan showPlan = ticketOrder.getShowPlan();
showPlan.setShowPlanStatus(ShowPlanStatus.ABUNDANCE);
showPlanRepository.save(showPlan);
return new ResultMessage(ResultMessage.SUCCESS, "取消成功");
} catch (Exception e) {
return new ResultMessage(ResultMessage.ERROR, "取消失败");
}
}
}
| UTF-8 | Java | 14,875 | java | OrderServiceImpl.java | Java | [
{
"context": "mport java.util.stream.Collectors;\n\n/**\n * @author keenan on 28/03/2018\n */\n@Service\npublic class OrderServ",
"end": 788,
"score": 0.9992522597312927,
"start": 782,
"tag": "USERNAME",
"value": "keenan"
}
] | null | [] | package com.keenan.Tickets.service.impl;
import com.keenan.Tickets.bean.*;
import com.keenan.Tickets.model.*;
import com.keenan.Tickets.model.util.OrderStatus;
import com.keenan.Tickets.model.util.SeatStatus;
import com.keenan.Tickets.model.util.ShowPlanStatus;
import com.keenan.Tickets.model.util.TicketOrderType;
import com.keenan.Tickets.repository.*;
import com.keenan.Tickets.service.OrderService;
import com.keenan.Tickets.service.ShowPlanService;
import com.keenan.Tickets.util.ParseSeatString;
import com.keenan.Tickets.util.ResultMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author keenan on 28/03/2018
*/
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private TicketOrderRepository ticketOrderRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private VenueRepository venueRepository;
@Autowired
private ShowPlanRepository showPlanRepository;
@Autowired
private SeatRepository seatRepository;
@Autowired
private SeatArrangementRepository seatArrangementRepository;
@Autowired
private UserCouponRepository userCouponRepository;
@Autowired
private ShowPlanService showPlanService;
@Autowired
private LevelCouponRepository levelCouponRepository;
@Override
public ResultMessage checkTicket(String ticketNumber, Long venueId) {
if (ticketNumber == null || ticketNumber.equals("")) {
return new ResultMessage(ResultMessage.ERROR, "请输入订单号");
}
TicketOrder ticketOrder = ticketOrderRepository.findFirstByTicketNumber(ticketNumber);
if (!ticketOrder.getShowPlan().getVenue().getId().equals(venueId)) {
return new ResultMessage(ResultMessage.ERROR, "该订单与当前场馆不对应");
}
if (ticketOrder == null) {
return new ResultMessage(ResultMessage.ERROR, "未找到对应订单");
}
if (!ticketOrder.getTicketOrderType().equals(TicketOrderType.SPOT_TICKETS) && !ticketOrder.getOrderStatus().equals(OrderStatus.SUCCESS_PAID)) {
return new ResultMessage(ResultMessage.ERROR, "该订单无效");
} else if (ticketOrder.getOrderStatus().equals(OrderStatus.COMPLETED)) {
return new ResultMessage(ResultMessage.ERROR, "该订单已完成,无法使用");
} else {
ticketOrder.setOrderStatus(OrderStatus.COMPLETED);
ticketOrderRepository.save(ticketOrder);
User user = ticketOrder.getUser();
// 加积分后,要更改会员等级和所拥有的等级优惠
Double newPoints = user.getPoints() + ticketOrder.getOrderPrice();
if (newPoints < 1500.0) {
user.setLevel(1);
LevelCoupon leve1 = levelCouponRepository.findFirstById(1L);
user.setLevelCoupon(leve1);
} else if (newPoints < 5000.0) {
user.setLevel(2);
LevelCoupon leve2 = levelCouponRepository.findFirstById(2L);
user.setLevelCoupon(leve2);
} else if (newPoints < 15000.0) {
user.setLevel(3);
LevelCoupon leve3 = levelCouponRepository.findFirstById(3L);
user.setLevelCoupon(leve3);
} else if (newPoints < 30000.0) {
user.setLevel(4);
LevelCoupon leve4 = levelCouponRepository.findFirstById(4L);
user.setLevelCoupon(leve4);
} else {
user.setLevel(5);
LevelCoupon leve5 = levelCouponRepository.findFirstById(5L);
user.setLevelCoupon(leve5);
}
user.setPoints(newPoints);
userRepository.save(user);
return new ResultMessage(ResultMessage.SUCCESS, "验票成功");
}
}
@Override
public ResultMessage createOrder(User user, UserCreateOrderBean createOrderBean) {
if (createOrderBean.showPlanId == null || createOrderBean.totalPrice == null
|| createOrderBean.totalPrice == 0 || createOrderBean.section == null
|| createOrderBean.section.trim().equals("")) {
return new ResultMessage(ResultMessage.ERROR, "内容有误");
}
ShowPlan showPlan = showPlanRepository.findFirstById(createOrderBean.showPlanId);
Venue venue = showPlan.getVenue();
TicketOrderType ticketOrderType = TicketOrderType.fromString(createOrderBean.ticketOrderType);
// 创建订单
TicketOrder ticketOrder = new TicketOrder(showPlan, user, new Timestamp(System.currentTimeMillis()), null, ticketOrderType, createOrderBean.totalPrice, String.valueOf(System.currentTimeMillis()), createOrderBean.seatNum, OrderStatus.SUCCESS_UNPAID);
ticketOrderRepository.save(ticketOrder);
// 改变座位状态
if (ticketOrderType.equals(TicketOrderType.CHOOSE_SEATS)) {
List<BriefSeatBean> seatBeans = ParseSeatString.parseFormString(createOrderBean.chosenSeats);
for (BriefSeatBean briefSeatBean : seatBeans) {
Seat seat = seatRepository.findFirstByVenueAndSeatColumnAndSeatRowAndSeatSectionAndIsValid(venue, briefSeatBean.col, briefSeatBean.row, createOrderBean.section, true);
SeatArrangement arrangement = seatArrangementRepository.findSeatArrangementBySeatAndShowPlan(seat, showPlan);
if (arrangement == null || arrangement.getSeatStatus().equals(SeatStatus.BOOKED)) {
return new ResultMessage(ResultMessage.ERROR, "选座失败");
} else {
arrangement.setTicketOrder(ticketOrder);
arrangement.setSeatStatus(SeatStatus.BOOKED);
seatArrangementRepository.save(arrangement);
}
}
}
// 检查活动座位是否还有剩余
showPlanService.checkShowPlanStatus(createOrderBean.showPlanId);
// 优惠券失效
if (createOrderBean.userCouponId != null && createOrderBean.userCouponId != 0L) {
UserCoupon userCoupon = userCouponRepository.findFirstById(createOrderBean.userCouponId);
userCoupon.setUsed(true);
userCouponRepository.save(userCoupon);
}
return new ResultMessage(ResultMessage.SUCCESS, String.valueOf(ticketOrder.getId()));
}
@Override
public TicketOrderPayingBean getTicketOrderPaying(Long orderId) {
TicketOrder ticketOrder = ticketOrderRepository.findFirstById(orderId);
TicketOrderPayingBean payingBean = new TicketOrderPayingBean();
payingBean.orderId = ticketOrder.getId();
payingBean.orderNumber = ticketOrder.getTicketNumber();
payingBean.orderPrice = ticketOrder.getOrderPrice();
payingBean.orderTime = ticketOrder.getOrderTime();
return payingBean;
}
@Override
public ResultMessage payOrder(User user, PayInfoBean payInfoBean) {
// pay
if (user.getBankAccount().equals(payInfoBean.bankAccount) && user.getBankPassword().equals(payInfoBean.password)) {
TicketOrder ticketOrder = ticketOrderRepository.findFirstById(payInfoBean.orderId);
if (ticketOrder.getOrderStatus().equals(OrderStatus.INVALID_EXPIRED)) {
return new ResultMessage(ResultMessage.ERROR, "该订单已失效");
}
if (user.getBalance() < ticketOrder.getOrderPrice()) {
return new ResultMessage(ResultMessage.ERROR, "账户余额不足");
}
user.setBalance(user.getBalance() - ticketOrder.getOrderPrice());
// 完成订单之后才为用户加积分
// user.setPoints(user.getPoints() + ticketOrder.getOrderPrice());
userRepository.save(user);
ticketOrder.setOrderStatus(OrderStatus.SUCCESS_PAID);
ticketOrder.setPayTime(new Timestamp(System.currentTimeMillis()));
ticketOrderRepository.save(ticketOrder);
return new ResultMessage(ResultMessage.SUCCESS, "支付成功");
} else {
return new ResultMessage(ResultMessage.ERROR, "银行账号或密码错误");
}
}
@Override
public UserOrdersBean getUserOrders(User user) {
UserOrdersBean userOrdersBean = new UserOrdersBean();
List<TicketOrder> ticketOrders = ticketOrderRepository.findTicketOrdersByUser(user);
ticketOrders.sort((TicketOrder t1, TicketOrder t2) -> t2.getOrderTime().compareTo(t1.getOrderTime()));
List<UserOrderBriefBean> allOrders = new ArrayList<>();
ticketOrders.forEach(ticketOrder -> allOrders.add(new UserOrderBriefBean(ticketOrder)));
userOrdersBean.allOrders = allOrders;
Map<OrderStatus, List<TicketOrder>> orderStatusMap = ticketOrders.stream().collect(Collectors.groupingBy(TicketOrder::getOrderStatus, Collectors.toList()));
List<UserOrderBriefBean> completedOrders = new ArrayList<>();
if (orderStatusMap.get(OrderStatus.COMPLETED) != null) {
List<TicketOrder> completedTicketOrders = orderStatusMap.get(OrderStatus.COMPLETED);
completedTicketOrders.forEach(ticketOrder -> completedOrders.add(new UserOrderBriefBean(ticketOrder)));
}
userOrdersBean.completedOrders = completedOrders;
List<UserOrderBriefBean> paidOrders = new ArrayList<>();
if (orderStatusMap.get(OrderStatus.SUCCESS_PAID) != null) {
List<TicketOrder> pairTicketOrders = orderStatusMap.get(OrderStatus.SUCCESS_PAID);
pairTicketOrders.forEach(ticketOrder -> paidOrders.add(new UserOrderBriefBean(ticketOrder)));
}
userOrdersBean.paidOrders = paidOrders;
List<UserOrderBriefBean> unpaidOrders = new ArrayList<>();
if (orderStatusMap.get(OrderStatus.SUCCESS_UNPAID) != null) {
List<TicketOrder> unpaidTicketOrders = orderStatusMap.get(OrderStatus.SUCCESS_UNPAID);
unpaidTicketOrders.forEach(ticketOrder -> unpaidOrders.add(new UserOrderBriefBean(ticketOrder)));
}
userOrdersBean.unpaidOrders = unpaidOrders;
List<UserOrderBriefBean> invalidOrders = new ArrayList<>();
List<TicketOrder> invalidTicketOrders = new ArrayList<>();
if (orderStatusMap.get(OrderStatus.INVALID_EXPIRED) != null) {
invalidTicketOrders.addAll(orderStatusMap.get(OrderStatus.INVALID_EXPIRED));
}
if (orderStatusMap.get(OrderStatus.INVALID_REFUND) != null) {
invalidTicketOrders.addAll(orderStatusMap.get(OrderStatus.INVALID_REFUND));
}
if (orderStatusMap.get(OrderStatus.FAILED_ALLOCATE) != null) {
invalidTicketOrders.addAll(orderStatusMap.get(OrderStatus.FAILED_ALLOCATE));
}
invalidTicketOrders.sort((TicketOrder t1, TicketOrder t2) -> t2.getOrderTime().compareTo(t1.getOrderTime()));
invalidTicketOrders.forEach(ticketOrder -> invalidOrders.add(new UserOrderBriefBean(ticketOrder)));
userOrdersBean.invalidOrders = invalidOrders;
return userOrdersBean;
}
@Override
public UserOrderDetailBean getUserOrderDetail(Long orderId) {
TicketOrder ticketOrder = ticketOrderRepository.findFirstById(orderId);
return new UserOrderDetailBean(ticketOrder);
}
@Override
public ResultMessage refundOrder(Long orderId) {
try {
// 改订单状态
TicketOrder ticketOrder = ticketOrderRepository.findFirstById(orderId);
ticketOrder.setOrderStatus(OrderStatus.INVALID_REFUND);
ticketOrderRepository.save(ticketOrder);
// 还位置
Set<SeatArrangement> arrangements = ticketOrder.getSeatArrangements();
for (SeatArrangement arrangement : arrangements) {
arrangement.setTicketOrder(null);
arrangement.setSeatStatus(SeatStatus.AVAILABLE);
seatArrangementRepository.save(arrangement);
}
ShowPlan showPlan = ticketOrder.getShowPlan();
showPlan.setShowPlanStatus(ShowPlanStatus.ABUNDANCE);
showPlanRepository.save(showPlan);
// 还钱
User user = ticketOrder.getUser();
//<li>演出开始前90天退票,将全额退还</li>
//<li>演出开始前60天退票,将退还付款金额的80%</li>
//<li>演出开始前40天退票,将退还付款金额的70%</li>
//<li>演出开始前20天退票,将退还付款金额的50%</li>
//<li>演出开始20天内退票,将不退还</li>
Timestamp showTime = showPlan.getStartTime();
Timestamp today = new Timestamp(System.currentTimeMillis());
int discrepantDays = (int) (showTime.getTime() - today.getTime()) / 1000 / 60 / 60 / 24;
if (discrepantDays >= 90) {
user.setBalance(user.getBalance() + ticketOrder.getOrderPrice());
} else if (discrepantDays >= 60) {
user.setBalance(user.getBalance() + ticketOrder.getOrderPrice() * 0.8);
} else if (discrepantDays >= 40) {
user.setBalance(user.getBalance() + ticketOrder.getOrderPrice() * 0.7);
} else if (discrepantDays >= 20) {
user.setBalance(user.getBalance() + ticketOrder.getOrderPrice() * 0.5);
}
userRepository.save(user);
return new ResultMessage(ResultMessage.SUCCESS, "退款成功");
} catch (Exception e) {
return new ResultMessage(ResultMessage.ERROR, "退款失败");
}
}
@Override
public ResultMessage cancelOrder(Long orderId) {
try {
// 改订单状态
TicketOrder ticketOrder = ticketOrderRepository.findFirstById(orderId);
ticketOrder.setOrderStatus(OrderStatus.INVALID_CANCELED);
ticketOrderRepository.save(ticketOrder);
// 还位置
Set<SeatArrangement> arrangements = ticketOrder.getSeatArrangements();
for (SeatArrangement arrangement : arrangements) {
arrangement.setTicketOrder(null);
arrangement.setSeatStatus(SeatStatus.AVAILABLE);
seatArrangementRepository.save(arrangement);
}
ShowPlan showPlan = ticketOrder.getShowPlan();
showPlan.setShowPlanStatus(ShowPlanStatus.ABUNDANCE);
showPlanRepository.save(showPlan);
return new ResultMessage(ResultMessage.SUCCESS, "取消成功");
} catch (Exception e) {
return new ResultMessage(ResultMessage.ERROR, "取消失败");
}
}
}
| 14,875 | 0.667687 | 0.66073 | 311 | 45.221867 | 35.618362 | 257 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.652733 | false | false | 3 |
1c8688b44c2215a4ae8547506492de65d4bce993 | 28,741,921,209,214 | fd2f5fbc2367e9d68a8e8485dbcd51e7c2869262 | /eTradeREST/src/main/java/edu/mum/dao/OrderDao.java | 66f380e8a48265f5db35f8ab42ab4ddadcb1c252 | [] | no_license | xtrememind/eTradeREST | https://github.com/xtrememind/eTradeREST | 739f1fd39bdc2f72cd391a4d3516fa2cd8c88594 | ca555f09646c53ca51aa2efaa9af004a250225d3 | refs/heads/master | 2021-04-11T05:56:57.653000 | 2018-03-22T06:57:50 | 2018-03-22T06:57:50 | 125,687,177 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.mum.dao;
import edu.mum.domain.Order;
//
public interface OrderDao extends GenericDao<Order> {
}
| UTF-8 | Java | 118 | java | OrderDao.java | Java | [] | null | [] | package edu.mum.dao;
import edu.mum.domain.Order;
//
public interface OrderDao extends GenericDao<Order> {
}
| 118 | 0.711864 | 0.711864 | 7 | 14.857142 | 18.719193 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 3 |
b5c7499f34357f1c31b83e7731c53a31e9f76cb2 | 6,923,487,329,891 | af73a938455cc1f86f89c1ca7538b218b24b4534 | /src/test/java/ee/icd0004/project/unit/ForecastReportTest.java | be58092a8f771037a1451d9dd4b1e2298df7dbf2 | [] | no_license | KarelVux/owm-api-automated-testing | https://github.com/KarelVux/owm-api-automated-testing | 8679b5a9a44cd52a0174913adaa8036c26a7ec2e | 0ece57fab4b75c7eb7c888b9007044fda327cb26 | refs/heads/master | 2023-02-03T10:01:06.288000 | 2020-12-20T22:07:15 | 2020-12-20T22:07:15 | 323,178,147 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ee.icd0004.project.unit;
import ee.icd0004.project.model.DailyWeather;
import ee.icd0004.project.model.ForecastReport;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ForecastReportTest {
@Test
public void should_have_dates_in_ascending_orders() {
List<String> unorderedDates = Arrays.asList("2020-09-05", "2020-12-11", "2019-11-11");
List<String> orderedDates = new LinkedList<>(Arrays.asList("2019-11-11", "2020-09-05", "2020-12-11"));
List<DailyWeather> unorderedDailyWeatherList = getInitializedDailyWeatherList(unorderedDates);
List<DailyWeather> orderedDailyWeatherList = getInitializedDailyWeatherList(orderedDates);
ForecastReport forecastReport = new ForecastReport();
forecastReport.setDailyWeathers(unorderedDailyWeatherList);
forecastReport.orderDailyWeathersByDate();
assertThat(forecastReport.getDailyWeathers()).isEqualTo(orderedDailyWeatherList);
}
private List<DailyWeather> getInitializedDailyWeatherList(List<String> datesList) {
List<DailyWeather> dailyWeatherDates = new ArrayList<>();
for (String date : datesList) {
DailyWeather dailyWeather = new DailyWeather();
dailyWeather.setDate(date);
dailyWeatherDates.add(dailyWeather);
}
return dailyWeatherDates;
}
}
| UTF-8 | Java | 1,504 | java | ForecastReportTest.java | Java | [] | null | [] | package ee.icd0004.project.unit;
import ee.icd0004.project.model.DailyWeather;
import ee.icd0004.project.model.ForecastReport;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ForecastReportTest {
@Test
public void should_have_dates_in_ascending_orders() {
List<String> unorderedDates = Arrays.asList("2020-09-05", "2020-12-11", "2019-11-11");
List<String> orderedDates = new LinkedList<>(Arrays.asList("2019-11-11", "2020-09-05", "2020-12-11"));
List<DailyWeather> unorderedDailyWeatherList = getInitializedDailyWeatherList(unorderedDates);
List<DailyWeather> orderedDailyWeatherList = getInitializedDailyWeatherList(orderedDates);
ForecastReport forecastReport = new ForecastReport();
forecastReport.setDailyWeathers(unorderedDailyWeatherList);
forecastReport.orderDailyWeathersByDate();
assertThat(forecastReport.getDailyWeathers()).isEqualTo(orderedDailyWeatherList);
}
private List<DailyWeather> getInitializedDailyWeatherList(List<String> datesList) {
List<DailyWeather> dailyWeatherDates = new ArrayList<>();
for (String date : datesList) {
DailyWeather dailyWeather = new DailyWeather();
dailyWeather.setDate(date);
dailyWeatherDates.add(dailyWeather);
}
return dailyWeatherDates;
}
}
| 1,504 | 0.729388 | 0.689495 | 40 | 36.599998 | 33.097431 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false | 3 |
1e419c11e1a8f47879e4e14ecc90e2453ce5fbee | 18,193,481,487,201 | 2f0574712121f4e5f09a19f1e03e19173191ddf7 | /src/main/java/com/asarao/service/ProcessService.java | c3bda1f3d9d45d87a9e151c883c8ea86fe135f65 | [] | no_license | astra-zhao/spring-camunda | https://github.com/astra-zhao/spring-camunda | cdb42da1ed7f4b22cbe246a74f874a7208da6459 | f2427116af30f136194a9544c3e7e1714f366ee6 | refs/heads/master | 2023-01-23T09:47:38.159000 | 2020-11-25T10:36:17 | 2020-11-25T10:36:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.asarao.service;
public interface ProcessService {
/**
* 委派
*/
void delegate(String taskId,String userId);
/**
* 转办
*/
void turn(String taskId,String assignee);
/**
* 抢占
*/
void preemption(String taskId,String userId);
/**
* 会签
*/
void countersign();
/**
* 委托代办
*/
void concierge(String taskId,String userId);
/**
* 催办
*/
void reminder();
/**
* 自由流
*/
void freeFlow();
/**
* 回退
*/
void fallback();
/**
* 取回
*/
void retrieve();
/**
* 指派
*/
void assign(String taskId,String userId);
/**
* 前加签
*/
void beforeAddSign();
/**
* 后加签
*/
void afterAddSign();
/**
* 改派
*/
void reassign();
/**
* 驳回
*/
void reject();
/**
* 终止
*/
void terminate();
/**
* 挂起
*/
void hang();
/**
* 激活
*/
void active();
}
| UTF-8 | Java | 1,103 | java | ProcessService.java | Java | [] | null | [] | package com.asarao.service;
public interface ProcessService {
/**
* 委派
*/
void delegate(String taskId,String userId);
/**
* 转办
*/
void turn(String taskId,String assignee);
/**
* 抢占
*/
void preemption(String taskId,String userId);
/**
* 会签
*/
void countersign();
/**
* 委托代办
*/
void concierge(String taskId,String userId);
/**
* 催办
*/
void reminder();
/**
* 自由流
*/
void freeFlow();
/**
* 回退
*/
void fallback();
/**
* 取回
*/
void retrieve();
/**
* 指派
*/
void assign(String taskId,String userId);
/**
* 前加签
*/
void beforeAddSign();
/**
* 后加签
*/
void afterAddSign();
/**
* 改派
*/
void reassign();
/**
* 驳回
*/
void reject();
/**
* 终止
*/
void terminate();
/**
* 挂起
*/
void hang();
/**
* 激活
*/
void active();
}
| 1,103 | 0.40878 | 0.40878 | 89 | 10.516854 | 11.195015 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.258427 | false | false | 3 |
fac74f0fe175cd642af9381f27654b80bd7c7dbf | 23,957,327,601,425 | 9422b83db9168576046db6876badbe3c8c388355 | /scheduleview/src/main/java/com/khoa/scheduleview/Util.java | 08ac3d86dbcfc6e6ebd9445a0f4d8e8670145fe5 | [] | no_license | KhoaMoya/PtitTools | https://github.com/KhoaMoya/PtitTools | 2a959ee3856b140d3b3ad70158f4e75f6d28da7d | 087fd671e77a134959a5407c95aba98bc5cdde02 | refs/heads/master | 2022-11-16T20:35:27.992000 | 2020-07-14T09:20:11 | 2020-07-14T09:20:11 | 254,524,884 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.khoa.scheduleview;
import android.content.Context;
public class Util {
public static float convertDpToPixel(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
}
| UTF-8 | Java | 235 | java | Util.java | Java | [] | null | [] | package com.khoa.scheduleview;
import android.content.Context;
public class Util {
public static float convertDpToPixel(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
}
| 235 | 0.73617 | 0.73617 | 9 | 25.111111 | 26.6143 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 3 |
97f8248c2f974b576baf4a6f52570e16c842aca7 | 6,090,263,648,936 | 2c80c1afc02413c6ea0e79695d01f30ff01766ac | / ttdc --username trevisthomas/River/source/Client/org/ttdc/gwt/shared/commands/results/PaginatedListCommandResult.java | f4770d426cd50b2197fdb2316d86907773c86054 | [] | no_license | trevisthomas/ttdc | https://github.com/trevisthomas/ttdc | 2f476b1771e7e80b604e8bbdd953b526fa399b40 | 39eceee94826afb7e286860ac428898359153c74 | refs/heads/master | 2021-07-02T08:53:19.859000 | 2020-09-16T14:56:08 | 2020-09-16T14:56:08 | 33,408,402 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ttdc.gwt.shared.commands.results;
import org.ttdc.gwt.client.services.CommandResult;
import org.ttdc.gwt.shared.util.PaginatedList;
public class PaginatedListCommandResult<T> implements CommandResult{
private PaginatedList<T> results;
public PaginatedListCommandResult(){}
public PaginatedListCommandResult(PaginatedList<T> results){
this.results = results;
}
public PaginatedList<T> getResults() {
return results;
}
}
| UTF-8 | Java | 467 | java | PaginatedListCommandResult.java | Java | [] | null | [] | package org.ttdc.gwt.shared.commands.results;
import org.ttdc.gwt.client.services.CommandResult;
import org.ttdc.gwt.shared.util.PaginatedList;
public class PaginatedListCommandResult<T> implements CommandResult{
private PaginatedList<T> results;
public PaginatedListCommandResult(){}
public PaginatedListCommandResult(PaginatedList<T> results){
this.results = results;
}
public PaginatedList<T> getResults() {
return results;
}
}
| 467 | 0.760171 | 0.760171 | 18 | 23.944445 | 23.229465 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.055556 | false | false | 3 |
89825c7dff5ddb02be08f367441837e8a14d5159 | 28,269,474,744,094 | c2294f4469d13b07683c0e2f2f116a2b499af6d7 | /Implementation/src/Controller/CampaignServlets/LifecycleCampaignServlets/StartCampaignServlet.java | 4c3c4fe6470110fefec2aff231f218f08f7d6be4 | [] | no_license | francescoalongi/CrowdsourcingPeak | https://github.com/francescoalongi/CrowdsourcingPeak | 57031f44fabcbb438398dc51fd01812a4b32b061 | 5f9366cffa7b34835798c6c2ea35e048b47426ba | refs/heads/master | 2020-03-30T06:17:51.026000 | 2018-10-04T16:59:22 | 2018-10-04T16:59:22 | 150,850,269 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Controller.CampaignServlets.LifecycleCampaignServlets;
import Model.Database.DataSource;
import Model.Manager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
@WebServlet(name = "StartCampaignServlet")
public class StartCampaignServlet extends HttpServlet {
DataSource dataSource;
@Override
public void init() throws ServletException {
this.dataSource = DataSource.getInstance();
super.init();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getSession(false).getAttribute("user") instanceof Manager) {
Manager manager = (Manager) request.getSession(false).getAttribute("user");
String startCampaignQuery = "UPDATE crowdsourcingpeak.campaign SET state = ?, startDate = ? WHERE idCampaign = ? AND idManager = ?";
try (Connection connection = this.dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(startCampaignQuery)) {
preparedStatement.setString(1, "STARTED");
Timestamp timestamp = new Timestamp(new Date().getTime());
preparedStatement.setTimestamp(2, timestamp);
preparedStatement.setInt(3, Integer.parseInt(request.getParameter("idCampaign")));
preparedStatement.setInt(4, manager.getIdUser());
preparedStatement.executeUpdate();
response.sendRedirect("/CrowdsourcingPeak");
} catch (SQLException e) {
e.printStackTrace();
}
} else {
response.sendRedirect("/CrowdsourcingPeak/GeneralError");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| UTF-8 | Java | 2,195 | java | StartCampaignServlet.java | Java | [] | null | [] | package Controller.CampaignServlets.LifecycleCampaignServlets;
import Model.Database.DataSource;
import Model.Manager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
@WebServlet(name = "StartCampaignServlet")
public class StartCampaignServlet extends HttpServlet {
DataSource dataSource;
@Override
public void init() throws ServletException {
this.dataSource = DataSource.getInstance();
super.init();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getSession(false).getAttribute("user") instanceof Manager) {
Manager manager = (Manager) request.getSession(false).getAttribute("user");
String startCampaignQuery = "UPDATE crowdsourcingpeak.campaign SET state = ?, startDate = ? WHERE idCampaign = ? AND idManager = ?";
try (Connection connection = this.dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(startCampaignQuery)) {
preparedStatement.setString(1, "STARTED");
Timestamp timestamp = new Timestamp(new Date().getTime());
preparedStatement.setTimestamp(2, timestamp);
preparedStatement.setInt(3, Integer.parseInt(request.getParameter("idCampaign")));
preparedStatement.setInt(4, manager.getIdUser());
preparedStatement.executeUpdate();
response.sendRedirect("/CrowdsourcingPeak");
} catch (SQLException e) {
e.printStackTrace();
}
} else {
response.sendRedirect("/CrowdsourcingPeak/GeneralError");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| 2,195 | 0.707062 | 0.705239 | 53 | 40.415092 | 34.867638 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.716981 | false | false | 3 |
5157c9af4de371e4a2e42b4b83d65a838e8d813b | 13,348,758,377,217 | 17a59eb26e1ff7e151c38a3d4e5aeef65f568b55 | /fromBOJ/SW11720.java | a0495cb424c60fd4ce7be12a37bec8fa98bc5a17 | [] | no_license | JangYoungJune/AlgorithmStudy | https://github.com/JangYoungJune/AlgorithmStudy | 0732e8ee7861c5a277f868fe7d23bef5fedf7d7a | d087ecbe7cb9feb7537880817d7f1d6e05b88f94 | refs/heads/master | 2021-07-02T18:35:41.188000 | 2020-09-17T08:31:00 | 2020-09-17T08:31:00 | 165,506,957 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fromBOJ;
import java.util.Scanner;
import java.util.stream.IntStream;
public class SW11720 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.nextInt();
String words = sc.next();
System.out.println(words.chars().map(x->x-'0').sum());
}
}
| UTF-8 | Java | 290 | java | SW11720.java | Java | [] | null | [] | package fromBOJ;
import java.util.Scanner;
import java.util.stream.IntStream;
public class SW11720 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.nextInt();
String words = sc.next();
System.out.println(words.chars().map(x->x-'0').sum());
}
}
| 290 | 0.689655 | 0.668966 | 13 | 21.307692 | 17.184002 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.307692 | false | false | 3 |
934374b5cda440265f0e5e82afcb843c63456621 | 14,370,960,599,795 | ca9e4760eb68147a7e68b0917c72efd7c3d3243e | /src/main/java/elle/tooted.java | 74c5c98f4b11ee4bd5e5513a6bf5ac5f6f5e280c | [] | no_license | elleelisa/t05veebirakendus | https://github.com/elleelisa/t05veebirakendus | b3a2c4a85eb4c58c685fe5522a911ba0a36cd965 | 112d946cc2345f7aa1bbc4dad9bf3ebd21b92e32 | refs/heads/master | 2020-12-30T11:28:26.192000 | 2017-05-23T09:30:58 | 2017-05-23T09:30:58 | 91,564,897 | 0 | 0 | null | true | 2017-05-17T10:37:44 | 2017-05-17T10:37:44 | 2017-02-28T13:40:09 | 2017-05-17T09:49:27 | 0 | 0 | 0 | 0 | null | null | null | package elle;
import javax.persistence.*;
@Entity
@Table (name="tooted")
public class tooted{
@Id
public String jook;
public String nimi;
public Double kogus;
}
| UTF-8 | Java | 167 | java | tooted.java | Java | [] | null | [] | package elle;
import javax.persistence.*;
@Entity
@Table (name="tooted")
public class tooted{
@Id
public String jook;
public String nimi;
public Double kogus;
}
| 167 | 0.730539 | 0.730539 | 12 | 12.916667 | 9.517163 | 27 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 3 |
eaff673bfe0e409aee0cffb8333ae5375559d979 | 25,245,817,817,113 | 821c091bb6b77c354ef10bae68f30269d61c4cf5 | /ruta-ep-addons/src/main/java/org/apache/uima/ruta/testing/evaluator/AbstractCasEvaluator.java | 15c9cf330df0225130e85c3424b4c2e3dd22bc9e | [
"CC-BY-3.0",
"Apache-2.0"
] | permissive | apache/uima-ruta | https://github.com/apache/uima-ruta | 902173ee31e56528641062dfce00f36d4bb6185f | 85f5720fe388c4791e85c88655162a047f58953a | refs/heads/main | 2023-09-03T06:28:29.070000 | 2023-08-10T16:55:03 | 2023-08-10T16:55:03 | 15,070,661 | 31 | 26 | Apache-2.0 | false | 2018-03-02T15:33:17 | 2013-12-10T08:00:24 | 2018-01-17T11:48:32 | 2018-03-02T13:53:08 | 20,135 | 17 | 16 | 0 | Java | false | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.uima.ruta.testing.evaluator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.TypeSystem;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.uima.cas.text.AnnotationIndex;
public abstract class AbstractCasEvaluator implements ICasEvaluator {
protected List<AnnotationFS> getAnnotations(List<Type> types, CAS cas, boolean includeSubtypes) {
List<AnnotationFS> result = new ArrayList<AnnotationFS>();
TypeSystem typeSystem = cas.getTypeSystem();
AnnotationIndex<AnnotationFS> annotationIndex = cas.getAnnotationIndex();
for (AnnotationFS each : annotationIndex) {
Type type = each.getType();
for (Type eachType : types) {
if (includeSubtypes && typeSystem.subsumes(eachType, type)) {
result.add(each);
break;
} else if (eachType.getName().equals(type.getName())) {
result.add(each);
break;
}
}
}
return result;
}
protected boolean match(AnnotationFS a1, AnnotationFS a2) {
if (a1 != null && a2 != null) {
if (a1.getBegin() == a2.getBegin() && a1.getEnd() == a2.getEnd()
&& a1.getType().getName().equals(a2.getType().getName()))
return true;
}
return false;
}
protected List<Type> getTypes(CAS test, Collection<String> excludedTypes, Type annotationType,
boolean useAllTypes) {
List<Type> allTypes = test.getTypeSystem().getProperlySubsumedTypes(annotationType);
List<Type> types = new ArrayList<Type>();
for (Type eachType : allTypes) {
int size = test.getAnnotationIndex(eachType).size();
if (!excludedTypes.contains(eachType.getName()) && (size > 0 || useAllTypes)
&& !eachType.equals(test.getDocumentAnnotation().getType())) {
types.add(eachType);
}
}
return types;
}
}
| UTF-8 | Java | 2,846 | java | AbstractCasEvaluator.java | Java | [] | null | [] | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.uima.ruta.testing.evaluator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.TypeSystem;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.uima.cas.text.AnnotationIndex;
public abstract class AbstractCasEvaluator implements ICasEvaluator {
protected List<AnnotationFS> getAnnotations(List<Type> types, CAS cas, boolean includeSubtypes) {
List<AnnotationFS> result = new ArrayList<AnnotationFS>();
TypeSystem typeSystem = cas.getTypeSystem();
AnnotationIndex<AnnotationFS> annotationIndex = cas.getAnnotationIndex();
for (AnnotationFS each : annotationIndex) {
Type type = each.getType();
for (Type eachType : types) {
if (includeSubtypes && typeSystem.subsumes(eachType, type)) {
result.add(each);
break;
} else if (eachType.getName().equals(type.getName())) {
result.add(each);
break;
}
}
}
return result;
}
protected boolean match(AnnotationFS a1, AnnotationFS a2) {
if (a1 != null && a2 != null) {
if (a1.getBegin() == a2.getBegin() && a1.getEnd() == a2.getEnd()
&& a1.getType().getName().equals(a2.getType().getName()))
return true;
}
return false;
}
protected List<Type> getTypes(CAS test, Collection<String> excludedTypes, Type annotationType,
boolean useAllTypes) {
List<Type> allTypes = test.getTypeSystem().getProperlySubsumedTypes(annotationType);
List<Type> types = new ArrayList<Type>();
for (Type eachType : allTypes) {
int size = test.getAnnotationIndex(eachType).size();
if (!excludedTypes.contains(eachType.getName()) && (size > 0 || useAllTypes)
&& !eachType.equals(test.getDocumentAnnotation().getType())) {
types.add(eachType);
}
}
return types;
}
}
| 2,846 | 0.672874 | 0.667604 | 76 | 35.447369 | 27.559216 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.513158 | false | false | 3 |
6af37f57166c7fd30722342546d2af361e484f04 | 11,845,519,803,448 | 3b44b989360e193f2fe4d62e200b78239b9071ed | /src/main/java/objects/DevelopmentCard.java | e4ce23d4a63abca58b60262e424f519c0b2a2a8b | [] | no_license | clarkta14/Catan-Portfolio | https://github.com/clarkta14/Catan-Portfolio | 7097b15304dbaa30b48a5f0c8acfa5ded4b816d5 | 092633d029c5f31cba7e1bd7012c7e4f2f2eb448 | refs/heads/master | 2022-11-17T20:47:51.829000 | 2020-07-14T15:47:46 | 2020-07-14T15:47:46 | 274,996,589 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package objects;
public abstract class DevelopmentCard {
public void playCard(TileType... resources) { }
public abstract DevelopmentCardType getDevelopmentCardType();
}
| UTF-8 | Java | 177 | java | DevelopmentCard.java | Java | [] | null | [] | package objects;
public abstract class DevelopmentCard {
public void playCard(TileType... resources) { }
public abstract DevelopmentCardType getDevelopmentCardType();
}
| 177 | 0.779661 | 0.779661 | 8 | 21.125 | 23.347578 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false | 3 |
4d141a76ae1af51885adee19005c6fd9cb666a0a | 15,625,091,027,825 | 564e96ad794624b2c029b933ad6f55e708b80d08 | /COSC_1337/Assignment_10/StringTooLongException.java | 20b8a6f67a600abccfd6261fe70f296ac76353b0 | [] | no_license | harrystaley/Homework | https://github.com/harrystaley/Homework | b0745ab7eacecfa74e06ac494a9648f65c33182e | 5fc3b1b682091c0f074321156500dd764e64ae0a | refs/heads/master | 2022-07-15T12:22:50.889000 | 2022-06-29T07:12:22 | 2022-06-29T07:12:22 | 25,446,565 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class StringTooLongException extends Exception{
public StringTooLongException (String message)
{
super(message);
}
} // end class StringTooLongException
| UTF-8 | Java | 184 | java | StringTooLongException.java | Java | [] | null | [] |
public class StringTooLongException extends Exception{
public StringTooLongException (String message)
{
super(message);
}
} // end class StringTooLongException
| 184 | 0.717391 | 0.717391 | 6 | 29.5 | 21.045586 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 3 |
bee084fcec89079d02d63a5aff2d1ec438b700f1 | 24,481,313,599,239 | 183931eedd8ed7ff685e22cb055f86f12a54d707 | /otus/preJava/m43/src/main/java/ru/otus/FileTutor1.java | 69318f5d33e56ef7b56dfb0cd5b275e84da89a56 | [] | no_license | cynepCTAPuk/headFirstJava | https://github.com/cynepCTAPuk/headFirstJava | 94a87be8f6958ab373cd1640a5bdb9c3cc3bf166 | 7cb45f6e2336bbc78852d297ad3474fd491e5870 | refs/heads/master | 2023-08-16T06:51:14.206000 | 2023-08-08T16:44:11 | 2023-08-08T16:44:11 | 154,661,091 | 0 | 1 | null | false | 2023-01-06T21:32:31 | 2018-10-25T11:40:54 | 2021-10-08T20:45:04 | 2023-01-06T21:32:27 | 46,377 | 0 | 0 | 75 | Java | false | false | package ru.otus;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class FileTutor1 {
private void createFile() {
File dir = new File("test");
dir.mkdir();
File f = new File("test/test.txt");
/*
try {
log("Файл создан? " + f.createNewFile());
} catch (IOException e) {
e.printStackTrace();
}
*/
// log(f.getAbsolutePath());
}
private void deleteFile() {
File f = new File("test/test.txt");
f.delete();
File dir = new File("test");
dir.delete();
}
@Test
public void testCreateFile() {
createFile();
File f = new File("test/test.txt");
Assert.assertTrue(f.exists());
}
@Test
public void testDeleteFile() {
deleteFile();
File f = new File("test/test.txt");
assertFalse(f.exists());
assertFalse(new File("test").exists());
}
public static void main(String[] args) throws IOException {
// System.out.println(new File(".").getName());
// System.out.println(new File(".").getAbsolutePath());
// System.out.println(new File(".").getCanonicalPath());
File dir = new File("dir");
System.out.println(dir.exists());
System.out.println(dir.mkdir());
System.out.println(dir.getPath());
System.out.println("-----------------");
File subdir = new File(dir.getPath() + "/subdir");
System.out.println(subdir.exists());
System.out.println(subdir.mkdir());
System.out.println(subdir.getPath());
System.out.println(Arrays.asList(subdir.listFiles()).toString());
System.out.println("-----------------");
File file = new File(subdir.getPath() + "/file.txt");
System.out.println(file.exists());
System.out.println(file.createNewFile());
System.out.println(file.getPath());
System.out.println(file.getParent());
System.out.println(file.getFreeSpace());
System.out.println(file.getTotalSpace());
System.out.println(file.getUsableSpace());
// System.out.println(file.delete());
// System.out.println(subdir.delete());
// System.out.println(dir.delete());
File root = new File(".");
System.out.println("-----------------");
String[] list = root.list(((d, name) -> !name.startsWith(".")));
for (String s : list) System.out.println(s);
System.out.println("-----------------");
File[] listFiles = root.listFiles(f -> !f.isDirectory());
for (File f : listFiles) System.out.println(f);
}
}
| UTF-8 | Java | 2,761 | java | FileTutor1.java | Java | [] | null | [] | package ru.otus;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class FileTutor1 {
private void createFile() {
File dir = new File("test");
dir.mkdir();
File f = new File("test/test.txt");
/*
try {
log("Файл создан? " + f.createNewFile());
} catch (IOException e) {
e.printStackTrace();
}
*/
// log(f.getAbsolutePath());
}
private void deleteFile() {
File f = new File("test/test.txt");
f.delete();
File dir = new File("test");
dir.delete();
}
@Test
public void testCreateFile() {
createFile();
File f = new File("test/test.txt");
Assert.assertTrue(f.exists());
}
@Test
public void testDeleteFile() {
deleteFile();
File f = new File("test/test.txt");
assertFalse(f.exists());
assertFalse(new File("test").exists());
}
public static void main(String[] args) throws IOException {
// System.out.println(new File(".").getName());
// System.out.println(new File(".").getAbsolutePath());
// System.out.println(new File(".").getCanonicalPath());
File dir = new File("dir");
System.out.println(dir.exists());
System.out.println(dir.mkdir());
System.out.println(dir.getPath());
System.out.println("-----------------");
File subdir = new File(dir.getPath() + "/subdir");
System.out.println(subdir.exists());
System.out.println(subdir.mkdir());
System.out.println(subdir.getPath());
System.out.println(Arrays.asList(subdir.listFiles()).toString());
System.out.println("-----------------");
File file = new File(subdir.getPath() + "/file.txt");
System.out.println(file.exists());
System.out.println(file.createNewFile());
System.out.println(file.getPath());
System.out.println(file.getParent());
System.out.println(file.getFreeSpace());
System.out.println(file.getTotalSpace());
System.out.println(file.getUsableSpace());
// System.out.println(file.delete());
// System.out.println(subdir.delete());
// System.out.println(dir.delete());
File root = new File(".");
System.out.println("-----------------");
String[] list = root.list(((d, name) -> !name.startsWith(".")));
for (String s : list) System.out.println(s);
System.out.println("-----------------");
File[] listFiles = root.listFiles(f -> !f.isDirectory());
for (File f : listFiles) System.out.println(f);
}
}
| 2,761 | 0.559796 | 0.559433 | 91 | 29.23077 | 21.097406 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.626374 | false | false | 3 |
800943c186546a5c9f0b5c83d171186f6fe9993f | 13,305,808,727,931 | dadf3c1ace8485b15422c34c08d79a48112f2179 | /src/main/java/com/example/DemoApplication.java | 4ff5e269cccd44ff13150518fe33600d045aca59 | [] | no_license | ayne/springboot-demo | https://github.com/ayne/springboot-demo | 9ba29717b2f3cc310256e27e31f8a0aa0710af7b | ccc46a2d35ce40efbe8c31e09410dd3fde99259e | refs/heads/master | 2021-01-23T02:43:40.029000 | 2017-03-24T05:12:42 | 2017-03-24T05:12:42 | 86,021,198 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@SpringBootApplication
@Slf4j
public class DemoApplication implements CommandLineRunner { //implementing CommandLineRunner is not needed if you don't want to execute jdbc command on application startup
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public void run(String... strings) throws Exception {
//auto insert user in DB. for demo purposed only
try {
String encryptedPassword = new BCryptPasswordEncoder().encode("pHiLippE");
jdbcTemplate.execute("INSERT INTO users (id, email, password) VALUES (1, \'charmane.santiago@gmail.com\'," +
" \'" + encryptedPassword + "\')");
} catch (DataIntegrityViolationException e) {
log.warn("DataIntegrityException during insertion of user ", e);
}
}
}
| UTF-8 | Java | 1,305 | java | DemoApplication.java | Java | [
{
"context": "tedPassword = new BCryptPasswordEncoder().encode(\"pHiLippE\");\n\t\t\tjdbcTemplate.execute(\"INSERT INTO users (id",
"end": 1022,
"score": 0.9981875419616699,
"start": 1014,
"tag": "PASSWORD",
"value": "pHiLippE"
},
{
"context": "ERT INTO users (id, email, password) VALUES (1, \\'charmane.santiago@gmail.com\\',\" +\n\t\t\t\t\t\" \\'\" + encryptedPassword + \"\\')\");\n\t\t",
"end": 1131,
"score": 0.9988484978675842,
"start": 1104,
"tag": "EMAIL",
"value": "charmane.santiago@gmail.com"
}
] | null | [] | package com.example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@SpringBootApplication
@Slf4j
public class DemoApplication implements CommandLineRunner { //implementing CommandLineRunner is not needed if you don't want to execute jdbc command on application startup
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public void run(String... strings) throws Exception {
//auto insert user in DB. for demo purposed only
try {
String encryptedPassword = new BCryptPasswordEncoder().encode("<PASSWORD>");
jdbcTemplate.execute("INSERT INTO users (id, email, password) VALUES (1, \'<EMAIL>\'," +
" \'" + encryptedPassword + "\')");
} catch (DataIntegrityViolationException e) {
log.warn("DataIntegrityException during insertion of user ", e);
}
}
}
| 1,287 | 0.791571 | 0.788506 | 35 | 36.285713 | 36.939774 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.457143 | false | false | 3 |
e6690dc6bdeac75a8e3db2bd780df0256bb19289 | 18,829,136,626,050 | 8dfd406e855dbef74ef6b80e7b1fcde43d0b7d56 | /springboot-ws-cxf-service-mutil-ds/src/main/java/com/hdwang/dao/datajpa/firstDs/UserRepository.java | bcabfee1920a4d6c3dea58f843866021174bdbe9 | [] | no_license | iechenyb/springboot | https://github.com/iechenyb/springboot | db0e4caaf545721f5b6a70d97cce2af2cbbd0797 | 46e541a6319bfced7d2445038464ce249b409e83 | refs/heads/master | 2021-01-20T01:35:04.050000 | 2019-05-16T02:02:04 | 2019-05-16T02:02:04 | 89,299,676 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hdwang.dao.datajpa.firstDs;
import com.hdwang.entity.dbFirst.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import javax.persistence.PersistenceContext;
/**
* Created by hdwang on 2017-06-17.
*/
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
/**
* spring data jpa 会自动注入实现(根据方法命名规范)
* @return
*/
User findByNumber(String number);
@Modifying
@Query("delete from User u where u.id = :id")
void deleteUser(@Param("id")int id);
}
| UTF-8 | Java | 1,009 | java | UserRepository.java | Java | [
{
"context": "sistence.PersistenceContext;\r\n\r\n/**\r\n * Created by hdwang on 2017-06-17.\r\n */\r\n@Repository\r\npublic interfac",
"end": 637,
"score": 0.9993012547492981,
"start": 631,
"tag": "USERNAME",
"value": "hdwang"
}
] | null | [] | package com.hdwang.dao.datajpa.firstDs;
import com.hdwang.entity.dbFirst.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import javax.persistence.PersistenceContext;
/**
* Created by hdwang on 2017-06-17.
*/
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
/**
* spring data jpa 会自动注入实现(根据方法命名规范)
* @return
*/
User findByNumber(String number);
@Modifying
@Query("delete from User u where u.id = :id")
void deleteUser(@Param("id")int id);
}
| 1,009 | 0.757949 | 0.749744 | 30 | 30.5 | 24.34988 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 3 |
f63700ab7b85ef98d3d0fe05d23d0dff5e0a0fc4 | 27,865,747,834,624 | e1e6ad3569a2fcd6a67ba02dcad7848219cde1de | /app/src/main/java/com/panaceasoft/psbuyandsell/ui/offlinepayment/adapter/OfflinePaymentAdapter.java | a9bd6b66ec958a81df829dfdf4b3735b1b2ba7a8 | [] | no_license | RITEKROUNAK/BUYSELL-JAVA | https://github.com/RITEKROUNAK/BUYSELL-JAVA | c1146c841801523b96045320a6801babc3b66d54 | bf9b1f1ddce364900d351b8a0981f4dfe6b227d0 | refs/heads/main | 2023-03-27T14:20:18.621000 | 2021-03-27T03:31:52 | 2021-03-27T03:31:52 | 333,428,865 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.panaceasoft.psbuyandsell.ui.offlinepayment.adapter;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.databinding.DataBindingUtil;
import com.panaceasoft.psbuyandsell.R;
import com.panaceasoft.psbuyandsell.databinding.ItemOfflinepaymentBinding;
import com.panaceasoft.psbuyandsell.ui.common.DataBoundListAdapter;
import com.panaceasoft.psbuyandsell.utils.Constants;
import com.panaceasoft.psbuyandsell.utils.Objects;
import com.panaceasoft.psbuyandsell.viewobject.OfflinePayment;
public class OfflinePaymentAdapter extends DataBoundListAdapter<OfflinePayment, ItemOfflinepaymentBinding> {
private final androidx.databinding.DataBindingComponent dataBindingComponent;
private OfflinePaymentClickCallback callback;
private DataBoundListAdapter.DiffUtilDispatchedInterface diffUtilDispatchedInterface;
public OfflinePaymentAdapter(androidx.databinding.DataBindingComponent dataBindingComponent,
OfflinePaymentClickCallback callback,
DiffUtilDispatchedInterface diffUtilDispatchedInterface) {
this.dataBindingComponent = dataBindingComponent;
this.callback = callback;
this.diffUtilDispatchedInterface = diffUtilDispatchedInterface;
}
@Override
protected ItemOfflinepaymentBinding createBinding(ViewGroup parent) {
ItemOfflinepaymentBinding binding = DataBindingUtil
.inflate(LayoutInflater.from(parent.getContext()),
R.layout.item_offlinepayment, parent, false,
dataBindingComponent);
binding.getRoot().setOnClickListener(v -> {
OfflinePayment offlinePayment = binding.getOfflinePayment();
if (offlinePayment != null && callback != null) {
callback.onClick(offlinePayment);
}
});
return binding;
}
@Override
protected void dispatched() {
if (diffUtilDispatchedInterface != null) {
diffUtilDispatchedInterface.onDispatched();
}
}
@Override
protected void bind(ItemOfflinepaymentBinding binding, OfflinePayment offlinePaymentMethod) {
binding.setOfflinePayment(offlinePaymentMethod);
if (offlinePaymentMethod.equals(Constants.ONE)) {
binding.OfflinePaymentConstraintLayout.setBackgroundColor(binding.getRoot().getResources().getColor(R.color.md_grey_200));
} else {
binding.OfflinePaymentConstraintLayout.setBackgroundColor(binding.getRoot().getResources().getColor(R.color.md_white_1000));
}
binding.titleTextView.setText(offlinePaymentMethod.title);
binding.descriptionTextView.setText(offlinePaymentMethod.description);
}
@Override
protected boolean areItemsTheSame(OfflinePayment oldItem, OfflinePayment newItem) {
return Objects.equals(oldItem.id, newItem.id)
&& oldItem.title.equals(newItem.title)
&& oldItem.description.equals(newItem.description);
}
@Override
protected boolean areContentsTheSame(OfflinePayment oldItem, OfflinePayment newItem) {
return Objects.equals(oldItem.id, newItem.id)
&& oldItem.title.equals(newItem.title)
&& oldItem.description.equals(newItem.description);
}
public interface OfflinePaymentClickCallback {
void onClick(OfflinePayment offlinePaymentMethod);
}
}
| UTF-8 | Java | 3,470 | java | OfflinePaymentAdapter.java | Java | [] | null | [] | package com.panaceasoft.psbuyandsell.ui.offlinepayment.adapter;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.databinding.DataBindingUtil;
import com.panaceasoft.psbuyandsell.R;
import com.panaceasoft.psbuyandsell.databinding.ItemOfflinepaymentBinding;
import com.panaceasoft.psbuyandsell.ui.common.DataBoundListAdapter;
import com.panaceasoft.psbuyandsell.utils.Constants;
import com.panaceasoft.psbuyandsell.utils.Objects;
import com.panaceasoft.psbuyandsell.viewobject.OfflinePayment;
public class OfflinePaymentAdapter extends DataBoundListAdapter<OfflinePayment, ItemOfflinepaymentBinding> {
private final androidx.databinding.DataBindingComponent dataBindingComponent;
private OfflinePaymentClickCallback callback;
private DataBoundListAdapter.DiffUtilDispatchedInterface diffUtilDispatchedInterface;
public OfflinePaymentAdapter(androidx.databinding.DataBindingComponent dataBindingComponent,
OfflinePaymentClickCallback callback,
DiffUtilDispatchedInterface diffUtilDispatchedInterface) {
this.dataBindingComponent = dataBindingComponent;
this.callback = callback;
this.diffUtilDispatchedInterface = diffUtilDispatchedInterface;
}
@Override
protected ItemOfflinepaymentBinding createBinding(ViewGroup parent) {
ItemOfflinepaymentBinding binding = DataBindingUtil
.inflate(LayoutInflater.from(parent.getContext()),
R.layout.item_offlinepayment, parent, false,
dataBindingComponent);
binding.getRoot().setOnClickListener(v -> {
OfflinePayment offlinePayment = binding.getOfflinePayment();
if (offlinePayment != null && callback != null) {
callback.onClick(offlinePayment);
}
});
return binding;
}
@Override
protected void dispatched() {
if (diffUtilDispatchedInterface != null) {
diffUtilDispatchedInterface.onDispatched();
}
}
@Override
protected void bind(ItemOfflinepaymentBinding binding, OfflinePayment offlinePaymentMethod) {
binding.setOfflinePayment(offlinePaymentMethod);
if (offlinePaymentMethod.equals(Constants.ONE)) {
binding.OfflinePaymentConstraintLayout.setBackgroundColor(binding.getRoot().getResources().getColor(R.color.md_grey_200));
} else {
binding.OfflinePaymentConstraintLayout.setBackgroundColor(binding.getRoot().getResources().getColor(R.color.md_white_1000));
}
binding.titleTextView.setText(offlinePaymentMethod.title);
binding.descriptionTextView.setText(offlinePaymentMethod.description);
}
@Override
protected boolean areItemsTheSame(OfflinePayment oldItem, OfflinePayment newItem) {
return Objects.equals(oldItem.id, newItem.id)
&& oldItem.title.equals(newItem.title)
&& oldItem.description.equals(newItem.description);
}
@Override
protected boolean areContentsTheSame(OfflinePayment oldItem, OfflinePayment newItem) {
return Objects.equals(oldItem.id, newItem.id)
&& oldItem.title.equals(newItem.title)
&& oldItem.description.equals(newItem.description);
}
public interface OfflinePaymentClickCallback {
void onClick(OfflinePayment offlinePaymentMethod);
}
}
| 3,470 | 0.720461 | 0.718444 | 84 | 40.309525 | 34.556019 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
5f9680cdb365454a33640ad04fb38cb8a34f6224 | 5,394,478,930,369 | eb7d04c6c3228f513fe33a26e3fcf0123c5d50b8 | /GuitarSearchV3/src/main/java/mysqlDAO/IGuitarDAOImpl.java | 9d8d5f73f8d49f0e63608701a2a216caf28ee54c | [] | no_license | Rutabaga1/GuitarVersionThree | https://github.com/Rutabaga1/GuitarVersionThree | f9a035828fe8d8b71302d006811885f27ff04ed6 | 9994cd70f859170fe9e4bac46aaa5bef8d68bbe4 | refs/heads/master | 2021-01-19T04:27:26.326000 | 2016-06-13T05:18:52 | 2016-06-13T05:18:52 | 61,007,850 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.java.mysqlDAO;
import main.java.model.Guitar;
import main.java.model.Inventory;
import java.util.List;
import main.java.guitarDAO.IGuitar;
public class IGuitarDAOImpl implements IGuitar {
@Override
public Inventory getGuitars() {
// TODO Auto-generated method stub
return null;
}
@Override
public void addNewGuitar(Guitar guitar, String inventoryNum) {
// TODO Auto-generated method stub
}
@Override
public List<Guitar> getAllGuitars() {
// TODO Auto-generated method stub
return null;
}
@Override
public void deleteGuitar(String[] serialNumber) {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 639 | java | IGuitarDAOImpl.java | Java | [] | null | [] | package main.java.mysqlDAO;
import main.java.model.Guitar;
import main.java.model.Inventory;
import java.util.List;
import main.java.guitarDAO.IGuitar;
public class IGuitarDAOImpl implements IGuitar {
@Override
public Inventory getGuitars() {
// TODO Auto-generated method stub
return null;
}
@Override
public void addNewGuitar(Guitar guitar, String inventoryNum) {
// TODO Auto-generated method stub
}
@Override
public List<Guitar> getAllGuitars() {
// TODO Auto-generated method stub
return null;
}
@Override
public void deleteGuitar(String[] serialNumber) {
// TODO Auto-generated method stub
}
}
| 639 | 0.738654 | 0.738654 | 36 | 16.75 | 17.926353 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 3 |
0148b1891a1202ff0fee67b892fb45f270463ead | 13,503,377,183,278 | 7d28d457ababf1b982f32a66a8896b764efba1e8 | /platform-web-resources/src/main/java/ua/com/fielden/platform/web/rx/eventsources/ProcessingProgressEventSource.java | 99410b51334c7dadb76c5ce32042f839b86b2ec2 | [
"MIT"
] | permissive | fieldenms/tg | https://github.com/fieldenms/tg | f742f332343f29387e0cb7a667f6cf163d06d101 | f145a85a05582b7f26cc52d531de9835f12a5e2d | refs/heads/develop | 2023-08-31T16:10:16.475000 | 2023-08-30T08:23:18 | 2023-08-30T08:23:18 | 20,488,386 | 17 | 9 | MIT | false | 2023-09-14T17:07:35 | 2014-06-04T15:09:44 | 2023-04-26T19:57:23 | 2023-09-14T17:07:34 | 172,430 | 14 | 8 | 226 | JavaScript | false | false | package ua.com.fielden.platform.web.rx.eventsources;
import static ua.com.fielden.platform.types.tuples.T2.t2;
import static ua.com.fielden.platform.utils.CollectionUtil.mapOf;
import java.util.Map;
import ua.com.fielden.platform.rx.observables.ProcessingProgressSubject;
import ua.com.fielden.platform.serialisation.api.ISerialiser;
import ua.com.fielden.platform.web.sse.AbstractEventSource;
/**
* This is a generic event source that should be used to update on events from subject of type {@link ProcessingProgressSubject}.
*
* @author TG Team
*
*/
public class ProcessingProgressEventSource extends AbstractEventSource<Integer, ProcessingProgressSubject> {
private final String jobUid;
public ProcessingProgressEventSource(final ProcessingProgressSubject observableKind, final String jobUid, final ISerialiser serialiser) {
super(observableKind, serialiser);
this.jobUid = jobUid;
}
@Override
protected Map<String, Object> eventToData(final Integer event) {
return mapOf(t2("prc", event), t2("jobUid", jobUid));
}
} | UTF-8 | Java | 1,080 | java | ProcessingProgressEventSource.java | Java | [
{
"context": "e {@link ProcessingProgressSubject}.\n *\n * @author TG Team\n *\n */\npublic class ProcessingProgressEventSource",
"end": 553,
"score": 0.9614962935447693,
"start": 546,
"tag": "NAME",
"value": "TG Team"
}
] | null | [] | package ua.com.fielden.platform.web.rx.eventsources;
import static ua.com.fielden.platform.types.tuples.T2.t2;
import static ua.com.fielden.platform.utils.CollectionUtil.mapOf;
import java.util.Map;
import ua.com.fielden.platform.rx.observables.ProcessingProgressSubject;
import ua.com.fielden.platform.serialisation.api.ISerialiser;
import ua.com.fielden.platform.web.sse.AbstractEventSource;
/**
* This is a generic event source that should be used to update on events from subject of type {@link ProcessingProgressSubject}.
*
* @author <NAME>
*
*/
public class ProcessingProgressEventSource extends AbstractEventSource<Integer, ProcessingProgressSubject> {
private final String jobUid;
public ProcessingProgressEventSource(final ProcessingProgressSubject observableKind, final String jobUid, final ISerialiser serialiser) {
super(observableKind, serialiser);
this.jobUid = jobUid;
}
@Override
protected Map<String, Object> eventToData(final Integer event) {
return mapOf(t2("prc", event), t2("jobUid", jobUid));
}
} | 1,079 | 0.769444 | 0.765741 | 32 | 32.78125 | 39.269688 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.59375 | false | false | 3 |
5a20a68f3e2535f39ce77eac916b69905529911e | 17,428,977,293,478 | 2fd231104ab649cd0b8bfe6c32ec8a216f1050b6 | /Controller.java | 2925550e5ed545250dcc19e3af0b296862aea353 | [] | no_license | GangadharMS/Recommender-System | https://github.com/GangadharMS/Recommender-System | 9e03c27b4b11e45bcea119c7c278ebbf8adb7521 | c25bd6a3bbc7bb901f801273bca583d350f54f6a | refs/heads/master | 2021-01-13T04:16:47.473000 | 2016-12-27T18:25:31 | 2016-12-27T18:25:31 | 77,474,642 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import org.junit.runners.Parameterized.UseParametersRunnerFactory;
import matrix.Matrix;
import matrix.NoSquareException;
import regression.MultiLinear;
public class Controller {
public static void main(String[] args){
System.out.println("Model building in progress...");
Scanner inputSource = null;
double[][] userRatingMatrix = new double[80000][2];
double[][] ratingMatrix = new double[80000][1];
int i = 0, j = 0, k = 0, l = 0;
Matrix beta = null;
try {
inputSource = new Scanner(new File("train_all_txt.txt"));
} catch (FileNotFoundException e) {
System.out.println("Specified file didn't found in the directory.");
System.exit(0);
}
while(inputSource.hasNext()){
j = 0;
String eachLine = inputSource.nextLine();
String eachLineContent[]=eachLine.split("\\s");
if(Integer.parseInt(eachLineContent[0]) == i){
}
userRatingMatrix[i][j++] = Double.parseDouble(eachLineContent[0]);
userRatingMatrix[i++][j] = Double.parseDouble(eachLineContent[1]);
ratingMatrix[k++][l] = Double.parseDouble(eachLineContent[2]);
}
//System.out.println("completed....i value is "+i +" k value is "+k);
final Matrix X = new Matrix(userRatingMatrix);
final Matrix Y = new Matrix(ratingMatrix);
final MultiLinear ml = new MultiLinear(X, Y);
try {
beta = ml.calculate();
assertNotNull(beta);
} catch (NoSquareException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Model construction completed.");
printY(Y, X, beta, true);
}
private static void printY(final Matrix Y, final Matrix X, final Matrix beta, final boolean bias) {
System.out.println("Prediction is in progress using the model constructed...");
PrintWriter outputWriter = null;
double[][] test = new double[1586126][3];
// System.out.println(beta.getValueAt(0, 0));
// System.out.println(beta.getValueAt(1, 0));
// System.out.println(beta.getValueAt(2, 0));
int count = 1;
int user = count;
int item = count;
for(int i=0;i<1586126;i++){//1586126
if(item == 1683){
user = ++ count;
item = 1;
}
test[i][0] = user;
test[i][1] = item++;
//System.out.println(test[i][0]+"->"+test[i][1]);
}
//System.out.println("item is "+item);
final Matrix testMatrix = new Matrix(test);
if (bias) {
for (int i=0;i<testMatrix.getNrows();i++) {
double predictedY = beta.getValueAt(0, 0);
for (int j=1; j< beta.getNrows(); j++) {
predictedY += beta.getValueAt(j, 0) * testMatrix.getValueAt(i, j-1);
}
//testMatrix.setValueAt(i, 2, Math.round(predictedY));
testMatrix.setValueAt(i, 2, predictedY);
//System.out.println(Y.getValueAt(i, 0) + " -> " + predictedY);
//outputWriter.println( predictedY);//Y.getValueAt(i, 0) +
}
//System.out.println("check "+testMatrix);
// for(int temp = 0; temp<testMatrix.getNrows();temp++){
// System.out.println(testMatrix.getValueAt(temp, 0) +"-->"+ testMatrix.getValueAt(temp, 1)
// +" = "+testMatrix.getValueAt(temp, 2));
// }
}
try {
try {
outputWriter = new PrintWriter("results.txt", "UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int temp = 0; temp<testMatrix.getNrows();temp++){
outputWriter.println(Math.round(testMatrix.getValueAt(temp, 0)) +" "+ Math.round(testMatrix.getValueAt(temp, 1))
+" "+testMatrix.getValueAt(temp, 2));
}
outputWriter.close();
System.out.println("Prediction completed, check results.txt");
}
}
| UTF-8 | Java | 4,013 | java | Controller.java | Java | [] | null | [] | import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import org.junit.runners.Parameterized.UseParametersRunnerFactory;
import matrix.Matrix;
import matrix.NoSquareException;
import regression.MultiLinear;
public class Controller {
public static void main(String[] args){
System.out.println("Model building in progress...");
Scanner inputSource = null;
double[][] userRatingMatrix = new double[80000][2];
double[][] ratingMatrix = new double[80000][1];
int i = 0, j = 0, k = 0, l = 0;
Matrix beta = null;
try {
inputSource = new Scanner(new File("train_all_txt.txt"));
} catch (FileNotFoundException e) {
System.out.println("Specified file didn't found in the directory.");
System.exit(0);
}
while(inputSource.hasNext()){
j = 0;
String eachLine = inputSource.nextLine();
String eachLineContent[]=eachLine.split("\\s");
if(Integer.parseInt(eachLineContent[0]) == i){
}
userRatingMatrix[i][j++] = Double.parseDouble(eachLineContent[0]);
userRatingMatrix[i++][j] = Double.parseDouble(eachLineContent[1]);
ratingMatrix[k++][l] = Double.parseDouble(eachLineContent[2]);
}
//System.out.println("completed....i value is "+i +" k value is "+k);
final Matrix X = new Matrix(userRatingMatrix);
final Matrix Y = new Matrix(ratingMatrix);
final MultiLinear ml = new MultiLinear(X, Y);
try {
beta = ml.calculate();
assertNotNull(beta);
} catch (NoSquareException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Model construction completed.");
printY(Y, X, beta, true);
}
private static void printY(final Matrix Y, final Matrix X, final Matrix beta, final boolean bias) {
System.out.println("Prediction is in progress using the model constructed...");
PrintWriter outputWriter = null;
double[][] test = new double[1586126][3];
// System.out.println(beta.getValueAt(0, 0));
// System.out.println(beta.getValueAt(1, 0));
// System.out.println(beta.getValueAt(2, 0));
int count = 1;
int user = count;
int item = count;
for(int i=0;i<1586126;i++){//1586126
if(item == 1683){
user = ++ count;
item = 1;
}
test[i][0] = user;
test[i][1] = item++;
//System.out.println(test[i][0]+"->"+test[i][1]);
}
//System.out.println("item is "+item);
final Matrix testMatrix = new Matrix(test);
if (bias) {
for (int i=0;i<testMatrix.getNrows();i++) {
double predictedY = beta.getValueAt(0, 0);
for (int j=1; j< beta.getNrows(); j++) {
predictedY += beta.getValueAt(j, 0) * testMatrix.getValueAt(i, j-1);
}
//testMatrix.setValueAt(i, 2, Math.round(predictedY));
testMatrix.setValueAt(i, 2, predictedY);
//System.out.println(Y.getValueAt(i, 0) + " -> " + predictedY);
//outputWriter.println( predictedY);//Y.getValueAt(i, 0) +
}
//System.out.println("check "+testMatrix);
// for(int temp = 0; temp<testMatrix.getNrows();temp++){
// System.out.println(testMatrix.getValueAt(temp, 0) +"-->"+ testMatrix.getValueAt(temp, 1)
// +" = "+testMatrix.getValueAt(temp, 2));
// }
}
try {
try {
outputWriter = new PrintWriter("results.txt", "UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int temp = 0; temp<testMatrix.getNrows();temp++){
outputWriter.println(Math.round(testMatrix.getValueAt(temp, 0)) +" "+ Math.round(testMatrix.getValueAt(temp, 1))
+" "+testMatrix.getValueAt(temp, 2));
}
outputWriter.close();
System.out.println("Prediction completed, check results.txt");
}
}
| 4,013 | 0.640169 | 0.620234 | 123 | 30.626017 | 24.668665 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.235772 | false | false | 3 |
5b99b1d54e076c20f64e695d8ee12805e7999a20 | 10,144,712,764,219 | 1c30efa3180f5a4fcba99c12b55d92b6f5bf6333 | /src/main/java/generated/ubdab/omkry/varfq/fioum/wnymk/Class004659.java | 9c9ee4e9c110e59cc7d0872062301e36755695b7 | [] | no_license | mojira/MojirAI.git | https://github.com/mojira/MojirAI.git | e4adc643511d943620e364ce46719bd02392484d | 5934d64874e54fddabb16826dfb5af397988825c | refs/heads/main | 2021-06-09T15:12:12.938000 | 2021-04-01T21:30:16 | 2021-04-01T21:30:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package generated.ubdab.omkry.varfq.fioum.wnymk;
import helpers.Config;
import helpers.Context;
import helpers.BullshifierException;
import java.util.*;
import java.util.logging.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class Class004659
{
public static final Logger logger = LoggerFactory.getLogger(Class004659.class);
public static final int classId = 4659;
public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
public static void method000(Context context) throws Exception
{
int methodId = 0;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 0);
// Start of fake locals generator
List<Object> root = new LinkedList<Object>();
int valWaeenaodmik = 18;
root.add(valWaeenaodmik);
boolean valHnrddjacvuc = false;
root.add(valHnrddjacvuc);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method000 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method000 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method000MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method000MethodToCall)
{
case (0): generated.rjmsm.xxzei.wsput.puwzz.rjpki.Class003616.method006(context); return;
case (1): generated.xxaxf.xvjit.bojww.lyocj.ahqyk.Class007644.method008(context); return;
case (2): generated.wythi.gxdsu.brtpd.zpijq.wcpzo.Class001396.method003(context); return;
case (3): generated.ylmyd.tobmp.myekl.fiunc.rfzot.Class004426.method004(context); return;
case (4): generated.yuzuq.ygdih.dpbuh.gsurr.jufaf.Class003552.method001(context); return;
case (5): generated.kkibc.cqbns.uxkdl.isbev.kbdor.Class004992.method003(context); return;
case (6): generated.dnsgr.kipqg.cdzzf.ujmrj.tlkqb.Class003890.method008(context); return;
case (7): generated.jnkry.ojngq.ggnun.xgjtx.ivamm.Class009351.method002(context); return;
case (8): generated.sbuno.dgebg.wthka.gnkis.orwzg.Class002413.method003(context); return;
case (9): generated.atemr.rqzwi.lwxgr.nfcio.eekpc.Class004784.method008(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method001(Context context) throws Exception
{
int methodId = 1;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 1);
// Start of fake locals generator
Set<Object> root = new HashSet<Object>();
int valVqcuuwhjlkl = 275;
root.add(valVqcuuwhjlkl);
int valYmncgumemyh = 665;
root.add(valYmncgumemyh);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method001 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method001 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method001MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method001MethodToCall)
{
case (0): generated.mlhhn.gaovg.tzmjt.kpgve.jxubh.Class006554.method004(context); return;
case (1): generated.xtrpy.psgev.bffou.yqpmb.qmpgj.Class004005.method004(context); return;
case (2): generated.misil.fxpnu.kiiff.lynlv.ibtxt.Class009536.method009(context); return;
case (3): generated.tujhl.sgwvn.rxjdd.tnthc.liyjn.Class009873.method008(context); return;
case (4): generated.mbhlq.bnuvj.edhqg.antkj.iuneq.Class004017.method007(context); return;
case (5): generated.smrgb.pdekg.dbhlh.zglzc.cdxyp.Class005441.method007(context); return;
case (6): generated.ahzwe.zxfac.pipej.yfjyu.omvwq.Class002833.method001(context); return;
case (7): generated.dcese.fwdok.ozojs.djcwh.tpixr.Class007744.method007(context); return;
case (8): generated.wogfa.dalnz.aoyhm.eafsz.ntsdz.Class009448.method009(context); return;
case (9): generated.tyugx.sahkj.keika.amkbo.uqkkj.Class008858.method002(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method002(Context context) throws Exception
{
int methodId = 2;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 2);
// Start of fake locals generator
Object[] root = new Object[4];
int valFgizragjpur = 839;
root[0] = valFgizragjpur;
for (int i = 1; i < 4; i++)
{
root[i] = Config.get().getRandom().nextInt(1000);
}
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method002 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method002 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method002MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method002MethodToCall)
{
case (0): generated.yjlkr.uakpw.lmgkx.ajeyp.vppua.Class002383.method006(context); return;
case (1): generated.tfssy.zckfi.kzogl.fzgfl.rnibm.Class000669.method000(context); return;
case (2): generated.prjvh.erlne.kdprl.expvb.jqupc.Class005531.method002(context); return;
case (3): generated.xhbyn.hqwgw.uzbfg.worhm.arasu.Class003099.method002(context); return;
case (4): generated.ipccf.xjkuu.xyagi.itgcp.ezhyv.Class007189.method000(context); return;
case (5): generated.xzjbi.pfvle.ueaoa.yitxv.gxegl.Class005826.method006(context); return;
case (6): generated.tnkky.chiup.ahozq.ngkrm.hmila.Class000381.method006(context); return;
case (7): generated.ppcsu.ixrbw.hscfn.ftvds.koxmc.Class000189.method005(context); return;
case (8): generated.oheee.jltrl.benmn.suxld.owrvt.Class003048.method004(context); return;
case (9): generated.xcoqt.frfwq.tbuzd.rdjod.afuzq.Class000058.method008(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method003(Context context) throws Exception
{
int methodId = 3;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 3);
// Start of fake locals generator
Set<Object> root = new HashSet<Object>();
int valSyhqipztxqa = 778;
root.add(valSyhqipztxqa);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method003 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method003 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method003MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method003MethodToCall)
{
case (0): generated.xcxpa.qjqlu.zrsze.heuld.yushk.Class000289.method007(context); return;
case (1): generated.ikmsq.bqtjm.cgfcs.gbjln.plaza.Class002964.method002(context); return;
case (2): generated.eplbb.dgrfi.onpsd.okequ.sunjg.Class002221.method003(context); return;
case (3): generated.fxlrd.cpdta.dwgia.nfaqp.mljqk.Class009279.method008(context); return;
case (4): generated.vzamm.tzkaq.ibsuv.vzxwj.sprxl.Class003816.method009(context); return;
case (5): generated.vvxrn.kqmdm.nnygk.fjlbi.lwneq.Class003632.method008(context); return;
case (6): generated.nottp.vgiye.qlvbt.prmoc.fjhqw.Class001773.method002(context); return;
case (7): generated.moevg.lqhcw.cjvlm.ggift.mgwco.Class002263.method009(context); return;
case (8): generated.amdwt.opivt.gylty.ghayn.hweky.Class003490.method003(context); return;
case (9): generated.mxjhd.mfmzp.zbyzu.ojcfu.snyey.Class000596.method005(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method004(Context context) throws Exception
{
int methodId = 4;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 4);
// Start of fake locals generator
Object[] root = new Object[10];
int valWctozhtamde = 259;
root[0] = valWctozhtamde;
for (int i = 1; i < 10; i++)
{
root[i] = Config.get().getRandom().nextInt(1000);
}
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method004 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method004 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method004MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method004MethodToCall)
{
case (0): generated.fqjna.qsehr.omkio.psmgg.vzmzl.Class003566.method001(context); return;
case (1): generated.rxvtg.lcanz.zynhg.euzxb.zkdou.Class003724.method005(context); return;
case (2): generated.zsumr.zlauk.pwvbm.choah.vlyyb.Class003627.method003(context); return;
case (3): generated.yeigx.fohda.xusnn.qzvef.xgjpj.Class005752.method008(context); return;
case (4): generated.iczbw.wlcui.ngkhh.pegmp.xjbqp.Class002100.method008(context); return;
case (5): generated.wjgvh.uchhu.hypbk.avpyp.ndcoz.Class008037.method007(context); return;
case (6): generated.oainp.jwwqi.nxhew.lzgjf.daibw.Class001269.method006(context); return;
case (7): generated.wuith.hswwm.qgrye.alhpu.hfmxa.Class001299.method009(context); return;
case (8): generated.jujtb.btrrz.xjnjb.sopvj.rxwjl.Class003971.method007(context); return;
case (9): generated.wlxuv.ipgzm.zcgqi.sxtkg.kaxjh.Class007388.method008(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method005(Context context) throws Exception
{
int methodId = 5;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 5);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
boolean mapValKpsxepyyrbb = false;
boolean mapKeyMqhdjdbrngy = true;
root.put("mapValKpsxepyyrbb","mapKeyMqhdjdbrngy" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method005 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method005 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method005MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method005MethodToCall)
{
case (0): generated.wpcke.hvbxr.zaqom.annee.jzwuk.Class002800.method007(context); return;
case (1): generated.xolzi.wyyqi.kttzg.khrcg.edlel.Class005722.method009(context); return;
case (2): generated.dghlw.neqwh.pngav.rnnlb.ywfdz.Class005667.method003(context); return;
case (3): generated.adfgl.ztvqk.yehdf.idsue.getqv.Class000708.method007(context); return;
case (4): generated.gjocz.fcytn.jncrg.wbjyh.afqcq.Class001277.method000(context); return;
case (5): generated.mucrn.nbgcw.ciibp.dfkez.zxybw.Class001155.method009(context); return;
case (6): generated.mreml.ltcys.gnjbh.vegwg.renxr.Class000851.method003(context); return;
case (7): generated.bmwxq.azouz.pdyew.asfgd.pwvol.Class007658.method000(context); return;
case (8): generated.hjmeq.wdccj.boyao.vdmva.pjufp.Class003606.method005(context); return;
case (9): generated.raigv.gbcze.pwzgs.ncntu.ihesb.Class005037.method006(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method006(Context context) throws Exception
{
int methodId = 6;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 6);
// Start of fake locals generator
List<Object> root = new LinkedList<Object>();
String valDnxybaxgplf = "StrMknjmvkmbya";
root.add(valDnxybaxgplf);
boolean valNhzqvvfqaqt = true;
root.add(valNhzqvvfqaqt);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method006 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method006 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method006MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method006MethodToCall)
{
case (0): generated.xgzpx.wqpcf.krigh.xzkjj.eibct.Class004394.method007(context); return;
case (1): generated.vcghz.ryymf.cpwts.sqyth.daoix.Class000003.method007(context); return;
case (2): generated.rhjcs.rzvyg.orhap.bvfgn.flsjn.Class008986.method001(context); return;
case (3): generated.stvds.xmsay.owgcc.jundy.zyiqk.Class001473.method009(context); return;
case (4): generated.nzajw.ikmov.absmv.wncwl.pavkh.Class008205.method002(context); return;
case (5): generated.uwppw.diplq.ogbum.bkysl.luprb.Class000211.method000(context); return;
case (6): generated.jywwd.gwzdi.smkmo.rloic.emonb.Class006366.method000(context); return;
case (7): generated.mhmvo.fpuzb.zsgzc.cuumt.kpdta.Class008575.method000(context); return;
case (8): generated.nvdxp.zsiim.czvip.ucrll.urgfg.Class003267.method005(context); return;
case (9): generated.xwwpr.xjgvw.yzxac.drehz.uwffa.Class009847.method007(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method007(Context context) throws Exception
{
int methodId = 7;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 7);
// Start of fake locals generator
Set<Object> root = new HashSet<Object>();
boolean valJfmgjygaqwb = false;
root.add(valJfmgjygaqwb);
long valNlpkpxvtwaa = 2230277200246268573L;
root.add(valNlpkpxvtwaa);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method007 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method007 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method007MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method007MethodToCall)
{
case (0): generated.utkol.xwgqi.blpwj.qxlmp.ihwmz.Class007094.method009(context); return;
case (1): generated.cgyfa.mpscu.lavkz.zjfos.pzgcx.Class002488.method005(context); return;
case (2): generated.yczqk.rivbx.ziooz.gpwun.hdedk.Class000543.method001(context); return;
case (3): generated.lbnng.sufqc.mtcka.wffhn.jhpex.Class005067.method005(context); return;
case (4): generated.wjtyw.kpbwx.iqpbx.mtoom.tyeso.Class009182.method006(context); return;
case (5): generated.zvtxr.zqcqk.nglks.rogiv.immjo.Class002802.method004(context); return;
case (6): generated.qupqr.avsmd.jplvj.lbucl.izfju.Class004343.method005(context); return;
case (7): generated.odrte.jmogm.fzejq.vdwzg.tmyrx.Class000839.method002(context); return;
case (8): generated.lnjxa.irbvp.ggfkk.vwtog.tjixu.Class000232.method006(context); return;
case (9): generated.eeobk.zvejg.dwbxc.wmkty.eynab.Class005070.method000(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method008(Context context) throws Exception
{
int methodId = 8;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 8);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
int mapValPkaasofnign = 574;
int mapKeyFfvhedrwqmv = 871;
root.put("mapValPkaasofnign","mapKeyFfvhedrwqmv" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method008 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method008 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method008MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method008MethodToCall)
{
case (0): generated.kgzbs.vafnm.aucet.capvx.ftljl.Class004672.method004(context); return;
case (1): generated.mcuqx.bgmac.npdix.hiaul.clzmy.Class009038.method001(context); return;
case (2): generated.olasq.ojdyg.ltxml.ttcpj.vvike.Class003511.method006(context); return;
case (3): generated.obhff.sfzfd.galct.hpcky.isuxj.Class008004.method008(context); return;
case (4): generated.wumiz.wzaqv.vfwyf.tpnii.unvez.Class006394.method004(context); return;
case (5): generated.cqubd.btiob.cfmxj.sncjl.jyqoo.Class007632.method008(context); return;
case (6): generated.woqlv.iqkkn.fhcvn.qsixn.hkpny.Class005141.method005(context); return;
case (7): generated.jdntf.gjtuc.iznav.dxiig.bupnn.Class007596.method005(context); return;
case (8): generated.ovwrg.omxxn.nykkk.hqetw.xmwko.Class002585.method006(context); return;
case (9): generated.swdsq.dnaix.znero.azdhv.lbcib.Class002092.method006(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method009(Context context) throws Exception
{
int methodId = 9;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 9);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
String mapValXropnvleyip = "StrVureqqjknzd";
int mapKeyGfjnaxtrgut = 165;
root.put("mapValXropnvleyip","mapKeyGfjnaxtrgut" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method009 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method009 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method009MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method009MethodToCall)
{
case (0): generated.jjhnj.raike.oadee.rzfxr.jlqkg.Class006752.method005(context); return;
case (1): generated.eplbb.dgrfi.onpsd.okequ.sunjg.Class002221.method001(context); return;
case (2): generated.lecbu.lcbpd.woyus.corsc.qzboc.Class002179.method002(context); return;
case (3): generated.sqyaq.cthme.hemhc.ndtov.mzyiq.Class007877.method004(context); return;
case (4): generated.ucgqu.olcog.vvkae.ubrht.hlklq.Class006246.method009(context); return;
case (5): generated.iztgn.hkdzz.rcgew.sqkjk.rmlef.Class006704.method009(context); return;
case (6): generated.oxwir.lqtms.nyrbs.swmbm.mkptp.Class000209.method004(context); return;
case (7): generated.yxoka.xitod.hlzzu.vhuyr.xgbmm.Class003669.method009(context); return;
case (8): generated.axmle.vtzyq.tpgat.hpqan.yjzsl.Class007690.method008(context); return;
case (9): generated.dhxgl.bimcs.byzml.tfjlk.dvbqd.Class000234.method003(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
}
| UTF-8 | Java | 33,621 | java | Class004659.java | Java | [
{
"context": "= \"StrVureqqjknzd\";\n\t\t\n\t\tint mapKeyGfjnaxtrgut = 165;\n\t\t\n\t\troot.put(\"mapValXropnvleyip\",\"mapKeyGfjnaxt",
"end": 30673,
"score": 0.555810809135437,
"start": 30671,
"tag": "KEY",
"value": "65"
}
] | null | [] | package generated.ubdab.omkry.varfq.fioum.wnymk;
import helpers.Config;
import helpers.Context;
import helpers.BullshifierException;
import java.util.*;
import java.util.logging.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class Class004659
{
public static final Logger logger = LoggerFactory.getLogger(Class004659.class);
public static final int classId = 4659;
public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
public static void method000(Context context) throws Exception
{
int methodId = 0;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 0);
// Start of fake locals generator
List<Object> root = new LinkedList<Object>();
int valWaeenaodmik = 18;
root.add(valWaeenaodmik);
boolean valHnrddjacvuc = false;
root.add(valHnrddjacvuc);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method000 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method000 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method000MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method000MethodToCall)
{
case (0): generated.rjmsm.xxzei.wsput.puwzz.rjpki.Class003616.method006(context); return;
case (1): generated.xxaxf.xvjit.bojww.lyocj.ahqyk.Class007644.method008(context); return;
case (2): generated.wythi.gxdsu.brtpd.zpijq.wcpzo.Class001396.method003(context); return;
case (3): generated.ylmyd.tobmp.myekl.fiunc.rfzot.Class004426.method004(context); return;
case (4): generated.yuzuq.ygdih.dpbuh.gsurr.jufaf.Class003552.method001(context); return;
case (5): generated.kkibc.cqbns.uxkdl.isbev.kbdor.Class004992.method003(context); return;
case (6): generated.dnsgr.kipqg.cdzzf.ujmrj.tlkqb.Class003890.method008(context); return;
case (7): generated.jnkry.ojngq.ggnun.xgjtx.ivamm.Class009351.method002(context); return;
case (8): generated.sbuno.dgebg.wthka.gnkis.orwzg.Class002413.method003(context); return;
case (9): generated.atemr.rqzwi.lwxgr.nfcio.eekpc.Class004784.method008(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method001(Context context) throws Exception
{
int methodId = 1;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 1);
// Start of fake locals generator
Set<Object> root = new HashSet<Object>();
int valVqcuuwhjlkl = 275;
root.add(valVqcuuwhjlkl);
int valYmncgumemyh = 665;
root.add(valYmncgumemyh);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method001 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method001 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method001MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method001MethodToCall)
{
case (0): generated.mlhhn.gaovg.tzmjt.kpgve.jxubh.Class006554.method004(context); return;
case (1): generated.xtrpy.psgev.bffou.yqpmb.qmpgj.Class004005.method004(context); return;
case (2): generated.misil.fxpnu.kiiff.lynlv.ibtxt.Class009536.method009(context); return;
case (3): generated.tujhl.sgwvn.rxjdd.tnthc.liyjn.Class009873.method008(context); return;
case (4): generated.mbhlq.bnuvj.edhqg.antkj.iuneq.Class004017.method007(context); return;
case (5): generated.smrgb.pdekg.dbhlh.zglzc.cdxyp.Class005441.method007(context); return;
case (6): generated.ahzwe.zxfac.pipej.yfjyu.omvwq.Class002833.method001(context); return;
case (7): generated.dcese.fwdok.ozojs.djcwh.tpixr.Class007744.method007(context); return;
case (8): generated.wogfa.dalnz.aoyhm.eafsz.ntsdz.Class009448.method009(context); return;
case (9): generated.tyugx.sahkj.keika.amkbo.uqkkj.Class008858.method002(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method002(Context context) throws Exception
{
int methodId = 2;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 2);
// Start of fake locals generator
Object[] root = new Object[4];
int valFgizragjpur = 839;
root[0] = valFgizragjpur;
for (int i = 1; i < 4; i++)
{
root[i] = Config.get().getRandom().nextInt(1000);
}
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method002 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method002 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method002MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method002MethodToCall)
{
case (0): generated.yjlkr.uakpw.lmgkx.ajeyp.vppua.Class002383.method006(context); return;
case (1): generated.tfssy.zckfi.kzogl.fzgfl.rnibm.Class000669.method000(context); return;
case (2): generated.prjvh.erlne.kdprl.expvb.jqupc.Class005531.method002(context); return;
case (3): generated.xhbyn.hqwgw.uzbfg.worhm.arasu.Class003099.method002(context); return;
case (4): generated.ipccf.xjkuu.xyagi.itgcp.ezhyv.Class007189.method000(context); return;
case (5): generated.xzjbi.pfvle.ueaoa.yitxv.gxegl.Class005826.method006(context); return;
case (6): generated.tnkky.chiup.ahozq.ngkrm.hmila.Class000381.method006(context); return;
case (7): generated.ppcsu.ixrbw.hscfn.ftvds.koxmc.Class000189.method005(context); return;
case (8): generated.oheee.jltrl.benmn.suxld.owrvt.Class003048.method004(context); return;
case (9): generated.xcoqt.frfwq.tbuzd.rdjod.afuzq.Class000058.method008(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method003(Context context) throws Exception
{
int methodId = 3;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 3);
// Start of fake locals generator
Set<Object> root = new HashSet<Object>();
int valSyhqipztxqa = 778;
root.add(valSyhqipztxqa);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method003 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method003 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method003MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method003MethodToCall)
{
case (0): generated.xcxpa.qjqlu.zrsze.heuld.yushk.Class000289.method007(context); return;
case (1): generated.ikmsq.bqtjm.cgfcs.gbjln.plaza.Class002964.method002(context); return;
case (2): generated.eplbb.dgrfi.onpsd.okequ.sunjg.Class002221.method003(context); return;
case (3): generated.fxlrd.cpdta.dwgia.nfaqp.mljqk.Class009279.method008(context); return;
case (4): generated.vzamm.tzkaq.ibsuv.vzxwj.sprxl.Class003816.method009(context); return;
case (5): generated.vvxrn.kqmdm.nnygk.fjlbi.lwneq.Class003632.method008(context); return;
case (6): generated.nottp.vgiye.qlvbt.prmoc.fjhqw.Class001773.method002(context); return;
case (7): generated.moevg.lqhcw.cjvlm.ggift.mgwco.Class002263.method009(context); return;
case (8): generated.amdwt.opivt.gylty.ghayn.hweky.Class003490.method003(context); return;
case (9): generated.mxjhd.mfmzp.zbyzu.ojcfu.snyey.Class000596.method005(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method004(Context context) throws Exception
{
int methodId = 4;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 4);
// Start of fake locals generator
Object[] root = new Object[10];
int valWctozhtamde = 259;
root[0] = valWctozhtamde;
for (int i = 1; i < 10; i++)
{
root[i] = Config.get().getRandom().nextInt(1000);
}
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method004 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method004 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method004MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method004MethodToCall)
{
case (0): generated.fqjna.qsehr.omkio.psmgg.vzmzl.Class003566.method001(context); return;
case (1): generated.rxvtg.lcanz.zynhg.euzxb.zkdou.Class003724.method005(context); return;
case (2): generated.zsumr.zlauk.pwvbm.choah.vlyyb.Class003627.method003(context); return;
case (3): generated.yeigx.fohda.xusnn.qzvef.xgjpj.Class005752.method008(context); return;
case (4): generated.iczbw.wlcui.ngkhh.pegmp.xjbqp.Class002100.method008(context); return;
case (5): generated.wjgvh.uchhu.hypbk.avpyp.ndcoz.Class008037.method007(context); return;
case (6): generated.oainp.jwwqi.nxhew.lzgjf.daibw.Class001269.method006(context); return;
case (7): generated.wuith.hswwm.qgrye.alhpu.hfmxa.Class001299.method009(context); return;
case (8): generated.jujtb.btrrz.xjnjb.sopvj.rxwjl.Class003971.method007(context); return;
case (9): generated.wlxuv.ipgzm.zcgqi.sxtkg.kaxjh.Class007388.method008(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method005(Context context) throws Exception
{
int methodId = 5;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 5);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
boolean mapValKpsxepyyrbb = false;
boolean mapKeyMqhdjdbrngy = true;
root.put("mapValKpsxepyyrbb","mapKeyMqhdjdbrngy" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method005 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method005 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method005MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method005MethodToCall)
{
case (0): generated.wpcke.hvbxr.zaqom.annee.jzwuk.Class002800.method007(context); return;
case (1): generated.xolzi.wyyqi.kttzg.khrcg.edlel.Class005722.method009(context); return;
case (2): generated.dghlw.neqwh.pngav.rnnlb.ywfdz.Class005667.method003(context); return;
case (3): generated.adfgl.ztvqk.yehdf.idsue.getqv.Class000708.method007(context); return;
case (4): generated.gjocz.fcytn.jncrg.wbjyh.afqcq.Class001277.method000(context); return;
case (5): generated.mucrn.nbgcw.ciibp.dfkez.zxybw.Class001155.method009(context); return;
case (6): generated.mreml.ltcys.gnjbh.vegwg.renxr.Class000851.method003(context); return;
case (7): generated.bmwxq.azouz.pdyew.asfgd.pwvol.Class007658.method000(context); return;
case (8): generated.hjmeq.wdccj.boyao.vdmva.pjufp.Class003606.method005(context); return;
case (9): generated.raigv.gbcze.pwzgs.ncntu.ihesb.Class005037.method006(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method006(Context context) throws Exception
{
int methodId = 6;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 6);
// Start of fake locals generator
List<Object> root = new LinkedList<Object>();
String valDnxybaxgplf = "StrMknjmvkmbya";
root.add(valDnxybaxgplf);
boolean valNhzqvvfqaqt = true;
root.add(valNhzqvvfqaqt);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method006 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method006 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method006MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method006MethodToCall)
{
case (0): generated.xgzpx.wqpcf.krigh.xzkjj.eibct.Class004394.method007(context); return;
case (1): generated.vcghz.ryymf.cpwts.sqyth.daoix.Class000003.method007(context); return;
case (2): generated.rhjcs.rzvyg.orhap.bvfgn.flsjn.Class008986.method001(context); return;
case (3): generated.stvds.xmsay.owgcc.jundy.zyiqk.Class001473.method009(context); return;
case (4): generated.nzajw.ikmov.absmv.wncwl.pavkh.Class008205.method002(context); return;
case (5): generated.uwppw.diplq.ogbum.bkysl.luprb.Class000211.method000(context); return;
case (6): generated.jywwd.gwzdi.smkmo.rloic.emonb.Class006366.method000(context); return;
case (7): generated.mhmvo.fpuzb.zsgzc.cuumt.kpdta.Class008575.method000(context); return;
case (8): generated.nvdxp.zsiim.czvip.ucrll.urgfg.Class003267.method005(context); return;
case (9): generated.xwwpr.xjgvw.yzxac.drehz.uwffa.Class009847.method007(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method007(Context context) throws Exception
{
int methodId = 7;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 7);
// Start of fake locals generator
Set<Object> root = new HashSet<Object>();
boolean valJfmgjygaqwb = false;
root.add(valJfmgjygaqwb);
long valNlpkpxvtwaa = 2230277200246268573L;
root.add(valNlpkpxvtwaa);
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method007 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method007 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method007MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method007MethodToCall)
{
case (0): generated.utkol.xwgqi.blpwj.qxlmp.ihwmz.Class007094.method009(context); return;
case (1): generated.cgyfa.mpscu.lavkz.zjfos.pzgcx.Class002488.method005(context); return;
case (2): generated.yczqk.rivbx.ziooz.gpwun.hdedk.Class000543.method001(context); return;
case (3): generated.lbnng.sufqc.mtcka.wffhn.jhpex.Class005067.method005(context); return;
case (4): generated.wjtyw.kpbwx.iqpbx.mtoom.tyeso.Class009182.method006(context); return;
case (5): generated.zvtxr.zqcqk.nglks.rogiv.immjo.Class002802.method004(context); return;
case (6): generated.qupqr.avsmd.jplvj.lbucl.izfju.Class004343.method005(context); return;
case (7): generated.odrte.jmogm.fzejq.vdwzg.tmyrx.Class000839.method002(context); return;
case (8): generated.lnjxa.irbvp.ggfkk.vwtog.tjixu.Class000232.method006(context); return;
case (9): generated.eeobk.zvejg.dwbxc.wmkty.eynab.Class005070.method000(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method008(Context context) throws Exception
{
int methodId = 8;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 8);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
int mapValPkaasofnign = 574;
int mapKeyFfvhedrwqmv = 871;
root.put("mapValPkaasofnign","mapKeyFfvhedrwqmv" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method008 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method008 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method008MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method008MethodToCall)
{
case (0): generated.kgzbs.vafnm.aucet.capvx.ftljl.Class004672.method004(context); return;
case (1): generated.mcuqx.bgmac.npdix.hiaul.clzmy.Class009038.method001(context); return;
case (2): generated.olasq.ojdyg.ltxml.ttcpj.vvike.Class003511.method006(context); return;
case (3): generated.obhff.sfzfd.galct.hpcky.isuxj.Class008004.method008(context); return;
case (4): generated.wumiz.wzaqv.vfwyf.tpnii.unvez.Class006394.method004(context); return;
case (5): generated.cqubd.btiob.cfmxj.sncjl.jyqoo.Class007632.method008(context); return;
case (6): generated.woqlv.iqkkn.fhcvn.qsixn.hkpny.Class005141.method005(context); return;
case (7): generated.jdntf.gjtuc.iznav.dxiig.bupnn.Class007596.method005(context); return;
case (8): generated.ovwrg.omxxn.nykkk.hqetw.xmwko.Class002585.method006(context); return;
case (9): generated.swdsq.dnaix.znero.azdhv.lbcib.Class002092.method006(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
public static void method009(Context context) throws Exception
{
int methodId = 9;
Integer entryPointNum = Config.get().entryPointIndex.get(); Config.get().updateContext(context, entryPointNum, 4659, 9);
// Start of fake locals generator
Map<Object, Object> root = new HashMap();
String mapValXropnvleyip = "StrVureqqjknzd";
int mapKeyGfjnaxtrgut = 165;
root.put("mapValXropnvleyip","mapKeyGfjnaxtrgut" );
// End of fake locals generator
String currentTime = dateFormat.format(new Date());
long currentTimeMillis = System.currentTimeMillis();
if (Config.get().shouldWriteLogInfo(context))
{
logger.info("Class004659.method009 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
if (Config.get().shouldWriteLogWarn(context))
{
logger.warn("Class004659.method009 called at {} (millis: {}) (stack-depth: {}) (prev method fail rate is: {})",
currentTime, System.currentTimeMillis(), context.framesDepth, context.lastSpotPrecentage);
}
context.instructionIndex = 1;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 2;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
context.instructionIndex = 3;
if (Config.get().shouldFireEvent(context))
{
BullshifierException.incHitsCount(context);
throw BullshifierException.build(context);
}
if (Config.get().shouldSuicide())
{
System.exit(0);
}
if (Config.get().shouldRunAway(context))
{
return;
}
try
{
int method009MethodToCall = Config.get().getStickyPath(classId, methodId, 10);
switch (method009MethodToCall)
{
case (0): generated.jjhnj.raike.oadee.rzfxr.jlqkg.Class006752.method005(context); return;
case (1): generated.eplbb.dgrfi.onpsd.okequ.sunjg.Class002221.method001(context); return;
case (2): generated.lecbu.lcbpd.woyus.corsc.qzboc.Class002179.method002(context); return;
case (3): generated.sqyaq.cthme.hemhc.ndtov.mzyiq.Class007877.method004(context); return;
case (4): generated.ucgqu.olcog.vvkae.ubrht.hlklq.Class006246.method009(context); return;
case (5): generated.iztgn.hkdzz.rcgew.sqkjk.rmlef.Class006704.method009(context); return;
case (6): generated.oxwir.lqtms.nyrbs.swmbm.mkptp.Class000209.method004(context); return;
case (7): generated.yxoka.xitod.hlzzu.vhuyr.xgbmm.Class003669.method009(context); return;
case (8): generated.axmle.vtzyq.tpgat.hpqan.yjzsl.Class007690.method008(context); return;
case (9): generated.dhxgl.bimcs.byzml.tfjlk.dvbqd.Class000234.method003(context); return;
}
}
catch (Exception e)
{
if (Config.get().shouldWriteLogError(context))
{
String serverName = System.getProperty("takipi.server.name");
String agentName = System.getProperty("takipi.name");
String deploymentName = System.getProperty("takipi.deployment.name");
logger.error("An error from ({}/{}/{})", serverName, agentName, deploymentName, e);
}
}
if (Boolean.parseBoolean("true")) { return; }
}
}
| 33,621 | 0.713483 | 0.66973 | 1,006 | 32.420479 | 35.027412 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.01491 | false | false | 3 |
48ebda0b1a74e49f2704e870a1e7637947efec88 | 33,457,795,246,764 | d0fac4c540c83fb1dadde0cbcab2b50844b6daa3 | /src/main/java/com/rodrigo/rodriservices/domain/enums/EstadoPagamento.java | 214ec0b5c4ef30eb99e8e6c339c5adaa630cb7a7 | [] | no_license | RodrigoRodrigues7/Rodri-Services_Backend | https://github.com/RodrigoRodrigues7/Rodri-Services_Backend | bee3091899c18ae32b5793a5b8f4efafb143034b | f456dccc38df05c0cf0da0e24149750ad4a58bdc | refs/heads/master | 2020-04-12T23:26:56.632000 | 2019-04-03T02:04:03 | 2019-04-03T02:04:03 | 162,819,788 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rodrigo.rodriservices.domain.enums;
public enum EstadoPagamento {
PENDENTE(1, "Pendente"),
QUITADO(2, "Quitado"),
CANCELADO(3, "Cancelado");
private int codigo;
private String descricao;
private EstadoPagamento(int codigo, String descricao) {
this.codigo = codigo;
this.descricao = descricao;
}
public int getCodigo() {
return codigo;
}
public String getDescricao() {
return descricao;
}
/*
* Metodo que recebe um código e retorna um objeto 'EstadoPagamento'
* instanciado.(Retorna baseado no código passado).
*/
public static EstadoPagamento toEnum(Integer codigo) {
if (codigo == null) {
return null;
}
// Esse for percorre todos os valores possíveis deste Enum 'TipoCliente'
for (EstadoPagamento x : EstadoPagamento.values()) {
if (codigo.equals(x.getCodigo())) {
return x;
}
}
throw new IllegalArgumentException("Id Inválido: " + codigo);
}
}
| UTF-8 | Java | 933 | java | EstadoPagamento.java | Java | [] | null | [] | package com.rodrigo.rodriservices.domain.enums;
public enum EstadoPagamento {
PENDENTE(1, "Pendente"),
QUITADO(2, "Quitado"),
CANCELADO(3, "Cancelado");
private int codigo;
private String descricao;
private EstadoPagamento(int codigo, String descricao) {
this.codigo = codigo;
this.descricao = descricao;
}
public int getCodigo() {
return codigo;
}
public String getDescricao() {
return descricao;
}
/*
* Metodo que recebe um código e retorna um objeto 'EstadoPagamento'
* instanciado.(Retorna baseado no código passado).
*/
public static EstadoPagamento toEnum(Integer codigo) {
if (codigo == null) {
return null;
}
// Esse for percorre todos os valores possíveis deste Enum 'TipoCliente'
for (EstadoPagamento x : EstadoPagamento.values()) {
if (codigo.equals(x.getCodigo())) {
return x;
}
}
throw new IllegalArgumentException("Id Inválido: " + codigo);
}
}
| 933 | 0.696448 | 0.693219 | 45 | 19.644444 | 21.422892 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.622222 | false | false | 3 |
0c86e45cfc6f4aebbd1e900e4987e26624ce5f68 | 12,223,476,934,049 | fbe301a2d72fd8b20b6bb78fff531861cbc69329 | /remap-core/src/main/java/koncept/remapped/meta/ReMapperMeta.java | 01d54900a6a83208768fd4d27a1bf05fb2102488 | [
"MIT"
] | permissive | nkrul/remapped | https://github.com/nkrul/remapped | 8f1841a66a19737b7929dce151dbabf6a3dd46bc | f07fbc9b1b84df265ad308ce4deae7b1c8973328 | refs/heads/master | 2017-12-21T19:57:01.829000 | 2014-10-12T22:09:58 | 2014-10-12T22:09:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package koncept.remapped.meta;
import java.util.HashMap;
import java.util.Map;
public class ReMapperMeta {
private final Class<?> type;
private final String versionTag;
private final int minorVersionRevision;
public ReMapperMeta(Map<String, String> map) {
try {
type = Class.forName(map.get("type"));
versionTag = map.get("versionTag");
minorVersionRevision = Integer.parseInt(map.get("minorVersionRevision"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public ReMapperMeta(Class<?> type, String versionTag, int minorVersionRevision) {
this.type = type;
this.versionTag = versionTag;
this.minorVersionRevision = minorVersionRevision;
}
public Class<?> getType() {
return type;
}
public String getVersionTag() {
return versionTag;
}
public int getMinorVersionRevision() {
return minorVersionRevision;
}
public Map<String, String> toMap() {
Map<String, String> map = new HashMap<String, String>();
map.put("type", type.getCanonicalName());
map.put("versionTag", versionTag);
map.put("minorVersionRevision", Integer.toString(minorVersionRevision));
return map;
}
}
| UTF-8 | Java | 1,189 | java | ReMapperMeta.java | Java | [] | null | [] | package koncept.remapped.meta;
import java.util.HashMap;
import java.util.Map;
public class ReMapperMeta {
private final Class<?> type;
private final String versionTag;
private final int minorVersionRevision;
public ReMapperMeta(Map<String, String> map) {
try {
type = Class.forName(map.get("type"));
versionTag = map.get("versionTag");
minorVersionRevision = Integer.parseInt(map.get("minorVersionRevision"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public ReMapperMeta(Class<?> type, String versionTag, int minorVersionRevision) {
this.type = type;
this.versionTag = versionTag;
this.minorVersionRevision = minorVersionRevision;
}
public Class<?> getType() {
return type;
}
public String getVersionTag() {
return versionTag;
}
public int getMinorVersionRevision() {
return minorVersionRevision;
}
public Map<String, String> toMap() {
Map<String, String> map = new HashMap<String, String>();
map.put("type", type.getCanonicalName());
map.put("versionTag", versionTag);
map.put("minorVersionRevision", Integer.toString(minorVersionRevision));
return map;
}
}
| 1,189 | 0.696384 | 0.696384 | 46 | 23.847826 | 21.853233 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.891304 | false | false | 3 |
9c00af5556672bd48bff57249a4b26a428dd7709 | 15,839,839,400,161 | 3952da905c97827a695313c974539f382636f949 | /app/src/main/java/com/garyhu/imagedemo/widget/charts/listener/DummyCompoLineColumnChartOnValueSelectListener.java | 3c42b91fc374a4cb95548e597dd7349e9223df0e | [
"Apache-2.0"
] | permissive | garyhu1/ChartView | https://github.com/garyhu1/ChartView | 014d770da02e96f550e9e204666f36c0043c93a8 | bcf1ee3275169e90b7b2eb8ab71af9d77c5837f7 | refs/heads/master | 2021-01-02T09:44:14.972000 | 2017-02-20T07:44:12 | 2017-02-20T07:44:12 | 78,715,020 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.garyhu.imagedemo.widget.charts.listener;
import com.garyhu.imagedemo.widget.charts.model.PointValue;
import com.garyhu.imagedemo.widget.charts.model.SubcolumnValue;
public class DummyCompoLineColumnChartOnValueSelectListener implements ComboLineColumnChartOnValueSelectListener {
@Override
public void onColumnValueSelected(int columnIndex, int subcolumnIndex, SubcolumnValue value) {
}
@Override
public void onPointValueSelected(int lineIndex, int pointIndex, PointValue value) {
}
@Override
public void onValueDeselected() {
}
}
| UTF-8 | Java | 588 | java | DummyCompoLineColumnChartOnValueSelectListener.java | Java | [] | null | [] | package com.garyhu.imagedemo.widget.charts.listener;
import com.garyhu.imagedemo.widget.charts.model.PointValue;
import com.garyhu.imagedemo.widget.charts.model.SubcolumnValue;
public class DummyCompoLineColumnChartOnValueSelectListener implements ComboLineColumnChartOnValueSelectListener {
@Override
public void onColumnValueSelected(int columnIndex, int subcolumnIndex, SubcolumnValue value) {
}
@Override
public void onPointValueSelected(int lineIndex, int pointIndex, PointValue value) {
}
@Override
public void onValueDeselected() {
}
}
| 588 | 0.784014 | 0.784014 | 23 | 24.565218 | 35.136784 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false | 3 |
49091d8654ebee82538985c97be1617651db7317 | 12,472,585,038,377 | 8cf0c3d6a0ac636d0abccfe494cab9ef7b0b1deb | /S-Query-examples/order-payment-jobs/order-payment-job/src/main/java/org/example/state/StockStateSerializer.java | 95fe3099d571bcb72d0224a52cb39d0782a225ce | [
"Apache-2.0"
] | permissive | delftdata/s-query | https://github.com/delftdata/s-query | f6d22236f1cdcde2eba2ca3741ad8e64b93ac223 | a8197e64b9630263d5a7a29cfa47e8a5f8c75e54 | refs/heads/master | 2023-08-31T16:41:48.796000 | 2021-11-03T20:18:22 | 2021-11-03T20:18:22 | 416,636,860 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.example.state;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;
import java.io.IOException;
public class StockStateSerializer implements StreamSerializer<StockState> {
@Override
public void write(ObjectDataOutput out, StockState object) throws IOException {
out.writeLong(object.getStock());
}
@Override
public StockState read(ObjectDataInput in) throws IOException {
return new StockState(in.readLong());
}
@Override
public int getTypeId() {
return 7;
}
}
| UTF-8 | Java | 627 | java | StockStateSerializer.java | Java | [] | null | [] | package org.example.state;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;
import java.io.IOException;
public class StockStateSerializer implements StreamSerializer<StockState> {
@Override
public void write(ObjectDataOutput out, StockState object) throws IOException {
out.writeLong(object.getStock());
}
@Override
public StockState read(ObjectDataInput in) throws IOException {
return new StockState(in.readLong());
}
@Override
public int getTypeId() {
return 7;
}
}
| 627 | 0.733652 | 0.732057 | 24 | 25.125 | 25.166632 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 3 |
7c51ac30c6a2d225406c218d41ceb02eb27ce8dc | 16,149,077,049,457 | 3b02c24cc65685a4e4997bd509d9bd5c3e5fec92 | /obdalib-sesame/src/main/java/it/unibz/krdb/obda/sesame/SesameStatement.java | e11d326e577eb6724ff6ae5e12464a9fa6eb6f7b | [
"Apache-2.0",
"CC-BY-4.0"
] | permissive | EvgenyKarataev/ontop | https://github.com/EvgenyKarataev/ontop | c5bd62879ab048641e407541706e0aacca2122cb | e0080a6c7fbf7bac5e0bbe70103b30dce0b5909d | refs/heads/master | 2020-12-13T18:25:00.904000 | 2014-10-10T10:23:43 | 2014-10-10T10:23:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.unibz.krdb.obda.sesame;
/*
* #%L
* ontop-obdalib-sesame
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import it.unibz.krdb.obda.model.BNode;
import it.unibz.krdb.obda.model.Constant;
import it.unibz.krdb.obda.model.Predicate;
import it.unibz.krdb.obda.model.URIConstant;
import it.unibz.krdb.obda.model.ValueConstant;
import it.unibz.krdb.obda.model.Predicate.COL_TYPE;
import it.unibz.krdb.obda.model.impl.OBDAVocabulary;
import it.unibz.krdb.obda.ontology.Assertion;
import it.unibz.krdb.obda.ontology.BinaryAssertion;
import it.unibz.krdb.obda.ontology.ClassAssertion;
import it.unibz.krdb.obda.ontology.UnaryAssertion;
import org.openrdf.model.Literal;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.ValueFactoryImpl;
public class SesameStatement implements Statement {
private static final long serialVersionUID = 3398547980791013746L;
private Resource subject = null;
private URI predicate = null;
private Value object = null;
private Resource context = null;
private ValueFactory fact = new ValueFactoryImpl();
public SesameStatement(Assertion assertion) {
Constant subj;
if (assertion instanceof BinaryAssertion) {
//object or data property assertion
BinaryAssertion ba = (BinaryAssertion) assertion;
subj = ba.getValue1();
Predicate pred = ba.getPredicate();
Constant obj = ba.getValue2();
// convert string into respective type
if (subj instanceof BNode)
subject = fact.createBNode(((BNode) subj).getName());
else if (subj instanceof URIConstant)
subject = fact.createURI(subj.getValue());
else if (subj instanceof ValueConstant)
throw new RuntimeException("Invalid ValueConstant as subject!");
predicate = fact.createURI(pred.getName().toString()); // URI
if (obj instanceof BNode)
object = fact.createBNode(((BNode) obj).getName());
else if (obj instanceof URIConstant)
object = fact.createURI(obj.getValue());
else if (obj instanceof ValueConstant)
object = getLiteral((ValueConstant)obj);
} else if (assertion instanceof UnaryAssertion) {
//class assertion
UnaryAssertion ua = (UnaryAssertion) assertion;
subj = ua.getValue();
String pred = OBDAVocabulary.RDF_TYPE;
Predicate obj = ua.getPredicate();
// convert string into respective type
if (subj instanceof BNode)
subject = fact.createBNode(((BNode) subj).getName());
else if (subj instanceof URIConstant)
subject = fact.createURI(subj.getValue());
else if (subj instanceof ValueConstant)
throw new RuntimeException("Invalid ValueConstant as subject!");
predicate = fact.createURI(pred); // URI
object = fact.createURI(obj.getName().toString());
}
}
private Literal getLiteral(ValueConstant literal)
{
URI datatype = null;
if (literal.getType() == COL_TYPE.BOOLEAN)
datatype = fact
.createURI(OBDAVocabulary.XSD_BOOLEAN_URI);
else if (literal.getType() == COL_TYPE.DATETIME)
datatype = fact
.createURI(OBDAVocabulary.XSD_DATETIME_URI);
else if (literal.getType() == COL_TYPE.DECIMAL)
datatype = fact
.createURI(OBDAVocabulary.XSD_DECIMAL_URI);
else if (literal.getType() == COL_TYPE.DOUBLE)
datatype = fact
.createURI(OBDAVocabulary.XSD_DOUBLE_URI);
else if (literal.getType() == COL_TYPE.INTEGER)
datatype = fact
.createURI(OBDAVocabulary.XSD_INTEGER_URI);
else if (literal.getType() == COL_TYPE.LITERAL)
datatype = null;
else if (literal.getType() == COL_TYPE.LITERAL_LANG)
{
datatype = null;
return fact.createLiteral(literal.getValue(), literal.getLanguage());
}
else if (literal.getType() == COL_TYPE.OBJECT)
datatype = fact
.createURI(OBDAVocabulary.XSD_STRING_URI);
else if (literal.getType() == COL_TYPE.STRING)
datatype = fact
.createURI(OBDAVocabulary.XSD_STRING_URI);
Literal value = fact.createLiteral(literal.getValue(), datatype);
return value;
}
public Resource getSubject() {
return subject;
}
public URI getPredicate() {
return predicate;
}
public Value getObject() {
return object;
}
public Resource getContext() {
// TODO Auto-generated method stub
return context;
}
@Override
public String toString()
{
return "("+subject+", "+predicate+", "+object+")";
}
}
| UTF-8 | Java | 5,011 | java | SesameStatement.java | Java | [] | null | [] | package it.unibz.krdb.obda.sesame;
/*
* #%L
* ontop-obdalib-sesame
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import it.unibz.krdb.obda.model.BNode;
import it.unibz.krdb.obda.model.Constant;
import it.unibz.krdb.obda.model.Predicate;
import it.unibz.krdb.obda.model.URIConstant;
import it.unibz.krdb.obda.model.ValueConstant;
import it.unibz.krdb.obda.model.Predicate.COL_TYPE;
import it.unibz.krdb.obda.model.impl.OBDAVocabulary;
import it.unibz.krdb.obda.ontology.Assertion;
import it.unibz.krdb.obda.ontology.BinaryAssertion;
import it.unibz.krdb.obda.ontology.ClassAssertion;
import it.unibz.krdb.obda.ontology.UnaryAssertion;
import org.openrdf.model.Literal;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.ValueFactoryImpl;
public class SesameStatement implements Statement {
private static final long serialVersionUID = 3398547980791013746L;
private Resource subject = null;
private URI predicate = null;
private Value object = null;
private Resource context = null;
private ValueFactory fact = new ValueFactoryImpl();
public SesameStatement(Assertion assertion) {
Constant subj;
if (assertion instanceof BinaryAssertion) {
//object or data property assertion
BinaryAssertion ba = (BinaryAssertion) assertion;
subj = ba.getValue1();
Predicate pred = ba.getPredicate();
Constant obj = ba.getValue2();
// convert string into respective type
if (subj instanceof BNode)
subject = fact.createBNode(((BNode) subj).getName());
else if (subj instanceof URIConstant)
subject = fact.createURI(subj.getValue());
else if (subj instanceof ValueConstant)
throw new RuntimeException("Invalid ValueConstant as subject!");
predicate = fact.createURI(pred.getName().toString()); // URI
if (obj instanceof BNode)
object = fact.createBNode(((BNode) obj).getName());
else if (obj instanceof URIConstant)
object = fact.createURI(obj.getValue());
else if (obj instanceof ValueConstant)
object = getLiteral((ValueConstant)obj);
} else if (assertion instanceof UnaryAssertion) {
//class assertion
UnaryAssertion ua = (UnaryAssertion) assertion;
subj = ua.getValue();
String pred = OBDAVocabulary.RDF_TYPE;
Predicate obj = ua.getPredicate();
// convert string into respective type
if (subj instanceof BNode)
subject = fact.createBNode(((BNode) subj).getName());
else if (subj instanceof URIConstant)
subject = fact.createURI(subj.getValue());
else if (subj instanceof ValueConstant)
throw new RuntimeException("Invalid ValueConstant as subject!");
predicate = fact.createURI(pred); // URI
object = fact.createURI(obj.getName().toString());
}
}
private Literal getLiteral(ValueConstant literal)
{
URI datatype = null;
if (literal.getType() == COL_TYPE.BOOLEAN)
datatype = fact
.createURI(OBDAVocabulary.XSD_BOOLEAN_URI);
else if (literal.getType() == COL_TYPE.DATETIME)
datatype = fact
.createURI(OBDAVocabulary.XSD_DATETIME_URI);
else if (literal.getType() == COL_TYPE.DECIMAL)
datatype = fact
.createURI(OBDAVocabulary.XSD_DECIMAL_URI);
else if (literal.getType() == COL_TYPE.DOUBLE)
datatype = fact
.createURI(OBDAVocabulary.XSD_DOUBLE_URI);
else if (literal.getType() == COL_TYPE.INTEGER)
datatype = fact
.createURI(OBDAVocabulary.XSD_INTEGER_URI);
else if (literal.getType() == COL_TYPE.LITERAL)
datatype = null;
else if (literal.getType() == COL_TYPE.LITERAL_LANG)
{
datatype = null;
return fact.createLiteral(literal.getValue(), literal.getLanguage());
}
else if (literal.getType() == COL_TYPE.OBJECT)
datatype = fact
.createURI(OBDAVocabulary.XSD_STRING_URI);
else if (literal.getType() == COL_TYPE.STRING)
datatype = fact
.createURI(OBDAVocabulary.XSD_STRING_URI);
Literal value = fact.createLiteral(literal.getValue(), datatype);
return value;
}
public Resource getSubject() {
return subject;
}
public URI getPredicate() {
return predicate;
}
public Value getObject() {
return object;
}
public Resource getContext() {
// TODO Auto-generated method stub
return context;
}
@Override
public String toString()
{
return "("+subject+", "+predicate+", "+object+")";
}
}
| 5,011 | 0.720415 | 0.71383 | 160 | 30.31875 | 21.583666 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.1875 | false | false | 3 |
8a90bf1addbe1ac02819631c45b28b6a2ec3ddd1 | 25,804,163,531,037 | a75fd02177db87acc4da00bb6a277c7d442b7a70 | /Exercicios-POO/Exer4/src/Exer4Test.java | 01f21084309590cc1dc4d5f6764a256fdabe9148 | [] | no_license | victor99z/poo-exercises | https://github.com/victor99z/poo-exercises | 4271e8b5036773c87b4b3ca1f784f782566c4d93 | e1c61ca0496d2b2756dcea171347bf8ebbc51596 | refs/heads/master | 2021-10-27T02:48:59.720000 | 2019-04-15T14:02:37 | 2019-04-15T14:02:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.IOException;
public class Exer4Test {
public static void main(String[] args){
// TODO Auto-generated method stub
Exer4 e1 = new Exer4("C:\\Users\\victo\\Documents\\workspace\\workspace-java\\Exercicios-POO\\Exer4\\src\\AT02.txt");
e1.AddMatch("ASDB", 11, "Brasil", 12);
}
}
| UTF-8 | Java | 304 | java | Exer4Test.java | Java | [
{
"context": "method stub\n\t\t\n\t\tExer4 e1 = new Exer4(\"C:\\\\Users\\\\victo\\\\Documents\\\\workspace\\\\workspace-java\\\\Exercicios",
"end": 176,
"score": 0.8777725696563721,
"start": 171,
"tag": "USERNAME",
"value": "victo"
}
] | null | [] | import java.io.IOException;
public class Exer4Test {
public static void main(String[] args){
// TODO Auto-generated method stub
Exer4 e1 = new Exer4("C:\\Users\\victo\\Documents\\workspace\\workspace-java\\Exercicios-POO\\Exer4\\src\\AT02.txt");
e1.AddMatch("ASDB", 11, "Brasil", 12);
}
}
| 304 | 0.6875 | 0.648026 | 12 | 24.333334 | 32.846443 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.416667 | false | false | 3 |
da0782a19fd8cbba9ef5af6a25385740d2d9b64c | 30,794,915,560,749 | 152605dc969bd737e28f5ea2d44d406d85b9ac7a | /print/src/main/java/com/github/johnkil/print/PrintConfig.java | 906fad8594904830fca2d31fabbe919331fab266 | [
"Apache-2.0"
] | permissive | orlleite/Print | https://github.com/orlleite/Print | f602cb028bff225316f31b2f64d30a42e69c4cf4 | 53bd9d9c622fbb218de2fa63804bb45565d41a28 | refs/heads/master | 2021-03-27T14:29:07.837000 | 2018-02-28T06:09:40 | 2018-02-28T06:09:40 | 123,237,958 | 0 | 0 | Apache-2.0 | true | 2018-02-28T06:07:45 | 2018-02-28T06:07:45 | 2018-01-08T12:45:29 | 2016-10-14T11:24:10 | 514 | 0 | 0 | 0 | null | false | null | /*
* Copyright (C) 2014 Evgeny Shishkin
*
* 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.github.johnkil.print;
import android.content.res.AssetManager;
import android.graphics.Typeface;
public class PrintConfig {
private static PrintConfig sInstance;
/**
* Define the default iconic font.
*
* @param assets The application's asset manager.
* @param defaultFontPath The file name of the font in the assets directory,
* e.g. "fonts/iconic-font.ttf".
* @see #initDefault(Typeface)
*/
public static void initDefault(AssetManager assets, String defaultFontPath) {
Typeface defaultFont = TypefaceManager.load(assets, defaultFontPath);
initDefault(defaultFont);
}
/**
* Define the default iconic font.
*
* @see #initDefault(AssetManager, String)
*/
public static void initDefault(Typeface defaultFont) {
sInstance = new PrintConfig(defaultFont);
}
static PrintConfig get() {
if (sInstance == null)
sInstance = new PrintConfig();
return sInstance;
}
private final Typeface mFont;
private final boolean mIsFontSet;
private PrintConfig() {
this(null);
}
private PrintConfig(Typeface defaultFont) {
mFont = defaultFont;
mIsFontSet = defaultFont != null;
}
/**
* @return the default font.
*/
Typeface getFont() {
return mFont;
}
/**
* @return true if default font is set.
*/
boolean isFontSet() {
return mIsFontSet;
}
} | UTF-8 | Java | 2,129 | java | PrintConfig.java | Java | [
{
"context": "/*\n * Copyright (C) 2014 Evgeny Shishkin\n *\n * Licensed under the Apache License, Version ",
"end": 40,
"score": 0.9998392462730408,
"start": 25,
"tag": "NAME",
"value": "Evgeny Shishkin"
}
] | null | [] | /*
* Copyright (C) 2014 <NAME>
*
* 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.github.johnkil.print;
import android.content.res.AssetManager;
import android.graphics.Typeface;
public class PrintConfig {
private static PrintConfig sInstance;
/**
* Define the default iconic font.
*
* @param assets The application's asset manager.
* @param defaultFontPath The file name of the font in the assets directory,
* e.g. "fonts/iconic-font.ttf".
* @see #initDefault(Typeface)
*/
public static void initDefault(AssetManager assets, String defaultFontPath) {
Typeface defaultFont = TypefaceManager.load(assets, defaultFontPath);
initDefault(defaultFont);
}
/**
* Define the default iconic font.
*
* @see #initDefault(AssetManager, String)
*/
public static void initDefault(Typeface defaultFont) {
sInstance = new PrintConfig(defaultFont);
}
static PrintConfig get() {
if (sInstance == null)
sInstance = new PrintConfig();
return sInstance;
}
private final Typeface mFont;
private final boolean mIsFontSet;
private PrintConfig() {
this(null);
}
private PrintConfig(Typeface defaultFont) {
mFont = defaultFont;
mIsFontSet = defaultFont != null;
}
/**
* @return the default font.
*/
Typeface getFont() {
return mFont;
}
/**
* @return true if default font is set.
*/
boolean isFontSet() {
return mIsFontSet;
}
} | 2,120 | 0.647722 | 0.643964 | 81 | 25.296297 | 24.144342 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.308642 | false | false | 3 |
19cfdb3bdc4593e74136f3d16bbf58108fdf12c6 | 37,821,482,022,245 | f94a6da78da6f0e6af804ea8e99d2e760005e729 | /java-8/src/com/jerin/presentation/stream/IntermediateOperations.java | 5c0688c25107da878ab38952bceaff5eef9dcb85 | [] | no_license | 07jerin/tech-sessions | https://github.com/07jerin/tech-sessions | b6407d9828f8b015e52a4231f9d0320d86b09dd2 | bac82d871d3278e5e0a9794da9edc7a970d11d93 | refs/heads/master | 2022-07-23T06:52:16.163000 | 2020-05-18T17:51:04 | 2020-05-18T17:51:04 | 265,012,678 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jerin.presentation.stream;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.jerin.presentation.common.Person;
import com.jerin.presentation.interfacemethods.PersonInterface;
public class IntermediateOperations {
static List<Person> persons = PersonInterface.getSamplePersons();
public static void main(String[] args) {
persons.forEach(System.out :: println);
System.out.println("********************************************************************");
mapOperation();
System.out.println("********************************************************************");
filterOperation();
System.out.println("********************************************************************");
distinctOperation();
System.out.println("********************************************************************");
limitOperation();
System.out.println("********************************************************************");
skipOperation();
System.out.println("********************************************************************");
sortOperation();
}
public static void mapOperation(){
Stream<Person> personStream = persons.stream();
// Stream<Integer> ageStream = personStream.map((p) -> p.getAge());
Stream<String> nameStream = personStream.map((p) -> p.getName());
// System.out.println("Age Stream : " + ageStream.collect(Collectors.toList()));
System.out.println("Name Stream : " + nameStream.collect(Collectors.toList()));
}
public static void filterOperation(){
Stream<Person> personStream = persons.stream();
Stream<Person> filteredAgeStream = personStream
.filter((p) -> p.getAge() > 30);
System.out.println("Filtered Age Stream : " + filteredAgeStream.collect(Collectors.toList()));
}
public static void distinctOperation(){
Stream<Person> personStream = persons.stream();
// Stream<String> nameStream = personStream.map((p) -> p.getName());
// Stream<String> distinctNames = nameStream.distinct();
Stream<String> distinctNames = personStream
.map((p) -> p.getName())
.distinct();
System.out.println("Distinct Names " + distinctNames.collect(Collectors.toList()));
}
public static void limitOperation(){
Stream<Person> personStream = persons.stream().limit(2);
System.out.println("Two Persons Limited " + personStream.collect(Collectors.toList()));
}
public static void skipOperation(){
Stream<Person> personStream = persons.stream().skip(2);
System.out.println("Two Persons Skipped " + personStream.collect(Collectors.toList()));
}
public static void sortOperation(){
Stream<String> sortedNames = persons
.stream()
.map((p) -> p.getName())
.sorted();
System.out.println("Default Sort " + sortedNames.collect(Collectors.toList()));
Stream<String> revrsesortedNames = persons
.stream()
.map((p) -> p.getName())
.sorted(Comparator.reverseOrder());
System.out.println("Reverse Sorted Names " + revrsesortedNames.collect(Collectors.toList()));
Stream<Person> sortByAge = persons
.stream()
// .sorted((p1, p2) -> p1.getAge().compareTo(p2.getAge()));
.sorted(Person :: sort);
System.out.println("Perons Sorted by age " + sortByAge.collect(Collectors.toList()));
}
}
| UTF-8 | Java | 3,443 | java | IntermediateOperations.java | Java | [] | null | [] | package com.jerin.presentation.stream;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.jerin.presentation.common.Person;
import com.jerin.presentation.interfacemethods.PersonInterface;
public class IntermediateOperations {
static List<Person> persons = PersonInterface.getSamplePersons();
public static void main(String[] args) {
persons.forEach(System.out :: println);
System.out.println("********************************************************************");
mapOperation();
System.out.println("********************************************************************");
filterOperation();
System.out.println("********************************************************************");
distinctOperation();
System.out.println("********************************************************************");
limitOperation();
System.out.println("********************************************************************");
skipOperation();
System.out.println("********************************************************************");
sortOperation();
}
public static void mapOperation(){
Stream<Person> personStream = persons.stream();
// Stream<Integer> ageStream = personStream.map((p) -> p.getAge());
Stream<String> nameStream = personStream.map((p) -> p.getName());
// System.out.println("Age Stream : " + ageStream.collect(Collectors.toList()));
System.out.println("Name Stream : " + nameStream.collect(Collectors.toList()));
}
public static void filterOperation(){
Stream<Person> personStream = persons.stream();
Stream<Person> filteredAgeStream = personStream
.filter((p) -> p.getAge() > 30);
System.out.println("Filtered Age Stream : " + filteredAgeStream.collect(Collectors.toList()));
}
public static void distinctOperation(){
Stream<Person> personStream = persons.stream();
// Stream<String> nameStream = personStream.map((p) -> p.getName());
// Stream<String> distinctNames = nameStream.distinct();
Stream<String> distinctNames = personStream
.map((p) -> p.getName())
.distinct();
System.out.println("Distinct Names " + distinctNames.collect(Collectors.toList()));
}
public static void limitOperation(){
Stream<Person> personStream = persons.stream().limit(2);
System.out.println("Two Persons Limited " + personStream.collect(Collectors.toList()));
}
public static void skipOperation(){
Stream<Person> personStream = persons.stream().skip(2);
System.out.println("Two Persons Skipped " + personStream.collect(Collectors.toList()));
}
public static void sortOperation(){
Stream<String> sortedNames = persons
.stream()
.map((p) -> p.getName())
.sorted();
System.out.println("Default Sort " + sortedNames.collect(Collectors.toList()));
Stream<String> revrsesortedNames = persons
.stream()
.map((p) -> p.getName())
.sorted(Comparator.reverseOrder());
System.out.println("Reverse Sorted Names " + revrsesortedNames.collect(Collectors.toList()));
Stream<Person> sortByAge = persons
.stream()
// .sorted((p1, p2) -> p1.getAge().compareTo(p2.getAge()));
.sorted(Person :: sort);
System.out.println("Perons Sorted by age " + sortByAge.collect(Collectors.toList()));
}
}
| 3,443 | 0.590764 | 0.58844 | 110 | 30.299999 | 31.089767 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.845454 | false | false | 3 |
7b0c78422ec40542754d6357cb1133467982b16b | 38,998,303,072,906 | e1f2a08defb9ecd230ac0c2aa312290eadcb13e9 | /Dialogue.java | 564878c95c585b442931416e2aa5cb18944442f0 | [] | no_license | blkilpatrick42/RadScape | https://github.com/blkilpatrick42/RadScape | 1ec5ecdf0d92dc76d1d7f72210cd0288bb5fadcf | 805eedbaa4d1f32e586aa98d8da93537caae0915 | refs/heads/master | 2021-01-16T21:05:33.082000 | 2016-11-08T21:27:48 | 2016-11-08T21:27:48 | 65,229,273 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mygdx.game;
import java.io.Serializable;
import java.util.Scanner;
import java.util.ArrayList;
public class Dialogue implements Serializable{
public ArrayList<DialogueNode> nodeList = new ArrayList<DialogueNode>();
public DialogueNode curNode;
public String name;
public String[] startStates;
public String[] portraits;
public Dialogue(String inName, String[] inPortraits, String[] inStates, Scanner inScan, int setCurNode){
portraits = inPortraits;
startStates = inStates;
name = inName;
while(inScan.hasNext()){
int inPortrait = inScan.nextInt();
//System.out.println("\ninPortrait = "+inPortrait);
String inString = inScan.nextLine();
//System.out.println("\ninString = "+inString);
Response inResponses[] = new Response[4];
for(int i = 0; i < 4; i++){
int tempNext = inScan.nextInt();
if(tempNext == -2){
inResponses[i] = new Response(-2,0,0,"");
}
else{
//System.out.println("tempNext: " + tempNext);
int tempSet = inScan.nextInt();
//System.out.println("tempSet: "+ tempSet);
int tempItem = inScan.nextInt();
//System.out.println("tempItem: "+ tempItem);
String inText = inScan.nextLine();
//System.out.println("inText: "+ inText);
inResponses[i] = new Response(tempNext,tempSet,tempItem,inText);
}
}
nodeList.add(new DialogueNode(inPortrait,inString,inResponses));
}
curNode = nodeList.get(setCurNode);
inScan.close();
}
public void setCurNode(int i){
curNode = nodeList.get(i);
}
public void getStartNode(){
Scanner tempScanner;
int tempA;
int tempB;
for(int i =0; i<startStates.length;i++){
tempScanner = new Scanner(startStates[i]);
tempA = tempScanner.nextInt();
tempB = tempScanner.nextInt();
if(tempA == 0){
setCurNode(0);
}
else if(Reader.statusListContains(tempA)){
setCurNode(tempB);
}
tempScanner.close();
}
}
}
| UTF-8 | Java | 1,989 | java | Dialogue.java | Java | [] | null | [] | package com.mygdx.game;
import java.io.Serializable;
import java.util.Scanner;
import java.util.ArrayList;
public class Dialogue implements Serializable{
public ArrayList<DialogueNode> nodeList = new ArrayList<DialogueNode>();
public DialogueNode curNode;
public String name;
public String[] startStates;
public String[] portraits;
public Dialogue(String inName, String[] inPortraits, String[] inStates, Scanner inScan, int setCurNode){
portraits = inPortraits;
startStates = inStates;
name = inName;
while(inScan.hasNext()){
int inPortrait = inScan.nextInt();
//System.out.println("\ninPortrait = "+inPortrait);
String inString = inScan.nextLine();
//System.out.println("\ninString = "+inString);
Response inResponses[] = new Response[4];
for(int i = 0; i < 4; i++){
int tempNext = inScan.nextInt();
if(tempNext == -2){
inResponses[i] = new Response(-2,0,0,"");
}
else{
//System.out.println("tempNext: " + tempNext);
int tempSet = inScan.nextInt();
//System.out.println("tempSet: "+ tempSet);
int tempItem = inScan.nextInt();
//System.out.println("tempItem: "+ tempItem);
String inText = inScan.nextLine();
//System.out.println("inText: "+ inText);
inResponses[i] = new Response(tempNext,tempSet,tempItem,inText);
}
}
nodeList.add(new DialogueNode(inPortrait,inString,inResponses));
}
curNode = nodeList.get(setCurNode);
inScan.close();
}
public void setCurNode(int i){
curNode = nodeList.get(i);
}
public void getStartNode(){
Scanner tempScanner;
int tempA;
int tempB;
for(int i =0; i<startStates.length;i++){
tempScanner = new Scanner(startStates[i]);
tempA = tempScanner.nextInt();
tempB = tempScanner.nextInt();
if(tempA == 0){
setCurNode(0);
}
else if(Reader.statusListContains(tempA)){
setCurNode(tempB);
}
tempScanner.close();
}
}
}
| 1,989 | 0.645551 | 0.640523 | 68 | 27.102942 | 20.686838 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.235294 | false | false | 3 |
77d182dc151376ab21275c32caf07a343919f1a9 | 38,225,208,941,331 | 76f95505876c82efc5bc2abeaae93b0490009415 | /JSP/timemarket_front/src/timeshop/member/membuyokAction.java | d2dddf3fe596a6a1f4eb5d944befd732022731ab | [] | no_license | LEEBYEONGGYU/WebDevelop | https://github.com/LEEBYEONGGYU/WebDevelop | ed75e060435b7d70a438c4367d68f8bfb01efc32 | 8412691411ac97074f15b68f74ff59ab52a5001d | refs/heads/master | 2022-12-23T21:21:51.873000 | 2021-04-27T12:59:16 | 2021-04-27T12:59:16 | 210,326,802 | 1 | 3 | null | false | 2022-12-16T15:33:08 | 2019-09-23T10:24:14 | 2021-04-27T12:59:38 | 2022-12-16T15:33:05 | 126,743 | 1 | 1 | 21 | Java | false | false | package timeshop.member;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import shop.Action.Action;
import shop.DBbean.MemberMyBuyBean;
import shop.DBbean.MemberMyBuyData;
public class membuyokAction implements Action{
public String requestProcess(HttpServletRequest request, HttpServletResponse response) throws Throwable {
MemberMyBuyData Purchase = new MemberMyBuyData();
String userid = Purchase.setUserid(request.getParameter("userid"));
String pro_name = Purchase.setPurproname(request.getParameter("bas_pname"));
String bas_proop = Purchase.setPurop1(request.getParameter("bas_proop1"));
String bas_proop2 = Purchase.setPurop2(request.getParameter("bas_proop2"));
String bas_proop3 = Purchase.setPurop3(request.getParameter("bas_proop3"));
String bas_proop4 = Purchase.setPurop4(request.getParameter("bas_proop4"));
String pro_opprice = Purchase.setPuropprice(request.getParameter("bas_opprice1"));
String pro_opprice2 = Purchase.setPuropprice2(request.getParameter("bas_opprice2"));
String pro_opprice3 = Purchase.setPuropprice3(request.getParameter("bas_opprice3"));
String pro_opprice4 = Purchase.setPuropprice4(request.getParameter("bas_opprice4"));
String pro_price = Purchase.setPurpirce(request.getParameter("pro_price"));
String pro_cot = Purchase.setPurcot(request.getParameter("pro_cot"));
MemberMyBuyBean PurchaseBean = MemberMyBuyBean.getInstance();
PurchaseBean.insertPurchase(Purchase);
return "/page/member/mem_buyok.jsp";
}
}
| UTF-8 | Java | 1,542 | java | membuyokAction.java | Java | [] | null | [] | package timeshop.member;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import shop.Action.Action;
import shop.DBbean.MemberMyBuyBean;
import shop.DBbean.MemberMyBuyData;
public class membuyokAction implements Action{
public String requestProcess(HttpServletRequest request, HttpServletResponse response) throws Throwable {
MemberMyBuyData Purchase = new MemberMyBuyData();
String userid = Purchase.setUserid(request.getParameter("userid"));
String pro_name = Purchase.setPurproname(request.getParameter("bas_pname"));
String bas_proop = Purchase.setPurop1(request.getParameter("bas_proop1"));
String bas_proop2 = Purchase.setPurop2(request.getParameter("bas_proop2"));
String bas_proop3 = Purchase.setPurop3(request.getParameter("bas_proop3"));
String bas_proop4 = Purchase.setPurop4(request.getParameter("bas_proop4"));
String pro_opprice = Purchase.setPuropprice(request.getParameter("bas_opprice1"));
String pro_opprice2 = Purchase.setPuropprice2(request.getParameter("bas_opprice2"));
String pro_opprice3 = Purchase.setPuropprice3(request.getParameter("bas_opprice3"));
String pro_opprice4 = Purchase.setPuropprice4(request.getParameter("bas_opprice4"));
String pro_price = Purchase.setPurpirce(request.getParameter("pro_price"));
String pro_cot = Purchase.setPurcot(request.getParameter("pro_cot"));
MemberMyBuyBean PurchaseBean = MemberMyBuyBean.getInstance();
PurchaseBean.insertPurchase(Purchase);
return "/page/member/mem_buyok.jsp";
}
}
| 1,542 | 0.789235 | 0.775616 | 32 | 47.1875 | 32.691204 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.03125 | false | false | 3 |
81b1e54f6de3a37268ebd5278ec2441e37e2101c | 154,618,881,692 | b62ffd1a69d195fa0f44693a3039509fdeaa1a0b | /MeusEstudosJava/src/Testes/Teste.java | 5f3e39bdf6ee3076c6dca35a3f3b8107fd6955ce | [] | no_license | wallyson2712/MeusEstudosJava | https://github.com/wallyson2712/MeusEstudosJava | f1953e8eeb5bd7b44a804b553d034b551c0b3c0a | 29ac8b4d39fe6b3efee1b6a253390a886f21fc95 | refs/heads/master | 2021-01-22T03:01:31.455000 | 2013-08-18T23:00:52 | 2013-08-18T23:00:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Testes;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Teste {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader ent = new BufferedReader(
new InputStreamReader(System.in));
String algo = ent.readLine();
String algo2 = ent.readLine();
System.out.println(Integer.parseInt(algo) + Integer.parseInt(algo2));
// vai ler a primeira linha é ficar cortando por expaços
StringTokenizer st = new StringTokenizer(ent.readLine());
// vai pegar o primeiro token da linha
int valor = Integer.parseInt(st.nextToken());
int valor2 = Integer.parseInt(st.nextToken());
System.out.println(valor + "" + valor2);
}
}
| UTF-8 | Java | 809 | java | Teste.java | Java | [] | null | [] | package Testes;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Teste {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader ent = new BufferedReader(
new InputStreamReader(System.in));
String algo = ent.readLine();
String algo2 = ent.readLine();
System.out.println(Integer.parseInt(algo) + Integer.parseInt(algo2));
// vai ler a primeira linha é ficar cortando por expaços
StringTokenizer st = new StringTokenizer(ent.readLine());
// vai pegar o primeiro token da linha
int valor = Integer.parseInt(st.nextToken());
int valor2 = Integer.parseInt(st.nextToken());
System.out.println(valor + "" + valor2);
}
}
| 809 | 0.723668 | 0.718711 | 32 | 24.21875 | 21.657467 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.34375 | false | false | 3 |
63dcd3bcff02744cc693c52c750119db4b0c6624 | 36,129,264,913,396 | e3624ce05e1a2772e28134be2c93c44bec428e51 | /src/main/java/me/brennan/discordauth/controllers/AuthController.java | 1246779000328a354c5a1e007320f8210f789094 | [] | no_license | skateboard/discord-auth | https://github.com/skateboard/discord-auth | 10bf6650781ecee507ff47885944062c1fb8854a | ca7a1898114dcdc403f507a18a53e8cd1899b6e8 | refs/heads/master | 2023-03-05T16:28:32.159000 | 2021-02-21T20:34:43 | 2021-02-21T20:34:43 | 339,564,729 | 8 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.brennan.discordauth.controllers;
import io.mokulu.discord.oauth.DiscordAPI;
import io.mokulu.discord.oauth.model.TokensResponse;
import io.mokulu.discord.oauth.model.User;
import me.brennan.discordauth.DiscordAuth;
import me.brennan.discordauth.models.StoredUser;
import me.brennan.discordauth.util.discord.Embeds;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Brennan
* @since 2/13/2021
**/
@Controller
@RequestMapping("auth/")
public class AuthController {
@GetMapping("logout")
public String logout(HttpServletRequest request) {
request.getSession().setAttribute("user", null);
return "redirect:../";
}
@GetMapping("login")
public void discordLogin(HttpServletResponse httpServletResponse) {
httpServletResponse.setHeader("Location", DiscordAuth.getINSTANCE().getOAuthHandler().getAuthorizationURL(""));
httpServletResponse.setStatus(302);
}
@GetMapping("callback")
public String discordAuth(@RequestParam("code") String code, HttpServletRequest request) {
try {
final TokensResponse tokens = DiscordAuth.getINSTANCE().getOAuthHandler().getTokens(code);
final DiscordAPI discordAPI = new DiscordAPI(tokens.getAccessToken());
final User discordUser = discordAPI.fetchUser();
final String avatar = "https://cdn.discordapp.com/avatars/" + discordUser.getId() + "/" + discordUser.getAvatar() + ".png";
StoredUser storedUser = DiscordAuth.getINSTANCE().getMySQL().getUser(discordUser.getId());
if(storedUser == null) {
storedUser = DiscordAuth.getINSTANCE().getMySQL().createUser(discordUser, avatar);
}
request.getSession().setAttribute("user", storedUser);
return "redirect:../dashboard/";
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/";
}
}
| UTF-8 | Java | 2,218 | java | AuthController.java | Java | [
{
"context": ".servlet.http.HttpServletResponse;\n\n/**\n * @author Brennan\n * @since 2/13/2021\n **/\n@Controller\n@RequestMapp",
"end": 677,
"score": 0.9271648526191711,
"start": 670,
"tag": "USERNAME",
"value": "Brennan"
}
] | null | [] | package me.brennan.discordauth.controllers;
import io.mokulu.discord.oauth.DiscordAPI;
import io.mokulu.discord.oauth.model.TokensResponse;
import io.mokulu.discord.oauth.model.User;
import me.brennan.discordauth.DiscordAuth;
import me.brennan.discordauth.models.StoredUser;
import me.brennan.discordauth.util.discord.Embeds;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Brennan
* @since 2/13/2021
**/
@Controller
@RequestMapping("auth/")
public class AuthController {
@GetMapping("logout")
public String logout(HttpServletRequest request) {
request.getSession().setAttribute("user", null);
return "redirect:../";
}
@GetMapping("login")
public void discordLogin(HttpServletResponse httpServletResponse) {
httpServletResponse.setHeader("Location", DiscordAuth.getINSTANCE().getOAuthHandler().getAuthorizationURL(""));
httpServletResponse.setStatus(302);
}
@GetMapping("callback")
public String discordAuth(@RequestParam("code") String code, HttpServletRequest request) {
try {
final TokensResponse tokens = DiscordAuth.getINSTANCE().getOAuthHandler().getTokens(code);
final DiscordAPI discordAPI = new DiscordAPI(tokens.getAccessToken());
final User discordUser = discordAPI.fetchUser();
final String avatar = "https://cdn.discordapp.com/avatars/" + discordUser.getId() + "/" + discordUser.getAvatar() + ".png";
StoredUser storedUser = DiscordAuth.getINSTANCE().getMySQL().getUser(discordUser.getId());
if(storedUser == null) {
storedUser = DiscordAuth.getINSTANCE().getMySQL().createUser(discordUser, avatar);
}
request.getSession().setAttribute("user", storedUser);
return "redirect:../dashboard/";
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/";
}
}
| 2,218 | 0.70514 | 0.700631 | 61 | 35.360657 | 33.031548 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52459 | false | false | 3 |
269e6a54fe7ec647a14318afba9594eb2f9fceba | 16,544,214,080,985 | 8efa4917649924468ec3899d9af8eaae8ba43d32 | /src/hqh/socket/sigle/thinkInJava/JabberClient.java | a5281a02d895443b090d583f7482fd949b76ec5c | [] | no_license | hqh1978/myTestJava | https://github.com/hqh1978/myTestJava | 37cde9f9a771621eaaa5e318ef020538e198203e | d2314ef48c0b0672854c2df08ab96a2a137711a5 | refs/heads/master | 2016-09-12T14:53:38.008000 | 2016-05-12T14:56:22 | 2016-05-12T14:56:22 | 58,650,265 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hqh.socket.sigle.thinkInJava;
//: JabberClient.java
//Very simple client that just sends
//lines to the server and reads lines
//that the server sends.
import java.net.*;
import java.util.Calendar;
import java.io.*;
public class JabberClient {
public static void main(String[] args) throws IOException {
Calendar c = Calendar.getInstance();
// Passing null to getByName() produces the
// special "Local Loopback" IP address, for
// testing on one machine w/o a network:
InetAddress addr = InetAddress.getByName(null);
// Alternatively, you can use
// the address or name:
// InetAddress addr =
// InetAddress.getByName("127.0.0.1");
// InetAddress addr =
// InetAddress.getByName("localhost");
System.out.println("addr = " + addr);
//不同于server端,此处为Socket 不是 serverSocket,此处需要服务端的Ip,和端口号
Socket socket = new Socket(addr, JabberServer.PORT);
// Guard everything in a try-finally to make
// sure that the socket is closed:
try {
System.out.println("socket = " + socket);
/*The client also creates an InputStream to hear what
the server is saying (which, in this case, is just the words echoed back).
*/
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//System.out.println("Client In="+in);
// Output is automatically flushed by PrintWriter: "true" 参数
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
true);
//System.out.println("Client Out="+out);
for (int i = 0; i < 10; i++) {
//给out中注入数据到socket,server 端在通过同一个socket 从 in中读出来。
//**** 这里往out中写入,不用write方法,用println方法,应为用write 写入的默认的为block bufferd, println 默认为line bufferd
//Step 1 ----begin
out.println("howdy " + i);
//Step 1 ----end
// String str = in.readLine();
// System.out.println(str);
}
out.println("END");
String temp=in.readLine();
System.out.println("get message from server :"+temp);
}catch(Exception e){
e.printStackTrace();
}
finally {
System.out.println("Client closing...");
socket.close();
}
}
} | GB18030 | Java | 2,309 | java | JabberClient.java | Java | [
{
"context": "/ InetAddress addr =\r\n\t\t// InetAddress.getByName(\"127.0.0.1\");\r\n\t\t// InetAddress addr =\r\n\t\t// InetAddress.get",
"end": 682,
"score": 0.999740719795227,
"start": 673,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null | [] | package hqh.socket.sigle.thinkInJava;
//: JabberClient.java
//Very simple client that just sends
//lines to the server and reads lines
//that the server sends.
import java.net.*;
import java.util.Calendar;
import java.io.*;
public class JabberClient {
public static void main(String[] args) throws IOException {
Calendar c = Calendar.getInstance();
// Passing null to getByName() produces the
// special "Local Loopback" IP address, for
// testing on one machine w/o a network:
InetAddress addr = InetAddress.getByName(null);
// Alternatively, you can use
// the address or name:
// InetAddress addr =
// InetAddress.getByName("127.0.0.1");
// InetAddress addr =
// InetAddress.getByName("localhost");
System.out.println("addr = " + addr);
//不同于server端,此处为Socket 不是 serverSocket,此处需要服务端的Ip,和端口号
Socket socket = new Socket(addr, JabberServer.PORT);
// Guard everything in a try-finally to make
// sure that the socket is closed:
try {
System.out.println("socket = " + socket);
/*The client also creates an InputStream to hear what
the server is saying (which, in this case, is just the words echoed back).
*/
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//System.out.println("Client In="+in);
// Output is automatically flushed by PrintWriter: "true" 参数
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
true);
//System.out.println("Client Out="+out);
for (int i = 0; i < 10; i++) {
//给out中注入数据到socket,server 端在通过同一个socket 从 in中读出来。
//**** 这里往out中写入,不用write方法,用println方法,应为用write 写入的默认的为block bufferd, println 默认为line bufferd
//Step 1 ----begin
out.println("howdy " + i);
//Step 1 ----end
// String str = in.readLine();
// System.out.println(str);
}
out.println("END");
String temp=in.readLine();
System.out.println("get message from server :"+temp);
}catch(Exception e){
e.printStackTrace();
}
finally {
System.out.println("Client closing...");
socket.close();
}
}
} | 2,309 | 0.669448 | 0.664349 | 62 | 32.822582 | 23.168753 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.596774 | false | false | 3 |
c6a5cba53807e3bccd7d1991c1e0411a19e9d664 | 7,095,286,023,088 | d0152db859cea65520ae93321576f0a91957ce87 | /bw-timezone-server-tzconvert/src/main/java/org/bedework/timezones/convert/RuleSet.java | 6cb1768f13554c6caba7acb9840884dfee6a27e5 | [] | no_license | Bedework/bw-timezone-server | https://github.com/Bedework/bw-timezone-server | 226db7611e8620fa65e36e9732a39006564bc4a4 | 1bea33b76c29807fb43b9c338e9beb74ab0bba6c | refs/heads/master | 2023-08-17T04:29:21.830000 | 2023-08-12T05:47:38 | 2023-08-12T05:47:38 | 7,165,340 | 2 | 3 | null | false | 2021-06-06T02:00:05 | 2012-12-14T12:47:17 | 2021-06-03T19:51:26 | 2021-06-06T02:00:04 | 2,795 | 1 | 3 | 0 | Java | false | false | /*
# Copyright (c) 2007-2013 Cyrus Daboo. 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 org.bedework.timezones.convert;
/*
from pycalendar.datetime import DateTime
from pycalendar.icalendar import definitions
from pycalendar.icalendar.property import Property
from pycalendar.icalendar.recurrence import Recurrence
from pycalendar.icalendar.vtimezonedaylight import Daylight
from pycalendar.icalendar.vtimezonestandard import Standard
from pycalendar.utcoffsetvalue import UTCOffsetValue
from pycalendar.utils import daysInMonth
import utils
*/
import java.util.ArrayList;
import java.util.List;
import static org.bedework.timezones.convert.Rule.DateOffset;
/**
Class that maintains a TZ data Rule.
A set of tzdata rules tied to a specific Rule name
*/
public class RuleSet extends ArrayList<Rule> {
private String name;
/**
Parse the set of Rule lines from tzdata.
* @param lines the lines to parse.
*/
void parse(final String lines) {
final String[] splitlines = lines.split("\n");
for (final String line: splitlines) {
final String[] splits = line.replace("\t", " ").split(" ");
final String nm = splits[1];
if (nm == null) {
Utils.print("Must have a zone name: '%s'", lines);
}
if (name == null) {
name = nm;
}
if (!nm.equals(name)) {
Utils.print("Different zone names %s and %s: %s", name, nm);
}
final Rule rule = new Rule();
rule.parse(line);
add(rule);
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
String delim = "";
for (final Rule rl: this) {
sb.append(delim);
sb.append(rl.generate());
delim = "\n";
}
return sb.toString();
}
/**
* Expand the set of rules into transition/offset pairs for the entire RuleSet
* starting at the beginning and going up to maxYear at most.
* @param zoneinfo: the Zone in which this RuleSet is being used
* @param maxYear: the maximum year to expand out to
*/
List<DateOffset> expand(final ZoneRule zoneinfo,
final int maxYear) {
final List<DateOffset> results = new ArrayList<>();
for (final Rule rule: this) {
rule.expand(results, zoneinfo, maxYear);
}
return results;
}
@Override
public boolean equals(final Object o) {
final RuleSet other = (RuleSet)o;
return name.equals(other.name) &&
super.equals(other);
}
} | UTF-8 | Java | 3,047 | java | RuleSet.java | Java | [
{
"context": "/*\n# Copyright (c) 2007-2013 Cyrus Daboo. All rights reserved.\n#\n# Licensed under the A",
"end": 43,
"score": 0.9998350143432617,
"start": 32,
"tag": "NAME",
"value": "Cyrus Daboo"
}
] | null | [] | /*
# Copyright (c) 2007-2013 <NAME>. 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 org.bedework.timezones.convert;
/*
from pycalendar.datetime import DateTime
from pycalendar.icalendar import definitions
from pycalendar.icalendar.property import Property
from pycalendar.icalendar.recurrence import Recurrence
from pycalendar.icalendar.vtimezonedaylight import Daylight
from pycalendar.icalendar.vtimezonestandard import Standard
from pycalendar.utcoffsetvalue import UTCOffsetValue
from pycalendar.utils import daysInMonth
import utils
*/
import java.util.ArrayList;
import java.util.List;
import static org.bedework.timezones.convert.Rule.DateOffset;
/**
Class that maintains a TZ data Rule.
A set of tzdata rules tied to a specific Rule name
*/
public class RuleSet extends ArrayList<Rule> {
private String name;
/**
Parse the set of Rule lines from tzdata.
* @param lines the lines to parse.
*/
void parse(final String lines) {
final String[] splitlines = lines.split("\n");
for (final String line: splitlines) {
final String[] splits = line.replace("\t", " ").split(" ");
final String nm = splits[1];
if (nm == null) {
Utils.print("Must have a zone name: '%s'", lines);
}
if (name == null) {
name = nm;
}
if (!nm.equals(name)) {
Utils.print("Different zone names %s and %s: %s", name, nm);
}
final Rule rule = new Rule();
rule.parse(line);
add(rule);
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
String delim = "";
for (final Rule rl: this) {
sb.append(delim);
sb.append(rl.generate());
delim = "\n";
}
return sb.toString();
}
/**
* Expand the set of rules into transition/offset pairs for the entire RuleSet
* starting at the beginning and going up to maxYear at most.
* @param zoneinfo: the Zone in which this RuleSet is being used
* @param maxYear: the maximum year to expand out to
*/
List<DateOffset> expand(final ZoneRule zoneinfo,
final int maxYear) {
final List<DateOffset> results = new ArrayList<>();
for (final Rule rule: this) {
rule.expand(results, zoneinfo, maxYear);
}
return results;
}
@Override
public boolean equals(final Object o) {
final RuleSet other = (RuleSet)o;
return name.equals(other.name) &&
super.equals(other);
}
} | 3,042 | 0.669839 | 0.665573 | 113 | 25.973452 | 24.228067 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.327434 | false | false | 3 |
9e8ae380757698d20518357b842046cd83c85f47 | 17,549,236,412,269 | 672da530cd91b0ff84842fd5628f4d89b61b34b1 | /src/main/java/com/cn/ldap/controller/LdapLogin.java | 9e38e714698963adae013cc39ee60059260c8468 | [] | no_license | SkyFreecss/LDAP_MANAGE | https://github.com/SkyFreecss/LDAP_MANAGE | bbf1ca84845ed3db101844c1322266c35fd8ad67 | 6fa7289da25c4215db27a2e834fbcc4a061acf84 | refs/heads/master | 2021-01-22T03:22:12.183000 | 2017-06-01T02:41:09 | 2017-06-01T02:41:09 | 92,370,344 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cn.ldap.controller;
import com.cn.ldap.entity.Ldap;
import com.cn.ldap.service.LdapLoginService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import javax.naming.directory.DirContext;
import java.util.logging.Logger;
/**
* Created by wejeh on 2017/5/15.
*/
@Controller
public class LdapLogin {
private static DirContext ctx;
private Logger logger = Logger.getLogger("LdapLogin.class");
Ldap ldap = new Ldap();
@Resource
private LdapLoginService ldapLoginService;
@RequestMapping("/ldaplogin")
public String getLoginContext(@RequestParam("username") String username, @RequestParam("password") String password, Model model)
{
ldap.setUsername(username);
ldap.setPassword(password);
ldap.setLDAP_PRINCIPAL("cn="+ldap.getUsername()/*+",dc=example,dc=com"*/);
String result = ldapLoginService.getLoginContext(ldap.getUsername(),ldap.getPassword());
if(result=="LDAP认证成功!") {
return "WEB-INF/jsp/home";
}
else {
logger.info("LDAP"+result);
return result;
}
}
}
| UTF-8 | Java | 1,443 | java | LdapLogin.java | Java | [
{
"context": "mport java.util.logging.Logger;\n\n/**\n * Created by wejeh on 2017/5/15.\n */\n@Controller\npublic class LdapLo",
"end": 455,
"score": 0.9996152520179749,
"start": 450,
"tag": "USERNAME",
"value": "wejeh"
},
{
"context": "rname(username);\n ldap.setPassword(password);\n ldap.setLDAP_PRINCIPAL(\"cn=\"+ld",
"end": 993,
"score": 0.9699701070785522,
"start": 985,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package com.cn.ldap.controller;
import com.cn.ldap.entity.Ldap;
import com.cn.ldap.service.LdapLoginService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import javax.naming.directory.DirContext;
import java.util.logging.Logger;
/**
* Created by wejeh on 2017/5/15.
*/
@Controller
public class LdapLogin {
private static DirContext ctx;
private Logger logger = Logger.getLogger("LdapLogin.class");
Ldap ldap = new Ldap();
@Resource
private LdapLoginService ldapLoginService;
@RequestMapping("/ldaplogin")
public String getLoginContext(@RequestParam("username") String username, @RequestParam("password") String password, Model model)
{
ldap.setUsername(username);
ldap.setPassword(<PASSWORD>);
ldap.setLDAP_PRINCIPAL("cn="+ldap.getUsername()/*+",dc=example,dc=com"*/);
String result = ldapLoginService.getLoginContext(ldap.getUsername(),ldap.getPassword());
if(result=="LDAP认证成功!") {
return "WEB-INF/jsp/home";
}
else {
logger.info("LDAP"+result);
return result;
}
}
}
| 1,445 | 0.642509 | 0.637631 | 42 | 33.166668 | 28.900417 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false | 3 |
b4c1ac7d6aa2705186e46f6a8730583efbf4c5ef | 17,549,236,412,698 | 55d4dd5b3fcac4564e4a20b4652caf8cb98edc94 | /JAVA_Basics/src/com/jala/pkg1/PrintName.java | bf312e74071232008741fba87563e537bdadce44 | [] | no_license | raiman220/Jala-Technolegies | https://github.com/raiman220/Jala-Technolegies | bcf5d3961f8a5a0527dcb20eabd7be555cf95efc | a3ac09346a2940ecef3b1688d3ca100e3ebf89dc | refs/heads/master | 2023-05-29T23:22:22.980000 | 2021-06-11T15:53:12 | 2021-06-11T15:53:12 | 374,705,194 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jala.pkg1;
public class PrintName
{
public static void main(String[] args)
{
System.out.println("RAIMANASABA HUSENSAB PINJAR");
}
}
| UTF-8 | Java | 164 | java | PrintName.java | Java | [
{
"context": "d main(String[] args) \r\n\t{\r\n\t\tSystem.out.println(\"RAIMANASABA HUSENSAB PINJAR\");\r\n\t}\r\n\r\n}\r\n",
"end": 150,
"score": 0.999705970287323,
"start": 123,
"tag": "NAME",
"value": "RAIMANASABA HUSENSAB PINJAR"
}
] | null | [] | package com.jala.pkg1;
public class PrintName
{
public static void main(String[] args)
{
System.out.println("<NAME>");
}
}
| 143 | 0.664634 | 0.658537 | 11 | 12.909091 | 17.706982 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 3 |
98d057e43b88489e4f2a2443123660fe49c65fb2 | 31,336,081,427,282 | 0095e6650f71c7f805c653c95b5aa1e423992871 | /src/main/java/com/kraluk/playground/algorithm/common/Multiples.java | 5f4374c7726ed3c6ff9d19326803663f37899c2c | [] | no_license | kraluk/algorithm-playground | https://github.com/kraluk/algorithm-playground | 87bf36a5ed3db3064dbcd7950918754bbbf0e872 | b651b89ead9f8a8eaac6d69f25b049b04ebcdcfc | refs/heads/master | 2022-02-22T10:11:31.869000 | 2019-06-16T13:58:30 | 2019-06-16T13:58:30 | 68,319,764 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kraluk.playground.algorithm.common;
import java.util.HashSet;
import java.util.Set;
/**
* Multiples Common Calculation Utils
*
* @author lukasz
*/
public final class Multiples {
public static final long MAX_LIMIT = 1_000_000;
@Deprecated
public static Set<Long> getMultiples(long number, long limit) {
checkLimit(limit);
Set<Long> result = new HashSet<>();
for (long i = 1; ; i++) {
long multiple = number * i;
if (multiple < limit) {
result.add(multiple);
} else {
break;
}
}
return result;
}
private static void checkLimit(long limit) {
if (limit >= MAX_LIMIT) {
throw new IllegalArgumentException(
"Given limit overruns the maximum limit for used method!");
}
}
} | UTF-8 | Java | 878 | java | Multiples.java | Java | [
{
"context": "* Multiples Common Calculation Utils\n *\n * @author lukasz\n */\npublic final class Multiples {\n public sta",
"end": 160,
"score": 0.7932935357093811,
"start": 154,
"tag": "NAME",
"value": "lukasz"
}
] | null | [] | package com.kraluk.playground.algorithm.common;
import java.util.HashSet;
import java.util.Set;
/**
* Multiples Common Calculation Utils
*
* @author lukasz
*/
public final class Multiples {
public static final long MAX_LIMIT = 1_000_000;
@Deprecated
public static Set<Long> getMultiples(long number, long limit) {
checkLimit(limit);
Set<Long> result = new HashSet<>();
for (long i = 1; ; i++) {
long multiple = number * i;
if (multiple < limit) {
result.add(multiple);
} else {
break;
}
}
return result;
}
private static void checkLimit(long limit) {
if (limit >= MAX_LIMIT) {
throw new IllegalArgumentException(
"Given limit overruns the maximum limit for used method!");
}
}
} | 878 | 0.560364 | 0.551253 | 39 | 21.538462 | 20.117407 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.358974 | false | false | 3 |
3f14b0fd5342e379574dbf412343beba0ba27fd5 | 21,071,109,583,995 | a17dcf34301039e540b72a1894c194214edacb16 | /Proyecto final(Daniel, andres, cristian)/trabajador.java | da9c73bc94b5ca77235e425dd2471dcb900b548e | [] | no_license | dajaramillo10/repositorioEstructuradedatos | https://github.com/dajaramillo10/repositorioEstructuradedatos | 2b023b3916b9684bf8a8e464e10806c372d1d462 | bc3e2c8cb4c818322c56640a4ccaab821608eb04 | refs/heads/master | 2022-12-24T02:09:07.163000 | 2020-09-19T16:49:17 | 2020-09-19T16:49:17 | 276,714,724 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 finalbin;
/**
*
* @author ccort
*/
public class trabajador {
private String nombre;
private String identi;
private String cargo;
private int horasTr;
public trabajador(String nombre, String identi, String cargo, int horasTr) {
this.nombre = nombre;
this.identi = identi;
this.cargo = cargo;
this.horasTr = horasTr;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getIdenti() {
return identi;
}
public void setIdenti(String identi) {
this.identi = identi;
}
public String getCargo() {
return cargo;
}
public void setCargo(String cargo) {
this.cargo = cargo;
}
public int getHorasTr() {
return horasTr;
}
public void setHorasTr(int horasTr) {
this.horasTr = horasTr;
}
@Override
public String toString() {
return "nombre=" + nombre + ", identi=" + identi + ", cargo=" + cargo + ", horasTr=" + horasTr ;
}
}
| UTF-8 | Java | 1,367 | java | trabajador.java | Java | [
{
"context": "or.\r\n */\r\npackage finalbin;\r\n\r\n/**\r\n *\r\n * @author ccort\r\n */\r\npublic class trabajador {\r\n private Stri",
"end": 236,
"score": 0.9995995759963989,
"start": 231,
"tag": "USERNAME",
"value": "ccort"
}
] | null | [] | /*
* 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 finalbin;
/**
*
* @author ccort
*/
public class trabajador {
private String nombre;
private String identi;
private String cargo;
private int horasTr;
public trabajador(String nombre, String identi, String cargo, int horasTr) {
this.nombre = nombre;
this.identi = identi;
this.cargo = cargo;
this.horasTr = horasTr;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getIdenti() {
return identi;
}
public void setIdenti(String identi) {
this.identi = identi;
}
public String getCargo() {
return cargo;
}
public void setCargo(String cargo) {
this.cargo = cargo;
}
public int getHorasTr() {
return horasTr;
}
public void setHorasTr(int horasTr) {
this.horasTr = horasTr;
}
@Override
public String toString() {
return "nombre=" + nombre + ", identi=" + identi + ", cargo=" + cargo + ", horasTr=" + horasTr ;
}
}
| 1,367 | 0.569129 | 0.569129 | 64 | 19.359375 | 21.104181 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421875 | false | false | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.